2 * Copyright (c) 2005 Apple Computer, Inc. All rights reserved.
4 * @APPLE_APACHE_LICENSE_HEADER_START@
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * @APPLE_APACHE_LICENSE_HEADER_END@
21 static const char *const __rcs_file_version__
= "$Revision: 23930 $";
25 #include "launch_priv.h"
26 #include "bootstrap.h"
28 #include "vproc_priv.h"
29 #include "vproc_internal.h"
30 #include "bootstrap_priv.h"
31 #include "launch_internal.h"
33 #include <CoreFoundation/CoreFoundation.h>
34 #include <CoreFoundation/CFPriv.h>
35 #include <CoreFoundation/CFLogUtilities.h>
36 #include <TargetConditionals.h>
38 #include <Security/Security.h>
39 #include <Security/AuthSession.h>
41 #include <IOKit/IOKitLib.h>
42 #include <NSSystemDirectories.h>
43 #include <mach/mach.h>
44 #include <sys/types.h>
45 #include <sys/sysctl.h>
47 #include <sys/sysctl.h>
49 #include <sys/socket.h>
51 /* This is just so it's easy for me to compile launchctl without buildit. */
52 #define SO_EXECPATH 0x1085
55 #include <sys/fcntl.h>
56 #include <sys/event.h>
57 #include <sys/resource.h>
58 #include <sys/param.h>
59 #include <sys/mount.h>
60 #include <sys/reboot.h>
62 #include <netinet/in.h>
63 #include <netinet/in_var.h>
64 #include <netinet6/nd6.h>
76 #include <readline/readline.h>
77 #include <readline/history.h>
81 #include <bootfiles.h>
85 #include <sys/syslimits.h>
88 #include <bsm/auditd_lib.h>
89 #ifndef AUDITD_PLIST_FILE
90 #define AUDITD_PLIST_FILE "/System/Library/LaunchDaemons/com.apple.auditd.plist"
94 extern char **environ
;
97 #define LAUNCH_SECDIR _PATH_TMP "launch-XXXXXX"
99 #define MACHINIT_JOBKEY_ONDEMAND "OnDemand"
100 #define MACHINIT_JOBKEY_SERVICENAME "ServiceName"
101 #define MACHINIT_JOBKEY_COMMAND "Command"
102 #define MACHINIT_JOBKEY_SERVERPORT "ServerPort"
103 #define MACHINIT_JOBKEY_SERVICEPORT "ServicePort"
106 (__builtin_expect(!(e), 0) ? _log_launchctl_bug(__rcs_file_version__, __FILE__, __LINE__, #e), false : true)
108 #define CFTypeCheck(cf, type) (CFGetTypeID(cf) == type ## GetTypeID())
110 struct load_unload_state
{
115 bool editondisk
:1, load
:1, forceload
:1;
118 static void myCFDictionaryApplyFunction(const void *key
, const void *value
, void *context
);
119 static void job_override(CFTypeRef key
, CFTypeRef val
, CFMutableDictionaryRef job
);
120 static CFTypeRef
CFTypeCreateFromLaunchData(launch_data_t obj
);
121 static CFArrayRef
CFArrayCreateFromLaunchArray(launch_data_t arr
);
122 static CFDictionaryRef
CFDictionaryCreateFromLaunchDictionary(launch_data_t dict
);
123 static bool launch_data_array_append(launch_data_t a
, launch_data_t o
);
124 static void distill_jobs(launch_data_t
);
125 static void distill_config_file(launch_data_t
);
126 static void sock_dict_cb(launch_data_t what
, const char *key
, void *context
);
127 static void sock_dict_edit_entry(launch_data_t tmp
, const char *key
, launch_data_t fdarray
, launch_data_t thejob
);
128 static launch_data_t
CF2launch_data(CFTypeRef
);
129 static launch_data_t
read_plist_file(const char *file
, bool editondisk
, bool load
);
130 static CFPropertyListRef
CreateMyPropertyListFromFile(const char *);
131 static CFPropertyListRef
CFPropertyListCreateFromFile(CFURLRef plistURL
);
132 static void WriteMyPropertyListToFile(CFPropertyListRef
, const char *);
133 static bool path_goodness_check(const char *path
, bool forceload
);
134 static void readpath(const char *, struct load_unload_state
*);
135 static void readfile(const char *, struct load_unload_state
*);
137 static int demux_cmd(int argc
, char *const argv
[]);
138 static launch_data_t
do_rendezvous_magic(const struct addrinfo
*res
, const char *serv
);
139 static void submit_job_pass(launch_data_t jobs
);
140 static void submit_mach_jobs(launch_data_t jobs
);
141 static void let_go_of_mach_jobs(launch_data_t jobs
);
142 static void do_mgroup_join(int fd
, int family
, int socktype
, int protocol
, const char *mgroup
);
143 static mach_port_t
str2bsport(const char *s
);
144 static void print_jobs(launch_data_t j
, const char *key
, void *context
);
145 static void print_obj(launch_data_t obj
, const char *key
, void *context
);
146 static bool is_legacy_mach_job(launch_data_t obj
);
147 static bool delay_to_second_pass(launch_data_t o
);
148 static void delay_to_second_pass2(launch_data_t o
, const char *key
, void *context
);
149 static bool str2lim(const char *buf
, rlim_t
*res
);
150 static const char *lim2str(rlim_t val
, char *buf
);
151 static const char *num2name(int n
);
152 static ssize_t
name2num(const char *n
);
153 static void unloadjob(launch_data_t job
);
154 static void print_key_value(launch_data_t obj
, const char *key
, void *context
);
155 static void print_launchd_env(launch_data_t obj
, const char *key
, void *context
);
156 static void _log_launchctl_bug(const char *rcs_rev
, const char *path
, unsigned int line
, const char *test
);
157 static void loopback_setup_ipv4(void);
158 static void loopback_setup_ipv6(void);
159 static pid_t
fwexec(const char *const *argv
, int *wstatus
);
160 static void do_potential_fsck(void);
161 static bool path_check(const char *path
);
162 static bool is_safeboot(void);
163 static bool is_netboot(void);
164 static void apply_sysctls_from_file(const char *thefile
);
165 static void empty_dir(const char *thedir
, struct stat
*psb
);
166 static int touch_file(const char *path
, mode_t m
);
167 static void do_sysversion_sysctl(void);
168 static void do_application_firewall_magic(int sfd
, launch_data_t thejob
);
169 static void preheat_page_cache_hack(void);
170 static void do_bootroot_magic(void);
171 static void do_single_user_mode(bool);
172 static bool do_single_user_mode2(void);
173 static void do_crash_debug_mode(void);
174 static bool do_crash_debug_mode2(void);
175 static void read_launchd_conf(void);
176 static void read_environment_dot_plist(void);
177 static bool job_disabled_logic(launch_data_t obj
);
178 static void fix_bogus_file_metadata(void);
179 static void do_file_init(void) __attribute__((constructor
));
180 static void setup_system_context(void);
181 static void handle_system_bootstrapper_crashes_separately(void);
182 static void fatal_signal_handler(int sig
, siginfo_t
*si
, void *uap
);
188 } BootCache_action_t
;
190 static void do_BootCache_magic(BootCache_action_t what
);
192 static int bootstrap_cmd(int argc
, char *const argv
[]);
193 static int load_and_unload_cmd(int argc
, char *const argv
[]);
194 //static int reload_cmd(int argc, char *const argv[]);
195 static int start_stop_remove_cmd(int argc
, char *const argv
[]);
196 static int submit_cmd(int argc
, char *const argv
[]);
197 static int list_cmd(int argc
, char *const argv
[]);
199 static int setenv_cmd(int argc
, char *const argv
[]);
200 static int unsetenv_cmd(int argc
, char *const argv
[]);
201 static int getenv_and_export_cmd(int argc
, char *const argv
[]);
202 static int wait4debugger_cmd(int argc
, char *const argv
[]);
204 static int limit_cmd(int argc
, char *const argv
[]);
205 static int stdio_cmd(int argc
, char *const argv
[]);
206 static int fyi_cmd(int argc
, char *const argv
[]);
207 static int logupdate_cmd(int argc
, char *const argv
[]);
208 static int umask_cmd(int argc
, char *const argv
[]);
209 static int getrusage_cmd(int argc
, char *const argv
[]);
210 static int bsexec_cmd(int argc
, char *const argv
[]);
211 static int _bslist_cmd(mach_port_t bport
, unsigned int depth
, bool show_job
, bool local_only
);
212 static int bslist_cmd(int argc
, char *const argv
[]);
213 static int _bstree_cmd(mach_port_t bsport
, unsigned int depth
, bool show_jobs
);
214 static int bstree_cmd(int argc
__attribute__((unused
)), char * const argv
[] __attribute__((unused
)));
215 static int managerpid_cmd(int argc
__attribute__((unused
)), char * const argv
[] __attribute__((unused
)));
216 static int manageruid_cmd(int argc
__attribute__((unused
)), char * const argv
[] __attribute__((unused
)));
217 static int managername_cmd(int argc
__attribute__((unused
)), char * const argv
[] __attribute__((unused
)));
218 static int exit_cmd(int argc
, char *const argv
[]) __attribute__((noreturn
));
219 static int help_cmd(int argc
, char *const argv
[]);
221 static const struct {
223 int (*func
)(int argc
, char *const argv
[]);
226 { "load", load_and_unload_cmd
, "Load configuration files and/or directories" },
227 { "unload", load_and_unload_cmd
, "Unload configuration files and/or directories" },
228 // { "reload", reload_cmd, "Reload configuration files and/or directories" },
229 { "start", start_stop_remove_cmd
, "Start specified job" },
230 { "stop", start_stop_remove_cmd
, "Stop specified job" },
231 { "submit", submit_cmd
, "Submit a job from the command line" },
232 { "remove", start_stop_remove_cmd
, "Remove specified job" },
233 { "bootstrap", bootstrap_cmd
, "Bootstrap launchd" },
234 { "list", list_cmd
, "List jobs and information about jobs" },
235 { "setenv", setenv_cmd
, "Set an environmental variable in launchd" },
236 { "unsetenv", unsetenv_cmd
, "Unset an environmental variable in launchd" },
237 { "getenv", getenv_and_export_cmd
, "Get an environmental variable from launchd" },
238 { "export", getenv_and_export_cmd
, "Export shell settings from launchd" },
239 { "debug", wait4debugger_cmd
, "Set the WaitForDebugger flag for the target job to true." },
240 { "limit", limit_cmd
, "View and adjust launchd resource limits" },
241 { "stdout", stdio_cmd
, "Redirect launchd's standard out to the given path" },
242 { "stderr", stdio_cmd
, "Redirect launchd's standard error to the given path" },
243 { "shutdown", fyi_cmd
, "Prepare for system shutdown" },
244 { "singleuser", fyi_cmd
, "Switch to single-user mode" },
245 { "getrusage", getrusage_cmd
, "Get resource usage statistics from launchd" },
246 { "log", logupdate_cmd
, "Adjust the logging level or mask of launchd" },
247 { "umask", umask_cmd
, "Change launchd's umask" },
248 { "bsexec", bsexec_cmd
, "Execute a process within a different Mach bootstrap subset" },
249 { "bslist", bslist_cmd
, "List Mach bootstrap services and optional servers" },
250 { "bstree", bstree_cmd
, "Show the entire Mach bootstrap tree. Requires root privileges." },
251 { "managerpid", managerpid_cmd
, "Print the PID of the launchd managing this Mach bootstrap." },
252 { "manageruid", manageruid_cmd
, "Print the UID of the launchd managing this Mach bootstrap." },
253 { "managername", managername_cmd
, "Print the name of this Mach bootstrap." },
254 { "exit", exit_cmd
, "Exit the interactive invocation of launchctl" },
255 { "quit", exit_cmd
, "Quit the interactive invocation of launchctl" },
256 { "help", help_cmd
, "This help output" },
261 static bool is_managed
;
262 static bool do_apple_internal_magic
;
263 static bool system_context
;
264 static bool rootuser_context
;
265 static bool bootstrapping_system
;
266 static bool bootstrapping_peruser
;
267 static bool g_verbose_boot
= false;
269 static bool g_job_overrides_db_has_changed
= false;
270 static CFMutableDictionaryRef g_job_overrides_db
= NULL
;
271 static char g_job_overrides_db_path
[PATH_MAX
];
274 static bool g_job_cache_db_has_changed
= false;
275 static launch_data_t g_job_cache_db
= NULL
;
276 static char g_job_cache_db_path
[PATH_MAX
];
280 main(int argc
, char *const argv
[])
282 int64_t is_managed_val
= 0;
285 if (vproc_swap_integer(NULL
, VPROC_GSK_IS_MANAGED
, NULL
, &is_managed_val
) == NULL
&& is_managed_val
) {
289 istty
= isatty(STDIN_FILENO
);
292 if (argc
> 0 && argv
[0][0] == '-') {
295 for (flago
= argv
[0] + 1; *flago
; flago
++) {
302 if( strncmp(argv
[1], "root", sizeof("root")) == 0 ) {
303 rootuser_context
= true;
305 fprintf(stderr
, "Unknown user: %s\n", argv
[1]);
310 fprintf(stderr
, "-u option requires an argument. Currently, only \"root\" is supported.\n");
314 system_context
= true;
317 fprintf(stderr
, "Unknown argument: '-%c'\n", *flago
);
324 /* Running in the context of the root user's per-user launchd is only supported ... well
325 * in the root user's per-user context. I know it's confusing. I'm genuinely sorry.
327 if( rootuser_context
) {
328 int64_t manager_uid
= -1, manager_pid
= -1;
329 if( vproc_swap_integer(NULL
, VPROC_GSK_MGR_UID
, NULL
, &manager_uid
) == NULL
) {
330 if( vproc_swap_integer(NULL
, VPROC_GSK_MGR_PID
, NULL
, &manager_pid
) == NULL
) {
331 if( manager_uid
|| manager_pid
== 1 ) {
332 fprintf(stderr
, "Running in the root user's per-user context is not supported outside of the root user's bootstrap.\n");
337 } else if( !(system_context
|| rootuser_context
) ) {
338 /* Running in the system context is implied when we're running as root and not running as a bootstrapper. */
339 system_context
= ( !is_managed
&& getuid() == 0 );
342 if( system_context
) {
343 if( getuid() == 0 ) {
344 setup_system_context();
346 fprintf(stderr
, "You must be root to run in the system context.\n");
349 } else if( rootuser_context
) {
350 if( getuid() != 0 ) {
351 fprintf(stderr
, "You must be root to run in the root user context.\n");
356 if (NULL
== readline
) {
357 fprintf(stderr
, "missing library: readline\n");
362 while ((l
= readline(istty
? "launchd% " : NULL
))) {
363 char *inputstring
= l
, *argv2
[100], **ap
= argv2
;
366 while ((*ap
= strsep(&inputstring
, " \t"))) {
386 exit(demux_cmd(argc
, argv
));
393 demux_cmd(int argc
, char *const argv
[])
400 for (i
= 0; i
< (sizeof cmds
/ sizeof cmds
[0]); i
++) {
401 if (!strcmp(cmds
[i
].name
, argv
[0])) {
402 return cmds
[i
].func(argc
, argv
);
406 fprintf(stderr
, "%s: unknown subcommand \"%s\"\n", getprogname(), argv
[0]);
411 read_launchd_conf(void)
413 char s
[1000], *c
, *av
[100];
419 if (getppid() == 1) {
420 file
= "/etc/launchd.conf";
422 file
= "/etc/launchd-user.conf";
425 if (!(f
= fopen(file
, "r"))) {
429 while ((c
= fgets(s
, (int) sizeof s
, f
))) {
431 if (len
&& c
[len
- 1] == '\n') {
437 while ((av
[i
] = strsep(&c
, " \t"))) {
438 if (*(av
[i
]) != '\0') {
451 CFPropertyListRef
CFPropertyListCreateFromFile(CFURLRef plistURL
)
453 CFReadStreamRef plistReadStream
= CFReadStreamCreateWithFile(NULL
, plistURL
);
455 CFErrorRef streamErr
= NULL
;
456 if( !CFReadStreamOpen(plistReadStream
) ) {
457 streamErr
= CFReadStreamCopyError(plistReadStream
);
458 CFStringRef errString
= CFErrorCopyDescription(streamErr
);
462 CFRelease(errString
);
463 CFRelease(streamErr
);
466 CFPropertyListRef plist
= NULL
;
467 if( plistReadStream
) {
468 CFStringRef errString
= NULL
;
469 CFPropertyListFormat plistFormat
= 0;
470 plist
= CFPropertyListCreateFromStream(NULL
, plistReadStream
, 0, kCFPropertyListImmutable
, &plistFormat
, &errString
);
473 CFRelease(errString
);
477 CFReadStreamClose(plistReadStream
);
478 CFRelease(plistReadStream
);
483 #define CFReleaseIfNotNULL(cf) if( cf ) CFRelease(cf);
485 read_environment_dot_plist(void)
487 CFStringRef plistPath
= NULL
;
488 CFURLRef plistURL
= NULL
;
489 CFDictionaryRef envPlist
= NULL
;
490 launch_data_t req
= NULL
, launch_env_dict
= NULL
, resp
= NULL
;
492 char plist_path_str
[PATH_MAX
];
493 plist_path_str
[PATH_MAX
- 1] = 0;
494 snprintf(plist_path_str
, sizeof(plist_path_str
), "%s/.MacOSX/environment.plist", getenv("HOME"));
497 if( stat(plist_path_str
, &sb
) == -1 ) {
501 plistPath
= CFStringCreateWithFormat(NULL
, NULL
, CFSTR("%s"), plist_path_str
);
502 if( !assumes(plistPath
!= NULL
) ) {
506 plistURL
= CFURLCreateWithFileSystemPath(NULL
, plistPath
, kCFURLPOSIXPathStyle
, false);
507 if( !assumes(plistURL
!= NULL
) ) {
511 envPlist
= (CFDictionaryRef
)CFPropertyListCreateFromFile(plistURL
);
512 if( !assumes(envPlist
!= NULL
) ) {
516 launch_env_dict
= CF2launch_data(envPlist
);
517 if( !assumes(launch_env_dict
!= NULL
) ) {
521 req
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
);
522 if( !assumes(req
!= NULL
) ) {
526 launch_data_dict_insert(req
, launch_env_dict
, LAUNCH_KEY_SETUSERENVIRONMENT
);
527 resp
= launch_msg(req
);
528 if( !assumes(resp
!= NULL
) ) {
532 if( !assumes(launch_data_get_type(resp
) == LAUNCH_DATA_ERRNO
) ) {
536 assumes(launch_data_get_errno(resp
) == 0);
538 CFReleaseIfNotNULL(plistPath
);
539 CFReleaseIfNotNULL(plistURL
);
540 CFReleaseIfNotNULL(envPlist
);
542 launch_data_free(req
);
546 launch_data_free(resp
);
551 unsetenv_cmd(int argc
, char *const argv
[])
553 launch_data_t resp
, tmp
, msg
;
556 fprintf(stderr
, "%s usage: unsetenv <key>\n", getprogname());
560 msg
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
);
562 tmp
= launch_data_new_string(argv
[1]);
563 launch_data_dict_insert(msg
, tmp
, LAUNCH_KEY_UNSETUSERENVIRONMENT
);
565 resp
= launch_msg(msg
);
567 launch_data_free(msg
);
570 launch_data_free(resp
);
572 fprintf(stderr
, "launch_msg(\"%s\"): %s\n", LAUNCH_KEY_UNSETUSERENVIRONMENT
, strerror(errno
));
579 setenv_cmd(int argc
, char *const argv
[])
581 launch_data_t resp
, tmp
, tmpv
, msg
;
584 fprintf(stderr
, "%s usage: setenv <key> <value>\n", getprogname());
588 msg
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
);
589 tmp
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
);
591 tmpv
= launch_data_new_string(argv
[2]);
592 launch_data_dict_insert(tmp
, tmpv
, argv
[1]);
593 launch_data_dict_insert(msg
, tmp
, LAUNCH_KEY_SETUSERENVIRONMENT
);
595 resp
= launch_msg(msg
);
596 launch_data_free(msg
);
599 launch_data_free(resp
);
601 fprintf(stderr
, "launch_msg(\"%s\"): %s\n", LAUNCH_KEY_SETUSERENVIRONMENT
, strerror(errno
));
608 print_launchd_env(launch_data_t obj
, const char *key
, void *context
)
610 bool *is_csh
= context
;
612 /* XXX escape the double quotes */
614 fprintf(stdout
, "setenv %s \"%s\";\n", key
, launch_data_get_string(obj
));
616 fprintf(stdout
, "%s=\"%s\"; export %s;\n", key
, launch_data_get_string(obj
), key
);
621 print_key_value(launch_data_t obj
, const char *key
, void *context
)
623 const char *k
= context
;
625 if (!strcmp(key
, k
)) {
626 fprintf(stdout
, "%s\n", launch_data_get_string(obj
));
631 getenv_and_export_cmd(int argc
, char *const argv
[])
637 if (!strcmp(argv
[0], "export")) {
638 char *s
= getenv("SHELL");
640 is_csh
= strstr(s
, "csh") ? true : false;
642 } else if (argc
!= 2) {
643 fprintf(stderr
, "%s usage: getenv <key>\n", getprogname());
649 if (vproc_swap_complex(NULL
, VPROC_GSK_ENVIRONMENT
, NULL
, &resp
) == NULL
) {
650 if (!strcmp(argv
[0], "export")) {
651 launch_data_dict_iterate(resp
, print_launchd_env
, &is_csh
);
653 launch_data_dict_iterate(resp
, print_key_value
, k
);
655 launch_data_free(resp
);
665 wait4debugger_cmd(int argc
, char * const argv
[])
668 fprintf(stderr
, "%s usage: debug <label> <value>\n", argv
[0]);
674 if( strncmp(argv
[2], "true", sizeof("true")) == 0 ) {
676 } else if( strncmp(argv
[2], "false", sizeof("false")) != 0 ) {
677 inval
= atoi(argv
[2]);
681 vproc_t vp
= vprocmgr_lookup_vproc(argv
[1]);
683 vproc_err_t verr
= vproc_swap_integer(vp
, VPROC_GSK_WAITFORDEBUGGER
, &inval
, NULL
);
685 fprintf(stderr
, "Failed to set WaitForDebugger flag on %s.\n", argv
[1]);
696 unloadjob(launch_data_t job
)
700 tmps
= launch_data_dict_lookup(job
, LAUNCH_JOBKEY_LABEL
);
703 fprintf(stderr
, "%s: Error: Missing Key: %s\n", getprogname(), LAUNCH_JOBKEY_LABEL
);
707 if (_vproc_send_signal_by_label(launch_data_get_string(tmps
), VPROC_MAGIC_UNLOAD_SIGNAL
) != NULL
) {
708 fprintf(stderr
, "%s: Error unloading: %s\n", getprogname(), launch_data_get_string(tmps
));
713 job_override(CFTypeRef key
, CFTypeRef val
, CFMutableDictionaryRef job
)
715 if( !CFTypeCheck(key
, CFString
) ) {
718 if( CFStringCompare(key
, CFSTR(LAUNCH_JOBKEY_LABEL
), kCFCompareCaseInsensitive
) == 0 ) {
722 CFDictionarySetValue(job
, key
, val
);
726 read_plist_file(const char *file
, bool editondisk
, bool load
)
728 CFPropertyListRef plist
= CreateMyPropertyListFromFile(file
);
729 launch_data_t r
= NULL
;
731 if( NULL
== plist
) {
732 fprintf(stderr
, "%s: no plist was returned for: %s\n", getprogname(), file
);
736 CFStringRef label
= CFDictionaryGetValue(plist
, CFSTR(LAUNCH_JOBKEY_LABEL
));
737 if( g_job_overrides_db
&& label
&& CFTypeCheck(label
, CFString
) ) {
738 CFDictionaryRef overrides
= CFDictionaryGetValue(g_job_overrides_db
, label
);
739 if( overrides
&& CFTypeCheck(overrides
, CFDictionary
) ) {
740 CFDictionaryApplyFunction(overrides
, (CFDictionaryApplierFunction
)job_override
, (void *)plist
);
745 if( g_job_overrides_db
) {
746 CFMutableDictionaryRef job
= (CFMutableDictionaryRef
)CFDictionaryGetValue(g_job_overrides_db
, label
);
747 if( !job
|| !CFTypeCheck(job
, CFDictionary
) ) {
748 job
= CFDictionaryCreateMutable(NULL
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
749 CFDictionarySetValue(g_job_overrides_db
, label
, job
);
753 CFDictionarySetValue(job
, CFSTR(LAUNCH_JOBKEY_DISABLED
), load
? kCFBooleanFalse
: kCFBooleanTrue
);
754 CFDictionarySetValue((CFMutableDictionaryRef
)plist
, CFSTR(LAUNCH_JOBKEY_DISABLED
), load
? kCFBooleanFalse
: kCFBooleanTrue
);
755 g_job_overrides_db_has_changed
= true;
758 CFDictionaryRemoveValue((CFMutableDictionaryRef
)plist
, CFSTR(LAUNCH_JOBKEY_DISABLED
));
760 CFDictionarySetValue((CFMutableDictionaryRef
)plist
, CFSTR(LAUNCH_JOBKEY_DISABLED
), kCFBooleanTrue
);
762 WriteMyPropertyListToFile(plist
, file
);
766 r
= CF2launch_data(plist
);
774 delay_to_second_pass2(launch_data_t o
, const char *key
, void *context
)
779 if (key
&& 0 == strcmp(key
, LAUNCH_JOBSOCKETKEY_BONJOUR
)) {
784 switch (launch_data_get_type(o
)) {
785 case LAUNCH_DATA_DICTIONARY
:
786 launch_data_dict_iterate(o
, delay_to_second_pass2
, context
);
788 case LAUNCH_DATA_ARRAY
:
789 for (i
= 0; i
< launch_data_array_get_count(o
); i
++) {
790 delay_to_second_pass2(launch_data_array_get_index(o
, i
), NULL
, context
);
799 delay_to_second_pass(launch_data_t o
)
803 launch_data_t socks
= launch_data_dict_lookup(o
, LAUNCH_JOBKEY_SOCKETS
);
809 delay_to_second_pass2(socks
, NULL
, &res
);
815 readfile(const char *what
, struct load_unload_state
*lus
)
817 char ourhostname
[1024];
818 launch_data_t tmpd
, tmps
, thejob
, tmpa
;
819 bool job_disabled
= false;
822 gethostname(ourhostname
, sizeof(ourhostname
));
824 if (NULL
== (thejob
= read_plist_file(what
, lus
->editondisk
, lus
->load
))) {
825 fprintf(stderr
, "%s: no plist was returned for: %s\n", getprogname(), what
);
829 if (is_legacy_mach_job(thejob
)) {
830 fprintf(stderr
, "%s: Please convert the following to launchd: %s\n", getprogname(), what
);
831 launch_data_array_append(lus
->pass0
, thejob
);
835 if (NULL
== launch_data_dict_lookup(thejob
, LAUNCH_JOBKEY_LABEL
)) {
836 fprintf(stderr
, "%s: missing the Label key: %s\n", getprogname(), what
);
840 if (NULL
!= (tmpa
= launch_data_dict_lookup(thejob
, LAUNCH_JOBKEY_LIMITLOADFROMHOSTS
))) {
841 c
= launch_data_array_get_count(tmpa
);
843 for (i
= 0; i
< c
; i
++) {
844 launch_data_t oai
= launch_data_array_get_index(tmpa
, i
);
845 if (!strcasecmp(ourhostname
, launch_data_get_string(oai
))) {
851 if (NULL
!= (tmpa
= launch_data_dict_lookup(thejob
, LAUNCH_JOBKEY_LIMITLOADTOHOSTS
))) {
852 c
= launch_data_array_get_count(tmpa
);
854 for (i
= 0; i
< c
; i
++) {
855 launch_data_t oai
= launch_data_array_get_index(tmpa
, i
);
856 if (!strcasecmp(ourhostname
, launch_data_get_string(oai
))) {
866 if (lus
->session_type
&& !(tmpa
= launch_data_dict_lookup(thejob
, LAUNCH_JOBKEY_LIMITLOADTOSESSIONTYPE
))) {
867 tmpa
= launch_data_new_string("Aqua");
868 launch_data_dict_insert(thejob
, tmpa
, LAUNCH_JOBKEY_LIMITLOADTOSESSIONTYPE
);
871 if ((tmpa
= launch_data_dict_lookup(thejob
, LAUNCH_JOBKEY_LIMITLOADTOSESSIONTYPE
))) {
872 const char *allowed_session
;
875 if (lus
->session_type
) switch (launch_data_get_type(tmpa
)) {
876 case LAUNCH_DATA_ARRAY
:
877 c
= launch_data_array_get_count(tmpa
);
878 for (i
= 0; i
< c
; i
++) {
879 tmps
= launch_data_array_get_index(tmpa
, i
);
880 allowed_session
= launch_data_get_string(tmps
);
881 if (strcasecmp(lus
->session_type
, allowed_session
) == 0) {
883 /* we have to do the following so job_reparent_hack() works within launchd */
884 tmpa
= launch_data_new_string(lus
->session_type
);
885 launch_data_dict_insert(thejob
, tmpa
, LAUNCH_JOBKEY_LIMITLOADTOSESSIONTYPE
);
890 case LAUNCH_DATA_STRING
:
891 allowed_session
= launch_data_get_string(tmpa
);
892 if (strcasecmp(lus
->session_type
, allowed_session
) == 0) {
905 if ((tmpd
= launch_data_dict_lookup(thejob
, LAUNCH_JOBKEY_DISABLED
))) {
906 job_disabled
= job_disabled_logic(tmpd
);
909 if (lus
->forceload
) {
910 job_disabled
= false;
913 if (job_disabled
&& lus
->load
) {
917 if( bootstrapping_system
|| bootstrapping_peruser
) {
921 launch_data_t uuid_d
= launch_data_new_opaque(uuid
, sizeof(uuid_t
));
922 launch_data_dict_insert(thejob
, uuid_d
, LAUNCH_JOBKEY_SECURITYSESSIONUUID
);
925 if (delay_to_second_pass(thejob
)) {
926 launch_data_array_append(lus
->pass2
, thejob
);
928 launch_data_array_append(lus
->pass1
, thejob
);
932 fprintf(stdout
, "Will load: %s\n", what
);
938 fprintf(stdout
, "Ignored: %s\n", what
);
940 launch_data_free(thejob
);
944 sysctl_hw_streq(int mib_slot
, const char *str
)
947 size_t bufsz
= sizeof(buf
);
948 int mib
[] = { CTL_HW
, mib_slot
};
950 if (sysctl(mib
, 2, buf
, &bufsz
, NULL
, 0) != -1) {
951 if (strcmp(buf
, str
) == 0) {
960 job_disabled_dict_logic(launch_data_t obj
, const char *key
, void *context
)
964 if (launch_data_get_type(obj
) != LAUNCH_DATA_STRING
) {
968 if (strcasecmp(key
, LAUNCH_JOBKEY_DISABLED_MACHINETYPE
) == 0) {
969 if (sysctl_hw_streq(HW_MACHINE
, launch_data_get_string(obj
))) {
972 } else if (strcasecmp(key
, LAUNCH_JOBKEY_DISABLED_MODELNAME
) == 0) {
973 if (sysctl_hw_streq(HW_MODEL
, launch_data_get_string(obj
))) {
980 job_disabled_logic(launch_data_t obj
)
984 switch (launch_data_get_type(obj
)) {
985 case LAUNCH_DATA_DICTIONARY
:
986 launch_data_dict_iterate(obj
, job_disabled_dict_logic
, &r
);
988 case LAUNCH_DATA_BOOL
:
989 r
= launch_data_get_bool(obj
);
999 path_goodness_check(const char *path
, bool forceload
)
1003 if (stat(path
, &sb
) == -1) {
1004 fprintf(stderr
, "%s: Couldn't stat(\"%s\"): %s\n", getprogname(), path
, strerror(errno
));
1012 if (sb
.st_mode
& (S_IWOTH
|S_IWGRP
)) {
1013 fprintf(stderr
, "%s: Dubious permissions on file (skipping): %s\n", getprogname(), path
);
1017 if (sb
.st_uid
!= 0 && sb
.st_uid
!= getuid()) {
1018 fprintf(stderr
, "%s: Dubious ownership on file (skipping): %s\n", getprogname(), path
);
1022 if (!(S_ISREG(sb
.st_mode
) || S_ISDIR(sb
.st_mode
))) {
1023 fprintf(stderr
, "%s: Dubious path. Not a regular file or directory (skipping): %s\n", getprogname(), path
);
1031 readpath(const char *what
, struct load_unload_state
*lus
)
1033 char buf
[MAXPATHLEN
];
1038 if (!path_goodness_check(what
, lus
->forceload
)) {
1042 if (stat(what
, &sb
) == -1) {
1046 if (S_ISREG(sb
.st_mode
)) {
1047 readfile(what
, lus
);
1048 } else if (S_ISDIR(sb
.st_mode
)) {
1049 if ((d
= opendir(what
)) == NULL
) {
1050 fprintf(stderr
, "%s: opendir() failed to open the directory\n", getprogname());
1054 while ((de
= readdir(d
))) {
1055 if ((de
->d_name
[0] == '.')) {
1058 snprintf(buf
, sizeof(buf
), "%s/%s", what
, de
->d_name
);
1060 if (!path_goodness_check(buf
, lus
->forceload
)) {
1070 struct distill_context
{
1072 launch_data_t newsockdict
;
1076 distill_jobs(launch_data_t jobs
)
1078 size_t i
, c
= launch_data_array_get_count(jobs
);
1080 for (i
= 0; i
< c
; i
++)
1081 distill_config_file(launch_data_array_get_index(jobs
, i
));
1085 distill_config_file(launch_data_t id_plist
)
1087 struct distill_context dc
= { id_plist
, NULL
};
1090 if ((tmp
= launch_data_dict_lookup(dc
.base
, LAUNCH_JOBKEY_SOCKETS
))) {
1091 dc
.newsockdict
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
);
1092 launch_data_dict_iterate(tmp
, sock_dict_cb
, &dc
);
1093 launch_data_dict_insert(dc
.base
, dc
.newsockdict
, LAUNCH_JOBKEY_SOCKETS
);
1098 sock_dict_cb(launch_data_t what
, const char *key
, void *context
)
1100 struct distill_context
*dc
= context
;
1101 launch_data_t fdarray
= launch_data_alloc(LAUNCH_DATA_ARRAY
);
1103 launch_data_dict_insert(dc
->newsockdict
, fdarray
, key
);
1105 if (launch_data_get_type(what
) == LAUNCH_DATA_DICTIONARY
) {
1106 sock_dict_edit_entry(what
, key
, fdarray
, dc
->base
);
1107 } else if (launch_data_get_type(what
) == LAUNCH_DATA_ARRAY
) {
1111 for (i
= 0; i
< launch_data_array_get_count(what
); i
++) {
1112 tmp
= launch_data_array_get_index(what
, i
);
1113 sock_dict_edit_entry(tmp
, key
, fdarray
, dc
->base
);
1119 sock_dict_edit_entry(launch_data_t tmp
, const char *key
, launch_data_t fdarray
, launch_data_t thejob
)
1121 launch_data_t a
, val
;
1122 int sfd
, st
= SOCK_STREAM
;
1123 bool passive
= true;
1125 if ((val
= launch_data_dict_lookup(tmp
, LAUNCH_JOBSOCKETKEY_TYPE
))) {
1126 if (!strcasecmp(launch_data_get_string(val
), "stream")) {
1128 } else if (!strcasecmp(launch_data_get_string(val
), "dgram")) {
1130 } else if (!strcasecmp(launch_data_get_string(val
), "seqpacket")) {
1131 st
= SOCK_SEQPACKET
;
1135 if ((val
= launch_data_dict_lookup(tmp
, LAUNCH_JOBSOCKETKEY_PASSIVE
))) {
1136 passive
= launch_data_get_bool(val
);
1139 if ((val
= launch_data_dict_lookup(tmp
, LAUNCH_JOBSOCKETKEY_SECUREWITHKEY
))) {
1140 char secdir
[] = LAUNCH_SECDIR
, buf
[1024];
1141 launch_data_t uenv
= launch_data_dict_lookup(thejob
, LAUNCH_JOBKEY_USERENVIRONMENTVARIABLES
);
1144 uenv
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
);
1145 launch_data_dict_insert(thejob
, uenv
, LAUNCH_JOBKEY_USERENVIRONMENTVARIABLES
);
1150 sprintf(buf
, "%s/%s", secdir
, key
);
1152 a
= launch_data_new_string(buf
);
1153 launch_data_dict_insert(tmp
, a
, LAUNCH_JOBSOCKETKEY_PATHNAME
);
1154 a
= launch_data_new_string(buf
);
1155 launch_data_dict_insert(uenv
, a
, launch_data_get_string(val
));
1158 if ((val
= launch_data_dict_lookup(tmp
, LAUNCH_JOBSOCKETKEY_PATHNAME
))) {
1159 struct sockaddr_un sun
;
1160 mode_t sun_mode
= 0;
1164 memset(&sun
, 0, sizeof(sun
));
1166 sun
.sun_family
= AF_UNIX
;
1168 strncpy(sun
.sun_path
, launch_data_get_string(val
), sizeof(sun
.sun_path
));
1170 if ((sfd
= _fd(socket(AF_UNIX
, st
, 0))) == -1) {
1174 if ((val
= launch_data_dict_lookup(tmp
, LAUNCH_JOBSOCKETKEY_PATHMODE
))) {
1175 sun_mode
= (mode_t
)launch_data_get_integer(val
);
1180 if (unlink(sun
.sun_path
) == -1 && errno
!= ENOENT
) {
1184 oldmask
= umask(S_IRWXG
|S_IRWXO
);
1185 if (bind(sfd
, (struct sockaddr
*)&sun
, (socklen_t
) sizeof sun
) == -1) {
1192 chmod(sun
.sun_path
, sun_mode
);
1194 if ((st
== SOCK_STREAM
|| st
== SOCK_SEQPACKET
) && listen(sfd
, -1) == -1) {
1198 } else if (connect(sfd
, (struct sockaddr
*)&sun
, (socklen_t
) sizeof sun
) == -1) {
1203 val
= launch_data_new_fd(sfd
);
1204 launch_data_array_append(fdarray
, val
);
1206 launch_data_t rnames
= NULL
;
1207 const char *node
= NULL
, *serv
= NULL
, *mgroup
= NULL
;
1209 struct addrinfo hints
, *res0
, *res
;
1210 int gerr
, sock_opt
= 1;
1211 bool rendezvous
= false;
1213 memset(&hints
, 0, sizeof(hints
));
1215 hints
.ai_socktype
= st
;
1217 hints
.ai_flags
|= AI_PASSIVE
;
1220 if ((val
= launch_data_dict_lookup(tmp
, LAUNCH_JOBSOCKETKEY_NODENAME
))) {
1221 node
= launch_data_get_string(val
);
1223 if ((val
= launch_data_dict_lookup(tmp
, LAUNCH_JOBSOCKETKEY_MULTICASTGROUP
))) {
1224 mgroup
= launch_data_get_string(val
);
1226 if ((val
= launch_data_dict_lookup(tmp
, LAUNCH_JOBSOCKETKEY_SERVICENAME
))) {
1227 if (LAUNCH_DATA_INTEGER
== launch_data_get_type(val
)) {
1228 sprintf(servnbuf
, "%lld", launch_data_get_integer(val
));
1231 serv
= launch_data_get_string(val
);
1234 if ((val
= launch_data_dict_lookup(tmp
, LAUNCH_JOBSOCKETKEY_FAMILY
))) {
1235 if (!strcasecmp("IPv4", launch_data_get_string(val
))) {
1236 hints
.ai_family
= AF_INET
;
1237 } else if (!strcasecmp("IPv6", launch_data_get_string(val
))) {
1238 hints
.ai_family
= AF_INET6
;
1241 if ((val
= launch_data_dict_lookup(tmp
, LAUNCH_JOBSOCKETKEY_PROTOCOL
))) {
1242 if (!strcasecmp("TCP", launch_data_get_string(val
))) {
1243 hints
.ai_protocol
= IPPROTO_TCP
;
1244 } else if (!strcasecmp("UDP", launch_data_get_string(val
))) {
1245 hints
.ai_protocol
= IPPROTO_UDP
;
1248 if ((rnames
= launch_data_dict_lookup(tmp
, LAUNCH_JOBSOCKETKEY_BONJOUR
))) {
1250 if (LAUNCH_DATA_BOOL
== launch_data_get_type(rnames
)) {
1251 rendezvous
= launch_data_get_bool(rnames
);
1256 if ((gerr
= getaddrinfo(node
, serv
, &hints
, &res0
)) != 0) {
1257 fprintf(stderr
, "getaddrinfo(): %s\n", gai_strerror(gerr
));
1261 for (res
= res0
; res
; res
= res
->ai_next
) {
1262 launch_data_t rvs_fd
= NULL
;
1263 if ((sfd
= _fd(socket(res
->ai_family
, res
->ai_socktype
, res
->ai_protocol
))) == -1) {
1264 fprintf(stderr
, "socket(): %s\n", strerror(errno
));
1268 do_application_firewall_magic(sfd
, thejob
);
1270 if (hints
.ai_flags
& AI_PASSIVE
) {
1271 if (AF_INET6
== res
->ai_family
&& -1 == setsockopt(sfd
, IPPROTO_IPV6
, IPV6_V6ONLY
,
1272 (void *)&sock_opt
, (socklen_t
) sizeof sock_opt
)) {
1273 fprintf(stderr
, "setsockopt(IPV6_V6ONLY): %m");
1277 if (setsockopt(sfd
, SOL_SOCKET
, SO_REUSEPORT
, (void *)&sock_opt
, (socklen_t
) sizeof sock_opt
) == -1) {
1278 fprintf(stderr
, "setsockopt(SO_REUSEPORT): %s\n", strerror(errno
));
1282 if (setsockopt(sfd
, SOL_SOCKET
, SO_REUSEADDR
, (void *)&sock_opt
, (socklen_t
) sizeof sock_opt
) == -1) {
1283 fprintf(stderr
, "setsockopt(SO_REUSEADDR): %s\n", strerror(errno
));
1287 if (bind(sfd
, res
->ai_addr
, res
->ai_addrlen
) == -1) {
1288 fprintf(stderr
, "bind(): %s\n", strerror(errno
));
1291 /* The kernel may have dynamically assigned some part of the
1292 * address. (The port being a common example.)
1294 if (getsockname(sfd
, res
->ai_addr
, &res
->ai_addrlen
) == -1) {
1295 fprintf(stderr
, "getsockname(): %s\n", strerror(errno
));
1300 do_mgroup_join(sfd
, res
->ai_family
, res
->ai_socktype
, res
->ai_protocol
, mgroup
);
1302 if ((res
->ai_socktype
== SOCK_STREAM
|| res
->ai_socktype
== SOCK_SEQPACKET
) && listen(sfd
, -1) == -1) {
1303 fprintf(stderr
, "listen(): %s\n", strerror(errno
));
1306 if (rendezvous
&& (res
->ai_family
== AF_INET
|| res
->ai_family
== AF_INET6
) &&
1307 (res
->ai_socktype
== SOCK_STREAM
|| res
->ai_socktype
== SOCK_DGRAM
)) {
1308 launch_data_t rvs_fds
= launch_data_dict_lookup(thejob
, LAUNCH_JOBKEY_BONJOURFDS
);
1309 if (NULL
== rvs_fds
) {
1310 rvs_fds
= launch_data_alloc(LAUNCH_DATA_ARRAY
);
1311 launch_data_dict_insert(thejob
, rvs_fds
, LAUNCH_JOBKEY_BONJOURFDS
);
1313 if (NULL
== rnames
) {
1314 rvs_fd
= do_rendezvous_magic(res
, serv
);
1316 launch_data_array_append(rvs_fds
, rvs_fd
);
1318 } else if (LAUNCH_DATA_STRING
== launch_data_get_type(rnames
)) {
1319 rvs_fd
= do_rendezvous_magic(res
, launch_data_get_string(rnames
));
1321 launch_data_array_append(rvs_fds
, rvs_fd
);
1323 } else if (LAUNCH_DATA_ARRAY
== launch_data_get_type(rnames
)) {
1324 size_t rn_i
, rn_ac
= launch_data_array_get_count(rnames
);
1326 for (rn_i
= 0; rn_i
< rn_ac
; rn_i
++) {
1327 launch_data_t rn_tmp
= launch_data_array_get_index(rnames
, rn_i
);
1329 rvs_fd
= do_rendezvous_magic(res
, launch_data_get_string(rn_tmp
));
1331 launch_data_array_append(rvs_fds
, rvs_fd
);
1337 if (connect(sfd
, res
->ai_addr
, res
->ai_addrlen
) == -1) {
1338 fprintf(stderr
, "connect(): %s\n", strerror(errno
));
1342 val
= launch_data_new_fd(sfd
);
1344 /* <rdar://problem/3964648> Launchd should not register the same service more than once */
1345 /* <rdar://problem/3965154> Switch to DNSServiceRegisterAddrInfo() */
1348 launch_data_array_append(fdarray
, val
);
1354 do_mgroup_join(int fd
, int family
, int socktype
, int protocol
, const char *mgroup
)
1356 struct addrinfo hints
, *res0
, *res
;
1357 struct ip_mreq mreq
;
1358 struct ipv6_mreq m6req
;
1361 memset(&hints
, 0, sizeof(hints
));
1363 hints
.ai_flags
|= AI_PASSIVE
;
1364 hints
.ai_family
= family
;
1365 hints
.ai_socktype
= socktype
;
1366 hints
.ai_protocol
= protocol
;
1368 if ((gerr
= getaddrinfo(mgroup
, NULL
, &hints
, &res0
)) != 0) {
1369 fprintf(stderr
, "getaddrinfo(): %s\n", gai_strerror(gerr
));
1373 for (res
= res0
; res
; res
= res
->ai_next
) {
1374 if (AF_INET
== family
) {
1375 memset(&mreq
, 0, sizeof(mreq
));
1376 mreq
.imr_multiaddr
= ((struct sockaddr_in
*)res
->ai_addr
)->sin_addr
;
1377 if (setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
, &mreq
, (socklen_t
) sizeof mreq
) == -1) {
1378 fprintf(stderr
, "setsockopt(IP_ADD_MEMBERSHIP): %s\n", strerror(errno
));
1382 } else if (AF_INET6
== family
) {
1383 memset(&m6req
, 0, sizeof(m6req
));
1384 m6req
.ipv6mr_multiaddr
= ((struct sockaddr_in6
*)res
->ai_addr
)->sin6_addr
;
1385 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_JOIN_GROUP
, &m6req
, (socklen_t
) sizeof m6req
) == -1) {
1386 fprintf(stderr
, "setsockopt(IPV6_JOIN_GROUP): %s\n", strerror(errno
));
1391 fprintf(stderr
, "unknown family during multicast group bind!\n");
1401 do_rendezvous_magic(const struct addrinfo
*res
, const char *serv
)
1404 DNSServiceRef service
;
1405 DNSServiceErrorType error
;
1408 static int statres
= 1;
1411 statres
= stat("/usr/sbin/mDNSResponder", &sb
);
1414 if (-1 == statres
) {
1418 sprintf(rvs_buf
, "_%s._%s.", serv
, res
->ai_socktype
== SOCK_STREAM
? "tcp" : "udp");
1420 if (res
->ai_family
== AF_INET
) {
1421 port
= ((struct sockaddr_in
*)res
->ai_addr
)->sin_port
;
1423 port
= ((struct sockaddr_in6
*)res
->ai_addr
)->sin6_port
;
1426 error
= DNSServiceRegister(&service
, 0, 0, NULL
, rvs_buf
, NULL
, NULL
, port
, 0, NULL
, NULL
, NULL
);
1428 if (error
== kDNSServiceErr_NoError
) {
1429 return launch_data_new_fd(DNSServiceRefSockFD(service
));
1432 fprintf(stderr
, "DNSServiceRegister(\"%s\"): %d\n", serv
, error
);
1437 CreateMyPropertyListFromFile(const char *posixfile
)
1439 CFPropertyListRef propertyList
;
1440 CFStringRef errorString
;
1441 CFDataRef resourceData
;
1445 fileURL
= CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault
, (const UInt8
*)posixfile
, strlen(posixfile
), false);
1447 fprintf(stderr
, "%s: CFURLCreateFromFileSystemRepresentation(%s) failed\n", getprogname(), posixfile
);
1449 if (!CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault
, fileURL
, &resourceData
, NULL
, NULL
, &errorCode
)) {
1450 fprintf(stderr
, "%s: CFURLCreateDataAndPropertiesFromResource(%s) failed: %d\n", getprogname(), posixfile
, (int)errorCode
);
1453 propertyList
= CFPropertyListCreateFromXMLData(kCFAllocatorDefault
, resourceData
, kCFPropertyListMutableContainersAndLeaves
, &errorString
);
1458 if( resourceData
) {
1459 CFRelease(resourceData
);
1462 return propertyList
;
1466 WriteMyPropertyListToFile(CFPropertyListRef plist
, const char *posixfile
)
1468 CFDataRef resourceData
;
1472 fileURL
= CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault
, (const UInt8
*)posixfile
, strlen(posixfile
), false);
1474 fprintf(stderr
, "%s: CFURLCreateFromFileSystemRepresentation(%s) failed\n", getprogname(), posixfile
);
1476 resourceData
= CFPropertyListCreateXMLData(kCFAllocatorDefault
, plist
);
1477 if (resourceData
== NULL
) {
1478 fprintf(stderr
, "%s: CFPropertyListCreateXMLData(%s) failed", getprogname(), posixfile
);
1480 if (!CFURLWriteDataAndPropertiesToResource(fileURL
, resourceData
, NULL
, &errorCode
)) {
1481 fprintf(stderr
, "%s: CFURLWriteDataAndPropertiesToResource(%s) failed: %d\n", getprogname(), posixfile
, (int)errorCode
);
1484 if( resourceData
) {
1485 CFRelease(resourceData
);
1489 static inline Boolean
__is_launch_data_t(launch_data_t obj
)
1491 Boolean result
= true;
1493 switch( launch_data_get_type(obj
) ) {
1494 case LAUNCH_DATA_STRING
: break;
1495 case LAUNCH_DATA_INTEGER
: break;
1496 case LAUNCH_DATA_REAL
: break;
1497 case LAUNCH_DATA_BOOL
: break;
1498 case LAUNCH_DATA_ARRAY
: break;
1499 case LAUNCH_DATA_DICTIONARY
: break;
1500 case LAUNCH_DATA_FD
: break;
1501 case LAUNCH_DATA_MACHPORT
: break;
1502 default : result
= false;
1508 static void __launch_data_iterate(launch_data_t obj
, const char *key
, CFMutableDictionaryRef dict
)
1510 if( obj
&& __is_launch_data_t(obj
) ) {
1511 CFStringRef cfKey
= CFStringCreateWithCString(NULL
, key
, kCFStringEncodingUTF8
);
1512 CFTypeRef cfVal
= CFTypeCreateFromLaunchData(obj
);
1515 CFDictionarySetValue(dict
, cfKey
, cfVal
);
1522 static CFTypeRef
CFTypeCreateFromLaunchData(launch_data_t obj
)
1524 CFTypeRef cfObj
= NULL
;
1526 switch( launch_data_get_type(obj
) ) {
1527 case LAUNCH_DATA_STRING
:
1529 const char *str
= launch_data_get_string(obj
);
1530 cfObj
= CFStringCreateWithCString(NULL
, str
, kCFStringEncodingUTF8
);
1534 case LAUNCH_DATA_INTEGER
:
1536 long long integer
= launch_data_get_integer(obj
);
1537 cfObj
= CFNumberCreate(NULL
, kCFNumberLongLongType
, &integer
);
1541 case LAUNCH_DATA_REAL
:
1543 double real
= launch_data_get_real(obj
);
1544 cfObj
= CFNumberCreate(NULL
, kCFNumberDoubleType
, &real
);
1548 case LAUNCH_DATA_BOOL
:
1550 bool yesno
= launch_data_get_bool(obj
);
1551 cfObj
= yesno
? kCFBooleanTrue
: kCFBooleanFalse
;
1555 case LAUNCH_DATA_ARRAY
:
1557 cfObj
= (CFTypeRef
)CFArrayCreateFromLaunchArray(obj
);
1561 case LAUNCH_DATA_DICTIONARY
:
1563 cfObj
= (CFTypeRef
)CFDictionaryCreateFromLaunchDictionary(obj
);
1567 case LAUNCH_DATA_FD
:
1569 int fd
= launch_data_get_fd(obj
);
1570 cfObj
= CFNumberCreate(NULL
, kCFNumberIntType
, &fd
);
1574 case LAUNCH_DATA_MACHPORT
:
1576 mach_port_t port
= launch_data_get_machport(obj
);
1577 cfObj
= CFNumberCreate(NULL
, kCFNumberIntType
, &port
);
1587 #pragma mark CFArray
1588 CFArrayRef
CFArrayCreateFromLaunchArray(launch_data_t arr
)
1590 CFArrayRef result
= NULL
;
1591 CFMutableArrayRef mutResult
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
1593 if( launch_data_get_type(arr
) == LAUNCH_DATA_ARRAY
) {
1594 unsigned int count
= launch_data_array_get_count(arr
);
1597 for( i
= 0; i
< count
; i
++ ) {
1598 launch_data_t launch_obj
= launch_data_array_get_index(arr
, i
);
1599 CFTypeRef obj
= CFTypeCreateFromLaunchData(launch_obj
);
1602 CFArrayAppendValue(mutResult
, obj
);
1607 result
= CFArrayCreateCopy(NULL
, mutResult
);
1611 CFRelease(mutResult
);
1616 #pragma mark CFDictionary / CFPropertyList
1617 static CFDictionaryRef
CFDictionaryCreateFromLaunchDictionary(launch_data_t dict
)
1619 CFDictionaryRef result
= NULL
;
1621 if( launch_data_get_type(dict
) == LAUNCH_DATA_DICTIONARY
) {
1622 CFMutableDictionaryRef mutResult
= CFDictionaryCreateMutable(NULL
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
1624 launch_data_dict_iterate(dict
, (void (*)(launch_data_t
, const char *, void *))__launch_data_iterate
, mutResult
);
1626 result
= CFDictionaryCreateCopy(NULL
, mutResult
);
1627 CFRelease(mutResult
);
1634 myCFDictionaryApplyFunction(const void *key
, const void *value
, void *context
)
1636 launch_data_t ik
, iw
, where
= context
;
1638 ik
= CF2launch_data(key
);
1639 iw
= CF2launch_data(value
);
1641 launch_data_dict_insert(where
, iw
, launch_data_get_string(ik
));
1642 launch_data_free(ik
);
1646 CF2launch_data(CFTypeRef cfr
)
1649 CFTypeID cft
= CFGetTypeID(cfr
);
1651 if (cft
== CFStringGetTypeID()) {
1653 CFStringGetCString(cfr
, buf
, sizeof(buf
), kCFStringEncodingUTF8
);
1654 r
= launch_data_alloc(LAUNCH_DATA_STRING
);
1655 launch_data_set_string(r
, buf
);
1656 } else if (cft
== CFBooleanGetTypeID()) {
1657 r
= launch_data_alloc(LAUNCH_DATA_BOOL
);
1658 launch_data_set_bool(r
, CFBooleanGetValue(cfr
));
1659 } else if (cft
== CFArrayGetTypeID()) {
1660 CFIndex i
, ac
= CFArrayGetCount(cfr
);
1661 r
= launch_data_alloc(LAUNCH_DATA_ARRAY
);
1662 for (i
= 0; i
< ac
; i
++) {
1663 CFTypeRef v
= CFArrayGetValueAtIndex(cfr
, i
);
1665 launch_data_t iv
= CF2launch_data(v
);
1666 launch_data_array_set_index(r
, iv
, i
);
1669 } else if (cft
== CFDictionaryGetTypeID()) {
1670 r
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
);
1671 CFDictionaryApplyFunction(cfr
, myCFDictionaryApplyFunction
, r
);
1672 } else if (cft
== CFDataGetTypeID()) {
1673 r
= launch_data_alloc(LAUNCH_DATA_ARRAY
);
1674 launch_data_set_opaque(r
, CFDataGetBytePtr(cfr
), CFDataGetLength(cfr
));
1675 } else if (cft
== CFNumberGetTypeID()) {
1678 CFNumberType cfnt
= CFNumberGetType(cfr
);
1680 case kCFNumberSInt8Type
:
1681 case kCFNumberSInt16Type
:
1682 case kCFNumberSInt32Type
:
1683 case kCFNumberSInt64Type
:
1684 case kCFNumberCharType
:
1685 case kCFNumberShortType
:
1686 case kCFNumberIntType
:
1687 case kCFNumberLongType
:
1688 case kCFNumberLongLongType
:
1689 CFNumberGetValue(cfr
, kCFNumberLongLongType
, &n
);
1690 r
= launch_data_alloc(LAUNCH_DATA_INTEGER
);
1691 launch_data_set_integer(r
, n
);
1693 case kCFNumberFloat32Type
:
1694 case kCFNumberFloat64Type
:
1695 case kCFNumberFloatType
:
1696 case kCFNumberDoubleType
:
1697 CFNumberGetValue(cfr
, kCFNumberDoubleType
, &d
);
1698 r
= launch_data_alloc(LAUNCH_DATA_REAL
);
1699 launch_data_set_real(r
, d
);
1712 help_cmd(int argc
, char *const argv
[])
1714 FILE *where
= stdout
;
1715 size_t i
, l
, cmdwidth
= 0;
1717 if (argc
== 0 || argv
== NULL
)
1720 fprintf(where
, "usage: %s <subcommand>\n", getprogname());
1722 for (i
= 0; i
< (sizeof cmds
/ sizeof cmds
[0]); i
++) {
1723 l
= strlen(cmds
[i
].name
);
1729 for (i
= 0; i
< (sizeof cmds
/ sizeof cmds
[0]); i
++) {
1730 fprintf(where
, "\t%-*s\t%s\n", (int)cmdwidth
, cmds
[i
].name
, cmds
[i
].desc
);
1737 exit_cmd(int argc
__attribute__((unused
)), char *const argv
[] __attribute__((unused
)))
1746 fcntl(fd
, F_SETFD
, 1);
1751 do_single_user_mode(bool sflag
)
1754 while (!do_single_user_mode2()) {
1761 do_single_user_mode2(void)
1763 bool runcom_fsck
= true; /* should_fsck(); */
1768 switch ((p
= fork())) {
1770 syslog(LOG_ERR
, "can't fork single-user shell, trying again: %m");
1775 assumes(waitpid(p
, &wstatus
, 0) != -1);
1776 if (WIFEXITED(wstatus
)) {
1777 if (WEXITSTATUS(wstatus
) == EXIT_SUCCESS
) {
1780 fprintf(stdout
, "single user mode: exit status: %d\n", WEXITSTATUS(wstatus
));
1783 fprintf(stdout
, "single user mode shell: %s\n", strsignal(WTERMSIG(wstatus
)));
1788 revoke(_PATH_CONSOLE
);
1789 if (!assumes((fd
= open(_PATH_CONSOLE
, O_RDWR
)) != -1)) {
1790 _exit(EXIT_FAILURE
);
1792 if (!assumes(login_tty(fd
) != -1)) {
1793 _exit(EXIT_FAILURE
);
1796 mach_timespec_t wt
= { 5, 0 };
1797 IOKitWaitQuiet(kIOMasterPortDefault
, &wt
); /* This will hopefully return after all the kexts have shut up. */
1799 setenv("TERM", "vt100", 1);
1801 fprintf(stdout
, "Singleuser boot -- fsck not done\n");
1802 fprintf(stdout
, "Root device is mounted read-only\n\n");
1803 fprintf(stdout
, "If you want to make modifications to files:\n");
1804 fprintf(stdout
, "\t/sbin/fsck -fy\n\t/sbin/mount -uw /\n\n");
1805 fprintf(stdout
, "If you wish to boot the system:\n");
1806 fprintf(stdout
, "\texit\n\n");
1810 execl(_PATH_BSHELL
, "-sh", NULL
);
1811 syslog(LOG_ERR
, "can't exec %s for single user: %m", _PATH_BSHELL
);
1812 _exit(EXIT_FAILURE
);
1816 do_crash_debug_mode(void)
1818 while (!do_crash_debug_mode2()) {
1824 do_crash_debug_mode2(void)
1830 switch ((p
= fork())) {
1832 syslog(LOG_ERR
, "can't fork crash debug shell, trying again: %m");
1837 assumes(waitpid(p
, &wstatus
, 0) != -1);
1838 if (WIFEXITED(wstatus
)) {
1839 if (WEXITSTATUS(wstatus
) == EXIT_SUCCESS
) {
1842 fprintf(stdout
, "crash debug mode: exit status: %d\n", WEXITSTATUS(wstatus
));
1845 fprintf(stdout
, "crash debug mode shell: %s\n", strsignal(WTERMSIG(wstatus
)));
1850 revoke(_PATH_CONSOLE
);
1851 if (!assumes((fd
= open(_PATH_CONSOLE
, O_RDWR
)) != -1)) {
1852 _exit(EXIT_FAILURE
);
1854 if (!assumes(login_tty(fd
) != -1)) {
1855 _exit(EXIT_FAILURE
);
1858 mach_timespec_t wt
= { 5, 0 };
1859 IOKitWaitQuiet(kIOMasterPortDefault
, &wt
); /* This will hopefully return after all the kexts have shut up. */
1861 setenv("TERM", "vt100", 1);
1862 fprintf(stdout
, "Entering boot-time debugging mode...\n");
1863 fprintf(stdout
, "The system bootstrapper process has crashed. To debug:\n");
1864 fprintf(stdout
, "\tgdb attach %i\n", getppid());
1865 fprintf(stdout
, "You can try booting the system with:\n");
1866 fprintf(stdout
, "\tlaunchctl load -S System -D All\n\n");
1868 execl(_PATH_BSHELL
, "-sh", NULL
);
1869 syslog(LOG_ERR
, "can't exec %s for crash debug: %m", _PATH_BSHELL
);
1870 _exit(EXIT_FAILURE
);
1874 exit_at_sigterm(int sig
)
1876 if( sig
== SIGTERM
) {
1877 _exit(EXIT_SUCCESS
);
1882 fatal_signal_handler(int sig
__attribute__((unused
)), siginfo_t
*si
__attribute__((unused
)), void *uap
__attribute__((unused
)))
1884 do_crash_debug_mode();
1888 handle_system_bootstrapper_crashes_separately(void)
1890 if( !g_verbose_boot
) {
1894 struct sigaction fsa
;
1896 fsa
.sa_sigaction
= fatal_signal_handler
;
1897 fsa
.sa_flags
= SA_SIGINFO
;
1898 sigemptyset(&fsa
.sa_mask
);
1900 assumes(sigaction(SIGILL
, &fsa
, NULL
) != -1);
1901 assumes(sigaction(SIGFPE
, &fsa
, NULL
) != -1);
1902 assumes(sigaction(SIGBUS
, &fsa
, NULL
) != -1);
1903 assumes(sigaction(SIGSEGV
, &fsa
, NULL
) != -1);
1904 assumes(sigaction(SIGTRAP
, &fsa
, NULL
) != -1);
1905 assumes(sigaction(SIGABRT
, &fsa
, NULL
) != -1);
1909 system_specific_bootstrap(bool sflag
)
1911 int hnmib
[] = { CTL_KERN
, KERN_HOSTNAME
};
1915 launch_data_t lda
, ldb
;
1918 do_sysversion_sysctl();
1920 do_single_user_mode(sflag
);
1922 assumes((kq
= kqueue()) != -1);
1924 EV_SET(&kev
, 0, EVFILT_TIMER
, EV_ADD
|EV_ONESHOT
, NOTE_SECONDS
, 60, 0);
1925 assumes(kevent(kq
, &kev
, 1, NULL
, 0, NULL
) != -1);
1927 EV_SET(&kev
, SIGTERM
, EVFILT_SIGNAL
, EV_ADD
, 0, 0, 0);
1928 assumes(kevent(kq
, &kev
, 1, NULL
, 0, NULL
) != -1);
1929 assumes(signal(SIGTERM
, SIG_IGN
) != SIG_ERR
);
1931 assumes(sysctl(hnmib
, 2, NULL
, NULL
, "localhost", sizeof("localhost")) != -1);
1933 loopback_setup_ipv4();
1934 loopback_setup_ipv6();
1936 apply_sysctls_from_file("/etc/sysctl.conf");
1938 #if TARGET_OS_EMBEDDED
1939 if (path_check("/etc/rc.boot")) {
1940 const char *rcboot_tool
[] = { "/etc/rc.boot", NULL
};
1942 assumes(signal(SIGTERM
, exit_at_sigterm
) != SIG_ERR
);
1943 assumes(fwexec(rcboot_tool
, NULL
) != -1);
1947 if (path_check("/etc/rc.cdrom")) {
1948 const char *rccdrom_tool
[] = { _PATH_BSHELL
, "/etc/rc.cdrom", "multiuser", NULL
};
1950 /* The bootstrapper should always be killable during install-time (rdar://problem/6103485).
1951 * This is a special case for /etc/rc.cdrom, which runs a process and never exits.
1953 assumes(signal(SIGTERM
, exit_at_sigterm
) != SIG_ERR
);
1954 assumes(fwexec(rccdrom_tool
, NULL
) != -1);
1955 assumes(reboot(RB_HALT
) != -1);
1956 _exit(EXIT_FAILURE
);
1957 } else if (is_netboot()) {
1958 const char *rcnetboot_tool
[] = { _PATH_BSHELL
, "/etc/rc.netboot", "init", NULL
};
1959 if (!assumes(fwexec(rcnetboot_tool
, NULL
) != -1)) {
1960 assumes(reboot(RB_HALT
) != -1);
1961 _exit(EXIT_FAILURE
);
1964 do_potential_fsck();
1967 if (path_check("/etc/rc.server")) {
1968 const char *rcserver_tool
[] = { _PATH_BSHELL
, "/etc/rc.server", NULL
};
1969 assumes(fwexec(rcserver_tool
, NULL
) != -1);
1972 read_launchd_conf();
1973 handle_system_bootstrapper_crashes_separately();
1975 if (path_check("/var/account/acct")) {
1976 assumes(acct("/var/account/acct") != -1);
1979 #if !TARGET_OS_EMBEDDED
1980 if (path_check("/etc/fstab")) {
1981 const char *mount_tool
[] = { "mount", "-vat", "nonfs", NULL
};
1982 assumes(fwexec(mount_tool
, NULL
) != -1);
1986 if (path_check("/etc/rc.installer_cleanup")) {
1987 const char *rccleanup_tool
[] = { _PATH_BSHELL
, "/etc/rc.installer_cleanup", "multiuser", NULL
};
1988 assumes(fwexec(rccleanup_tool
, NULL
) != -1);
1991 if( path_check("/etc/rc.deferred_install") ) {
1993 const char *deferredinstall_tool
[] = { _PATH_BSHELL
, "/etc/rc.deferred_install", NULL
};
1994 if( assumes(fwexec(deferredinstall_tool
, &status
) != -1) ) {
1995 if( WEXITSTATUS(status
) == EXIT_SUCCESS
) {
1996 if( do_apple_internal_magic
) {
1997 fprintf(stdout
, "Deferred install script completed successfully. Rebooting in 3 seconds...\n");
2001 assumes(remove(deferredinstall_tool
[1]) != -1);
2002 assumes(reboot(RB_AUTOBOOT
) != -1);
2005 fprintf(stdout
, "Deferred install script exited with status %i. Continuing boot and hoping it'll work...\n", WEXITSTATUS(status
));
2006 assumes(remove(deferredinstall_tool
[1]) != -1);
2011 empty_dir(_PATH_VARRUN
, NULL
);
2012 empty_dir(_PATH_TMP
, NULL
);
2013 remove(_PATH_NOLOGIN
);
2015 if (path_check("/usr/libexec/dirhelper")) {
2016 const char *dirhelper_tool
[] = { "/usr/libexec/dirhelper", "-machineBoot", NULL
};
2017 assumes(fwexec(dirhelper_tool
, NULL
) != -1);
2020 assumes(touch_file(_PATH_UTMPX
, DEFFILEMODE
) != -1);
2021 #if !TARGET_OS_EMBEDDED
2022 assumes(touch_file(_PATH_VARRUN
"/.systemStarterRunning", DEFFILEMODE
) != -1);
2027 * Only start auditing if not "Disabled" in auditd plist.
2029 if ((lda
= read_plist_file(AUDITD_PLIST_FILE
, false, false)) != NULL
&&
2030 ((ldb
= launch_data_dict_lookup(lda
, LAUNCH_JOBKEY_DISABLED
)) == NULL
||
2031 job_disabled_logic(ldb
) == false))
2033 assumes(audit_quick_start() == 0);
2034 launch_data_free(lda
);
2037 if (path_check("/etc/security/rc.audit")) {
2038 const char *audit_tool
[] = { _PATH_BSHELL
, "/etc/security/rc.audit", NULL
};
2039 assumes(fwexec(audit_tool
, NULL
) != -1);
2043 do_BootCache_magic(BOOTCACHE_START
);
2045 preheat_page_cache_hack();
2047 _vproc_set_global_on_demand(true);
2049 char *load_launchd_items
[] = { "load", "-D", "all", "/etc/mach_init.d", NULL
};
2050 int load_launchd_items_cnt
= 4;
2052 if (is_safeboot()) {
2053 load_launchd_items
[2] = "system";
2056 assumes(load_and_unload_cmd(load_launchd_items_cnt
, load_launchd_items
) == 0);
2061 * We need to revisit this after Leopard ships.
2063 * I want a plist defined knob for jobs to give advisory hints that
2064 * will "hopefully" serialize bootstrap. Reasons for doing so include
2065 * pragmatic performance optimizations and attempts to workaround bugs
2066 * in jobs. Something like what follows might work:
2068 * The BootCache would switch to launchd and add this to the plist:
2070 * <key>HopefullyStartsSerially<key>
2072 * <key>ReadyTimeout</key>
2073 * <integer>2</integer>
2076 * And kextd would add the following:
2078 * <key>HopefullyStartsSerially<key>
2080 * <key>ReadyTimeout</key>
2081 * <integer>5</integer>
2082 * <key>HopefullyStartsAfter</key>
2083 * <string>com.apple.BootCache.daemon</string>
2087 * Then both the BootCache and kextd could call something like:
2089 * vproc_declare_ready_state();
2091 * To tell launchd to short circuit the readiness timeout and let the
2092 * next wave of jobs start.
2094 * Yes, this mechanism smells a lot like SystemStarter, rc.d and
2095 * friends. I think as long as we document that artificial
2096 * serialization is only advisory and not guaranteed, we should be
2097 * fine. Remember: IPC is the preferred way to serialize operations.
2100 if (!do_apple_internal_magic
) {
2101 mach_timespec_t w
= { 5, 0 };
2102 IOKitWaitQuiet(kIOMasterPortDefault
, &w
);
2105 do_BootCache_magic(BOOTCACHE_TAG
);
2107 do_bootroot_magic();
2109 _vproc_set_global_on_demand(false);
2111 assumes(kevent(kq
, NULL
, 0, &kev
, 1, NULL
) == 1);
2113 do_BootCache_magic(BOOTCACHE_STOP
);
2115 assumes(close(kq
) != -1);
2119 do_BootCache_magic(BootCache_action_t what
)
2121 const char *bcc_tool
[] = { "/usr/sbin/BootCacheControl", "-f", "/var/db/BootCache.playlist", NULL
, NULL
};
2123 if (is_safeboot() || !path_check(bcc_tool
[0])) {
2128 case BOOTCACHE_START
:
2129 bcc_tool
[3] = "start";
2132 bcc_tool
[3] = "tag";
2134 case BOOTCACHE_STOP
:
2135 bcc_tool
[3] = "stop";
2142 fwexec(bcc_tool
, NULL
);
2146 bootstrap_cmd(int argc
, char *const argv
[])
2148 char *session_type
= NULL
;
2152 while ((ch
= getopt(argc
, argv
, "sS:")) != -1) {
2158 session_type
= optarg
;
2169 if (!session_type
) {
2170 fprintf(stderr
, "usage: %s bootstrap [-s] -S <session-type>\n", getprogname());
2174 if (strcasecmp(session_type
, "System") == 0) {
2175 bootstrapping_system
= true;
2176 system_specific_bootstrap(sflag
);
2178 char *load_launchd_items
[] = { "load", "-S", session_type
, "-D", "all", NULL
, NULL
, NULL
, NULL
, NULL
, NULL
};
2181 char *load_launchd_items_user
[] = { "load", "-S", VPROCMGR_SESSION_BACKGROUND
, "-D", "user", NULL
};
2182 int the_argc_user
= 0;
2184 if (is_safeboot()) {
2185 load_launchd_items
[4] = "system";
2188 if (strcasecmp(session_type
, VPROCMGR_SESSION_BACKGROUND
) == 0 || strcasecmp(session_type
, VPROCMGR_SESSION_LOGINWINDOW
) == 0) {
2189 load_launchd_items
[4] = "system";
2190 if (!is_safeboot()) {
2191 load_launchd_items
[5] = "-D";
2192 load_launchd_items
[6] = "local";
2195 if (strcasecmp(session_type
, VPROCMGR_SESSION_LOGINWINDOW
) == 0) {
2196 load_launchd_items
[the_argc
] = "/etc/mach_init_per_login_session.d";
2199 } else if (strcasecmp(session_type
, VPROCMGR_SESSION_AQUA
) == 0) {
2200 load_launchd_items
[5] = "/etc/mach_init_per_user.d";
2202 /* For now, we'll just load user Background agents when
2203 * bootstrapping the Aqua session. This way, we can
2204 * safely assume that the home directory is present. If
2205 * we try reading the user's Background agents when we're
2206 * actually bootstrapping the Background session, we run the
2207 * risk of deadlocking against mount_url. But this fix should
2208 * satisfy <rdar://problem/5279345>.
2212 /* We want to read environment.plist, which is in the user's home directory.
2213 * Since the dance to mount a network home directory is fairly complex, all we
2214 * can do is try and read environment.plist when bootstrapping the Aqua session,
2215 * which is when we assume the home directory is present.
2217 * The drawback here is that jobs bootstrapped in the Background session won't
2218 * get the new environment until they quit and relaunch. But then again, they
2219 * won't get the updated HOME directory or anything either. This is just a messy
2222 read_environment_dot_plist();
2225 if (strcasecmp(session_type
, VPROCMGR_SESSION_BACKGROUND
) == 0) {
2226 bootstrapping_peruser
= true;
2227 read_launchd_conf();
2228 #if 0 /* XXX PR-6456403 */
2229 assumes(SessionCreate(sessionKeepCurrentBootstrap
, 0) == 0);
2233 int retval
= load_and_unload_cmd(the_argc
, load_launchd_items
);
2234 if( retval
== 0 && the_argc_user
!= 0 ) {
2237 vproc_err_t err
= vproc_swap_integer(NULL
, VPROC_GSK_WEIRD_BOOTSTRAP
, &junk
, NULL
);
2239 retval
= load_and_unload_cmd(the_argc_user
, load_launchd_items_user
);
2250 load_and_unload_cmd(int argc
, char *const argv
[])
2252 NSSearchPathEnumerationState es
= 0;
2253 char nspath
[PATH_MAX
* 2]; /* safe side, we need to append */
2254 bool badopts
= false;
2255 struct load_unload_state lus
;
2259 memset(&lus
, 0, sizeof(lus
));
2261 if (strcmp(argv
[0], "load") == 0) {
2265 while ((ch
= getopt(argc
, argv
, "wFS:D:")) != -1) {
2268 lus
.editondisk
= true;
2271 lus
.forceload
= true;
2274 lus
.session_type
= optarg
;
2277 if (strcasecmp(optarg
, "all") == 0) {
2278 es
|= NSAllDomainsMask
;
2279 } else if (strcasecmp(optarg
, "user") == 0) {
2280 es
|= NSUserDomainMask
;
2281 } else if (strcasecmp(optarg
, "local") == 0) {
2282 es
|= NSLocalDomainMask
;
2283 } else if (strcasecmp(optarg
, "network") == 0) {
2284 es
|= NSNetworkDomainMask
;
2285 } else if (strcasecmp(optarg
, "system") == 0) {
2286 es
|= NSSystemDomainMask
;
2300 if (lus
.session_type
== NULL
) {
2301 es
&= ~NSUserDomainMask
;
2304 if (argc
== 0 && es
== 0) {
2309 fprintf(stderr
, "usage: %s load [-wF] [-D <user|local|network|system|all>] paths...\n", getprogname());
2315 vproc_err_t verr
= vproc_swap_string(NULL
, VPROC_GSK_JOB_OVERRIDES_DB
, NULL
, &db
);
2317 fprintf(stderr
, "Could not get location of job overrides database.\n");
2318 g_job_overrides_db_path
[0] = 0;
2320 strncpy(g_job_overrides_db_path
, db
, strlen(db
));
2322 /* If we can't create or lock the overrides database, we'll fall back to writing to the
2323 * plist file directly.
2325 assumes((dbfd
= open(g_job_overrides_db_path
, O_RDONLY
| O_EXLOCK
| O_CREAT
, S_IRUSR
| S_IWUSR
)) != -1);
2327 g_job_overrides_db
= (CFMutableDictionaryRef
)CreateMyPropertyListFromFile(g_job_overrides_db_path
);
2328 if( !g_job_overrides_db
) {
2329 g_job_overrides_db
= CFDictionaryCreateMutable(NULL
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
2335 /* I wish I didn't need to do three passes, but I need to load mDNSResponder and use it too.
2336 * And loading legacy mach init jobs is extra fun.
2338 * In later versions of launchd, I hope to load everything in the first pass,
2339 * then do the Bonjour magic on the jobs that need it, and reload them, but for now,
2340 * I haven't thought through the various complexities of reloading jobs, and therefore
2341 * launchd doesn't have reload support right now.
2344 lus
.pass0
= launch_data_alloc(LAUNCH_DATA_ARRAY
);
2345 lus
.pass1
= launch_data_alloc(LAUNCH_DATA_ARRAY
);
2346 lus
.pass2
= launch_data_alloc(LAUNCH_DATA_ARRAY
);
2348 es
= NSStartSearchPathEnumeration(NSLibraryDirectory
, es
);
2350 while ((es
= NSGetNextSearchPathEnumeration(es
, nspath
))) {
2353 if (lus
.session_type
) {
2354 strcat(nspath
, "/LaunchAgents");
2356 strcat(nspath
, "/LaunchDaemons");
2359 if (glob(nspath
, GLOB_TILDE
|GLOB_NOSORT
, NULL
, &g
) == 0) {
2360 for (i
= 0; i
< g
.gl_pathc
; i
++) {
2361 readpath(g
.gl_pathv
[i
], &lus
);
2367 for (i
= 0; i
< (size_t)argc
; i
++) {
2368 readpath(argv
[i
], &lus
);
2371 if (launch_data_array_get_count(lus
.pass0
) == 0 &&
2372 launch_data_array_get_count(lus
.pass1
) == 0 &&
2373 launch_data_array_get_count(lus
.pass2
) == 0) {
2375 fprintf(stderr
, "nothing found to %s\n", lus
.load
? "load" : "unload");
2377 launch_data_free(lus
.pass0
);
2378 launch_data_free(lus
.pass1
);
2379 launch_data_free(lus
.pass2
);
2380 return is_managed
? 0 : 1;
2384 distill_jobs(lus
.pass1
);
2385 submit_mach_jobs(lus
.pass0
);
2386 submit_job_pass(lus
.pass1
);
2387 let_go_of_mach_jobs(lus
.pass0
);
2388 distill_jobs(lus
.pass2
);
2389 submit_job_pass(lus
.pass2
);
2391 for (i
= 0; i
< launch_data_array_get_count(lus
.pass1
); i
++) {
2392 unloadjob(launch_data_array_get_index(lus
.pass1
, i
));
2394 for (i
= 0; i
< launch_data_array_get_count(lus
.pass2
); i
++) {
2395 unloadjob(launch_data_array_get_index(lus
.pass2
, i
));
2399 if( g_job_overrides_db_has_changed
) {
2400 WriteMyPropertyListToFile(g_job_overrides_db
, g_job_overrides_db_path
);
2403 flock(dbfd
, LOCK_UN
);
2409 submit_mach_jobs(launch_data_t jobs
)
2413 c
= launch_data_array_get_count(jobs
);
2415 for (i
= 0; i
< c
; i
++) {
2416 launch_data_t tmp
, oai
= launch_data_array_get_index(jobs
, i
);
2417 const char *sn
= NULL
, *cmd
= NULL
;
2419 mach_port_t msr
, msv
;
2423 if ((tmp
= launch_data_dict_lookup(oai
, MACHINIT_JOBKEY_ONDEMAND
)))
2424 d
= launch_data_get_bool(tmp
);
2425 if ((tmp
= launch_data_dict_lookup(oai
, MACHINIT_JOBKEY_SERVICENAME
)))
2426 sn
= launch_data_get_string(tmp
);
2427 if ((tmp
= launch_data_dict_lookup(oai
, MACHINIT_JOBKEY_COMMAND
)))
2428 cmd
= launch_data_get_string(tmp
);
2430 if ((kr
= bootstrap_create_server(bootstrap_port
, (char *)cmd
, u
, d
, &msr
)) != KERN_SUCCESS
) {
2431 fprintf(stderr
, "%s: bootstrap_create_server(): %s\n", getprogname(), bootstrap_strerror(kr
));
2434 if ((kr
= bootstrap_check_in(msr
, (char*)sn
, &msv
)) != KERN_SUCCESS
) {
2435 fprintf(stderr
, "%s: bootstrap_check_in(): %s\n", getprogname(), bootstrap_strerror(kr
));
2436 mach_port_mod_refs(mach_task_self(), msv
, MACH_PORT_RIGHT_RECEIVE
, -1);
2439 launch_data_dict_insert(oai
, launch_data_new_machport(msr
), MACHINIT_JOBKEY_SERVERPORT
);
2440 launch_data_dict_insert(oai
, launch_data_new_machport(msv
), MACHINIT_JOBKEY_SERVICEPORT
);
2445 let_go_of_mach_jobs(launch_data_t jobs
)
2447 size_t i
, c
= launch_data_array_get_count(jobs
);
2449 for (i
= 0; i
< c
; i
++) {
2450 launch_data_t tmp
, oai
= launch_data_array_get_index(jobs
, i
);
2451 if ((tmp
= launch_data_dict_lookup(oai
, MACHINIT_JOBKEY_SERVICEPORT
))) {
2452 mach_port_destroy(mach_task_self(), launch_data_get_machport(tmp
));
2454 fprintf(stderr
, "%s: ack! missing service port!\n", getprogname());
2456 if ((tmp
= launch_data_dict_lookup(oai
, MACHINIT_JOBKEY_SERVERPORT
))) {
2457 mach_port_destroy(mach_task_self(), launch_data_get_machport(tmp
));
2459 fprintf(stderr
, "%s: ack! missing server port!\n", getprogname());
2465 submit_job_pass(launch_data_t jobs
)
2467 launch_data_t msg
, resp
;
2471 if (launch_data_array_get_count(jobs
) == 0)
2474 msg
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
);
2476 launch_data_dict_insert(msg
, jobs
, LAUNCH_KEY_SUBMITJOB
);
2478 resp
= launch_msg(msg
);
2481 switch (launch_data_get_type(resp
)) {
2482 case LAUNCH_DATA_ERRNO
:
2483 if ((e
= launch_data_get_errno(resp
)))
2484 fprintf(stderr
, "%s\n", strerror(e
));
2486 case LAUNCH_DATA_ARRAY
:
2487 for (i
= 0; i
< launch_data_array_get_count(jobs
); i
++) {
2488 launch_data_t obatind
= launch_data_array_get_index(resp
, i
);
2489 launch_data_t jatind
= launch_data_array_get_index(jobs
, i
);
2490 const char *lab4job
= launch_data_get_string(launch_data_dict_lookup(jatind
, LAUNCH_JOBKEY_LABEL
));
2491 if (LAUNCH_DATA_ERRNO
== launch_data_get_type(obatind
)) {
2492 e
= launch_data_get_errno(obatind
);
2495 fprintf(stderr
, "%s: %s\n", lab4job
, "Already loaded");
2498 fprintf(stderr
, "%s: %s\n", lab4job
, "Not loaded");
2501 fprintf(stderr
, "%s: %s\n", lab4job
, "Could not set security session");
2503 fprintf(stderr
, "%s: %s\n", lab4job
, strerror(e
));
2511 fprintf(stderr
, "unknown respose from launchd!\n");
2514 launch_data_free(resp
);
2516 fprintf(stderr
, "launch_msg(): %s\n", strerror(errno
));
2519 launch_data_free(msg
);
2523 start_stop_remove_cmd(int argc
, char *const argv
[])
2525 launch_data_t resp
, msg
;
2526 const char *lmsgcmd
= LAUNCH_KEY_STOPJOB
;
2529 if (0 == strcmp(argv
[0], "start"))
2530 lmsgcmd
= LAUNCH_KEY_STARTJOB
;
2532 if (0 == strcmp(argv
[0], "remove"))
2533 lmsgcmd
= LAUNCH_KEY_REMOVEJOB
;
2536 fprintf(stderr
, "usage: %s %s <job label>\n", getprogname(), argv
[0]);
2540 msg
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
);
2541 launch_data_dict_insert(msg
, launch_data_new_string(argv
[1]), lmsgcmd
);
2543 resp
= launch_msg(msg
);
2544 launch_data_free(msg
);
2547 fprintf(stderr
, "launch_msg(): %s\n", strerror(errno
));
2549 } else if (launch_data_get_type(resp
) == LAUNCH_DATA_ERRNO
) {
2550 if ((e
= launch_data_get_errno(resp
))) {
2551 fprintf(stderr
, "%s %s error: %s\n", getprogname(), argv
[0], strerror(e
));
2555 fprintf(stderr
, "%s %s returned unknown response\n", getprogname(), argv
[0]);
2559 launch_data_free(resp
);
2564 print_jobs(launch_data_t j
, const char *key
__attribute__((unused
)), void *context
__attribute__((unused
)))
2566 static size_t depth
= 0;
2567 launch_data_t lo
= launch_data_dict_lookup(j
, LAUNCH_JOBKEY_LABEL
);
2568 launch_data_t pido
= launch_data_dict_lookup(j
, LAUNCH_JOBKEY_PID
);
2569 launch_data_t stato
= launch_data_dict_lookup(j
, LAUNCH_JOBKEY_LASTEXITSTATUS
);
2570 const char *label
= launch_data_get_string(lo
);
2574 fprintf(stdout
, "%lld\t-\t", launch_data_get_integer(pido
));
2576 int wstatus
= (int)launch_data_get_integer(stato
);
2577 if (WIFEXITED(wstatus
)) {
2578 fprintf(stdout
, "-\t%d\t", WEXITSTATUS(wstatus
));
2579 } else if (WIFSIGNALED(wstatus
)) {
2580 fprintf(stdout
, "-\t-%d\t", WTERMSIG(wstatus
));
2582 fprintf(stdout
, "-\t???\t");
2585 fprintf(stdout
, "-\t-\t");
2587 for (i
= 0; i
< depth
; i
++)
2588 fprintf(stdout
, "\t");
2590 fprintf(stdout
, "%s\n", label
);
2594 print_obj(launch_data_t obj
, const char *key
, void *context
__attribute__((unused
)))
2596 static size_t indent
= 0;
2599 for (i
= 0; i
< indent
; i
++)
2600 fprintf(stdout
, "\t");
2603 fprintf(stdout
, "\"%s\" = ", key
);
2605 switch (launch_data_get_type(obj
)) {
2606 case LAUNCH_DATA_STRING
:
2607 fprintf(stdout
, "\"%s\";\n", launch_data_get_string(obj
));
2609 case LAUNCH_DATA_INTEGER
:
2610 fprintf(stdout
, "%lld;\n", launch_data_get_integer(obj
));
2612 case LAUNCH_DATA_REAL
:
2613 fprintf(stdout
, "%f;\n", launch_data_get_real(obj
));
2615 case LAUNCH_DATA_BOOL
:
2616 fprintf(stdout
, "%s;\n", launch_data_get_bool(obj
) ? "true" : "false");
2618 case LAUNCH_DATA_ARRAY
:
2619 c
= launch_data_array_get_count(obj
);
2620 fprintf(stdout
, "(\n");
2622 for (i
= 0; i
< c
; i
++)
2623 print_obj(launch_data_array_get_index(obj
, i
), NULL
, NULL
);
2625 for (i
= 0; i
< indent
; i
++)
2626 fprintf(stdout
, "\t");
2627 fprintf(stdout
, ");\n");
2629 case LAUNCH_DATA_DICTIONARY
:
2630 fprintf(stdout
, "{\n");
2632 launch_data_dict_iterate(obj
, print_obj
, NULL
);
2634 for (i
= 0; i
< indent
; i
++)
2635 fprintf(stdout
, "\t");
2636 fprintf(stdout
, "};\n");
2638 case LAUNCH_DATA_FD
:
2639 fprintf(stdout
, "file-descriptor-object;\n");
2641 case LAUNCH_DATA_MACHPORT
:
2642 fprintf(stdout
, "mach-port-object;\n");
2645 fprintf(stdout
, "???;\n");
2651 list_cmd(int argc
, char *const argv
[])
2653 launch_data_t resp
, msg
= NULL
;
2656 bool plist_output
= false;
2659 fprintf(stderr
, "usage: %s list [-x] [label]\n", getprogname());
2661 } else if( argc
>= 2 ) {
2662 plist_output
= ( strncmp(argv
[1], "-x", sizeof("-x")) == 0 );
2663 label
= plist_output
? argv
[2] : argv
[1];
2667 msg
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
);
2668 launch_data_dict_insert(msg
, launch_data_new_string(label
), LAUNCH_KEY_GETJOB
);
2670 resp
= launch_msg(msg
);
2671 launch_data_free(msg
);
2674 fprintf(stderr
, "launch_msg(): %s\n", strerror(errno
));
2676 } else if (launch_data_get_type(resp
) == LAUNCH_DATA_DICTIONARY
) {
2677 if( plist_output
) {
2678 CFDictionaryRef respDict
= CFDictionaryCreateFromLaunchDictionary(resp
);
2679 CFStringRef plistStr
= NULL
;
2681 CFDataRef plistData
= CFPropertyListCreateXMLData(NULL
, (CFPropertyListRef
)respDict
);
2682 CFRelease(respDict
);
2684 plistStr
= CFStringCreateWithBytes(NULL
, CFDataGetBytePtr(plistData
), CFDataGetLength(plistData
), kCFStringEncodingUTF8
, false);
2685 CFRelease(plistData
);
2695 CFRelease(plistStr
);
2699 print_obj(resp
, NULL
, NULL
);
2702 launch_data_free(resp
);
2704 fprintf(stderr
, "%s %s returned unknown response\n", getprogname(), argv
[0]);
2706 launch_data_free(resp
);
2708 } else if( vproc_swap_complex(NULL
, VPROC_GSK_ALLJOBS
, NULL
, &resp
) == NULL
) {
2709 fprintf(stdout
, "PID\tStatus\tLabel\n");
2710 launch_data_dict_iterate(resp
, print_jobs
, NULL
);
2711 launch_data_free(resp
);
2720 stdio_cmd(int argc
__attribute__((unused
)), char *const argv
[])
2722 fprintf(stderr
, "%s %s: This sub-command no longer does anything\n", getprogname(), argv
[0]);
2727 fyi_cmd(int argc
, char *const argv
[])
2729 launch_data_t resp
, msg
;
2730 const char *lmsgk
= NULL
;
2734 fprintf(stderr
, "usage: %s %s\n", getprogname(), argv
[0]);
2738 if (!strcmp(argv
[0], "shutdown")) {
2739 lmsgk
= LAUNCH_KEY_SHUTDOWN
;
2740 } else if (!strcmp(argv
[0], "singleuser")) {
2741 lmsgk
= LAUNCH_KEY_SINGLEUSER
;
2746 msg
= launch_data_new_string(lmsgk
);
2747 resp
= launch_msg(msg
);
2748 launch_data_free(msg
);
2751 fprintf(stderr
, "launch_msg(): %s\n", strerror(errno
));
2753 } else if (launch_data_get_type(resp
) == LAUNCH_DATA_ERRNO
) {
2754 if ((e
= launch_data_get_errno(resp
))) {
2755 fprintf(stderr
, "%s %s error: %s\n", getprogname(), argv
[0], strerror(e
));
2759 fprintf(stderr
, "%s %s returned unknown response\n", getprogname(), argv
[0]);
2763 launch_data_free(resp
);
2769 logupdate_cmd(int argc
, char *const argv
[])
2771 int64_t inval
, outval
;
2772 bool badargs
= false, maskmode
= false, onlymode
= false, levelmode
= false;
2773 static const struct {
2777 { "debug", LOG_DEBUG
},
2778 { "info", LOG_INFO
},
2779 { "notice", LOG_NOTICE
},
2780 { "warning", LOG_WARNING
},
2781 { "error", LOG_ERR
},
2782 { "critical", LOG_CRIT
},
2783 { "alert", LOG_ALERT
},
2784 { "emergency", LOG_EMERG
},
2786 size_t i
, j
, logtblsz
= sizeof logtbl
/ sizeof logtbl
[0];
2790 if (!strcmp(argv
[1], "mask"))
2792 else if (!strcmp(argv
[1], "only"))
2794 else if (!strcmp(argv
[1], "level"))
2801 m
= LOG_UPTO(LOG_DEBUG
);
2803 if (argc
> 2 && (maskmode
|| onlymode
)) {
2804 for (i
= 2; i
< (size_t)argc
; i
++) {
2805 for (j
= 0; j
< logtblsz
; j
++) {
2806 if (!strcmp(argv
[i
], logtbl
[j
].name
)) {
2808 m
&= ~(LOG_MASK(logtbl
[j
].level
));
2810 m
|= LOG_MASK(logtbl
[j
].level
);
2814 if (j
== logtblsz
) {
2819 } else if (argc
> 2 && levelmode
) {
2820 for (j
= 0; j
< logtblsz
; j
++) {
2821 if (!strcmp(argv
[2], logtbl
[j
].name
)) {
2822 m
= LOG_UPTO(logtbl
[j
].level
);
2828 } else if (argc
!= 1) {
2833 fprintf(stderr
, "usage: %s [[mask loglevels...] | [only loglevels...] [level loglevel]]\n", getprogname());
2839 if (vproc_swap_integer(NULL
, VPROC_GSK_GLOBAL_LOG_MASK
, argc
!= 1 ? &inval
: NULL
, &outval
) == NULL
) {
2841 for (j
= 0; j
< logtblsz
; j
++) {
2842 if (outval
& LOG_MASK(logtbl
[j
].level
)) {
2843 fprintf(stdout
, "%s ", logtbl
[j
].name
);
2846 fprintf(stdout
, "\n");
2854 static const struct {
2858 { "cpu", RLIMIT_CPU
},
2859 { "filesize", RLIMIT_FSIZE
},
2860 { "data", RLIMIT_DATA
},
2861 { "stack", RLIMIT_STACK
},
2862 { "core", RLIMIT_CORE
},
2863 { "rss", RLIMIT_RSS
},
2864 { "memlock", RLIMIT_MEMLOCK
},
2865 { "maxproc", RLIMIT_NPROC
},
2866 { "maxfiles", RLIMIT_NOFILE
}
2869 static const size_t limlookupcnt
= sizeof limlookup
/ sizeof limlookup
[0];
2872 name2num(const char *n
)
2876 for (i
= 0; i
< limlookupcnt
; i
++) {
2877 if (!strcmp(limlookup
[i
].name
, n
)) {
2878 return limlookup
[i
].lim
;
2889 for (i
= 0; i
< limlookupcnt
; i
++) {
2890 if (limlookup
[i
].lim
== n
)
2891 return limlookup
[i
].name
;
2897 lim2str(rlim_t val
, char *buf
)
2899 if (val
== RLIM_INFINITY
)
2900 strcpy(buf
, "unlimited");
2902 sprintf(buf
, "%lld", val
);
2907 str2lim(const char *buf
, rlim_t
*res
)
2910 *res
= strtoll(buf
, &endptr
, 10);
2911 if (!strcmp(buf
, "unlimited")) {
2912 *res
= RLIM_INFINITY
;
2914 } else if (*endptr
== '\0') {
2921 limit_cmd(int argc
, char *const argv
[])
2925 struct rlimit
*lmts
= NULL
;
2926 launch_data_t resp
, resp1
= NULL
, msg
, tmp
;
2930 rlim_t slim
= -1, hlim
= -1;
2931 bool badargs
= false;
2936 if (argc
>= 3 && str2lim(argv
[2], &slim
))
2941 if (argc
== 4 && str2lim(argv
[3], &hlim
))
2944 if (argc
>= 2 && -1 == (which
= name2num(argv
[1])))
2948 fprintf(stderr
, "usage: %s %s [", getprogname(), argv
[0]);
2949 for (i
= 0; i
< limlookupcnt
; i
++)
2950 fprintf(stderr
, "%s %s", limlookup
[i
].name
, (i
+ 1) == limlookupcnt
? "" : "| ");
2951 fprintf(stderr
, "[both | soft hard]]\n");
2955 msg
= launch_data_new_string(LAUNCH_KEY_GETRESOURCELIMITS
);
2956 resp
= launch_msg(msg
);
2957 launch_data_free(msg
);
2960 fprintf(stderr
, "launch_msg(): %s\n", strerror(errno
));
2962 } else if (launch_data_get_type(resp
) == LAUNCH_DATA_OPAQUE
) {
2963 lmts
= launch_data_get_opaque(resp
);
2964 lsz
= launch_data_get_opaque_size(resp
);
2966 for (i
= 0; i
< (lsz
/ sizeof(struct rlimit
)); i
++) {
2967 if (argc
== 2 && (size_t)which
!= i
)
2969 fprintf(stdout
, "\t%-12s%-15s%-15s\n", num2name((int)i
),
2970 lim2str(lmts
[i
].rlim_cur
, slimstr
),
2971 lim2str(lmts
[i
].rlim_max
, hlimstr
));
2974 } else if (launch_data_get_type(resp
) == LAUNCH_DATA_STRING
) {
2975 fprintf(stderr
, "%s %s error: %s\n", getprogname(), argv
[0], launch_data_get_string(resp
));
2978 fprintf(stderr
, "%s %s returned unknown response\n", getprogname(), argv
[0]);
2982 if (argc
<= 2 || r
!= 0) {
2983 launch_data_free(resp
);
2989 lmts
[which
].rlim_cur
= slim
;
2990 lmts
[which
].rlim_max
= hlim
;
2992 bool maxfiles_exceeded
= false;
2993 if( strncmp(argv
[1], "maxfiles", sizeof("maxfiles")) == 0 ) {
2995 maxfiles_exceeded
= ( strncmp(argv
[2], "unlimited", sizeof("unlimited")) == 0 );
2999 maxfiles_exceeded
= ( maxfiles_exceeded
|| strncmp(argv
[3], "unlimited", sizeof("unlimited")) == 0 );
3002 if( maxfiles_exceeded
) {
3003 fprintf(stderr
, "Neither the hard nor soft limit for \"maxfiles\" can be unlimited. Please use a numeric parameter for both.\n");
3008 msg
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
);
3009 tmp
= launch_data_new_opaque(lmts
, lsz
);
3010 launch_data_dict_insert(msg
, tmp
, LAUNCH_KEY_SETRESOURCELIMITS
);
3011 resp
= launch_msg(msg
);
3012 launch_data_free(msg
);
3015 fprintf(stderr
, "launch_msg(): %s\n", strerror(errno
));
3017 } else if (launch_data_get_type(resp
) == LAUNCH_DATA_STRING
) {
3018 fprintf(stderr
, "%s %s error: %s\n", getprogname(), argv
[0], launch_data_get_string(resp
));
3020 } else if (launch_data_get_type(resp
) != LAUNCH_DATA_OPAQUE
) {
3021 fprintf(stderr
, "%s %s returned unknown response\n", getprogname(), argv
[0]);
3025 launch_data_free(resp
);
3026 launch_data_free(resp1
);
3032 umask_cmd(int argc
, char *const argv
[])
3034 bool badargs
= false;
3037 int64_t inval
, outval
;
3040 m
= strtol(argv
[1], &endptr
, 8);
3041 if (*endptr
!= '\0' || m
> 0777)
3045 if (argc
> 2 || badargs
) {
3046 fprintf(stderr
, "usage: %s %s <mask>\n", getprogname(), argv
[0]);
3052 if (vproc_swap_integer(NULL
, VPROC_GSK_GLOBAL_UMASK
, argc
== 2 ? &inval
: NULL
, &outval
) == NULL
) {
3054 fprintf(stdout
, "%o\n", (unsigned int)outval
);
3063 setup_system_context(void)
3065 if( geteuid() != 0 ) {
3066 fprintf(stderr
, "You must be the root user to perform this operation.\n");
3070 /* Use the system launchd's socket. */
3071 setenv("__USE_SYSTEM_LAUNCHD", "1", 0);
3073 /* Put ourselves in the system launchd's bootstrap. */
3074 mach_port_t rootbs
= str2bsport("/");
3075 mach_port_deallocate(mach_task_self(), bootstrap_port
);
3076 task_set_bootstrap_port(mach_task_self(), rootbs
);
3077 bootstrap_port
= rootbs
;
3081 submit_cmd(int argc
, char *const argv
[])
3083 launch_data_t msg
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
);
3084 launch_data_t job
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
);
3085 launch_data_t resp
, largv
= launch_data_alloc(LAUNCH_DATA_ARRAY
);
3088 launch_data_dict_insert(job
, launch_data_new_bool(false), LAUNCH_JOBKEY_ONDEMAND
);
3090 while ((ch
= getopt(argc
, argv
, "l:p:o:e:")) != -1) {
3093 launch_data_dict_insert(job
, launch_data_new_string(optarg
), LAUNCH_JOBKEY_LABEL
);
3096 launch_data_dict_insert(job
, launch_data_new_string(optarg
), LAUNCH_JOBKEY_PROGRAM
);
3099 launch_data_dict_insert(job
, launch_data_new_string(optarg
), LAUNCH_JOBKEY_STANDARDOUTPATH
);
3102 launch_data_dict_insert(job
, launch_data_new_string(optarg
), LAUNCH_JOBKEY_STANDARDERRORPATH
);
3105 fprintf(stderr
, "usage: %s submit ...\n", getprogname());
3112 for (i
= 0; argv
[i
]; i
++) {
3113 launch_data_array_append(largv
, launch_data_new_string(argv
[i
]));
3116 launch_data_dict_insert(job
, largv
, LAUNCH_JOBKEY_PROGRAMARGUMENTS
);
3118 launch_data_dict_insert(msg
, job
, LAUNCH_KEY_SUBMITJOB
);
3120 resp
= launch_msg(msg
);
3121 launch_data_free(msg
);
3124 fprintf(stderr
, "launch_msg(): %s\n", strerror(errno
));
3126 } else if (launch_data_get_type(resp
) == LAUNCH_DATA_ERRNO
) {
3127 errno
= launch_data_get_errno(resp
);
3129 fprintf(stderr
, "%s %s error: %s\n", getprogname(), argv
[0], strerror(errno
));
3133 fprintf(stderr
, "%s %s error: %s\n", getprogname(), argv
[0], "unknown response");
3136 launch_data_free(resp
);
3142 getrusage_cmd(int argc
, char *const argv
[])
3144 launch_data_t resp
, msg
;
3145 bool badargs
= false;
3150 else if (strcmp(argv
[1], "self") && strcmp(argv
[1], "children"))
3154 fprintf(stderr
, "usage: %s %s self | children\n", getprogname(), argv
[0]);
3158 if (!strcmp(argv
[1], "self")) {
3159 msg
= launch_data_new_string(LAUNCH_KEY_GETRUSAGESELF
);
3161 msg
= launch_data_new_string(LAUNCH_KEY_GETRUSAGECHILDREN
);
3164 resp
= launch_msg(msg
);
3165 launch_data_free(msg
);
3168 fprintf(stderr
, "launch_msg(): %s\n", strerror(errno
));
3170 } else if (launch_data_get_type(resp
) == LAUNCH_DATA_ERRNO
) {
3171 fprintf(stderr
, "%s %s error: %s\n", getprogname(), argv
[0], strerror(launch_data_get_errno(resp
)));
3173 } else if (launch_data_get_type(resp
) == LAUNCH_DATA_OPAQUE
) {
3174 struct rusage
*rusage
= launch_data_get_opaque(resp
);
3175 fprintf(stdout
, "\t%-10f\tuser time used\n",
3176 (double)rusage
->ru_utime
.tv_sec
+ (double)rusage
->ru_utime
.tv_usec
/ (double)1000000);
3177 fprintf(stdout
, "\t%-10f\tsystem time used\n",
3178 (double)rusage
->ru_stime
.tv_sec
+ (double)rusage
->ru_stime
.tv_usec
/ (double)1000000);
3179 fprintf(stdout
, "\t%-10ld\tmax resident set size\n", rusage
->ru_maxrss
);
3180 fprintf(stdout
, "\t%-10ld\tshared text memory size\n", rusage
->ru_ixrss
);
3181 fprintf(stdout
, "\t%-10ld\tunshared data size\n", rusage
->ru_idrss
);
3182 fprintf(stdout
, "\t%-10ld\tunshared stack size\n", rusage
->ru_isrss
);
3183 fprintf(stdout
, "\t%-10ld\tpage reclaims\n", rusage
->ru_minflt
);
3184 fprintf(stdout
, "\t%-10ld\tpage faults\n", rusage
->ru_majflt
);
3185 fprintf(stdout
, "\t%-10ld\tswaps\n", rusage
->ru_nswap
);
3186 fprintf(stdout
, "\t%-10ld\tblock input operations\n", rusage
->ru_inblock
);
3187 fprintf(stdout
, "\t%-10ld\tblock output operations\n", rusage
->ru_oublock
);
3188 fprintf(stdout
, "\t%-10ld\tmessages sent\n", rusage
->ru_msgsnd
);
3189 fprintf(stdout
, "\t%-10ld\tmessages received\n", rusage
->ru_msgrcv
);
3190 fprintf(stdout
, "\t%-10ld\tsignals received\n", rusage
->ru_nsignals
);
3191 fprintf(stdout
, "\t%-10ld\tvoluntary context switches\n", rusage
->ru_nvcsw
);
3192 fprintf(stdout
, "\t%-10ld\tinvoluntary context switches\n", rusage
->ru_nivcsw
);
3194 fprintf(stderr
, "%s %s returned unknown response\n", getprogname(), argv
[0]);
3198 launch_data_free(resp
);
3204 launch_data_array_append(launch_data_t a
, launch_data_t o
)
3206 size_t offt
= launch_data_array_get_count(a
);
3208 return launch_data_array_set_index(a
, o
, offt
);
3212 str2bsport(const char *s
)
3214 bool getrootbs
= strcmp(s
, "/") == 0;
3215 mach_port_t last_bport
, bport
= bootstrap_port
;
3216 task_t task
= mach_task_self();
3217 kern_return_t result
;
3219 if (strcmp(s
, "..") == 0 || getrootbs
) {
3222 result
= bootstrap_parent(last_bport
, &bport
);
3224 if (result
== BOOTSTRAP_NOT_PRIVILEGED
) {
3225 fprintf(stderr
, "Permission denied\n");
3227 } else if (result
!= BOOTSTRAP_SUCCESS
) {
3228 fprintf(stderr
, "bootstrap_parent() %d\n", result
);
3231 } while (getrootbs
&& last_bport
!= bport
);
3232 } else if( strcmp(s
, "0") == 0 || strcmp(s
, "NULL") == 0 ) {
3233 bport
= MACH_PORT_NULL
;
3237 result
= task_for_pid(mach_task_self(), pid
, &task
);
3239 if (result
!= KERN_SUCCESS
) {
3240 fprintf(stderr
, "task_for_pid() %s\n", mach_error_string(result
));
3244 result
= task_get_bootstrap_port(task
, &bport
);
3246 if (result
!= KERN_SUCCESS
) {
3247 fprintf(stderr
, "Couldn't get bootstrap port: %s\n", mach_error_string(result
));
3256 bsexec_cmd(int argc
, char *const argv
[])
3258 kern_return_t result
;
3262 fprintf(stderr
, "usage: %s bsexec <PID> prog...\n", getprogname());
3266 bport
= str2bsport(argv
[1]);
3268 result
= task_set_bootstrap_port(mach_task_self(), bport
);
3270 if (result
!= KERN_SUCCESS
) {
3271 fprintf(stderr
, "Couldn't switch to new bootstrap port: %s\n", mach_error_string(result
));
3278 if (fwexec((const char *const *)argv
+ 2, NULL
) == -1) {
3279 fprintf(stderr
, "%s bsexec failed: %s\n", getprogname(), strerror(errno
));
3287 _bslist_cmd(mach_port_t bport
, unsigned int depth
, bool show_job
, bool local_only
)
3289 kern_return_t result
;
3290 name_array_t service_names
;
3291 name_array_t service_jobs
;
3292 mach_msg_type_number_t service_cnt
, service_jobs_cnt
, service_active_cnt
;
3293 bootstrap_status_array_t service_actives
;
3296 if (bport
== MACH_PORT_NULL
) {
3297 fprintf(stderr
, "Invalid bootstrap port\n");
3302 flags
|= local_only
? BOOTSTRAP_FORCE_LOCAL
: 0;
3303 result
= bootstrap_info(bport
, &service_names
, &service_cnt
, &service_jobs
, &service_jobs_cnt
, &service_actives
, &service_active_cnt
, flags
);
3304 if (result
!= BOOTSTRAP_SUCCESS
) {
3305 fprintf(stderr
, "bootstrap_info(): %d\n", result
);
3309 #define bport_state(x) (((x) == BOOTSTRAP_STATUS_ACTIVE) ? "A" : ((x) == BOOTSTRAP_STATUS_ON_DEMAND) ? "D" : "I")
3311 for (i
= 0; i
< service_cnt
; i
++) {
3312 fprintf(stdout
, "%*s%-3s%s", depth
, "", bport_state((service_actives
[i
])), service_names
[i
]);
3314 fprintf(stdout
, " (%s)", service_jobs
[i
]);
3316 fprintf(stdout
, "\n");
3323 bslist_cmd(int argc
, char *const argv
[])
3325 mach_port_t bport
= bootstrap_port
;
3326 bool show_jobs
= false;
3327 if( argc
> 2 && strcmp(argv
[2], "-j") == 0 ) {
3333 bport
= str2bsport(argv
[1]);
3334 } else if( strcmp(argv
[1], "-j") == 0 ) {
3339 if( bport
== MACH_PORT_NULL
) {
3340 fprintf(stderr
, "Invalid bootstrap port\n");
3344 return _bslist_cmd(bport
, 0, show_jobs
, false);
3348 _bstree_cmd(mach_port_t bsport
, unsigned int depth
, bool show_jobs
)
3350 if( bsport
== MACH_PORT_NULL
) {
3351 fprintf(stderr
, "No root port!\n");
3355 mach_port_array_t child_ports
= NULL
;
3356 name_array_t child_names
= NULL
;
3357 bootstrap_property_array_t child_props
= NULL
;
3358 unsigned int cnt
= 0;
3360 kern_return_t kr
= bootstrap_lookup_children(bsport
, &child_ports
, &child_names
, &child_props
, (mach_msg_type_number_t
*)&cnt
);
3361 if( kr
!= BOOTSTRAP_SUCCESS
&& kr
!= BOOTSTRAP_NO_CHILDREN
) {
3362 if( kr
== BOOTSTRAP_NOT_PRIVILEGED
) {
3363 fprintf(stderr
, "You must be root to perform this operation.\n");
3365 fprintf(stderr
, "bootstrap_lookup_children(): %d\n", kr
);
3372 _bslist_cmd(bsport
, depth
, show_jobs
, true);
3374 for( i
= 0; i
< cnt
; i
++ ) {
3376 if( child_props
[i
] & BOOTSTRAP_PROPERTY_PERUSER
) {
3378 } else if( child_props
[i
] & BOOTSTRAP_PROPERTY_EXPLICITSUBSET
) {
3379 type
= "Explicit Subset";
3380 } else if( child_props
[i
] & BOOTSTRAP_PROPERTY_IMPLICITSUBSET
) {
3381 type
= "Implicit Subset";
3382 } else if( child_props
[i
] & BOOTSTRAP_PROPERTY_MOVEDSUBSET
) {
3383 type
= "Moved Subset";
3386 fprintf(stdout
, "%*s%s (%s)/\n", depth
, "", child_names
[i
], type
);
3387 if( child_ports
[i
] != MACH_PORT_NULL
) {
3388 _bstree_cmd(child_ports
[i
], depth
+ 4, show_jobs
);
3396 bstree_cmd(int argc
, char * const argv
[])
3398 bool show_jobs
= false;
3399 if( geteuid() != 0 ) {
3400 fprintf(stderr
, "You must be root to perform this operation.\n");
3403 if( argc
== 2 && strcmp(argv
[1], "-j") == 0 ) {
3406 fprintf(stdout
, "System/\n");
3409 return _bstree_cmd(str2bsport("/"), 4, show_jobs
);
3413 managerpid_cmd(int argc
__attribute__((unused
)), char * const argv
[] __attribute__((unused
)))
3415 int64_t manager_pid
= 0;
3416 vproc_err_t verr
= vproc_swap_integer(NULL
, VPROC_GSK_MGR_PID
, NULL
, (int64_t *)&manager_pid
);
3418 fprintf(stdout
, "Unknown job manager!\n");
3422 fprintf(stdout
, "%d\n", (pid_t
)manager_pid
);
3427 manageruid_cmd(int argc
__attribute__((unused
)), char * const argv
[] __attribute__((unused
)))
3429 int64_t manager_uid
= 0;
3430 vproc_err_t verr
= vproc_swap_integer(NULL
, VPROC_GSK_MGR_UID
, NULL
, (int64_t *)&manager_uid
);
3432 fprintf(stdout
, "Unknown job manager!\n");
3436 fprintf(stdout
, "%lli\n", manager_uid
);
3441 managername_cmd(int argc
__attribute__((unused
)), char * const argv
[] __attribute__((unused
)))
3443 char *manager_name
= NULL
;
3444 vproc_err_t verr
= vproc_swap_string(NULL
, VPROC_GSK_MGR_NAME
, NULL
, &manager_name
);
3446 fprintf(stdout
, "Unknown job manager!\n");
3450 fprintf(stdout
, "%s\n", manager_name
);
3457 is_legacy_mach_job(launch_data_t obj
)
3459 bool has_servicename
= launch_data_dict_lookup(obj
, MACHINIT_JOBKEY_SERVICENAME
);
3460 bool has_command
= launch_data_dict_lookup(obj
, MACHINIT_JOBKEY_COMMAND
);
3461 bool has_label
= launch_data_dict_lookup(obj
, LAUNCH_JOBKEY_LABEL
);
3463 return has_command
&& has_servicename
&& !has_label
;
3467 _log_launchctl_bug(const char *rcs_rev
, const char *path
, unsigned int line
, const char *test
)
3469 int saved_errno
= errno
;
3471 const char *file
= strrchr(path
, '/');
3472 char *rcs_rev_tmp
= strchr(rcs_rev
, ' ');
3481 strlcpy(buf
, rcs_rev
, sizeof(buf
));
3483 strlcpy(buf
, rcs_rev_tmp
+ 1, sizeof(buf
));
3484 rcs_rev_tmp
= strchr(buf
, ' ');
3486 *rcs_rev_tmp
= '\0';
3489 fprintf(stderr
, "Bug: %s:%u (%s):%u: %s\n", file
, line
, buf
, saved_errno
, test
);
3493 loopback_setup_ipv4(void)
3495 struct ifaliasreq ifra
;
3499 memset(&ifr
, 0, sizeof(ifr
));
3500 strcpy(ifr
.ifr_name
, "lo0");
3502 if ((s
= socket(AF_INET
, SOCK_DGRAM
, 0)) == -1)
3505 if (assumes(ioctl(s
, SIOCGIFFLAGS
, &ifr
) != -1)) {
3506 ifr
.ifr_flags
|= IFF_UP
;
3507 assumes(ioctl(s
, SIOCSIFFLAGS
, &ifr
) != -1);
3510 memset(&ifra
, 0, sizeof(ifra
));
3511 strcpy(ifra
.ifra_name
, "lo0");
3512 ((struct sockaddr_in
*)&ifra
.ifra_addr
)->sin_family
= AF_INET
;
3513 ((struct sockaddr_in
*)&ifra
.ifra_addr
)->sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
3514 ((struct sockaddr_in
*)&ifra
.ifra_addr
)->sin_len
= sizeof(struct sockaddr_in
);
3515 ((struct sockaddr_in
*)&ifra
.ifra_mask
)->sin_family
= AF_INET
;
3516 ((struct sockaddr_in
*)&ifra
.ifra_mask
)->sin_addr
.s_addr
= htonl(IN_CLASSA_NET
);
3517 ((struct sockaddr_in
*)&ifra
.ifra_mask
)->sin_len
= sizeof(struct sockaddr_in
);
3519 assumes(ioctl(s
, SIOCAIFADDR
, &ifra
) != -1);
3521 assumes(close(s
) == 0);
3525 loopback_setup_ipv6(void)
3527 struct in6_aliasreq ifra6
;
3531 memset(&ifr
, 0, sizeof(ifr
));
3532 strcpy(ifr
.ifr_name
, "lo0");
3534 if ((s6
= socket(AF_INET6
, SOCK_DGRAM
, 0)) == -1)
3537 memset(&ifr
, 0, sizeof(ifr
));
3538 strcpy(ifr
.ifr_name
, "lo0");
3540 if (assumes(ioctl(s6
, SIOCGIFFLAGS
, &ifr
) != -1)) {
3541 ifr
.ifr_flags
|= IFF_UP
;
3542 assumes(ioctl(s6
, SIOCSIFFLAGS
, &ifr
) != -1);
3545 memset(&ifra6
, 0, sizeof(ifra6
));
3546 strcpy(ifra6
.ifra_name
, "lo0");
3548 ifra6
.ifra_addr
.sin6_family
= AF_INET6
;
3549 ifra6
.ifra_addr
.sin6_addr
= in6addr_loopback
;
3550 ifra6
.ifra_addr
.sin6_len
= sizeof(struct sockaddr_in6
);
3551 ifra6
.ifra_prefixmask
.sin6_family
= AF_INET6
;
3552 memset(&ifra6
.ifra_prefixmask
.sin6_addr
, 0xff, sizeof(struct in6_addr
));
3553 ifra6
.ifra_prefixmask
.sin6_len
= sizeof(struct sockaddr_in6
);
3554 ifra6
.ifra_lifetime
.ia6t_vltime
= ND6_INFINITE_LIFETIME
;
3555 ifra6
.ifra_lifetime
.ia6t_pltime
= ND6_INFINITE_LIFETIME
;
3557 assumes(ioctl(s6
, SIOCAIFADDR_IN6
, &ifra6
) != -1);
3559 assumes(close(s6
) == 0);
3563 fwexec(const char *const *argv
, int *wstatus
)
3568 /* We'd use posix_spawnp(), but we want to workaround: 6288899 */
3570 if ((p
= vfork()) == -1) {
3572 } else if (p
== 0) {
3573 execvp(argv
[0], (char *const *)argv
);
3574 _exit(EXIT_FAILURE
);
3577 if (waitpid(p
, wstatus
? wstatus
: &wstatus2
, 0) == -1) {
3583 } else if (WIFEXITED(wstatus2
) && WEXITSTATUS(wstatus2
) == EXIT_SUCCESS
) {
3591 do_potential_fsck(void)
3593 const char *safe_fsck_tool
[] = { "fsck", "-fy", NULL
};
3594 const char *fsck_tool
[] = { "fsck", "-p", NULL
};
3595 const char *remount_tool
[] = { "mount", "-uw", "/", NULL
};
3598 if (!assumes(statfs("/", &sfs
) != -1)) {
3602 if (!(sfs
.f_flags
& MNT_RDONLY
)) {
3606 if (!is_safeboot()) {
3608 /* We have disabled this block for now. We need to revisit this optimization after Leopard. */
3609 if (sfs
.f_flags
& MNT_JOURNALED
) {
3613 fprintf(stdout
, "Running fsck on the boot volume...\n");
3614 if (fwexec(fsck_tool
, NULL
) != -1) {
3619 if (fwexec(safe_fsck_tool
, NULL
) != -1) {
3623 fprintf(stdout
, "fsck failed!\n");
3625 /* someday, we should keep booting read-only, but as of today, other sub-systems cannot handle that scenario */
3626 assumes(reboot(RB_HALT
) != -1);
3631 * Once this is fixed:
3633 * <rdar://problem/3948774> Mount flag updates should be possible with NULL as the forth argument to mount()
3635 * We can then do this one system call instead of calling out a full blown process.
3637 * assumes(mount(sfs.f_fstypename, "/", MNT_UPDATE, NULL) != -1);
3639 #if TARGET_OS_EMBEDDED
3640 if (path_check("/etc/fstab")) {
3641 const char *mount_tool
[] = { "mount", "-vat", "nonfs", NULL
};
3642 assumes(fwexec(mount_tool
, NULL
) != -1);
3646 assumes(fwexec(remount_tool
, NULL
) != -1);
3649 fix_bogus_file_metadata();
3653 fix_bogus_file_metadata(void)
3655 static const struct {
3659 const mode_t needed_bits
;
3660 const mode_t bad_bits
;
3663 { "/sbin/launchd", 0, 0, S_IRUSR
|S_IXUSR
|S_IRGRP
|S_IXGRP
|S_IROTH
|S_IXOTH
, S_ISUID
|S_ISGID
|S_ISVTX
|S_IWOTH
, false },
3664 { _PATH_TMP
, 0, 0, S_ISTXT
|S_IRWXU
|S_IRWXG
|S_IRWXO
, S_ISUID
|S_ISGID
, true },
3665 { _PATH_VARTMP
, 0, 0, S_ISTXT
|S_IRWXU
|S_IRWXG
|S_IRWXO
, S_ISUID
|S_ISGID
, true },
3666 { "/var/folders", 0, 0, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
, S_ISUID
| S_ISGID
, true },
3667 { LAUNCHD_DB_PREFIX
, 0, 0, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
, S_IWGRP
| S_IWOTH
, true },
3668 { LAUNCHD_DB_PREFIX
"/com.apple.launchd", 0, 0, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
, S_IWGRP
| S_IWOTH
, true }
3673 for (i
= 0; i
< (sizeof(f
) / sizeof(f
[0])); i
++) {
3674 mode_t i_needed_bits
;
3676 bool fix_mode
= false;
3677 bool fix_id
= false;
3679 if (!assumes(stat(f
[i
].path
, &sb
) != -1)) {
3680 fprintf(stdout
, "Crucial filesystem check: Path not present: %s. %s\n", f
[i
].path
, f
[i
].create
? "Will create." : "");
3682 if( !assumes(mkdir(f
[i
].path
, f
[i
].needed_bits
) != -1) ) {
3684 } else if( !assumes(stat(f
[i
].path
, &sb
) != -1) ) {
3692 i_needed_bits
= ~sb
.st_mode
& f
[i
].needed_bits
;
3693 i_bad_bits
= sb
.st_mode
& f
[i
].bad_bits
;
3696 fprintf(stderr
, "Crucial filesystem check: Removing bogus mode bits 0%o on path: %s\n", i_bad_bits
, f
[i
].path
);
3699 if (i_needed_bits
) {
3700 fprintf(stderr
, "Crucial filesystem check: Adding missing mode bits 0%o on path: %s\n", i_needed_bits
, f
[i
].path
);
3703 if (sb
.st_uid
!= f
[i
].owner
) {
3704 fprintf(stderr
, "Crucial filesystem check: Fixing bogus UID %u on path: %s\n", sb
.st_uid
, f
[i
].path
);
3707 if (sb
.st_gid
!= f
[i
].group
) {
3708 fprintf(stderr
, "Crucial filesystem check: Fixing bogus GID %u on path: %s\n", sb
.st_gid
, f
[i
].path
);
3713 assumes(chmod(f
[i
].path
, (sb
.st_mode
& ~i_bad_bits
) | i_needed_bits
) != -1);
3716 assumes(chown(f
[i
].path
, f
[i
].owner
, f
[i
].group
) != -1);
3723 path_check(const char *path
)
3727 if (stat(path
, &sb
) == 0)
3735 int sbmib
[] = { CTL_KERN
, KERN_SAFEBOOT
};
3737 size_t sbsz
= sizeof(sb
);
3739 if (!assumes(sysctl(sbmib
, 2, &sb
, &sbsz
, NULL
, 0) == 0))
3748 int nbmib
[] = { CTL_KERN
, KERN_NETBOOT
};
3750 size_t nbsz
= sizeof(nb
);
3752 if (!assumes(sysctl(nbmib
, 2, &nb
, &nbsz
, NULL
, 0) == 0))
3759 empty_dir(const char *thedir
, struct stat
*psb
)
3768 if (!assumes(lstat(thedir
, psb
) != -1)) {
3773 if (!assumes((currend_dir_fd
= open(".", 0)) != -1)) {
3777 if (!assumes(chdir(thedir
) != -1)) {
3781 if (!assumes(od
= opendir("."))) {
3785 while ((de
= readdir(od
))) {
3788 if (strcmp(de
->d_name
, ".") == 0) {
3792 if (strcmp(de
->d_name
, "..") == 0) {
3796 if (!assumes(lstat(de
->d_name
, &sb
) != -1)) {
3800 if (psb
->st_dev
!= sb
.st_dev
) {
3801 assumes(unmount(de
->d_name
, MNT_FORCE
) != -1);
3803 /* Let's lstat() again to see if the unmount() worked and what was under it */
3804 if (!assumes(lstat(de
->d_name
, &sb
) != -1)) {
3808 if (!assumes(psb
->st_dev
== sb
.st_dev
)) {
3813 if (S_ISDIR(sb
.st_mode
)) {
3814 empty_dir(de
->d_name
, &sb
);
3817 assumes(lchflags(de
->d_name
, 0) != -1);
3818 assumes(remove(de
->d_name
) != -1);
3821 assumes(closedir(od
) != -1);
3824 assumes(fchdir(currend_dir_fd
) != -1);
3825 assumes(close(currend_dir_fd
) != -1);
3829 touch_file(const char *path
, mode_t m
)
3831 int fd
= open(path
, O_CREAT
, m
);
3840 apply_sysctls_from_file(const char *thefile
)
3842 const char *sysctl_tool
[] = { "sysctl", "-w", NULL
, NULL
};
3847 if (!(sf
= fopen(thefile
, "r")))
3850 while ((val
= fgetln(sf
, &ln_len
))) {
3854 if (!assumes((tmpstr
= malloc(ln_len
+ 1)) != NULL
)) {
3857 memcpy(tmpstr
, val
, ln_len
);
3861 if (val
[ln_len
- 1] == '\n' || val
[ln_len
- 1] == '\r') {
3862 val
[ln_len
- 1] = '\0';
3865 while (*val
&& isspace(*val
))
3867 if (*val
== '\0' || *val
== '#') {
3868 goto skip_sysctl_tool
;
3870 sysctl_tool
[2] = val
;
3871 assumes(fwexec(sysctl_tool
, NULL
) != -1);
3876 assumes(fclose(sf
) == 0);
3880 do_sysversion_sysctl(void)
3882 int mib
[] = { CTL_KERN
, KERN_OSVERSION
};
3883 CFDictionaryRef versdict
;
3884 CFStringRef buildvers
;
3886 size_t bufsz
= sizeof(buf
);
3888 /* <rdar://problem/4477682> ER: launchd should set kern.osversion very early in boot */
3890 if (sysctl(mib
, 2, buf
, &bufsz
, NULL
, 0) == -1) {
3891 fprintf(stderr
, "sysctl(): %s\n", strerror(errno
));
3895 if (buf
[0] != '\0') {
3899 if (!assumes((versdict
= _CFCopySystemVersionDictionary()))) {
3903 if (assumes((buildvers
= CFDictionaryGetValue(versdict
, _kCFSystemVersionBuildVersionKey
)))) {
3904 CFStringGetCString(buildvers
, buf
, sizeof(buf
), kCFStringEncodingUTF8
);
3906 assumes(sysctl(mib
, 2, NULL
, 0, buf
, strlen(buf
) + 1) != -1);
3909 CFRelease(versdict
);
3913 do_application_firewall_magic(int sfd
, launch_data_t thejob
)
3915 const char *prog
= NULL
, *partialprog
= NULL
;
3916 char *path
, *pathtmp
, **pathstmp
;
3922 * <rdar://problem/4684434> setsockopt() with the executable path as the argument
3925 if ((tmp
= launch_data_dict_lookup(thejob
, LAUNCH_JOBKEY_PROGRAM
))) {
3926 prog
= launch_data_get_string(tmp
);
3930 if ((tmp
= launch_data_dict_lookup(thejob
, LAUNCH_JOBKEY_PROGRAMARGUMENTS
))) {
3931 if ((tmp
= launch_data_array_get_index(tmp
, 0))) {
3932 if (assumes((partialprog
= launch_data_get_string(tmp
)) != NULL
)) {
3933 if (partialprog
[0] == '/') {
3942 pathtmp
= path
= strdup(getenv("PATH"));
3946 while ((*pathstmp
= strsep(&pathtmp
, ":"))) {
3947 if (**pathstmp
!= '\0') {
3953 pathtmp
= alloca(MAXPATHLEN
);
3957 for (; *pathstmp
; pathstmp
++) {
3958 snprintf(pathtmp
, MAXPATHLEN
, "%s/%s", *pathstmp
, partialprog
);
3959 if (path_check(pathtmp
)) {
3966 if (assumes(prog
!= NULL
)) {
3967 /* The networking team has asked us to ignore the failure of this API if errno == ENOPROTOOPT */
3968 assumes(setsockopt(sfd
, SOL_SOCKET
, SO_EXECPATH
, prog
, (socklen_t
)(strlen(prog
) + 1)) != -1 || errno
== ENOPROTOOPT
);
3974 preheat_page_cache_hack(void)
3979 /* Disable this hack for now */
3982 if ((thedir
= opendir("/etc/preheat_at_boot")) == NULL
) {
3986 while ((de
= readdir(thedir
))) {
3991 if (de
->d_name
[0] == '.') {
3995 if ((fd
= open(de
->d_name
, O_RDONLY
)) == -1) {
3999 if (fstat(fd
, &sb
) != -1) {
4000 if ((sb
.st_size
< 10*1024*1024) && (junkbuf
= malloc((size_t)sb
.st_size
)) != NULL
) {
4001 assumes(read(fd
, junkbuf
, (size_t)sb
.st_size
) == (ssize_t
)sb
.st_size
);
4014 do_bootroot_magic(void)
4016 const char *kextcache_tool
[] = { "kextcache", "-U", "/", NULL
};
4017 CFTypeRef bootrootProp
;
4018 io_service_t chosen
;
4022 chosen
= IORegistryEntryFromPath(kIOMasterPortDefault
, "IODeviceTree:/chosen");
4024 if (!assumes(chosen
)) {
4028 bootrootProp
= IORegistryEntryCreateCFProperty(chosen
, CFSTR(kBootRootActiveKey
), kCFAllocatorDefault
, 0);
4030 IOObjectRelease(chosen
);
4032 if (!bootrootProp
) {
4036 CFRelease(bootrootProp
);
4038 if (!assumes((p
= fwexec(kextcache_tool
, &wstatus
)) != -1)) {
4042 if (WIFEXITED(wstatus
) && WEXITSTATUS(wstatus
) == EX_OSFILE
) {
4043 assumes(reboot(RB_AUTOBOOT
) != -1);
4052 if (stat("/AppleInternal", &sb
) == 0 && stat("/var/db/disableAppleInternal", &sb
) == -1) {
4053 do_apple_internal_magic
= true;
4057 size_t len
= sizeof(bootargs
) - 1;
4058 int r
= sysctlbyname("kern.bootargs", bootargs
, &len
, NULL
, 0);
4059 if( r
== 0 && stat("/var/db/.launchd_shutdown_debugging", &sb
) == 0 && strnstr(bootargs
, "-v", len
) != NULL
) {
4060 g_verbose_boot
= true;