diff options
Diffstat (limited to 'win/tclWinSock.c')
| -rw-r--r-- | win/tclWinSock.c | 1912 |
1 files changed, 983 insertions, 929 deletions
diff --git a/win/tclWinSock.c b/win/tclWinSock.c index 10c24bd..3990111 100644 --- a/win/tclWinSock.c +++ b/win/tclWinSock.c @@ -8,11 +8,56 @@ * See the file "license.terms" for information on usage and redistribution of * this file, and for a DISCLAIMER OF ALL WARRANTIES. * - * RCS: @(#) $Id: tclWinSock.c,v 1.48 2005/07/24 22:56:50 dkf Exp $ + * ----------------------------------------------------------------------- + * + * General information on how this module works. + * + * - Each Tcl-thread with its sockets maintains an internal window to receive + * socket messages from the OS. + * + * - To ensure that message reception is always running this window is + * actually owned and handled by an internal thread. This we call the + * co-thread of Tcl's thread. + * + * - The whole structure is set up by InitSockets() which is called for each + * Tcl thread. The implementation of the co-thread is in SocketThread(), + * and the messages are handled by SocketProc(). The connection between + * both is not directly visible, it is done through a Win32 window class. + * This class is initialized by InitSockets() as well, and used in the + * creation of the message receiver windows. + * + * - An important thing to note is that *both* thread and co-thread have + * access to the list of sockets maintained in the private TSD data of the + * thread. The co-thread was given access to it upon creation through the + * new thread's client-data. + * + * Because of this dual access the TSD data contains an OS mutex, the + * "socketListLock", to mediate exclusion between thread and co-thread. + * + * The co-thread's access is all in SocketProc(). The thread's access is + * through SocketEventProc() (1) and the functions called by it. + * + * (Ad 1) This is the handler function for all queued socket events, which + * all the OS messages are translated to through the EventSource (2) + * driven by the OS messages. + * + * (Ad 2) The main functions for this are SocketSetupProc() and + * SocketCheckProc(). */ #include "tclWinInt.h" +#ifdef _MSC_VER +# pragma comment (lib, "ws2_32") +#endif + +/* + * Support for control over sockets' KEEPALIVE and NODELAY behavior is + * currently disabled. + */ + +#undef TCL_FEATURE_KEEPALIVE_NAGLE + /* * Make sure to remove the redirection defines set in tclWinPort.h that is in * use in other sections of the core, except for us. @@ -20,139 +65,69 @@ #undef getservbyname #undef getsockopt -#undef ntohs #undef setsockopt /* * The following variable is used to tell whether this module has been - * initialized. + * initialized. If 1, initialization of sockets was successful, if -1 then + * socket initialization failed (WSAStartup failed). */ static int initialized = 0; +static const TCHAR classname[] = TEXT("TclSocket"); TCL_DECLARE_MUTEX(socketMutex) /* * The following variable holds the network name of this host. */ -static TclInitProcessGlobalValueProc InitializeHostName; -static ProcessGlobalValue hostName = - {0, 0, NULL, NULL, InitializeHostName, NULL, NULL}; +static TclInitProcessGlobalValueProc InitializeHostName; +static ProcessGlobalValue hostName = { + 0, 0, NULL, NULL, InitializeHostName, NULL, NULL +}; /* - * Mingw, Cygwin and OpenWatcom may not have LPFN_* typedefs. + * The following defines declare the messages used on socket windows. */ -#ifdef HAVE_NO_LPFN_DECLS - typedef SOCKET (PASCAL FAR *LPFN_ACCEPT)(SOCKET s, - struct sockaddr FAR * addr, int FAR * addrlen); - typedef int (PASCAL FAR *LPFN_BIND)(SOCKET s, - const struct sockaddr FAR *addr, int namelen); - typedef int (PASCAL FAR *LPFN_CLOSESOCKET)(SOCKET s); - typedef int (PASCAL FAR *LPFN_CONNECT)(SOCKET s, - const struct sockaddr FAR *name, int namelen); - typedef struct hostent FAR * (PASCAL FAR *LPFN_GETHOSTBYADDR) - (const char FAR *addr, int addrlen, int addrtype); - typedef struct hostent FAR * (PASCAL FAR *LPFN_GETHOSTBYNAME) - (const char FAR * name); - typedef int (PASCAL FAR *LPFN_GETHOSTNAME)(char FAR * name, - int namelen); - typedef int (PASCAL FAR *LPFN_GETPEERNAME)(SOCKET sock, - struct sockaddr FAR *name, int FAR *namelen); - typedef struct servent FAR * (PASCAL FAR *LPFN_GETSERVBYNAME) - (const char FAR * name, const char FAR * proto); - typedef int (PASCAL FAR *LPFN_GETSOCKNAME)(SOCKET sock, - struct sockaddr FAR *name, int FAR *namelen); - typedef int (PASCAL FAR *LPFN_GETSOCKOPT)(SOCKET s, int level, - int optname, char FAR * optval, int FAR *optlen); - typedef u_short (PASCAL FAR *LPFN_HTONS)(u_short hostshort); - typedef unsigned long (PASCAL FAR *LPFN_INET_ADDR) - (const char FAR * cp); - typedef char FAR * (PASCAL FAR *LPFN_INET_NTOA) - (struct in_addr in); - typedef int (PASCAL FAR *LPFN_IOCTLSOCKET)(SOCKET s, - long cmd, u_long FAR *argp); - typedef int (PASCAL FAR *LPFN_LISTEN)(SOCKET s, int backlog); - typedef u_short (PASCAL FAR *LPFN_NTOHS)(u_short netshort); - typedef int (PASCAL FAR *LPFN_RECV)(SOCKET s, char FAR * buf, - int len, int flags); - typedef int (PASCAL FAR *LPFN_SELECT)(int nfds, - fd_set FAR * readfds, fd_set FAR * writefds, - fd_set FAR * exceptfds, - const struct timeval FAR * timeout); - typedef int (PASCAL FAR *LPFN_SEND)(SOCKET s, - const char FAR * buf, int len, int flags); - typedef int (PASCAL FAR *LPFN_SETSOCKOPT)(SOCKET s, - int level, int optname, const char FAR * optval, - int optlen); - typedef SOCKET (PASCAL FAR *LPFN_SOCKET)(int af, - int type, int protocol); - typedef int (PASCAL FAR *LPFN_WSAASYNCSELECT)(SOCKET s, - HWND hWnd, u_int wMsg, long lEvent); - typedef int (PASCAL FAR *LPFN_WSACLEANUP)(void); - typedef int (PASCAL FAR *LPFN_WSAGETLASTERROR)(void); - typedef int (PASCAL FAR *LPFN_WSASTARTUP)(WORD wVersionRequired, - LPWSADATA lpWSAData); -#endif - +#define SOCKET_MESSAGE WM_USER+1 +#define SOCKET_SELECT WM_USER+2 +#define SOCKET_TERMINATE WM_USER+3 +#define SELECT TRUE +#define UNSELECT FALSE /* - * The following structure contains pointers to all of the WinSock API entry - * points used by Tcl. It is initialized by InitSockets. Since we dynamically - * load the Winsock DLL on demand, we must use this function table to refer to - * functions in the winsock API. + * This is needed to comply with the strict aliasing rules of GCC, but it also + * simplifies casting between the different sockaddr types. */ -static struct { - HMODULE hModule; /* Handle to WinSock library. */ - - /* Winsock 1.1 functions */ - LPFN_ACCEPT accept; - LPFN_BIND bind; - LPFN_CLOSESOCKET closesocket; - LPFN_CONNECT connect; - LPFN_GETHOSTBYADDR gethostbyaddr; - LPFN_GETHOSTBYNAME gethostbyname; - LPFN_GETHOSTNAME gethostname; - LPFN_GETPEERNAME getpeername; - LPFN_GETSERVBYNAME getservbyname; - LPFN_GETSOCKNAME getsockname; - LPFN_GETSOCKOPT getsockopt; - LPFN_HTONS htons; - LPFN_INET_ADDR inet_addr; - LPFN_INET_NTOA inet_ntoa; - LPFN_IOCTLSOCKET ioctlsocket; - LPFN_LISTEN listen; - LPFN_NTOHS ntohs; - LPFN_RECV recv; - LPFN_SELECT select; - LPFN_SEND send; - LPFN_SETSOCKOPT setsockopt; - LPFN_SOCKET socket; - LPFN_WSAASYNCSELECT WSAAsyncSelect; - LPFN_WSACLEANUP WSACleanup; - LPFN_WSAGETLASTERROR WSAGetLastError; - LPFN_WSASTARTUP WSAStartup; -} winSock; +typedef union { + struct sockaddr sa; + struct sockaddr_in sa4; + struct sockaddr_in6 sa6; + struct sockaddr_storage sas; +} address; -/* - * The following defines declare the messages used on socket windows. - */ +#ifndef IN6_ARE_ADDR_EQUAL +#define IN6_ARE_ADDR_EQUAL IN6_ADDR_EQUAL +#endif -#define SOCKET_MESSAGE WM_USER+1 -#define SOCKET_SELECT WM_USER+2 -#define SOCKET_TERMINATE WM_USER+3 -#define SELECT TRUE -#define UNSELECT FALSE +typedef struct SocketInfo SocketInfo; + +typedef struct TcpFdList { + SocketInfo *infoPtr; + SOCKET fd; + struct TcpFdList *next; +} TcpFdList; /* * The following structure is used to store the data associated with each * socket. */ -typedef struct SocketInfo { +struct SocketInfo { Tcl_Channel channel; /* Channel associated with this socket. */ - SOCKET socket; /* Windows SOCKET handle. */ + struct TcpFdList *sockets; /* Windows SOCKET handle. */ int flags; /* Bit field comprised of the flags described * below. */ int watchEvents; /* OR'ed combination of FD_READ, FD_WRITE, @@ -173,14 +148,14 @@ typedef struct SocketInfo { int lastError; /* Error code from last message. */ struct SocketInfo *nextPtr; /* The next socket on the per-thread socket * list. */ -} SocketInfo; +}; /* * The following structure is what is added to the Tcl event queue when a * socket event occurs. */ -typedef struct SocketEvent { +typedef struct { Tcl_Event header; /* Information that is standard for all * events. */ SOCKET socket; /* Socket descriptor that is ready. Used to @@ -208,7 +183,7 @@ typedef struct SocketEvent { #define SOCKET_PENDING (1<<3) /* A message has been sent for this * socket */ -typedef struct ThreadSpecificData { +typedef struct { HWND hwnd; /* Handle to window for socket messages. */ HANDLE socketThread; /* Thread handling the window */ Tcl_ThreadId threadId; /* Parent thread. */ @@ -229,17 +204,15 @@ static WNDCLASS windowClass; */ static SocketInfo * CreateSocket(Tcl_Interp *interp, int port, - CONST char *host, int server, CONST char *myaddr, + const char *host, int server, const char *myaddr, int myport, int async); -static int CreateSocketAddress(LPSOCKADDR_IN sockaddrPtr, - CONST char *host, int port); static void InitSockets(void); static SocketInfo * NewSocketInfo(SOCKET socket); static void SocketExitHandler(ClientData clientData); static LRESULT CALLBACK SocketProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); static int SocketsEnabled(void); -static void TcpAccept(SocketInfo *infoPtr); +static void TcpAccept(TcpFdList *fds, SOCKET newSocket, address addr); static int WaitForSocketEvent(SocketInfo *infoPtr, int events, int *errorCodePtr); static DWORD WINAPI SocketThread(LPVOID arg); @@ -249,9 +222,9 @@ static void TcpThreadActionProc(ClientData instanceData, static Tcl_EventCheckProc SocketCheckProc; static Tcl_EventProc SocketEventProc; static Tcl_EventSetupProc SocketSetupProc; -static Tcl_ExitProc SocketThreadExitHandler; static Tcl_DriverBlockModeProc TcpBlockProc; static Tcl_DriverCloseProc TcpCloseProc; +static Tcl_DriverClose2Proc TcpClose2Proc; static Tcl_DriverSetOptionProc TcpSetOptionProc; static Tcl_DriverGetOptionProc TcpGetOptionProc; static Tcl_DriverInputProc TcpInputProc; @@ -264,9 +237,9 @@ static Tcl_DriverGetHandleProc TcpGetHandleProc; * based IO. */ -static Tcl_ChannelType tcpChannelType = { +static const Tcl_ChannelType tcpChannelType = { "tcp", /* Type name. */ - TCL_CHANNEL_VERSION_4, /* v4 channel */ + TCL_CHANNEL_VERSION_5, /* v5 channel */ TcpCloseProc, /* Close proc. */ TcpInputProc, /* Input proc. */ TcpOutputProc, /* Output proc. */ @@ -275,145 +248,44 @@ static Tcl_ChannelType tcpChannelType = { TcpGetOptionProc, /* Get option proc. */ TcpWatchProc, /* Set up notifier to watch this channel. */ TcpGetHandleProc, /* Get an OS handle from channel. */ - NULL, /* close2proc. */ + TcpClose2Proc, /* Close2proc. */ TcpBlockProc, /* Set socket into (non-)blocking mode. */ NULL, /* flush proc. */ NULL, /* handler proc. */ NULL, /* wide seek proc */ TcpThreadActionProc, /* thread action proc */ + NULL /* truncate */ }; - /* *---------------------------------------------------------------------- * * InitSockets -- * - * Initialize the socket module. Attempts to load the wsock32.dll library - * and set up the winSock function table. If successful, registers the - * event window for the socket notifier code. + * Initialize the socket module. If winsock startup is successful, + * registers the event window for the socket notifier code. * - * Assumes Mutex is held. + * Assumes socketMutex is held. * * Results: * None. * * Side effects: - * Dynamically loads wsock32.dll, and registers a new window class and - * creates a window for use in asynchronous socket notification. + * Initializes winsock, registers a new window class and creates a + * window for use in asynchronous socket notification. * *---------------------------------------------------------------------- */ static void -InitSockets() +InitSockets(void) { DWORD id; - WSADATA wsaData; - DWORD err; - ThreadSpecificData *tsdPtr = (ThreadSpecificData *) - TclThreadDataKeyGet(&dataKey); + ThreadSpecificData *tsdPtr = TclThreadDataKeyGet(&dataKey); if (!initialized) { initialized = 1; - Tcl_CreateExitHandler(SocketExitHandler, (ClientData) NULL); - - winSock.hModule = LoadLibraryA("wsock32.dll"); - - if (winSock.hModule == NULL) { - return; - } - - /* - * Initialize the function table. - */ - - winSock.accept = (LPFN_ACCEPT) - GetProcAddress(winSock.hModule, "accept"); - winSock.bind = (LPFN_BIND) - GetProcAddress(winSock.hModule, "bind"); - winSock.closesocket = (LPFN_CLOSESOCKET) - GetProcAddress(winSock.hModule, "closesocket"); - winSock.connect = (LPFN_CONNECT) - GetProcAddress(winSock.hModule, "connect"); - winSock.gethostbyaddr = (LPFN_GETHOSTBYADDR) - GetProcAddress(winSock.hModule, "gethostbyaddr"); - winSock.gethostbyname = (LPFN_GETHOSTBYNAME) - GetProcAddress(winSock.hModule, "gethostbyname"); - winSock.gethostname = (LPFN_GETHOSTNAME) - GetProcAddress(winSock.hModule, "gethostname"); - winSock.getpeername = (LPFN_GETPEERNAME) - GetProcAddress(winSock.hModule, "getpeername"); - winSock.getservbyname = (LPFN_GETSERVBYNAME) - GetProcAddress(winSock.hModule, "getservbyname"); - winSock.getsockname = (LPFN_GETSOCKNAME) - GetProcAddress(winSock.hModule, "getsockname"); - winSock.getsockopt = (LPFN_GETSOCKOPT) - GetProcAddress(winSock.hModule, "getsockopt"); - winSock.htons = (LPFN_HTONS) - GetProcAddress(winSock.hModule, "htons"); - winSock.inet_addr = (LPFN_INET_ADDR) - GetProcAddress(winSock.hModule, "inet_addr"); - winSock.inet_ntoa = (LPFN_INET_NTOA) - GetProcAddress(winSock.hModule, "inet_ntoa"); - winSock.ioctlsocket = (LPFN_IOCTLSOCKET) - GetProcAddress(winSock.hModule, "ioctlsocket"); - winSock.listen = (LPFN_LISTEN) - GetProcAddress(winSock.hModule, "listen"); - winSock.ntohs = (LPFN_NTOHS) - GetProcAddress(winSock.hModule, "ntohs"); - winSock.recv = (LPFN_RECV) - GetProcAddress(winSock.hModule, "recv"); - winSock.select = (LPFN_SELECT) - GetProcAddress(winSock.hModule, "select"); - winSock.send = (LPFN_SEND) - GetProcAddress(winSock.hModule, "send"); - winSock.setsockopt = (LPFN_SETSOCKOPT) - GetProcAddress(winSock.hModule, "setsockopt"); - winSock.socket = (LPFN_SOCKET) - GetProcAddress(winSock.hModule, "socket"); - winSock.WSAAsyncSelect = (LPFN_WSAASYNCSELECT) - GetProcAddress(winSock.hModule, "WSAAsyncSelect"); - winSock.WSACleanup = (LPFN_WSACLEANUP) - GetProcAddress(winSock.hModule, "WSACleanup"); - winSock.WSAGetLastError = (LPFN_WSAGETLASTERROR) - GetProcAddress(winSock.hModule, "WSAGetLastError"); - winSock.WSAStartup = (LPFN_WSASTARTUP) - GetProcAddress(winSock.hModule, "WSAStartup"); - - /* - * Now check that all fields are properly initialized. If not, return - * zero to indicate that we failed to initialize properly. - */ - - if ((winSock.accept == NULL) || - (winSock.bind == NULL) || - (winSock.closesocket == NULL) || - (winSock.connect == NULL) || - (winSock.gethostbyname == NULL) || - (winSock.gethostbyaddr == NULL) || - (winSock.gethostname == NULL) || - (winSock.getpeername == NULL) || - (winSock.getservbyname == NULL) || - (winSock.getsockname == NULL) || - (winSock.getsockopt == NULL) || - (winSock.htons == NULL) || - (winSock.inet_addr == NULL) || - (winSock.inet_ntoa == NULL) || - (winSock.ioctlsocket == NULL) || - (winSock.listen == NULL) || - (winSock.ntohs == NULL) || - (winSock.recv == NULL) || - (winSock.select == NULL) || - (winSock.send == NULL) || - (winSock.setsockopt == NULL) || - (winSock.socket == NULL) || - (winSock.WSAAsyncSelect == NULL) || - (winSock.WSACleanup == NULL) || - (winSock.WSAGetLastError == NULL) || - (winSock.WSAStartup == NULL)) { - goto unloadLibrary; - } + TclCreateLateExitHandler(SocketExitHandler, NULL); /* * Create the async notification window with a new class. We must @@ -428,95 +300,68 @@ InitSockets() windowClass.hInstance = TclWinGetTclInstance(); windowClass.hbrBackground = NULL; windowClass.lpszMenuName = NULL; - windowClass.lpszClassName = "TclSocket"; + windowClass.lpszClassName = classname; windowClass.lpfnWndProc = SocketProc; windowClass.hIcon = NULL; windowClass.hCursor = NULL; - if (!RegisterClassA(&windowClass)) { + if (!RegisterClass(&windowClass)) { TclWinConvertError(GetLastError()); - goto unloadLibrary; - } - - /* - * Initialize the winsock library and check the interface version - * actually loaded. We only ask for the 1.1 interface and do require - * that it not be less than 1.1. - */ - -#define WSA_VERSION_MAJOR 1 -#define WSA_VERSION_MINOR 1 -#define WSA_VERSION_REQD MAKEWORD(WSA_VERSION_MAJOR, WSA_VERSION_MINOR) - - if ((err = winSock.WSAStartup(WSA_VERSION_REQD, &wsaData)) != 0) { - TclWinConvertWSAError(err); - goto unloadLibrary; + goto initFailure; } - - /* - * Note the byte positions are swapped for the comparison, so that - * 0x0002 (2.0, MAKEWORD(2,0)) doesn't look less than 0x0101 (1.1). - * We want the comparison to be 0x0200 < 0x0101. - */ - - if (MAKEWORD(HIBYTE(wsaData.wVersion), LOBYTE(wsaData.wVersion)) - < MAKEWORD(WSA_VERSION_MINOR, WSA_VERSION_MAJOR)) { - TclWinConvertWSAError(WSAVERNOTSUPPORTED); - winSock.WSACleanup(); - goto unloadLibrary; - } - -#undef WSA_VERSION_REQD -#undef WSA_VERSION_MAJOR -#undef WSA_VERSION_MINOR } /* * Check for per-thread initialization. */ - if (tsdPtr == NULL) { - tsdPtr = TCL_TSD_INIT(&dataKey); - tsdPtr->socketList = NULL; - tsdPtr->hwnd = NULL; - - tsdPtr->threadId = Tcl_GetCurrentThread(); - - tsdPtr->readyEvent = CreateEvent(NULL, FALSE, FALSE, NULL); - tsdPtr->socketListLock = CreateEvent(NULL, FALSE, TRUE, NULL); - tsdPtr->socketThread = CreateThread(NULL, 256, SocketThread, - tsdPtr, 0, &id); - SetThreadPriority(tsdPtr->socketThread, THREAD_PRIORITY_HIGHEST); + if (tsdPtr != NULL) { + return; + } - if (tsdPtr->socketThread == NULL) { - goto unloadLibrary; - } + /* + * OK, this thread has never done anything with sockets before. Construct + * a worker thread to handle asynchronous events related to sockets + * assigned to _this_ thread. + */ + tsdPtr = TCL_TSD_INIT(&dataKey); + tsdPtr->socketList = NULL; + tsdPtr->hwnd = NULL; + tsdPtr->threadId = Tcl_GetCurrentThread(); + tsdPtr->readyEvent = CreateEvent(NULL, FALSE, FALSE, NULL); + if (tsdPtr->readyEvent == NULL) { + goto initFailure; + } + tsdPtr->socketListLock = CreateEvent(NULL, FALSE, TRUE, NULL); + if (tsdPtr->socketListLock == NULL) { + goto initFailure; + } + tsdPtr->socketThread = CreateThread(NULL, 256, SocketThread, tsdPtr, 0, + &id); + if (tsdPtr->socketThread == NULL) { + goto initFailure; + } - /* - * Wait for the thread to signal that the window has been created and - * is ready to go. Timeout after twenty seconds. - */ + SetThreadPriority(tsdPtr->socketThread, THREAD_PRIORITY_HIGHEST); - if (WaitForSingleObject(tsdPtr->readyEvent, 20000) == WAIT_TIMEOUT) { - goto unloadLibrary; - } + /* + * Wait for the thread to signal when the window has been created and if + * it is ready to go. + */ - if (tsdPtr->hwnd == NULL) { - goto unloadLibrary; - } + WaitForSingleObject(tsdPtr->readyEvent, INFINITE); - Tcl_CreateEventSource(SocketSetupProc, SocketCheckProc, NULL); - Tcl_CreateThreadExitHandler(SocketThreadExitHandler, NULL); + if (tsdPtr->hwnd == NULL) { + goto initFailure; /* Trouble creating the window. */ } + + Tcl_CreateEventSource(SocketSetupProc, SocketCheckProc, NULL); return; - unloadLibrary: - if (tsdPtr != NULL && tsdPtr->hwnd != NULL) { - SocketThreadExitHandler(0); - } - FreeLibrary(winSock.hModule); - winSock.hModule = NULL; + initFailure: + TclpFinalizeSockets(); + initialized = -1; return; } @@ -525,7 +370,7 @@ InitSockets() * * SocketsEnabled -- * - * Check that the WinSock DLL is loaded and ready. + * Check that the WinSock was successfully initialized. * * Results: * 1 if it is. @@ -538,11 +383,12 @@ InitSockets() /* ARGSUSED */ static int -SocketsEnabled() +SocketsEnabled(void) { int enabled; + Tcl_MutexLock(&socketMutex); - enabled = (winSock.hModule != NULL); + enabled = (initialized == 1); Tcl_MutexUnlock(&socketMutex); return enabled; } @@ -567,22 +413,18 @@ SocketsEnabled() /* ARGSUSED */ static void -SocketExitHandler(clientData) - ClientData clientData; /* Not used. */ +SocketExitHandler( + ClientData clientData) /* Not used. */ { Tcl_MutexLock(&socketMutex); - if (winSock.hModule) { - /* - * Make sure the socket event handling window is cleaned-up for, at - * most, this thread. - */ - SocketThreadExitHandler(clientData); - UnregisterClass("TclSocket", TclWinGetTclInstance()); - winSock.WSACleanup(); - FreeLibrary(winSock.hModule); - winSock.hModule = NULL; - } + /* + * Make sure the socket event handling window is cleaned-up for, at + * most, this thread. + */ + + TclpFinalizeSockets(); + UnregisterClass(classname, TclWinGetTclInstance()); initialized = 0; Tcl_MutexUnlock(&socketMutex); } @@ -590,52 +432,59 @@ SocketExitHandler(clientData) /* *---------------------------------------------------------------------- * - * SocketThreadExitHandler -- + * TclpFinalizeSockets -- * - * Callback invoked during thread clean up to delete the socket event - * source. + * This function is called from Tcl_FinalizeThread to finalize the + * platform specific socket subsystem. Also, it may be called from within + * this module to cleanup the state if unable to initialize the sockets + * subsystem. * * Results: * None. * * Side effects: - * Delete the event source. + * Deletes the event source and destroys the socket thread. * *---------------------------------------------------------------------- */ - /* ARGSUSED */ -static void -SocketThreadExitHandler(clientData) - ClientData clientData; /* Not used. */ +void +TclpFinalizeSockets(void) { - ThreadSpecificData *tsdPtr = - (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey); + ThreadSpecificData *tsdPtr = TclThreadDataKeyGet(&dataKey); - if (tsdPtr != NULL && tsdPtr->socketThread != NULL) { - DWORD exitCode; + /* + * Careful! This is a finalizer! + */ - GetExitCodeThread(tsdPtr->socketThread, &exitCode); - if (exitCode == STILL_ACTIVE) { + if (tsdPtr == NULL) { + return; + } + + if (tsdPtr->socketThread != NULL) { + if (tsdPtr->hwnd != NULL) { PostMessage(tsdPtr->hwnd, SOCKET_TERMINATE, 0, 0); /* - * Wait for the thread to close. This ensures that we are - * completely cleaned up before we leave this function. If - * Tcl_Finalize was called from DllMain, the thread is in a paused - * state so we need to timeout and continue. + * Wait for the thread to exit. This ensures that we are + * completely cleaned up before we leave this function. */ - WaitForSingleObject(tsdPtr->socketThread, 100); + WaitForSingleObject(tsdPtr->readyEvent, INFINITE); + tsdPtr->hwnd = NULL; } CloseHandle(tsdPtr->socketThread); tsdPtr->socketThread = NULL; + } + if (tsdPtr->readyEvent != NULL) { CloseHandle(tsdPtr->readyEvent); + tsdPtr->readyEvent = NULL; + } + if (tsdPtr->socketListLock != NULL) { CloseHandle(tsdPtr->socketListLock); - - Tcl_DeleteThreadExitHandler(SocketThreadExitHandler, NULL); - Tcl_DeleteEventSource(SocketSetupProc, SocketCheckProc, NULL); + tsdPtr->socketListLock = NULL; } + Tcl_DeleteEventSource(SocketSetupProc, SocketCheckProc, NULL); } /* @@ -660,8 +509,10 @@ SocketThreadExitHandler(clientData) */ int -TclpHasSockets(interp) - Tcl_Interp *interp; +TclpHasSockets( + Tcl_Interp *interp) /* Where to write an error message if sockets + * are not present, or NULL if no such message + * is to be written. */ { Tcl_MutexLock(&socketMutex); InitSockets(); @@ -671,8 +522,8 @@ TclpHasSockets(interp) return TCL_OK; } if (interp != NULL) { - Tcl_AppendResult(interp, "sockets are not available on this system", - NULL); + Tcl_SetObjResult(interp, Tcl_NewStringObj( + "sockets are not available on this system", -1)); } return TCL_ERROR; } @@ -695,9 +546,9 @@ TclpHasSockets(interp) */ void -SocketSetupProc(data, flags) - ClientData data; /* Not used. */ - int flags; /* Event flags as passed to Tcl_DoOneEvent. */ +SocketSetupProc( + ClientData data, /* Not used. */ + int flags) /* Event flags as passed to Tcl_DoOneEvent. */ { SocketInfo *infoPtr; Tcl_Time blockTime = { 0, 0 }; @@ -740,9 +591,9 @@ SocketSetupProc(data, flags) */ static void -SocketCheckProc(data, flags) - ClientData data; /* Not used. */ - int flags; /* Event flags as passed to Tcl_DoOneEvent. */ +SocketCheckProc( + ClientData data, /* Not used. */ + int flags) /* Event flags as passed to Tcl_DoOneEvent. */ { SocketInfo *infoPtr; SocketEvent *evPtr; @@ -764,9 +615,9 @@ SocketCheckProc(data, flags) if ((infoPtr->readyEvents & infoPtr->watchEvents) && !(infoPtr->flags & SOCKET_PENDING)) { infoPtr->flags |= SOCKET_PENDING; - evPtr = (SocketEvent *) ckalloc(sizeof(SocketEvent)); + evPtr = ckalloc(sizeof(SocketEvent)); evPtr->header.proc = SocketEventProc; - evPtr->socket = infoPtr->socket; + evPtr->socket = infoPtr->sockets->fd; Tcl_QueueEvent((Tcl_Event *) evPtr, TCL_QUEUE_TAIL); } } @@ -795,16 +646,19 @@ SocketCheckProc(data, flags) */ static int -SocketEventProc(evPtr, flags) - Tcl_Event *evPtr; /* Event to service. */ - int flags; /* Flags that indicate what events to handle, +SocketEventProc( + Tcl_Event *evPtr, /* Event to service. */ + int flags) /* Flags that indicate what events to handle, * such as TCL_FILE_EVENTS. */ { SocketInfo *infoPtr; SocketEvent *eventPtr = (SocketEvent *) evPtr; - int mask = 0; - int events; + int mask = 0, events; ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); + TcpFdList *fds; + SOCKET newSocket; + address addr; + int len; if (!(flags & TCL_FILE_EVENTS)) { return 0; @@ -817,17 +671,17 @@ SocketEventProc(evPtr, flags) WaitForSingleObject(tsdPtr->socketListLock, INFINITE); for (infoPtr = tsdPtr->socketList; infoPtr != NULL; infoPtr = infoPtr->nextPtr) { - if (infoPtr->socket == eventPtr->socket) { + if (infoPtr->sockets->fd == eventPtr->socket) { break; } } - SetEvent(tsdPtr->socketListLock); /* * Discard events that have gone stale. */ if (!infoPtr) { + SetEvent(tsdPtr->socketListLock); return 1; } @@ -838,10 +692,66 @@ SocketEventProc(evPtr, flags) */ if (infoPtr->readyEvents & FD_ACCEPT) { - TcpAccept(infoPtr); + for (fds = infoPtr->sockets; fds != NULL; fds = fds->next) { + + /* + * Accept the incoming connection request. + */ + len = sizeof(address); + + newSocket = accept(fds->fd, &(addr.sa), &len); + + /* On Tcl server sockets with multiple OS fds we loop over the fds trying + * an accept() on each, so we expect INVALID_SOCKET. There are also other + * network stack conditions that can result in FD_ACCEPT but a subsequent + * failure on accept() by the time we get around to it. + * Access to sockets (acceptEventCount, readyEvents) in socketList + * is still protected by the lock (prevents reintroduction of + * SF Tcl Bug 3056775. + */ + + if (newSocket == INVALID_SOCKET) { + /* int err = WSAGetLastError(); */ + continue; + } + + /* + * It is possible that more than one FD_ACCEPT has been sent, so an extra + * count must be kept. Decrement the count, and reset the readyEvent bit + * if the count is no longer > 0. + */ + infoPtr->acceptEventCount--; + + if (infoPtr->acceptEventCount <= 0) { + infoPtr->readyEvents &= ~(FD_ACCEPT); + } + + SetEvent(tsdPtr->socketListLock); + + /* Caution: TcpAccept() has the side-effect of evaluating the server + * accept script (via AcceptCallbackProc() in tclIOCmd.c), which can + * close the server socket and invalidate infoPtr and fds. + * If TcpAccept() accepts a socket we must return immediately and let + * SocketCheckProc queue additional FD_ACCEPT events. + */ + TcpAccept(fds, newSocket, addr); + return 1; + } + + /* Loop terminated with no sockets accepted; clear the ready mask so + * we can detect the next connection request. Note that connection + * requests are level triggered, so if there is a request already + * pending, a new event will be generated. + */ + infoPtr->acceptEventCount = 0; + infoPtr->readyEvents &= ~(FD_ACCEPT); + + SetEvent(tsdPtr->socketListLock); return 1; } + SetEvent(tsdPtr->socketListLock); + /* * Mask off unwanted events and compute the read/write mask so we can * notify the channel. @@ -861,6 +771,7 @@ SocketEventProc(evPtr, flags) */ Tcl_Time blockTime = { 0, 0 }; + Tcl_SetMaxBlockTime(&blockTime); mask |= TCL_READABLE|TCL_WRITABLE; } else if (events & FD_READ) { @@ -879,11 +790,11 @@ SocketEventProc(evPtr, flags) (WPARAM) UNSELECT, (LPARAM) infoPtr); FD_ZERO(&readFds); - FD_SET(infoPtr->socket, &readFds); + FD_SET(infoPtr->sockets->fd, &readFds); timeout.tv_usec = 0; timeout.tv_sec = 0; - if (winSock.select(0, &readFds, NULL, NULL, &timeout) != 0) { + if (select(0, &readFds, NULL, NULL, &timeout) != 0) { mask |= TCL_READABLE; } else { infoPtr->readyEvents &= ~(FD_READ); @@ -925,12 +836,12 @@ SocketEventProc(evPtr, flags) */ static int -TcpBlockProc(instanceData, mode) - ClientData instanceData; /* The socket to block/un-block. */ - int mode; /* TCL_MODE_BLOCKING or +TcpBlockProc( + ClientData instanceData, /* The socket to block/un-block. */ + int mode) /* TCL_MODE_BLOCKING or * TCL_MODE_NONBLOCKING. */ { - SocketInfo *infoPtr = (SocketInfo *) instanceData; + SocketInfo *infoPtr = instanceData; if (mode == TCL_MODE_NONBLOCKING) { infoPtr->flags |= SOCKET_ASYNC; @@ -960,14 +871,14 @@ TcpBlockProc(instanceData, mode) /* ARGSUSED */ static int -TcpCloseProc(instanceData, interp) - ClientData instanceData; /* The socket to close. */ - Tcl_Interp *interp; /* Unused. */ +TcpCloseProc( + ClientData instanceData, /* The socket to close. */ + Tcl_Interp *interp) /* Unused. */ { - SocketInfo *infoPtr = (SocketInfo *) instanceData; + SocketInfo *infoPtr = instanceData; /* TIP #218 */ int errorCode = 0; - ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); + /* ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); */ /* * Check that WinSock is initialized; do not call it if not, to prevent @@ -982,9 +893,15 @@ TcpCloseProc(instanceData, interp) * background. */ - if (winSock.closesocket(infoPtr->socket) == SOCKET_ERROR) { - TclWinConvertWSAError((DWORD) winSock.WSAGetLastError()); - errorCode = Tcl_GetErrno(); + while ( infoPtr->sockets != NULL ) { + TcpFdList *thisfd = infoPtr->sockets; + infoPtr->sockets = thisfd->next; + + if (closesocket(thisfd->fd) == SOCKET_ERROR) { + TclWinConvertError((DWORD) WSAGetLastError()); + errorCode = Tcl_GetErrno(); + } + ckfree(thisfd); } } @@ -995,13 +912,113 @@ TcpCloseProc(instanceData, interp) * fear of damaging the list. */ - ckfree((char *) infoPtr); + ckfree(infoPtr); + return errorCode; +} + +/* + *---------------------------------------------------------------------- + * + * TcpClose2Proc -- + * + * This function is called by the generic IO level to perform the channel + * type specific part of a half-close: namely, a shutdown() on a socket. + * + * Results: + * 0 if successful, the value of errno if failed. + * + * Side effects: + * Shuts down one side of the socket. + * + *---------------------------------------------------------------------- + */ + +static int +TcpClose2Proc( + ClientData instanceData, /* The socket to close. */ + Tcl_Interp *interp, /* For error reporting. */ + int flags) /* Flags that indicate which side to close. */ +{ + SocketInfo *infoPtr = instanceData; + int errorCode = 0, sd; + + /* + * Shutdown the OS socket handle. + */ + + switch (flags) { + case TCL_CLOSE_READ: + sd = SD_RECEIVE; + break; + case TCL_CLOSE_WRITE: + sd = SD_SEND; + break; + default: + if (interp) { + Tcl_SetObjResult(interp, Tcl_NewStringObj( + "Socket close2proc called bidirectionally", -1)); + } + return TCL_ERROR; + } + + /* single fd operation: Tcl_OpenTcpServer() does not set TCL_READABLE or + * TCL_WRITABLE so this should never be called for a server socket. */ + if (shutdown(infoPtr->sockets->fd, sd) == SOCKET_ERROR) { + TclWinConvertError((DWORD) WSAGetLastError()); + errorCode = Tcl_GetErrno(); + } + return errorCode; } /* *---------------------------------------------------------------------- * + * AddSocketInfoFd -- + * + * This function adds a SOCKET file descriptor to the 'sockets' linked + * list of a SocketInfo structure. + * + * Results: + * None. + * + * Side effects: + * None, except for allocation of memory. + * + *---------------------------------------------------------------------- + */ + +static void +AddSocketInfoFd( + SocketInfo *infoPtr, + SOCKET socket) +{ + TcpFdList *fds = infoPtr->sockets; + + if ( fds == NULL ) { + /* Add the first FD */ + infoPtr->sockets = ckalloc(sizeof(TcpFdList)); + fds = infoPtr->sockets; + } else { + /* Find end of list and append FD */ + while ( fds->next != NULL ) { + fds = fds->next; + } + + fds->next = ckalloc(sizeof(TcpFdList)); + fds = fds->next; + } + + /* Populate new FD */ + fds->fd = socket; + fds->infoPtr = infoPtr; + fds->next = NULL; +} + + +/* + *---------------------------------------------------------------------- + * * NewSocketInfo -- * * This function allocates and initializes a new SocketInfo structure. @@ -1016,15 +1033,14 @@ TcpCloseProc(instanceData, interp) */ static SocketInfo * -NewSocketInfo(socket) - SOCKET socket; +NewSocketInfo( + SOCKET socket) { - SocketInfo *infoPtr; - ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); + SocketInfo *infoPtr = ckalloc(sizeof(SocketInfo)); - infoPtr = (SocketInfo *) ckalloc((unsigned) sizeof(SocketInfo)); + /* ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); */ infoPtr->channel = 0; - infoPtr->socket = socket; + infoPtr->sockets = NULL; infoPtr->flags = 0; infoPtr->watchEvents = 0; infoPtr->readyEvents = 0; @@ -1042,6 +1058,8 @@ NewSocketInfo(socket) infoPtr->nextPtr = NULL; + AddSocketInfoFd(infoPtr, socket); + return infoPtr; } @@ -1063,26 +1081,29 @@ NewSocketInfo(socket) */ static SocketInfo * -CreateSocket(interp, port, host, server, myaddr, myport, async) - Tcl_Interp *interp; /* For error reporting; can be NULL. */ - int port; /* Port number to open. */ - CONST char *host; /* Name of host on which to open port. */ - int server; /* 1 if socket should be a server socket, else +CreateSocket( + Tcl_Interp *interp, /* For error reporting; can be NULL. */ + int port, /* Port number to open. */ + const char *host, /* Name of host on which to open port. */ + int server, /* 1 if socket should be a server socket, else * 0 for a client socket. */ - CONST char *myaddr; /* Optional client-side address */ - int myport; /* Optional client-side port */ - int async; /* If nonzero, connect client socket + const char *myaddr, /* Optional client-side address */ + int myport, /* Optional client-side port */ + int async) /* If nonzero, connect client socket * asynchronously. */ { u_long flag = 1; /* Indicates nonblocking mode. */ int asyncConnect = 0; /* Will be 1 if async connect is in * progress. */ - SOCKADDR_IN sockaddr; /* Socket address */ - SOCKADDR_IN mysockaddr; /* Socket address for client */ - SOCKET sock; - SocketInfo *infoPtr; /* The returned value. */ - ThreadSpecificData *tsdPtr = (ThreadSpecificData *) - TclThreadDataKeyGet(&dataKey); + unsigned short chosenport = 0; + struct addrinfo *addrlist = NULL, *addrPtr; + /* Socket address to connect to. */ + struct addrinfo *myaddrlist = NULL, *myaddrPtr; + /* Socket address for our side. */ + const char *errorMsg = NULL; + SOCKET sock = INVALID_SOCKET; + SocketInfo *infoPtr = NULL; /* The returned value. */ + ThreadSpecificData *tsdPtr = TclThreadDataKeyGet(&dataKey); /* * Check that WinSock is initialized; do not call it if not, to prevent @@ -1094,113 +1115,196 @@ CreateSocket(interp, port, host, server, myaddr, myport, async) return NULL; } - if (!CreateSocketAddress(&sockaddr, host, port)) { - goto error; - } - if ((myaddr != NULL || myport != 0) && - !CreateSocketAddress(&mysockaddr, myaddr, myport)) { + /* + * Construct the addresses for each end of the socket. + */ + + if (!TclCreateSocketAddress(interp, &addrlist, host, port, server, + &errorMsg)) { goto error; } - - sock = winSock.socket(AF_INET, SOCK_STREAM, 0); - if (sock == INVALID_SOCKET) { + if (!TclCreateSocketAddress(interp, &myaddrlist, myaddr, myport, 1, + &errorMsg)) { goto error; } - /* - * Win-NT has a misfeature that sockets are inherited in child processes - * by default. Turn off the inherit bit. - */ + if (server) { - SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0); + for (addrPtr = addrlist; addrPtr != NULL; addrPtr = addrPtr->ai_next) { + sock = socket(addrPtr->ai_family, SOCK_STREAM, 0); + if (sock == INVALID_SOCKET) { + TclWinConvertError((DWORD) WSAGetLastError()); + continue; + } - /* - * Set kernel space buffering - */ + /* + * Win-NT has a misfeature that sockets are inherited in child + * processes by default. Turn off the inherit bit. + */ - TclSockMinimumBuffers((int) sock, TCP_BUFFER_SIZE); + SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0); - if (server) { - /* - * Bind to the specified port. Note that we must not call setsockopt - * with SO_REUSEADDR because Microsoft allows addresses to be reused - * even if they are still in use. - * - * Bind should not be affected by the socket having already been set - * into nonblocking mode. If there is trouble, this is one place to - * look for bugs. - */ + /* + * Set kernel space buffering + */ - if (winSock.bind(sock, (SOCKADDR *) &sockaddr, - sizeof(SOCKADDR_IN)) == SOCKET_ERROR) { - goto error; - } + TclSockMinimumBuffers((void *)sock, TCP_BUFFER_SIZE); - /* - * Set the maximum number of pending connect requests to the max value - * allowed on each platform (Win32 and Win32s may be different, and - * there may be differences between TCP/IP stacks). - */ + /* + * Make sure we use the same port when opening two server sockets + * for IPv4 and IPv6. + * + * As sockaddr_in6 uses the same offset and size for the port + * member as sockaddr_in, we can handle both through the IPv4 API. + */ - if (winSock.listen(sock, SOMAXCONN) == SOCKET_ERROR) { - goto error; - } + if (port == 0 && chosenport != 0) { + ((struct sockaddr_in *) addrPtr->ai_addr)->sin_port = + htons(chosenport); + } - /* - * Add this socket to the global list of sockets. - */ + /* + * Bind to the specified port. Note that we must not call + * setsockopt with SO_REUSEADDR because Microsoft allows addresses + * to be reused even if they are still in use. + * + * Bind should not be affected by the socket having already been + * set into nonblocking mode. If there is trouble, this is one + * place to look for bugs. + */ - infoPtr = NewSocketInfo(sock); + if (bind(sock, addrPtr->ai_addr, addrPtr->ai_addrlen) + == SOCKET_ERROR) { + TclWinConvertError((DWORD) WSAGetLastError()); + closesocket(sock); + continue; + } + if (port == 0 && chosenport == 0) { + address sockname; + socklen_t namelen = sizeof(sockname); - /* - * Set up the select mask for connection request events. - */ + /* + * Synchronize port numbers when binding to port 0 of multiple + * addresses. + */ - infoPtr->selectEvents = FD_ACCEPT; - infoPtr->watchEvents |= FD_ACCEPT; + if (getsockname(sock, &sockname.sa, &namelen) >= 0) { + chosenport = ntohs(sockname.sa4.sin_port); + } + } - } else { - /* - * Try to bind to a local port, if specified. - */ + /* + * Set the maximum number of pending connect requests to the max + * value allowed on each platform (Win32 and Win32s may be + * different, and there may be differences between TCP/IP stacks). + */ - if (myaddr != NULL || myport != 0) { - if (winSock.bind(sock, (SOCKADDR *) &mysockaddr, - sizeof(SOCKADDR_IN)) == SOCKET_ERROR) { - goto error; + if (listen(sock, SOMAXCONN) == SOCKET_ERROR) { + TclWinConvertError((DWORD) WSAGetLastError()); + closesocket(sock); + continue; } - } - /* - * Set the socket into nonblocking mode if the connect should be done - * in the background. - */ + if (infoPtr == NULL) { + /* + * Add this socket to the global list of sockets. + */ - if (async) { - if (winSock.ioctlsocket(sock, (long) FIONBIO, - &flag) == SOCKET_ERROR) { - goto error; + infoPtr = NewSocketInfo(sock); + + /* + * Set up the select mask for connection request events. + */ + + infoPtr->selectEvents = FD_ACCEPT; + infoPtr->watchEvents |= FD_ACCEPT; + + } else { + AddSocketInfoFd( infoPtr, sock ); } } + } else { + for (addrPtr = addrlist; addrPtr != NULL; + addrPtr = addrPtr->ai_next) { + for (myaddrPtr = myaddrlist; myaddrPtr != NULL; + myaddrPtr = myaddrPtr->ai_next) { + /* + * No need to try combinations of local and remote addresses + * of different families. + */ - /* - * Attempt to connect to the remote socket. - */ + if (myaddrPtr->ai_family != addrPtr->ai_family) { + continue; + } - if (winSock.connect(sock, (SOCKADDR *) &sockaddr, - sizeof(SOCKADDR_IN)) == SOCKET_ERROR) { - TclWinConvertWSAError((DWORD) winSock.WSAGetLastError()); - if (Tcl_GetErrno() != EWOULDBLOCK) { - goto error; - } + sock = socket(myaddrPtr->ai_family, SOCK_STREAM, 0); + if (sock == INVALID_SOCKET) { + TclWinConvertError((DWORD) WSAGetLastError()); + continue; + } - /* - * The connection is progressing in the background. - */ + /* + * Win-NT has a misfeature that sockets are inherited in child + * processes by default. Turn off the inherit bit. + */ + + SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0); + + /* + * Set kernel space buffering + */ + + TclSockMinimumBuffers((void *) sock, TCP_BUFFER_SIZE); + + /* + * Try to bind to a local port. + */ + + if (bind(sock, myaddrPtr->ai_addr, myaddrPtr->ai_addrlen) + == SOCKET_ERROR) { + TclWinConvertError((DWORD) WSAGetLastError()); + goto looperror; + } + /* + * Set the socket into nonblocking mode if the connect should + * be done in the background. + */ + if (async && ioctlsocket(sock, (long) FIONBIO, &flag) + == SOCKET_ERROR) { + TclWinConvertError((DWORD) WSAGetLastError()); + goto looperror; + } - asyncConnect = 1; + /* + * Attempt to connect to the remote socket. + */ + + if (connect(sock, addrPtr->ai_addr, addrPtr->ai_addrlen) + == SOCKET_ERROR) { + DWORD error = (DWORD) WSAGetLastError(); + if (error != WSAEWOULDBLOCK) { + TclWinConvertError(error); + goto looperror; + } + + /* + * The connection is progressing in the background. + */ + + asyncConnect = 1; + } + goto connected; + + looperror: + if (sock != INVALID_SOCKET) { + closesocket(sock); + sock = INVALID_SOCKET; + } + } } + goto error; + connected: /* * Add this socket to the global list of sockets. */ @@ -1219,25 +1323,35 @@ CreateSocket(interp, port, host, server, myaddr, myport, async) } } + error: + if (addrlist != NULL) { + freeaddrinfo(addrlist); + } + if (myaddrlist != NULL) { + freeaddrinfo(myaddrlist); + } + /* * Register for interest in events in the select mask. Note that this * automatically places the socket into non-blocking mode. */ - winSock.ioctlsocket(sock, (long) FIONBIO, &flag); - SendMessage(tsdPtr->hwnd, SOCKET_SELECT, - (WPARAM) SELECT, (LPARAM) infoPtr); + if (infoPtr != NULL) { + ioctlsocket(sock, (long) FIONBIO, &flag); + SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM) SELECT, + (LPARAM) infoPtr); - return infoPtr; + return infoPtr; + } - error: - TclWinConvertWSAError((DWORD) winSock.WSAGetLastError()); if (interp != NULL) { - Tcl_AppendResult(interp, "couldn't open socket: ", - Tcl_PosixError(interp), (char *) NULL); + Tcl_SetObjResult(interp, Tcl_ObjPrintf( + "couldn't open socket: %s", + (errorMsg ? errorMsg : Tcl_PosixError(interp)))); } + if (sock != INVALID_SOCKET) { - winSock.closesocket(sock); + closesocket(sock); } return NULL; } @@ -1245,78 +1359,6 @@ CreateSocket(interp, port, host, server, myaddr, myport, async) /* *---------------------------------------------------------------------- * - * CreateSocketAddress -- - * - * This function initializes a sockaddr structure for a host and port. - * - * Results: - * 1 if the host was valid, 0 if the host could not be converted to an IP - * address. - * - * Side effects: - * Fills in the *sockaddrPtr structure. - * - *---------------------------------------------------------------------- - */ - -static int -CreateSocketAddress(sockaddrPtr, host, port) - LPSOCKADDR_IN sockaddrPtr; /* Socket address */ - CONST char *host; /* Host. NULL implies INADDR_ANY */ - int port; /* Port number */ -{ - struct hostent *hostent; /* Host database entry */ - struct in_addr addr; /* For 64/32 bit madness */ - - /* - * Check that WinSock is initialized; do not call it if not, to prevent - * system crashes. This can happen at exit time if the exit handler for - * WinSock ran before other exit handlers that want to use sockets. - */ - - if (!SocketsEnabled()) { - Tcl_SetErrno(EFAULT); - return 0; - } - - ZeroMemory(sockaddrPtr, sizeof(SOCKADDR_IN)); - sockaddrPtr->sin_family = AF_INET; - sockaddrPtr->sin_port = winSock.htons((u_short) (port & 0xFFFF)); - if (host == NULL) { - addr.s_addr = INADDR_ANY; - } else { - addr.s_addr = winSock.inet_addr(host); - if (addr.s_addr == INADDR_NONE) { - hostent = winSock.gethostbyname(host); - if (hostent != NULL) { - memcpy(&addr, hostent->h_addr, (size_t) hostent->h_length); - } else { -#ifdef EHOSTUNREACH - Tcl_SetErrno(EHOSTUNREACH); -#else -#ifdef ENXIO - Tcl_SetErrno(ENXIO); -#endif -#endif - return 0; /* Error. */ - } - } - } - - /* - * NOTE: On 64 bit machines the assignment below is rumored to not do the - * right thing. Please report errors related to this if you observe - * incorrect behavior on 64 bit machines such as DEC Alphas. Should we - * modify this code to do an explicit memcpy? - */ - - sockaddrPtr->sin_addr.s_addr = addr.s_addr; - return 1; /* Success. */ -} - -/* - *---------------------------------------------------------------------- - * * WaitForSocketEvent -- * * Waits until one of the specified events occurs on a socket. @@ -1332,15 +1374,14 @@ CreateSocketAddress(sockaddrPtr, host, port) */ static int -WaitForSocketEvent(infoPtr, events, errorCodePtr) - SocketInfo *infoPtr; /* Information about this socket. */ - int events; /* Events to look for. */ - int *errorCodePtr; /* Where to store errors? */ +WaitForSocketEvent( + SocketInfo *infoPtr, /* Information about this socket. */ + int events, /* Events to look for. */ + int *errorCodePtr) /* Where to store errors? */ { int result = 1; int oldMode; - ThreadSpecificData *tsdPtr = (ThreadSpecificData *) - TclThreadDataKeyGet(&dataKey); + ThreadSpecificData *tsdPtr = TclThreadDataKeyGet(&dataKey); /* * Be sure to disable event servicing so we are truly modal. @@ -1352,11 +1393,10 @@ WaitForSocketEvent(infoPtr, events, errorCodePtr) * Reset WSAAsyncSelect so we have a fresh set of events pending. */ - SendMessage(tsdPtr->hwnd, SOCKET_SELECT, - (WPARAM) UNSELECT, (LPARAM) infoPtr); - - SendMessage(tsdPtr->hwnd, SOCKET_SELECT, - (WPARAM) SELECT, (LPARAM) infoPtr); + SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM) UNSELECT, + (LPARAM) infoPtr); + SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM) SELECT, + (LPARAM) infoPtr); while (1) { if (infoPtr->lastError) { @@ -1400,13 +1440,13 @@ WaitForSocketEvent(infoPtr, events, errorCodePtr) */ Tcl_Channel -Tcl_OpenTcpClient(interp, port, host, myaddr, myport, async) - Tcl_Interp *interp; /* For error reporting; can be NULL. */ - int port; /* Port number to open. */ - CONST char *host; /* Host on which to open port. */ - CONST char *myaddr; /* Client-side address */ - int myport; /* Client-side port */ - int async; /* If nonzero, should connect client socket +Tcl_OpenTcpClient( + Tcl_Interp *interp, /* For error reporting; can be NULL. */ + int port, /* Port number to open. */ + const char *host, /* Host on which to open port. */ + const char *myaddr, /* Client-side address */ + int myport, /* Client-side port */ + int async) /* If nonzero, should connect client socket * asynchronously. */ { SocketInfo *infoPtr; @@ -1425,19 +1465,18 @@ Tcl_OpenTcpClient(interp, port, host, myaddr, myport, async) return NULL; } - wsprintfA(channelName, "sock%d", infoPtr->socket); + sprintf(channelName, "sock%" TCL_I_MODIFIER "u", (size_t) infoPtr->sockets->fd); infoPtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName, - (ClientData) infoPtr, (TCL_READABLE | TCL_WRITABLE)); - if (Tcl_SetChannelOption(interp, infoPtr->channel, "-translation", - "auto crlf") == TCL_ERROR) { - Tcl_Close((Tcl_Interp *) NULL, infoPtr->channel); - return (Tcl_Channel) NULL; - } - if (Tcl_SetChannelOption(NULL, infoPtr->channel, "-eofchar", "") - == TCL_ERROR) { - Tcl_Close((Tcl_Interp *) NULL, infoPtr->channel); - return (Tcl_Channel) NULL; + infoPtr, (TCL_READABLE | TCL_WRITABLE)); + if (TCL_ERROR == Tcl_SetChannelOption(NULL, infoPtr->channel, + "-translation", "auto crlf")) { + Tcl_Close(NULL, infoPtr->channel); + return NULL; + } else if (TCL_ERROR == Tcl_SetChannelOption(NULL, infoPtr->channel, + "-eofchar", "")) { + Tcl_Close(NULL, infoPtr->channel); + return NULL; } return infoPtr->channel; } @@ -1461,8 +1500,8 @@ Tcl_OpenTcpClient(interp, port, host, myaddr, myport, async) */ Tcl_Channel -Tcl_MakeTcpClientChannel(sock) - ClientData sock; /* The socket to wrap up into a channel. */ +Tcl_MakeTcpClientChannel( + ClientData sock) /* The socket to wrap up into a channel. */ { SocketInfo *infoPtr; char channelName[16 + TCL_INTEGER_SPACE]; @@ -1472,13 +1511,13 @@ Tcl_MakeTcpClientChannel(sock) return NULL; } - tsdPtr = (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey); + tsdPtr = TclThreadDataKeyGet(&dataKey); /* * Set kernel space buffering and non-blocking. */ - TclSockMinimumBuffers((int) sock, TCP_BUFFER_SIZE); + TclSockMinimumBuffers(sock, TCP_BUFFER_SIZE); infoPtr = NewSocketInfo((SOCKET) sock); @@ -1487,12 +1526,11 @@ Tcl_MakeTcpClientChannel(sock) */ infoPtr->selectEvents = FD_READ | FD_CLOSE | FD_WRITE; - SendMessage(tsdPtr->hwnd, SOCKET_SELECT, - (WPARAM) SELECT, (LPARAM) infoPtr); + SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM)SELECT, (LPARAM)infoPtr); - wsprintfA(channelName, "sock%d", infoPtr->socket); + sprintf(channelName, "sock%" TCL_I_MODIFIER "u", (size_t) infoPtr->sockets->fd); infoPtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName, - (ClientData) infoPtr, (TCL_READABLE | TCL_WRITABLE)); + infoPtr, (TCL_READABLE | TCL_WRITABLE)); Tcl_SetChannelOption(NULL, infoPtr->channel, "-translation", "auto crlf"); return infoPtr->channel; } @@ -1515,14 +1553,14 @@ Tcl_MakeTcpClientChannel(sock) */ Tcl_Channel -Tcl_OpenTcpServer(interp, port, host, acceptProc, acceptProcData) - Tcl_Interp *interp; /* For error reporting - may be NULL. */ - int port; /* Port number to open. */ - CONST char *host; /* Name of local host. */ - Tcl_TcpAcceptProc *acceptProc; +Tcl_OpenTcpServer( + Tcl_Interp *interp, /* For error reporting - may be NULL. */ + int port, /* Port number to open. */ + const char *host, /* Name of local host. */ + Tcl_TcpAcceptProc *acceptProc, /* Callback for accepting connections from new * clients. */ - ClientData acceptProcData; /* Data for the callback. */ + ClientData acceptProcData) /* Data for the callback. */ { SocketInfo *infoPtr; char channelName[16 + TCL_INTEGER_SPACE]; @@ -1543,14 +1581,14 @@ Tcl_OpenTcpServer(interp, port, host, acceptProc, acceptProcData) infoPtr->acceptProc = acceptProc; infoPtr->acceptProcData = acceptProcData; - wsprintfA(channelName, "sock%d", infoPtr->socket); + sprintf(channelName, "sock%" TCL_I_MODIFIER "u", (size_t) infoPtr->sockets->fd); infoPtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName, - (ClientData) infoPtr, 0); + infoPtr, 0); if (Tcl_SetChannelOption(interp, infoPtr->channel, "-eofchar", "") == TCL_ERROR) { - Tcl_Close((Tcl_Interp *) NULL, infoPtr->channel); - return (Tcl_Channel) NULL; + Tcl_Close(NULL, infoPtr->channel); + return NULL; } return infoPtr->channel; @@ -1561,8 +1599,9 @@ Tcl_OpenTcpServer(interp, port, host, acceptProc, acceptProcData) * * TcpAccept -- * - * Accept a TCP socket connection. This is called by SocketEventProc and - * it in turns calls the registered accept function. + * Creates a channel for a newly accepted socket connection. This is + * called by SocketEventProc and it in turns calls the registered + * accept function. * * Results: * None. @@ -1574,49 +1613,17 @@ Tcl_OpenTcpServer(interp, port, host, acceptProc, acceptProcData) */ static void -TcpAccept(infoPtr) - SocketInfo *infoPtr; /* Socket to accept. */ +TcpAccept( + TcpFdList *fds, /* Server socket that accepted newSocket. */ + SOCKET newSocket, /* Newly accepted socket. */ + address addr) /* Address of new socket. */ { - SOCKET newSocket; SocketInfo *newInfoPtr; - SOCKADDR_IN addr; - int len; + SocketInfo *infoPtr = fds->infoPtr; + int len = sizeof(addr); char channelName[16 + TCL_INTEGER_SPACE]; - ThreadSpecificData *tsdPtr = (ThreadSpecificData *) - TclThreadDataKeyGet(&dataKey); - - /* - * Accept the incoming connection request. - */ - - len = sizeof(SOCKADDR_IN); - - newSocket = winSock.accept(infoPtr->socket, (SOCKADDR *)&addr, - &len); - - /* - * Clear the ready mask so we can detect the next connection request. - * Note that connection requests are level triggered, so if there is a - * request already pending, a new event will be generated. - */ - - if (newSocket == INVALID_SOCKET) { - infoPtr->acceptEventCount = 0; - infoPtr->readyEvents &= ~(FD_ACCEPT); - return; - } - - /* - * It is possible that more than one FD_ACCEPT has been sent, so an extra - * count must be kept. Decrement the count, and reset the readyEvent bit - * if the count is no longer > 0. - */ - - infoPtr->acceptEventCount--; - - if (infoPtr->acceptEventCount <= 0) { - infoPtr->readyEvents &= ~(FD_ACCEPT); - } + char host[NI_MAXHOST], port[NI_MAXSERV]; + ThreadSpecificData *tsdPtr = TclThreadDataKeyGet(&dataKey); /* * Win-NT has a misfeature that sockets are inherited in child processes @@ -1636,20 +1643,20 @@ TcpAccept(infoPtr) */ newInfoPtr->selectEvents = (FD_READ | FD_WRITE | FD_CLOSE); - SendMessage(tsdPtr->hwnd, SOCKET_SELECT, - (WPARAM) SELECT, (LPARAM) newInfoPtr); + SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM) SELECT, + (LPARAM) newInfoPtr); - wsprintfA(channelName, "sock%d", newInfoPtr->socket); + sprintf(channelName, "sock%" TCL_I_MODIFIER "u", (size_t) newInfoPtr->sockets->fd); newInfoPtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName, - (ClientData) newInfoPtr, (TCL_READABLE | TCL_WRITABLE)); + newInfoPtr, (TCL_READABLE | TCL_WRITABLE)); if (Tcl_SetChannelOption(NULL, newInfoPtr->channel, "-translation", "auto crlf") == TCL_ERROR) { - Tcl_Close((Tcl_Interp *) NULL, newInfoPtr->channel); + Tcl_Close(NULL, newInfoPtr->channel); return; } if (Tcl_SetChannelOption(NULL, newInfoPtr->channel, "-eofchar", "") == TCL_ERROR) { - Tcl_Close((Tcl_Interp *) NULL, newInfoPtr->channel); + Tcl_Close(NULL, newInfoPtr->channel); return; } @@ -1658,9 +1665,10 @@ TcpAccept(infoPtr) */ if (infoPtr->acceptProc != NULL) { - (infoPtr->acceptProc) (infoPtr->acceptProcData, newInfoPtr->channel, - winSock.inet_ntoa(addr.sin_addr), - winSock.ntohs(addr.sin_port)); + getnameinfo(&(addr.sa), len, host, sizeof(host), port, sizeof(port), + NI_NUMERICHOST|NI_NUMERICSERV); + infoPtr->acceptProc(infoPtr->acceptProcData, newInfoPtr->channel, + host, atoi(port)); } } @@ -1682,17 +1690,16 @@ TcpAccept(infoPtr) */ static int -TcpInputProc(instanceData, buf, toRead, errorCodePtr) - ClientData instanceData; /* The socket state. */ - char *buf; /* Where to store data. */ - int toRead; /* Maximum number of bytes to read. */ - int *errorCodePtr; /* Where to store error codes. */ +TcpInputProc( + ClientData instanceData, /* The socket state. */ + char *buf, /* Where to store data. */ + int toRead, /* Maximum number of bytes to read. */ + int *errorCodePtr) /* Where to store error codes. */ { - SocketInfo *infoPtr = (SocketInfo *) instanceData; + SocketInfo *infoPtr = instanceData; int bytesRead; DWORD error; - ThreadSpecificData *tsdPtr = - (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey); + ThreadSpecificData *tsdPtr = TclThreadDataKeyGet(&dataKey); *errorCodePtr = 0; @@ -1721,7 +1728,7 @@ TcpInputProc(instanceData, buf, toRead, errorCodePtr) */ if ((infoPtr->flags & SOCKET_ASYNC_CONNECT) - && ! WaitForSocketEvent(infoPtr, FD_CONNECT, errorCodePtr)) { + && !WaitForSocketEvent(infoPtr, FD_CONNECT, errorCodePtr)) { return -1; } @@ -1736,7 +1743,8 @@ TcpInputProc(instanceData, buf, toRead, errorCodePtr) while (1) { SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM) UNSELECT, (LPARAM) infoPtr); - bytesRead = winSock.recv(infoPtr->socket, buf, toRead, 0); + /* single fd operation: this proc is only called for a connected socket. */ + bytesRead = recv(infoPtr->sockets->fd, buf, toRead, 0); infoPtr->readyEvents &= ~(FD_READ); /* @@ -1761,13 +1769,25 @@ TcpInputProc(instanceData, buf, toRead, errorCodePtr) break; } + error = WSAGetLastError(); + + /* + * If an RST comes, then ignore the error and report an EOF just like + * on unix. + */ + + if (error == WSAECONNRESET) { + infoPtr->flags |= SOCKET_EOF; + bytesRead = 0; + break; + } + /* * Check for error condition or underflow in non-blocking case. */ - error = winSock.WSAGetLastError(); if ((infoPtr->flags & SOCKET_ASYNC) || (error != WSAEWOULDBLOCK)) { - TclWinConvertWSAError(error); + TclWinConvertError(error); *errorCodePtr = Tcl_GetErrno(); bytesRead = -1; break; @@ -1784,8 +1804,7 @@ TcpInputProc(instanceData, buf, toRead, errorCodePtr) } } - SendMessage(tsdPtr->hwnd, SOCKET_SELECT, - (WPARAM) SELECT, (LPARAM) infoPtr); + SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM)SELECT, (LPARAM)infoPtr); return bytesRead; } @@ -1808,17 +1827,16 @@ TcpInputProc(instanceData, buf, toRead, errorCodePtr) */ static int -TcpOutputProc(instanceData, buf, toWrite, errorCodePtr) - ClientData instanceData; /* The socket state. */ - CONST char *buf; /* Where to get data. */ - int toWrite; /* Maximum number of bytes to write. */ - int *errorCodePtr; /* Where to store error codes. */ +TcpOutputProc( + ClientData instanceData, /* The socket state. */ + const char *buf, /* Where to get data. */ + int toWrite, /* Maximum number of bytes to write. */ + int *errorCodePtr) /* Where to store error codes. */ { - SocketInfo *infoPtr = (SocketInfo *) instanceData; + SocketInfo *infoPtr = instanceData; int bytesWritten; DWORD error; - ThreadSpecificData *tsdPtr = - (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey); + ThreadSpecificData *tsdPtr = TclThreadDataKeyGet(&dataKey); *errorCodePtr = 0; @@ -1838,7 +1856,7 @@ TcpOutputProc(instanceData, buf, toWrite, errorCodePtr) */ if ((infoPtr->flags & SOCKET_ASYNC_CONNECT) - && ! WaitForSocketEvent(infoPtr, FD_CONNECT, errorCodePtr)) { + && !WaitForSocketEvent(infoPtr, FD_CONNECT, errorCodePtr)) { return -1; } @@ -1846,7 +1864,8 @@ TcpOutputProc(instanceData, buf, toWrite, errorCodePtr) SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM) UNSELECT, (LPARAM) infoPtr); - bytesWritten = winSock.send(infoPtr->socket, buf, toWrite, 0); + /* single fd operation: this proc is only called for a connected socket. */ + bytesWritten = send(infoPtr->sockets->fd, buf, toWrite, 0); if (bytesWritten != SOCKET_ERROR) { /* * Since Windows won't generate a new write event until we hit an @@ -1868,7 +1887,7 @@ TcpOutputProc(instanceData, buf, toWrite, errorCodePtr) * send fails with WSAEWOULDBLOCK. */ - error = winSock.WSAGetLastError(); + error = WSAGetLastError(); if (error == WSAEWOULDBLOCK) { infoPtr->readyEvents &= ~(FD_WRITE); if (infoPtr->flags & SOCKET_ASYNC) { @@ -1877,7 +1896,7 @@ TcpOutputProc(instanceData, buf, toWrite, errorCodePtr) break; } } else { - TclWinConvertWSAError(error); + TclWinConvertError(error); *errorCodePtr = Tcl_GetErrno(); bytesWritten = -1; break; @@ -1894,8 +1913,7 @@ TcpOutputProc(instanceData, buf, toWrite, errorCodePtr) } } - SendMessage(tsdPtr->hwnd, SOCKET_SELECT, - (WPARAM) SELECT, (LPARAM) infoPtr); + SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM)SELECT, (LPARAM)infoPtr); return bytesWritten; } @@ -1917,18 +1935,17 @@ TcpOutputProc(instanceData, buf, toWrite, errorCodePtr) */ static int -TcpSetOptionProc ( +TcpSetOptionProc( ClientData instanceData, /* Socket state. */ Tcl_Interp *interp, /* For error reporting - can be NULL. */ - CONST char *optionName, /* Name of the option to set. */ - CONST char *value) /* New value for option. */ + const char *optionName, /* Name of the option to set. */ + const char *value) /* New value for option. */ { - SocketInfo *infoPtr; +#ifdef TCL_FEATURE_KEEPALIVE_NAGLE + SocketInfo *infoPtr = instanceData; SOCKET sock; -/* - BOOL val = FALSE; - int boolVar, rtn; -*/ +#endif /*TCL_FEATURE_KEEPALIVE_NAGLE*/ + /* * Check that WinSock is initialized; do not call it if not, to prevent * system crashes. This can happen at exit time if the exit handler for @@ -1937,44 +1954,56 @@ TcpSetOptionProc ( if (!SocketsEnabled()) { if (interp) { - Tcl_AppendResult(interp, "winsock is not initialized", NULL); + Tcl_SetObjResult(interp, Tcl_NewStringObj( + "winsock is not initialized", -1)); } return TCL_ERROR; } - infoPtr = (SocketInfo *) instanceData; - sock = infoPtr->socket; +#ifdef TCL_FEATURE_KEEPALIVE_NAGLE + #error "TCL_FEATURE_KEEPALIVE_NAGLE not reviewed for whether to treat infoPtr->sockets as single fd or list" + sock = infoPtr->sockets->fd; + + if (!strcasecmp(optionName, "-keepalive")) { + BOOL val = FALSE; + int boolVar, rtn; -/* - if (!stricmp(optionName, "-keepalive")) { if (Tcl_GetBoolean(interp, value, &boolVar) != TCL_OK) { return TCL_ERROR; } - if (boolVar) val = TRUE; - rtn = winSock.setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, + if (boolVar) { + val = TRUE; + } + rtn = setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (const char *) &val, sizeof(BOOL)); if (rtn != 0) { - TclWinConvertWSAError(winSock.WSAGetLastError()); + TclWinConvertError(WSAGetLastError()); if (interp) { - Tcl_AppendResult(interp, "couldn't set socket option: ", - Tcl_PosixError(interp), NULL); + Tcl_SetObjResult(interp, Tcl_ObjPrintf( + "couldn't set socket option: %s", + Tcl_PosixError(interp))); } return TCL_ERROR; } return TCL_OK; + } else if (!strcasecmp(optionName, "-nagle")) { + BOOL val = FALSE; + int boolVar, rtn; - } else if (!stricmp(optionName, "-nagle")) { if (Tcl_GetBoolean(interp, value, &boolVar) != TCL_OK) { return TCL_ERROR; } - if (!boolVar) val = TRUE; - rtn = winSock.setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, + if (!boolVar) { + val = TRUE; + } + rtn = setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const char *) &val, sizeof(BOOL)); if (rtn != 0) { - TclWinConvertWSAError(winSock.WSAGetLastError()); + TclWinConvertError(WSAGetLastError()); if (interp) { - Tcl_AppendResult(interp, "couldn't set socket option: ", - Tcl_PosixError(interp), NULL); + Tcl_SetObjResult(interp, Tcl_ObjPrintf( + "couldn't set socket option: %s", + Tcl_PosixError(interp))); } return TCL_ERROR; } @@ -1982,8 +2011,9 @@ TcpSetOptionProc ( } return Tcl_BadChannelOption(interp, optionName, "keepalive nagle"); -*/ +#else return Tcl_BadChannelOption(interp, optionName, ""); +#endif /*TCL_FEATURE_KEEPALIVE_NAGLE*/ } /* @@ -2007,23 +2037,21 @@ TcpSetOptionProc ( */ static int -TcpGetOptionProc(instanceData, interp, optionName, dsPtr) - ClientData instanceData; /* Socket state. */ - Tcl_Interp *interp; /* For error reporting - can be NULL */ - CONST char *optionName; /* Name of the option to retrieve the value +TcpGetOptionProc( + ClientData instanceData, /* Socket state. */ + Tcl_Interp *interp, /* For error reporting - can be NULL */ + const char *optionName, /* Name of the option to retrieve the value * for, or NULL to get all options and their * values. */ - Tcl_DString *dsPtr; /* Where to store the computed value; + Tcl_DString *dsPtr) /* Where to store the computed value; * initialized by caller. */ { - SocketInfo *infoPtr; - SOCKADDR_IN sockname; - SOCKADDR_IN peername; - struct hostent *hostEntPtr; + SocketInfo *infoPtr = instanceData; + char host[NI_MAXHOST], port[NI_MAXSERV]; SOCKET sock; - int size = sizeof(SOCKADDR_IN); size_t len = 0; - char buf[TCL_INTEGER_SPACE]; + int reverseDNS = 0; +#define SUPPRESS_RDNS_VAR "::tcl::unsupported::noReverseDNS" /* * Check that WinSock is initialized; do not call it if not, to prevent @@ -2033,14 +2061,14 @@ TcpGetOptionProc(instanceData, interp, optionName, dsPtr) if (!SocketsEnabled()) { if (interp) { - Tcl_AppendResult(interp, "winsock is not initialized", NULL); + Tcl_SetObjResult(interp, Tcl_NewStringObj( + "winsock is not initialized", -1)); } return TCL_ERROR; } - infoPtr = (SocketInfo *) instanceData; - sock = (int) infoPtr->socket; - if (optionName != (char *) NULL) { + sock = infoPtr->sockets->fd; + if (optionName != NULL) { len = strlen(optionName); } @@ -2054,40 +2082,37 @@ TcpGetOptionProc(instanceData, interp, optionName, dsPtr) ret = TclWinGetSockOpt(sock, SOL_SOCKET, SO_ERROR, (char *)&err, &optlen); if (ret == SOCKET_ERROR) { - err = winSock.WSAGetLastError(); + err = WSAGetLastError(); } if (err) { - TclWinConvertWSAError(err); + TclWinConvertError(err); Tcl_DStringAppend(dsPtr, Tcl_ErrnoMsg(Tcl_GetErrno()), -1); } return TCL_OK; } + if (interp != NULL && Tcl_GetVar(interp, SUPPRESS_RDNS_VAR, 0) != NULL) { + reverseDNS = NI_NUMERICHOST; + } + if ((len == 0) || ((len > 1) && (optionName[1] == 'p') && (strncmp(optionName, "-peername", len) == 0))) { - if (winSock.getpeername(sock, (LPSOCKADDR) &peername, &size) == 0) { + address peername; + socklen_t size = sizeof(peername); + + if (getpeername(sock, (LPSOCKADDR) &(peername.sa), &size) == 0) { if (len == 0) { Tcl_DStringAppendElement(dsPtr, "-peername"); Tcl_DStringStartSublist(dsPtr); } - Tcl_DStringAppendElement(dsPtr, - winSock.inet_ntoa(peername.sin_addr)); - if (peername.sin_addr.s_addr == 0) { - hostEntPtr = (struct hostent *) NULL; - } else { - hostEntPtr = winSock.gethostbyaddr( - (char *) &(peername.sin_addr), - sizeof(peername.sin_addr), AF_INET); - } - if (hostEntPtr != (struct hostent *) NULL) { - Tcl_DStringAppendElement(dsPtr, hostEntPtr->h_name); - } else { - Tcl_DStringAppendElement(dsPtr, - winSock.inet_ntoa(peername.sin_addr)); - } - TclFormatInt(buf, winSock.ntohs(peername.sin_port)); - Tcl_DStringAppendElement(dsPtr, buf); + getnameinfo(&(peername.sa), size, host, sizeof(host), + NULL, 0, NI_NUMERICHOST); + Tcl_DStringAppendElement(dsPtr, host); + getnameinfo(&(peername.sa), size, host, sizeof(host), + port, sizeof(port), reverseDNS | NI_NUMERICSERV); + Tcl_DStringAppendElement(dsPtr, host); + Tcl_DStringAppendElement(dsPtr, port); if (len == 0) { Tcl_DStringEndSublist(dsPtr); } else { @@ -2097,15 +2122,16 @@ TcpGetOptionProc(instanceData, interp, optionName, dsPtr) /* * getpeername failed - but if we were asked for all the options * (len==0), don't flag an error at that point because it could be - * an fconfigure request on a server socket (which have no peer). - * {Copied from unix/tclUnixChan.c} + * an fconfigure request on a server socket (such sockets have no + * peer). {Copied from unix/tclUnixChan.c} */ if (len) { - TclWinConvertWSAError((DWORD) winSock.WSAGetLastError()); + TclWinConvertError((DWORD) WSAGetLastError()); if (interp) { - Tcl_AppendResult(interp, "can't get peername: ", - Tcl_PosixError(interp), (char *) NULL); + Tcl_SetObjResult(interp, Tcl_ObjPrintf( + "can't get peername: %s", + Tcl_PosixError(interp))); } return TCL_ERROR; } @@ -2114,28 +2140,53 @@ TcpGetOptionProc(instanceData, interp, optionName, dsPtr) if ((len == 0) || ((len > 1) && (optionName[1] == 's') && (strncmp(optionName, "-sockname", len) == 0))) { - if (winSock.getsockname(sock, (LPSOCKADDR) &sockname, &size) == 0) { - if (len == 0) { - Tcl_DStringAppendElement(dsPtr, "-sockname"); - Tcl_DStringStartSublist(dsPtr); - } - Tcl_DStringAppendElement(dsPtr, - winSock.inet_ntoa(sockname.sin_addr)); - if (sockname.sin_addr.s_addr == 0) { - hostEntPtr = (struct hostent *) NULL; - } else { - hostEntPtr = winSock.gethostbyaddr( - (char *) &(sockname.sin_addr), - sizeof(peername.sin_addr), AF_INET); - } - if (hostEntPtr != (struct hostent *) NULL) { - Tcl_DStringAppendElement(dsPtr, hostEntPtr->h_name); - } else { - Tcl_DStringAppendElement(dsPtr, - winSock.inet_ntoa(sockname.sin_addr)); + TcpFdList *fds; + address sockname; + socklen_t size; + int found = 0; + + if (len == 0) { + Tcl_DStringAppendElement(dsPtr, "-sockname"); + Tcl_DStringStartSublist(dsPtr); + } + for (fds = infoPtr->sockets; fds != NULL; fds = fds->next) { + sock = fds->fd; + size = sizeof(sockname); + if (getsockname(sock, &(sockname.sa), &size) >= 0) { + int flags = reverseDNS; + + found = 1; + getnameinfo(&sockname.sa, size, host, sizeof(host), + NULL, 0, NI_NUMERICHOST); + Tcl_DStringAppendElement(dsPtr, host); + + /* + * We don't want to resolve INADDR_ANY and sin6addr_any; they + * can sometimes cause problems (and never have a name). + */ + flags |= NI_NUMERICSERV; + if (sockname.sa.sa_family == AF_INET) { + if (sockname.sa4.sin_addr.s_addr == INADDR_ANY) { + flags |= NI_NUMERICHOST; + } + } else if (sockname.sa.sa_family == AF_INET6) { + if ((IN6_ARE_ADDR_EQUAL(&sockname.sa6.sin6_addr, + &in6addr_any)) || + (IN6_IS_ADDR_V4MAPPED(&sockname.sa6.sin6_addr) + && sockname.sa6.sin6_addr.s6_addr[12] == 0 + && sockname.sa6.sin6_addr.s6_addr[13] == 0 + && sockname.sa6.sin6_addr.s6_addr[14] == 0 + && sockname.sa6.sin6_addr.s6_addr[15] == 0)) { + flags |= NI_NUMERICHOST; + } + } + getnameinfo(&sockname.sa, size, host, sizeof(host), + port, sizeof(port), flags); + Tcl_DStringAppendElement(dsPtr, host); + Tcl_DStringAppendElement(dsPtr, port); } - TclFormatInt(buf, winSock.ntohs(sockname.sin_port)); - Tcl_DStringAppendElement(dsPtr, buf); + } + if (found) { if (len == 0) { Tcl_DStringEndSublist(dsPtr); } else { @@ -2143,15 +2194,15 @@ TcpGetOptionProc(instanceData, interp, optionName, dsPtr) } } else { if (interp) { - TclWinConvertWSAError((DWORD) winSock.WSAGetLastError()); - Tcl_AppendResult(interp, "can't get sockname: ", - Tcl_PosixError(interp), (char *) NULL); + TclWinConvertError((DWORD) WSAGetLastError()); + Tcl_SetObjResult(interp, Tcl_ObjPrintf( + "can't get sockname: %s", Tcl_PosixError(interp))); } return TCL_ERROR; } } -/* +#ifdef TCL_FEATURE_KEEPALIVE_NAGLE if (len == 0 || !strncmp(optionName, "-keepalive", len)) { int optlen; BOOL opt = FALSE; @@ -2160,8 +2211,7 @@ TcpGetOptionProc(instanceData, interp, optionName, dsPtr) Tcl_DStringAppendElement(dsPtr, "-keepalive"); } optlen = sizeof(BOOL); - winSock.getsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char *)&opt, - &optlen); + getsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char *)&opt, &optlen); if (opt) { Tcl_DStringAppendElement(dsPtr, "1"); } else { @@ -2180,8 +2230,7 @@ TcpGetOptionProc(instanceData, interp, optionName, dsPtr) Tcl_DStringAppendElement(dsPtr, "-nagle"); } optlen = sizeof(BOOL); - winSock.getsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&opt, - &optlen); + getsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&opt, &optlen); if (opt) { Tcl_DStringAppendElement(dsPtr, "0"); } else { @@ -2191,11 +2240,15 @@ TcpGetOptionProc(instanceData, interp, optionName, dsPtr) return TCL_OK; } } -*/ +#endif /*TCL_FEATURE_KEEPALIVE_NAGLE*/ if (len > 0) { - /*return Tcl_BadChannelOption(interp, optionName, "peername sockname keepalive nagle");*/ +#ifdef TCL_FEATURE_KEEPALIVE_NAGLE + return Tcl_BadChannelOption(interp, optionName, + "peername sockname keepalive nagle"); +#else return Tcl_BadChannelOption(interp, optionName, "peername sockname"); +#endif /*TCL_FEATURE_KEEPALIVE_NAGLE*/ } return TCL_OK; @@ -2220,17 +2273,17 @@ TcpGetOptionProc(instanceData, interp, optionName, dsPtr) */ static void -TcpWatchProc(instanceData, mask) - ClientData instanceData; /* The socket state. */ - int mask; /* Events of interest; an OR-ed combination of +TcpWatchProc( + ClientData instanceData, /* The socket state. */ + int mask) /* Events of interest; an OR-ed combination of * TCL_READABLE, TCL_WRITABLE and * TCL_EXCEPTION. */ { - SocketInfo *infoPtr = (SocketInfo *) instanceData; + SocketInfo *infoPtr = instanceData; /* * Update the watch events mask. Only if the socket is not a server - * socket. Fix for SF Tcl Bug #557878. + * socket. [Bug 557878] */ if (!infoPtr->acceptProc) { @@ -2249,6 +2302,7 @@ TcpWatchProc(instanceData, mask) if (infoPtr->readyEvents & infoPtr->watchEvents) { Tcl_Time blockTime = { 0, 0 }; + Tcl_SetMaxBlockTime(&blockTime); } } @@ -2272,14 +2326,14 @@ TcpWatchProc(instanceData, mask) */ static int -TcpGetHandleProc(instanceData, direction, handlePtr) - ClientData instanceData; /* The socket state. */ - int direction; /* Not used. */ - ClientData *handlePtr; /* Where to store the handle. */ +TcpGetHandleProc( + ClientData instanceData, /* The socket state. */ + int direction, /* Not used. */ + ClientData *handlePtr) /* Where to store the handle. */ { - SocketInfo *statePtr = (SocketInfo *) instanceData; + SocketInfo *statePtr = instanceData; - *handlePtr = (ClientData) statePtr->socket; + *handlePtr = INT2PTR(statePtr->sockets->fd); return TCL_OK; } @@ -2300,33 +2354,49 @@ TcpGetHandleProc(instanceData, direction, handlePtr) */ static DWORD WINAPI -SocketThread(LPVOID arg) +SocketThread( + LPVOID arg) { MSG msg; - ThreadSpecificData *tsdPtr = (ThreadSpecificData *)(arg); + ThreadSpecificData *tsdPtr = arg; + + /* + * Create a dummy window receiving socket events. + */ - tsdPtr->hwnd = CreateWindow("TclSocket", "TclSocket", - WS_TILED, 0, 0, 0, 0, NULL, NULL, windowClass.hInstance, arg); + tsdPtr->hwnd = CreateWindow(classname, classname, WS_TILED, 0, 0, 0, 0, + NULL, NULL, windowClass.hInstance, arg); /* - * Signal the main thread that the window has been created and that the - * socket thread is ready to go. + * Signalize thread creator that we are done creating the window. */ SetEvent(tsdPtr->readyEvent); + /* + * If unable to create the window, exit this thread immediately. + */ + if (tsdPtr->hwnd == NULL) { return 1; } /* - * Process all messages on the socket window until WM_QUIT. + * Process all messages on the socket window until WM_QUIT. This threads + * exits only when instructed to do so by the call to + * PostMessage(SOCKET_TERMINATE) in TclpFinalizeSockets(). */ while (GetMessage(&msg, NULL, 0, 0) > 0) { DispatchMessage(&msg); } + /* + * This releases waiters on thread exit in TclpFinalizeSockets() + */ + + SetEvent(tsdPtr->readyEvent); + return msg.wParam; } @@ -2344,26 +2414,27 @@ SocketThread(LPVOID arg) * * Side effects: * The flags for the given socket are updated to reflect the event that - * occured. + * occurred. * *---------------------------------------------------------------------- */ static LRESULT CALLBACK -SocketProc(hwnd, message, wParam, lParam) - HWND hwnd; - UINT message; - WPARAM wParam; - LPARAM lParam; +SocketProc( + HWND hwnd, + UINT message, + WPARAM wParam, + LPARAM lParam) { int event, error; SOCKET socket; SocketInfo *infoPtr; - ThreadSpecificData *tsdPtr = + TcpFdList *fds = NULL; + ThreadSpecificData *tsdPtr = (ThreadSpecificData *) #ifdef _WIN64 - (ThreadSpecificData *) GetWindowLongPtr(hwnd, GWLP_USERDATA); + GetWindowLongPtr(hwnd, GWLP_USERDATA); #else - (ThreadSpecificData *) GetWindowLong(hwnd, GWL_USERDATA); + GetWindowLong(hwnd, GWL_USERDATA); #endif switch (message) { @@ -2373,7 +2444,7 @@ SocketProc(hwnd, message, wParam, lParam) case WM_CREATE: /* - * store the initial tsdPtr, it's from a different thread, so it's not + * Store the initial tsdPtr, it's from a different thread, so it's not * directly accessible, but needed. */ @@ -2403,59 +2474,60 @@ SocketProc(hwnd, message, wParam, lParam) WaitForSingleObject(tsdPtr->socketListLock, INFINITE); for (infoPtr = tsdPtr->socketList; infoPtr != NULL; infoPtr = infoPtr->nextPtr) { - if (infoPtr->socket == socket) { - /* - * Update the socket state. - */ - - /* - * A count of FD_ACCEPTS is stored, so if an FD_CLOSE event - * happens, then clear the FD_ACCEPT count. Otherwise, - * increment the count if the current event is an FD_ACCEPT. - */ - - if (event & FD_CLOSE) { - infoPtr->acceptEventCount = 0; - infoPtr->readyEvents &= ~(FD_WRITE|FD_ACCEPT); - } else if (event & FD_ACCEPT) { - infoPtr->acceptEventCount++; - } - - if (event & FD_CONNECT) { + for (fds = infoPtr->sockets; fds != NULL; fds = fds->next) { + if (fds->fd == socket) { /* - * The socket is now connected, clear the async connect - * flag. + * Update the socket state. + * + * A count of FD_ACCEPTS is stored, so if an FD_CLOSE event + * happens, then clear the FD_ACCEPT count. Otherwise, + * increment the count if the current event is an FD_ACCEPT. */ - infoPtr->flags &= ~(SOCKET_ASYNC_CONNECT); + if (event & FD_CLOSE) { + infoPtr->acceptEventCount = 0; + infoPtr->readyEvents &= ~(FD_WRITE|FD_ACCEPT); + } else if (event & FD_ACCEPT) { + infoPtr->acceptEventCount++; + } - /* - * Remember any error that occurred so we can report - * connection failures. - */ + if (event & FD_CONNECT) { + /* + * The socket is now connected, clear the async connect + * flag. + */ + + infoPtr->flags &= ~(SOCKET_ASYNC_CONNECT); + + /* + * Remember any error that occurred so we can report + * connection failures. + */ - if (error != ERROR_SUCCESS) { - TclWinConvertWSAError((DWORD) error); - infoPtr->lastError = Tcl_GetErrno(); + if (error != ERROR_SUCCESS) { + TclWinConvertError((DWORD) error); + infoPtr->lastError = Tcl_GetErrno(); + } } - } - if (infoPtr->flags & SOCKET_ASYNC_CONNECT) { - infoPtr->flags &= ~(SOCKET_ASYNC_CONNECT); - if (error != ERROR_SUCCESS) { - TclWinConvertWSAError((DWORD) error); - infoPtr->lastError = Tcl_GetErrno(); + if (infoPtr->flags & SOCKET_ASYNC_CONNECT) { + infoPtr->flags &= ~(SOCKET_ASYNC_CONNECT); + if (error != ERROR_SUCCESS) { + TclWinConvertError((DWORD) error); + infoPtr->lastError = Tcl_GetErrno(); + } + infoPtr->readyEvents |= FD_WRITE; } - infoPtr->readyEvents |= FD_WRITE; - } - infoPtr->readyEvents |= event; + infoPtr->readyEvents |= event; - /* - * Wake up the Main Thread. - */ - SetEvent(tsdPtr->readyEvent); - Tcl_ThreadAlert(tsdPtr->threadId); - break; + /* + * Wake up the Main Thread. + */ + + SetEvent(tsdPtr->readyEvent); + Tcl_ThreadAlert(tsdPtr->threadId); + break; + } } } SetEvent(tsdPtr->socketListLock); @@ -2463,15 +2535,18 @@ SocketProc(hwnd, message, wParam, lParam) case SOCKET_SELECT: infoPtr = (SocketInfo *) lParam; - if (wParam == SELECT) { - winSock.WSAAsyncSelect(infoPtr->socket, hwnd, - SOCKET_MESSAGE, infoPtr->selectEvents); - } else { - /* - * Clear the selection mask - */ + for (fds = infoPtr->sockets; fds != NULL; fds = fds->next) { + infoPtr = (SocketInfo *) lParam; + if (wParam == SELECT) { + WSAAsyncSelect(fds->fd, hwnd, + SOCKET_MESSAGE, infoPtr->selectEvents); + } else { + /* + * Clear the selection mask + */ - winSock.WSAAsyncSelect(infoPtr->socket, hwnd, 0, 0); + WSAAsyncSelect(fds->fd, hwnd, 0, 0); + } } break; @@ -2500,8 +2575,8 @@ SocketProc(hwnd, message, wParam, lParam) *---------------------------------------------------------------------- */ -CONST char * -Tcl_GetHostName() +const char * +Tcl_GetHostName(void) { return Tcl_GetString(TclGetProcessGlobalValue(&hostName)); } @@ -2521,43 +2596,47 @@ Tcl_GetHostName() */ void -InitializeHostName(valuePtr, lengthPtr, encodingPtr) - char **valuePtr; - int *lengthPtr; - Tcl_Encoding *encodingPtr; +InitializeHostName( + char **valuePtr, + int *lengthPtr, + Tcl_Encoding *encodingPtr) { - WCHAR wbuf[MAX_COMPUTERNAME_LENGTH + 1]; - DWORD length = sizeof(wbuf) / sizeof(WCHAR); + TCHAR tbuf[MAX_COMPUTERNAME_LENGTH + 1]; + DWORD length = MAX_COMPUTERNAME_LENGTH + 1; Tcl_DString ds; - if ((*tclWinProcs->getComputerNameProc)(wbuf, &length) != 0) { + if (GetComputerName(tbuf, &length) != 0) { /* * Convert string from native to UTF then change to lowercase. */ - Tcl_UtfToLower(Tcl_WinTCharToUtf((TCHAR *) wbuf, -1, &ds)); - - } else if (TclpHasSockets(NULL) == TCL_OK) { - /* - * Buffer length of 255 copied slavishly from previous version of this - * routine. Presumably there's a more "correct" macro value for a - * properly sized buffer for a gethostname() call. Maintainers are - * welcome to supply it. - */ + Tcl_UtfToLower(Tcl_WinTCharToUtf(tbuf, -1, &ds)); + } else { Tcl_DStringInit(&ds); - Tcl_DStringSetLength(&ds, 255); - if (winSock.gethostname(Tcl_DStringValue(&ds), - Tcl_DStringLength(&ds)) == 0) { - Tcl_DStringSetLength(&ds, 0); + if (TclpHasSockets(NULL) == TCL_OK) { + /* + * The buffer size of 256 is recommended by the MSDN page that + * documents gethostname() as being always adequate. + */ + + Tcl_DString inDs; + + Tcl_DStringInit(&inDs); + Tcl_DStringSetLength(&inDs, 256); + if (gethostname(Tcl_DStringValue(&inDs), + Tcl_DStringLength(&inDs)) == 0) { + Tcl_ExternalToUtfDString(NULL, Tcl_DStringValue(&inDs), -1, + &ds); + } + Tcl_DStringFree(&inDs); } } *encodingPtr = Tcl_GetEncoding(NULL, "utf-8"); *lengthPtr = Tcl_DStringLength(&ds); - *valuePtr = ckalloc((unsigned int) (*lengthPtr)+1); - memcpy((VOID *) *valuePtr, (VOID *) Tcl_DStringValue(&ds), - (size_t)(*lengthPtr)+1); + *valuePtr = ckalloc((*lengthPtr) + 1); + memcpy(*valuePtr, Tcl_DStringValue(&ds), (size_t)(*lengthPtr)+1); Tcl_DStringFree(&ds); } @@ -2580,70 +2659,45 @@ InitializeHostName(valuePtr, lengthPtr, encodingPtr) *---------------------------------------------------------------------- */ +#undef TclWinGetSockOpt int -TclWinGetSockOpt(SOCKET s, int level, int optname, char * optval, - int FAR *optlen) +TclWinGetSockOpt( + SOCKET s, + int level, + int optname, + char *optval, + int *optlen) { - /* - * Check that WinSock is initialized; do not call it if not, to prevent - * system crashes. This can happen at exit time if the exit handler for - * WinSock ran before other exit handlers that want to use sockets. - */ - - if (!SocketsEnabled()) { - return SOCKET_ERROR; - } - - return winSock.getsockopt(s, level, optname, optval, optlen); + return getsockopt(s, level, optname, optval, optlen); } +#undef TclWinSetSockOpt int -TclWinSetSockOpt(SOCKET s, int level, int optname, const char * optval, - int optlen) +TclWinSetSockOpt( + SOCKET s, + int level, + int optname, + const char *optval, + int optlen) { - /* - * Check that WinSock is initialized; do not call it if not, to prevent - * system crashes. This can happen at exit time if the exit handler for - * WinSock ran before other exit handlers that want to use sockets. - */ - - if (!SocketsEnabled()) { - return SOCKET_ERROR; - } - - return winSock.setsockopt(s, level, optname, optval, optlen); + return setsockopt(s, level, optname, optval, optlen); } -u_short -TclWinNToHS(u_short netshort) +#undef TclpInetNtoa +char * +TclpInetNtoa( + struct in_addr addr) { - /* - * Check that WinSock is initialized; do not call it if not, to prevent - * system crashes. This can happen at exit time if the exit handler for - * WinSock ran before other exit handlers that want to use sockets. - */ - - if (!SocketsEnabled()) { - return (u_short) -1; - } - - return winSock.ntohs(netshort); + return inet_ntoa(addr); } +#undef TclWinGetServByName struct servent * -TclWinGetServByName(const char * name, const char * proto) +TclWinGetServByName( + const char *name, + const char *proto) { - /* - * Check that WinSock is initialized; do not call it if not, to prevent - * system crashes. This can happen at exit time if the exit handler for - * WinSock ran before other exit handlers that want to use sockets. - */ - - if (!SocketsEnabled()) { - return (struct servent *) NULL; - } - - return winSock.getservbyname(name, proto); + return getservbyname(name, proto); } /* @@ -2663,12 +2717,12 @@ TclWinGetServByName(const char * name, const char * proto) */ static void -TcpThreadActionProc (instanceData, action) - ClientData instanceData; - int action; +TcpThreadActionProc( + ClientData instanceData, + int action) { ThreadSpecificData *tsdPtr; - SocketInfo *infoPtr = (SocketInfo *) instanceData; + SocketInfo *infoPtr = instanceData; int notifyCmd; if (action == TCL_CHANNEL_THREAD_INSERT) { @@ -2693,7 +2747,7 @@ TcpThreadActionProc (instanceData, action) SocketInfo **nextPtrPtr; int removed = 0; - tsdPtr = TCL_TSD_INIT(&dataKey); + tsdPtr = TCL_TSD_INIT(&dataKey); /* * TIP #218, Bugfix: All access to socketList has to be protected by @@ -2702,7 +2756,7 @@ TcpThreadActionProc (instanceData, action) WaitForSingleObject(tsdPtr->socketListLock, INFINITE); for (nextPtrPtr = &(tsdPtr->socketList); (*nextPtrPtr) != NULL; - nextPtrPtr = &((*nextPtrPtr)->nextPtr)) { + nextPtrPtr = &((*nextPtrPtr)->nextPtr)) { if ((*nextPtrPtr) == infoPtr) { (*nextPtrPtr) = infoPtr->nextPtr; removed = 1; |
