Diff
Not logged in

Differences From Artifact [bdb2b3a406]:

To Artifact [2f4880c74f]:


1
2
3
4
5
6
7
8
9
10
11

12
13
14
15
16
17
18
1
2
3
4
5
6
7
8
9
10

11
12
13
14
15
16
17
18










-
+







/*
 * tclWinSock.c --
 *
 *	This file contains Windows-specific socket related code.
 *
 * Copyright (c) 1995-1997 Sun Microsystems, Inc.
 *
 * 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.70 2010/03/07 14:39:25 nijtmans Exp $
 * RCS: @(#) $Id: tclWinSock.c,v 1.70.2.1 2010/03/30 16:26:08 rmax Exp $
 */

#include "tclWinInt.h"

#ifdef _MSC_VER
#   pragma comment (lib, "ws2_32")
#endif
58
59
60
61
62
63
64





















65
66
67
68
69
70

71
72

73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

94
95
96
97
98
99
100
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90

91
92

93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113

114
115
116
117
118
119
120
121







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+





-
+

-
+




















-
+








#define SOCKET_MESSAGE	    WM_USER+1
#define SOCKET_SELECT	    WM_USER+2
#define SOCKET_TERMINATE    WM_USER+3
#define SELECT		    TRUE
#define UNSELECT	    FALSE

/*
 * This is needed to comply with the strict aliasing rules of GCC, but it also
 * simplifies casting between the different sockaddr types.
 */
typedef union {
    struct sockaddr sa;
    struct sockaddr_in sa4;
    struct sockaddr_in6 sa6;
    struct sockaddr_storage sas;
} address;

#define IN6_ARE_ADDR_EQUAL IN6_ADDR_EQUAL

typedef struct SocketInfo SocketInfo;

typedef struct TcpFdList {
    SocketInfo *infoPtr;
    int 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,
				 * FD_CLOSE, FD_ACCEPT and FD_CONNECT that
				 * indicate which events are interesting. */
    int readyEvents;		/* OR'ed combination of FD_READ, FD_WRITE,
				 * FD_CLOSE, FD_ACCEPT and FD_CONNECT that
				 * indicate which events have occurred. */
    int selectEvents;		/* OR'ed combination of FD_READ, FD_WRITE,
				 * FD_CLOSE, FD_ACCEPT and FD_CONNECT that
				 * indicate which events are currently being
				 * selected. */
    int acceptEventCount;	/* Count of the current number of FD_ACCEPTs
				 * that have arrived and not yet processed. */
    Tcl_TcpAcceptProc *acceptProc;
				/* Proc to call on accept. */
    ClientData acceptProcData;	/* The data for the accept proc. */
    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 {
144
145
146
147
148
149
150

151
152

153
154

155
156
157
158
159

160
161
162
163
164
165
166
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182

183
184
185
186
187
188
189
190







+


+


+




-
+







/*
 * Static functions defined in this file.
 */

static SocketInfo *	CreateSocket(Tcl_Interp *interp, int port,
			    const char *host, int server, const char *myaddr,
			    int myport, int async);
#if 0
static int		CreateSocketAddress(LPSOCKADDR_IN sockaddrPtr,
			    const char *host, int port);
#endif
static void		InitSockets(void);
static SocketInfo *	NewSocketInfo(SOCKET socket);
static SocketInfo *	NewSocketInfoEx(TcpFdList *sockets);
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);
static int		WaitForSocketEvent(SocketInfo *infoPtr, int events,
			    int *errorCodePtr);
static DWORD WINAPI	SocketThread(LPVOID arg);
static void		TcpThreadActionProc(ClientData instanceData,
			    int action);

static Tcl_EventCheckProc	SocketCheckProc;
579
580
581
582
583
584
585
586

587
588
589
590
591
592
593
603
604
605
606
607
608
609

610
611
612
613
614
615
616
617







-
+







    for (infoPtr = tsdPtr->socketList; infoPtr != NULL;
	    infoPtr = infoPtr->nextPtr) {
	if ((infoPtr->readyEvents & infoPtr->watchEvents)
		&& !(infoPtr->flags & SOCKET_PENDING)) {
	    infoPtr->flags |= SOCKET_PENDING;
	    evPtr = (SocketEvent *) ckalloc(sizeof(SocketEvent));
	    evPtr->header.proc = SocketEventProc;
	    evPtr->socket = infoPtr->socket;
	    evPtr->socket = infoPtr->sockets->fd;
	    Tcl_QueueEvent((Tcl_Event *) evPtr, TCL_QUEUE_TAIL);
	}
    }
    SetEvent(tsdPtr->socketListLock);
}

