Debian Codegraph @

unix/tclUnixSock.c

raw
1 /*
2 * tclUnixSock.c --
3 *
4 * This file contains Unix-specific socket related code.
5 *
6 * Copyright (c) 1995 Sun Microsystems, Inc.
7 *
8 * See the file "license.terms" for information on usage and redistribution of
9 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
10 */
11
12 #include "tclInt.h"
13
14 /*
15 * Helper macros to make parts of this file clearer. The macros do exactly
16 * what they say on the tin. :-) They also only ever refer to their arguments
17 * once, and so can be used without regard to side effects.
18 */
19
20 #define SET_BITS(var, bits) ((var) |= (bits))
21 #define CLEAR_BITS(var, bits) ((var) &= ~(bits))
22 #define GOT_BITS(var, bits) (((var) & (bits)) != 0)
23
24 /* "sock" + a pointer in hex + \0 */
25 #define SOCK_CHAN_LENGTH (4 + sizeof(void *) * 2 + 1)
26 #define SOCK_TEMPLATE "sock%lx"
27
28 #undef SOCKET /* Possible conflict with win32 SOCKET */
29
30 /*
31 * This is needed to comply with the strict aliasing rules of GCC, but it also
32 * simplifies casting between the different sockaddr types.
33 */
34
35 typedef union {
36 struct sockaddr sa;
37 struct sockaddr_in sa4;
38 struct sockaddr_in6 sa6;
39 struct sockaddr_storage sas;
40 } address;
41
42 /*
43 * This structure describes per-instance state of a tcp-based channel.
44 */
45
46 typedef struct TcpState TcpState;
47
48 typedef struct TcpFdList {
49 TcpState *statePtr;
50 int fd;
51 struct TcpFdList *next;
52 } TcpFdList;
53
54 struct TcpState {
55 Tcl_Channel channel; /* Channel associated with this file. */
56 TcpFdList fds; /* The file descriptors of the sockets. */
57 int flags; /* OR'ed combination of the bitfields defined
58 * below. */
59 int interest; /* Event types of interest */
60
61 /*
62 * Only needed for server sockets
63 */
64
65 Tcl_TcpAcceptProc *acceptProc; /* Proc to call on accept. */
66 void *acceptProcData; /* The data for the accept proc. */
67
68 /*
69 * Only needed for client sockets
70 */
71
72 struct addrinfo *addrlist; /* Addresses to connect to. */
73 struct addrinfo *addr; /* Iterator over addrlist. */
74 struct addrinfo *myaddrlist;/* Local address. */
75 struct addrinfo *myaddr; /* Iterator over myaddrlist. */
76 int filehandlers; /* Caches FileHandlers that get set up while
77 * an async socket is not yet connected. */
78 int connectError; /* Cache SO_ERROR of async socket. */
79 int cachedBlocking; /* Cache blocking mode of async socket. */
80 };
81
82 /*
83 * These bits may be OR'ed together into the "flags" field of a TcpState
84 * structure.
85 */
86
87 #define TCP_NONBLOCKING (1<<0) /* Socket with non-blocking I/O */
88 #define TCP_ASYNC_CONNECT (1<<1) /* Async connect in progress. */
89 #define TCP_ASYNC_PENDING (1<<4) /* TcpConnect was called to
90 * process an async connect. This
91 * flag indicates that reentry is
92 * still pending */
93 #define TCP_ASYNC_FAILED (1<<5) /* An async connect finally failed */
94
95 /*
96 * The following defines the maximum length of the listen queue. This is the
97 * number of outstanding yet-to-be-serviced requests for a connection on a
98 * server socket, more than this number of outstanding requests and the
99 * connection request will fail.
100 */
101
102 #ifndef SOMAXCONN
103 # define SOMAXCONN 100
104 #elif (SOMAXCONN < 100)
105 # undef SOMAXCONN
106 # define SOMAXCONN 100
107 #endif /* SOMAXCONN < 100 */
108
109 /*
110 * The following defines how much buffer space the kernel should maintain for
111 * a socket.
112 */
113
114 #define SOCKET_BUFSIZE 4096
115
116 /*
117 * Static routines for this file:
118 */
119
120 static void TcpAsyncCallback(void *clientData, int mask);
121 static int TcpConnect(Tcl_Interp *interp, TcpState *state);
122 static void TcpAccept(void *data, int mask);
123 static int TcpBlockModeProc(void *data, int mode);
124 static int TcpCloseProc(void *instanceData,
125 Tcl_Interp *interp);
126 static int TcpClose2Proc(void *instanceData,
127 Tcl_Interp *interp, int flags);
128 static int TcpGetHandleProc(void *instanceData,
129 int direction, void **handlePtr);
130 static int TcpGetOptionProc(void *instanceData,
131 Tcl_Interp *interp, const char *optionName,
132 Tcl_DString *dsPtr);
133 static int TcpInputProc(void *instanceData, char *buf,
134 int toRead, int *errorCode);
135 static int TcpOutputProc(void *instanceData,
136 const char *buf, int toWrite, int *errorCode);
137 static void TcpThreadActionProc(void *instanceData, int action);
138 static void TcpWatchProc(void *instanceData, int mask);
139 static int WaitForConnect(TcpState *statePtr, int *errorCodePtr);
140 static Tcl_FileProc WrapNotify;
141
142 /*
143 * This structure describes the channel type structure for TCP socket
144 * based IO:
145 */
146
147 static const Tcl_ChannelType tcpChannelType = {
148 "tcp",
149 TCL_CHANNEL_VERSION_5,
150 TcpCloseProc,
151 TcpInputProc,
152 TcpOutputProc,
153 NULL, /* Seek proc. */
154 NULL, /* Set option proc. */
155 TcpGetOptionProc,
156 TcpWatchProc,
157 TcpGetHandleProc,
158 TcpClose2Proc,
159 TcpBlockModeProc,
160 NULL, /* Flush proc. */
161 NULL, /* Bubbled event handler proc. */
162 NULL, /* Seek proc. */
163 TcpThreadActionProc,
164 NULL /* Truncate proc. */
165 };
166
167 /*
168 * The following variable holds the network name of this host.
169 */
170
171 static TclInitProcessGlobalValueProc InitializeHostName;
172 static ProcessGlobalValue hostName =
173 {0, 0, NULL, NULL, InitializeHostName, NULL, NULL};
174
175 #if 0
176 /* printf debugging */
177 void
178 printaddrinfo(
179 struct addrinfo *addrlist,
180 char *prefix)
181 {
182 char host[NI_MAXHOST], port[NI_MAXSERV];
183 struct addrinfo *ai;
184
185 for (ai = addrlist; ai != NULL; ai = ai->ai_next) {
186 getnameinfo(ai->ai_addr, ai->ai_addrlen,
187 host, sizeof(host), port, sizeof(port),
188 NI_NUMERICHOST|NI_NUMERICSERV);
189 fprintf(stderr,"%s: %s:%s\n", prefix, host, port);
190 }
191 }
192 #endif
193 /*
194 * ----------------------------------------------------------------------
195 *
196 * InitializeHostName --
197 *
198 * This routine sets the process global value of the name of the local
199 * host on which the process is running.
200 *
201 * Results:
202 * None.
203 *
204 * ----------------------------------------------------------------------
205 */
206
207 static void
208 InitializeHostName(
209 char **valuePtr,
210 int *lengthPtr,
211 Tcl_Encoding *encodingPtr)
212 {
213 const char *native = NULL;
214
215 #ifndef NO_UNAME
216 struct utsname u;
217 struct hostent *hp;
218
219 memset(&u, (int) 0, sizeof(struct utsname));
220 if (uname(&u) >= 0) { /* INTL: Native. */
221 hp = TclpGetHostByName(u.nodename); /* INTL: Native. */
222 if (hp == NULL) {
223 /*
224 * Sometimes the nodename is fully qualified, but gets truncated
225 * as it exceeds SYS_NMLN. See if we can just get the immediate
226 * nodename and get a proper answer that way.
227 */
228
229 char *dot = strchr(u.nodename, '.');
230
231 if (dot != NULL) {
232 char *node = (char *)ckalloc(dot - u.nodename + 1);
233
234 memcpy(node, u.nodename, dot - u.nodename);
235 node[dot - u.nodename] = '\0';
236 hp = TclpGetHostByName(node);
237 ckfree(node);
238 }
239 }
240 if (hp != NULL) {
241 native = hp->h_name;
242 } else {
243 native = u.nodename;
244 }
245 }
246 if (native == NULL) {
247 native = tclEmptyStringRep;
248 }
249 #else /* !NO_UNAME */
250 /*
251 * Uname doesn't exist; try gethostname instead.
252 *
253 * There is no portable macro for the maximum length of host names
254 * returned by gethostbyname(). We should only trust SYS_NMLN if it is at
255 * least 255 + 1 bytes to comply with DNS host name limits.
256 *
257 * Note: SYS_NMLN is a restriction on "uname" not on gethostbyname!
258 *
259 * For example HP-UX 10.20 has SYS_NMLN == 9, while gethostbyname() can
260 * return a fully qualified name from DNS of up to 255 bytes.
261 *
262 * Fix suggested by Viktor Dukhovni ([email protected])
263 */
264
265 # if defined(SYS_NMLN) && (SYS_NMLEN >= 256)
266 char buffer[SYS_NMLEN];
267 # else
268 char buffer[256];
269 # endif
270
271 if (gethostname(buffer, sizeof(buffer)) >= 0) { /* INTL: Native. */
272 native = buffer;
273 }
274 #endif /* NO_UNAME */
275
276 *encodingPtr = Tcl_GetEncoding(NULL, NULL);
277 *lengthPtr = strlen(native);
278 *valuePtr = (char *)ckalloc(*lengthPtr + 1);
279 memcpy(*valuePtr, native, *lengthPtr + 1);
280 }
281
282 /*
283 * ----------------------------------------------------------------------
284 *
285 * Tcl_GetHostName --
286 *
287 * Returns the name of the local host.
288 *
289 * Results:
290 * A string containing the network name for this machine, or an empty
291 * string if we can't figure out the name. The caller must not modify or
292 * free this string.
293 *
294 * Side effects:
295 * Caches the name to return for future calls.
296 *
297 * ----------------------------------------------------------------------
298 */
299
300 const char *
301 Tcl_GetHostName(void)
302 {
303 return Tcl_GetString(TclGetProcessGlobalValue(&hostName));
304 }
305
306 /*
307 * ----------------------------------------------------------------------
308 *
309 * TclpHasSockets --
310 *
311 * Detect if sockets are available on this platform.
312 *
313 * Results:
314 * Returns TCL_OK.
315 *
316 * Side effects:
317 * None.
318 *
319 * ----------------------------------------------------------------------
320 */
321
322 int
323 TclpHasSockets(
324 Tcl_Interp *dummy) /* Not used. */
325 {
326 (void)dummy;
327
328 return TCL_OK;
329 }
330
331 /*
332 * ----------------------------------------------------------------------
333 *
334 * TclpFinalizeSockets --
335 *
336 * Performs per-thread socket subsystem finalization.
337 *
338 * Results:
339 * None.
340 *
341 * Side effects:
342 * None.
343 *
344 * ----------------------------------------------------------------------
345 */
346
347 void
348 TclpFinalizeSockets(void)
349 {
350 return;
351 }
352
353 /*
354 * ----------------------------------------------------------------------
355 *
356 * TcpBlockModeProc --
357 *
358 * This function is invoked by the generic IO level to set blocking and
359 * nonblocking mode on a TCP socket based channel.
360 *
361 * Results:
362 * 0 if successful, errno when failed.
363 *
364 * Side effects:
365 * Sets the device into blocking or nonblocking mode.
366 *
367 * ----------------------------------------------------------------------
368 */
369
370 static int
371 TcpBlockModeProc(
372 void *instanceData, /* Socket state. */
373 int mode) /* The mode to set. Can be one of
374 * TCL_MODE_BLOCKING or
375 * TCL_MODE_NONBLOCKING. */
376 {
377 TcpState *statePtr = (TcpState *)instanceData;
378
379 if (mode == TCL_MODE_BLOCKING) {
380 CLEAR_BITS(statePtr->flags, TCP_NONBLOCKING);
381 } else {
382 SET_BITS(statePtr->flags, TCP_NONBLOCKING);
383 }
384 if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
385 statePtr->cachedBlocking = mode;
386 return 0;
387 }
388 if (TclUnixSetBlockingMode(statePtr->fds.fd, mode) < 0) {
389 return errno;
390 }
391 return 0;
392 }
393
394 /*
395 * ----------------------------------------------------------------------
396 *
397 * WaitForConnect --
398 *
399 * Check the state of an async connect process. If a connection attempt
400 * terminated, process it, which may finalize it or may start the next
401 * attempt. If a connect error occurs, it is saved in
402 * statePtr->connectError to be reported by 'fconfigure -error'.
403 *
404 * There are two modes of operation, defined by errorCodePtr:
405 * * non-NULL: Called by explicit read/write command. Blocks if the
406 * socket is blocking.
407 * May return two error codes:
408 * * EWOULDBLOCK: if connect is still in progress
409 * * ENOTCONN: if connect failed. This would be the error message
410 * of a recv or sendto syscall so this is emulated here.
411 * * NULL: Called by a background operation. Do not block and do not
412 * return any error code.
413 *
414 * Results:
415 * 0 if the connection has completed, -1 if still in progress or there is
416 * an error.
417 *
418 * Side effects:
419 * Processes socket events off the system queue. May process
420 * asynchronous connects.
421 *
422 *----------------------------------------------------------------------
423 */
424
425 static int
426 WaitForConnect(
427 TcpState *statePtr, /* State of the socket. */
428 int *errorCodePtr)
429 {
430 int timeout;
431
432 /*
433 * Check if an async connect failed already and error reporting is
434 * demanded, return the error ENOTCONN
435 */
436
437 if (errorCodePtr != NULL && GOT_BITS(statePtr->flags, TCP_ASYNC_FAILED)) {
438 *errorCodePtr = ENOTCONN;
439 return -1;
440 }
441
442 /*
443 * Check if an async connect is running. If not return ok.
444 */
445
446 if (!GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
447 return 0;
448 }
449
450 if (errorCodePtr == NULL || GOT_BITS(statePtr->flags, TCP_NONBLOCKING)) {
451 timeout = 0;
452 } else {
453 timeout = -1;
454 }
455 do {
456 if (TclUnixWaitForFile(statePtr->fds.fd,
457 TCL_WRITABLE | TCL_EXCEPTION, timeout) != 0) {
458 TcpConnect(NULL, statePtr);
459 }
460
461 /*
462 * Do this only once in the nonblocking case and repeat it until the
463 * socket is final when blocking.
464 */
465 } while (timeout == -1 && GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT));
466
467 if (errorCodePtr != NULL) {
468 if (GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
469 *errorCodePtr = EAGAIN;
470 return -1;
471 } else if (statePtr->connectError != 0) {
472 *errorCodePtr = ENOTCONN;
473 return -1;
474 }
475 }
476 return 0;
477 }
478
479 /*
480 *----------------------------------------------------------------------
481 *
482 * TcpInputProc --
483 *
484 * This function is invoked by the generic IO level to read input from a
485 * TCP socket based channel.
486 *
487 * NOTE: We cannot share code with FilePipeInputProc because here we must
488 * use recv to obtain the input from the channel, not read.
489 *
490 * Results:
491 * The number of bytes read is returned or -1 on error. An output
492 * argument contains the POSIX error code on error, or zero if no error
493 * occurred.
494 *
495 * Side effects:
496 * Reads input from the input device of the channel.
497 *
498 *----------------------------------------------------------------------
499 */
500
501 static int
502 TcpInputProc(
503 void *instanceData, /* Socket state. */
504 char *buf, /* Where to store data read. */
505 int bufSize, /* How much space is available in the
506 * buffer? */
507 int *errorCodePtr) /* Where to store error code. */
508 {
509 TcpState *statePtr = (TcpState *)instanceData;
510 int bytesRead;
511
512 *errorCodePtr = 0;
513 if (WaitForConnect(statePtr, errorCodePtr) != 0) {
514 return -1;
515 }
516 bytesRead = recv(statePtr->fds.fd, buf, bufSize, 0);
517 if (bytesRead >= 0) {
518 return bytesRead;
519 }
520 if (errno == ECONNRESET) {
521 /*
522 * Turn ECONNRESET into a soft EOF condition.
523 */
524
525 return 0;
526 }
527 *errorCodePtr = errno;
528 return -1;
529 }
530
531 /*
532 *----------------------------------------------------------------------
533 *
534 * TcpOutputProc --
535 *
536 * This function is invoked by the generic IO level to write output to a
537 * TCP socket based channel.
538 *
539 * NOTE: We cannot share code with FilePipeOutputProc because here we
540 * must use send, not write, to get reliable error reporting.
541 *
542 * Results:
543 * The number of bytes written is returned. An output argument is set to
544 * a POSIX error code if an error occurred, or zero.
545 *
546 * Side effects:
547 * Writes output on the output device of the channel.
548 *
549 *----------------------------------------------------------------------
550 */
551
552 static int
553 TcpOutputProc(
554 void *instanceData, /* Socket state. */
555 const char *buf, /* The data buffer. */
556 int toWrite, /* How many bytes to write? */
557 int *errorCodePtr) /* Where to store error code. */
558 {
559 TcpState *statePtr = (TcpState *)instanceData;
560 int written;
561
562 *errorCodePtr = 0;
563 if (WaitForConnect(statePtr, errorCodePtr) != 0) {
564 return -1;
565 }
566 written = send(statePtr->fds.fd, buf, toWrite, 0);
567
568 if (written >= 0) {
569 return written;
570 }
571 *errorCodePtr = errno;
572 return -1;
573 }
574
575 /*
576 *----------------------------------------------------------------------
577 *
578 * TcpCloseProc --
579 *
580 * This function is invoked by the generic IO level to perform
581 * channel-type-specific cleanup when a TCP socket based channel is
582 * closed.
583 *
584 * Results:
585 * 0 if successful, the value of errno if failed.
586 *
587 * Side effects:
588 * Closes the socket of the channel.
589 *
590 *----------------------------------------------------------------------
591 */
592
593 static int
594 TcpCloseProc(
595 void *instanceData, /* The socket to close. */
596 Tcl_Interp *dummy) /* For error reporting - unused. */
597 {
598 TcpState *statePtr = (TcpState *)instanceData;
599 int errorCode = 0;
600 TcpFdList *fds;
601 (void)dummy;
602
603 /*
604 * Delete a file handler that may be active for this socket if this is a
605 * server socket - the file handler was created automatically by Tcl as
606 * part of the mechanism to accept new client connections. Channel
607 * handlers are already deleted in the generic IO channel closing code
608 * that called this function, so we do not have to delete them here.
609 */
610
611 for (fds = &statePtr->fds; fds != NULL; fds = fds->next) {
612 if (fds->fd < 0) {
613 continue;
614 }
615 Tcl_DeleteFileHandler(fds->fd);
616 if (close(fds->fd) < 0) {
617 errorCode = errno;
618 }
619
620 }
621 fds = statePtr->fds.next;
622 while (fds != NULL) {
623 TcpFdList *next = fds->next;
624
625 ckfree(fds);
626 fds = next;
627 }
628 if (statePtr->addrlist != NULL) {
629 freeaddrinfo(statePtr->addrlist);
630 }
631 if (statePtr->myaddrlist != NULL) {
632 freeaddrinfo(statePtr->myaddrlist);
633 }
634 ckfree(statePtr);
635 return errorCode;
636 }
637
638 /*
639 *----------------------------------------------------------------------
640 *
641 * TcpClose2Proc --
642 *
643 * This function is called by the generic IO level to perform the channel
644 * type specific part of a half-close: namely, a shutdown() on a socket.
645 *
646 * Results:
647 * 0 if successful, the value of errno if failed.
648 *
649 * Side effects:
650 * Shuts down one side of the socket.
651 *
652 *----------------------------------------------------------------------
653 */
654
655 static int
656 TcpClose2Proc(
657 void *instanceData, /* The socket to close. */
658 Tcl_Interp *dummy, /* For error reporting. */
659 int flags) /* Flags that indicate which side to close. */
660 {
661 TcpState *statePtr = (TcpState *)instanceData;
662 int readError = 0;
663 int writeError = 0;
664 (void)dummy;
665
666 /*
667 * Shutdown the OS socket handle.
668 */
669 if ((flags & (TCL_CLOSE_READ|TCL_CLOSE_WRITE)) == 0) {
670 return TcpCloseProc(instanceData, NULL);
671 }
672 if ((flags & TCL_CLOSE_READ) && (shutdown(statePtr->fds.fd, SHUT_RD) < 0)) {
673 readError = errno;
674 }
675 if ((flags & TCL_CLOSE_WRITE) && (shutdown(statePtr->fds.fd, SHUT_WR) < 0)) {
676 writeError = errno;
677 }
678 return (readError != 0) ? readError : writeError;
679 }
680
681 /*
682 *----------------------------------------------------------------------
683 *
684 * TcpHostPortList --
685 *
686 * This function is called by the -gethostname and -getpeername switches
687 * of TcpGetOptionProc() to add three list elements with the textual
688 * representation of the given address to the given DString.
689 *
690 * Results:
691 * None.
692 *
693 * Side effects:
694 * Adds three elements do dsPtr
695 *
696 *----------------------------------------------------------------------
697 */
698
699 #ifndef NEED_FAKE_RFC2553
700 #if defined (__clang__) || ((__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
701 #pragma GCC diagnostic push
702 #pragma GCC diagnostic ignored "-Wstrict-aliasing"
703 #endif
704 static inline int
705 IPv6AddressNeedsNumericRendering(
706 struct in6_addr addr)
707 {
708 if (IN6_ARE_ADDR_EQUAL(&addr, &in6addr_any)) {
709 return 1;
710 }
711
712 /*
713 * The IN6_IS_ADDR_V4MAPPED macro has a problem with aliasing warnings on
714 * at least some versions of OSX.
715 */
716
717 if (!IN6_IS_ADDR_V4MAPPED(&addr)) {
718 return 0;
719 }
720
721 return (addr.s6_addr[12] == 0 && addr.s6_addr[13] == 0
722 && addr.s6_addr[14] == 0 && addr.s6_addr[15] == 0);
723 }
724 #if defined (__clang__) || ((__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
725 #pragma GCC diagnostic pop
726 #endif
727 #endif /* NEED_FAKE_RFC2553 */
728
729 static void
730 TcpHostPortList(
731 Tcl_Interp *interp,
732 Tcl_DString *dsPtr,
733 address addr,
734 socklen_t salen)
735 {
736 #define SUPPRESS_RDNS_VAR "::tcl::unsupported::noReverseDNS"
737 char host[NI_MAXHOST], nhost[NI_MAXHOST], nport[NI_MAXSERV];
738 int flags = 0;
739
740 getnameinfo(&addr.sa, salen, nhost, sizeof(nhost), nport, sizeof(nport),
741 NI_NUMERICHOST | NI_NUMERICSERV);
742 Tcl_DStringAppendElement(dsPtr, nhost);
743
744 /*
745 * We don't want to resolve INADDR_ANY and sin6addr_any; they can
746 * sometimes cause problems (and never have a name).
747 */
748
749 if (addr.sa.sa_family == AF_INET) {
750 if (addr.sa4.sin_addr.s_addr == INADDR_ANY) {
751 flags |= NI_NUMERICHOST;
752 }
753 #ifndef NEED_FAKE_RFC2553
754 } else if (addr.sa.sa_family == AF_INET6) {
755 if (IPv6AddressNeedsNumericRendering(addr.sa6.sin6_addr)) {
756 flags |= NI_NUMERICHOST;
757 }
758 #endif /* NEED_FAKE_RFC2553 */
759 }
760
761 /*
762 * Check if reverse DNS has been switched off globally.
763 */
764
765 if (interp != NULL &&
766 Tcl_GetVar2(interp, SUPPRESS_RDNS_VAR, NULL, 0) != NULL) {
767 flags |= NI_NUMERICHOST;
768 }
769 if (getnameinfo(&addr.sa, salen, host, sizeof(host), NULL, 0,
770 flags) == 0) {
771 /*
772 * Reverse mapping worked.
773 */
774
775 Tcl_DStringAppendElement(dsPtr, host);
776 } else {
777 /*
778 * Reverse mapping failed - use the numeric rep once more.
779 */
780
781 Tcl_DStringAppendElement(dsPtr, nhost);
782 }
783 Tcl_DStringAppendElement(dsPtr, nport);
784 }
785
786 /*
787 *----------------------------------------------------------------------
788 *
789 * TcpGetOptionProc --
790 *
791 * Computes an option value for a TCP socket based channel, or a list of
792 * all options and their values.
793 *
794 * Note: This code is based on code contributed by John Haxby.
795 *
796 * Results:
797 * A standard Tcl result. The value of the specified option or a list of
798 * all options and their values is returned in the supplied DString. Sets
799 * Error message if needed.
800 *
801 * Side effects:
802 * None.
803 *
804 *----------------------------------------------------------------------
805 */
806
807 static int
808 TcpGetOptionProc(
809 void *instanceData, /* Socket state. */
810 Tcl_Interp *interp, /* For error reporting - can be NULL. */
811 const char *optionName, /* Name of the option to retrieve the value
812 * for, or NULL to get all options and their
813 * values. */
814 Tcl_DString *dsPtr) /* Where to store the computed value;
815 * initialized by caller. */
816 {
817 TcpState *statePtr = (TcpState *)instanceData;
818 size_t len = 0;
819
820 WaitForConnect(statePtr, NULL);
821
822 if (optionName != NULL) {
823 len = strlen(optionName);
824 }
825
826 if ((len > 1) && (optionName[1] == 'e') &&
827 (strncmp(optionName, "-error", len) == 0)) {
828 socklen_t optlen = sizeof(int);
829
830 if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
831 /*
832 * Suppress errors as long as we are not done.
833 */
834
835 errno = 0;
836 } else if (statePtr->connectError != 0) {
837 errno = statePtr->connectError;
838 statePtr->connectError = 0;
839 } else {
840 int err;
841
842 getsockopt(statePtr->fds.fd, SOL_SOCKET, SO_ERROR, (char *) &err,
843 &optlen);
844 errno = err;
845 }
846 if (errno != 0) {
847 Tcl_DStringAppend(dsPtr, Tcl_ErrnoMsg(errno), -1);
848 }
849 return TCL_OK;
850 }
851
852 if ((len > 1) && (optionName[1] == 'c') &&
853 (strncmp(optionName, "-connecting", len) == 0)) {
854 Tcl_DStringAppend(dsPtr,
855 GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT) ? "1" : "0", -1);
856 return TCL_OK;
857 }
858
859 if ((len == 0) || ((len > 1) && (optionName[1] == 'p') &&
860 (strncmp(optionName, "-peername", len) == 0))) {
861 address peername;
862 socklen_t size = sizeof(peername);
863
864 if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
865 /*
866 * In async connect output an empty string
867 */
868
869 if (len == 0) {
870 Tcl_DStringAppendElement(dsPtr, "-peername");
871 Tcl_DStringAppendElement(dsPtr, "");
872 } else {
873 return TCL_OK;
874 }
875 } else if (getpeername(statePtr->fds.fd, &peername.sa, &size) >= 0) {
876 /*
877 * Peername fetch succeeded - output list
878 */
879
880 if (len == 0) {
881 Tcl_DStringAppendElement(dsPtr, "-peername");
882 Tcl_DStringStartSublist(dsPtr);
883 }
884 TcpHostPortList(interp, dsPtr, peername, size);
885 if (len) {
886 return TCL_OK;
887 }
888 Tcl_DStringEndSublist(dsPtr);
889 } else {
890 /*
891 * getpeername failed - but if we were asked for all the options
892 * (len==0), don't flag an error at that point because it could be
893 * an fconfigure request on a server socket (which have no peer).
894 * Same must be done on win&mac.
895 */
896
897 if (len) {
898 if (interp) {
899 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
900 "can't get peername: %s",
901 Tcl_PosixError(interp)));
902 }
903 return TCL_ERROR;
904 }
905 }
906 }
907
908 if ((len == 0) || ((len > 1) && (optionName[1] == 's') &&
909 (strncmp(optionName, "-sockname", len) == 0))) {
910 TcpFdList *fds;
911 address sockname;
912 socklen_t size;
913 int found = 0;
914
915 if (len == 0) {
916 Tcl_DStringAppendElement(dsPtr, "-sockname");
917 Tcl_DStringStartSublist(dsPtr);
918 }
919 if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
920 /*
921 * In async connect output an empty string
922 */
923
924 found = 1;
925 } else {
926 for (fds = &statePtr->fds; fds != NULL; fds = fds->next) {
927 size = sizeof(sockname);
928 if (getsockname(fds->fd, &(sockname.sa), &size) >= 0) {
929 found = 1;
930 TcpHostPortList(interp, dsPtr, sockname, size);
931 }
932 }
933 }
934 if (found) {
935 if (len) {
936 return TCL_OK;
937 }
938 Tcl_DStringEndSublist(dsPtr);
939 } else {
940 if (interp) {
941 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
942 "can't get sockname: %s", Tcl_PosixError(interp)));
943 }
944 return TCL_ERROR;
945 }
946 }
947
948 if (len > 0) {
949 return Tcl_BadChannelOption(interp, optionName,
950 "connecting peername sockname");
951 }
952
953 return TCL_OK;
954 }
955
956 /*
957 * ----------------------------------------------------------------------
958 *
959 * TcpThreadActionProc --
960 *
961 * Handles detach/attach for asynchronously connecting socket.
962 *
963 * Reassigning the file handler associated with thread-related channel
964 * notification, responsible for callbacks (signaling that asynchronous
965 * connection attempt has succeeded or failed).
966 *
967 * Results:
968 * None.
969 *
970 * ----------------------------------------------------------------------
971 */
972
973 static void
974 TcpThreadActionProc(
975 void *instanceData,
976 int action)
977 {
978 TcpState *statePtr = (TcpState *)instanceData;
979
980 if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
981 /*
982 * Async-connecting socket must get reassigned handler if it have been
983 * transferred to another thread. Remove the handler if the socket is
984 * not managed by this thread anymore and create new handler (TSD related)
985 * so the callback will run in the correct thread, bug [f583715154].
986 */
987 switch (action) {
988 case TCL_CHANNEL_THREAD_REMOVE:
989 CLEAR_BITS(statePtr->flags, TCP_ASYNC_PENDING);
990 Tcl_DeleteFileHandler(statePtr->fds.fd);
991 break;
992 case TCL_CHANNEL_THREAD_INSERT:
993 Tcl_CreateFileHandler(statePtr->fds.fd,
994 TCL_WRITABLE | TCL_EXCEPTION, TcpAsyncCallback, statePtr);
995 SET_BITS(statePtr->flags, TCP_ASYNC_PENDING);
996 break;
997 }
998 }
999 }
1000
1001 /*
1002 * ----------------------------------------------------------------------
1003 *
1004 * TcpWatchProc --
1005 *
1006 * Initialize the notifier to watch the fd from this channel.
1007 *
1008 * Results:
1009 * None.
1010 *
1011 * Side effects:
1012 * Sets up the notifier so that a future event on the channel will be
1013 * seen by Tcl.
1014 *
1015 * ----------------------------------------------------------------------
1016 */
1017
1018 static void
1019 WrapNotify(
1020 void *clientData,
1021 int mask)
1022 {
1023 TcpState *statePtr = (TcpState *) clientData;
1024 int newmask = mask & statePtr->interest;
1025
1026 if (newmask == 0) {
1027 /*
1028 * There was no overlap between the states the channel is interested
1029 * in notifications for, and the states that are reported present on
1030 * the file descriptor by select(). The only way that can happen is
1031 * when the channel is interested in a writable condition, and only a
1032 * readable state is reported present (see TcpWatchProc() below). In
1033 * that case, signal back to the caller the writable state, which is
1034 * really an error condition. As an extra check on that assumption,
1035 * check for a non-zero value of errno before reporting an artificial
1036 * writable state.
1037 */
1038
1039 if (errno == 0) {
1040 return;
1041 }
1042 newmask = TCL_WRITABLE;
1043 }
1044 Tcl_NotifyChannel(statePtr->channel, newmask);
1045 }
1046
1047 static void
1048 TcpWatchProc(
1049 void *instanceData, /* The socket state. */
1050 int mask) /* Events of interest; an OR-ed combination of
1051 * TCL_READABLE, TCL_WRITABLE and
1052 * TCL_EXCEPTION. */
1053 {
1054 TcpState *statePtr = (TcpState *)instanceData;
1055
1056 if (statePtr->acceptProc != NULL) {
1057 /*
1058 * Make sure we don't mess with server sockets since they will never
1059 * be readable or writable at the Tcl level. This keeps Tcl scripts
1060 * from interfering with the -accept behavior (bug #3394732).
1061 */
1062
1063 return;
1064 }
1065
1066 if (GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
1067 /*
1068 * Async sockets use a FileHandler internally while connecting, so we
1069 * need to cache this request until the connection has succeeded.
1070 */
1071
1072 statePtr->filehandlers = mask;
1073 } else if (mask) {
1074
1075 /*
1076 * Whether it is a bug or feature or otherwise, it is a fact of life
1077 * that on at least some Linux kernels select() fails to report that a
1078 * socket file descriptor is writable when the other end of the socket
1079 * is closed. This is in contrast to the guarantees Tcl makes that
1080 * its channels become writable and fire writable events on an error
1081 * condition. This has caused a leak of file descriptors in a state of
1082 * background flushing. See Tcl ticket 1758a0b603.
1083 *
1084 * As a workaround, when our caller indicates an interest in writable
1085 * notifications, we must tell the notifier built around select() that
1086 * we are interested in the readable state of the file descriptor as
1087 * well, as that is the only reliable means to get notified of error
1088 * conditions. Then it is the task of WrapNotify() above to untangle
1089 * the meaning of these channel states and report the chan events as
1090 * best it can. We save a copy of the mask passed in to assist with
1091 * that.
1092 */
1093
1094 statePtr->interest = mask;
1095 Tcl_CreateFileHandler(statePtr->fds.fd, mask|TCL_READABLE,
1096 WrapNotify, statePtr);
1097 } else {
1098 Tcl_DeleteFileHandler(statePtr->fds.fd);
1099 }
1100 }
1101
1102 /*
1103 * ----------------------------------------------------------------------
1104 *
1105 * TcpGetHandleProc --
1106 *
1107 * Called from Tcl_GetChannelHandle to retrieve OS handles from inside a
1108 * TCP socket based channel.
1109 *
1110 * Results:
1111 * Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if there is no
1112 * handle for the specified direction.
1113 *
1114 * Side effects:
1115 * None.
1116 *
1117 * ----------------------------------------------------------------------
1118 */
1119
1120 static int
1121 TcpGetHandleProc(
1122 void *instanceData, /* The socket state. */
1123 int direction, /* Not used. */
1124 void **handlePtr) /* Where to store the handle. */
1125 {
1126 TcpState *statePtr = (TcpState *)instanceData;
1127 (void)direction;
1128
1129 *handlePtr = INT2PTR(statePtr->fds.fd);
1130 return TCL_OK;
1131 }
1132
1133 /*
1134 * ----------------------------------------------------------------------
1135 *
1136 * TcpAsyncCallback --
1137 *
1138 * Called by the event handler that TcpConnect sets up internally for
1139 * [socket -async] to get notified when the asynchronous connection
1140 * attempt has succeeded or failed.
1141 *
1142 * ----------------------------------------------------------------------
1143 */
1144
1145 static void
1146 TcpAsyncCallback(
1147 void *clientData, /* The socket state. */
1148 int mask) /* Events of interest; an OR-ed combination of
1149 * TCL_READABLE, TCL_WRITABLE and
1150 * TCL_EXCEPTION. */
1151 {
1152 (void)mask;
1153
1154 TcpConnect(NULL, (TcpState *)clientData);
1155 }
1156
1157 /*
1158 * ----------------------------------------------------------------------
1159 *
1160 * TcpConnect --
1161 *
1162 * This function opens a new socket in client mode.
1163 *
1164 * Results:
1165 * TCL_OK, if the socket was successfully connected or an asynchronous
1166 * connection is in progress. If an error occurs, TCL_ERROR is returned
1167 * and an error message is left in interp.
1168 *
1169 * Side effects:
1170 * Opens a socket.
1171 *
1172 * Remarks:
1173 * A single host name may resolve to more than one IP address, e.g. for
1174 * an IPv4/IPv6 dual stack host. For handling asynchronously connecting
1175 * sockets in the background for such hosts, this function can act as a
1176 * coroutine. On the first call, it sets up the control variables for the
1177 * two nested loops over the local and remote addresses. Once the first
1178 * connection attempt is in progress, it sets up itself as a writable
1179 * event handler for that socket, and returns. When the callback occurs,
1180 * control is transferred to the "reenter" label, right after the initial
1181 * return and the loops resume as if they had never been interrupted.
1182 * For synchronously connecting sockets, the loops work the usual way.
1183 *
1184 * ----------------------------------------------------------------------
1185 */
1186
1187 static int
1188 TcpConnect(
1189 Tcl_Interp *interp, /* For error reporting; can be NULL. */
1190 TcpState *statePtr)
1191 {
1192 socklen_t optlen;
1193 int async_callback = GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING);
1194 int ret = -1, error = EHOSTUNREACH;
1195 int async = GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT);
1196 static const int reuseaddr = 1;
1197
1198 if (async_callback) {
1199 goto reenter;
1200 }
1201
1202 for (statePtr->addr = statePtr->addrlist; statePtr->addr != NULL;
1203 statePtr->addr = statePtr->addr->ai_next) {
1204 for (statePtr->myaddr = statePtr->myaddrlist;
1205 statePtr->myaddr != NULL;
1206 statePtr->myaddr = statePtr->myaddr->ai_next) {
1207 /*
1208 * No need to try combinations of local and remote addresses of
1209 * different families.
1210 */
1211
1212 if (statePtr->myaddr->ai_family != statePtr->addr->ai_family) {
1213 continue;
1214 }
1215
1216 /*
1217 * Close the socket if it is still open from the last unsuccessful
1218 * iteration.
1219 */
1220
1221 if (statePtr->fds.fd >= 0) {
1222 close(statePtr->fds.fd);
1223 statePtr->fds.fd = -1;
1224 errno = 0;
1225 }
1226
1227 statePtr->fds.fd = socket(statePtr->addr->ai_family, SOCK_STREAM,
1228 0);
1229 if (statePtr->fds.fd < 0) {
1230 continue;
1231 }
1232
1233 /*
1234 * Set the close-on-exec flag so that the socket will not get
1235 * inherited by child processes.
1236 */
1237
1238 fcntl(statePtr->fds.fd, F_SETFD, FD_CLOEXEC);
1239
1240 /*
1241 * Set kernel space buffering
1242 */
1243
1244 TclSockMinimumBuffers(INT2PTR(statePtr->fds.fd), SOCKET_BUFSIZE);
1245
1246 if (async) {
1247 ret = TclUnixSetBlockingMode(statePtr->fds.fd,
1248 TCL_MODE_NONBLOCKING);
1249 if (ret < 0) {
1250 continue;
1251 }
1252 }
1253
1254 /*
1255 * Must reset the error variable here, before we use it for the
1256 * first time in this iteration.
1257 */
1258
1259 error = 0;
1260
1261 (void) setsockopt(statePtr->fds.fd, SOL_SOCKET, SO_REUSEADDR,
1262 (char *) &reuseaddr, sizeof(reuseaddr));
1263 ret = bind(statePtr->fds.fd, statePtr->myaddr->ai_addr,
1264 statePtr->myaddr->ai_addrlen);
1265 if (ret < 0) {
1266 error = errno;
1267 continue;
1268 }
1269
1270 /*
1271 * Attempt to connect. The connect may fail at present with an
1272 * EINPROGRESS but at a later time it will complete. The caller
1273 * will set up a file handler on the socket if she is interested
1274 * in being informed when the connect completes.
1275 */
1276
1277 ret = connect(statePtr->fds.fd, statePtr->addr->ai_addr,
1278 statePtr->addr->ai_addrlen);
1279 if (ret < 0) {
1280 error = errno;
1281 }
1282 if (ret < 0 && errno == EINPROGRESS) {
1283 Tcl_CreateFileHandler(statePtr->fds.fd,
1284 TCL_WRITABLE | TCL_EXCEPTION, TcpAsyncCallback,
1285 statePtr);
1286 errno = EWOULDBLOCK;
1287 SET_BITS(statePtr->flags, TCP_ASYNC_PENDING);
1288 return TCL_OK;
1289
1290 reenter:
1291 CLEAR_BITS(statePtr->flags, TCP_ASYNC_PENDING);
1292 Tcl_DeleteFileHandler(statePtr->fds.fd);
1293
1294 /*
1295 * Read the error state from the socket to see if the async
1296 * connection has succeeded or failed. As this clears the
1297 * error condition, we cache the status in the socket state
1298 * struct for later retrieval by [fconfigure -error].
1299 */
1300
1301 optlen = sizeof(int);
1302
1303 getsockopt(statePtr->fds.fd, SOL_SOCKET, SO_ERROR,
1304 (char *) &error, &optlen);
1305 errno = error;
1306 }
1307 if (error == 0) {
1308 goto out;
1309 }
1310 }
1311 }
1312
1313 out:
1314 statePtr->connectError = error;
1315 CLEAR_BITS(statePtr->flags, TCP_ASYNC_CONNECT);
1316 if (async_callback) {
1317 /*
1318 * An asynchonous connection has finally succeeded or failed.
1319 */
1320
1321 TcpWatchProc(statePtr, statePtr->filehandlers);
1322 TclUnixSetBlockingMode(statePtr->fds.fd, statePtr->cachedBlocking);
1323
1324 if (error != 0) {
1325 SET_BITS(statePtr->flags, TCP_ASYNC_FAILED);
1326 }
1327
1328 /*
1329 * We need to forward the writable event that brought us here, because
1330 * upon reading of getsockopt(SO_ERROR), at least some OSes clear the
1331 * writable state from the socket, and so a subsequent select() on
1332 * behalf of a script level [fileevent] would not fire. It doesn't
1333 * hurt that this is also called in the successful case and will save
1334 * the event mechanism one roundtrip through select().
1335 */
1336
1337 if (statePtr->cachedBlocking == TCL_MODE_NONBLOCKING) {
1338 Tcl_NotifyChannel(statePtr->channel, TCL_WRITABLE);
1339 }
1340 }
1341 if (error != 0) {
1342 /*
1343 * Failure for either a synchronous connection, or an async one that
1344 * failed before it could enter background mode, e.g. because an
1345 * invalid -myaddr was given.
1346 */
1347
1348 if (interp != NULL) {
1349 errno = error;
1350 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1351 "couldn't open socket: %s", Tcl_PosixError(interp)));
1352 }
1353 return TCL_ERROR;
1354 }
1355 return TCL_OK;
1356 }
1357
1358 /*
1359 *----------------------------------------------------------------------
1360 *
1361 * Tcl_OpenTcpClient --
1362 *
1363 * Opens a TCP client socket and creates a channel around it.
1364 *
1365 * Results:
1366 * The channel or NULL if failed. An error message is returned in the
1367 * interpreter on failure.
1368 *
1369 * Side effects:
1370 * Opens a client socket and creates a new channel.
1371 *
1372 *----------------------------------------------------------------------
1373 */
1374
1375 Tcl_Channel
1376 Tcl_OpenTcpClient(
1377 Tcl_Interp *interp, /* For error reporting; can be NULL. */
1378 int port, /* Port number to open. */
1379 const char *host, /* Host on which to open port. */
1380 const char *myaddr, /* Client-side address */
1381 int myport, /* Client-side port */
1382 int async) /* If nonzero, attempt to do an asynchronous
1383 * connect. Otherwise we do a blocking
1384 * connect. */
1385 {
1386 TcpState *statePtr;
1387 const char *errorMsg = NULL;
1388 struct addrinfo *addrlist = NULL, *myaddrlist = NULL;
1389 char channelName[SOCK_CHAN_LENGTH];
1390
1391 /*
1392 * Do the name lookups for the local and remote addresses.
1393 */
1394
1395 if (!TclCreateSocketAddress(interp, &addrlist, host, port, 0, &errorMsg)
1396 || !TclCreateSocketAddress(interp, &myaddrlist, myaddr, myport, 1,
1397 &errorMsg)) {
1398 if (addrlist != NULL) {
1399 freeaddrinfo(addrlist);
1400 }
1401 if (interp != NULL) {
1402 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1403 "couldn't open socket: %s", errorMsg));
1404 }
1405 return NULL;
1406 }
1407
1408 /*
1409 * Allocate a new TcpState for this socket.
1410 */
1411
1412 statePtr = (TcpState *)ckalloc(sizeof(TcpState));
1413 memset(statePtr, 0, sizeof(TcpState));
1414 statePtr->flags = async ? TCP_ASYNC_CONNECT : 0;
1415 statePtr->cachedBlocking = TCL_MODE_BLOCKING;
1416 statePtr->addrlist = addrlist;
1417 statePtr->myaddrlist = myaddrlist;
1418 statePtr->fds.fd = -1;
1419
1420 /*
1421 * Create a new client socket and wrap it in a channel.
1422 */
1423
1424 if (TcpConnect(interp, statePtr) != TCL_OK) {
1425 TcpCloseProc(statePtr, NULL);
1426 return NULL;
1427 }
1428
1429 snprintf(channelName, sizeof(channelName), SOCK_TEMPLATE, (long)statePtr);
1430
1431 statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
1432 statePtr, TCL_READABLE | TCL_WRITABLE);
1433 if (Tcl_SetChannelOption(interp, statePtr->channel, "-translation",
1434 "auto crlf") == TCL_ERROR) {
1435 Tcl_Close(NULL, statePtr->channel);
1436 return NULL;
1437 }
1438 return statePtr->channel;
1439 }
1440
1441 /*
1442 *----------------------------------------------------------------------
1443 *
1444 * Tcl_MakeTcpClientChannel --
1445 *
1446 * Creates a Tcl_Channel from an existing client TCP socket.
1447 *
1448 * Results:
1449 * The Tcl_Channel wrapped around the preexisting TCP socket.
1450 *
1451 * Side effects:
1452 * None.
1453 *
1454 *----------------------------------------------------------------------
1455 */
1456
1457 Tcl_Channel
1458 Tcl_MakeTcpClientChannel(
1459 void *sock) /* The socket to wrap up into a channel. */
1460 {
1461 return (Tcl_Channel) TclpMakeTcpClientChannelMode(sock,
1462 TCL_READABLE | TCL_WRITABLE);
1463 }
1464
1465 /*
1466 *----------------------------------------------------------------------
1467 *
1468 * TclpMakeTcpClientChannelMode --
1469 *
1470 * Creates a Tcl_Channel from an existing client TCP socket
1471 * with given mode.
1472 *
1473 * Results:
1474 * The Tcl_Channel wrapped around the preexisting TCP socket.
1475 *
1476 * Side effects:
1477 * None.
1478 *
1479 *----------------------------------------------------------------------
1480 */
1481
1482 void *
1483 TclpMakeTcpClientChannelMode(
1484 void *sock, /* The socket to wrap up into a channel. */
1485 int mode) /* OR'ed combination of TCL_READABLE and
1486 * TCL_WRITABLE to indicate file mode. */
1487 {
1488 TcpState *statePtr;
1489 char channelName[SOCK_CHAN_LENGTH];
1490
1491 statePtr = (TcpState *)ckalloc(sizeof(TcpState));
1492 memset(statePtr, 0, sizeof(TcpState));
1493 statePtr->fds.fd = PTR2INT(sock);
1494 statePtr->flags = 0;
1495
1496 snprintf(channelName, sizeof(channelName), SOCK_TEMPLATE, (long)statePtr);
1497
1498 statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
1499 statePtr, mode);
1500 if (Tcl_SetChannelOption(NULL, statePtr->channel, "-translation",
1501 "auto crlf") == TCL_ERROR) {
1502 Tcl_Close(NULL, statePtr->channel);
1503 return NULL;
1504 }
1505 return statePtr->channel;
1506 }
1507
1508 /*
1509 *----------------------------------------------------------------------
1510 *
1511 * Tcl_OpenTcpServer --
1512 *
1513 * Opens a TCP server socket and creates a channel around it.
1514 *
1515 * Results:
1516 * The channel or NULL if failed. If an error occurred, an error message
1517 * is left in the interp's result if interp is not NULL.
1518 *
1519 * Side effects:
1520 * Opens a server socket and creates a new channel.
1521 *
1522 *----------------------------------------------------------------------
1523 */
1524
1525 Tcl_Channel
1526 Tcl_OpenTcpServer(
1527 Tcl_Interp *interp, /* For error reporting - may be NULL. */
1528 int port, /* Port number to open. */
1529 const char *myHost, /* Name of local host. */
1530 Tcl_TcpAcceptProc *acceptProc,
1531 /* Callback for accepting connections from new
1532 * clients. */
1533 void *acceptProcData) /* Data for the callback. */
1534 {
1535 int status = 0, sock = -1, reuseaddr = 1, chosenport = 0;
1536 struct addrinfo *addrlist = NULL, *addrPtr; /* socket address */
1537 TcpState *statePtr = NULL;
1538 char channelName[SOCK_CHAN_LENGTH];
1539 const char *errorMsg = NULL;
1540 TcpFdList *fds = NULL, *newfds;
1541
1542 /*
1543 * Try to record and return the most meaningful error message, i.e. the
1544 * one from the first socket that went the farthest before it failed.
1545 */
1546
1547 enum { LOOKUP, SOCKET, BIND, LISTEN } howfar = LOOKUP;
1548 int my_errno = 0;
1549
1550 if (!TclCreateSocketAddress(interp, &addrlist, myHost, port, 1, &errorMsg)) {
1551 my_errno = errno;
1552 goto error;
1553 }
1554
1555 for (addrPtr = addrlist; addrPtr != NULL; addrPtr = addrPtr->ai_next) {
1556 sock = socket(addrPtr->ai_family, addrPtr->ai_socktype,
1557 addrPtr->ai_protocol);
1558 if (sock == -1) {
1559 if (howfar < SOCKET) {
1560 howfar = SOCKET;
1561 my_errno = errno;
1562 }
1563 continue;
1564 }
1565
1566 /*
1567 * Set the close-on-exec flag so that the socket will not get
1568 * inherited by child processes.
1569 */
1570
1571 fcntl(sock, F_SETFD, FD_CLOEXEC);
1572
1573 /*
1574 * Set kernel space buffering
1575 */
1576
1577 TclSockMinimumBuffers(INT2PTR(sock), SOCKET_BUFSIZE);
1578
1579 /*
1580 * Set up to reuse server addresses and/or ports if requested.
1581 */
1582
1583 (void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
1584 (char *) &reuseaddr, sizeof(reuseaddr));
1585
1586 /*
1587 * Make sure we use the same port number when opening two server
1588 * sockets for IPv4 and IPv6 on a random port.
1589 *
1590 * As sockaddr_in6 uses the same offset and size for the port member
1591 * as sockaddr_in, we can handle both through the IPv4 API.
1592 */
1593
1594 if (port == 0 && chosenport != 0) {
1595 ((struct sockaddr_in *) addrPtr->ai_addr)->sin_port =
1596 htons(chosenport);
1597 }
1598
1599 #ifdef IPV6_V6ONLY
1600 /*
1601 * Missing on: Solaris 2.8
1602 */
1603
1604 if (addrPtr->ai_family == AF_INET6) {
1605 int v6only = 1;
1606
1607 (void) setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
1608 &v6only, sizeof(v6only));
1609 }
1610 #endif /* IPV6_V6ONLY */
1611
1612 status = bind(sock, addrPtr->ai_addr, addrPtr->ai_addrlen);
1613 if (status == -1) {
1614 if (howfar < BIND) {
1615 howfar = BIND;
1616 my_errno = errno;
1617 }
1618 close(sock);
1619 sock = -1;
1620 continue;
1621 }
1622 if (port == 0 && chosenport == 0) {
1623 address sockname;
1624 socklen_t namelen = sizeof(sockname);
1625
1626 /*
1627 * Synchronize port numbers when binding to port 0 of multiple
1628 * addresses.
1629 */
1630
1631 if (getsockname(sock, &sockname.sa, &namelen) >= 0) {
1632 chosenport = ntohs(sockname.sa4.sin_port);
1633 }
1634 }
1635 status = listen(sock, SOMAXCONN);
1636 if (status < 0) {
1637 if (howfar < LISTEN) {
1638 howfar = LISTEN;
1639 my_errno = errno;
1640 }
1641 close(sock);
1642 sock = -1;
1643 continue;
1644 }
1645 if (statePtr == NULL) {
1646 /*
1647 * Allocate a new TcpState for this socket.
1648 */
1649
1650 statePtr = (TcpState *)ckalloc(sizeof(TcpState));
1651 memset(statePtr, 0, sizeof(TcpState));
1652 statePtr->acceptProc = acceptProc;
1653 statePtr->acceptProcData = acceptProcData;
1654 snprintf(channelName, sizeof(channelName), SOCK_TEMPLATE, (long)statePtr);
1655 newfds = &statePtr->fds;
1656 } else {
1657 newfds = (TcpFdList *)ckalloc(sizeof(TcpFdList));
1658 memset(newfds, (int) 0, sizeof(TcpFdList));
1659 fds->next = newfds;
1660 }
1661 newfds->fd = sock;
1662 newfds->statePtr = statePtr;
1663 fds = newfds;
1664
1665 /*
1666 * Set up the callback mechanism for accepting connections from new
1667 * clients.
1668 */
1669
1670 Tcl_CreateFileHandler(sock, TCL_READABLE, TcpAccept, fds);
1671 }
1672
1673 error:
1674 if (addrlist != NULL) {
1675 freeaddrinfo(addrlist);
1676 }
1677 if (statePtr != NULL) {
1678 statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
1679 statePtr, 0);
1680 return statePtr->channel;
1681 }
1682 if (interp != NULL) {
1683 Tcl_Obj *errorObj = Tcl_NewStringObj("couldn't open socket: ", -1);
1684
1685 if (errorMsg == NULL) {
1686 errno = my_errno;
1687 Tcl_AppendToObj(errorObj, Tcl_PosixError(interp), -1);
1688 } else {
1689 Tcl_AppendToObj(errorObj, errorMsg, -1);
1690 }
1691 Tcl_SetObjResult(interp, errorObj);
1692 }
1693 if (sock != -1) {
1694 close(sock);
1695 }
1696 return NULL;
1697 }
1698
1699 /*
1700 *----------------------------------------------------------------------
1701 *
1702 * TcpAccept --
1703 * Accept a TCP socket connection. This is called by the event loop.
1704 *
1705 * Results:
1706 * None.
1707 *
1708 * Side effects:
1709 * Creates a new connection socket. Calls the registered callback for the
1710 * connection acceptance mechanism.
1711 *
1712 *----------------------------------------------------------------------
1713 */
1714
1715 static void
1716 TcpAccept(
1717 void *data, /* Callback token. */
1718 int mask) /* Not used. */
1719 {
1720 TcpFdList *fds = (TcpFdList *)data; /* Client data of server socket. */
1721 int newsock; /* The new client socket */
1722 TcpState *newSockState; /* State for new socket. */
1723 address addr; /* The remote address */
1724 socklen_t len; /* For accept interface */
1725 char channelName[SOCK_CHAN_LENGTH];
1726 char host[NI_MAXHOST], port[NI_MAXSERV];
1727 (void)mask;
1728
1729 len = sizeof(addr);
1730 newsock = accept(fds->fd, &addr.sa, &len);
1731 if (newsock < 0) {
1732 return;
1733 }
1734
1735 /*
1736 * Set close-on-exec flag to prevent the newly accepted socket from being
1737 * inherited by child processes.
1738 */
1739
1740 (void) fcntl(newsock, F_SETFD, FD_CLOEXEC);
1741
1742 newSockState = (TcpState *)ckalloc(sizeof(TcpState));
1743 memset(newSockState, 0, sizeof(TcpState));
1744 newSockState->flags = 0;
1745 newSockState->fds.fd = newsock;
1746
1747 snprintf(channelName, sizeof(channelName), SOCK_TEMPLATE, (long)newSockState);
1748 newSockState->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
1749 newSockState, TCL_READABLE | TCL_WRITABLE);
1750
1751 Tcl_SetChannelOption(NULL, newSockState->channel, "-translation",
1752 "auto crlf");
1753
1754 if (fds->statePtr->acceptProc != NULL) {
1755 getnameinfo(&addr.sa, len, host, sizeof(host), port, sizeof(port),
1756 NI_NUMERICHOST|NI_NUMERICSERV);
1757 fds->statePtr->acceptProc(fds->statePtr->acceptProcData,
1758 newSockState->channel, host, atoi(port));
1759 }
1760 }
1761
1762 /*
1763 * Local Variables:
1764 * mode: c
1765 * c-basic-offset: 4
1766 * fill-column: 78
1767 * tab-width: 8
1768 * indent-tabs-mode: nil
1769 * End:
1770 */