GCDAsyncHTTPSProxySocket.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. //
  2. // GCDAsyncHTTPSProxySocket.m
  3. //
  4. // Copyright © 2019 Threema GmbH. All rights reserved.
  5. // Derived from ProxyKit, Copyright (c) 2014 Chris Ballinger
  6. //
  7. #import "GCDAsyncHTTPSProxySocket.h"
  8. #if DEBUG
  9. static const int ddLogLevel = DDLogLevelVerbose;
  10. #else
  11. static const int ddLogLevel = DDLogLevelOff;
  12. #endif
  13. // Define various socket tags
  14. #define HTTP_CONNECT 10100
  15. // Timeouts
  16. #define TIMEOUT_CONNECT 8.00
  17. #define TIMEOUT_READ 5.00
  18. #define TIMEOUT_TOTAL 80.00
  19. @interface GCDAsyncHTTPSProxySocket()
  20. @property (nonatomic, strong, readonly) GCDAsyncSocket *proxySocket;
  21. @property (nonatomic, readonly) dispatch_queue_t proxyDelegateQueue;
  22. @property (nonatomic, strong, readonly) NSString *destinationHost;
  23. @property (nonatomic, readonly) uint16_t destinationPort;
  24. @property (nonatomic, strong) NSError *lastDisconnectError;
  25. @end
  26. @implementation GCDAsyncHTTPSProxySocket
  27. - (void) setProxyHost:(NSString *)host port:(uint16_t)port {
  28. _proxyHost = host;
  29. _proxyPort = port;
  30. }
  31. #pragma mark Overridden methods
  32. - (id)initWithDelegate:(id)aDelegate delegateQueue:(dispatch_queue_t)dq socketQueue:(dispatch_queue_t)sq {
  33. if (self = [super initWithDelegate:aDelegate delegateQueue:dq socketQueue:sq]) {
  34. _proxyHost = nil;
  35. _proxyPort = 0;
  36. _destinationHost = nil;
  37. _destinationPort = 0;
  38. _proxyDelegateQueue = dispatch_queue_create("GCDAsyncHTTPSProxySocket delegate queue", 0);
  39. }
  40. return self;
  41. }
  42. - (BOOL)connectToHost:(NSString *)inHost
  43. onPort:(uint16_t)port
  44. viaInterface:(NSString *)inInterface
  45. withTimeout:(NSTimeInterval)timeout
  46. error:(NSError **)errPtr
  47. {
  48. if (!self.proxySocket) {
  49. _proxySocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:self.proxyDelegateQueue socketQueue:NULL];
  50. }
  51. _destinationHost = inHost;
  52. _destinationPort = port;
  53. return [self.proxySocket connectToHost:self.proxyHost onPort:self.proxyPort viaInterface:inInterface withTimeout:timeout error:errPtr];
  54. }
  55. /** Returns YES if tag is reserved for internal functions */
  56. - (BOOL) checkForReservedTag:(long)tag {
  57. if (tag == HTTP_CONNECT) {
  58. return YES;
  59. } else {
  60. return NO;
  61. }
  62. }
  63. - (void) writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag {
  64. if ([self checkForReservedTag:tag]) {
  65. DDLogError(@"This tag is reserved and won't work: %ld", tag);
  66. return;
  67. }
  68. [self.proxySocket writeData:data withTimeout:timeout tag:tag];
  69. }
  70. - (void)readDataWithTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInteger)offset tag:(long)tag {
  71. if ([self checkForReservedTag:tag]) {
  72. DDLogError(@"This tag is reserved and won't work: %ld", tag);
  73. return;
  74. }
  75. [self.proxySocket readDataWithTimeout:timeout buffer:buffer bufferOffset:offset tag:tag];
  76. }
  77. - (void)readDataWithTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInteger)offset maxLength:(NSUInteger)length tag:(long)tag {
  78. if ([self checkForReservedTag:tag]) {
  79. DDLogError(@"This tag is reserved and won't work: %ld", tag);
  80. return;
  81. }
  82. [self.proxySocket readDataWithTimeout:timeout buffer:buffer bufferOffset:offset maxLength:length tag:tag];
  83. }
  84. - (void) readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag {
  85. if ([self checkForReservedTag:tag]) {
  86. DDLogError(@"This tag is reserved and won't work: %ld", tag);
  87. return;
  88. }
  89. [self.proxySocket readDataWithTimeout:timeout tag:tag];
  90. }
  91. - (void)readDataToLength:(NSUInteger)length withTimeout:(NSTimeInterval)timeout tag:(long)tag {
  92. if ([self checkForReservedTag:tag]) {
  93. DDLogError(@"This tag is reserved and won't work: %ld", tag);
  94. return;
  95. }
  96. [self.proxySocket readDataToLength:length withTimeout:timeout tag:tag];
  97. }
  98. - (void)readDataToLength:(NSUInteger)length withTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInteger)offset tag:(long)tag {
  99. if ([self checkForReservedTag:tag]) {
  100. DDLogError(@"This tag is reserved and won't work: %ld", tag);
  101. return;
  102. }
  103. [self.proxySocket readDataToLength:length withTimeout:timeout buffer:buffer bufferOffset:offset tag:tag];
  104. }
  105. - (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag {
  106. if ([self checkForReservedTag:tag]) {
  107. DDLogError(@"This tag is reserved and won't work: %ld", tag);
  108. return;
  109. }
  110. [self.proxySocket readDataToData:data withTimeout:timeout tag:tag];
  111. }
  112. - (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInteger)offset tag:(long)tag {
  113. if ([self checkForReservedTag:tag]) {
  114. DDLogError(@"This tag is reserved and won't work: %ld", tag);
  115. return;
  116. }
  117. [self.proxySocket readDataToData:data withTimeout:timeout buffer:buffer bufferOffset:offset tag:tag];
  118. }
  119. - (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout maxLength:(NSUInteger)length tag:(long)tag {
  120. if ([self checkForReservedTag:tag]) {
  121. DDLogError(@"This tag is reserved and won't work: %ld", tag);
  122. return;
  123. }
  124. [self.proxySocket readDataToData:data withTimeout:timeout maxLength:length tag:tag];
  125. }
  126. - (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInteger)offset maxLength:(NSUInteger)length tag:(long)tag {
  127. if ([self checkForReservedTag:tag]) {
  128. DDLogError(@"This tag is reserved and won't work: %ld", tag);
  129. return;
  130. }
  131. [self.proxySocket readDataToData:data withTimeout:timeout buffer:buffer bufferOffset:offset maxLength:length tag:tag];
  132. }
  133. - (void) startTLS:(NSDictionary *)tlsSettings {
  134. NSMutableDictionary *settings = [NSMutableDictionary dictionaryWithDictionary:tlsSettings];
  135. /*
  136. NSString *peerName = self.destinationHost;
  137. [settings setObject:peerName forKey:(NSString *)kCFStreamSSLPeerName];
  138. */
  139. [self.proxySocket startTLS:settings];
  140. }
  141. - (void) disconnect {
  142. self.lastDisconnectError = nil;
  143. [self.proxySocket disconnect];
  144. }
  145. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  146. #pragma mark HTTP
  147. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  148. /**
  149. * Sends the HTTP CONNECT request, and starts reading the response.
  150. **/
  151. - (void)httpConnect
  152. {
  153. NSString *connectRequest = [NSString stringWithFormat:@"CONNECT %@:%d HTTP/1.1\r\nHost: %@:%d\r\nUser-Agent: Threema\r\nConnection: keep-alive\r\nProxy-Connection: keep-alive\r\n\r\n",
  154. self.destinationHost, self.destinationPort, self.destinationHost, self.destinationPort];
  155. [self.proxySocket writeData:[connectRequest dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:HTTP_CONNECT];
  156. [self.proxySocket readDataToData:[@"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding] withTimeout:TIMEOUT_READ tag:HTTP_CONNECT];
  157. }
  158. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  159. #pragma mark AsyncSocket Delegate Methods
  160. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  161. - (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
  162. {
  163. DDLogInfo(@"proxySocket did connect to %@:%d", host, port);
  164. [self httpConnect];
  165. }
  166. - (void) socket:(GCDAsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag {
  167. DDLogVerbose(@"read partial data with tag %ld of length %d", tag, (int)partialLength);
  168. if (self.delegate && [self.delegate respondsToSelector:@selector(socket:didReadPartialDataOfLength:tag:)]) {
  169. dispatch_async(self.delegateQueue, ^{
  170. @autoreleasepool {
  171. [self.delegate socket:self didReadPartialDataOfLength:partialLength tag:tag];
  172. }
  173. });
  174. }
  175. }
  176. - (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
  177. {
  178. DDLogVerbose(@"did read tag[%ld] data: %@", tag, data);
  179. if (tag == HTTP_CONNECT)
  180. {
  181. NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  182. DDLogVerbose(@"GCDAsyncHTTPSProxySocket: HTTP_CONNECT response: %@", response);
  183. NSInteger statusCode = -1;
  184. NSRegularExpression *responseRegex = [NSRegularExpression regularExpressionWithPattern:@"^HTTP\\S+ (\\d+) " options:0 error:nil];
  185. NSTextCheckingResult *result = [responseRegex firstMatchInString:response options:0 range:NSMakeRange(0, response.length)];
  186. if (result.numberOfRanges == 2) {
  187. statusCode = [[response substringWithRange:[result rangeAtIndex:1]] integerValue];
  188. }
  189. if (statusCode != 200) {
  190. DDLogError(@"Proxy returned status code %ld", (long)statusCode);
  191. self.lastDisconnectError = [NSError errorWithDomain:NSURLErrorDomain code:statusCode userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Proxy server returned status code %ld", (long)statusCode]}];
  192. [self.proxySocket disconnect];
  193. return;
  194. }
  195. if (self.delegate && [self.delegate respondsToSelector:@selector(socket:didConnectToHost:port:)]) {
  196. dispatch_async(self.delegateQueue, ^{
  197. @autoreleasepool {
  198. [self.delegate socket:self didConnectToHost:self.destinationHost port:self.destinationPort];
  199. }
  200. });
  201. }
  202. }
  203. else {
  204. if (self.delegate && [self.delegate respondsToSelector:@selector(socket:didReadData:withTag:)]) {
  205. dispatch_async(self.delegateQueue, ^{
  206. @autoreleasepool {
  207. [self.delegate socket:self didReadData:data withTag:tag];
  208. }
  209. });
  210. }
  211. }
  212. }
  213. #pragma mark GCDAsyncSocketDelegate methods
  214. - (void) socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag {
  215. if (self.delegate && [self.delegate respondsToSelector:@selector(socket:didWriteDataWithTag:)]) {
  216. dispatch_async(self.delegateQueue, ^{
  217. @autoreleasepool {
  218. [self.delegate socket:self didWriteDataWithTag:tag];
  219. }
  220. });
  221. }
  222. }
  223. - (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err {
  224. DDLogVerbose(@"proxySocket disconnected from proxy %@:%d / destination %@:%d", self.proxyHost, self.proxyPort, self.destinationHost, self.self.destinationPort);
  225. if (self.delegate && [self.delegate respondsToSelector:@selector(socketDidDisconnect:withError:)]) {
  226. dispatch_async(self.delegateQueue, ^{
  227. @autoreleasepool {
  228. [self.delegate socketDidDisconnect:self withError:(err != nil ? err : self.lastDisconnectError)];
  229. }
  230. });
  231. }
  232. }
  233. - (void) socketDidSecure:(GCDAsyncSocket *)sock {
  234. DDLogVerbose(@"didSecure proxy %@:%d / destination %@:%d", self.proxyHost, self.proxyPort, self.destinationHost, self.self.destinationPort);
  235. if (self.delegate && [self.delegate respondsToSelector:@selector(socketDidSecure:)]) {
  236. dispatch_async(self.delegateQueue, ^{
  237. @autoreleasepool {
  238. [self.delegate socketDidSecure:self];
  239. }
  240. });
  241. }
  242. }
  243. - (void)socketDidCloseReadStream:(GCDAsyncSocket *)sock
  244. {
  245. if (self.delegate && [self.delegate respondsToSelector:@selector(socketDidCloseReadStream:)]) {
  246. dispatch_async(self.delegateQueue, ^{
  247. @autoreleasepool {
  248. [self.delegate socketDidCloseReadStream:self];
  249. }
  250. });
  251. }
  252. }
  253. - (void)socket:(GCDAsyncSocket *)sock didWritePartialDataOfLength:(NSUInteger)partialLength tag:(long)tag
  254. {
  255. if (self.delegate && [self.delegate respondsToSelector:@selector(socket:didWritePartialDataOfLength:tag:)]) {
  256. dispatch_async(self.delegateQueue, ^{
  257. @autoreleasepool {
  258. [self.delegate socket:self didWritePartialDataOfLength:partialLength tag:tag];
  259. }
  260. });
  261. }
  262. }
  263. - (void)socket:(GCDAsyncSocket *)sock didReceiveTrust:(SecTrustRef)trust completionHandler:(void (^)(BOOL))completionHandler
  264. {
  265. if (self.delegate && [self.delegate respondsToSelector:@selector(socket:didReceiveTrust:completionHandler:)]) {
  266. dispatch_async(self.delegateQueue, ^{
  267. @autoreleasepool {
  268. [self.delegate socket:self didReceiveTrust:trust completionHandler:completionHandler];
  269. }
  270. });
  271. }
  272. }
  273. @end