SRWebSocket.m 54 KB

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