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