SRWebSocket.m 55 KB

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