]> code.delx.au - osx-proxyconf/blob - sysconfig.c
Autodetect value types
[osx-proxyconf] / sysconfig.c
1 #include <CoreFoundation/CoreFoundation.h>
2 #include <SystemConfiguration/SCDynamicStoreCopySpecific.h>
3
4 const char* KEYFILE = "/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCSchemaDefinitions.h";
5
6
7 Boolean
8 getDictValue(CFTypeRef* value, CFStringRef key)
9 {
10 assert(value != NULL);
11 assert(key != NULL);
12
13 Boolean result;
14 CFDictionaryRef dictRef;
15 dictRef = SCDynamicStoreCopyProxies((SCDynamicStoreRef)NULL);
16 result = (dictRef != NULL);
17 if(result) {
18 *value = (CFNumberRef)CFDictionaryGetValue(dictRef, key);
19 }
20 if(*value != NULL) {
21 CFRetain(*value);
22 }
23
24 if(dictRef != NULL) {
25 CFRelease(dictRef);
26 }
27 if(!result) {
28 *value = NULL;
29 }
30 return result;
31 }
32
33 Boolean
34 printNumber(CFNumberRef numberRef)
35 {
36 assert(numberRef != NULL);
37
38 int numberVal = 0;
39 if(CFNumberGetValue(numberRef, kCFNumberIntType, &numberVal)) {
40 printf("%d\n", numberVal);
41 return TRUE;
42 }
43 return FALSE;
44 }
45
46 Boolean
47 printString(CFStringRef strRef)
48 {
49 assert(strRef != NULL);
50
51 char strVal[1024];
52 if(CFStringGetCString(strRef, strVal, (CFIndex)1024,
53 kCFStringEncodingASCII))
54 {
55 printf("%s\n", strVal);
56 return TRUE;
57 }
58 return FALSE;
59 }
60
61 CFStringRef
62 createCFString(const char* str)
63 {
64 return CFStringCreateWithCStringNoCopy(NULL, str,
65 kCFStringEncodingASCII,
66 kCFAllocatorNull);
67 }
68
69 void
70 usage(const char* program)
71 {
72 fprintf(stderr, "Usage: %s [-q] key\n", program);
73 fprintf(stderr, "Look in %s for keys. Eg, HTTPProxy\n\n", KEYFILE);
74 }
75
76 int
77 main(int argc, char** argv)
78 {
79 int quiet = 0;
80 const char* key;
81 if(argc == 2) {
82 key = argv[1];
83 } else if(argc == 3 && strcmp("-q", argv[1]) == 0) {
84 quiet = 1;
85 key = argv[2];
86 } else {
87 usage(argv[0]);
88 return 1;
89 }
90
91
92 CFStringRef keyRef = createCFString(argv[1]);
93 if(keyRef == NULL) {
94 fprintf(stderr, "Fatal error: Couldn't create CFStringRef from arg2\n");
95 return 1;
96 }
97
98 CFTypeRef valueRef = NULL;
99 if(!getDictValue(&valueRef, keyRef)) {
100 fprintf(stderr, "Fatal error: Error accessing dictionary\n");
101 return 1;
102 }
103
104 if(valueRef == NULL) {
105 if(!quiet) {
106 fprintf(stderr, "No value for that key\n");
107 }
108 return 0;
109 }
110 else if(CFStringGetTypeID() == CFGetTypeID(valueRef)) {
111 printString((CFStringRef)valueRef);
112 }
113 else if(CFNumberGetTypeID() == CFGetTypeID(valueRef)) {
114 printNumber((CFNumberRef)valueRef);
115 }
116 else {
117 fprintf(stderr, "Fatal error: Unsupported value type in dictionary\n");
118 CFRelease(valueRef);
119 return 1;
120 }
121
122 CFRelease(valueRef);
123 return 0;
124 }
125