FSRWebSocket.m 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874
  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 start];
  1400. networkRunLoop = networkThread.runLoop;
  1401. });
  1402. return networkRunLoop;
  1403. }
  1404. @end
  1405. @implementation _FSRRunLoopThread {
  1406. dispatch_group_t _waitGroup;
  1407. }
  1408. @synthesize runLoop = _runLoop;
  1409. - (void)dealloc
  1410. {
  1411. sr_dispatch_release(_waitGroup);
  1412. }
  1413. - (id)init
  1414. {
  1415. self = [super init];
  1416. if (self) {
  1417. _waitGroup = dispatch_group_create();
  1418. dispatch_group_enter(_waitGroup);
  1419. }
  1420. return self;
  1421. }
  1422. /**
  1423. * This is the main method of the thread on which the socket events are scheduled in a run loop.
  1424. */
  1425. - (void)main;
  1426. {
  1427. @autoreleasepool {
  1428. _runLoop = [NSRunLoop currentRunLoop];
  1429. dispatch_group_leave(_waitGroup);
  1430. // Add an empty run loop source to prevent runloop from spinning.
  1431. CFRunLoopSourceContext sourceCtx = {
  1432. .version = 0,
  1433. .info = NULL,
  1434. .retain = NULL,
  1435. .release = NULL,
  1436. .copyDescription = NULL,
  1437. .equal = NULL,
  1438. .hash = NULL,
  1439. .schedule = NULL,
  1440. .cancel = NULL,
  1441. .perform = NULL
  1442. };
  1443. CFRunLoopSourceRef source = CFRunLoopSourceCreate(NULL, 0, &sourceCtx);
  1444. CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
  1445. CFRelease(source);
  1446. while ([_runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) {
  1447. }
  1448. assert(NO);
  1449. }
  1450. }
  1451. - (NSRunLoop *)runLoop;
  1452. {
  1453. dispatch_group_wait(_waitGroup, DISPATCH_TIME_FOREVER);
  1454. return _runLoop;
  1455. }
  1456. @end
  1457. #endif // TARGET_OS_WATCH