动态修改iOS网络配置

iOS进行系统网络设置后的同步

失败的尝试

系统网络配置默认存储在/Library/Preferences/SystemConfiguration/preferences.plist
尝试直接修改该文件,这样的效果是再次打开设置app,显示结果是更新后的配置, 然而并没有触发真正的逻辑,比如PAC更新
跟踪了一天发现系统使用SCPreferences API对配置进行增删改查,SCPreferences API通过受控方式存取XML配置并在必要时自动发送通知给其他监控配置改变的进程。使用时首先使用SCPreferencesCreate建立一个preferences的会话,在指定特定的preferences时需要传入prefsID参数,0代表访问系统默认配置;路径以/开头用于指定配置文件的绝对路径,否则是相对路径;最后使用CFRelease释放对象。SCPreferencesPath API可以以字典方式访问配置;

API

SCPreferencesRef SCPreferencesCreate(CFAllocatorRef allocator, 
    CFStringRef name,       // 进程标识
    CFStringRef prefsID)    // preferences组名
SCPreferencesRef SCPreferencesCreateWithAuthorization(CFAllocatorRef allocator,
    CFStringRef name,
    CFStringRef prefsID,
    AuthorizationRef authorization) // 提权访问
Boolean SCPreferencesLock(SCPreferencesRef prefs, Boolean wait) // exclusive方式锁定preferences
Boolean SCPreferencesCommitChanges(SCPreferencesRef prefs)      // commit对preferences的修改并持久化存储
Boolean SCPreferencesApplyChanges(SCPreferencesRef prefs)       // 将当前存储的preferences应用到活跃的配置中
Boolean SCPreferencesUnlock(SCPreferencesRef prefs)
CFArrayRef SCPreferencesCopyKeyList(SCPreferencesRef prefs)     // 获取当前定义的preferences键
CFPropertyListRef SCPreferencesGetValue(SCPreferencesRef prefs, CFStringRef key)
Boolean SCPreferencesAddValue(SCPreferencesRef prefs, CFStringRef key, CFPropertyListRef value)
Boolean SCPreferencesSetValue(SCPreferencesRef prefs, CFStringRef key, CFPropertyListRef value)
Boolean SCPreferencesRemoveValue(SCPreferencesRef prefs, CFStringRef key)
void SCPreferencesSynchronize(SCPreferencesRef prefs)           // 使用commit的preferences来访问
CFDictionaryRef SCPreferencesPathGetValue(SCPreferencesRef prefs, CFStringRef path)
CFStringRef SCPreferencesPathGetLink(SCPreferencesRef prefs, CFStringRef path)
Boolean SCPreferencesPathSetValue(SCPreferencesRef prefs, CFStringRef path, CFDictionaryRef value)
Boolean SCPreferencesPathSetLink(SCPreferencesRef prefs, CFStringRef path, CFStringRef link)
Boolean SCPreferencesPathRemoveValue(SCPreferencesRef prefs, CFStringRef path)                          

具体实现

#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
#import <Foundation/Foundation.h>

typedef void* SCPreferencesRef;
typedef void* AuthorizationRef;
SCPreferencesRef (*_SCPreferencesCreate)(CFAllocatorRef allocator, NSString* name, NSString* prefsID);
SCPreferencesRef (*_SCPreferencesCreateWithAuthorization)(CFAllocatorRef allocator, NSString* name,
    NSString* prefsID, AuthorizationRef authorization);
Boolean (*_SCPreferencesLock)(SCPreferencesRef prefs, Boolean wait);
Boolean (*_SCPreferencesCommitChanges)(SCPreferencesRef prefs);
Boolean (*_SCPreferencesApplyChanges)(SCPreferencesRef prefs);
Boolean (*_SCPreferencesUnlock)(SCPreferencesRef prefs);
NSArray* (*_SCPreferencesCopyKeyList)(SCPreferencesRef prefs);
id (*_SCPreferencesGetValue)(SCPreferencesRef prefs, NSString* key);
Boolean (*_SCPreferencesAddValue)(SCPreferencesRef prefs, NSString* key, id value);
Boolean (*_SCPreferencesSetValue)(SCPreferencesRef prefs, NSString* key, id value);
Boolean (*_SCPreferencesRemoveValue)(SCPreferencesRef prefs, NSString* key);
void (*_SCPreferencesSynchronize)(SCPreferencesRef prefs);
NSDictionary* (*_SCPreferencesPathGetValue)(SCPreferencesRef prefs, NSString* path);
NSString* (*_SCPreferencesPathGetLink)(SCPreferencesRef prefs, NSString* path);
Boolean (*_SCPreferencesPathSetValue)(SCPreferencesRef prefs, NSString* path, NSDictionary* value);
Boolean (*_SCPreferencesPathSetLink)(SCPreferencesRef prefs, NSString* path, NSString* link);
Boolean (*_SCPreferencesPathRemoveValue)(SCPreferencesRef prefs, NSString* path);

