/
CFSocket.c
2641 lines (2374 loc) · 108 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
/* CFSocket.c
Copyright (c) 1999-2019, Apple Inc. and the Swift project authors
Portions Copyright (c) 2014-2019, Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
Responsibility: Michael LeHew
*/
#include <CoreFoundation/CFSocket.h>
#include <sys/types.h>
#include <math.h>
#include <limits.h>
#if TARGET_OS_MAC
#include <sys/sysctl.h>
#include <sys/un.h>
#include <libc.h>
#include <dlfcn.h>
#if TARGET_OS_CYGWIN
#include <sys/socket.h>
#endif
#endif
#if TARGET_OS_CYGWIN || TARGET_OS_BSD
#include <sys/socket.h>
#endif
#if TARGET_OS_WIN32
#include <WinSock2.h>
#else
#include <arpa/inet.h>
#include <netinet/in.h>
#endif
#if !TARGET_OS_WIN32
#include <sys/ioctl.h>
#endif
#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
#include <unistd.h>
#endif
#include <fcntl.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"
#include "CFRuntime_Internal.h"
#if TARGET_OS_WIN32
#include <process.h>
#endif
#ifndef NBBY
#define NBBY 8
#endif
#if TARGET_OS_WIN32
// redefine this to the winsock error in this file
#undef EINPROGRESS
#define EINPROGRESS WSAEINPROGRESS
// redefine this to the winsock error in this file
#undef EBADF
#define EBADF WSAENOTSOCK
#define NFDBITS (sizeof(int32_t) * NBBY)
typedef int32_t fd_mask;
typedef int socklen_t;
#define gettimeofday _NS_gettimeofday
struct timezone;
CF_PRIVATE int _NS_gettimeofday(struct timeval *tv, struct timezone *tz);
// although this is only used for debug info, we define it for compatibility
#define timersub(tvp, uvp, vvp) \
do { \
(vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \
(vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \
if ((vvp)->tv_usec < 0) { \
(vvp)->tv_sec--; \
(vvp)->tv_usec += 1000000; \
} \
} while (0)
static void timeradd(struct timeval *a, struct timeval *b, struct timeval *res) {
res->tv_sec = a->tv_sec + b->tv_sec;
res->tv_usec = a->tv_usec + b->tv_usec;
if (res->tv_usec > 1e06) {
res->tv_sec++;
res->tv_usec -= 1e06;
}
}
#endif // TARGET_OS_WIN32
// 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.
#undef LOG_CFSOCKET
//#define LOG_CFSOCKET 1
#define DEBUG_POLLING_SELECT 1
#if defined(LOG_CFSOCKET)
#include <sys/syslog.h>
static _CFThreadRef __cfSocketTid()
{
#if TARGET_OS_MAC
uint64_t tid = 0;
if (0 != pthread_threadid_np(NULL, &tid))
tid = pthread_mach_thread_np(pthread_self());
return (_CFThreadRef) tid;
#elif TARGET_OS_WIN32
return (_CFThreadRef) GetCurrentThreadId();
#else
return (_CFThreadRef) pthread_self();
#endif
}
static void __cfSocketLog(const char* function, int line, const char* fmt, ...)
{
#if 0
char* p = nil;
va_list args;
va_start(args, fmt);
vasprintf(&p, fmt, args);
va_end(args);
// CFLog(kCFLogLevelNotice, CFSTR("CFSocket:%d %s"), line, p);
char* s = nil;
asprintf(&s, "CFSocket:%d %s", line, p);
syslog(LOG_NOTICE, "%s", s);
free(s);
free(p);
#else
va_list args;
va_start(args, fmt);
CFStringRef fmtString = CFStringCreateWithCString(kCFAllocatorDefault, fmt, kCFStringEncodingUTF8);
CFStringRef payload = CFStringCreateWithFormatAndArguments(kCFAllocatorDefault, NULL, fmtString, args);
if (fmtString)
CFRelease(fmtString);
if (payload == NULL)
syslog(LOG_NOTICE, "CFSocket[%p]:%s:%d - no payload?", __cfSocketTid(),function, line);
else {
CFDataRef payloadData = CFStringCreateExternalRepresentation(kCFAllocatorDefault, payload, kCFStringEncodingUTF8, '.');
CFRelease(payload);
if (payloadData == NULL)
syslog(LOG_NOTICE, "CFSocket[%p]:%s:%d - no payload?", __cfSocketTid(),function, line);
else {
syslog(LOG_NOTICE, "CFSocket[%p]:%s:%d - %.*s", __cfSocketTid(),function, line, (int) CFDataGetLength(payloadData), CFDataGetBytePtr(payloadData));
CFRelease(payloadData);
}
}
#endif
}
static void __cfSocketLogWithSocket(CFSocketRef s, const char* function, int line, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
CFStringRef fmtString = CFStringCreateWithCString(kCFAllocatorDefault, fmt, kCFStringEncodingUTF8);
CFStringRef payload = CFStringCreateWithFormatAndArguments(kCFAllocatorDefault, NULL, fmtString, args);
if (fmtString)
CFRelease(fmtString);
if (payload == NULL)
syslog(LOG_NOTICE, "CFSocket[%p]:%s:%d (%p, fd %d) - no payload?", __cfSocketTid(), function, line, s, CFSocketGetNative(s));
else {
CFDataRef payloadData = CFStringCreateExternalRepresentation(kCFAllocatorDefault, payload, kCFStringEncodingUTF8, '.');
CFRelease(payload);
if (payloadData == NULL)
syslog(LOG_NOTICE, "CFSocket[%p]:%s:%d (%p, fd %d) - no payload?", __cfSocketTid(), function, line, s, CFSocketGetNative(s));
else {
syslog(LOG_NOTICE, "CFSocket[%p]:%s:%d (%p, fd %d) - %.*s", __cfSocketTid(), function, line, s, CFSocketGetNative(s), (int) CFDataGetLength(payloadData), CFDataGetBytePtr(payloadData));
CFRelease(payloadData);
}
}
}
#define __CFSOCKETLOG(xxx...) __cfSocketLog(__FUNCTION__, __LINE__, xxx)
#define __CFSOCKETLOG_WS(S, xxx...) __cfSocketLogWithSocket(S, __FUNCTION__, __LINE__, xxx)
#else
#define __CFSOCKETLOG(xxx...) /**/
#define __CFSOCKETLOG_WS(S, xxx...) /**/
#endif
#if TARGET_OS_MAC || TARGET_OS_LINUX || TARGET_OS_BSD
#define INVALID_SOCKET (CFSocketNativeHandle)(-1)
#define closesocket(a) close((a))
#define ioctlsocket(a,b,c) ioctl((a),(b),(c))
#endif
CF_INLINE int __CFSocketLastError(void) {
#if TARGET_OS_WIN32
return WSAGetLastError();
#else
return thread_errno();
#endif
}
CF_INLINE CFIndex __CFSocketFdGetSize(CFDataRef fdSet) {
return NBBY * CFDataGetLength(fdSet);
}
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) {
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);
}
}
return retval;
}
#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 CFLock_t __CFAllSocketsLock = CFLockInit; /* controls __CFAllSockets */
static CFMutableDictionaryRef __CFAllSockets = NULL;
static CFLock_t __CFActiveSocketsLock = CFLockInit; /* 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;
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 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;
CFLock_t _lock;
CFLock_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;
// <rdar://problem/17849895>
// If the timeout is set on the CFSocketRef but we never get select() timeout
// because we always have some network events so select never times out (e.g. while having a large download).
// We need to notify any waiting buffered read clients if there is data available without relying on select timing out.
struct timeval _readBufferTimeoutNotificationTime;
Boolean _hitTheTimeout;
};
/* 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 __CFRuntimeGetFlag(s, 6);
}
CF_INLINE void __CFSocketSetWriteSignalled(CFSocketRef s) {
__CFRuntimeSetFlag(s, 6, true);
}
CF_INLINE void __CFSocketUnsetWriteSignalled(CFSocketRef s) {
__CFRuntimeSetFlag(s, 6, false);
}
CF_INLINE Boolean __CFSocketIsReadSignalled(CFSocketRef s) {
return __CFRuntimeGetFlag(s, 5);
}
CF_INLINE void __CFSocketSetReadSignalled(CFSocketRef s) {
__CFRuntimeSetFlag(s, 5, true);
}
CF_INLINE void __CFSocketUnsetReadSignalled(CFSocketRef s) {
__CFRuntimeSetFlag(s, 5, false);
}
CF_INLINE Boolean __CFSocketIsValid(CFSocketRef s) {
return __CFRuntimeGetFlag(s, 4);
}
CF_INLINE void __CFSocketSetValid(CFSocketRef s) {
__CFRuntimeSetFlag(s, 4, true);
}
CF_INLINE void __CFSocketUnsetValid(CFSocketRef s) {
__CFRuntimeSetFlag(s, 4, false);
}
CF_INLINE uint8_t __CFSocketCallBackTypes(CFSocketRef s) {
return (uint8_t)__CFRuntimeGetValue(s, 3, 0);
}
CF_INLINE uint8_t __CFSocketReadCallBackType(CFSocketRef s) {
return (uint8_t)__CFRuntimeGetValue(s, 1, 0);
}
CF_INLINE void __CFSocketSetCallBackTypes(CFSocketRef s, uint8_t types) {
__CFRuntimeSetValue(s, 3, 0, types & 0xF);
}
CF_INLINE void __CFSocketLock(CFSocketRef s) {
__CFLock(&(s->_lock));
}
CF_INLINE void __CFSocketUnlock(CFSocketRef s) {
__CFUnlock(&(s->_lock));
}
CF_INLINE Boolean __CFSocketIsConnectionOriented(CFSocketRef s) {
return (SOCK_STREAM == 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) && 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) && 0 < namelen) {
s->_peerAddress = CFDataCreate(CFGetAllocator(s), name, namelen);
}
}
static Boolean __CFNativeSocketIsValid(CFSocketNativeHandle sock) {
Boolean result;
#if TARGET_OS_WIN32
SInt32 errorCode = 0;
int errorSize = sizeof(errorCode);
result = !(0 != getsockopt(sock, SOL_SOCKET, SO_ERROR, (char *)&errorCode, &errorSize) && __CFSocketLastError() == WSAENOTSOCK);
#else
SInt32 flags = fcntl(sock, F_GETFL, 0);
result = !(0 > flags && EBADF == __CFSocketLastError());
#endif
__CFSOCKETLOG("socket fd %d => %d", sock, result);
return result;
}
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) {
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);
}
}
}
return retval;
}
static SInt32 __CFSocketCreateWakeupSocketPair(void) {
#if TARGET_OS_MAC
SInt32 error;
error = socketpair(PF_LOCAL, SOCK_DGRAM, 0, __CFWakeupSocketPair);
if (0 <= error) error = fcntl(__CFWakeupSocketPair[0], F_SETFD, FD_CLOEXEC);
if (0 <= error) error = fcntl(__CFWakeupSocketPair[1], F_SETFD, FD_CLOEXEC);
if (0 > error) {
closesocket(__CFWakeupSocketPair[0]);
closesocket(__CFWakeupSocketPair[1]);
__CFWakeupSocketPair[0] = INVALID_SOCKET;
__CFWakeupSocketPair[1] = INVALID_SOCKET;
}
#else
UInt32 i;
SInt32 error = 0;
struct sockaddr_in address[2];
int namelen = sizeof(struct sockaddr_in);
for (i = 0; i < 2; i++) {
__CFWakeupSocketPair[i] = 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]), (socklen_t *)&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]);
__CFWakeupSocketPair[0] = INVALID_SOCKET;
__CFWakeupSocketPair[1] = INVALID_SOCKET;
}
#endif
__CFSOCKETLOG("wakeup socket pair is %d / %d\n", __CFWakeupSocketPair[0], __CFWakeupSocketPair[1]);
return error;
}
// Version 0 RunLoopSources set a mask in an FD set to control what socket activity we hear about.
// Changes to the master fs_sets occur via these 4 functions.
CF_INLINE Boolean __CFSocketSetFDForRead(CFSocketRef s) {
__CFSOCKETLOG_WS(s, "");
__CFReadSocketsTimeoutInvalid = true;
Boolean b = __CFSocketFdSet(s->_socket, __CFReadSocketsFds);
if (b && INVALID_SOCKET != __CFWakeupSocketPair[0]) {
uint8_t c = 'r';
send(__CFWakeupSocketPair[0], (const char *)&c, sizeof(c), 0);
}
return b;
}
CF_INLINE Boolean __CFSocketClearFDForRead(CFSocketRef s) {
__CFSOCKETLOG_WS(s, "");
__CFReadSocketsTimeoutInvalid = true;
Boolean b = __CFSocketFdClr(s->_socket, __CFReadSocketsFds);
if (b && INVALID_SOCKET != __CFWakeupSocketPair[0]) {
uint8_t c = 's';
send(__CFWakeupSocketPair[0], (const char *)&c, sizeof(c), 0);
}
return b;
}
CF_INLINE Boolean __CFSocketSetFDForWrite(CFSocketRef s) {
__CFSOCKETLOG_WS(s, "");
Boolean b = __CFSocketFdSet(s->_socket, __CFWriteSocketsFds);
if (b && INVALID_SOCKET != __CFWakeupSocketPair[0]) {
uint8_t c = 'w';
send(__CFWakeupSocketPair[0], (const char *)&c, sizeof(c), 0);
}
return b;
}
CF_INLINE Boolean __CFSocketClearFDForWrite(CFSocketRef s) {
__CFSOCKETLOG_WS(s, "");
Boolean b = __CFSocketFdClr(s->_socket, __CFWriteSocketsFds);
if (b && INVALID_SOCKET != __CFWakeupSocketPair[0]) {
uint8_t c = 'x';
send(__CFWakeupSocketPair[0], (const char *)&c, sizeof(c), 0);
}
return b;
}
#if TARGET_OS_WIN32
static Boolean WinSockUsed = FALSE;
static void __CFSocketInitializeWinSock_Guts(void) {
if (!WinSockUsed) {
WinSockUsed = TRUE;
WORD versionRequested = MAKEWORD(2, 2);
WSADATA wsaData;
int errorStatus = WSAStartup(versionRequested, &wsaData);
if (errorStatus != 0 || LOBYTE(wsaData.wVersion) != LOBYTE(versionRequested) || HIBYTE(wsaData.wVersion) != HIBYTE(versionRequested)) {
WSACleanup();
CFLog(kCFLogLevelWarning, CFSTR("*** Could not initialize WinSock subsystem!!!"));
}
}
}
CF_EXPORT void __CFSocketInitializeWinSock(void) {
__CFLock(&__CFActiveSocketsLock);
__CFSocketInitializeWinSock_Guts();
__CFUnlock(&__CFActiveSocketsLock);
}
CF_PRIVATE void __CFSocketCleanup(void) {
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) {
// technically this is not supposed to be called here since it will be called from dllmain, but I don't know where else to put it
WSACleanup();
}
}
#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 TARGET_OS_WIN32
__CFSocketInitializeWinSock_Guts();
#endif
if (0 > __CFSocketCreateWakeupSocketPair()) {
CFLog(kCFLogLevelWarning, CFSTR("*** Could not create wakeup socket pair for CFSocket!!!"));
} else {
UInt32 yes = 1;
/* wakeup sockets must be non-blocking */
ioctlsocket(__CFWakeupSocketPair[0], FIONBIO, (u_long *)&yes);
ioctlsocket(__CFWakeupSocketPair[1], FIONBIO, (u_long *)&yes);
__CFSocketFdSet(__CFWakeupSocketPair[1], __CFReadSocketsFds);
}
}
static CFRunLoopRef __CFSocketCopyRunLoopToWakeUp(CFRunLoopSourceRef src, CFMutableArrayRef runLoops) {
if (!src) return NULL;
CFRunLoopRef rl = NULL;
SInt32 idx, cnt = CFArrayGetCount(runLoops);
if (0 < cnt) {
rl = (CFRunLoopRef)CFArrayGetValueAtIndex(runLoops, 0);
for (idx = 1; NULL != rl && idx < cnt; idx++) {
CFRunLoopRef value = (CFRunLoopRef)CFArrayGetValueAtIndex(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(runLoops, idx);
CFStringRef currentMode = CFRunLoopCopyCurrentMode(value);
if (NULL != currentMode) {
if (CFRunLoopContainsSource(value, src, currentMode)) {
if (CFRunLoopIsWaiting(value)) {
foundIdx = idx;
foundIt = true;
} else if (!foundBackup) {
foundIdx = idx;
foundBackup = true;
}
}
CFRelease(currentMode);
}
}
rl = (CFRunLoopRef)CFArrayGetValueAtIndex(runLoops, foundIdx);
CFRetain(rl);
CFArrayRemoveValueAtIndex(runLoops, foundIdx);
CFArrayAppendValue(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 (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
if (errorCode) {
__CFSOCKETLOG_WS(s, "error %ld", (long)errorCode);
}
__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);
__CFSOCKETLOG_WS(s, "signalling write");
if (callBackNow) {
__CFSocketDoCallback(s, NULL, NULL, 0);
} else {
CFRunLoopSourceSignal(s->_source0);
CFMutableArrayRef runLoopsOrig = (CFMutableArrayRef)CFRetain(s->_runLoops);
CFMutableArrayRef runLoopsCopy = CFArrayCreateMutableCopy(kCFAllocatorSystemDefault, 0, s->_runLoops);
CFRunLoopSourceRef source0 = s->_source0;
if (NULL != source0 && !CFRunLoopSourceIsValid(source0)) {
source0 = NULL;
}
if (source0) CFRetain(source0);
__CFSocketUnlock(s);
CFRunLoopRef rl = __CFSocketCopyRunLoopToWakeUp(source0, runLoopsCopy);
if (source0) CFRelease(source0);
if (NULL != rl) {
CFRunLoopWakeUp(rl);
CFRelease(rl);
}
__CFSocketLock(s);
if (runLoopsOrig == s->_runLoops) {
s->_runLoops = runLoopsCopy;
runLoopsCopy = NULL;
CFRelease(runLoopsOrig);
}
__CFSocketUnlock(s);
CFRelease(runLoopsOrig);
if (runLoopsCopy) CFRelease(runLoopsCopy);
}
}
#if defined(LOG_CFSOCKET)
static CFStringRef someAddrToString(CFAllocatorRef alloc, int (*fun) (int, struct sockaddr*, socklen_t*), const char* name, CFSocketNativeHandle s)
{
CFStringRef resultString = NULL;
union {
struct sockaddr sa;
struct sockaddr_in sa4b;
struct sockaddr_in6 sa6b;
UInt8 static_buffer[SOCK_MAXADDRLEN];
} u;
socklen_t addrlen = sizeof(u.static_buffer);
uint16_t* pPort = NULL;
char buffer[1024];
if ((*fun) (s, &u.sa, &addrlen) != 0)
snprintf(buffer, sizeof(buffer), "error %d resolving %s address for socket %d", errno, name, s);
else {
void* pAddr = NULL;
switch (u.sa.sa_family) {
case AF_INET:
pAddr = &u.sa4b.sin_addr;
pPort = &u.sa4b.sin_port;
break;
case AF_INET6:
pAddr = &u.sa6b.sin6_addr;
pPort = &u.sa6b.sin6_port;
break;
}
if (pAddr == NULL || inet_ntop(u.sa.sa_family, pAddr, buffer, sizeof(buffer)) == NULL)
snprintf(buffer, sizeof(buffer), "[error %d converting %s address for socket %d]", pAddr != NULL? errno : EBADF, name, s);
}
if (pPort) {
resultString = CFStringCreateWithFormat(alloc, NULL, CFSTR("%s:%d"), buffer, htons(*pPort));
} else {
resultString = CFStringCreateWithFormat(alloc, NULL, CFSTR("%s"), buffer);
}
return resultString;
}
static CFStringRef copyPeerAddress(CFAllocatorRef alloc, CFSocketNativeHandle s)
{
return someAddrToString(alloc, getpeername, "peer", s);
}
static CFStringRef copyLocalAddress(CFAllocatorRef alloc, CFSocketNativeHandle s)
{
return someAddrToString(alloc, getsockname, "local", s);
}
#endif
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];
int namelen = sizeof(name);
SInt32 recvlen = 0;
if (__CFSocketIsConnectionOriented(s)) {
buffer = bufferArray;
recvlen = recvfrom(s->_socket, (char *)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, (char *)buffer, MAX_DATA_SIZE, 0, (struct sockaddr *)name, (socklen_t *)&namelen);
}
__CFSOCKETLOG_WS(s, "read %ld", (long) recvlen);
if (0 >= recvlen) {
//??? should return error if <0
/* zero-length data is the signal for perform to invalidate if socket is connection oriented */
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 (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)
) {
__CFLock(&__CFActiveSocketsLock);
/* restore socket to fds */
__CFSocketSetFDForRead(s);
__CFUnlock(&__CFActiveSocketsLock);
}
} else if (__CFSocketReadCallBackType(s) == kCFSocketAcceptCallBack) {
uint8_t name[MAX_SOCKADDR_LEN];
int namelen = sizeof(name);
sock = accept(s->_socket, (struct sockaddr *)name, (socklen_t *)&namelen);
if (INVALID_SOCKET == sock) {
//??? should return error
return;
}
if (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)
) {
__CFLock(&__CFActiveSocketsLock);
/* restore socket to fds */
__CFSocketSetFDForRead(s);
__CFUnlock(&__CFActiveSocketsLock);
}
} else {
__CFSocketLock(s);
if (!__CFSocketIsValid(s) || (s->_f.disabled & kCFSocketReadCallBack) != 0) {
__CFSocketUnlock(s);
return;
}
if (causedByTimeout) {
__CFSOCKETLOG_WS(s, "TIMEOUT RECEIVED - WILL SIGNAL IMMEDIATELY TO FLUSH (%ld buffered)", s->_bytesToBufferPos);
/* we've got a timeout, but no bytes read, and we don't have any bytes to send. Ignore the timeout. */
if (s->_bytesToBufferPos == 0 && s->_leftoverBytes == NULL) {
__CFSOCKETLOG_WS(s, "TIMEOUT - but no bytes, restoring to active set", s->_bytesToBufferPos);
// Clear the timeout notification time if there is no prefetched data left
timerclear(&s->_readBufferTimeoutNotificationTime);
__CFLock(&__CFActiveSocketsLock);
/* restore socket to fds */
__CFSocketSetFDForRead(s);
__CFUnlock(&__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);
ctRead = read(CFSocketGetNative(s), &base[s->_bytesToBufferPos], ctRemaining);
switch (ctRead) {
case -1:
if (errno == EAGAIN) { // no error
__CFLock(&__CFActiveSocketsLock);
/* restore socket to fds */
__CFSocketSetFDForRead(s);
__CFUnlock(&__CFActiveSocketsLock);
__CFSocketUnlock(s);
return;
} else {
s->_bufferedReadError = errno;
s->_atEOF = true;
}
__CFSOCKETLOG_WS(s, "BUFFERED READ GOT ERROR %d", errno);
break;
case 0:
__CFSOCKETLOG_WS(s, "DONE READING (EOF) - GOING TO SIGNAL");
s->_atEOF = true;
break;
default:
s->_bytesToBufferPos += ctRead;
if (s->_bytesToBuffer != s->_bytesToBufferPos) {
// Update the timeout notification time
struct timeval timeNow = { 0 };
gettimeofday(&timeNow, NULL);
timeradd(&timeNow, &s->_readBufferTimeout, &s->_readBufferTimeoutNotificationTime);
__CFSOCKETLOG_WS(s, "READ %ld - need %ld MORE - GOING BACK FOR MORE", ctRead, s->_bytesToBuffer - s->_bytesToBufferPos);
__CFLock(&__CFActiveSocketsLock);
/* restore socket to fds */
__CFSocketSetFDForRead(s);
__CFUnlock(&__CFActiveSocketsLock);
__CFSocketUnlock(s);
return;
} else {
// Clear the timeout notification time if the buffer is full
timerclear(&s->_readBufferTimeoutNotificationTime);
__CFSOCKETLOG_WS(s, "DONE READING (read %ld bytes) - GOING TO SIGNAL", ctRead);
}
}
}
}
__CFSocketSetReadSignalled(s);
}
__CFSOCKETLOG_WS(s, "read signaling source");
CFRunLoopSourceSignal(s->_source0);
CFMutableArrayRef runLoopsOrig = (CFMutableArrayRef)CFRetain(s->_runLoops);
CFMutableArrayRef runLoopsCopy = CFArrayCreateMutableCopy(kCFAllocatorSystemDefault, 0, s->_runLoops);
CFRunLoopSourceRef source0 = s->_source0;
if (NULL != source0 && !CFRunLoopSourceIsValid(source0)) {
source0 = NULL;
}
if (source0) CFRetain(source0);
__CFSocketUnlock(s);
CFRunLoopRef rl = __CFSocketCopyRunLoopToWakeUp(source0, runLoopsCopy);
if (source0) CFRelease(source0);
if (NULL != rl) {
CFRunLoopWakeUp(rl);
CFRelease(rl);
}
__CFSocketLock(s);
if (runLoopsOrig == s->_runLoops) {
s->_runLoops = runLoopsCopy;
runLoopsCopy = NULL;
CFRelease(runLoopsOrig);
}
__CFSocketUnlock(s);
CFRelease(runLoopsOrig);
if (runLoopsCopy) CFRelease(runLoopsCopy);
}
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);
__CFLock(&__CFActiveSocketsLock);
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.
*/
__CFSOCKETLOG_WS(s, "WARNING: shouldn't set read buffer length while data (%ld bytes) is still in the read buffer (leftover total %ld)", ctBuffer, s->_leftoverBytes? CFDataGetLength(s->_leftoverBytes) : 0);