]> code.delx.au - osx-proxyconf/blob - proxyconf.m
category
[osx-proxyconf] / proxyconf.m
1 #include <stdio.h>
2
3 #import <Foundation/Foundation.h>
4 #import <SystemConfiguration/SCDynamicStoreCopySpecific.h>
5
6 void
7 DXPrint(NSString* format, ...)
8 {
9 va_list args;
10 va_start(args, format);
11 NSString* string = [[NSString alloc] initWithFormat:format arguments:args];
12 va_end(args);
13 fputs([string UTF8String], stdout);
14 [string release];
15 }
16
17
18
19
20 NSDictionary* proxies;
21 BOOL proxyFound;
22
23 void
24 printUnset(NSString* env)
25 {
26 DXPrint(@"unset %@\n", env);
27 }
28
29 void
30 printProxy(NSDictionary* proxies, NSString* proto)
31 {
32 NSString* key = nil;
33 NSString* env = [[proto lowercaseString] stringByAppendingString:@"_proxy"];
34
35 key = [proto stringByAppendingString:@"Enable"];
36 NSNumber* enabled = [proxies objectForKey:key];
37 if(enabled == nil || [enabled intValue] != 1) {
38 printUnset(env);
39 return;
40 }
41
42 key = [proto stringByAppendingString:@"Proxy"];
43 id host = [proxies objectForKey:key];
44 if(host == nil) {
45 printUnset(env);
46 return;
47 }
48
49 key = [proto stringByAppendingString:@"Port"];
50 id port = [proxies objectForKey:key];
51 if(port == nil) {
52 printUnset(env);
53 return;
54 }
55
56 NSString* uriPrefix = nil;
57 if(![proto isEqual:@"SOCKS"]) {
58 uriPrefix = @"http://";
59 } else {
60 uriPrefix = @"socks://";
61 }
62
63 DXPrint(@"export %@='%@%@:%@'\n", env, uriPrefix, host, port);
64 proxyFound = YES;
65 }
66
67 void
68 printExceptions(NSDictionary* proxies)
69 {
70 id exceptions = [proxies objectForKey:@"ExceptionsList"];
71 if(exceptions == nil || ![exceptions isKindOfClass:[NSArray class]] || !proxyFound) {
72 printUnset(@"no_proxy");
73 return;
74 }
75
76 DXPrint(@"export no_proxy='%@'\n", [exceptions componentsJoinedByString:@","]);
77 }
78
79 int
80 main()
81 {
82 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
83
84 proxies = (NSDictionary*)SCDynamicStoreCopyProxies(nil);
85 proxyFound = NO;
86 printProxy(proxies, @"HTTP");
87 printProxy(proxies, @"HTTPS");
88 printProxy(proxies, @"FTP");
89 printProxy(proxies, @"SOCKS");
90 printExceptions(proxies);
91
92 [pool release];
93 return 0;
94 }
95