Debian Codegraph @

win/tclWinSock.c

raw
1 /*
2 * tclWinSock.c --
3 *
4 * This file contains Windows-specific socket related code.
5 *
6 * Copyright (c) 1995-1997 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 * The order and naming of functions in this file should minimize
13 * the file diff to tclUnixSock.c.
14 * -----------------------------------------------------------------------
15 *
16 * General information on how this module works.
17 *
18 * - Each Tcl-thread with its sockets maintains an internal window to receive
19 * socket messages from the OS.
20 *
21 * - To ensure that message reception is always running this window is
22 * actually owned and handled by an internal thread. This we call the
23 * co-thread of Tcl's thread.
24 *
25 * - The whole structure is set up by InitSockets() which is called for each
26 * Tcl thread. The implementation of the co-thread is in SocketThread(),
27 * and the messages are handled by SocketProc(). The connection between
28 * both is not directly visible, it is done through a Win32 window class.
29 * This class is initialized by InitSockets() as well, and used in the
30 * creation of the message receiver windows.
31 *
32 * - An important thing to note is that *both* thread and co-thread have
33 * access to the list of sockets maintained in the private TSD data of the
34 * thread. The co-thread was given access to it upon creation through the
35 * new thread's client-data.
36 *
37 * Because of this dual access the TSD data contains an OS mutex, the
38 * "socketListLock", to mediate exclusion between thread and co-thread.
39 *
40 * The co-thread's access is all in SocketProc(). The thread's access is
41 * through SocketEventProc() (1) and the functions called by it.
42 *
43 * (Ad 1) This is the handler function for all queued socket events, which
44 * all the OS messages are translated to through the EventSource (2)
45 * driven by the OS messages.
46 *
47 * (Ad 2) The main functions for this are SocketSetupProc() and
48 * SocketCheckProc().
49 */
50
51 #include "tclWinInt.h"
52
53 #ifdef _MSC_VER
54 # pragma comment (lib, "ws2_32")
55 #endif
56
57 /*
58 * Support for control over sockets' KEEPALIVE and NODELAY behavior is
59 * currently disabled.
60 */
61
62 #undef TCL_FEATURE_KEEPALIVE_NAGLE
63
64 /*
65 * Make sure to remove the redirection defines set in tclWinPort.h that is in
66 * use in other sections of the core, except for us.
67 */
68
69 #undef getservbyname
70 #undef getsockopt
71 #undef setsockopt
72
73 /*
74 * Helper macros to make parts of this file clearer. The macros do exactly
75 * what they say on the tin. :-) They also only ever refer to their arguments
76 * once, and so can be used without regard to side effects.
77 */
78
79 #define SET_BITS(var, bits) ((var) |= (bits))
80 #define CLEAR_BITS(var, bits) ((var) &= ~(bits))
81 #define GOT_BITS(var, bits) (((var) & (bits)) != 0)
82
83 /* "sock" + a pointer in hex + \0 */
84 #define SOCK_CHAN_LENGTH (16 + TCL_INTEGER_SPACE)
85 #define SOCK_TEMPLATE "sock%p"
86
87 /*
88 * The following variable is used to tell whether this module has been
89 * initialized. If 1, initialization of sockets was successful, if -1 then
90 * socket initialization failed (WSAStartup failed).
91 */
92
93 static int initialized = 0;
94 static const WCHAR className[] = L"TclSocket";
95 TCL_DECLARE_MUTEX(socketMutex)
96
97 /*
98 * The following defines declare the messages used on socket windows.
99 */
100
101 #define SOCKET_MESSAGE WM_USER+1
102 #define SOCKET_SELECT WM_USER+2
103 #define SOCKET_TERMINATE WM_USER+3
104 #define SELECT TRUE
105 #define UNSELECT FALSE
106
107 /*
108 * This is needed to comply with the strict aliasing rules of GCC, but it also
109 * simplifies casting between the different sockaddr types.
110 */
111
112 typedef union {
113 struct sockaddr sa;
114 struct sockaddr_in sa4;
115 struct sockaddr_in6 sa6;
116 struct sockaddr_storage sas;
117 } address;
118
119 #ifndef IN6_ARE_ADDR_EQUAL
120 #define IN6_ARE_ADDR_EQUAL IN6_ADDR_EQUAL
121 #endif
122
123 /*
124 * This structure describes per-instance state of a tcp-based channel.
125 */
126
127 typedef struct TcpState TcpState;
128
129 typedef struct TcpFdList {
130 TcpState *statePtr;
131 SOCKET fd;
132 struct TcpFdList *next;
133 } TcpFdList;
134
135 struct TcpState {
136 Tcl_Channel channel; /* Channel associated with this socket. */
137 struct TcpFdList *sockets; /* Windows SOCKET handle. */
138 int flags; /* Bit field comprised of the flags described
139 * below. */
140 int watchEvents; /* OR'ed combination of FD_READ, FD_WRITE,
141 * FD_CLOSE, FD_ACCEPT and FD_CONNECT that
142 * indicate which events are interesting. */
143 volatile int readyEvents; /* OR'ed combination of FD_READ, FD_WRITE,
144 * FD_CLOSE, FD_ACCEPT and FD_CONNECT that
145 * indicate which events have occurred.
146 * Set by notifier thread, access must be
147 * protected by semaphore */
148 int selectEvents; /* OR'ed combination of FD_READ, FD_WRITE,
149 * FD_CLOSE, FD_ACCEPT and FD_CONNECT that
150 * indicate which events are currently being
151 * selected. */
152 volatile int acceptEventCount;
153 /* Count of the current number of FD_ACCEPTs
154 * that have arrived and not yet processed.
155 * Set by notifier thread, access must be
156 * protected by semaphore */
157 Tcl_TcpAcceptProc *acceptProc;
158 /* Proc to call on accept. */
159 void *acceptProcData; /* The data for the accept proc. */
160
161 /*
162 * Only needed for client sockets
163 */
164
165 struct addrinfo *addrlist; /* Addresses to connect to. */
166 struct addrinfo *addr; /* Iterator over addrlist. */
167 struct addrinfo *myaddrlist;/* Local address. */
168 struct addrinfo *myaddr; /* Iterator over myaddrlist. */
169 int connectError; /* Cache status of async socket. */
170 int cachedBlocking; /* Cache blocking mode of async socket. */
171 volatile int notifierConnectError;
172 /* Async connect error set by notifier thread.
173 * This error is still a windows error code.
174 * Access must be protected by semaphore */
175 struct TcpState *nextPtr; /* The next socket on the per-thread socket
176 * list. */
177 };
178
179 /*
180 * These bits may be OR'ed together into the "flags" field of a TcpState
181 * structure.
182 */
183
184 #define TCP_NONBLOCKING (1<<0) /* Socket with non-blocking I/O */
185 #define TCP_ASYNC_CONNECT (1<<1) /* Async connect in progress. */
186 #define SOCKET_EOF (1<<2) /* A zero read happened on the
187 * socket. */
188 #define SOCKET_PENDING (1<<3) /* A message has been sent for this
189 * socket */
190 #define TCP_ASYNC_PENDING (1<<4) /* TcpConnect was called to
191 * process an async connect. This
192 * flag indicates that reentry is
193 * still pending */
194 #define TCP_ASYNC_FAILED (1<<5) /* An async connect finally failed */
195
196 /*
197 * The following structure is what is added to the Tcl event queue when a
198 * socket event occurs.
199 */
200
201 typedef struct {
202 Tcl_Event header; /* Information that is standard for all
203 * events. */
204 SOCKET socket; /* Socket descriptor that is ready. Used to
205 * find the TcpState structure for the file
206 * (can't point directly to the TcpState
207 * structure because it could go away while
208 * the event is queued). */
209 } SocketEvent;
210
211 /*
212 * This defines the minimum buffersize maintained by the kernel.
213 */
214
215 #define TCP_BUFFER_SIZE 4096
216
217
218 typedef struct {
219 HWND hwnd; /* Handle to window for socket messages. */
220 HANDLE socketThread; /* Thread handling the window */
221 Tcl_ThreadId threadId; /* Parent thread. */
222 HANDLE readyEvent; /* Event indicating that a socket event is
223 * ready. Also used to indicate that the
224 * socketThread has been initialized and has
225 * started. */
226 HANDLE socketListLock; /* Win32 Event to lock the socketList */
227 TcpState *pendingTcpState;
228 /* This socket is opened but not jet in the
229 * list. This value is also checked by
230 * the event structure. */
231 TcpState *socketList; /* Every open socket in this thread has an
232 * entry on this list. */
233 } ThreadSpecificData;
234
235 static Tcl_ThreadDataKey dataKey;
236 static WNDCLASSW windowClass;
237
238 /*
239 * Static routines for this file:
240 */
241
242 static int TcpConnect(Tcl_Interp *interp,
243 TcpState *state);
244 static void InitSockets(void);
245 static TcpState * NewSocketInfo(SOCKET socket);
246 static void SocketExitHandler(void *clientData);
247 static LRESULT CALLBACK SocketProc(HWND hwnd, UINT message, WPARAM wParam,
248 LPARAM lParam);
249 static int SocketsEnabled(void);
250 static void TcpAccept(TcpFdList *fds, SOCKET newSocket, address addr);
251 static int WaitForConnect(TcpState *statePtr, int *errorCodePtr);
252 static int WaitForSocketEvent(TcpState *statePtr, int events,
253 int *errorCodePtr);
254 static void AddSocketInfoFd(TcpState *statePtr, SOCKET socket);
255 static int FindFDInList(TcpState *statePtr, SOCKET socket);
256 static DWORD WINAPI SocketThread(LPVOID arg);
257 static void TcpThreadActionProc(void *instanceData,
258 int action);
259
260 static Tcl_EventCheckProc SocketCheckProc;
261 static Tcl_EventProc SocketEventProc;
262 static Tcl_EventSetupProc SocketSetupProc;
263 static Tcl_DriverBlockModeProc TcpBlockModeProc;
264 static Tcl_DriverCloseProc TcpCloseProc;
265 static Tcl_DriverClose2Proc TcpClose2Proc;
266 static Tcl_DriverSetOptionProc TcpSetOptionProc;
267 static Tcl_DriverGetOptionProc TcpGetOptionProc;
268 static Tcl_DriverInputProc TcpInputProc;
269 static Tcl_DriverOutputProc TcpOutputProc;
270 static Tcl_DriverWatchProc TcpWatchProc;
271 static Tcl_DriverGetHandleProc TcpGetHandleProc;
272
273 /*
274 * This structure describes the channel type structure for TCP socket
275 * based IO:
276 */
277
278 static const Tcl_ChannelType tcpChannelType = {
279 "tcp", /* Type name. */
280 TCL_CHANNEL_VERSION_5, /* v5 channel */
281 TcpCloseProc, /* Close proc. */
282 TcpInputProc, /* Input proc. */
283 TcpOutputProc, /* Output proc. */
284 NULL, /* Seek proc. */
285 TcpSetOptionProc, /* Set option proc. */
286 TcpGetOptionProc, /* Get option proc. */
287 TcpWatchProc, /* Initialize notifier. */
288 TcpGetHandleProc, /* Get OS handles out of channel. */
289 TcpClose2Proc, /* Close2 proc. */
290 TcpBlockModeProc, /* Set blocking or non-blocking mode.*/
291 NULL, /* flush proc. */
292 NULL, /* handler proc. */
293 NULL, /* wide seek proc. */
294 TcpThreadActionProc, /* thread action proc. */
295 NULL /* truncate proc. */
296 };
297
298 /*
299 * The following variable holds the network name of this host.
300 */
301
302 static TclInitProcessGlobalValueProc InitializeHostName;
303 static ProcessGlobalValue hostName =
304 {0, 0, NULL, NULL, InitializeHostName, NULL, NULL};
305
306 /*
307 * Simple wrapper round the SendMessage syscall.
308 */
309
310 #define SendSelectMessage(tsdPtr, message, payload) \
311 SendMessageW((tsdPtr)->hwnd, SOCKET_SELECT, \
312 (WPARAM) (message), (LPARAM) (payload))
313
314
315 /*
316 * Address print debug functions
317 */
318 #if 0
319 void
320 printaddrinfo(
321 struct addrinfo *ai,
322 char *prefix)
323 {
324 char host[NI_MAXHOST], port[NI_MAXSERV];
325
326 getnameinfo(ai->ai_addr, ai->ai_addrlen,
327 host, sizeof(host), port, sizeof(port),
328 NI_NUMERICHOST|NI_NUMERICSERV);
329 }
330
331 void
332 printaddrinfolist(
333 struct addrinfo *addrlist,
334 char *prefix)
335 {
336 struct addrinfo *ai;
337
338 for (ai = addrlist; ai != NULL; ai = ai->ai_next) {
339 printaddrinfo(ai, prefix);
340 }
341 }
342 #endif
343
344 /*
345 *----------------------------------------------------------------------
346 *
347 * InitializeHostName --
348 *
349 * This routine sets the process global value of the name of the local
350 * host on which the process is running.
351 *
352 * Results:
353 * None.
354 *
355 *----------------------------------------------------------------------
356 */
357
358 void
359 InitializeHostName(
360 char **valuePtr,
361 int *lengthPtr,
362 Tcl_Encoding *encodingPtr)
363 {
364 WCHAR wbuf[256];
365 DWORD length = sizeof(wbuf)/sizeof(WCHAR);
366 Tcl_DString ds;
367
368 if (GetComputerNameExW(ComputerNamePhysicalDnsFullyQualified, wbuf, &length) != 0) {
369 /*
370 * Convert string from WCHAR to utf-8, then change to lowercase,
371 * then to system encoding.
372 */
373 Tcl_DString inDs;
374
375 Tcl_UtfToLower(Tcl_WinTCharToUtf((TCHAR *)wbuf, -1, &inDs));
376 Tcl_UtfToExternalDString(NULL, Tcl_DStringValue(&inDs), -1, &ds);
377 Tcl_DStringFree(&inDs);
378 } else {
379 Tcl_DStringInit(&ds);
380 if (TclpHasSockets(NULL) == TCL_OK) {
381 /*
382 * The buffer size of 256 is recommended by the MSDN page that
383 * documents gethostname() as being always adequate.
384 */
385
386 Tcl_DStringInit(&ds);
387 Tcl_DStringSetLength(&ds, 256);
388 gethostname(Tcl_DStringValue(&ds), Tcl_DStringLength(&ds));
389 Tcl_DStringSetLength(&ds, strlen(Tcl_DStringValue(&ds)));
390 }
391 }
392
393 *encodingPtr = Tcl_GetEncoding(NULL, NULL);
394 *lengthPtr = Tcl_DStringLength(&ds);
395 *valuePtr = (char *)ckalloc(*lengthPtr + 1);
396 memcpy(*valuePtr, Tcl_DStringValue(&ds), *lengthPtr + 1);
397 Tcl_DStringFree(&ds);
398 }
399
400 /*
401 *----------------------------------------------------------------------
402 *
403 * Tcl_GetHostName --
404 *
405 * Returns the name of the local host.
406 *
407 * Results:
408 * A string containing the network name for this machine, or an empty
409 * string if we can't figure out the name. The caller must not modify or
410 * free this string.
411 *
412 * Side effects:
413 * Caches the name to return for future calls.
414 *
415 *----------------------------------------------------------------------
416 */
417
418 const char *
419 Tcl_GetHostName(void)
420 {
421 return Tcl_GetString(TclGetProcessGlobalValue(&hostName));
422 }
423
424 /*
425 *----------------------------------------------------------------------
426 *
427 * TclpHasSockets --
428 *
429 * This function determines whether sockets are available on the current
430 * system and returns an error in interp if they are not. Note that
431 * interp may be NULL.
432 *
433 * Results:
434 * Returns TCL_OK if the system supports sockets, or TCL_ERROR with an
435 * error in interp (if non-NULL).
436 *
437 * Side effects:
438 * If not already prepared, initializes the TSD structure and socket
439 * message handling thread associated to the calling thread for the
440 * subsystem of the driver.
441 *
442 *----------------------------------------------------------------------
443 */
444
445 int
446 TclpHasSockets(
447 Tcl_Interp *interp) /* Where to write an error message if sockets
448 * are not present, or NULL if no such message
449 * is to be written. */
450 {
451 Tcl_MutexLock(&socketMutex);
452 InitSockets();
453 Tcl_MutexUnlock(&socketMutex);
454
455 if (SocketsEnabled()) {
456 return TCL_OK;
457 }
458 if (interp != NULL) {
459 Tcl_SetObjResult(interp, Tcl_NewStringObj(
460 "sockets are not available on this system", -1));
461 }
462 return TCL_ERROR;
463 }
464
465 /*
466 *----------------------------------------------------------------------
467 *
468 * TclpFinalizeSockets --
469 *
470 * This function is called from Tcl_FinalizeThread to finalize the
471 * platform specific socket subsystem. Also, it may be called from within
472 * this module to cleanup the state if unable to initialize the sockets
473 * subsystem.
474 *
475 * Results:
476 * None.
477 *
478 * Side effects:
479 * Deletes the event source and destroys the socket thread.
480 *
481 *----------------------------------------------------------------------
482 */
483
484 void
485 TclpFinalizeSockets(void)
486 {
487 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
488
489 /*
490 * Careful! This is a finalizer!
491 */
492
493 if (tsdPtr == NULL) {
494 return;
495 }
496
497 if (tsdPtr->socketThread != NULL) {
498 if (tsdPtr->hwnd != NULL) {
499 PostMessageW(tsdPtr->hwnd, SOCKET_TERMINATE, 0, 0);
500
501 /*
502 * Wait for the thread to exit. This ensures that we are
503 * completely cleaned up before we leave this function.
504 */
505
506 WaitForSingleObject(tsdPtr->readyEvent, INFINITE);
507 tsdPtr->hwnd = NULL;
508 }
509 CloseHandle(tsdPtr->socketThread);
510 tsdPtr->socketThread = NULL;
511 }
512 if (tsdPtr->readyEvent != NULL) {
513 CloseHandle(tsdPtr->readyEvent);
514 tsdPtr->readyEvent = NULL;
515 }
516 if (tsdPtr->socketListLock != NULL) {
517 CloseHandle(tsdPtr->socketListLock);
518 tsdPtr->socketListLock = NULL;
519 }
520 Tcl_DeleteEventSource(SocketSetupProc, SocketCheckProc, NULL);
521 }
522
523 /*
524 *----------------------------------------------------------------------
525 *
526 * TcpBlockModeProc --
527 *
528 * This function is invoked by the generic IO level to set blocking and
529 * nonblocking mode on a TCP socket based channel.
530 *
531 * Results:
532 * 0 if successful, errno when failed.
533 *
534 * Side effects:
535 * Sets the device into blocking or nonblocking mode.
536 *
537 *----------------------------------------------------------------------
538 */
539
540 static int
541 TcpBlockModeProc(
542 void *instanceData, /* Socket state. */
543 int mode) /* The mode to set. Can be one of
544 * TCL_MODE_BLOCKING or
545 * TCL_MODE_NONBLOCKING. */
546 {
547 TcpState *statePtr = (TcpState *)instanceData;
548
549 if (mode == TCL_MODE_NONBLOCKING) {
550 SET_BITS(statePtr->flags, TCP_NONBLOCKING);
551 } else {
552 CLEAR_BITS(statePtr->flags, TCP_NONBLOCKING);
553 }
554 return 0;
555 }
556
557 /*
558 *----------------------------------------------------------------------
559 *
560 * WaitForConnect --
561 *
562 * Check the state of an async connect process. If a connection attempt
563 * terminated, process it, which may finalize it or may start the next
564 * attempt. If a connect error occures, it is saved in
565 * statePtr->connectError to be reported by 'fconfigure -error'.
566 *
567 * There are two modes of operation, defined by errorCodePtr:
568 * * non-NULL: Called by explicite read/write command. Block if socket
569 * is blocking.
570 * May return two error codes:
571 * * EWOULDBLOCK: if connect is still in progress
572 * * ENOTCONN: if connect failed. This would be the error message
573 * of a recv or sendto syscall so this is emulated here.
574 * * Null: Called by a background operation. Do not block and don't
575 * return any error code.
576 *
577 * Results:
578 * 0 if the connection has completed, -1 if still in progress or there is
579 * an error.
580 *
581 * Side effects:
582 * Processes socket events off the system queue. May process
583 * asynchronous connect.
584 *
585 *----------------------------------------------------------------------
586 */
587
588 static int
589 WaitForConnect(
590 TcpState *statePtr, /* State of the socket. */
591 int *errorCodePtr) /* Where to store errors? A passed
592 * null-pointer activates background mode. */
593 {
594 int result;
595 int oldMode;
596 ThreadSpecificData *tsdPtr;
597
598 /*
599 * Check if an async connect failed already and error reporting is
600 * demanded, return the error ENOTCONN.
601 */
602
603 if (errorCodePtr != NULL && GOT_BITS(statePtr->flags, TCP_ASYNC_FAILED)) {
604 *errorCodePtr = ENOTCONN;
605 return -1;
606 }
607
608 /*
609 * Check if an async connect is running. If not return ok
610 */
611
612 if (!GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
613 return 0;
614 }
615
616 /*
617 * Be sure to disable event servicing so we are truly modal.
618 */
619
620 oldMode = Tcl_SetServiceMode(TCL_SERVICE_NONE);
621
622 /*
623 * Loop in the blocking case until the connect signal is present
624 */
625
626 while (1) {
627 /*
628 * Get the statePtr lock.
629 */
630
631 tsdPtr = (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
632 WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
633
634 /*
635 * Check for connect event.
636 */
637
638 if (GOT_BITS(statePtr->readyEvents, FD_CONNECT)) {
639 /*
640 * Consume the connect event.
641 */
642
643 CLEAR_BITS(statePtr->readyEvents, FD_CONNECT);
644
645 /*
646 * For blocking sockets and foreground processing, disable async
647 * connect as we continue now synchronously.
648 */
649
650 if (errorCodePtr != NULL &&
651 !GOT_BITS(statePtr->flags, TCP_NONBLOCKING)) {
652 CLEAR_BITS(statePtr->flags, TCP_ASYNC_CONNECT);
653 }
654
655 /*
656 * Free list lock.
657 */
658
659 SetEvent(tsdPtr->socketListLock);
660
661 /*
662 * Continue connect. If switched to synchronous connect, the
663 * connect is terminated.
664 */
665
666 result = TcpConnect(NULL, statePtr);
667
668 /*
669 * Restore event service mode.
670 */
671
672 (void) Tcl_SetServiceMode(oldMode);
673
674 /*
675 * Check for Successful connect or async connect restart
676 */
677
678 if (result == TCL_OK) {
679 /*
680 * Check for async connect restart (not possible for
681 * foreground blocking operation)
682 */
683
684 if (GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
685 if (errorCodePtr != NULL) {
686 *errorCodePtr = EWOULDBLOCK;
687 }
688 return -1;
689 }
690 return 0;
691 }
692
693 /*
694 * Connect finally failed. For foreground operation return
695 * ENOTCONN.
696 */
697
698 if (errorCodePtr != NULL) {
699 *errorCodePtr = ENOTCONN;
700 }
701 return -1;
702 }
703
704 /*
705 * Free list lock.
706 */
707
708 SetEvent(tsdPtr->socketListLock);
709
710 /*
711 * Background operation returns with no action as there was no connect
712 * event
713 */
714
715 if (errorCodePtr == NULL) {
716 return -1;
717 }
718
719 /*
720 * A non blocking socket waiting for an asynchronous connect
721 * returns directly the error EWOULDBLOCK
722 */
723
724 if (GOT_BITS(statePtr->flags, TCP_NONBLOCKING)) {
725 *errorCodePtr = EWOULDBLOCK;
726 return -1;
727 }
728
729 /*
730 * Wait until something happens.
731 */
732
733 WaitForSingleObject(tsdPtr->readyEvent, INFINITE);
734 }
735 }
736
737 /*
738 *----------------------------------------------------------------------
739 *
740 * TcpInputProc --
741 *
742 * This function is invoked by the generic IO level to read input from a
743 * TCP socket based channel.
744 *
745 * Results:
746 * The number of bytes read is returned or -1 on error. An output
747 * argument contains the POSIX error code on error, or zero if no error
748 * occurred.
749 *
750 * Side effects:
751 * Reads input from the input device of the channel.
752 *
753 *----------------------------------------------------------------------
754 */
755
756 static int
757 TcpInputProc(
758 void *instanceData, /* Socket state. */
759 char *buf, /* Where to store data read. */
760 int bufSize, /* How much space is available in the
761 * buffer? */
762 int *errorCodePtr) /* Where to store error code. */
763 {
764 TcpState *statePtr = (TcpState *)instanceData;
765 int bytesRead;
766 DWORD error;
767 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
768
769 *errorCodePtr = 0;
770
771 /*
772 * Check that WinSock is initialized; do not call it if not, to prevent
773 * system crashes. This can happen at exit time if the exit handler for
774 * WinSock ran before other exit handlers that want to use sockets.
775 */
776
777 if (!SocketsEnabled()) {
778 *errorCodePtr = EFAULT;
779 return -1;
780 }
781
782 /*
783 * First check to see if EOF was already detected, to prevent calling the
784 * socket stack after the first time EOF is detected.
785 */
786
787 if (GOT_BITS(statePtr->flags, SOCKET_EOF)) {
788 return 0;
789 }
790
791 /*
792 * Check if there is an async connect running.
793 * For blocking sockets terminate connect, otherwise do one step.
794 * For a non blocking socket return EWOULDBLOCK if connect not terminated
795 */
796
797 if (WaitForConnect(statePtr, errorCodePtr) != 0) {
798 return -1;
799 }
800
801 /*
802 * No EOF, and it is connected, so try to read more from the socket. Note
803 * that we clear the FD_READ bit because read events are level triggered
804 * so a new event will be generated if there is still data available to be
805 * read. We have to simulate blocking behavior here since we are always
806 * using non-blocking sockets.
807 */
808
809 while (1) {
810 SendSelectMessage(tsdPtr, UNSELECT, statePtr);
811
812 /*
813 * Single fd operation: this proc is only called for a connected
814 * socket.
815 */
816
817 bytesRead = recv(statePtr->sockets->fd, buf, bufSize, 0);
818 CLEAR_BITS(statePtr->readyEvents, FD_READ);
819
820 /*
821 * Check for end-of-file condition or successful read.
822 */
823
824 if (bytesRead == 0) {
825 SET_BITS(statePtr->flags, SOCKET_EOF);
826 }
827 if (bytesRead != SOCKET_ERROR) {
828 break;
829 }
830
831 /*
832 * If an error occurs after the FD_CLOSE has arrived, then ignore the
833 * error and report an EOF.
834 */
835
836 if (GOT_BITS(statePtr->readyEvents, FD_CLOSE)) {
837 SET_BITS(statePtr->flags, SOCKET_EOF);
838 bytesRead = 0;
839 break;
840 }
841
842 error = WSAGetLastError();
843
844 /*
845 * If an RST comes, then ignore the error and report an EOF just like
846 * on Unix.
847 */
848
849 if (error == WSAECONNRESET) {
850 SET_BITS(statePtr->flags, SOCKET_EOF);
851 bytesRead = 0;
852 break;
853 }
854
855 /*
856 * Check for error condition or underflow in non-blocking case.
857 */
858
859 if (GOT_BITS(statePtr->flags, TCP_NONBLOCKING)
860 || (error != WSAEWOULDBLOCK)) {
861 TclWinConvertError(error);
862 *errorCodePtr = Tcl_GetErrno();
863 bytesRead = -1;
864 break;
865 }
866
867 /*
868 * In the blocking case, wait until the file becomes readable or
869 * closed and try again.
870 */
871
872 if (!WaitForSocketEvent(statePtr, FD_READ|FD_CLOSE, errorCodePtr)) {
873 bytesRead = -1;
874 break;
875 }
876 }
877
878 SendSelectMessage(tsdPtr, SELECT, statePtr);
879
880 return bytesRead;
881 }
882
883 /*
884 *----------------------------------------------------------------------
885 *
886 * TcpOutputProc --
887 *
888 * This function is called by the generic IO level to write data to a
889 * socket based channel.
890 *
891 * Results:
892 * The number of bytes written or -1 on failure.
893 *
894 * Side effects:
895 * Produces output on the socket.
896 *
897 *----------------------------------------------------------------------
898 */
899
900 static int
901 TcpOutputProc(
902 void *instanceData, /* Socket state. */
903 const char *buf, /* The data buffer. */
904 int toWrite, /* How many bytes to write? */
905 int *errorCodePtr) /* Where to store error code. */
906 {
907 TcpState *statePtr = (TcpState *)instanceData;
908 int written;
909 DWORD error;
910 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
911
912 *errorCodePtr = 0;
913
914 /*
915 * Check that WinSock is initialized; do not call it if not, to prevent
916 * system crashes. This can happen at exit time if the exit handler for
917 * WinSock ran before other exit handlers that want to use sockets.
918 */
919
920 if (!SocketsEnabled()) {
921 *errorCodePtr = EFAULT;
922 return -1;
923 }
924
925 /*
926 * Check if there is an async connect running.
927 * For blocking sockets terminate connect, otherwise do one step.
928 * For a non blocking socket return EWOULDBLOCK if connect not terminated
929 */
930
931 if (WaitForConnect(statePtr, errorCodePtr) != 0) {
932 return -1;
933 }
934
935 while (1) {
936 SendSelectMessage(tsdPtr, UNSELECT, statePtr);
937
938 /*
939 * Single fd operation: this proc is only called for a connected
940 * socket.
941 */
942
943 written = send(statePtr->sockets->fd, buf, toWrite, 0);
944 if (written != SOCKET_ERROR) {
945 /*
946 * Since Windows won't generate a new write event until we hit an
947 * overflow condition, we need to force the event loop to poll
948 * until the condition changes.
949 */
950
951 if (GOT_BITS(statePtr->watchEvents, FD_WRITE)) {
952 Tcl_Time blockTime = { 0, 0 };
953
954 Tcl_SetMaxBlockTime(&blockTime);
955 }
956 break;
957 }
958
959 /*
960 * Check for error condition or overflow. In the event of overflow, we
961 * need to clear the FD_WRITE flag so we can detect the next writable
962 * event. Note that Windows only sends a new writable event after a
963 * send fails with WSAEWOULDBLOCK.
964 */
965
966 error = WSAGetLastError();
967 if (error == WSAEWOULDBLOCK) {
968 CLEAR_BITS(statePtr->readyEvents, FD_WRITE);
969 if (GOT_BITS(statePtr->flags, TCP_NONBLOCKING)) {
970 *errorCodePtr = EWOULDBLOCK;
971 written = -1;
972 break;
973 }
974 } else {
975 TclWinConvertError(error);
976 *errorCodePtr = Tcl_GetErrno();
977 written = -1;
978 break;
979 }
980
981 /*
982 * In the blocking case, wait until the file becomes writable or
983 * closed and try again.
984 */
985
986 if (!WaitForSocketEvent(statePtr, FD_WRITE|FD_CLOSE, errorCodePtr)) {
987 written = -1;
988 break;
989 }
990 }
991
992 SendSelectMessage(tsdPtr, SELECT, statePtr);
993
994 return written;
995 }
996
997 /*
998 *----------------------------------------------------------------------
999 *
1000 * TcpCloseProc --
1001 *
1002 * This function is called by the generic IO level to perform channel
1003 * type specific cleanup on a socket based channel when the channel is
1004 * closed.
1005 *
1006 * Results:
1007 * 0 if successful, the value of errno if failed.
1008 *
1009 * Side effects:
1010 * Closes the socket.
1011 *
1012 *----------------------------------------------------------------------
1013 */
1014
1015 static int
1016 TcpCloseProc(
1017 void *instanceData, /* The socket to close. */
1018 Tcl_Interp *interp) /* Unused. */
1019 {
1020 TcpState *statePtr = (TcpState *)instanceData;
1021 /* TIP #218 */
1022 int errorCode = 0;
1023 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
1024
1025 /*
1026 * Check that WinSock is initialized; do not call it if not, to prevent
1027 * system crashes. This can happen at exit time if the exit handler for
1028 * WinSock ran before other exit handlers that want to use sockets.
1029 */
1030
1031 if (SocketsEnabled()) {
1032 /*
1033 * Clean up the OS socket handle. The default Windows setting for a
1034 * socket is SO_DONTLINGER, which does a graceful shutdown in the
1035 * background.
1036 */
1037
1038 while (statePtr->sockets != NULL) {
1039 TcpFdList *thisfd = statePtr->sockets;
1040
1041 statePtr->sockets = thisfd->next;
1042 if (closesocket(thisfd->fd) == SOCKET_ERROR) {
1043 TclWinConvertError((DWORD) WSAGetLastError());
1044 errorCode = Tcl_GetErrno();
1045 }
1046 ckfree(thisfd);
1047 }
1048 }
1049
1050 if (statePtr->addrlist != NULL) {
1051 freeaddrinfo(statePtr->addrlist);
1052 }
1053 if (statePtr->myaddrlist != NULL) {
1054 freeaddrinfo(statePtr->myaddrlist);
1055 }
1056
1057 /*
1058 * Clear an eventual tsd info list pointer.
1059 *
1060 * This may be called, if an async socket connect fails or is closed
1061 * between connect and thread action callback.
1062 */
1063
1064 if (tsdPtr->pendingTcpState != NULL
1065 && tsdPtr->pendingTcpState == statePtr) {
1066 /*
1067 * Get infoPtr lock, because this concerns the notifier thread.
1068 */
1069
1070 WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
1071
1072 tsdPtr->pendingTcpState = NULL;
1073
1074 /*
1075 * Free list lock.
1076 */
1077
1078 SetEvent(tsdPtr->socketListLock);
1079 }
1080
1081 /*
1082 * TIP #218. Removed the code removing the structure from the global
1083 * socket list. This is now done by the thread action callbacks, and only
1084 * there. This happens before this code is called. We can free without
1085 * fear of damaging the list.
1086 */
1087
1088 ckfree(statePtr);
1089 return errorCode;
1090 }
1091
1092 /*
1093 *----------------------------------------------------------------------
1094 *
1095 * TcpClose2Proc --
1096 *
1097 * This function is called by the generic IO level to perform the channel
1098 * type specific part of a half-close: namely, a shutdown() on a socket.
1099 *
1100 * Results:
1101 * 0 if successful, the value of errno if failed.
1102 *
1103 * Side effects:
1104 * Shuts down one side of the socket.
1105 *
1106 *----------------------------------------------------------------------
1107 */
1108
1109 static int
1110 TcpClose2Proc(
1111 void *instanceData, /* The socket to close. */
1112 Tcl_Interp *interp, /* For error reporting. */
1113 int flags) /* Flags that indicate which side to close. */
1114 {
1115 TcpState *statePtr = (TcpState *)instanceData;
1116 int readError = 0;
1117 int writeError = 0;
1118
1119 /*
1120 * Shutdown the OS socket handle.
1121 */
1122
1123 if ((flags & (TCL_CLOSE_READ|TCL_CLOSE_WRITE)) == 0) {
1124 return TcpCloseProc(instanceData, interp);
1125 }
1126
1127 /*
1128 * Single fd operation: Tcl_OpenTcpServer() does not set TCL_READABLE or
1129 * TCL_WRITABLE so this should never be called for a server socket.
1130 */
1131
1132 if ((flags & TCL_CLOSE_READ) && (shutdown(statePtr->sockets->fd, SD_RECEIVE) == SOCKET_ERROR)) {
1133 TclWinConvertError((DWORD) WSAGetLastError());
1134 readError = Tcl_GetErrno();
1135 }
1136 if ((flags & TCL_CLOSE_WRITE) && (shutdown(statePtr->sockets->fd, SD_SEND) == SOCKET_ERROR)) {
1137 TclWinConvertError((DWORD) WSAGetLastError());
1138 writeError = Tcl_GetErrno();
1139 }
1140 return (readError != 0) ? readError : writeError;
1141 }
1142
1143 /*
1144 *----------------------------------------------------------------------
1145 *
1146 * TcpSetOptionProc --
1147 *
1148 * Sets Tcp channel specific options.
1149 *
1150 * Results:
1151 * None, unless an error happens.
1152 *
1153 * Side effects:
1154 * Changes attributes of the socket at the system level.
1155 *
1156 *----------------------------------------------------------------------
1157 */
1158
1159 static int
1160 TcpSetOptionProc(
1161 void *instanceData, /* Socket state. */
1162 Tcl_Interp *interp, /* For error reporting - can be NULL. */
1163 const char *optionName, /* Name of the option to set. */
1164 const char *value) /* New value for option. */
1165 {
1166 #ifdef TCL_FEATURE_KEEPALIVE_NAGLE
1167 TcpState *statePtr = instanceData;
1168 SOCKET sock;
1169 #endif /*TCL_FEATURE_KEEPALIVE_NAGLE*/
1170
1171 /*
1172 * Check that WinSock is initialized; do not call it if not, to prevent
1173 * system crashes. This can happen at exit time if the exit handler for
1174 * WinSock ran before other exit handlers that want to use sockets.
1175 */
1176
1177 if (!SocketsEnabled()) {
1178 if (interp) {
1179 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1180 "winsock is not initialized", -1));
1181 }
1182 return TCL_ERROR;
1183 }
1184
1185 #ifdef TCL_FEATURE_KEEPALIVE_NAGLE
1186 #error "TCL_FEATURE_KEEPALIVE_NAGLE not reviewed for whether to treat statePtr->sockets as single fd or list"
1187 sock = statePtr->sockets->fd;
1188
1189 if (!strcasecmp(optionName, "-keepalive")) {
1190 BOOL val = FALSE;
1191 int boolVar, rtn;
1192
1193 if (Tcl_GetBoolean(interp, value, &boolVar) != TCL_OK) {
1194 return TCL_ERROR;
1195 }
1196 if (boolVar) {
1197 val = TRUE;
1198 }
1199 rtn = setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE,
1200 (const char *) &val, sizeof(BOOL));
1201 if (rtn != 0) {
1202 TclWinConvertError(WSAGetLastError());
1203 if (interp) {
1204 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1205 "couldn't set socket option: %s",
1206 Tcl_PosixError(interp)));
1207 }
1208 return TCL_ERROR;
1209 }
1210 return TCL_OK;
1211 } else if (!strcasecmp(optionName, "-nagle")) {
1212 BOOL val = FALSE;
1213 int boolVar, rtn;
1214
1215 if (Tcl_GetBoolean(interp, value, &boolVar) != TCL_OK) {
1216 return TCL_ERROR;
1217 }
1218 if (!boolVar) {
1219 val = TRUE;
1220 }
1221 rtn = setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
1222 (const char *) &val, sizeof(BOOL));
1223 if (rtn != 0) {
1224 TclWinConvertError(WSAGetLastError());
1225 if (interp) {
1226 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1227 "couldn't set socket option: %s",
1228 Tcl_PosixError(interp)));
1229 }
1230 return TCL_ERROR;
1231 }
1232 return TCL_OK;
1233 }
1234
1235 return Tcl_BadChannelOption(interp, optionName, "keepalive nagle");
1236 #else
1237 return Tcl_BadChannelOption(interp, optionName, "");
1238 #endif /*TCL_FEATURE_KEEPALIVE_NAGLE*/
1239 }
1240
1241 /*
1242 *----------------------------------------------------------------------
1243 *
1244 * TcpGetOptionProc --
1245 *
1246 * Computes an option value for a TCP socket based channel, or a list of
1247 * all options and their values.
1248 *
1249 * Note: This code is based on code contributed by John Haxby.
1250 *
1251 * Results:
1252 * A standard Tcl result. The value of the specified option or a list of
1253 * all options and their values is returned in the supplied DString. Sets
1254 * Error message if needed.
1255 *
1256 * Side effects:
1257 * None.
1258 *
1259 *----------------------------------------------------------------------
1260 */
1261
1262 static int
1263 TcpGetOptionProc(
1264 void *instanceData, /* Socket state. */
1265 Tcl_Interp *interp, /* For error reporting - can be NULL. */
1266 const char *optionName, /* Name of the option to retrieve the value
1267 * for, or NULL to get all options and their
1268 * values. */
1269 Tcl_DString *dsPtr) /* Where to store the computed value;
1270 * initialized by caller. */
1271 {
1272 TcpState *statePtr = (TcpState *)instanceData;
1273 char host[NI_MAXHOST], port[NI_MAXSERV];
1274 SOCKET sock;
1275 size_t len = 0;
1276 int reverseDNS = 0;
1277 #define SUPPRESS_RDNS_VAR "::tcl::unsupported::noReverseDNS"
1278
1279 /*
1280 * Check that WinSock is initialized; do not call it if not, to prevent
1281 * system crashes. This can happen at exit time if the exit handler for
1282 * WinSock ran before other exit handlers that want to use sockets.
1283 */
1284
1285 if (!SocketsEnabled()) {
1286 if (interp) {
1287 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1288 "winsock is not initialized", -1));
1289 }
1290 return TCL_ERROR;
1291 }
1292
1293 /*
1294 * Go one step in async connect
1295 *
1296 * If any error is thrown save it as background error to report eventually
1297 * below.
1298 */
1299 WaitForConnect(statePtr, NULL);
1300
1301 sock = statePtr->sockets->fd;
1302 if (optionName != NULL) {
1303 len = strlen(optionName);
1304 }
1305
1306 if ((len > 1) && (optionName[1] == 'e') &&
1307 (strncmp(optionName, "-error", len) == 0)) {
1308 /*
1309 * Do not return any errors if async connect is running.
1310 */
1311
1312 if (!GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
1313 if (GOT_BITS(statePtr->flags, TCP_ASYNC_FAILED)) {
1314 /*
1315 * In case of a failed async connect, eventually report the
1316 * connect error only once. Do not report the system error,
1317 * as this comes again and again.
1318 */
1319
1320 if (statePtr->connectError != 0) {
1321 Tcl_DStringAppend(dsPtr,
1322 Tcl_ErrnoMsg(statePtr->connectError), -1);
1323 statePtr->connectError = 0;
1324 }
1325 } else {
1326 /*
1327 * Report an eventual last error of the socket system.
1328 */
1329
1330 int optlen;
1331 int ret;
1332 DWORD err;
1333
1334 /*
1335 * Populate the err variable with a POSIX error
1336 */
1337
1338 optlen = sizeof(int);
1339 ret = getsockopt(sock, SOL_SOCKET, SO_ERROR,
1340 (char *)&err, &optlen);
1341
1342 /*
1343 * The error was not returned directly but should be taken
1344 * from WSA.
1345 */
1346
1347 if (ret == SOCKET_ERROR) {
1348 err = WSAGetLastError();
1349 }
1350
1351 /*
1352 * Return error message.
1353 */
1354
1355 if (err) {
1356 TclWinConvertError(err);
1357 Tcl_DStringAppend(dsPtr, Tcl_ErrnoMsg(Tcl_GetErrno()), -1);
1358 }
1359 }
1360 }
1361 return TCL_OK;
1362 }
1363
1364 if ((len > 1) && (optionName[1] == 'c') &&
1365 (strncmp(optionName, "-connecting", len) == 0)) {
1366 Tcl_DStringAppend(dsPtr,
1367 GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)
1368 ? "1" : "0", -1);
1369 return TCL_OK;
1370 }
1371
1372 if (interp != NULL
1373 && Tcl_GetVar(interp, SUPPRESS_RDNS_VAR, 0) != NULL) {
1374 reverseDNS = NI_NUMERICHOST;
1375 }
1376
1377 if ((len == 0) || ((len > 1) && (optionName[1] == 'p') &&
1378 (strncmp(optionName, "-peername", len) == 0))) {
1379 address peername;
1380 socklen_t size = sizeof(peername);
1381
1382 if (GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
1383 /*
1384 * In async connect output an empty string
1385 */
1386
1387 if (len == 0) {
1388 Tcl_DStringAppendElement(dsPtr, "-peername");
1389 Tcl_DStringAppendElement(dsPtr, "");
1390 } else {
1391 return TCL_OK;
1392 }
1393 } else if (getpeername(sock, (LPSOCKADDR) &(peername.sa),
1394 &size) == 0) {
1395 /*
1396 * Peername fetch succeeded - output list
1397 */
1398
1399 if (len == 0) {
1400 Tcl_DStringAppendElement(dsPtr, "-peername");
1401 Tcl_DStringStartSublist(dsPtr);
1402 }
1403
1404 getnameinfo(&(peername.sa), size, host, sizeof(host),
1405 NULL, 0, NI_NUMERICHOST);
1406 Tcl_DStringAppendElement(dsPtr, host);
1407 getnameinfo(&(peername.sa), size, host, sizeof(host),
1408 port, sizeof(port), reverseDNS | NI_NUMERICSERV);
1409 Tcl_DStringAppendElement(dsPtr, host);
1410 Tcl_DStringAppendElement(dsPtr, port);
1411 if (len == 0) {
1412 Tcl_DStringEndSublist(dsPtr);
1413 } else {
1414 return TCL_OK;
1415 }
1416 } else {
1417 /*
1418 * getpeername failed - but if we were asked for all the options
1419 * (len==0), don't flag an error at that point because it could be
1420 * an fconfigure request on a server socket (such sockets have no
1421 * peer). {Copied from unix/tclUnixChan.c}
1422 */
1423
1424 if (len) {
1425 TclWinConvertError((DWORD) WSAGetLastError());
1426 if (interp) {
1427 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1428 "can't get peername: %s",
1429 Tcl_PosixError(interp)));
1430 }
1431 return TCL_ERROR;
1432 }
1433 }
1434 }
1435
1436 if ((len == 0) || ((len > 1) && (optionName[1] == 's') &&
1437 (strncmp(optionName, "-sockname", len) == 0))) {
1438 TcpFdList *fds;
1439 address sockname;
1440 socklen_t size;
1441 int found = 0;
1442
1443 if (len == 0) {
1444 Tcl_DStringAppendElement(dsPtr, "-sockname");
1445 Tcl_DStringStartSublist(dsPtr);
1446 }
1447 if (GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
1448 /*
1449 * In async connect output an empty string
1450 */
1451
1452 found = 1;
1453 } else {
1454 for (fds = statePtr->sockets; fds != NULL; fds = fds->next) {
1455 sock = fds->fd;
1456 size = sizeof(sockname);
1457 if (getsockname(sock, &(sockname.sa), &size) >= 0) {
1458 int flags = reverseDNS;
1459
1460 found = 1;
1461 getnameinfo(&sockname.sa, size, host, sizeof(host),
1462 NULL, 0, NI_NUMERICHOST);
1463 Tcl_DStringAppendElement(dsPtr, host);
1464
1465 /*
1466 * We don't want to resolve INADDR_ANY and sin6addr_any;
1467 * they can sometimes cause problems (and never have a
1468 * name).
1469 */
1470
1471 flags |= NI_NUMERICSERV;
1472 if (sockname.sa.sa_family == AF_INET) {
1473 if (sockname.sa4.sin_addr.s_addr == INADDR_ANY) {
1474 flags |= NI_NUMERICHOST;
1475 }
1476 } else if (sockname.sa.sa_family == AF_INET6) {
1477 if ((IN6_ARE_ADDR_EQUAL(&sockname.sa6.sin6_addr,
1478 &in6addr_any)) ||
1479 (IN6_IS_ADDR_V4MAPPED(&sockname.sa6.sin6_addr)
1480 && sockname.sa6.sin6_addr.s6_addr[12] == 0
1481 && sockname.sa6.sin6_addr.s6_addr[13] == 0
1482 && sockname.sa6.sin6_addr.s6_addr[14] == 0
1483 && sockname.sa6.sin6_addr.s6_addr[15] == 0)) {
1484 flags |= NI_NUMERICHOST;
1485 }
1486 }
1487 getnameinfo(&sockname.sa, size, host, sizeof(host),
1488 port, sizeof(port), flags);
1489 Tcl_DStringAppendElement(dsPtr, host);
1490 Tcl_DStringAppendElement(dsPtr, port);
1491 }
1492 }
1493 }
1494 if (found) {
1495 if (len) {
1496 return TCL_OK;
1497 }
1498 Tcl_DStringEndSublist(dsPtr);
1499 } else {
1500 if (interp) {
1501 TclWinConvertError((DWORD) WSAGetLastError());
1502 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1503 "can't get sockname: %s", Tcl_PosixError(interp)));
1504 }
1505 return TCL_ERROR;
1506 }
1507 }
1508
1509 #ifdef TCL_FEATURE_KEEPALIVE_NAGLE
1510 if (len == 0 || !strncmp(optionName, "-keepalive", len)) {
1511 int optlen;
1512 BOOL opt = FALSE;
1513
1514 if (len == 0) {
1515 Tcl_DStringAppendElement(dsPtr, "-keepalive");
1516 }
1517 optlen = sizeof(BOOL);
1518 getsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char *)&opt, &optlen);
1519 if (opt) {
1520 Tcl_DStringAppendElement(dsPtr, "1");
1521 } else {
1522 Tcl_DStringAppendElement(dsPtr, "0");
1523 }
1524 if (len > 0) {
1525 return TCL_OK;
1526 }
1527 }
1528
1529 if (len == 0 || !strncmp(optionName, "-nagle", len)) {
1530 int optlen;
1531 BOOL opt = FALSE;
1532
1533 if (len == 0) {
1534 Tcl_DStringAppendElement(dsPtr, "-nagle");
1535 }
1536 optlen = sizeof(BOOL);
1537 getsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&opt, &optlen);
1538 if (opt) {
1539 Tcl_DStringAppendElement(dsPtr, "0");
1540 } else {
1541 Tcl_DStringAppendElement(dsPtr, "1");
1542 }
1543 if (len > 0) {
1544 return TCL_OK;
1545 }
1546 }
1547 #endif /*TCL_FEATURE_KEEPALIVE_NAGLE*/
1548
1549 if (len > 0) {
1550 #ifdef TCL_FEATURE_KEEPALIVE_NAGLE
1551 return Tcl_BadChannelOption(interp, optionName,
1552 "connecting peername sockname keepalive nagle");
1553 #else
1554 return Tcl_BadChannelOption(interp, optionName,
1555 "connecting peername sockname");
1556 #endif /*TCL_FEATURE_KEEPALIVE_NAGLE*/
1557 }
1558
1559 return TCL_OK;
1560 }
1561
1562 /*
1563 *----------------------------------------------------------------------
1564 *
1565 * TcpWatchProc --
1566 *
1567 * Informs the channel driver of the events that the generic channel code
1568 * wishes to receive on this socket.
1569 *
1570 * Results:
1571 * None.
1572 *
1573 * Side effects:
1574 * May cause the notifier to poll if any of the specified conditions are
1575 * already true.
1576 *
1577 *----------------------------------------------------------------------
1578 */
1579
1580 static void
1581 TcpWatchProc(
1582 void *instanceData, /* The socket state. */
1583 int mask) /* Events of interest; an OR-ed combination of
1584 * TCL_READABLE, TCL_WRITABLE and
1585 * TCL_EXCEPTION. */
1586 {
1587 TcpState *statePtr = (TcpState *)instanceData;
1588
1589 /*
1590 * Update the watch events mask. Only if the socket is not a server
1591 * socket. [Bug 557878]
1592 */
1593
1594 if (!statePtr->acceptProc) {
1595 statePtr->watchEvents = 0;
1596 if (GOT_BITS(mask, TCL_READABLE)) {
1597 SET_BITS(statePtr->watchEvents, FD_READ | FD_CLOSE);
1598 }
1599 if (GOT_BITS(mask, TCL_WRITABLE)) {
1600 SET_BITS(statePtr->watchEvents, FD_WRITE | FD_CLOSE);
1601 }
1602
1603 /*
1604 * If there are any conditions already set, then tell the notifier to
1605 * poll rather than block.
1606 */
1607
1608 if (statePtr->readyEvents & statePtr->watchEvents) {
1609 Tcl_Time blockTime = { 0, 0 };
1610
1611 Tcl_SetMaxBlockTime(&blockTime);
1612 }
1613 }
1614 }
1615
1616 /*
1617 *----------------------------------------------------------------------
1618 *
1619 * TcpGetHandleProc --
1620 *
1621 * Called from Tcl_GetChannelHandle to retrieve OS handles from inside a
1622 * TCP socket based channel.
1623 *
1624 * Results:
1625 * Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if there is no
1626 * handle for the specified direction.
1627 *
1628 * Side effects:
1629 * None.
1630 *
1631 *----------------------------------------------------------------------
1632 */
1633
1634 static int
1635 TcpGetHandleProc(
1636 void *instanceData, /* The socket state. */
1637 int direction, /* Not used. */
1638 void **handlePtr) /* Where to store the handle. */
1639 {
1640 TcpState *statePtr = (TcpState *)instanceData;
1641
1642 *handlePtr = INT2PTR(statePtr->sockets->fd);
1643 return TCL_OK;
1644 }
1645
1646
1647
1648 /*
1649 *----------------------------------------------------------------------
1650 *
1651 * TcpConnect --
1652 *
1653 * This function opens a new socket in client mode.
1654 *
1655 * This might be called in 3 circumstances:
1656 * - By a regular socket command
1657 * - By the event handler to continue an asynchronously connect
1658 * - By a blocking socket function (gets/puts) to terminate the
1659 * connect synchronously
1660 *
1661 * Results:
1662 * TCL_OK, if the socket was successfully connected or an asynchronous
1663 * connection is in progress. If an error occurs, TCL_ERROR is returned
1664 * and an error message is left in interp.
1665 *
1666 * Side effects:
1667 * Opens a socket.
1668 *
1669 * Remarks:
1670 * A single host name may resolve to more than one IP address, e.g. for
1671 * an IPv4/IPv6 dual stack host. For handling asynchronously connecting
1672 * sockets in the background for such hosts, this function can act as a
1673 * coroutine. On the first call, it sets up the control variables for the
1674 * two nested loops over the local and remote addresses. Once the first
1675 * connection attempt is in progress, it sets up itself as a writable
1676 * event handler for that socket, and returns. When the callback occurs,
1677 * control is transferred to the "reenter" label, right after the initial
1678 * return and the loops resume as if they had never been interrupted.
1679 * For synchronously connecting sockets, the loops work the usual way.
1680 *
1681 *----------------------------------------------------------------------
1682 */
1683
1684 static int
1685 TcpConnect(
1686 Tcl_Interp *interp, /* For error reporting; can be NULL. */
1687 TcpState *statePtr)
1688 {
1689 DWORD error;
1690 int async_connect = GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT);
1691 /* We are started with async connect and the
1692 * connect notification was not yet
1693 * received. */
1694 int async_callback = GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING);
1695 /* We were called by the event procedure and
1696 * continue our loop. */
1697 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
1698
1699 if (async_callback) {
1700 goto reenter;
1701 }
1702
1703 for (statePtr->addr = statePtr->addrlist; statePtr->addr != NULL;
1704 statePtr->addr = statePtr->addr->ai_next) {
1705 for (statePtr->myaddr = statePtr->myaddrlist;
1706 statePtr->myaddr != NULL;
1707 statePtr->myaddr = statePtr->myaddr->ai_next) {
1708 /*
1709 * No need to try combinations of local and remote addresses
1710 * of different families.
1711 */
1712
1713 if (statePtr->myaddr->ai_family != statePtr->addr->ai_family) {
1714 continue;
1715 }
1716
1717 /*
1718 * Close the socket if it is still open from the last unsuccessful
1719 * iteration.
1720 */
1721
1722 if (statePtr->sockets->fd != INVALID_SOCKET) {
1723 closesocket(statePtr->sockets->fd);
1724 }
1725
1726 /*
1727 * Get statePtr lock.
1728 */
1729
1730 WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
1731
1732 /*
1733 * Reset last error from last try
1734 */
1735
1736 statePtr->notifierConnectError = 0;
1737 Tcl_SetErrno(0);
1738
1739 statePtr->sockets->fd = socket(statePtr->myaddr->ai_family,
1740 SOCK_STREAM, 0);
1741
1742 /*
1743 * Free list lock.
1744 */
1745
1746 SetEvent(tsdPtr->socketListLock);
1747
1748 /*
1749 * Continue on socket creation error.
1750 */
1751
1752 if (statePtr->sockets->fd == INVALID_SOCKET) {
1753 TclWinConvertError((DWORD) WSAGetLastError());
1754 continue;
1755 }
1756
1757 /*
1758 * Win-NT has a misfeature that sockets are inherited in child
1759 * processes by default. Turn off the inherit bit.
1760 */
1761
1762 SetHandleInformation((HANDLE) statePtr->sockets->fd,
1763 HANDLE_FLAG_INHERIT, 0);
1764
1765 /*
1766 * Set kernel space buffering
1767 */
1768
1769 TclSockMinimumBuffers((void *) statePtr->sockets->fd,
1770 TCP_BUFFER_SIZE);
1771
1772 /*
1773 * Try to bind to a local port.
1774 */
1775
1776 if (bind(statePtr->sockets->fd, statePtr->myaddr->ai_addr,
1777 statePtr->myaddr->ai_addrlen) == SOCKET_ERROR) {
1778 TclWinConvertError((DWORD) WSAGetLastError());
1779 continue;
1780 }
1781
1782 /*
1783 * For asynchronous connect set the socket in nonblocking mode
1784 * and activate connect notification
1785 */
1786
1787 if (async_connect) {
1788 TcpState *statePtr2;
1789 int in_socket_list = 0;
1790
1791 /*
1792 * Get statePtr lock.
1793 */
1794
1795 WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
1796
1797 /*
1798 * Bugfig for 336441ed59 to not ignore notifications until the
1799 * infoPtr is in the list.
1800 * Check if my statePtr is already in the tsdPtr->socketList
1801 * It is set after this call by TcpThreadActionProc and is set
1802 * on a second round.
1803 *
1804 * If not, we buffer my statePtr in the tsd memory so it is
1805 * not lost by the event procedure
1806 */
1807
1808 for (statePtr2 = tsdPtr->socketList; statePtr2 != NULL;
1809 statePtr2 = statePtr2->nextPtr) {
1810 if (statePtr2 == statePtr) {
1811 in_socket_list = 1;
1812 break;
1813 }
1814 }
1815 if (!in_socket_list) {
1816 tsdPtr->pendingTcpState = statePtr;
1817 }
1818
1819 /*
1820 * Set connect mask to connect events
1821 *
1822 * This is activated by a SOCKET_SELECT message to the
1823 * notifier thread.
1824 */
1825
1826 SET_BITS(statePtr->selectEvents, FD_CONNECT);
1827
1828 /*
1829 * Free list lock.
1830 */
1831
1832 SetEvent(tsdPtr->socketListLock);
1833
1834 /*
1835 * Activate accept notification.
1836 */
1837
1838 SendSelectMessage(tsdPtr, SELECT, statePtr);
1839 }
1840
1841 /*
1842 * Attempt to connect to the remote socket.
1843 */
1844
1845 connect(statePtr->sockets->fd, statePtr->addr->ai_addr,
1846 statePtr->addr->ai_addrlen);
1847
1848 error = WSAGetLastError();
1849 TclWinConvertError(error);
1850
1851 if (async_connect && error == WSAEWOULDBLOCK) {
1852 /*
1853 * Asynchronous connect
1854 *
1855 * Remember that we jump back behind this next round
1856 */
1857
1858 SET_BITS(statePtr->flags, TCP_ASYNC_PENDING);
1859 return TCL_OK;
1860
1861 reenter:
1862 /*
1863 * Re-entry point for async connect after connect event or
1864 * blocking operation
1865 *
1866 * Clear the reenter flag
1867 */
1868
1869 CLEAR_BITS(statePtr->flags, TCP_ASYNC_PENDING);
1870
1871 /*
1872 * Get statePtr lock.
1873 */
1874
1875 WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
1876
1877 /*
1878 * Get signaled connect error.
1879 */
1880
1881 TclWinConvertError((DWORD) statePtr->notifierConnectError);
1882
1883 /*
1884 * Clear eventual connect flag.
1885 */
1886
1887 CLEAR_BITS(statePtr->selectEvents, FD_CONNECT);
1888
1889 /*
1890 * Free list lock.
1891 */
1892
1893 SetEvent(tsdPtr->socketListLock);
1894 }
1895
1896 /*
1897 * Clear the tsd socket list pointer if we did not wait for
1898 * the FD_CONNECT asynchronously
1899 */
1900
1901 tsdPtr->pendingTcpState = NULL;
1902
1903 if (Tcl_GetErrno() == 0) {
1904 goto out;
1905 }
1906 }
1907 }
1908
1909 out:
1910 /*
1911 * Socket connected or connection failed
1912 */
1913
1914 /*
1915 * Async connect terminated
1916 */
1917
1918 CLEAR_BITS(statePtr->flags, TCP_ASYNC_CONNECT);
1919
1920 if (Tcl_GetErrno() == 0) {
1921 /*
1922 * Successfully connected
1923 *
1924 * Set up the select mask for read/write events.
1925 */
1926
1927 statePtr->selectEvents = FD_READ | FD_WRITE | FD_CLOSE;
1928
1929 /*
1930 * Register for interest in events in the select mask. Note that this
1931 * automatically places the socket into non-blocking mode.
1932 */
1933
1934 SendSelectMessage(tsdPtr, SELECT, statePtr);
1935 } else {
1936 /*
1937 * Connect failed
1938 *
1939 * For async connect schedule a writable event to report the fail.
1940 */
1941
1942 if (async_callback) {
1943 /*
1944 * Set up the select mask for read/write events.
1945 */
1946
1947 statePtr->selectEvents = FD_WRITE|FD_READ;
1948
1949 /*
1950 * Get statePtr lock.
1951 */
1952
1953 WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
1954
1955 /*
1956 * Signal ready readable and writable events.
1957 */
1958
1959 SET_BITS(statePtr->readyEvents, FD_WRITE | FD_READ);
1960
1961 /*
1962 * Flag error to event routine.
1963 */
1964
1965 SET_BITS(statePtr->flags, TCP_ASYNC_FAILED);
1966
1967 /*
1968 * Save connect error to be reported by 'fconfigure -error'.
1969 */
1970
1971 statePtr->connectError = Tcl_GetErrno();
1972
1973 /*
1974 * Free list lock.
1975 */
1976
1977 SetEvent(tsdPtr->socketListLock);
1978 }
1979
1980 /*
1981 * Error message on synchronous connect
1982 */
1983
1984 if (interp != NULL) {
1985 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1986 "couldn't open socket: %s", Tcl_PosixError(interp)));
1987 }
1988 return TCL_ERROR;
1989 }
1990 return TCL_OK;
1991 }
1992
1993 /*
1994 *----------------------------------------------------------------------
1995 *
1996 * Tcl_OpenTcpClient --
1997 *
1998 * Opens a TCP client socket and creates a channel around it.
1999 *
2000 * Results:
2001 * The channel or NULL if failed. An error message is returned in the
2002 * interpreter on failure.
2003 *
2004 * Side effects:
2005 * Opens a client socket and creates a new channel.
2006 *
2007 *----------------------------------------------------------------------
2008 */
2009
2010 Tcl_Channel
2011 Tcl_OpenTcpClient(
2012 Tcl_Interp *interp, /* For error reporting; can be NULL. */
2013 int port, /* Port number to open. */
2014 const char *host, /* Host on which to open port. */
2015 const char *myaddr, /* Client-side address */
2016 int myport, /* Client-side port */
2017 int async) /* If nonzero, attempt to do an asynchronous
2018 * connect. Otherwise we do a blocking
2019 * connect. */
2020 {
2021 TcpState *statePtr;
2022 const char *errorMsg = NULL;
2023 struct addrinfo *addrlist = NULL, *myaddrlist = NULL;
2024 char channelName[SOCK_CHAN_LENGTH];
2025
2026 if (TclpHasSockets(interp) != TCL_OK) {
2027 return NULL;
2028 }
2029
2030 /*
2031 * Check that WinSock is initialized; do not call it if not, to prevent
2032 * system crashes. This can happen at exit time if the exit handler for
2033 * WinSock ran before other exit handlers that want to use sockets.
2034 */
2035
2036 if (!SocketsEnabled()) {
2037 return NULL;
2038 }
2039
2040 /*
2041 * Do the name lookups for the local and remote addresses.
2042 */
2043
2044 if (!TclCreateSocketAddress(interp, &addrlist, host, port, 0, &errorMsg)
2045 || !TclCreateSocketAddress(interp, &myaddrlist, myaddr, myport, 1,
2046 &errorMsg)) {
2047 if (addrlist != NULL) {
2048 freeaddrinfo(addrlist);
2049 }
2050 if (interp != NULL) {
2051 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2052 "couldn't open socket: %s", errorMsg));
2053 }
2054 return NULL;
2055 }
2056
2057 statePtr = NewSocketInfo(INVALID_SOCKET);
2058 statePtr->addrlist = addrlist;
2059 statePtr->myaddrlist = myaddrlist;
2060 if (async) {
2061 SET_BITS(statePtr->flags, TCP_ASYNC_CONNECT);
2062 }
2063
2064 /*
2065 * Create a new client socket and wrap it in a channel.
2066 */
2067 if (TcpConnect(interp, statePtr) != TCL_OK) {
2068 TcpCloseProc(statePtr, NULL);
2069 return NULL;
2070 }
2071
2072 snprintf(channelName, sizeof(channelName), SOCK_TEMPLATE, statePtr);
2073
2074 statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
2075 statePtr, (TCL_READABLE | TCL_WRITABLE));
2076 if (TCL_ERROR == Tcl_SetChannelOption(NULL, statePtr->channel,
2077 "-translation", "auto crlf")) {
2078 Tcl_Close(NULL, statePtr->channel);
2079 return NULL;
2080 } else if (TCL_ERROR == Tcl_SetChannelOption(NULL, statePtr->channel,
2081 "-eofchar", "")) {
2082 Tcl_Close(NULL, statePtr->channel);
2083 return NULL;
2084 }
2085 return statePtr->channel;
2086 }
2087
2088 /*
2089 *----------------------------------------------------------------------
2090 *
2091 * Tcl_MakeTcpClientChannel --
2092 *
2093 * Creates a Tcl_Channel from an existing client TCP socket.
2094 *
2095 * Results:
2096 * The Tcl_Channel wrapped around the preexisting TCP socket.
2097 *
2098 * Side effects:
2099 * None.
2100 *
2101 *----------------------------------------------------------------------
2102 */
2103
2104 Tcl_Channel
2105 Tcl_MakeTcpClientChannel(
2106 void *sock) /* The socket to wrap up into a channel. */
2107 {
2108 TcpState *statePtr;
2109 char channelName[SOCK_CHAN_LENGTH];
2110 ThreadSpecificData *tsdPtr;
2111
2112 if (TclpHasSockets(NULL) != TCL_OK) {
2113 return NULL;
2114 }
2115
2116 tsdPtr = (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
2117
2118 /*
2119 * Set kernel space buffering and non-blocking.
2120 */
2121
2122 TclSockMinimumBuffers(sock, TCP_BUFFER_SIZE);
2123
2124 statePtr = NewSocketInfo((SOCKET) sock);
2125
2126 /*
2127 * Start watching for read/write events on the socket.
2128 */
2129
2130 statePtr->selectEvents = FD_READ | FD_CLOSE | FD_WRITE;
2131 SendSelectMessage(tsdPtr, SELECT, statePtr);
2132
2133 snprintf(channelName, sizeof(channelName), SOCK_TEMPLATE, statePtr);
2134 statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
2135 statePtr, (TCL_READABLE | TCL_WRITABLE));
2136 Tcl_SetChannelOption(NULL, statePtr->channel, "-translation", "auto crlf");
2137 return statePtr->channel;
2138 }
2139
2140 /*
2141 *----------------------------------------------------------------------
2142 *
2143 * Tcl_OpenTcpServer --
2144 *
2145 * Opens a TCP server socket and creates a channel around it.
2146 *
2147 * Results:
2148 * The channel or NULL if failed. If an error occurred, an error message
2149 * is left in the interp's result if interp is not NULL.
2150 *
2151 * Side effects:
2152 * Opens a server socket and creates a new channel.
2153 *
2154 *----------------------------------------------------------------------
2155 */
2156
2157 Tcl_Channel
2158 Tcl_OpenTcpServer(
2159 Tcl_Interp *interp, /* For error reporting - may be NULL. */
2160 int port, /* Port number to open. */
2161 const char *myHost, /* Name of local host. */
2162 Tcl_TcpAcceptProc *acceptProc,
2163 /* Callback for accepting connections from new
2164 * clients. */
2165 void *acceptProcData) /* Data for the callback. */
2166 {
2167 SOCKET sock = INVALID_SOCKET;
2168 unsigned short chosenport = 0;
2169 struct addrinfo *addrlist = NULL;
2170 struct addrinfo *addrPtr; /* Socket address to listen on. */
2171 TcpState *statePtr = NULL; /* The returned value. */
2172 char channelName[SOCK_CHAN_LENGTH];
2173 u_long flag = 1; /* Indicates nonblocking mode. */
2174 const char *errorMsg = NULL;
2175
2176 if (TclpHasSockets(interp) != TCL_OK) {
2177 return NULL;
2178 }
2179
2180 /*
2181 * Check that WinSock is initialized; do not call it if not, to prevent
2182 * system crashes. This can happen at exit time if the exit handler for
2183 * WinSock ran before other exit handlers that want to use sockets.
2184 */
2185
2186 if (!SocketsEnabled()) {
2187 return NULL;
2188 }
2189
2190 /*
2191 * Construct the addresses for each end of the socket.
2192 */
2193
2194 if (!TclCreateSocketAddress(interp, &addrlist, myHost, port, 1,
2195 &errorMsg)) {
2196 goto error;
2197 }
2198
2199 for (addrPtr = addrlist; addrPtr != NULL; addrPtr = addrPtr->ai_next) {
2200 sock = socket(addrPtr->ai_family, addrPtr->ai_socktype,
2201 addrPtr->ai_protocol);
2202 if (sock == INVALID_SOCKET) {
2203 TclWinConvertError((DWORD) WSAGetLastError());
2204 continue;
2205 }
2206
2207 /*
2208 * Win-NT has a misfeature that sockets are inherited in child
2209 * processes by default. Turn off the inherit bit.
2210 */
2211
2212 SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
2213
2214 /*
2215 * Set kernel space buffering
2216 */
2217
2218 TclSockMinimumBuffers((void *)sock, TCP_BUFFER_SIZE);
2219
2220 /*
2221 * Make sure we use the same port when opening two server sockets
2222 * for IPv4 and IPv6.
2223 *
2224 * As sockaddr_in6 uses the same offset and size for the port
2225 * member as sockaddr_in, we can handle both through the IPv4 API.
2226 */
2227
2228 if (port == 0 && chosenport != 0) {
2229 ((struct sockaddr_in *) addrPtr->ai_addr)->sin_port =
2230 htons(chosenport);
2231 }
2232
2233 /*
2234 * Bind to the specified port. Note that we must not call
2235 * setsockopt with SO_REUSEADDR because Microsoft allows addresses
2236 * to be reused even if they are still in use.
2237 *
2238 * Bind should not be affected by the socket having already been
2239 * set into nonblocking mode. If there is trouble, this is one
2240 * place to look for bugs.
2241 */
2242
2243 if (bind(sock, addrPtr->ai_addr,
2244 addrPtr->ai_addrlen) == SOCKET_ERROR) {
2245 TclWinConvertError((DWORD) WSAGetLastError());
2246 closesocket(sock);
2247 continue;
2248 }
2249 if (port == 0 && chosenport == 0) {
2250 address sockname;
2251 socklen_t namelen = sizeof(sockname);
2252
2253 /*
2254 * Synchronize port numbers when binding to port 0 of multiple
2255 * addresses.
2256 */
2257
2258 if (getsockname(sock, &sockname.sa, &namelen) >= 0) {
2259 chosenport = ntohs(sockname.sa4.sin_port);
2260 }
2261 }
2262
2263 /*
2264 * Set the maximum number of pending connect requests to the max
2265 * value allowed on each platform (Win32 and Win32s may be
2266 * different, and there may be differences between TCP/IP stacks).
2267 */
2268
2269 if (listen(sock, SOMAXCONN) == SOCKET_ERROR) {
2270 TclWinConvertError((DWORD) WSAGetLastError());
2271 closesocket(sock);
2272 continue;
2273 }
2274
2275 if (statePtr == NULL) {
2276 /*
2277 * Add this socket to the global list of sockets.
2278 */
2279
2280 statePtr = NewSocketInfo(sock);
2281 } else {
2282 AddSocketInfoFd(statePtr, sock);
2283 }
2284 }
2285
2286 error:
2287 if (addrlist != NULL) {
2288 freeaddrinfo(addrlist);
2289 }
2290
2291 if (statePtr != NULL) {
2292 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
2293
2294 statePtr->acceptProc = acceptProc;
2295 statePtr->acceptProcData = acceptProcData;
2296 snprintf(channelName, sizeof(channelName), SOCK_TEMPLATE, statePtr);
2297 statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
2298 statePtr, 0);
2299 /*
2300 * Set up the select mask for connection request events.
2301 */
2302
2303 statePtr->selectEvents = FD_ACCEPT;
2304
2305 /*
2306 * Register for interest in events in the select mask. Note that this
2307 * automatically places the socket into non-blocking mode.
2308 */
2309
2310 ioctlsocket(sock, (long) FIONBIO, &flag);
2311 SendSelectMessage(tsdPtr, SELECT, statePtr);
2312 if (Tcl_SetChannelOption(interp, statePtr->channel, "-eofchar", "")
2313 == TCL_ERROR) {
2314 Tcl_Close(NULL, statePtr->channel);
2315 return NULL;
2316 }
2317 return statePtr->channel;
2318 }
2319
2320 if (interp != NULL) {
2321 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2322 "couldn't open socket: %s",
2323 (errorMsg ? errorMsg : Tcl_PosixError(interp))));
2324 }
2325
2326 if (sock != INVALID_SOCKET) {
2327 closesocket(sock);
2328 }
2329 return NULL;
2330 }
2331
2332 /*
2333 *----------------------------------------------------------------------
2334 *
2335 * TcpAccept --
2336 * Accept a TCP socket connection. This is called by the event loop.
2337 *
2338 * Results:
2339 * None.
2340 *
2341 * Side effects:
2342 * Creates a new connection socket. Calls the registered callback for the
2343 * connection acceptance mechanism.
2344 *
2345 *----------------------------------------------------------------------
2346 */
2347
2348 static void
2349 TcpAccept(
2350 TcpFdList *fds, /* Server socket that accepted newSocket. */
2351 SOCKET newSocket, /* Newly accepted socket. */
2352 address addr) /* Address of new socket. */
2353 {
2354 TcpState *newInfoPtr;
2355 TcpState *statePtr = fds->statePtr;
2356 int len = sizeof(addr);
2357 char channelName[SOCK_CHAN_LENGTH];
2358 char host[NI_MAXHOST], port[NI_MAXSERV];
2359 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
2360
2361 /*
2362 * Win-NT has a misfeature that sockets are inherited in child processes
2363 * by default. Turn off the inherit bit.
2364 */
2365
2366 SetHandleInformation((HANDLE) newSocket, HANDLE_FLAG_INHERIT, 0);
2367
2368 /*
2369 * Add this socket to the global list of sockets.
2370 */
2371
2372 newInfoPtr = NewSocketInfo(newSocket);
2373
2374 /*
2375 * Select on read/write events and create the channel.
2376 */
2377
2378 newInfoPtr->selectEvents = (FD_READ | FD_WRITE | FD_CLOSE);
2379 SendSelectMessage(tsdPtr, SELECT, newInfoPtr);
2380
2381 snprintf(channelName, sizeof(channelName), SOCK_TEMPLATE, newInfoPtr);
2382 newInfoPtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
2383 newInfoPtr, (TCL_READABLE | TCL_WRITABLE));
2384 if (Tcl_SetChannelOption(NULL, newInfoPtr->channel, "-translation",
2385 "auto crlf") == TCL_ERROR) {
2386 Tcl_Close(NULL, newInfoPtr->channel);
2387 return;
2388 }
2389 if (Tcl_SetChannelOption(NULL, newInfoPtr->channel, "-eofchar", "")
2390 == TCL_ERROR) {
2391 Tcl_Close(NULL, newInfoPtr->channel);
2392 return;
2393 }
2394
2395 /*
2396 * Invoke the accept callback function.
2397 */
2398
2399 if (statePtr->acceptProc != NULL) {
2400 getnameinfo(&(addr.sa), len, host, sizeof(host), port, sizeof(port),
2401 NI_NUMERICHOST|NI_NUMERICSERV);
2402 statePtr->acceptProc(statePtr->acceptProcData, newInfoPtr->channel,
2403 host, atoi(port));
2404 }
2405 }
2406
2407 /*
2408 *----------------------------------------------------------------------
2409 *
2410 * InitSockets --
2411 *
2412 * Registers the event window for the socket notifier code.
2413 *
2414 * Assumes socketMutex is held.
2415 *
2416 * Results:
2417 * None.
2418 *
2419 * Side effects:
2420 * Register a new window class and creates a
2421 * window for use in asynchronous socket notification.
2422 *
2423 *----------------------------------------------------------------------
2424 */
2425
2426 static void
2427 InitSockets(void)
2428 {
2429 DWORD id;
2430 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
2431
2432 if (!initialized) {
2433 initialized = 1;
2434 TclCreateLateExitHandler(SocketExitHandler, NULL);
2435
2436 /*
2437 * Create the async notification window with a new class. We must
2438 * create a new class to avoid a Windows 95 bug that causes us to get
2439 * the wrong message number for socket events if the message window is
2440 * a subclass of a static control.
2441 */
2442
2443 windowClass.style = 0;
2444 windowClass.cbClsExtra = 0;
2445 windowClass.cbWndExtra = 0;
2446 windowClass.hInstance = (HINSTANCE)TclWinGetTclInstance();
2447 windowClass.hbrBackground = NULL;
2448 windowClass.lpszMenuName = NULL;
2449 windowClass.lpszClassName = className;
2450 windowClass.lpfnWndProc = SocketProc;
2451 windowClass.hIcon = NULL;
2452 windowClass.hCursor = NULL;
2453
2454 if (!RegisterClassW(&windowClass)) {
2455 TclWinConvertError(GetLastError());
2456 goto initFailure;
2457 }
2458 }
2459
2460 /*
2461 * Check for per-thread initialization.
2462 */
2463
2464 if (tsdPtr != NULL) {
2465 return;
2466 }
2467
2468 /*
2469 * OK, this thread has never done anything with sockets before. Construct
2470 * a worker thread to handle asynchronous events related to sockets
2471 * assigned to _this_ thread.
2472 */
2473
2474 tsdPtr = TCL_TSD_INIT(&dataKey);
2475 tsdPtr->pendingTcpState = NULL;
2476 tsdPtr->socketList = NULL;
2477 tsdPtr->hwnd = NULL;
2478 tsdPtr->threadId = Tcl_GetCurrentThread();
2479 tsdPtr->readyEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
2480 if (tsdPtr->readyEvent == NULL) {
2481 goto initFailure;
2482 }
2483 tsdPtr->socketListLock = CreateEventW(NULL, FALSE, TRUE, NULL);
2484 if (tsdPtr->socketListLock == NULL) {
2485 goto initFailure;
2486 }
2487 tsdPtr->socketThread = CreateThread(NULL, 256, SocketThread, tsdPtr, 0,
2488 &id);
2489 if (tsdPtr->socketThread == NULL) {
2490 goto initFailure;
2491 }
2492
2493 SetThreadPriority(tsdPtr->socketThread, THREAD_PRIORITY_HIGHEST);
2494
2495 /*
2496 * Wait for the thread to signal when the window has been created and if
2497 * it is ready to go.
2498 */
2499
2500 WaitForSingleObject(tsdPtr->readyEvent, INFINITE);
2501
2502 if (tsdPtr->hwnd == NULL) {
2503 goto initFailure; /* Trouble creating the window. */
2504 }
2505
2506 Tcl_CreateEventSource(SocketSetupProc, SocketCheckProc, NULL);
2507 return;
2508
2509 initFailure:
2510 TclpFinalizeSockets();
2511 initialized = -1;
2512 return;
2513 }
2514
2515 /*
2516 *----------------------------------------------------------------------
2517 *
2518 * SocketsEnabled --
2519 *
2520 * Check that the WinSock was successfully initialized.
2521 *
2522 * Warning:
2523 * This check was useful in times of Windows98 where WinSock may
2524 * not be available. This is not the case any more.
2525 * This function may be removed with TCL 9.0
2526 *
2527 * Results:
2528 * 1 if it is.
2529 *
2530 * Side effects:
2531 * None.
2532 *
2533 *----------------------------------------------------------------------
2534 */
2535
2536 static int
2537 SocketsEnabled(void)
2538 {
2539 int enabled;
2540
2541 Tcl_MutexLock(&socketMutex);
2542 enabled = (initialized == 1);
2543 Tcl_MutexUnlock(&socketMutex);
2544 return enabled;
2545 }
2546
2547
2548 /*
2549 *----------------------------------------------------------------------
2550 *
2551 * SocketExitHandler --
2552 *
2553 * Callback invoked during exit clean up to delete the socket
2554 * communication window.
2555 *
2556 * Results:
2557 * None.
2558 *
2559 * Side effects:
2560 * None.
2561 *
2562 *----------------------------------------------------------------------
2563 */
2564
2565 static void
2566 SocketExitHandler(
2567 void *clientData) /* Not used. */
2568 {
2569 Tcl_MutexLock(&socketMutex);
2570
2571 /*
2572 * Make sure the socket event handling window is cleaned-up for, at
2573 * most, this thread.
2574 */
2575
2576 TclpFinalizeSockets();
2577 UnregisterClassW(className, (HINSTANCE)TclWinGetTclInstance());
2578 initialized = 0;
2579 Tcl_MutexUnlock(&socketMutex);
2580 }
2581
2582 /*
2583 *----------------------------------------------------------------------
2584 *
2585 * SocketSetupProc --
2586 *
2587 * This function is invoked before Tcl_DoOneEvent blocks waiting for an
2588 * event.
2589 *
2590 * Results:
2591 * None.
2592 *
2593 * Side effects:
2594 * Adjusts the block time if needed.
2595 *
2596 *----------------------------------------------------------------------
2597 */
2598
2599 void
2600 SocketSetupProc(
2601 void *data, /* Not used. */
2602 int flags) /* Event flags as passed to Tcl_DoOneEvent. */
2603 {
2604 TcpState *statePtr;
2605 Tcl_Time blockTime = { 0, 0 };
2606 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
2607
2608 if (!GOT_BITS(flags, TCL_FILE_EVENTS)) {
2609 return;
2610 }
2611
2612 /*
2613 * Check to see if there is a ready socket. If so, poll.
2614 */
2615 WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
2616 for (statePtr = tsdPtr->socketList; statePtr != NULL;
2617 statePtr = statePtr->nextPtr) {
2618 if (GOT_BITS(statePtr->readyEvents,
2619 statePtr->watchEvents | FD_CONNECT | FD_ACCEPT)) {
2620 Tcl_SetMaxBlockTime(&blockTime);
2621 break;
2622 }
2623 }
2624 SetEvent(tsdPtr->socketListLock);
2625 }
2626
2627 /*
2628 *----------------------------------------------------------------------
2629 *
2630 * SocketCheckProc --
2631 *
2632 * This function is called by Tcl_DoOneEvent to check the socket event
2633 * source for events.
2634 *
2635 * Results:
2636 * None.
2637 *
2638 * Side effects:
2639 * May queue an event.
2640 *
2641 *----------------------------------------------------------------------
2642 */
2643
2644 static void
2645 SocketCheckProc(
2646 void *data, /* Not used. */
2647 int flags) /* Event flags as passed to Tcl_DoOneEvent. */
2648 {
2649 TcpState *statePtr;
2650 SocketEvent *evPtr;
2651 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
2652
2653 if (!GOT_BITS(flags, TCL_FILE_EVENTS)) {
2654 return;
2655 }
2656
2657 /*
2658 * Queue events for any ready sockets that don't already have events
2659 * queued (caused by persistent states that won't generate WinSock
2660 * events).
2661 */
2662
2663 WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
2664 for (statePtr = tsdPtr->socketList; statePtr != NULL;
2665 statePtr = statePtr->nextPtr) {
2666 if (GOT_BITS(statePtr->readyEvents,
2667 statePtr->watchEvents | FD_CONNECT | FD_ACCEPT)
2668 && !GOT_BITS(statePtr->flags, SOCKET_PENDING)) {
2669 SET_BITS(statePtr->flags, SOCKET_PENDING);
2670 evPtr = (SocketEvent *)ckalloc(sizeof(SocketEvent));
2671 evPtr->header.proc = SocketEventProc;
2672 evPtr->socket = statePtr->sockets->fd;
2673 Tcl_QueueEvent((Tcl_Event *) evPtr, TCL_QUEUE_TAIL);
2674 }
2675 }
2676 SetEvent(tsdPtr->socketListLock);
2677 }
2678
2679 /*
2680 *----------------------------------------------------------------------
2681 *
2682 * SocketEventProc --
2683 *
2684 * This function is called by Tcl_ServiceEvent when a socket event
2685 * reaches the front of the event queue. This function is responsible for
2686 * notifying the generic channel code.
2687 *
2688 * Results:
2689 * Returns 1 if the event was handled, meaning it should be removed from
2690 * the queue. Returns 0 if the event was not handled, meaning it should
2691 * stay on the queue. The only time the event isn't handled is if the
2692 * TCL_FILE_EVENTS flag bit isn't set.
2693 *
2694 * Side effects:
2695 * Whatever the channel callback functions do.
2696 *
2697 *----------------------------------------------------------------------
2698 */
2699
2700 static int
2701 SocketEventProc(
2702 Tcl_Event *evPtr, /* Event to service. */
2703 int flags) /* Flags that indicate what events to handle,
2704 * such as TCL_FILE_EVENTS. */
2705 {
2706 TcpState *statePtr;
2707 SocketEvent *eventPtr = (SocketEvent *) evPtr;
2708 int mask = 0, events;
2709 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
2710 TcpFdList *fds;
2711 SOCKET newSocket;
2712 address addr;
2713 int len;
2714
2715 if (!GOT_BITS(flags, TCL_FILE_EVENTS)) {
2716 return 0;
2717 }
2718
2719 /*
2720 * Find the specified socket on the socket list.
2721 */
2722
2723 WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
2724 for (statePtr = tsdPtr->socketList; statePtr != NULL;
2725 statePtr = statePtr->nextPtr) {
2726 if (statePtr->sockets->fd == eventPtr->socket) {
2727 break;
2728 }
2729 }
2730
2731 /*
2732 * Discard events that have gone stale.
2733 */
2734
2735 if (!statePtr) {
2736 SetEvent(tsdPtr->socketListLock);
2737 return 1;
2738 }
2739
2740 /*
2741 * Clear flag that (this) event is pending
2742 */
2743
2744 CLEAR_BITS(statePtr->flags, SOCKET_PENDING);
2745
2746 /*
2747 * Continue async connect if pending and ready
2748 */
2749
2750 if (GOT_BITS(statePtr->readyEvents, FD_CONNECT)) {
2751 if (GOT_BITS(statePtr->flags, TCP_ASYNC_PENDING)) {
2752 /*
2753 * Do one step and save eventual connect error
2754 */
2755
2756 SetEvent(tsdPtr->socketListLock);
2757 WaitForConnect(statePtr,NULL);
2758 } else {
2759 /*
2760 * No async connect reenter pending. Just clear event.
2761 */
2762
2763 CLEAR_BITS(statePtr->readyEvents, FD_CONNECT);
2764 SetEvent(tsdPtr->socketListLock);
2765 }
2766 return 1;
2767 }
2768
2769 /*
2770 * Handle connection requests directly.
2771 */
2772
2773 if (GOT_BITS(statePtr->readyEvents, FD_ACCEPT)) {
2774 for (fds = statePtr->sockets; fds != NULL; fds = fds->next) {
2775 /*
2776 * Accept the incoming connection request.
2777 */
2778
2779 len = sizeof(address);
2780 newSocket = accept(fds->fd, &(addr.sa), &len);
2781
2782 /*
2783 * On Tcl server sockets with multiple OS fds we loop over the fds
2784 * trying an accept() on each, so we expect INVALID_SOCKET. There
2785 * are also other network stack conditions that can result in
2786 * FD_ACCEPT but a subsequent failure on accept() by the time we
2787 * get around to it.
2788 *
2789 * Access to sockets (acceptEventCount, readyEvents) in socketList
2790 * is still protected by the lock (prevents reintroduction of
2791 * SF Tcl Bug 3056775.
2792 */
2793
2794 if (newSocket == INVALID_SOCKET) {
2795 /* int err = WSAGetLastError(); */
2796 continue;
2797 }
2798
2799 /*
2800 * It is possible that more than one FD_ACCEPT has been sent, so
2801 * an extra count must be kept. Decrement the count, and reset the
2802 * readyEvent bit if the count is no longer > 0.
2803 */
2804
2805 statePtr->acceptEventCount--;
2806
2807 if (statePtr->acceptEventCount <= 0) {
2808 CLEAR_BITS(statePtr->readyEvents, FD_ACCEPT);
2809 }
2810
2811 SetEvent(tsdPtr->socketListLock);
2812
2813 /*
2814 * Caution: TcpAccept() has the side-effect of evaluating the
2815 * server accept script (via AcceptCallbackProc() in tclIOCmd.c),
2816 * which can close the server socket and invalidate statePtr and
2817 * fds. If TcpAccept() accepts a socket we must return immediately
2818 * and let SocketCheckProc queue additional FD_ACCEPT events.
2819 */
2820
2821 TcpAccept(fds, newSocket, addr);
2822 return 1;
2823 }
2824
2825 /*
2826 * Loop terminated with no sockets accepted; clear the ready mask so
2827 * we can detect the next connection request. Note that connection
2828 * requests are level triggered, so if there is a request already
2829 * pending, a new event will be generated.
2830 */
2831
2832 statePtr->acceptEventCount = 0;
2833 CLEAR_BITS(statePtr->readyEvents, FD_ACCEPT);
2834
2835 SetEvent(tsdPtr->socketListLock);
2836 return 1;
2837 }
2838
2839 SetEvent(tsdPtr->socketListLock);
2840
2841 /*
2842 * Mask off unwanted events and compute the read/write mask so we can
2843 * notify the channel.
2844 */
2845
2846 events = statePtr->readyEvents & statePtr->watchEvents;
2847
2848 if (GOT_BITS(events, FD_CLOSE)) {
2849 /*
2850 * If the socket was closed and the channel is still interested in
2851 * read events, then we need to ensure that we keep polling for this
2852 * event until someone does something with the channel. Note that we
2853 * do this before calling Tcl_NotifyChannel so we don't have to watch
2854 * out for the channel being deleted out from under us. This may cause
2855 * a redundant trip through the event loop, but it's simpler than
2856 * trying to do unwind protection.
2857 */
2858
2859 Tcl_Time blockTime = { 0, 0 };
2860
2861 Tcl_SetMaxBlockTime(&blockTime);
2862 SET_BITS(mask, TCL_READABLE | TCL_WRITABLE);
2863 } else if (GOT_BITS(events, FD_READ)) {
2864 /*
2865 * Throw the readable event if an async connect failed.
2866 */
2867
2868 if (GOT_BITS(statePtr->flags, TCP_ASYNC_FAILED)) {
2869 SET_BITS(mask, TCL_READABLE);
2870 } else {
2871 fd_set readFds;
2872 struct timeval timeout;
2873
2874 /*
2875 * We must check to see if data is really available, since someone
2876 * could have consumed the data in the meantime. Turn off async
2877 * notification so select will work correctly. If the socket is
2878 * still readable, notify the channel driver, otherwise reset the
2879 * async select handler and keep waiting.
2880 */
2881
2882 SendSelectMessage(tsdPtr, UNSELECT, statePtr);
2883
2884 FD_ZERO(&readFds);
2885 FD_SET(statePtr->sockets->fd, &readFds);
2886 timeout.tv_usec = 0;
2887 timeout.tv_sec = 0;
2888
2889 if (select(0, &readFds, NULL, NULL, &timeout) != 0) {
2890 SET_BITS(mask, TCL_READABLE);
2891 } else {
2892 CLEAR_BITS(statePtr->readyEvents, FD_READ);
2893 SendSelectMessage(tsdPtr, SELECT, statePtr);
2894 }
2895 }
2896 }
2897
2898 /*
2899 * writable event
2900 */
2901
2902 if (GOT_BITS(events, FD_WRITE)) {
2903 SET_BITS(mask, TCL_WRITABLE);
2904 }
2905
2906 /*
2907 * Call registered event procedures
2908 */
2909
2910 if (mask) {
2911 Tcl_NotifyChannel(statePtr->channel, mask);
2912 }
2913 return 1;
2914 }
2915
2916 /*
2917 *----------------------------------------------------------------------
2918 *
2919 * AddSocketInfoFd --
2920 *
2921 * This function adds a SOCKET file descriptor to the 'sockets' linked
2922 * list of a TcpState structure.
2923 *
2924 * Results:
2925 * None.
2926 *
2927 * Side effects:
2928 * None, except for allocation of memory.
2929 *
2930 *----------------------------------------------------------------------
2931 */
2932
2933 static void
2934 AddSocketInfoFd(
2935 TcpState *statePtr,
2936 SOCKET socket)
2937 {
2938 TcpFdList *fds = statePtr->sockets;
2939
2940 if (fds == NULL) {
2941 /*
2942 * Add the first FD.
2943 */
2944
2945 statePtr->sockets = (TcpFdList *)ckalloc(sizeof(TcpFdList));
2946 fds = statePtr->sockets;
2947 } else {
2948 /*
2949 * Find end of list and append FD.
2950 */
2951
2952 while (fds->next != NULL) {
2953 fds = fds->next;
2954 }
2955
2956 fds->next = (TcpFdList *)ckalloc(sizeof(TcpFdList));
2957 fds = fds->next;
2958 }
2959
2960 /*
2961 * Populate new FD.
2962 */
2963
2964 fds->fd = socket;
2965 fds->statePtr = statePtr;
2966 fds->next = NULL;
2967 }
2968
2969
2970 /*
2971 *----------------------------------------------------------------------
2972 *
2973 * NewSocketInfo --
2974 *
2975 * This function allocates and initializes a new TcpState structure.
2976 *
2977 * Results:
2978 * Returns a newly allocated TcpState.
2979 *
2980 * Side effects:
2981 * None, except for allocation of memory.
2982 *
2983 *----------------------------------------------------------------------
2984 */
2985
2986 static TcpState *
2987 NewSocketInfo(SOCKET socket)
2988 {
2989 TcpState *statePtr = (TcpState *)ckalloc(sizeof(TcpState));
2990
2991 memset(statePtr, 0, sizeof(TcpState));
2992
2993 /*
2994 * TIP #218. Removed the code inserting the new structure into the global
2995 * list. This is now handled in the thread action callbacks, and only
2996 * there.
2997 */
2998
2999 AddSocketInfoFd(statePtr, socket);
3000
3001 return statePtr;
3002 }
3003
3004 /*
3005 *----------------------------------------------------------------------
3006 *
3007 * WaitForSocketEvent --
3008 *
3009 * Waits until one of the specified events occurs on a socket.
3010 * For event FD_CONNECT use WaitForConnect.
3011 *
3012 * Results:
3013 * Returns 1 on success or 0 on failure, with an error code in
3014 * errorCodePtr.
3015 *
3016 * Side effects:
3017 * Processes socket events off the system queue.
3018 *
3019 *----------------------------------------------------------------------
3020 */
3021
3022 static int
3023 WaitForSocketEvent(
3024 TcpState *statePtr, /* Information about this socket. */
3025 int events, /* Events to look for. May be one of
3026 * FD_READ or FD_WRITE.
3027 */
3028 int *errorCodePtr) /* Where to store errors? */
3029 {
3030 int result = 1;
3031 int oldMode;
3032 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
3033
3034 /*
3035 * Be sure to disable event servicing so we are truly modal.
3036 */
3037
3038 oldMode = Tcl_SetServiceMode(TCL_SERVICE_NONE);
3039
3040 /*
3041 * Reset WSAAsyncSelect so we have a fresh set of events pending.
3042 */
3043
3044 SendSelectMessage(tsdPtr, UNSELECT, statePtr);
3045 SendSelectMessage(tsdPtr, SELECT, statePtr);
3046
3047 while (1) {
3048 int event_found;
3049
3050 /*
3051 * Get statePtr lock.
3052 */
3053
3054 WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
3055
3056 /*
3057 * Check if event occurred.
3058 */
3059
3060 event_found = GOT_BITS(statePtr->readyEvents, events);
3061
3062 /*
3063 * Free list lock.
3064 */
3065
3066 SetEvent(tsdPtr->socketListLock);
3067
3068 /*
3069 * Exit loop if event occurred.
3070 */
3071
3072 if (event_found) {
3073 break;
3074 }
3075
3076 /*
3077 * Exit loop if event did not occur but this is a non-blocking channel
3078 */
3079
3080 if (statePtr->flags & TCP_NONBLOCKING) {
3081 *errorCodePtr = EWOULDBLOCK;
3082 result = 0;
3083 break;
3084 }
3085
3086 /*
3087 * Wait until something happens.
3088 */
3089
3090 WaitForSingleObject(tsdPtr->readyEvent, INFINITE);
3091 }
3092
3093 (void) Tcl_SetServiceMode(oldMode);
3094 return result;
3095 }
3096
3097 /*
3098 *----------------------------------------------------------------------
3099 *
3100 * SocketThread --
3101 *
3102 * Helper thread used to manage the socket event handling window.
3103 *
3104 * Results:
3105 * 1 if unable to create socket event window, 0 otherwise.
3106 *
3107 * Side effects:
3108 * None.
3109 *
3110 *----------------------------------------------------------------------
3111 */
3112
3113 static DWORD WINAPI
3114 SocketThread(
3115 LPVOID arg)
3116 {
3117 MSG msg;
3118 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)arg;
3119
3120 /*
3121 * Create a dummy window receiving socket events.
3122 */
3123
3124 tsdPtr->hwnd = CreateWindowW(className, className, WS_TILED, 0, 0, 0, 0,
3125 NULL, NULL, windowClass.hInstance, arg);
3126
3127 /*
3128 * Signalize thread creator that we are done creating the window.
3129 */
3130
3131 SetEvent(tsdPtr->readyEvent);
3132
3133 /*
3134 * If unable to create the window, exit this thread immediately.
3135 */
3136
3137 if (tsdPtr->hwnd == NULL) {
3138 return 1;
3139 }
3140
3141 /*
3142 * Process all messages on the socket window until WM_QUIT. This threads
3143 * exits only when instructed to do so by the call to
3144 * PostMessageW(SOCKET_TERMINATE) in TclpFinalizeSockets().
3145 */
3146
3147 while (GetMessageW(&msg, NULL, 0, 0) > 0) {
3148 DispatchMessageW(&msg);
3149 }
3150
3151 /*
3152 * This releases waiters on thread exit in TclpFinalizeSockets()
3153 */
3154
3155 SetEvent(tsdPtr->readyEvent);
3156
3157 return msg.wParam;
3158 }
3159
3160
3161 /*
3162 *----------------------------------------------------------------------
3163 *
3164 * SocketProc --
3165 *
3166 * This function is called when WSAAsyncSelect has been used to register
3167 * interest in a socket event, and the event has occurred.
3168 *
3169 * Results:
3170 * 0 on success.
3171 *
3172 * Side effects:
3173 * The flags for the given socket are updated to reflect the event that
3174 * occurred.
3175 *
3176 *----------------------------------------------------------------------
3177 */
3178
3179 static LRESULT CALLBACK
3180 SocketProc(
3181 HWND hwnd,
3182 UINT message,
3183 WPARAM wParam,
3184 LPARAM lParam)
3185 {
3186 int event, error;
3187 SOCKET socket;
3188 TcpState *statePtr;
3189 int info_found = 0;
3190 TcpFdList *fds = NULL;
3191 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
3192 #ifdef _WIN64
3193 GetWindowLongPtrW(hwnd, GWLP_USERDATA);
3194 #else
3195 GetWindowLongW(hwnd, GWL_USERDATA);
3196 #endif
3197
3198 switch (message) {
3199 default:
3200 return DefWindowProcW(hwnd, message, wParam, lParam);
3201 break;
3202
3203 case WM_CREATE:
3204 /*
3205 * Store the initial tsdPtr, it's from a different thread, so it's not
3206 * directly accessible, but needed.
3207 */
3208
3209 #ifdef _WIN64
3210 SetWindowLongPtrW(hwnd, GWLP_USERDATA,
3211 (LONG_PTR) ((LPCREATESTRUCT)lParam)->lpCreateParams);
3212 #else
3213 SetWindowLongW(hwnd, GWL_USERDATA,
3214 (LONG) ((LPCREATESTRUCT)lParam)->lpCreateParams);
3215 #endif
3216 break;
3217
3218 case WM_DESTROY:
3219 PostQuitMessage(0);
3220 break;
3221
3222 case SOCKET_MESSAGE:
3223 event = WSAGETSELECTEVENT(lParam);
3224 error = WSAGETSELECTERROR(lParam);
3225 socket = (SOCKET) wParam;
3226
3227 WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
3228
3229 /*
3230 * Find the specified socket on the socket list and update its
3231 * eventState flag.
3232 */
3233
3234 for (statePtr = tsdPtr->socketList; statePtr != NULL;
3235 statePtr = statePtr->nextPtr) {
3236 if (FindFDInList(statePtr, socket)) {
3237 info_found = 1;
3238 break;
3239 }
3240 }
3241
3242 /*
3243 * Check if there is a pending info structure not jet in the list.
3244 */
3245
3246 if (!info_found
3247 && tsdPtr->pendingTcpState != NULL
3248 && FindFDInList(tsdPtr->pendingTcpState, socket)) {
3249 statePtr = tsdPtr->pendingTcpState;
3250 info_found = 1;
3251 }
3252 if (info_found) {
3253 /*
3254 * Update the socket state.
3255 *
3256 * A count of FD_ACCEPTS is stored, so if an FD_CLOSE event
3257 * happens, then clear the FD_ACCEPT count. Otherwise, increment
3258 * the count if the current event is an FD_ACCEPT.
3259 */
3260
3261 if (GOT_BITS(event, FD_CLOSE)) {
3262 statePtr->acceptEventCount = 0;
3263 CLEAR_BITS(statePtr->readyEvents, FD_WRITE | FD_ACCEPT);
3264 } else if (GOT_BITS(event, FD_ACCEPT)) {
3265 statePtr->acceptEventCount++;
3266 }
3267
3268 if (GOT_BITS(event, FD_CONNECT)) {
3269 /*
3270 * Remember any error that occurred so we can report
3271 * connection failures.
3272 */
3273
3274 if (error != ERROR_SUCCESS) {
3275 statePtr->notifierConnectError = error;
3276 }
3277 }
3278
3279 /*
3280 * Inform main thread about signaled events
3281 */
3282
3283 SET_BITS(statePtr->readyEvents, event);
3284
3285 /*
3286 * Wake up the Main Thread.
3287 */
3288
3289 SetEvent(tsdPtr->readyEvent);
3290 Tcl_ThreadAlert(tsdPtr->threadId);
3291 }
3292 SetEvent(tsdPtr->socketListLock);
3293 break;
3294
3295 case SOCKET_SELECT:
3296 statePtr = (TcpState *) lParam;
3297 for (fds = statePtr->sockets; fds != NULL; fds = fds->next) {
3298 if (wParam == SELECT) {
3299 WSAAsyncSelect(fds->fd, hwnd,
3300 SOCKET_MESSAGE, statePtr->selectEvents);
3301 } else {
3302 /*
3303 * Clear the selection mask
3304 */
3305
3306 WSAAsyncSelect(fds->fd, hwnd, 0, 0);
3307 }
3308 }
3309 break;
3310
3311 case SOCKET_TERMINATE:
3312 DestroyWindow(hwnd);
3313 break;
3314 }
3315
3316 return 0;
3317 }
3318
3319 /*
3320 *----------------------------------------------------------------------
3321 *
3322 * FindFDInList --
3323 *
3324 * Return true, if the given file descriptor is contained in the
3325 * file descriptor list.
3326 *
3327 * Results:
3328 * true if found.
3329 *
3330 * Side effects:
3331 *
3332 *----------------------------------------------------------------------
3333 */
3334
3335 static int
3336 FindFDInList(
3337 TcpState *statePtr,
3338 SOCKET socket)
3339 {
3340 TcpFdList *fds;
3341 for (fds = statePtr->sockets; fds != NULL; fds = fds->next) {
3342 if (fds->fd == socket) {
3343 return 1;
3344 }
3345 }
3346 return 0;
3347 }
3348
3349 /*
3350 *----------------------------------------------------------------------
3351 *
3352 * TclWinGetSockOpt, et al. --
3353 *
3354 * Those functions are historically exported by the stubs table and
3355 * just use the original system calls now.
3356 *
3357 * Warning:
3358 * Those functions are depreciated and will be removed with TCL 9.0.
3359 *
3360 * Results:
3361 * As defined for each function.
3362 *
3363 * Side effects:
3364 * As defined for each function.
3365 *
3366 *----------------------------------------------------------------------
3367 */
3368
3369 #undef TclWinGetSockOpt
3370 int
3371 TclWinGetSockOpt(
3372 SOCKET s,
3373 int level,
3374 int optname,
3375 char *optval,
3376 int *optlen)
3377 {
3378
3379 return getsockopt(s, level, optname, optval, optlen);
3380 }
3381 #undef TclWinSetSockOpt
3382 int
3383 TclWinSetSockOpt(
3384 SOCKET s,
3385 int level,
3386 int optname,
3387 const char *optval,
3388 int optlen)
3389 {
3390 return setsockopt(s, level, optname, optval, optlen);
3391 }
3392
3393 #undef TclpInetNtoa
3394 char *
3395 TclpInetNtoa(
3396 struct in_addr addr)
3397 {
3398 return inet_ntoa(addr);
3399 }
3400 #undef TclWinGetServByName
3401 struct servent *
3402 TclWinGetServByName(
3403 const char *name,
3404 const char *proto)
3405 {
3406 return getservbyname(name, proto);
3407 }
3408
3409 /*
3410 *----------------------------------------------------------------------
3411 *
3412 * TcpThreadActionProc --
3413 *
3414 * Insert or remove any thread local refs to this channel.
3415 *
3416 * Results:
3417 * None.
3418 *
3419 * Side effects:
3420 * Changes thread local list of valid channels.
3421 *
3422 *----------------------------------------------------------------------
3423 */
3424
3425 static void
3426 TcpThreadActionProc(
3427 void *instanceData,
3428 int action)
3429 {
3430 ThreadSpecificData *tsdPtr;
3431 TcpState *statePtr = (TcpState *)instanceData;
3432 int notifyCmd;
3433
3434 if (action == TCL_CHANNEL_THREAD_INSERT) {
3435 /*
3436 * Ensure that socket subsystem is initialized in this thread, or else
3437 * sockets will not work.
3438 */
3439
3440 Tcl_MutexLock(&socketMutex);
3441 InitSockets();
3442 Tcl_MutexUnlock(&socketMutex);
3443
3444 tsdPtr = TCL_TSD_INIT(&dataKey);
3445
3446 WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
3447 statePtr->nextPtr = tsdPtr->socketList;
3448 tsdPtr->socketList = statePtr;
3449
3450 if (statePtr == tsdPtr->pendingTcpState) {
3451 tsdPtr->pendingTcpState = NULL;
3452 }
3453
3454 SetEvent(tsdPtr->socketListLock);
3455
3456 notifyCmd = SELECT;
3457 } else {
3458 TcpState **nextPtrPtr;
3459 int removed = 0;
3460
3461 tsdPtr = TCL_TSD_INIT(&dataKey);
3462
3463 /*
3464 * TIP #218, Bugfix: All access to socketList has to be protected by
3465 * the lock.
3466 */
3467
3468 WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
3469 for (nextPtrPtr = &(tsdPtr->socketList); (*nextPtrPtr) != NULL;
3470 nextPtrPtr = &((*nextPtrPtr)->nextPtr)) {
3471 if ((*nextPtrPtr) == statePtr) {
3472 (*nextPtrPtr) = statePtr->nextPtr;
3473 removed = 1;
3474 break;
3475 }
3476 }
3477 SetEvent(tsdPtr->socketListLock);
3478
3479 /*
3480 * This could happen if the channel was created in one thread and then
3481 * moved to another without updating the thread local data in each
3482 * thread.
3483 */
3484
3485 if (!removed) {
3486 Tcl_Panic("file info ptr not on thread channel list");
3487 }
3488
3489 notifyCmd = UNSELECT;
3490 }
3491
3492 /*
3493 * Ensure that, or stop, notifications for the socket occur in this
3494 * thread.
3495 */
3496
3497 SendSelectMessage(tsdPtr, notifyCmd, statePtr);
3498 }
3499
3500 /*
3501 * Local Variables:
3502 * mode: c
3503 * c-basic-offset: 4
3504 * fill-column: 78
3505 * tab-width: 8
3506 * indent-tabs-mode: nil
3507 * End:
3508 */