-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathWebSocket00.m
534 lines (464 loc) · 16 KB
/
WebSocket00.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
//
// WebSocket00.m
// UnittWebSocketClient
//
// Created by Josh Morris on 5/3/11.
// Copyright 2011 UnitT Software. All rights reserved.
//
// 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 "WebSocket00.h"
@interface WebSocket00(Private)
- (void) dispatchFailure:(NSError*) aError;
- (void) dispatchClosed:(NSError*) aWasClean;
- (void) dispatchOpened;
- (void) dispatchMessageReceived:(NSString*) aMessage;
- (void) readNextMessage;
- (NSString*) buildOrigin;
- (NSString*) buildHost;
- (NSString*) getRequest:(NSString*) aRequestPath;
- (NSData*) getMD5:(NSData*) aPlainText;
- (void) generateSecKeys;
- (BOOL) isUpgradeResponse: (NSString*) aResponse;
- (NSString*) getServerProtocol:(NSString*) aResponse;
@end
int randFromRange(int min, int max);
@implementation WebSocket00
NSString* const WebSocket00Exception = @"WebSocketException";
NSString* const WebSocket00ErrorDomain = @"WebSocketErrorDomain";
enum
{
TagHandshake = 0,
TagMessage = 1
};
@synthesize delegate;
@synthesize url;
@synthesize origin;
@synthesize readystate;
@synthesize timeout;
@synthesize tlsSettings;
@synthesize protocols;
@synthesize verifyHandshake;
@synthesize serverProtocol;
@synthesize closingError;
@synthesize serverHandshake;
@synthesize socket;
#pragma mark Public Interface
- (void) open
{
UInt16 port = isSecure ? 443 : 80;
if (self.url.port)
{
port = [self.url.port intValue];
}
NSError* error = nil;
BOOL successful = false;
@try
{
successful = [socket connectToHost:self.url.host onPort:port error:&error];
}
@catch (NSException *exception)
{
error = [NSError errorWithDomain:WebSocket00ErrorDomain code:0 userInfo:exception.userInfo];
}
@finally
{
if (!successful)
{
[self dispatchClosed:error];
}
}
}
- (void) close
{
readystate = WebSocketReadyStateClosing;
[socket disconnectAfterWriting];
}
- (void) send:(NSString*) aMessage
{
NSMutableData* data = [NSMutableData data];
[data appendBytes:"\x00" length:1];
[data appendData:[aMessage dataUsingEncoding:NSUTF8StringEncoding]];
[data appendBytes:"\xFF" length:1];
[socket writeData:data withTimeout:self.timeout tag:TagMessage];
}
#pragma mark Internal Web Socket Logic
- (void) readNextMessage
{
[socket readDataToData:[NSData dataWithBytes:"\xFF" length:1] withTimeout:self.timeout tag:TagMessage];
}
- (NSData*) getMD5:(NSData*) aPlainText
{
unsigned char result[16];
CC_MD5( aPlainText.bytes, [aPlainText length], result );
return [NSData dataWithBytes:result length:16];
}
- (NSString*) buildOrigin
{
if (self.url.port && [self.url.port intValue] != 80 && [self.url.port intValue] != 443)
{
return [NSString stringWithFormat:@"%@://%@:%i%@", isSecure ? @"https" : @"http", self.url.host, [self.url.port intValue], self.url.path ? self.url.path : @""];
}
return [NSString stringWithFormat:@"%@://%@%@", isSecure ? @"https" : @"http", self.url.host, self.url.path ? self.url.path : @""];
}
- (NSString*) buildHost
{
if (self.url.port)
{
if ([self.url.port intValue] == 80 || [self.url.port intValue] == 443)
{
return self.url.host;
}
return [NSString stringWithFormat:@"%@:%i", self.url.host, [self.url.port intValue]];
}
return self.url.host;
}
// TODO: use key1, key2, key3 handshake stuff
- (NSString*) getRequest: (NSString*) aRequestPath
{
[self generateSecKeys];
if (self.protocols && self.protocols.count > 0)
{
//build protocol fragment
NSMutableString* protocolFragment = [NSMutableString string];
for (NSString* item in protocols)
{
if ([protocolFragment length] > 0)
{
[protocolFragment appendString:@", "];
}
[protocolFragment appendString:item];
}
//return request with protocols
if ([protocolFragment length] > 0)
{
return [NSString stringWithFormat:@"GET %@ HTTP/1.1\r\n"
"Upgrade: WebSocket\r\n"
"Connection: Upgrade\r\n"
"Host: %@\r\n"
"Origin: %@\r\n"
"Sec-WebSocket-Protocol: %@\r\n"
"\r\n",
aRequestPath, [self buildHost], self.origin, protocolFragment];
}
}
//return request normally
return [NSString stringWithFormat:@"GET %@ HTTP/1.1\r\n"
"Upgrade: WebSocket\r\n"
"Connection: Upgrade\r\n"
"Host: %@\r\n"
"Origin: %@\r\n"
"\r\n",
aRequestPath, [self buildHost], self.origin];
/*
return [NSString stringWithFormat:@"GET %@ HTTP/1.1\r\n"
"Upgrade: WebSocket\r\n"
"Connection: Upgrade\r\n"
"Host: %@\r\n"
"Origin: %@\r\n"
"Sec-WebSocket-Key1: %@\r\n"
"Sec-WebSocket-Key2: %@\r\n"
"Sec-WebSocket-Version: 0\r\n"
"\r\n@",
aRequestPath, self.url.host, self.origin, key1, key2, [[NSString alloc] initWithData:[NSData dataWithBytes:&key3 length:8] encoding:NSASCIIStringEncoding]];
*/
}
int randFromRange(int min, int max)
{
return (arc4random() % max) + min;
}
- (NSData*) createRandomBytes
{
unsigned char bytes[8];
for (int i = 0; i < 8; i++)
{
bytes[i] = randFromRange(0, 255) & 0xFF;
}
return [NSData dataWithBytes:bytes length:8];
}
- (NSString*) insertRandomCharacters: (NSString*) aString
{
NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
NSString* result = aString;
int count = randFromRange(1, 12);
for (int i = 0; i < count; i++)
{
int split = randFromRange(1, [result length] - 1);
NSString* part1 = [result substringWithRange:NSMakeRange(0, split)];
NSString* part2 = [result substringWithRange:NSMakeRange(split, [result length] - split)];
result = [NSString stringWithFormat:@"%@%c%@", part1, [letters characterAtIndex: randFromRange(0, [letters length])], part2];
}
return result;
}
- (NSString*) insertSpaces:(int) aSpaces string:(NSString*) aString
{
NSString* result = aString;
for (int i = 0; i < aSpaces; i++)
{
int split = randFromRange(1, [result length] - 1);
NSString* part1 = [result substringWithRange:NSMakeRange(0, split)];
NSString* part2 = [result substringWithRange:NSMakeRange(split, [result length] - split)];
result = [NSString stringWithFormat:@"%@ %@", part1, part2];
}
return result;
}
- (void) generateSecKeys
{
int spaces1 = randFromRange(1,12);
int spaces2 = randFromRange(1,12);
int max1 = INT32_MAX / spaces1;
int max2 = INT32_MAX / spaces2;
int number1 = randFromRange(0, max1);
int number2 = randFromRange(0, max2);
int product1 = number1 * spaces1;
int product2 = number2 * spaces2;
key1 = [NSString stringWithFormat:@"%i", product1];
key2 = [NSString stringWithFormat:@"%i", product2];
key1 = [self insertRandomCharacters:key1];
key2 = [self insertRandomCharacters:key2];
key1 = [self insertSpaces:spaces1 string:key1];
key2 = [self insertSpaces:spaces2 string:key2];
key3 = [self createRandomBytes];
NSMutableData* challenge = [NSMutableData data];
int key1int = [key1 intValue];
int key2int = [key2 intValue];
[challenge appendBytes:(char*)&key1int length:4];
[challenge appendBytes:(char*)&key2int length:4];
[challenge appendBytes:[key3 bytes] length:8];
self.serverHandshake = [self getMD5:challenge];
}
- (BOOL) isUpgradeResponse: (NSString*) aResponse
{
//NSLog(@"Handshake Response:\n%@", aResponse);
//a HTTP 101 response is the only valid one
if ([aResponse hasPrefix:@"HTTP/1.1 101"])
{
//continuing verifying that we are upgrading
NSArray *listItems = [aResponse componentsSeparatedByString:@"\r\n"];
BOOL foundUpgrade = NO;
BOOL foundConnection = NO;
BOOL verifiedHandshake = !verifyHandshake;
//loop through headers testing values
for (NSString* item in listItems)
{
//search for -> Upgrade: websocket & Connection: Upgrade
if ([item rangeOfString:@"Upgrade" options:NSCaseInsensitiveSearch].length)
{
if (!foundUpgrade)
{
foundUpgrade = [item rangeOfString:@"WebSocket" options:NSCaseInsensitiveSearch].length;
}
if (!foundConnection)
{
foundConnection = [item rangeOfString:@"Connection" options:NSCaseInsensitiveSearch].length;
}
}
//if we are verifying - do so
if (!verifiedHandshake)
{
NSData* handshakeData = [item dataUsingEncoding:NSASCIIStringEncoding];
verifiedHandshake = [handshakeData rangeOfData:self.serverHandshake options:NSDataSearchBackwards range:NSMakeRange(0, [handshakeData length])].length > 0;
}
//if we have what we need, get out
if (foundUpgrade && foundConnection && verifiedHandshake)
{
return true;
}
}
}
return false;
}
- (NSString*) getServerProtocol:(NSString*) aResponse
{
//loop through headers looking for the protocol
NSArray *listItems = [aResponse componentsSeparatedByString:@"\r\n"];
for (NSString* item in listItems)
{
//if this is the protocol - return the value
if ([item rangeOfString:@"Sec-WebSocket-Protocol" options:NSCaseInsensitiveSearch].length)
{
NSRange range = [item rangeOfString:@":" options:NSLiteralSearch];
NSString* value = [item substringFromIndex:range.length + range.location];
return [value stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
}
}
return nil;
}
#pragma mark Web Socket Delegate
- (void) dispatchFailure:(NSError*) aError
{
if(delegate)
{
[delegate didReceiveError:aError];
}
}
- (void) dispatchClosed:(NSError*) aError
{
if (delegate)
{
[delegate didClose: aError];
}
}
- (void) dispatchOpened
{
if (delegate)
{
[delegate didOpen];
}
}
- (void) dispatchMessageReceived:(NSString*) aMessage
{
if (delegate)
{
[delegate didReceiveMessage:aMessage];
}
}
#pragma mark AsyncSocket Delegate
- (void) onSocketDidDisconnect:(AsyncSocket*) aSock
{
readystate = WebSocketReadyStateClosed;
[self dispatchClosed:self.closingError];
}
- (void) onSocket:(AsyncSocket *) aSocket willDisconnectWithError:(NSError *) aError
{
switch (self.readystate)
{
case WebSocketReadyStateOpen:
case WebSocketReadyStateConnecting:
readystate = WebSocketReadyStateClosing;
[self dispatchFailure:aError];
case WebSocketReadyStateClosing:
self.closingError = aError;
}
}
- (void) onSocket:(AsyncSocket*) aSocket didConnectToHost:(NSString*) aHost port:(UInt16) aPort
{
//start TLS if this is a secure websocket
if (isSecure)
{
// Configure SSL/TLS settings
NSDictionary *settings = self.tlsSettings;
//seed with defaults if missing
if (!settings)
{
settings = [NSMutableDictionary dictionaryWithCapacity:3];
}
[socket startTLS:settings];
}
//continue with handshake
NSString *requestPath = self.url.path;
if (self.url.query)
{
requestPath = [requestPath stringByAppendingFormat:@"?%@", self.url.query];
}
NSString* getRequest = [self getRequest: requestPath];
//NSLog(@"Handshake Request: %@", getRequest);
[aSocket writeData:[getRequest dataUsingEncoding:NSASCIIStringEncoding] withTimeout:self.timeout tag:TagHandshake];
}
- (void) onSocket:(AsyncSocket*) aSocket didWriteDataWithTag:(long) aTag
{
if (aTag == TagHandshake)
{
[aSocket readDataToData:[@"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding] withTimeout:self.timeout tag:TagHandshake];
}
}
- (void) onSocket: (AsyncSocket*) aSocket didReadData:(NSData*) aData withTag:(long) aTag
{
if (aTag == TagHandshake)
{
NSString* response = [[[NSString alloc] initWithData:aData encoding:NSASCIIStringEncoding] autorelease];
if ([self isUpgradeResponse: response])
{
//grab protocol from server
NSString* protocol = [self getServerProtocol:response];
if (protocol)
{
self.serverProtocol = protocol;
}
//handle state & delegates
readystate = WebSocketReadyStateOpen;
[self dispatchOpened];
[self readNextMessage];
}
else
{
[self dispatchFailure:[NSError errorWithDomain:WebSocket00ErrorDomain code:0 userInfo:[NSDictionary dictionaryWithObject:@"Bad handshake" forKey:NSLocalizedFailureReasonErrorKey]]];
}
}
else if (aTag == TagMessage)
{
unsigned char firstByte = 0xFF;
[aData getBytes:&firstByte length:1];
if (firstByte != 0x00) return; // Discard message
NSString* message = [[[NSString alloc] initWithData:[aData subdataWithRange:NSMakeRange(1, [aData length]-2)] encoding:NSUTF8StringEncoding] autorelease];
[self dispatchMessageReceived:message];
[self readNextMessage];
}
}
#pragma mark Lifecycle
+ (id) webSocketWithURLString:(NSString*) aUrlString delegate:(id<WebSocket00Delegate>) aDelegate origin:(NSString*) aOrigin protocols:(NSArray*) aProtocols tlsSettings:(NSDictionary*) aTlsSettings verifyHandshake:(BOOL) aVerifyHandshake
{
return [[[[self class] alloc] initWithURLString:aUrlString delegate:aDelegate origin:aOrigin protocols:aProtocols tlsSettings:aTlsSettings verifyHandshake:aVerifyHandshake] autorelease];
}
// TODO: add verify handshake info
- (id) initWithURLString:(NSString *) aUrlString delegate:(id<WebSocket00Delegate>) aDelegate origin:(NSString*) aOrigin protocols:(NSArray*) aProtocols tlsSettings:(NSDictionary*) aTlsSettings verifyHandshake:(BOOL) aVerifyHandshake
{
self = [super init];
if (self)
{
//validate
NSURL* tempUrl = [NSURL URLWithString:aUrlString];
if (![tempUrl.scheme isEqualToString:@"ws"] && ![tempUrl.scheme isEqualToString:@"wss"])
{
[NSException raise:WebSocket00Exception format:@"Unsupported protocol %@",tempUrl.scheme];
}
//apply properties
self.url = tempUrl;
self.delegate = aDelegate;
isSecure = [self.url.scheme isEqualToString:@"wss"];
if (aOrigin)
{
self.origin = aOrigin;
}
else
{
self.origin = [self buildOrigin];
}
if (aProtocols)
{
self.protocols = aProtocols;
}
if (aTlsSettings)
{
self.tlsSettings = aTlsSettings;
}
verifyHandshake = NO;
self.socket = [[[AsyncSocket alloc] initWithDelegate:self] autorelease];
self.timeout = 30.0;
}
return self;
}
-(void) dealloc
{
socket.delegate = nil;
self.serverHandshake = nil;
[self.socket disconnect];
self.socket = nil;
self.url = nil;
self.origin = nil;
self.closingError = nil;
self.protocols = nil;
self.tlsSettings = nil;
[super dealloc];
}
@end