FLEXNetworkObserver.m 40 KB

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