SRWebSocket.m 54 KB

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