/*
618
619
620
621
622
623
624

625
626
627
628
629
630
631
632
633
634
635
636
637

638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657

658


659
660
661
662
663
664
665
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661

662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683

684
685
686
687
688
689
690
691
692







+












-
+




















+
-
+
+







				 * such as TCL_FILE_EVENTS. */
{
    SocketInfo *infoPtr;
    SocketEvent *eventPtr = (SocketEvent *) evPtr;
    int mask = 0;
    int events;
    ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
    TcpFdList *fds;

    if (!(flags & TCL_FILE_EVENTS)) {
	return 0;
    }

    /*
     * Find the specified socket on the socket list.
     */

    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) {
	return 1;
    }

    infoPtr->flags &= ~SOCKET_PENDING;

    /*
     * Handle connection requests directly.
     */

    if (infoPtr->readyEvents & FD_ACCEPT) {
	for (fds = infoPtr->sockets; fds != NULL; fds = fds->next) {
	TcpAccept(infoPtr);
	    TcpAccept(fds);
	}
	return 1;
    }

    /*
     * Mask off unwanted events and compute the read/write mask so we can
     * notify the channel.
     */
692
693
694
695
696
697
698
699

700
701
702
703
704
705
706
719
720
721
722
723
724
725

726
727
728
729
730
731
732
733







