FLEXNetworkObserver.m 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  1. //
  2. // FLEXNetworkObserver.m
  3. // Derived from:
  4. //
  5. // PDAFNetworkDomainController.m
  6. // PonyDebugger
  7. //
  8. // Created by Mike Lewis on 2/27/12.
  9. //
  10. // Licensed to Square, Inc. under one or more contributor license agreements.
  11. // See the LICENSE file distributed with this work for the terms under
  12. // which Square, Inc. licenses this file to you.
  13. //
  14. #import "FLEXNetworkObserver.h"
  15. #import "FLEXNetworkRecorder.h"
  16. #import <objc/runtime.h>
  17. #import <objc/message.h>
  18. #import <dispatch/queue.h>
  19. NSString *const kFLEXNetworkObserverEnabledStateChangedNotification = @"kFLEXNetworkObserverEnabledStateChangedNotification";
  20. static NSString *const kFLEXNetworkObserverEnabledDefaultsKey = @"com.flex.FLEXNetworkObserver.enableOnLaunch";
  21. typedef void (^NSURLSessionAsyncCompletion)(id fileURLOrData, NSURLResponse *response, NSError *error);
  22. @interface FLEXInternalRequestState : NSObject
  23. @property (nonatomic, copy) NSURLRequest *request;
  24. @property (nonatomic, strong) NSMutableData *dataAccumulator;
  25. @end
  26. @implementation FLEXInternalRequestState
  27. @end
  28. @interface FLEXNetworkObserver (NSURLConnectionHelpers)
  29. - (void)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response delegate:(id <NSURLConnectionDelegate>)delegate;
  30. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response delegate:(id <NSURLConnectionDelegate>)delegate;
  31. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data delegate:(id <NSURLConnectionDelegate>)delegate;
  32. - (void)connectionDidFinishLoading:(NSURLConnection *)connection delegate:(id <NSURLConnectionDelegate>)delegate;
  33. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error delegate:(id <NSURLConnectionDelegate>)delegate;
  34. - (void)connectionWillCancel:(NSURLConnection *)connection;
  35. @end
  36. @interface FLEXNetworkObserver (NSURLSessionTaskHelpers)
  37. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler delegate:(id <NSURLSessionDelegate>)delegate;
  38. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler delegate:(id <NSURLSessionDelegate>)delegate;
  39. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data delegate:(id <NSURLSessionDelegate>)delegate;
  40. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
  41. didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask delegate:(id <NSURLSessionDelegate>)delegate;
  42. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error delegate:(id <NSURLSessionDelegate>)delegate;
  43. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite delegate:(id <NSURLSessionDelegate>)delegate;
  44. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location data:(NSData *)data delegate:(id <NSURLSessionDelegate>)delegate;
  45. - (void)URLSessionTaskWillResume:(NSURLSessionTask *)task;
  46. @end
  47. @interface FLEXNetworkObserver ()
  48. @property (nonatomic, strong) NSMutableDictionary *requestStatesForRequestIDs;
  49. @property (nonatomic, strong) dispatch_queue_t queue;
  50. @end
  51. @implementation FLEXNetworkObserver
  52. #pragma mark - Public Methods
  53. + (void)setEnabled:(BOOL)enabled
  54. {
  55. BOOL previouslyEnabled = [self isEnabled];
  56. [[NSUserDefaults standardUserDefaults] setBool:enabled forKey:kFLEXNetworkObserverEnabledDefaultsKey];
  57. if (enabled) {
  58. // Inject if needed. This injection is protected with a dispatch_once, so we're ok calling it multiple times.
  59. // By doing the injection lazily, we keep the impact of the tool lower when this feature isn't enabled.
  60. [self injectIntoAllNSURLConnectionDelegateClasses];
  61. }
  62. if (previouslyEnabled != enabled) {
  63. [[NSNotificationCenter defaultCenter] postNotificationName:kFLEXNetworkObserverEnabledStateChangedNotification object:self];
  64. }
  65. }
  66. + (BOOL)isEnabled
  67. {
  68. return [[[NSUserDefaults standardUserDefaults] objectForKey:kFLEXNetworkObserverEnabledDefaultsKey] boolValue];
  69. }
  70. + (void)load
  71. {
  72. // We don't want to do the swizzling from +load because not all the classes may be loaded at this point.
  73. dispatch_async(dispatch_get_main_queue(), ^{
  74. if ([self isEnabled]) {
  75. [self injectIntoAllNSURLConnectionDelegateClasses];
  76. }
  77. });
  78. }
  79. #pragma mark - Statics
  80. + (instancetype)sharedObserver
  81. {
  82. static FLEXNetworkObserver *sharedObserver = nil;
  83. static dispatch_once_t onceToken;
  84. dispatch_once(&onceToken, ^{
  85. sharedObserver = [[[self class] alloc] init];
  86. });
  87. return sharedObserver;
  88. }
  89. + (NSString *)nextRequestID
  90. {
  91. return [[NSUUID UUID] UUIDString];
  92. }
  93. #pragma mark Delegate Injection Convenience Methods
  94. + (SEL)swizzledSelectorForSelector:(SEL)selector
  95. {
  96. return NSSelectorFromString([NSString stringWithFormat:@"_flex_swizzle_%x_%@", arc4random(), NSStringFromSelector(selector)]);
  97. }
  98. /// All swizzled delegate methods should make use of this guard.
  99. /// This will prevent duplicated sniffing when the original implementation calls up to a superclass implementation which we've also swizzled.
  100. /// The superclass implementation (and implementations in classes above that) will be executed without inteference if called from the original implementation.
  101. + (void)sniffWithoutDuplicationForObject:(NSObject *)object selector:(SEL)selector sniffingBlock:(void (^)(void))sniffingBlock originalImplementationBlock:(void (^)(void))originalImplementationBlock
  102. {
  103. // If we don't have an object to detect nested calls on, just run the original implmentation and bail.
  104. // This case can happen if someone besides the URL loading system calls the delegate methods directly.
  105. // See https://github.com/Flipboard/FLEX/issues/61 for an example.
  106. if (!object) {
  107. originalImplementationBlock();
  108. return;
  109. }
  110. const void *key = selector;
  111. // Don't run the sniffing block if we're inside a nested call
  112. if (!objc_getAssociatedObject(object, key)) {
  113. sniffingBlock();
  114. }
  115. // Mark that we're calling through to the original so we can detect nested calls
  116. objc_setAssociatedObject(object, key, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  117. originalImplementationBlock();
  118. objc_setAssociatedObject(object, key, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  119. }
  120. + (BOOL)instanceRespondsButDoesNotImplementSelector:(SEL)selector class:(Class)cls
  121. {
  122. if ([cls instancesRespondToSelector:selector]) {
  123. unsigned int numMethods = 0;
  124. Method *methods = class_copyMethodList(cls, &numMethods);
  125. BOOL implementsSelector = NO;
  126. for (int index = 0; index < numMethods; index++) {
  127. SEL methodSelector = method_getName(methods[index]);
  128. if (selector == methodSelector) {
  129. implementsSelector = YES;
  130. break;
  131. }
  132. }
  133. free(methods);
  134. if (!implementsSelector) {
  135. return YES;
  136. }
  137. }
  138. return NO;
  139. }
  140. + (void)replaceImplementationOfKnownSelector:(SEL)originalSelector onClass:(Class)class withBlock:(id)block swizzledSelector:(SEL)swizzledSelector
  141. {
  142. // This method is only intended for swizzling methods that are know to exist on the class.
  143. // Bail if that isn't the case.
  144. Method originalMethod = class_getInstanceMethod(class, originalSelector);
  145. if (!originalMethod) {
  146. return;
  147. }
  148. IMP implementation = imp_implementationWithBlock(block);
  149. class_addMethod(class, swizzledSelector, implementation, method_getTypeEncoding(originalMethod));
  150. Method newMethod = class_getInstanceMethod(class, swizzledSelector);
  151. method_exchangeImplementations(originalMethod, newMethod);
  152. }
  153. + (void)replaceImplementationOfSelector:(SEL)selector withSelector:(SEL)swizzledSelector forClass:(Class)cls withMethodDescription:(struct objc_method_description)methodDescription implementationBlock:(id)implementationBlock undefinedBlock:(id)undefinedBlock
  154. {
  155. if ([self instanceRespondsButDoesNotImplementSelector:selector class:cls]) {
  156. return;
  157. }
  158. IMP implementation = imp_implementationWithBlock((id)([cls instancesRespondToSelector:selector] ? implementationBlock : undefinedBlock));
  159. Method oldMethod = class_getInstanceMethod(cls, selector);
  160. if (oldMethod) {
  161. class_addMethod(cls, swizzledSelector, implementation, methodDescription.types);
  162. Method newMethod = class_getInstanceMethod(cls, swizzledSelector);
  163. method_exchangeImplementations(oldMethod, newMethod);
  164. } else {
  165. class_addMethod(cls, selector, implementation, methodDescription.types);
  166. }
  167. }
  168. #pragma mark - Delegate Injection
  169. + (void)injectIntoAllNSURLConnectionDelegateClasses
  170. {
  171. // Only allow swizzling once.
  172. static dispatch_once_t onceToken;
  173. dispatch_once(&onceToken, ^{
  174. // Swizzle any classes that implement one of these selectors.
  175. const SEL selectors[] = {
  176. @selector(connectionDidFinishLoading:),
  177. @selector(connection:willSendRequest:redirectResponse:),
  178. @selector(connection:didReceiveResponse:),
  179. @selector(connection:didReceiveData:),
  180. @selector(connection:didFailWithError:),
  181. @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:),
  182. @selector(URLSession:dataTask:didReceiveData:),
  183. @selector(URLSession:dataTask:didReceiveResponse:completionHandler:),
  184. @selector(URLSession:task:didCompleteWithError:),
  185. @selector(URLSession:dataTask:didBecomeDownloadTask:delegate:),
  186. @selector(URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:),
  187. @selector(URLSession:downloadTask:didFinishDownloadingToURL:)
  188. };
  189. const int numSelectors = sizeof(selectors) / sizeof(SEL);
  190. Class *classes = NULL;
  191. int numClasses = objc_getClassList(NULL, 0);
  192. if (numClasses > 0) {
  193. classes = (__unsafe_unretained Class *)malloc(sizeof(Class) * numClasses);
  194. numClasses = objc_getClassList(classes, numClasses);
  195. for (NSInteger classIndex = 0; classIndex < numClasses; ++classIndex) {
  196. Class class = classes[classIndex];
  197. if (class == [FLEXNetworkObserver class]) {
  198. continue;
  199. }
  200. // Use the runtime API rather than the methods on NSObject to avoid sending messages to
  201. // classes we're not interested in swizzling. Otherwise we hit +initialize on all classes.
  202. // NOTE: calling class_getInstanceMethod() DOES send +initialize to the class. That's why we iterate through the method list.
  203. unsigned int methodCount = 0;
  204. Method *methods = class_copyMethodList(class, &methodCount);
  205. BOOL matchingSelectorFound = NO;
  206. for (unsigned int methodIndex = 0; methodIndex < methodCount; methodIndex++) {
  207. for (int selectorIndex = 0; selectorIndex < numSelectors; ++selectorIndex) {
  208. if (method_getName(methods[methodIndex]) == selectors[selectorIndex]) {
  209. [self injectIntoDelegateClass:class];
  210. matchingSelectorFound = YES;
  211. break;
  212. }
  213. }
  214. if (matchingSelectorFound) {
  215. break;
  216. }
  217. }
  218. free(methods);
  219. }
  220. free(classes);
  221. }
  222. [self injectIntoNSURLConnectionCancel];
  223. [self injectIntoNSURLSessionTaskResume];
  224. [self injectIntoNSURLConnectionAsynchronousClassMethod];
  225. [self injectIntoNSURLConnectionSynchronousClassMethod];
  226. [self injectIntoNSURLSessionAsyncDataAndDownloadTaskMethods];
  227. [self injectIntoNSURLSessionAsyncUploadTaskMethods];
  228. });
  229. }
  230. + (void)injectIntoDelegateClass:(Class)cls
  231. {
  232. // Connections
  233. [self injectWillSendRequestIntoDelegateClass:cls];
  234. [self injectDidReceiveDataIntoDelegateClass:cls];
  235. [self injectDidReceiveResponseIntoDelegateClass:cls];
  236. [self injectDidFinishLoadingIntoDelegateClass:cls];
  237. [self injectDidFailWithErrorIntoDelegateClass:cls];
  238. // Sessions
  239. [self injectTaskWillPerformHTTPRedirectionIntoDelegateClass:cls];
  240. [self injectTaskDidReceiveDataIntoDelegateClass:cls];
  241. [self injectTaskDidReceiveResponseIntoDelegateClass:cls];
  242. [self injectTaskDidCompleteWithErrorIntoDelegateClass:cls];
  243. [self injectRespondsToSelectorIntoDelegateClass:cls];
  244. // Data tasks
  245. [self injectDataTaskDidBecomeDownloadTaskIntoDelegateClass:cls];
  246. // Download tasks
  247. [self injectDownloadTaskDidWriteDataIntoDelegateClass:cls];
  248. [self injectDownloadTaskDidFinishDownloadingIntoDelegateClass:cls];
  249. }
  250. + (void)injectIntoNSURLConnectionCancel
  251. {
  252. static dispatch_once_t onceToken;
  253. dispatch_once(&onceToken, ^{
  254. Class class = [NSURLConnection class];
  255. SEL selector = @selector(cancel);
  256. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  257. Method originalCancel = class_getInstanceMethod(class, selector);
  258. void (^swizzleBlock)(NSURLConnection *) = ^(NSURLConnection *slf) {
  259. [[FLEXNetworkObserver sharedObserver] connectionWillCancel:slf];
  260. ((void(*)(id, SEL))objc_msgSend)(slf, swizzledSelector);
  261. };
  262. IMP implementation = imp_implementationWithBlock(swizzleBlock);
  263. class_addMethod(class, swizzledSelector, implementation, method_getTypeEncoding(originalCancel));
  264. Method newCancel = class_getInstanceMethod(class, swizzledSelector);
  265. method_exchangeImplementations(originalCancel, newCancel);
  266. });
  267. }
  268. + (void)injectIntoNSURLSessionTaskResume
  269. {
  270. static dispatch_once_t onceToken;
  271. dispatch_once(&onceToken, ^{
  272. // In iOS 7 resume lives in __NSCFLocalSessionTask
  273. // In iOS 8 resume lives in NSURLSessionTask
  274. // In iOS 9 resume lives in __NSCFURLSessionTask
  275. Class class = Nil;
  276. if (![[NSProcessInfo processInfo] respondsToSelector:@selector(operatingSystemVersion)]) {
  277. class = NSClassFromString([@[@"__", @"NSC", @"FLocalS", @"ession", @"Task"] componentsJoinedByString:@""]);
  278. } else if ([[NSProcessInfo processInfo] operatingSystemVersion].majorVersion < 9) {
  279. class = [NSURLSessionTask class];
  280. } else {
  281. class = NSClassFromString([@[@"__", @"NSC", @"FURLS", @"ession", @"Task"] componentsJoinedByString:@""]);
  282. }
  283. SEL selector = @selector(resume);
  284. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  285. Method originalResume = class_getInstanceMethod(class, selector);
  286. void (^swizzleBlock)(NSURLSessionTask *) = ^(NSURLSessionTask *slf) {
  287. [[FLEXNetworkObserver sharedObserver] URLSessionTaskWillResume:slf];
  288. ((void(*)(id, SEL))objc_msgSend)(slf, swizzledSelector);
  289. };
  290. IMP implementation = imp_implementationWithBlock(swizzleBlock);
  291. class_addMethod(class, swizzledSelector, implementation, method_getTypeEncoding(originalResume));
  292. Method newResume = class_getInstanceMethod(class, swizzledSelector);
  293. method_exchangeImplementations(originalResume, newResume);
  294. });
  295. }
  296. + (void)injectIntoNSURLConnectionAsynchronousClassMethod
  297. {
  298. static dispatch_once_t onceToken;
  299. dispatch_once(&onceToken, ^{
  300. Class class = objc_getMetaClass(class_getName([NSURLConnection class]));
  301. SEL selector = @selector(sendAsynchronousRequest:queue:completionHandler:);
  302. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  303. typedef void (^NSURLConnectionAsyncCompletion)(NSURLResponse* response, NSData* data, NSError* connectionError);
  304. void (^asyncSwizzleBlock)(Class, NSURLRequest *, NSOperationQueue *, NSURLConnectionAsyncCompletion) = ^(Class slf, NSURLRequest *request, NSOperationQueue *queue, NSURLConnectionAsyncCompletion completion) {
  305. if ([FLEXNetworkObserver isEnabled]) {
  306. NSString *requestID = [self nextRequestID];
  307. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:request redirectResponse:nil];
  308. NSString *mechanism = [self mechansimFromClassMethod:selector onClass:class];
  309. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:mechanism forRequestID:requestID];
  310. NSURLConnectionAsyncCompletion completionWrapper = ^(NSURLResponse *response, NSData *data, NSError *connectionError) {
  311. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:response];
  312. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:[data length]];
  313. if (connectionError) {
  314. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:connectionError];
  315. } else {
  316. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:data];
  317. }
  318. // Call through to the original completion handler
  319. if (completion) {
  320. completion(response, data, connectionError);
  321. }
  322. };
  323. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, request, queue, completionWrapper);
  324. } else {
  325. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, request, queue, completion);
  326. }
  327. };
  328. [self replaceImplementationOfKnownSelector:selector onClass:class withBlock:asyncSwizzleBlock swizzledSelector:swizzledSelector];
  329. });
  330. }
  331. + (void)injectIntoNSURLConnectionSynchronousClassMethod
  332. {
  333. static dispatch_once_t onceToken;
  334. dispatch_once(&onceToken, ^{
  335. Class class = objc_getMetaClass(class_getName([NSURLConnection class]));
  336. SEL selector = @selector(sendSynchronousRequest:returningResponse:error:);
  337. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  338. NSData *(^syncSwizzleBlock)(Class, NSURLRequest *, NSURLResponse **, NSError **) = ^NSData *(Class slf, NSURLRequest *request, NSURLResponse **response, NSError **error) {
  339. NSData *data = nil;
  340. if ([FLEXNetworkObserver isEnabled]) {
  341. NSString *requestID = [self nextRequestID];
  342. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:request redirectResponse:nil];
  343. NSString *mechanism = [self mechansimFromClassMethod:selector onClass:class];
  344. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:mechanism forRequestID:requestID];
  345. NSError *temporaryError = nil;
  346. NSURLResponse *temporaryResponse = nil;
  347. data = ((id(*)(id, SEL, id, NSURLResponse **, NSError **))objc_msgSend)(slf, swizzledSelector, request, &temporaryResponse, &temporaryError);
  348. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:temporaryResponse];
  349. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:[data length]];
  350. if (temporaryError) {
  351. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:temporaryError];
  352. } else {
  353. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:data];
  354. }
  355. if (error) {
  356. *error = temporaryError;
  357. }
  358. if (response) {
  359. *response = temporaryResponse;
  360. }
  361. } else {
  362. data = ((id(*)(id, SEL, id, NSURLResponse **, NSError **))objc_msgSend)(slf, swizzledSelector, request, response, error);
  363. }
  364. return data;
  365. };
  366. [self replaceImplementationOfKnownSelector:selector onClass:class withBlock:syncSwizzleBlock swizzledSelector:swizzledSelector];
  367. });
  368. }
  369. + (void)injectIntoNSURLSessionAsyncDataAndDownloadTaskMethods
  370. {
  371. static dispatch_once_t onceToken;
  372. dispatch_once(&onceToken, ^{
  373. Class class = [NSURLSession class];
  374. // The method signatures here are close enough that we can use the same logic to inject into all of them.
  375. const SEL selectors[] = {
  376. @selector(dataTaskWithRequest:completionHandler:),
  377. @selector(dataTaskWithURL:completionHandler:),
  378. @selector(downloadTaskWithRequest:completionHandler:),
  379. @selector(downloadTaskWithResumeData:completionHandler:),
  380. @selector(downloadTaskWithURL:completionHandler:)
  381. };
  382. const int numSelectors = sizeof(selectors) / sizeof(SEL);
  383. for (int selectorIndex = 0; selectorIndex < numSelectors; selectorIndex++) {
  384. SEL selector = selectors[selectorIndex];
  385. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  386. if ([self instanceRespondsButDoesNotImplementSelector:selector class:class]) {
  387. // iOS 7 does not implement these methods on NSURLSession. We actually want to
  388. // swizzle __NSCFURLSession, which we can get from the class of the shared session
  389. class = [[NSURLSession sharedSession] class];
  390. }
  391. NSURLSessionTask *(^asyncDataOrDownloadSwizzleBlock)(Class, id, NSURLSessionAsyncCompletion) = ^NSURLSessionTask *(Class slf, id argument, NSURLSessionAsyncCompletion completion) {
  392. NSURLSessionTask *task = nil;
  393. // If completion block was not provided sender expect to receive delegated methods or does not
  394. // interested in callback at all. In this case we should just call original method implementation
  395. // with nil completion block.
  396. if ([FLEXNetworkObserver isEnabled] && completion) {
  397. NSString *requestID = [self nextRequestID];
  398. NSString *mechanism = [self mechansimFromClassMethod:selector onClass:class];
  399. NSURLSessionAsyncCompletion completionWrapper = [self asyncCompletionWrapperForRequestID:requestID mechanism:mechanism completion:completion];
  400. task = ((id(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, argument, completionWrapper);
  401. [self setRequestID:requestID forConnectionOrTask:task];
  402. } else {
  403. task = ((id(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, argument, completion);
  404. }
  405. return task;
  406. };
  407. [self replaceImplementationOfKnownSelector:selector onClass:class withBlock:asyncDataOrDownloadSwizzleBlock swizzledSelector:swizzledSelector];
  408. }
  409. });
  410. }
  411. + (void)injectIntoNSURLSessionAsyncUploadTaskMethods
  412. {
  413. static dispatch_once_t onceToken;
  414. dispatch_once(&onceToken, ^{
  415. Class class = [NSURLSession class];
  416. // The method signatures here are close enough that we can use the same logic to inject into both of them.
  417. // Note that they have 3 arguments, so we can't easily combine with the data and download method above.
  418. const SEL selectors[] = {
  419. @selector(uploadTaskWithRequest:fromData:completionHandler:),
  420. @selector(uploadTaskWithRequest:fromFile:completionHandler:)
  421. };
  422. const int numSelectors = sizeof(selectors) / sizeof(SEL);
  423. for (int selectorIndex = 0; selectorIndex < numSelectors; selectorIndex++) {
  424. SEL selector = selectors[selectorIndex];
  425. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  426. if ([self instanceRespondsButDoesNotImplementSelector:selector class:class]) {
  427. // iOS 7 does not implement these methods on NSURLSession. We actually want to
  428. // swizzle __NSCFURLSession, which we can get from the class of the shared session
  429. class = [[NSURLSession sharedSession] class];
  430. }
  431. NSURLSessionUploadTask *(^asyncUploadTaskSwizzleBlock)(Class, NSURLRequest *, id, NSURLSessionAsyncCompletion) = ^NSURLSessionUploadTask *(Class slf, NSURLRequest *request, id argument, NSURLSessionAsyncCompletion completion) {
  432. NSURLSessionUploadTask *task = nil;
  433. if ([FLEXNetworkObserver isEnabled]) {
  434. NSString *requestID = [self nextRequestID];
  435. NSString *mechanism = [self mechansimFromClassMethod:selector onClass:class];
  436. NSURLSessionAsyncCompletion completionWrapper = [self asyncCompletionWrapperForRequestID:requestID mechanism:mechanism completion:completion];
  437. task = ((id(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, request, argument, completionWrapper);
  438. [self setRequestID:requestID forConnectionOrTask:task];
  439. } else {
  440. task = ((id(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, request, argument, completion);
  441. }
  442. return task;
  443. };
  444. [self replaceImplementationOfKnownSelector:selector onClass:class withBlock:asyncUploadTaskSwizzleBlock swizzledSelector:swizzledSelector];
  445. }
  446. });
  447. }
  448. + (NSString *)mechansimFromClassMethod:(SEL)selector onClass:(Class)class
  449. {
  450. return [NSString stringWithFormat:@"+[%@ %@]", NSStringFromClass(class), NSStringFromSelector(selector)];
  451. }
  452. + (NSURLSessionAsyncCompletion)asyncCompletionWrapperForRequestID:(NSString *)requestID mechanism:(NSString *)mechanism completion:(NSURLSessionAsyncCompletion)completion
  453. {
  454. NSURLSessionAsyncCompletion completionWrapper = ^(id fileURLOrData, NSURLResponse *response, NSError *error) {
  455. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:mechanism forRequestID:requestID];
  456. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:response];
  457. NSData *data = nil;
  458. if ([fileURLOrData isKindOfClass:[NSURL class]]) {
  459. data = [NSData dataWithContentsOfURL:fileURLOrData];
  460. } else if ([fileURLOrData isKindOfClass:[NSData class]]) {
  461. data = fileURLOrData;
  462. }
  463. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:[data length]];
  464. if (error) {
  465. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:error];
  466. } else {
  467. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:data];
  468. }
  469. // Call through to the original completion handler
  470. if (completion) {
  471. completion(fileURLOrData, response, error);
  472. }
  473. };
  474. return completionWrapper;
  475. }
  476. + (void)injectWillSendRequestIntoDelegateClass:(Class)cls
  477. {
  478. SEL selector = @selector(connection:willSendRequest:redirectResponse:);
  479. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  480. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  481. if (!protocol) {
  482. protocol = @protocol(NSURLConnectionDelegate);
  483. }
  484. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  485. typedef NSURLRequest *(^NSURLConnectionWillSendRequestBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response);
  486. NSURLConnectionWillSendRequestBlock undefinedBlock = ^NSURLRequest *(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) {
  487. [[FLEXNetworkObserver sharedObserver] connection:connection willSendRequest:request redirectResponse:response delegate:slf];
  488. return request;
  489. };
  490. NSURLConnectionWillSendRequestBlock implementationBlock = ^NSURLRequest *(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) {
  491. __block NSURLRequest *returnValue = nil;
  492. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  493. undefinedBlock(slf, connection, request, response);
  494. } originalImplementationBlock:^{
  495. returnValue = ((id(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, connection, request, response);
  496. }];
  497. return returnValue;
  498. };
  499. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  500. }
  501. + (void)injectDidReceiveResponseIntoDelegateClass:(Class)cls
  502. {
  503. SEL selector = @selector(connection:didReceiveResponse:);
  504. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  505. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  506. if (!protocol) {
  507. protocol = @protocol(NSURLConnectionDelegate);
  508. }
  509. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  510. typedef void (^NSURLConnectionDidReceiveResponseBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response);
  511. NSURLConnectionDidReceiveResponseBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response) {
  512. [[FLEXNetworkObserver sharedObserver] connection:connection didReceiveResponse:response delegate:slf];
  513. };
  514. NSURLConnectionDidReceiveResponseBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response) {
  515. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  516. undefinedBlock(slf, connection, response);
  517. } originalImplementationBlock:^{
  518. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, response);
  519. }];
  520. };
  521. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  522. }
  523. + (void)injectDidReceiveDataIntoDelegateClass:(Class)cls
  524. {
  525. SEL selector = @selector(connection:didReceiveData:);
  526. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  527. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  528. if (!protocol) {
  529. protocol = @protocol(NSURLConnectionDelegate);
  530. }
  531. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  532. typedef void (^NSURLConnectionDidReceiveDataBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data);
  533. NSURLConnectionDidReceiveDataBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data) {
  534. [[FLEXNetworkObserver sharedObserver] connection:connection didReceiveData:data delegate:slf];
  535. };
  536. NSURLConnectionDidReceiveDataBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data) {
  537. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  538. undefinedBlock(slf, connection, data);
  539. } originalImplementationBlock:^{
  540. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, data);
  541. }];
  542. };
  543. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  544. }
  545. + (void)injectDidFinishLoadingIntoDelegateClass:(Class)cls
  546. {
  547. SEL selector = @selector(connectionDidFinishLoading:);
  548. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  549. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  550. if (!protocol) {
  551. protocol = @protocol(NSURLConnectionDelegate);
  552. }
  553. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  554. typedef void (^NSURLConnectionDidFinishLoadingBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection);
  555. NSURLConnectionDidFinishLoadingBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection) {
  556. [[FLEXNetworkObserver sharedObserver] connectionDidFinishLoading:connection delegate:slf];
  557. };
  558. NSURLConnectionDidFinishLoadingBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection) {
  559. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  560. undefinedBlock(slf, connection);
  561. } originalImplementationBlock:^{
  562. ((void(*)(id, SEL, id))objc_msgSend)(slf, swizzledSelector, connection);
  563. }];
  564. };
  565. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  566. }
  567. + (void)injectDidFailWithErrorIntoDelegateClass:(Class)cls
  568. {
  569. SEL selector = @selector(connection:didFailWithError:);
  570. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  571. Protocol *protocol = @protocol(NSURLConnectionDelegate);
  572. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  573. typedef void (^NSURLConnectionDidFailWithErrorBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error);
  574. NSURLConnectionDidFailWithErrorBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error) {
  575. [[FLEXNetworkObserver sharedObserver] connection:connection didFailWithError:error delegate:slf];
  576. };
  577. NSURLConnectionDidFailWithErrorBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error) {
  578. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  579. undefinedBlock(slf, connection, error);
  580. } originalImplementationBlock:^{
  581. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, error);
  582. }];
  583. };
  584. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  585. }
  586. + (void)injectTaskWillPerformHTTPRedirectionIntoDelegateClass:(Class)cls
  587. {
  588. SEL selector = @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:);
  589. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  590. Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  591. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  592. typedef void (^NSURLSessionWillPerformHTTPRedirectionBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *));
  593. NSURLSessionWillPerformHTTPRedirectionBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *)) {
  594. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task willPerformHTTPRedirection:response newRequest:newRequest completionHandler:completionHandler delegate:slf];
  595. };
  596. NSURLSessionWillPerformHTTPRedirectionBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *)) {
  597. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  598. undefinedBlock(slf, session, task, response, newRequest, completionHandler);
  599. } originalImplementationBlock:^{
  600. ((id(*)(id, SEL, id, id, id, id, void(^)()))objc_msgSend)(slf, swizzledSelector, session, task, response, newRequest, completionHandler);
  601. }];
  602. };
  603. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  604. }
  605. + (void)injectTaskDidReceiveDataIntoDelegateClass:(Class)cls
  606. {
  607. SEL selector = @selector(URLSession:dataTask:didReceiveData:);
  608. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  609. Protocol *protocol = @protocol(NSURLSessionDataDelegate);
  610. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  611. typedef void (^NSURLSessionDidReceiveDataBlock)(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data);
  612. NSURLSessionDidReceiveDataBlock undefinedBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data) {
  613. [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didReceiveData:data delegate:slf];
  614. };
  615. NSURLSessionDidReceiveDataBlock implementationBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data) {
  616. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  617. undefinedBlock(slf, session, dataTask, data);
  618. } originalImplementationBlock:^{
  619. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, dataTask, data);
  620. }];
  621. };
  622. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  623. }
  624. + (void)injectDataTaskDidBecomeDownloadTaskIntoDelegateClass:(Class)cls
  625. {
  626. SEL selector = @selector(URLSession:dataTask:didBecomeDownloadTask:);
  627. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  628. Protocol *protocol = @protocol(NSURLSessionDataDelegate);
  629. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  630. typedef void (^NSURLSessionDidBecomeDownloadTaskBlock)(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask);
  631. NSURLSessionDidBecomeDownloadTaskBlock undefinedBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask) {
  632. [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didBecomeDownloadTask:downloadTask delegate:slf];
  633. };
  634. NSURLSessionDidBecomeDownloadTaskBlock implementationBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask) {
  635. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  636. undefinedBlock(slf, session, dataTask, downloadTask);
  637. } originalImplementationBlock:^{
  638. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, dataTask, downloadTask);
  639. }];
  640. };
  641. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  642. }
  643. + (void)injectTaskDidReceiveResponseIntoDelegateClass:(Class)cls
  644. {
  645. SEL selector = @selector(URLSession:dataTask:didReceiveResponse:completionHandler:);
  646. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  647. Protocol *protocol = @protocol(NSURLSessionDataDelegate);
  648. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  649. typedef void (^NSURLSessionDidReceiveResponseBlock)(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition));
  650. NSURLSessionDidReceiveResponseBlock undefinedBlock = ^(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition)) {
  651. [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:completionHandler delegate:slf];
  652. };
  653. NSURLSessionDidReceiveResponseBlock implementationBlock = ^(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition)) {
  654. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  655. undefinedBlock(slf, session, dataTask, response, completionHandler);
  656. } originalImplementationBlock:^{
  657. ((void(*)(id, SEL, id, id, id, void(^)()))objc_msgSend)(slf, swizzledSelector, session, dataTask, response, completionHandler);
  658. }];
  659. };
  660. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  661. }
  662. + (void)injectTaskDidCompleteWithErrorIntoDelegateClass:(Class)cls
  663. {
  664. SEL selector = @selector(URLSession:task:didCompleteWithError:);
  665. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  666. Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  667. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  668. typedef void (^NSURLSessionTaskDidCompleteWithErrorBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error);
  669. NSURLSessionTaskDidCompleteWithErrorBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error) {
  670. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task didCompleteWithError:error delegate:slf];
  671. };
  672. NSURLSessionTaskDidCompleteWithErrorBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error) {
  673. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  674. undefinedBlock(slf, session, task, error);
  675. } originalImplementationBlock:^{
  676. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, task, error);
  677. }];
  678. };
  679. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  680. }
  681. // Used for overriding AFNetworking behavior
  682. + (void)injectRespondsToSelectorIntoDelegateClass:(Class)cls
  683. {
  684. SEL selector = @selector(respondsToSelector:);
  685. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  686. //Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  687. Method method = class_getInstanceMethod(cls, selector);
  688. struct objc_method_description methodDescription = *method_getDescription(method);
  689. BOOL (^undefinedBlock)(id <NSURLSessionTaskDelegate>, SEL) = ^(id slf, SEL sel) {
  690. return YES;
  691. };
  692. BOOL (^implementationBlock)(id <NSURLSessionTaskDelegate>, SEL) = ^(id <NSURLSessionTaskDelegate> slf, SEL sel) {
  693. if (sel == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) {
  694. return undefinedBlock(slf, sel);
  695. }
  696. return ((BOOL(*)(id, SEL, SEL))objc_msgSend)(slf, swizzledSelector, sel);
  697. };
  698. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  699. }
  700. + (void)injectDownloadTaskDidFinishDownloadingIntoDelegateClass:(Class)cls
  701. {
  702. SEL selector = @selector(URLSession:downloadTask:didFinishDownloadingToURL:);
  703. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  704. Protocol *protocol = @protocol(NSURLSessionDownloadDelegate);
  705. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  706. typedef void (^NSURLSessionDownloadTaskDidFinishDownloadingBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location);
  707. NSURLSessionDownloadTaskDidFinishDownloadingBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location) {
  708. NSData *data = [NSData dataWithContentsOfFile:location.relativePath];
  709. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task didFinishDownloadingToURL:location data:data delegate:slf];
  710. };
  711. NSURLSessionDownloadTaskDidFinishDownloadingBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location) {
  712. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  713. undefinedBlock(slf, session, task, location);
  714. } originalImplementationBlock:^{
  715. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, task, location);
  716. }];
  717. };
  718. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  719. }
  720. + (void)injectDownloadTaskDidWriteDataIntoDelegateClass:(Class)cls
  721. {
  722. SEL selector = @selector(URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:);
  723. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  724. Protocol *protocol = @protocol(NSURLSessionDownloadDelegate);
  725. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  726. typedef void (^NSURLSessionDownloadTaskDidWriteDataBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite);
  727. NSURLSessionDownloadTaskDidWriteDataBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
  728. [[FLEXNetworkObserver sharedObserver] URLSession:session downloadTask:task didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite delegate:slf];
  729. };
  730. NSURLSessionDownloadTaskDidWriteDataBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
  731. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  732. undefinedBlock(slf, session, task, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
  733. } originalImplementationBlock:^{
  734. ((void(*)(id, SEL, id, id, int64_t, int64_t, int64_t))objc_msgSend)(slf, swizzledSelector, session, task, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
  735. }];
  736. };
  737. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  738. }
  739. static char const * const kFLEXRequestIDKey = "kFLEXRequestIDKey";
  740. + (NSString *)requestIDForConnectionOrTask:(id)connectionOrTask
  741. {
  742. NSString *requestID = objc_getAssociatedObject(connectionOrTask, kFLEXRequestIDKey);
  743. if (!requestID) {
  744. requestID = [self nextRequestID];
  745. [self setRequestID:requestID forConnectionOrTask:connectionOrTask];
  746. }
  747. return requestID;
  748. }
  749. + (void)setRequestID:(NSString *)requestID forConnectionOrTask:(id)connectionOrTask
  750. {
  751. objc_setAssociatedObject(connectionOrTask, kFLEXRequestIDKey, requestID, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  752. }
  753. #pragma mark - Initialization
  754. - (id)init
  755. {
  756. self = [super init];
  757. if (self) {
  758. self.requestStatesForRequestIDs = [[NSMutableDictionary alloc] init];
  759. self.queue = dispatch_queue_create("com.flex.FLEXNetworkObserver", DISPATCH_QUEUE_SERIAL);
  760. }
  761. return self;
  762. }
  763. #pragma mark - Private Methods
  764. - (void)performBlock:(dispatch_block_t)block
  765. {
  766. if ([[self class] isEnabled]) {
  767. dispatch_async(_queue, block);
  768. }
  769. }
  770. - (FLEXInternalRequestState *)requestStateForRequestID:(NSString *)requestID
  771. {
  772. FLEXInternalRequestState *requestState = [self.requestStatesForRequestIDs objectForKey:requestID];
  773. if (!requestState) {
  774. requestState = [[FLEXInternalRequestState alloc] init];
  775. [self.requestStatesForRequestIDs setObject:requestState forKey:requestID];
  776. }
  777. return requestState;
  778. }
  779. - (void)removeRequestStateForRequestID:(NSString *)requestID
  780. {
  781. [self.requestStatesForRequestIDs removeObjectForKey:requestID];
  782. }
  783. @end
  784. @implementation FLEXNetworkObserver (NSURLConnectionHelpers)
  785. - (void)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response delegate:(id<NSURLConnectionDelegate>)delegate
  786. {
  787. [self performBlock:^{
  788. NSString *requestID = [[self class] requestIDForConnectionOrTask:connection];
  789. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  790. requestState.request = request;
  791. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:request redirectResponse:response];
  792. NSString *mechanism = [NSString stringWithFormat:@"NSURLConnection (delegate: %@)", [delegate class]];
  793. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:mechanism forRequestID:requestID];
  794. }];
  795. }
  796. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response delegate:(id<NSURLConnectionDelegate>)delegate
  797. {
  798. [self performBlock:^{
  799. NSString *requestID = [[self class] requestIDForConnectionOrTask:connection];
  800. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  801. NSMutableData *dataAccumulator = nil;
  802. if (response.expectedContentLength < 0) {
  803. dataAccumulator = [[NSMutableData alloc] init];
  804. } else {
  805. dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)response.expectedContentLength];
  806. }
  807. requestState.dataAccumulator = dataAccumulator;
  808. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:response];
  809. }];
  810. }
  811. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data delegate:(id<NSURLConnectionDelegate>)delegate
  812. {
  813. // Just to be safe since we're doing this async
  814. data = [data copy];
  815. [self performBlock:^{
  816. NSString *requestID = [[self class] requestIDForConnectionOrTask:connection];
  817. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  818. [requestState.dataAccumulator appendData:data];
  819. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:data.length];
  820. }];
  821. }
  822. - (void)connectionDidFinishLoading:(NSURLConnection *)connection delegate:(id<NSURLConnectionDelegate>)delegate
  823. {
  824. [self performBlock:^{
  825. NSString *requestID = [[self class] requestIDForConnectionOrTask:connection];
  826. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  827. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:requestState.dataAccumulator];
  828. [self removeRequestStateForRequestID:requestID];
  829. }];
  830. }
  831. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error delegate:(id<NSURLConnectionDelegate>)delegate
  832. {
  833. [self performBlock:^{
  834. NSString *requestID = [[self class] requestIDForConnectionOrTask:connection];
  835. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  836. // Cancellations can occur prior to the willSendRequest:... NSURLConnection delegate call.
  837. // These are pretty common and clutter up the logs. Only record the failure if the recorder already knows about the request through willSendRequest:...
  838. if (requestState.request) {
  839. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:error];
  840. }
  841. [self removeRequestStateForRequestID:requestID];
  842. }];
  843. }
  844. - (void)connectionWillCancel:(NSURLConnection *)connection
  845. {
  846. [self performBlock:^{
  847. // Mimic the behavior of NSURLSession which is to create an error on cancellation.
  848. NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : @"cancelled" };
  849. NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
  850. [self connection:connection didFailWithError:error delegate:nil];
  851. }];
  852. }
  853. @end
  854. @implementation FLEXNetworkObserver (NSURLSessionTaskHelpers)
  855. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler delegate:(id<NSURLSessionDelegate>)delegate
  856. {
  857. [self performBlock:^{
  858. NSString *requestID = [[self class] requestIDForConnectionOrTask:task];
  859. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:request redirectResponse:response];
  860. }];
  861. }
  862. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler delegate:(id<NSURLSessionDelegate>)delegate
  863. {
  864. [self performBlock:^{
  865. NSString *requestID = [[self class] requestIDForConnectionOrTask:dataTask];
  866. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  867. NSMutableData *dataAccumulator = nil;
  868. if (response.expectedContentLength < 0) {
  869. dataAccumulator = [[NSMutableData alloc] init];
  870. } else {
  871. dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)response.expectedContentLength];
  872. }
  873. requestState.dataAccumulator = dataAccumulator;
  874. NSString *requestMechanism = [NSString stringWithFormat:@"NSURLSessionDataTask (delegate: %@)", [delegate class]];
  875. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:requestMechanism forRequestID:requestID];
  876. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:response];
  877. }];
  878. }
  879. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask delegate:(id<NSURLSessionDelegate>)delegate
  880. {
  881. [self performBlock:^{
  882. // By setting the request ID of the download task to match the data task,
  883. // it can pick up where the data task left off.
  884. NSString *requestID = [[self class] requestIDForConnectionOrTask:dataTask];
  885. [[self class] setRequestID:requestID forConnectionOrTask:downloadTask];
  886. }];
  887. }
  888. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data delegate:(id<NSURLSessionDelegate>)delegate
  889. {
  890. // Just to be safe since we're doing this async
  891. data = [data copy];
  892. [self performBlock:^{
  893. NSString *requestID = [[self class] requestIDForConnectionOrTask:dataTask];
  894. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  895. [requestState.dataAccumulator appendData:data];
  896. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:data.length];
  897. }];
  898. }
  899. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error delegate:(id<NSURLSessionDelegate>)delegate
  900. {
  901. [self performBlock:^{
  902. NSString *requestID = [[self class] requestIDForConnectionOrTask:task];
  903. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  904. if (error) {
  905. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:error];
  906. } else {
  907. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:requestState.dataAccumulator];
  908. }
  909. [self removeRequestStateForRequestID:requestID];
  910. }];
  911. }
  912. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite delegate:(id<NSURLSessionDelegate>)delegate
  913. {
  914. [self performBlock:^{
  915. NSString *requestID = [[self class] requestIDForConnectionOrTask:downloadTask];
  916. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  917. if (!requestState.dataAccumulator) {
  918. NSUInteger unsignedBytesExpectedToWrite = totalBytesExpectedToWrite > 0 ? (NSUInteger)totalBytesExpectedToWrite : 0;
  919. requestState.dataAccumulator = [[NSMutableData alloc] initWithCapacity:unsignedBytesExpectedToWrite];
  920. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:downloadTask.response];
  921. NSString *requestMechanism = [NSString stringWithFormat:@"NSURLSessionDownloadTask (delegate: %@)", [delegate class]];
  922. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:requestMechanism forRequestID:requestID];
  923. }
  924. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:bytesWritten];
  925. }];
  926. }
  927. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location data:(NSData *)data delegate:(id<NSURLSessionDelegate>)delegate
  928. {
  929. data = [data copy];
  930. [self performBlock:^{
  931. NSString *requestID = [[self class] requestIDForConnectionOrTask:downloadTask];
  932. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  933. [requestState.dataAccumulator appendData:data];
  934. }];
  935. }
  936. - (void)URLSessionTaskWillResume:(NSURLSessionTask *)task
  937. {
  938. // Since resume can be called multiple times on the same task, only treat the first resume as
  939. // the equivalent to connection:willSendRequest:...
  940. [self performBlock:^{
  941. NSString *requestID = [[self class] requestIDForConnectionOrTask:task];
  942. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  943. if (!requestState.request) {
  944. requestState.request = task.currentRequest;
  945. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:task.currentRequest redirectResponse:nil];
  946. }
  947. }];
  948. }
  949. @end