void FLog(NSString* msg) {
    NSLog(@"%@", msg);
}

int main(int argc, char **argv, char **envp) {
    _SCPreferencesCreate = (typeof(_SCPreferencesCreate))dlsym(RTLD_DEFAULT, "SCPreferencesCreate");
    _SCPreferencesCreateWithAuthorization = (typeof(_SCPreferencesCreateWithAuthorization))dlsym(RTLD_DEFAULT, 
        "SCPreferencesCreateWithAuthorization");
    _SCPreferencesLock = (typeof(_SCPreferencesLock))dlsym(RTLD_DEFAULT, "SCPreferencesLock");
    _SCPreferencesCommitChanges = (typeof(_SCPreferencesCommitChanges))dlsym(RTLD_DEFAULT, "SCPreferencesCommitChanges");
    _SCPreferencesApplyChanges = (typeof(_SCPreferencesApplyChanges))dlsym(RTLD_DEFAULT, "SCPreferencesApplyChanges");
    _SCPreferencesUnlock = (typeof(_SCPreferencesUnlock))dlsym(RTLD_DEFAULT, "SCPreferencesUnlock");
    _SCPreferencesCopyKeyList = (typeof(_SCPreferencesCopyKeyList))dlsym(RTLD_DEFAULT, "SCPreferencesCopyKeyList");
    _SCPreferencesGetValue = (typeof(_SCPreferencesGetValue))dlsym(RTLD_DEFAULT, "SCPreferencesGetValue");
    _SCPreferencesAddValue = (typeof(_SCPreferencesAddValue))dlsym(RTLD_DEFAULT, "SCPreferencesAddValue");
    _SCPreferencesSetValue = (typeof(_SCPreferencesSetValue))dlsym(RTLD_DEFAULT, "SCPreferencesSetValue");
    _SCPreferencesRemoveValue = (typeof(_SCPreferencesRemoveValue))dlsym(RTLD_DEFAULT, "SCPreferencesRemoveValue");
    _SCPreferencesSynchronize = (typeof(_SCPreferencesSynchronize))dlsym(RTLD_DEFAULT, "SCPreferencesSynchronize");
    _SCPreferencesPathGetValue = (typeof(_SCPreferencesPathGetValue))dlsym(RTLD_DEFAULT, "SCPreferencesPathGetValue");
    _SCPreferencesPathGetLink = (typeof(_SCPreferencesPathGetLink))dlsym(RTLD_DEFAULT, "SCPreferencesPathGetLink");
    _SCPreferencesPathSetValue = (typeof(_SCPreferencesPathSetValue))dlsym(RTLD_DEFAULT, "SCPreferencesPathSetValue");
    _SCPreferencesPathSetLink = (typeof(_SCPreferencesPathSetLink))dlsym(RTLD_DEFAULT, "SCPreferencesPathSetLink");
    _SCPreferencesPathRemoveValue = (typeof(_SCPreferencesPathRemoveValue))dlsym(RTLD_DEFAULT, "SCPreferencesPathRemoveValue");

    if (argc < 2) {
        return 0;
    }
    NSMutableDictionary* proxyconf = [[NSMutableDictionary alloc] init];
    proxyconf[@"proxymode"] = [NSString stringWithUTF8String:argv[1]];
    if ([proxyconf[@"proxymode"] isEqualToString:@"close"]) {
    } else if ([proxyconf[@"proxymode"] isEqualToString:@"manual"]) {
        proxyconf[@"proxyhost"] = [NSString stringWithUTF8String:argv[2]];
        proxyconf[@"proxyport"] = @([[NSString stringWithUTF8String:argv[3]] integerValue]);
    } else if ([proxyconf[@"proxymode"] isEqualToString:@"auto"]) {
        proxyconf[@"proxyurl"] = [NSString stringWithUTF8String:argv[2]];
    }

    SCPreferencesRef prefs = _SCPreferencesCreate(nil, @"", nil);
    _SCPreferencesLock(prefs, TRUE);
    BOOL change_proxy_success = NO;
    do {
        NSString* CurrentSet = (NSString*)_SCPreferencesGetValue(prefs, @"CurrentSet");
        if (CurrentSet == nil) {
            FLog(@"unchroot CurrentSet nil");
            break;
        }
        NSString* IPv4Path = [NSString stringWithFormat:@"%@/Network/Global/IPv4", CurrentSet];
        NSDictionary* IPv4 = _SCPreferencesPathGetValue(prefs, IPv4Path);
        NSString* service_en0 = nil;
        if (IPv4 == nil || ![[IPv4 allKeys] containsObject:@"ServiceOrder"]) {
            FLog(@"unchroot IPv4 nil");
            break;
        }
        for (NSString* service in IPv4[@"ServiceOrder"]) {
            NSString* InterfacePath = [NSString stringWithFormat:@"/NetworkServices/%@/Interface", service];
            NSDictionary* Interface = _SCPreferencesPathGetValue(prefs, InterfacePath);
            if (Interface == nil) {
                continue;
            }
            if ([Interface[@"DeviceName"] isEqualToString:@"en0"]) {
                service_en0 = service;
            }
        }
        if (service_en0 == nil) {
            FLog(@"unchroot service.en0 not exist");
            break;
        }
        NSString* ServiceEn0Path = [NSString stringWithFormat:@"/NetworkServices/%@", service_en0];
        NSDictionary* ServiceEn0 = _SCPreferencesPathGetValue(prefs, ServiceEn0Path);
        if (ServiceEn0 == nil) {
            FLog(@"unchroot service.en0 nil");
            break;
        }
        NSMutableDictionary* serviceobj = [[ServiceEn0 mutableCopy] autorelease];
        if ([proxyconf[@"proxymode"] isEqualToString:@"close"]) {
            serviceobj[@"Proxies"] = @{
                @"FTPPassive": @1, 
                @"ExceptionsList": @[
                    @"*.local", 
                    @"169.254/16"
                ]
            };
        } else if ([proxyconf[@"proxymode"] isEqualToString:@"manual"]) {
            if (![[proxyconf allKeys] containsObject:@"proxyhost"] || 
                    ![[proxyconf allKeys] containsObject:@"proxyport"]) {
                FLog(@"unchroot lack of param proxyhost or proxyport");
                break;
            }
            serviceobj[@"Proxies"] = @{
                @"HTTPProxy": proxyconf[@"proxyhost"], 
                @"HTTPPort": proxyconf[@"proxyport"], 
                @"HTTPSProxy": proxyconf[@"proxyhost"], 
                @"HTTPSPort": proxyconf[@"proxyport"],
                @"HTTPEnable": @1, 
                @"HTTPSEnable": @1, 
                @"FTPPassive": @1,
                @"ExceptionsList": @[
                    @"*.local", 
                    @"169.254/16"
                ]
            };
        } else if ([proxyconf[@"proxymode"] isEqualToString:@"auto"]) {
            if (![[proxyconf allKeys] containsObject:@"proxyurl"]) {
                FLog(@"unchroot lack of param proxyurl");
                break;
            }
            serviceobj[@"Proxies"] = @{
                @"FTPPassive": @1, 
                @"ExceptionsList": @[
                    @"*.local", 
                    @"169.254/16"
                ], 
                @"ProxyAutoConfigEnable": @1, 
                @"ProxyAutoConfigURLString": proxyconf[@"proxyurl"]
            };
        } else {
            FLog(@"unchroot unknown proxymode");
            break;
        }
        if (_SCPreferencesPathSetValue(prefs, ServiceEn0Path, serviceobj)) {
            change_proxy_success = YES;
        }
    } while (false);
    if (change_proxy_success) {
        _SCPreferencesCommitChanges(prefs);
        _SCPreferencesApplyChanges(prefs);
        _SCPreferencesSynchronize(prefs);
    }
    _SCPreferencesUnlock(prefs);
    CFRelease(prefs);

    if (change_proxy_success) {
        printf("change ok\n");
    } else {
        printf("change fail\n");
    }
    return 0;
}

最后要注意,使用SCPreferences API需要签名:

<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>platform-application</key>
    <true/>
  </dict>
</plist>
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容

  • 1,NSObject中description属性的意义,它可以重写吗?答案:每当 NSLog(@"")函数中出现 ...
    eightzg阅读 4,077评论 2 19
  • feisky云计算、虚拟化与Linux技术笔记posts - 1014, comments - 298, trac...
    不排版阅读 3,753评论 0 5
  • 去年有段时间得空,就把谷歌GAE的API权威指南看了一遍,收获颇丰,特别是在自己几乎独立开发了公司的云数据中心之后...
    骑单车的勋爵阅读 20,127评论 0 41
  • 文/宏木每 哆唻咪发索拉西 你的黑键我的白键
    宏木每阅读 124评论 0 0
  • 最近换了一份工作,一下子变得忙碌起来,每周更新一篇文章的任务险些完不成了。 趁中午的间隙,我努力整理一下最近的思绪...
    素素琴阅读 171评论 0 0