This repository has been archived by the owner on Jul 6, 2021. It is now read-only.
forked from nevali/opencflite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCFSocket.c
2387 lines (2202 loc) · 96.5 KB
/
CFSocket.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
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
587
588
589
590
591
592
593
594
595
596
597
598
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
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
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
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
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
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
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
/*
* Copyright (c) 2008-2009 Brent Fulgham <bfulgham@gmail.org>. All rights reserved.
*
* This source code is a modified version of the CoreFoundation sources released by Apple Inc. under
* the terms of the APSL version 2.0 (see below).
*
* For information about changes from the original Apple source release can be found by reviewing the
* source control system for the project at https://sourceforge.net/svn/?group_id=246198.
*
* The original license information is as follows:
*
* Copyright (c) 2008 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/* CFSocket.c
Copyright (c) 1999-2007 Apple Inc. All rights reserved.
Responsibility: Christopher Kane
*/
#define _DARWIN_UNLIMITED_SELECT 1
#include <CoreFoundation/CFSocket.h>
#include <sys/types.h>
#include <math.h>
#include <limits.h>
#include <CoreFoundation/CFArray.h>
#include <CoreFoundation/CFData.h>
#include <CoreFoundation/CFDictionary.h>
#include <CoreFoundation/CFRunLoop.h>
#include <CoreFoundation/CFString.h>
#include <CoreFoundation/CFPropertyList.h>
#include "CFInternal.h"
#if DEPLOYMENT_TARGET_MACOSX
#include <libc.h>
#include <dlfcn.h>
#define SOCK_DATA_TYPE uint8_t*
#elif DEPLOYMENT_TARGET_WINDOWS
#include <winsock2.h>
#include <ws2tcpip.h>
#include <fcntl.h>
#include <io.h>
#include <stdio.h>
// Careful with remapping these - different WinSock routines return different errors than
// on BSD, so if these are used many places they won't work.
#define EINPROGRESS WSAEINPROGRESS
#ifdef EBADF
#undef EBADF
#endif
#define EBADF WSAENOTSOCK
extern void gettimeofday(struct timeval *tv, void *dummy);
#elif DEPLOYMENT_TARGET_LINUX
#include <dlfcn.h>
#include <fcntl.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/param.h>
#include <sys/socket.h>
#endif /* DEPLOYMENT_TARGET_MACOSX */
#include "auto_stubs.h"
#if defined(DEBUG)
#include <stdio.h>
#endif
#if DEPLOYMENT_TARGET_WINDOWS
/* Use crazy Microsoft signatures */
#define SOCK_DATA char*
#define SOCK_CONST_DATA const char*
#define read _read
/* The following macro is from:
* The olsr.org Optimized Link-State Routing daemon (olsrd)
* Copyright (c) 2004, Thomas Lopatic (thomas@lopatic.de)
* All rights reserved.
*
* BSD license
*/
#define timersub(x, y, z) \
do \
{ \
(z)->tv_sec = (x)->tv_sec - (y)->tv_sec; \
\
(z)->tv_usec = (x)->tv_usec - (y)->tv_usec; \
\
if ((z)->tv_usec < 0) \
{ \
(z)->tv_sec--; \
(z)->tv_usec += 1000000; \
} \
} \
while (0)
#else
#define SOCK_DATA void*
#define SOCK_CONST_DATA const void*
#endif
// On Mach we use a v0 RunLoopSource to make client callbacks. That source is signalled by a
// separate SocketManager thread who uses select() to watch the sockets' fds.
//#define LOG_CFSOCKET
#if !DEPLOYMENT_TARGET_WINDOWS
#define INVALID_SOCKET (CFSocketNativeHandle)(-1)
#endif
enum {
kCFSocketLeaveErrors = 64 // candidate for publicization in future
};
static uint16_t __CFSocketDefaultNameRegistryPortNumber = 2454;
CONST_STRING_DECL(kCFSocketCommandKey, "Command")
CONST_STRING_DECL(kCFSocketNameKey, "Name")
CONST_STRING_DECL(kCFSocketValueKey, "Value")
CONST_STRING_DECL(kCFSocketResultKey, "Result")
CONST_STRING_DECL(kCFSocketErrorKey, "Error")
CONST_STRING_DECL(kCFSocketRegisterCommand, "Register")
CONST_STRING_DECL(kCFSocketRetrieveCommand, "Retrieve")
CONST_STRING_DECL(__kCFSocketRegistryRequestRunLoopMode, "CFSocketRegistryRequest")
#if DEPLOYMENT_TARGET_WINDOWS
static Boolean __CFSocketWinSockInitialized = false;
#else
#define closesocket(a) close((a))
#define ioctlsocket(a,b,c) ioctl((a),(b),(c))
#endif
CF_INLINE int __CFSocketLastError(void) {
#if DEPLOYMENT_TARGET_WINDOWS
return WSAGetLastError();
#else
return thread_errno();
#endif
}
CF_INLINE CFIndex __CFSocketFdGetSize(CFDataRef fdSet) {
#if DEPLOYMENT_TARGET_WINDOWS
fd_set* set = (fd_set*)CFDataGetBytePtr(fdSet);
return set ? set->fd_count : 0;
#else
return NBBY * CFDataGetLength(fdSet);
#endif
}
CF_INLINE Boolean __CFSocketFdSet(CFSocketNativeHandle sock, CFMutableDataRef fdSet) {
/* returns true if a change occurred, false otherwise */
Boolean retval = false;
if (INVALID_SOCKET != sock && 0 <= sock) {
#if DEPLOYMENT_TARGET_WINDOWS
fd_set* set = (fd_set*)CFDataGetMutableBytePtr(fdSet);
if ((set->fd_count * sizeof(SOCKET) + sizeof(u_int)) >= CFDataGetLength(fdSet)) {
CFDataIncreaseLength(fdSet, sizeof(SOCKET));
set = (fd_set*)CFDataGetMutableBytePtr(fdSet);
}
if (!FD_ISSET(sock, set)) {
retval = true;
FD_SET(sock, set);
}
#else
CFIndex numFds = NBBY * CFDataGetLength(fdSet);
fd_mask *fds_bits;
if (sock >= numFds) {
CFIndex oldSize = numFds / NFDBITS, newSize = (sock + NFDBITS) / NFDBITS, changeInBytes = (newSize - oldSize) * sizeof(fd_mask);
CFDataIncreaseLength(fdSet, changeInBytes);
fds_bits = (fd_mask *)CFDataGetMutableBytePtr(fdSet);
memset(fds_bits + oldSize, 0, changeInBytes);
} else {
fds_bits = (fd_mask *)CFDataGetMutableBytePtr(fdSet);
}
if (!FD_ISSET(sock, (fd_set *)fds_bits)) {
retval = true;
FD_SET(sock, (fd_set *)fds_bits);
}
#endif
}
return retval;
}
#define NEW_SOCKET 0
#if NEW_SOCKET
__private_extern__ void __CFSocketInitialize(void) {}
#else
#define MAX_SOCKADDR_LEN 256
#define MAX_DATA_SIZE 65535
#define MAX_CONNECTION_ORIENTED_DATA_SIZE 32768
/* locks are to be acquired in the following order:
(1) __CFAllSocketsLock
(2) an individual CFSocket's lock
(3) __CFActiveSocketsLock
*/
static CFSpinLock_t __CFAllSocketsLock = CFSpinLockInit; /* controls __CFAllSockets */
static CFMutableDictionaryRef __CFAllSockets = NULL;
static CFSpinLock_t __CFActiveSocketsLock = CFSpinLockInit; /* controls __CFRead/WriteSockets, __CFRead/WriteSocketsFds, __CFSocketManagerThread, and __CFSocketManagerIteration */
static volatile UInt32 __CFSocketManagerIteration = 0;
static CFMutableArrayRef __CFWriteSockets = NULL;
static CFMutableArrayRef __CFReadSockets = NULL;
static CFMutableDataRef __CFWriteSocketsFds = NULL;
static CFMutableDataRef __CFReadSocketsFds = NULL;
#if DEPLOYMENT_TARGET_WINDOWS
// We need to select on exceptFDs on Win32 to hear of connect failures
static CFMutableDataRef __CFExceptSocketsFds = NULL;
#endif
static CFDataRef zeroLengthData = NULL;
static Boolean __CFReadSocketsTimeoutInvalid = true; /* rebuild the timeout value before calling select */
static CFSocketNativeHandle __CFWakeupSocketPair[2] = {INVALID_SOCKET, INVALID_SOCKET};
static void *__CFSocketManagerThread = NULL;
static CFTypeID __kCFSocketTypeID = _kCFRuntimeNotATypeID;
static void __CFSocketDoCallback(CFSocketRef s, CFDataRef data, CFDataRef address, CFSocketNativeHandle sock);
struct __CFSocket {
CFRuntimeBase _base;
struct {
unsigned client:8; // flags set by client (reenable, CloseOnInvalidate)
unsigned disabled:8; // flags marking disabled callbacks
unsigned connected:1; // Are we connected yet? (also true for connectionless sockets)
unsigned writableHint:1; // Did the polling the socket show it to be writable?
unsigned closeSignaled:1; // Have we seen FD_CLOSE? (only used on Win32)
unsigned unused:13;
} _f;
CFSpinLock_t _lock;
CFSpinLock_t _writeLock;
CFSocketNativeHandle _socket; /* immutable */
SInt32 _socketType;
SInt32 _errorCode;
CFDataRef _address;
CFDataRef _peerAddress;
SInt32 _socketSetCount;
CFRunLoopSourceRef _source0; // v0 RLS, messaged from SocketMgr
CFMutableArrayRef _runLoops;
CFSocketCallBack _callout; /* immutable */
CFSocketContext _context; /* immutable */
CFMutableArrayRef _dataQueue; // queues to pass data from SocketMgr thread
CFMutableArrayRef _addressQueue;
struct timeval _readBufferTimeout;
CFMutableDataRef _readBuffer;
CFIndex _bytesToBuffer; /* is length of _readBuffer */
CFIndex _bytesToBufferPos; /* where the next _CFSocketRead starts from */
CFIndex _bytesToBufferReadPos; /* Where the buffer will next be read into (always after _bytesToBufferPos, but less than _bytesToBuffer) */
Boolean _atEOF;
int _bufferedReadError;
CFMutableDataRef _leftoverBytes;
};
/* Bit 6 in the base reserved bits is used for write-signalled state (mutable) */
/* Bit 5 in the base reserved bits is used for read-signalled state (mutable) */
/* Bit 4 in the base reserved bits is used for invalid state (mutable) */
/* Bits 0-3 in the base reserved bits are used for callback types (immutable) */
/* Of this, bits 0-1 are used for the read callback type. */
CF_INLINE Boolean __CFSocketIsWriteSignalled(CFSocketRef s) {
return (Boolean)__CFBitfieldGetValue(((const CFRuntimeBase *)s)->_cfinfo[CF_INFO_BITS], 6, 6);
}
CF_INLINE void __CFSocketSetWriteSignalled(CFSocketRef s) {
__CFBitfieldSetValue(((CFRuntimeBase *)s)->_cfinfo[CF_INFO_BITS], 6, 6, 1);
}
CF_INLINE void __CFSocketUnsetWriteSignalled(CFSocketRef s) {
__CFBitfieldSetValue(((CFRuntimeBase *)s)->_cfinfo[CF_INFO_BITS], 6, 6, 0);
}
CF_INLINE Boolean __CFSocketIsReadSignalled(CFSocketRef s) {
return (Boolean)__CFBitfieldGetValue(((const CFRuntimeBase *)s)->_cfinfo[CF_INFO_BITS], 5, 5);
}
CF_INLINE void __CFSocketSetReadSignalled(CFSocketRef s) {
__CFBitfieldSetValue(((CFRuntimeBase *)s)->_cfinfo[CF_INFO_BITS], 5, 5, 1);
}
CF_INLINE void __CFSocketUnsetReadSignalled(CFSocketRef s) {
__CFBitfieldSetValue(((CFRuntimeBase *)s)->_cfinfo[CF_INFO_BITS], 5, 5, 0);
}
CF_INLINE Boolean __CFSocketIsValid(CFSocketRef s) {
return (Boolean)__CFBitfieldGetValue(((const CFRuntimeBase *)s)->_cfinfo[CF_INFO_BITS], 4, 4);
}
CF_INLINE void __CFSocketSetValid(CFSocketRef s) {
__CFBitfieldSetValue(((CFRuntimeBase *)s)->_cfinfo[CF_INFO_BITS], 4, 4, 1);
}
CF_INLINE void __CFSocketUnsetValid(CFSocketRef s) {
__CFBitfieldSetValue(((CFRuntimeBase *)s)->_cfinfo[CF_INFO_BITS], 4, 4, 0);
}
CF_INLINE uint8_t __CFSocketCallBackTypes(CFSocketRef s) {
return (uint8_t)__CFBitfieldGetValue(((const CFRuntimeBase *)s)->_cfinfo[CF_INFO_BITS], 3, 0);
}
CF_INLINE uint8_t __CFSocketReadCallBackType(CFSocketRef s) {
return (uint8_t)__CFBitfieldGetValue(((const CFRuntimeBase *)s)->_cfinfo[CF_INFO_BITS], 1, 0);
}
CF_INLINE void __CFSocketSetCallBackTypes(CFSocketRef s, uint8_t types) {
__CFBitfieldSetValue(((CFRuntimeBase *)s)->_cfinfo[CF_INFO_BITS], 3, 0, types & 0xF);
}
CF_INLINE void __CFSocketLock(CFSocketRef s) {
__CFSpinLock(&(s->_lock));
}
CF_INLINE void __CFSocketUnlock(CFSocketRef s) {
__CFSpinUnlock(&(s->_lock));
}
CF_INLINE Boolean __CFSocketIsConnectionOriented(CFSocketRef s) {
return (SOCK_STREAM == s->_socketType || SOCK_SEQPACKET == s->_socketType);
}
CF_INLINE Boolean __CFSocketIsScheduled(CFSocketRef s) {
return (s->_socketSetCount > 0);
}
CF_INLINE void __CFSocketEstablishAddress(CFSocketRef s) {
/* socket should already be locked */
uint8_t name[MAX_SOCKADDR_LEN];
int namelen = sizeof(name);
if (__CFSocketIsValid(s) && NULL == s->_address && INVALID_SOCKET != s->_socket && 0 == getsockname(s->_socket, (struct sockaddr *)name, (socklen_t *)&namelen) && NULL != name && 0 < namelen) {
s->_address = CFDataCreate(CFGetAllocator(s), name, namelen);
}
}
CF_INLINE void __CFSocketEstablishPeerAddress(CFSocketRef s) {
/* socket should already be locked */
uint8_t name[MAX_SOCKADDR_LEN];
int namelen = sizeof(name);
if (__CFSocketIsValid(s) && NULL == s->_peerAddress && INVALID_SOCKET != s->_socket && 0 == getpeername(s->_socket, (struct sockaddr *)name, (socklen_t *)&namelen) && NULL != name && 0 < namelen) {
s->_peerAddress = CFDataCreate(CFGetAllocator(s), name, namelen);
}
}
static Boolean __CFNativeSocketIsValid(CFSocketNativeHandle sock) {
#if DEPLOYMENT_TARGET_WINDOWS
SInt32 flags = ioctlsocket (sock, FIONREAD, 0);
return (0 == flags);
#else
SInt32 flags = fcntl(sock, F_GETFL, 0);
return !(0 > flags && EBADF == thread_errno());
#endif
}
CF_INLINE Boolean __CFSocketFdClr(CFSocketNativeHandle sock, CFMutableDataRef fdSet) {
/* returns true if a change occurred, false otherwise */
Boolean retval = false;
if (INVALID_SOCKET != sock && 0 <= sock) {
#if DEPLOYMENT_TARGET_WINDOWS
fd_set* set = (fd_set*)CFDataGetMutableBytePtr(fdSet);
if (FD_ISSET(sock, set)) {
retval = true;
FD_CLR(sock, set);
}
#else
CFIndex numFds = NBBY * CFDataGetLength(fdSet);
fd_mask *fds_bits;
if (sock < numFds) {
fds_bits = (fd_mask *)CFDataGetMutableBytePtr(fdSet);
if (FD_ISSET(sock, (fd_set *)fds_bits)) {
retval = true;
FD_CLR(sock, (fd_set *)fds_bits);
}
}
#endif
}
return retval;
}
static SInt32 __CFSocketCreateWakeupSocketPair(void) {
#if !DEPLOYMENT_TARGET_WINDOWS
return socketpair(PF_LOCAL, SOCK_DGRAM, 0, __CFWakeupSocketPair);
#else
//??? should really use native Win32 facilities
UInt32 i;
SInt32 error = 0;
struct sockaddr_in address[2];
int namelen = sizeof(struct sockaddr_in);
for (i = 0; i < 2; i++) {
__CFWakeupSocketPair[i] = (CFSocketNativeHandle)socket(PF_INET, SOCK_DGRAM, 0);
memset(&(address[i]), 0, sizeof(struct sockaddr_in));
address[i].sin_family = AF_INET;
address[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (0 <= error) error = bind(__CFWakeupSocketPair[i], (struct sockaddr *)&(address[i]), sizeof(struct sockaddr_in));
if (0 <= error) error = getsockname(__CFWakeupSocketPair[i], (struct sockaddr *)&(address[i]), &namelen);
if (sizeof(struct sockaddr_in) != namelen) error = -1;
}
if (0 <= error) error = connect(__CFWakeupSocketPair[0], (struct sockaddr *)&(address[1]), sizeof(struct sockaddr_in));
if (0 <= error) error = connect(__CFWakeupSocketPair[1], (struct sockaddr *)&(address[0]), sizeof(struct sockaddr_in));
if (0 > error) {
closesocket(__CFWakeupSocketPair[0]);
closesocket(__CFWakeupSocketPair[1]);
}
return error;
#endif
}
// Version 0 RunLoopSources set a mask in an FD set to control what socket activity we hear about.
CF_INLINE Boolean __CFSocketSetFDForRead(CFSocketRef s) {
__CFReadSocketsTimeoutInvalid = true;
return __CFSocketFdSet(s->_socket, __CFReadSocketsFds);
}
CF_INLINE Boolean __CFSocketClearFDForRead(CFSocketRef s) {
__CFReadSocketsTimeoutInvalid = true;
return __CFSocketFdClr(s->_socket, __CFReadSocketsFds);
}
CF_INLINE Boolean __CFSocketSetFDForWrite(CFSocketRef s) {
return __CFSocketFdSet(s->_socket, __CFWriteSocketsFds);
}
CF_INLINE Boolean __CFSocketClearFDForWrite(CFSocketRef s) {
return __CFSocketFdClr(s->_socket, __CFWriteSocketsFds);
}
#if DEPLOYMENT_TARGET_WINDOWS
static Boolean WinSockUsed = FALSE;
static void __CFSocketInitializeWinSock_Guts(void) {
if (!WinSockUsed) {
WinSockUsed = TRUE;
WORD versionRequested = MAKEWORD(2, 0);
WSADATA wsaData;
int errorStatus = WSAStartup(versionRequested, &wsaData);
if (errorStatus != 0 || LOBYTE(wsaData.wVersion) != LOBYTE(versionRequested) || HIBYTE(wsaData.wVersion) != HIBYTE(versionRequested)) {
WSACleanup();
CFLog(0, CFSTR("*** Could not initialize WinSock subsystem!!!"));
}
}
}
CF_EXPORT void __CFSocketInitializeWinSock(void) {
__CFSpinLock(&__CFActiveSocketsLock);
__CFSocketInitializeWinSock_Guts();
__CFSpinUnlock(&__CFActiveSocketsLock);
}
__private_extern__ void __CFSocketCleanup(void) {
__CFSpinLock(&__CFActiveSocketsLock);
if (NULL != __CFReadSockets) {
CFRelease(__CFWriteSockets);
__CFWriteSockets = NULL;
CFRelease(__CFReadSockets);
__CFReadSockets = NULL;
CFRelease(__CFWriteSocketsFds);
__CFWriteSocketsFds = NULL;
CFRelease(__CFReadSocketsFds);
__CFReadSocketsFds = NULL;
CFRelease(__CFExceptSocketsFds);
__CFExceptSocketsFds = NULL;
CFRelease(zeroLengthData);
zeroLengthData = NULL;
}
if (NULL != __CFAllSockets) {
CFRelease(__CFAllSockets);
__CFAllSockets = NULL;
}
if (INVALID_SOCKET != __CFWakeupSocketPair[0]) {
closesocket(__CFWakeupSocketPair[0]);
__CFWakeupSocketPair[0] = INVALID_SOCKET;
}
if (INVALID_SOCKET != __CFWakeupSocketPair[1]) {
closesocket(__CFWakeupSocketPair[1]);
__CFWakeupSocketPair[1] = INVALID_SOCKET;
}
if (WinSockUsed) {
WSACleanup();
}
__CFSpinUnlock(&__CFActiveSocketsLock);
}
#endif
// CFNetwork needs to call this, especially for Win32 to get WSAStartup
static void __CFSocketInitializeSockets(void) {
__CFWriteSockets = CFArrayCreateMutable(kCFAllocatorSystemDefault, 0, NULL);
__CFReadSockets = CFArrayCreateMutable(kCFAllocatorSystemDefault, 0, NULL);
__CFWriteSocketsFds = CFDataCreateMutable(kCFAllocatorSystemDefault, 0);
__CFReadSocketsFds = CFDataCreateMutable(kCFAllocatorSystemDefault, 0);
zeroLengthData = CFDataCreateMutable(kCFAllocatorSystemDefault, 0);
#if DEPLOYMENT_TARGET_WINDOWS
__CFSocketInitializeWinSock_Guts();
// make sure we have space for the count field and the first socket
CFDataIncreaseLength(__CFWriteSocketsFds, sizeof(u_int) + sizeof(SOCKET));
CFDataIncreaseLength(__CFReadSocketsFds, sizeof(u_int) + sizeof(SOCKET));
__CFExceptSocketsFds = CFDataCreateMutable(kCFAllocatorSystemDefault, 0);
CFDataIncreaseLength(__CFExceptSocketsFds, sizeof(u_int) + sizeof(SOCKET));
#endif
if (0 > __CFSocketCreateWakeupSocketPair()) {
CFLog(kCFLogLevelWarning, CFSTR("*** Could not create wakeup socket pair for CFSocket!!!"));
} else {
#if DEPLOYMENT_TARGET_WINDOWS
u_long yes = 1;
#else
UInt32 yes = 1;
#endif
/* wakeup sockets must be non-blocking */
ioctlsocket(__CFWakeupSocketPair[0], FIONBIO, &yes);
ioctlsocket(__CFWakeupSocketPair[1], FIONBIO, &yes);
__CFSocketFdSet(__CFWakeupSocketPair[1], __CFReadSocketsFds);
}
}
static CFRunLoopRef __CFSocketCopyRunLoopToWakeUp(CFSocketRef s) {
CFRunLoopRef rl = NULL;
SInt32 idx, cnt = CFArrayGetCount(s->_runLoops);
if (0 < cnt) {
rl = (CFRunLoopRef)CFArrayGetValueAtIndex(s->_runLoops, 0);
for (idx = 1; NULL != rl && idx < cnt; idx++) {
CFRunLoopRef value = (CFRunLoopRef)CFArrayGetValueAtIndex(s->_runLoops, idx);
if (value != rl) rl = NULL;
}
if (NULL == rl) { /* more than one different rl, so we must pick one */
/* ideally, this would be a run loop which isn't also in a
* signaled state for this or another source, but that's tricky;
* we pick one that is running in an appropriate mode for this
* source, and from those if possible one that is waiting; then
* we move this run loop to the end of the list to scramble them
* a bit, and always search from the front */
Boolean foundIt = false, foundBackup = false;
SInt32 foundIdx = 0;
for (idx = 0; !foundIt && idx < cnt; idx++) {
CFRunLoopRef value = (CFRunLoopRef)CFArrayGetValueAtIndex(s->_runLoops, idx);
CFStringRef currentMode = CFRunLoopCopyCurrentMode(value);
if (NULL != currentMode) {
if (CFRunLoopContainsSource(value, s->_source0, currentMode)) {
if (CFRunLoopIsWaiting(value)) {
foundIdx = idx;
foundIt = true;
} else if (!foundBackup) {
foundIdx = idx;
foundBackup = true;
}
}
CFRelease(currentMode);
}
}
rl = (CFRunLoopRef)CFArrayGetValueAtIndex(s->_runLoops, foundIdx);
CFRetain(rl);
CFArrayRemoveValueAtIndex(s->_runLoops, foundIdx);
CFArrayAppendValue(s->_runLoops, rl);
} else {
CFRetain(rl);
}
}
return rl;
}
// If callBackNow, we immediately do client callbacks, else we have to signal a v0 RunLoopSource so the
// callbacks can happen in another thread.
static void __CFSocketHandleWrite(CFSocketRef s, Boolean callBackNow) {
SInt32 errorCode = 0;
int errorSize = sizeof(errorCode);
CFOptionFlags writeCallBacksAvailable;
if (!CFSocketIsValid(s)) return;
#if DEPLOYMENT_TARGET_WINDOWS
if (0 != (s->_f.client & kCFSocketLeaveErrors) || 0 != getsockopt(s->_socket, SOL_SOCKET, SO_ERROR, (char *)&errorCode, (socklen_t *)&errorSize)) errorCode = 0; // cast for WinSock bad API
#else
if (0 != (s->_f.client & kCFSocketLeaveErrors) || 0 != getsockopt(s->_socket, SOL_SOCKET, SO_ERROR, (void *)&errorCode, (socklen_t *)&errorSize)) errorCode = 0; // cast for WinSock bad API
#endif
#if defined(LOG_CFSOCKET)
if (errorCode) fprintf(stdout, "error %ld on socket %d\n", errorCode, s->_socket);
#endif
__CFSocketLock(s);
writeCallBacksAvailable = __CFSocketCallBackTypes(s) & (kCFSocketWriteCallBack | kCFSocketConnectCallBack);
if ((s->_f.client & kCFSocketConnectCallBack) != 0) writeCallBacksAvailable &= ~kCFSocketConnectCallBack;
if (!__CFSocketIsValid(s) || ((s->_f.disabled & writeCallBacksAvailable) == writeCallBacksAvailable)) {
__CFSocketUnlock(s);
return;
}
s->_errorCode = errorCode;
__CFSocketSetWriteSignalled(s);
#if defined(LOG_CFSOCKET)
fprintf(stdout, "write signaling source for socket %d\n", s->_socket);
#endif
if (callBackNow) {
__CFSocketDoCallback(s, NULL, NULL, 0);
} else {
CFRunLoopRef rl;
CFRunLoopSourceSignal(s->_source0);
rl = __CFSocketCopyRunLoopToWakeUp(s);
__CFSocketUnlock(s);
if (NULL != rl) {
CFRunLoopWakeUp(rl);
CFRelease(rl);
}
}
}
static void __CFSocketHandleRead(CFSocketRef s, Boolean causedByTimeout)
{
CFDataRef data = NULL, address = NULL;
CFSocketNativeHandle sock = INVALID_SOCKET;
if (!CFSocketIsValid(s)) return;
if (__CFSocketReadCallBackType(s) == kCFSocketDataCallBack) {
uint8_t bufferArray[MAX_CONNECTION_ORIENTED_DATA_SIZE], *buffer;
uint8_t name[MAX_SOCKADDR_LEN];
#if !DEPLOYMENT_TARGET_WINDOWS
int namelen = sizeof(name);
#else
int namelen = 0;
#endif
SInt32 recvlen = 0;
if (__CFSocketIsConnectionOriented(s)) {
buffer = bufferArray;
recvlen = recvfrom(s->_socket, (SOCK_DATA)buffer, MAX_CONNECTION_ORIENTED_DATA_SIZE, 0, (struct sockaddr *)name, (socklen_t *)&namelen);
} else {
buffer = (uint8_t*)malloc(MAX_DATA_SIZE);
if (buffer) recvlen = recvfrom(s->_socket, (SOCK_DATA)buffer, MAX_DATA_SIZE, 0, (struct sockaddr *)name, (socklen_t *)&namelen);
}
#if defined(LOG_CFSOCKET)
fprintf(stdout, "read %ld bytes on socket %d\n", recvlen, s->_socket);
#endif
if (0 >= recvlen) {
//??? should return error if <0
/* zero-length data is the signal for perform to invalidate */
data = (CFDataRef)CFRetain(zeroLengthData);
} else {
data = CFDataCreate(CFGetAllocator(s), buffer, recvlen);
}
if (buffer && buffer != bufferArray) free(buffer);
__CFSocketLock(s);
if (!__CFSocketIsValid(s)) {
CFRelease(data);
__CFSocketUnlock(s);
return;
}
__CFSocketSetReadSignalled(s);
if (NULL != name && 0 < namelen) {
//??? possible optimizations: uniquing; storing last value
address = CFDataCreate(CFGetAllocator(s), name, namelen);
} else if (__CFSocketIsConnectionOriented(s)) {
if (NULL == s->_peerAddress) __CFSocketEstablishPeerAddress(s);
if (NULL != s->_peerAddress) address = (CFDataRef)CFRetain(s->_peerAddress);
}
if (NULL == address) {
address = (CFDataRef)CFRetain(zeroLengthData);
}
if (NULL == s->_dataQueue) {
s->_dataQueue = CFArrayCreateMutable(CFGetAllocator(s), 0, &kCFTypeArrayCallBacks);
}
if (NULL == s->_addressQueue) {
s->_addressQueue = CFArrayCreateMutable(CFGetAllocator(s), 0, &kCFTypeArrayCallBacks);
}
CFArrayAppendValue(s->_dataQueue, data);
CFRelease(data);
CFArrayAppendValue(s->_addressQueue, address);
CFRelease(address);
if (0 < recvlen
&& (s->_f.client & kCFSocketDataCallBack) != 0 && (s->_f.disabled & kCFSocketDataCallBack) == 0
&& __CFSocketIsScheduled(s)
) {
__CFSpinLock(&__CFActiveSocketsLock);
/* restore socket to fds */
__CFSocketSetFDForRead(s);
__CFSpinUnlock(&__CFActiveSocketsLock);
}
} else if (__CFSocketReadCallBackType(s) == kCFSocketAcceptCallBack) {
uint8_t name[MAX_SOCKADDR_LEN];
int namelen = sizeof(name);
sock = (CFSocketNativeHandle)accept(s->_socket, (struct sockaddr *)name, (socklen_t *)&namelen);
if (INVALID_SOCKET == sock) {
//??? should return error
return;
}
if (NULL != name && 0 < namelen) {
address = CFDataCreate(CFGetAllocator(s), name, namelen);
} else {
address = (CFDataRef)CFRetain(zeroLengthData);
}
__CFSocketLock(s);
if (!__CFSocketIsValid(s)) {
closesocket(sock);
CFRelease(address);
__CFSocketUnlock(s);
return;
}
__CFSocketSetReadSignalled(s);
if (NULL == s->_dataQueue) {
s->_dataQueue = CFArrayCreateMutable(CFGetAllocator(s), 0, NULL);
}
if (NULL == s->_addressQueue) {
s->_addressQueue = CFArrayCreateMutable(CFGetAllocator(s), 0, &kCFTypeArrayCallBacks);
}
CFArrayAppendValue(s->_dataQueue, (void *)(uintptr_t)sock);
CFArrayAppendValue(s->_addressQueue, address);
CFRelease(address);
if ((s->_f.client & kCFSocketAcceptCallBack) != 0 && (s->_f.disabled & kCFSocketAcceptCallBack) == 0
&& __CFSocketIsScheduled(s)
) {
__CFSpinLock(&__CFActiveSocketsLock);
/* restore socket to fds */
__CFSocketSetFDForRead(s);
__CFSpinUnlock(&__CFActiveSocketsLock);
}
} else {
__CFSocketLock(s);
if (!__CFSocketIsValid(s) || (s->_f.disabled & kCFSocketReadCallBack) != 0) {
__CFSocketUnlock(s);
return;
}
if (causedByTimeout) {
#if defined(LOG_CFSOCKET)
fprintf(stdout, "TIMEOUT RECEIVED - WILL SIGNAL IMMEDIATELY TO FLUSH (%d buffered)\n", s->_bytesToBufferPos);
#endif
/* we've got a timeout, but no bytes read. Ignore the timeout. */
if (s->_bytesToBufferPos == 0) {
#if defined(LOG_CFSOCKET)
fprintf(stdout, "TIMEOUT - but no bytes, restoring to active set\n");
fflush(stdout);
#endif
__CFSpinLock(&__CFActiveSocketsLock);
/* restore socket to fds */
__CFSocketSetFDForRead(s);
__CFSpinUnlock(&__CFActiveSocketsLock);
__CFSocketUnlock(s);
return;
}
} else if (s->_bytesToBuffer != 0 && ! s->_atEOF) {
UInt8* base;
CFIndex ctRead;
CFIndex ctRemaining = s->_bytesToBuffer - s->_bytesToBufferPos;
/* if our buffer has room, we go ahead and buffer */
if (ctRemaining > 0) {
base = CFDataGetMutableBytePtr(s->_readBuffer);
do {
ctRead = read(CFSocketGetNative(s), &base[s->_bytesToBufferPos], ctRemaining);
} while (ctRead == -1 && errno == EAGAIN);
switch (ctRead) {
case -1:
s->_bufferedReadError = errno;
s->_atEOF = true;
#if defined(LOG_CFSOCKET)
fprintf(stderr, "BUFFERED READ GOT ERROR %d\n", errno);
#endif
break;
case 0:
#if defined(LOG_CFSOCKET)
fprintf(stdout, "DONE READING (EOF) - GOING TO SIGNAL\n");
#endif
s->_atEOF = true;
break;
default:
s->_bytesToBufferPos += ctRead;
if (s->_bytesToBuffer != s->_bytesToBufferPos) {
#if defined(LOG_CFSOCKET)
fprintf(stdout, "READ %d - need %d MORE - GOING BACK FOR MORE\n", ctRead, s->_bytesToBuffer - s->_bytesToBufferPos);
#endif
__CFSpinLock(&__CFActiveSocketsLock);
/* restore socket to fds */
__CFSocketSetFDForRead(s);
__CFSpinUnlock(&__CFActiveSocketsLock);
__CFSocketUnlock(s);
return;
} else {
#if defined(LOG_CFSOCKET)
fprintf(stdout, "DONE READING (read %d bytes) - GOING TO SIGNAL\n", ctRead);
#endif
}
}
}
}
__CFSocketSetReadSignalled(s);
}
#if defined(LOG_CFSOCKET)
fprintf(stdout, "read signaling source for socket %d\n", s->_socket);
#endif
CFRunLoopSourceSignal(s->_source0);
CFRunLoopRef rl = __CFSocketCopyRunLoopToWakeUp(s);
__CFSocketUnlock(s);
if (NULL != rl) {
CFRunLoopWakeUp(rl);
CFRelease(rl);
}
}
static struct timeval* intervalToTimeval(CFTimeInterval timeout, struct timeval* tv)
{
if (timeout == 0.0)
timerclear(tv);
else {
tv->tv_sec = (0 >= timeout || INT_MAX <= timeout) ? INT_MAX : (int)(float)floor(timeout);
tv->tv_usec = (int)((timeout - floor(timeout)) * 1.0E6);
}
return tv;
}
/* note that this returns a pointer to the min value, which won't have changed during
the dictionary apply, since we've got the active sockets lock held */
static void _calcMinTimeout_locked(const void* val, void* ctxt)
{
CFSocketRef s = (CFSocketRef) val;
struct timeval** minTime = (struct timeval**) ctxt;
if (timerisset(&s->_readBufferTimeout) && (*minTime == NULL || timercmp(&s->_readBufferTimeout, *minTime, <)))
*minTime = &s->_readBufferTimeout;
else if (s->_leftoverBytes) {
/* If there's anyone with leftover bytes, they'll need to be awoken immediately */
static struct timeval sKickerTime = { 0, 0 };
*minTime = &sKickerTime;
}
}
void __CFSocketSetSocketReadBufferAttrs(CFSocketRef s, CFTimeInterval timeout, CFIndex length)
{
struct timeval timeoutVal;
intervalToTimeval(timeout, &timeoutVal);
/* lock ordering is socket lock, activesocketslock */
/* activesocketslock protects our timeout calculation */
__CFSocketLock(s);
__CFSpinLock(&__CFActiveSocketsLock);
#if defined(LOG_CFSOCKET)
s->didLogSomething = false;
#endif
if (s->_bytesToBuffer != length) {
CFIndex ctBuffer = s->_bytesToBufferPos - s->_bytesToBufferReadPos;
if (ctBuffer) {
/* As originally envisaged, you were supposed to be sure to drain the buffer before
* issuing another request on the socket. In practice, there seem to be times when we want to re-use
* the stream (or perhaps, are on our way to closing it out) and this policy doesn't work so well.
* So, if someone changes the buffer size while we have bytes already buffered, we put them
* aside and use them to satisfy any subsequent reads.
*/
#if defined(LOG_CFSOCKET)
__socketLog("%s(%d): WARNING: shouldn't set read buffer length while data (%d bytes) is still in the read buffer (leftover total %d)", __FUNCTION__, __LINE__, ctBuffer, s->_leftoverBytes? CFDataGetLength(s->_leftoverBytes) : 0);
#endif
if (s->_leftoverBytes == NULL)
s->_leftoverBytes = CFDataCreateMutable(CFGetAllocator(s), 0);
/* append the current buffered bytes over. We'll keep draining _leftoverBytes while we have them... */
CFDataAppendBytes(s->_leftoverBytes, CFDataGetBytePtr(s->_readBuffer) + s->_bytesToBufferReadPos, ctBuffer);
CFRelease(s->_readBuffer);
s->_readBuffer = NULL;
s->_bytesToBuffer = 0;
s->_bytesToBufferPos = 0;
s->_bytesToBufferReadPos = 0;
}
if (length == 0) {
s->_bytesToBuffer = 0;
s->_bytesToBufferPos = 0;
s->_bytesToBufferReadPos = 0;
if (s->_readBuffer) {
CFRelease(s->_readBuffer);
s->_readBuffer = NULL;
}
// Zero length buffer, smash the timeout
static struct timeval sReset = { 0, 0 };
timeoutVal = sReset;
} else {
/* if the buffer shrank, we can re-use the old one */
if (length > s->_bytesToBuffer) {
if (s->_readBuffer) {
CFRelease(s->_readBuffer);
s->_readBuffer = NULL;
}
}
s->_bytesToBuffer = length;
s->_bytesToBufferPos = 0;
s->_bytesToBufferReadPos = 0;
if (s->_readBuffer == NULL) {
s->_readBuffer = CFDataCreateMutable(kCFAllocatorSystemDefault, length);
CFDataSetLength(s->_readBuffer, length);
}
}
}
if (timercmp(&s->_readBufferTimeout, &timeoutVal, !=)) {
s->_readBufferTimeout = timeoutVal;
__CFReadSocketsTimeoutInvalid = true;
}
__CFSpinUnlock(&__CFActiveSocketsLock);
__CFSocketUnlock(s);
}
void __CFSocketSetReadBufferTimeout(CFSocketRef s, CFTimeInterval timeout)
{
#if defined(LOG_CFSOCKET)
__socketLog("### (%s DEPRECATED) SET READ BUFFER TIMEOUT for %p (bufferSize %d, timeout %d.%d)\n", __FUNCTION__, s, s->_bytesToBuffer, s->_readBufferTimeout.tv_sec, s->_readBufferTimeout.tv_usec);
#endif
__CFSocketSetSocketReadBufferAttrs(s, timeout, s->_bytesToBuffer);
}
void __CFSocketSetReadBufferLength(CFSocketRef s, CFIndex length)
{
#if defined(LOG_CFSOCKET)
__socketLog("### (%s DEPRECATED) SET READ BUFFER LENGTH for %p (bufferSize %d, timeout %d.%d)\n", __FUNCTION__, s, s->_bytesToBuffer, s->_readBufferTimeout.tv_sec, s->_readBufferTimeout.tv_usec);
#endif
CFTimeInterval timeout;
if (! timerisset(&s->_readBufferTimeout))
timeout = 0;
else
timeout = 0.1;
__CFSocketSetSocketReadBufferAttrs(s, timeout, length);
}
CFIndex __CFSocketRead(CFSocketRef s, UInt8* buffer, CFIndex length, int* error)
{
#if defined(LOG_CFSOCKET)
fprintf(stdout, "READING BYTES FOR SOCKET %d (%d buffered, out of %d desired, eof = %d, err = %d)\n", s->_socket, s->_bytesToBufferPos, s->_bytesToBuffer, s->_atEOF, s->_bufferedReadError);
#endif
CFIndex result = -1;
__CFSocketLock(s);
*error = 0;
/* Any leftover buffered bytes? */
if (s->_leftoverBytes) {
CFIndex ctBuffer = CFDataGetLength(s->_leftoverBytes);
#if defined(DEBUG)
fprintf(stderr, "%s(%d): WARNING: Draining %lu leftover bytes first\n\n", __FUNCTION__, __LINE__, ctBuffer);
#endif
if (ctBuffer > length)
ctBuffer = length;
memcpy(buffer, CFDataGetBytePtr(s->_leftoverBytes), ctBuffer);
if (ctBuffer < CFDataGetLength(s->_leftoverBytes))
CFDataReplaceBytes(s->_leftoverBytes, CFRangeMake(0, ctBuffer), NULL, 0);
else {
CFRelease(s->_leftoverBytes);
s->_leftoverBytes = NULL;
}
result = ctBuffer;
goto unlock;
}
/* return whatever we've buffered */
if (s->_bytesToBuffer != 0) {
CFIndex ctBuffer = s->_bytesToBufferPos - s->_bytesToBufferReadPos;
if (ctBuffer > 0) {
/* drain our buffer first */
if (ctBuffer > length)
ctBuffer = length;
memcpy(buffer, CFDataGetBytePtr(s->_readBuffer) + s->_bytesToBufferReadPos, ctBuffer);
s->_bytesToBufferReadPos += ctBuffer;
if (s->_bytesToBufferReadPos == s->_bytesToBufferPos) {
#if defined(LOG_CFSOCKET)
fprintf(stdout, "DRAINED BUFFER - SHOULD START BUFFERING AGAIN!\n");
#endif
s->_bytesToBufferPos = 0;
s->_bytesToBufferReadPos = 0;
}
#if defined(LOG_CFSOCKET)
fprintf(stdout, "SLURPED %d BYTES FROM BUFFER %d LEFT TO READ!\n", ctBuffer, length);
#endif
result = ctBuffer;
goto unlock;
}
}