Ingen beskrivning

FIRAuthAppDelegateProxy.m 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FIRAuthAppDelegateProxy.h"
  17. #import <GoogleUtilities/GULAppEnvironmentUtil.h>
  18. #import <objc/runtime.h>
  19. NS_ASSUME_NONNULL_BEGIN
  20. /** @var kProxyEnabledBundleKey
  21. @brief The key in application's bundle plist for whether or not proxy should be enabled.
  22. @remarks This key is a shared constant with Analytics and FCM.
  23. */
  24. static NSString *const kProxyEnabledBundleKey = @"FirebaseAppDelegateProxyEnabled";
  25. /** @fn noop
  26. @brief A function that does nothing.
  27. @remarks This is used as the placeholder for unimplemented UApplicationDelegate methods,
  28. because once we added a method there is no way to remove it from the class.
  29. */
  30. #if !OBJC_OLD_DISPATCH_PROTOTYPES
  31. static void noop(void) {
  32. }
  33. #else
  34. static id noop(id object, SEL cmd, ...) {
  35. return nil;
  36. }
  37. #endif
  38. /** @fn isIOS9orLater
  39. @brief Checks whether the iOS version is 9 or later.
  40. @returns Whether the iOS version is 9 or later.
  41. */
  42. static BOOL isIOS9orLater() {
  43. #if defined(__IPHONE_11_0) && (__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_11_0)
  44. if (@available(iOS 9.0, *)) {
  45. return YES;
  46. }
  47. return NO;
  48. #else
  49. // UIApplicationOpenURLOptionsAnnotationKey is only available on iOS 9+.
  50. return &UIApplicationOpenURLOptionsAnnotationKey != NULL;
  51. #endif
  52. }
  53. @implementation FIRAuthAppDelegateProxy {
  54. /** @var _appDelegate
  55. @brief The application delegate whose method is being swizzled.
  56. */
  57. id<UIApplicationDelegate> _appDelegate;
  58. /** @var _orginalImplementationsBySelector
  59. @brief A map from selectors to original implementations that have been swizzled.
  60. */
  61. NSMutableDictionary<NSValue *, NSValue *> *_originalImplementationsBySelector;
  62. /** @var _handlers
  63. @brief The array of weak pointers of `id<FIRAuthAppDelegateHandler>`.
  64. */
  65. NSPointerArray *_handlers;
  66. }
  67. - (nullable instancetype)initWithApplication:(nullable UIApplication *)application {
  68. self = [super init];
  69. if (self) {
  70. id proxyEnabled = [[NSBundle mainBundle] objectForInfoDictionaryKey:kProxyEnabledBundleKey];
  71. if ([proxyEnabled isKindOfClass:[NSNumber class]] && !((NSNumber *)proxyEnabled).boolValue) {
  72. return nil;
  73. }
  74. _appDelegate = application.delegate;
  75. if (![_appDelegate conformsToProtocol:@protocol(UIApplicationDelegate)]) {
  76. return nil;
  77. }
  78. _originalImplementationsBySelector = [[NSMutableDictionary<NSValue *, NSValue *> alloc] init];
  79. _handlers = [[NSPointerArray alloc] initWithOptions:NSPointerFunctionsWeakMemory];
  80. // Swizzle the methods.
  81. __weak FIRAuthAppDelegateProxy *weakSelf = self;
  82. SEL registerDeviceTokenSelector =
  83. @selector(application:didRegisterForRemoteNotificationsWithDeviceToken:);
  84. [self replaceSelector:registerDeviceTokenSelector
  85. withBlock:^(id object, UIApplication* application, NSData *deviceToken) {
  86. [weakSelf object:object
  87. selector:registerDeviceTokenSelector
  88. application:application
  89. didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
  90. }];
  91. SEL failToRegisterRemoteNotificationSelector =
  92. @selector(application:didFailToRegisterForRemoteNotificationsWithError:);
  93. [self replaceSelector:failToRegisterRemoteNotificationSelector
  94. withBlock:^(id object, UIApplication* application, NSError *error) {
  95. [weakSelf object:object
  96. selector:failToRegisterRemoteNotificationSelector
  97. application:application
  98. didFailToRegisterForRemoteNotificationsWithError:error];
  99. }];
  100. SEL receiveNotificationSelector = @selector(application:didReceiveRemoteNotification:);
  101. SEL receiveNotificationWithHandlerSelector =
  102. @selector(application:didReceiveRemoteNotification:fetchCompletionHandler:);
  103. if ([_appDelegate respondsToSelector:receiveNotificationWithHandlerSelector] ||
  104. ![_appDelegate respondsToSelector:receiveNotificationSelector]) {
  105. // Replace the modern selector which is available on iOS 7 and above.
  106. [self replaceSelector:receiveNotificationWithHandlerSelector
  107. withBlock:^(id object, UIApplication *application, NSDictionary *notification,
  108. void (^completionHandler)(UIBackgroundFetchResult)) {
  109. [weakSelf object:object
  110. selector:receiveNotificationWithHandlerSelector
  111. application:application
  112. didReceiveRemoteNotification:notification
  113. fetchCompletionHandler:completionHandler];
  114. }];
  115. } else {
  116. // Replace the deprecated selector because this is the only one that the client app uses.
  117. [self replaceSelector:receiveNotificationSelector
  118. withBlock:^(id object, UIApplication *application, NSDictionary *notification) {
  119. [weakSelf object:object
  120. selector:receiveNotificationSelector
  121. application:application
  122. didReceiveRemoteNotification:notification];
  123. }];
  124. }
  125. SEL openURLOptionsSelector = @selector(application:openURL:options:);
  126. SEL openURLAnnotationSelector = @selector(application:openURL:sourceApplication:annotation:);
  127. SEL handleOpenURLSelector = @selector(application:handleOpenURL:);
  128. if (isIOS9orLater() &&
  129. ([_appDelegate respondsToSelector:openURLOptionsSelector] ||
  130. (![_appDelegate respondsToSelector:openURLAnnotationSelector] &&
  131. ![_appDelegate respondsToSelector:handleOpenURLSelector]))) {
  132. // Replace the modern selector which is avaliable on iOS 9 and above because this is the one
  133. // that the client app uses or the client app doesn't use any of them.
  134. [self replaceSelector:openURLOptionsSelector
  135. withBlock:^BOOL(id object, UIApplication *application, NSURL *url,
  136. NSDictionary *options) {
  137. return [weakSelf object:object
  138. selector:openURLOptionsSelector
  139. application:application
  140. openURL:url
  141. options:options];
  142. }];
  143. } else if ([_appDelegate respondsToSelector:openURLAnnotationSelector] ||
  144. ![_appDelegate respondsToSelector:handleOpenURLSelector]) {
  145. // Replace the longer form of the deprecated selectors on iOS 8 and below because this is the
  146. // one that the client app uses or the client app doesn't use either of the applicable ones.
  147. [self replaceSelector:openURLAnnotationSelector
  148. withBlock:^(id object, UIApplication *application, NSURL *url,
  149. NSString *sourceApplication, id annotation) {
  150. return [weakSelf object:object
  151. selector:openURLAnnotationSelector
  152. application:application
  153. openURL:url
  154. sourceApplication:sourceApplication
  155. annotation:annotation];
  156. }];
  157. } else {
  158. // Replace the shorter form of the deprecated selectors on iOS 8 and below because this is
  159. // the only one that the client app uses.
  160. [self replaceSelector:handleOpenURLSelector
  161. withBlock:^(id object, UIApplication *application, NSURL *url) {
  162. return [weakSelf object:object
  163. selector:handleOpenURLSelector
  164. application:application
  165. handleOpenURL:url];
  166. }];
  167. }
  168. // Reset the application delegate to clear the system cache that indicates whether each of the
  169. // openURL: methods is implemented on the application delegate.
  170. application.delegate = nil;
  171. application.delegate = _appDelegate;
  172. }
  173. return self;
  174. }
  175. - (void)dealloc {
  176. for (NSValue *selector in _originalImplementationsBySelector) {
  177. IMP implementation = _originalImplementationsBySelector[selector].pointerValue;
  178. Method method = class_getInstanceMethod([_appDelegate class], selector.pointerValue);
  179. imp_removeBlock(method_setImplementation(method, implementation));
  180. }
  181. }
  182. - (void)addHandler:(__weak id<FIRAuthAppDelegateHandler>)handler {
  183. @synchronized (_handlers) {
  184. [_handlers addPointer:(__bridge void *)handler];
  185. }
  186. }
  187. + (nullable instancetype)sharedInstance {
  188. static dispatch_once_t onceToken;
  189. static FIRAuthAppDelegateProxy *_Nullable sharedInstance;
  190. // iOS App extensions should not call [UIApplication sharedApplication], even if UIApplication
  191. // responds to it.
  192. static Class applicationClass = nil;
  193. dispatch_once(&onceToken, ^{
  194. if (![GULAppEnvironmentUtil isAppExtension]) {
  195. Class cls = NSClassFromString(@"UIApplication");
  196. if (cls && [cls respondsToSelector:NSSelectorFromString(@"sharedApplication")]) {
  197. applicationClass = cls;
  198. }
  199. }
  200. UIApplication *application = [applicationClass sharedApplication];
  201. sharedInstance = [[self alloc] initWithApplication:application];
  202. });
  203. return sharedInstance;
  204. }
  205. #pragma mark - UIApplicationDelegate proxy methods.
  206. - (void)object:(id)object
  207. selector:(SEL)selector
  208. application:(UIApplication *)application
  209. didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  210. if (object == _appDelegate) {
  211. for (id<FIRAuthAppDelegateHandler> handler in [self handlers]) {
  212. [handler setAPNSToken:deviceToken];
  213. }
  214. }
  215. IMP originalImplementation = [self originalImplementationForSelector:selector];
  216. if (originalImplementation && originalImplementation != &noop) {
  217. typedef void (*Implmentation)(id, SEL, UIApplication*, NSData *);
  218. ((Implmentation)originalImplementation)(object, selector, application, deviceToken);
  219. }
  220. }
  221. - (void)object:(id)object
  222. selector:(SEL)selector
  223. application:(UIApplication *)application
  224. didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  225. if (object == _appDelegate) {
  226. for (id<FIRAuthAppDelegateHandler> handler in [self handlers]) {
  227. [handler handleAPNSTokenError:error];
  228. }
  229. }
  230. IMP originalImplementation = [self originalImplementationForSelector:selector];
  231. if (originalImplementation && originalImplementation != &noop) {
  232. typedef void (*Implmentation)(id, SEL, UIApplication *, NSError *);
  233. ((Implmentation)originalImplementation)(object, selector, application, error);
  234. }
  235. }
  236. - (void)object:(id)object
  237. selector:(SEL)selector
  238. application:(UIApplication *)application
  239. didReceiveRemoteNotification:(NSDictionary *)notification
  240. fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  241. if (object == _appDelegate) {
  242. for (id<FIRAuthAppDelegateHandler> handler in [self handlers]) {
  243. if ([handler canHandleNotification:notification]) {
  244. completionHandler(UIBackgroundFetchResultNoData);
  245. return;
  246. };
  247. }
  248. }
  249. IMP originalImplementation = [self originalImplementationForSelector:selector];
  250. if (originalImplementation && originalImplementation != &noop) {
  251. typedef void (*Implmentation)(id, SEL, UIApplication*, NSDictionary *,
  252. void (^)(UIBackgroundFetchResult));
  253. ((Implmentation)originalImplementation)(object, selector, application, notification,
  254. completionHandler);
  255. }
  256. }
  257. - (void)object:(id)object
  258. selector:(SEL)selector
  259. application:(UIApplication *)application
  260. didReceiveRemoteNotification:(NSDictionary *)notification {
  261. if (object == _appDelegate) {
  262. for (id<FIRAuthAppDelegateHandler> handler in [self handlers]) {
  263. if ([handler canHandleNotification:notification]) {
  264. return;
  265. };
  266. }
  267. }
  268. IMP originalImplementation = [self originalImplementationForSelector:selector];
  269. if (originalImplementation && originalImplementation != &noop) {
  270. typedef void (*Implmentation)(id, SEL, UIApplication*, NSDictionary *);
  271. ((Implmentation)originalImplementation)(object, selector, application, notification);
  272. }
  273. }
  274. - (BOOL)object:(id)object
  275. selector:(SEL)selector
  276. application:(UIApplication *)application
  277. openURL:(NSURL *)url
  278. options:(NSDictionary *)options {
  279. if (object == _appDelegate && [self delegateCanHandleURL:url]) {
  280. return YES;
  281. }
  282. IMP originalImplementation = [self originalImplementationForSelector:selector];
  283. if (originalImplementation && originalImplementation != &noop) {
  284. typedef BOOL (*Implmentation)(id, SEL, UIApplication*, NSURL *, NSDictionary *);
  285. return ((Implmentation)originalImplementation)(object, selector, application, url, options);
  286. }
  287. return NO;
  288. }
  289. - (BOOL)object:(id)object
  290. selector:(SEL)selector
  291. application:(UIApplication *)application
  292. openURL:(NSURL *)url
  293. sourceApplication:(NSString *)sourceApplication
  294. annotation:(id)annotation {
  295. if (object == _appDelegate && [self delegateCanHandleURL:url]) {
  296. return YES;
  297. }
  298. IMP originalImplementation = [self originalImplementationForSelector:selector];
  299. if (originalImplementation && originalImplementation != &noop) {
  300. typedef BOOL (*Implmentation)(id, SEL, UIApplication*, NSURL *, NSString *, id);
  301. return ((Implmentation)originalImplementation)(object, selector, application, url,
  302. sourceApplication, annotation);
  303. }
  304. return NO;
  305. }
  306. - (BOOL)object:(id)object
  307. selector:(SEL)selector
  308. application:(UIApplication *)application
  309. handleOpenURL:(NSURL *)url {
  310. if (object == _appDelegate && [self delegateCanHandleURL:url]) {
  311. return YES;
  312. }
  313. IMP originalImplementation = [self originalImplementationForSelector:selector];
  314. if (originalImplementation && originalImplementation != &noop) {
  315. typedef BOOL (*Implmentation)(id, SEL, UIApplication*, NSURL *);
  316. return ((Implmentation)originalImplementation)(object, selector, application, url);
  317. }
  318. return NO;
  319. }
  320. #pragma mark - Internal Methods
  321. /** @fn delegateCanHandleURL:
  322. @brief Checks for whether any of the delegates can handle the URL.
  323. @param url The URL in question.
  324. @return Whether any of the delegate can handle the URL.
  325. */
  326. - (BOOL)delegateCanHandleURL:(NSURL *)url {
  327. for (id<FIRAuthAppDelegateHandler> handler in [self handlers]) {
  328. if ([handler canHandleURL:url]) {
  329. return YES;
  330. };
  331. }
  332. return NO;
  333. }
  334. /** @fn handlers
  335. @brief Gets the list of handlers from `_handlers` safely.
  336. */
  337. - (NSArray<id<FIRAuthAppDelegateHandler>> *)handlers {
  338. @synchronized (_handlers) {
  339. NSMutableArray<id<FIRAuthAppDelegateHandler>> *liveHandlers =
  340. [[NSMutableArray<id<FIRAuthAppDelegateHandler>> alloc] initWithCapacity:_handlers.count];
  341. for (__weak id<FIRAuthAppDelegateHandler> handler in _handlers) {
  342. if (handler) {
  343. [liveHandlers addObject:handler];
  344. }
  345. }
  346. if (liveHandlers.count < _handlers.count) {
  347. [_handlers compact];
  348. }
  349. return liveHandlers;
  350. }
  351. }
  352. /** @fn replaceSelector:withBlock:
  353. @brief replaces the implementation for a method of `_appDelegate` specified by a selector.
  354. @param selector The selector for the method.
  355. @param block The block as the new implementation of the method.
  356. */
  357. - (void)replaceSelector:(SEL)selector withBlock:(id)block {
  358. Method originalMethod = class_getInstanceMethod([_appDelegate class], selector);
  359. IMP newImplementation = imp_implementationWithBlock(block);
  360. IMP originalImplementation;
  361. if (originalMethod) {
  362. originalImplementation = method_setImplementation(originalMethod, newImplementation) ?: &noop;
  363. } else {
  364. // The original method was not implemented in the class, add it with the new implementation.
  365. struct objc_method_description methodDescription =
  366. protocol_getMethodDescription(@protocol(UIApplicationDelegate), selector, NO, YES);
  367. class_addMethod([_appDelegate class], selector, newImplementation, methodDescription.types);
  368. originalImplementation = &noop;
  369. }
  370. _originalImplementationsBySelector[[NSValue valueWithPointer:selector]] =
  371. [NSValue valueWithPointer:originalImplementation];
  372. }
  373. /** @fn originalImplementationForSelector:
  374. @brief Gets the original implementation for the given selector.
  375. @param selector The selector for the method that has been replaced.
  376. @return The original implementation if there was one.
  377. */
  378. - (IMP)originalImplementationForSelector:(SEL)selector {
  379. return _originalImplementationsBySelector[[NSValue valueWithPointer:selector]].pointerValue;
  380. }
  381. @end
  382. NS_ASSUME_NONNULL_END