Diff
Not logged in

Differences From Artifact [b0395f7d37]:

To Artifact [d892fac22d]:


293
294
295
296
297
298
299


300


301
302

303
304

305
306

307



308


309
310

311
312
313
314
315
316
317
293
294
295
296
297
298
299
300
301

302
303
304
305
306
307

308


309
310
311
312
313

314
315
316
317
318
319
320
321
322
323
324
325







+
+
-
+
+


+

-
+
-
-
+

+
+
+
-
+
+


+







static ProcessGlobalValue hostName =
	{0, 0, NULL, NULL, InitializeHostName, NULL, NULL};

/*
 * Address print debug functions
 */
#if 0
void
printaddrinfo(
void printaddrinfo(struct addrinfo *ai, char *prefix)
    struct addrinfo *ai,
    char *prefix)
{
    char host[NI_MAXHOST], port[NI_MAXSERV];

    getnameinfo(ai->ai_addr, ai->ai_addrlen,
		host, sizeof(host),
	    host, sizeof(host), port, sizeof(port),
		port, sizeof(port),
		NI_NUMERICHOST|NI_NUMERICSERV);
	    NI_NUMERICHOST|NI_NUMERICSERV);
}

void
printaddrinfolist(
void printaddrinfolist(struct addrinfo *addrlist, char *prefix)
    struct addrinfo *addrlist,
    char *prefix)
{
    struct addrinfo *ai;

    for (ai = addrlist; ai != NULL; ai = ai->ai_next) {
	printaddrinfo(ai, prefix);
    }
}
#endif

/*
520
521
522
523
524
525
526
527

528
529

530
531
532
533
534
535
536
537
538
539
540
541
542




543
544
545
546


547
548
549
550


551
552
553


554
555
556
557


558
559
560
561


562
563
564
565
566
567
568
569
570


571
572
573
574
575
576
577
578
579


580
581
582
583
584
585
586
528
529
530
531
532
533
534

535
536

537
538
539
540
541
542
543
544
545
546




547
548
549
550
551
552


553
554
555
556


557
558



559
560
561
562


563
564
565
566


567
568
569
570
571
572
573
574
575


576
577

578
579
580
581
582
583


584
585
586
587
588
589
590
591
592







-
+

-
+









-
-
-
-
+
+
+
+


-
-
+
+


-
-
+
+
-
-
-
+
+


-
-
+
+


-
-
+
+







-
-
+
+
-






-
-
+
+







    int mode)			/* The mode to set. Can be one of
				 * TCL_MODE_BLOCKING or
				 * TCL_MODE_NONBLOCKING. */
{
    TcpState *statePtr = instanceData;

    if (mode == TCL_MODE_NONBLOCKING) {
	statePtr->flags |= TCP_NONBLOCKING;
	SET_BITS(statePtr->flags, TCP_NONBLOCKING);
    } else {
	statePtr->flags &= ~(TCP_NONBLOCKING);
        CLEAR_BITS(statePtr->flags, TCP_NONBLOCKING);
    }
    return 0;
}

/*
 *----------------------------------------------------------------------
 *
 * WaitForConnect --
 *
 *	Check the state of an async connect process. If a connection
 *	attempt terminated, process it, which may finalize it or may
 *	start the next attempt. If a connect error occures, it is saved
 *	in statePtr->connectError to be reported by 'fconfigure -error'.
 *	Check the state of an async connect process. If a connection attempt
 *	terminated, process it, which may finalize it or may start the next
 *	attempt. If a connect error occures, it is saved in
 *	statePtr->connectError to be reported by 'fconfigure -error'.
 *
 *	There are two modes of operation, defined by errorCodePtr:
 *	 *  non-NULL: Called by explicite read/write command. block if
 *	    socket is blocking.
 *	 *  non-NULL: Called by explicite read/write command. Block if socket
 *	    is blocking.
 *	    May return two error codes:
 *	     *	EWOULDBLOCK: if connect is still in progress
 *	     *	ENOTCONN: if connect failed. This would be the error
 *		message of a rect or sendto syscall so this is
 *	     *	ENOTCONN: if connect failed. This would be the error message
 *		of a rect or sendto syscall so this is emulated here.
 *		emulated here.
 *	 *  Null: Called by a backround operation. Do not block and
 *	    don't return any error code.
 *	 *  Null: Called by a backround operation. Do not block and don't
 *	    return any error code.
 *
 * Results:
 * 	0 if the connection has completed, -1 if still in progress
 * 	or there is an error.
 * 	0 if the connection has completed, -1 if still in progress or there is
 * 	an error.
 *
 * Side effects:
 *	Processes socket events off the system queue.
 *	May process asynchroneous connect.
 *	Processes socket events off the system queue. May process
 *	asynchroneous connect.
 *
 *----------------------------------------------------------------------
 */

