FLEX除了支持查看UI,内存之外,还能看网络抓包,下边探究其底层的实现:
load/setEnabled
要想抓包,就需要对一些代理函数进行hook,主要逻辑在FLEXNetworkObserver这个类里边。首先既然是hook,先找到其load函数实现如下:
+ (void)load
{
dispatch_async(dispatch_get_main_queue(), ^{
if ([self isEnabled]) {
[self injectIntoAllNSURLConnectionDelegateClasses];
}
});
}
这里的[self isEnabled]
是一个网络抓包的开关,用userdault
存在本地,在+[FLEXNetworkObserver setEnabled:]
的代码如下:
+ (void)setEnabled:(BOOL)enabled
{
BOOL previouslyEnabled = [self isEnabled];
[[NSUserDefaults standardUserDefaults] setBool:enabled forKey:kFLEXNetworkObserverEnabledDefaultsKey];
if (enabled) {
[self injectIntoAllNSURLConnectionDelegateClasses];
}
if (previouslyEnabled != enabled) {
[[NSNotificationCenter defaultCenter] postNotificationName:kFLEXNetworkObserverEnabledStateChangedNotification object:self];
}
}
injectIntoAllNSURLConnectionDelegateClasses
上面两个方法都调用了+[FLEXNetworkObserver injectIntoAllNSURLConnectionDelegateClasses]
方法,这个方法实现如下:
+ (void)injectIntoAllNSURLConnectionDelegateClasses
{
1.
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
2.
const SEL selectors[] = {
@selector(connectionDidFinishLoading:),
@selector(connection:willSendRequest:redirectResponse:),
@selector(connection:didReceiveResponse:),
@selector(connection:didReceiveData:),
@selector(connection:didFailWithError:),
@selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:),
@selector(URLSession:dataTask:didReceiveData:),
@selector(URLSession:dataTask:didReceiveResponse:completionHandler:),
@selector(URLSession:task:didCompleteWithError:),
@selector(URLSession:dataTask:didBecomeDownloadTask:delegate:),
@selector(URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:),
@selector(URLSession:downloadTask:didFinishDownloadingToURL:)
};
const int numSelectors = sizeof(selectors) / sizeof(SEL);
3.
Class *classes = NULL;
int numClasses = objc_getClassList(NULL, 0);
if (numClasses > 0) {
classes = (__unsafe_unretained Class *)malloc(sizeof(Class) * numClasses);
numClasses = objc_getClassList(classes, numClasses);
for (NSInteger classIndex = 0; classIndex < numClasses; ++classIndex) {
Class class = classes[classIndex];
if (class == [FLEXNetworkObserver class]) {
continue;
}
4.
unsigned int methodCount = 0;
Method *methods = class_copyMethodList(class, &methodCount);
5.
BOOL matchingSelectorFound = NO;
for (unsigned int methodIndex = 0; methodIndex < methodCount; methodIndex++) {
for (int selectorIndex = 0; selectorIndex < numSelectors; ++selectorIndex) {
if (method_getName(methods[methodIndex]) == selectors[selectorIndex]) {
[self injectIntoDelegateClass:class];
matchingSelectorFound = YES;
break;
}
}
if (matchingSelectorFound) {
break;
}
}
free(methods);
}
free(classes);
}
6.
[self injectIntoNSURLConnectionCancel];
[self injectIntoNSURLSessionTaskResume];
[self injectIntoNSURLConnectionAsynchronousClassMethod];
[self injectIntoNSURLConnectionSynchronousClassMethod];
[self injectIntoNSURLSessionAsyncDataAndDownloadTaskMethods];
[self injectIntoNSURLSessionAsyncUploadTaskMethods];
});
}
- 虽然有两个方法调用这里,但是还是要确保swizzle的代码只执行一次
- 需要swizzle的方法清单,基本都是代理方法
- 获取所有类,其实就是苹果在
objc_getClassList
说明的时候就推荐使用这种方法来获取 - 获取类中的所有方法列表,这里不使用
class_getInstanceMethod()
是因为不想触发类的+initialize
方法 - 如果方法实现了任何swizzle的方法中的一个方法,就进行hook
- hook其它类的一些方法(比如URLSession,URLSessionTask)
对于6中的hook就不展开讲了,基本上是一些常规swizzle的操作
对于5,+[FLEXNetworkObserver injectIntoDelegateClass:]
的实现如下:
+ (void)injectIntoDelegateClass:(Class)cls
{
[self injectWillSendRequestIntoDelegateClass:cls];
[self injectDidReceiveDataIntoDelegateClass:cls];
[self injectDidReceiveResponseIntoDelegateClass:cls];
[self injectDidFinishLoadingIntoDelegateClass:cls];
[self injectDidFailWithErrorIntoDelegateClass:cls];
[self injectTaskWillPerformHTTPRedirectionIntoDelegateClass:cls];
[self injectTaskDidReceiveDataIntoDelegateClass:cls];
[self injectTaskDidReceiveResponseIntoDelegateClass:cls];
[self injectTaskDidCompleteWithErrorIntoDelegateClass:cls];
[self injectRespondsToSelectorIntoDelegateClass:cls];
[self injectDataTaskDidBecomeDownloadTaskIntoDelegateClass:cls];
[self injectDownloadTaskDidWriteDataIntoDelegateClass:cls];
[self injectDownloadTaskDidFinishDownloadingIntoDelegateClass:cls];
}
这里基本对每一个代理函数都执行了inject,实现思路基本一样的,下面只调一个讲:
inject方法实现
+ (void)injectWillSendRequestIntoDelegateClass:(Class)cls
{
SEL selector = @selector(connection:willSendRequest:redirectResponse:);
SEL swizzledSelector = [FLEXUtility swizzledSelectorForSelector:selector];
Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
if (!protocol) {
protocol = @protocol(NSURLConnectionDelegate);
}
struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
typedef NSURLRequest *(^NSURLConnectionWillSendRequestBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response);
1.
NSURLConnectionWillSendRequestBlock undefinedBlock = ^NSURLRequest *(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) {
[[FLEXNetworkObserver sharedObserver] connection:connection willSendRequest:request redirectResponse:response delegate:slf];
return request;
};
2.
NSURLConnectionWillSendRequestBlock implementationBlock = ^NSURLRequest *(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) {
__block NSURLRequest *returnValue = nil;
[self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
undefinedBlock(slf, connection, request, response);
} originalImplementationBlock:^{
returnValue = ((id(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, connection, request, response);
}];
return returnValue;
};
[FLEXUtility replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
}
- 由于需要进行网络抓包,这意味着如果该类没有实现对应的代理方法名,也需要实现一个,这就是
undefinedBlock
的作用,可以看出抓包的信息源自于这里。 -
implementationBlock
是新方法的实现block。 - 顾名思义,就是替换方法实现,如果原本没有这个方法名,就增加一个实现是undefinedBlock的方法
sniff那个函数的实现如下:
+ (void)sniffWithoutDuplicationForObject:(NSObject *)object selector:(SEL)selector sniffingBlock:(void (^)(void))sniffingBlock originalImplementationBlock:(void (^)(void))originalImplementationBlock
{
1.
if (!object) {
originalImplementationBlock();
return;
}
const void *key = selector;
2.
if (!objc_getAssociatedObject(object, key)) {
sniffingBlock();
}
objc_setAssociatedObject(object, key, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
originalImplementationBlock();
objc_setAssociatedObject(object, key, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- 检查
object
是否存在,这里的object
指的是传进来的NSURLSession或者NSURLConnection,如果不存在,就不需要抓包,调用原函数即可 - 先调用
undefinedBlock
的函数,再调用原来的实现,这里增加了一个变量防止这个代理方法被嵌套调用多次(AFNetworking
和SDWebImage
的网络实现都存在嵌套调用的情况)
replaceImplementationOfSelector
方法方法实现如下:
+ (void)replaceImplementationOfSelector:(SEL)selector withSelector:(SEL)swizzledSelector forClass:(Class)cls withMethodDescription:(struct objc_method_description)methodDescription implementationBlock:(id)implementationBlock undefinedBlock:(id)undefinedBlock
{
1.
if ([self instanceRespondsButDoesNotImplementSelector:selector class:cls]) {
return;
}
2.
IMP implementation = imp_implementationWithBlock((id)([cls instancesRespondToSelector:selector] ? implementationBlock : undefinedBlock));
3.
Method oldMethod = class_getInstanceMethod(cls, selector);
if (oldMethod) {
class_addMethod(cls, swizzledSelector, implementation, methodDescription.types);
Method newMethod = class_getInstanceMethod(cls, swizzledSelector);
method_exchangeImplementations(oldMethod, newMethod);
} else {
class_addMethod(cls, selector, implementation, methodDescription.types);
}
}
- 判断该类是否只能响应方法但并没有实现方法,其实就是其父类实现了方法,这种场景就不进行hook
- 如果这个方法已经实现,替换的block就是
implementationBlock
,否则就是undefinedBlock
- 执行swizzle,这个swizzle跟原来的不太一样,主要在于
swizzledSelector
并不是写死在代码里的方法,hook的时候需要添加上。此外,如果对象并不响应这个方法,只需要添加一个原有的方法实现就行,不需要swizzle,此时调用的是undefinedBlock
,在里面并没有调用swizzledSelector
。
对每个网络请求的代理方法都这么做,就能手收集网络请求的数据了,接下来就是将数据进行记录,并呈现在tableView上面。这里就不展开讲了。