Permalink
Browse files

Improving secure connection handling.

  • Loading branch information...
1 parent 7e3ba4a commit 6d1f99227c5d3d375d4c23fac3d989863098d2ae @pk committed Apr 25, 2012
Showing with 23 additions and 4 deletions.
  1. +22 −4 PKWebSocket/Handlers/PKWebSocketHandler.m
  2. +1 −0 PKWebSocket/PKWebSocketConstants.h
@@ -27,7 +27,9 @@ @interface PKWebSocketHandler ()
@end
-@implementation PKWebSocketHandler
+@implementation PKWebSocketHandler {
+ BOOL _didSecure;
+}
// Public
@synthesize parser = _parser;
@@ -45,7 +47,8 @@ @implementation PKWebSocketHandler
- (id)init {
self = [super init];
if (self != nil) {
- self.parser = nil;
+ self->_didSecure = NO;
+ self.parser = nil;
self->_status = PKWebSocketDisconnectedStatus;
self->_runLoopModes = [NSArray arrayWithObject:NSRunLoopCommonModes];
self.timeout = 5;
@@ -72,7 +75,7 @@ - (BOOL)connectWithURL:(PKWebSocketURL *)anURL error:(NSError **)outError {
self->_url = anURL;
self.status = PKWebSocketConnectingStatus;
- if ([anURL isSecure] && self.tlsSettings != nil) {
+ if ([anURL isSecure]) {
[self.socket startTLS:self.tlsSettings];
}
@@ -164,7 +167,7 @@ - (NSData *)handshakeResponseFrameBoundary {
#pragma mark AsyncSocket delegate methods
- (BOOL)onSocketWillConnect:(AsyncSocket *)sock {
- if (self.url.isSecure && self.tlsSettings != nil) {
+ if (self.url.isSecure) {
CFReadStreamSetProperty([sock getCFReadStream],
kCFStreamPropertySSLSettings, (__bridge CFDictionaryRef)self.tlsSettings);
CFWriteStreamSetProperty([sock getCFWriteStream],
@@ -174,6 +177,17 @@ - (BOOL)onSocketWillConnect:(AsyncSocket *)sock {
}
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
+ if ([self.url isSecure] && !self->_didSecure) {
+ NSString *reason = @"Secure URL used, connection established but connection failed to secure! Disconnecting...";
+ NSDictionary *ui = [NSDictionary dictionaryWithObjectsAndKeys:reason, NSLocalizedDescriptionKey, nil];
+ NSError *error = [NSError errorWithDomain:PKWebSocketErrorDomain
+ code:PKWebSocketTLSError
+ userInfo:ui];
+ [self.delegate handler:self didFailWithError:error];
+ [self disconnect];
+ return;
+ }
+
self.status = PKWebSocketOpeningStatus;
NSError *error;
@@ -194,6 +208,7 @@ - (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)outError
}
- (void)onSocketDidDisconnect:(AsyncSocket *)sock {
+ self->_didSecure = NO;
self.status = PKWebSocketDisconnectedStatus;
}
@@ -231,6 +246,9 @@ - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)ta
}
}
+- (void)onSocketDidSecure:(AsyncSocket *)sock {
+ self->_didSecure = YES;
+}
#pragma mark - Frame delegate
@@ -34,5 +34,6 @@ typedef enum {
PKWebSocketInvalidHandshakeRequest,
PKWebSocketInvalidResponse,
PKWebSocketIncompleteResponseHeaders,
+ PKWebSocketTLSError
} PKWebSocketError;

0 comments on commit 6d1f992

Please sign in to comment.