FSRWebSocket.m 57 KB

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