FSRWebSocket.m 57 KB

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