FLEXNetworkObserver.m 40 KB

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