-
Notifications
You must be signed in to change notification settings - Fork 0
/
SRWebSocket.m
1755 lines (1363 loc) · 55 KB
/
SRWebSocket.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright 2012 Square Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "SRWebSocket.h"
#if TARGET_OS_IPHONE
#define HAS_ICU
#endif
#ifdef HAS_ICU
#import <unicode/utf8.h>
#endif
#if TARGET_OS_IPHONE
#import <Endian.h>
#else
#import <CoreServices/CoreServices.h>
#endif
#import <CommonCrypto/CommonDigest.h>
#import <Security/SecRandom.h>
#if OS_OBJECT_USE_OBJC_RETAIN_RELEASE
#define sr_dispatch_retain(x)
#define sr_dispatch_release(x)
#define maybe_bridge(x) ((__bridge void *) x)
#else
#define sr_dispatch_retain(x) dispatch_retain(x)
#define sr_dispatch_release(x) dispatch_release(x)
#define maybe_bridge(x) (x)
#endif
#if !__has_feature(objc_arc)
#error SocketRocket must be compiled with ARC enabled
#endif
typedef enum {
SROpCodeTextFrame = 0x1,
SROpCodeBinaryFrame = 0x2,
// 3-7 reserved.
SROpCodeConnectionClose = 0x8,
SROpCodePing = 0x9,
SROpCodePong = 0xA,
// B-F reserved.
} SROpCode;
typedef struct {
BOOL fin;
// BOOL rsv1;
// BOOL rsv2;
// BOOL rsv3;
uint8_t opcode;
BOOL masked;
uint64_t payload_length;
} frame_header;
static NSString *const SRWebSocketAppendToSecKeyString = @"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
static inline int32_t validate_dispatch_data_partial_string(NSData *data);
static inline void SRFastLog(NSString *format, ...);
@interface NSData (SRWebSocket)
- (NSString *)stringBySHA1ThenBase64Encoding;
@end
@interface NSString (SRWebSocket)
- (NSString *)stringBySHA1ThenBase64Encoding;
@end
@interface NSURL (SRWebSocket)
// The origin isn't really applicable for a native application.
// So instead, just map ws -> http and wss -> https.
- (NSString *)SR_origin;
@end
@interface _SRRunLoopThread : NSThread
@property (nonatomic, readonly) NSRunLoop *runLoop;
@end
static NSString *newSHA1String(const char *bytes, size_t length) {
uint8_t md[CC_SHA1_DIGEST_LENGTH];
assert(length >= 0);
assert(length <= UINT32_MAX);
CC_SHA1(bytes, (CC_LONG)length, md);
NSData *data = [NSData dataWithBytes:md length:CC_SHA1_DIGEST_LENGTH];
if ([data respondsToSelector:@selector(base64EncodedStringWithOptions:)]) {
return [data base64EncodedStringWithOptions:0];
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
return [data base64Encoding];
#pragma clang diagnostic pop
}
@implementation NSData (SRWebSocket)
- (NSString *)stringBySHA1ThenBase64Encoding;
{
return newSHA1String(self.bytes, self.length);
}
@end
@implementation NSString (SRWebSocket)
- (NSString *)stringBySHA1ThenBase64Encoding;
{
return newSHA1String(self.UTF8String, self.length);
}
@end
NSString *const SRWebSocketErrorDomain = @"SRWebSocketErrorDomain";
NSString *const SRHTTPResponseErrorKey = @"HTTPResponseStatusCode";
// Returns number of bytes consumed. Returning 0 means you didn't match.
// Sends bytes to callback handler;
typedef size_t (^stream_scanner)(NSData *collected_data);
typedef void (^data_callback)(SRWebSocket *webSocket, NSData *data);
@interface SRIOConsumer : NSObject {
stream_scanner _scanner;
data_callback _handler;
size_t _bytesNeeded;
BOOL _readToCurrentFrame;
BOOL _unmaskBytes;
}
@property (nonatomic, copy, readonly) stream_scanner consumer;
@property (nonatomic, copy, readonly) data_callback handler;
@property (nonatomic, assign) size_t bytesNeeded;
@property (nonatomic, assign, readonly) BOOL readToCurrentFrame;
@property (nonatomic, assign, readonly) BOOL unmaskBytes;
@end
// This class is not thread-safe, and is expected to always be run on the same queue.
@interface SRIOConsumerPool : NSObject
- (id)initWithBufferCapacity:(NSUInteger)poolSize;
- (SRIOConsumer *)consumerWithScanner:(stream_scanner)scanner handler:(data_callback)handler bytesNeeded:(size_t)bytesNeeded readToCurrentFrame:(BOOL)readToCurrentFrame unmaskBytes:(BOOL)unmaskBytes;
- (void)returnConsumer:(SRIOConsumer *)consumer;
@end
@interface SRWebSocket () <NSStreamDelegate>
@property (nonatomic) SRReadyState readyState;
@property (nonatomic) NSOperationQueue *delegateOperationQueue;
@property (nonatomic) dispatch_queue_t delegateDispatchQueue;
@end
@implementation SRWebSocket {
NSInteger _webSocketVersion;
NSOperationQueue *_delegateOperationQueue;
dispatch_queue_t _delegateDispatchQueue;
dispatch_queue_t _workQueue;
NSMutableArray *_consumers;
NSInputStream *_inputStream;
NSOutputStream *_outputStream;
NSMutableData *_readBuffer;
NSUInteger _readBufferOffset;
NSMutableData *_outputBuffer;
NSUInteger _outputBufferOffset;
uint8_t _currentFrameOpcode;
size_t _currentFrameCount;
size_t _readOpCount;
uint32_t _currentStringScanPosition;
NSMutableData *_currentFrameData;
NSString *_closeReason;
NSString *_secKey;
BOOL _pinnedCertFound;
uint8_t _currentReadMaskKey[4];
size_t _currentReadMaskOffset;
BOOL _consumerStopped;
BOOL _closeWhenFinishedWriting;
BOOL _failed;
BOOL _secure;
NSURLRequest *_urlRequest;
CFHTTPMessageRef _receivedHTTPHeaders;
BOOL _sentClose;
BOOL _didFail;
int _closeCode;
BOOL _isPumping;
NSMutableSet *_scheduledRunloops;
// We use this to retain ourselves.
__strong SRWebSocket *_selfRetain;
NSArray *_requestedProtocols;
SRIOConsumerPool *_consumerPool;
}
@synthesize delegate = _delegate;
@synthesize url = _url;
@synthesize readyState = _readyState;
@synthesize protocol = _protocol;
static __strong NSData *CRLFCRLF;
+ (void)initialize;
{
CRLFCRLF = [[NSData alloc] initWithBytes:"\r\n\r\n" length:4];
}
- (id)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray *)protocols;
{
self = [super init];
if (self) {
assert(request.URL);
_url = request.URL;
_urlRequest = request;
_requestedProtocols = [protocols copy];
[self _SR_commonInit];
}
return self;
}
- (id)initWithURLRequest:(NSURLRequest *)request;
{
return [self initWithURLRequest:request protocols:nil];
}
- (id)initWithURL:(NSURL *)url;
{
return [self initWithURL:url protocols:nil];
}
- (id)initWithURL:(NSURL *)url protocols:(NSArray *)protocols;
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
return [self initWithURLRequest:request protocols:protocols];
}
- (void)_SR_commonInit;
{
NSString *scheme = _url.scheme.lowercaseString;
assert([scheme isEqualToString:@"ws"] || [scheme isEqualToString:@"http"] || [scheme isEqualToString:@"wss"] || [scheme isEqualToString:@"https"]);
if ([scheme isEqualToString:@"wss"] || [scheme isEqualToString:@"https"]) {
_secure = YES;
}
_readyState = SR_CONNECTING;
_consumerStopped = YES;
_webSocketVersion = 13;
_workQueue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
// Going to set a specific on the queue so we can validate we're on the work queue
dispatch_queue_set_specific(_workQueue, (__bridge void *)self, maybe_bridge(_workQueue), NULL);
_delegateDispatchQueue = dispatch_get_main_queue();
sr_dispatch_retain(_delegateDispatchQueue);
_readBuffer = [[NSMutableData alloc] init];
_outputBuffer = [[NSMutableData alloc] init];
_currentFrameData = [[NSMutableData alloc] init];
_consumers = [[NSMutableArray alloc] init];
_consumerPool = [[SRIOConsumerPool alloc] init];
_scheduledRunloops = [[NSMutableSet alloc] init];
[self _initializeStreams];
// default handlers
}
- (void)assertOnWorkQueue;
{
assert(dispatch_get_specific((__bridge void *)self) == maybe_bridge(_workQueue));
}
- (void)dealloc
{
_inputStream.delegate = nil;
_outputStream.delegate = nil;
[_inputStream close];
[_outputStream close];
sr_dispatch_release(_workQueue);
_workQueue = NULL;
if (_receivedHTTPHeaders) {
CFRelease(_receivedHTTPHeaders);
_receivedHTTPHeaders = NULL;
}
if (_delegateDispatchQueue) {
sr_dispatch_release(_delegateDispatchQueue);
_delegateDispatchQueue = NULL;
}
}
#ifndef NDEBUG
- (void)setReadyState:(SRReadyState)aReadyState;
{
[self willChangeValueForKey:@"readyState"];
assert(aReadyState > _readyState);
_readyState = aReadyState;
[self didChangeValueForKey:@"readyState"];
}
#endif
- (void)open;
{
assert(_url);
NSAssert(_readyState == SR_CONNECTING, @"Cannot call -(void)open on SRWebSocket more than once");
_selfRetain = self;
[self _openConnection];
}
// Calls block on delegate queue
- (void)_performDelegateBlock:(dispatch_block_t)block;
{
if (_delegateOperationQueue) {
[_delegateOperationQueue addOperationWithBlock:block];
} else {
assert(_delegateDispatchQueue);
dispatch_async(_delegateDispatchQueue, block);
}
}
- (void)setDelegateDispatchQueue:(dispatch_queue_t)queue;
{
if (queue) {
sr_dispatch_retain(queue);
}
if (_delegateDispatchQueue) {
sr_dispatch_release(_delegateDispatchQueue);
}
_delegateDispatchQueue = queue;
}
- (BOOL)_checkHandshake:(CFHTTPMessageRef)httpMessage;
{
NSString *acceptHeader = CFBridgingRelease(CFHTTPMessageCopyHeaderFieldValue(httpMessage, CFSTR("Sec-WebSocket-Accept")));
if (acceptHeader == nil) {
return NO;
}
NSString *concattedString = [_secKey stringByAppendingString:SRWebSocketAppendToSecKeyString];
NSString *expectedAccept = [concattedString stringBySHA1ThenBase64Encoding];
return [acceptHeader isEqualToString:expectedAccept];
}
- (void)_HTTPHeadersDidFinish;
{
NSInteger responseCode = CFHTTPMessageGetResponseStatusCode(_receivedHTTPHeaders);
if (responseCode >= 400) {
SRFastLog(@"Request failed with response code %d", responseCode);
[self _failWithError:[NSError errorWithDomain:SRWebSocketErrorDomain code:2132 userInfo:@{NSLocalizedDescriptionKey:[NSString stringWithFormat:@"received bad response code from server %ld", (long)responseCode], SRHTTPResponseErrorKey:@(responseCode)}]];
return;
}
if(![self _checkHandshake:_receivedHTTPHeaders]) {
[self _failWithError:[NSError errorWithDomain:SRWebSocketErrorDomain code:2133 userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Invalid Sec-WebSocket-Accept response"] forKey:NSLocalizedDescriptionKey]]];
return;
}
NSString *negotiatedProtocol = CFBridgingRelease(CFHTTPMessageCopyHeaderFieldValue(_receivedHTTPHeaders, CFSTR("Sec-WebSocket-Protocol")));
if (negotiatedProtocol) {
// Make sure we requested the protocol
if ([_requestedProtocols indexOfObject:negotiatedProtocol] == NSNotFound) {
[self _failWithError:[NSError errorWithDomain:SRWebSocketErrorDomain code:2133 userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Server specified Sec-WebSocket-Protocol that wasn't requested"] forKey:NSLocalizedDescriptionKey]]];
return;
}
_protocol = negotiatedProtocol;
}
self.readyState = SR_OPEN;
if (!_didFail) {
[self _readFrameNew];
}
[self _performDelegateBlock:^{
if ([self.delegate respondsToSelector:@selector(webSocketDidOpen:)]) {
[self.delegate webSocketDidOpen:self];
};
}];
}
- (void)_readHTTPHeader;
{
if (_receivedHTTPHeaders == NULL) {
_receivedHTTPHeaders = CFHTTPMessageCreateEmpty(NULL, NO);
}
[self _readUntilHeaderCompleteWithCallback:^(SRWebSocket *self, NSData *data) {
CFHTTPMessageAppendBytes(_receivedHTTPHeaders, (const UInt8 *)data.bytes, data.length);
if (CFHTTPMessageIsHeaderComplete(_receivedHTTPHeaders)) {
SRFastLog(@"Finished reading headers %@", CFBridgingRelease(CFHTTPMessageCopyAllHeaderFields(_receivedHTTPHeaders)));
[self _HTTPHeadersDidFinish];
} else {
[self _readHTTPHeader];
}
}];
}
- (void)didConnect
{
SRFastLog(@"Connected");
CFHTTPMessageRef request = CFHTTPMessageCreateRequest(NULL, CFSTR("GET"), (__bridge CFURLRef)_url, kCFHTTPVersion1_1);
// Set host first so it defaults
CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Host"), (__bridge CFStringRef)(_url.port ? [NSString stringWithFormat:@"%@:%@", _url.host, _url.port] : _url.host));
NSMutableData *keyBytes = [[NSMutableData alloc] initWithLength:16];
SecRandomCopyBytes(kSecRandomDefault, keyBytes.length, keyBytes.mutableBytes);
if ([keyBytes respondsToSelector:@selector(base64EncodedStringWithOptions:)]) {
_secKey = [keyBytes base64EncodedStringWithOptions:0];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
_secKey = [keyBytes base64Encoding];
#pragma clang diagnostic pop
}
assert([_secKey length] == 24);
CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Upgrade"), CFSTR("websocket"));
CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Connection"), CFSTR("Upgrade"));
CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Sec-WebSocket-Key"), (__bridge CFStringRef)_secKey);
CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Sec-WebSocket-Version"), (__bridge CFStringRef)[NSString stringWithFormat:@"%ld", (long)_webSocketVersion]);
CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Origin"), (__bridge CFStringRef)_url.SR_origin);
if (_requestedProtocols) {
CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Sec-WebSocket-Protocol"), (__bridge CFStringRef)[_requestedProtocols componentsJoinedByString:@", "]);
}
[_urlRequest.allHTTPHeaderFields enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
CFHTTPMessageSetHeaderFieldValue(request, (__bridge CFStringRef)key, (__bridge CFStringRef)obj);
}];
NSData *message = CFBridgingRelease(CFHTTPMessageCopySerializedMessage(request));
CFRelease(request);
[self _writeData:message];
[self _readHTTPHeader];
}
- (void)_initializeStreams;
{
assert(_url.port.unsignedIntValue <= UINT32_MAX);
uint32_t port = _url.port.unsignedIntValue;
if (port == 0) {
if (!_secure) {
port = 80;
} else {
port = 443;
}
}
NSString *host = _url.host;
CFReadStreamRef readStream = NULL;
CFWriteStreamRef writeStream = NULL;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, port, &readStream, &writeStream);
_outputStream = CFBridgingRelease(writeStream);
_inputStream = CFBridgingRelease(readStream);
if (_secure) {
NSMutableDictionary *SSLOptions = [[NSMutableDictionary alloc] init];
[_outputStream setProperty:(__bridge id)kCFStreamSocketSecurityLevelNegotiatedSSL forKey:(__bridge id)kCFStreamPropertySocketSecurityLevel];
// If we're using pinned certs, don't validate the certificate chain
if ([_urlRequest SR_SSLPinnedCertificates].count) {
[SSLOptions setValue:[NSNumber numberWithBool:NO] forKey:(__bridge id)kCFStreamSSLValidatesCertificateChain];
}
#if DEBUG
[SSLOptions setValue:[NSNumber numberWithBool:NO] forKey:(__bridge id)kCFStreamSSLValidatesCertificateChain];
NSLog(@"SocketRocket: In debug mode. Allowing connection to any root cert");
#endif
[_outputStream setProperty:SSLOptions
forKey:(__bridge id)kCFStreamPropertySSLSettings];
}
_inputStream.delegate = self;
_outputStream.delegate = self;
}
- (void)_openConnection;
{
if (!_scheduledRunloops.count) {
[self scheduleInRunLoop:[NSRunLoop SR_networkRunLoop] forMode:NSDefaultRunLoopMode];
}
[_outputStream open];
[_inputStream open];
}
- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
{
[_outputStream scheduleInRunLoop:aRunLoop forMode:mode];
[_inputStream scheduleInRunLoop:aRunLoop forMode:mode];
[_scheduledRunloops addObject:@[aRunLoop, mode]];
}
- (void)unscheduleFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
{
[_outputStream removeFromRunLoop:aRunLoop forMode:mode];
[_inputStream removeFromRunLoop:aRunLoop forMode:mode];
[_scheduledRunloops removeObject:@[aRunLoop, mode]];
}
- (void)close;
{
[self closeWithCode:SRStatusCodeNormal reason:nil];
}
- (void)closeWithCode:(NSInteger)code reason:(NSString *)reason;
{
assert(code);
dispatch_async(_workQueue, ^{
if (self.readyState == SR_CLOSING || self.readyState == SR_CLOSED) {
return;
}
BOOL wasConnecting = self.readyState == SR_CONNECTING;
self.readyState = SR_CLOSING;
SRFastLog(@"Closing with code %d reason %@", code, reason);
if (wasConnecting) {
[self _closeConnection];
return;
}
size_t maxMsgSize = [reason maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSMutableData *mutablePayload = [[NSMutableData alloc] initWithLength:sizeof(uint16_t) + maxMsgSize];
NSData *payload = mutablePayload;
((uint16_t *)mutablePayload.mutableBytes)[0] = EndianU16_BtoN(code);
if (reason) {
NSRange remainingRange = {0};
NSUInteger usedLength = 0;
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];
#pragma unused (success)
assert(success);
assert(remainingRange.length == 0);
if (usedLength != maxMsgSize) {
payload = [payload subdataWithRange:NSMakeRange(0, usedLength + sizeof(uint16_t))];
}
}
[self _sendFrameWithOpcode:SROpCodeConnectionClose data:payload];
});
}
- (void)_closeWithProtocolError:(NSString *)message;
{
// Need to shunt this on the _callbackQueue first to see if they received any messages
[self _performDelegateBlock:^{
[self closeWithCode:SRStatusCodeProtocolError reason:message];
dispatch_async(_workQueue, ^{
[self _closeConnection];
});
}];
}
- (void)_failWithError:(NSError *)error;
{
dispatch_async(_workQueue, ^{
if (self.readyState != SR_CLOSED) {
_failed = YES;
[self _performDelegateBlock:^{
if ([self.delegate respondsToSelector:@selector(webSocket:didFailWithError:)]) {
[self.delegate webSocket:self didFailWithError:error];
}
}];
self.readyState = SR_CLOSED;
_selfRetain = nil;
SRFastLog(@"Failing with error %@", error.localizedDescription);
[self _closeConnection];
}
});
}
- (void)_writeData:(NSData *)data;
{
[self assertOnWorkQueue];
if (_closeWhenFinishedWriting) {
return;
}
[_outputBuffer appendData:data];
[self _pumpWriting];
}
- (void)send:(id)data;
{
NSAssert(self.readyState != SR_CONNECTING, @"Invalid State: Cannot call send: until connection is open");
// TODO: maybe not copy this for performance
data = [data copy];
dispatch_async(_workQueue, ^{
if ([data isKindOfClass:[NSString class]]) {
[self _sendFrameWithOpcode:SROpCodeTextFrame data:[(NSString *)data dataUsingEncoding:NSUTF8StringEncoding]];
} else if ([data isKindOfClass:[NSData class]]) {
[self _sendFrameWithOpcode:SROpCodeBinaryFrame data:data];
} else if (data == nil) {
[self _sendFrameWithOpcode:SROpCodeTextFrame data:data];
} else {
assert(NO);
}
});
}
- (void)sendPing:(NSData *)data;
{
NSAssert(self.readyState == SR_OPEN, @"Invalid State: Cannot call send: until connection is open");
// TODO: maybe not copy this for performance
data = [data copy] ?: [NSData data]; // It's okay for a ping to be empty
dispatch_async(_workQueue, ^{
[self _sendFrameWithOpcode:SROpCodePing data:data];
});
}
- (void)handlePing:(NSData *)pingData;
{
// Need to pingpong this off _callbackQueue first to make sure messages happen in order
[self _performDelegateBlock:^{
dispatch_async(_workQueue, ^{
[self _sendFrameWithOpcode:SROpCodePong data:pingData];
});
}];
}
- (void)handlePong:(NSData *)pongData;
{
SRFastLog(@"Received pong");
[self _performDelegateBlock:^{
if ([self.delegate respondsToSelector:@selector(webSocket:didReceivePong:)]) {
[self.delegate webSocket:self didReceivePong:pongData];
}
}];
}
- (void)_handleMessage:(id)message
{
SRFastLog(@"Received message");
[self _performDelegateBlock:^{
[self.delegate webSocket:self didReceiveMessage:message];
}];
}
static inline BOOL closeCodeIsValid(int closeCode) {
if (closeCode < 1000) {
return NO;
}
if (closeCode >= 1000 && closeCode <= 1011) {
if (closeCode == 1004 ||
closeCode == 1005 ||
closeCode == 1006) {
return NO;
}
return YES;
}
if (closeCode >= 3000 && closeCode <= 3999) {
return YES;
}
if (closeCode >= 4000 && closeCode <= 4999) {
return YES;
}
return NO;
}
// Note from RFC:
//
// If there is a body, the first two
// bytes of the body MUST be a 2-byte unsigned integer (in network byte
// order) representing a status code with value /code/ defined in
// Section 7.4. Following the 2-byte integer the body MAY contain UTF-8
// encoded data with value /reason/, the interpretation of which is not
// defined by this specification.
- (void)handleCloseWithData:(NSData *)data;
{
size_t dataSize = data.length;
__block uint16_t closeCode = 0;
SRFastLog(@"Received close frame");
if (dataSize == 1) {
// TODO handle error
[self _closeWithProtocolError:@"Payload for close must be larger than 2 bytes"];
return;
} else if (dataSize >= 2) {
[data getBytes:&closeCode length:sizeof(closeCode)];
_closeCode = EndianU16_BtoN(closeCode);
if (!closeCodeIsValid(_closeCode)) {
[self _closeWithProtocolError:[NSString stringWithFormat:@"Cannot have close code of %d", _closeCode]];
return;
}
if (dataSize > 2) {
_closeReason = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(2, dataSize - 2)] encoding:NSUTF8StringEncoding];
if (!_closeReason) {
[self _closeWithProtocolError:@"Close reason MUST be valid UTF-8"];
return;
}
}
} else {
_closeCode = SRStatusNoStatusReceived;
}
[self assertOnWorkQueue];
if (self.readyState == SR_OPEN) {
[self closeWithCode:1000 reason:nil];
}
dispatch_async(_workQueue, ^{
[self _closeConnection];
});
}
- (void)_closeConnection;
{
[self assertOnWorkQueue];
SRFastLog(@"Trying to disconnect");
_closeWhenFinishedWriting = YES;
[self _pumpWriting];
}
- (void)_handleFrameWithData:(NSData *)frameData opCode:(NSInteger)opcode;
{
// Check that the current data is valid UTF8
BOOL isControlFrame = (opcode == SROpCodePing || opcode == SROpCodePong || opcode == SROpCodeConnectionClose);
if (!isControlFrame) {
[self _readFrameNew];
} else {
dispatch_async(_workQueue, ^{
[self _readFrameContinue];
});
}
switch (opcode) {
case SROpCodeTextFrame: {
NSString *str = [[NSString alloc] initWithData:frameData encoding:NSUTF8StringEncoding];
if (str == nil && frameData) {
[self closeWithCode:SRStatusCodeInvalidUTF8 reason:@"Text frames must be valid UTF-8"];
dispatch_async(_workQueue, ^{
[self _closeConnection];
});
return;
}
[self _handleMessage:str];
break;
}
case SROpCodeBinaryFrame:
[self _handleMessage:[frameData copy]];
break;
case SROpCodeConnectionClose:
[self handleCloseWithData:frameData];
break;
case SROpCodePing:
[self handlePing:frameData];
break;
case SROpCodePong:
[self handlePong:frameData];
break;
default:
[self _closeWithProtocolError:[NSString stringWithFormat:@"Unknown opcode %ld", (long)opcode]];
// TODO: Handle invalid opcode
break;
}
}
- (void)_handleFrameHeader:(frame_header)frame_header curData:(NSData *)curData;
{
assert(frame_header.opcode != 0);
if (self.readyState != SR_OPEN) {
return;
}
BOOL isControlFrame = (frame_header.opcode == SROpCodePing || frame_header.opcode == SROpCodePong || frame_header.opcode == SROpCodeConnectionClose);
if (isControlFrame && !frame_header.fin) {
[self _closeWithProtocolError:@"Fragmented control frames not allowed"];
return;
}
if (isControlFrame && frame_header.payload_length >= 126) {
[self _closeWithProtocolError:@"Control frames cannot have payloads larger than 126 bytes"];
return;
}
if (!isControlFrame) {
_currentFrameOpcode = frame_header.opcode;
_currentFrameCount += 1;
}
if (frame_header.payload_length == 0) {
if (isControlFrame) {
[self _handleFrameWithData:curData opCode:frame_header.opcode];
} else {
if (frame_header.fin) {
[self _handleFrameWithData:_currentFrameData opCode:frame_header.opcode];
} else {
// TODO add assert that opcode is not a control;
[self _readFrameContinue];
}
}
} else {
assert(frame_header.payload_length <= SIZE_T_MAX);
[self _addConsumerWithDataLength:(size_t)frame_header.payload_length callback:^(SRWebSocket *self, NSData *newData) {
if (isControlFrame) {
[self _handleFrameWithData:newData opCode:frame_header.opcode];
} else {
if (frame_header.fin) {
[self _handleFrameWithData:self->_currentFrameData opCode:frame_header.opcode];
} else {
// TODO add assert that opcode is not a control;
[self _readFrameContinue];
}
}
} readToCurrentFrame:!isControlFrame unmaskBytes:frame_header.masked];
}
}
/* From RFC:
0 1 2 3
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
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| | (if payload len==126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
| Extended payload length continued, if payload len == 127 |
+ - - - - - - - - - - - - - - - +-------------------------------+
| |Masking-key, if MASK set to 1 |
+-------------------------------+-------------------------------+
| Masking-key (continued) | Payload Data |
+-------------------------------- - - - - - - - - - - - - - - - +
: Payload Data continued ... :
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
| Payload Data continued ... |
+---------------------------------------------------------------+
*/
static const uint8_t SRFinMask = 0x80;
static const uint8_t SROpCodeMask = 0x0F;
static const uint8_t SRRsvMask = 0x70;
static const uint8_t SRMaskMask = 0x80;
static const uint8_t SRPayloadLenMask = 0x7F;
- (void)_readFrameContinue;
{
assert((_currentFrameCount == 0 && _currentFrameOpcode == 0) || (_currentFrameCount > 0 && _currentFrameOpcode > 0));
[self _addConsumerWithDataLength:2 callback:^(SRWebSocket *self, NSData *data) {
__block frame_header header = {0};
const uint8_t *headerBuffer = data.bytes;
assert(data.length >= 2);
if (headerBuffer[0] & SRRsvMask) {
[self _closeWithProtocolError:@"Server used RSV bits"];
return;
}
uint8_t receivedOpcode = (SROpCodeMask & headerBuffer[0]);
BOOL isControlFrame = (receivedOpcode == SROpCodePing || receivedOpcode == SROpCodePong || receivedOpcode == SROpCodeConnectionClose);
if (!isControlFrame && receivedOpcode != 0 && self->_currentFrameCount > 0) {
[self _closeWithProtocolError:@"all data frames after the initial data frame must have opcode 0"];
return;
}
if (receivedOpcode == 0 && self->_currentFrameCount == 0) {
[self _closeWithProtocolError:@"cannot continue a message"];
return;
}
header.opcode = receivedOpcode == 0 ? self->_currentFrameOpcode : receivedOpcode;
header.fin = !!(SRFinMask & headerBuffer[0]);
header.masked = !!(SRMaskMask & headerBuffer[1]);
header.payload_length = SRPayloadLenMask & headerBuffer[1];
headerBuffer = NULL;
if (header.masked) {
[self _closeWithProtocolError:@"Client must receive unmasked data"];
}
size_t extra_bytes_needed = header.masked ? sizeof(_currentReadMaskKey) : 0;
if (header.payload_length == 126) {
extra_bytes_needed += sizeof(uint16_t);
} else if (header.payload_length == 127) {