iOS FLEX網(wǎng)絡(luò)抓包底層原理(hook代理函數(shù))

FLEX除了支持查看UI,內(nèi)存之外,還能看網(wǎng)絡(luò)抓包,下邊探究其底層的實(shí)現(xiàn):

load/setEnabled

要想抓包,就需要對(duì)一些代理函數(shù)進(jìn)行hook,主要邏輯在FLEXNetworkObserver這個(gè)類里邊。首先既然是hook,先找到其load函數(shù)實(shí)現(xiàn)如下:

+ (void)load
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([self isEnabled]) {
            [self injectIntoAllNSURLConnectionDelegateClasses];
        }
    });
}

這里的[self isEnabled]是一個(gè)網(wǎng)絡(luò)抓包的開關(guān),用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

上面兩個(gè)方法都調(diào)用了+[FLEXNetworkObserver injectIntoAllNSURLConnectionDelegateClasses]方法,這個(gè)方法實(shí)現(xiàn)如下:

+ (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];
    });
}
  1. 雖然有兩個(gè)方法調(diào)用這里,但是還是要確保swizzle的代碼只執(zhí)行一次
  2. 需要swizzle的方法清單,基本都是代理方法
  3. 獲取所有類,其實(shí)就是蘋果在objc_getClassList說明的時(shí)候就推薦使用這種方法來獲取
  4. 獲取類中的所有方法列表,這里不使用class_getInstanceMethod()是因?yàn)椴幌胗|發(fā)類的+initialize方法
  5. 如果方法實(shí)現(xiàn)了任何swizzle的方法中的一個(gè)方法,就進(jìn)行hook
  6. hook其它類的一些方法(比如URLSession,URLSessionTask)

對(duì)于6中的hook就不展開講了,基本上是一些常規(guī)swizzle的操作
對(duì)于5,+[FLEXNetworkObserver injectIntoDelegateClass:]的實(shí)現(xiàn)如下:

+ (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];
}

這里基本對(duì)每一個(gè)代理函數(shù)都執(zhí)行了inject,實(shí)現(xiàn)思路基本一樣的,下面只調(diào)一個(gè)講:

inject方法實(shí)現(xiàn)

+ (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];
}
  1. 由于需要進(jìn)行網(wǎng)絡(luò)抓包,這意味著如果該類沒有實(shí)現(xiàn)對(duì)應(yīng)的代理方法名,也需要實(shí)現(xiàn)一個(gè),這就是undefinedBlock的作用,可以看出抓包的信息源自于這里。
  2. implementationBlock是新方法的實(shí)現(xiàn)block。
  3. 顧名思義,就是替換方法實(shí)現(xiàn),如果原本沒有這個(gè)方法名,就增加一個(gè)實(shí)現(xiàn)是undefinedBlock的方法

sniff那個(gè)函數(shù)的實(shí)現(xiàn)如下:

+ (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);
}
  1. 檢查object是否存在,這里的object指的是傳進(jìn)來的NSURLSession或者NSURLConnection,如果不存在,就不需要抓包,調(diào)用原函數(shù)即可
  2. 先調(diào)用undefinedBlock的函數(shù),再調(diào)用原來的實(shí)現(xiàn),這里增加了一個(gè)變量防止這個(gè)代理方法被嵌套調(diào)用多次(AFNetworkingSDWebImage的網(wǎng)絡(luò)實(shí)現(xiàn)都存在嵌套調(diào)用的情況)

replaceImplementationOfSelector方法方法實(shí)現(xiàn)如下:

+ (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);
    }
}
  1. 判斷該類是否只能響應(yīng)方法但并沒有實(shí)現(xiàn)方法,其實(shí)就是其父類實(shí)現(xiàn)了方法,這種場(chǎng)景就不進(jìn)行hook
  2. 如果這個(gè)方法已經(jīng)實(shí)現(xiàn),替換的block就是implementationBlock,否則就是undefinedBlock
  3. 執(zhí)行swizzle,這個(gè)swizzle跟原來的不太一樣,主要在于swizzledSelector并不是寫死在代碼里的方法,hook的時(shí)候需要添加上。此外,如果對(duì)象并不響應(yīng)這個(gè)方法,只需要添加一個(gè)原有的方法實(shí)現(xiàn)就行,不需要swizzle,此時(shí)調(diào)用的是undefinedBlock,在里面并沒有調(diào)用swizzledSelector。

對(duì)每個(gè)網(wǎng)絡(luò)請(qǐng)求的代理方法都這么做,就能手收集網(wǎng)絡(luò)請(qǐng)求的數(shù)據(jù)了,接下來就是將數(shù)據(jù)進(jìn)行記錄,并呈現(xiàn)在tableView上面。這里就不展開講了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容