|
| 1 | +// Copyright 2025 The Lynx Authors. All rights reserved. |
| 2 | +// Licensed under the Apache License Version 2.0 that can be found in the |
| 3 | +// LICENSE file in the root directory of this source tree. |
| 4 | + |
| 5 | +#import "LocalNetworkPermissionChecker.h" |
| 6 | +#import <Network/Network.h> |
| 7 | +#import <stdatomic.h> |
| 8 | + |
| 9 | +@interface LocalNetworkPermissionChecker () <NSNetServiceDelegate> |
| 10 | +@property(nonatomic, strong) NSNetService *netService; |
| 11 | +@property(nonatomic, copy) LocalNetworkPermissionCompletion completion; |
| 12 | +@property(nonatomic, assign) BOOL didReturnResult; |
| 13 | +@end |
| 14 | + |
| 15 | +@implementation LocalNetworkPermissionChecker |
| 16 | + |
| 17 | +NSString *serviceType; |
| 18 | +static const NSTimeInterval kBonjourWaitTime = 3; |
| 19 | +static const NSTimeInterval kGlobalTimeout = 6; |
| 20 | + |
| 21 | +static _Atomic(int) isChecking = 0; |
| 22 | +static LocalNetworkPermissionChecker *currentChecker = nil; |
| 23 | + |
| 24 | ++ (void)checkPermissionWithCompletion:(LocalNetworkPermissionCompletion)completion { |
| 25 | + int expected = 0; |
| 26 | + // Thread safety |
| 27 | + if (!atomic_compare_exchange_strong(&isChecking, &expected, 1)) { |
| 28 | + NSError *error = [NSError |
| 29 | + errorWithDomain:@"LocalNetworkPermission" |
| 30 | + code:LocalNetworkPermissionNotDetermined |
| 31 | + userInfo:@{ |
| 32 | + NSLocalizedDescriptionKey : @"Another permission check is already in progress" |
| 33 | + }]; |
| 34 | + if (completion) { |
| 35 | + dispatch_async(dispatch_get_main_queue(), ^{ |
| 36 | + completion(NO, error); |
| 37 | + }); |
| 38 | + } |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + // The first check after the APP is installed will pop up a prompt to guide you to open the local |
| 43 | + // network. |
| 44 | + if (![self isInfoPlistProperlyConfigured]) { |
| 45 | + NSError *error = [NSError |
| 46 | + errorWithDomain:@"LocalNetworkPermission" |
| 47 | + code:LocalNetworkPermissionErrorInfoPlistMissing |
| 48 | + userInfo:@{ |
| 49 | + NSLocalizedDescriptionKey : |
| 50 | + @"Info.plist misses NSLocalNetworkUsageDescription or NSBonjourServices" |
| 51 | + }]; |
| 52 | + // reset flag |
| 53 | + atomic_store(&isChecking, 0); |
| 54 | + completion(NO, error); |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + currentChecker = [[LocalNetworkPermissionChecker alloc] init]; |
| 59 | + currentChecker.completion = completion; |
| 60 | + [currentChecker startBonjourCheck]; |
| 61 | + |
| 62 | + // prevent timeout callback operation errors |
| 63 | + LocalNetworkPermissionChecker *capturedChecker = currentChecker; |
| 64 | + |
| 65 | + dispatch_after( |
| 66 | + dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kGlobalTimeout * NSEC_PER_SEC)), |
| 67 | + dispatch_get_main_queue(), ^{ |
| 68 | + // ensure timeout callback only works on the corresponding checker instance |
| 69 | + if (capturedChecker == currentChecker && !capturedChecker.didReturnResult) { |
| 70 | + NSError *timeoutError = [NSError |
| 71 | + errorWithDomain:@"LocalNetworkPermission" |
| 72 | + code:LocalNetworkPermissionErrorTimeoutFallback |
| 73 | + userInfo:@{ |
| 74 | + NSLocalizedDescriptionKey : @"Tiemout: Bonjour and TCP checking no resp" |
| 75 | + }]; |
| 76 | + [capturedChecker returnResult:NO error:timeoutError]; |
| 77 | + } |
| 78 | + }); |
| 79 | +} |
| 80 | + |
| 81 | +#pragma mark - Info.plist checking |
| 82 | + |
| 83 | ++ (BOOL)isInfoPlistProperlyConfigured { |
| 84 | + NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary]; |
| 85 | + |
| 86 | + NSString *desc = infoDict[@"NSLocalNetworkUsageDescription"]; |
| 87 | + if (![desc isKindOfClass:[NSString class]] || desc.length == 0) { |
| 88 | + return NO; |
| 89 | + } |
| 90 | + |
| 91 | + if (@available(iOS 14, *)) { |
| 92 | + NSArray *bonjourServices = infoDict[@"NSBonjourServices"]; |
| 93 | + NSString *requiredService1 = @"_check_local_network_permission._tcp"; |
| 94 | + NSString *requiredService2 = @"_check_local_network_permission._tcp."; |
| 95 | + if ([bonjourServices isKindOfClass:[NSArray class]]) { |
| 96 | + if ([bonjourServices containsObject:requiredService1]) { |
| 97 | + serviceType = requiredService1; |
| 98 | + } else if ([bonjourServices containsObject:requiredService2]) { |
| 99 | + serviceType = requiredService2; |
| 100 | + } else { |
| 101 | + return NO; |
| 102 | + } |
| 103 | + } else { |
| 104 | + return NO; |
| 105 | + } |
| 106 | + |
| 107 | + } else { |
| 108 | + NSLog(@"System before iOS 14, local network permissions were always on"); |
| 109 | + } |
| 110 | + |
| 111 | + return YES; |
| 112 | +} |
| 113 | + |
| 114 | +#pragma mark - Bonjour checking |
| 115 | + |
| 116 | +- (void)startBonjourCheck { |
| 117 | + self.netService = [[NSNetService alloc] initWithDomain:@"local." |
| 118 | + type:serviceType |
| 119 | + name:@"LocalNetCheckService" |
| 120 | + port:12345]; |
| 121 | + self.netService.delegate = self; |
| 122 | + [self.netService publish]; |
| 123 | + |
| 124 | + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kBonjourWaitTime * NSEC_PER_SEC)), |
| 125 | + dispatch_get_main_queue(), ^{ |
| 126 | + if (!self.didReturnResult) { |
| 127 | + [self.netService stop]; |
| 128 | + // Bonjour no resp, fallback to TCP checking |
| 129 | + [self fallbackTCPCheck]; |
| 130 | + } |
| 131 | + }); |
| 132 | +} |
| 133 | + |
| 134 | +- (void)netServiceDidPublish:(NSNetService *)sender { |
| 135 | + [self.netService stop]; |
| 136 | + [self returnResult:YES error:nil]; |
| 137 | +} |
| 138 | + |
| 139 | +- (void)netService:(NSNetService *)sender |
| 140 | + didNotPublish:(NSDictionary<NSString *, NSNumber *> *)errorDict { |
| 141 | + [self.netService stop]; |
| 142 | + |
| 143 | + // Bonjour publish failed,try TCP checking |
| 144 | + [self fallbackTCPCheck]; |
| 145 | +} |
| 146 | + |
| 147 | +#pragma mark - TCP checking |
| 148 | + |
| 149 | +- (void)fallbackTCPCheck { |
| 150 | + nw_endpoint_t endpoint = nw_endpoint_create_host("192.168.1.1", "12345"); |
| 151 | + nw_parameters_t parameters = nw_parameters_create_secure_tcp(NW_PARAMETERS_DEFAULT_CONFIGURATION, |
| 152 | + NW_PARAMETERS_DEFAULT_CONFIGURATION); |
| 153 | + nw_connection_t connection = nw_connection_create(endpoint, parameters); |
| 154 | + nw_connection_set_queue(connection, dispatch_get_main_queue()); |
| 155 | + |
| 156 | + nw_connection_set_state_changed_handler( |
| 157 | + connection, ^(nw_connection_state_t state, nw_error_t error) { |
| 158 | + if (state == nw_connection_state_ready) { |
| 159 | + nw_connection_cancel(connection); |
| 160 | + [self returnResult:YES error:nil]; |
| 161 | + } else if (state == nw_connection_state_failed) { |
| 162 | + nw_connection_cancel(connection); |
| 163 | + NSError *tcpError = |
| 164 | + [NSError errorWithDomain:@"LocalNetworkPermission" |
| 165 | + code:LocalNetworkPermissionErrorTCPConnectionFailed |
| 166 | + userInfo:@{ |
| 167 | + NSLocalizedDescriptionKey : |
| 168 | + @"TCP connection failed, LocalNetworking has been denied" |
| 169 | + }]; |
| 170 | + [self returnResult:NO error:tcpError]; |
| 171 | + } |
| 172 | + }); |
| 173 | + |
| 174 | + nw_connection_start(connection); |
| 175 | +} |
| 176 | + |
| 177 | +#pragma mark - Result |
| 178 | + |
| 179 | +- (void)returnResult:(BOOL)granted error:(NSError *)error { |
| 180 | + if (self.didReturnResult) return; |
| 181 | + self.didReturnResult = YES; |
| 182 | + |
| 183 | + if (self.completion) { |
| 184 | + self.completion(granted, error); |
| 185 | + self.completion = nil; |
| 186 | + } |
| 187 | + |
| 188 | + // reset flag |
| 189 | + atomic_store(&isChecking, 0); |
| 190 | + currentChecker = nil; |
| 191 | +} |
| 192 | + |
| 193 | +@end |
0 commit comments