SRWebSocket.m 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638
  1. //
  2. // Copyright 2012 Square Inc.
  3. // Portions Copyright (c) 2016-present, Facebook, Inc.
  4. //
  5. // All rights reserved.
  6. //
  7. // This source code is licensed under the BSD-style license found in the
  8. // LICENSE file in the root directory of this source tree. An additional grant
  9. // of patent rights can be found in the PATENTS file in the same directory.
  10. //
  11. #import "SRWebSocket.h"
  12. #if TARGET_OS_IPHONE
  13. #define HAS_ICU
  14. #endif
  15. #ifdef HAS_ICU
  16. #import <unicode/utf8.h>
  17. #endif
  18. #import <libkern/OSAtomic.h>
  19. #import "SRDelegateController.h"
  20. #import "SRIOConsumer.h"
  21. #import "SRIOConsumerPool.h"
  22. #import "SRHash.h"
  23. #import "SRURLUtilities.h"
  24. #import "SRError.h"
  25. #import "NSURLRequest+SRWebSocket.h"
  26. #import "NSRunLoop+SRWebSocket.h"
  27. #import "SRProxyConnect.h"
  28. #import "SRSecurityPolicy.h"
  29. #import "SRHTTPConnectMessage.h"
  30. #import "SRRandom.h"
  31. #import "SRLog.h"
  32. #import "SRMutex.h"
  33. #import "SRSIMDHelpers.h"
  34. #import "NSURLRequest+SRWebSocketPrivate.h"
  35. #import "NSRunLoop+SRWebSocketPrivate.h"
  36. #import "SRConstants.h"
  37. #if !__has_feature(objc_arc)
  38. #error SocketRocket must be compiled with ARC enabled
  39. #endif
  40. __attribute__((used)) static void importCategories()
  41. {
  42. import_NSURLRequest_SRWebSocket();
  43. import_NSRunLoop_SRWebSocket();
  44. }
  45. typedef struct {
  46. BOOL fin;
  47. // BOOL rsv1;
  48. // BOOL rsv2;
  49. // BOOL rsv3;
  50. uint8_t opcode;
  51. BOOL masked;
  52. uint64_t payload_length;
  53. } frame_header;
  54. static NSString *const SRWebSocketAppendToSecKeyString = @"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  55. static inline int32_t validate_dispatch_data_partial_string(NSData *data);
  56. static uint8_t const SRWebSocketProtocolVersion = 13;
  57. NSString *const SRWebSocketErrorDomain = @"SRWebSocketErrorDomain";
  58. NSString *const SRHTTPResponseErrorKey = @"HTTPResponseStatusCode";
  59. @interface SRWebSocket () <NSStreamDelegate>
  60. @property (atomic, assign, readwrite) SRReadyState readyState;
  61. // Specifies whether SSL trust chain should NOT be evaluated.
  62. // By default this flag is set to NO, meaning only secure SSL connections are allowed.
  63. // For DEBUG builds this flag is ignored, and SSL connections are allowed regardless
  64. // of the certificate trust configuration
  65. @property (nonatomic, assign, readwrite) BOOL allowsUntrustedSSLCertificates;
  66. @property (nonatomic, strong, readonly) SRDelegateController *delegateController;
  67. @end
  68. @implementation SRWebSocket {
  69. SRMutex _kvoLock;
  70. OSSpinLock _propertyLock;
  71. dispatch_queue_t _workQueue;
  72. NSMutableArray<SRIOConsumer *> *_consumers;
  73. NSInputStream *_inputStream;
  74. NSOutputStream *_outputStream;
  75. dispatch_data_t _readBuffer;
  76. NSUInteger _readBufferOffset;
  77. dispatch_data_t _outputBuffer;
  78. NSUInteger _outputBufferOffset;
  79. uint8_t _currentFrameOpcode;
  80. size_t _currentFrameCount;
  81. size_t _readOpCount;
  82. uint32_t _currentStringScanPosition;
  83. NSMutableData *_currentFrameData;
  84. NSString *_closeReason;
  85. NSString *_secKey;
  86. SRSecurityPolicy *_securityPolicy;
  87. BOOL _requestRequiresSSL;
  88. BOOL _streamSecurityValidated;
  89. uint8_t _currentReadMaskKey[4];
  90. size_t _currentReadMaskOffset;
  91. BOOL _closeWhenFinishedWriting;
  92. BOOL _failed;
  93. NSURLRequest *_urlRequest;
  94. BOOL _sentClose;
  95. BOOL _didFail;
  96. BOOL _cleanupScheduled;
  97. int _closeCode;
  98. BOOL _isPumping;
  99. NSMutableSet<NSArray *> *_scheduledRunloops; // Set<[RunLoop, Mode]>. TODO: (nlutsenko) Fix clowntown
  100. // We use this to retain ourselves.
  101. __strong SRWebSocket *_selfRetain;
  102. NSArray<NSString *> *_requestedProtocols;
  103. SRIOConsumerPool *_consumerPool;
  104. // proxy support
  105. SRProxyConnect *_proxyConnect;
  106. }
  107. @synthesize readyState = _readyState;
  108. ///--------------------------------------
  109. #pragma mark - Init
  110. ///--------------------------------------
  111. - (instancetype)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray<NSString *> *)protocols securityPolicy:(SRSecurityPolicy *)securityPolicy
  112. {
  113. self = [super init];
  114. if (!self) return self;
  115. assert(request.URL);
  116. _url = request.URL;
  117. _urlRequest = request;
  118. _requestedProtocols = [protocols copy];
  119. _securityPolicy = securityPolicy;
  120. _requestRequiresSSL = SRURLRequiresSSL(_url);
  121. _readyState = SR_CONNECTING;
  122. _propertyLock = OS_SPINLOCK_INIT;
  123. _kvoLock = SRMutexInitRecursive();
  124. _workQueue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
  125. // Going to set a specific on the queue so we can validate we're on the work queue
  126. dispatch_queue_set_specific(_workQueue, (__bridge void *)self, (__bridge void *)(_workQueue), NULL);
  127. _delegateController = [[SRDelegateController alloc] init];
  128. _readBuffer = dispatch_data_empty;
  129. _outputBuffer = dispatch_data_empty;
  130. _currentFrameData = [[NSMutableData alloc] init];
  131. _consumers = [[NSMutableArray alloc] init];
  132. _consumerPool = [[SRIOConsumerPool alloc] init];
  133. _scheduledRunloops = [[NSMutableSet alloc] init];
  134. return self;
  135. }
  136. - (instancetype)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray<NSString *> *)protocols allowsUntrustedSSLCertificates:(BOOL)allowsUntrustedSSLCertificates
  137. {
  138. SRSecurityPolicy *securityPolicy;
  139. NSArray *pinnedCertificates = request.SR_SSLPinnedCertificates;
  140. if (pinnedCertificates) {
  141. securityPolicy = [SRSecurityPolicy pinnningPolicyWithCertificates:pinnedCertificates];
  142. } else {
  143. BOOL certificateChainValidationEnabled = !allowsUntrustedSSLCertificates;
  144. securityPolicy = [[SRSecurityPolicy alloc] initWithCertificateChainValidationEnabled:certificateChainValidationEnabled];
  145. }
  146. return [self initWithURLRequest:request protocols:protocols securityPolicy:securityPolicy];
  147. }
  148. - (instancetype)initWithURLRequest:(NSURLRequest *)request securityPolicy:(SRSecurityPolicy *)securityPolicy
  149. {
  150. return [self initWithURLRequest:request protocols:nil securityPolicy:securityPolicy];
  151. }
  152. - (instancetype)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray<NSString *> *)protocols
  153. {
  154. return [self initWithURLRequest:request protocols:protocols allowsUntrustedSSLCertificates:NO];
  155. }
  156. - (instancetype)initWithURLRequest:(NSURLRequest *)request
  157. {
  158. return [self initWithURLRequest:request protocols:nil];
  159. }
  160. - (instancetype)initWithURL:(NSURL *)url;
  161. {
  162. return [self initWithURL:url protocols:nil];
  163. }
  164. - (instancetype)initWithURL:(NSURL *)url protocols:(NSArray<NSString *> *)protocols;
  165. {
  166. return [self initWithURL:url protocols:protocols allowsUntrustedSSLCertificates:NO];
  167. }
  168. - (instancetype)initWithURL:(NSURL *)url securityPolicy:(SRSecurityPolicy *)securityPolicy
  169. {
  170. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  171. return [self initWithURLRequest:request protocols:nil securityPolicy:securityPolicy];
  172. }
  173. - (instancetype)initWithURL:(NSURL *)url protocols:(NSArray<NSString *> *)protocols allowsUntrustedSSLCertificates:(BOOL)allowsUntrustedSSLCertificates
  174. {
  175. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  176. return [self initWithURLRequest:request protocols:protocols allowsUntrustedSSLCertificates:allowsUntrustedSSLCertificates];
  177. }
  178. - (void)assertOnWorkQueue;
  179. {
  180. assert(dispatch_get_specific((__bridge void *)self) == (__bridge void *)_workQueue);
  181. }
  182. ///--------------------------------------
  183. #pragma mark - Dealloc
  184. ///--------------------------------------
  185. - (void)dealloc
  186. {
  187. _inputStream.delegate = nil;
  188. _outputStream.delegate = nil;
  189. [_inputStream close];
  190. [_outputStream close];
  191. if (_receivedHTTPHeaders) {
  192. CFRelease(_receivedHTTPHeaders);
  193. _receivedHTTPHeaders = NULL;
  194. }
  195. SRMutexDestroy(_kvoLock);
  196. }
  197. ///--------------------------------------
  198. #pragma mark - Accessors
  199. ///--------------------------------------
  200. #pragma mark readyState
  201. - (void)setReadyState:(SRReadyState)readyState
  202. {
  203. @try {
  204. SRMutexLock(_kvoLock);
  205. if (_readyState != readyState) {
  206. [self willChangeValueForKey:@"readyState"];
  207. OSSpinLockLock(&_propertyLock);
  208. _readyState = readyState;
  209. OSSpinLockUnlock(&_propertyLock);
  210. [self didChangeValueForKey:@"readyState"];
  211. }
  212. }
  213. @finally {
  214. SRMutexUnlock(_kvoLock);
  215. }
  216. }
  217. - (SRReadyState)readyState
  218. {
  219. SRReadyState state = 0;
  220. OSSpinLockLock(&_propertyLock);
  221. state = _readyState;
  222. OSSpinLockUnlock(&_propertyLock);
  223. return state;
  224. }
  225. + (BOOL)automaticallyNotifiesObserversOfReadyState {
  226. return NO;
  227. }
  228. -(void)_onTimeout
  229. {
  230. if (self.readyState == SR_CONNECTING) {
  231. NSError *error = SRErrorWithDomainCodeDescription(NSURLErrorDomain, NSURLErrorTimedOut, @"Timed out connecting to server.");
  232. [self _failWithError:error];
  233. }
  234. }
  235. ///--------------------------------------
  236. #pragma mark - Open / Close
  237. ///--------------------------------------
  238. - (void)open
  239. {
  240. assert(_url);
  241. NSAssert(self.readyState == SR_CONNECTING, @"Cannot call -(void)open on SRWebSocket more than once.");
  242. _selfRetain = self;
  243. if (_urlRequest.timeoutInterval > 0) {
  244. [self performSelector:@selector(_onTimeout) withObject:nil afterDelay:_urlRequest.timeoutInterval];
  245. }
  246. _proxyConnect = [[SRProxyConnect alloc] initWithURL:_url];
  247. __weak __typeof(self) wself = self;
  248. [_proxyConnect openNetworkStreamWithCompletion:^(NSError *error, NSInputStream *readStream, NSOutputStream *writeStream) {
  249. [wself _connectionDoneWithError:error readStream:readStream writeStream:writeStream];
  250. }];
  251. }
  252. - (void)_connectionDoneWithError:(NSError *)error readStream:(NSInputStream *)readStream writeStream:(NSOutputStream *)writeStream
  253. {
  254. if (error != nil) {
  255. [self _failWithError:error];
  256. } else {
  257. _outputStream = writeStream;
  258. _inputStream = readStream;
  259. _inputStream.delegate = self;
  260. _outputStream.delegate = self;
  261. [self _updateSecureStreamOptions];
  262. if (!_scheduledRunloops.count) {
  263. [self scheduleInRunLoop:[NSRunLoop SR_networkRunLoop] forMode:NSDefaultRunLoopMode];
  264. }
  265. // If we don't require SSL validation - consider that we connected.
  266. // Otherwise `didConnect` is called when SSL validation finishes.
  267. if (!_requestRequiresSSL) {
  268. dispatch_async(_workQueue, ^{
  269. [self didConnect];
  270. });
  271. }
  272. }
  273. // Schedule to run on a work queue, to make sure we don't run this inline and deallocate `self` inside `SRProxyConnect`.
  274. // TODO: (nlutsenko) Find a better structure for this, maybe Bolts Tasks?
  275. dispatch_async(_workQueue, ^{
  276. _proxyConnect = nil;
  277. });
  278. }
  279. - (BOOL)_checkHandshake:(CFHTTPMessageRef)httpMessage;
  280. {
  281. NSString *acceptHeader = CFBridgingRelease(CFHTTPMessageCopyHeaderFieldValue(httpMessage, CFSTR("Sec-WebSocket-Accept")));
  282. if (acceptHeader == nil) {
  283. return NO;
  284. }
  285. NSString *concattedString = [_secKey stringByAppendingString:SRWebSocketAppendToSecKeyString];
  286. NSData *hashedString = SRSHA1HashFromString(concattedString);
  287. NSString *expectedAccept = SRBase64EncodedStringFromData(hashedString);
  288. return [acceptHeader isEqualToString:expectedAccept];
  289. }
  290. - (void)_HTTPHeadersDidFinish;
  291. {
  292. NSInteger responseCode = CFHTTPMessageGetResponseStatusCode(_receivedHTTPHeaders);
  293. if (responseCode >= 400) {
  294. SRDebugLog(@"Request failed with response code %d", responseCode);
  295. NSError *error = SRHTTPErrorWithCodeDescription(responseCode, 2132,
  296. [NSString stringWithFormat:@"Received bad response code from server: %d.",
  297. (int)responseCode]);
  298. [self _failWithError:error];
  299. return;
  300. }
  301. if(![self _checkHandshake:_receivedHTTPHeaders]) {
  302. NSError *error = SRErrorWithCodeDescription(2133, @"Invalid Sec-WebSocket-Accept response.");
  303. [self _failWithError:error];
  304. return;
  305. }
  306. NSString *negotiatedProtocol = CFBridgingRelease(CFHTTPMessageCopyHeaderFieldValue(_receivedHTTPHeaders, CFSTR("Sec-WebSocket-Protocol")));
  307. if (negotiatedProtocol) {
  308. // Make sure we requested the protocol
  309. if ([_requestedProtocols indexOfObject:negotiatedProtocol] == NSNotFound) {
  310. NSError *error = SRErrorWithCodeDescription(2133, @"Server specified Sec-WebSocket-Protocol that wasn't requested.");
  311. [self _failWithError:error];
  312. return;
  313. }
  314. _protocol = negotiatedProtocol;
  315. }
  316. self.readyState = SR_OPEN;
  317. if (!_didFail) {
  318. [self _readFrameNew];
  319. }
  320. [self.delegateController performDelegateBlock:^(id<SRWebSocketDelegate> _Nullable delegate, SRDelegateAvailableMethods availableMethods) {
  321. if (availableMethods.didOpen) {
  322. [delegate webSocketDidOpen:self];
  323. }
  324. }];
  325. }
  326. - (void)_readHTTPHeader;
  327. {
  328. if (_receivedHTTPHeaders == NULL) {
  329. _receivedHTTPHeaders = CFHTTPMessageCreateEmpty(NULL, NO);
  330. }
  331. // Uses weak self object in the block, otherwise Consumers will retain SRWebSocket instance,
  332. // and SRWebSocket instance also hold consumers, cycle reference will occur.
  333. __weak __typeof(self) wself = self;
  334. [self _readUntilHeaderCompleteWithCallback:^(SRWebSocket *socket, NSData *data) {
  335. __strong __typeof(wself) sself = wself;
  336. if (sself == nil)
  337. return;
  338. CFHTTPMessageAppendBytes(sself.receivedHTTPHeaders, (const UInt8 *)data.bytes, data.length);
  339. if (CFHTTPMessageIsHeaderComplete(sself.receivedHTTPHeaders)) {
  340. SRDebugLog(@"Finished reading headers %@", CFBridgingRelease(CFHTTPMessageCopyAllHeaderFields(sself.receivedHTTPHeaders)));
  341. [sself _HTTPHeadersDidFinish];
  342. } else {
  343. [sself _readHTTPHeader];
  344. }
  345. }];
  346. }
  347. - (void)didConnect;
  348. {
  349. SRDebugLog(@"Connected");
  350. _secKey = SRBase64EncodedStringFromData(SRRandomData(16));
  351. assert([_secKey length] == 24);
  352. CFHTTPMessageRef message = SRHTTPConnectMessageCreate(_urlRequest,
  353. _secKey,
  354. SRWebSocketProtocolVersion,
  355. self.requestCookies,
  356. _requestedProtocols);
  357. NSData *messageData = CFBridgingRelease(CFHTTPMessageCopySerializedMessage(message));
  358. CFRelease(message);
  359. [self _writeData:messageData];
  360. [self _readHTTPHeader];
  361. }
  362. - (void)_updateSecureStreamOptions
  363. {
  364. if (_requestRequiresSSL) {
  365. SRDebugLog(@"Setting up security for streams.");
  366. [_securityPolicy updateSecurityOptionsInStream:_inputStream];
  367. [_securityPolicy updateSecurityOptionsInStream:_outputStream];
  368. }
  369. NSString *networkServiceType = SRStreamNetworkServiceTypeFromURLRequest(_urlRequest);
  370. if (networkServiceType != nil) {
  371. [_inputStream setProperty:networkServiceType forKey:NSStreamNetworkServiceType];
  372. [_outputStream setProperty:networkServiceType forKey:NSStreamNetworkServiceType];
  373. }
  374. }
  375. - (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
  376. {
  377. [_outputStream scheduleInRunLoop:aRunLoop forMode:mode];
  378. [_inputStream scheduleInRunLoop:aRunLoop forMode:mode];
  379. [_scheduledRunloops addObject:@[aRunLoop, mode]];
  380. }
  381. - (void)unscheduleFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
  382. {
  383. [_outputStream removeFromRunLoop:aRunLoop forMode:mode];
  384. [_inputStream removeFromRunLoop:aRunLoop forMode:mode];
  385. [_scheduledRunloops removeObject:@[aRunLoop, mode]];
  386. }
  387. - (void)close;
  388. {
  389. [self closeWithCode:SRStatusCodeNormal reason:nil];
  390. }
  391. - (void)closeWithCode:(NSInteger)code reason:(NSString *)reason;
  392. {
  393. assert(code);
  394. dispatch_async(_workQueue, ^{
  395. if (self.readyState == SR_CLOSING || self.readyState == SR_CLOSED) {
  396. return;
  397. }
  398. BOOL wasConnecting = self.readyState == SR_CONNECTING;
  399. self.readyState = SR_CLOSING;
  400. SRDebugLog(@"Closing with code %d reason %@", code, reason);
  401. if (wasConnecting) {
  402. [self closeConnection];
  403. return;
  404. }
  405. size_t maxMsgSize = [reason maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  406. NSMutableData *mutablePayload = [[NSMutableData alloc] initWithLength:sizeof(uint16_t) + maxMsgSize];
  407. NSData *payload = mutablePayload;
  408. ((uint16_t *)mutablePayload.mutableBytes)[0] = CFSwapInt16BigToHost((uint16_t)code);
  409. if (reason) {
  410. NSRange remainingRange = {0};
  411. NSUInteger usedLength = 0;
  412. 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];
  413. #pragma unused (success)
  414. assert(success);
  415. assert(remainingRange.length == 0);
  416. if (usedLength != maxMsgSize) {
  417. payload = [payload subdataWithRange:NSMakeRange(0, usedLength + sizeof(uint16_t))];
  418. }
  419. }
  420. [self _sendFrameWithOpcode:SROpCodeConnectionClose data:payload];
  421. });
  422. }
  423. - (void)_closeWithProtocolError:(NSString *)message;
  424. {
  425. // Need to shunt this on the _callbackQueue first to see if they received any messages
  426. [self.delegateController performDelegateQueueBlock:^{
  427. [self closeWithCode:SRStatusCodeProtocolError reason:message];
  428. dispatch_async(_workQueue, ^{
  429. [self closeConnection];
  430. });
  431. }];
  432. }
  433. - (void)_failWithError:(NSError *)error;
  434. {
  435. dispatch_async(_workQueue, ^{
  436. if (self.readyState != SR_CLOSED) {
  437. _failed = YES;
  438. [self.delegateController performDelegateBlock:^(id<SRWebSocketDelegate> _Nullable delegate, SRDelegateAvailableMethods availableMethods) {
  439. if (availableMethods.didFailWithError) {
  440. [delegate webSocket:self didFailWithError:error];
  441. }
  442. }];
  443. self.readyState = SR_CLOSED;
  444. SRDebugLog(@"Failing with error %@", error.localizedDescription);
  445. [self closeConnection];
  446. [self _scheduleCleanup];
  447. }
  448. });
  449. }
  450. - (void)_writeData:(NSData *)data;
  451. {
  452. [self assertOnWorkQueue];
  453. if (_closeWhenFinishedWriting) {
  454. return;
  455. }
  456. __block NSData *strongData = data;
  457. dispatch_data_t newData = dispatch_data_create(data.bytes, data.length, nil, ^{
  458. strongData = nil;
  459. });
  460. _outputBuffer = dispatch_data_create_concat(_outputBuffer, newData);
  461. [self _pumpWriting];
  462. }
  463. - (void)send:(nullable id)message
  464. {
  465. if (!message) {
  466. [self sendData:nil error:nil]; // Send Data, but it doesn't matter since we are going to send the same text frame with 0 length.
  467. } else if ([message isKindOfClass:[NSString class]]) {
  468. [self sendString:message error:nil];
  469. } else if ([message isKindOfClass:[NSData class]]) {
  470. [self sendData:message error:nil];
  471. } else {
  472. NSAssert(NO, @"Unrecognized message. Not able to send anything other than a String or NSData.");
  473. }
  474. }
  475. - (BOOL)sendString:(NSString *)string error:(NSError **)error
  476. {
  477. if (self.readyState != SR_OPEN) {
  478. NSString *message = @"Invalid State: Cannot call `sendString:error:` until connection is open.";
  479. if (error) {
  480. *error = SRErrorWithCodeDescription(2134, message);
  481. }
  482. SRDebugLog(message);
  483. return NO;
  484. }
  485. string = [string copy];
  486. dispatch_async(_workQueue, ^{
  487. [self _sendFrameWithOpcode:SROpCodeTextFrame data:[string dataUsingEncoding:NSUTF8StringEncoding]];
  488. });
  489. return YES;
  490. }
  491. - (BOOL)sendData:(nullable NSData *)data error:(NSError **)error
  492. {
  493. data = [data copy];
  494. return [self sendDataNoCopy:data error:error];
  495. }
  496. - (BOOL)sendDataNoCopy:(nullable NSData *)data error:(NSError **)error
  497. {
  498. if (self.readyState != SR_OPEN) {
  499. NSString *message = @"Invalid State: Cannot call `sendDataNoCopy:error:` until connection is open.";
  500. if (error) {
  501. *error = SRErrorWithCodeDescription(2134, message);
  502. }
  503. SRDebugLog(message);
  504. return NO;
  505. }
  506. dispatch_async(_workQueue, ^{
  507. if (data) {
  508. [self _sendFrameWithOpcode:SROpCodeBinaryFrame data:data];
  509. } else {
  510. [self _sendFrameWithOpcode:SROpCodeTextFrame data:nil];
  511. }
  512. });
  513. return YES;
  514. }
  515. - (BOOL)sendPing:(nullable NSData *)data error:(NSError **)error
  516. {
  517. if (self.readyState != SR_OPEN) {
  518. NSString *message = @"Invalid State: Cannot call `sendPing:error:` until connection is open.";
  519. if (error) {
  520. *error = SRErrorWithCodeDescription(2134, message);
  521. }
  522. SRDebugLog(message);
  523. return NO;
  524. }
  525. data = [data copy] ?: [NSData data]; // It's okay for a ping to be empty
  526. dispatch_async(_workQueue, ^{
  527. [self _sendFrameWithOpcode:SROpCodePing data:data];
  528. });
  529. return YES;
  530. }
  531. - (void)_handlePingWithData:(nullable NSData *)data
  532. {
  533. // Need to pingpong this off _callbackQueue first to make sure messages happen in order
  534. [self.delegateController performDelegateBlock:^(id<SRWebSocketDelegate> _Nullable delegate, SRDelegateAvailableMethods availableMethods) {
  535. if (availableMethods.didReceivePing) {
  536. [delegate webSocket:self didReceivePingWithData:data];
  537. }
  538. dispatch_async(_workQueue, ^{
  539. [self _sendFrameWithOpcode:SROpCodePong data:data];
  540. });
  541. }];
  542. }
  543. - (void)handlePong:(NSData *)pongData;
  544. {
  545. SRDebugLog(@"Received pong");
  546. [self.delegateController performDelegateBlock:^(id<SRWebSocketDelegate> _Nullable delegate, SRDelegateAvailableMethods availableMethods) {
  547. if (availableMethods.didReceivePong) {
  548. [delegate webSocket:self didReceivePong:pongData];
  549. }
  550. }];
  551. }
  552. static inline BOOL closeCodeIsValid(int closeCode) {
  553. if (closeCode < 1000) {
  554. return NO;
  555. }
  556. if (closeCode >= 1000 && closeCode <= 1011) {
  557. if (closeCode == 1004 ||
  558. closeCode == 1005 ||
  559. closeCode == 1006) {
  560. return NO;
  561. }
  562. return YES;
  563. }
  564. if (closeCode >= 3000 && closeCode <= 3999) {
  565. return YES;
  566. }
  567. if (closeCode >= 4000 && closeCode <= 4999) {
  568. return YES;
  569. }
  570. return NO;
  571. }
  572. // Note from RFC:
  573. //
  574. // If there is a body, the first two
  575. // bytes of the body MUST be a 2-byte unsigned integer (in network byte
  576. // order) representing a status code with value /code/ defined in
  577. // Section 7.4. Following the 2-byte integer the body MAY contain UTF-8
  578. // encoded data with value /reason/, the interpretation of which is not
  579. // defined by this specification.
  580. - (void)handleCloseWithData:(NSData *)data;
  581. {
  582. size_t dataSize = data.length;
  583. __block uint16_t closeCode = 0;
  584. SRDebugLog(@"Received close frame");
  585. if (dataSize == 1) {
  586. // TODO handle error
  587. [self _closeWithProtocolError:@"Payload for close must be larger than 2 bytes"];
  588. return;
  589. } else if (dataSize >= 2) {
  590. [data getBytes:&closeCode length:sizeof(closeCode)];
  591. _closeCode = CFSwapInt16BigToHost(closeCode);
  592. if (!closeCodeIsValid(_closeCode)) {
  593. [self _closeWithProtocolError:[NSString stringWithFormat:@"Cannot have close code of %d", _closeCode]];
  594. return;
  595. }
  596. if (dataSize > 2) {
  597. _closeReason = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(2, dataSize - 2)] encoding:NSUTF8StringEncoding];
  598. if (!_closeReason) {
  599. [self _closeWithProtocolError:@"Close reason MUST be valid UTF-8"];
  600. return;
  601. }
  602. }
  603. } else {
  604. _closeCode = SRStatusNoStatusReceived;
  605. }
  606. [self assertOnWorkQueue];
  607. if (self.readyState == SR_OPEN) {
  608. [self closeWithCode:1000 reason:nil];
  609. }
  610. dispatch_async(_workQueue, ^{
  611. [self closeConnection];
  612. });
  613. }
  614. - (void)closeConnection;
  615. {
  616. [self assertOnWorkQueue];
  617. SRDebugLog(@"Trying to disconnect");
  618. _closeWhenFinishedWriting = YES;
  619. [self _pumpWriting];
  620. }
  621. - (void)_handleFrameWithData:(NSData *)frameData opCode:(SROpCode)opcode
  622. {
  623. // Check that the current data is valid UTF8
  624. BOOL isControlFrame = (opcode == SROpCodePing || opcode == SROpCodePong || opcode == SROpCodeConnectionClose);
  625. if (isControlFrame) {
  626. //frameData will be copied before passing to handlers
  627. //otherwise there can be misbehaviours when value at the pointer is changed
  628. frameData = [frameData copy];
  629. dispatch_async(_workQueue, ^{
  630. [self _readFrameContinue];
  631. });
  632. } else {
  633. [self _readFrameNew];
  634. }
  635. switch (opcode) {
  636. case SROpCodeTextFrame: {
  637. NSString *string = [[NSString alloc] initWithData:frameData encoding:NSUTF8StringEncoding];
  638. if (!string && frameData) {
  639. [self closeWithCode:SRStatusCodeInvalidUTF8 reason:@"Text frames must be valid UTF-8."];
  640. dispatch_async(_workQueue, ^{
  641. [self closeConnection];
  642. });
  643. return;
  644. }
  645. SRDebugLog(@"Received text message.");
  646. [self.delegateController performDelegateBlock:^(id<SRWebSocketDelegate> _Nullable delegate, SRDelegateAvailableMethods availableMethods) {
  647. // Don't convert into string - iff `delegate` tells us not to. Otherwise - create UTF8 string and handle that.
  648. if (availableMethods.shouldConvertTextFrameToString && ![delegate webSocketShouldConvertTextFrameToString:self]) {
  649. if (availableMethods.didReceiveMessage) {
  650. [delegate webSocket:self didReceiveMessage:frameData];
  651. }
  652. if (availableMethods.didReceiveMessageWithData) {
  653. [delegate webSocket:self didReceiveMessageWithData:frameData];
  654. }
  655. } else {
  656. if (availableMethods.didReceiveMessage) {
  657. [delegate webSocket:self didReceiveMessage:string];
  658. }
  659. if (availableMethods.didReceiveMessageWithString) {
  660. [delegate webSocket:self didReceiveMessageWithString:string];
  661. }
  662. }
  663. }];
  664. break;
  665. }
  666. case SROpCodeBinaryFrame: {
  667. SRDebugLog(@"Received data message.");
  668. [self.delegateController performDelegateBlock:^(id<SRWebSocketDelegate> _Nullable delegate, SRDelegateAvailableMethods availableMethods) {
  669. if (availableMethods.didReceiveMessage) {
  670. [delegate webSocket:self didReceiveMessage:frameData];
  671. }
  672. if (availableMethods.didReceiveMessageWithData) {
  673. [delegate webSocket:self didReceiveMessageWithData:frameData];
  674. }
  675. }];
  676. }
  677. break;
  678. case SROpCodeConnectionClose:
  679. [self handleCloseWithData:frameData];
  680. break;
  681. case SROpCodePing:
  682. [self _handlePingWithData:frameData];
  683. break;
  684. case SROpCodePong:
  685. [self handlePong:frameData];
  686. break;
  687. default:
  688. [self _closeWithProtocolError:[NSString stringWithFormat:@"Unknown opcode %ld", (long)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_CLOSED) {
  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. assert(frame_header.payload_length <= SIZE_T_MAX);
  725. [self _addConsumerWithDataLength:(size_t)frame_header.payload_length callback:^(SRWebSocket *sself, NSData *newData) {
  726. if (isControlFrame) {
  727. [sself _handleFrameWithData:newData opCode:frame_header.opcode];
  728. } else {
  729. if (frame_header.fin) {
  730. [sself _handleFrameWithData:sself->_currentFrameData opCode:frame_header.opcode];
  731. } else {
  732. // TODO add assert that opcode is not a control;
  733. [sself _readFrameContinue];
  734. }
  735. }
  736. } readToCurrentFrame:!isControlFrame unmaskBytes:frame_header.masked];
  737. }
  738. }
  739. /* From RFC:
  740. 0 1 2 3
  741. 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
  742. +-+-+-+-+-------+-+-------------+-------------------------------+
  743. |F|R|R|R| opcode|M| Payload len | Extended payload length |
  744. |I|S|S|S| (4) |A| (7) | (16/64) |
  745. |N|V|V|V| |S| | (if payload len==126/127) |
  746. | |1|2|3| |K| | |
  747. +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
  748. | Extended payload length continued, if payload len == 127 |
  749. + - - - - - - - - - - - - - - - +-------------------------------+
  750. | |Masking-key, if MASK set to 1 |
  751. +-------------------------------+-------------------------------+
  752. | Masking-key (continued) | Payload Data |
  753. +-------------------------------- - - - - - - - - - - - - - - - +
  754. : Payload Data continued ... :
  755. + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
  756. | Payload Data continued ... |
  757. +---------------------------------------------------------------+
  758. */
  759. static const uint8_t SRFinMask = 0x80;
  760. static const uint8_t SROpCodeMask = 0x0F;
  761. static const uint8_t SRRsvMask = 0x70;
  762. static const uint8_t SRMaskMask = 0x80;
  763. static const uint8_t SRPayloadLenMask = 0x7F;
  764. - (void)_readFrameContinue;
  765. {
  766. assert((_currentFrameCount == 0 && _currentFrameOpcode == 0) || (_currentFrameCount > 0 && _currentFrameOpcode > 0));
  767. [self _addConsumerWithDataLength:2 callback:^(SRWebSocket *sself, NSData *data) {
  768. __block frame_header header = {0};
  769. const uint8_t *headerBuffer = data.bytes;
  770. assert(data.length >= 2);
  771. if (headerBuffer[0] & SRRsvMask) {
  772. [sself _closeWithProtocolError:@"Server used RSV bits"];
  773. return;
  774. }
  775. uint8_t receivedOpcode = (SROpCodeMask & headerBuffer[0]);
  776. BOOL isControlFrame = (receivedOpcode == SROpCodePing || receivedOpcode == SROpCodePong || receivedOpcode == SROpCodeConnectionClose);
  777. if (!isControlFrame && receivedOpcode != 0 && sself->_currentFrameCount > 0) {
  778. [sself _closeWithProtocolError:@"all data frames after the initial data frame must have opcode 0"];
  779. return;
  780. }
  781. if (receivedOpcode == 0 && sself->_currentFrameCount == 0) {
  782. [sself _closeWithProtocolError:@"cannot continue a message"];
  783. return;
  784. }
  785. header.opcode = receivedOpcode == 0 ? sself->_currentFrameOpcode : receivedOpcode;
  786. header.fin = !!(SRFinMask & headerBuffer[0]);
  787. header.masked = !!(SRMaskMask & headerBuffer[1]);
  788. header.payload_length = SRPayloadLenMask & headerBuffer[1];
  789. headerBuffer = NULL;
  790. if (header.masked) {
  791. [sself _closeWithProtocolError:@"Client must receive unmasked data"];
  792. return;
  793. }
  794. size_t extra_bytes_needed = header.masked ? sizeof(_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. [sself _handleFrameHeader:header curData:sself->_currentFrameData];
  802. } else {
  803. [sself _addConsumerWithDataLength:extra_bytes_needed callback:^(SRWebSocket *eself, NSData *edata) {
  804. size_t mapped_size = edata.length;
  805. #pragma unused (mapped_size)
  806. const void *mapped_buffer = edata.bytes;
  807. size_t offset = 0;
  808. if (header.payload_length == 126) {
  809. assert(mapped_size >= sizeof(uint16_t));
  810. uint16_t payloadLength = 0;
  811. memcpy(&payloadLength, mapped_buffer, sizeof(uint16_t));
  812. payloadLength = CFSwapInt16BigToHost(payloadLength);
  813. header.payload_length = payloadLength;
  814. offset += sizeof(uint16_t);
  815. } else if (header.payload_length == 127) {
  816. assert(mapped_size >= sizeof(uint64_t));
  817. uint64_t payloadLength = 0;
  818. memcpy(&payloadLength, mapped_buffer, sizeof(uint64_t));
  819. payloadLength = CFSwapInt64BigToHost(payloadLength);
  820. header.payload_length = payloadLength;
  821. offset += sizeof(uint64_t);
  822. } else {
  823. assert(header.payload_length < 126 && header.payload_length >= 0);
  824. }
  825. if (header.masked) {
  826. assert(mapped_size >= sizeof(_currentReadMaskOffset) + offset);
  827. memcpy(eself->_currentReadMaskKey, ((uint8_t *)mapped_buffer) + offset, sizeof(eself->_currentReadMaskKey));
  828. }
  829. [eself _handleFrameHeader:header curData:eself->_currentFrameData];
  830. } readToCurrentFrame:NO unmaskBytes:NO];
  831. }
  832. } readToCurrentFrame:NO unmaskBytes:NO];
  833. }
  834. - (void)_readFrameNew;
  835. {
  836. dispatch_async(_workQueue, ^{
  837. // Don't reset the length, since Apple doesn't guarantee that this will free the memory (and in tests on
  838. // some platforms, it doesn't seem to, effectively causing a leak the size of the biggest frame so far).
  839. _currentFrameData = [[NSMutableData alloc] init];
  840. _currentFrameOpcode = 0;
  841. _currentFrameCount = 0;
  842. _readOpCount = 0;
  843. _currentStringScanPosition = 0;
  844. [self _readFrameContinue];
  845. });
  846. }
  847. - (void)_pumpWriting;
  848. {
  849. [self assertOnWorkQueue];
  850. NSUInteger dataLength = dispatch_data_get_size(_outputBuffer);
  851. if (dataLength - _outputBufferOffset > 0 && _outputStream.hasSpaceAvailable) {
  852. __block NSInteger bytesWritten = 0;
  853. __block BOOL streamFailed = NO;
  854. dispatch_data_t dataToSend = dispatch_data_create_subrange(_outputBuffer, _outputBufferOffset, dataLength - _outputBufferOffset);
  855. dispatch_data_apply(dataToSend, ^bool(dispatch_data_t region, size_t offset, const void *buffer, size_t size) {
  856. NSInteger sentLength = [_outputStream write:buffer maxLength:size];
  857. if (sentLength == -1) {
  858. streamFailed = YES;
  859. return false;
  860. }
  861. bytesWritten += sentLength;
  862. return (sentLength >= (NSInteger)size); // If we can't write all the data into the stream - bail-out early.
  863. });
  864. if (streamFailed) {
  865. NSInteger code = 2145;
  866. NSString *description = @"Error writing to stream.";
  867. NSError *streamError = _outputStream.streamError;
  868. NSError *error = streamError ? SRErrorWithCodeDescriptionUnderlyingError(code, description, streamError) : SRErrorWithCodeDescription(code, description);
  869. [self _failWithError:error];
  870. return;
  871. }
  872. _outputBufferOffset += bytesWritten;
  873. if (_outputBufferOffset > SRDefaultBufferSize() && _outputBufferOffset > dataLength / 2) {
  874. _outputBuffer = dispatch_data_create_subrange(_outputBuffer, _outputBufferOffset, dataLength - _outputBufferOffset);
  875. _outputBufferOffset = 0;
  876. }
  877. }
  878. if (_closeWhenFinishedWriting &&
  879. (dispatch_data_get_size(_outputBuffer) - _outputBufferOffset) == 0 &&
  880. (_inputStream.streamStatus != NSStreamStatusNotOpen &&
  881. _inputStream.streamStatus != NSStreamStatusClosed) &&
  882. !_sentClose) {
  883. _sentClose = YES;
  884. @synchronized(self) {
  885. [_outputStream close];
  886. [_inputStream close];
  887. for (NSArray *runLoop in [_scheduledRunloops copy]) {
  888. [self unscheduleFromRunLoop:[runLoop objectAtIndex:0] forMode:[runLoop objectAtIndex:1]];
  889. }
  890. }
  891. if (!_failed) {
  892. [self.delegateController performDelegateBlock:^(id<SRWebSocketDelegate> _Nullable delegate, SRDelegateAvailableMethods availableMethods) {
  893. if (availableMethods.didCloseWithCode) {
  894. [delegate webSocket:self didCloseWithCode:_closeCode reason:_closeReason wasClean:YES];
  895. }
  896. }];
  897. }
  898. [self _scheduleCleanup];
  899. }
  900. }
  901. - (void)_addConsumerWithScanner:(stream_scanner)consumer callback:(data_callback)callback;
  902. {
  903. [self assertOnWorkQueue];
  904. [self _addConsumerWithScanner:consumer callback:callback dataLength:0];
  905. }
  906. - (void)_addConsumerWithDataLength:(size_t)dataLength callback:(data_callback)callback readToCurrentFrame:(BOOL)readToCurrentFrame unmaskBytes:(BOOL)unmaskBytes;
  907. {
  908. [self assertOnWorkQueue];
  909. assert(dataLength);
  910. [_consumers addObject:[_consumerPool consumerWithScanner:nil handler:callback bytesNeeded:dataLength readToCurrentFrame:readToCurrentFrame unmaskBytes:unmaskBytes]];
  911. [self _pumpScanner];
  912. }
  913. - (void)_addConsumerWithScanner:(stream_scanner)consumer callback:(data_callback)callback dataLength:(size_t)dataLength;
  914. {
  915. [self assertOnWorkQueue];
  916. [_consumers addObject:[_consumerPool consumerWithScanner:consumer handler:callback bytesNeeded:dataLength readToCurrentFrame:NO unmaskBytes:NO]];
  917. [self _pumpScanner];
  918. }
  919. - (void)_scheduleCleanup
  920. {
  921. @synchronized(self) {
  922. if (_cleanupScheduled) {
  923. return;
  924. }
  925. _cleanupScheduled = YES;
  926. // _consumers retain SRWebSocket instance by block copy, if there are consumers here, clear them.
  927. [_consumers removeAllObjects];
  928. [_consumerPool clear];
  929. // Cancel the timer which retains SRWebSocket instance.
  930. // If we don't cancel the timer, the 'dealloc' method will be invoked only after the time (default: 60s) have come, which may cause memory increase.
  931. dispatch_async(dispatch_get_main_queue(), ^(){
  932. [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_onTimeout) object:nil];
  933. });
  934. // Cleanup NSStream delegate's in the same RunLoop used by the streams themselves:
  935. // This way we'll prevent race conditions between handleEvent and SRWebsocket's dealloc
  936. NSTimer *timer = [NSTimer timerWithTimeInterval:(0.0f) target:self selector:@selector(_cleanupSelfReference:) userInfo:nil repeats:NO];
  937. [[NSRunLoop SR_networkRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
  938. }
  939. }
  940. - (void)_cleanupSelfReference:(NSTimer *)timer
  941. {
  942. @synchronized(self) {
  943. // Nuke NSStream delegate's
  944. _inputStream.delegate = nil;
  945. _outputStream.delegate = nil;
  946. // Remove the streams, right now, from the networkRunLoop
  947. [_inputStream close];
  948. [_outputStream close];
  949. }
  950. // Cleanup selfRetain in the same GCD queue as usual
  951. dispatch_async(_workQueue, ^{
  952. _selfRetain = nil;
  953. });
  954. }
  955. static const char CRLFCRLFBytes[] = {'\r', '\n', '\r', '\n'};
  956. - (void)_readUntilHeaderCompleteWithCallback:(data_callback)dataHandler;
  957. {
  958. [self _readUntilBytes:CRLFCRLFBytes length:sizeof(CRLFCRLFBytes) callback:dataHandler];
  959. }
  960. - (void)_readUntilBytes:(const void *)bytes length:(size_t)length callback:(data_callback)dataHandler;
  961. {
  962. // TODO optimize so this can continue from where we last searched
  963. stream_scanner consumer = ^size_t(NSData *data) {
  964. __block size_t found_size = 0;
  965. __block size_t match_count = 0;
  966. size_t size = data.length;
  967. const unsigned char *buffer = data.bytes;
  968. for (size_t i = 0; i < size; i++ ) {
  969. if (((const unsigned char *)buffer)[i] == ((const unsigned char *)bytes)[match_count]) {
  970. match_count += 1;
  971. if (match_count == length) {
  972. found_size = i + 1;
  973. break;
  974. }
  975. } else {
  976. match_count = 0;
  977. }
  978. }
  979. return found_size;
  980. };
  981. [self _addConsumerWithScanner:consumer callback:dataHandler];
  982. }
  983. // Returns true if did work
  984. - (BOOL)_innerPumpScanner {
  985. BOOL didWork = NO;
  986. if (self.readyState >= SR_CLOSED) {
  987. return didWork;
  988. }
  989. size_t readBufferSize = dispatch_data_get_size(_readBuffer);
  990. if (!_consumers.count) {
  991. return didWork;
  992. }
  993. size_t curSize = readBufferSize - _readBufferOffset;
  994. if (!curSize) {
  995. return didWork;
  996. }
  997. SRIOConsumer *consumer = [_consumers objectAtIndex:0];
  998. size_t bytesNeeded = consumer.bytesNeeded;
  999. size_t foundSize = 0;
  1000. if (consumer.consumer) {
  1001. NSData *subdata = (NSData *)dispatch_data_create_subrange(_readBuffer, _readBufferOffset, readBufferSize - _readBufferOffset);
  1002. foundSize = consumer.consumer(subdata);
  1003. } else {
  1004. assert(consumer.bytesNeeded);
  1005. if (curSize >= bytesNeeded) {
  1006. foundSize = bytesNeeded;
  1007. } else if (consumer.readToCurrentFrame) {
  1008. foundSize = curSize;
  1009. }
  1010. }
  1011. if (consumer.readToCurrentFrame || foundSize) {
  1012. dispatch_data_t slice = dispatch_data_create_subrange(_readBuffer, _readBufferOffset, foundSize);
  1013. _readBufferOffset += foundSize;
  1014. if (_readBufferOffset > SRDefaultBufferSize() && _readBufferOffset > readBufferSize / 2) {
  1015. _readBuffer = dispatch_data_create_subrange(_readBuffer, _readBufferOffset, readBufferSize - _readBufferOffset);
  1016. _readBufferOffset = 0;
  1017. }
  1018. if (consumer.unmaskBytes) {
  1019. __block NSMutableData *mutableSlice = [slice mutableCopy];
  1020. NSUInteger len = mutableSlice.length;
  1021. uint8_t *bytes = mutableSlice.mutableBytes;
  1022. for (NSUInteger i = 0; i < len; i++) {
  1023. bytes[i] = bytes[i] ^ _currentReadMaskKey[_currentReadMaskOffset % sizeof(_currentReadMaskKey)];
  1024. _currentReadMaskOffset += 1;
  1025. }
  1026. slice = dispatch_data_create(bytes, len, nil, ^{
  1027. mutableSlice = nil;
  1028. });
  1029. }
  1030. if (consumer.readToCurrentFrame) {
  1031. dispatch_data_apply(slice, ^bool(dispatch_data_t region, size_t offset, const void *buffer, size_t size) {
  1032. [_currentFrameData appendBytes:buffer length:size];
  1033. return true;
  1034. });
  1035. _readOpCount += 1;
  1036. if (_currentFrameOpcode == SROpCodeTextFrame) {
  1037. // Validate UTF8 stuff.
  1038. size_t currentDataSize = _currentFrameData.length;
  1039. if (_currentFrameOpcode == SROpCodeTextFrame && currentDataSize > 0) {
  1040. // TODO: Optimize the crap out of this. Don't really have to copy all the data each time
  1041. size_t scanSize = currentDataSize - _currentStringScanPosition;
  1042. NSData *scan_data = [_currentFrameData subdataWithRange:NSMakeRange(_currentStringScanPosition, scanSize)];
  1043. int32_t valid_utf8_size = validate_dispatch_data_partial_string(scan_data);
  1044. if (valid_utf8_size == -1) {
  1045. [self closeWithCode:SRStatusCodeInvalidUTF8 reason:@"Text frames must be valid UTF-8"];
  1046. dispatch_async(_workQueue, ^{
  1047. [self closeConnection];
  1048. });
  1049. return didWork;
  1050. } else {
  1051. _currentStringScanPosition += valid_utf8_size;
  1052. }
  1053. }
  1054. }
  1055. consumer.bytesNeeded -= foundSize;
  1056. if (consumer.bytesNeeded == 0) {
  1057. [_consumers removeObjectAtIndex:0];
  1058. consumer.handler(self, nil);
  1059. [_consumerPool returnConsumer:consumer];
  1060. didWork = YES;
  1061. }
  1062. } else if (foundSize) {
  1063. [_consumers removeObjectAtIndex:0];
  1064. consumer.handler(self, (NSData *)slice);
  1065. [_consumerPool returnConsumer:consumer];
  1066. didWork = YES;
  1067. }
  1068. }
  1069. return didWork;
  1070. }
  1071. -(void)_pumpScanner;
  1072. {
  1073. [self assertOnWorkQueue];
  1074. if (!_isPumping) {
  1075. _isPumping = YES;
  1076. } else {
  1077. return;
  1078. }
  1079. while ([self _innerPumpScanner]) {
  1080. }
  1081. _isPumping = NO;
  1082. }
  1083. //#define NOMASK
  1084. static const size_t SRFrameHeaderOverhead = 32;
  1085. - (void)_sendFrameWithOpcode:(SROpCode)opCode data:(NSData *)data
  1086. {
  1087. [self assertOnWorkQueue];
  1088. if (!data) {
  1089. return;
  1090. }
  1091. size_t payloadLength = data.length;
  1092. NSMutableData *frameData = [[NSMutableData alloc] initWithLength:payloadLength + SRFrameHeaderOverhead];
  1093. if (!frameData) {
  1094. [self closeWithCode:SRStatusCodeMessageTooBig reason:@"Message too big"];
  1095. return;
  1096. }
  1097. uint8_t *frameBuffer = (uint8_t *)frameData.mutableBytes;
  1098. // set fin
  1099. frameBuffer[0] = SRFinMask | opCode;
  1100. // set the mask and header
  1101. frameBuffer[1] |= SRMaskMask;
  1102. size_t frameBufferSize = 2;
  1103. if (payloadLength < 126) {
  1104. frameBuffer[1] |= payloadLength;
  1105. } else {
  1106. uint64_t declaredPayloadLength = 0;
  1107. size_t declaredPayloadLengthSize = 0;
  1108. if (payloadLength <= UINT16_MAX) {
  1109. frameBuffer[1] |= 126;
  1110. declaredPayloadLength = CFSwapInt16BigToHost((uint16_t)payloadLength);
  1111. declaredPayloadLengthSize = sizeof(uint16_t);
  1112. } else {
  1113. frameBuffer[1] |= 127;
  1114. declaredPayloadLength = CFSwapInt64BigToHost((uint64_t)payloadLength);
  1115. declaredPayloadLengthSize = sizeof(uint64_t);
  1116. }
  1117. memcpy((frameBuffer + frameBufferSize), &declaredPayloadLength, declaredPayloadLengthSize);
  1118. frameBufferSize += declaredPayloadLengthSize;
  1119. }
  1120. const uint8_t *unmaskedPayloadBuffer = (uint8_t *)data.bytes;
  1121. uint8_t *maskKey = frameBuffer + frameBufferSize;
  1122. size_t randomBytesSize = sizeof(uint32_t);
  1123. int result = SecRandomCopyBytes(kSecRandomDefault, randomBytesSize, maskKey);
  1124. if (result != 0) {
  1125. //TODO: (nlutsenko) Check if there was an error.
  1126. }
  1127. frameBufferSize += randomBytesSize;
  1128. // Copy and unmask the buffer
  1129. uint8_t *frameBufferPayloadPointer = frameBuffer + frameBufferSize;
  1130. memcpy(frameBufferPayloadPointer, unmaskedPayloadBuffer, payloadLength);
  1131. SRMaskBytesSIMD(frameBufferPayloadPointer, payloadLength, maskKey);
  1132. frameBufferSize += payloadLength;
  1133. assert(frameBufferSize <= frameData.length);
  1134. frameData.length = frameBufferSize;
  1135. [self _writeData:frameData];
  1136. }
  1137. - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
  1138. {
  1139. __weak __typeof(self) wself = self;
  1140. if (_requestRequiresSSL && !_streamSecurityValidated &&
  1141. (eventCode == NSStreamEventHasBytesAvailable || eventCode == NSStreamEventHasSpaceAvailable)) {
  1142. SecTrustRef trust = (__bridge SecTrustRef)[aStream propertyForKey:(__bridge id)kCFStreamPropertySSLPeerTrust];
  1143. if (trust) {
  1144. _streamSecurityValidated = [_securityPolicy evaluateServerTrust:trust forDomain:_urlRequest.URL.host];
  1145. }
  1146. if (!_streamSecurityValidated) {
  1147. dispatch_async(_workQueue, ^{
  1148. NSError *error = SRErrorWithDomainCodeDescription(NSURLErrorDomain,
  1149. NSURLErrorClientCertificateRejected,
  1150. @"Invalid server certificate.");
  1151. [wself _failWithError:error];
  1152. });
  1153. return;
  1154. }
  1155. dispatch_async(_workQueue, ^{
  1156. [self didConnect];
  1157. });
  1158. }
  1159. dispatch_async(_workQueue, ^{
  1160. [wself safeHandleEvent:eventCode stream:aStream];
  1161. });
  1162. }
  1163. - (void)safeHandleEvent:(NSStreamEvent)eventCode stream:(NSStream *)aStream
  1164. {
  1165. switch (eventCode) {
  1166. case NSStreamEventOpenCompleted: {
  1167. SRDebugLog(@"NSStreamEventOpenCompleted %@", aStream);
  1168. if (self.readyState >= SR_CLOSING) {
  1169. return;
  1170. }
  1171. assert(_readBuffer);
  1172. if (!_requestRequiresSSL && self.readyState == SR_CONNECTING && aStream == _inputStream) {
  1173. [self didConnect];
  1174. }
  1175. [self _pumpWriting];
  1176. [self _pumpScanner];
  1177. break;
  1178. }
  1179. case NSStreamEventErrorOccurred: {
  1180. SRDebugLog(@"NSStreamEventErrorOccurred %@ %@", aStream, [[aStream streamError] copy]);
  1181. /// TODO specify error better!
  1182. [self _failWithError:aStream.streamError];
  1183. _readBufferOffset = 0;
  1184. _readBuffer = dispatch_data_empty;
  1185. break;
  1186. }
  1187. case NSStreamEventEndEncountered: {
  1188. [self _pumpScanner];
  1189. SRDebugLog(@"NSStreamEventEndEncountered %@", aStream);
  1190. if (aStream.streamError) {
  1191. [self _failWithError:aStream.streamError];
  1192. } else {
  1193. dispatch_async(_workQueue, ^{
  1194. if (self.readyState != SR_CLOSED) {
  1195. self.readyState = SR_CLOSED;
  1196. [self _scheduleCleanup];
  1197. }
  1198. if (!_sentClose && !_failed) {
  1199. _sentClose = YES;
  1200. // If we get closed in this state it's probably not clean because we should be sending this when we send messages
  1201. [self.delegateController performDelegateBlock:^(id<SRWebSocketDelegate> _Nullable delegate, SRDelegateAvailableMethods availableMethods) {
  1202. if (availableMethods.didCloseWithCode) {
  1203. [delegate webSocket:self
  1204. didCloseWithCode:SRStatusCodeGoingAway
  1205. reason:@"Stream end encountered"
  1206. wasClean:NO];
  1207. }
  1208. }];
  1209. }
  1210. });
  1211. }
  1212. break;
  1213. }
  1214. case NSStreamEventHasBytesAvailable: {
  1215. SRDebugLog(@"NSStreamEventHasBytesAvailable %@", aStream);
  1216. uint8_t buffer[SRDefaultBufferSize()];
  1217. while (_inputStream.hasBytesAvailable) {
  1218. NSInteger bytesRead = [_inputStream read:buffer maxLength:SRDefaultBufferSize()];
  1219. if (bytesRead > 0) {
  1220. dispatch_data_t data = dispatch_data_create(buffer, bytesRead, nil, DISPATCH_DATA_DESTRUCTOR_DEFAULT);
  1221. if (!data) {
  1222. NSError *error = SRErrorWithCodeDescription(SRStatusCodeMessageTooBig,
  1223. @"Unable to allocate memory to read from socket.");
  1224. [self _failWithError:error];
  1225. return;
  1226. }
  1227. _readBuffer = dispatch_data_create_concat(_readBuffer, data);
  1228. } else if (bytesRead == -1) {
  1229. [self _failWithError:_inputStream.streamError];
  1230. }
  1231. }
  1232. [self _pumpScanner];
  1233. break;
  1234. }
  1235. case NSStreamEventHasSpaceAvailable: {
  1236. SRDebugLog(@"NSStreamEventHasSpaceAvailable %@", aStream);
  1237. [self _pumpWriting];
  1238. break;
  1239. }
  1240. case NSStreamEventNone:
  1241. SRDebugLog(@"(default) %@", aStream);
  1242. break;
  1243. }
  1244. }
  1245. ///--------------------------------------
  1246. #pragma mark - Delegate
  1247. ///--------------------------------------
  1248. - (id<SRWebSocketDelegate> _Nullable)delegate
  1249. {
  1250. return self.delegateController.delegate;
  1251. }
  1252. - (void)setDelegate:(id<SRWebSocketDelegate> _Nullable)delegate
  1253. {
  1254. self.delegateController.delegate = delegate;
  1255. }
  1256. - (void)setDelegateDispatchQueue:(dispatch_queue_t _Nullable)queue
  1257. {
  1258. self.delegateController.dispatchQueue = queue;
  1259. }
  1260. - (dispatch_queue_t _Nullable)delegateDispatchQueue
  1261. {
  1262. return self.delegateController.dispatchQueue;
  1263. }
  1264. - (void)setDelegateOperationQueue:(NSOperationQueue *_Nullable)queue
  1265. {
  1266. self.delegateController.operationQueue = queue;
  1267. }
  1268. - (NSOperationQueue *_Nullable)delegateOperationQueue
  1269. {
  1270. return self.delegateController.operationQueue;
  1271. }
  1272. @end
  1273. #ifdef HAS_ICU
  1274. static inline int32_t validate_dispatch_data_partial_string(NSData *data) {
  1275. if ([data length] > INT32_MAX) {
  1276. // INT32_MAX is the limit so long as this Framework is using 32 bit ints everywhere.
  1277. return -1;
  1278. }
  1279. int32_t size = (int32_t)[data length];
  1280. const void * contents = [data bytes];
  1281. const uint8_t *str = (const uint8_t *)contents;
  1282. UChar32 codepoint = 1;
  1283. int32_t offset = 0;
  1284. int32_t lastOffset = 0;
  1285. while(offset < size && codepoint > 0) {
  1286. lastOffset = offset;
  1287. U8_NEXT(str, offset, size, codepoint);
  1288. }
  1289. if (codepoint == -1) {
  1290. // Check to see if the last byte is valid or whether it was just continuing
  1291. if (!U8_IS_LEAD(str[lastOffset]) || U8_COUNT_TRAIL_BYTES(str[lastOffset]) + lastOffset < (int32_t)size) {
  1292. size = -1;
  1293. } else {
  1294. uint8_t leadByte = str[lastOffset];
  1295. U8_MASK_LEAD_BYTE(leadByte, U8_COUNT_TRAIL_BYTES(leadByte));
  1296. for (int i = lastOffset + 1; i < offset; i++) {
  1297. if (U8_IS_SINGLE(str[i]) || U8_IS_LEAD(str[i]) || !U8_IS_TRAIL(str[i])) {
  1298. size = -1;
  1299. }
  1300. }
  1301. if (size != -1) {
  1302. size = lastOffset;
  1303. }
  1304. }
  1305. }
  1306. if (size != -1 && ![[NSString alloc] initWithBytesNoCopy:(char *)[data bytes] length:size encoding:NSUTF8StringEncoding freeWhenDone:NO]) {
  1307. size = -1;
  1308. }
  1309. return size;
  1310. }
  1311. #else
  1312. // This is a hack, and probably not optimal
  1313. static inline int32_t validate_dispatch_data_partial_string(NSData *data) {
  1314. static const int maxCodepointSize = 3;
  1315. for (int i = 0; i < maxCodepointSize; i++) {
  1316. NSString *str = [[NSString alloc] initWithBytesNoCopy:(char *)data.bytes length:data.length - i encoding:NSUTF8StringEncoding freeWhenDone:NO];
  1317. if (str) {
  1318. return (int32_t)data.length - i;
  1319. }
  1320. }
  1321. return -1;
  1322. }
  1323. #endif