FSRWebSocket.m 58 KB

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