FSRWebSocket.m 58 KB

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