]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSMacOSX/helper-main.c
mDNSResponder-171.4.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 Change History (most recent first):
18
19 $Log: helper-main.c,v $
20 Revision 1.13 2007/09/21 16:13:14 cheshire
21 Additional Tiger compatibility fix: After bootstrap_check_in, we need to give
22 ourselves a Mach "send" right to the port, otherwise our ten-second idle timeout
23 mechanism is not able to send the "mDNSIdleExit" message to itself
24
25 Revision 1.12 2007/09/20 22:26:20 cheshire
26 Add necessary bootstrap_check_in() in Tiger compatibility code (not used on Leopard)
27
28 Revision 1.11 2007/09/18 19:09:02 cheshire
29 <rdar://problem/5489549> mDNSResponderHelper (and other binaries) missing SCCS version strings
30
31 Revision 1.10 2007/09/09 02:21:17 mcguire
32 <rdar://problem/5469345> Leopard Server9A547(Insatll):mDNSResponderHelper crashing
33
34 Revision 1.9 2007/09/07 22:44:03 mcguire
35 <rdar://problem/5448420> Move CFUserNotification code to mDNSResponderHelper
36
37 Revision 1.8 2007/09/07 22:24:36 vazquez
38 <rdar://problem/5466301> Need to stop spewing mDNSResponderHelper logs
39
40 Revision 1.7 2007/08/31 18:09:32 cheshire
41 <rdar://problem/5434050> Restore ability to run mDNSResponder on Tiger
42
43 Revision 1.6 2007/08/31 17:45:13 cheshire
44 Allow maxidle time of zero, meaning "run indefinitely"
45
46 Revision 1.5 2007/08/31 00:09:54 cheshire
47 Deleted extraneous whitespace (shortened code from 260 lines to 160)
48
49 Revision 1.4 2007/08/28 00:33:04 jgraessley
50 <rdar://problem/5423932> Selective compilation options
51
52 Revision 1.3 2007/08/23 23:21:24 cheshire
53 Tiger compatibility: Use old bootstrap_register() instead of Leopard-only bootstrap_register2()
54
55 Revision 1.2 2007/08/23 21:36:17 cheshire
56 Made code layout style consistent with existing project style; added $Log header
57
58 Revision 1.1 2007/08/08 22:34:58 mcguire
59 <rdar://problem/5197869> Security: Run mDNSResponder as user id mdnsresponder instead of root
60 */
61
62 #define _FORTIFY_SOURCE 2
63 #include <CoreFoundation/CoreFoundation.h>
64 #include <sys/cdefs.h>
65 #include <sys/time.h>
66 #include <sys/types.h>
67 #include <mach/mach.h>
68 #include <mach/mach_error.h>
69 #include <servers/bootstrap.h>
70 #include <asl.h>
71 #include <launch.h>
72 #include <pwd.h>
73 #include <pthread.h>
74 #include <stdarg.h>
75 #include <stdbool.h>
76 #include <stdio.h>
77 #include <stdlib.h>
78 #include <time.h>
79 #include <unistd.h>
80 #include <Security/Security.h>
81 #include "helper.h"
82 #include "helper-server.h"
83 #include "helpermsg.h"
84 #include "helpermsgServer.h"
85
86 #if TARGET_OS_EMBEDDED
87 #define NO_SECURITYFRAMEWORK 1
88 #endif
89
90 #ifndef LAUNCH_JOBKEY_MACHSERVICES
91 #define LAUNCH_JOBKEY_MACHSERVICES "MachServices"
92 #define LAUNCH_DATA_MACHPORT 10
93 #define launch_data_get_machport launch_data_get_fd
94 #endif
95
96 union max_msg_size
97 {
98 union __RequestUnion__proxy_helper_subsystem req;
99 union __ReplyUnion__proxy_helper_subsystem rep;
100 };
101
102 static const mach_msg_size_t MAX_MSG_SIZE = sizeof(union max_msg_size) + MAX_TRAILER_SIZE;
103 static aslclient logclient = NULL;
104 static int opt_debug;
105 static pthread_t idletimer_thread;
106
107 unsigned long maxidle = 10;
108 unsigned long actualidle = 3600;
109
110 CFRunLoopRef gRunLoop = NULL;
111 CFRunLoopTimerRef gTimer = NULL;
112
113 static void helplogv(int level, const char *fmt, va_list ap)
114 {
115 if (NULL == logclient) { vfprintf(stderr, fmt, ap); fflush(stderr); }
116 else asl_vlog(logclient, NULL, level, fmt, ap);
117 }
118
119 void helplog(int level, const char *fmt, ...)
120 {
121 va_list ap;
122 va_start(ap, fmt);
123 helplogv(level, fmt, ap);
124 va_end(ap);
125 }
126
127 static void initialize_logging(void)
128 {
129 logclient = asl_open(NULL, kmDNSHelperServiceName, (opt_debug ? ASL_OPT_STDERR : 0));
130 if (NULL == logclient) { fprintf(stderr, "Could not initialize ASL logging.\n"); fflush(stderr); return; }
131 if (opt_debug) asl_set_filter(logclient, ASL_FILTER_MASK_UPTO(ASL_LEVEL_DEBUG));
132 }
133
134 static void initialize_id(void)
135 {
136 static char login[] = "_mdnsresponder";
137 struct passwd *pwd = getpwnam(login);
138
139 if (!pwd) { helplog(ASL_LEVEL_ERR, "Could not find account name `%s'. I will only help root.", login); return; }
140 mDNSResponderUID = pwd->pw_uid;
141 mDNSResponderGID = pwd->pw_gid;
142 }
143
144 static void diediedie(CFRunLoopTimerRef timer, void *context)
145 {
146 debug("entry");
147 assert(gTimer == timer);
148 if (maxidle)
149 (void)proxy_mDNSIdleExit((mach_port_t)context);
150 }
151
152 void pause_idle_timer(void)
153 {
154 debug("entry");
155 assert(gTimer);
156 assert(gRunLoop);
157 CFRunLoopRemoveTimer(gRunLoop, gTimer, kCFRunLoopDefaultMode);
158 }
159
160 void unpause_idle_timer(void)
161 {
162 debug("entry");
163 assert(gRunLoop);
164 assert(gTimer);
165 CFRunLoopAddTimer(gRunLoop, gTimer, kCFRunLoopDefaultMode);
166 }
167
168 void update_idle_timer(void)
169 {
170 debug("entry");
171 assert(gTimer);
172 CFRunLoopTimerSetNextFireDate(gTimer, CFAbsoluteTimeGetCurrent() + actualidle);
173 }
174
175 static void *idletimer(void *context)
176 {
177 debug("entry context=%p", context);
178 gRunLoop = CFRunLoopGetCurrent();
179
180 unpause_idle_timer();
181
182 for (;;)
183 {
184 debug("Running CFRunLoop");
185 CFRunLoopRun();
186 sleep(1);
187 }
188
189 return NULL;
190 }
191
192 static void initialize_timer(mach_port_t port)
193 {
194 CFRunLoopTimerContext cxt = {0, (void *)port, NULL, NULL, NULL};
195 gTimer = CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + actualidle, actualidle, 0, 0, diediedie, &cxt);
196 int err = 0;
197
198 debug("entry port=%p", port);
199 if (0 != (err = pthread_create(&idletimer_thread, NULL, idletimer, (void *)port)))
200 helplog(ASL_LEVEL_ERR, "Could not start idletimer thread: %s", strerror(err));
201 }
202
203 static mach_port_t checkin(char *service_name)
204 {
205 kern_return_t kr = KERN_SUCCESS;
206 mach_port_t port = MACH_PORT_NULL;
207 launch_data_t msg = NULL, reply = NULL, datum = NULL;
208
209 if (NULL == (msg = launch_data_new_string(LAUNCH_KEY_CHECKIN)))
210 { helplog(ASL_LEVEL_ERR, "Could not create checkin message for launchd."); goto fin; }
211 if (NULL == (reply = launch_msg(msg)))
212 { helplog(ASL_LEVEL_ERR, "Could not message launchd."); goto fin; }
213 if (LAUNCH_DATA_ERRNO == launch_data_get_type(reply))
214 {
215 if (launch_data_get_errno(reply) == EACCES) { launch_data_free(msg); launch_data_free(reply); return(MACH_PORT_NULL); }
216 helplog(ASL_LEVEL_ERR, "Launchd checkin failed: %s.", strerror(launch_data_get_errno(reply))); goto fin;
217 }
218 if (NULL == (datum = launch_data_dict_lookup(reply, LAUNCH_JOBKEY_MACHSERVICES)) || LAUNCH_DATA_DICTIONARY != launch_data_get_type(datum))
219 { helplog(ASL_LEVEL_ERR, "Launchd reply does not contain %s dictionary.", LAUNCH_JOBKEY_MACHSERVICES); goto fin; }
220 if (NULL == (datum = launch_data_dict_lookup(datum, service_name)) || LAUNCH_DATA_MACHPORT != launch_data_get_type(datum))
221 { helplog(ASL_LEVEL_ERR, "Launchd reply does not contain %s Mach port.", service_name); goto fin; }
222 if (MACH_PORT_NULL == (port = launch_data_get_machport(datum)))
223 { helplog(ASL_LEVEL_ERR, "Launchd gave me a null Mach port."); goto fin; }
224 if (KERN_SUCCESS != (kr = mach_port_insert_right(mach_task_self(), port, port, MACH_MSG_TYPE_MAKE_SEND)))
225 { helplog(ASL_LEVEL_ERR, "mach_port_insert_right: %s", mach_error_string(kr)); goto fin; }
226
227 fin:
228 if (NULL != msg) launch_data_free(msg);
229 if (NULL != reply) launch_data_free(reply);
230 if (MACH_PORT_NULL == port) exit(EXIT_FAILURE);
231 return port;
232 }
233
234 static mach_port_t register_service(const char *service_name)
235 {
236 mach_port_t port = MACH_PORT_NULL;
237 kern_return_t kr;
238
239 if (KERN_SUCCESS == (kr = bootstrap_check_in(bootstrap_port, (char *)service_name, &port)))
240 {
241 if (KERN_SUCCESS != (kr = mach_port_insert_right(mach_task_self(), port, port, MACH_MSG_TYPE_MAKE_SEND)))
242 helplog(ASL_LEVEL_ERR, "mach_port_insert_right: %s", mach_error_string(kr));
243 else
244 return port;
245 }
246 if (KERN_SUCCESS != (kr = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &port)))
247 { helplog(ASL_LEVEL_ERR, "mach_port_allocate: %s", mach_error_string(kr)); goto error; }
248 if (KERN_SUCCESS != (kr = mach_port_insert_right(mach_task_self(), port, port, MACH_MSG_TYPE_MAKE_SEND)))
249 { helplog(ASL_LEVEL_ERR, "mach_port_insert_right: %s", mach_error_string(kr)); goto error; }
250 // XXX bootstrap_register does not modify its second argument, but the prototype does not include const.
251 if (KERN_SUCCESS != (kr = bootstrap_register(bootstrap_port, (char *)service_name, port)))
252 { helplog(ASL_LEVEL_ERR, "bootstrap_register failed: %s", mach_error_string(kr)); goto error; }
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 mach_port_t port = MACH_PORT_NULL;
264 long n;
265 int ch;
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 SecKeychainSetPreferenceDomain(kSecPreferencesDomainSystem);
293 #endif
294 if (!opt_debug)
295 {
296 port = checkin(kmDNSHelperServiceName);
297 if (!port) helplog(ASL_LEVEL_ERR, "Launchd provided no launchdata; will open Mach port explicitly");
298 }
299 if (!port) port = register_service(kmDNSHelperServiceName);
300
301 if (maxidle) actualidle = maxidle;
302 initialize_timer(port);
303
304 kr = mach_msg_server(helper_server, MAX_MSG_SIZE, port,
305 MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_AUDIT) | MACH_RCV_TRAILER_TYPE(MACH_MSG_TRAILER_FORMAT_0));
306 if (KERN_SUCCESS != kr)
307 { helplog(ASL_LEVEL_ERR, "mach_msg_server: %s\n", mach_error_string(kr)); exit(EXIT_FAILURE); }
308 exit(EXIT_SUCCESS);
309 }
310
311 // Note: The C preprocessor stringify operator ('#') makes a string from its argument, without macro expansion
312 // e.g. If "version" is #define'd to be "4", then STRINGIFY_AWE(version) will return the string "version", not "4"
313 // To expand "version" to its value before making the string, use STRINGIFY(version) instead
314 #define STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s) #s
315 #define STRINGIFY(s) STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s)
316
317 // For convenience when using the "strings" command, this is the last thing in the file
318 // The "@(#) " pattern is a special prefix the "what" command looks for
319 const char VersionString_SCCS[] = "@(#) mDNSResponderHelper " STRINGIFY(mDNSResponderVersion) " (" __DATE__ " " __TIME__ ")";
320
321 // If the process crashes, then this string will be magically included in the automatically-generated crash log
322 const char *__crashreporter_info__ = VersionString_SCCS + 5;
323 asm(".desc ___crashreporter_info__, 0x10");