FLEXNetworkObserver.m 58 KB

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