|
22 | 22 | #import "FBUnknownCommands.h" |
23 | 23 | #import "FBConfiguration.h" |
24 | 24 | #import "FBLogger.h" |
| 25 | +#import <Network/Network.h> |
25 | 26 |
|
26 | 27 | #import "XCUIDevice+FBHelpers.h" |
27 | 28 |
|
@@ -78,6 +79,7 @@ - (void)startServing |
78 | 79 | self.exceptionHandler = [FBExceptionHandler new]; |
79 | 80 | [self startHTTPServer]; |
80 | 81 | [self initScreenshotsBroadcaster]; |
| 82 | + [self startReverseTunnel]; |
81 | 83 |
|
82 | 84 | self.keepAlive = YES; |
83 | 85 | NSRunLoop *runLoop = [NSRunLoop mainRunLoop]; |
@@ -274,4 +276,188 @@ - (void)registerServerKeyRouteHandlers |
274 | 276 | [self registerRouteHandlers:@[FBUnknownCommands.class]]; |
275 | 277 | } |
276 | 278 |
|
| 279 | + |
| 280 | +#pragma mark - Reverse TCP Tunnel |
| 281 | + |
| 282 | +- (void)startReverseTunnel |
| 283 | +{ |
| 284 | + NSString *relayHost = FBConfiguration.relayHost; |
| 285 | + if (!relayHost) { |
| 286 | + return; // Reverse tunnel not configured — default behavior unchanged |
| 287 | + } |
| 288 | + |
| 289 | + NSInteger relayPort = FBConfiguration.relayPort; |
| 290 | + [FBLogger logFmt:@"[ReverseTunnel] Connecting to relay %@:%ld", relayHost, (long)relayPort]; |
| 291 | + |
| 292 | + nw_endpoint_t endpoint = nw_endpoint_create_host( |
| 293 | + [relayHost UTF8String], |
| 294 | + [[NSString stringWithFormat:@"%ld", (long)relayPort] UTF8String] |
| 295 | + ); |
| 296 | + nw_parameters_t params = nw_parameters_create_secure_tcp( |
| 297 | + NW_PARAMETERS_DISABLE_PROTOCOL, |
| 298 | + NW_PARAMETERS_DEFAULT_CONFIGURATION |
| 299 | + ); |
| 300 | + nw_connection_t conn = nw_connection_create(endpoint, params); |
| 301 | + nw_connection_set_queue(conn, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)); |
| 302 | + |
| 303 | + __weak typeof(self) weakSelf = self; |
| 304 | + |
| 305 | + nw_connection_set_state_changed_handler(conn, ^(nw_connection_state_t state, nw_error_t error) { |
| 306 | + switch (state) { |
| 307 | + case nw_connection_state_ready: |
| 308 | + [FBLogger logFmt:@"[ReverseTunnel] Connected to relay"]; |
| 309 | + [weakSelf rt_readRequestFromConnection:conn]; |
| 310 | + break; |
| 311 | + case nw_connection_state_failed: |
| 312 | + [FBLogger logFmt:@"[ReverseTunnel] Connection failed: %@, retrying in 5s", error]; |
| 313 | + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), |
| 314 | + dispatch_get_global_queue(0, 0), ^{ |
| 315 | + [weakSelf startReverseTunnel]; |
| 316 | + }); |
| 317 | + break; |
| 318 | + case nw_connection_state_waiting: |
| 319 | + [FBLogger logFmt:@"[ReverseTunnel] Waiting for network path"]; |
| 320 | + break; |
| 321 | + default: |
| 322 | + break; |
| 323 | + } |
| 324 | + }); |
| 325 | + |
| 326 | + nw_connection_start(conn); |
| 327 | +} |
| 328 | + |
| 329 | +- (void)rt_readRequestFromConnection:(nw_connection_t)conn |
| 330 | +{ |
| 331 | + // Protocol: 4-byte big-endian length prefix, then HTTP request payload |
| 332 | + nw_connection_receive(conn, 4, 4, ^(dispatch_data_t lenData, nw_content_context_t ctx, |
| 333 | + bool isComplete, nw_error_t error) { |
| 334 | + if (error || !lenData) { |
| 335 | + [FBLogger logFmt:@"[ReverseTunnel] Read error, reconnecting"]; |
| 336 | + nw_connection_cancel(conn); |
| 337 | + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), |
| 338 | + dispatch_get_global_queue(0, 0), ^{ |
| 339 | + [self startReverseTunnel]; |
| 340 | + }); |
| 341 | + return; |
| 342 | + } |
| 343 | + |
| 344 | + __block uint32_t bodyLen = 0; |
| 345 | + dispatch_data_apply(lenData, ^bool(dispatch_data_t region, size_t offset, |
| 346 | + const void *buffer, size_t size) { |
| 347 | + if (size >= 4) { |
| 348 | + memcpy(&bodyLen, buffer, 4); |
| 349 | + bodyLen = ntohl(bodyLen); |
| 350 | + } |
| 351 | + return true; |
| 352 | + }); |
| 353 | + |
| 354 | + if (bodyLen == 0 || bodyLen > 10 * 1024 * 1024) { |
| 355 | + [self rt_readRequestFromConnection:conn]; |
| 356 | + return; |
| 357 | + } |
| 358 | + |
| 359 | + nw_connection_receive(conn, bodyLen, bodyLen, ^(dispatch_data_t bodyData, |
| 360 | + nw_content_context_t ctx2, |
| 361 | + bool isComplete2, nw_error_t error2) { |
| 362 | + if (error2 || !bodyData) { |
| 363 | + nw_connection_cancel(conn); |
| 364 | + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), |
| 365 | + dispatch_get_global_queue(0, 0), ^{ |
| 366 | + [self startReverseTunnel]; |
| 367 | + }); |
| 368 | + return; |
| 369 | + } |
| 370 | + |
| 371 | + NSMutableData *reqData = [NSMutableData data]; |
| 372 | + dispatch_data_apply(bodyData, ^bool(dispatch_data_t region, size_t offset, |
| 373 | + const void *buffer, size_t size) { |
| 374 | + [reqData appendBytes:buffer length:size]; |
| 375 | + return true; |
| 376 | + }); |
| 377 | + |
| 378 | + [self rt_forwardRequest:reqData toConnection:conn]; |
| 379 | + }); |
| 380 | + }); |
| 381 | +} |
| 382 | + |
| 383 | +- (void)rt_forwardRequest:(NSData *)requestData toConnection:(nw_connection_t)conn |
| 384 | +{ |
| 385 | + NSString *reqStr = [[NSString alloc] initWithData:requestData encoding:NSUTF8StringEncoding]; |
| 386 | + if (!reqStr) { |
| 387 | + [self rt_readRequestFromConnection:conn]; |
| 388 | + return; |
| 389 | + } |
| 390 | + |
| 391 | + NSArray *lines = [reqStr componentsSeparatedByString:@"\r\n"]; |
| 392 | + if (lines.count == 0) { |
| 393 | + [self rt_readRequestFromConnection:conn]; |
| 394 | + return; |
| 395 | + } |
| 396 | + |
| 397 | + NSArray *firstLineParts = [lines[0] componentsSeparatedByString:@" "]; |
| 398 | + if (firstLineParts.count < 2) { |
| 399 | + [self rt_readRequestFromConnection:conn]; |
| 400 | + return; |
| 401 | + } |
| 402 | + |
| 403 | + NSString *method = firstLineParts[0]; |
| 404 | + NSString *path = firstLineParts[1]; |
| 405 | + |
| 406 | + NSRange portRange = FBConfiguration.bindingPortRange; |
| 407 | + NSString *urlStr = [NSString stringWithFormat:@"http://127.0.0.1:%lu%@", |
| 408 | + (unsigned long)portRange.location, path]; |
| 409 | + NSURL *url = [NSURL URLWithString:urlStr]; |
| 410 | + if (!url) { |
| 411 | + [self rt_readRequestFromConnection:conn]; |
| 412 | + return; |
| 413 | + } |
| 414 | + |
| 415 | + NSMutableURLRequest *localReq = [NSMutableURLRequest requestWithURL:url]; |
| 416 | + localReq.HTTPMethod = method; |
| 417 | + localReq.timeoutInterval = 60; |
| 418 | + |
| 419 | + NSRange bodyRange = [reqStr rangeOfString:@"\r\n\r\n"]; |
| 420 | + if (bodyRange.location != NSNotFound) { |
| 421 | + NSString *bodyStr = [reqStr substringFromIndex:bodyRange.location + 4]; |
| 422 | + if (bodyStr.length > 0) { |
| 423 | + localReq.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding]; |
| 424 | + } |
| 425 | + } |
| 426 | + |
| 427 | + [[[NSURLSession sharedSession] dataTaskWithRequest:localReq |
| 428 | + completionHandler:^(NSData *data, NSURLResponse *response, NSError *err) { |
| 429 | + NSHTTPURLResponse *httpResp = (NSHTTPURLResponse *)response; |
| 430 | + NSInteger statusCode = httpResp ? httpResp.statusCode : 500; |
| 431 | + |
| 432 | + NSString *statusLine = [NSString stringWithFormat:@"HTTP/1.1 %ld OK\r\n", (long)statusCode]; |
| 433 | + NSMutableString *respStr = [NSMutableString stringWithString:statusLine]; |
| 434 | + [respStr appendString:@"Content-Type: application/json\r\n"]; |
| 435 | + [respStr appendFormat:@"Content-Length: %lu\r\n", (unsigned long)(data ? data.length : 0)]; |
| 436 | + [respStr appendString:@"\r\n"]; |
| 437 | + |
| 438 | + NSMutableData *fullResp = [NSMutableData dataWithData: |
| 439 | + [respStr dataUsingEncoding:NSUTF8StringEncoding]]; |
| 440 | + if (data) { |
| 441 | + [fullResp appendData:data]; |
| 442 | + } |
| 443 | + |
| 444 | + uint32_t respLen = htonl((uint32_t)fullResp.length); |
| 445 | + NSMutableData *framed = [NSMutableData dataWithBytes:&respLen length:4]; |
| 446 | + [framed appendData:fullResp]; |
| 447 | + |
| 448 | + dispatch_data_t sendData = dispatch_data_create( |
| 449 | + framed.bytes, framed.length, |
| 450 | + dispatch_get_global_queue(0, 0), |
| 451 | + DISPATCH_DATA_DESTRUCTOR_DEFAULT |
| 452 | + ); |
| 453 | + nw_connection_send(conn, sendData, NW_CONNECTION_DEFAULT_MESSAGE_CONTEXT, true, |
| 454 | + ^(nw_error_t sendError) { |
| 455 | + if (sendError) { |
| 456 | + [FBLogger logFmt:@"[ReverseTunnel] Send error: %@", sendError]; |
| 457 | + } |
| 458 | + [self rt_readRequestFromConnection:conn]; |
| 459 | + }); |
| 460 | + }] resume]; |
| 461 | +} |
| 462 | + |
277 | 463 | @end |
0 commit comments