-
+







	 * select handler and keep waiting.
	 */

	SendMessage(tsdPtr->hwnd, SOCKET_SELECT,
		(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 (select(0, &readFds, NULL, NULL, &timeout) != 0) {
	    mask |= TCL_READABLE;
	} else {
	    infoPtr->readyEvents &= ~(FD_READ);
795
796
797
798
799
800
801
802

803
804
805
806
807
808
809
822
823
824
825
826
827
828

829
830
831
832
833
834
835
836







-
+







    if (SocketsEnabled()) {
	/*
	 * Clean up the OS socket handle. The default Windows setting for a
	 * socket is SO_DONTLINGER, which does a graceful shutdown in the
	 * background.
	 */

	if (closesocket(infoPtr->socket) == SOCKET_ERROR) {
	if (closesocket(infoPtr->sockets->fd) == SOCKET_ERROR) {
	    TclWinConvertWSAError((DWORD) WSAGetLastError());
	    errorCode = Tcl_GetErrno();
	}
    }

    /*
     * TIP #218. Removed the code removing the structure from the global
856
857
858
859
860
861
862
863

864
865
866
867
868
869
870
883
884
885
886
887
888
889

890
891
892
893
894
895
896
897







-
+







	    break;
	default:
	    if (interp) {
		Tcl_AppendResult(interp, "Socket close2proc called bidirectionally", NULL);
	    }
	    return TCL_ERROR;
	}
    if (shutdown(infoPtr->socket,sd) == SOCKET_ERROR) {
    if (shutdown(infoPtr->sockets->fd,sd) == SOCKET_ERROR) {
	TclWinConvertWSAError((DWORD) WSAGetLastError());
	errorCode = Tcl_GetErrno();
    }

    return errorCode;
}

884
885
886
887
888
889
890











891

892
893
894



895
896

897
898
899
900
901
902
903
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937

938
939
940
941
942
943
944
945







+
+
+
+
+
+
+
+
+
+
+

+



+
+
+

-
+







 *----------------------------------------------------------------------
 */

static SocketInfo *
NewSocketInfo(
    SOCKET socket)
{
    TcpFdList *fds;
    fds = (TcpFdList*) ckalloc(sizeof(TcpFdList));
    fds->fd = socket;
    fds->next = 0;
    return NewSocketInfoEx(fds);
}

static SocketInfo *
NewSocketInfoEx(
    TcpFdList *sockets)
{
    SocketInfo *infoPtr;
    TcpFdList *fds;
    /* ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); */

    infoPtr = (SocketInfo *) ckalloc((unsigned) sizeof(SocketInfo));
    for (fds = sockets; fds != NULL; fds = fds->next) {
	fds->infoPtr = infoPtr;
    }
    infoPtr->channel = 0;
    infoPtr->socket = socket;
    infoPtr->sockets = sockets;
    infoPtr->flags = 0;
    infoPtr->watchEvents = 0;
    infoPtr->readyEvents = 0;
    infoPtr->selectEvents = 0;
    infoPtr->acceptEventCount = 0;
    infoPtr->acceptProc = NULL;
    infoPtr->acceptProcData = NULL;
942
943
944
945
946
947
948


949
950



951
952

953
954
955
956
957
958
959
960
961
962
963
964
965
966

967
968
969
970

971
972
973



974
975
976
977
978
979
980
981
982



















































































































983
984

985
986
987
988
989
990
991






992
993
994


995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009






























1010
1011
1012
1013
1014
1015
1016
1017























1018
1019
1020
1021

1022
1023

1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080


1081
1082

1083
1084
1085
1086
1087
1088
1089






1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100








1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111

1112
1113
1114
1115
1116
1117
1118
984
985
986
987
988
989
990
991
992


993
994
995
996

997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010

1011
1012
1013
1014

1015
1016
1017
1018
1019
1020
1021









1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137

1138
1139






1140
1141
1142
1143
1144
1145



1146
1147















1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177








1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203

1204
1205

1206
1207
























































1208
1209
1210

1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228







1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255







+
+
-
-
+
+
+

-
+













-
+



-
+



+
+
+
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
+

-
-
-
-
-
-
+
+
+
+
+
+
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+



-
+

-
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+

-
+







+
+
+
+
+
+




-
-
-
-
-
-
-
+
+
+
+
+
+
+
+











+







    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. */
    int connected = 0;
    int chosenport = 0;
    SOCKADDR_IN sockaddr;	/* Socket address */
    SOCKADDR_IN mysockaddr;	/* Socket address for client */
    struct addrinfo *addrlist = NULL, *addrPtr;	/* socket address */
    struct addrinfo *myaddrlist = NULL, *myaddrPtr; /* Socket address for client */
    const char *errorMsg = NULL;
    SOCKET sock = INVALID_SOCKET;
    SocketInfo *infoPtr;	/* The returned value. */
    SocketInfo *infoPtr = NULL;	/* The returned value. */
    ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
	    TclThreadDataKeyGet(&dataKey);

    /*
     * 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 NULL;
    }

    if (!CreateSocketAddress(&sockaddr, host, port)) {
    if (!TclCreateSocketAddress(&addrlist, host, port, server, &errorMsg)) {
	goto error;
    }
    if ((myaddr != NULL || myport != 0) &&
	    !CreateSocketAddress(&mysockaddr, myaddr, myport)) {
	!TclCreateSocketAddress(&myaddrlist, myaddr, myport, 1, &errorMsg)) {
	goto error;
    }

    if (server) {
	TcpFdList *fds = NULL, *newfds;
	for (addrPtr = addrlist; addrPtr != NULL; addrPtr = addrPtr->ai_next) {
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == INVALID_SOCKET) {
	goto error;
    }

    /*
     * Win-NT has a misfeature that sockets are inherited in child processes
     * by default. Turn off the inherit bit.
     */
	    sock = socket(addrPtr->ai_family, SOCK_STREAM, 0);
	    if (sock == INVALID_SOCKET) {
		continue;
	    }
	
	    /*
	     * 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((int) sock, TCP_BUFFER_SIZE);

	    /*
	     * 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 (port == 0 && chosenport != 0) {
		((struct sockaddr_in *) addrPtr->ai_addr)->sin_port =
		    htons(chosenport);
	    }

	    /*
	     * 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.
	     */

	    if (bind(sock, addrPtr->ai_addr, addrPtr->ai_addrlen)
		== SOCKET_ERROR) {
		closesocket(sock);
		continue;
	    }
	    if (port == 0 && chosenport == 0) {
		address sockname;
		socklen_t namelen = sizeof(sockname);
		/*
		 * Synchronize port numbers when binding to port 0 of multiple
		 * addresses.
		 */
		if (getsockname(sock, &sockname.sa, &namelen) >= 0) {
		    chosenport = ntohs(sockname.sa4.sin_port);
		}
	    }
	    
	    /*
	     * 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 (listen(sock, SOMAXCONN) == SOCKET_ERROR) {
		closesocket(sock);
		continue;
	    }
	    
	    if (infoPtr == NULL) {
		/*
		 * Add this socket to the global list of sockets.
		 */
		
		infoPtr = NewSocketInfo(sock);
		fds = infoPtr->sockets;
		
		/*
		 * Set up the select mask for connection request events.
		 */
		
		infoPtr->selectEvents = FD_ACCEPT;
		infoPtr->watchEvents |= FD_ACCEPT;
		
	    } else {
		newfds = (TcpFdList *) ckalloc((unsigned) sizeof(TcpFdList));
		memset(newfds, (int) 0, sizeof(TcpFdList));
		newfds->fd = sock;
		newfds->infoPtr = infoPtr;
		newfds->next = NULL;
		fds->next = newfds;
		fds = newfds;
	    }
	}
    } else {
	for (myaddrPtr = myaddrlist; myaddrPtr != NULL;
	     myaddrPtr = myaddrPtr->ai_next) {
	    for (addrPtr = addrlist; addrPtr != NULL;
		 addrPtr = addrPtr->ai_next) {
		/*
		 * No need to try combinations of local and remote addresses
		 * of different families.
		 */
		if (myaddrPtr->ai_family != addrPtr->ai_family) {
		    continue;
		}

		sock = socket(myaddrPtr->ai_family, SOCK_STREAM, 0);
		if (sock == INVALID_SOCKET) {
		    continue;
		}
		
		/*
		 * 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);
		SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);

    /*
     * Set kernel space buffering
     */

    TclSockMinimumBuffers((int) sock, TCP_BUFFER_SIZE);

		/*
		 * Set kernel space buffering
		 */
		
		TclSockMinimumBuffers((int) sock, TCP_BUFFER_SIZE);
		
    if (server) {
	/*
	 * Bind to the specified port. Note that we must not call setsockopt
		/*
		 * Try to bind to a local port.
	 * 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.
	 */

	if (bind(sock, (SOCKADDR *) &sockaddr, sizeof(SOCKADDR_IN))
		== SOCKET_ERROR) {
	    goto error;
	}

	/*
	 * Set the maximum number of pending connect requests to the max value
		 */
		
		if (bind(sock, myaddrPtr->ai_addr, myaddrPtr->ai_addrlen)
		    == SOCKET_ERROR) {
		    goto looperror;
		}
		/*
		 * Set the socket into nonblocking mode if the connect should
		 * be done in the background.
		 */
		if (async) {
		    if (ioctlsocket(sock, (long) FIONBIO, &flag)
			== SOCKET_ERROR) {
			goto looperror;
		    }
		}

		/*
		 * Attempt to connect to the remote socket.
		 */
		
		if (connect(sock, addrPtr->ai_addr, addrPtr->ai_addrlen)
		    == SOCKET_ERROR) {
		    TclWinConvertWSAError((DWORD) WSAGetLastError());
		    if (Tcl_GetErrno() != EWOULDBLOCK) {
			goto looperror;
		    }
		    
		    /*
		     * The connection is progressing in the background.
	 * allowed on each platform (Win32 and Win32s may be different, and
	 * there may be differences between TCP/IP stacks).
	 */

	if (listen(sock, SOMAXCONN) == SOCKET_ERROR) {
	    goto error;
	}

		     */
		    
		    asyncConnect = 1;
		    connected = 1;
		    break;
		} else {
		    connected = 1;
		    break;
		}
	    looperror:
		if (sock != INVALID_SOCKET) {
		    closesocket(sock);
		    sock = INVALID_SOCKET;
		}
	    }
	    if (connected) {
		break;
	    }
	    if (sock != INVALID_SOCKET) {
		closesocket(sock);
		sock = INVALID_SOCKET;
	    }
	}
	/*
	 * Add this socket to the global list of sockets.
	 */

	
	infoPtr = NewSocketInfo(sock);

	
	/*
	 * Set up the select mask for connection request events.
	 */

	infoPtr->selectEvents = FD_ACCEPT;
	infoPtr->watchEvents |= FD_ACCEPT;

    } else {
	/*
	 * Try to bind to a local port, if specified.
	 */

	if (myaddr != NULL || myport != 0) {
	    if (bind(sock, (SOCKADDR *) &mysockaddr, sizeof(SOCKADDR_IN))
		    == SOCKET_ERROR) {
		goto error;
	    }
	}

	/*
	 * Set the socket into nonblocking mode if the connect should be done
	 * in the background.
	 */

	if (async) {
	    if (ioctlsocket(sock, (long) FIONBIO, &flag) == SOCKET_ERROR) {
		goto error;
	    }
	}

	/*
	 * Attempt to connect to the remote socket.
	 */

	if (connect(sock, (SOCKADDR *) &sockaddr,
		sizeof(SOCKADDR_IN)) == SOCKET_ERROR) {
	    TclWinConvertWSAError((DWORD) WSAGetLastError());
	    if (Tcl_GetErrno() != EWOULDBLOCK) {
		goto error;
	    }

	    /*
	     * The connection is progressing in the background.
	     */

	    asyncConnect = 1;
	}

	/*
	 * Add this socket to the global list of sockets.
	 */

	infoPtr = NewSocketInfo(sock);

	/*
	 * Set up the select mask for read/write events. If the connect
	 * attempt has not completed, include connect events.
	 * Set up the select mask for read/write events. If the
	 * connect attempt has not completed, include connect events.
	 */

	    
	infoPtr->selectEvents = FD_READ | FD_WRITE | FD_CLOSE;
	if (asyncConnect) {
	    infoPtr->flags |= SOCKET_ASYNC_CONNECT;
	    infoPtr->selectEvents |= FD_CONNECT;
	}
    }

  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.
     */

    ioctlsocket(sock, (long) FIONBIO, &flag);
    SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM) SELECT, (LPARAM) infoPtr);

    return infoPtr;

  error:
    
    if (infoPtr != NULL) {
	ioctlsocket(sock, (long) FIONBIO, &flag);
	SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM) SELECT, (LPARAM) infoPtr);
	
	return infoPtr;
    }

    TclWinConvertWSAError((DWORD) WSAGetLastError());
    if (interp != NULL) {
	Tcl_AppendResult(interp, "couldn't open socket: ",
		Tcl_PosixError(interp), NULL);
    }
    if (sock != INVALID_SOCKET) {
	closesocket(sock);
    }
    return NULL;
}

