FSRWebSocket.m 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858
  1. //
  2. // Copyright 2012 Square Inc.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. #import <Foundation/Foundation.h>
  17. #import "FSRWebSocket.h"
  18. #if __has_include(<unicode/utf8.h>)
  19. #define HAS_ICU
  20. #endif
  21. #import <sys/socket.h>
  22. #ifdef HAS_ICU
  23. #import <unicode/utf8.h>
  24. #endif
  25. #if __has_include(<Endian.h>)
  26. #import <Endian.h>
  27. #else
  28. #import <CoreServices/CoreServices.h>
  29. #endif
  30. #import <CommonCrypto/CommonDigest.h>
  31. #import <Security/SecRandom.h>
  32. #import "fbase64.h"
  33. #import "NSData+SRB64Additions.h"
  34. #if OS_OBJECT_USE_OBJC_RETAIN_RELEASE
  35. #define sr_dispatch_retain(x)
  36. #define sr_dispatch_release(x)
  37. #define maybe_bridge(x) ((__bridge void *) x)
  38. #else
  39. #define sr_dispatch_retain(x) dispatch_retain(x)
  40. #define sr_dispatch_release(x) dispatch_release(x)
  41. #define maybe_bridge(x) (x)
  42. #endif
  43. typedef enum {
  44. SROpCodeTextFrame = 0x1,
  45. SROpCodeBinaryFrame = 0x2,
  46. //3-7Reserved
  47. SROpCodeConnectionClose = 0x8,
  48. SROpCodePing = 0x9,
  49. SROpCodePong = 0xA,
  50. //B-F reserved
  51. } FSROpCode;
  52. typedef enum {
  53. SRStatusCodeNormal = 1000,
  54. SRStatusCodeGoingAway = 1001,
  55. SRStatusCodeProtocolError = 1002,
  56. SRStatusCodeUnhandledType = 1003,
  57. // 1004 reserved
  58. SRStatusNoStatusReceived = 1005,
  59. // 1004-1006 reserved
  60. SRStatusCodeInvalidUTF8 = 1007,
  61. SRStatusCodePolicyViolated = 1008,
  62. SRStatusCodeMessageTooBig = 1009,
  63. } FSRStatusCode;
  64. typedef struct {
  65. BOOL fin;
  66. // BOOL rsv1;
  67. // BOOL rsv2;
  68. // BOOL rsv3;
  69. uint8_t opcode;
  70. BOOL masked;
  71. uint64_t payload_length;
  72. } frame_header;
  73. static NSString *const SRWebSocketAppendToSecKeyString = @"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  74. static inline int32_t validate_dispatch_data_partial_string(NSData *data);
  75. static inline void SRFastLog(NSString *format, ...);
  76. @interface NSData (FSRWebSocket)
  77. - (NSString *)stringBySHA1ThenBase64Encoding;
  78. @end
  79. @interface NSString (FSRWebSocket)
  80. - (NSString *)stringBySHA1ThenBase64Encoding;
  81. @end
  82. @interface NSURL (FSRWebSocket)
  83. // The origin isn't really applicable for a native application
  84. // So instead, just map ws -> http and wss -> https
  85. - (NSString *)SR_origin;
  86. @end
  87. @interface _FSRRunLoopThread : NSThread
  88. @property (nonatomic, readonly) NSRunLoop *runLoop;
  89. @end
  90. static NSString *newSHA1String(const char *bytes, size_t length) {
  91. uint8_t md[CC_SHA1_DIGEST_LENGTH];
  92. CC_SHA1(bytes, (int)length, md);
  93. size_t buffer_size = ((sizeof(md) * 3 + 2) / 2);
  94. char *buffer = (char *)malloc(buffer_size);
  95. int len = f_b64_ntop(md, CC_SHA1_DIGEST_LENGTH, buffer, buffer_size);
  96. if (len == -1) {
  97. free(buffer);
  98. return nil;
  99. } else{
  100. return [[NSString alloc] initWithBytesNoCopy:buffer length:len encoding:NSASCIIStringEncoding freeWhenDone:YES];
  101. }
  102. }
  103. @implementation NSData (FSRWebSocket)
  104. - (NSString *)stringBySHA1ThenBase64Encoding;
  105. {
  106. return newSHA1String(self.bytes, self.length);
  107. }
  108. @end
  109. @implementation NSString (FSRWebSocket)
  110. - (NSString *)stringBySHA1ThenBase64Encoding;
  111. {
  112. return newSHA1String(self.UTF8String, self.length);
  113. }
  114. @end
  115. NSString *const FSRWebSocketErrorDomain = @"FSRWebSocketErrorDomain";
  116. // Returns number of bytes consumed. returning 0 means you didn't match.
  117. // Sends bytes to callback handler;
  118. typedef size_t (^stream_scanner)(NSData *collected_data);
  119. typedef void (^data_callback)(FSRWebSocket *webSocket, NSData *data);
  120. @interface FSRIOConsumer : NSObject {
  121. stream_scanner _scanner;
  122. data_callback _handler;
  123. size_t _bytesNeeded;
  124. BOOL _readToCurrentFrame;
  125. BOOL _unmaskBytes;
  126. }
  127. @property (nonatomic, copy, readonly) stream_scanner consumer;
  128. @property (nonatomic, copy, readonly) data_callback handler;
  129. @property (nonatomic, assign) size_t bytesNeeded;
  130. @property (nonatomic, assign, readonly) BOOL readToCurrentFrame;
  131. @property (nonatomic, assign, readonly) BOOL unmaskBytes;
  132. @end
  133. // This class is not thread-safe, and is expected to always be run on the same queue.
  134. @interface FSRIOConsumerPool : NSObject
  135. - (id)initWithBufferCapacity:(NSUInteger)poolSize;
  136. - (FSRIOConsumer *)consumerWithScanner:(stream_scanner)scanner handler:(data_callback)handler bytesNeeded:(size_t)bytesNeeded readToCurrentFrame:(BOOL)readToCurrentFrame unmaskBytes:(BOOL)unmaskBytes;
  137. - (void)returnConsumer:(FSRIOConsumer *)consumer;
  138. @end
  139. @interface FSRWebSocket () <NSStreamDelegate>
  140. - (void)_writeData:(NSData *)data;
  141. - (void)_closeWithProtocolError:(NSString *)message;
  142. - (void)_failWithError:(NSError *)error;
  143. - (void)_disconnect;
  144. - (void)_readFrameNew;
  145. - (void)_readFrameContinue;
  146. - (void)_pumpScanner;
  147. - (void)_pumpWriting;
  148. - (void)_addConsumerWithScanner:(stream_scanner)consumer callback:(data_callback)callback;
  149. - (void)_addConsumerWithDataLength:(size_t)dataLength callback:(data_callback)callback readToCurrentFrame:(BOOL)readToCurrentFrame unmaskBytes:(BOOL)unmaskBytes;
  150. - (void)_addConsumerWithScanner:(stream_scanner)consumer callback:(data_callback)callback dataLength:(size_t)dataLength;
  151. - (void)_readUntilBytes:(const void *)bytes length:(size_t)length callback:(data_callback)dataHandler;
  152. - (void)_readUntilHeaderCompleteWithCallback:(data_callback)dataHandler;
  153. - (void)_sendFrameWithOpcode:(FSROpCode)opcode data:(id)data;
  154. - (BOOL)_checkHandshake:(CFHTTPMessageRef)httpMessage;
  155. - (void)_SR_commonInit;
  156. - (void)_initializeStreams;
  157. - (void)_connect;
  158. @property (nonatomic) FSRReadyState readyState;
  159. @property (nonatomic) NSOperationQueue *delegateOperationQueue;
  160. @property (nonatomic) dispatch_queue_t delegateDispatchQueue;
  161. @end
  162. @implementation FSRWebSocket {
  163. NSInteger _webSocketVersion;
  164. NSOperationQueue *_delegateOperationQueue;
  165. dispatch_queue_t _delegateDispatchQueue;
  166. dispatch_queue_t _workQueue;
  167. NSMutableArray *_consumers;
  168. NSInputStream *_inputStream;
  169. NSOutputStream *_outputStream;
  170. NSMutableData *_readBuffer;
  171. NSInteger _readBufferOffset;
  172. NSMutableData *_outputBuffer;
  173. NSInteger _outputBufferOffset;
  174. uint8_t _currentFrameOpcode;
  175. size_t _currentFrameCount;
  176. size_t _readOpCount;
  177. uint32_t _currentStringScanPosition;
  178. NSMutableData *_currentFrameData;
  179. NSString *_closeReason;
  180. NSString *_secKey;
  181. BOOL _pinnedCertFound;
  182. uint8_t _currentReadMaskKey[4];
  183. size_t _currentReadMaskOffset;
  184. BOOL _consumerStopped;
  185. BOOL _closeWhenFinishedWriting;
  186. BOOL _failed;
  187. BOOL _secure;
  188. NSURLRequest *_urlRequest;
  189. NSString *_userAgent;
  190. CFHTTPMessageRef _receivedHTTPHeaders;
  191. BOOL _sentClose;
  192. BOOL _didFail;
  193. BOOL _cleanupScheduled;
  194. int _closeCode;
  195. BOOL _isPumping;
  196. NSMutableSet *_scheduledRunloops;
  197. // We use this to retain ourselves.
  198. __strong FSRWebSocket *_selfRetain;
  199. NSArray *_requestedProtocols;
  200. FSRIOConsumerPool *_consumerPool;
  201. }
  202. @synthesize delegate = _delegate;
  203. @synthesize url = _url;
  204. @synthesize readyState = _readyState;
  205. @synthesize protocol = _protocol;
  206. static __strong NSData *CRLFCRLF;
  207. + (void)initialize;
  208. {
  209. CRLFCRLF = [[NSData alloc] initWithBytes:"\r\n\r\n" length:4];
  210. }
  211. - (id)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray *)protocols queue:(dispatch_queue_t)queue andUserAgent:(NSString *)userAgent;
  212. {
  213. self = [super init];
  214. if (self) {
  215. assert(request.URL);
  216. _url = request.URL;
  217. NSString *scheme = [_url scheme];
  218. _requestedProtocols = [protocols copy];
  219. _userAgent = userAgent;
  220. assert([scheme isEqualToString:@"ws"] || [scheme isEqualToString:@"http"] || [scheme isEqualToString:@"wss"] || [scheme isEqualToString:@"https"]);
  221. _urlRequest = request;
  222. if ([scheme isEqualToString:@"wss"] || [scheme isEqualToString:@"https"]) {
  223. _secure = YES;
  224. }
  225. if (!queue) {
  226. _delegateDispatchQueue = dispatch_get_main_queue();
  227. } else {
  228. _delegateDispatchQueue = queue;
  229. }
  230. [self _SR_commonInit];
  231. }
  232. return self;
  233. }
  234. - (id)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray *)protocols;
  235. {
  236. return [self initWithURLRequest:request protocols:nil queue:nil andUserAgent:nil];
  237. }
  238. - (id)initWithURLRequest:(NSURLRequest *)request queue:(dispatch_queue_t)queue andUserAgent:(NSString *)userAgent;
  239. {
  240. return [self initWithURLRequest:request protocols:nil queue:queue andUserAgent:userAgent];
  241. }
  242. - (id)initWithURLRequest:(NSURLRequest *)request;
  243. {
  244. return [self initWithURLRequest:request protocols:nil];
  245. }
  246. - (id)initWithURL:(NSURL *)url;
  247. {
  248. return [self initWithURL:url protocols:nil];
  249. }
  250. - (id)initWithURL:(NSURL *)url protocols:(NSArray *)protocols;
  251. {
  252. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
  253. return [self initWithURLRequest:request protocols:protocols];
  254. }
  255. - (void)_SR_commonInit;
  256. {
  257. _readyState = SR_CONNECTING;
  258. _consumerStopped = YES;
  259. _webSocketVersion = 13;
  260. _workQueue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
  261. // Going to set a specific on the queue so we can validate we're on the work queue
  262. dispatch_queue_set_specific(_workQueue, (__bridge void *)self, maybe_bridge(_workQueue), NULL);
  263. sr_dispatch_retain(_delegateDispatchQueue);
  264. _readBuffer = [[NSMutableData alloc] init];
  265. _outputBuffer = [[NSMutableData alloc] init];
  266. _currentFrameData = [[NSMutableData alloc] init];
  267. _consumers = [[NSMutableArray alloc] init];
  268. _consumerPool = [[FSRIOConsumerPool alloc] init];
  269. _scheduledRunloops = [[NSMutableSet alloc] init];
  270. [self _initializeStreams];
  271. // default handlers
  272. }
  273. - (void)assertOnWorkQueue;
  274. {
  275. assert(dispatch_get_specific((__bridge void *)self) == maybe_bridge(_workQueue));
  276. }
  277. - (void)dealloc
  278. {
  279. _inputStream.delegate = nil;
  280. _outputStream.delegate = nil;
  281. [_inputStream close];
  282. [_outputStream close];
  283. sr_dispatch_release(_workQueue);
  284. _workQueue = NULL;
  285. if (_receivedHTTPHeaders) {
  286. CFRelease(_receivedHTTPHeaders);
  287. _receivedHTTPHeaders = NULL;
  288. }
  289. if (_delegateDispatchQueue) {
  290. sr_dispatch_release(_delegateDispatchQueue);
  291. _delegateDispatchQueue = NULL;
  292. }
  293. }
  294. #ifndef NDEBUG
  295. - (void)setReadyState:(FSRReadyState)aReadyState;
  296. {
  297. [self willChangeValueForKey:@"readyState"];
  298. assert(aReadyState > _readyState);
  299. _readyState = aReadyState;
  300. [self didChangeValueForKey:@"readyState"];
  301. }
  302. #endif
  303. - (void)open;
  304. {
  305. assert(_url);
  306. NSAssert(_readyState == SR_CONNECTING, @"Cannot call -(void)open on SRWebSocket more than once");
  307. _selfRetain = self;
  308. [self _connect];
  309. }
  310. // Calls block on delegate queue
  311. - (void)_performDelegateBlock:(dispatch_block_t)block;
  312. {
  313. if (_delegateOperationQueue) {
  314. [_delegateOperationQueue addOperationWithBlock:block];
  315. } else {
  316. assert(_delegateDispatchQueue);
  317. dispatch_async(_delegateDispatchQueue, block);
  318. }
  319. }
  320. - (void)setDelegateDispatchQueue:(dispatch_queue_t)queue;
  321. {
  322. if (queue) {
  323. sr_dispatch_retain(queue);
  324. }
  325. if (_delegateDispatchQueue) {
  326. sr_dispatch_release(_delegateDispatchQueue);
  327. }
  328. _delegateDispatchQueue = queue;
  329. }
  330. - (BOOL)_checkHandshake:(CFHTTPMessageRef)httpMessage;
  331. {
  332. NSString *acceptHeader = CFBridgingRelease(CFHTTPMessageCopyHeaderFieldValue(httpMessage, CFSTR("Sec-WebSocket-Accept")));
  333. if (acceptHeader == nil) {
  334. return NO;
  335. }
  336. NSString *concattedString = [_secKey stringByAppendingString:SRWebSocketAppendToSecKeyString];
  337. NSString *expectedAccept = [concattedString stringBySHA1ThenBase64Encoding];
  338. return [acceptHeader isEqualToString:expectedAccept];
  339. }
  340. - (void)_HTTPHeadersDidFinish;
  341. {
  342. NSInteger responseCode = CFHTTPMessageGetResponseStatusCode(_receivedHTTPHeaders);
  343. if (responseCode >= 400) {
  344. SRFastLog(@"Request failed with response code %d", responseCode);
  345. [self _failWithError:[NSError errorWithDomain:@"org.lolrus.SocketRocket" code:2132 userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"received bad response code from server %u", (int)responseCode] forKey:NSLocalizedDescriptionKey]]];
  346. return;
  347. }
  348. if(![self _checkHandshake:_receivedHTTPHeaders]) {
  349. [self _failWithError:[NSError errorWithDomain:FSRWebSocketErrorDomain code:2133 userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Invalid Sec-WebSocket-Accept response"] forKey:NSLocalizedDescriptionKey]]];
  350. return;
  351. }
  352. NSString *negotiatedProtocol = CFBridgingRelease(CFHTTPMessageCopyHeaderFieldValue(_receivedHTTPHeaders, CFSTR("Sec-WebSocket-Protocol")));
  353. if (negotiatedProtocol) {
  354. // Make sure we requested the protocol
  355. if ([_requestedProtocols indexOfObject:negotiatedProtocol] == NSNotFound) {
  356. [self _failWithError:[NSError errorWithDomain:FSRWebSocketErrorDomain code:2133 userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Server specified Sec-WebSocket-Protocol that wasn't requested"] forKey:NSLocalizedDescriptionKey]]];
  357. return;
  358. }
  359. _protocol = negotiatedProtocol;
  360. }
  361. self.readyState = SR_OPEN;
  362. if (!_didFail) {
  363. [self _readFrameNew];
  364. }
  365. [self _performDelegateBlock:^{
  366. if ([self.delegate respondsToSelector:@selector(webSocketDidOpen:)]) {
  367. [self.delegate webSocketDidOpen:self];
  368. };
  369. }];
  370. }
  371. - (void)_readHTTPHeader;
  372. {
  373. if (_receivedHTTPHeaders == NULL) {
  374. _receivedHTTPHeaders = CFHTTPMessageCreateEmpty(NULL, NO);
  375. }
  376. [self _readUntilHeaderCompleteWithCallback:^(FSRWebSocket *self, NSData *data) {
  377. CFHTTPMessageAppendBytes(self->_receivedHTTPHeaders, (const UInt8 *)data.bytes, data.length);
  378. if (CFHTTPMessageIsHeaderComplete(self->_receivedHTTPHeaders)) {
  379. SRFastLog(@"Finished reading headers %@", CFBridgingRelease(CFHTTPMessageCopyAllHeaderFields(self->_receivedHTTPHeaders)));
  380. [self _HTTPHeadersDidFinish];
  381. } else {
  382. [self _readHTTPHeader];
  383. }
  384. }];
  385. }
  386. - (void)didConnect
  387. {
  388. SRFastLog(@"Connected");
  389. CFHTTPMessageRef request = CFHTTPMessageCreateRequest(NULL, CFSTR("GET"), (__bridge CFURLRef)_url, kCFHTTPVersion1_1);
  390. // Set host first so it defaults
  391. CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Host"), (__bridge CFStringRef)
  392. (_url.port != nil ? [NSString stringWithFormat:@"%@:%@",
  393. _url.host, _url.port] : _url.host));
  394. NSMutableData *keyBytes = [[NSMutableData alloc] initWithLength:16];
  395. int result = SecRandomCopyBytes(kSecRandomDefault, keyBytes.length, keyBytes.mutableBytes);
  396. assert(result == 0);
  397. _secKey = [FSRUtilities base64EncodedStringFromData:keyBytes];
  398. assert([_secKey length] == 24);
  399. CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Upgrade"), CFSTR("websocket"));
  400. CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Connection"), CFSTR("Upgrade"));
  401. if (_userAgent) {
  402. CFHTTPMessageSetHeaderFieldValue(request, CFSTR("User-Agent"), (__bridge CFStringRef)_userAgent);
  403. }
  404. CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Sec-WebSocket-Key"), (__bridge CFStringRef)_secKey);
  405. CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Sec-WebSocket-Version"), (__bridge CFStringRef)[NSString stringWithFormat:@"%u", (int)_webSocketVersion]);
  406. CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Origin"), (__bridge CFStringRef)_url.SR_origin);
  407. if (_requestedProtocols) {
  408. CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Sec-WebSocket-Protocol"), (__bridge CFStringRef)[_requestedProtocols componentsJoinedByString:@", "]);
  409. }
  410. [_urlRequest.allHTTPHeaderFields enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
  411. CFHTTPMessageSetHeaderFieldValue(request, (__bridge CFStringRef)key, (__bridge CFStringRef)obj);
  412. }];
  413. NSData *message = CFBridgingRelease(CFHTTPMessageCopySerializedMessage(request));
  414. CFRelease(request);
  415. [self _writeData:message];
  416. [self _readHTTPHeader];
  417. }
  418. //- (void)_connectToHost:(NSString *)host port:(NSInteger)port;
  419. - (void)_initializeStreams;
  420. {
  421. NSInteger port = _url.port.integerValue;
  422. if (port == 0) {
  423. if (!_secure) {
  424. port = 80;
  425. } else {
  426. port = 443;
  427. }
  428. }
  429. NSString *host = _url.host;
  430. CFReadStreamRef readStream = NULL;
  431. CFWriteStreamRef writeStream = NULL;
  432. CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, (int)port, &readStream, &writeStream);
  433. // XXX
  434. CFReadStreamSetProperty(readStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeBackground);
  435. CFWriteStreamSetProperty(writeStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeBackground);
  436. _outputStream = CFBridgingRelease(writeStream);
  437. _inputStream = CFBridgingRelease(readStream);
  438. if (_secure) {
  439. NSMutableDictionary *SSLOptions = [[NSMutableDictionary alloc] init];
  440. [_outputStream setProperty:(__bridge id)kCFStreamSocketSecurityLevelNegotiatedSSL forKey:(__bridge id)kCFStreamPropertySocketSecurityLevel];
  441. // If we're using pinned certs, don't validate the certificate chain
  442. if ([_urlRequest FSR_SSLPinnedCertificates].count) {
  443. [SSLOptions setValue:[NSNumber numberWithBool:NO] forKey:(__bridge id)kCFStreamSSLValidatesCertificateChain];
  444. }
  445. [_outputStream setProperty:SSLOptions
  446. forKey:(__bridge id)kCFStreamPropertySSLSettings];
  447. }
  448. _inputStream.delegate = self;
  449. _outputStream.delegate = self;
  450. [_outputStream open];
  451. [_inputStream open];
  452. }
  453. - (void)_connect;
  454. {
  455. if (!_scheduledRunloops.count) {
  456. [self scheduleInRunLoop:[NSRunLoop FSR_networkRunLoop] forMode:NSDefaultRunLoopMode];
  457. }
  458. [_outputStream open];
  459. [_inputStream open];
  460. }
  461. - (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
  462. {
  463. [_outputStream scheduleInRunLoop:aRunLoop forMode:mode];
  464. [_inputStream scheduleInRunLoop:aRunLoop forMode:mode];
  465. [_scheduledRunloops addObject:@[aRunLoop, mode]];
  466. }
  467. - (void)unscheduleFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
  468. {
  469. [_outputStream removeFromRunLoop:aRunLoop forMode:mode];
  470. [_inputStream removeFromRunLoop:aRunLoop forMode:mode];
  471. [_scheduledRunloops removeObject:@[aRunLoop, mode]];
  472. }
  473. - (void)close;
  474. {
  475. [self closeWithCode:-1 reason:nil];
  476. }
  477. - (void)closeWithCode:(NSInteger)code reason:(NSString *)reason;
  478. {
  479. assert(code);
  480. dispatch_async(_workQueue, ^{
  481. if (self.readyState == SR_CLOSING || self.readyState == SR_CLOSED) {
  482. return;
  483. }
  484. BOOL wasConnecting = self.readyState == SR_CONNECTING;
  485. self.readyState = SR_CLOSING;
  486. SRFastLog(@"Closing with code %d reason %@", code, reason);
  487. if (wasConnecting) {
  488. [self _disconnect];
  489. return;
  490. }
  491. size_t maxMsgSize = [reason maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  492. NSMutableData *mutablePayload = [[NSMutableData alloc] initWithLength:sizeof(uint16_t) + maxMsgSize];
  493. NSData *payload = mutablePayload;
  494. ((uint16_t *)mutablePayload.mutableBytes)[0] = EndianU16_BtoN(code);
  495. if (reason) {
  496. NSRange remainingRange = {0};
  497. NSUInteger usedLength = 0;
  498. BOOL success = [reason getBytes:(char *)mutablePayload.mutableBytes + sizeof(uint16_t) maxLength:payload.length - sizeof(uint16_t) usedLength:&usedLength encoding:NSUTF8StringEncoding options:NSStringEncodingConversionExternalRepresentation range:NSMakeRange(0, reason.length) remainingRange:&remainingRange];
  499. assert(success);
  500. assert(remainingRange.length == 0);
  501. if (usedLength != maxMsgSize) {
  502. payload = [payload subdataWithRange:NSMakeRange(0, usedLength + sizeof(uint16_t))];
  503. }
  504. }
  505. [self _sendFrameWithOpcode:SROpCodeConnectionClose data:payload];
  506. });
  507. }
  508. - (void)_closeWithProtocolError:(NSString *)message;
  509. {
  510. // Need to shunt this on the _callbackQueue first to see if they received any messages
  511. [self _performDelegateBlock:^{
  512. [self closeWithCode:SRStatusCodeProtocolError reason:message];
  513. dispatch_async(self->_workQueue, ^{
  514. [self _disconnect];
  515. });
  516. }];
  517. }
  518. - (void)_failWithError:(NSError *)error;
  519. {
  520. dispatch_async(_workQueue, ^{
  521. if (self.readyState != SR_CLOSED) {
  522. self->_failed = YES;
  523. [self _performDelegateBlock:^{
  524. if ([self.delegate respondsToSelector:@selector(webSocket:didFailWithError:)]) {
  525. [self.delegate webSocket:self didFailWithError:error];
  526. }
  527. }];
  528. self.readyState = SR_CLOSED;
  529. SRFastLog(@"Failing with error %@", error.localizedDescription);
  530. [self _disconnect];
  531. [self _scheduleCleanup];
  532. }
  533. });
  534. }
  535. - (void)_writeData:(NSData *)data;
  536. {
  537. [self assertOnWorkQueue];
  538. if (_closeWhenFinishedWriting) {
  539. return;
  540. }
  541. [_outputBuffer appendData:data];
  542. [self _pumpWriting];
  543. }
  544. - (void)send:(id)data;
  545. {
  546. SRFastLog(@"Sending data %@", data);
  547. NSAssert(self.readyState != SR_CONNECTING, @"Invalid State: Cannot call send: until connection is open");
  548. // TODO: maybe not copy this for performance
  549. data = [data copy];
  550. dispatch_async(_workQueue, ^{
  551. if ([data isKindOfClass:[NSString class]]) {
  552. [self _sendFrameWithOpcode:SROpCodeTextFrame data:[(NSString *)data dataUsingEncoding:NSUTF8StringEncoding]];
  553. } else if ([data isKindOfClass:[NSData class]]) {
  554. [self _sendFrameWithOpcode:SROpCodeBinaryFrame data:data];
  555. } else if (data == nil) {
  556. [self _sendFrameWithOpcode:SROpCodeTextFrame data:data];
  557. } else {
  558. assert(NO);
  559. }
  560. });
  561. }
  562. - (void)handlePing:(NSData *)pingData;
  563. {
  564. // Need to pingpong this off _callbackQueue first to make sure messages happen in order
  565. [self _performDelegateBlock:^{
  566. dispatch_async(self->_workQueue, ^{
  567. [self _sendFrameWithOpcode:SROpCodePong data:pingData];
  568. });
  569. }];
  570. }
  571. - (void)handlePong;
  572. {
  573. // NOOP
  574. }
  575. - (void)_handleMessage:(id)message
  576. {
  577. SRFastLog(@"Received message");
  578. [self _performDelegateBlock:^{
  579. if ([self.delegate respondsToSelector:@selector(webSocket:didReceiveMessage:)]) {
  580. [self.delegate webSocket:self didReceiveMessage:message];
  581. }
  582. }];
  583. }
  584. static inline BOOL closeCodeIsValid(int closeCode) {
  585. if (closeCode < 1000) {
  586. return NO;
  587. }
  588. if (closeCode >= 1000 && closeCode <= 1011) {
  589. if (closeCode == 1004 ||
  590. closeCode == 1005 ||
  591. closeCode == 1006) {
  592. return NO;
  593. }
  594. return YES;
  595. }
  596. if (closeCode >= 3000 && closeCode <= 3999) {
  597. return YES;
  598. }
  599. if (closeCode >= 4000 && closeCode <= 4999) {
  600. return YES;
  601. }
  602. return NO;
  603. }
  604. // Note from RFC:
  605. //
  606. // If there is a body, the first two
  607. // bytes of the body MUST be a 2-byte unsigned integer (in network byte
  608. // order) representing a status code with value /code/ defined in
  609. // Section 7.4. Following the 2-byte integer the body MAY contain UTF-8
  610. // encoded data with value /reason/, the interpretation of which is not
  611. // defined by this specification.
  612. - (void)handleCloseWithData:(NSData *)data;
  613. {
  614. size_t dataSize = data.length;
  615. __block uint16_t closeCode = 0;
  616. SRFastLog(@"Received close frame");
  617. if (dataSize == 1) {
  618. // TODO handle error
  619. [self _closeWithProtocolError:@"Payload for close must be larger than 2 bytes"];
  620. return;
  621. } else if (dataSize >= 2) {
  622. [data getBytes:&closeCode length:sizeof(closeCode)];
  623. _closeCode = EndianU16_BtoN(closeCode);
  624. if (!closeCodeIsValid(_closeCode)) {
  625. [self _closeWithProtocolError:[NSString stringWithFormat:@"Cannot have close code of %d", _closeCode]];
  626. return;
  627. }
  628. if (dataSize > 2) {
  629. _closeReason = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(2, dataSize - 2)] encoding:NSUTF8StringEncoding];
  630. if (!_closeReason) {
  631. [self _closeWithProtocolError:@"Close reason MUST be valid UTF-8"];
  632. return;
  633. }
  634. }
  635. } else {
  636. _closeCode = SRStatusNoStatusReceived;
  637. }
  638. [self assertOnWorkQueue];
  639. if (self.readyState == SR_OPEN) {
  640. [self closeWithCode:1000 reason:nil];
  641. }
  642. dispatch_async(_workQueue, ^{
  643. [self _disconnect];
  644. });
  645. }
  646. - (void)_disconnect;
  647. {
  648. [self assertOnWorkQueue];
  649. SRFastLog(@"Trying to disconnect");
  650. _closeWhenFinishedWriting = YES;
  651. [self _pumpWriting];
  652. }
  653. - (void)_handleFrameWithData:(NSData *)frameData opCode:(NSInteger)opcode;
  654. {
  655. // Check that the current data is valid UTF8
  656. BOOL isControlFrame = (opcode == SROpCodePing || opcode == SROpCodePong || opcode == SROpCodeConnectionClose);
  657. if (!isControlFrame) {
  658. [self _readFrameNew];
  659. } else {
  660. dispatch_async(_workQueue, ^{
  661. [self _readFrameContinue];
  662. });
  663. }
  664. switch (opcode) {
  665. case SROpCodeTextFrame: {
  666. NSString *str = [[NSString alloc] initWithData:frameData encoding:NSUTF8StringEncoding];
  667. if (str == nil && frameData) {
  668. [self closeWithCode:SRStatusCodeInvalidUTF8 reason:@"Text frames must be valid UTF-8"];
  669. dispatch_async(_workQueue, ^{
  670. [self _disconnect];
  671. });
  672. return;
  673. }
  674. [self _handleMessage:str];
  675. break;
  676. }
  677. case SROpCodeBinaryFrame:
  678. [self _handleMessage:[frameData copy]];
  679. break;
  680. case SROpCodeConnectionClose:
  681. [self handleCloseWithData:frameData];
  682. break;
  683. case SROpCodePing:
  684. [self handlePing:frameData];
  685. break;
  686. case SROpCodePong:
  687. [self handlePong];
  688. break;
  689. default:
  690. [self _closeWithProtocolError:[NSString stringWithFormat:@"Unknown opcode %u", (int)opcode]];
  691. // TODO: Handle invalid opcode
  692. break;
  693. }
  694. }
  695. - (void)_handleFrameHeader:(frame_header)frame_header curData:(NSData *)curData;
  696. {
  697. assert(frame_header.opcode != 0);
  698. if (self.readyState != SR_OPEN) {
  699. return;
  700. }
  701. BOOL isControlFrame = (frame_header.opcode == SROpCodePing || frame_header.opcode == SROpCodePong || frame_header.opcode == SROpCodeConnectionClose);
  702. if (isControlFrame && !frame_header.fin) {
  703. [self _closeWithProtocolError:@"Fragmented control frames not allowed"];
  704. return;
  705. }
  706. if (isControlFrame && frame_header.payload_length >= 126) {
  707. [self _closeWithProtocolError:@"Control frames cannot have payloads larger than 126 bytes"];
  708. return;
  709. }
  710. if (!isControlFrame) {
  711. _currentFrameOpcode = frame_header.opcode;
  712. _currentFrameCount += 1;
  713. }
  714. if (frame_header.payload_length == 0) {
  715. if (isControlFrame) {
  716. [self _handleFrameWithData:curData opCode:frame_header.opcode];
  717. } else {
  718. if (frame_header.fin) {
  719. [self _handleFrameWithData:_currentFrameData opCode:frame_header.opcode];
  720. } else {
  721. // TODO add assert that opcode is not a control;
  722. [self _readFrameContinue];
  723. }
  724. }
  725. } else {
  726. [self _addConsumerWithDataLength:(size_t)frame_header.payload_length callback:^(FSRWebSocket *self, NSData *newData) {
  727. if (isControlFrame) {
  728. [self _handleFrameWithData:newData opCode:frame_header.opcode];
  729. } else {
  730. if (frame_header.fin) {
  731. [self _handleFrameWithData:self->_currentFrameData opCode:frame_header.opcode];
  732. } else {
  733. // TODO add assert that opcode is not a control;
  734. [self _readFrameContinue];
  735. }
  736. }
  737. } readToCurrentFrame:!isControlFrame unmaskBytes:frame_header.masked];
  738. }
  739. }
  740. /* From RFC:
  741. 0 1 2 3
  742. 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
  743. +-+-+-+-+-------+-+-------------+-------------------------------+
  744. |F|R|R|R| opcode|M| Payload len | Extended payload length |
  745. |I|S|S|S| (4) |A| (7) | (16/64) |
  746. |N|V|V|V| |S| | (if payload len==126/127) |
  747. | |1|2|3| |K| | |
  748. +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
  749. | Extended payload length continued, if payload len == 127 |
  750. + - - - - - - - - - - - - - - - +-------------------------------+
  751. | |Masking-key, if MASK set to 1 |
  752. +-------------------------------+-------------------------------+
  753. | Masking-key (continued) | Payload Data |
  754. +-------------------------------- - - - - - - - - - - - - - - - +
  755. : Payload Data continued ... :
  756. + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
  757. | Payload Data continued ... |
  758. +---------------------------------------------------------------+
  759. */
  760. static const uint8_t SRFinMask = 0x80;
  761. static const uint8_t SROpCodeMask = 0x0F;
  762. static const uint8_t SRRsvMask = 0x70;
  763. static const uint8_t SRMaskMask = 0x80;
  764. static const uint8_t SRPayloadLenMask = 0x7F;
  765. - (void)_readFrameContinue;
  766. {
  767. assert((_currentFrameCount == 0 && _currentFrameOpcode == 0) || (_currentFrameCount > 0 && _currentFrameOpcode > 0));
  768. [self _addConsumerWithDataLength:2 callback:^(FSRWebSocket *self, NSData *data) {
  769. __block frame_header header = {0};
  770. const uint8_t *headerBuffer = data.bytes;
  771. assert(data.length >= 2);
  772. if (headerBuffer[0] & SRRsvMask) {
  773. [self _closeWithProtocolError:@"Server used RSV bits"];
  774. return;
  775. }
  776. uint8_t receivedOpcode = (SROpCodeMask & headerBuffer[0]);
  777. BOOL isControlFrame = (receivedOpcode == SROpCodePing || receivedOpcode == SROpCodePong || receivedOpcode == SROpCodeConnectionClose);
  778. if (!isControlFrame && receivedOpcode != 0 && self->_currentFrameCount > 0) {
  779. [self _closeWithProtocolError:@"all data frames after the initial data frame must have opcode 0"];
  780. return;
  781. }
  782. if (receivedOpcode == 0 && self->_currentFrameCount == 0) {
  783. [self _closeWithProtocolError:@"cannot continue a message"];
  784. return;
  785. }
  786. header.opcode = receivedOpcode == 0 ? self->_currentFrameOpcode : receivedOpcode;
  787. header.fin = !!(SRFinMask & headerBuffer[0]);
  788. header.masked = !!(SRMaskMask & headerBuffer[1]);
  789. header.payload_length = SRPayloadLenMask & headerBuffer[1];
  790. headerBuffer = NULL;
  791. if (header.masked) {
  792. [self _closeWithProtocolError:@"Client must receive unmasked data"];
  793. }
  794. size_t extra_bytes_needed = header.masked ? sizeof(self->_currentReadMaskKey) : 0;
  795. if (header.payload_length == 126) {
  796. extra_bytes_needed += sizeof(uint16_t);
  797. } else if (header.payload_length == 127) {
  798. extra_bytes_needed += sizeof(uint64_t);
  799. }
  800. if (extra_bytes_needed == 0) {
  801. [self _handleFrameHeader:header curData:self->_currentFrameData];
  802. } else {
  803. [self _addConsumerWithDataLength:extra_bytes_needed callback:^(FSRWebSocket *self, NSData *data) {
  804. size_t mapped_size = data.length;
  805. const void *mapped_buffer = data.bytes;
  806. size_t offset = 0;
  807. if (header.payload_length == 126) {
  808. assert(mapped_size >= sizeof(uint16_t));
  809. uint16_t newLen = EndianU16_BtoN(*(uint16_t *)(mapped_buffer));
  810. header.payload_length = newLen;
  811. offset += sizeof(uint16_t);
  812. } else if (header.payload_length == 127) {
  813. assert(mapped_size >= sizeof(uint64_t));
  814. header.payload_length = EndianU64_BtoN(*(uint64_t *)(mapped_buffer));
  815. offset += sizeof(uint64_t);
  816. } else {
  817. assert(header.payload_length < 126 && header.payload_length >= 0);
  818. }
  819. if (header.masked) {
  820. assert(mapped_size >= sizeof(self->_currentReadMaskOffset) + offset);
  821. memcpy(self->_currentReadMaskKey, ((uint8_t *)mapped_buffer) + offset, sizeof(self->_currentReadMaskKey));
  822. }
  823. [self _handleFrameHeader:header curData:self->_currentFrameData];
  824. } readToCurrentFrame:NO unmaskBytes:NO];
  825. }
  826. } readToCurrentFrame:NO unmaskBytes:NO];
  827. }
  828. - (void)_readFrameNew;
  829. {
  830. dispatch_async(_workQueue, ^{
  831. [self->_currentFrameData setLength:0];
  832. self->_currentFrameOpcode = 0;
  833. self->_currentFrameCount = 0;
  834. self->_readOpCount = 0;
  835. self->_currentStringScanPosition = 0;
  836. [self _readFrameContinue];
  837. });
  838. }
  839. - (void)_pumpWriting;
  840. {
  841. [self assertOnWorkQueue];
  842. NSUInteger dataLength = _outputBuffer.length;
  843. if (dataLength - _outputBufferOffset > 0 && _outputStream.hasSpaceAvailable) {
  844. NSUInteger bytesWritten = [_outputStream write:_outputBuffer.bytes + _outputBufferOffset maxLength:dataLength - _outputBufferOffset];
  845. if (bytesWritten == -1) {
  846. [self _failWithError:[NSError errorWithDomain:@"org.lolrus.SocketRocket" code:2145 userInfo:[NSDictionary dictionaryWithObject:@"Error writing to stream" forKey:NSLocalizedDescriptionKey]]];
  847. return;
  848. }
  849. _outputBufferOffset += bytesWritten;
  850. if (_outputBufferOffset > 4096 && _outputBufferOffset > (_outputBuffer.length >> 1)) {
  851. _outputBuffer = [[NSMutableData alloc] initWithBytes:(char *)_outputBuffer.bytes + _outputBufferOffset length:_outputBuffer.length - _outputBufferOffset];
  852. _outputBufferOffset = 0;
  853. }
  854. }
  855. if (_closeWhenFinishedWriting &&
  856. _outputBuffer.length - _outputBufferOffset == 0 &&
  857. (_inputStream.streamStatus != NSStreamStatusNotOpen &&
  858. _inputStream.streamStatus != NSStreamStatusClosed) &&
  859. !_sentClose) {
  860. _sentClose = YES;
  861. @synchronized (self) {
  862. [_outputStream close];
  863. [_inputStream close];
  864. // TODO: Why are we missing the SocketRocket code to call unscheduleFromRunLoop???
  865. }
  866. if (!_failed) {
  867. [self _performDelegateBlock:^{
  868. if ([self.delegate respondsToSelector:@selector(webSocket:didCloseWithCode:reason:wasClean:)]) {
  869. [self.delegate webSocket:self didCloseWithCode:self->_closeCode reason:self->_closeReason wasClean:YES];
  870. }
  871. }];
  872. }
  873. [self _scheduleCleanup];
  874. }
  875. }
  876. - (void)_addConsumerWithScanner:(stream_scanner)consumer callback:(data_callback)callback;
  877. {
  878. [self assertOnWorkQueue];
  879. [self _addConsumerWithScanner:consumer callback:callback dataLength:0];
  880. }
  881. - (void)_addConsumerWithDataLength:(size_t)dataLength callback:(data_callback)callback readToCurrentFrame:(BOOL)readToCurrentFrame unmaskBytes:(BOOL)unmaskBytes;
  882. {
  883. [self assertOnWorkQueue];
  884. assert(dataLength);
  885. [_consumers addObject:[_consumerPool consumerWithScanner:nil handler:callback bytesNeeded:dataLength readToCurrentFrame:readToCurrentFrame unmaskBytes:unmaskBytes]];
  886. [self _pumpScanner];
  887. }
  888. - (void)_addConsumerWithScanner:(stream_scanner)consumer callback:(data_callback)callback dataLength:(size_t)dataLength;
  889. {
  890. [self assertOnWorkQueue];
  891. [_consumers addObject:[_consumerPool consumerWithScanner:consumer handler:callback bytesNeeded:dataLength readToCurrentFrame:NO unmaskBytes:NO]];
  892. [self _pumpScanner];
  893. }
  894. - (void)_scheduleCleanup
  895. {
  896. @synchronized(self) {
  897. if (_cleanupScheduled) {
  898. return;
  899. }
  900. _cleanupScheduled = YES;
  901. // Cleanup NSStream delegate's in the same RunLoop used by the streams themselves:
  902. // This way we'll prevent race conditions between handleEvent and SRWebsocket's dealloc
  903. NSTimer *timer = [NSTimer timerWithTimeInterval:(0.0f) target:self selector:@selector(_cleanupSelfReference:) userInfo:nil repeats:NO];
  904. [[NSRunLoop FSR_networkRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
  905. }
  906. }
  907. - (void)_cleanupSelfReference:(NSTimer *)timer
  908. {
  909. @synchronized(self) {
  910. // Nuke NSStream delegate's
  911. _inputStream.delegate = nil;
  912. _outputStream.delegate = nil;
  913. // Remove the streams, right now, from the networkRunLoop
  914. [_inputStream close];
  915. [_outputStream close];
  916. }
  917. // Cleanup selfRetain in the same GCD queue as usual
  918. dispatch_async(_workQueue, ^{
  919. self->_selfRetain = nil;
  920. });
  921. }
  922. static const char CRLFCRLFBytes[] = {'\r', '\n', '\r', '\n'};
  923. - (void)_readUntilHeaderCompleteWithCallback:(data_callback)dataHandler;
  924. {
  925. [self _readUntilBytes:CRLFCRLFBytes length:sizeof(CRLFCRLFBytes) callback:dataHandler];
  926. }
  927. - (void)_readUntilBytes:(const void *)bytes length:(size_t)length callback:(data_callback)dataHandler;
  928. {
  929. // TODO optimize so this can continue from where we last searched
  930. stream_scanner consumer = ^size_t(NSData *data) {
  931. __block size_t found_size = 0;
  932. __block size_t match_count = 0;
  933. size_t size = data.length;
  934. const unsigned char *buffer = data.bytes;
  935. for (int i = 0; i < size; i++ ) {
  936. if (((const unsigned char *)buffer)[i] == ((const unsigned char *)bytes)[match_count]) {
  937. match_count += 1;
  938. if (match_count == length) {
  939. found_size = i + 1;
  940. break;
  941. }
  942. } else {
  943. match_count = 0;
  944. }
  945. }
  946. return found_size;
  947. };
  948. [self _addConsumerWithScanner:consumer callback:dataHandler];
  949. }
  950. // Returns true if did work
  951. - (BOOL)_innerPumpScanner {
  952. BOOL didWork = NO;
  953. if (self.readyState >= SR_CLOSING) {
  954. return didWork;
  955. }
  956. if (!_consumers.count) {
  957. return didWork;
  958. }
  959. size_t curSize = _readBuffer.length - _readBufferOffset;
  960. if (!curSize) {
  961. return didWork;
  962. }
  963. FSRIOConsumer *consumer = [_consumers objectAtIndex:0];
  964. size_t bytesNeeded = consumer.bytesNeeded;
  965. size_t foundSize = 0;
  966. if (consumer.consumer) {
  967. NSData *tempView = [NSData dataWithBytesNoCopy:(char *)_readBuffer.bytes + _readBufferOffset length:_readBuffer.length - _readBufferOffset freeWhenDone:NO];
  968. foundSize = consumer.consumer(tempView);
  969. } else {
  970. assert(consumer.bytesNeeded);
  971. if (curSize >= bytesNeeded) {
  972. foundSize = bytesNeeded;
  973. } else if (consumer.readToCurrentFrame) {
  974. foundSize = curSize;
  975. }
  976. }
  977. NSData *slice = nil;
  978. if (consumer.readToCurrentFrame || foundSize) {
  979. NSRange sliceRange = NSMakeRange(_readBufferOffset, foundSize);
  980. slice = [_readBuffer subdataWithRange:sliceRange];
  981. _readBufferOffset += foundSize;
  982. if (_readBufferOffset > 4096 && _readBufferOffset > (_readBuffer.length >> 1)) {
  983. _readBuffer = [[NSMutableData alloc] initWithBytes:(char *)_readBuffer.bytes + _readBufferOffset length:_readBuffer.length - _readBufferOffset]; _readBufferOffset = 0;
  984. }
  985. if (consumer.unmaskBytes) {
  986. NSMutableData *mutableSlice = [slice mutableCopy];
  987. NSUInteger len = mutableSlice.length;
  988. uint8_t *bytes = mutableSlice.mutableBytes;
  989. for (int i = 0; i < len; i++) {
  990. bytes[i] = bytes[i] ^ _currentReadMaskKey[_currentReadMaskOffset % sizeof(_currentReadMaskKey)];
  991. _currentReadMaskOffset += 1;
  992. }
  993. slice = mutableSlice;
  994. }
  995. if (consumer.readToCurrentFrame) {
  996. [_currentFrameData appendData:slice];
  997. _readOpCount += 1;
  998. if (_currentFrameOpcode == SROpCodeTextFrame) {
  999. // Validate UTF8 stuff.
  1000. size_t currentDataSize = _currentFrameData.length;
  1001. if (_currentFrameOpcode == SROpCodeTextFrame && currentDataSize > 0) {
  1002. // TODO: Optimize the crap out of this. Don't really have to copy all the data each time
  1003. size_t scanSize = currentDataSize - _currentStringScanPosition;
  1004. NSData *scan_data = [_currentFrameData subdataWithRange:NSMakeRange(_currentStringScanPosition, scanSize)];
  1005. int32_t valid_utf8_size = validate_dispatch_data_partial_string(scan_data);
  1006. if (valid_utf8_size == -1) {
  1007. [self closeWithCode:SRStatusCodeInvalidUTF8 reason:@"Text frames must be valid UTF-8"];
  1008. dispatch_async(_workQueue, ^{
  1009. [self _disconnect];
  1010. });
  1011. return didWork;
  1012. } else {
  1013. _currentStringScanPosition += valid_utf8_size;
  1014. }
  1015. }
  1016. }
  1017. consumer.bytesNeeded -= foundSize;
  1018. if (consumer.bytesNeeded == 0) {
  1019. [_consumers removeObjectAtIndex:0];
  1020. consumer.handler(self, nil);
  1021. didWork = YES;
  1022. }
  1023. } else if (foundSize) {
  1024. [_consumers removeObjectAtIndex:0];
  1025. consumer.handler(self, slice);
  1026. didWork = YES;
  1027. }
  1028. }
  1029. return didWork;
  1030. }
  1031. -(void)_pumpScanner;
  1032. {
  1033. [self assertOnWorkQueue];
  1034. if (!_isPumping) {
  1035. _isPumping = YES;
  1036. } else {
  1037. return;
  1038. }
  1039. while ([self _innerPumpScanner]) {
  1040. }
  1041. _isPumping = NO;
  1042. }
  1043. //#define NOMASK
  1044. static const size_t SRFrameHeaderOverhead = 32;
  1045. - (void)_sendFrameWithOpcode:(FSROpCode)opcode data:(id)data;
  1046. {
  1047. [self assertOnWorkQueue];
  1048. if (data == nil) {
  1049. return;
  1050. }
  1051. NSAssert([data isKindOfClass:[NSData class]] || [data isKindOfClass:[NSString class]], @"Function expects nil, NSString or NSData");
  1052. size_t payloadLength = [data isKindOfClass:[NSString class]] ? [(NSString *)data lengthOfBytesUsingEncoding:NSUTF8StringEncoding] : [data length];
  1053. NSMutableData *frame = [[NSMutableData alloc] initWithLength:payloadLength + SRFrameHeaderOverhead];
  1054. if (!frame) {
  1055. [self closeWithCode:SRStatusCodeMessageTooBig reason:@"Message too big"];
  1056. return;
  1057. }
  1058. uint8_t *frame_buffer = (uint8_t *)[frame mutableBytes];
  1059. // set fin
  1060. frame_buffer[0] = SRFinMask | opcode;
  1061. BOOL useMask = YES;
  1062. #ifdef NOMASK
  1063. useMask = NO;
  1064. #endif
  1065. if (useMask) {
  1066. // set the mask and header
  1067. frame_buffer[1] |= SRMaskMask;
  1068. }
  1069. size_t frame_buffer_size = 2;
  1070. const uint8_t *unmasked_payload = NULL;
  1071. if ([data isKindOfClass:[NSData class]]) {
  1072. unmasked_payload = (uint8_t *)[data bytes];
  1073. } else if ([data isKindOfClass:[NSString class]]) {
  1074. unmasked_payload = (const uint8_t *)[data UTF8String];
  1075. } else {
  1076. assert(NO);
  1077. }
  1078. if (payloadLength < 126) {
  1079. frame_buffer[1] |= payloadLength;
  1080. } else if (payloadLength <= UINT16_MAX) {
  1081. frame_buffer[1] |= 126;
  1082. *((uint16_t *)(frame_buffer + frame_buffer_size)) = EndianU16_BtoN((uint16_t)payloadLength);
  1083. frame_buffer_size += sizeof(uint16_t);
  1084. } else {
  1085. frame_buffer[1] |= 127;
  1086. *((uint64_t *)(frame_buffer + frame_buffer_size)) = EndianU64_BtoN((uint64_t)payloadLength);
  1087. frame_buffer_size += sizeof(uint64_t);
  1088. }
  1089. if (!useMask) {
  1090. for (int i = 0; i < payloadLength; i++) {
  1091. frame_buffer[frame_buffer_size] = unmasked_payload[i];
  1092. frame_buffer_size += 1;
  1093. }
  1094. } else {
  1095. uint8_t *mask_key = frame_buffer + frame_buffer_size;
  1096. int result = SecRandomCopyBytes(kSecRandomDefault, sizeof(uint32_t), (uint8_t *)mask_key);
  1097. assert(result == 0);
  1098. frame_buffer_size += sizeof(uint32_t);
  1099. // TODO: could probably optimize this with SIMD
  1100. for (int i = 0; i < payloadLength; i++) {
  1101. frame_buffer[frame_buffer_size] = unmasked_payload[i] ^ mask_key[i % sizeof(uint32_t)];
  1102. frame_buffer_size += 1;
  1103. }
  1104. }
  1105. assert(frame_buffer_size <= [frame length]);
  1106. frame.length = frame_buffer_size;
  1107. [self _writeData:frame];
  1108. }
  1109. - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode;
  1110. {
  1111. __weak __typeof__(self) weakSelf = self;
  1112. // turn on keep-alive for the output stream.
  1113. if (eventCode == NSStreamEventOpenCompleted && aStream == _outputStream) {
  1114. CFDataRef socketData = CFWriteStreamCopyProperty((CFWriteStreamRef)_outputStream, kCFStreamPropertySocketNativeHandle);
  1115. // In rare cases socketData might be nil (there are crash reports out there), in which case we'll have to just
  1116. // live without keep-alive :(
  1117. if (socketData != nil) {
  1118. CFSocketNativeHandle socket;
  1119. CFDataGetBytes(socketData, CFRangeMake(0, sizeof(CFSocketNativeHandle)), (UInt8 *)&socket);
  1120. CFRelease(socketData);
  1121. int keepAliveOn = 1;
  1122. if (setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, &keepAliveOn, sizeof(keepAliveOn)) == -1) {
  1123. SRFastLog(@"Failed to turn on TCP keepalive for websocket");
  1124. }
  1125. }
  1126. }
  1127. if (_secure && !_pinnedCertFound && (eventCode == NSStreamEventHasBytesAvailable || eventCode == NSStreamEventHasSpaceAvailable)) {
  1128. NSArray *sslCerts = [_urlRequest FSR_SSLPinnedCertificates];
  1129. if (sslCerts) {
  1130. SecTrustRef secTrust = (__bridge SecTrustRef)[aStream propertyForKey:(__bridge id)kCFStreamPropertySSLPeerTrust];
  1131. if (secTrust) {
  1132. NSInteger numCerts = SecTrustGetCertificateCount(secTrust);
  1133. for (NSInteger i = 0; i < numCerts && !_pinnedCertFound; i++) {
  1134. SecCertificateRef cert = SecTrustGetCertificateAtIndex(secTrust, i);
  1135. NSData *certData = CFBridgingRelease(SecCertificateCopyData(cert));
  1136. for (id ref in sslCerts) {
  1137. SecCertificateRef trustedCert = (__bridge SecCertificateRef)ref;
  1138. NSData *trustedCertData = CFBridgingRelease(SecCertificateCopyData(trustedCert));
  1139. if ([trustedCertData isEqualToData:certData]) {
  1140. _pinnedCertFound = YES;
  1141. break;
  1142. }
  1143. }
  1144. }
  1145. }
  1146. if (!_pinnedCertFound) {
  1147. dispatch_async(_workQueue, ^{
  1148. NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : @"Invalid server cert" };
  1149. [weakSelf _failWithError:[NSError errorWithDomain:@"org.lolrus.SocketRocket" code:23556 userInfo:userInfo]];
  1150. });
  1151. return;
  1152. }
  1153. }
  1154. }
  1155. // SRFastLog(@"%@ Got stream event %d", aStream, eventCode);
  1156. dispatch_async(_workQueue, ^{
  1157. [weakSelf safeHandleEvent:eventCode stream:aStream];
  1158. });
  1159. }
  1160. - (void)safeHandleEvent:(NSStreamEvent)eventCode stream:(NSStream *)aStream
  1161. {
  1162. switch (eventCode) {
  1163. case NSStreamEventOpenCompleted: {
  1164. SRFastLog(@"NSStreamEventOpenCompleted %@", aStream);
  1165. if (self.readyState >= SR_CLOSING) {
  1166. return;
  1167. }
  1168. assert(_readBuffer);
  1169. if (self.readyState == SR_CONNECTING && aStream == _inputStream) {
  1170. [self didConnect];
  1171. }
  1172. [self _pumpWriting];
  1173. [self _pumpScanner];
  1174. break;
  1175. }
  1176. case NSStreamEventErrorOccurred: {
  1177. // Note: The upstream code for SocketRocket logs the error message, but this causes
  1178. // crashes on iOS 13 (https://github.com/firebase/firebase-ios-sdk/issues/3950)
  1179. SRFastLog(@"NSStreamEventErrorOccurred %@", aStream);
  1180. /// TODO specify error better!
  1181. [self _failWithError:aStream.streamError];
  1182. _readBufferOffset = 0;
  1183. [_readBuffer setLength:0];
  1184. break;
  1185. }
  1186. case NSStreamEventEndEncountered: {
  1187. [self _pumpScanner];
  1188. SRFastLog(@"NSStreamEventEndEncountered %@", aStream);
  1189. if (aStream.streamError) {
  1190. [self _failWithError:aStream.streamError];
  1191. } else {
  1192. dispatch_async(_workQueue, ^{
  1193. if (self.readyState != SR_CLOSED) {
  1194. self.readyState = SR_CLOSED;
  1195. [self _scheduleCleanup];
  1196. }
  1197. if (!self->_sentClose && !self->_failed) {
  1198. self->_sentClose = YES;
  1199. // If we get closed in this state it's probably not clean because we should be sending this when we send messages
  1200. [self _performDelegateBlock:^{
  1201. if ([self.delegate respondsToSelector:@selector(webSocket:didCloseWithCode:reason:wasClean:)]) {
  1202. [self.delegate webSocket:self didCloseWithCode:0 reason:@"Stream end encountered" wasClean:NO];
  1203. }
  1204. }];
  1205. }
  1206. });
  1207. }
  1208. break;
  1209. }
  1210. case NSStreamEventHasBytesAvailable: {
  1211. SRFastLog(@"NSStreamEventHasBytesAvailable %@", aStream);
  1212. const NSUInteger bufferSize = 2048;
  1213. uint8_t buffer[bufferSize];
  1214. while (_inputStream.hasBytesAvailable) {
  1215. NSInteger bytes_read = [_inputStream read:buffer maxLength:bufferSize];
  1216. if (bytes_read > 0) {
  1217. [_readBuffer appendBytes:buffer length:bytes_read];
  1218. } else if (bytes_read < 0) {
  1219. [self _failWithError:_inputStream.streamError];
  1220. }
  1221. if (bytes_read != bufferSize) {
  1222. break;
  1223. }
  1224. };
  1225. [self _pumpScanner];
  1226. break;
  1227. }
  1228. case NSStreamEventHasSpaceAvailable: {
  1229. SRFastLog(@"NSStreamEventHasSpaceAvailable %@", aStream);
  1230. [self _pumpWriting];
  1231. break;
  1232. }
  1233. default:
  1234. SRFastLog(@"(default) %@", aStream);
  1235. break;
  1236. }
  1237. }
  1238. @end
  1239. @implementation FSRIOConsumer
  1240. @synthesize bytesNeeded = _bytesNeeded;
  1241. @synthesize consumer = _scanner;
  1242. @synthesize handler = _handler;
  1243. @synthesize readToCurrentFrame = _readToCurrentFrame;
  1244. @synthesize unmaskBytes = _unmaskBytes;
  1245. - (void)setupWithScanner:(stream_scanner)scanner handler:(data_callback)handler bytesNeeded:(size_t)bytesNeeded readToCurrentFrame:(BOOL)readToCurrentFrame unmaskBytes:(BOOL)unmaskBytes;
  1246. {
  1247. _scanner = [scanner copy];
  1248. _handler = [handler copy];
  1249. _bytesNeeded = bytesNeeded;
  1250. _readToCurrentFrame = readToCurrentFrame;
  1251. _unmaskBytes = unmaskBytes;
  1252. assert(_scanner || _bytesNeeded);
  1253. }
  1254. @end
  1255. @implementation FSRIOConsumerPool {
  1256. NSUInteger _poolSize;
  1257. NSMutableArray *_bufferedConsumers;
  1258. }
  1259. - (id)initWithBufferCapacity:(NSUInteger)poolSize;
  1260. {
  1261. self = [super init];
  1262. if (self) {
  1263. _poolSize = poolSize;
  1264. _bufferedConsumers = [[NSMutableArray alloc] initWithCapacity:poolSize];
  1265. }
  1266. return self;
  1267. }
  1268. - (id)init
  1269. {
  1270. return [self initWithBufferCapacity:8];
  1271. }
  1272. - (FSRIOConsumer *)consumerWithScanner:(stream_scanner)scanner handler:(data_callback)handler bytesNeeded:(size_t)bytesNeeded readToCurrentFrame:(BOOL)readToCurrentFrame unmaskBytes:(BOOL)unmaskBytes;
  1273. {
  1274. FSRIOConsumer *consumer = nil;
  1275. if (_bufferedConsumers.count) {
  1276. consumer = [_bufferedConsumers lastObject];
  1277. [_bufferedConsumers removeLastObject];
  1278. } else {
  1279. consumer = [[FSRIOConsumer alloc] init];
  1280. }
  1281. [consumer setupWithScanner:scanner handler:handler bytesNeeded:bytesNeeded readToCurrentFrame:readToCurrentFrame unmaskBytes:unmaskBytes];
  1282. return consumer;
  1283. }
  1284. - (void)returnConsumer:(FSRIOConsumer *)consumer;
  1285. {
  1286. if (_bufferedConsumers.count < _poolSize) {
  1287. [_bufferedConsumers addObject:consumer];
  1288. }
  1289. }
  1290. @end
  1291. @implementation NSURLRequest (FCertificateAdditions)
  1292. - (NSArray *)FSR_SSLPinnedCertificates;
  1293. {
  1294. return [NSURLProtocol propertyForKey:@"FSR_SSLPinnedCertificates" inRequest:self];
  1295. }
  1296. @end
  1297. @implementation NSMutableURLRequest (FCertificateAdditions)
  1298. - (NSArray *)FSR_SSLPinnedCertificates;
  1299. {
  1300. return [NSURLProtocol propertyForKey:@"FSR_SSLPinnedCertificates" inRequest:self];
  1301. }
  1302. - (void)setFSR_SSLPinnedCertificates:(NSArray *)FSR_SSLPinnedCertificates;
  1303. {
  1304. [NSURLProtocol setProperty:FSR_SSLPinnedCertificates forKey:@"FSR_SSLPinnedCertificates" inRequest:self];
  1305. }
  1306. @end
  1307. @implementation NSURL (FSRWebSocket)
  1308. - (NSString *)SR_origin;
  1309. {
  1310. NSString *scheme = [self.scheme lowercaseString];
  1311. if ([scheme isEqualToString:@"wss"]) {
  1312. scheme = @"https";
  1313. } else if ([scheme isEqualToString:@"ws"]) {
  1314. scheme = @"http";
  1315. }
  1316. if (self.port != nil) {
  1317. return [NSString stringWithFormat:@"%@://%@:%@/", scheme, self.host, self.port];
  1318. } else {
  1319. return [NSString stringWithFormat:@"%@://%@/", scheme, self.host];
  1320. }
  1321. }
  1322. @end
  1323. // #define SR_ENABLE_LOG
  1324. static inline void SRFastLog(NSString *format, ...) {
  1325. #ifdef SR_ENABLE_LOG
  1326. __block va_list arg_list;
  1327. va_start (arg_list, format);
  1328. NSString *formattedString = [[NSString alloc] initWithFormat:format arguments:arg_list];
  1329. va_end(arg_list);
  1330. NSLog(@"[SR] %@", formattedString);
  1331. #endif
  1332. }
  1333. #ifdef HAS_ICU
  1334. static inline int32_t validate_dispatch_data_partial_string(NSData *data) {
  1335. const void * contents = [data bytes];
  1336. long size = [data length];
  1337. const uint8_t *str = (const uint8_t *)contents;
  1338. UChar32 codepoint = 1;
  1339. int32_t offset = 0;
  1340. int32_t lastOffset = 0;
  1341. while(offset < size && codepoint > 0) {
  1342. lastOffset = offset;
  1343. U8_NEXT(str, offset, size, codepoint);
  1344. }
  1345. if (codepoint == -1) {
  1346. // Check to see if the last byte is valid or whether it was just continuing
  1347. if (!U8_IS_LEAD(str[lastOffset]) || U8_COUNT_TRAIL_BYTES(str[lastOffset]) + lastOffset < (int32_t)size) {
  1348. size = -1;
  1349. } else {
  1350. uint8_t leadByte = str[lastOffset];
  1351. U8_MASK_LEAD_BYTE(leadByte, U8_COUNT_TRAIL_BYTES(leadByte));
  1352. for (int i = lastOffset + 1; i < offset; i++) {
  1353. if (U8_IS_SINGLE(str[i]) || U8_IS_LEAD(str[i]) || !U8_IS_TRAIL(str[i])) {
  1354. size = -1;
  1355. }
  1356. }
  1357. if (size != -1) {
  1358. size = lastOffset;
  1359. }
  1360. }
  1361. }
  1362. if (size != -1 && ![[NSString alloc] initWithBytesNoCopy:(char *)[data bytes] length:size encoding:NSUTF8StringEncoding freeWhenDone:NO]) {
  1363. size = -1;
  1364. }
  1365. return (int32_t)size;
  1366. }
  1367. #else
  1368. // This is a hack, and probably not optimal
  1369. static inline int32_t validate_dispatch_data_partial_string(NSData *data) {
  1370. static const int maxCodepointSize = 3;
  1371. for (int i = 0; i < maxCodepointSize; i++) {
  1372. NSString *str = [[NSString alloc] initWithBytesNoCopy:(char *)data.bytes length:data.length - i encoding:NSUTF8StringEncoding freeWhenDone:NO];
  1373. if (str) {
  1374. return (int)(data.length - i);
  1375. }
  1376. }
  1377. return -1;
  1378. }
  1379. #endif
  1380. static _FSRRunLoopThread *networkThread = nil;
  1381. static NSRunLoop *networkRunLoop = nil;
  1382. @implementation NSRunLoop (FSRWebSocket)
  1383. + (NSRunLoop *)FSR_networkRunLoop {
  1384. static dispatch_once_t onceToken;
  1385. dispatch_once(&onceToken, ^{
  1386. networkThread = [[_FSRRunLoopThread alloc] init];
  1387. networkThread.name = @"com.squareup.SocketRocket.NetworkThread";
  1388. [networkThread start];
  1389. networkRunLoop = networkThread.runLoop;
  1390. });
  1391. return networkRunLoop;
  1392. }
  1393. @end
  1394. @implementation _FSRRunLoopThread {
  1395. dispatch_group_t _waitGroup;
  1396. }
  1397. @synthesize runLoop = _runLoop;
  1398. - (void)dealloc
  1399. {
  1400. sr_dispatch_release(_waitGroup);
  1401. }
  1402. - (id)init
  1403. {
  1404. self = [super init];
  1405. if (self) {
  1406. _waitGroup = dispatch_group_create();
  1407. dispatch_group_enter(_waitGroup);
  1408. }
  1409. return self;
  1410. }
  1411. /**
  1412. * This is the main method of the thread on which the socket events are scheduled in a run loop.
  1413. */
  1414. - (void)main;
  1415. {
  1416. @autoreleasepool {
  1417. _runLoop = [NSRunLoop currentRunLoop];
  1418. dispatch_group_leave(_waitGroup);
  1419. // Add an empty run loop source to prevent runloop from spinning.
  1420. CFRunLoopSourceContext sourceCtx = {
  1421. .version = 0,
  1422. .info = NULL,
  1423. .retain = NULL,
  1424. .release = NULL,
  1425. .copyDescription = NULL,
  1426. .equal = NULL,
  1427. .hash = NULL,
  1428. .schedule = NULL,
  1429. .cancel = NULL,
  1430. .perform = NULL
  1431. };
  1432. CFRunLoopSourceRef source = CFRunLoopSourceCreate(NULL, 0, &sourceCtx);
  1433. CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
  1434. CFRelease(source);
  1435. while ([_runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) {
  1436. }
  1437. assert(NO);
  1438. }
  1439. }
  1440. - (NSRunLoop *)runLoop;
  1441. {
  1442. dispatch_group_wait(_waitGroup, DISPATCH_TIME_FOREVER);
  1443. return _runLoop;
  1444. }
  1445. @end