1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2007 Apple Inc. All rights reserved.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #define _FORTIFY_SOURCE 2
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
23 #include <CoreFoundation/CoreFoundation.h>
24 #include <sys/cdefs.h>
26 #include <sys/types.h>
27 #include <mach/mach.h>
28 #include <mach/mach_error.h>
29 #include <servers/bootstrap.h>
40 #include <Security/Security.h>
42 #include "helper-server.h"
43 #include "helpermsg.h"
44 #include "helpermsgServer.h"
45 #include "safe_vproc.h"
47 #if TARGET_OS_EMBEDDED
48 #include <bootstrap_priv.h>
49 #define NO_SECURITYFRAMEWORK 1
51 #define bootstrap_register(A,B,C) bootstrap_register2((A),(B),(C),0)
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
62 union __RequestUnion__proxy_helper_subsystem req
;
63 union __ReplyUnion__proxy_helper_subsystem rep
;
66 #ifdef VPROC_HAS_TRANSACTIONS
67 typedef struct __transaction_s
69 struct __transaction_s
* next
;
70 vproc_transaction_t vt
;
73 static transaction_t
* transactions
= NULL
;
76 static const mach_msg_size_t MAX_MSG_SIZE
= sizeof(union max_msg_size
) + MAX_TRAILER_SIZE
;
77 static aslclient logclient
= NULL
;
79 static pthread_t idletimer_thread
;
81 unsigned long maxidle
= 15;
82 unsigned long actualidle
= 3600;
84 CFRunLoopRef gRunLoop
= NULL
;
85 CFRunLoopTimerRef gTimer
= NULL
;
87 mach_port_t gPort
= MACH_PORT_NULL
;
89 static void helplogv(int level
, const char *fmt
, va_list ap
)
91 if (NULL
== logclient
) { vfprintf(stderr
, fmt
, ap
); fflush(stderr
); }
92 else asl_vlog(logclient
, NULL
, level
, fmt
, ap
);
95 void helplog(int level
, const char *fmt
, ...)
99 helplogv(level
, fmt
, ap
);
104 void LogMsgWithLevel(mDNSLogLevel_t logLevel
, const char *fmt
, ...)
109 // safe_vproc only calls LogMsg, so assume logLevel maps to ASL_LEVEL_ERR
110 helplog(ASL_LEVEL_ERR
, fmt
, ap
);
114 static void handle_sigterm(int sig
)
116 // debug("entry sig=%d", sig); Can't use syslog from within a signal handler
117 assert(sig
== SIGTERM
);
118 (void)proxy_mDNSExit(gPort
);
121 static void initialize_logging(void)
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
));
128 static void initialize_id(void)
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;
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
;
141 static void diediedie(CFRunLoopTimerRef timer
, void *context
)
143 debug("entry %p %p %d", timer
, context
, maxidle
);
144 assert(gTimer
== timer
);
146 (void)proxy_mDNSExit(gPort
);
149 void pause_idle_timer(void)
154 CFRunLoopRemoveTimer(gRunLoop
, gTimer
, kCFRunLoopDefaultMode
);
157 void unpause_idle_timer(void)
162 CFRunLoopAddTimer(gRunLoop
, gTimer
, kCFRunLoopDefaultMode
);
165 void update_idle_timer(void)
169 CFRunLoopTimerSetNextFireDate(gTimer
, CFAbsoluteTimeGetCurrent() + actualidle
);
172 static void *idletimer(void *context
)
174 debug("entry context=%p", context
);
175 gRunLoop
= CFRunLoopGetCurrent();
177 unpause_idle_timer();
181 debug("Running CFRunLoop");
189 static int initialize_timer()
191 gTimer
= CFRunLoopTimerCreate(kCFAllocatorDefault
, CFAbsoluteTimeGetCurrent() + actualidle
, actualidle
, 0, 0, diediedie
, NULL
);
195 if (0 != (err
= pthread_create(&idletimer_thread
, NULL
, idletimer
, NULL
)))
196 helplog(ASL_LEVEL_ERR
, "Could not start idletimer thread: %s", strerror(err
));
201 static mach_port_t
checkin(char *service_name
)
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
;
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
))
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
;
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
; }
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
);
232 static mach_port_t
register_service(const char *service_name
)
234 mach_port_t port
= MACH_PORT_NULL
;
237 if (KERN_SUCCESS
== (kr
= bootstrap_check_in(bootstrap_port
, (char *)service_name
, &port
)))
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
));
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
; }
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
; }
255 if (MACH_PORT_NULL
!= port
) mach_port_deallocate(mach_task_self(), port
);
256 return MACH_PORT_NULL
;
259 int main(int ac
, char *av
[])
262 kern_return_t kr
= KERN_FAILURE
;
265 mach_msg_header_t hdr
;
267 while ((ch
= getopt(ac
, av
, "dt:")) != -1)
270 case 'd': opt_debug
= 1; break;
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
); }
279 fprintf(stderr
, "Usage: mDNSResponderHelper [-d] [-t maxidle]\n");
285 initialize_logging();
286 helplog(ASL_LEVEL_INFO
, "Starting");
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
);
294 gPort
= checkin(kmDNSHelperServiceName
);
297 helplog(ASL_LEVEL_ERR
, "Launchd provided no launchdata; will open Mach port explicitly");
298 gPort
= register_service(kmDNSHelperServiceName
);
301 if (maxidle
) actualidle
= maxidle
;
303 signal(SIGTERM
, handle_sigterm
);
305 if (initialize_timer()) exit(EXIT_FAILURE
);
306 for (n
=0; n
<100000; n
++) if (!gRunLoop
) usleep(100);
309 helplog(ASL_LEVEL_ERR
, "gRunLoop not set after waiting");
316 hdr
.msgh_local_port
= gPort
;
317 hdr
.msgh_remote_port
= MACH_PORT_NULL
;
318 hdr
.msgh_size
= sizeof(hdr
);
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
));
324 safe_vproc_transaction_begin();
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
); }
331 safe_vproc_transaction_end();
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)
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__
")";
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");