#if 0
/*
 *----------------------------------------------------------------------
 *
 * CreateSocketAddress --
 *
 *	This function initializes a sockaddr structure for a host and port.
 *
1176
1177
1178
1179
1180
1181
1182

1183
1184
1185
1186
1187
1188
1189
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327







+







     * 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. */
}
#endif

/*
 *----------------------------------------------------------------------
 *
 * WaitForSocketEvent --
 *
 *	Waits until one of the specified events occurs on a socket.
1288
1289
1290
1291
1292
1293
1294
1295

1296
1297
1298
1299
1300
1301
1302
1426
1427
1428
1429
1430
1431
1432

1433
1434
1435
1436
1437
1438
1439
1440







-
+







     */

    infoPtr = CreateSocket(interp, port, host, 0, myaddr, myport, async);
    if (infoPtr == NULL) {
	return NULL;
    }

    wsprintfA(channelName, "sock%d", infoPtr->socket);
    wsprintfA(channelName, "sock%d", 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;
1353
1354
1355
1356
1357
1358
1359
1360

1361
1362
1363
1364
1365
1366
1367
1491
1492
1493
1494
1495
1496
1497

1498
1499
1500
1501
1502
1503
1504
1505







-
+







     * Start watching for read/write events on the socket.
     */

    infoPtr->selectEvents = FD_READ | FD_CLOSE | FD_WRITE;
    SendMessage(tsdPtr->hwnd, SOCKET_SELECT,
	    (WPARAM) SELECT, (LPARAM) infoPtr);

    wsprintfA(channelName, "sock%d", infoPtr->socket);
    wsprintfA(channelName, "sock%d", infoPtr->sockets->fd);
    infoPtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
	    (ClientData) infoPtr, (TCL_READABLE | TCL_WRITABLE));
    Tcl_SetChannelOption(NULL, infoPtr->channel, "-translation", "auto crlf");
    return infoPtr->channel;
}

