wxr
2021-07-01 43b0d5870d528f23ecd6aeceb6cfd4325188b46f
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
//
// MQTTSSLSecurityPolicyEncoder.m
// MQTTClient.framework
//
// Copyright © 2013-2017, Christoph Krey. All rights reserved.
//
 
#import "MQTTSSLSecurityPolicyEncoder.h"
 
#import "MQTTLog.h"
 
@interface MQTTSSLSecurityPolicyEncoder()
@property (nonatomic) BOOL securityPolicyApplied;
 
@end
 
@implementation MQTTSSLSecurityPolicyEncoder
 
- (instancetype)init {
    self = [super init];
    self.securityPolicy = nil;
    self.securityDomain = nil;
    
    return self;
}
 
- (BOOL)applySSLSecurityPolicy:(NSStream *)writeStream withEvent:(NSStreamEvent)eventCode {
    if (!self.securityPolicy) {
        return YES;
    }
    
    if (self.securityPolicyApplied) {
        return YES;
    }
    
    SecTrustRef serverTrust = (__bridge SecTrustRef)[writeStream propertyForKey:(__bridge NSString *)kCFStreamPropertySSLPeerTrust];
    if (!serverTrust) {
        return NO;
    }
    
    self.securityPolicyApplied = [self.securityPolicy evaluateServerTrust:serverTrust forDomain:self.securityDomain];
    return self.securityPolicyApplied;
}
 
- (void)stream:(NSStream *)sender handleEvent:(NSStreamEvent)eventCode {
    if (eventCode & NSStreamEventHasSpaceAvailable) {
        DDLogVerbose(@"[MQTTCFSocketEncoder] NSStreamEventHasSpaceAvailable");
        if (![self applySSLSecurityPolicy:sender withEvent:eventCode]){
            self.state = MQTTCFSocketEncoderStateError;
            self.error = [NSError errorWithDomain:@"MQTT"
                                             code:errSSLXCertChainInvalid
                                         userInfo:@{NSLocalizedDescriptionKey: @"Unable to apply security policy, the SSL connection is insecure!"}];
            [self.delegate encoder:self didFailWithError:self.error];
            return;
        }
    }
    [super stream:sender handleEvent:eventCode];
}
 
@end