SRWebSocket.m 55 KB

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