forked from adamjernst/cocoa-websocket
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathWebSocket.m
404 lines (303 loc) · 12.4 KB
/
WebSocket.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
//
// WebSocket.m
//
// Originally created for Zimt by Esad Hajdarevic on 2/14/10.
// Copyright 2010 OpenResearch Software Development OG. All rights reserved.
//
// Erich Ocean made the code more generic.
//
// Tobias Rodäbel implemented support for draft-hixie-thewebsocketprotocol-76.
//
#import "WebSocket.h"
#import "AsyncSocket.h"
#import <CommonCrypto/CommonDigest.h>
// Set this to 1 if you are running in secure mode on a box without a valid cert
#define WEBSOCKET_DEV_MODE 0
NSString * const WebSocketErrorDomain = @"WebSocketErrorDomain";
NSString * const WebSocketException = @"WebSocketException";
enum {
WebSocketTagHandshake = 0,
WebSocketTagMessage = 1
};
typedef struct SecKey {
uint32_t num;
NSString *key;
} SecKey;
#define HANDSHAKE_REQUEST @"GET %@ HTTP/1.1\r\n" \
"Upgrade: WebSocket\r\n" \
"Connection: Upgrade\r\n" \
"Sec-WebSocket-Protocol: sample\r\n" \
"Sec-WebSocket-Key1: %@\r\n" \
"Sec-WebSocket-Key2: %@\r\n" \
"Host: %@%@\r\n" \
"Origin: %@\r\n\r\n"
@interface NSData (WebSocketDataAdditions)
- (NSData *) MD5;
@end
@implementation NSData (WebSocketDataAdditions)
- (NSData *) MD5
{
NSMutableData *digest = [NSMutableData dataWithLength:CC_MD5_DIGEST_LENGTH];
CC_MD5([self bytes], (unsigned)[self length], [digest mutableBytes]);
return digest;
}
@end
@interface WebSocket ()
@property(nonatomic,readwrite) WebSocketState state;
@end
@implementation WebSocket
@synthesize delegate, url, origin, state, expectedChallenge, runLoopModes, secure;
#pragma mark Initializers
+ (id)webSocketWithURLString:(NSString*)urlString delegate:(id<WebSocketDelegate>)aDelegate {
return [[[WebSocket alloc] initWithURLString:urlString delegate:aDelegate] autorelease];
}
- (id)initWithURLString:(NSString *)urlString delegate:(id<WebSocketDelegate>)aDelegate {
self = [super init];
if (self) {
self.delegate = aDelegate;
url = [[NSURL URLWithString:urlString] retain];
if (![url.scheme isEqualToString:@"ws"] && ![url.scheme isEqualToString:@"wss"]) {
[NSException raise:WebSocketException format:@"Unsupported protocol %@", url.scheme];
}
if ([url.scheme isEqualToString:@"wss"]) {
secure = YES;
}
socket = [[AsyncSocket alloc] initWithDelegate:self];
self.runLoopModes = [NSArray arrayWithObjects:NSRunLoopCommonModes, nil];
}
return self;
}
#pragma mark Delegate dispatch methods
- (void)_dispatchFailure:(NSError *)error {
if(delegate && [delegate respondsToSelector:@selector(webSocket:didFailWithError:)]) {
[delegate webSocket:self didFailWithError:error];
}
}
- (void)_dispatchClosed {
if (delegate && [delegate respondsToSelector:@selector(webSocketDidClose:)]) {
[delegate webSocketDidClose:self];
}
}
- (void)_dispatchOpened {
if (delegate && [delegate respondsToSelector:@selector(webSocketDidOpen:)]) {
[delegate webSocketDidOpen:self];
}
}
- (void)_dispatchMessageReceived:(NSString*)message {
if (delegate && [delegate respondsToSelector:@selector(webSocket:didReceiveMessage:)]) {
[delegate webSocket:self didReceiveMessage:message];
}
}
- (void)_dispatchMessageSent {
if (delegate && [delegate respondsToSelector:@selector(webSocketDidSendMessage:)]) {
[delegate webSocketDidSendMessage:self];
}
}
- (void)_dispatchSecured {
if (delegate && [delegate respondsToSelector:@selector(webSocketDidSecure:)]) {
[delegate webSocketDidSecure:self];
}
}
#pragma mark Private
- (void)_readNextMessage {
[socket readDataToData:[NSData dataWithBytes:"\xFF" length:1] withTimeout:-1 tag:WebSocketTagMessage];
}
- (struct SecKey)_makeKey {
struct SecKey seckey;
uint32_t spaces;
uint32_t max, num, prod;
NSInteger keylen;
unichar letter;
spaces = (arc4random() % 12) + 1;
max = (arc4random() % 4294967295U) / spaces;
num = arc4random() % max;
prod = spaces * num;
NSMutableString *key = [NSMutableString stringWithFormat:@"%ld", prod];
keylen = [key length];
for (NSInteger i=0; i<12; i++) {
if ((arc4random() % 2) == 0)
letter = (arc4random() % (47 - 33 + 1)) + 33;
else
letter = (arc4random() % (126 - 58 + 1)) + 58;
[key insertString:[[[NSString alloc] initWithCharacters:&letter length:1] autorelease] atIndex:(arc4random() % (keylen-1))];
}
keylen = [key length];
for (uint32_t i=0; i<spaces; i++)
[key insertString:@" " atIndex:((arc4random() % (keylen-2))+1)];
seckey.num = num;
seckey.key = key;
return seckey;
}
- (void)_makeChallengeNumber:(uint32_t)number withBuffer:(unsigned char *)buf {
unsigned char *p = buf + 3;
for (int i = 0; i < 4; i++) {
*p = number & 0xFF;
--p;
number >>= 8;
}
}
- (NSError *)_makeError:(int)code underlyingError:(NSError *)underlyingError {
NSDictionary *userInfo = nil;
if (underlyingError) {
userInfo = [NSDictionary dictionaryWithObject:underlyingError forKey:NSUnderlyingErrorKey];
}
return [NSError errorWithDomain:WebSocketErrorDomain code:code userInfo:userInfo];
}
#pragma mark Public interface
- (void)close {
[socket disconnect];
}
- (void)open {
if ([self state] == WebSocketStateDisconnected) {
if (secure) {
NSDictionary *settings = nil;
if (WEBSOCKET_DEV_MODE) {
settings = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],
(NSString *)kCFStreamSSLAllowsAnyRoot, nil];
}
[socket startTLS:settings];
}
[socket connectToHost:url.host onPort:[url.port intValue] withTimeout:5 error:nil];
if (runLoopModes) [socket setRunLoopModes:runLoopModes];
}
}
- (void)send:(NSString*)message {
NSMutableData* data = [NSMutableData data];
[data appendBytes:"\x00" length:1];
[data appendData:[message dataUsingEncoding:NSUTF8StringEncoding]];
[data appendBytes:"\xFF" length:1];
[socket writeData:data withTimeout:-1 tag:WebSocketTagMessage];
}
- (BOOL)connected {
// Backwards compatibility only.
return [self state] == WebSocketStateConnected;
}
#pragma mark AsyncSocket delegate methods
- (BOOL)onSocketWillConnect:(AsyncSocket *)sock {
if (secure && WEBSOCKET_DEV_MODE) {
// Connecting to a secure server
NSMutableDictionary * settings = [NSMutableDictionary dictionaryWithCapacity:2];
// Use the highest possible security
[settings setObject:(NSString *)kCFStreamSocketSecurityLevelNegotiatedSSL
forKey:(NSString *)kCFStreamSSLLevel];
// Allow self-signed certificates
[settings setObject:[NSNumber numberWithBool:YES]
forKey:(NSString *)kCFStreamSSLAllowsAnyRoot];
CFReadStreamSetProperty([sock getCFReadStream],
kCFStreamPropertySSLSettings, (CFDictionaryRef)settings);
CFWriteStreamSetProperty([sock getCFWriteStream],
kCFStreamPropertySSLSettings, (CFDictionaryRef)settings);
}
return YES;
}
- (void)onSocketDidSecure:(AsyncSocket *)sock {
[self _dispatchSecured];
}
- (void)onSocketDidDisconnect:(AsyncSocket *)sock {
BOOL wasConnected = ([self state] == WebSocketStateConnected);
[self setState:WebSocketStateDisconnected];
// Only dispatch the websocket closed message if it previously opened
// (completed the handshake). If it never opened, this is probably a
// connection timeout error.
if (wasConnected) [self _dispatchClosed];
}
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err {
if ([self state] == WebSocketStateConnecting) {
[self _dispatchFailure:[self _makeError:WebSocketErrorConnectionFailed underlyingError:err]];
} else {
[self _dispatchFailure:err];
}
}
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
NSString *requestOrigin = (self.origin) ? self.origin : [NSString stringWithFormat:@"http://%@", url.host];
NSString *requestPath = (url.query) ? [NSString stringWithFormat:@"%@?%@", url.path, url.query] : url.path;
SecKey seckey1 = [self _makeKey];
SecKey seckey2 = [self _makeKey];
NSString *key1 = seckey1.key;
NSString *key2 = seckey2.key;
char letters[8];
for (int i=0; i<8; i++)
letters[i] = arc4random() % 126;
NSData *key3 = [NSData dataWithBytes:letters length:8];
unsigned char bytes[8];
[self _makeChallengeNumber:seckey1.num withBuffer:&bytes[0]];
[self _makeChallengeNumber:seckey2.num withBuffer:&bytes[4]];
NSMutableData *challenge = [NSMutableData dataWithBytes:bytes length:sizeof(bytes)];
[challenge appendData:key3];
self.expectedChallenge = [challenge MD5];
NSString *headers = [NSString stringWithFormat:HANDSHAKE_REQUEST,
requestPath,
key1,
key2,
url.host,
((secure && [url.port intValue] != 443) ||
(!secure && [url.port intValue] != 80)) ?
[NSString stringWithFormat:@":%d", [url.port intValue]] : @"",
requestOrigin];
NSMutableData *request = [NSMutableData dataWithData:[headers dataUsingEncoding:NSASCIIStringEncoding]];
[request appendData:key3];
[socket writeData:request withTimeout:-1 tag:WebSocketTagHandshake];
}
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag {
switch (tag) {
case WebSocketTagHandshake:
[sock readDataToData:self.expectedChallenge withTimeout:5 tag:WebSocketTagHandshake];
break;
case WebSocketTagMessage:
[self _dispatchMessageSent];
break;
default:
break;
}
}
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
if (tag == WebSocketTagHandshake) {
NSString *upgrade;
NSString *connection;
NSData *body;
UInt32 statusCode = 0;
CFHTTPMessageRef message = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, FALSE);
if (!message || !CFHTTPMessageAppendBytes(message, [data bytes], [data length])) {
[self _dispatchFailure:[self _makeError:WebSocketErrorHandshakeFailed underlyingError:nil]];
if (message) CFRelease(message);
return;
}
if (CFHTTPMessageIsHeaderComplete(message)) {
upgrade = [(NSString *) CFHTTPMessageCopyHeaderFieldValue(message, CFSTR("Upgrade")) autorelease];
connection = [(NSString *) CFHTTPMessageCopyHeaderFieldValue(message, CFSTR("Connection")) autorelease];
statusCode = (UInt32)CFHTTPMessageGetResponseStatusCode(message);
}
if (statusCode == 101 && [upgrade isEqualToString:@"WebSocket"] && [connection isEqualToString:@"Upgrade"]) {
body = [(NSData *)CFHTTPMessageCopyBody(message) autorelease];
CFRelease(message);
if (![body isEqualToData:self.expectedChallenge]) {
[self _dispatchFailure:[self _makeError:WebSocketErrorHandshakeFailed underlyingError:nil]];
return;
}
[self setState:WebSocketStateConnected];
[self _dispatchOpened];
[self _readNextMessage];
} else {
CFRelease(message);
[self _dispatchFailure:[self _makeError:WebSocketErrorHandshakeFailed underlyingError:nil]];
}
} else if (tag == WebSocketTagMessage) {
char firstByte = 0xFF;
[data getBytes:&firstByte length:1];
if (firstByte != 0x00) return; // Discard message
NSString *message = [[[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(1, [data length]-2)] encoding:NSUTF8StringEncoding] autorelease];
[self _dispatchMessageReceived:message];
[self _readNextMessage];
}
}
#pragma mark Destructor
- (void)dealloc {
socket.delegate = nil;
[socket disconnect];
[socket release];
[expectedChallenge release];
[runLoopModes release];
[url release];
[super dealloc];
}
@end