/*
1406
1407
1408
1409
1410
1411
1412
1413

1414
1415
1416
1417
1418
1419
1420
1544
1545
1546
1547
1548
1549
1550

1551
1552
1553
1554
1555
1556
1557
1558







-
+







    if (infoPtr == NULL) {
	return NULL;
    }

    infoPtr->acceptProc = acceptProc;
    infoPtr->acceptProcData = acceptProcData;

    wsprintfA(channelName, "sock%d", infoPtr->socket);
    wsprintfA(channelName, "sock%d", infoPtr->sockets->fd);

    infoPtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
	    (ClientData) infoPtr, 0);
    if (Tcl_SetChannelOption(interp, infoPtr->channel, "-eofchar", "")
	    == TCL_ERROR) {
	Tcl_Close((Tcl_Interp *) NULL, infoPtr->channel);
	return (Tcl_Channel) NULL;
1438
1439
1440
1441
1442
1443
1444
1445

1446
1447
1448

1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461

1462
1463
1464
1465
1466
1467
1468
1469
1576
1577
1578
1579
1580
1581
1582

1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599

1600

1601
1602
1603
1604
1605
1606
1607







-
+



+












-
+
-







 *	Invokes the accept proc which may invoke arbitrary Tcl code.
 *
 *----------------------------------------------------------------------
 */

