FLEXNetworkObserver.m 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  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. @interface FLEXInternalRequestState : NSObject
  21. @property (nonatomic, copy) NSURLRequest *request;
  22. @property (nonatomic, strong) NSMutableData *dataAccumulator;
  23. @property (nonatomic, copy) NSString *requestID;
  24. @end
  25. @implementation FLEXInternalRequestState
  26. @end
  27. @interface FLEXNetworkObserver (NSURLConnectionHelpers)
  28. - (void)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response delegate:(id <NSURLConnectionDelegate>)delegate;
  29. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response delegate:(id <NSURLConnectionDelegate>)delegate;
  30. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data delegate:(id <NSURLConnectionDelegate>)delegate;
  31. - (void)connectionDidFinishLoading:(NSURLConnection *)connection delegate:(id <NSURLConnectionDelegate>)delegate;
  32. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error delegate:(id <NSURLConnectionDelegate>)delegate;
  33. @end
  34. @interface FLEXNetworkObserver (NSURLSessionTaskHelpers)
  35. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler delegate:(id <NSURLSessionDelegate>)delegate;
  36. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler delegate:(id <NSURLSessionDelegate>)delegate;
  37. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data delegate:(id <NSURLSessionDelegate>)delegate;
  38. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error delegate:(id <NSURLSessionDelegate>)delegate;
  39. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite delegate:(id <NSURLSessionDelegate>)delegate;
  40. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location data:(NSData *)data delegate:(id <NSURLSessionDelegate>)delegate;
  41. @end
  42. @interface NSData (FLEXNetworkHelpers)
  43. + (NSData *)emptyDataOfLength:(NSUInteger)length;
  44. @end
  45. @interface FLEXNetworkObserver ()
  46. @property (nonatomic, assign, getter=isEnabled) BOOL enabled;
  47. @property (nonatomic, strong) NSMutableDictionary *connectionStates;
  48. @property (nonatomic, strong) dispatch_queue_t queue;
  49. @end
  50. @implementation FLEXNetworkObserver
  51. #pragma mark - Public Methods
  52. + (void)setEnabled:(BOOL)enabled
  53. {
  54. if (enabled) {
  55. // Inject if needed. This injection is protected with a dispatch_once, so we're ok calling it multiple times.
  56. // By doing the injection lazily, we keep the impact of the tool lower when this feature isn't enabled.
  57. [self injectIntoAllNSURLConnectionDelegateClasses];
  58. }
  59. [[self sharedObserver] setEnabled:enabled];
  60. }
  61. + (BOOL)isEnabled
  62. {
  63. return [[self sharedObserver] isEnabled];
  64. }
  65. - (void)setEnabled:(BOOL)enabled
  66. {
  67. if (_enabled != enabled) {
  68. _enabled = enabled;
  69. [[NSNotificationCenter defaultCenter] postNotificationName:kFLEXNetworkObserverEnabledStateChangedNotification object:self];
  70. }
  71. }
  72. #pragma mark - Statics
  73. + (instancetype)sharedObserver
  74. {
  75. static FLEXNetworkObserver *sharedObserver = nil;
  76. static dispatch_once_t onceToken;
  77. dispatch_once(&onceToken, ^{
  78. sharedObserver = [[[self class] alloc] init];
  79. });
  80. return sharedObserver;
  81. }
  82. + (NSString *)nextRequestID
  83. {
  84. static NSInteger sequenceNumber = 0;
  85. static NSString *seed = nil;
  86. static dispatch_once_t onceToken;
  87. dispatch_once(&onceToken, ^{
  88. CFUUIDRef uuid = CFUUIDCreate(CFAllocatorGetDefault());
  89. seed = (__bridge NSString *)CFUUIDCreateString(CFAllocatorGetDefault(), uuid);
  90. CFRelease(uuid);
  91. });
  92. return [[NSString alloc] initWithFormat:@"%@-%ld", seed, (long)(++sequenceNumber)];
  93. }
  94. #pragma mark Delegate Injection Convenience Methods
  95. + (SEL)swizzledSelectorForSelector:(SEL)selector
  96. {
  97. return NSSelectorFromString([NSString stringWithFormat:@"_flex_swizzle_%x_%@", arc4random(), NSStringFromSelector(selector)]);
  98. }
  99. + (BOOL)instanceRespondsButDoesNotImplementSelector:(SEL)selector class:(Class)cls
  100. {
  101. if ([cls instancesRespondToSelector:selector]) {
  102. unsigned int numMethods = 0;
  103. Method *methods = class_copyMethodList(cls, &numMethods);
  104. BOOL implementsSelector = NO;
  105. for (int index = 0; index < numMethods; index++) {
  106. SEL methodSelector = method_getName(methods[index]);
  107. if (selector == methodSelector) {
  108. implementsSelector = YES;
  109. break;
  110. }
  111. }
  112. free(methods);
  113. if (!implementsSelector) {
  114. return YES;
  115. }
  116. }
  117. return NO;
  118. }
  119. + (void)replaceImplementationOfSelector:(SEL)selector withSelector:(SEL)swizzledSelector forClass:(Class)cls withMethodDescription:(struct objc_method_description)methodDescription implementationBlock:(id)implementationBlock undefinedBlock:(id)undefinedBlock
  120. {
  121. if ([self instanceRespondsButDoesNotImplementSelector:selector class:cls]) {
  122. return;
  123. }
  124. IMP implementation = imp_implementationWithBlock((id)([cls instancesRespondToSelector:selector] ? implementationBlock : undefinedBlock));
  125. Method oldMethod = class_getInstanceMethod(cls, selector);
  126. if (oldMethod) {
  127. class_addMethod(cls, swizzledSelector, implementation, methodDescription.types);
  128. Method newMethod = class_getInstanceMethod(cls, swizzledSelector);
  129. method_exchangeImplementations(oldMethod, newMethod);
  130. } else {
  131. class_addMethod(cls, selector, implementation, methodDescription.types);
  132. }
  133. }
  134. #pragma mark - Delegate Injection
  135. + (void)injectIntoAllNSURLConnectionDelegateClasses
  136. {
  137. // Only allow swizzling once.
  138. static dispatch_once_t onceToken;
  139. dispatch_once(&onceToken, ^{
  140. // Swizzle any classes that implement one of these selectors.
  141. const SEL selectors[] = {
  142. @selector(connectionDidFinishLoading:),
  143. @selector(connection:didReceiveResponse:),
  144. @selector(URLSession:dataTask:didReceiveResponse:completionHandler:),
  145. @selector(URLSession:task:didCompleteWithError:),
  146. @selector(URLSession:downloadTask:didFinishDownloadingToURL:)
  147. };
  148. const int numSelectors = sizeof(selectors) / sizeof(SEL);
  149. Class *classes = NULL;
  150. int numClasses = objc_getClassList(NULL, 0);
  151. if (numClasses > 0) {
  152. classes = (__unsafe_unretained Class *)malloc(sizeof(Class) * numClasses);
  153. numClasses = objc_getClassList(classes, numClasses);
  154. for (NSInteger classIndex = 0; classIndex < numClasses; ++classIndex) {
  155. Class class = classes[classIndex];
  156. // We're not interested in swizzling CLTilesManagerClient, and sending any message to the class fires +initialize causing sandbox violations.
  157. if (strcmp(class_getName(class), [[@[@"C", @"LT", @"ilesM", @"anage", @"rClient"] componentsJoinedByString:@""] UTF8String]) == 0) {
  158. continue;
  159. }
  160. if (class_getClassMethod(class, @selector(isSubclassOfClass:)) == NULL) {
  161. continue;
  162. }
  163. if (![class isSubclassOfClass:[NSObject class]]) {
  164. continue;
  165. }
  166. if ([class isSubclassOfClass:[FLEXNetworkObserver class]]) {
  167. continue;
  168. }
  169. for (int selectorIndex = 0; selectorIndex < numSelectors; ++selectorIndex) {
  170. if ([class instancesRespondToSelector:selectors[selectorIndex]]) {
  171. [self injectIntoDelegateClass:class];
  172. break;
  173. }
  174. }
  175. }
  176. free(classes);
  177. }
  178. });
  179. }
  180. + (void)injectIntoDelegateClass:(Class)cls
  181. {
  182. // Connections
  183. [self injectWillSendRequestIntoDelegateClass:cls];
  184. [self injectDidReceiveDataIntoDelegateClass:cls];
  185. [self injectDidReceiveResponseIntoDelegateClass:cls];
  186. [self injectDidFinishLoadingIntoDelegateClass:cls];
  187. [self injectDidFailWithErrorIntoDelegateClass:cls];
  188. // Sessions
  189. [self injectTaskWillPerformHTTPRedirectionIntoDelegateClass:cls];
  190. [self injectTaskDidReceiveDataIntoDelegateClass:cls];
  191. [self injectTaskDidReceiveResponseIntoDelegateClass:cls];
  192. [self injectTaskDidCompleteWithErrorIntoDelegateClass:cls];
  193. [self injectRespondsToSelectorIntoDelegateClass:cls];
  194. // Download tasks
  195. [self injectDownloadTaskDidWriteDataIntoDelegateClass:cls];
  196. [self injectDownloadTaskDidFinishDownloadingIntoDelegateClass:cls];
  197. }
  198. + (void)injectWillSendRequestIntoDelegateClass:(Class)cls
  199. {
  200. SEL selector = @selector(connection:willSendRequest:redirectResponse:);
  201. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  202. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  203. if (!protocol) {
  204. protocol = @protocol(NSURLConnectionDelegate);
  205. }
  206. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  207. typedef NSURLRequest *(^NSURLConnectionWillSendRequestBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response);
  208. NSURLConnectionWillSendRequestBlock undefinedBlock = ^NSURLRequest *(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) {
  209. [[FLEXNetworkObserver sharedObserver] connection:connection willSendRequest:request redirectResponse:response delegate:slf];
  210. return request;
  211. };
  212. NSURLConnectionWillSendRequestBlock implementationBlock = ^NSURLRequest *(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) {
  213. NSURLRequest *returnValue = ((id(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, connection, request, response);
  214. undefinedBlock(slf, connection, request, response);
  215. return returnValue;
  216. };
  217. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  218. }
  219. + (void)injectDidReceiveResponseIntoDelegateClass:(Class)cls
  220. {
  221. SEL selector = @selector(connection:didReceiveResponse:);
  222. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  223. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  224. if (!protocol) {
  225. protocol = @protocol(NSURLConnectionDelegate);
  226. }
  227. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  228. typedef void (^NSURLConnectionDidReceiveResponseBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response);
  229. NSURLConnectionDidReceiveResponseBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response) {
  230. [[FLEXNetworkObserver sharedObserver] connection:connection didReceiveResponse:response delegate:slf];
  231. };
  232. NSURLConnectionDidReceiveResponseBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response) {
  233. undefinedBlock(slf, connection, response);
  234. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, response);
  235. };
  236. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  237. }
  238. + (void)injectDidReceiveDataIntoDelegateClass:(Class)cls
  239. {
  240. SEL selector = @selector(connection:didReceiveData:);
  241. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  242. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  243. if (!protocol) {
  244. protocol = @protocol(NSURLConnectionDelegate);
  245. }
  246. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  247. typedef void (^NSURLConnectionDidReceiveDataBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data);
  248. NSURLConnectionDidReceiveDataBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data) {
  249. [[FLEXNetworkObserver sharedObserver] connection:connection didReceiveData:data delegate:slf];
  250. };
  251. NSURLConnectionDidReceiveDataBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data) {
  252. undefinedBlock(slf, connection, data);
  253. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, data);
  254. };
  255. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  256. }
  257. + (void)injectDidFinishLoadingIntoDelegateClass:(Class)cls
  258. {
  259. SEL selector = @selector(connectionDidFinishLoading:);
  260. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  261. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  262. if (!protocol) {
  263. protocol = @protocol(NSURLConnectionDelegate);
  264. }
  265. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  266. typedef void (^NSURLConnectionDidFinishLoadingBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection);
  267. NSURLConnectionDidFinishLoadingBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection) {
  268. [[FLEXNetworkObserver sharedObserver] connectionDidFinishLoading:connection delegate:slf];
  269. };
  270. NSURLConnectionDidFinishLoadingBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection) {
  271. undefinedBlock(slf, connection);
  272. ((void(*)(id, SEL, id))objc_msgSend)(slf, swizzledSelector, connection);
  273. };
  274. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  275. }
  276. + (void)injectDidFailWithErrorIntoDelegateClass:(Class)cls
  277. {
  278. SEL selector = @selector(connection:didFailWithError:);
  279. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  280. Protocol *protocol = @protocol(NSURLConnectionDelegate);
  281. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  282. typedef void (^NSURLConnectionDidFailWithErrorBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error);
  283. NSURLConnectionDidFailWithErrorBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error) {
  284. [[FLEXNetworkObserver sharedObserver] connection:connection didFailWithError:error delegate:slf];
  285. };
  286. NSURLConnectionDidFailWithErrorBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error) {
  287. undefinedBlock(slf, connection, error);
  288. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, error);
  289. };
  290. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  291. }
  292. + (void)injectTaskWillPerformHTTPRedirectionIntoDelegateClass:(Class)cls
  293. {
  294. SEL selector = @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:);
  295. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  296. Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  297. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  298. typedef void (^NSURLSessionWillPerformHTTPRedirectionBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *));
  299. NSURLSessionWillPerformHTTPRedirectionBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *)) {
  300. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task willPerformHTTPRedirection:response newRequest:newRequest completionHandler:completionHandler delegate:slf];
  301. };
  302. NSURLSessionWillPerformHTTPRedirectionBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *)) {
  303. ((id(*)(id, SEL, id, id, id, id, void(^)()))objc_msgSend)(slf, swizzledSelector, session, task, response, newRequest, completionHandler);
  304. undefinedBlock(slf, session, task, response, newRequest, completionHandler);
  305. };
  306. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  307. }
  308. + (void)injectTaskDidReceiveDataIntoDelegateClass:(Class)cls
  309. {
  310. SEL selector = @selector(URLSession:dataTask:didReceiveData:);
  311. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  312. Protocol *protocol = @protocol(NSURLSessionDataDelegate);
  313. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  314. typedef void (^NSURLSessionDidReceiveDataBlock)(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data);
  315. NSURLSessionDidReceiveDataBlock undefinedBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data) {
  316. [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didReceiveData:data delegate:slf];
  317. };
  318. NSURLSessionDidReceiveDataBlock implementationBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data) {
  319. undefinedBlock(slf, session, dataTask, data);
  320. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, dataTask, data);
  321. };
  322. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  323. }
  324. + (void)injectTaskDidReceiveResponseIntoDelegateClass:(Class)cls
  325. {
  326. SEL selector = @selector(URLSession:dataTask:didReceiveResponse:completionHandler:);
  327. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  328. Protocol *protocol = @protocol(NSURLSessionDataDelegate);
  329. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  330. typedef void (^NSURLSessionDidReceiveResponseBlock)(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition));
  331. NSURLSessionDidReceiveResponseBlock undefinedBlock = ^(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition)) {
  332. [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:completionHandler delegate:slf];
  333. };
  334. NSURLSessionDidReceiveResponseBlock implementationBlock = ^(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition)) {
  335. undefinedBlock(slf, session, dataTask, response, completionHandler);
  336. ((void(*)(id, SEL, id, id, id, void(^)()))objc_msgSend)(slf, swizzledSelector, session, dataTask, response, completionHandler);
  337. };
  338. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  339. }
  340. + (void)injectTaskDidCompleteWithErrorIntoDelegateClass:(Class)cls
  341. {
  342. SEL selector = @selector(URLSession:task:didCompleteWithError:);
  343. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  344. Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  345. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  346. typedef void (^NSURLSessionTaskDidCompleteWithErrorBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error);
  347. NSURLSessionTaskDidCompleteWithErrorBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error) {
  348. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task didCompleteWithError:error delegate:slf];
  349. };
  350. NSURLSessionTaskDidCompleteWithErrorBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error) {
  351. undefinedBlock(slf, session, task, error);
  352. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, task, error);
  353. };
  354. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  355. }
  356. // Used for overriding AFNetworking behavior
  357. + (void)injectRespondsToSelectorIntoDelegateClass:(Class)cls
  358. {
  359. SEL selector = @selector(respondsToSelector:);
  360. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  361. //Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  362. Method method = class_getInstanceMethod(cls, selector);
  363. struct objc_method_description methodDescription = *method_getDescription(method);
  364. typedef void (^NSURLSessionTaskDidCompleteWithErrorBlock)(id slf, SEL sel);
  365. BOOL (^undefinedBlock)(id <NSURLSessionTaskDelegate>, SEL) = ^(id slf, SEL sel) {
  366. return YES;
  367. };
  368. BOOL (^implementationBlock)(id <NSURLSessionTaskDelegate>, SEL) = ^(id <NSURLSessionTaskDelegate> slf, SEL sel) {
  369. if (sel == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) {
  370. return undefinedBlock(slf, sel);
  371. }
  372. return ((BOOL(*)(id, SEL, SEL))objc_msgSend)(slf, swizzledSelector, sel);
  373. };
  374. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  375. }
  376. + (void)injectDownloadTaskDidFinishDownloadingIntoDelegateClass:(Class)cls
  377. {
  378. SEL selector = @selector(URLSession:downloadTask:didFinishDownloadingToURL:);
  379. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  380. Protocol *protocol = @protocol(NSURLSessionDownloadDelegate);
  381. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  382. typedef void (^NSURLSessionDownloadTaskDidFinishDownloadingBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location);
  383. NSURLSessionDownloadTaskDidFinishDownloadingBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location) {
  384. NSData *data = [NSData dataWithContentsOfFile:location.relativePath];
  385. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task didFinishDownloadingToURL:location data:data delegate:slf];
  386. };
  387. NSURLSessionDownloadTaskDidFinishDownloadingBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location) {
  388. undefinedBlock(slf, session, task, location);
  389. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, task, location);
  390. };
  391. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  392. }
  393. + (void)injectDownloadTaskDidWriteDataIntoDelegateClass:(Class)cls
  394. {
  395. SEL selector = @selector(URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:);
  396. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  397. Protocol *protocol = @protocol(NSURLSessionDownloadDelegate);
  398. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  399. typedef void (^NSURLSessionDownloadTaskDidWriteDataBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite);
  400. NSURLSessionDownloadTaskDidWriteDataBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
  401. [[FLEXNetworkObserver sharedObserver] URLSession:session downloadTask:task didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite delegate:slf];
  402. };
  403. NSURLSessionDownloadTaskDidWriteDataBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
  404. undefinedBlock(slf, session, task, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
  405. ((void(*)(id, SEL, id, id, int64_t, int64_t, int64_t))objc_msgSend)(slf, swizzledSelector, session, task, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
  406. };
  407. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  408. }
  409. #pragma mark - Initialization
  410. - (id)init
  411. {
  412. self = [super init];
  413. if (!self) {
  414. return nil;
  415. }
  416. _connectionStates = [[NSMutableDictionary alloc] init];
  417. _queue = dispatch_queue_create("com.flex.FLEXNetworkObserver", DISPATCH_QUEUE_SERIAL);
  418. return self;
  419. }
  420. #pragma mark - Private Methods
  421. - (void)performBlock:(dispatch_block_t)block
  422. {
  423. if (self.isEnabled) {
  424. dispatch_async(_queue, block);
  425. }
  426. }
  427. #pragma mark - Private Methods (Connections)
  428. - (FLEXInternalRequestState *)requestStateForConnection:(NSURLConnection *)connection
  429. {
  430. NSValue *key = [NSValue valueWithNonretainedObject:connection];
  431. FLEXInternalRequestState *state = [_connectionStates objectForKey:key];
  432. if (!state) {
  433. state = [[FLEXInternalRequestState alloc] init];
  434. state.requestID = [[self class] nextRequestID];
  435. [_connectionStates setObject:state forKey:key];
  436. }
  437. return state;
  438. }
  439. - (NSString *)requestIDForConnection:(NSURLConnection *)connection
  440. {
  441. return [self requestStateForConnection:connection].requestID;
  442. }
  443. - (void)setRequest:(NSURLRequest *)request forConnection:(NSURLConnection *)connection
  444. {
  445. [self requestStateForConnection:connection].request = request;
  446. }
  447. - (NSURLRequest *)requestForConnection:(NSURLConnection *)connection
  448. {
  449. return [self requestStateForConnection:connection].request;
  450. }
  451. - (void)setAccumulatedData:(NSMutableData *)data forConnection:(NSURLConnection *)connection
  452. {
  453. FLEXInternalRequestState *requestState = [self requestStateForConnection:connection];
  454. requestState.dataAccumulator = data;
  455. }
  456. - (void)addAccumulatedData:(NSData *)data forConnection:(NSURLConnection *)connection
  457. {
  458. NSMutableData *dataAccumulator = [self requestStateForConnection:connection].dataAccumulator;
  459. [dataAccumulator appendData:data];
  460. }
  461. - (NSData *)accumulatedDataForConnection:(NSURLConnection *)connection
  462. {
  463. return [self requestStateForConnection:connection].dataAccumulator;
  464. }
  465. // This removes storing the accumulated request/response from the dictionary so we can release connection
  466. - (void)connectionFinished:(NSURLConnection *)connection
  467. {
  468. NSValue *key = [NSValue valueWithNonretainedObject:connection];
  469. [_connectionStates removeObjectForKey:key];
  470. }
  471. #pragma mark - Private Methods (Tasks)
  472. - (FLEXInternalRequestState *)requestStateForTask:(NSURLSessionTask *)task
  473. {
  474. NSValue *key = [NSValue valueWithNonretainedObject:task];
  475. FLEXInternalRequestState *state = [_connectionStates objectForKey:key];
  476. if (!state) {
  477. state = [[FLEXInternalRequestState alloc] init];
  478. state.requestID = [[self class] nextRequestID];
  479. [_connectionStates setObject:state forKey:key];
  480. }
  481. return state;
  482. }
  483. - (NSString *)requestIDForTask:(NSURLSessionTask *)task
  484. {
  485. return [self requestStateForTask:task].requestID;
  486. }
  487. - (void)setRequest:(NSURLRequest *)request forTask:(NSURLSessionTask *)task
  488. {
  489. [self requestStateForTask:task].request = request;
  490. }
  491. - (NSURLRequest *)requestForTask:(NSURLSessionTask *)task
  492. {
  493. return [self requestStateForTask:task].request;
  494. }
  495. - (void)setAccumulatedData:(NSMutableData *)data forTask:(NSURLSessionTask *)task
  496. {
  497. FLEXInternalRequestState *requestState = [self requestStateForTask:task];
  498. requestState.dataAccumulator = data;
  499. }
  500. - (void)addAccumulatedData:(NSData *)data forTask:(NSURLSessionTask *)task
  501. {
  502. NSMutableData *dataAccumulator = [self requestStateForTask:task].dataAccumulator;
  503. [dataAccumulator appendData:data];
  504. }
  505. - (NSData *)accumulatedDataForTask:(NSURLSessionTask *)task
  506. {
  507. return [self requestStateForTask:task].dataAccumulator;
  508. }
  509. // This removes storing the accumulated request/response from the dictionary so we can release task
  510. - (void)taskFinished:(NSURLSessionTask *)task
  511. {
  512. NSValue *key = [NSValue valueWithNonretainedObject:task];
  513. [_connectionStates removeObjectForKey:key];
  514. }
  515. @end
  516. @implementation FLEXNetworkObserver (NSURLConnectionHelpers)
  517. - (void)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response delegate:(id<NSURLConnectionDelegate>)delegate
  518. {
  519. [self performBlock:^{
  520. [self setRequest:request forConnection:connection];
  521. NSString *requestId = [self requestIDForConnection:connection];
  522. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:requestId request:request redirectResponse:response];
  523. }];
  524. }
  525. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response delegate:(id<NSURLConnectionDelegate>)delegate
  526. {
  527. [self performBlock:^{
  528. if ([response respondsToSelector:@selector(copyWithZone:)]) {
  529. // If the request wasn't generated yet, then willSendRequest was not called. This appears to be an inconsistency in documentation
  530. // and behavior.
  531. NSURLRequest *request = [self requestForConnection:connection];
  532. if (!request && [connection respondsToSelector:@selector(currentRequest)]) {
  533. request = connection.currentRequest;
  534. [self setRequest:request forConnection:connection];
  535. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:[self requestIDForConnection:connection] request:request redirectResponse:nil];
  536. }
  537. NSMutableData *dataAccumulator = nil;
  538. if (response.expectedContentLength < 0) {
  539. dataAccumulator = [[NSMutableData alloc] init];
  540. } else {
  541. dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)response.expectedContentLength];
  542. }
  543. [self setAccumulatedData:dataAccumulator forConnection:connection];
  544. NSString *requestID = [self requestIDForConnection:connection];
  545. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestId:requestID response:response];
  546. }
  547. }];
  548. }
  549. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data delegate:(id<NSURLConnectionDelegate>)delegate
  550. {
  551. // Just to be safe since we're doing this async
  552. data = [data copy];
  553. [self performBlock:^{
  554. [self addAccumulatedData:data forConnection:connection];
  555. if ([self accumulatedDataForConnection:connection] == nil) return;
  556. NSString *requestID = [self requestIDForConnection:connection];
  557. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestId:requestID dataLength:data.length];
  558. }];
  559. }
  560. - (void)connectionDidFinishLoading:(NSURLConnection *)connection delegate:(id<NSURLConnectionDelegate>)delegate
  561. {
  562. [self performBlock:^{
  563. NSString *requestID = [self requestIDForConnection:connection];
  564. NSData *accumulatedData = [self accumulatedDataForConnection:connection];
  565. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestId:requestID responseBody:accumulatedData];
  566. [self connectionFinished:connection];
  567. }];
  568. }
  569. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error delegate:(id<NSURLConnectionDelegate>)delegate
  570. {
  571. [self performBlock:^{
  572. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestId:[self requestIDForConnection:connection] error:error];
  573. [self connectionFinished:connection];
  574. }];
  575. }
  576. @end
  577. @implementation FLEXNetworkObserver (NSURLSessionTaskHelpers)
  578. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler delegate:(id<NSURLSessionDelegate>)delegate
  579. {
  580. [self performBlock:^{
  581. [self setRequest:request forTask:task];
  582. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:[self requestIDForTask:task] request:request redirectResponse:response];
  583. }];
  584. }
  585. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler delegate:(id<NSURLSessionDelegate>)delegate
  586. {
  587. if ([response respondsToSelector:@selector(copyWithZone:)]) {
  588. // willSendRequest does not exist in NSURLSession. Here's a workaround.
  589. NSURLRequest *request = [self requestForTask:dataTask];
  590. if (!request && [dataTask respondsToSelector:@selector(currentRequest)]) {
  591. request = dataTask.currentRequest;
  592. [self setRequest:request forTask:dataTask];
  593. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:[self requestIDForTask:dataTask] request:request redirectResponse:nil];
  594. }
  595. NSMutableData *dataAccumulator = nil;
  596. if (response.expectedContentLength < 0) {
  597. dataAccumulator = [[NSMutableData alloc] init];
  598. } else {
  599. dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)response.expectedContentLength];
  600. }
  601. [self setAccumulatedData:dataAccumulator forTask:dataTask];
  602. NSString *requestID = [self requestIDForTask:dataTask];
  603. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestId:requestID response:response];
  604. }
  605. }
  606. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data delegate:(id<NSURLSessionDelegate>)delegate
  607. {
  608. // Just to be safe since we're doing this async
  609. data = [data copy];
  610. [self performBlock:^{
  611. [self addAccumulatedData:data forTask:dataTask];
  612. if ([self accumulatedDataForTask:dataTask] == nil) return;
  613. NSString *requestID = [self requestIDForTask:dataTask];
  614. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestId:requestID dataLength:data.length];
  615. }];
  616. }
  617. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error delegate:(id<NSURLSessionDelegate>)delegate
  618. {
  619. [self performBlock:^{
  620. NSString *requestID = [self requestIDForTask:task];
  621. NSData *accumulatedData = [self accumulatedDataForTask:task];
  622. if (error) {
  623. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestId:[self requestIDForTask:task] error:error];
  624. } else {
  625. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestId:requestID responseBody:accumulatedData];
  626. }
  627. [self taskFinished:task];
  628. }];
  629. }
  630. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  631. {
  632. [self performBlock:^{
  633. // If the request wasn't generated yet, then willSendRequest was not called. This appears to be an inconsistency in documentation
  634. // and behavior.
  635. NSURLRequest *request = [self requestForTask:downloadTask];
  636. if (!request && [downloadTask respondsToSelector:@selector(currentRequest)]) {
  637. request = downloadTask.currentRequest;
  638. [self setRequest:request forTask:downloadTask];
  639. NSString *requestID = [self requestIDForTask:downloadTask];
  640. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:requestID request:request redirectResponse:nil];
  641. NSMutableData *dataAccumulator = nil;
  642. dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger) totalBytesExpectedToWrite];
  643. [self setAccumulatedData:dataAccumulator forTask:downloadTask];
  644. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestId:requestID response:downloadTask.response];
  645. }
  646. [self addAccumulatedData:[NSData emptyDataOfLength:(NSUInteger) bytesWritten] forTask:downloadTask];
  647. NSString *requestID = [self requestIDForTask:downloadTask];
  648. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestId:requestID dataLength:bytesWritten];
  649. }];
  650. }
  651. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location data:(NSData *)data delegate:(id<NSURLSessionDelegate>)delegate
  652. {
  653. [self performBlock:^{
  654. NSString *requestID = [self requestIDForTask:downloadTask];
  655. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestId:requestID responseBody:data];
  656. [self taskFinished:downloadTask];
  657. }];
  658. }
  659. @end
  660. @implementation NSData (FLEXNetworkHelpers)
  661. + (NSData *)emptyDataOfLength:(NSUInteger)length
  662. {
  663. NSMutableData *theData = [NSMutableData dataWithCapacity:length];
  664. for (unsigned int i = 0 ; i < length/4 ; ++i) {
  665. u_int32_t randomBits = 0;
  666. [theData appendBytes:(void*)&randomBits length:4];
  667. }
  668. return theData;
  669. }
  670. @end