static int
WaitForConnect(
    TcpState *statePtr,		/* State of the socket. */
    int *errorCodePtr)		/* Where to store errors?
				 * A passed null-pointer activates background mode.
    int *errorCodePtr)		/* Where to store errors? A passed
				 * null-pointer activates background mode. */
				 */
{
    int result;
    int oldMode;
    ThreadSpecificData *tsdPtr;

    /*
     * Check if an async connect failed already and error reporting is demanded,
     * return the error ENOTCONN
     * Check if an async connect failed already and error reporting is
     * demanded, return the error ENOTCONN.
     */

    if (errorCodePtr != NULL && (statePtr->flags & TCP_ASYNC_FAILED)) {
	*errorCodePtr = ENOTCONN;
	return -1;
    }

599
600
601
602
603
604
605



606
607
608
609
610

611



612
613
614
615





616
617
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
666

667



668
669
670
671
672
673
674
675

676
677
678
679
680
681


682
683
684
685
686
687
688
605
606
607
608
609
610
611
612
613
614
615

616
617
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
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
693
694
695
696
697
698
699

700
701
702
703
704


705
706
707
708
709
710
711
712
713







+
+
+

-



+
-
+
+
+

-
-
-
+
+
+
+
+


-
-
+
+

+
-
-
+
+



+
-
+
+
+



-
-
+
+

+


+
-
+
+
+








-
-
+
+

+
-
+









-
-
+
+








+
-
+
+
+







-
+




-
-
+
+







    oldMode = Tcl_SetServiceMode(TCL_SERVICE_NONE);

    /*
     * Loop in the blocking case until the connect signal is present
     */

    while (1) {
	/*
         * Get the statePtr lock.
         */

	/* get statePtr lock */
        tsdPtr = TclThreadDataKeyGet(&dataKey);
	WaitForSingleObject(tsdPtr->socketListLock, INFINITE);

	/*
	/* Check for connect event */
         * Check for connect event.
         */

	if (statePtr->readyEvents & FD_CONNECT) {

	    /* Consume the connect event */
	    statePtr->readyEvents &= ~(FD_CONNECT);
	    /*
             * Consume the connect event.
             */

	    CLEAR_BITS(statePtr->readyEvents, FD_CONNECT);

	    /*
	     * For blocking sockets and foreground processing
	     * disable async connect as we continue now synchoneously
	     * For blocking sockets and foreground processing, disable async
	     * connect as we continue now synchoneously.
	     */

	    if ( errorCodePtr != NULL &&
		    ! (statePtr->flags & TCP_NONBLOCKING) ) {
	    if (errorCodePtr != NULL &&
		    !(statePtr->flags & TCP_NONBLOCKING)) {
		CLEAR_BITS(statePtr->flags, TCP_ASYNC_CONNECT);
	    }

	    /*
	    /* Free list lock */
             * Free list lock.
             */

	    SetEvent(tsdPtr->socketListLock);

	    /*
	     * Continue connect.
	     * If switched to synchroneous connect, the connect is terminated.
	     * Continue connect. If switched to synchroneous connect, the
	     * connect is terminated.
	     */

	    result = TcpConnect(NULL, statePtr);

	    /*
	    /* Restore event service mode */
             * Restore event service mode.
             */

	    (void) Tcl_SetServiceMode(oldMode);

	    /*
	     * Check for Succesfull connect or async connect restart
	     */

	    if (result == TCL_OK) {
		/*
		 * Check for async connect restart
		 * (not possible for foreground blocking operation)
		 * Check for async connect restart (not possible for
		 * foreground blocking operation)
		 */

		if ( statePtr->flags & TCP_ASYNC_PENDING ) {
		if (statePtr->flags & TCP_ASYNC_PENDING) {
		    if (errorCodePtr != NULL) {
			*errorCodePtr = EWOULDBLOCK;
		    }
		    return -1;
		}
		return 0;
	    }

	    /*
	     * Connect finally failed.
	     * For foreground operation return ENOTCONN.
	     * Connect finally failed. For foreground operation return
	     * ENOTCONN.
	     */

	    if (errorCodePtr != NULL) {
		*errorCodePtr = ENOTCONN;
	    }
	    return -1;
	}

        /*
        /* Free list lock */
         * Free list lock.
         */

        SetEvent(tsdPtr->socketListLock);

	/*
	 * Background operation returns with no action as there was no connect
	 * event
	 */

	if ( errorCodePtr == NULL ) {
	if (errorCodePtr == NULL) {
	    return -1;
	}

	/*
	 * A non blocking socket waiting for an asyncronous connect
	 * returns directly the error EWOULDBLOCK
	 * A non blocking socket waiting for an asyncronous connect returns
	 * directly the error EWOULDBLOCK.
	 */

	if (statePtr->flags & TCP_NONBLOCKING) {
	    *errorCodePtr = EWOULDBLOCK;
	    return -1;
	}

766
767
768
769
770
771
772

773




774
775

776
777
778
779
780
781
782

783
784
785
786
787
788
789
790
791
792
793
794

795
796
797
798
799
800
801
802
803
804
805
806
807

808
809
810
811
812
813
814
791
792
793
794
795
796
797
798

799
800
801
802
803

804
805
806
807
808
809
810

811
812
813
814
815
816
817
818
819
820
821
822

823
824
825
826
827
828
829
830
831
832
833
834
835

836
837
838
839
840
841
842
843







+
-
+
+
+
+

-
+






-
+











-
+












-
+







     * 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) statePtr);
	/*
	/* single fd operation: this proc is only called for a connected socket. */
         * Single fd operation: this proc is only called for a connected
         * socket.
         */

	bytesRead = recv(statePtr->sockets->fd, buf, bufSize, 0);
	statePtr->readyEvents &= ~(FD_READ);
	CLEAR_BITS(statePtr->readyEvents, FD_READ);

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

	if (bytesRead == 0) {
	    statePtr->flags |= SOCKET_EOF;
	    SET_BITS(statePtr->flags, SOCKET_EOF);
	}
	if (bytesRead != SOCKET_ERROR) {
	    break;
	}

	/*
	 * If an error occurs after the FD_CLOSE has arrived, then ignore the
	 * error and report an EOF.
	 */

	if (statePtr->readyEvents & FD_CLOSE) {
	    statePtr->flags |= SOCKET_EOF;
	    SET_BITS(statePtr->flags, SOCKET_EOF);
	    bytesRead = 0;
	    break;
	}

	error = WSAGetLastError();

	/*
	 * If an RST comes, then ignore the error and report an EOF just like
	 * on unix.
	 */

	if (error == WSAECONNRESET) {
	    statePtr->flags |= SOCKET_EOF;
	    SET_BITS(statePtr->flags, SOCKET_EOF);
	    bytesRead = 0;
	    break;
	}

	/*
	 * Check for error condition or underflow in non-blocking case.
	 */
888
889
890
891
892
893
894

895




896
897
898
899
900
901
902
917
918
919
920
921
922
923
924

925
926
927
928
929
930
931
932
933
934
935







+
-
+
+
+
+







	return -1;
    }

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

	/*
	/* single fd operation: this proc is only called for a connected socket. */
         * Single fd operation: this proc is only called for a connected
         * socket.
         */

	written = send(statePtr->sockets->fd, buf, toWrite, 0);
	if (written != 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.
	     */
913
914
915
916
917
918
919
920

921
922
923
924
925
926
927
946
947
948
949
950
951
952

953
954
955
956
957
958
959
960







-
+







	 * need to clear the FD_WRITE flag so we can detect the next writable
	 * event. Note that Windows only sends a new writable event after a
	 * send fails with WSAEWOULDBLOCK.
	 */

	error = WSAGetLastError();
	if (error == WSAEWOULDBLOCK) {
	    statePtr->readyEvents &= ~(FD_WRITE);
	    CLEAR_BITS(statePtr->readyEvents, FD_WRITE);
	    if (statePtr->flags & TCP_NONBLOCKING) {
		*errorCodePtr = EWOULDBLOCK;
		written = -1;
		break;
	    }
	} else {
	    TclWinConvertError(error);
937
938
939
940
941
942
943
944


945
946
947
948
949
950
951
970
971
972
973
974
975
976

977
978
979
980
981
982
983
984
985







-
+
+








	if (!WaitForSocketEvent(statePtr, FD_WRITE|FD_CLOSE, errorCodePtr)) {
	    written = -1;
	    break;
	}
    }

    SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM)SELECT, (LPARAM)statePtr);
    SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM)SELECT,
            (LPARAM)statePtr);

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







-
+

-

+

















+



+


-
-
+
+
+
+