static void
TcpAccept(
    SocketInfo *infoPtr)	/* Socket to accept. */
    TcpFdList *fds)	/* Socket to accept. */
{
    SOCKET newSocket;
    SocketInfo *newInfoPtr;
    SocketInfo *infoPtr = fds->infoPtr;
    SOCKADDR_IN addr;
    int len;
    char channelName[16 + TCL_INTEGER_SPACE];
    ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
	    TclThreadDataKeyGet(&dataKey);

    /*
     * Accept the incoming connection request.
     */

    len = sizeof(SOCKADDR_IN);

    newSocket = accept(infoPtr->socket, (SOCKADDR *)&addr,
    newSocket = accept(fds->fd, (SOCKADDR *)&addr, &len);
	    &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.
     */

1502
1503
1504
1505
1506
1507
1508
1509

1510
1511
1512
1513
1514
1515
1516
1640
1641
1642
1643
1644
1645
1646

1647
1648
1649
1650
1651
1652
1653
1654







-
+







     * Select on read/write events and create the channel.
     */

    newInfoPtr->selectEvents = (FD_READ | FD_WRITE | FD_CLOSE);
    SendMessage(tsdPtr->hwnd, SOCKET_SELECT,
	    (WPARAM) SELECT, (LPARAM) newInfoPtr);

    wsprintfA(channelName, "sock%d", newInfoPtr->socket);
    wsprintfA(channelName, "sock%d", newInfoPtr->sockets->fd);
    newInfoPtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
	    (ClientData) newInfoPtr, (TCL_READABLE | TCL_WRITABLE));
    if (Tcl_SetChannelOption(NULL, newInfoPtr->channel, "-translation",
	    "auto crlf") == TCL_ERROR) {
	Tcl_Close((Tcl_Interp *) NULL, newInfoPtr->channel);
	return;
    }
1598
1599
1600
1601
1602
1603
1604
1605

1606
1607
1608
1609
1610
1611
1612
1736
1737
1738
1739
1740
1741
1742

1743
1744
1745
1746
1747
1748
1749
1750







-
+







     * read. We have to simulate blocking behavior here since we are always
     * using non-blocking sockets.
     */

    while (1) {
	SendMessage(tsdPtr->hwnd, SOCKET_SELECT,
		(WPARAM) UNSELECT, (LPARAM) infoPtr);
	bytesRead = recv(infoPtr->socket, buf, toRead, 0);
	bytesRead = recv(infoPtr->sockets->fd, buf, toRead, 0);
	infoPtr->readyEvents &= ~(FD_READ);

	/*
	 * Check for end-of-file condition or successful read.
	 */

	if (bytesRead == 0) {
1720
1721
1722
1723
1724
1725
1726
1727

1728
1729
1730
1731
1732
1733
1734
1858
1859
1860
1861
1862
1863
1864

1865
1866
1867
1868
1869
1870
1871
1872







-
+







	return -1;
    }

    while (1) {
	SendMessage(tsdPtr->hwnd, SOCKET_SELECT,
		(WPARAM) UNSELECT, (LPARAM) infoPtr);

	bytesWritten = send(infoPtr->socket, buf, toWrite, 0);
	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
	     * overflow condition, we need to force the event loop to poll
	     * until the condition changes.
	     */

1814
1815
1816
1817
1818
1819
1820
1821

1822
1823
1824
1825
1826
1827
1828
1952
1953
1954
1955
1956
1957
1958

1959
1960
1961
1962
1963
1964
1965
1966







-
+







	if (interp) {
	    Tcl_AppendResult(interp, "winsock is not initialized", NULL);
	}
	return TCL_ERROR;
    }

    infoPtr = (SocketInfo *) instanceData;
    sock = infoPtr->socket;
    sock = infoPtr->sockets->fd;

#ifdef TCL_FEATURE_KEEPALIVE_NAGLE
    if (!strcasecmp(optionName, "-keepalive")) {
	BOOL val = FALSE;
	int boolVar, rtn;

	if (Tcl_GetBoolean(interp, value, &boolVar) != TCL_OK) {
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907

1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927

1928
1929
1930
1931
1932
1933
1934
2036
2037
2038
2039
2040
2041
2042



2043
2044

2045

2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060

2061
2062
2063
2064
2065
2066
2067
2068







-
-
-
+

-

-















-
+







    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;
				 * initialized by caller. */
{
    SocketInfo *infoPtr;
    SOCKADDR_IN sockname;
    SOCKADDR_IN peername;
    struct hostent *hostEntPtr;
    char host[NI_MAXHOST], port[NI_MAXSERV];
    SOCKET sock;
    int size = sizeof(SOCKADDR_IN);
    size_t len = 0;
    char buf[TCL_INTEGER_SPACE];

    /*
     * 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()) {
	if (interp) {
	    Tcl_AppendResult(interp, "winsock is not initialized", NULL);
	}
	return TCL_ERROR;
    }

    infoPtr = (SocketInfo *) instanceData;
    sock = (int) infoPtr->socket;
    sock = (int) infoPtr->sockets->fd;
    if (optionName != NULL) {
	len = strlen(optionName);
    }

    if ((len > 1) && (optionName[1] == 'e') &&
	    (strncmp(optionName, "-error", len) == 0)) {
	int optlen;
1946
1947
1948
1949
1950
1951
1952


1953

1954
1955
1956
1957
1958
1959
1960
1961


1962
1963
1964
1965
1966
1967

1968
1969



1970
1971
1972

1973
1974
1975
1976
1977
1978
1979
2080
2081
2082
2083
2084
2085
2086
2087
2088

2089
2090
2091
2092
2093

2094


2095
2096






2097


2098
2099
2100



2101
2102
2103
2104
2105
2106
2107
2108







+
+
-
+




-

-
-
+
+
-
-
-
-
-
-
+
-
-
+
+
+
-
-
-
+







	    Tcl_DStringAppend(dsPtr, Tcl_ErrnoMsg(Tcl_GetErrno()), -1);
	}
	return TCL_OK;
    }

    if ((len == 0) || ((len > 1) && (optionName[1] == 'p') &&
	    (strncmp(optionName, "-peername", len) == 0))) {
	address peername;
	socklen_t size = sizeof(peername);
	if (getpeername(sock, (LPSOCKADDR) &peername, &size) == 0) {
	if (getpeername(sock, (LPSOCKADDR) &(peername.sa), &size) == 0) {
	    if (len == 0) {
		Tcl_DStringAppendElement(dsPtr, "-peername");
		Tcl_DStringStartSublist(dsPtr);
	    }
	    Tcl_DStringAppendElement(dsPtr, inet_ntoa(peername.sin_addr));

	    if (peername.sin_addr.s_addr == 0) {
		hostEntPtr = NULL;
	    getnameinfo(&(peername.sa), size, host, sizeof(host),
                        NULL, 0, NI_NUMERICHOST);
	    } else {
		hostEntPtr = gethostbyaddr((char *) &(peername.sin_addr),
			sizeof(peername.sin_addr), AF_INET);
	    }
	    if (hostEntPtr != NULL) {
		Tcl_DStringAppendElement(dsPtr, hostEntPtr->h_name);
	    Tcl_DStringAppendElement(dsPtr, host);
	    } else {
		Tcl_DStringAppendElement(dsPtr, inet_ntoa(peername.sin_addr));
	    getnameinfo(&(peername.sa), size, host, sizeof(host),
                        port, sizeof(port), NI_NUMERICSERV);
	    Tcl_DStringAppendElement(dsPtr, host);
	    }
	    TclFormatInt(buf, ntohs(peername.sin_port));
	    Tcl_DStringAppendElement(dsPtr, buf);
	    Tcl_DStringAppendElement(dsPtr, port);
	    if (len == 0) {
		Tcl_DStringEndSublist(dsPtr);
	    } else {
		return TCL_OK;
	    }
	} else {
	    /*
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012












































2013
2014

2015
2016
2017


2018
2019
2020
2021
2022
2023
2024
2025
2026
2027

2028
2029
2030
2031
2032

2033
2034
2035
2036
2037
2038
2039
2121
2122
2123
2124
2125
2126
2127














2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171


2172
2173


2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184

2185
2186
2187
2188
2189

2190
2191
2192
2193
2194
2195
2196
2197







-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+

-
-
+
+









-
+




-
+







		return TCL_ERROR;
	    }
	}
    }

    if ((len == 0) || ((len > 1) && (optionName[1] == 's') &&
	    (strncmp(optionName, "-sockname", len) == 0))) {
	if (getsockname(sock, (LPSOCKADDR) &sockname, &size) == 0) {
	    if (len == 0) {
		Tcl_DStringAppendElement(dsPtr, "-sockname");
		Tcl_DStringStartSublist(dsPtr);
	    }
	    Tcl_DStringAppendElement(dsPtr, inet_ntoa(sockname.sin_addr));
	    if (sockname.sin_addr.s_addr == 0) {
		hostEntPtr = NULL;
	    } else {
		hostEntPtr = gethostbyaddr((char *) &(sockname.sin_addr),
			sizeof(peername.sin_addr), AF_INET);
	    }
	    if (hostEntPtr != NULL) {
		Tcl_DStringAppendElement(dsPtr, hostEntPtr->h_name);

	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;
		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);
	    } else {
		Tcl_DStringAppendElement(dsPtr, inet_ntoa(sockname.sin_addr));
		Tcl_DStringAppendElement(dsPtr, port);
	    }
	    TclFormatInt(buf, ntohs(sockname.sin_port));
	    Tcl_DStringAppendElement(dsPtr, buf);
	}
	if (found) {
	    if (len == 0) {
		Tcl_DStringEndSublist(dsPtr);
	    } else {
		return TCL_OK;
	    }
	} else {
	    if (interp) {
		TclWinConvertWSAError((DWORD) WSAGetLastError());
		Tcl_AppendResult(interp, "can't get sockname: ",
			Tcl_PosixError(interp), NULL);
				 Tcl_PosixError(interp), NULL);
	    }
	    return TCL_ERROR;
	}
    }

	
#ifdef TCL_FEATURE_KEEPALIVE_NAGLE
    if (len == 0 || !strncmp(optionName, "-keepalive", len)) {
	int optlen;
	BOOL opt = FALSE;

	if (len == 0) {
	    Tcl_DStringAppendElement(dsPtr, "-keepalive");
2157
2158
2159
2160
2161
2162
2163
2164

2165
2166
2167
2168
2169
2170
2171
2315
2316
2317
2318
2319
2320
2321

2322
2323
2324
2325
2326
2327
2328
2329







-
+







TcpGetHandleProc(
    ClientData instanceData,	/* The socket state. */
    int direction,		/* Not used. */
    ClientData *handlePtr)	/* Where to store the handle. */
{
    SocketInfo *statePtr = (SocketInfo *) instanceData;

    *handlePtr = (ClientData) statePtr->socket;
    *handlePtr = (ClientData) statePtr->sockets->fd;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * SocketThread --
2297
2298
2299
2300
2301
2302
2303
2304

2305
2306
2307
2308
2309
2310
2311
2455
2456
2457
2458
2459
2460
2461

2462
2463
2464
2465
2466
2467
2468
2469







-
+







	 * Find the specified socket on the socket list and update its
	 * eventState flag.
	 */

	WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
	for (infoPtr = tsdPtr->socketList; infoPtr != NULL;
		infoPtr = infoPtr->nextPtr) {
	    if (infoPtr->socket == socket) {
	    if (infoPtr->sockets->fd == 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.
		 */
2357
2358
2359
2360
2361
2362
2363
2364

2365
2366
2367
2368
2369
2370
2371

2372
2373
2374
2375
2376
2377
2378
2515
2516
2517
2518
2519
2520
2521

2522
2523
2524
2525
2526
2527
2528

2529
2530
2531
2532
2533
2534
2535
2536







-
+






-
+







	}
	SetEvent(tsdPtr->socketListLock);
	break;

    case SOCKET_SELECT:
	infoPtr = (SocketInfo *) lParam;
	if (wParam == SELECT) {
	    WSAAsyncSelect(infoPtr->socket, hwnd,
	    WSAAsyncSelect(infoPtr->sockets->fd, hwnd,
		    SOCKET_MESSAGE, infoPtr->selectEvents);
	} else {
	    /*
	     * Clear the selection mask
	     */

	    WSAAsyncSelect(infoPtr->socket, hwnd, 0, 0);
	    WSAAsyncSelect(infoPtr->sockets->fd, hwnd, 0, 0);
	}
	break;

    case SOCKET_TERMINATE:
	DestroyWindow(hwnd);
	break;
    }