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;			/* ORed 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;
66                                 /* Proc to call on accept. */
67     ClientData acceptProcData;  /* The data for the accept proc. */
68 
69     /*
70      * Only needed for client sockets
71      */
72 
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. */
81 };
82 
83 /*
84  * These bits may be ORed together into the "flags" field of a TcpState
85  * structure.
86  */
87 
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
93 					 * still pending */
94 #define TCP_ASYNC_FAILED	(1<<5)	/* An async connect finally failed */
95 
96 /*
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.
101  */
102 
103 #ifndef SOMAXCONN
104 #   define SOMAXCONN	100
105 #elif (SOMAXCONN < 100)
106 #   undef  SOMAXCONN
107 #   define SOMAXCONN	100
108 #endif /* SOMAXCONN < 100 */
109 
110 /*
111  * The following defines how much buffer space the kernel should maintain for
112  * a socket.
113  */
114 
115 #define SOCKET_BUFSIZE	4096
116 
117 /*
118  * Static routines for this file:
119  */
120 
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,
126 			    Tcl_Interp *interp);
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,
133 			    Tcl_DString *dsPtr);
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);
142 
143 /*
144  * This structure describes the channel type structure for TCP socket
145  * based IO:
146  */
147 
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. */
166 };
167 
168 /*
169  * The following variable holds the network name of this host.
170  */
171 
172 static TclInitProcessGlobalValueProc InitializeHostName;
173 static ProcessGlobalValue hostName =
174 	{0, 0, NULL, NULL, InitializeHostName, NULL, NULL};
175 
176 #if 0
177 /* printf debugging */
178 void
179 printaddrinfo(
180     struct addrinfo *addrlist,
181     char *prefix)
182 {
183     char host[NI_MAXHOST], port[NI_MAXSERV];
184     struct addrinfo *ai;
185 
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);
191     }
192 }
193 #endif
194 /*
195  * ----------------------------------------------------------------------
196  *
197  * InitializeHostName --
198  *
199  * 	This routine sets the process global value of the name of the local
200  * 	host on which the process is running.
201  *
202  * Results:
203  *	None.
204  *
205  * ----------------------------------------------------------------------
206  */
207 
208 static void
InitializeHostName(char ** valuePtr,int * lengthPtr,Tcl_Encoding * encodingPtr)209 InitializeHostName(
210     char **valuePtr,
211     int *lengthPtr,
212     Tcl_Encoding *encodingPtr)
213 {
214     const char *native = NULL;
215 
216 #ifndef NO_UNAME
217     struct utsname u;
218     struct hostent *hp;
219 
220     memset(&u, (int) 0, sizeof(struct utsname));
221     if (uname(&u) > -1) {				/* INTL: Native. */
222         hp = TclpGetHostByName(u.nodename);		/* INTL: Native. */
223 	if (hp == NULL) {
224 	    /*
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.
228 	     */
229 
230 	    char *dot = strchr(u.nodename, '.');
231 
232 	    if (dot != NULL) {
233 		char *node = (char *)ckalloc(dot - u.nodename + 1);
234 
235 		memcpy(node, u.nodename, dot - u.nodename);
236 		node[dot - u.nodename] = '\0';
237 		hp = TclpGetHostByName(node);
238 		ckfree(node);
239 	    }
240 	}
241         if (hp != NULL) {
242 	    native = hp->h_name;
243         } else {
244 	    native = u.nodename;
245         }
246     }
247     if (native == NULL) {
248 	native = tclEmptyStringRep;
249     }
250 #else /* !NO_UNAME */
251     /*
252      * Uname doesn't exist; try gethostname instead.
253      *
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.
257      *
258      * Note: SYS_NMLN is a restriction on "uname" not on gethostbyname!
259      *
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.
262      *
263      * Fix suggested by Viktor Dukhovni (viktor@esm.com)
264      */
265 
266 #    if defined(SYS_NMLN) && (SYS_NMLEN >= 256)
267     char buffer[SYS_NMLEN];
268 #    else
269     char buffer[256];
270 #    endif
271 
272     if (gethostname(buffer, sizeof(buffer)) > -1) {	/* INTL: Native. */
273 	native = buffer;
274     }
275 #endif /* NO_UNAME */
276 
277     *encodingPtr = Tcl_GetEncoding(NULL, NULL);
278     *lengthPtr = strlen(native);
279     *valuePtr = ckalloc(*lengthPtr + 1);
280     memcpy(*valuePtr, native, *lengthPtr + 1);
281 }
282 
283 /*
284  * ----------------------------------------------------------------------
285  *
286  * Tcl_GetHostName --
287  *
288  *	Returns the name of the local host.
289  *
290  * Results:
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
293  *	free this string.
294  *
295  * Side effects:
296  *	Caches the name to return for future calls.
297  *
298  * ----------------------------------------------------------------------
299  */
300 
301 const char *
Tcl_GetHostName(void)302 Tcl_GetHostName(void)
303 {
304     return Tcl_GetString(TclGetProcessGlobalValue(&hostName));
305 }
306 
307 /*
308  * ----------------------------------------------------------------------
309  *
310  * TclpHasSockets --
311  *
312  *	Detect if sockets are available on this platform.
313  *
314  * Results:
315  *	Returns TCL_OK.
316  *
317  * Side effects:
318  *	None.
319  *
320  * ----------------------------------------------------------------------
321  */
322 
323 int
TclpHasSockets(Tcl_Interp * dummy)324 TclpHasSockets(
325     Tcl_Interp *dummy)		/* Not used. */
326 {
327     (void)dummy;
328 
329     return TCL_OK;
330 }
331 
332 /*
333  * ----------------------------------------------------------------------
334  *
335  * TclpFinalizeSockets --
336  *
337  *	Performs per-thread socket subsystem finalization.
338  *
339  * Results:
340  *	None.
341  *
342  * Side effects:
343  *	None.
344  *
345  * ----------------------------------------------------------------------
346  */
347 
348 void
TclpFinalizeSockets(void)349 TclpFinalizeSockets(void)
350 {
351     return;
352 }
353 
354 /*
355  * ----------------------------------------------------------------------
356  *
357  * TcpBlockModeProc --
358  *
359  *	This function is invoked by the generic IO level to set blocking and
360  *	nonblocking mode on a TCP socket based channel.
361  *
362  * Results:
363  *	0 if successful, errno when failed.
364  *
365  * Side effects:
366  *	Sets the device into blocking or nonblocking mode.
367  *
368  * ----------------------------------------------------------------------
369  */
370 
371 static int
TcpBlockModeProc(ClientData instanceData,int mode)372 TcpBlockModeProc(
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. */
377 {
378     TcpState *statePtr = (TcpState *)instanceData;
379 
380     if (mode == TCL_MODE_BLOCKING) {
381 	CLEAR_BITS(statePtr->flags, TCP_NONBLOCKING);
382     } else {
383 	SET_BITS(statePtr->flags, TCP_NONBLOCKING);
384     }
385     if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
386         statePtr->cachedBlocking = mode;
387         return 0;
388     }
389     if (TclUnixSetBlockingMode(statePtr->fds.fd, mode) < 0) {
390 	return errno;
391     }
392     return 0;
393 }
394 
395 /*
396  * ----------------------------------------------------------------------
397  *
398  * WaitForConnect --
399  *
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'.
404  *
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.
414  *
415  * Results:
416  * 	0 if the connection has completed, -1 if still in progress or there is
417  * 	an error.
418  *
419  * Side effects:
420  *	Processes socket events off the system queue. May process
421  *	asynchroneous connects.
422  *
423  *----------------------------------------------------------------------
424  */
425 
426 static int
WaitForConnect(TcpState * statePtr,int * errorCodePtr)427 WaitForConnect(
428     TcpState *statePtr,		/* State of the socket. */
429     int *errorCodePtr)
430 {
431     int timeout;
432 
433     /*
434      * Check if an async connect failed already and error reporting is
435      * demanded, return the error ENOTCONN
436      */
437 
438     if (errorCodePtr != NULL && GOT_BITS(statePtr->flags, TCP_ASYNC_FAILED)) {
439 	*errorCodePtr = ENOTCONN;
440 	return -1;
441     }
442 
443     /*
444      * Check if an async connect is running. If not return ok
445      */
446 
447     if (!GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
448 	return 0;
449     }
450 
451     if (errorCodePtr == NULL || GOT_BITS(statePtr->flags, TCP_NONBLOCKING)) {
452         timeout = 0;
453     } else {
454         timeout = -1;
455     }
456     do {
457         if (TclUnixWaitForFile(statePtr->fds.fd,
458                 TCL_WRITABLE | TCL_EXCEPTION, timeout) != 0) {
459             TcpConnect(NULL, statePtr);
460         }
461 
462         /*
463          * Do this only once in the nonblocking case and repeat it until the
464          * socket is final when blocking.
465          */
466     } while (timeout == -1 && GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT));
467 
468     if (errorCodePtr != NULL) {
469         if (GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
470             *errorCodePtr = EAGAIN;
471             return -1;
472         } else if (statePtr->connectError != 0) {
473             *errorCodePtr = ENOTCONN;
474             return -1;
475         }
476     }
477     return 0;
478 }
479 
480 /*
481  *----------------------------------------------------------------------
482  *
483  * TcpInputProc --
484  *
485  *	This function is invoked by the generic IO level to read input from a
486  *	TCP socket based channel.
487  *
488  *	NOTE: We cannot share code with FilePipeInputProc because here we must
489  *	use recv to obtain the input from the channel, not read.
490  *
491  * Results:
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
494  *	occurred.
495  *
496  * Side effects:
497  *	Reads input from the input device of the channel.
498  *
499  *----------------------------------------------------------------------
500  */
501 
502 static int
TcpInputProc(ClientData instanceData,char * buf,int bufSize,int * errorCodePtr)503 TcpInputProc(
504     ClientData instanceData,	/* Socket state. */
505     char *buf,			/* Where to store data read. */
506     int bufSize,		/* How much space is available in the
507 				 * buffer? */
508     int *errorCodePtr)		/* Where to store error code. */
509 {
510     TcpState *statePtr = (TcpState *)instanceData;
511     int bytesRead;
512 
513     *errorCodePtr = 0;
514     if (WaitForConnect(statePtr, errorCodePtr) != 0) {
515 	return -1;
516     }
517     bytesRead = recv(statePtr->fds.fd, buf, (size_t) bufSize, 0);
518     if (bytesRead > -1) {
519 	return bytesRead;
520     }
521     if (errno == ECONNRESET) {
522 	/*
523 	 * Turn ECONNRESET into a soft EOF condition.
524 	 */
525 
526 	return 0;
527     }
528     *errorCodePtr = errno;
529     return -1;
530 }
531 
532 /*
533  *----------------------------------------------------------------------
534  *
535  * TcpOutputProc --
536  *
537  *	This function is invoked by the generic IO level to write output to a
538  *	TCP socket based channel.
539  *
540  *	NOTE: We cannot share code with FilePipeOutputProc because here we
541  *	must use send, not write, to get reliable error reporting.
542  *
543  * Results:
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.
546  *
547  * Side effects:
548  *	Writes output on the output device of the channel.
549  *
550  *----------------------------------------------------------------------
551  */
552 
553 static int
TcpOutputProc(ClientData instanceData,const char * buf,int toWrite,int * errorCodePtr)554 TcpOutputProc(
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. */
559 {
560     TcpState *statePtr = (TcpState *)instanceData;
561     int written;
562 
563     *errorCodePtr = 0;
564     if (WaitForConnect(statePtr, errorCodePtr) != 0) {
565 	return -1;
566     }
567     written = send(statePtr->fds.fd, buf, (size_t) toWrite, 0);
568 
569     if (written > -1) {
570 	return written;
571     }
572     *errorCodePtr = errno;
573     return -1;
574 }
575 
576 /*
577  *----------------------------------------------------------------------
578  *
579  * TcpCloseProc --
580  *
581  *	This function is invoked by the generic IO level to perform
582  *	channel-type-specific cleanup when a TCP socket based channel is
583  *	closed.
584  *
585  * Results:
586  *	0 if successful, the value of errno if failed.
587  *
588  * Side effects:
589  *	Closes the socket of the channel.
590  *
591  *----------------------------------------------------------------------
592  */
593 
594 static int
TcpCloseProc(ClientData instanceData,Tcl_Interp * dummy)595 TcpCloseProc(
596     ClientData instanceData,	/* The socket to close. */
597     Tcl_Interp *dummy)		/* For error reporting - unused. */
598 {
599     TcpState *statePtr = (TcpState *)instanceData;
600     int errorCode = 0;
601     TcpFdList *fds;
602     (void)dummy;
603 
604     /*
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.
610      */
611 
612     for (fds = &statePtr->fds; fds != NULL; fds = fds->next) {
613 	if (fds->fd < 0) {
614 	    continue;
615 	}
616 	Tcl_DeleteFileHandler(fds->fd);
617 	if (close(fds->fd) < 0) {
618 	    errorCode = errno;
619 	}
620 
621     }
622     fds = statePtr->fds.next;
623     while (fds != NULL) {
624 	TcpFdList *next = fds->next;
625 
626 	ckfree(fds);
627 	fds = next;
628     }
629     if (statePtr->addrlist != NULL) {
630         freeaddrinfo(statePtr->addrlist);
631     }
632     if (statePtr->myaddrlist != NULL) {
633         freeaddrinfo(statePtr->myaddrlist);
634     }
635     ckfree(statePtr);
636     return errorCode;
637 }
638 
639 /*
640  *----------------------------------------------------------------------
641  *
642  * TcpClose2Proc --
643  *
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.
646  *
647  * Results:
648  *	0 if successful, the value of errno if failed.
649  *
650  * Side effects:
651  *	Shuts down one side of the socket.
652  *
653  *----------------------------------------------------------------------
654  */
655 
656 static int
TcpClose2Proc(ClientData instanceData,Tcl_Interp * dummy,int flags)657 TcpClose2Proc(
658     ClientData instanceData,	/* The socket to close. */
659     Tcl_Interp *dummy,		/* For error reporting. */
660     int flags)			/* Flags that indicate which side to close. */
661 {
662     TcpState *statePtr = (TcpState *)instanceData;
663     int readError = 0;
664     int writeError = 0;
665     (void)dummy;
666 
667     /*
668      * Shutdown the OS socket handle.
669      */
670     if ((flags & (TCL_CLOSE_READ|TCL_CLOSE_WRITE)) == 0) {
671 	return TcpCloseProc(instanceData, NULL);
672     }
673     if ((flags & TCL_CLOSE_READ) && (shutdown(statePtr->fds.fd, SHUT_RD) < 0)) {
674 	readError = errno;
675     }
676     if ((flags & TCL_CLOSE_WRITE) && (shutdown(statePtr->fds.fd, SHUT_WR) < 0)) {
677 	writeError = errno;
678     }
679     return (readError != 0) ? readError : writeError;
680 }
681 
682 /*
683  *----------------------------------------------------------------------
684  *
685  * TcpHostPortList --
686  *
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.
690  *
691  * Results:
692  *	None.
693  *
694  * Side effects:
695  *	Adds three elements do dsPtr
696  *
697  *----------------------------------------------------------------------
698  */
699 
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"
704 #endif
705 static inline int
IPv6AddressNeedsNumericRendering(struct in6_addr addr)706 IPv6AddressNeedsNumericRendering(
707     struct in6_addr addr)
708 {
709     if (IN6_ARE_ADDR_EQUAL(&addr, &in6addr_any)) {
710         return 1;
711     }
712 
713     /*
714      * The IN6_IS_ADDR_V4MAPPED macro has a problem with aliasing warnings on
715      * at least some versions of OSX.
716      */
717 
718     if (!IN6_IS_ADDR_V4MAPPED(&addr)) {
719         return 0;
720     }
721 
722     return (addr.s6_addr[12] == 0 && addr.s6_addr[13] == 0
723             && addr.s6_addr[14] == 0 && addr.s6_addr[15] == 0);
724 }
725 #if defined (__clang__) || ((__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
726 #pragma GCC diagnostic pop
727 #endif
728 #endif /* NEED_FAKE_RFC2553 */
729 
730 static void
TcpHostPortList(Tcl_Interp * interp,Tcl_DString * dsPtr,address addr,socklen_t salen)731 TcpHostPortList(
732     Tcl_Interp *interp,
733     Tcl_DString *dsPtr,
734     address addr,
735     socklen_t salen)
736 {
737 #define SUPPRESS_RDNS_VAR "::tcl::unsupported::noReverseDNS"
738     char host[NI_MAXHOST], nhost[NI_MAXHOST], nport[NI_MAXSERV];
739     int flags = 0;
740 
741     getnameinfo(&addr.sa, salen, nhost, sizeof(nhost), nport, sizeof(nport),
742             NI_NUMERICHOST | NI_NUMERICSERV);
743     Tcl_DStringAppendElement(dsPtr, nhost);
744 
745     /*
746      * We don't want to resolve INADDR_ANY and sin6addr_any; they can
747      * sometimes cause problems (and never have a name).
748      */
749 
750     if (addr.sa.sa_family == AF_INET) {
751         if (addr.sa4.sin_addr.s_addr == INADDR_ANY) {
752             flags |= NI_NUMERICHOST;
753         }
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;
758         }
759 #endif /* NEED_FAKE_RFC2553 */
760     }
761 
762     /*
763      * Check if reverse DNS has been switched off globally.
764      */
765 
766     if (interp != NULL &&
767             Tcl_GetVar2(interp, SUPPRESS_RDNS_VAR, NULL, 0) != NULL) {
768         flags |= NI_NUMERICHOST;
769     }
770     if (getnameinfo(&addr.sa, salen, host, sizeof(host), NULL, 0,
771             flags) == 0) {
772         /*
773          * Reverse mapping worked.
774          */
775 
776         Tcl_DStringAppendElement(dsPtr, host);
777     } else {
778         /*
779          * Reverse mapping failed - use the numeric rep once more.
780          */
781 
782         Tcl_DStringAppendElement(dsPtr, nhost);
783     }
784     Tcl_DStringAppendElement(dsPtr, nport);
785 }
786 
787 /*
788  *----------------------------------------------------------------------
789  *
790  * TcpGetOptionProc --
791  *
792  *	Computes an option value for a TCP socket based channel, or a list of
793  *	all options and their values.
794  *
795  *	Note: This code is based on code contributed by John Haxby.
796  *
797  * Results:
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.
801  *
802  * Side effects:
803  *	None.
804  *
805  *----------------------------------------------------------------------
806  */
807 
808 static int
TcpGetOptionProc(ClientData instanceData,Tcl_Interp * interp,const char * optionName,Tcl_DString * dsPtr)809 TcpGetOptionProc(
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
814 				 * values. */
815     Tcl_DString *dsPtr)		/* Where to store the computed value;
816 				 * initialized by caller. */
817 {
818     TcpState *statePtr = (TcpState *)instanceData;
819     size_t len = 0;
820 
821     WaitForConnect(statePtr, NULL);
822 
823     if (optionName != NULL) {
824 	len = strlen(optionName);
825     }
826 
827     if ((len > 1) && (optionName[1] == 'e') &&
828 	    (strncmp(optionName, "-error", len) == 0)) {
829 	socklen_t optlen = sizeof(int);
830 
831         if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
832             /*
833              * Suppress errors as long as we are not done.
834              */
835 
836             errno = 0;
837         } else if (statePtr->connectError != 0) {
838             errno = statePtr->connectError;
839             statePtr->connectError = 0;
840         } else {
841             int err;
842 
843             getsockopt(statePtr->fds.fd, SOL_SOCKET, SO_ERROR, (char *) &err,
844                     &optlen);
845             errno = err;
846         }
847         if (errno != 0) {
848 	    Tcl_DStringAppend(dsPtr, Tcl_ErrnoMsg(errno), -1);
849         }
850 	return TCL_OK;
851     }
852 
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);
857         return TCL_OK;
858     }
859 
860     if ((len == 0) || ((len > 1) && (optionName[1] == 'p') &&
861 	    (strncmp(optionName, "-peername", len) == 0))) {
862         address peername;
863         socklen_t size = sizeof(peername);
864 
865 	if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
866 	    /*
867 	     * In async connect output an empty string
868 	     */
869 
870 	    if (len == 0) {
871 		Tcl_DStringAppendElement(dsPtr, "-peername");
872 		Tcl_DStringAppendElement(dsPtr, "");
873 	    } else {
874 		return TCL_OK;
875 	    }
876 	} else if (getpeername(statePtr->fds.fd, &peername.sa, &size) >= 0) {
877 	    /*
878 	     * Peername fetch succeeded - output list
879 	     */
880 
881 	    if (len == 0) {
882 		Tcl_DStringAppendElement(dsPtr, "-peername");
883 		Tcl_DStringStartSublist(dsPtr);
884 	    }
885             TcpHostPortList(interp, dsPtr, peername, size);
886 	    if (len) {
887                 return TCL_OK;
888             }
889             Tcl_DStringEndSublist(dsPtr);
890 	} else {
891 	    /*
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.
896 	     */
897 
898 	    if (len) {
899 		if (interp) {
900 		    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
901                             "can't get peername: %s",
902 			    Tcl_PosixError(interp)));
903 		}
904 		return TCL_ERROR;
905 	    }
906 	}
907     }
908 
909     if ((len == 0) || ((len > 1) && (optionName[1] == 's') &&
910 	    (strncmp(optionName, "-sockname", len) == 0))) {
911 	TcpFdList *fds;
912         address sockname;
913         socklen_t size;
914 	int found = 0;
915 
916 	if (len == 0) {
917 	    Tcl_DStringAppendElement(dsPtr, "-sockname");
918 	    Tcl_DStringStartSublist(dsPtr);
919 	}
920 	if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
921 	    /*
922 	     * In async connect output an empty string
923 	     */
924 
925             found = 1;
926 	} else {
927 	    for (fds = &statePtr->fds; fds != NULL; fds = fds->next) {
928 		size = sizeof(sockname);
929 		if (getsockname(fds->fd, &(sockname.sa), &size) >= 0) {
930 		    found = 1;
931 		    TcpHostPortList(interp, dsPtr, sockname, size);
932 		}
933 	    }
934 	}
935         if (found) {
936             if (len) {
937                 return TCL_OK;
938             }
939             Tcl_DStringEndSublist(dsPtr);
940         } else {
941             if (interp) {
942                 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
943                         "can't get sockname: %s", Tcl_PosixError(interp)));
944             }
945 	    return TCL_ERROR;
946 	}
947     }
948 
949     if (len > 0) {
950 	return Tcl_BadChannelOption(interp, optionName,
951                 "connecting peername sockname");
952     }
953 
954     return TCL_OK;
955 }
956 
957 /*
958  * ----------------------------------------------------------------------
959  *
960  * TcpThreadActionProc --
961  *
962  *	Handles detach/attach for asynchronously connecting socket.
963  *
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).
967  *
968  * Results:
969  *	None.
970  *
971  * ----------------------------------------------------------------------
972  */
973 
974 static void
TcpThreadActionProc(ClientData instanceData,int action)975 TcpThreadActionProc(
976     ClientData instanceData,
977     int action)
978 {
979     TcpState *statePtr = (TcpState *)instanceData;
980 
981     if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
982 	/*
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].
987 	 */
988 	switch (action) {
989 	  case TCL_CHANNEL_THREAD_REMOVE:
990 	    CLEAR_BITS(statePtr->flags, TCP_ASYNC_PENDING);
991 	    Tcl_DeleteFileHandler(statePtr->fds.fd);
992 	  break;
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);
997 	  break;
998 	}
999     }
1000 }
1001 
1002 /*
1003  * ----------------------------------------------------------------------
1004  *
1005  * TcpWatchProc --
1006  *
1007  *	Initialize the notifier to watch the fd from this channel.
1008  *
1009  * Results:
1010  *	None.
1011  *
1012  * Side effects:
1013  *	Sets up the notifier so that a future event on the channel will be
1014  *	seen by Tcl.
1015  *
1016  * ----------------------------------------------------------------------
1017  */
1018 
1019 static void
WrapNotify(ClientData clientData,int mask)1020 WrapNotify(
1021     ClientData clientData,
1022     int mask)
1023 {
1024     TcpState *statePtr = (TcpState *) clientData;
1025     int newmask = mask & statePtr->interest;
1026 
1027     if (newmask == 0) {
1028 	/*
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
1037 	 * writable state.
1038 	 */
1039 
1040 	if (errno == 0) {
1041 	    return;
1042 	}
1043 	newmask = TCL_WRITABLE;
1044     }
1045     Tcl_NotifyChannel(statePtr->channel, newmask);
1046 }
1047 
1048 static void
TcpWatchProc(ClientData instanceData,int mask)1049 TcpWatchProc(
1050     ClientData instanceData,	/* The socket state. */
1051     int mask)			/* Events of interest; an OR-ed combination of
1052 				 * TCL_READABLE, TCL_WRITABLE and
1053 				 * TCL_EXCEPTION. */
1054 {
1055     TcpState *statePtr = (TcpState *)instanceData;
1056 
1057     if (statePtr->acceptProc != NULL) {
1058         /*
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).
1062          */
1063 
1064     	return;
1065     }
1066 
1067     if (GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
1068         /*
1069          * Async sockets use a FileHandler internally while connecting, so we
1070          * need to cache this request until the connection has succeeded.
1071          */
1072 
1073         statePtr->filehandlers = mask;
1074     } else if (mask) {
1075 
1076 	/*
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.
1084 	 *
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
1092 	 * that.
1093 	 */
1094 
1095 	statePtr->interest = mask;
1096         Tcl_CreateFileHandler(statePtr->fds.fd, mask|TCL_READABLE,
1097                 (Tcl_FileProc *) WrapNotify, statePtr);
1098     } else {
1099         Tcl_DeleteFileHandler(statePtr->fds.fd);
1100     }
1101 }
1102 
1103 /*
1104  * ----------------------------------------------------------------------
1105  *
1106  * TcpGetHandleProc --
1107  *
1108  *	Called from Tcl_GetChannelHandle to retrieve OS handles from inside a
1109  *	TCP socket based channel.
1110  *
1111  * Results:
1112  *	Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if there is no
1113  *	handle for the specified direction.
1114  *
1115  * Side effects:
1116  *	None.
1117  *
1118  * ----------------------------------------------------------------------
1119  */
1120 
1121 static int
TcpGetHandleProc(ClientData instanceData,int direction,ClientData * handlePtr)1122 TcpGetHandleProc(
1123     ClientData instanceData,	/* The socket state. */
1124     int direction,		/* Not used. */
1125     ClientData *handlePtr)	/* Where to store the handle. */
1126 {
1127     TcpState *statePtr = (TcpState *)instanceData;
1128     (void)direction;
1129 
1130     *handlePtr = INT2PTR(statePtr->fds.fd);
1131     return TCL_OK;
1132 }
1133 
1134 /*
1135  * ----------------------------------------------------------------------
1136  *
1137  * TcpAsyncCallback --
1138  *
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.
1142  *
1143  * ----------------------------------------------------------------------
1144  */
1145 
1146 static void
TcpAsyncCallback(ClientData clientData,int mask)1147 TcpAsyncCallback(
1148     ClientData clientData,	/* The socket state. */
1149     int mask)			/* Events of interest; an OR-ed combination of
1150 				 * TCL_READABLE, TCL_WRITABLE and
1151 				 * TCL_EXCEPTION. */
1152 {
1153     (void)mask;
1154 
1155     TcpConnect(NULL, (TcpState *)clientData);
1156 }
1157 
1158 /*
1159  * ----------------------------------------------------------------------
1160  *
1161  * TcpConnect --
1162  *
1163  *	This function opens a new socket in client mode.
1164  *
1165  * Results:
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.
1169  *
1170  * Side effects:
1171  *	Opens a socket.
1172  *
1173  * Remarks:
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.
1184  *
1185  * ----------------------------------------------------------------------
1186  */
1187 
1188 static int
TcpConnect(Tcl_Interp * interp,TcpState * statePtr)1189 TcpConnect(
1190     Tcl_Interp *interp,		/* For error reporting; can be NULL. */
1191     TcpState *statePtr)
1192 {
1193     socklen_t optlen;
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);
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             int reuseaddr = 1;
1208 
1209 	    /*
1210 	     * No need to try combinations of local and remote addresses of
1211 	     * different families.
1212 	     */
1213 
1214 	    if (statePtr->myaddr->ai_family != statePtr->addr->ai_family) {
1215 		continue;
1216 	    }
1217 
1218             /*
1219              * Close the socket if it is still open from the last unsuccessful
1220              * iteration.
1221              */
1222 
1223             if (statePtr->fds.fd >= 0) {
1224 		close(statePtr->fds.fd);
1225 		statePtr->fds.fd = -1;
1226                 errno = 0;
1227 	    }
1228 
1229 	    statePtr->fds.fd = socket(statePtr->addr->ai_family, SOCK_STREAM,
1230                     0);
1231 	    if (statePtr->fds.fd < 0) {
1232 		continue;
1233 	    }
1234 
1235 	    /*
1236 	     * Set the close-on-exec flag so that the socket will not get
1237 	     * inherited by child processes.
1238 	     */
1239 
1240 	    fcntl(statePtr->fds.fd, F_SETFD, FD_CLOEXEC);
1241 
1242 	    /*
1243 	     * Set kernel space buffering
1244 	     */
1245 
1246 	    TclSockMinimumBuffers(INT2PTR(statePtr->fds.fd), SOCKET_BUFSIZE);
1247 
1248 	    if (async) {
1249                 ret = TclUnixSetBlockingMode(statePtr->fds.fd,
1250                         TCL_MODE_NONBLOCKING);
1251                 if (ret < 0) {
1252                     continue;
1253                 }
1254             }
1255 
1256             /*
1257              * Must reset the error variable here, before we use it for the
1258              * first time in this iteration.
1259              */
1260 
1261             error = 0;
1262 
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);
1267             if (ret < 0) {
1268                 error = errno;
1269                 continue;
1270             }
1271 
1272 	    /*
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.
1277 	     */
1278 
1279 	    ret = connect(statePtr->fds.fd, statePtr->addr->ai_addr,
1280                         statePtr->addr->ai_addrlen);
1281             if (ret < 0) {
1282                 error = errno;
1283             }
1284 	    if (ret < 0 && errno == EINPROGRESS) {
1285                 Tcl_CreateFileHandler(statePtr->fds.fd,
1286                         TCL_WRITABLE | TCL_EXCEPTION, TcpAsyncCallback,
1287                         statePtr);
1288                 errno = EWOULDBLOCK;
1289                 SET_BITS(statePtr->flags, TCP_ASYNC_PENDING);
1290                 return TCL_OK;
1291 
1292             reenter:
1293                 CLEAR_BITS(statePtr->flags, TCP_ASYNC_PENDING);
1294                 Tcl_DeleteFileHandler(statePtr->fds.fd);
1295 
1296                 /*
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].
1301                  */
1302 
1303                 optlen = sizeof(int);
1304 
1305                 getsockopt(statePtr->fds.fd, SOL_SOCKET, SO_ERROR,
1306                         (char *) &error, &optlen);
1307                 errno = error;
1308             }
1309 	    if (error == 0) {
1310 		goto out;
1311 	    }
1312 	}
1313     }
1314 
1315   out:
1316     statePtr->connectError = error;
1317     CLEAR_BITS(statePtr->flags, TCP_ASYNC_CONNECT);
1318     if (async_callback) {
1319         /*
1320          * An asynchonous connection has finally succeeded or failed.
1321          */
1322 
1323         TcpWatchProc(statePtr, statePtr->filehandlers);
1324         TclUnixSetBlockingMode(statePtr->fds.fd, statePtr->cachedBlocking);
1325 
1326         if (error != 0) {
1327             SET_BITS(statePtr->flags, TCP_ASYNC_FAILED);
1328         }
1329 
1330         /*
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().
1337          */
1338 
1339 	if (statePtr->cachedBlocking == TCL_MODE_NONBLOCKING) {
1340 	    Tcl_NotifyChannel(statePtr->channel, TCL_WRITABLE);
1341 	}
1342     }
1343     if (error != 0) {
1344         /*
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.
1348          */
1349 
1350         if (interp != NULL) {
1351             errno = error;
1352             Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1353                     "couldn't open socket: %s", Tcl_PosixError(interp)));
1354         }
1355         return TCL_ERROR;
1356     }
1357     return TCL_OK;
1358 }
1359 
1360 /*
1361  *----------------------------------------------------------------------
1362  *
1363  * Tcl_OpenTcpClient --
1364  *
1365  *	Opens a TCP client socket and creates a channel around it.
1366  *
1367  * Results:
1368  *	The channel or NULL if failed. An error message is returned in the
1369  *	interpreter on failure.
1370  *
1371  * Side effects:
1372  *	Opens a client socket and creates a new channel.
1373  *
1374  *----------------------------------------------------------------------
1375  */
1376 
1377 Tcl_Channel
Tcl_OpenTcpClient(Tcl_Interp * interp,int port,const char * host,const char * myaddr,int myport,int async)1378 Tcl_OpenTcpClient(
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
1386 				 * connect. */
1387 {
1388     TcpState *statePtr;
1389     const char *errorMsg = NULL;
1390     struct addrinfo *addrlist = NULL, *myaddrlist = NULL;
1391     char channelName[SOCK_CHAN_LENGTH];
1392 
1393     /*
1394      * Do the name lookups for the local and remote addresses.
1395      */
1396 
1397     if (!TclCreateSocketAddress(interp, &addrlist, host, port, 0, &errorMsg)
1398             || !TclCreateSocketAddress(interp, &myaddrlist, myaddr, myport, 1,
1399                     &errorMsg)) {
1400         if (addrlist != NULL) {
1401             freeaddrinfo(addrlist);
1402         }
1403         if (interp != NULL) {
1404             Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1405                     "couldn't open socket: %s", errorMsg));
1406         }
1407         return NULL;
1408     }
1409 
1410     /*
1411      * Allocate a new TcpState for this socket.
1412      */
1413 
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;
1421 
1422     /*
1423      * Create a new client socket and wrap it in a channel.
1424      */
1425 
1426     if (TcpConnect(interp, statePtr) != TCL_OK) {
1427         TcpCloseProc(statePtr, NULL);
1428         return NULL;
1429     }
1430 
1431     sprintf(channelName, SOCK_TEMPLATE, (long) statePtr);
1432 
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);
1438 	return NULL;
1439     }
1440     return statePtr->channel;
1441 }
1442 
1443 /*
1444  *----------------------------------------------------------------------
1445  *
1446  * Tcl_MakeTcpClientChannel --
1447  *
1448  *	Creates a Tcl_Channel from an existing client TCP socket.
1449  *
1450  * Results:
1451  *	The Tcl_Channel wrapped around the preexisting TCP socket.
1452  *
1453  * Side effects:
1454  *	None.
1455  *
1456  *----------------------------------------------------------------------
1457  */
1458 
1459 Tcl_Channel
Tcl_MakeTcpClientChannel(ClientData sock)1460 Tcl_MakeTcpClientChannel(
1461     ClientData sock)		/* The socket to wrap up into a channel. */
1462 {
1463     return (Tcl_Channel) TclpMakeTcpClientChannelMode(sock,
1464             TCL_READABLE | TCL_WRITABLE);
1465 }
1466 
1467 /*
1468  *----------------------------------------------------------------------
1469  *
1470  * TclpMakeTcpClientChannelMode --
1471  *
1472  *	Creates a Tcl_Channel from an existing client TCP socket
1473  *	with given mode.
1474  *
1475  * Results:
1476  *	The Tcl_Channel wrapped around the preexisting TCP socket.
1477  *
1478  * Side effects:
1479  *	None.
1480  *
1481  *----------------------------------------------------------------------
1482  */
1483 
1484 void *
TclpMakeTcpClientChannelMode(void * sock,int mode)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. */
1489 {
1490     TcpState *statePtr;
1491     char channelName[SOCK_CHAN_LENGTH];
1492 
1493     statePtr = (TcpState *)ckalloc(sizeof(TcpState));
1494     memset(statePtr, 0, sizeof(TcpState));
1495     statePtr->fds.fd = PTR2INT(sock);
1496     statePtr->flags = 0;
1497 
1498     sprintf(channelName, SOCK_TEMPLATE, (long)statePtr);
1499 
1500     statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
1501 	    statePtr, mode);
1502     if (Tcl_SetChannelOption(NULL, statePtr->channel, "-translation",
1503 	    "auto crlf") == TCL_ERROR) {
1504 	Tcl_Close(NULL, statePtr->channel);
1505 	return NULL;
1506     }
1507     return statePtr->channel;
1508 }
1509 
1510 /*
1511  *----------------------------------------------------------------------
1512  *
1513  * Tcl_OpenTcpServer --
1514  *
1515  *	Opens a TCP server socket and creates a channel around it.
1516  *
1517  * Results:
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.
1520  *
1521  * Side effects:
1522  *	Opens a server socket and creates a new channel.
1523  *
1524  *----------------------------------------------------------------------
1525  */
1526 
1527 Tcl_Channel
Tcl_OpenTcpServer(Tcl_Interp * interp,int port,const char * myHost,Tcl_TcpAcceptProc * acceptProc,ClientData acceptProcData)1528 Tcl_OpenTcpServer(
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
1534 				 * clients. */
1535     ClientData acceptProcData)	/* Data for the callback. */
1536 {
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;
1543 
1544     /*
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.
1547      */
1548 
1549     enum { LOOKUP, SOCKET, BIND, LISTEN } howfar = LOOKUP;
1550     int my_errno = 0;
1551 
1552     if (!TclCreateSocketAddress(interp, &addrlist, myHost, port, 1, &errorMsg)) {
1553 	my_errno = errno;
1554 	goto error;
1555     }
1556 
1557     for (addrPtr = addrlist; addrPtr != NULL; addrPtr = addrPtr->ai_next) {
1558 	sock = socket(addrPtr->ai_family, addrPtr->ai_socktype,
1559                 addrPtr->ai_protocol);
1560 	if (sock == -1) {
1561 	    if (howfar < SOCKET) {
1562 		howfar = SOCKET;
1563 		my_errno = errno;
1564 	    }
1565 	    continue;
1566 	}
1567 
1568 	/*
1569 	 * Set the close-on-exec flag so that the socket will not get
1570 	 * inherited by child processes.
1571 	 */
1572 
1573 	fcntl(sock, F_SETFD, FD_CLOEXEC);
1574 
1575 	/*
1576 	 * Set kernel space buffering
1577 	 */
1578 
1579 	TclSockMinimumBuffers(INT2PTR(sock), SOCKET_BUFSIZE);
1580 
1581 	/*
1582 	 * Set up to reuse server addresses automatically and bind to the
1583 	 * specified port.
1584 	 */
1585 
1586 	(void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
1587 		(char *) &reuseaddr, sizeof(reuseaddr));
1588 
1589         /*
1590          * Make sure we use the same port number when opening two server
1591          * sockets for IPv4 and IPv6 on a random port.
1592          *
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.
1595          */
1596 
1597 	if (port == 0 && chosenport != 0) {
1598 	    ((struct sockaddr_in *) addrPtr->ai_addr)->sin_port =
1599                     htons(chosenport);
1600 	}
1601 
1602 #ifdef IPV6_V6ONLY
1603 	/*
1604          * Missing on: Solaris 2.8
1605          */
1606 
1607         if (addrPtr->ai_family == AF_INET6) {
1608             int v6only = 1;
1609 
1610             (void) setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
1611                     &v6only, sizeof(v6only));
1612         }
1613 #endif /* IPV6_V6ONLY */
1614 
1615 	status = bind(sock, addrPtr->ai_addr, addrPtr->ai_addrlen);
1616         if (status == -1) {
1617 	    if (howfar < BIND) {
1618 		howfar = BIND;
1619 		my_errno = errno;
1620 	    }
1621             close(sock);
1622             sock = -1;
1623             continue;
1624         }
1625         if (port == 0 && chosenport == 0) {
1626             address sockname;
1627             socklen_t namelen = sizeof(sockname);
1628 
1629             /*
1630              * Synchronize port numbers when binding to port 0 of multiple
1631              * addresses.
1632              */
1633 
1634             if (getsockname(sock, &sockname.sa, &namelen) >= 0) {
1635                 chosenport = ntohs(sockname.sa4.sin_port);
1636             }
1637         }
1638         status = listen(sock, SOMAXCONN);
1639         if (status < 0) {
1640 	    if (howfar < LISTEN) {
1641 		howfar = LISTEN;
1642 		my_errno = errno;
1643 	    }
1644             close(sock);
1645             sock = -1;
1646             continue;
1647         }
1648         if (statePtr == NULL) {
1649             /*
1650              * Allocate a new TcpState for this socket.
1651              */
1652 
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;
1659         } else {
1660             newfds = (TcpFdList *)ckalloc(sizeof(TcpFdList));
1661             memset(newfds, (int) 0, sizeof(TcpFdList));
1662             fds->next = newfds;
1663         }
1664         newfds->fd = sock;
1665         newfds->statePtr = statePtr;
1666         fds = newfds;
1667 
1668         /*
1669          * Set up the callback mechanism for accepting connections from new
1670          * clients.
1671          */
1672 
1673         Tcl_CreateFileHandler(sock, TCL_READABLE, TcpAccept, fds);
1674     }
1675 
1676   error:
1677     if (addrlist != NULL) {
1678 	freeaddrinfo(addrlist);
1679     }
1680     if (statePtr != NULL) {
1681 	statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
1682 		statePtr, 0);
1683 	return statePtr->channel;
1684     }
1685     if (interp != NULL) {
1686         Tcl_Obj *errorObj = Tcl_NewStringObj("couldn't open socket: ", -1);
1687 
1688 	if (errorMsg == NULL) {
1689             errno = my_errno;
1690             Tcl_AppendToObj(errorObj, Tcl_PosixError(interp), -1);
1691         } else {
1692 	    Tcl_AppendToObj(errorObj, errorMsg, -1);
1693 	}
1694         Tcl_SetObjResult(interp, errorObj);
1695     }
1696     if (sock != -1) {
1697 	close(sock);
1698     }
1699     return NULL;
1700 }
1701 
1702 /*
1703  *----------------------------------------------------------------------
1704  *
1705  * TcpAccept --
1706  *	Accept a TCP socket connection.	 This is called by the event loop.
1707  *
1708  * Results:
1709  *	None.
1710  *
1711  * Side effects:
1712  *	Creates a new connection socket. Calls the registered callback for the
1713  *	connection acceptance mechanism.
1714  *
1715  *----------------------------------------------------------------------
1716  */
1717 
1718 static void
TcpAccept(ClientData data,int mask)1719 TcpAccept(
1720     ClientData data,		/* Callback token. */
1721     int mask)			/* Not used. */
1722 {
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];
1730     (void)mask;
1731 
1732     len = sizeof(addr);
1733     newsock = accept(fds->fd, &addr.sa, &len);
1734     if (newsock < 0) {
1735 	return;
1736     }
1737 
1738     /*
1739      * Set close-on-exec flag to prevent the newly accepted socket from being
1740      * inherited by child processes.
1741      */
1742 
1743     (void) fcntl(newsock, F_SETFD, FD_CLOEXEC);
1744 
1745     newSockState = (TcpState *)ckalloc(sizeof(TcpState));
1746     memset(newSockState, 0, sizeof(TcpState));
1747     newSockState->flags = 0;
1748     newSockState->fds.fd = newsock;
1749 
1750     sprintf(channelName, SOCK_TEMPLATE, (long) newSockState);
1751     newSockState->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
1752 	    newSockState, TCL_READABLE | TCL_WRITABLE);
1753 
1754     Tcl_SetChannelOption(NULL, newSockState->channel, "-translation",
1755 	    "auto crlf");
1756 
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));
1762     }
1763 }
1764 
1765 /*
1766  * Local Variables:
1767  * mode: c
1768  * c-basic-offset: 4
1769  * fill-column: 78
1770  * tab-width: 8
1771  * indent-tabs-mode: nil
1772  * End:
1773  */
1774