+
-
+
+
+







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

	while ( statePtr->sockets != NULL ) {
	while (statePtr->sockets != NULL) {
	    TcpFdList *thisfd = statePtr->sockets;
	    statePtr->sockets = thisfd->next;

	    statePtr->sockets = thisfd->next;
	    if (closesocket(thisfd->fd) == SOCKET_ERROR) {
		TclWinConvertError((DWORD) WSAGetLastError());
		errorCode = Tcl_GetErrno();
	    }
	    ckfree(thisfd);
	}
    }

    if (statePtr->addrlist != NULL) {
        freeaddrinfo(statePtr->addrlist);
    }
    if (statePtr->myaddrlist != NULL) {
        freeaddrinfo(statePtr->myaddrlist);
    }

    /*
     * Clear an eventual tsd info list pointer.
     *
     * This may be called, if an async socket connect fails or is closed
     * between connect and thread action callback.
     */

    if (tsdPtr->pendingTcpState != NULL
	    && tsdPtr->pendingTcpState == statePtr) {

	/* get infoPtr lock, because this concerns the notifier thread */
	/*
         * Get infoPtr lock, because this concerns the notifier thread.
         */

	WaitForSingleObject(tsdPtr->socketListLock, INFINITE);

	tsdPtr->pendingTcpState = NULL;

	/*
	/* Free list lock */
         * Free list lock.
         */

	SetEvent(tsdPtr->socketListLock);
    }

    /*
     * TIP #218. Removed the code removing the structure from the global
     * socket list. This is now done by the thread action callbacks, and only
     * there. This happens before this code is called. We can free without
1077
1078
1079
1080
1081
1082
1083

1084
1085




1086
1087
1088
1089
1090
1091
1092
1118
1119
1120
1121
1122
1123
1124
1125


1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136







+
-
-
+
+
+
+







	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. */
     * 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(statePtr->sockets->fd, sd) == SOCKET_ERROR) {
	TclWinConvertError((DWORD) WSAGetLastError());
	errorCode = Tcl_GetErrno();
    }

    return errorCode;
}
1130
1131
1132
1133
1134
1135
1136
1137

1138
1139
1140
1141
1142
1143
1144
1174
1175
1176
1177
1178
1179
1180

1181
1182
1183
1184
1185
1186
1187
1188







-
+







	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "winsock is not initialized", -1));
	}
	return TCL_ERROR;
    }

#ifdef TCL_FEATURE_KEEPALIVE_NAGLE
    #error "TCL_FEATURE_KEEPALIVE_NAGLE not reviewed for whether to treat statePtr->sockets as single fd or list"
