SRWebSocket.m 54 KB

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