4 * This file contains Unix-specific socket related code.
6 * Copyright (c) 1995 Sun Microsystems, Inc.
8 * See the file "license.terms" for information on usage and redistribution of
9 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
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.
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)
24 /* "sock" + a pointer in hex + \0 */
25 #define SOCK_CHAN_LENGTH (4 + sizeof(void *) * 2 + 1)
26 #define SOCK_TEMPLATE "sock%lx"
28 #undef SOCKET /* Possible conflict with win32 SOCKET */
31 * This is needed to comply with the strict aliasing rules of GCC, but it also
32 * simplifies casting between the different sockaddr types.
37 struct sockaddr_in sa4;
38 struct sockaddr_in6 sa6;
39 struct sockaddr_storage sas;
43 * This structure describes per-instance state of a tcp based channel.
46 typedef struct TcpState TcpState;
48 typedef struct TcpFdList {
51 struct TcpFdList *next;
55 Tcl_Channel channel; /* Channel associated with this file. */
56 TcpFdList fds; /* The file descriptors of the sockets. */
57 int flags; /* ORed combination of the bitfields defined
59 int interest; /* Event types of interest */
62 * Only needed for server sockets
65 Tcl_TcpAcceptProc *acceptProc;
66 /* Proc to call on accept. */
67 ClientData acceptProcData; /* The data for the accept proc. */
70 * Only needed for client sockets
73 struct addrinfo *addrlist; /* Addresses to connect to. */
74 struct addrinfo *addr; /* Iterator over addrlist. */
75 struct addrinfo *myaddrlist;/* Local address. */
76 struct addrinfo *myaddr; /* Iterator over myaddrlist. */
77 int filehandlers; /* Caches FileHandlers that get set up while
78 * an async socket is not yet connected. */
79 int connectError; /* Cache SO_ERROR of async socket. */
80 int cachedBlocking; /* Cache blocking mode of async socket. */
84 * These bits may be ORed together into the "flags" field of a TcpState
88 #define TCP_NONBLOCKING (1<<0) /* Socket with non-blocking I/O */
89 #define TCP_ASYNC_CONNECT (1<<1) /* Async connect in progress. */
90 #define TCP_ASYNC_PENDING (1<<4) /* TcpConnect was called to
91 * process an async connect. This
92 * flag indicates that reentry is
94 #define TCP_ASYNC_FAILED (1<<5) /* An async connect finally failed */
97 * The following defines the maximum length of the listen queue. This is the
98 * number of outstanding yet-to-be-serviced requests for a connection on a
99 * server socket, more than this number of outstanding requests and the
100 * connection request will fail.
104 # define SOMAXCONN 100
105 #elif (SOMAXCONN < 100)
107 # define SOMAXCONN 100
108 #endif /* SOMAXCONN < 100 */
111 * The following defines how much buffer space the kernel should maintain for
115 #define SOCKET_BUFSIZE 4096
118 * Static routines for this file:
121 static void TcpAsyncCallback(ClientData clientData, int mask);
122 static int TcpConnect(Tcl_Interp *interp, TcpState *state);
123 static void TcpAccept(ClientData data, int mask);
124 static int TcpBlockModeProc(ClientData data, int mode);
125 static int TcpCloseProc(ClientData instanceData,
127 static int TcpClose2Proc(ClientData instanceData,
128 Tcl_Interp *interp, int flags);
129 static int TcpGetHandleProc(ClientData instanceData,
130 int direction, ClientData *handlePtr);
131 static int TcpGetOptionProc(ClientData instanceData,
132 Tcl_Interp *interp, const char *optionName,
134 static int TcpInputProc(ClientData instanceData, char *buf,
135 int toRead, int *errorCode);
136 static int TcpOutputProc(ClientData instanceData,
137 const char *buf, int toWrite, int *errorCode);
138 static void TcpThreadActionProc(ClientData instanceData, int action);
139 static void TcpWatchProc(ClientData instanceData, int mask);
140 static int WaitForConnect(TcpState *statePtr, int *errorCodePtr);
141 static void WrapNotify(ClientData clientData, int mask);
144 * This structure describes the channel type structure for TCP socket
148 static const Tcl_ChannelType tcpChannelType = {
149 "tcp", /* Type name. */
150 TCL_CHANNEL_VERSION_5, /* v5 channel */
151 TcpCloseProc, /* Close proc. */
152 TcpInputProc, /* Input proc. */
153 TcpOutputProc, /* Output proc. */
154 NULL, /* Seek proc. */
155 NULL, /* Set option proc. */
156 TcpGetOptionProc, /* Get option proc. */
157 TcpWatchProc, /* Initialize notifier. */
158 TcpGetHandleProc, /* Get OS handles out of channel. */
159 TcpClose2Proc, /* Close2 proc. */
160 TcpBlockModeProc, /* Set blocking or non-blocking mode.*/
161 NULL, /* flush proc. */
162 NULL, /* handler proc. */
163 NULL, /* wide seek proc. */
164 TcpThreadActionProc, /* thread action proc. */
165 NULL /* truncate proc. */
169 * The following variable holds the network name of this host.
172 static TclInitProcessGlobalValueProc InitializeHostName;
173 static ProcessGlobalValue hostName =
174 {0, 0, NULL, NULL, InitializeHostName, NULL, NULL};
177 /* printf debugging */
180 struct addrinfo *addrlist,
183 char host[NI_MAXHOST], port[NI_MAXSERV];
186 for (ai = addrlist; ai != NULL; ai = ai->ai_next) {
187 getnameinfo(ai->ai_addr, ai->ai_addrlen,
188 host, sizeof(host), port, sizeof(port),
189 NI_NUMERICHOST|NI_NUMERICSERV);
190 fprintf(stderr,"%s: %s:%s\n", prefix, host, port);
195 * ----------------------------------------------------------------------
197 * InitializeHostName --
199 * This routine sets the process global value of the name of the local
200 * host on which the process is running.
205 * ----------------------------------------------------------------------
212 Tcl_Encoding *encodingPtr)
214 const char *native = NULL;
220 memset(&u, (int) 0, sizeof(struct utsname));
221 if (uname(&u) > -1) { /* INTL: Native. */
222 hp = TclpGetHostByName(u.nodename); /* INTL: Native. */
225 * Sometimes the nodename is fully qualified, but gets truncated
226 * as it exceeds SYS_NMLN. See if we can just get the immediate
227 * nodename and get a proper answer that way.
230 char *dot = strchr(u.nodename, '.');
233 char *node = (char *)ckalloc(dot - u.nodename + 1);
235 memcpy(node, u.nodename, dot - u.nodename);
236 node[dot - u.nodename] = '\0';
237 hp = TclpGetHostByName(node);
247 if (native == NULL) {
248 native = tclEmptyStringRep;
250 #else /* !NO_UNAME */
252 * Uname doesn't exist; try gethostname instead.
254 * There is no portable macro for the maximum length of host names
255 * returned by gethostbyname(). We should only trust SYS_NMLN if it is at
256 * least 255 + 1 bytes to comply with DNS host name limits.
258 * Note: SYS_NMLN is a restriction on "uname" not on gethostbyname!
260 * For example HP-UX 10.20 has SYS_NMLN == 9, while gethostbyname() can
261 * return a fully qualified name from DNS of up to 255 bytes.
263 * Fix suggested by Viktor Dukhovni (viktor@esm.com)
266 # if defined(SYS_NMLN) && (SYS_NMLEN >= 256)
267 char buffer[SYS_NMLEN];
272 if (gethostname(buffer, sizeof(buffer)) > -1) { /* INTL: Native. */
275 #endif /* NO_UNAME */
277 *encodingPtr = Tcl_GetEncoding(NULL, NULL);
278 *lengthPtr = strlen(native);
279 *valuePtr = ckalloc(*lengthPtr + 1);
280 memcpy(*valuePtr, native, *lengthPtr + 1);
284 * ----------------------------------------------------------------------
288 * Returns the name of the local host.
291 * A string containing the network name for this machine, or an empty
292 * string if we can't figure out the name. The caller must not modify or
296 * Caches the name to return for future calls.
298 * ----------------------------------------------------------------------
302 Tcl_GetHostName(void)
304 return Tcl_GetString(TclGetProcessGlobalValue(&hostName));
308 * ----------------------------------------------------------------------
312 * Detect if sockets are available on this platform.
320 * ----------------------------------------------------------------------
325 Tcl_Interp *dummy) /* Not used. */
333 * ----------------------------------------------------------------------
335 * TclpFinalizeSockets --
337 * Performs per-thread socket subsystem finalization.
345 * ----------------------------------------------------------------------
349 TclpFinalizeSockets(void)
355 * ----------------------------------------------------------------------
357 * TcpBlockModeProc --
359 * This function is invoked by the generic IO level to set blocking and
360 * nonblocking mode on a TCP socket based channel.
363 * 0 if successful, errno when failed.
366 * Sets the device into blocking or nonblocking mode.
368 * ----------------------------------------------------------------------
373 ClientData instanceData, /* Socket state. */
374 int mode) /* The mode to set. Can be one of
375 * TCL_MODE_BLOCKING or
376 * TCL_MODE_NONBLOCKING. */
378 TcpState *statePtr = (TcpState *)instanceData;
380 if (mode == TCL_MODE_BLOCKING) {
381 CLEAR_BITS(statePtr->flags, TCP_NONBLOCKING);
383 SET_BITS(statePtr->flags, TCP_NONBLOCKING);
385 if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
386 statePtr->cachedBlocking = mode;
389 if (TclUnixSetBlockingMode(statePtr->fds.fd, mode) < 0) {
396 * ----------------------------------------------------------------------
400 * Check the state of an async connect process. If a connection attempt
401 * terminated, process it, which may finalize it or may start the next
402 * attempt. If a connect error occures, it is saved in
403 * statePtr->connectError to be reported by 'fconfigure -error'.
405 * There are two modes of operation, defined by errorCodePtr:
406 * * non-NULL: Called by explicite read/write command. Blocks if the
407 * socket is blocking.
408 * May return two error codes:
409 * * EWOULDBLOCK: if connect is still in progress
410 * * ENOTCONN: if connect failed. This would be the error message
411 * of a rect or sendto syscall so this is emulated here.
412 * * NULL: Called by a backround operation. Do not block and do not
413 * return any error code.
416 * 0 if the connection has completed, -1 if still in progress or there is
420 * Processes socket events off the system queue. May process
421 * asynchroneous connects.
423 *----------------------------------------------------------------------
428 TcpState *statePtr, /* State of the socket. */
434 * Check if an async connect failed already and error reporting is
435 * demanded, return the error ENOTCONN
438 if (errorCodePtr != NULL && GOT_BITS(statePtr->flags, TCP_ASYNC_FAILED)) {
439 *errorCodePtr = ENOTCONN;
444 * Check if an async connect is running. If not return ok
447 if (!GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
451 if (errorCodePtr == NULL || GOT_BITS(statePtr->flags, TCP_NONBLOCKING)) {
457 if (TclUnixWaitForFile(statePtr->fds.fd,
458 TCL_WRITABLE | TCL_EXCEPTION, timeout) != 0) {
459 TcpConnect(NULL, statePtr);
463 * Do this only once in the nonblocking case and repeat it until the
464 * socket is final when blocking.
466 } while (timeout == -1 && GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT));
468 if (errorCodePtr != NULL) {
469 if (GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
470 *errorCodePtr = EAGAIN;
472 } else if (statePtr->connectError != 0) {
473 *errorCodePtr = ENOTCONN;
481 *----------------------------------------------------------------------
485 * This function is invoked by the generic IO level to read input from a
486 * TCP socket based channel.
488 * NOTE: We cannot share code with FilePipeInputProc because here we must
489 * use recv to obtain the input from the channel, not read.
492 * The number of bytes read is returned or -1 on error. An output
493 * argument contains the POSIX error code on error, or zero if no error
497 * Reads input from the input device of the channel.
499 *----------------------------------------------------------------------
504 ClientData instanceData, /* Socket state. */
505 char *buf, /* Where to store data read. */
506 int bufSize, /* How much space is available in the
508 int *errorCodePtr) /* Where to store error code. */
510 TcpState *statePtr = (TcpState *)instanceData;
514 if (WaitForConnect(statePtr, errorCodePtr) != 0) {
517 bytesRead = recv(statePtr->fds.fd, buf, (size_t) bufSize, 0);
518 if (bytesRead > -1) {
521 if (errno == ECONNRESET) {
523 * Turn ECONNRESET into a soft EOF condition.
528 *errorCodePtr = errno;
533 *----------------------------------------------------------------------
537 * This function is invoked by the generic IO level to write output to a
538 * TCP socket based channel.
540 * NOTE: We cannot share code with FilePipeOutputProc because here we
541 * must use send, not write, to get reliable error reporting.
544 * The number of bytes written is returned. An output argument is set to
545 * a POSIX error code if an error occurred, or zero.
548 * Writes output on the output device of the channel.
550 *----------------------------------------------------------------------
555 ClientData instanceData, /* Socket state. */
556 const char *buf, /* The data buffer. */
557 int toWrite, /* How many bytes to write? */
558 int *errorCodePtr) /* Where to store error code. */
560 TcpState *statePtr = (TcpState *)instanceData;
564 if (WaitForConnect(statePtr, errorCodePtr) != 0) {
567 written = send(statePtr->fds.fd, buf, (size_t) toWrite, 0);
572 *errorCodePtr = errno;
577 *----------------------------------------------------------------------
581 * This function is invoked by the generic IO level to perform
582 * channel-type-specific cleanup when a TCP socket based channel is
586 * 0 if successful, the value of errno if failed.
589 * Closes the socket of the channel.
591 *----------------------------------------------------------------------
596 ClientData instanceData, /* The socket to close. */
597 Tcl_Interp *dummy) /* For error reporting - unused. */
599 TcpState *statePtr = (TcpState *)instanceData;
605 * Delete a file handler that may be active for this socket if this is a
606 * server socket - the file handler was created automatically by Tcl as
607 * part of the mechanism to accept new client connections. Channel
608 * handlers are already deleted in the generic IO channel closing code
609 * that called this function, so we do not have to delete them here.
612 for (fds = &statePtr->fds; fds != NULL; fds = fds->next) {
616 Tcl_DeleteFileHandler(fds->fd);
617 if (close(fds->fd) < 0) {
622 fds = statePtr->fds.next;
623 while (fds != NULL) {
624 TcpFdList *next = fds->next;
629 if (statePtr->addrlist != NULL) {
630 freeaddrinfo(statePtr->addrlist);
632 if (statePtr->myaddrlist != NULL) {
633 freeaddrinfo(statePtr->myaddrlist);
640 *----------------------------------------------------------------------
644 * This function is called by the generic IO level to perform the channel
645 * type specific part of a half-close: namely, a shutdown() on a socket.
648 * 0 if successful, the value of errno if failed.
651 * Shuts down one side of the socket.
653 *----------------------------------------------------------------------
658 ClientData instanceData, /* The socket to close. */
659 Tcl_Interp *dummy, /* For error reporting. */
660 int flags) /* Flags that indicate which side to close. */
662 TcpState *statePtr = (TcpState *)instanceData;
668 * Shutdown the OS socket handle.
670 if ((flags & (TCL_CLOSE_READ|TCL_CLOSE_WRITE)) == 0) {
671 return TcpCloseProc(instanceData, NULL);
673 if ((flags & TCL_CLOSE_READ) && (shutdown(statePtr->fds.fd, SHUT_RD) < 0)) {
676 if ((flags & TCL_CLOSE_WRITE) && (shutdown(statePtr->fds.fd, SHUT_WR) < 0)) {
679 return (readError != 0) ? readError : writeError;
683 *----------------------------------------------------------------------
687 * This function is called by the -gethostname and -getpeername switches
688 * of TcpGetOptionProc() to add three list elements with the textual
689 * representation of the given address to the given DString.
695 * Adds three elements do dsPtr
697 *----------------------------------------------------------------------
700 #ifndef NEED_FAKE_RFC2553
701 #if defined (__clang__) || ((__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
702 #pragma GCC diagnostic push
703 #pragma GCC diagnostic ignored "-Wstrict-aliasing"
706 IPv6AddressNeedsNumericRendering(
707 struct in6_addr addr)
709 if (IN6_ARE_ADDR_EQUAL(&addr, &in6addr_any)) {
714 * The IN6_IS_ADDR_V4MAPPED macro has a problem with aliasing warnings on
715 * at least some versions of OSX.
718 if (!IN6_IS_ADDR_V4MAPPED(&addr)) {
722 return (addr.s6_addr[12] == 0 && addr.s6_addr[13] == 0
723 && addr.s6_addr[14] == 0 && addr.s6_addr[15] == 0);
725 #if defined (__clang__) || ((__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
726 #pragma GCC diagnostic pop
728 #endif /* NEED_FAKE_RFC2553 */
737 #define SUPPRESS_RDNS_VAR "::tcl::unsupported::noReverseDNS"
738 char host[NI_MAXHOST], nhost[NI_MAXHOST], nport[NI_MAXSERV];
741 getnameinfo(&addr.sa, salen, nhost, sizeof(nhost), nport, sizeof(nport),
742 NI_NUMERICHOST | NI_NUMERICSERV);
743 Tcl_DStringAppendElement(dsPtr, nhost);
746 * We don't want to resolve INADDR_ANY and sin6addr_any; they can
747 * sometimes cause problems (and never have a name).
750 if (addr.sa.sa_family == AF_INET) {
751 if (addr.sa4.sin_addr.s_addr == INADDR_ANY) {
752 flags |= NI_NUMERICHOST;
754 #ifndef NEED_FAKE_RFC2553
755 } else if (addr.sa.sa_family == AF_INET6) {
756 if (IPv6AddressNeedsNumericRendering(addr.sa6.sin6_addr)) {
757 flags |= NI_NUMERICHOST;
759 #endif /* NEED_FAKE_RFC2553 */
763 * Check if reverse DNS has been switched off globally.
766 if (interp != NULL &&
767 Tcl_GetVar2(interp, SUPPRESS_RDNS_VAR, NULL, 0) != NULL) {
768 flags |= NI_NUMERICHOST;
770 if (getnameinfo(&addr.sa, salen, host, sizeof(host), NULL, 0,
773 * Reverse mapping worked.
776 Tcl_DStringAppendElement(dsPtr, host);
779 * Reverse mapping failed - use the numeric rep once more.
782 Tcl_DStringAppendElement(dsPtr, nhost);
784 Tcl_DStringAppendElement(dsPtr, nport);
788 *----------------------------------------------------------------------
790 * TcpGetOptionProc --
792 * Computes an option value for a TCP socket based channel, or a list of
793 * all options and their values.
795 * Note: This code is based on code contributed by John Haxby.
798 * A standard Tcl result. The value of the specified option or a list of
799 * all options and their values is returned in the supplied DString. Sets
800 * Error message if needed.
805 *----------------------------------------------------------------------
810 ClientData instanceData, /* Socket state. */
811 Tcl_Interp *interp, /* For error reporting - can be NULL. */
812 const char *optionName, /* Name of the option to retrieve the value
813 * for, or NULL to get all options and their
815 Tcl_DString *dsPtr) /* Where to store the computed value;
816 * initialized by caller. */
818 TcpState *statePtr = (TcpState *)instanceData;
821 WaitForConnect(statePtr, NULL);
823 if (optionName != NULL) {
824 len = strlen(optionName);
827 if ((len > 1) && (optionName[1] == 'e') &&
828 (strncmp(optionName, "-error", len) == 0)) {
829 socklen_t optlen = sizeof(int);
831 if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
833 * Suppress errors as long as we are not done.
837 } else if (statePtr->connectError != 0) {
838 errno = statePtr->connectError;
839 statePtr->connectError = 0;
843 getsockopt(statePtr->fds.fd, SOL_SOCKET, SO_ERROR, (char *) &err,
848 Tcl_DStringAppend(dsPtr, Tcl_ErrnoMsg(errno), -1);
853 if ((len > 1) && (optionName[1] == 'c') &&
854 (strncmp(optionName, "-connecting", len) == 0)) {
855 Tcl_DStringAppend(dsPtr,
856 GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT) ? "1" : "0", -1);
860 if ((len == 0) || ((len > 1) && (optionName[1] == 'p') &&
861 (strncmp(optionName, "-peername", len) == 0))) {
863 socklen_t size = sizeof(peername);
865 if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
867 * In async connect output an empty string
871 Tcl_DStringAppendElement(dsPtr, "-peername");
872 Tcl_DStringAppendElement(dsPtr, "");
876 } else if (getpeername(statePtr->fds.fd, &peername.sa, &size) >= 0) {
878 * Peername fetch succeeded - output list
882 Tcl_DStringAppendElement(dsPtr, "-peername");
883 Tcl_DStringStartSublist(dsPtr);
885 TcpHostPortList(interp, dsPtr, peername, size);
889 Tcl_DStringEndSublist(dsPtr);
892 * getpeername failed - but if we were asked for all the options
893 * (len==0), don't flag an error at that point because it could be
894 * an fconfigure request on a server socket (which have no peer).
895 * Same must be done on win&mac.
900 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
901 "can't get peername: %s",
902 Tcl_PosixError(interp)));
909 if ((len == 0) || ((len > 1) && (optionName[1] == 's') &&
910 (strncmp(optionName, "-sockname", len) == 0))) {
917 Tcl_DStringAppendElement(dsPtr, "-sockname");
918 Tcl_DStringStartSublist(dsPtr);
920 if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
922 * In async connect output an empty string
927 for (fds = &statePtr->fds; fds != NULL; fds = fds->next) {
928 size = sizeof(sockname);
929 if (getsockname(fds->fd, &(sockname.sa), &size) >= 0) {
931 TcpHostPortList(interp, dsPtr, sockname, size);
939 Tcl_DStringEndSublist(dsPtr);
942 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
943 "can't get sockname: %s", Tcl_PosixError(interp)));
950 return Tcl_BadChannelOption(interp, optionName,
951 "connecting peername sockname");
958 * ----------------------------------------------------------------------
960 * TcpThreadActionProc --
962 * Handles detach/attach for asynchronously connecting socket.
964 * Reassigning the file handler associated with thread-related channel
965 * notification, responsible for callbacks (signaling that asynchronous
966 * connection attempt has succeeded or failed).
971 * ----------------------------------------------------------------------
976 ClientData instanceData,
979 TcpState *statePtr = (TcpState *)instanceData;
981 if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
983 * Async-connecting socket must get reassigned handler if it have been
984 * transferred to another thread. Remove the handler if the socket is
985 * not managed by this thread anymore and create new handler (TSD related)
986 * so the callback will run in the correct thread, bug [f583715154].
989 case TCL_CHANNEL_THREAD_REMOVE:
990 CLEAR_BITS(statePtr->flags, TCP_ASYNC_PENDING);
991 Tcl_DeleteFileHandler(statePtr->fds.fd);
993 case TCL_CHANNEL_THREAD_INSERT:
994 Tcl_CreateFileHandler(statePtr->fds.fd,
995 TCL_WRITABLE | TCL_EXCEPTION, TcpAsyncCallback, statePtr);
996 SET_BITS(statePtr->flags, TCP_ASYNC_PENDING);
1003 * ----------------------------------------------------------------------
1007 * Initialize the notifier to watch the fd from this channel.
1013 * Sets up the notifier so that a future event on the channel will be
1016 * ----------------------------------------------------------------------
1021 ClientData clientData,
1024 TcpState *statePtr = (TcpState *) clientData;
1025 int newmask = mask & statePtr->interest;
1029 * There was no overlap between the states the channel is interested
1030 * in notifications for, and the states that are reported present on
1031 * the file descriptor by select(). The only way that can happen is
1032 * when the channel is interested in a writable condition, and only a
1033 * readable state is reported present (see TcpWatchProc() below). In
1034 * that case, signal back to the caller the writable state, which is
1035 * really an error condition. As an extra check on that assumption,
1036 * check for a non-zero value of errno before reporting an artificial
1043 newmask = TCL_WRITABLE;
1045 Tcl_NotifyChannel(statePtr->channel, newmask);
1050 ClientData instanceData, /* The socket state. */
1051 int mask) /* Events of interest; an OR-ed combination of
1052 * TCL_READABLE, TCL_WRITABLE and
1055 TcpState *statePtr = (TcpState *)instanceData;
1057 if (statePtr->acceptProc != NULL) {
1059 * Make sure we don't mess with server sockets since they will never
1060 * be readable or writable at the Tcl level. This keeps Tcl scripts
1061 * from interfering with the -accept behavior (bug #3394732).
1067 if (GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
1069 * Async sockets use a FileHandler internally while connecting, so we
1070 * need to cache this request until the connection has succeeded.
1073 statePtr->filehandlers = mask;
1077 * Whether it is a bug or feature or otherwise, it is a fact of life
1078 * that on at least some Linux kernels select() fails to report that a
1079 * socket file descriptor is writable when the other end of the socket
1080 * is closed. This is in contrast to the guarantees Tcl makes that
1081 * its channels become writable and fire writable events on an error
1082 * conditon. This has caused a leak of file descriptors in a state of
1083 * background flushing. See Tcl ticket 1758a0b603.
1085 * As a workaround, when our caller indicates an interest in writable
1086 * notifications, we must tell the notifier built around select() that
1087 * we are interested in the readable state of the file descriptor as
1088 * well, as that is the only reliable means to get notified of error
1089 * conditions. Then it is the task of WrapNotify() above to untangle
1090 * the meaning of these channel states and report the chan events as
1091 * best it can. We save a copy of the mask passed in to assist with
1095 statePtr->interest = mask;
1096 Tcl_CreateFileHandler(statePtr->fds.fd, mask|TCL_READABLE,
1097 (Tcl_FileProc *) WrapNotify, statePtr);
1099 Tcl_DeleteFileHandler(statePtr->fds.fd);
1104 * ----------------------------------------------------------------------
1106 * TcpGetHandleProc --
1108 * Called from Tcl_GetChannelHandle to retrieve OS handles from inside a
1109 * TCP socket based channel.
1112 * Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if there is no
1113 * handle for the specified direction.
1118 * ----------------------------------------------------------------------
1123 ClientData instanceData, /* The socket state. */
1124 int direction, /* Not used. */
1125 ClientData *handlePtr) /* Where to store the handle. */
1127 TcpState *statePtr = (TcpState *)instanceData;
1130 *handlePtr = INT2PTR(statePtr->fds.fd);
1135 * ----------------------------------------------------------------------
1137 * TcpAsyncCallback --
1139 * Called by the event handler that TcpConnect sets up internally for
1140 * [socket -async] to get notified when the asynchronous connection
1141 * attempt has succeeded or failed.
1143 * ----------------------------------------------------------------------
1148 ClientData clientData, /* The socket state. */
1149 int mask) /* Events of interest; an OR-ed combination of
1150 * TCL_READABLE, TCL_WRITABLE and
1155 TcpConnect(NULL, (TcpState *)clientData);
1159 * ----------------------------------------------------------------------
1163 * This function opens a new socket in client mode.
1166 * TCL_OK, if the socket was successfully connected or an asynchronous
1167 * connection is in progress. If an error occurs, TCL_ERROR is returned
1168 * and an error message is left in interp.
1174 * A single host name may resolve to more than one IP address, e.g. for
1175 * an IPv4/IPv6 dual stack host. For handling asynchronously connecting
1176 * sockets in the background for such hosts, this function can act as a
1177 * coroutine. On the first call, it sets up the control variables for the
1178 * two nested loops over the local and remote addresses. Once the first
1179 * connection attempt is in progress, it sets up itself as a writable
1180 * event handler for that socket, and returns. When the callback occurs,
1181 * control is transferred to the "reenter" label, right after the initial
1182 * return and the loops resume as if they had never been interrupted.
1183 * For synchronously connecting sockets, the loops work the usual way.
1185 * ----------------------------------------------------------------------
1190 Tcl_Interp *interp, /* For error reporting; can be NULL. */
1194 int async_callback = GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING);
1195 int ret = -1, error = EHOSTUNREACH;
1196 int async = GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT);
1198 if (async_callback) {
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) {
1210 * No need to try combinations of local and remote addresses of
1211 * different families.
1214 if (statePtr->myaddr->ai_family != statePtr->addr->ai_family) {
1219 * Close the socket if it is still open from the last unsuccessful
1223 if (statePtr->fds.fd >= 0) {
1224 close(statePtr->fds.fd);
1225 statePtr->fds.fd = -1;
1229 statePtr->fds.fd = socket(statePtr->addr->ai_family, SOCK_STREAM,
1231 if (statePtr->fds.fd < 0) {
1236 * Set the close-on-exec flag so that the socket will not get
1237 * inherited by child processes.
1240 fcntl(statePtr->fds.fd, F_SETFD, FD_CLOEXEC);
1243 * Set kernel space buffering
1246 TclSockMinimumBuffers(INT2PTR(statePtr->fds.fd), SOCKET_BUFSIZE);
1249 ret = TclUnixSetBlockingMode(statePtr->fds.fd,
1250 TCL_MODE_NONBLOCKING);
1257 * Must reset the error variable here, before we use it for the
1258 * first time in this iteration.
1263 (void) setsockopt(statePtr->fds.fd, SOL_SOCKET, SO_REUSEADDR,
1264 (char *) &reuseaddr, sizeof(reuseaddr));
1265 ret = bind(statePtr->fds.fd, statePtr->myaddr->ai_addr,
1266 statePtr->myaddr->ai_addrlen);
1273 * Attempt to connect. The connect may fail at present with an
1274 * EINPROGRESS but at a later time it will complete. The caller
1275 * will set up a file handler on the socket if she is interested
1276 * in being informed when the connect completes.
1279 ret = connect(statePtr->fds.fd, statePtr->addr->ai_addr,
1280 statePtr->addr->ai_addrlen);
1284 if (ret < 0 && errno == EINPROGRESS) {
1285 Tcl_CreateFileHandler(statePtr->fds.fd,
1286 TCL_WRITABLE | TCL_EXCEPTION, TcpAsyncCallback,
1288 errno = EWOULDBLOCK;
1289 SET_BITS(statePtr->flags, TCP_ASYNC_PENDING);
1293 CLEAR_BITS(statePtr->flags, TCP_ASYNC_PENDING);
1294 Tcl_DeleteFileHandler(statePtr->fds.fd);
1297 * Read the error state from the socket to see if the async
1298 * connection has succeeded or failed. As this clears the
1299 * error condition, we cache the status in the socket state
1300 * struct for later retrieval by [fconfigure -error].
1303 optlen = sizeof(int);
1305 getsockopt(statePtr->fds.fd, SOL_SOCKET, SO_ERROR,
1306 (char *) &error, &optlen);
1316 statePtr->connectError = error;
1317 CLEAR_BITS(statePtr->flags, TCP_ASYNC_CONNECT);
1318 if (async_callback) {
1320 * An asynchonous connection has finally succeeded or failed.
1323 TcpWatchProc(statePtr, statePtr->filehandlers);
1324 TclUnixSetBlockingMode(statePtr->fds.fd, statePtr->cachedBlocking);
1327 SET_BITS(statePtr->flags, TCP_ASYNC_FAILED);
1331 * We need to forward the writable event that brought us here, bcasue
1332 * upon reading of getsockopt(SO_ERROR), at least some OSes clear the
1333 * writable state from the socket, and so a subsequent select() on
1334 * behalf of a script level [fileevent] would not fire. It doesn't
1335 * hurt that this is also called in the successful case and will save
1336 * the event mechanism one roundtrip through select().
1339 if (statePtr->cachedBlocking == TCL_MODE_NONBLOCKING) {
1340 Tcl_NotifyChannel(statePtr->channel, TCL_WRITABLE);
1345 * Failure for either a synchronous connection, or an async one that
1346 * failed before it could enter background mode, e.g. because an
1347 * invalid -myaddr was given.
1350 if (interp != NULL) {
1352 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1353 "couldn't open socket: %s", Tcl_PosixError(interp)));
1361 *----------------------------------------------------------------------
1363 * Tcl_OpenTcpClient --
1365 * Opens a TCP client socket and creates a channel around it.
1368 * The channel or NULL if failed. An error message is returned in the
1369 * interpreter on failure.
1372 * Opens a client socket and creates a new channel.
1374 *----------------------------------------------------------------------
1379 Tcl_Interp *interp, /* For error reporting; can be NULL. */
1380 int port, /* Port number to open. */
1381 const char *host, /* Host on which to open port. */
1382 const char *myaddr, /* Client-side address */
1383 int myport, /* Client-side port */
1384 int async) /* If nonzero, attempt to do an asynchronous
1385 * connect. Otherwise we do a blocking
1389 const char *errorMsg = NULL;
1390 struct addrinfo *addrlist = NULL, *myaddrlist = NULL;
1391 char channelName[SOCK_CHAN_LENGTH];
1394 * Do the name lookups for the local and remote addresses.
1397 if (!TclCreateSocketAddress(interp, &addrlist, host, port, 0, &errorMsg)
1398 || !TclCreateSocketAddress(interp, &myaddrlist, myaddr, myport, 1,
1400 if (addrlist != NULL) {
1401 freeaddrinfo(addrlist);
1403 if (interp != NULL) {
1404 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1405 "couldn't open socket: %s", errorMsg));
1411 * Allocate a new TcpState for this socket.
1414 statePtr = (TcpState *)ckalloc(sizeof(TcpState));
1415 memset(statePtr, 0, sizeof(TcpState));
1416 statePtr->flags = async ? TCP_ASYNC_CONNECT : 0;
1417 statePtr->cachedBlocking = TCL_MODE_BLOCKING;
1418 statePtr->addrlist = addrlist;
1419 statePtr->myaddrlist = myaddrlist;
1420 statePtr->fds.fd = -1;
1423 * Create a new client socket and wrap it in a channel.
1426 if (TcpConnect(interp, statePtr) != TCL_OK) {
1427 TcpCloseProc(statePtr, NULL);
1431 sprintf(channelName, SOCK_TEMPLATE, (long) statePtr);
1433 statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
1434 statePtr, TCL_READABLE | TCL_WRITABLE);
1435 if (Tcl_SetChannelOption(interp, statePtr->channel, "-translation",
1436 "auto crlf") == TCL_ERROR) {
1437 Tcl_Close(NULL, statePtr->channel);
1440 return statePtr->channel;
1444 *----------------------------------------------------------------------
1446 * Tcl_MakeTcpClientChannel --
1448 * Creates a Tcl_Channel from an existing client TCP socket.
1451 * The Tcl_Channel wrapped around the preexisting TCP socket.
1456 *----------------------------------------------------------------------
1460 Tcl_MakeTcpClientChannel(
1461 ClientData sock) /* The socket to wrap up into a channel. */
1463 return (Tcl_Channel) TclpMakeTcpClientChannelMode(sock,
1464 TCL_READABLE | TCL_WRITABLE);
1468 *----------------------------------------------------------------------
1470 * TclpMakeTcpClientChannelMode --
1472 * Creates a Tcl_Channel from an existing client TCP socket
1476 * The Tcl_Channel wrapped around the preexisting TCP socket.
1481 *----------------------------------------------------------------------
1485 TclpMakeTcpClientChannelMode(
1486 void *sock, /* The socket to wrap up into a channel. */
1487 int mode) /* ORed combination of TCL_READABLE and
1488 * TCL_WRITABLE to indicate file mode. */
1491 char channelName[SOCK_CHAN_LENGTH];
1493 statePtr = (TcpState *)ckalloc(sizeof(TcpState));
1494 memset(statePtr, 0, sizeof(TcpState));
1495 statePtr->fds.fd = PTR2INT(sock);
1496 statePtr->flags = 0;
1498 sprintf(channelName, SOCK_TEMPLATE, (long)statePtr);
1500 statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
1502 if (Tcl_SetChannelOption(NULL, statePtr->channel, "-translation",
1503 "auto crlf") == TCL_ERROR) {
1504 Tcl_Close(NULL, statePtr->channel);
1507 return statePtr->channel;
1511 *----------------------------------------------------------------------
1513 * Tcl_OpenTcpServer --
1515 * Opens a TCP server socket and creates a channel around it.
1518 * The channel or NULL if failed. If an error occurred, an error message
1519 * is left in the interp's result if interp is not NULL.
1522 * Opens a server socket and creates a new channel.
1524 *----------------------------------------------------------------------
1529 Tcl_Interp *interp, /* For error reporting - may be NULL. */
1530 int port, /* Port number to open. */
1531 const char *myHost, /* Name of local host. */
1532 Tcl_TcpAcceptProc *acceptProc,
1533 /* Callback for accepting connections from new
1535 ClientData acceptProcData) /* Data for the callback. */
1537 int status = 0, sock = -1, reuseaddr = 1, chosenport = 0;
1538 struct addrinfo *addrlist = NULL, *addrPtr; /* socket address */
1539 TcpState *statePtr = NULL;
1540 char channelName[SOCK_CHAN_LENGTH];
1541 const char *errorMsg = NULL;
1542 TcpFdList *fds = NULL, *newfds;
1545 * Try to record and return the most meaningful error message, i.e. the
1546 * one from the first socket that went the farthest before it failed.
1549 enum { LOOKUP, SOCKET, BIND, LISTEN } howfar = LOOKUP;
1552 if (!TclCreateSocketAddress(interp, &addrlist, myHost, port, 1, &errorMsg)) {
1557 for (addrPtr = addrlist; addrPtr != NULL; addrPtr = addrPtr->ai_next) {
1558 sock = socket(addrPtr->ai_family, addrPtr->ai_socktype,
1559 addrPtr->ai_protocol);
1561 if (howfar < SOCKET) {
1569 * Set the close-on-exec flag so that the socket will not get
1570 * inherited by child processes.
1573 fcntl(sock, F_SETFD, FD_CLOEXEC);
1576 * Set kernel space buffering
1579 TclSockMinimumBuffers(INT2PTR(sock), SOCKET_BUFSIZE);
1582 * Set up to reuse server addresses automatically and bind to the
1586 (void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
1587 (char *) &reuseaddr, sizeof(reuseaddr));
1590 * Make sure we use the same port number when opening two server
1591 * sockets for IPv4 and IPv6 on a random port.
1593 * As sockaddr_in6 uses the same offset and size for the port member
1594 * as sockaddr_in, we can handle both through the IPv4 API.
1597 if (port == 0 && chosenport != 0) {
1598 ((struct sockaddr_in *) addrPtr->ai_addr)->sin_port =
1604 * Missing on: Solaris 2.8
1607 if (addrPtr->ai_family == AF_INET6) {
1610 (void) setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
1611 &v6only, sizeof(v6only));
1613 #endif /* IPV6_V6ONLY */
1615 status = bind(sock, addrPtr->ai_addr, addrPtr->ai_addrlen);
1617 if (howfar < BIND) {
1625 if (port == 0 && chosenport == 0) {
1627 socklen_t namelen = sizeof(sockname);
1630 * Synchronize port numbers when binding to port 0 of multiple
1634 if (getsockname(sock, &sockname.sa, &namelen) >= 0) {
1635 chosenport = ntohs(sockname.sa4.sin_port);
1638 status = listen(sock, SOMAXCONN);
1640 if (howfar < LISTEN) {
1648 if (statePtr == NULL) {
1650 * Allocate a new TcpState for this socket.
1653 statePtr = (TcpState *)ckalloc(sizeof(TcpState));
1654 memset(statePtr, 0, sizeof(TcpState));
1655 statePtr->acceptProc = acceptProc;
1656 statePtr->acceptProcData = acceptProcData;
1657 sprintf(channelName, SOCK_TEMPLATE, (long) statePtr);
1658 newfds = &statePtr->fds;
1660 newfds = (TcpFdList *)ckalloc(sizeof(TcpFdList));
1661 memset(newfds, (int) 0, sizeof(TcpFdList));
1665 newfds->statePtr = statePtr;
1669 * Set up the callback mechanism for accepting connections from new
1673 Tcl_CreateFileHandler(sock, TCL_READABLE, TcpAccept, fds);
1677 if (addrlist != NULL) {
1678 freeaddrinfo(addrlist);
1680 if (statePtr != NULL) {
1681 statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
1683 return statePtr->channel;
1685 if (interp != NULL) {
1686 Tcl_Obj *errorObj = Tcl_NewStringObj("couldn't open socket: ", -1);
1688 if (errorMsg == NULL) {
1690 Tcl_AppendToObj(errorObj, Tcl_PosixError(interp), -1);
1692 Tcl_AppendToObj(errorObj, errorMsg, -1);
1694 Tcl_SetObjResult(interp, errorObj);
1703 *----------------------------------------------------------------------
1706 * Accept a TCP socket connection. This is called by the event loop.
1712 * Creates a new connection socket. Calls the registered callback for the
1713 * connection acceptance mechanism.
1715 *----------------------------------------------------------------------
1720 ClientData data, /* Callback token. */
1721 int mask) /* Not used. */
1723 TcpFdList *fds = (TcpFdList *)data; /* Client data of server socket. */
1724 int newsock; /* The new client socket */
1725 TcpState *newSockState; /* State for new socket. */
1726 address addr; /* The remote address */
1727 socklen_t len; /* For accept interface */
1728 char channelName[SOCK_CHAN_LENGTH];
1729 char host[NI_MAXHOST], port[NI_MAXSERV];
1733 newsock = accept(fds->fd, &addr.sa, &len);
1739 * Set close-on-exec flag to prevent the newly accepted socket from being
1740 * inherited by child processes.
1743 (void) fcntl(newsock, F_SETFD, FD_CLOEXEC);
1745 newSockState = (TcpState *)ckalloc(sizeof(TcpState));
1746 memset(newSockState, 0, sizeof(TcpState));
1747 newSockState->flags = 0;
1748 newSockState->fds.fd = newsock;
1750 sprintf(channelName, SOCK_TEMPLATE, (long) newSockState);
1751 newSockState->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
1752 newSockState, TCL_READABLE | TCL_WRITABLE);
1754 Tcl_SetChannelOption(NULL, newSockState->channel, "-translation",
1757 if (fds->statePtr->acceptProc != NULL) {
1758 getnameinfo(&addr.sa, len, host, sizeof(host), port, sizeof(port),
1759 NI_NUMERICHOST|NI_NUMERICSERV);
1760 fds->statePtr->acceptProc(fds->statePtr->acceptProcData,
1761 newSockState->channel, host, atoi(port));
1771 * indent-tabs-mode: nil