#error "TCL_FEATURE_KEEPALIVE_NAGLE not reviewed for whether to treat statePtr->sockets as single fd or list"
    sock = statePtr->sockets->fd;

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

	if (Tcl_GetBoolean(interp, value, &boolVar) != TCL_OK) {
1239
1240
1241
1242
1243
1244
1245

1246


1247

1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260


1261
1262
1263
1264


1265
1266
1267
1268
1269


1270
1271
1272

1273
1274
1275
1276
1277
1278
1279
1280
1281

1282
1283
1284
1285
1286
1287
1288
1289

1290

1291
1292
1293

1294
1295
1296


1297

1298
1299
1300

1301
1302

1303

1304
1305
1306


1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321

1322

1323
1324
1325
1326
1327
1328
1329
1330
1331

1332
1333
1334

1335
1336
1337
1338
1339
1340
1341


1342
1343
1344

1345
1346
1347
1348
1349
1350
1351
1283
1284
1285
1286
1287
1288
1289
1290

1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303

1304


1305
1306

1307


1308
1309

1310
1311


1312
1313
1314
1315

1316
1317
1318
1319
1320

1321

1322

1323
1324
1325
1326
1327
1328
1329
1330

1331
1332
1333
1334
1335
1336
1337
1338


1339
1340
1341
1342
1343
1344
1345
1346
1347

1348
1349
1350
1351
1352

1353
1354
1355
1356
1357
1358
1359
1360
1361
1362

1363
1364
1365
1366
1367
1368
1369

1370
1371
1372
1373
1374
1375
1376
1377
1378

1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389

1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402







+
-
+
+

+









-

-
-
+
+
-

-
-
+
+
-


-
-
+
+


-
+




-

-

-
+







-
+

+



+

-
-
+
+

+



+

-
+

+


-
+
+








-






+
-
+








-
+



+






-
+
+



+







		    "winsock is not initialized", -1));
	}
	return TCL_ERROR;
    }

    /*
     * Go one step in async connect
     *
     * If any error is thrown save it as backround error to report eventually below
     * If any error is thrown save it as backround error to report eventually
     * below.
     */

    WaitForConnect(statePtr, NULL);

    sock = statePtr->sockets->fd;
    if (optionName != NULL) {
	len = strlen(optionName);
    }

    if ((len > 1) && (optionName[1] == 'e') &&
	    (strncmp(optionName, "-error", len) == 0)) {

	/*
	* Do not return any errors if async connect is running
	*/
         * Do not return any errors if async connect is running.
         */
	if ( ! (statePtr->flags & TCP_ASYNC_PENDING) ) {


	    if ( statePtr->flags & TCP_ASYNC_FAILED ) {
	if (!(statePtr->flags & TCP_ASYNC_PENDING)) {
	    if (statePtr->flags & TCP_ASYNC_FAILED) {

		/*
		 * In case of a failed async connect, eventually report the
		 * connect error only once.
		 * Do not report the system error, as this comes again and again.
		 * connect error only once.  Do not report the system error,
		 * as this comes again and again.
		 */

		if ( statePtr->connectError != 0 ) {
		if (statePtr->connectError != 0) {
		    Tcl_DStringAppend(dsPtr,
			    Tcl_ErrnoMsg(statePtr->connectError), -1);
		    statePtr->connectError = 0;
		}

	    } else {

		/*
		 * Report an eventual last error of the socket system
		 * Report an eventual last error of the socket system.
		 */

		int optlen;
		int ret;
		DWORD err;

		/*
		 * Populater the err Variable with a possix error
		 * Populate the err variable with a POSIX error
		 */

		optlen = sizeof(int);
		ret = getsockopt(sock, SOL_SOCKET, SO_ERROR,
			(char *)&err, &optlen);

		/*
		 * The error was not returned directly but should be
		 * taken from WSA
		 * The error was not returned directly but should be taken
		 * from WSA.
		 */

		if (ret == SOCKET_ERROR) {
		    err = WSAGetLastError();
		}

		/*
		 * Return error message
		 * Return error message.
		 */

		if (err) {
		    TclWinConvertError(err);
		    Tcl_DStringAppend(dsPtr, Tcl_ErrnoMsg(Tcl_GetErrno()), -1);
		    Tcl_DStringAppend(dsPtr, Tcl_ErrnoMsg(Tcl_GetErrno()),
                            -1);
		}
	    }
	}
	return TCL_OK;
    }

    if ((len > 1) && (optionName[1] == 'c') &&
	    (strncmp(optionName, "-connecting", len) == 0)) {

	Tcl_DStringAppend(dsPtr,
		(statePtr->flags & TCP_ASYNC_PENDING)
		? "1" : "0", -1);
        return TCL_OK;
    }

    if (interp != NULL
    if (interp != NULL && Tcl_GetVar2(interp, SUPPRESS_RDNS_VAR, NULL, 0) != NULL) {
            && Tcl_GetVar2(interp, SUPPRESS_RDNS_VAR, NULL, 0) != NULL) {
	reverseDNS = NI_NUMERICHOST;
    }

    if ((len == 0) || ((len > 1) && (optionName[1] == 'p') &&
	    (strncmp(optionName, "-peername", len) == 0))) {
	address peername;
	socklen_t size = sizeof(peername);

	if ( (statePtr->flags & TCP_ASYNC_PENDING) ) {
	if (statePtr->flags & TCP_ASYNC_PENDING) {
	    /*
	     * In async connect output an empty string
	     */

	    if (len == 0) {
		Tcl_DStringAppendElement(dsPtr, "-peername");
		Tcl_DStringAppendElement(dsPtr, "");
	    } else {
		return TCL_OK;
	    }
	} else if ( getpeername(sock, (LPSOCKADDR) &(peername.sa), &size) == 0) {
	} else if (getpeername(sock, (LPSOCKADDR) &(peername.sa),
                &size) == 0) {
	    /*
	     * Peername fetch succeeded - output list
	     */

	    if (len == 0) {
		Tcl_DStringAppendElement(dsPtr, "-peername");
		Tcl_DStringStartSublist(dsPtr);
	    }

	    getnameinfo(&(peername.sa), size, host, sizeof(host),
		    NULL, 0, NI_NUMERICHOST);
1386
1387
1388
1389
1390
1391
1392
1393

1394
1395
1396

1397

1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412



1413

1414
1415
1416
1417
1418
1419
1420
1437
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
1470
1471
1472
1473
1474







-
+



+
-
+













-
-
+
+
+

+







	socklen_t size;
	int found = 0;

	if (len == 0) {
	    Tcl_DStringAppendElement(dsPtr, "-sockname");
	    Tcl_DStringStartSublist(dsPtr);
	}
	if ( (statePtr->flags & TCP_ASYNC_PENDING ) ) {
	if (statePtr->flags & TCP_ASYNC_PENDING) {
	    /*
	     * In async connect output an empty string
	     */

	     found = 1;
            found = 1;
	} else {
	    for (fds = statePtr->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).
		     * 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,
1490
1491
1492
1493
1494
1495
1496
1497


1498
1499
1500
1501
1502
1503
1504
1544
1545
1546
1547
1548
1549
1550

1551
1552
1553
1554
1555
1556
1557
1558
1559







-
+
+







#endif /*TCL_FEATURE_KEEPALIVE_NAGLE*/

    if (len > 0) {
#ifdef TCL_FEATURE_KEEPALIVE_NAGLE
	return Tcl_BadChannelOption(interp, optionName,
		"connecting peername sockname keepalive nagle");
#else
	return Tcl_BadChannelOption(interp, optionName, "connecting peername sockname");
	return Tcl_BadChannelOption(interp, optionName,
                "connecting peername sockname");
#endif /*TCL_FEATURE_KEEPALIVE_NAGLE*/
    }

    return TCL_OK;
}

/*
1532
1533
1534
1535
1536
1537
1538
1539

1540
1541
1542

1543
1544
1545
1546
1547
1548
1549
1587
1588
1589
1590
1591
1592
1593

1594
1595
1596

1597
1598
1599
1600
1601
1602
1603
1604







-
+


-
+







     * Update the watch events mask. Only if the socket is not a server
     * socket. [Bug 557878]
     */

    if (!statePtr->acceptProc) {
	statePtr->watchEvents = 0;
	if (mask & TCL_READABLE) {
	    statePtr->watchEvents |= (FD_READ|FD_CLOSE);
	    SET_BITS(statePtr->watchEvents, FD_READ | FD_CLOSE);
	}
	if (mask & TCL_WRITABLE) {
	    statePtr->watchEvents |= (FD_WRITE|FD_CLOSE);
	    SET_BITS(statePtr->watchEvents, FD_WRITE | FD_CLOSE);
	}

	/*
	 * If there are any conditions already set, then tell the notifier to
	 * poll rather than block.
	 */

1626
1627
1628
1629
1630
1631
1632
1633
1634
1635




1636
1637
1638
1639



1640
1641
1642
1643
1644
1645
1646
1647

1648
1649
1650



1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664

1665
1666
1667
1668

1669



1670
1671
1672
1673
1674

1675
1676
1677
1678


1679

1680



1681
1682

1683



1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694


1695
1696
1697
1698
1699
1700


1701
1702
1703
1704
1705
1706
1707

1708
1709
1710

1711
1712
1713
1714

1715
1716
1717


1718



1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729


1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741

1742
1743

1744
1745


1746

1747

1748
1749
1750

1751

1752
1753

1754



1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773

1774
1775
1776

1777

1778
1779
1780
1781
1782
1783
1784
1785
1786

1787
1788






1789


1790



1791


1792
1793
1794









1795
1796
1797
1798
1799
1800


1801

1802
1803
1804
1805
1806
1807
1808
1809
1810

1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821

1822
1823
1824
1825

1826
1827

1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841

1842
1843
1844

1845
1846
1847
1848

1849


1850



1851


1852
1853
1854
1855
1856















1857


1858



1859
1860

1861
1862
1863

1864
1865
1866
1867
1868
1869
1870
1681
1682
1683
1684
1685
1686
1687



1688
1689
1690
1691




1692
1693
1694
1695
1696
1697
1698
1699
1700
1701

1702



1703
1704
1705

1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724

1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736

1737
1738
1739
1740

1741
1742
1743
1744
1745
1746

1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759

1760
1761
1762
1763
1764
1765
1766

1767
1768
1769
1770
1771
1772
1773
1774

1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789

1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801


1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819


1820
1821
1822
1823

1824
1825
1826

1827
1828
1829
1830
1831
1832

1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852


1853

1854
1855
1856

1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867


1868
1869
1870
1871
1872
1873
1874
1875
1876

1877
1878
1879
1880
1881
1882



1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895


1896
1897
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
1935
1936
1937


1938

1939
1940
1941
1942
1943
1944
1945
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
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990







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







-
+
-
-
-
+
+
+
-













+




+
-
+
+
+





+



-
+
+

+
-
+
+
+


+
-
+
+
+










-
+
+





-
+
+






-
+



+




+



+
+
-
+
+
+









-
-
+
+












+


+
-
-
+
+

+
-
+


-
+

+


+
-
+
+
+

















-
-
+
-


+
-
+









+
-
-
+
+
+
+
+
+

+
+
-
+
+
+

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




-
-
+
+

+








-
+










-
+


-
-
+


+












-
-
+
-


+




+

+
+
-
+
+
+

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

+
+
-
+
+
+


+



+








static int
TcpConnect(
    Tcl_Interp *interp,		/* For error reporting; can be NULL. */
    TcpState *statePtr)
{
    DWORD error;
    /*
     * We are started with async connect and the connect notification
     * was not jet received
    int async_connect = statePtr->flags & TCP_ASYNC_CONNECT;
                                /* We are started with async connect and the
                                 * connect notification was not yet
                                 * received. */
     */
    int async_connect = statePtr->flags & TCP_ASYNC_CONNECT;
    /* We were called by the event procedure and continue our loop */
    int async_callback = statePtr->flags & TCP_ASYNC_PENDING;
    int async_callback = statePtr->flags & TCP_ASYNC_PENDING;
                                /* We were called by the event procedure and
                                 * continue our loop. */
    ThreadSpecificData *tsdPtr = TclThreadDataKeyGet(&dataKey);

    if (async_callback) {
        goto reenter;
    }

    for (statePtr->addr = statePtr->addrlist; statePtr->addr != NULL;
	 statePtr->addr = statePtr->addr->ai_next) {
	    statePtr->addr = statePtr->addr->ai_next) {

        for (statePtr->myaddr = statePtr->myaddrlist; statePtr->myaddr != NULL;
	     statePtr->myaddr = statePtr->myaddr->ai_next) {
        for (statePtr->myaddr = statePtr->myaddrlist;
                statePtr->myaddr != NULL;
                statePtr->myaddr = statePtr->myaddr->ai_next) {

	    /*
	     * No need to try combinations of local and remote addresses
	     * of different families.
	     */

	    if (statePtr->myaddr->ai_family != statePtr->addr->ai_family) {
		continue;
	    }

            /*
             * Close the socket if it is still open from the last unsuccessful
             * iteration.
             */

	    if (statePtr->sockets->fd != INVALID_SOCKET) {
		closesocket(statePtr->sockets->fd);
	    }

	    /*
	    /* get statePtr lock */
             * Get statePtr lock.
             */

	    WaitForSingleObject(tsdPtr->socketListLock, INFINITE);

	    /*
	     * Reset last error from last try
	     */

	    statePtr->notifierConnectError = 0;
	    Tcl_SetErrno(0);

	    statePtr->sockets->fd = socket(statePtr->myaddr->ai_family, SOCK_STREAM, 0);
	    statePtr->sockets->fd = socket(statePtr->myaddr->ai_family,
                    SOCK_STREAM, 0);

	    /*
	    /* Free list lock */
             * Free list lock.
             */

	    SetEvent(tsdPtr->socketListLock);

	    /*
	    /* continue on socket creation error */
             * Continue on socket creation error.
             */

	    if (statePtr->sockets->fd == INVALID_SOCKET) {
		TclWinConvertError((DWORD) WSAGetLastError());
		continue;
	    }

	    /*
	     * Win-NT has a misfeature that sockets are inherited in child
	     * processes by default. Turn off the inherit bit.
	     */

	    SetHandleInformation((HANDLE) statePtr->sockets->fd, HANDLE_FLAG_INHERIT, 0);
	    SetHandleInformation((HANDLE) statePtr->sockets->fd,
                    HANDLE_FLAG_INHERIT, 0);

	    /*
	     * Set kernel space buffering
	     */

	    TclSockMinimumBuffers((void *) statePtr->sockets->fd, TCP_BUFFER_SIZE);
	    TclSockMinimumBuffers((void *) statePtr->sockets->fd,
                    TCP_BUFFER_SIZE);

	    /*
	     * Try to bind to a local port.
	     */

	    if (bind(statePtr->sockets->fd, statePtr->myaddr->ai_addr,
			statePtr->myaddr->ai_addrlen) == SOCKET_ERROR) {
		    statePtr->myaddr->ai_addrlen) == SOCKET_ERROR) {
		TclWinConvertError((DWORD) WSAGetLastError());
		continue;
	    }

	    /*
	     * For asyncroneous connect set the socket in nonblocking mode
	     * and activate connect notification
	     */

	    if (async_connect) {
		TcpState *statePtr2;
		int in_socket_list = 0;

		/*
		/* get statePtr lock */
                 * Get statePtr lock.
                 */

		WaitForSingleObject(tsdPtr->socketListLock, INFINITE);

		/*
		 * Bugfig for 336441ed59 to not ignore notifications until the
		 * infoPtr is in the list.
		 * Check if my statePtr is already in the tsdPtr->socketList
		 * It is set after this call by TcpThreadActionProc and is set
		 * on a second round.
		 *
		 * If not, we buffer my statePtr in the tsd memory so it is not
		 * lost by the event procedure
		 * If not, we buffer my statePtr in the tsd memory so it is
		 * not lost by the event procedure
		 */

		for (statePtr2 = tsdPtr->socketList; statePtr2 != NULL;
			statePtr2 = statePtr2->nextPtr) {
		    if (statePtr2 == statePtr) {
			in_socket_list = 1;
			break;
		    }
		}
		if (!in_socket_list) {
		    tsdPtr->pendingTcpState = statePtr;
		}

		/*
		 * Set connect mask to connect events
                 *
		 * This is activated by a SOCKET_SELECT message to the notifier
		 * thread.
		 * This is activated by a SOCKET_SELECT message to the
		 * notifier thread.
		 */

		statePtr->selectEvents |= FD_CONNECT;
		SET_BITS(statePtr->selectEvents, FD_CONNECT);

		/*
		 * Free list lock
		 * Free list lock.
		 */

		SetEvent(tsdPtr->socketListLock);

    		/*
    		/* activate accept notification */
                 * Activate accept notification.
                 */

		SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM) SELECT,
			(LPARAM) statePtr);
	    }

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

	    connect(statePtr->sockets->fd, statePtr->addr->ai_addr,
		    statePtr->addr->ai_addrlen);

	    error = WSAGetLastError();
	    TclWinConvertError(error);

	    if (async_connect && error == WSAEWOULDBLOCK) {
		/*
		 * Asynchroneous connect
		 */

		 *
		/*
		 * Remember that we jump back behind this next round
		 */

		statePtr->flags |= TCP_ASYNC_PENDING;
		SET_BITS(statePtr->flags, TCP_ASYNC_PENDING);
		return TCL_OK;

	    reenter:
		/*
		 * Re-entry point for async connect after connect event or
		 * blocking operation
		 *
		 * Clear the reenter flag
		 */

		statePtr->flags &= ~(TCP_ASYNC_PENDING);
		/* get statePtr lock */
		CLEAR_BITS(statePtr->flags, TCP_ASYNC_PENDING);

		/*
                 * Get statePtr lock.
                 */

		WaitForSingleObject(tsdPtr->socketListLock, INFINITE);

		/*
		/* Get signaled connect error */
                 * Get signaled connect error.
                 */

		TclWinConvertError((DWORD) statePtr->notifierConnectError);

		/*
		/* Clear eventual connect flag */
		statePtr->selectEvents &= ~(FD_CONNECT);
		/* Free list lock */
                 * Clear eventual connect flag.
                 */

		CLEAR_BITS(statePtr->selectEvents, FD_CONNECT);

		/*
                 * Free list lock.
                 */

		SetEvent(tsdPtr->socketListLock);
	    }

	    /*
	     * Clear the tsd socket list pointer if we did not wait for
	     * the FD_CONNECT asyncroneously
	     * Clear the tsd socket list pointer if we did not wait for the
	     * FD_CONNECT asynchronously.
	     */

	    tsdPtr->pendingTcpState = NULL;

	    if (Tcl_GetErrno() == 0) {
		goto out;
	    }
	}
    }

out:
  out:
    /*
     * Socket connected or connection failed
     */

    /*
     * Async connect terminated
     */

    CLEAR_BITS(statePtr->flags, TCP_ASYNC_CONNECT);

    if ( Tcl_GetErrno() == 0 ) {
    if (Tcl_GetErrno() == 0) {
	/*
	 * Succesfully connected
	 */
	/*
	 *
	 * Set up the select mask for read/write events.
	 */

	statePtr->selectEvents = FD_READ | FD_WRITE | FD_CLOSE;

	/*
	 * Register for interest in events in the select mask. Note that this
	 * automatically places the socket into non-blocking mode.
	 */

	SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM) SELECT,
		    (LPARAM) statePtr);
    } else {
	/*
	 * Connect failed
	 */

	 *
	/*
	 * For async connect schedule a writable event to report the fail.
	 */

	if (async_callback) {
	    /*
	     * Set up the select mask for read/write events.
	     */

	    statePtr->selectEvents = FD_WRITE|FD_READ;

	    /*
	    /* get statePtr lock */
             * Get statePtr lock.
             */

	    WaitForSingleObject(tsdPtr->socketListLock, INFINITE);

	    /*
	    /* Signal ready readable and writable events */
	    statePtr->readyEvents |= FD_WRITE | FD_READ;
	    /* Flag error to event routine */
	    statePtr->flags |= TCP_ASYNC_FAILED;
	    /* Save connect error to be reported by 'fconfigure -error' */
             * Signal ready readable and writable events.
             */

	    SET_BITS(statePtr->readyEvents, FD_WRITE | FD_READ);

	    /*
             * Flag error to event routine.
             */

	    SET_BITS(statePtr->flags, TCP_ASYNC_FAILED);

	    /*
             * Save connect error to be reported by 'fconfigure -error'.
             */

	    statePtr->connectError = Tcl_GetErrno();

	    /*
	    /* Free list lock */
             * Free list lock.
             */

	    SetEvent(tsdPtr->socketListLock);
	}

	/*
	 * Error message on syncroneous connect
	 */

	if (interp != NULL) {
	    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		    "couldn't open socket: %s", Tcl_PosixError(interp)));
	}
	return TCL_ERROR;
    }
    return TCL_OK;
1934
1935
1936
1937
1938
1939
1940
1941

1942
1943
1944
1945
1946
1947
1948
2054
2055
2056
2057
2058
2059
2060

2061
2062
2063
2064
2065
2066
2067
2068







-
+







        return NULL;
    }

    statePtr = NewSocketInfo(INVALID_SOCKET);
    statePtr->addrlist = addrlist;
    statePtr->myaddrlist = myaddrlist;
    if (async) {
	statePtr->flags |= TCP_ASYNC_CONNECT;
	SET_BITS(statePtr->flags, TCP_ASYNC_CONNECT);
    }

    /*
     * Create a new client socket and wrap it in a channel.
     */
    if (TcpConnect(interp, statePtr) != TCL_OK) {
	TcpCloseProc(statePtr, NULL);
2004
2005
2006
2007
2008
2009
2010
2011


2012
2013
2014
2015
2016
2017
2018
2124
2125
2126
2127
2128
2129
2130

2131
2132
2133
2134
2135
2136
2137
2138
2139







-
+
+







    statePtr = NewSocketInfo((SOCKET) sock);

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

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

    sprintf(channelName, SOCK_TEMPLATE, statePtr);
    statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
	    statePtr, (TCL_READABLE | TCL_WRITABLE));
    Tcl_SetChannelOption(NULL, statePtr->channel, "-translation", "auto crlf");
    return statePtr->channel;
}
2074
2075
2076
2077
2078
2079
2080
2081


2082
2083
2084
2085
2086
2087
2088
2195
2196
2197
2198
2199
2200
2201

2202
2203
2204
2205
2206
2207
2208
2209
2210







-
+
+







     */

    if (TclSockGetPort(interp, service, "tcp", &port) != TCL_OK) {
	errorMsg = "invalid port number";
	goto error;
    }

    if (!TclCreateSocketAddress(interp, &addrlist, myHost, port, 1, &errorMsg)) {
    if (!TclCreateSocketAddress(interp, &addrlist, myHost, port, 1,
            &errorMsg)) {
	goto error;
    }

    for (addrPtr = addrlist; addrPtr != NULL; addrPtr = addrPtr->ai_next) {
	sock = socket(addrPtr->ai_family, addrPtr->ai_socktype,
                addrPtr->ai_protocol);
	if (sock == INVALID_SOCKET) {
2113
2114
2115
2116
2117
2118
2119
2120
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
2235
2236
2237
2238
2239
2240
2241


2242
2243
2244
2245
2246
2247
2248

2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259


2260
2261
2262
2263
2264
2265
2266
2267
2268







-
-
+
+

+



-
+










-
-
+
+








	if (port == 0 && chosenport != 0) {
	    ((struct sockaddr_in *) addrPtr->ai_addr)->sin_port =
		htons(chosenport);
	}

	/*
	 * The SO_REUSEADDR option on Windows behaves like SO_REUSEPORT on unix
	 * systems.
	 * The SO_REUSEADDR option on Windows behaves like SO_REUSEPORT on
	 * unix systems.
	 */

	if (flags & TCL_TCPSERVER_REUSEPORT) {
	    optvalue = 1;
	    (void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
			      (char *) &optvalue, sizeof(optvalue));
		    (char *) &optvalue, sizeof(optvalue));
	}

	/*
	 * Bind to the specified port.
	 *
	 * 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) {
	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);
2166
2167
2168
2169
2170
2171
2172

2173
2174
2175

2176
2177
2178
2179

2180
2181
2182
2183
2184
2185
2186
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298

2299
2300
2301
2302

2303
2304
2305
2306
2307
2308
2309
2310







+


-
+



-
+







	    continue;
	}

	if (statePtr == NULL) {
	    /*
	     * Add this socket to the global list of sockets.
	     */

	    statePtr = NewSocketInfo(sock);
	} else {
	    AddSocketInfoFd( statePtr, sock );
	    AddSocketInfoFd(statePtr, sock);
	}
    }

error:
  error:
    if (addrlist != NULL) {
	freeaddrinfo(addrlist);
    }

    if (statePtr != NULL) {
	ThreadSpecificData *tsdPtr = TclThreadDataKeyGet(&dataKey);

2198
2199
2200
2201
2202
2203
2204
2205

2206
2207
2208
2209
2210
2211
2212
2322
2323
2324
2325
2326
2327
2328

2329
2330
2331
2332
2333
2334
2335
2336







-
+







	/*
	 * 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) statePtr);
		(LPARAM) statePtr);
	if (Tcl_SetChannelOption(interp, statePtr->channel, "-eofchar", "")
	    == TCL_ERROR) {
	    Tcl_Close(NULL, statePtr->channel);
	    return NULL;
	}
	return statePtr->channel;
    }
2560
2561
2562
2563
2564
2565
2566
2567

2568
2569

2570
2571
2572
2573
2574
2575
2576
2684
2685
2686
2687
2688
2689
2690

2691


2692
2693
2694
2695
2696
2697
2698
2699







-
+
-
-
+







     */

    WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
    for (statePtr = tsdPtr->socketList; statePtr != NULL;
	    statePtr = statePtr->nextPtr) {
	if ((statePtr->readyEvents &
		(statePtr->watchEvents | FD_CONNECT | FD_ACCEPT))
	    && !(statePtr->flags & SOCKET_PENDING)
                && !(statePtr->flags & SOCKET_PENDING)) {
	) {
	    statePtr->flags |= SOCKET_PENDING;
	    SET_BITS(statePtr->flags, SOCKET_PENDING);
	    evPtr = ckalloc(sizeof(SocketEvent));
	    evPtr->header.proc = SocketEventProc;
	    evPtr->socket = statePtr->sockets->fd;
	    Tcl_QueueEvent((Tcl_Event *) evPtr, TCL_QUEUE_TAIL);
	}
    }
    SetEvent(tsdPtr->socketListLock);
2637
2638
2639
2640
2641
2642
2643
2644

2645
2646
2647
2648
2649
2650
2651


2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666

2667
2668
2669
2670
2671
2672
2673
2674

2675
2676
2677
2678
2679
2680


2681
2682

2683
2684

2685
2686
2687
2688






2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702



2703

2704
2705
2706
2707

2708
2709
2710
2711

2712
2713
2714
2715
2716





2717

2718
2719
2720
2721

2722

2723
2724
2725
2726

2727
2728

2729
2730
2731
2732
2733
2734
2735
2760
2761
2762
2763
2764
2765
2766

2767
2768
2769
2770
2771
2772


2773
2774

2775
2776
2777
2778
2779
2780

2781

2782
2783
2784
2785

2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797

2798


2799
2800

2801
2802
2803
2804
2805




2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822



2823
2824
2825
2826
2827
2828
2829
2830

2831
2832
2833
2834
2835
2836





2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848

2849
2850
2851
2852
2853
2854
2855

2856
2857
2858
2859
2860
2861
2862
2863







-
+





-
-
+
+
-






-

-




-
+








+


-

-
-
+
+
-

+


+
-
-
-
-
+
+
+
+
+
+











-
-
-
+
+
+

+



-
+




+
-
-
-
-
-
+
+
+
+
+

+




+
-
+




+

-
+







	return 1;
    }

    /*
     * Clear flag that (this) event is pending
     */

    statePtr->flags &= ~SOCKET_PENDING;
    CLEAR_BITS(statePtr->flags, SOCKET_PENDING);

    /*
     * Continue async connect if pending and ready
     */

    if ( statePtr->readyEvents & FD_CONNECT ) {
	if ( statePtr->flags & TCP_ASYNC_PENDING ) {
    if (statePtr->readyEvents & FD_CONNECT) {
	if (statePtr->flags & TCP_ASYNC_PENDING) {

	    /*
	     * Do one step and save eventual connect error
	     */

	    SetEvent(tsdPtr->socketListLock);
	    WaitForConnect(statePtr,NULL);

	} else {

	    /*
	     * No async connect reenter pending. Just clear event.
	     */

	    statePtr->readyEvents &= ~(FD_CONNECT);
	    CLEAR_BITS(statePtr->readyEvents, FD_CONNECT);
	    SetEvent(tsdPtr->socketListLock);
	}
	return 1;
    }

    /*
     * Handle connection requests directly.
     */

    if (statePtr->readyEvents & FD_ACCEPT) {
	for (fds = statePtr->sockets; fds != NULL; fds = fds->next) {

	    /*
	    * Accept the incoming connection request.
	    */
             * Accept the incoming connection request.
             */
	    len = sizeof(address);

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

	    statePtr->acceptEventCount--;

	    if (statePtr->acceptEventCount <= 0) {
		statePtr->readyEvents &= ~(FD_ACCEPT);
		CLEAR_BITS(statePtr->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 statePtr and fds.
	     * If TcpAccept() accepts a socket we must return immediately and let
	     * SocketCheckProc queue additional FD_ACCEPT events.
             * 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 statePtr 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
         * 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.
	 */

	statePtr->acceptEventCount = 0;
	statePtr->readyEvents &= ~(FD_ACCEPT);
	CLEAR_BITS(statePtr->readyEvents, FD_ACCEPT);

	SetEvent(tsdPtr->socketListLock);
	return 1;
    }

    SetEvent(tsdPtr->socketListLock);

2750
2751
2752
2753
2754
2755
2756
2757

2758
2759
2760
2761
2762
2763
2764

2765
2766

2767
2768
2769
2770
2771
2772
2773
2878
2879
2880
2881
2882
2883
2884

2885
2886
2887
2888
2889
2890
2891

2892


2893
2894
2895
2896
2897
2898
2899
2900







-
+






-
+
-
-
+







	 * a redundant trip through the event loop, but it's simpler than
	 * trying to do unwind protection.
	 */

	Tcl_Time blockTime = { 0, 0 };

	Tcl_SetMaxBlockTime(&blockTime);
	mask |= TCL_READABLE|TCL_WRITABLE;
	SET_BITS(mask, TCL_READABLE | TCL_WRITABLE);
    } else if (events & FD_READ) {

	/*
	 * Throw the readable event if an async connect failed.
	 */

	if ( statePtr->flags & TCP_ASYNC_FAILED ) {
	if (statePtr->flags & TCP_ASYNC_FAILED) {

	    mask |= TCL_READABLE;
	    SET_BITS(mask, TCL_READABLE);

	} else {
	    fd_set readFds;
	    struct timeval timeout;

	    /*
	     * We must check to see if data is really available, since someone
2782
2783
2784
2785
2786
2787
2788
2789

2790
2791

2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803

2804
2805
2806
2807
2808
2809
2810
2909
2910
2911
2912
2913
2914
2915

2916
2917

2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929

2930
2931
2932
2933
2934
2935
2936
2937







-
+

-
+











-
+








	    FD_ZERO(&readFds);
	    FD_SET(statePtr->sockets->fd, &readFds);
	    timeout.tv_usec = 0;
	    timeout.tv_sec = 0;

	    if (select(0, &readFds, NULL, NULL, &timeout) != 0) {
		mask |= TCL_READABLE;
		SET_BITS(mask, TCL_READABLE);
	    } else {
		statePtr->readyEvents &= ~(FD_READ);
		CLEAR_BITS(statePtr->readyEvents, FD_READ);
		SendMessage(tsdPtr->hwnd, SOCKET_SELECT,
			(WPARAM) SELECT, (LPARAM) statePtr);
	    }
	}
    }

    /*
     * writable event
     */

    if (events & FD_WRITE) {
	mask |= TCL_WRITABLE;
	SET_BITS(mask, TCL_WRITABLE);
    }

    /*
     * Call registered event procedures
     */

    if (mask) {
2833
2834
2835
2836
2837
2838
2839
2840
2841





2842
2843
2844

2845
2846




2847
2848
2849
2850
2851
2852
2853

2854



2855
2856
2857
2858
2859
2860
2861
2960
2961
2962
2963
2964
2965
2966


2967
2968
2969
2970
2971
2972
2973
2974
2975


2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987

2988
2989
2990
2991
2992
2993
2994
2995
2996
2997







-
-
+
+
+
+
+



+
-
-
+
+
+
+







+
-
+
+
+







static void
AddSocketInfoFd(
    TcpState *statePtr,
    SOCKET socket)
{
    TcpFdList *fds = statePtr->sockets;

    if ( fds == NULL ) {
	/* Add the first FD */
    if (fds == NULL) {
	/*
         * Add the first FD.
         */

	statePtr->sockets = ckalloc(sizeof(TcpFdList));
	fds = statePtr->sockets;
    } else {
	/*
	/* Find end of list and append FD */
	while ( fds->next != NULL ) {
         * 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 */
     * Populate new FD.
     */

    fds->fd = socket;
    fds->statePtr = statePtr;
    fds->next = NULL;
}


/*
2917
2918
2919
2920
2921
2922
2923

2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941

2942



2943
2944

2945



2946
2947

2948



2949
2950

2951



2952
2953
2954
2955

2956



2957
2958
2959
2960
2961
2962
2963
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079

3080
3081
3082
3083
3084
3085

3086
3087
3088
3089
3090
3091

3092
3093
3094
3095
3096
3097

3098
3099
3100
3101
3102
3103
3104
3105

3106
3107
3108
3109
3110
3111
3112
3113
3114
3115







+


















+
-
+
+
+


+
-
+
+
+


+
-
+
+
+


+
-
+
+
+




+
-
+
+
+







				 * FD_READ or FD_WRITE.
				 */
    int *errorCodePtr)		/* Where to store errors? */
{
    int result = 1;
    int oldMode;
    ThreadSpecificData *tsdPtr = TclThreadDataKeyGet(&dataKey);

    /*
     * Be sure to disable event servicing so we are truly modal.
     */

    oldMode = Tcl_SetServiceMode(TCL_SERVICE_NONE);

    /*
     * Reset WSAAsyncSelect so we have a fresh set of events pending.
     */

    SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM) UNSELECT,
	    (LPARAM) statePtr);
    SendMessage(tsdPtr->hwnd, SOCKET_SELECT, (WPARAM) SELECT,
	    (LPARAM) statePtr);

    while (1) {
	int event_found;

	/*
	/* get statePtr lock */
         * Get statePtr lock.
         */

	WaitForSingleObject(tsdPtr->socketListLock, INFINITE);

	/*
	/* Check if event occured */
         * Check if event occured.
         */

	event_found = (statePtr->readyEvents & events);

	/*
	/* Free list lock */
         * Free list lock.
         */

	SetEvent(tsdPtr->socketListLock);

	/*
	/* exit loop if event occured */
         * Exit loop if event occured.
         */

	if (event_found) {
	    break;
	}

	/*
	/* Exit loop if event did not occur but this is a non-blocking channel */
         * Exit loop if event did not occur but this is a non-blocking channel
         */

	if (statePtr->flags & TCP_NONBLOCKING) {
	    *errorCodePtr = EWOULDBLOCK;
	    result = 0;
	    break;
	}

	/*
3106
3107
3108
3109
3110
3111
3112
3113

3114
3115
3116
3117

3118
3119

3120
3121

3122

3123
3124

3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135


3136
3137
3138
3139
3140

3141
3142
3143
3144
3145
3146
3147
3148
3149

3150
3151
3152
3153

3154
3155
3156

3157

3158
3159
3160
3161

3162
3163
3164
3165
3166
3167
3168
3258
3259
3260
3261
3262
3263
3264

3265
3266
3267
3268
3269
3270
3271

3272

3273
3274

3275
3276

3277
3278
3279
3280
3281

3282
3283
3284
3285


3286
3287
3288
3289
3290
3291

3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311

3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324







-
+




+

-
+
-

+
-
+

-
+




-




-
-
+
+




-
+









+




+



+
-
+




+







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

	for (statePtr = tsdPtr->socketList; statePtr != NULL;
		statePtr = statePtr->nextPtr) {
	    if ( FindFDInList(statePtr,socket) ) {
	    if (FindFDInList(statePtr, socket)) {
		info_found = 1;
		break;
	    }
	}

	/*
	 * Check if there is a pending info structure not jet in the
	 * Check if there is a pending info structure not jet in the list.
	 * list
	 */

	if ( !info_found
	if (!info_found
		&& tsdPtr->pendingTcpState != NULL
		&& FindFDInList(tsdPtr->pendingTcpState,socket) ) {
		&& FindFDInList(tsdPtr->pendingTcpState, socket)) {
	    statePtr = tsdPtr->pendingTcpState;
	    info_found = 1;
	}
	if (info_found) {

	    /*
	     * 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.
	     * happens, then clear the FD_ACCEPT count. Otherwise, increment
	     * the count if the current event is an FD_ACCEPT.
	     */

	    if (event & FD_CLOSE) {
		statePtr->acceptEventCount = 0;
		statePtr->readyEvents &= ~(FD_WRITE|FD_ACCEPT);
		CLEAR_BITS(statePtr->readyEvents, FD_WRITE | FD_ACCEPT);
	    } else if (event & FD_ACCEPT) {
		statePtr->acceptEventCount++;
	    }

	    if (event & FD_CONNECT) {
		/*
		 * Remember any error that occurred so we can report
		 * connection failures.
		 */

		if (error != ERROR_SUCCESS) {
		    statePtr->notifierConnectError = error;
		}
	    }

	    /*
	     * Inform main thread about signaled events
	     */

	    statePtr->readyEvents |= event;
	    SET_BITS(statePtr->readyEvents, event);

	    /*
	     * Wake up the Main Thread.
	     */

	    SetEvent(tsdPtr->readyEvent);
	    Tcl_ThreadAlert(tsdPtr->threadId);
	}
	SetEvent(tsdPtr->socketListLock);
	break;

    case SOCKET_SELECT: