FSRWebSocket.m 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884
  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 __unused result =
  402. SecRandomCopyBytes(kSecRandomDefault, keyBytes.length, keyBytes.mutableBytes);
  403. assert(result == 0);
  404. _secKey = [FSRUtilities base64EncodedStringFromData:keyBytes];
  405. assert([_secKey length] == 24);
  406. CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Upgrade"), CFSTR("websocket"));
  407. CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Connection"), CFSTR("Upgrade"));
  408. if (_userAgent) {
  409. CFHTTPMessageSetHeaderFieldValue(request, CFSTR("User-Agent"), (__bridge CFStringRef)_userAgent);
  410. }
  411. if (_googleAppID) {
  412. CFHTTPMessageSetHeaderFieldValue(request, CFSTR("X-Firebase-GMPID"), (__bridge CFStringRef)_googleAppID);
  413. }
  414. CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Sec-WebSocket-Key"), (__bridge CFStringRef)_secKey);
  415. CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Sec-WebSocket-Version"), (__bridge CFStringRef)[NSString stringWithFormat:@"%u", (int)_webSocketVersion]);
  416. CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Origin"), (__bridge CFStringRef)_url.SR_origin);
  417. if (_requestedProtocols) {
  418. CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Sec-WebSocket-Protocol"), (__bridge CFStringRef)[_requestedProtocols componentsJoinedByString:@", "]);
  419. }
  420. [_urlRequest.allHTTPHeaderFields enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
  421. CFHTTPMessageSetHeaderFieldValue(request, (__bridge CFStringRef)key, (__bridge CFStringRef)obj);
  422. }];
  423. NSData *message = CFBridgingRelease(CFHTTPMessageCopySerializedMessage(request));
  424. CFRelease(request);
  425. [self _writeData:message];
  426. [self _readHTTPHeader];
  427. }
  428. //- (void)_connectToHost:(NSString *)host port:(NSInteger)port;
  429. - (void)_initializeStreams;
  430. {
  431. NSInteger port = _url.port.integerValue;
  432. if (port == 0) {
  433. if (!_secure) {
  434. port = 80;
  435. } else {
  436. port = 443;
  437. }
  438. }
  439. NSString *host = _url.host;
  440. CFReadStreamRef readStream = NULL;
  441. CFWriteStreamRef writeStream = NULL;
  442. CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, (int)port, &readStream, &writeStream);
  443. // XXX
  444. CFReadStreamSetProperty(readStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeBackground);
  445. CFWriteStreamSetProperty(writeStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeBackground);
  446. _outputStream = CFBridgingRelease(writeStream);
  447. _inputStream = CFBridgingRelease(readStream);
  448. if (_secure) {
  449. NSMutableDictionary *SSLOptions = [[NSMutableDictionary alloc] init];
  450. [_outputStream setProperty:(__bridge id)kCFStreamSocketSecurityLevelNegotiatedSSL forKey:(__bridge id)kCFStreamPropertySocketSecurityLevel];
  451. // If we're using pinned certs, don't validate the certificate chain
  452. if ([_urlRequest FSR_SSLPinnedCertificates].count) {
  453. [SSLOptions setValue:[NSNumber numberWithBool:NO] forKey:(__bridge id)kCFStreamSSLValidatesCertificateChain];
  454. }
  455. [_outputStream setProperty:SSLOptions
  456. forKey:(__bridge id)kCFStreamPropertySSLSettings];
  457. }
  458. _inputStream.delegate = self;
  459. _outputStream.delegate = self;
  460. [_outputStream open];
  461. [_inputStream open];
  462. }
  463. - (void)_connect;
  464. {
  465. if (!_scheduledRunloops.count) {
  466. [self scheduleInRunLoop:[NSRunLoop FSR_networkRunLoop] forMode:NSDefaultRunLoopMode];
  467. }
  468. [_outputStream open];
  469. [_inputStream open];
  470. }
  471. - (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
  472. {
  473. [_outputStream scheduleInRunLoop:aRunLoop forMode:mode];
  474. [_inputStream scheduleInRunLoop:aRunLoop forMode:mode];
  475. [_scheduledRunloops addObject:@[aRunLoop, mode]];
  476. }
  477. - (void)unscheduleFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
  478. {
  479. [_outputStream removeFromRunLoop:aRunLoop forMode:mode];
  480. [_inputStream removeFromRunLoop:aRunLoop forMode:mode];
  481. [_scheduledRunloops removeObject:@[aRunLoop, mode]];
  482. }
  483. - (void)close;
  484. {
  485. [self closeWithCode:-1 reason:nil];
  486. }
  487. - (void)closeWithCode:(NSInteger)code reason:(NSString *)reason;
  488. {
  489. assert(code);
  490. dispatch_async(_workQueue, ^{
  491. if (self.readyState == SR_CLOSING || self.readyState == SR_CLOSED) {
  492. return;
  493. }
  494. BOOL wasConnecting = self.readyState == SR_CONNECTING;
  495. self.readyState = SR_CLOSING;
  496. SRFastLog(@"Closing with code %d reason %@", code, reason);
  497. if (wasConnecting) {
  498. [self _disconnect];
  499. return;
  500. }
  501. size_t maxMsgSize = [reason maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  502. NSMutableData *mutablePayload = [[NSMutableData alloc] initWithLength:sizeof(uint16_t) + maxMsgSize];
  503. NSData *payload = mutablePayload;
  504. ((uint16_t *)mutablePayload.mutableBytes)[0] = EndianU16_BtoN(code);
  505. if (reason) {
  506. NSRange remainingRange = {0};
  507. NSUInteger usedLength = 0;
  508. BOOL __unused success =
  509. [reason getBytes:(char *)mutablePayload.mutableBytes + sizeof(uint16_t)
  510. maxLength:payload.length - sizeof(uint16_t)
  511. usedLength:&usedLength
  512. encoding:NSUTF8StringEncoding
  513. options:NSStringEncodingConversionExternalRepresentation
  514. range:NSMakeRange(0, reason.length)
  515. remainingRange:&remainingRange];
  516. assert(success);
  517. assert(remainingRange.length == 0);
  518. if (usedLength != maxMsgSize) {
  519. payload = [payload subdataWithRange:NSMakeRange(0, usedLength + sizeof(uint16_t))];
  520. }
  521. }
  522. [self _sendFrameWithOpcode:SROpCodeConnectionClose data:payload];
  523. });
  524. }
  525. - (void)_closeWithProtocolError:(NSString *)message;
  526. {
  527. // Need to shunt this on the _callbackQueue first to see if they received any messages
  528. [self _performDelegateBlock:^{
  529. [self closeWithCode:SRStatusCodeProtocolError reason:message];
  530. dispatch_async(self->_workQueue, ^{
  531. [self _disconnect];
  532. });
  533. }];
  534. }
  535. - (void)_failWithError:(NSError *)error;
  536. {
  537. dispatch_async(_workQueue, ^{
  538. if (self.readyState != SR_CLOSED) {
  539. self->_failed = YES;
  540. [self _performDelegateBlock:^{
  541. if ([self.delegate respondsToSelector:@selector(webSocket:didFailWithError:)]) {
  542. [self.delegate webSocket:self didFailWithError:error];
  543. }
  544. }];
  545. self.readyState = SR_CLOSED;
  546. SRFastLog(@"Failing with error %@", error.localizedDescription);
  547. [self _disconnect];
  548. [self _scheduleCleanup];
  549. }
  550. });
  551. }
  552. - (void)_writeData:(NSData *)data;
  553. {
  554. [self assertOnWorkQueue];
  555. if (_closeWhenFinishedWriting) {
  556. return;
  557. }
  558. [_outputBuffer appendData:data];
  559. [self _pumpWriting];
  560. }
  561. - (void)send:(id)data;
  562. {
  563. SRFastLog(@"Sending data %@", data);
  564. NSAssert(self.readyState != SR_CONNECTING, @"Invalid State: Cannot call send: until connection is open");
  565. // TODO: maybe not copy this for performance
  566. data = [data copy];
  567. dispatch_async(_workQueue, ^{
  568. if ([data isKindOfClass:[NSString class]]) {
  569. [self _sendFrameWithOpcode:SROpCodeTextFrame data:[(NSString *)data dataUsingEncoding:NSUTF8StringEncoding]];
  570. } else if ([data isKindOfClass:[NSData class]]) {
  571. [self _sendFrameWithOpcode:SROpCodeBinaryFrame data:data];
  572. } else if (data == nil) {
  573. [self _sendFrameWithOpcode:SROpCodeTextFrame data:data];
  574. } else {
  575. assert(NO);
  576. }
  577. });
  578. }
  579. - (void)handlePing:(NSData *)pingData;
  580. {
  581. // Need to pingpong this off _callbackQueue first to make sure messages happen in order
  582. [self _performDelegateBlock:^{
  583. dispatch_async(self->_workQueue, ^{
  584. [self _sendFrameWithOpcode:SROpCodePong data:pingData];
  585. });
  586. }];
  587. }
  588. - (void)handlePong;
  589. {
  590. // NOOP
  591. }
  592. - (void)_handleMessage:(id)message
  593. {
  594. SRFastLog(@"Received message");
  595. [self _performDelegateBlock:^{
  596. if ([self.delegate respondsToSelector:@selector(webSocket:didReceiveMessage:)]) {
  597. [self.delegate webSocket:self didReceiveMessage:message];
  598. }
  599. }];
  600. }
  601. static inline BOOL closeCodeIsValid(int closeCode) {
  602. if (closeCode < 1000) {
  603. return NO;
  604. }
  605. if (closeCode >= 1000 && closeCode <= 1011) {
  606. if (closeCode == 1004 ||
  607. closeCode == 1005 ||
  608. closeCode == 1006) {
  609. return NO;
  610. }
  611. return YES;
  612. }
  613. if (closeCode >= 3000 && closeCode <= 3999) {
  614. return YES;
  615. }
  616. if (closeCode >= 4000 && closeCode <= 4999) {
  617. return YES;
  618. }
  619. return NO;
  620. }
  621. // Note from RFC:
  622. //
  623. // If there is a body, the first two
  624. // bytes of the body MUST be a 2-byte unsigned integer (in network byte
  625. // order) representing a status code with value /code/ defined in
  626. // Section 7.4. Following the 2-byte integer the body MAY contain UTF-8
  627. // encoded data with value /reason/, the interpretation of which is not
  628. // defined by this specification.
  629. - (void)handleCloseWithData:(NSData *)data;
  630. {
  631. size_t dataSize = data.length;
  632. __block uint16_t closeCode = 0;
  633. SRFastLog(@"Received close frame");
  634. if (dataSize == 1) {
  635. // TODO handle error
  636. [self _closeWithProtocolError:@"Payload for close must be larger than 2 bytes"];
  637. return;
  638. } else if (dataSize >= 2) {
  639. [data getBytes:&closeCode length:sizeof(closeCode)];
  640. _closeCode = EndianU16_BtoN(closeCode);
  641. if (!closeCodeIsValid(_closeCode)) {
  642. [self _closeWithProtocolError:[NSString stringWithFormat:@"Cannot have close code of %d", _closeCode]];
  643. return;
  644. }
  645. if (dataSize > 2) {
  646. _closeReason = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(2, dataSize - 2)] encoding:NSUTF8StringEncoding];
  647. if (!_closeReason) {
  648. [self _closeWithProtocolError:@"Close reason MUST be valid UTF-8"];
  649. return;
  650. }
  651. }
  652. } else {
  653. _closeCode = SRStatusNoStatusReceived;
  654. }
  655. [self assertOnWorkQueue];
  656. if (self.readyState == SR_OPEN) {
  657. [self closeWithCode:1000 reason:nil];
  658. }
  659. dispatch_async(_workQueue, ^{
  660. [self _disconnect];
  661. });
  662. }
  663. - (void)_disconnect;
  664. {
  665. [self assertOnWorkQueue];
  666. SRFastLog(@"Trying to disconnect");
  667. _closeWhenFinishedWriting = YES;
  668. [self _pumpWriting];
  669. }
  670. - (void)_handleFrameWithData:(NSData *)frameData opCode:(NSInteger)opcode;
  671. {
  672. // Check that the current data is valid UTF8
  673. BOOL isControlFrame = (opcode == SROpCodePing || opcode == SROpCodePong || opcode == SROpCodeConnectionClose);
  674. if (!isControlFrame) {
  675. [self _readFrameNew];
  676. } else {
  677. dispatch_async(_workQueue, ^{
  678. [self _readFrameContinue];
  679. });
  680. }
  681. switch (opcode) {
  682. case SROpCodeTextFrame: {
  683. NSString *str = [[NSString alloc] initWithData:frameData encoding:NSUTF8StringEncoding];
  684. if (str == nil && frameData) {
  685. [self closeWithCode:SRStatusCodeInvalidUTF8 reason:@"Text frames must be valid UTF-8"];
  686. dispatch_async(_workQueue, ^{
  687. [self _disconnect];
  688. });
  689. return;
  690. }
  691. [self _handleMessage:str];
  692. break;
  693. }
  694. case SROpCodeBinaryFrame:
  695. [self _handleMessage:[frameData copy]];
  696. break;
  697. case SROpCodeConnectionClose:
  698. [self handleCloseWithData:frameData];
  699. break;
  700. case SROpCodePing:
  701. [self handlePing:frameData];
  702. break;
  703. case SROpCodePong:
  704. [self handlePong];
  705. break;
  706. default:
  707. [self _closeWithProtocolError:[NSString stringWithFormat:@"Unknown opcode %u", (int)opcode]];
  708. // TODO: Handle invalid opcode
  709. break;
  710. }
  711. }
  712. - (void)_handleFrameHeader:(frame_header)frame_header curData:(NSData *)curData;
  713. {
  714. assert(frame_header.opcode != 0);
  715. if (self.readyState != SR_OPEN) {
  716. return;
  717. }
  718. BOOL isControlFrame = (frame_header.opcode == SROpCodePing || frame_header.opcode == SROpCodePong || frame_header.opcode == SROpCodeConnectionClose);
  719. if (isControlFrame && !frame_header.fin) {
  720. [self _closeWithProtocolError:@"Fragmented control frames not allowed"];
  721. return;
  722. }
  723. if (isControlFrame && frame_header.payload_length >= 126) {
  724. [self _closeWithProtocolError:@"Control frames cannot have payloads larger than 126 bytes"];
  725. return;
  726. }
  727. if (!isControlFrame) {
  728. _currentFrameOpcode = frame_header.opcode;
  729. _currentFrameCount += 1;
  730. }
  731. if (frame_header.payload_length == 0) {
  732. if (isControlFrame) {
  733. [self _handleFrameWithData:curData opCode:frame_header.opcode];
  734. } else {
  735. if (frame_header.fin) {
  736. [self _handleFrameWithData:_currentFrameData opCode:frame_header.opcode];
  737. } else {
  738. // TODO add assert that opcode is not a control;
  739. [self _readFrameContinue];
  740. }
  741. }
  742. } else {
  743. [self _addConsumerWithDataLength:(size_t)frame_header.payload_length callback:^(FSRWebSocket *self, NSData *newData) {
  744. if (isControlFrame) {
  745. [self _handleFrameWithData:newData opCode:frame_header.opcode];
  746. } else {
  747. if (frame_header.fin) {
  748. [self _handleFrameWithData:self->_currentFrameData opCode:frame_header.opcode];
  749. } else {
  750. // TODO add assert that opcode is not a control;
  751. [self _readFrameContinue];
  752. }
  753. }
  754. } readToCurrentFrame:!isControlFrame unmaskBytes:frame_header.masked];
  755. }
  756. }
  757. /* From RFC:
  758. 0 1 2 3
  759. 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
  760. +-+-+-+-+-------+-+-------------+-------------------------------+
  761. |F|R|R|R| opcode|M| Payload len | Extended payload length |
  762. |I|S|S|S| (4) |A| (7) | (16/64) |
  763. |N|V|V|V| |S| | (if payload len==126/127) |
  764. | |1|2|3| |K| | |
  765. +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
  766. | Extended payload length continued, if payload len == 127 |
  767. + - - - - - - - - - - - - - - - +-------------------------------+
  768. | |Masking-key, if MASK set to 1 |
  769. +-------------------------------+-------------------------------+
  770. | Masking-key (continued) | Payload Data |
  771. +-------------------------------- - - - - - - - - - - - - - - - +
  772. : Payload Data continued ... :
  773. + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
  774. | Payload Data continued ... |
  775. +---------------------------------------------------------------+
  776. */
  777. static const uint8_t SRFinMask = 0x80;
  778. static const uint8_t SROpCodeMask = 0x0F;
  779. static const uint8_t SRRsvMask = 0x70;
  780. static const uint8_t SRMaskMask = 0x80;
  781. static const uint8_t SRPayloadLenMask = 0x7F;
  782. - (void)_readFrameContinue;
  783. {
  784. assert((_currentFrameCount == 0 && _currentFrameOpcode == 0) || (_currentFrameCount > 0 && _currentFrameOpcode > 0));
  785. [self _addConsumerWithDataLength:2 callback:^(FSRWebSocket *self, NSData *data) {
  786. __block frame_header header = {0};
  787. const uint8_t *headerBuffer = data.bytes;
  788. assert(data.length >= 2);
  789. if (headerBuffer[0] & SRRsvMask) {
  790. [self _closeWithProtocolError:@"Server used RSV bits"];
  791. return;
  792. }
  793. uint8_t receivedOpcode = (SROpCodeMask & headerBuffer[0]);
  794. BOOL isControlFrame = (receivedOpcode == SROpCodePing || receivedOpcode == SROpCodePong || receivedOpcode == SROpCodeConnectionClose);
  795. if (!isControlFrame && receivedOpcode != 0 && self->_currentFrameCount > 0) {
  796. [self _closeWithProtocolError:@"all data frames after the initial data frame must have opcode 0"];
  797. return;
  798. }
  799. if (receivedOpcode == 0 && self->_currentFrameCount == 0) {
  800. [self _closeWithProtocolError:@"cannot continue a message"];
  801. return;
  802. }
  803. header.opcode = receivedOpcode == 0 ? self->_currentFrameOpcode : receivedOpcode;
  804. header.fin = !!(SRFinMask & headerBuffer[0]);
  805. header.masked = !!(SRMaskMask & headerBuffer[1]);
  806. header.payload_length = SRPayloadLenMask & headerBuffer[1];
  807. headerBuffer = NULL;
  808. if (header.masked) {
  809. [self _closeWithProtocolError:@"Client must receive unmasked data"];
  810. }
  811. size_t extra_bytes_needed = header.masked ? sizeof(self->_currentReadMaskKey) : 0;
  812. if (header.payload_length == 126) {
  813. extra_bytes_needed += sizeof(uint16_t);
  814. } else if (header.payload_length == 127) {
  815. extra_bytes_needed += sizeof(uint64_t);
  816. }
  817. if (extra_bytes_needed == 0) {
  818. [self _handleFrameHeader:header curData:self->_currentFrameData];
  819. } else {
  820. [self _addConsumerWithDataLength:extra_bytes_needed callback:^(FSRWebSocket *self, NSData *data) {
  821. size_t __unused mapped_size = data.length;
  822. const void *mapped_buffer = data.bytes;
  823. size_t offset = 0;
  824. if (header.payload_length == 126) {
  825. assert(mapped_size >= sizeof(uint16_t));
  826. uint16_t newLen = EndianU16_BtoN(*(uint16_t *)(mapped_buffer));
  827. header.payload_length = newLen;
  828. offset += sizeof(uint16_t);
  829. } else if (header.payload_length == 127) {
  830. assert(mapped_size >= sizeof(uint64_t));
  831. header.payload_length = EndianU64_BtoN(*(uint64_t *)(mapped_buffer));
  832. offset += sizeof(uint64_t);
  833. } else {
  834. assert(header.payload_length < 126 && header.payload_length >= 0);
  835. }
  836. if (header.masked) {
  837. assert(mapped_size >= sizeof(self->_currentReadMaskOffset) + offset);
  838. memcpy(self->_currentReadMaskKey, ((uint8_t *)mapped_buffer) + offset, sizeof(self->_currentReadMaskKey));
  839. }
  840. [self _handleFrameHeader:header curData:self->_currentFrameData];
  841. } readToCurrentFrame:NO unmaskBytes:NO];
  842. }
  843. } readToCurrentFrame:NO unmaskBytes:NO];
  844. }
  845. - (void)_readFrameNew;
  846. {
  847. dispatch_async(_workQueue, ^{
  848. [self->_currentFrameData setLength:0];
  849. self->_currentFrameOpcode = 0;
  850. self->_currentFrameCount = 0;
  851. self->_readOpCount = 0;
  852. self->_currentStringScanPosition = 0;
  853. [self _readFrameContinue];
  854. });
  855. }
  856. - (void)_pumpWriting;
  857. {
  858. [self assertOnWorkQueue];
  859. NSUInteger dataLength = _outputBuffer.length;
  860. if (dataLength - _outputBufferOffset > 0 && _outputStream.hasSpaceAvailable) {
  861. NSUInteger bytesWritten = [_outputStream write:_outputBuffer.bytes + _outputBufferOffset maxLength:dataLength - _outputBufferOffset];
  862. if (bytesWritten == -1) {
  863. [self _failWithError:[NSError errorWithDomain:@"org.lolrus.SocketRocket" code:2145 userInfo:[NSDictionary dictionaryWithObject:@"Error writing to stream" forKey:NSLocalizedDescriptionKey]]];
  864. return;
  865. }
  866. _outputBufferOffset += bytesWritten;
  867. if (_outputBufferOffset > 4096 && _outputBufferOffset > (_outputBuffer.length >> 1)) {
  868. _outputBuffer = [[NSMutableData alloc] initWithBytes:(char *)_outputBuffer.bytes + _outputBufferOffset length:_outputBuffer.length - _outputBufferOffset];
  869. _outputBufferOffset = 0;
  870. }
  871. }
  872. if (_closeWhenFinishedWriting &&
  873. _outputBuffer.length - _outputBufferOffset == 0 &&
  874. (_inputStream.streamStatus != NSStreamStatusNotOpen &&
  875. _inputStream.streamStatus != NSStreamStatusClosed) &&
  876. !_sentClose) {
  877. _sentClose = YES;
  878. @synchronized (self) {
  879. [_outputStream close];
  880. [_inputStream close];
  881. // TODO: Why are we missing the SocketRocket code to call unscheduleFromRunLoop???
  882. }
  883. if (!_failed) {
  884. [self _performDelegateBlock:^{
  885. if ([self.delegate respondsToSelector:@selector(webSocket:didCloseWithCode:reason:wasClean:)]) {
  886. [self.delegate webSocket:self didCloseWithCode:self->_closeCode reason:self->_closeReason wasClean:YES];
  887. }
  888. }];
  889. }
  890. [self _scheduleCleanup];
  891. }
  892. }
  893. - (void)_addConsumerWithScanner:(stream_scanner)consumer callback:(data_callback)callback;
  894. {
  895. [self assertOnWorkQueue];
  896. [self _addConsumerWithScanner:consumer callback:callback dataLength:0];
  897. }
  898. - (void)_addConsumerWithDataLength:(size_t)dataLength callback:(data_callback)callback readToCurrentFrame:(BOOL)readToCurrentFrame unmaskBytes:(BOOL)unmaskBytes;
  899. {
  900. [self assertOnWorkQueue];
  901. assert(dataLength);
  902. [_consumers addObject:[_consumerPool consumerWithScanner:nil handler:callback bytesNeeded:dataLength readToCurrentFrame:readToCurrentFrame unmaskBytes:unmaskBytes]];
  903. [self _pumpScanner];
  904. }
  905. - (void)_addConsumerWithScanner:(stream_scanner)consumer callback:(data_callback)callback dataLength:(size_t)dataLength;
  906. {
  907. [self assertOnWorkQueue];
  908. [_consumers addObject:[_consumerPool consumerWithScanner:consumer handler:callback bytesNeeded:dataLength readToCurrentFrame:NO unmaskBytes:NO]];
  909. [self _pumpScanner];
  910. }
  911. - (void)_scheduleCleanup
  912. {
  913. @synchronized(self) {
  914. if (_cleanupScheduled) {
  915. return;
  916. }
  917. _cleanupScheduled = YES;
  918. // Cleanup NSStream delegate's in the same RunLoop used by the streams themselves:
  919. // This way we'll prevent race conditions between handleEvent and SRWebsocket's dealloc
  920. NSTimer *timer = [NSTimer timerWithTimeInterval:(0.0f) target:self selector:@selector(_cleanupSelfReference:) userInfo:nil repeats:NO];
  921. [[NSRunLoop FSR_networkRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
  922. }
  923. }
  924. - (void)_cleanupSelfReference:(NSTimer *)timer
  925. {
  926. @synchronized(self) {
  927. // Nuke NSStream delegate's
  928. _inputStream.delegate = nil;
  929. _outputStream.delegate = nil;
  930. // Remove the streams, right now, from the networkRunLoop
  931. [_inputStream close];
  932. [_outputStream close];
  933. }
  934. // Cleanup selfRetain in the same GCD queue as usual
  935. dispatch_async(_workQueue, ^{
  936. self->_selfRetain = nil;
  937. });
  938. }
  939. static const char CRLFCRLFBytes[] = {'\r', '\n', '\r', '\n'};
  940. - (void)_readUntilHeaderCompleteWithCallback:(data_callback)dataHandler;
  941. {
  942. [self _readUntilBytes:CRLFCRLFBytes length:sizeof(CRLFCRLFBytes) callback:dataHandler];
  943. }
  944. - (void)_readUntilBytes:(const void *)bytes length:(size_t)length callback:(data_callback)dataHandler;
  945. {
  946. // TODO optimize so this can continue from where we last searched
  947. stream_scanner consumer = ^size_t(NSData *data) {
  948. __block size_t found_size = 0;
  949. __block size_t match_count = 0;
  950. size_t size = data.length;
  951. const unsigned char *buffer = data.bytes;
  952. for (int i = 0; i < size; i++ ) {
  953. if (((const unsigned char *)buffer)[i] == ((const unsigned char *)bytes)[match_count]) {
  954. match_count += 1;
  955. if (match_count == length) {
  956. found_size = i + 1;
  957. break;
  958. }
  959. } else {
  960. match_count = 0;
  961. }
  962. }
  963. return found_size;
  964. };
  965. [self _addConsumerWithScanner:consumer callback:dataHandler];
  966. }
  967. // Returns true if did work
  968. - (BOOL)_innerPumpScanner {
  969. BOOL didWork = NO;
  970. if (self.readyState >= SR_CLOSING) {
  971. return didWork;
  972. }
  973. if (!_consumers.count) {
  974. return didWork;
  975. }
  976. size_t curSize = _readBuffer.length - _readBufferOffset;
  977. if (!curSize) {
  978. return didWork;
  979. }
  980. FSRIOConsumer *consumer = [_consumers objectAtIndex:0];
  981. size_t bytesNeeded = consumer.bytesNeeded;
  982. size_t foundSize = 0;
  983. if (consumer.consumer) {
  984. NSData *tempView = [NSData dataWithBytesNoCopy:(char *)_readBuffer.bytes + _readBufferOffset length:_readBuffer.length - _readBufferOffset freeWhenDone:NO];
  985. foundSize = consumer.consumer(tempView);
  986. } else {
  987. assert(consumer.bytesNeeded);
  988. if (curSize >= bytesNeeded) {
  989. foundSize = bytesNeeded;
  990. } else if (consumer.readToCurrentFrame) {
  991. foundSize = curSize;
  992. }
  993. }
  994. NSData *slice = nil;
  995. if (consumer.readToCurrentFrame || foundSize) {
  996. NSRange sliceRange = NSMakeRange(_readBufferOffset, foundSize);
  997. slice = [_readBuffer subdataWithRange:sliceRange];
  998. _readBufferOffset += foundSize;
  999. if (_readBufferOffset > 4096 && _readBufferOffset > (_readBuffer.length >> 1)) {
  1000. _readBuffer = [[NSMutableData alloc] initWithBytes:(char *)_readBuffer.bytes + _readBufferOffset length:_readBuffer.length - _readBufferOffset]; _readBufferOffset = 0;
  1001. }
  1002. if (consumer.unmaskBytes) {
  1003. NSMutableData *mutableSlice = [slice mutableCopy];
  1004. NSUInteger len = mutableSlice.length;
  1005. uint8_t *bytes = mutableSlice.mutableBytes;
  1006. for (int i = 0; i < len; i++) {
  1007. bytes[i] = bytes[i] ^ _currentReadMaskKey[_currentReadMaskOffset % sizeof(_currentReadMaskKey)];
  1008. _currentReadMaskOffset += 1;
  1009. }
  1010. slice = mutableSlice;
  1011. }
  1012. if (consumer.readToCurrentFrame) {
  1013. [_currentFrameData appendData:slice];
  1014. _readOpCount += 1;
  1015. if (_currentFrameOpcode == SROpCodeTextFrame) {
  1016. // Validate UTF8 stuff.
  1017. size_t currentDataSize = _currentFrameData.length;
  1018. if (_currentFrameOpcode == SROpCodeTextFrame && currentDataSize > 0) {
  1019. // TODO: Optimize the crap out of this. Don't really have to copy all the data each time
  1020. size_t scanSize = currentDataSize - _currentStringScanPosition;
  1021. NSData *scan_data = [_currentFrameData subdataWithRange:NSMakeRange(_currentStringScanPosition, scanSize)];
  1022. int32_t valid_utf8_size = validate_dispatch_data_partial_string(scan_data);
  1023. if (valid_utf8_size == -1) {
  1024. [self closeWithCode:SRStatusCodeInvalidUTF8 reason:@"Text frames must be valid UTF-8"];
  1025. dispatch_async(_workQueue, ^{
  1026. [self _disconnect];
  1027. });
  1028. return didWork;
  1029. } else {
  1030. _currentStringScanPosition += valid_utf8_size;
  1031. }
  1032. }
  1033. }
  1034. consumer.bytesNeeded -= foundSize;
  1035. if (consumer.bytesNeeded == 0) {
  1036. [_consumers removeObjectAtIndex:0];
  1037. consumer.handler(self, nil);
  1038. didWork = YES;
  1039. }
  1040. } else if (foundSize) {
  1041. [_consumers removeObjectAtIndex:0];
  1042. consumer.handler(self, slice);
  1043. didWork = YES;
  1044. }
  1045. }
  1046. return didWork;
  1047. }
  1048. -(void)_pumpScanner;
  1049. {
  1050. [self assertOnWorkQueue];
  1051. if (!_isPumping) {
  1052. _isPumping = YES;
  1053. } else {
  1054. return;
  1055. }
  1056. while ([self _innerPumpScanner]) {
  1057. }
  1058. _isPumping = NO;
  1059. }
  1060. //#define NOMASK
  1061. static const size_t SRFrameHeaderOverhead = 32;
  1062. - (void)_sendFrameWithOpcode:(FSROpCode)opcode data:(id)data;
  1063. {
  1064. [self assertOnWorkQueue];
  1065. if (data == nil) {
  1066. return;
  1067. }
  1068. NSAssert([data isKindOfClass:[NSData class]] || [data isKindOfClass:[NSString class]], @"Function expects nil, NSString or NSData");
  1069. size_t payloadLength = [data isKindOfClass:[NSString class]] ? [(NSString *)data lengthOfBytesUsingEncoding:NSUTF8StringEncoding] : [data length];
  1070. NSMutableData *frame = [[NSMutableData alloc] initWithLength:payloadLength + SRFrameHeaderOverhead];
  1071. if (!frame) {
  1072. [self closeWithCode:SRStatusCodeMessageTooBig reason:@"Message too big"];
  1073. return;
  1074. }
  1075. uint8_t *frame_buffer = (uint8_t *)[frame mutableBytes];
  1076. // set fin
  1077. frame_buffer[0] = SRFinMask | opcode;
  1078. BOOL useMask = YES;
  1079. #endif // !TARGET_OS_WATCH
  1080. #ifdef NOMASK
  1081. useMask = NO;
  1082. #endif
  1083. #if !TARGET_OS_WATCH
  1084. if (useMask) {
  1085. // set the mask and header
  1086. frame_buffer[1] |= SRMaskMask;
  1087. }
  1088. size_t frame_buffer_size = 2;
  1089. const uint8_t *unmasked_payload = NULL;
  1090. if ([data isKindOfClass:[NSData class]]) {
  1091. unmasked_payload = (uint8_t *)[data bytes];
  1092. } else if ([data isKindOfClass:[NSString class]]) {
  1093. unmasked_payload = (const uint8_t *)[data UTF8String];
  1094. } else {
  1095. assert(NO);
  1096. }
  1097. if (payloadLength < 126) {
  1098. frame_buffer[1] |= payloadLength;
  1099. } else if (payloadLength <= UINT16_MAX) {
  1100. frame_buffer[1] |= 126;
  1101. *((uint16_t *)(frame_buffer + frame_buffer_size)) = EndianU16_BtoN((uint16_t)payloadLength);
  1102. frame_buffer_size += sizeof(uint16_t);
  1103. } else {
  1104. frame_buffer[1] |= 127;
  1105. *((uint64_t *)(frame_buffer + frame_buffer_size)) = EndianU64_BtoN((uint64_t)payloadLength);
  1106. frame_buffer_size += sizeof(uint64_t);
  1107. }
  1108. if (!useMask) {
  1109. for (int i = 0; i < payloadLength; i++) {
  1110. frame_buffer[frame_buffer_size] = unmasked_payload[i];
  1111. frame_buffer_size += 1;
  1112. }
  1113. } else {
  1114. uint8_t *mask_key = frame_buffer + frame_buffer_size;
  1115. int __unused result =
  1116. SecRandomCopyBytes(kSecRandomDefault, sizeof(uint32_t), (uint8_t *)mask_key);
  1117. assert(result == 0);
  1118. frame_buffer_size += sizeof(uint32_t);
  1119. // TODO: could probably optimize this with SIMD
  1120. for (int i = 0; i < payloadLength; i++) {
  1121. frame_buffer[frame_buffer_size] = unmasked_payload[i] ^ mask_key[i % sizeof(uint32_t)];
  1122. frame_buffer_size += 1;
  1123. }
  1124. }
  1125. assert(frame_buffer_size <= [frame length]);
  1126. frame.length = frame_buffer_size;
  1127. [self _writeData:frame];
  1128. }
  1129. - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode;
  1130. {
  1131. __weak __typeof__(self) weakSelf = self;
  1132. // turn on keep-alive for the output stream.
  1133. if (eventCode == NSStreamEventOpenCompleted && aStream == _outputStream) {
  1134. CFDataRef socketData = CFWriteStreamCopyProperty((CFWriteStreamRef)_outputStream, kCFStreamPropertySocketNativeHandle);
  1135. // In rare cases socketData might be nil (there are crash reports out there), in which case we'll have to just
  1136. // live without keep-alive :(
  1137. if (socketData != nil) {
  1138. CFSocketNativeHandle socket;
  1139. CFDataGetBytes(socketData, CFRangeMake(0, sizeof(CFSocketNativeHandle)), (UInt8 *)&socket);
  1140. CFRelease(socketData);
  1141. int keepAliveOn = 1;
  1142. if (setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, &keepAliveOn, sizeof(keepAliveOn)) == -1) {
  1143. SRFastLog(@"Failed to turn on TCP keepalive for websocket");
  1144. }
  1145. }
  1146. }
  1147. if (_secure && !_pinnedCertFound && (eventCode == NSStreamEventHasBytesAvailable || eventCode == NSStreamEventHasSpaceAvailable)) {
  1148. NSArray *sslCerts = [_urlRequest FSR_SSLPinnedCertificates];
  1149. if (sslCerts) {
  1150. SecTrustRef secTrust = (__bridge SecTrustRef)[aStream propertyForKey:(__bridge id)kCFStreamPropertySSLPeerTrust];
  1151. if (secTrust) {
  1152. NSInteger numCerts = SecTrustGetCertificateCount(secTrust);
  1153. for (NSInteger i = 0; i < numCerts && !_pinnedCertFound; i++) {
  1154. SecCertificateRef cert = SecTrustGetCertificateAtIndex(secTrust, i);
  1155. NSData *certData = CFBridgingRelease(SecCertificateCopyData(cert));
  1156. for (id ref in sslCerts) {
  1157. SecCertificateRef trustedCert = (__bridge SecCertificateRef)ref;
  1158. NSData *trustedCertData = CFBridgingRelease(SecCertificateCopyData(trustedCert));
  1159. if ([trustedCertData isEqualToData:certData]) {
  1160. _pinnedCertFound = YES;
  1161. break;
  1162. }
  1163. }
  1164. }
  1165. }
  1166. if (!_pinnedCertFound) {
  1167. dispatch_async(_workQueue, ^{
  1168. NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : @"Invalid server cert" };
  1169. [weakSelf _failWithError:[NSError errorWithDomain:@"org.lolrus.SocketRocket" code:23556 userInfo:userInfo]];
  1170. });
  1171. return;
  1172. }
  1173. }
  1174. }
  1175. // SRFastLog(@"%@ Got stream event %d", aStream, eventCode);
  1176. dispatch_async(_workQueue, ^{
  1177. [weakSelf safeHandleEvent:eventCode stream:aStream];
  1178. });
  1179. }
  1180. - (void)safeHandleEvent:(NSStreamEvent)eventCode stream:(NSStream *)aStream
  1181. {
  1182. switch (eventCode) {
  1183. case NSStreamEventOpenCompleted: {
  1184. SRFastLog(@"NSStreamEventOpenCompleted %@", aStream);
  1185. if (self.readyState >= SR_CLOSING) {
  1186. return;
  1187. }
  1188. assert(_readBuffer);
  1189. if (self.readyState == SR_CONNECTING && aStream == _inputStream) {
  1190. [self didConnect];
  1191. }
  1192. [self _pumpWriting];
  1193. [self _pumpScanner];
  1194. break;
  1195. }
  1196. case NSStreamEventErrorOccurred: {
  1197. // Note: The upstream code for SocketRocket logs the error message, but this causes
  1198. // crashes on iOS 13 (https://github.com/firebase/firebase-ios-sdk/issues/3950)
  1199. SRFastLog(@"NSStreamEventErrorOccurred %@", aStream);
  1200. /// TODO specify error better!
  1201. [self _failWithError:aStream.streamError];
  1202. _readBufferOffset = 0;
  1203. [_readBuffer setLength:0];
  1204. break;
  1205. }
  1206. case NSStreamEventEndEncountered: {
  1207. [self _pumpScanner];
  1208. SRFastLog(@"NSStreamEventEndEncountered %@", aStream);
  1209. if (aStream.streamError) {
  1210. [self _failWithError:aStream.streamError];
  1211. } else {
  1212. dispatch_async(_workQueue, ^{
  1213. if (self.readyState != SR_CLOSED) {
  1214. self.readyState = SR_CLOSED;
  1215. [self _scheduleCleanup];
  1216. }
  1217. if (!self->_sentClose && !self->_failed) {
  1218. self->_sentClose = YES;
  1219. // If we get closed in this state it's probably not clean because we should be sending this when we send messages
  1220. [self _performDelegateBlock:^{
  1221. if ([self.delegate respondsToSelector:@selector(webSocket:didCloseWithCode:reason:wasClean:)]) {
  1222. [self.delegate webSocket:self didCloseWithCode:0 reason:@"Stream end encountered" wasClean:NO];
  1223. }
  1224. }];
  1225. }
  1226. });
  1227. }
  1228. break;
  1229. }
  1230. case NSStreamEventHasBytesAvailable: {
  1231. SRFastLog(@"NSStreamEventHasBytesAvailable %@", aStream);
  1232. #define FSRWEB_SOCKET_BUFFER_SIZE 2048
  1233. uint8_t buffer[FSRWEB_SOCKET_BUFFER_SIZE];
  1234. while (_inputStream.hasBytesAvailable) {
  1235. NSInteger bytes_read = [_inputStream read:buffer maxLength:FSRWEB_SOCKET_BUFFER_SIZE];
  1236. if (bytes_read > 0) {
  1237. [_readBuffer appendBytes:buffer length:bytes_read];
  1238. } else if (bytes_read < 0) {
  1239. [self _failWithError:_inputStream.streamError];
  1240. }
  1241. if (bytes_read != FSRWEB_SOCKET_BUFFER_SIZE) {
  1242. break;
  1243. }
  1244. };
  1245. [self _pumpScanner];
  1246. break;
  1247. }
  1248. case NSStreamEventHasSpaceAvailable: {
  1249. SRFastLog(@"NSStreamEventHasSpaceAvailable %@", aStream);
  1250. [self _pumpWriting];
  1251. break;
  1252. }
  1253. default:
  1254. SRFastLog(@"(default) %@", aStream);
  1255. break;
  1256. }
  1257. }
  1258. @end
  1259. @implementation FSRIOConsumer
  1260. @synthesize bytesNeeded = _bytesNeeded;
  1261. @synthesize consumer = _scanner;
  1262. @synthesize handler = _handler;
  1263. @synthesize readToCurrentFrame = _readToCurrentFrame;
  1264. @synthesize unmaskBytes = _unmaskBytes;
  1265. - (void)setupWithScanner:(stream_scanner)scanner handler:(data_callback)handler bytesNeeded:(size_t)bytesNeeded readToCurrentFrame:(BOOL)readToCurrentFrame unmaskBytes:(BOOL)unmaskBytes;
  1266. {
  1267. _scanner = [scanner copy];
  1268. _handler = [handler copy];
  1269. _bytesNeeded = bytesNeeded;
  1270. _readToCurrentFrame = readToCurrentFrame;
  1271. _unmaskBytes = unmaskBytes;
  1272. assert(_scanner || _bytesNeeded);
  1273. }
  1274. @end
  1275. @implementation FSRIOConsumerPool {
  1276. NSUInteger _poolSize;
  1277. NSMutableArray *_bufferedConsumers;
  1278. }
  1279. - (id)initWithBufferCapacity:(NSUInteger)poolSize;
  1280. {
  1281. self = [super init];
  1282. if (self) {
  1283. _poolSize = poolSize;
  1284. _bufferedConsumers = [[NSMutableArray alloc] initWithCapacity:poolSize];
  1285. }
  1286. return self;
  1287. }
  1288. - (id)init
  1289. {
  1290. return [self initWithBufferCapacity:8];
  1291. }
  1292. - (FSRIOConsumer *)consumerWithScanner:(stream_scanner)scanner handler:(data_callback)handler bytesNeeded:(size_t)bytesNeeded readToCurrentFrame:(BOOL)readToCurrentFrame unmaskBytes:(BOOL)unmaskBytes;
  1293. {
  1294. FSRIOConsumer *consumer = nil;
  1295. if (_bufferedConsumers.count) {
  1296. consumer = [_bufferedConsumers lastObject];
  1297. [_bufferedConsumers removeLastObject];
  1298. } else {
  1299. consumer = [[FSRIOConsumer alloc] init];
  1300. }
  1301. [consumer setupWithScanner:scanner handler:handler bytesNeeded:bytesNeeded readToCurrentFrame:readToCurrentFrame unmaskBytes:unmaskBytes];
  1302. return consumer;
  1303. }
  1304. - (void)returnConsumer:(FSRIOConsumer *)consumer;
  1305. {
  1306. if (_bufferedConsumers.count < _poolSize) {
  1307. [_bufferedConsumers addObject:consumer];
  1308. }
  1309. }
  1310. @end
  1311. @implementation NSURLRequest (FCertificateAdditions)
  1312. - (NSArray *)FSR_SSLPinnedCertificates;
  1313. {
  1314. return [NSURLProtocol propertyForKey:@"FSR_SSLPinnedCertificates" inRequest:self];
  1315. }
  1316. @end
  1317. @implementation NSMutableURLRequest (FCertificateAdditions)
  1318. - (NSArray *)FSR_SSLPinnedCertificates;
  1319. {
  1320. return [NSURLProtocol propertyForKey:@"FSR_SSLPinnedCertificates" inRequest:self];
  1321. }
  1322. - (void)setFSR_SSLPinnedCertificates:(NSArray *)FSR_SSLPinnedCertificates;
  1323. {
  1324. [NSURLProtocol setProperty:FSR_SSLPinnedCertificates forKey:@"FSR_SSLPinnedCertificates" inRequest:self];
  1325. }
  1326. @end
  1327. @implementation NSURL (FSRWebSocket)
  1328. - (NSString *)SR_origin;
  1329. {
  1330. NSString *scheme = [self.scheme lowercaseString];
  1331. if ([scheme isEqualToString:@"wss"]) {
  1332. scheme = @"https";
  1333. } else if ([scheme isEqualToString:@"ws"]) {
  1334. scheme = @"http";
  1335. }
  1336. if (self.port != nil) {
  1337. return [NSString stringWithFormat:@"%@://%@:%@/", scheme, self.host, self.port];
  1338. } else {
  1339. return [NSString stringWithFormat:@"%@://%@/", scheme, self.host];
  1340. }
  1341. }
  1342. @end
  1343. // #define SR_ENABLE_LOG
  1344. static inline void SRFastLog(NSString *format, ...) {
  1345. #ifdef SR_ENABLE_LOG
  1346. __block va_list arg_list;
  1347. va_start (arg_list, format);
  1348. NSString *formattedString = [[NSString alloc] initWithFormat:format arguments:arg_list];
  1349. va_end(arg_list);
  1350. NSLog(@"[SR] %@", formattedString);
  1351. #endif
  1352. }
  1353. #ifdef HAS_ICU
  1354. static inline int32_t validate_dispatch_data_partial_string(NSData *data) {
  1355. const void * contents = [data bytes];
  1356. long size = [data length];
  1357. const uint8_t *str = (const uint8_t *)contents;
  1358. UChar32 codepoint = 1;
  1359. int32_t offset = 0;
  1360. int32_t lastOffset = 0;
  1361. while(offset < size && codepoint > 0) {
  1362. lastOffset = offset;
  1363. U8_NEXT(str, offset, size, codepoint);
  1364. }
  1365. if (codepoint == -1) {
  1366. // Check to see if the last byte is valid or whether it was just continuing
  1367. if (!U8_IS_LEAD(str[lastOffset]) || U8_COUNT_TRAIL_BYTES(str[lastOffset]) + lastOffset < (int32_t)size) {
  1368. size = -1;
  1369. } else {
  1370. uint8_t leadByte = str[lastOffset];
  1371. U8_MASK_LEAD_BYTE(leadByte, U8_COUNT_TRAIL_BYTES(leadByte));
  1372. for (int i = lastOffset + 1; i < offset; i++) {
  1373. if (U8_IS_SINGLE(str[i]) || U8_IS_LEAD(str[i]) || !U8_IS_TRAIL(str[i])) {
  1374. size = -1;
  1375. }
  1376. }
  1377. if (size != -1) {
  1378. size = lastOffset;
  1379. }
  1380. }
  1381. }
  1382. if (size != -1 && ![[NSString alloc] initWithBytesNoCopy:(char *)[data bytes] length:size encoding:NSUTF8StringEncoding freeWhenDone:NO]) {
  1383. size = -1;
  1384. }
  1385. return (int32_t)size;
  1386. }
  1387. #else
  1388. // This is a hack, and probably not optimal
  1389. static inline int32_t validate_dispatch_data_partial_string(NSData *data) {
  1390. static const int maxCodepointSize = 3;
  1391. for (int i = 0; i < maxCodepointSize; i++) {
  1392. NSString *str = [[NSString alloc] initWithBytesNoCopy:(char *)data.bytes length:data.length - i encoding:NSUTF8StringEncoding freeWhenDone:NO];
  1393. if (str) {
  1394. return (int)(data.length - i);
  1395. }
  1396. }
  1397. return -1;
  1398. }
  1399. #endif
  1400. static _FSRRunLoopThread *networkThread = nil;
  1401. static NSRunLoop *networkRunLoop = nil;
  1402. @implementation NSRunLoop (FSRWebSocket)
  1403. + (NSRunLoop *)FSR_networkRunLoop {
  1404. static dispatch_once_t onceToken;
  1405. dispatch_once(&onceToken, ^{
  1406. networkThread = [[_FSRRunLoopThread alloc] init];
  1407. networkThread.name = @"com.squareup.SocketRocket.NetworkThread";
  1408. networkThread.qualityOfService = NSQualityOfServiceUserInitiated;
  1409. [networkThread start];
  1410. networkRunLoop = networkThread.runLoop;
  1411. });
  1412. return networkRunLoop;
  1413. }
  1414. @end
  1415. @implementation _FSRRunLoopThread {
  1416. dispatch_group_t _waitGroup;
  1417. }
  1418. @synthesize runLoop = _runLoop;
  1419. - (void)dealloc
  1420. {
  1421. sr_dispatch_release(_waitGroup);
  1422. }
  1423. - (id)init
  1424. {
  1425. self = [super init];
  1426. if (self) {
  1427. _waitGroup = dispatch_group_create();
  1428. dispatch_group_enter(_waitGroup);
  1429. }
  1430. return self;
  1431. }
  1432. /**
  1433. * This is the main method of the thread on which the socket events are scheduled in a run loop.
  1434. */
  1435. - (void)main;
  1436. {
  1437. @autoreleasepool {
  1438. _runLoop = [NSRunLoop currentRunLoop];
  1439. dispatch_group_leave(_waitGroup);
  1440. // Add an empty run loop source to prevent runloop from spinning.
  1441. CFRunLoopSourceContext sourceCtx = {
  1442. .version = 0,
  1443. .info = NULL,
  1444. .retain = NULL,
  1445. .release = NULL,
  1446. .copyDescription = NULL,
  1447. .equal = NULL,
  1448. .hash = NULL,
  1449. .schedule = NULL,
  1450. .cancel = NULL,
  1451. .perform = NULL
  1452. };
  1453. CFRunLoopSourceRef source = CFRunLoopSourceCreate(NULL, 0, &sourceCtx);
  1454. CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
  1455. CFRelease(source);
  1456. while ([_runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) {
  1457. }
  1458. assert(NO);
  1459. }
  1460. }
  1461. - (NSRunLoop *)runLoop;
  1462. {
  1463. dispatch_group_wait(_waitGroup, DISPATCH_TIME_FOREVER);
  1464. return _runLoop;
  1465. }
  1466. @end
  1467. #endif // TARGET_OS_WATCH