]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSMacOSX/helper-main.c
mDNSResponder-258.18.tar.gz
[apple/mdnsresponder.git] / mDNSMacOSX / helper-main.c
1 /* -*- Mode: C; tab-width: 4 -*-
2 *
3 * Copyright (c) 2007 Apple Inc. All rights reserved.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 #define _FORTIFY_SOURCE 2
19
20 // We set VERSION_MIN_REQUIRED to 10.4 to avoid "bootstrap_register is deprecated" warnings from bootstrap.h
21 #define MAC_OS_X_VERSION_MIN_REQUIRED MAC_OS_X_VERSION_10_4
22
23 #include <CoreFoundation/CoreFoundation.h>
24 #include <sys/cdefs.h>
25 #include <sys/time.h>
26 #include <sys/types.h>
27 #include <mach/mach.h>
28 #include <mach/mach_error.h>
29 #include <servers/bootstrap.h>
30 #include <asl.h>
31 #include <launch.h>
32 #include <pwd.h>
33 #include <pthread.h>
34 #include <stdarg.h>
35 #include <stdbool.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <time.h>
39 #include <unistd.h>
40 #include <Security/Security.h>
41 #include "helper.h"
42 #include "helper-server.h"
43 #include "helpermsg.h"
44 #include "helpermsgServer.h"
45 #include "safe_vproc.h"
46
47 #if TARGET_OS_EMBEDDED
48 #include <bootstrap_priv.h>
49 #define NO_SECURITYFRAMEWORK 1
50
51 #define bootstrap_register(A,B,C) bootstrap_register2((A),(B),(C),0)
52 #endif
53
54 #ifndef LAUNCH_JOBKEY_MACHSERVICES
55 #define LAUNCH_JOBKEY_MACHSERVICES "MachServices"
56 #define LAUNCH_DATA_MACHPORT 10
57 #define launch_data_get_machport launch_data_get_fd
58 #endif
59
60 union max_msg_size
61 {
62 union __RequestUnion__proxy_helper_subsystem req;
63 union __ReplyUnion__proxy_helper_subsystem rep;
64 };
65
66 #ifdef VPROC_HAS_TRANSACTIONS
67 typedef struct __transaction_s
68 {
69 struct __transaction_s* next;
70 vproc_transaction_t vt;
71 } transaction_t;
72
73 static transaction_t* transactions = NULL;
74 #endif
75
76 static const mach_msg_size_t MAX_MSG_SIZE = sizeof(union max_msg_size) + MAX_TRAILER_SIZE;
77 static aslclient logclient = NULL;
78 static int opt_debug;
79 static pthread_t idletimer_thread;
80
81 unsigned long maxidle = 15;
82 unsigned long actualidle = 3600;
83
84 CFRunLoopRef gRunLoop = NULL;
85 CFRunLoopTimerRef gTimer = NULL;
86
87 mach_port_t gPort = MACH_PORT_NULL;
88
89 static void helplogv(int level, const char *fmt, va_list ap)
90 {
91 if (NULL == logclient) { vfprintf(stderr, fmt, ap); fflush(stderr); }
92 else asl_vlog(logclient, NULL, level, fmt, ap);
93 }
94
95 void helplog(int level, const char *fmt, ...)
96 {
97 va_list ap;
98 va_start(ap, fmt);
99 helplogv(level, fmt, ap);
100 va_end(ap);
101 }
102
103 // for safe_vproc
104 void LogMsgWithLevel(mDNSLogLevel_t logLevel, const char *fmt, ...)
105 {
106 (void)logLevel;
107 va_list ap;
108 va_start(ap, fmt);
109 // safe_vproc only calls LogMsg, so assume logLevel maps to ASL_LEVEL_ERR
110 helplog(ASL_LEVEL_ERR, fmt, ap);
111 va_end(ap);
112 }
113
114 static void handle_sigterm(int sig)
115 {
116 // debug("entry sig=%d", sig); Can't use syslog from within a signal handler
117 assert(sig == SIGTERM);
118 (void)proxy_mDNSExit(gPort);
119 }
120
121 static void initialize_logging(void)
122 {
123 logclient = asl_open(NULL, kmDNSHelperServiceName, (opt_debug ? ASL_OPT_STDERR : 0));
124 if (NULL == logclient) { fprintf(stderr, "Could not initialize ASL logging.\n"); fflush(stderr); return; }
125 if (opt_debug) asl_set_filter(logclient, ASL_FILTER_MASK_UPTO(ASL_LEVEL_DEBUG));
126 }
127
128 static void initialize_id(void)
129 {
130 static char login[] = "_mdnsresponder";
131 struct passwd hardcode;
132 struct passwd *pwd = &hardcode; // getpwnam(login);
133 hardcode.pw_uid = 65;
134 hardcode.pw_gid = 65;
135
136 if (!pwd) { helplog(ASL_LEVEL_ERR, "Could not find account name `%s'. I will only help root.", login); return; }
137 mDNSResponderUID = pwd->pw_uid;
138 mDNSResponderGID = pwd->pw_gid;
139 }
140
141 static void diediedie(CFRunLoopTimerRef timer, void *context)
142 {
143 debug("entry %p %p %d", timer, context, maxidle);
144 assert(gTimer == timer);
145 if (maxidle)
146 (void)proxy_mDNSExit(gPort);
147 }
148
149 void pause_idle_timer(void)
150 {
151 debug("entry");
152 assert(gTimer);
153 assert(gRunLoop);
154 CFRunLoopRemoveTimer(gRunLoop, gTimer, kCFRunLoopDefaultMode);
155 }
156
157 void unpause_idle_timer(void)
158 {
159 debug("entry");
160 assert(gRunLoop);
161 assert(gTimer);
162 CFRunLoopAddTimer(gRunLoop, gTimer, kCFRunLoopDefaultMode);
163 }
164
165 void update_idle_timer(void)
166 {
167 debug("entry");
168 assert(gTimer);
169 CFRunLoopTimerSetNextFireDate(gTimer, CFAbsoluteTimeGetCurrent() + actualidle);
170 }
171
172 static void *idletimer(void *context)
173 {
174 debug("entry context=%p", context);
175 gRunLoop = CFRunLoopGetCurrent();
176
177 unpause_idle_timer();
178
179 for (;;)
180 {
181 debug("Running CFRunLoop");
182 CFRunLoopRun();
183 sleep(1);
184 }
185
186 return NULL;
187 }
188
189 static int initialize_timer()
190 {
191 gTimer = CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + actualidle, actualidle, 0, 0, diediedie, NULL);
192 int err = 0;
193
194 debug("entry");
195 if (0 != (err = pthread_create(&idletimer_thread, NULL, idletimer, NULL)))
196 helplog(ASL_LEVEL_ERR, "Could not start idletimer thread: %s", strerror(err));
197
198 return err;
199 }
200
201 static mach_port_t checkin(char *service_name)
202 {
203 kern_return_t kr = KERN_SUCCESS;
204 mach_port_t port = MACH_PORT_NULL;
205 launch_data_t msg = NULL, reply = NULL, datum = NULL;
206
207 if (NULL == (msg = launch_data_new_string(LAUNCH_KEY_CHECKIN)))
208 { helplog(ASL_LEVEL_ERR, "Could not create checkin message for launchd."); goto fin; }
209 if (NULL == (reply = launch_msg(msg)))
210 { helplog(ASL_LEVEL_ERR, "Could not message launchd."); goto fin; }
211 if (LAUNCH_DATA_ERRNO == launch_data_get_type(reply))
212 {
213 if (launch_data_get_errno(reply) == EACCES) { launch_data_free(msg); launch_data_free(reply); return(MACH_PORT_NULL); }
214 helplog(ASL_LEVEL_ERR, "Launchd checkin failed: %s.", strerror(launch_data_get_errno(reply))); goto fin;
215 }
216 if (NULL == (datum = launch_data_dict_lookup(reply, LAUNCH_JOBKEY_MACHSERVICES)) || LAUNCH_DATA_DICTIONARY != launch_data_get_type(datum))
217 { helplog(ASL_LEVEL_ERR, "Launchd reply does not contain %s dictionary.", LAUNCH_JOBKEY_MACHSERVICES); goto fin; }
218 if (NULL == (datum = launch_data_dict_lookup(datum, service_name)) || LAUNCH_DATA_MACHPORT != launch_data_get_type(datum))
219 { helplog(ASL_LEVEL_ERR, "Launchd reply does not contain %s Mach port.", service_name); goto fin; }
220 if (MACH_PORT_NULL == (port = launch_data_get_machport(datum)))
221 { helplog(ASL_LEVEL_ERR, "Launchd gave me a null Mach port."); goto fin; }
222 if (KERN_SUCCESS != (kr = mach_port_insert_right(mach_task_self(), port, port, MACH_MSG_TYPE_MAKE_SEND)))
223 { helplog(ASL_LEVEL_ERR, "mach_port_insert_right: %d %X %s", kr, kr, mach_error_string(kr)); goto fin; }
224
225 fin:
226 if (NULL != msg) launch_data_free(msg);
227 if (NULL != reply) launch_data_free(reply);
228 if (MACH_PORT_NULL == port) exit(EXIT_FAILURE);
229 return port;
230 }
231
232 static mach_port_t register_service(const char *service_name)
233 {
234 mach_port_t port = MACH_PORT_NULL;
235 kern_return_t kr;
236
237 if (KERN_SUCCESS == (kr = bootstrap_check_in(bootstrap_port, (char *)service_name, &port)))
238 {
239 if (KERN_SUCCESS != (kr = mach_port_insert_right(mach_task_self(), port, port, MACH_MSG_TYPE_MAKE_SEND)))
240 helplog(ASL_LEVEL_ERR, "mach_port_insert_right: %d %X %s", kr, kr, mach_error_string(kr));
241 else
242 return port;
243 }
244 if (KERN_SUCCESS != (kr = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &port)))
245 { helplog(ASL_LEVEL_ERR, "mach_port_allocate: %d %X %s", kr, kr, mach_error_string(kr)); goto error; }
246 if (KERN_SUCCESS != (kr = mach_port_insert_right(mach_task_self(), port, port, MACH_MSG_TYPE_MAKE_SEND)))
247 { helplog(ASL_LEVEL_ERR, "mach_port_insert_right: %d %X %s", kr, kr, mach_error_string(kr)); goto error; }
248
249 // XXX bootstrap_register does not modify its second argument, but the prototype does not include const.
250 if (KERN_SUCCESS != (kr = bootstrap_register(bootstrap_port, (char *)service_name, port)))
251 { helplog(ASL_LEVEL_ERR, "bootstrap_register failed: %s %d %X %s", service_name, kr, kr, mach_error_string(kr)); goto error; }
252
253 return port;
254 error:
255 if (MACH_PORT_NULL != port) mach_port_deallocate(mach_task_self(), port);
256 return MACH_PORT_NULL;
257 }
258
259 int main(int ac, char *av[])
260 {
261 char *p = NULL;
262 kern_return_t kr = KERN_FAILURE;
263 long n;
264 int ch;
265 mach_msg_header_t hdr;
266
267 while ((ch = getopt(ac, av, "dt:")) != -1)
268 switch (ch)
269 {
270 case 'd': opt_debug = 1; break;
271 case 't':
272 n = strtol(optarg, &p, 0);
273 if ('\0' == optarg[0] || '\0' != *p || n > LONG_MAX || n < 0)
274 { fprintf(stderr, "Invalid idle timeout: %s\n", optarg); exit(EXIT_FAILURE); }
275 maxidle = n;
276 break;
277 case '?':
278 default:
279 fprintf(stderr, "Usage: mDNSResponderHelper [-d] [-t maxidle]\n");
280 exit(EXIT_FAILURE);
281 }
282 ac -= optind;
283 av += optind;
284
285 initialize_logging();
286 helplog(ASL_LEVEL_INFO, "Starting");
287 initialize_id();
288
289 #ifndef NO_SECURITYFRAMEWORK
290 // We should normally be running as a system daemon. However, that might not be the case in some scenarios (e.g. debugging).
291 // Explicitly ensure that our Keychain operations utilize the system domain.
292 if (opt_debug) SecKeychainSetPreferenceDomain(kSecPreferencesDomainSystem);
293 #endif
294 gPort = checkin(kmDNSHelperServiceName);
295 if (!gPort)
296 {
297 helplog(ASL_LEVEL_ERR, "Launchd provided no launchdata; will open Mach port explicitly");
298 gPort = register_service(kmDNSHelperServiceName);
299 }
300
301 if (maxidle) actualidle = maxidle;
302
303 signal(SIGTERM, handle_sigterm);
304
305 if (initialize_timer()) exit(EXIT_FAILURE);
306 for (n=0; n<100000; n++) if (!gRunLoop) usleep(100);
307 if (!gRunLoop)
308 {
309 helplog(ASL_LEVEL_ERR, "gRunLoop not set after waiting");
310 exit(EXIT_FAILURE);
311 }
312
313 for(;;)
314 {
315 hdr.msgh_bits = 0;
316 hdr.msgh_local_port = gPort;
317 hdr.msgh_remote_port = MACH_PORT_NULL;
318 hdr.msgh_size = sizeof(hdr);
319 hdr.msgh_id = 0;
320 kr = mach_msg(&hdr, MACH_RCV_LARGE | MACH_RCV_MSG, 0, hdr.msgh_size, gPort, 0, 0);
321 if (MACH_RCV_TOO_LARGE != kr)
322 helplog(ASL_LEVEL_ERR, "main MACH_RCV_MSG error: %d %X %s", kr, kr, mach_error_string(kr));
323
324 safe_vproc_transaction_begin();
325
326 kr = mach_msg_server_once(helper_server, MAX_MSG_SIZE, gPort,
327 MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_AUDIT) | MACH_RCV_TRAILER_TYPE(MACH_MSG_TRAILER_FORMAT_0));
328 if (KERN_SUCCESS != kr)
329 { helplog(ASL_LEVEL_ERR, "mach_msg_server: %d %X %s", kr, kr, mach_error_string(kr)); exit(EXIT_FAILURE); }
330
331 safe_vproc_transaction_end();
332 }
333 exit(EXIT_SUCCESS);
334 }
335
336 // Note: The C preprocessor stringify operator ('#') makes a string from its argument, without macro expansion
337 // e.g. If "version" is #define'd to be "4", then STRINGIFY_AWE(version) will return the string "version", not "4"
338 // To expand "version" to its value before making the string, use STRINGIFY(version) instead
339 #define STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s) #s
340 #define STRINGIFY(s) STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s)
341
342 // For convenience when using the "strings" command, this is the last thing in the file
343 // The "@(#) " pattern is a special prefix the "what" command looks for
344 const char VersionString_SCCS[] = "@(#) mDNSResponderHelper " STRINGIFY(mDNSResponderVersion) " (" __DATE__ " " __TIME__ ")";
345
346 #if _BUILDING_XCODE_PROJECT_
347 // If the process crashes, then this string will be magically included in the automatically-generated crash log
348 const char *__crashreporter_info__ = VersionString_SCCS + 5;
349 asm(".desc ___crashreporter_info__, 0x10");
350 #endif