xref: /trueos/sbin/launchd/core.c (revision 9c1dde6c551c2fcfdb84a29c80e2a77eff789c59)
1 /*
2  * @APPLE_APACHE_LICENSE_HEADER_START@
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  * @APPLE_APACHE_LICENSE_HEADER_END@
17  */
18 
19 #define __APPLE_API_PRIVATE
20 #define PRIVATE 1
21 
22 #include "config.h"
23 #include "core.h"
24 
25 #include "internal.h"
26 #include "helper.h"
27 
28 #include <TargetConditionals.h>
29 #include <mach/mach.h>
30 #include <mach/mach_error.h>
31 #include <mach/boolean.h>
32 #include <mach/message.h>
33 #include <mach/notify.h>
34 #include <mach/mig_errors.h>
35 #include <mach/mach_traps.h>
36 #include <mach/mach_interface.h>
37 #include <mach/host_info.h>
38 #include <mach/mach_host.h>
39 #include <mach/exception.h>
40 #include <mach/host_reboot.h>
41 #include <sys/types.h>
42 #include <sys/queue.h>
43 #include <sys/endian.h>
44 #include <sys/event.h>
45 #include <sys/stat.h>
46 #include <sys/ucred.h>
47 #include <sys/fcntl.h>
48 #include <sys/un.h>
49 #include <sys/reboot.h>
50 #include <sys/wait.h>
51 #include <sys/sysctl.h>
52 #include <sys/sockio.h>
53 #include <sys/time.h>
54 #include <sys/resource.h>
55 #include <sys/ioctl.h>
56 #include <sys/mount.h>
57 #if 0
58 #include <sys/pipe.h>
59 #endif
60 #include <sys/mman.h>
61 #include <sys/proc.h>
62 #include <sys/socket.h>
63 #include <sys/syscall.h>
64 #include <sys/kern_memorystatus.h>
65 #include <net/if.h>
66 #include <net/if_var.h>
67 #include <netinet/in.h>
68 #include <netinet/in_var.h>
69 #include <netinet6/nd6.h>
70 #include <bsm/libbsm.h>
71 #include <unistd.h>
72 #include <signal.h>
73 #include <errno.h>
74 #include <libgen.h>
75 #include <stdio.h>
76 #include <stdlib.h>
77 #include <stdarg.h>
78 #include <stdbool.h>
79 #include <paths.h>
80 #include <pwd.h>
81 #include <grp.h>
82 #include <ttyent.h>
83 #include <dlfcn.h>
84 #include <dirent.h>
85 #include <string.h>
86 #include <ctype.h>
87 #include <glob.h>
88 #include <spawn.h>
89 #include <spawn_private.h>
90 #include <sys/spawn_internal.h>
91 #include <System/sys/spawn.h>
92 #include <System/sys/spawn_internal.h>
93 
94 #include <spawn_private.h>
95 #include <time.h>
96 #include <libinfo.h>
97 #include <os/assumes.h>
98 #include <xpc/launchd.h>
99 #include <asl.h>
100 #include <_simple.h>
101 #include <mach/mach_vm.h>
102 
103 #include <libproc.h>
104 #include <libproc_internal.h>
105 #include <System/sys/proc_info.h>
106 
107 #include <pthread.h>
108 #if HAVE_SANDBOX
109 #define __APPLE_API_PRIVATE
110 #include <sandbox.h>
111 #endif
112 #if HAVE_QUARANTINE
113 #include <quarantine.h>
114 #endif
115 #if HAVE_RESPONSIBILITY
116 #include <responsibility.h>
117 #endif
118 
119 #if !TARGET_OS_EMBEDDED
120 extern int gL1CacheEnabled;
121 #endif
122 
123 #if HAVE_SYSTEMSTATS
124 #include <systemstats/systemstats.h>
125 #endif
126 
127 #include "launch.h"
128 #include "launch_priv.h"
129 #include "launch_internal.h"
130 #include "bootstrap.h"
131 #include "bootstrap_priv.h"
132 #include "vproc.h"
133 #include "vproc_internal.h"
134 
135 #include "reboot2.h"
136 
137 #include "launchd.h"
138 #include "runtime.h"
139 #include "ipc.h"
140 #include "job.h"
141 
142 #include "jobServer.h"
143 #include "job_reply.h"
144 #include "job_forward.h"
145 
146 #include "mach_excServer.h"
147 
148 #include "shim.h"
149 
150 #define POSIX_SPAWN_IOS_INTERACTIVE 0
151 
152 #if TARGET_OS_EMBEDDED
153 /* Default memory highwatermark for daemons as set out in <rdar://problem/10307788>. */
154 #define DEFAULT_JETSAM_DAEMON_HIGHWATERMARK 5
155 #endif
156 
157 /* LAUNCHD_DEFAULT_EXIT_TIMEOUT
158  *   If the job hasn't exited in the given number of seconds after sending
159  *   it a SIGTERM, SIGKILL it. Can be overriden in the job plist.
160  */
161 #define LAUNCHD_MIN_JOB_RUN_TIME 10
162 #define LAUNCHD_DEFAULT_EXIT_TIMEOUT 20
163 #define LAUNCHD_SIGKILL_TIMER 30
164 #define LAUNCHD_LOG_FAILED_EXEC_FREQ 10
165 
166 #define SHUTDOWN_LOG_DIR "/var/log/shutdown"
167 
168 #define TAKE_SUBSET_NAME "TakeSubsetName"
169 #define TAKE_SUBSET_PID "TakeSubsetPID"
170 #define TAKE_SUBSET_PERPID "TakeSubsetPerPID"
171 
172 #define IS_POWER_OF_TWO(v) (!(v & (v - 1)) && v)
173 
174 extern char **environ;
175 extern bool uflag;
176 
177 struct waiting_for_removal {
178 	SLIST_ENTRY(waiting_for_removal) sle;
179 	mach_port_t reply_port;
180 };
181 
182 static bool waiting4removal_new(job_t j, mach_port_t rp);
183 static void waiting4removal_delete(job_t j, struct waiting_for_removal *w4r);
184 
185 struct machservice {
186 	SLIST_ENTRY(machservice) sle;
187 	SLIST_ENTRY(machservice) special_port_sle;
188 	LIST_ENTRY(machservice) name_hash_sle;
189 	LIST_ENTRY(machservice) port_hash_sle;
190 	struct machservice *alias;
191 	job_t job;
192 	unsigned int gen_num;
193 	mach_port_name_t port;
194 	unsigned int
195 		isActive:1,
196 		reset:1,
197 		recv:1,
198 		hide:1,
199 		kUNCServer:1,
200 		per_user_hack:1,
201 		debug_on_close:1,
202 		per_pid:1,
203 		delete_on_destruction:1,
204 		drain_one_on_crash:1,
205 		drain_all_on_crash:1,
206 		upfront:1,
207 		event_channel:1,
208 		recv_race_hack :1,
209 		/* Don't let the size of this field to get too small. It has to be large
210 		 * enough to represent the reasonable range of special port numbers.
211 		 */
212 		special_port_num:17;
213 	const char name[0];
214 };
215 
216 // HACK: This should be per jobmgr_t
217 static SLIST_HEAD(, machservice) special_ports;
218 
219 #define PORT_HASH_SIZE 32
220 #define HASH_PORT(x) (IS_POWER_OF_TWO(PORT_HASH_SIZE) ? (MACH_PORT_INDEX(x) & (PORT_HASH_SIZE - 1)) : (MACH_PORT_INDEX(x) % PORT_HASH_SIZE))
221 
222 static LIST_HEAD(, machservice) port_hash[PORT_HASH_SIZE];
223 
224 static void machservice_setup(launch_data_t obj, const char *key, void *context);
225 static void machservice_setup_options(launch_data_t obj, const char *key, void *context);
226 static void machservice_resetport(job_t j, struct machservice *ms);
227 static void machservice_stamp_port(job_t j, struct machservice *ms);
228 static struct machservice *machservice_new(job_t j, const char *name, mach_port_t *serviceport, bool pid_local);
229 static struct machservice *machservice_new_alias(job_t aj, struct machservice *orig);
230 static void machservice_ignore(job_t j, struct machservice *ms);
231 static void machservice_watch(job_t j, struct machservice *ms);
232 static void machservice_delete(job_t j, struct machservice *, bool port_died);
233 static void machservice_request_notifications(struct machservice *);
234 static mach_port_t machservice_port(struct machservice *);
235 static job_t machservice_job(struct machservice *);
236 static bool machservice_hidden(struct machservice *);
237 static bool machservice_active(struct machservice *);
238 static const char *machservice_name(struct machservice *);
239 static bootstrap_status_t machservice_status(struct machservice *);
240 void machservice_drain_port(struct machservice *);
241 
242 struct socketgroup {
243 	SLIST_ENTRY(socketgroup) sle;
244 	int *fds;
245 	unsigned int fd_cnt;
246 	union {
247 		const char name[0];
248 		char name_init[0];
249 	};
250 };
251 
252 static bool socketgroup_new(job_t j, const char *name, int *fds, size_t fd_cnt);
253 static void socketgroup_delete(job_t j, struct socketgroup *sg);
254 static void socketgroup_watch(job_t j, struct socketgroup *sg);
255 static void socketgroup_ignore(job_t j, struct socketgroup *sg);
256 static void socketgroup_callback(job_t j);
257 static void socketgroup_setup(launch_data_t obj, const char *key, void *context);
258 static void socketgroup_kevent_mod(job_t j, struct socketgroup *sg, bool do_add);
259 
260 struct calendarinterval {
261 	LIST_ENTRY(calendarinterval) global_sle;
262 	SLIST_ENTRY(calendarinterval) sle;
263 	job_t job;
264 	struct tm when;
265 	time_t when_next;
266 };
267 
268 static LIST_HEAD(, calendarinterval) sorted_calendar_events;
269 
270 static bool calendarinterval_new(job_t j, struct tm *w);
271 static bool calendarinterval_new_from_obj(job_t j, launch_data_t obj);
272 static void calendarinterval_new_from_obj_dict_walk(launch_data_t obj, const char *key, void *context);
273 static void calendarinterval_delete(job_t j, struct calendarinterval *ci);
274 static void calendarinterval_setalarm(job_t j, struct calendarinterval *ci);
275 static void calendarinterval_callback(void);
276 static void calendarinterval_sanity_check(void);
277 
278 struct envitem {
279 	SLIST_ENTRY(envitem) sle;
280 	char *value;
281 	union {
282 		const char key[0];
283 		char key_init[0];
284 	};
285 };
286 
287 static bool envitem_new(job_t j, const char *k, const char *v, bool global);
288 static void envitem_delete(job_t j, struct envitem *ei, bool global);
289 static void envitem_setup(launch_data_t obj, const char *key, void *context);
290 
291 struct limititem {
292 	SLIST_ENTRY(limititem) sle;
293 	struct rlimit lim;
294 	unsigned int setsoft:1, sethard:1, which:30;
295 };
296 
297 static bool limititem_update(job_t j, int w, rlim_t r);
298 static void limititem_delete(job_t j, struct limititem *li);
299 static void limititem_setup(launch_data_t obj, const char *key, void *context);
300 #if HAVE_SANDBOX
301 static void seatbelt_setup_flags(launch_data_t obj, const char *key, void *context);
302 #endif
303 
304 static void jetsam_property_setup(launch_data_t obj, const char *key, job_t j);
305 
306 typedef enum {
307 	NETWORK_UP = 1,
308 	NETWORK_DOWN,
309 	SUCCESSFUL_EXIT,
310 	FAILED_EXIT,
311 	CRASHED,
312 	DID_NOT_CRASH,
313 	OTHER_JOB_ENABLED,
314 	OTHER_JOB_DISABLED,
315 	OTHER_JOB_ACTIVE,
316 	OTHER_JOB_INACTIVE,
317 } semaphore_reason_t;
318 
319 struct semaphoreitem {
320 	SLIST_ENTRY(semaphoreitem) sle;
321 	semaphore_reason_t why;
322 
323 	union {
324 		const char what[0];
325 		char what_init[0];
326 	};
327 };
328 
329 struct semaphoreitem_dict_iter_context {
330 	job_t j;
331 	semaphore_reason_t why_true;
332 	semaphore_reason_t why_false;
333 };
334 
335 static bool semaphoreitem_new(job_t j, semaphore_reason_t why, const char *what);
336 static void semaphoreitem_delete(job_t j, struct semaphoreitem *si);
337 static void semaphoreitem_setup(launch_data_t obj, const char *key, void *context);
338 static void semaphoreitem_setup_dict_iter(launch_data_t obj, const char *key, void *context);
339 static void semaphoreitem_runtime_mod_ref(struct semaphoreitem *si, bool add);
340 
341 struct externalevent {
342 	LIST_ENTRY(externalevent) sys_le;
343 	LIST_ENTRY(externalevent) job_le;
344 	struct eventsystem *sys;
345 
346 	uint64_t id;
347 	job_t job;
348 	bool state;
349 	bool wanted_state;
350 	bool internal;
351 	xpc_object_t event;
352 	xpc_object_t entitlements;
353 
354 	char name[0];
355 };
356 
357 struct externalevent_iter_ctx {
358 	job_t j;
359 	struct eventsystem *sys;
360 };
361 
362 static bool externalevent_new(job_t j, struct eventsystem *sys, const char *evname, xpc_object_t event, uint64_t flags);
363 static void externalevent_delete(struct externalevent *ee);
364 static void externalevent_setup(launch_data_t obj, const char *key, void *context);
365 static struct externalevent *externalevent_find(const char *sysname, uint64_t id);
366 
367 struct eventsystem {
368 	LIST_ENTRY(eventsystem) global_le;
369 	LIST_HEAD(, externalevent) events;
370 	uint64_t curid;
371 	char name[0];
372 };
373 
374 static struct eventsystem *eventsystem_new(const char *name);
375 static void eventsystem_delete(struct eventsystem *sys) __attribute__((unused));
376 static void eventsystem_setup(launch_data_t obj, const char *key, void *context);
377 static struct eventsystem *eventsystem_find(const char *name);
378 static void eventsystem_ping(void);
379 
380 struct waiting4attach {
381 	LIST_ENTRY(waiting4attach) le;
382 	mach_port_t port;
383 	pid_t dest;
384 	xpc_service_type_t type;
385 	char name[0];
386 };
387 
388 static LIST_HEAD(, waiting4attach) _launchd_domain_waiters;
389 
390 static struct waiting4attach *waiting4attach_new(jobmgr_t jm, const char *name, mach_port_t port, pid_t dest, xpc_service_type_t type);
391 static void waiting4attach_delete(jobmgr_t jm, struct waiting4attach *w4a);
392 static struct waiting4attach *waiting4attach_find(jobmgr_t jm, job_t j);
393 
394 #define ACTIVE_JOB_HASH_SIZE 32
395 #define ACTIVE_JOB_HASH(x) (IS_POWER_OF_TWO(ACTIVE_JOB_HASH_SIZE) ? (x & (ACTIVE_JOB_HASH_SIZE - 1)) : (x % ACTIVE_JOB_HASH_SIZE))
396 
397 #define MACHSERVICE_HASH_SIZE	37
398 
399 #define LABEL_HASH_SIZE 53
400 struct jobmgr_s {
401 	kq_callback kqjobmgr_callback;
402 	LIST_ENTRY(jobmgr_s) xpc_le;
403 	SLIST_ENTRY(jobmgr_s) sle;
404 	SLIST_HEAD(, jobmgr_s) submgrs;
405 	LIST_HEAD(, job_s) jobs;
406 	LIST_HEAD(, waiting4attach) attaches;
407 
408 	/* For legacy reasons, we keep all job labels that are imported in the root
409 	 * job manager's label hash. If a job manager is an XPC domain, then it gets
410 	 * its own label hash that is separate from the "global" one stored in the
411 	 * root job manager.
412 	 */
413 	LIST_HEAD(, job_s) label_hash[LABEL_HASH_SIZE];
414 	LIST_HEAD(, job_s) active_jobs[ACTIVE_JOB_HASH_SIZE];
415 	LIST_HEAD(, machservice) ms_hash[MACHSERVICE_HASH_SIZE];
416 	LIST_HEAD(, job_s) global_env_jobs;
417 	mach_port_t jm_port;
418 	mach_port_t req_port;
419 	jobmgr_t parentmgr;
420 	int reboot_flags;
421 	time_t shutdown_time;
422 	unsigned int global_on_demand_cnt;
423 	unsigned int normal_active_cnt;
424 	unsigned int
425 		shutting_down:1,
426 		session_initialized:1,
427 		killed_stray_jobs:1,
428 		monitor_shutdown:1,
429 		shutdown_jobs_dirtied:1,
430 		shutdown_jobs_cleaned:1,
431 		xpc_singleton:1;
432 	uint32_t properties;
433 	// XPC-specific properties.
434 	char owner[MAXCOMLEN];
435 	const char *shortdesc;
436 	mach_port_t req_bsport;
437 	mach_port_t req_excport;
438 	mach_port_t req_asport;
439 	mach_port_t req_gui_asport;
440 	pid_t req_pid;
441 	uid_t req_euid;
442 	gid_t req_egid;
443 	au_asid_t req_asid;
444 	vm_offset_t req_ctx;
445 	mach_msg_type_number_t req_ctx_sz;
446 	mach_port_t req_rport;
447 	uint64_t req_uniqueid;
448 	kern_return_t error;
449 	union {
450 		const char name[0];
451 		char name_init[0];
452 	};
453 };
454 
455 // Global XPC domains.
456 static jobmgr_t _s_xpc_system_domain;
457 static LIST_HEAD(, jobmgr_s) _s_xpc_user_domains;
458 static LIST_HEAD(, jobmgr_s) _s_xpc_session_domains;
459 
460 #define jobmgr_assumes(jm, e) os_assumes_ctx(jobmgr_log_bug, jm, (e))
461 #define jobmgr_assumes_zero(jm, e) os_assumes_zero_ctx(jobmgr_log_bug, jm, (e))
462 #define jobmgr_assumes_zero_p(jm, e) posix_assumes_zero_ctx(jobmgr_log_bug, jm, (e))
463 
464 static jobmgr_t jobmgr_new(jobmgr_t jm, mach_port_t requestorport, mach_port_t transfer_port, bool sflag, const char *name, bool no_init, mach_port_t asport);
465 static jobmgr_t jobmgr_new_xpc_singleton_domain(jobmgr_t jm, name_t name);
466 static jobmgr_t jobmgr_find_xpc_per_user_domain(jobmgr_t jm, uid_t uid);
467 static jobmgr_t jobmgr_find_xpc_per_session_domain(jobmgr_t jm, au_asid_t asid);
468 static job_t jobmgr_import2(jobmgr_t jm, launch_data_t pload);
469 static jobmgr_t jobmgr_parent(jobmgr_t jm);
470 static jobmgr_t jobmgr_do_garbage_collection(jobmgr_t jm);
471 static bool jobmgr_label_test(jobmgr_t jm, const char *str);
472 static void jobmgr_reap_bulk(jobmgr_t jm, struct kevent *kev);
473 static void jobmgr_log_stray_children(jobmgr_t jm, bool kill_strays);
474 static void jobmgr_kill_stray_children(jobmgr_t jm, pid_t *p, size_t np);
475 static void jobmgr_remove(jobmgr_t jm);
476 static void jobmgr_dispatch_all(jobmgr_t jm, bool newmounthack);
477 static job_t jobmgr_init_session(jobmgr_t jm, const char *session_type, bool sflag);
478 static job_t jobmgr_find_by_pid_deep(jobmgr_t jm, pid_t p, bool anon_okay);
479 static job_t jobmgr_find_by_pid(jobmgr_t jm, pid_t p, bool create_anon);
480 static job_t managed_job(pid_t p);
481 static jobmgr_t jobmgr_find_by_name(jobmgr_t jm, const char *where);
482 static job_t job_mig_intran2(jobmgr_t jm, mach_port_t mport, pid_t upid);
483 static job_t jobmgr_lookup_per_user_context_internal(job_t j, uid_t which_user, mach_port_t *mp);
484 static void job_export_all2(jobmgr_t jm, launch_data_t where);
485 static void jobmgr_callback(void *obj, struct kevent *kev);
486 static void jobmgr_setup_env_from_other_jobs(jobmgr_t jm);
487 static void jobmgr_export_env_from_other_jobs(jobmgr_t jm, launch_data_t dict);
488 static struct machservice *jobmgr_lookup_service(jobmgr_t jm, const char *name, bool check_parent, pid_t target_pid);
489 static void jobmgr_logv(jobmgr_t jm, int pri, int err, const char *msg, va_list ap) __attribute__((format(printf, 4, 0)));
490 static void jobmgr_log(jobmgr_t jm, int pri, const char *msg, ...) __attribute__((format(printf, 3, 4)));
491 static void jobmgr_log_perf_statistics(jobmgr_t jm, bool signal_children);
492 // static void jobmgr_log_error(jobmgr_t jm, int pri, const char *msg, ...) __attribute__((format(printf, 3, 4)));
493 static bool jobmgr_log_bug(_SIMPLE_STRING asl_message, void *ctx, const char *message);
494 
495 #define AUTO_PICK_LEGACY_LABEL (const char *)(~0)
496 #define AUTO_PICK_ANONYMOUS_LABEL (const char *)(~1)
497 #define AUTO_PICK_XPC_LABEL (const char *)(~2)
498 
499 struct suspended_peruser {
500 	LIST_ENTRY(suspended_peruser) sle;
501 	job_t j;
502 };
503 
504 struct job_s {
505 	// MUST be first element of this structure.
506 	kq_callback kqjob_callback;
507 	LIST_ENTRY(job_s) sle;
508 	LIST_ENTRY(job_s) subjob_sle;
509 	LIST_ENTRY(job_s) needing_session_sle;
510 	LIST_ENTRY(job_s) jetsam_sle;
511 	LIST_ENTRY(job_s) pid_hash_sle;
512 	LIST_ENTRY(job_s) global_pid_hash_sle;
513 	LIST_ENTRY(job_s) label_hash_sle;
514 	LIST_ENTRY(job_s) global_env_sle;
515 	SLIST_ENTRY(job_s) curious_jobs_sle;
516 	LIST_HEAD(, suspended_peruser) suspended_perusers;
517 	LIST_HEAD(, waiting_for_exit) exit_watchers;
518 	LIST_HEAD(, job_s) subjobs;
519 	LIST_HEAD(, externalevent) events;
520 	SLIST_HEAD(, socketgroup) sockets;
521 	SLIST_HEAD(, calendarinterval) cal_intervals;
522 	SLIST_HEAD(, envitem) global_env;
523 	SLIST_HEAD(, envitem) env;
524 	SLIST_HEAD(, limititem) limits;
525 	SLIST_HEAD(, machservice) machservices;
526 	SLIST_HEAD(, semaphoreitem) semaphores;
527 	SLIST_HEAD(, waiting_for_removal) removal_watchers;
528 	struct waiting4attach *w4a;
529 	job_t original;
530 	job_t alias;
531 	cpu_type_t *j_binpref;
532 	size_t j_binpref_cnt;
533 	mach_port_t j_port;
534 	mach_port_t exit_status_dest;
535 	mach_port_t exit_status_port;
536 	mach_port_t spawn_reply_port;
537 	uid_t mach_uid;
538 	jobmgr_t mgr;
539 	size_t argc;
540 	char **argv;
541 	char *prog;
542 	char *rootdir;
543 	char *workingdir;
544 	char *username;
545 	char *groupname;
546 	char *stdinpath;
547 	char *stdoutpath;
548 	char *stderrpath;
549 	char *alt_exc_handler;
550 	char *cfbundleidentifier;
551 	unsigned int nruns;
552 	uint64_t trt;
553 #if HAVE_SANDBOX
554 	char *seatbelt_profile;
555 	uint64_t seatbelt_flags;
556 	char *container_identifier;
557 #endif
558 #if HAVE_QUARANTINE
559 	void *quarantine_data;
560 	size_t quarantine_data_sz;
561 #endif
562 	pid_t p;
563 	uint64_t uniqueid;
564 	int last_exit_status;
565 	int stdin_fd;
566 	int fork_fd;
567 	int nice;
568 	uint32_t pstype;
569 	uint32_t psproctype;
570 	int32_t jetsam_priority;
571 	int32_t jetsam_memlimit;
572 	int32_t main_thread_priority;
573 	uint32_t timeout;
574 	uint32_t exit_timeout;
575 	uint64_t sent_signal_time;
576 	uint64_t start_time;
577 	uint32_t min_run_time;
578 	bool unthrottle;
579 	uint32_t start_interval;
580 	uint32_t peruser_suspend_count;
581 	uuid_t instance_id;
582 	mode_t mask;
583 	mach_port_t asport;
584 	au_asid_t asid;
585 	uuid_t expected_audit_uuid;
586 	bool
587 		// man launchd.plist --> Debug
588 		debug:1,
589 		// man launchd.plist --> KeepAlive == false
590 		ondemand:1,
591 		// man launchd.plist --> SessionCreate
592 		session_create:1,
593 		// man launchd.plist --> LowPriorityIO
594 		low_pri_io:1,
595 		// man launchd.plist --> InitGroups
596 		no_init_groups:1,
597 		/* A legacy mach_init concept to make bootstrap_create_server/service()
598 		 * work
599 		 */
600 		priv_port_has_senders:1,
601 		// A hack during job importing
602 		importing_global_env:1,
603 		// A hack during job importing
604 		importing_hard_limits:1,
605 		// man launchd.plist --> Umask
606 		setmask:1,
607 		// A process that launchd knows about but doesn't manage.
608 		anonymous:1,
609 		// A legacy mach_init concept to detect sick jobs
610 		checkedin:1,
611 		// A job created via bootstrap_create_server()
612 		legacy_mach_job:1,
613 		// A job created via spawn_via_launchd()
614 		legacy_LS_job:1,
615 		// A legacy job that wants inetd compatible semantics
616 		inetcompat:1,
617 		// A twist on inetd compatibility
618 		inetcompat_wait:1,
619 		/* An event fired and the job should start, but not necessarily right
620 		 * away.
621 		 */
622 		start_pending:1,
623 		// man launchd.plist --> EnableGlobbing
624 		globargv:1,
625 		// man launchd.plist --> WaitForDebugger
626 		wait4debugger:1,
627 		// One-shot WaitForDebugger.
628 		wait4debugger_oneshot:1,
629 		// MachExceptionHandler == true
630 		internal_exc_handler:1,
631 		// A hack to support an option of spawn_via_launchd()
632 		stall_before_exec:1,
633 		/* man launchd.plist --> LaunchOnlyOnce.
634 		 *
635 		 * Note: <rdar://problem/5465184> Rename this to "HopefullyNeverExits".
636 		 */
637 		only_once:1,
638 		/* Make job_ignore() / job_watch() work. If these calls were balanced,
639 		 * then this wouldn't be necessarily.
640 		 */
641 		currently_ignored:1,
642 		/* A job that forced all other jobs to be temporarily launch-on-
643 		 * demand
644 		 */
645 		forced_peers_to_demand_mode:1,
646 		// man launchd.plist --> Nice
647 		setnice:1,
648 		/* A job was asked to be unloaded/removed while running, we'll remove it
649 		 * after it exits.
650 		 */
651 		removal_pending:1,
652 		// job_kill() was called.
653 		sent_sigkill:1,
654 		// Enter the kernel debugger before killing a job.
655 		debug_before_kill:1,
656 		// A hack that launchd+launchctl use during jobmgr_t creation.
657 		weird_bootstrap:1,
658 		// man launchd.plist --> StartOnMount
659 		start_on_mount:1,
660 		// This job is a per-user launchd managed by the PID 1 launchd.
661 		per_user:1,
662 		// A job thoroughly confused launchd. We need to unload it ASAP.
663 		unload_at_mig_return:1,
664 		// man launchd.plist --> AbandonProcessGroup
665 		abandon_pg:1,
666 		/* During shutdown, do not send SIGTERM to stray processes in the
667 		 * process group of this job.
668 		 */
669 		ignore_pg_at_shutdown:1,
670 		/* Don't let this job create new 'job_t' objects in launchd. Has been
671 		 * seriously overloaded for the purposes of sandboxing.
672 		 */
673 		deny_job_creation:1,
674 		// man launchd.plist --> EnableTransactions
675 		enable_transactions:1,
676 		// The job was sent SIGKILL because it was clean.
677 		clean_kill:1,
678 		// The job has an OtherJobEnabled KeepAlive criterion.
679 		nosy:1,
680 		// The job exited due to a crash.
681 		crashed:1,
682 		// We've received NOTE_EXIT for the job and reaped it.
683 		reaped:1,
684 		// job_stop() was called.
685 		stopped:1,
686 		/* The job is to be kept alive continuously, but it must first get an
687 		 * initial kick off.
688 		 */
689 		needs_kickoff:1,
690 		// The job is a bootstrapper.
691 		is_bootstrapper:1,
692 		// The job owns the console.
693 		has_console:1,
694 		/* The job runs as a non-root user on embedded but has select privileges
695 		 * of the root user. This is SpringBoard.
696 		 */
697 		embedded_god:1,
698 		// The job is responsible for drawing the home screen on embedded.
699 		embedded_home:1,
700 		// We got NOTE_EXEC for the job.
701 		did_exec:1,
702 		// The job is an XPC service, and XPC proxy successfully exec(3)ed.
703 		xpcproxy_did_exec:1,
704 		// The (anonymous) job called vprocmgr_switch_to_session().
705 		holds_ref:1,
706 		// The job has Jetsam limits in place.
707 		jetsam_properties:1,
708 		// The job's Jetsam memory limits should only be applied in the background
709  		jetsam_memory_limit_background:1,
710 		/* This job was created as the result of a look up of a service provided
711 		 * by a MultipleInstance job.
712 		 */
713 		dedicated_instance:1,
714 		// The job supports creating additional instances of itself.
715 		multiple_instances:1,
716 		/* The sub-job was already removed from the parent's list of
717 		 * sub-jobs.
718 		 */
719 		former_subjob:1,
720 		/* The job is responsible for monitoring external events for this
721 		 * launchd.
722 		 */
723 		event_monitor:1,
724 		// The event monitor job has retrieved the initial list of events.
725 		event_monitor_ready2signal:1,
726 		// A lame hack.
727 		removing:1,
728 		// Disable ASLR when launching this job.
729 		disable_aslr:1,
730 		// The job is an XPC Service.
731 		xpc_service:1,
732 		// The job is the Performance team's shutdown monitor.
733 		shutdown_monitor:1,
734 		// We should open a transaction for the job when shutdown begins.
735 		dirty_at_shutdown:1,
736 		/* The job was sent SIGKILL but did not exit in a timely fashion,
737 		 * indicating a kernel bug.
738 		 */
739 		workaround9359725:1,
740 		// The job is the XPC domain bootstrapper.
741 		xpc_bootstrapper:1,
742 		// The job is an app (on either iOS or OS X) and has different resource
743 		// limitations.
744 		app:1,
745 		// FairPlay decryption failed on the job. This should only ever happen
746 		// to apps.
747 		fpfail:1,
748 		// The job failed to exec(3) for reasons that may be transient, so we're
749 		// waiting for UserEventAgent to tell us when it's okay to try spawning
750 		// again (i.e. when the executable path appears, when the UID appears,
751 		// etc.).
752 		waiting4ok:1,
753 		// The job exited due to memory pressure.
754 		jettisoned:1,
755 		// The job supports idle-exit.
756 		idle_exit:1,
757 		// The job was implicitly reaped by the kernel.
758 		implicit_reap:1,
759 		system_app :1,
760 		joins_gui_session :1,
761 		low_priority_background_io :1,
762 		legacy_timers :1;
763 
764 	const char label[0];
765 };
766 
767 static size_t hash_label(const char *label) __attribute__((pure));
768 static size_t hash_ms(const char *msstr) __attribute__((pure));
769 static SLIST_HEAD(, job_s) s_curious_jobs;
770 static LIST_HEAD(, job_s) managed_actives[ACTIVE_JOB_HASH_SIZE];
771 
772 #define job_assumes(j, e) os_assumes_ctx(job_log_bug, j, (e))
773 #if 1
774 #define job_assumes_zero(j, e) os_assumes_zero_ctx(job_log_bug, j, (e))
775 #else
776 static int
crapout(int value,void * j,const char * e)777 crapout(int value, void *j, const char *e)
778 {
779 	if (value) {
780 		printf("%s=%d j=%p\n", (e), value, j);
781 		abort();
782 	}
783 	return (value);
784 }
785 
786 #define job_assumes_zero(j, e) crapout((e), j, #e)
787 #endif
788 
789 #define job_assumes_zero_p(j, e) posix_assumes_zero_ctx(job_log_bug, j, (e))
790 
791 static void job_import_keys(launch_data_t obj, const char *key, void *context);
792 static void job_import_bool(job_t j, const char *key, bool value);
793 static void job_import_string(job_t j, const char *key, const char *value);
794 static void job_import_integer(job_t j, const char *key, long long value);
795 static void job_import_dictionary(job_t j, const char *key, launch_data_t value);
796 static void job_import_array(job_t j, const char *key, launch_data_t value);
797 static void job_import_opaque(job_t j, const char *key, launch_data_t value);
798 static bool job_set_global_on_demand(job_t j, bool val);
799 static const char *job_active(job_t j);
800 static void job_watch(job_t j);
801 static void job_ignore(job_t j);
802 static void job_reap(job_t j);
803 static bool job_useless(job_t j);
804 static bool job_keepalive(job_t j);
805 static void job_dispatch_curious_jobs(job_t j);
806 static void job_start(job_t j);
807 static void job_start_child(job_t j) __attribute__((noreturn));
808 static void job_setup_attributes(job_t j);
809 static bool job_setup_machport(job_t j);
810 static kern_return_t job_setup_exit_port(job_t j);
811 static void job_setup_fd(job_t j, int target_fd, const char *path, int flags);
812 static void job_postfork_become_user(job_t j);
813 static void job_postfork_test_user(job_t j);
814 static void job_log_pids_with_weird_uids(job_t j);
815 static void job_setup_exception_port(job_t j, task_t target_task);
816 static void job_callback(void *obj, struct kevent *kev);
817 static void job_callback_proc(job_t j, struct kevent *kev);
818 static void job_callback_timer(job_t j, void *ident);
819 static void job_callback_read(job_t j, int ident);
820 static void job_log_stray_pg(job_t j);
821 static void job_log_children_without_exec(job_t j);
822 static job_t job_new_anonymous(jobmgr_t jm, pid_t anonpid) __attribute__((malloc, nonnull, warn_unused_result));
823 static job_t job_new(jobmgr_t jm, const char *label, const char *prog, const char *const *argv) __attribute__((malloc, nonnull(1,2), warn_unused_result));
824 static job_t job_new_alias(jobmgr_t jm, job_t src);
825 static job_t job_new_via_mach_init(job_t j, const char *cmd, uid_t uid, bool ond) __attribute__((malloc, nonnull, warn_unused_result));
826 static job_t job_new_subjob(job_t j, uuid_t identifier);
827 static void job_kill(job_t j);
828 static void job_uncork_fork(job_t j);
829 static void job_logv(job_t j, int pri, int err, const char *msg, va_list ap) __attribute__((format(printf, 4, 0)));
830 static void job_log_error(job_t j, int pri, const char *msg, ...) __attribute__((format(printf, 3, 4)));
831 static bool job_log_bug(_SIMPLE_STRING asl_message, void *ctx, const char *message);
832 static void job_log_perf_statistics(job_t j, struct rusage_info_v1 *ri, int64_t exit_status);
833 #if HAVE_SYSTEMSTATS
834 static void job_log_systemstats(pid_t pid, uint64_t uniqueid, uint64_t parent_uniqueid, pid_t req_pid, uint64_t req_uniqueid, const char *name, struct rusage_info_v1 *ri, int64_t exit_status);
835 #endif
836 static void job_set_exception_port(job_t j, mach_port_t port);
837 static kern_return_t job_mig_spawn_internal(job_t j, vm_offset_t indata, mach_msg_type_number_t indataCnt, mach_port_t asport, job_t *outj);
838 static void job_open_shutdown_transaction(job_t ji);
839 static void job_close_shutdown_transaction(job_t ji);
840 #ifndef __FreeBSD__
841 static launch_data_t job_do_legacy_ipc_request(job_t j, launch_data_t request, mach_port_t asport);
842 #endif
843 static void job_setup_per_user_directory(job_t j, uid_t uid, const char *path);
844 static void job_setup_per_user_directories(job_t j, uid_t uid, const char *label);
845 static void job_update_jetsam_properties(job_t j, xpc_jetsam_band_t band, uint64_t user_data);
846 static void job_update_jetsam_memory_limit(job_t j, int32_t limit);
847 
848 #if TARGET_OS_EMBEDDED
849 static bool job_import_defaults(launch_data_t pload);
850 #endif
851 
852 
853 static struct priority_properties_t {
854 	long long band;
855 	int priority;
856 } _launchd_priority_map[] = {
857 	{ 0, 0}
858 #if 0
859 	{ XPC_JETSAM_BAND_SUSPENDED, JETSAM_PRIORITY_IDLE },
860 	{ XPC_JETSAM_BAND_BACKGROUND_OPPORTUNISTIC, JETSAM_PRIORITY_BACKGROUND_OPPORTUNISTIC },
861 	{ XPC_JETSAM_BAND_BACKGROUND, JETSAM_PRIORITY_BACKGROUND },
862 	{ XPC_JETSAM_BAND_MAIL, JETSAM_PRIORITY_MAIL },
863 	{ XPC_JETSAM_BAND_PHONE, JETSAM_PRIORITY_PHONE },
864 	{ XPC_JETSAM_BAND_UI_SUPPORT, JETSAM_PRIORITY_UI_SUPPORT },
865 	{ XPC_JETSAM_BAND_FOREGROUND_SUPPORT, JETSAM_PRIORITY_FOREGROUND_SUPPORT },
866 	{ XPC_JETSAM_BAND_FOREGROUND, JETSAM_PRIORITY_FOREGROUND },
867 	{ XPC_JETSAM_BAND_AUDIO, JETSAM_PRIORITY_AUDIO_AND_ACCESSORY },
868 	{ XPC_JETSAM_BAND_ACCESSORY, JETSAM_PRIORITY_AUDIO_AND_ACCESSORY },
869 	{ XPC_JETSAM_BAND_CRITICAL, JETSAM_PRIORITY_CRITICAL },
870 	{ XPC_JETSAM_BAND_TELEPHONY, JETSAM_PRIORITY_TELEPHONY },
871 #endif
872 };
873 
874 static const struct {
875 	const char *key;
876 	int val;
877 } launchd_keys2limits[] = {
878 	{ LAUNCH_JOBKEY_RESOURCELIMIT_CORE, RLIMIT_CORE },
879 	{ LAUNCH_JOBKEY_RESOURCELIMIT_CPU, RLIMIT_CPU },
880 	{ LAUNCH_JOBKEY_RESOURCELIMIT_DATA, RLIMIT_DATA },
881 	{ LAUNCH_JOBKEY_RESOURCELIMIT_FSIZE, RLIMIT_FSIZE },
882 	{ LAUNCH_JOBKEY_RESOURCELIMIT_MEMLOCK, RLIMIT_MEMLOCK },
883 	{ LAUNCH_JOBKEY_RESOURCELIMIT_NOFILE, RLIMIT_NOFILE },
884 	{ LAUNCH_JOBKEY_RESOURCELIMIT_NPROC, RLIMIT_NPROC },
885 	{ LAUNCH_JOBKEY_RESOURCELIMIT_RSS, RLIMIT_RSS },
886 	{ LAUNCH_JOBKEY_RESOURCELIMIT_STACK, RLIMIT_STACK },
887 };
888 
889 static time_t cronemu(int mon, int mday, int hour, int min);
890 static time_t cronemu_wday(int wday, int hour, int min);
891 static bool cronemu_mon(struct tm *wtm, int mon, int mday, int hour, int min);
892 static bool cronemu_mday(struct tm *wtm, int mday, int hour, int min);
893 static bool cronemu_hour(struct tm *wtm, int hour, int min);
894 static bool cronemu_min(struct tm *wtm, int min);
895 
896 // miscellaneous file local functions
897 static size_t get_kern_max_proc(void);
898 static char **mach_cmd2argv(const char *string);
899 static size_t our_strhash(const char *s) __attribute__((pure));
900 
901 void eliminate_double_reboot(void);
902 
903 #pragma mark XPC Domain Forward Declarations
904 static job_t _xpc_domain_import_service(jobmgr_t jm, launch_data_t pload);
905 static int _xpc_domain_import_services(job_t j, launch_data_t services);
906 
907 #pragma mark XPC Event Forward Declarations
908 static int xpc_event_find_channel(job_t j, const char *stream, struct machservice **ms);
909 static int xpc_event_get_event_name(job_t j, xpc_object_t request, xpc_object_t *reply);
910 static int xpc_event_set_event(job_t j, xpc_object_t request, xpc_object_t *reply);
911 static int xpc_event_copy_event(job_t j, xpc_object_t request, xpc_object_t *reply);
912 static int xpc_event_channel_check_in(job_t j, xpc_object_t request, xpc_object_t *reply);
913 static int xpc_event_channel_look_up(job_t j, xpc_object_t request, xpc_object_t *reply);
914 static int xpc_event_provider_check_in(job_t j, xpc_object_t request, xpc_object_t *reply);
915 static int xpc_event_provider_set_state(job_t j, xpc_object_t request, xpc_object_t *reply);
916 
917 #pragma mark XPC Process Forward Declarations
918 static int xpc_process_set_jetsam_band(job_t j, xpc_object_t request, xpc_object_t *reply);
919 static int xpc_process_set_jetsam_memory_limit(job_t j, xpc_object_t request, xpc_object_t *reply);
920 
921 // file local globals
922 static job_t _launchd_embedded_god = NULL;
923 static job_t _launchd_embedded_home = NULL;
924 static size_t total_children;
925 static size_t total_anon_children;
926 static mach_port_t the_exception_server;
927 static job_t workaround_5477111;
928 static LIST_HEAD(, job_s) s_needing_sessions;
929 static LIST_HEAD(, eventsystem) _s_event_systems;
930 static struct eventsystem *_launchd_support_system;
931 static job_t _launchd_event_monitor;
932 static job_t _launchd_xpc_bootstrapper;
933 static job_t _launchd_shutdown_monitor;
934 
935 #if TARGET_OS_EMBEDDED
936 static xpc_object_t _launchd_defaults_cache;
937 
938 mach_port_t launchd_audit_port = MACH_PORT_DEAD;
939 pid_t launchd_audit_session = 0;
940 #else
941 mach_port_t launchd_audit_port = MACH_PORT_NULL;
942 au_asid_t launchd_audit_session = AU_DEFAUDITSID;
943 #endif
944 
945 static int s_no_hang_fd = -1;
946 
947 // process wide globals
948 mach_port_t inherited_bootstrap_port;
949 jobmgr_t root_jobmgr;
950 bool launchd_shutdown_debugging = false;
951 bool launchd_verbose_boot = false;
952 bool launchd_embedded_handofgod = false;
953 bool launchd_runtime_busy_time = false;
954 
955 void
job_ignore(job_t j)956 job_ignore(job_t j)
957 {
958 	struct socketgroup *sg;
959 	struct machservice *ms;
960 
961 	if (j->currently_ignored) {
962 		return;
963 	}
964 
965 	job_log(j, LOG_DEBUG, "Ignoring...");
966 
967 	j->currently_ignored = true;
968 
969 	SLIST_FOREACH(sg, &j->sockets, sle) {
970 		socketgroup_ignore(j, sg);
971 	}
972 
973 	SLIST_FOREACH(ms, &j->machservices, sle) {
974 		machservice_ignore(j, ms);
975 	}
976 }
977 
978 void
job_watch(job_t j)979 job_watch(job_t j)
980 {
981 	struct socketgroup *sg;
982 	struct machservice *ms;
983 
984 	if (!j->currently_ignored) {
985 		return;
986 	}
987 
988 	job_log(j, LOG_DEBUG, "Watching...");
989 
990 	j->currently_ignored = false;
991 
992 	SLIST_FOREACH(sg, &j->sockets, sle) {
993 		socketgroup_watch(j, sg);
994 	}
995 
996 	SLIST_FOREACH(ms, &j->machservices, sle) {
997 		machservice_watch(j, ms);
998 	}
999 }
1000 
1001 void
job_stop(job_t j)1002 job_stop(job_t j)
1003 {
1004 	int sig;
1005 
1006 	if (unlikely(!j->p || j->stopped || j->anonymous)) {
1007 		return;
1008 	}
1009 
1010 #if TARGET_OS_EMBEDDED
1011 	if (launchd_embedded_handofgod && _launchd_embedded_god) {
1012 		if (!_launchd_embedded_god->username || !j->username) {
1013 			errno = EPERM;
1014 			return;
1015 		}
1016 
1017 		if (strcmp(j->username, _launchd_embedded_god->username) != 0) {
1018 			errno = EPERM;
1019 			return;
1020 		}
1021 	} else if (launchd_embedded_handofgod) {
1022 		errno = EINVAL;
1023 		return;
1024 	}
1025 #endif
1026 
1027 	j->sent_signal_time = runtime_get_opaque_time();
1028 
1029 	job_log(j, LOG_DEBUG | LOG_CONSOLE, "Stopping job...");
1030 
1031 	int error = -1;
1032 	error = proc_terminate(j->p, &sig);
1033 	if (error) {
1034 		job_log(j, LOG_ERR | LOG_CONSOLE, "Could not terminate job: %d: %s", error, strerror(error));
1035 		job_log(j, LOG_NOTICE | LOG_CONSOLE, "Using fallback option to terminate job...");
1036 		error = kill2(j->p, SIGTERM);
1037 		if (error) {
1038 			job_log(j, LOG_ERR, "Could not signal job: %d: %s", error, strerror(error));
1039 		} else {
1040 			sig = SIGTERM;
1041 		}
1042 	}
1043 
1044 	if (!error) {
1045 		switch (sig) {
1046 		case SIGKILL:
1047 			j->sent_sigkill = true;
1048 			j->clean_kill = true;
1049 
1050 			/* We cannot effectively simulate an exit for jobs during the course
1051 			 * of a normal run. Even if we pretend that the job exited, we will
1052 			 * still not have gotten the receive rights associated with the
1053 			 * job's MachServices back, so we cannot safely respawn it.
1054 			 */
1055 			if (j->mgr->shutting_down) {
1056 				error = kevent_mod((uintptr_t)&j->exit_timeout, EVFILT_TIMER, EV_ADD|EV_ONESHOT, NOTE_SECONDS, LAUNCHD_SIGKILL_TIMER, j);
1057 				(void)job_assumes_zero_p(j, error);
1058 			}
1059 
1060 			job_log(j, LOG_DEBUG | LOG_CONSOLE, "Sent job SIGKILL.");
1061 			break;
1062 		case SIGTERM:
1063 			if (j->exit_timeout) {
1064 				error = kevent_mod((uintptr_t)&j->exit_timeout, EVFILT_TIMER, EV_ADD|EV_ONESHOT, NOTE_SECONDS, j->exit_timeout, j);
1065 				(void)job_assumes_zero_p(j, error);
1066 			} else {
1067 				job_log(j, LOG_NOTICE, "This job has an infinite exit timeout");
1068 			}
1069 			job_log(j, LOG_DEBUG, "Sent job SIGTERM.");
1070 			break;
1071 		default:
1072 			job_log(j, LOG_ERR | LOG_CONSOLE, "Job was sent unexpected signal: %d: %s", sig, strsignal(sig));
1073 			break;
1074 		}
1075 	}
1076 
1077 	j->stopped = true;
1078 }
1079 
1080 launch_data_t
job_export(job_t j)1081 job_export(job_t j)
1082 {
1083 	launch_data_t tmp, tmp2, tmp3, r = launch_data_alloc(LAUNCH_DATA_DICTIONARY);
1084 
1085 	if (r == NULL) {
1086 		return NULL;
1087 	}
1088 
1089 	if ((tmp = launch_data_new_string(j->label))) {
1090 		launch_data_dict_insert(r, tmp, LAUNCH_JOBKEY_LABEL);
1091 	}
1092 	if ((tmp = launch_data_new_string(j->mgr->name))) {
1093 		launch_data_dict_insert(r, tmp, LAUNCH_JOBKEY_LIMITLOADTOSESSIONTYPE);
1094 	}
1095 	if ((tmp = launch_data_new_bool(j->ondemand))) {
1096 		launch_data_dict_insert(r, tmp, LAUNCH_JOBKEY_ONDEMAND);
1097 	}
1098 
1099 	long long status = j->last_exit_status;
1100 	if (j->fpfail) {
1101 		status = LAUNCH_EXITSTATUS_FAIRPLAY_FAIL;
1102 	}
1103 	if ((tmp = launch_data_new_integer(status))) {
1104 		launch_data_dict_insert(r, tmp, LAUNCH_JOBKEY_LASTEXITSTATUS);
1105 	}
1106 
1107 	if (j->p && (tmp = launch_data_new_integer(j->p))) {
1108 		launch_data_dict_insert(r, tmp, LAUNCH_JOBKEY_PID);
1109 	}
1110 	if ((tmp = launch_data_new_integer(j->timeout))) {
1111 		launch_data_dict_insert(r, tmp, LAUNCH_JOBKEY_TIMEOUT);
1112 	}
1113 	if (j->prog && (tmp = launch_data_new_string(j->prog))) {
1114 		launch_data_dict_insert(r, tmp, LAUNCH_JOBKEY_PROGRAM);
1115 	}
1116 	if (j->stdinpath && (tmp = launch_data_new_string(j->stdinpath))) {
1117 		launch_data_dict_insert(r, tmp, LAUNCH_JOBKEY_STANDARDINPATH);
1118 	}
1119 	if (j->stdoutpath && (tmp = launch_data_new_string(j->stdoutpath))) {
1120 		launch_data_dict_insert(r, tmp, LAUNCH_JOBKEY_STANDARDOUTPATH);
1121 	}
1122 	if (j->stderrpath && (tmp = launch_data_new_string(j->stderrpath))) {
1123 		launch_data_dict_insert(r, tmp, LAUNCH_JOBKEY_STANDARDERRORPATH);
1124 	}
1125 	if (likely(j->argv) && (tmp = launch_data_alloc(LAUNCH_DATA_ARRAY))) {
1126 		size_t i;
1127 
1128 		for (i = 0; i < j->argc; i++) {
1129 			if ((tmp2 = launch_data_new_string(j->argv[i]))) {
1130 				launch_data_array_set_index(tmp, tmp2, i);
1131 			}
1132 		}
1133 
1134 		launch_data_dict_insert(r, tmp, LAUNCH_JOBKEY_PROGRAMARGUMENTS);
1135 	}
1136 
1137 	if (!SLIST_EMPTY(&j->env) && (tmp = launch_data_alloc(LAUNCH_DATA_DICTIONARY))) {
1138 		struct envitem *ei = NULL;
1139 		SLIST_FOREACH(ei, &j->env, sle) {
1140 			launch_data_dict_insert(tmp, launch_data_new_string(ei->value), ei->key);
1141 		}
1142 
1143 		launch_data_dict_insert(r, tmp, LAUNCH_JOBKEY_ENVIRONMENTVARIABLES);
1144 	}
1145 
1146 	if (j->enable_transactions && (tmp = launch_data_new_bool(true))) {
1147 		launch_data_dict_insert(r, tmp, LAUNCH_JOBKEY_ENABLETRANSACTIONS);
1148 	}
1149 
1150 	if (j->session_create && (tmp = launch_data_new_bool(true))) {
1151 		launch_data_dict_insert(r, tmp, LAUNCH_JOBKEY_SESSIONCREATE);
1152 	}
1153 
1154 	if (j->inetcompat && (tmp = launch_data_alloc(LAUNCH_DATA_DICTIONARY))) {
1155 		if ((tmp2 = launch_data_new_bool(j->inetcompat_wait))) {
1156 			launch_data_dict_insert(tmp, tmp2, LAUNCH_JOBINETDCOMPATIBILITY_WAIT);
1157 		}
1158 		launch_data_dict_insert(r, tmp, LAUNCH_JOBKEY_INETDCOMPATIBILITY);
1159 	}
1160 
1161 	if (!SLIST_EMPTY(&j->sockets) && (tmp = launch_data_alloc(LAUNCH_DATA_DICTIONARY))) {
1162 		struct socketgroup *sg;
1163 		unsigned int i;
1164 
1165 		SLIST_FOREACH(sg, &j->sockets, sle) {
1166 			if ((tmp2 = launch_data_alloc(LAUNCH_DATA_ARRAY))) {
1167 				for (i = 0; i < sg->fd_cnt; i++) {
1168 					if ((tmp3 = launch_data_new_fd(sg->fds[i]))) {
1169 						launch_data_array_set_index(tmp2, tmp3, i);
1170 					}
1171 				}
1172 				launch_data_dict_insert(tmp, tmp2, sg->name);
1173 			}
1174 		}
1175 
1176 		launch_data_dict_insert(r, tmp, LAUNCH_JOBKEY_SOCKETS);
1177 	}
1178 
1179 	if (!SLIST_EMPTY(&j->machservices) && (tmp = launch_data_alloc(LAUNCH_DATA_DICTIONARY))) {
1180 		struct machservice *ms;
1181 
1182 		tmp3 = NULL;
1183 
1184 		SLIST_FOREACH(ms, &j->machservices, sle) {
1185 			if (ms->per_pid) {
1186 				if (tmp3 == NULL) {
1187 					tmp3 = launch_data_alloc(LAUNCH_DATA_DICTIONARY);
1188 				}
1189 				if (tmp3) {
1190 					tmp2 = launch_data_new_machport(MACH_PORT_NULL);
1191 					launch_data_dict_insert(tmp3, tmp2, ms->name);
1192 				}
1193 			} else {
1194 				tmp2 = launch_data_new_machport(MACH_PORT_NULL);
1195 				launch_data_dict_insert(tmp, tmp2, ms->name);
1196 			}
1197 		}
1198 
1199 		launch_data_dict_insert(r, tmp, LAUNCH_JOBKEY_MACHSERVICES);
1200 
1201 		if (tmp3) {
1202 			launch_data_dict_insert(r, tmp3, LAUNCH_JOBKEY_PERJOBMACHSERVICES);
1203 		}
1204 	}
1205 
1206 	return r;
1207 }
1208 
1209 static void
jobmgr_log_active_jobs(jobmgr_t jm)1210 jobmgr_log_active_jobs(jobmgr_t jm)
1211 {
1212 	const char *why_active;
1213 	jobmgr_t jmi;
1214 	job_t ji;
1215 
1216 	SLIST_FOREACH(jmi, &jm->submgrs, sle) {
1217 		jobmgr_log_active_jobs(jmi);
1218 	}
1219 
1220 	int level = LOG_DEBUG;
1221 	if (pid1_magic) {
1222 		level |= LOG_CONSOLE;
1223 	}
1224 
1225 	LIST_FOREACH(ji, &jm->jobs, sle) {
1226 		if ((why_active = job_active(ji))) {
1227 			if (ji->p != 1) {
1228 				job_log(ji, level, "%s", why_active);
1229 
1230 				uint32_t flags = 0;
1231 				(void)proc_get_dirty(ji->p, &flags);
1232 				if (!(flags & PROC_DIRTY_TRACKED)) {
1233 					continue;
1234 				}
1235 
1236 				const char *dirty = "clean";
1237 				if (flags & PROC_DIRTY_IS_DIRTY) {
1238 					dirty = "dirty";
1239 				}
1240 
1241 				const char *idle_exit = "idle-exit unsupported";
1242 				if (flags & PROC_DIRTY_ALLOWS_IDLE_EXIT) {
1243 					idle_exit = "idle-exit supported";
1244 				}
1245 
1246 				job_log(ji, level, "Killability: %s/%s", dirty, idle_exit);
1247 			}
1248 		}
1249 	}
1250 }
1251 
1252 static void
jobmgr_still_alive_with_check(jobmgr_t jm)1253 jobmgr_still_alive_with_check(jobmgr_t jm)
1254 {
1255 	int level = LOG_DEBUG;
1256 	if (pid1_magic) {
1257 		level |= LOG_CONSOLE;
1258 	}
1259 
1260 	jobmgr_log(jm, level, "Still alive with %lu/%lu (normal/anonymous) children.", total_children, total_anon_children);
1261 	jobmgr_log_active_jobs(jm);
1262 	launchd_log_push();
1263 }
1264 
1265 jobmgr_t
jobmgr_shutdown(jobmgr_t jm)1266 jobmgr_shutdown(jobmgr_t jm)
1267 {
1268 	jobmgr_t jmi, jmn;
1269 	launchd_syslog(LOG_CRIT, "Beginning job manager shutdown with flags: %s", reboot_flags_to_C_names(jm->reboot_flags));
1270 	jobmgr_log(jm, LOG_DEBUG, "Beginning job manager shutdown with flags: %s", reboot_flags_to_C_names(jm->reboot_flags));
1271 
1272 	jm->shutdown_time = runtime_get_wall_time() / USEC_PER_SEC;
1273 
1274 	struct tm curtime;
1275 	(void)localtime_r(&jm->shutdown_time, &curtime);
1276 
1277 	char date[26];
1278 	(void)asctime_r(&curtime, date);
1279 	// Trim the new line that asctime_r(3) puts there for some reason.
1280 	date[24] = 0;
1281 
1282 	if (jm == root_jobmgr && pid1_magic) {
1283 		jobmgr_log(jm, LOG_DEBUG | LOG_CONSOLE, "Userspace shutdown begun at: %s", date);
1284 	} else {
1285 		jobmgr_log(jm, LOG_DEBUG, "Job manager shutdown begun at: %s", date);
1286 	}
1287 
1288 	jm->shutting_down = true;
1289 
1290 	SLIST_FOREACH_SAFE(jmi, &jm->submgrs, sle, jmn) {
1291 		jobmgr_shutdown(jmi);
1292 	}
1293 
1294 	if (!jm->parentmgr) {
1295 		if (pid1_magic) {
1296 			// Spawn the shutdown monitor.
1297 			if (_launchd_shutdown_monitor && !_launchd_shutdown_monitor->p) {
1298 				job_log(_launchd_shutdown_monitor, LOG_NOTICE | LOG_CONSOLE, "Starting shutdown monitor.");
1299 				job_dispatch(_launchd_shutdown_monitor, true);
1300 			}
1301 		}
1302 
1303 		(void)jobmgr_assumes_zero_p(jm, kevent_mod((uintptr_t)jm, EVFILT_TIMER, EV_ADD, NOTE_SECONDS, 5, jm));
1304 	}
1305 
1306 	return jobmgr_do_garbage_collection(jm);
1307 }
1308 
1309 void
jobmgr_remove(jobmgr_t jm)1310 jobmgr_remove(jobmgr_t jm)
1311 {
1312 	jobmgr_t jmi;
1313 	job_t ji;
1314 
1315 	jobmgr_log(jm, LOG_DEBUG, "Removing job manager.");
1316 	if (!SLIST_EMPTY(&jm->submgrs)) {
1317 		size_t cnt = 0;
1318 		while ((jmi = SLIST_FIRST(&jm->submgrs))) {
1319 			jobmgr_remove(jmi);
1320 			cnt++;
1321 		}
1322 
1323 		(void)jobmgr_assumes_zero(jm, cnt);
1324 	}
1325 
1326 	while ((ji = LIST_FIRST(&jm->jobs))) {
1327 		if (!ji->anonymous && ji->p != 0) {
1328 			job_log(ji, LOG_ERR, "Job is still active at job manager teardown.");
1329 			ji->p = 0;
1330 		}
1331 
1332 		job_remove(ji);
1333 	}
1334 
1335 	struct waiting4attach *w4ai = NULL;
1336 	while ((w4ai = LIST_FIRST(&jm->attaches))) {
1337 		waiting4attach_delete(jm, w4ai);
1338 	}
1339 
1340 	if (jm->req_port) {
1341 		(void)jobmgr_assumes_zero(jm, launchd_mport_deallocate(jm->req_port));
1342 	}
1343 	if (jm->jm_port) {
1344 		(void)jobmgr_assumes_zero(jm, launchd_mport_close_recv(jm->jm_port));
1345 	}
1346 
1347 	if (jm->req_bsport) {
1348 		(void)jobmgr_assumes_zero(jm, launchd_mport_deallocate(jm->req_bsport));
1349 	}
1350 	if (jm->req_excport) {
1351 		(void)jobmgr_assumes_zero(jm, launchd_mport_deallocate(jm->req_excport));
1352 	}
1353 	if (MACH_PORT_VALID(jm->req_asport)) {
1354 		(void)jobmgr_assumes_zero(jm, launchd_mport_deallocate(jm->req_asport));
1355 	}
1356 	if (jm->req_rport) {
1357 		kern_return_t kr = xpc_call_wakeup(jm->req_rport, jm->error);
1358 		if (!(kr == KERN_SUCCESS || kr == MACH_SEND_INVALID_DEST)) {
1359 			/* If the originator went away, the reply port will be a dead name,
1360 			 * and we expect this to fail.
1361 			 */
1362 			(void)jobmgr_assumes_zero(jm, kr);
1363 		}
1364 	}
1365 	if (jm->req_ctx) {
1366 		(void)jobmgr_assumes_zero(jm, vm_deallocate(mach_task_self(), jm->req_ctx, jm->req_ctx_sz));
1367 	}
1368 
1369 	time_t ts = runtime_get_wall_time() / USEC_PER_SEC;
1370 	struct tm curtime;
1371 	(void)localtime_r(&ts, &curtime);
1372 
1373 	char date[26];
1374 	(void)asctime_r(&curtime, date);
1375 	date[24] = 0;
1376 
1377 	time_t delta = ts - jm->shutdown_time;
1378 	if (jm == root_jobmgr && pid1_magic) {
1379 		jobmgr_log(jm, LOG_DEBUG | LOG_CONSOLE, "Userspace shutdown finished at: %s", date);
1380 		jobmgr_log(jm, LOG_DEBUG | LOG_CONSOLE, "Userspace shutdown took approximately %ld second%s.", delta, (delta != 1) ? "s" : "");
1381 	} else {
1382 		jobmgr_log(jm, LOG_DEBUG, "Job manager shutdown finished at: %s", date);
1383 		jobmgr_log(jm, LOG_DEBUG, "Job manager shutdown took approximately %ld second%s.", delta, (delta != 1) ? "s" : "");
1384 	}
1385 
1386 	if (jm->parentmgr) {
1387 		runtime_del_weak_ref();
1388 		SLIST_REMOVE(&jm->parentmgr->submgrs, jm, jobmgr_s, sle);
1389 
1390 		// Hack for the guest user so that its stuff doesn't persist.
1391 		//
1392 		// <rdar://problem/14527875>
1393 		if (strcmp(jm->name, VPROCMGR_SESSION_AQUA) == 0 && getuid() == 201) {
1394 			raise(SIGTERM);
1395 		}
1396 	} else if (pid1_magic) {
1397 		eliminate_double_reboot();
1398 		launchd_log_vm_stats();
1399 		jobmgr_log_stray_children(jm, true);
1400 		jobmgr_log(root_jobmgr, LOG_NOTICE | LOG_CONSOLE, "About to call: reboot(%s).", reboot_flags_to_C_names(jm->reboot_flags));
1401 
1402 		syslog(LOG_CRIT, "About to call reboot, flags = %#x (%s)", jm->reboot_flags, reboot_flags_to_C_names(jm->reboot_flags));
1403 		launchd_closelog();
1404 		(void)jobmgr_assumes_zero_p(jm, reboot(jm->reboot_flags));
1405 	} else {
1406 		jobmgr_log(jm, LOG_DEBUG, "About to exit");
1407 		launchd_closelog();
1408 		exit(EXIT_SUCCESS);
1409 	}
1410 
1411 	free(jm);
1412 }
1413 
1414 void
job_remove(job_t j)1415 job_remove(job_t j)
1416 {
1417 	struct waiting_for_removal *w4r;
1418 	struct calendarinterval *ci;
1419 	struct semaphoreitem *si;
1420 	struct socketgroup *sg;
1421 	struct machservice *ms;
1422 	struct limititem *li;
1423 	struct envitem *ei;
1424 
1425 	if (j->alias) {
1426 		/* HACK: Egregious code duplication. But as with machservice_delete(),
1427 		 * job aliases can't (and shouldn't) have any complex behaviors
1428 		 * associated with them.
1429 		 */
1430 		while ((ms = SLIST_FIRST(&j->machservices))) {
1431 			machservice_delete(j, ms, false);
1432 		}
1433 
1434 		LIST_REMOVE(j, sle);
1435 		LIST_REMOVE(j, label_hash_sle);
1436 		free(j);
1437 		return;
1438 	}
1439 
1440 #if TARGET_OS_EMBEDDED
1441 	if (launchd_embedded_handofgod && _launchd_embedded_god) {
1442 		if (!(_launchd_embedded_god->username && j->username)) {
1443 			errno = EPERM;
1444 			return;
1445 		}
1446 
1447 		if (strcmp(j->username, _launchd_embedded_god->username) != 0) {
1448 			errno = EPERM;
1449 			return;
1450 		}
1451 	} else if (launchd_embedded_handofgod) {
1452 		errno = EINVAL;
1453 		return;
1454 	}
1455 #endif
1456 
1457 	/* Do this BEFORE we check and see whether the job is still active. If we're
1458 	 * a sub-job, we're being removed due to the parent job removing us.
1459 	 * Therefore, the parent job will free itself after this call completes. So
1460 	 * if we defer removing ourselves from the parent's list, we'll crash when
1461 	 * we finally get around to it.
1462 	 */
1463 	if (j->dedicated_instance && !j->former_subjob) {
1464 		LIST_REMOVE(j, subjob_sle);
1465 		j->former_subjob = true;
1466 	}
1467 
1468 	if (unlikely(j->p)) {
1469 		if (j->anonymous) {
1470 			job_reap(j);
1471 		} else {
1472 			job_log(j, LOG_DEBUG, "Removal pended until the job exits");
1473 
1474 			if (!j->removal_pending) {
1475 				j->removal_pending = true;
1476 				job_stop(j);
1477 			}
1478 
1479 			return;
1480 		}
1481 	}
1482 
1483 	if (!j->removing) {
1484 		j->removing = true;
1485 		job_dispatch_curious_jobs(j);
1486 	}
1487 
1488 	ipc_close_all_with_job(j);
1489 
1490 	if (j->forced_peers_to_demand_mode) {
1491 		job_set_global_on_demand(j, false);
1492 	}
1493 
1494 	if (job_assumes_zero(j, j->fork_fd)) {
1495 		(void)posix_assumes_zero(runtime_close(j->fork_fd));
1496 	}
1497 
1498 	if (j->stdin_fd) {
1499 		(void)posix_assumes_zero(runtime_close(j->stdin_fd));
1500 	}
1501 
1502 	if (j->j_port) {
1503 		(void)job_assumes_zero(j, launchd_mport_close_recv(j->j_port));
1504 	}
1505 
1506 	while ((sg = SLIST_FIRST(&j->sockets))) {
1507 		socketgroup_delete(j, sg);
1508 	}
1509 	while ((ci = SLIST_FIRST(&j->cal_intervals))) {
1510 		calendarinterval_delete(j, ci);
1511 	}
1512 	while ((ei = SLIST_FIRST(&j->env))) {
1513 		envitem_delete(j, ei, false);
1514 	}
1515 	while ((ei = SLIST_FIRST(&j->global_env))) {
1516 		envitem_delete(j, ei, true);
1517 	}
1518 	while ((li = SLIST_FIRST(&j->limits))) {
1519 		limititem_delete(j, li);
1520 	}
1521 	while ((ms = SLIST_FIRST(&j->machservices))) {
1522 		machservice_delete(j, ms, false);
1523 	}
1524 	while ((si = SLIST_FIRST(&j->semaphores))) {
1525 		semaphoreitem_delete(j, si);
1526 	}
1527 	while ((w4r = SLIST_FIRST(&j->removal_watchers))) {
1528 		waiting4removal_delete(j, w4r);
1529 	}
1530 
1531 	struct externalevent *eei = NULL;
1532 	while ((eei = LIST_FIRST(&j->events))) {
1533 		externalevent_delete(eei);
1534 	}
1535 
1536 	if (j->event_monitor) {
1537 		_launchd_event_monitor = NULL;
1538 	}
1539 	if (j->xpc_bootstrapper) {
1540 		_launchd_xpc_bootstrapper = NULL;
1541 	}
1542 
1543 	if (j->prog) {
1544 		free(j->prog);
1545 	}
1546 	if (j->argv) {
1547 		free(j->argv);
1548 	}
1549 	if (j->rootdir) {
1550 		free(j->rootdir);
1551 	}
1552 	if (j->workingdir) {
1553 		free(j->workingdir);
1554 	}
1555 	if (j->username) {
1556 		free(j->username);
1557 	}
1558 	if (j->groupname) {
1559 		free(j->groupname);
1560 	}
1561 	if (j->stdinpath) {
1562 		free(j->stdinpath);
1563 	}
1564 	if (j->stdoutpath) {
1565 		free(j->stdoutpath);
1566 	}
1567 	if (j->stderrpath) {
1568 		free(j->stderrpath);
1569 	}
1570 	if (j->alt_exc_handler) {
1571 		free(j->alt_exc_handler);
1572 	}
1573 	if (j->cfbundleidentifier) {
1574 		free(j->cfbundleidentifier);
1575 	}
1576 #if HAVE_SANDBOX
1577 	if (j->seatbelt_profile) {
1578 		free(j->seatbelt_profile);
1579 	}
1580 	if (j->container_identifier) {
1581 		free(j->container_identifier);
1582 	}
1583 #endif
1584 #if HAVE_QUARANTINE
1585 	if (j->quarantine_data) {
1586 		free(j->quarantine_data);
1587 	}
1588 #endif
1589 	if (j->j_binpref) {
1590 		free(j->j_binpref);
1591 	}
1592 	if (j->start_interval) {
1593 		runtime_del_weak_ref();
1594 		(void)job_assumes_zero_p(j, kevent_mod((uintptr_t)&j->start_interval, EVFILT_TIMER, EV_DELETE, 0, 0, NULL));
1595 	}
1596 	if (j->exit_timeout) {
1597 		/* If this fails, it just means the timer's already fired, so no need to
1598 		 * wrap it in an assumes() macro.
1599 		 */
1600 		(void)kevent_mod((uintptr_t)&j->exit_timeout, EVFILT_TIMER, EV_DELETE, 0, 0, NULL);
1601 	}
1602 	if (j->asport != MACH_PORT_NULL) {
1603 		(void)job_assumes_zero(j, launchd_mport_deallocate(j->asport));
1604 	}
1605 	if (!uuid_is_null(j->expected_audit_uuid)) {
1606 		LIST_REMOVE(j, needing_session_sle);
1607 	}
1608 	if (j->embedded_god) {
1609 		_launchd_embedded_god = NULL;
1610 	}
1611 	if (j->embedded_home) {
1612 		_launchd_embedded_home = NULL;
1613 	}
1614 	if (j->shutdown_monitor) {
1615 		_launchd_shutdown_monitor = NULL;
1616 	}
1617 
1618 	(void)kevent_mod((uintptr_t)j, EVFILT_TIMER, EV_DELETE, 0, 0, NULL);
1619 
1620 	LIST_REMOVE(j, sle);
1621 	LIST_REMOVE(j, label_hash_sle);
1622 
1623 	job_t ji = NULL;
1624 	job_t jit = NULL;
1625 	LIST_FOREACH_SAFE(ji, &j->subjobs, subjob_sle, jit) {
1626 		job_remove(ji);
1627 	}
1628 
1629 	job_log(j, LOG_DEBUG, "Removed");
1630 
1631 	j->kqjob_callback = (kq_callback)0x8badf00d;
1632 	free(j);
1633 }
1634 
1635 void
socketgroup_setup(launch_data_t obj,const char * key,void * context)1636 socketgroup_setup(launch_data_t obj, const char *key, void *context)
1637 {
1638 	launch_data_t tmp_oai;
1639 	job_t j = context;
1640 	size_t i, fd_cnt = 1;
1641 	int *fds;
1642 
1643 	if (launch_data_get_type(obj) == LAUNCH_DATA_ARRAY) {
1644 		fd_cnt = launch_data_array_get_count(obj);
1645 	}
1646 
1647 	fds = alloca(fd_cnt * sizeof(int));
1648 
1649 	for (i = 0; i < fd_cnt; i++) {
1650 		if (launch_data_get_type(obj) == LAUNCH_DATA_ARRAY) {
1651 			tmp_oai = launch_data_array_get_index(obj, i);
1652 		} else {
1653 			tmp_oai = obj;
1654 		}
1655 
1656 		fds[i] = launch_data_get_fd(tmp_oai);
1657 	}
1658 
1659 	socketgroup_new(j, key, fds, fd_cnt);
1660 
1661 	ipc_revoke_fds(obj);
1662 }
1663 
1664 bool
job_set_global_on_demand(job_t j,bool val)1665 job_set_global_on_demand(job_t j, bool val)
1666 {
1667 	if (j->forced_peers_to_demand_mode && val) {
1668 		return false;
1669 	} else if (!j->forced_peers_to_demand_mode && !val) {
1670 		return false;
1671 	}
1672 
1673 	if ((j->forced_peers_to_demand_mode = val)) {
1674 		j->mgr->global_on_demand_cnt++;
1675 	} else {
1676 		j->mgr->global_on_demand_cnt--;
1677 	}
1678 
1679 	if (j->mgr->global_on_demand_cnt == 0) {
1680 		jobmgr_dispatch_all(j->mgr, false);
1681 	}
1682 
1683 	return true;
1684 }
1685 
1686 bool
job_setup_machport(job_t j)1687 job_setup_machport(job_t j)
1688 {
1689 	if (job_assumes_zero(j, launchd_mport_create_recv(&j->j_port)) != KERN_SUCCESS) {
1690 		goto out_bad;
1691 	}
1692 
1693 	if (job_assumes_zero(j, runtime_add_mport(j->j_port, job_server)) != KERN_SUCCESS) {
1694 		goto out_bad2;
1695 	}
1696 
1697 	if (job_assumes_zero(j, launchd_mport_notify_req(j->j_port, MACH_NOTIFY_NO_SENDERS)) != KERN_SUCCESS) {
1698 		(void)job_assumes_zero(j, launchd_mport_close_recv(j->j_port));
1699 		goto out_bad;
1700 	}
1701 
1702 	return true;
1703 out_bad2:
1704 	(void)job_assumes_zero(j, launchd_mport_close_recv(j->j_port));
1705 out_bad:
1706 	return false;
1707 }
1708 
1709 kern_return_t
job_setup_exit_port(job_t j)1710 job_setup_exit_port(job_t j)
1711 {
1712 	kern_return_t kr = launchd_mport_create_recv(&j->exit_status_port);
1713 	if (job_assumes_zero(j, kr) != KERN_SUCCESS) {
1714 		return MACH_PORT_NULL;
1715 	}
1716 
1717 	struct mach_port_limits limits = {
1718 		.mpl_qlimit = 1,
1719 	};
1720 	kr = mach_port_set_attributes(mach_task_self(), j->exit_status_port, MACH_PORT_LIMITS_INFO, (mach_port_info_t)&limits, sizeof(limits));
1721 	(void)job_assumes_zero(j, kr);
1722 
1723 	kr = launchd_mport_make_send_once(j->exit_status_port, &j->exit_status_dest);
1724 	if (job_assumes_zero(j, kr) != KERN_SUCCESS) {
1725 		(void)job_assumes_zero(j, launchd_mport_close_recv(j->exit_status_port));
1726 		j->exit_status_port = MACH_PORT_NULL;
1727 	}
1728 
1729 	return kr;
1730 }
1731 
1732 job_t
job_new_via_mach_init(job_t j,const char * cmd,uid_t uid,bool ond)1733 job_new_via_mach_init(job_t j, const char *cmd, uid_t uid, bool ond)
1734 {
1735 	const char **argv = (const char **)mach_cmd2argv(cmd);
1736 	job_t jr = NULL;
1737 
1738 	if (!argv) {
1739 		goto out_bad;
1740 	}
1741 
1742 	jr = job_new(j->mgr, AUTO_PICK_LEGACY_LABEL, NULL, argv);
1743 	free(argv);
1744 
1745 	// Job creation can be denied during shutdown.
1746 	if (unlikely(jr == NULL)) {
1747 		goto out_bad;
1748 	}
1749 
1750 	jr->mach_uid = uid;
1751 	jr->ondemand = ond;
1752 	jr->legacy_mach_job = true;
1753 	jr->abandon_pg = true;
1754 	jr->priv_port_has_senders = true; // the IPC that called us will make-send on this port
1755 
1756 	if (!job_setup_machport(jr)) {
1757 		goto out_bad;
1758 	}
1759 
1760 	job_log(jr, LOG_INFO, "Legacy%s server created", ond ? " on-demand" : "");
1761 
1762 	return jr;
1763 
1764 out_bad:
1765 	if (jr) {
1766 		job_remove(jr);
1767 	}
1768 	return NULL;
1769 }
1770 
1771 job_t
job_new_anonymous(jobmgr_t jm,pid_t anonpid)1772 job_new_anonymous(jobmgr_t jm, pid_t anonpid)
1773 {
1774 	struct proc_bsdshortinfo proc;
1775 	bool shutdown_state;
1776 	job_t jp = NULL, jr = NULL;
1777 	uid_t kp_euid, kp_uid, kp_svuid;
1778 	gid_t kp_egid, kp_gid, kp_svgid;
1779 
1780 	if (anonpid == 0) {
1781 		errno = EINVAL;
1782 		return NULL;
1783 	}
1784 
1785 	if (anonpid >= 100000) {
1786 		/* The kernel current defines PID_MAX to be 99999, but that define isn't
1787 		 * exported.
1788 		 */
1789 		launchd_syslog(LOG_WARNING, "Did PID_MAX change? Got request from PID: %d", anonpid);
1790 		errno = EINVAL;
1791 		return NULL;
1792 	}
1793 
1794 	/* libproc returns the number of bytes written into the buffer upon success,
1795 	 * zero on failure. I'd much rather it return -1 on failure, like sysctl(3).
1796 	 */
1797 	if (proc_pidinfo(anonpid, PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0) {
1798 		if (errno != ESRCH) {
1799 			(void)jobmgr_assumes_zero(jm, errno);
1800 		}
1801 		return NULL;
1802 	}
1803 
1804 	if (proc.pbsi_comm[0] == '\0') {
1805 		launchd_syslog(LOG_WARNING, "Blank command for PID: %d", anonpid);
1806 		errno = EINVAL;
1807 		return NULL;
1808 	}
1809 
1810 	if (unlikely(proc.pbsi_status == SZOMB)) {
1811 		jobmgr_log(jm, LOG_DEBUG, "Tried to create an anonymous job for zombie PID %u: %s", anonpid, proc.pbsi_comm);
1812 	}
1813 
1814 	if (unlikely(proc.pbsi_flags & P_SUGID)) {
1815 		jobmgr_log(jm, LOG_DEBUG, "Inconsistency: P_SUGID is set on PID %u: %s", anonpid, proc.pbsi_comm);
1816 	}
1817 
1818 	kp_euid = proc.pbsi_uid;
1819 	kp_uid = proc.pbsi_ruid;
1820 	kp_svuid = proc.pbsi_svuid;
1821 	kp_egid = proc.pbsi_gid;
1822 	kp_gid = proc.pbsi_rgid;
1823 	kp_svgid = proc.pbsi_svgid;
1824 
1825 	if (unlikely(kp_euid != kp_uid || kp_euid != kp_svuid || kp_uid != kp_svuid || kp_egid != kp_gid || kp_egid != kp_svgid || kp_gid != kp_svgid)) {
1826 		jobmgr_log(jm, LOG_DEBUG, "Inconsistency: Mixed credentials (e/r/s UID %u/%u/%u GID %u/%u/%u) detected on PID %u: %s",
1827 				kp_euid, kp_uid, kp_svuid, kp_egid, kp_gid, kp_svgid, anonpid, proc.pbsi_comm);
1828 	}
1829 
1830 	/* "Fix" for when the kernel turns the process tree into a weird, cyclic
1831 	 * graph.
1832 	 *
1833 	 * See <rdar://problem/7264615> for the symptom and <rdar://problem/5020256>
1834 	 * as to why this can happen.
1835 	 */
1836 	if ((pid_t)proc.pbsi_ppid == anonpid) {
1837 		jobmgr_log(jm, LOG_WARNING, "Process has become its own parent through ptrace(3). Ignoring: %s", proc.pbsi_comm);
1838 		errno = EINVAL;
1839 		return NULL;
1840 	}
1841 
1842 	/* HACK: Normally, job_new() returns an error during shutdown, but anonymous
1843 	 * jobs can pop up during shutdown and need to talk to us.
1844 	 */
1845 	if (unlikely(shutdown_state = jm->shutting_down)) {
1846 		jm->shutting_down = false;
1847 	}
1848 
1849 	// We only set requestor_pid for XPC domains.
1850 	const char *whichlabel = (jm->req_pid == anonpid) ? AUTO_PICK_XPC_LABEL : AUTO_PICK_ANONYMOUS_LABEL;
1851 	if ((jr = job_new(jm, whichlabel, proc.pbsi_comm, NULL))) {
1852 		u_int proc_fflags = NOTE_EXEC|NOTE_FORK|NOTE_EXIT;
1853 
1854 		total_anon_children++;
1855 		jr->anonymous = true;
1856 		jr->p = anonpid;
1857 
1858 		// Anonymous process reaping is messy.
1859 		LIST_INSERT_HEAD(&jm->active_jobs[ACTIVE_JOB_HASH(jr->p)], jr, pid_hash_sle);
1860 
1861 		if (unlikely(kevent_mod(jr->p, EVFILT_PROC, EV_ADD, proc_fflags, 0, root_jobmgr) == -1)) {
1862 			if (errno != ESRCH) {
1863 				(void)job_assumes_zero(jr, errno);
1864 			}
1865 
1866 			// Zombies interact weirdly with kevent(3).
1867 			job_log(jr, LOG_ERR, "Failed to add kevent for PID %u. Will unload at MIG return", jr->p);
1868 			jr->unload_at_mig_return = true;
1869 		}
1870 
1871 		if (unlikely(shutdown_state)) {
1872 			job_log(jr, LOG_APPLEONLY, "This process showed up to the party while all the guests were leaving. Odds are that it will have a miserable time.");
1873 		}
1874 
1875 		job_log(jr, LOG_DEBUG, "Created PID %u anonymously by PPID %u%s%s", anonpid, proc.pbsi_ppid, jp ? ": " : "", jp ? jp->label : "");
1876 	} else {
1877 		(void)os_assumes_zero(errno);
1878 	}
1879 
1880 	// Undo our hack from above.
1881 	if (unlikely(shutdown_state)) {
1882 		jm->shutting_down = true;
1883 	}
1884 
1885 	/* This is down here to prevent infinite recursion due to a process
1886 	 * attaching to its parent through ptrace(3) -- causing a cycle in the
1887 	 * process tree and thereby not making it a tree anymore. We need to make
1888 	 * sure that the anonymous job has been added to the process list so that
1889 	 * we'll find the tracing parent PID of the parent process, which is the
1890 	 * child, when we go looking for it in jobmgr_find_by_pid().
1891 	 *
1892 	 * <rdar://problem/7264615>
1893 	 */
1894 	switch (proc.pbsi_ppid) {
1895 	case 0:
1896 		// The kernel.
1897 		break;
1898 	case 1:
1899 		if (!pid1_magic) {
1900 			break;
1901 		}
1902 		// Fall through.
1903 	default:
1904 		jp = jobmgr_find_by_pid(jm, proc.pbsi_ppid, true);
1905 		if (jobmgr_assumes(jm, jp != NULL)) {
1906 			if (jp && !jp->anonymous && unlikely(!(proc.pbsi_flags & P_EXEC))) {
1907 				job_log(jp, LOG_DEBUG, "Called *fork(). Please switch to posix_spawn*(), pthreads or launchd. Child PID %u", proc.pbsi_pid);
1908 			}
1909 		}
1910 		break;
1911 	}
1912 
1913 	return jr;
1914 }
1915 
1916 job_t
job_new_subjob(job_t j,uuid_t identifier)1917 job_new_subjob(job_t j, uuid_t identifier)
1918 {
1919 	char label[0];
1920 	uuid_string_t idstr;
1921 	uuid_unparse(identifier, idstr);
1922 	size_t label_sz = snprintf(label, 0, "%s.%s", j->label, idstr);
1923 
1924 	job_t nj = (struct job_s *)calloc(1, sizeof(struct job_s) + label_sz + 1);
1925 	if (nj != NULL) {
1926 		nj->kqjob_callback = job_callback;
1927 		nj->original = j;
1928 		nj->mgr = j->mgr;
1929 		nj->min_run_time = j->min_run_time;
1930 		nj->timeout = j->timeout;
1931 		nj->exit_timeout = j->exit_timeout;
1932 
1933 		snprintf((char *)nj->label, label_sz + 1, "%s.%s", j->label, idstr);
1934 
1935 		// Set all our simple Booleans that are applicable.
1936 		nj->debug = j->debug;
1937 		nj->ondemand = j->ondemand;
1938 		nj->checkedin = true;
1939 		nj->low_pri_io = j->low_pri_io;
1940 		nj->setmask = j->setmask;
1941 		nj->wait4debugger = j->wait4debugger;
1942 		nj->internal_exc_handler = j->internal_exc_handler;
1943 		nj->setnice = j->setnice;
1944 		nj->abandon_pg = j->abandon_pg;
1945 		nj->ignore_pg_at_shutdown = j->ignore_pg_at_shutdown;
1946 		nj->deny_job_creation = j->deny_job_creation;
1947 		nj->enable_transactions = j->enable_transactions;
1948 		nj->needs_kickoff = j->needs_kickoff;
1949 		nj->currently_ignored = true;
1950 		nj->dedicated_instance = true;
1951 		nj->xpc_service = j->xpc_service;
1952 		nj->xpc_bootstrapper = j->xpc_bootstrapper;
1953 		nj->jetsam_priority = j->jetsam_priority;
1954 		nj->jetsam_memlimit = j->jetsam_memlimit;
1955 		nj->psproctype = j->psproctype;
1956 
1957 		nj->mask = j->mask;
1958 		uuid_copy(nj->instance_id, identifier);
1959 
1960 		// These jobs are purely on-demand Mach jobs.
1961 		// {Hard | Soft}ResourceLimits are not supported.
1962 		// JetsamPriority is not supported.
1963 
1964 		if (j->prog) {
1965 			nj->prog = strdup(j->prog);
1966 		}
1967 		if (j->argv) {
1968 			size_t sz = malloc_size(j->argv);
1969 			nj->argv = (char **)malloc(sz);
1970 			if (nj->argv != NULL) {
1971 				// This is the start of our strings.
1972 				char *p = ((char *)nj->argv) + ((j->argc + 1) * sizeof(char *));
1973 
1974 				size_t i = 0;
1975 				for (i = 0; i < j->argc; i++) {
1976 					(void)strcpy(p, j->argv[i]);
1977 					nj->argv[i] = p;
1978 					p += (strlen(j->argv[i]) + 1);
1979 				}
1980 				nj->argv[i] = NULL;
1981 			} else {
1982 				(void)job_assumes_zero(nj, errno);
1983 			}
1984 
1985 			nj->argc = j->argc;
1986 		}
1987 
1988 		struct machservice *msi = NULL;
1989 		SLIST_FOREACH(msi, &j->machservices, sle) {
1990 			/* Only copy MachServices that were actually declared in the plist.
1991 			 * So skip over per-PID ones and ones that were created via
1992 			 * bootstrap_register().
1993 			 */
1994 			if (msi->upfront) {
1995 				mach_port_t mp = MACH_PORT_NULL;
1996 				struct machservice *msj = machservice_new(nj, msi->name, &mp, false);
1997 				if (msj != NULL) {
1998 					msj->reset = msi->reset;
1999 					msj->delete_on_destruction = msi->delete_on_destruction;
2000 					msj->drain_one_on_crash = msi->drain_one_on_crash;
2001 					msj->drain_all_on_crash = msi->drain_all_on_crash;
2002 
2003 					kern_return_t kr = mach_port_set_attributes(mach_task_self(), msj->port, MACH_PORT_TEMPOWNER, NULL, 0);
2004 					(void)job_assumes_zero(j, kr);
2005 				} else {
2006 					(void)job_assumes_zero(nj, errno);
2007 				}
2008 			}
2009 		}
2010 
2011 		// We ignore global environment variables.
2012 		struct envitem *ei = NULL;
2013 		SLIST_FOREACH(ei, &j->env, sle) {
2014 			if (envitem_new(nj, ei->key, ei->value, false)) {
2015 				(void)job_assumes_zero(nj, errno);
2016 			}
2017 		}
2018 		uuid_string_t val;
2019 		uuid_unparse(identifier, val);
2020 		if (envitem_new(nj, LAUNCH_ENV_INSTANCEID, val, false)) {
2021 			(void)job_assumes_zero(nj, errno);
2022 		}
2023 
2024 		if (j->rootdir) {
2025 			nj->rootdir = strdup(j->rootdir);
2026 		}
2027 		if (j->workingdir) {
2028 			nj->workingdir = strdup(j->workingdir);
2029 		}
2030 		if (j->username) {
2031 			nj->username = strdup(j->username);
2032 		}
2033 		if (j->groupname) {
2034 			nj->groupname = strdup(j->groupname);
2035 		}
2036 
2037 		/* FIXME: We shouldn't redirect all the output from these jobs to the
2038 		 * same file. We should uniquify the file names. But this hasn't shown
2039 		 * to be a problem in practice.
2040 		 */
2041 		if (j->stdinpath) {
2042 			nj->stdinpath = strdup(j->stdinpath);
2043 		}
2044 		if (j->stdoutpath) {
2045 			nj->stdoutpath = strdup(j->stdinpath);
2046 		}
2047 		if (j->stderrpath) {
2048 			nj->stderrpath = strdup(j->stderrpath);
2049 		}
2050 		if (j->alt_exc_handler) {
2051 			nj->alt_exc_handler = strdup(j->alt_exc_handler);
2052 		}
2053 		if (j->cfbundleidentifier) {
2054 			nj->cfbundleidentifier = strdup(j->cfbundleidentifier);
2055 		}
2056 #if HAVE_SANDBOX
2057 		if (j->seatbelt_profile) {
2058 			nj->seatbelt_profile = strdup(j->seatbelt_profile);
2059 		}
2060 		if (j->container_identifier) {
2061 			nj->container_identifier = strdup(j->container_identifier);
2062 		}
2063 #endif
2064 
2065 #if HAVE_QUARANTINE
2066 		if (j->quarantine_data) {
2067 			nj->quarantine_data = strdup(j->quarantine_data);
2068 		}
2069 		nj->quarantine_data_sz = j->quarantine_data_sz;
2070 #endif
2071 		if (j->j_binpref) {
2072 			size_t sz = malloc_size(j->j_binpref);
2073 			nj->j_binpref = (cpu_type_t *)malloc(sz);
2074 			if (nj->j_binpref) {
2075 				memcpy(&nj->j_binpref, &j->j_binpref, sz);
2076 			} else {
2077 				(void)job_assumes_zero(nj, errno);
2078 			}
2079 		}
2080 
2081 		if (j->asport != MACH_PORT_NULL) {
2082 			(void)job_assumes_zero(nj, launchd_mport_copy_send(j->asport));
2083 			nj->asport = j->asport;
2084 		}
2085 
2086 		LIST_INSERT_HEAD(&nj->mgr->jobs, nj, sle);
2087 
2088 		jobmgr_t where2put = root_jobmgr;
2089 		if (j->mgr->properties & BOOTSTRAP_PROPERTY_XPC_DOMAIN) {
2090 			where2put = j->mgr;
2091 		}
2092 		LIST_INSERT_HEAD(&where2put->label_hash[hash_label(nj->label)], nj, label_hash_sle);
2093 		LIST_INSERT_HEAD(&j->subjobs, nj, subjob_sle);
2094 	} else {
2095 		(void)os_assumes_zero(errno);
2096 	}
2097 
2098 	return nj;
2099 }
2100 
2101 job_t
job_new(jobmgr_t jm,const char * label,const char * prog,const char * const * argv)2102 job_new(jobmgr_t jm, const char *label, const char *prog, const char *const *argv)
2103 {
2104 	const char *const *argv_tmp = argv;
2105 	char tmp_path[PATH_MAX];
2106 	char auto_label[1000];
2107 	const char *bn = NULL;
2108 	char *co;
2109 	size_t minlabel_len;
2110 	size_t i, cc = 0;
2111 	job_t j;
2112 
2113 	__OS_COMPILETIME_ASSERT__(offsetof(struct job_s, kqjob_callback) == 0);
2114 
2115 	if (unlikely(jm->shutting_down)) {
2116 		errno = EINVAL;
2117 		return NULL;
2118 	}
2119 
2120 	if (unlikely(prog == NULL && argv == NULL)) {
2121 		errno = EINVAL;
2122 		return NULL;
2123 	}
2124 
2125 	/* I'd really like to redo this someday. Anonymous jobs carry all the
2126 	 * baggage of managed jobs with them, even though most of it is unused.
2127 	 * Maybe when we have Objective-C objects in libSystem, there can be a base
2128 	 * job type that anonymous and managed jobs inherit from...
2129 	 */
2130 	const char *anon_or_legacy = (label == AUTO_PICK_ANONYMOUS_LABEL) ? "anonymous" : "mach_init";
2131 	if (unlikely(label == AUTO_PICK_LEGACY_LABEL || label == AUTO_PICK_ANONYMOUS_LABEL)) {
2132 		if (prog) {
2133 			bn = prog;
2134 		} else {
2135 			strlcpy(tmp_path, argv[0], sizeof(tmp_path));
2136 			// prog for auto labels is kp.kp_kproc.p_comm.
2137 			bn = basename(tmp_path);
2138 		}
2139 
2140 		(void)snprintf(auto_label, sizeof(auto_label), "%s.%s.%s", sizeof(void *) == 8 ? "0xdeadbeeffeedface" : "0xbabecafe", anon_or_legacy, bn);
2141 		label = auto_label;
2142 		/* This is so we can do gross things later. See NOTE_EXEC for anonymous
2143 		 * jobs.
2144 		 */
2145 		minlabel_len = strlen(label) + MAXCOMLEN;
2146 	} else {
2147 		if (label == AUTO_PICK_XPC_LABEL) {
2148 			minlabel_len = snprintf(auto_label, sizeof(auto_label), "com.apple.xpc.domain-owner.%s", jm->owner);
2149 		} else {
2150 			minlabel_len = strlen(label);
2151 		}
2152 	}
2153 
2154 	j = calloc(1, sizeof(struct job_s) + minlabel_len + 1);
2155 
2156 	if (!j) {
2157 		(void)os_assumes_zero(errno);
2158 		return NULL;
2159 	}
2160 
2161 	if (unlikely(label == auto_label)) {
2162 		(void)snprintf((char *)j->label, strlen(label) + 1, "%p.%s.%s", j, anon_or_legacy, bn);
2163 	} else {
2164 		(void)strcpy((char *)j->label, (label == AUTO_PICK_XPC_LABEL) ? auto_label : label);
2165 	}
2166 
2167 	j->kqjob_callback = job_callback;
2168 	j->mgr = jm;
2169 	j->min_run_time = LAUNCHD_MIN_JOB_RUN_TIME;
2170 	j->timeout = RUNTIME_ADVISABLE_IDLE_TIMEOUT;
2171 	if (uflag == true)
2172 		j->exit_timeout = 60;
2173 	else
2174 		j->exit_timeout = LAUNCHD_DEFAULT_EXIT_TIMEOUT;
2175 	j->currently_ignored = true;
2176 	j->ondemand = true;
2177 	j->checkedin = true;
2178 	j->jetsam_priority = DEFAULT_JETSAM_PRIORITY;
2179 	j->jetsam_memlimit = -1;
2180 	uuid_clear(j->expected_audit_uuid);
2181 #if TARGET_OS_EMBEDDED
2182 	/* Run embedded daemons as background by default. SpringBoard jobs are
2183 	 * Interactive by default. Unfortunately, so many daemons have opted into
2184 	 * this priority band that its usefulness is highly questionable.
2185 	 *
2186 	 * See <rdar://problem/9539873>.
2187 	 *
2188 	 * Also ensure that daemons have a default memory highwatermark unless
2189 	 * otherwise specified, as per <rdar://problem/10307814>.
2190 	 */
2191 	if (launchd_embedded_handofgod) {
2192 		j->psproctype = POSIX_SPAWN_PROC_TYPE_APP_DEFAULT;
2193 		j->app = true;
2194 	} else {
2195 		j->psproctype = POSIX_SPAWN_PROC_TYPE_DAEMON_BACKGROUND;
2196 		j->jetsam_memlimit = DEFAULT_JETSAM_DAEMON_HIGHWATERMARK;
2197 	}
2198 #else
2199 	/* Jobs on OS X that just come from disk are "standard" by default so that
2200 	 * third-party daemons/agents don't encounter unexpected throttling.
2201 	 */
2202 	j->psproctype = POSIX_SPAWN_PROC_TYPE_DAEMON_STANDARD;
2203 #endif
2204 
2205 	if (prog) {
2206 		j->prog = strdup(prog);
2207 		if (!j->prog) {
2208 			(void)os_assumes_zero(errno);
2209 			goto out_bad;
2210 		}
2211 	}
2212 
2213 	if (likely(argv)) {
2214 		while (*argv_tmp++) {
2215 			j->argc++;
2216 		}
2217 
2218 		for (i = 0; i < j->argc; i++) {
2219 			cc += strlen(argv[i]) + 1;
2220 		}
2221 
2222 		j->argv = malloc((j->argc + 1) * sizeof(char *) + cc);
2223 		if (!j->argv) {
2224 			(void)job_assumes_zero(j, errno);
2225 			goto out_bad;
2226 		}
2227 
2228 		co = ((char *)j->argv) + ((j->argc + 1) * sizeof(char *));
2229 
2230 		for (i = 0; i < j->argc; i++) {
2231 			j->argv[i] = co;
2232 			(void)strcpy(co, argv[i]);
2233 			co += strlen(argv[i]) + 1;
2234 		}
2235 		j->argv[i] = NULL;
2236 	}
2237 
2238 	// Sssshhh... don't tell anyone.
2239 	if (strcmp(j->label, "com.apple.WindowServer") == 0) {
2240 		j->has_console = true;
2241 	}
2242 
2243 	LIST_INSERT_HEAD(&jm->jobs, j, sle);
2244 
2245 	jobmgr_t where2put_label = root_jobmgr;
2246 	if (j->mgr->properties & BOOTSTRAP_PROPERTY_XPC_DOMAIN) {
2247 		where2put_label = j->mgr;
2248 	}
2249 	LIST_INSERT_HEAD(&where2put_label->label_hash[hash_label(j->label)], j, label_hash_sle);
2250 	uuid_clear(j->expected_audit_uuid);
2251 
2252 	job_log(j, LOG_DEBUG, "Conceived");
2253 
2254 	return j;
2255 
2256 out_bad:
2257 	if (j->prog) {
2258 		free(j->prog);
2259 	}
2260 	free(j);
2261 
2262 	return NULL;
2263 }
2264 
2265 job_t
job_new_alias(jobmgr_t jm,job_t src)2266 job_new_alias(jobmgr_t jm, job_t src)
2267 {
2268 	if (job_find(jm, src->label)) {
2269 		errno = EEXIST;
2270 		return NULL;
2271 	}
2272 
2273 	job_t j = calloc(1, sizeof(struct job_s) + strlen(src->label) + 1);
2274 	if (!j) {
2275 		(void)os_assumes_zero(errno);
2276 		return NULL;
2277 	}
2278 
2279 	(void)strcpy((char *)j->label, src->label);
2280 	LIST_INSERT_HEAD(&jm->jobs, j, sle);
2281 	LIST_INSERT_HEAD(&jm->label_hash[hash_label(j->label)], j, label_hash_sle);
2282 	/* Bad jump address. The kqueue callback for aliases should never be
2283 	 * invoked.
2284 	 */
2285 	j->kqjob_callback = (kq_callback)0xfa1afe1;
2286 	j->alias = src;
2287 	j->mgr = jm;
2288 
2289 	struct machservice *msi = NULL;
2290 	SLIST_FOREACH(msi, &src->machservices, sle) {
2291 		if (!machservice_new_alias(j, msi)) {
2292 			jobmgr_log(jm, LOG_ERR, "Failed to alias job: %s", src->label);
2293 			errno = EINVAL;
2294 			job_remove(j);
2295 			j = NULL;
2296 			break;
2297 		}
2298 	}
2299 
2300 	if (j) {
2301 		job_log(j, LOG_DEBUG, "Aliased service into domain: %s", jm->name);
2302 	}
2303 
2304 	return j;
2305 }
2306 
2307 job_t
job_import(launch_data_t pload)2308 job_import(launch_data_t pload)
2309 {
2310 #if TARGET_OS_EMBEDDED
2311 	/* If this is the special payload of default values, handle it here */
2312 	if (unlikely(launch_data_dict_lookup(pload, LAUNCH_JOBKEY_DEFAULTS))) {
2313 		job_import_defaults(pload);
2314 		return NULL;
2315 	}
2316 #endif
2317 
2318 	job_t j = jobmgr_import2(root_jobmgr, pload);
2319 
2320 	if (unlikely(j == NULL)) {
2321 		return NULL;
2322 	}
2323 
2324 	/* Since jobs are effectively stalled until they get security sessions
2325 	 * assigned to them, we may wish to reconsider this behavior of calling the
2326 	 * job "enabled" as far as other jobs with the OtherJobEnabled KeepAlive
2327 	 * criterion set.
2328 	 */
2329 	job_dispatch_curious_jobs(j);
2330 	return job_dispatch(j, false);
2331 }
2332 
2333 #if TARGET_OS_EMBEDDED
2334 
2335 bool
job_import_defaults(launch_data_t pload)2336 job_import_defaults(launch_data_t pload)
2337 {
2338 	bool result = false;
2339 	xpc_object_t xd = NULL, defaults;
2340 
2341 	if (_launchd_defaults_cache) {
2342 		xpc_release(_launchd_defaults_cache);
2343 		_launchd_defaults_cache = NULL;
2344 	}
2345 
2346 	xd = ld2xpc(pload);
2347 	if (!xd || xpc_get_type(xd) != XPC_TYPE_DICTIONARY) {
2348 		goto out;
2349 	}
2350 
2351 	defaults = xpc_dictionary_get_value(xd, LAUNCHD_JOB_DEFAULTS);
2352 	if (!defaults || xpc_get_type(defaults) != XPC_TYPE_DICTIONARY) {
2353 		goto out;
2354 	}
2355 
2356 	_launchd_defaults_cache = xpc_copy(defaults);
2357 	result = true;
2358 out:
2359 	if (xd) {
2360 		xpc_release(xd);
2361 	}
2362 
2363 	return result;
2364 }
2365 
2366 bool
job_apply_defaults(job_t j)2367 job_apply_defaults(job_t j) {
2368 	const char *test_prefix = "com.apple.test.";
2369 
2370 	char *sb_prefix_end, *sb_suffix_start;
2371 	char true_job_label[strlen(j->label)];
2372 	const char *label;
2373 
2374 	if (((sb_prefix_end = strchr(j->label, ':')) != NULL) &&
2375 	    ((sb_suffix_start = strchr(sb_prefix_end + 1, '[')) != NULL)) {
2376  		/*
2377  		 * Workaround 'UIKitApplication:com.apple.foo[bar]' convention for the processes
2378  		 * we're interested in. To be removed when <rdar://problem/13066361> is addressed.
2379  		 */
2380 		snprintf(true_job_label, sb_suffix_start - sb_prefix_end, "%s", sb_prefix_end + 1);
2381  		label = true_job_label;
2382 	} else {
2383 		/* Just test the standard label */
2384 		label = j->label;
2385 	}
2386 
2387 	/* Test for cache presence and apply if found */
2388 	if (_launchd_defaults_cache) {
2389 		xpc_object_t props = xpc_dictionary_get_value(_launchd_defaults_cache, label);
2390 		if (props && xpc_get_type(props) == XPC_TYPE_DICTIONARY) {
2391 			launch_data_t lv = xpc2ld(props);
2392 			launch_data_dict_iterate(lv, job_import_keys, j);
2393 			launch_data_free(lv);
2394 			return true;
2395 		}
2396 	}
2397 
2398 	/* Limit free? Disable the memory limit if this is a test job; see <rdar://problem/13180697> */
2399 	if (!strncmp(label, test_prefix, strlen(test_prefix))) {
2400 		j->jetsam_memlimit = -1;
2401 		return true;
2402 	}
2403 
2404 	return false;
2405 }
2406 
2407 #endif
2408 
2409 launch_data_t
job_import_bulk(launch_data_t pload)2410 job_import_bulk(launch_data_t pload)
2411 {
2412 	launch_data_t resp = launch_data_alloc(LAUNCH_DATA_ARRAY);
2413 	job_t *ja;
2414 	size_t i, c = launch_data_array_get_count(pload);
2415 
2416 	ja = alloca(c * sizeof(job_t));
2417 
2418 	for (i = 0; i < c; i++) {
2419 		if ((likely(ja[i] = jobmgr_import2(root_jobmgr, launch_data_array_get_index(pload, i)))) && errno != ENEEDAUTH) {
2420 			errno = 0;
2421 		}
2422 		launch_data_array_set_index(resp, launch_data_new_errno(errno), i);
2423 	}
2424 
2425 	for (i = 0; i < c; i++) {
2426 		if (likely(ja[i])) {
2427 			job_dispatch_curious_jobs(ja[i]);
2428 			job_dispatch(ja[i], false);
2429 		}
2430 	}
2431 
2432 	return resp;
2433 }
2434 
2435 void
job_import_bool(job_t j,const char * key,bool value)2436 job_import_bool(job_t j, const char *key, bool value)
2437 {
2438 	bool found_key = false;
2439 
2440 	switch (key[0]) {
2441 	case 'a':
2442 	case 'A':
2443 		if (strcasecmp(key, LAUNCH_JOBKEY_ABANDONPROCESSGROUP) == 0) {
2444 			j->abandon_pg = value;
2445 			found_key = true;
2446 		}
2447 		break;
2448 	case 'b':
2449 	case 'B':
2450 		if (strcasecmp(key, LAUNCH_JOBKEY_BEGINTRANSACTIONATSHUTDOWN) == 0) {
2451 			j->dirty_at_shutdown = value;
2452 			found_key = true;
2453 		}
2454 		break;
2455 	case 'j':
2456 	case 'J':
2457 		if (strcasecmp(key, LAUNCH_JOBKEY_JOINGUISESSION) == 0) {
2458 			j->joins_gui_session = value;
2459 			found_key = true;
2460 		}
2461 		break;
2462 	case 'k':
2463 	case 'K':
2464 		if (strcasecmp(key, LAUNCH_JOBKEY_KEEPALIVE) == 0) {
2465 			j->ondemand = !value;
2466 			found_key = true;
2467 		}
2468 		break;
2469 	case 'o':
2470 	case 'O':
2471 		if (strcasecmp(key, LAUNCH_JOBKEY_ONDEMAND) == 0) {
2472 			j->ondemand = value;
2473 			found_key = true;
2474 		}
2475 		break;
2476 	case 'd':
2477 	case 'D':
2478 		if (strcasecmp(key, LAUNCH_JOBKEY_DEBUG) == 0) {
2479 			j->debug = value;
2480 			found_key = true;
2481 		} else if (strcasecmp(key, LAUNCH_JOBKEY_DISABLED) == 0) {
2482 			(void)job_assumes(j, !value);
2483 			found_key = true;
2484 		} else if (strcasecmp(key, LAUNCH_JOBKEY_DISABLEASLR) == 0) {
2485 			j->disable_aslr = value;
2486 			found_key = true;
2487 		}
2488 		break;
2489 	case 'h':
2490 	case 'H':
2491 		if (strcasecmp(key, LAUNCH_JOBKEY_HOPEFULLYEXITSLAST) == 0) {
2492 			job_log(j, LOG_PERF, "%s has been deprecated. Please use the new %s key instead and add EnableTransactions to your launchd.plist.", LAUNCH_JOBKEY_HOPEFULLYEXITSLAST, LAUNCH_JOBKEY_BEGINTRANSACTIONATSHUTDOWN);
2493 			j->dirty_at_shutdown = value;
2494 			found_key = true;
2495 		}
2496 		break;
2497 	case 's':
2498 	case 'S':
2499 		if (strcasecmp(key, LAUNCH_JOBKEY_SESSIONCREATE) == 0) {
2500 			j->session_create = value;
2501 			found_key = true;
2502 		} else if (strcasecmp(key, LAUNCH_JOBKEY_STARTONMOUNT) == 0) {
2503 			j->start_on_mount = value;
2504 			found_key = true;
2505 		} else if (strcasecmp(key, LAUNCH_JOBKEY_SERVICEIPC) == 0) {
2506 			// this only does something on Mac OS X 10.4 "Tiger"
2507 			found_key = true;
2508 		} else if (strcasecmp(key, LAUNCH_JOBKEY_SHUTDOWNMONITOR) == 0) {
2509 			if (_launchd_shutdown_monitor) {
2510 				job_log(j, LOG_ERR, "Only one job may monitor shutdown.");
2511 			} else {
2512 				j->shutdown_monitor = true;
2513 				_launchd_shutdown_monitor = j;
2514 			}
2515 			found_key = true;
2516 		}
2517 		break;
2518 	case 'l':
2519 	case 'L':
2520 		if (strcasecmp(key, LAUNCH_JOBKEY_LOWPRIORITYIO) == 0) {
2521 			j->low_pri_io = value;
2522 			found_key = true;
2523 		} else if (strcasecmp(key, LAUNCH_JOBKEY_LAUNCHONLYONCE) == 0) {
2524 			j->only_once = value;
2525 			found_key = true;
2526 		} else if (strcasecmp(key, LAUNCH_JOBKEY_LOWPRIORITYBACKGROUNDIO) == 0) {
2527 			j->low_priority_background_io = true;
2528 			found_key = true;
2529 		} else if (strcasecmp(key, LAUNCH_JOBKEY_LEGACYTIMERS) == 0) {
2530 #if !TARGET_OS_EMBEDDED
2531 			j->legacy_timers = value;
2532 #else // !TARGET_OS_EMBEDDED
2533 			job_log(j, LOG_ERR, "This key is not supported on this platform: %s", key);
2534 #endif // !TARGET_OS_EMBEDDED
2535 			found_key = true;
2536 		}
2537 		break;
2538 	case 'm':
2539 	case 'M':
2540 		if (strcasecmp(key, LAUNCH_JOBKEY_MACHEXCEPTIONHANDLER) == 0) {
2541 			j->internal_exc_handler = value;
2542 			found_key = true;
2543 		} else if (strcasecmp(key, LAUNCH_JOBKEY_MULTIPLEINSTANCES) == 0) {
2544 			j->multiple_instances = value;
2545 			found_key = true;
2546 		}
2547 		break;
2548 	case 'i':
2549 	case 'I':
2550 		if (strcasecmp(key, LAUNCH_JOBKEY_INITGROUPS) == 0) {
2551 			if (getuid() != 0) {
2552 				job_log(j, LOG_WARNING, "Ignored this key: %s", key);
2553 				return;
2554 			}
2555 			j->no_init_groups = !value;
2556 			found_key = true;
2557 		} else if (strcasecmp(key, LAUNCH_JOBKEY_IGNOREPROCESSGROUPATSHUTDOWN) == 0) {
2558 			j->ignore_pg_at_shutdown = value;
2559 			found_key = true;
2560 		}
2561 		break;
2562 	case 'r':
2563 	case 'R':
2564 		if (strcasecmp(key, LAUNCH_JOBKEY_RUNATLOAD) == 0) {
2565 			if (value) {
2566 				// We don't want value == false to change j->start_pending
2567 				j->start_pending = true;
2568 			}
2569 			found_key = true;
2570 		}
2571 		break;
2572 	case 'e':
2573 	case 'E':
2574 		if (strcasecmp(key, LAUNCH_JOBKEY_ENABLEGLOBBING) == 0) {
2575 			j->globargv = value;
2576 			found_key = true;
2577 		} else if (strcasecmp(key, LAUNCH_JOBKEY_ENABLETRANSACTIONS) == 0) {
2578 			j->enable_transactions = value;
2579 			found_key = true;
2580 		} else if (strcasecmp(key, LAUNCH_JOBKEY_ENTERKERNELDEBUGGERBEFOREKILL) == 0) {
2581 			j->debug_before_kill = value;
2582 			found_key = true;
2583 		} else if (strcasecmp(key, LAUNCH_JOBKEY_EMBEDDEDPRIVILEGEDISPENSATION) == 0) {
2584 #if TARGET_OS_EMBEDDED
2585 			if (!_launchd_embedded_god) {
2586 				if ((j->embedded_god = value)) {
2587 					_launchd_embedded_god = j;
2588 				}
2589 			} else {
2590 				job_log(j, LOG_ERR, "Job tried to claim %s after it has already been claimed.", key);
2591 			}
2592 #else
2593 			job_log(j, LOG_ERR, "This key is not supported on this platform: %s", key);
2594 #endif
2595 			found_key = true;
2596 		} else if (strcasecmp(key, LAUNCH_JOBKEY_EMBEDDEDHOMESCREEN) == 0) {
2597 #if TARGET_OS_EMBEDDED
2598 			if (!_launchd_embedded_home) {
2599 				if ((j->embedded_home = value)) {
2600 					_launchd_embedded_home = j;
2601 				}
2602 			} else {
2603 				job_log(j, LOG_ERR, "Job tried to claim %s after it has already been claimed.", key);
2604 			}
2605 #else
2606 			job_log(j, LOG_ERR, "This key is not supported on this platform: %s", key);
2607 #endif
2608 		} else if (strcasecmp(key, LAUNCH_JOBKEY_EVENTMONITOR) == 0) {
2609 			if (!_launchd_event_monitor) {
2610 				j->event_monitor = value;
2611 				if (value) {
2612 					_launchd_event_monitor = j;
2613 				}
2614 			} else {
2615 				job_log(j, LOG_NOTICE, "Job tried to steal event monitoring responsibility from: %s", _launchd_event_monitor->label);
2616 			}
2617 			found_key = true;
2618 		}
2619 		break;
2620 	case 'w':
2621 	case 'W':
2622 		if (strcasecmp(key, LAUNCH_JOBKEY_WAITFORDEBUGGER) == 0) {
2623 			j->wait4debugger = value;
2624 			found_key = true;
2625 		}
2626 		break;
2627 	case 'x':
2628 	case 'X':
2629 		if (strcasecmp(key, LAUNCH_JOBKEY_XPCDOMAINBOOTSTRAPPER) == 0) {
2630 			if (pid1_magic) {
2631 				if (_launchd_xpc_bootstrapper) {
2632 					job_log(j, LOG_ERR, "This job tried to steal the XPC domain bootstrapper property from the following job: %s", _launchd_xpc_bootstrapper->label);
2633 				} else {
2634 					_launchd_xpc_bootstrapper = j;
2635 					j->xpc_bootstrapper = value;
2636 				}
2637 			} else {
2638 				job_log(j, LOG_ERR, "Non-daemon tried to claim XPC bootstrapper property.");
2639 			}
2640 		}
2641 		found_key = true;
2642 		break;
2643 	default:
2644 		break;
2645 	}
2646 
2647 	if (unlikely(!found_key)) {
2648 		job_log(j, LOG_WARNING, "Unknown key for boolean: %s", key);
2649 	}
2650 }
2651 
2652 void
job_import_string(job_t j,const char * key,const char * value)2653 job_import_string(job_t j, const char *key, const char *value)
2654 {
2655 	char **where2put = NULL;
2656 
2657 	switch (key[0]) {
2658 	case 'c':
2659 	case 'C':
2660 		if (strcasecmp(key, LAUNCH_JOBKEY_CFBUNDLEIDENTIFIER) == 0) {
2661 			where2put = &j->cfbundleidentifier;
2662 		}
2663 		break;
2664 	case 'm':
2665 	case 'M':
2666 		if (strcasecmp(key, LAUNCH_JOBKEY_MACHEXCEPTIONHANDLER) == 0) {
2667 			where2put = &j->alt_exc_handler;
2668 		}
2669 		break;
2670 	case 'p':
2671 	case 'P':
2672 		if (strcasecmp(key, LAUNCH_JOBKEY_PROGRAM) == 0) {
2673 			return;
2674 		} else if (strcasecmp(key, LAUNCH_JOBKEY_POSIXSPAWNTYPE) == 0
2675 				|| strcasecmp(key, LAUNCH_JOBKEY_PROCESSTYPE) == 0) {
2676 			if (strcasecmp(value, LAUNCH_KEY_POSIXSPAWNTYPE_INTERACTIVE) == 0) {
2677 				j->psproctype = POSIX_SPAWN_PROC_TYPE_DAEMON_INTERACTIVE;
2678 			} else if (strcasecmp(value, LAUNCH_KEY_POSIXSPAWNTYPE_ADAPTIVE) == 0) {
2679 				j->psproctype = POSIX_SPAWN_PROC_TYPE_DAEMON_ADAPTIVE;
2680 			} else if (strcasecmp(value, LAUNCH_KEY_POSIXSPAWNTYPE_STANDARD) == 0) {
2681 				j->psproctype = POSIX_SPAWN_PROC_TYPE_DAEMON_STANDARD;
2682 			} else if (strcasecmp(value, LAUNCH_KEY_POSIXSPAWNTYPE_BACKGROUND) == 0) {
2683 				j->psproctype = POSIX_SPAWN_PROC_TYPE_DAEMON_BACKGROUND;
2684 			} else if (strcasecmp(value, LAUNCH_KEY_POSIXSPAWNTYPE_TALAPP) == 0) {
2685 				j->psproctype = POSIX_SPAWN_PROC_TYPE_APP_TAL;
2686 			} else if (strcasecmp(value, LAUNCH_KEY_POSIXSPAWNTYPE_SYSTEMAPP) == 0) {
2687 				j->psproctype = POSIX_SPAWN_PROC_TYPE_APP_DEFAULT;
2688 				j->system_app = true;
2689 			} else if (strcasecmp(value, LAUNCH_KEY_POSIXSPAWNTYPE_APP) == 0) {
2690 				j->psproctype = POSIX_SPAWN_PROC_TYPE_APP_DEFAULT;
2691 				j->app = true;
2692 			} else {
2693 				job_log(j, LOG_ERR, "Unknown value for key %s: %s", key, value);
2694 			}
2695 			return;
2696 		}
2697 		break;
2698 	case 'l':
2699 	case 'L':
2700 		if (strcasecmp(key, LAUNCH_JOBKEY_LABEL) == 0) {
2701 			return;
2702 		} else if (strcasecmp(key, LAUNCH_JOBKEY_LIMITLOADTOHOSTS) == 0) {
2703 			return;
2704 		} else if (strcasecmp(key, LAUNCH_JOBKEY_LIMITLOADFROMHOSTS) == 0) {
2705 			return;
2706 		} else if (strcasecmp(key, LAUNCH_JOBKEY_LIMITLOADTOSESSIONTYPE) == 0) {
2707 			return;
2708 		}
2709 		break;
2710 	case 'r':
2711 	case 'R':
2712 		if (strcasecmp(key, LAUNCH_JOBKEY_ROOTDIRECTORY) == 0) {
2713 			if (getuid() != 0) {
2714 				job_log(j, LOG_WARNING, "Ignored this key: %s", key);
2715 				return;
2716 			}
2717 			where2put = &j->rootdir;
2718 		}
2719 		break;
2720 	case 'w':
2721 	case 'W':
2722 		if (strcasecmp(key, LAUNCH_JOBKEY_WORKINGDIRECTORY) == 0) {
2723 			where2put = &j->workingdir;
2724 		}
2725 		break;
2726 	case 'u':
2727 	case 'U':
2728 		if (strcasecmp(key, LAUNCH_JOBKEY_USERNAME) == 0) {
2729 			if (getuid() != 0) {
2730 				job_log(j, LOG_WARNING, "Ignored this key: %s", key);
2731 				return;
2732 			} else if (strcmp(value, "root") == 0) {
2733 				return;
2734 			}
2735 			where2put = &j->username;
2736 		}
2737 		break;
2738 	case 'g':
2739 	case 'G':
2740 		if (strcasecmp(key, LAUNCH_JOBKEY_GROUPNAME) == 0) {
2741 			if (getuid() != 0) {
2742 				job_log(j, LOG_WARNING, "Ignored this key: %s", key);
2743 				return;
2744 			} else if (strcmp(value, "wheel") == 0) {
2745 				return;
2746 			}
2747 			where2put = &j->groupname;
2748 		}
2749 		break;
2750 	case 's':
2751 	case 'S':
2752 		if (strcasecmp(key, LAUNCH_JOBKEY_STANDARDOUTPATH) == 0) {
2753 			where2put = &j->stdoutpath;
2754 		} else if (strcasecmp(key, LAUNCH_JOBKEY_STANDARDERRORPATH) == 0) {
2755 			where2put = &j->stderrpath;
2756 		} else if (strcasecmp(key, LAUNCH_JOBKEY_STANDARDINPATH) == 0) {
2757 			where2put = &j->stdinpath;
2758 			j->stdin_fd = _fd(open(value, O_RDONLY|O_CREAT|O_NOCTTY|O_NONBLOCK, DEFFILEMODE));
2759 			if (job_assumes_zero_p(j, j->stdin_fd) != -1) {
2760 				// open() should not block, but regular IO by the job should
2761 				(void)job_assumes_zero_p(j, fcntl(j->stdin_fd, F_SETFL, 0));
2762 				// XXX -- EV_CLEAR should make named pipes happy?
2763 				(void)job_assumes_zero_p(j, kevent_mod(j->stdin_fd, EVFILT_READ, EV_ADD|EV_CLEAR, 0, 0, j));
2764 			} else {
2765 				j->stdin_fd = 0;
2766 			}
2767 #if HAVE_SANDBOX
2768 		} else if (strcasecmp(key, LAUNCH_JOBKEY_SANDBOXPROFILE) == 0) {
2769 			where2put = &j->seatbelt_profile;
2770 		} else if (strcasecmp(key, LAUNCH_JOBKEY_SANDBOXCONTAINER) == 0) {
2771 			where2put = &j->container_identifier;
2772 #endif
2773 		}
2774 		break;
2775 	case 'X':
2776 	case 'x':
2777 		if (strcasecmp(key, LAUNCH_JOBKEY_XPCDOMAIN) == 0) {
2778 			return;
2779 		}
2780 		break;
2781 	default:
2782 		job_log(j, LOG_WARNING, "Unknown key for string: %s", key);
2783 		break;
2784 	}
2785 
2786 	if (likely(where2put)) {
2787 		if (!(*where2put = strdup(value))) {
2788 			(void)job_assumes_zero(j, errno);
2789 		}
2790 	} else {
2791 		// See rdar://problem/5496612. These two are okay.
2792 		if (strncmp(key, "SHAuthorizationRight", sizeof("SHAuthorizationRight")) == 0
2793 			|| strncmp(key, "ServiceDescription", sizeof("ServiceDescription")) == 0) {
2794 			job_log(j, LOG_APPLEONLY, "This key is no longer relevant and should be removed: %s", key);
2795 		} else {
2796 			job_log(j, LOG_WARNING, "Unknown key: %s", key);
2797 		}
2798 	}
2799 }
2800 
2801 void
job_import_integer(job_t j,const char * key,long long value)2802 job_import_integer(job_t j, const char *key, long long value)
2803 {
2804 	switch (key[0]) {
2805 	case 'a':
2806 	case 'A':
2807 #if TARGET_OS_EMBEDDED
2808 		if (strcasecmp(key, LAUNCH_JOBKEY_ASID) == 0) {
2809 			if (launchd_embedded_handofgod) {
2810 				if (audit_session_port((au_asid_t)value, &j->asport) == -1 && errno != ENOSYS) {
2811 					(void)job_assumes_zero(j, errno);
2812 				}
2813 			}
2814 		}
2815 #endif
2816 	case 'e':
2817 	case 'E':
2818 		if (strcasecmp(key, LAUNCH_JOBKEY_EXITTIMEOUT) == 0) {
2819 			if (unlikely(value < 0)) {
2820 				job_log(j, LOG_WARNING, "%s less than zero. Ignoring.", LAUNCH_JOBKEY_EXITTIMEOUT);
2821 			} else if (unlikely(value > UINT32_MAX)) {
2822 				job_log(j, LOG_WARNING, "%s is too large. Ignoring.", LAUNCH_JOBKEY_EXITTIMEOUT);
2823 			} else {
2824 				j->exit_timeout = (typeof(j->exit_timeout)) value;
2825 			}
2826 		} else if (strcasecmp(key, LAUNCH_JOBKEY_EMBEDDEDMAINTHREADPRIORITY) == 0) {
2827 			j->main_thread_priority = value;
2828 		}
2829 		break;
2830 	case 'j':
2831 	case 'J':
2832 		if (strcasecmp(key, LAUNCH_JOBKEY_JETSAMPRIORITY) == 0) {
2833 			job_log(j, LOG_WARNING | LOG_CONSOLE, "Please change the JetsamPriority key to be in a dictionary named JetsamProperties.");
2834 
2835 			launch_data_t pri = launch_data_new_integer(value);
2836 			if (job_assumes(j, pri != NULL)) {
2837 				jetsam_property_setup(pri, LAUNCH_JOBKEY_JETSAMPRIORITY, j);
2838 				launch_data_free(pri);
2839 			}
2840 		}
2841 	case 'n':
2842 	case 'N':
2843 		if (strcasecmp(key, LAUNCH_JOBKEY_NICE) == 0) {
2844 			if (unlikely(value < PRIO_MIN)) {
2845 				job_log(j, LOG_WARNING, "%s less than %d. Ignoring.", LAUNCH_JOBKEY_NICE, PRIO_MIN);
2846 			} else if (unlikely(value > PRIO_MAX)) {
2847 				job_log(j, LOG_WARNING, "%s is greater than %d. Ignoring.", LAUNCH_JOBKEY_NICE, PRIO_MAX);
2848 			} else {
2849 				j->nice = (typeof(j->nice)) value;
2850 				j->setnice = true;
2851 			}
2852 		}
2853 		break;
2854 	case 't':
2855 	case 'T':
2856 		if (strcasecmp(key, LAUNCH_JOBKEY_TIMEOUT) == 0) {
2857 			if (unlikely(value < 0)) {
2858 				job_log(j, LOG_WARNING, "%s less than zero. Ignoring.", LAUNCH_JOBKEY_TIMEOUT);
2859 			} else if (unlikely(value > UINT32_MAX)) {
2860 				job_log(j, LOG_WARNING, "%s is too large. Ignoring.", LAUNCH_JOBKEY_TIMEOUT);
2861 			} else {
2862 				j->timeout = (typeof(j->timeout)) value;
2863 			}
2864 		} else if (strcasecmp(key, LAUNCH_JOBKEY_THROTTLEINTERVAL) == 0) {
2865 			if (value < 0) {
2866 				job_log(j, LOG_WARNING, "%s less than zero. Ignoring.", LAUNCH_JOBKEY_THROTTLEINTERVAL);
2867 			} else if (value > UINT32_MAX) {
2868 				job_log(j, LOG_WARNING, "%s is too large. Ignoring.", LAUNCH_JOBKEY_THROTTLEINTERVAL);
2869 			} else {
2870 				j->min_run_time = (typeof(j->min_run_time)) value;
2871 			}
2872 		}
2873 		break;
2874 	case 'u':
2875 	case 'U':
2876 		if (strcasecmp(key, LAUNCH_JOBKEY_UMASK) == 0) {
2877 			j->mask = value;
2878 			j->setmask = true;
2879 		}
2880 		break;
2881 	case 's':
2882 	case 'S':
2883 		if (strcasecmp(key, LAUNCH_JOBKEY_STARTINTERVAL) == 0) {
2884 			if (unlikely(value <= 0)) {
2885 				job_log(j, LOG_WARNING, "%s is not greater than zero. Ignoring.", LAUNCH_JOBKEY_STARTINTERVAL);
2886 			} else if (unlikely(value > UINT32_MAX)) {
2887 				job_log(j, LOG_WARNING, "%s is too large. Ignoring.", LAUNCH_JOBKEY_STARTINTERVAL);
2888 			} else {
2889 				runtime_add_weak_ref();
2890 				j->start_interval = (typeof(j->start_interval)) value;
2891 
2892 				(void)job_assumes_zero_p(j, kevent_mod((uintptr_t)&j->start_interval, EVFILT_TIMER, EV_ADD, NOTE_SECONDS, j->start_interval, j));
2893 			}
2894 #if HAVE_SANDBOX
2895 		} else if (strcasecmp(key, LAUNCH_JOBKEY_SANDBOXFLAGS) == 0) {
2896 			j->seatbelt_flags = value;
2897 #endif
2898 		}
2899 
2900 		break;
2901 	default:
2902 		job_log(j, LOG_WARNING, "Unknown key for integer: %s", key);
2903 		break;
2904 	}
2905 }
2906 
2907 void
job_import_opaque(job_t j,const char * key,launch_data_t value)2908 job_import_opaque(job_t j __attribute__((unused)), const char *key, launch_data_t value __attribute__((unused)))
2909 {
2910 	switch (key[0]) {
2911 	case 'q':
2912 	case 'Q':
2913 #if HAVE_QUARANTINE
2914 		if (strcasecmp(key, LAUNCH_JOBKEY_QUARANTINEDATA) == 0) {
2915 			size_t tmpsz = launch_data_get_opaque_size(value);
2916 
2917 			if (job_assumes(j, j->quarantine_data = malloc(tmpsz))) {
2918 				memcpy(j->quarantine_data, launch_data_get_opaque(value), tmpsz);
2919 				j->quarantine_data_sz = tmpsz;
2920 			}
2921 		}
2922 #endif
2923 	case 's':
2924 	case 'S':
2925 		if (strcasecmp(key, LAUNCH_JOBKEY_SECURITYSESSIONUUID) == 0) {
2926 			size_t tmpsz = launch_data_get_opaque_size(value);
2927 			if (job_assumes(j, tmpsz == sizeof(uuid_t))) {
2928 				memcpy(j->expected_audit_uuid, launch_data_get_opaque(value), sizeof(uuid_t));
2929 			}
2930 		}
2931 		break;
2932 	default:
2933 		break;
2934 	}
2935 }
2936 
2937 static void
policy_setup(launch_data_t obj,const char * key,void * context)2938 policy_setup(launch_data_t obj, const char *key, void *context)
2939 {
2940 	job_t j = context;
2941 	bool found_key = false;
2942 
2943 	switch (key[0]) {
2944 	case 'd':
2945 	case 'D':
2946 		if (strcasecmp(key, LAUNCH_JOBPOLICY_DENYCREATINGOTHERJOBS) == 0) {
2947 			j->deny_job_creation = launch_data_get_bool(obj);
2948 			found_key = true;
2949 		}
2950 		break;
2951 	default:
2952 		break;
2953 	}
2954 
2955 	if (unlikely(!found_key)) {
2956 		job_log(j, LOG_WARNING, "Unknown policy: %s", key);
2957 	}
2958 }
2959 
2960 void
job_import_dictionary(job_t j,const char * key,launch_data_t value)2961 job_import_dictionary(job_t j, const char *key, launch_data_t value)
2962 {
2963 	launch_data_t tmp;
2964 
2965 	switch (key[0]) {
2966 	case 'p':
2967 	case 'P':
2968 		if (strcasecmp(key, LAUNCH_JOBKEY_POLICIES) == 0) {
2969 			launch_data_dict_iterate(value, policy_setup, j);
2970 		}
2971 		break;
2972 	case 'k':
2973 	case 'K':
2974 		if (strcasecmp(key, LAUNCH_JOBKEY_KEEPALIVE) == 0) {
2975 			launch_data_dict_iterate(value, semaphoreitem_setup, j);
2976 		}
2977 		break;
2978 	case 'i':
2979 	case 'I':
2980 		if (strcasecmp(key, LAUNCH_JOBKEY_INETDCOMPATIBILITY) == 0) {
2981 			j->inetcompat = true;
2982 			j->abandon_pg = true;
2983 			if ((tmp = launch_data_dict_lookup(value, LAUNCH_JOBINETDCOMPATIBILITY_WAIT))) {
2984 				j->inetcompat_wait = launch_data_get_bool(tmp);
2985 			}
2986 		}
2987 		break;
2988 	case 'j':
2989 	case 'J':
2990 		if (strcasecmp(key, LAUNCH_JOBKEY_JETSAMPROPERTIES) == 0) {
2991 			launch_data_dict_iterate(value, (void (*)(launch_data_t, const char *, void *))jetsam_property_setup, j);
2992 		}
2993 	case 'e':
2994 	case 'E':
2995 		if (strcasecmp(key, LAUNCH_JOBKEY_ENVIRONMENTVARIABLES) == 0) {
2996 			launch_data_dict_iterate(value, envitem_setup, j);
2997 		}
2998 		break;
2999 	case 'u':
3000 	case 'U':
3001 		if (strcasecmp(key, LAUNCH_JOBKEY_USERENVIRONMENTVARIABLES) == 0) {
3002 			j->importing_global_env = true;
3003 			launch_data_dict_iterate(value, envitem_setup, j);
3004 			j->importing_global_env = false;
3005 		}
3006 		break;
3007 	case 's':
3008 	case 'S':
3009 		if (strcasecmp(key, LAUNCH_JOBKEY_SOCKETS) == 0) {
3010 			launch_data_dict_iterate(value, socketgroup_setup, j);
3011 		} else if (strcasecmp(key, LAUNCH_JOBKEY_STARTCALENDARINTERVAL) == 0) {
3012 			calendarinterval_new_from_obj(j, value);
3013 		} else if (strcasecmp(key, LAUNCH_JOBKEY_SOFTRESOURCELIMITS) == 0) {
3014 			launch_data_dict_iterate(value, limititem_setup, j);
3015 #if HAVE_SANDBOX
3016 		} else if (strcasecmp(key, LAUNCH_JOBKEY_SANDBOXFLAGS) == 0) {
3017 			launch_data_dict_iterate(value, seatbelt_setup_flags, j);
3018 #endif
3019 		}
3020 		break;
3021 	case 'h':
3022 	case 'H':
3023 		if (strcasecmp(key, LAUNCH_JOBKEY_HARDRESOURCELIMITS) == 0) {
3024 			j->importing_hard_limits = true;
3025 			launch_data_dict_iterate(value, limititem_setup, j);
3026 			j->importing_hard_limits = false;
3027 		}
3028 		break;
3029 	case 'm':
3030 	case 'M':
3031 		if (strcasecmp(key, LAUNCH_JOBKEY_MACHSERVICES) == 0) {
3032 			launch_data_dict_iterate(value, machservice_setup, j);
3033 		}
3034 		break;
3035 	case 'l':
3036 	case 'L':
3037 		if (strcasecmp(key, LAUNCH_JOBKEY_LAUNCHEVENTS) == 0) {
3038 			launch_data_dict_iterate(value, eventsystem_setup, j);
3039 		} else {
3040 			if (strcasecmp(key, LAUNCH_JOBKEY_LIMITLOADTOHARDWARE) == 0) {
3041 				return;
3042 			}
3043 			if (strcasecmp(key, LAUNCH_JOBKEY_LIMITLOADFROMHARDWARE) == 0) {
3044 				return;
3045 			}
3046 		}
3047 		break;
3048 	default:
3049 		job_log(j, LOG_WARNING, "Unknown key for dictionary: %s", key);
3050 		break;
3051 	}
3052 }
3053 
3054 void
job_import_array(job_t j,const char * key,launch_data_t value)3055 job_import_array(job_t j, const char *key, launch_data_t value)
3056 {
3057 	size_t i, value_cnt = launch_data_array_get_count(value);
3058 
3059 	switch (key[0]) {
3060 	case 'p':
3061 	case 'P':
3062 		if (strcasecmp(key, LAUNCH_JOBKEY_PROGRAMARGUMENTS) == 0) {
3063 			return;
3064 		}
3065 		break;
3066 	case 'l':
3067 	case 'L':
3068 		if (strcasecmp(key, LAUNCH_JOBKEY_LIMITLOADTOHOSTS) == 0) {
3069 			return;
3070 		} else if (strcasecmp(key, LAUNCH_JOBKEY_LIMITLOADFROMHOSTS) == 0) {
3071 			return;
3072 		} else if (strcasecmp(key, LAUNCH_JOBKEY_LIMITLOADTOSESSIONTYPE) == 0) {
3073 			job_log(j, LOG_NOTICE, "launchctl should have transformed the \"%s\" array to a string", LAUNCH_JOBKEY_LIMITLOADTOSESSIONTYPE);
3074 			return;
3075 		}
3076 		break;
3077 	case 'b':
3078 	case 'B':
3079 		if (strcasecmp(key, LAUNCH_JOBKEY_BINARYORDERPREFERENCE) == 0) {
3080 			if (job_assumes(j, j->j_binpref = malloc(value_cnt * sizeof(*j->j_binpref)))) {
3081 				j->j_binpref_cnt = value_cnt;
3082 				for (i = 0; i < value_cnt; i++) {
3083 					j->j_binpref[i] = (cpu_type_t) launch_data_get_integer(launch_data_array_get_index(value, i));
3084 				}
3085 			}
3086 		}
3087 		break;
3088 	case 's':
3089 	case 'S':
3090 		if (strcasecmp(key, LAUNCH_JOBKEY_STARTCALENDARINTERVAL) == 0) {
3091 			for (i = 0; i < value_cnt; i++) {
3092 				calendarinterval_new_from_obj(j, launch_data_array_get_index(value, i));
3093 			}
3094 		}
3095 		break;
3096 	default:
3097 		job_log(j, LOG_WARNING, "Unknown key for array: %s", key);
3098 		break;
3099 	}
3100 }
3101 
3102 void
job_import_keys(launch_data_t obj,const char * key,void * context)3103 job_import_keys(launch_data_t obj, const char *key, void *context)
3104 {
3105 	job_t j = context;
3106 	launch_data_type_t kind;
3107 
3108 	if (!obj) {
3109 		launchd_syslog(LOG_ERR, "NULL object given to job_import_keys().");
3110 		return;
3111 	}
3112 
3113 	kind = launch_data_get_type(obj);
3114 
3115 	switch (kind) {
3116 	case LAUNCH_DATA_BOOL:
3117 		job_import_bool(j, key, launch_data_get_bool(obj));
3118 		break;
3119 	case LAUNCH_DATA_STRING:
3120 		job_import_string(j, key, launch_data_get_string(obj));
3121 		break;
3122 	case LAUNCH_DATA_INTEGER:
3123 		job_import_integer(j, key, launch_data_get_integer(obj));
3124 		break;
3125 	case LAUNCH_DATA_DICTIONARY:
3126 		job_import_dictionary(j, key, obj);
3127 		break;
3128 	case LAUNCH_DATA_ARRAY:
3129 		job_import_array(j, key, obj);
3130 		break;
3131 	case LAUNCH_DATA_OPAQUE:
3132 		job_import_opaque(j, key, obj);
3133 		break;
3134 	default:
3135 		job_log(j, LOG_WARNING, "Unknown value type '%d' for key: %s", kind, key);
3136 		break;
3137 	}
3138 }
3139 
3140 job_t
jobmgr_import2(jobmgr_t jm,launch_data_t pload)3141 jobmgr_import2(jobmgr_t jm, launch_data_t pload)
3142 {
3143 	launch_data_t tmp, ldpa;
3144 	const char *label = NULL, *prog = NULL;
3145 	const char **argv = NULL;
3146 	job_t j;
3147 
3148 	if (!jobmgr_assumes(jm, pload != NULL)) {
3149 		errno = EINVAL;
3150 		return NULL;
3151 	}
3152 
3153 	if (unlikely(launch_data_get_type(pload) != LAUNCH_DATA_DICTIONARY)) {
3154 		errno = EINVAL;
3155 		return NULL;
3156 	}
3157 
3158 	if (unlikely(!(tmp = launch_data_dict_lookup(pload, LAUNCH_JOBKEY_LABEL)))) {
3159 		errno = EINVAL;
3160 		return NULL;
3161 	}
3162 
3163 	if (unlikely(launch_data_get_type(tmp) != LAUNCH_DATA_STRING)) {
3164 		errno = EINVAL;
3165 		return NULL;
3166 	}
3167 
3168 	if (unlikely(!(label = launch_data_get_string(tmp)))) {
3169 		errno = EINVAL;
3170 		return NULL;
3171 	}
3172 
3173 #if TARGET_OS_EMBEDDED
3174 	if (unlikely(launchd_embedded_handofgod && _launchd_embedded_god)) {
3175 		if (unlikely(!(tmp = launch_data_dict_lookup(pload, LAUNCH_JOBKEY_USERNAME)))) {
3176 			errno = EPERM;
3177 			return NULL;
3178 		}
3179 
3180 		const char *username = NULL;
3181 		if (likely(tmp && launch_data_get_type(tmp) == LAUNCH_DATA_STRING)) {
3182 			username = launch_data_get_string(tmp);
3183 		} else {
3184 			errno = EPERM;
3185 			return NULL;
3186 		}
3187 
3188 		if (!jobmgr_assumes(jm, _launchd_embedded_god->username != NULL && username != NULL)) {
3189 			errno = EPERM;
3190 			return NULL;
3191 		}
3192 
3193 		if (unlikely(strcmp(_launchd_embedded_god->username, username) != 0)) {
3194 			errno = EPERM;
3195 			return NULL;
3196 		}
3197 	} else if (launchd_embedded_handofgod) {
3198 		errno = EINVAL;
3199 		return NULL;
3200 	}
3201 #endif
3202 
3203 	if ((tmp = launch_data_dict_lookup(pload, LAUNCH_JOBKEY_PROGRAM))
3204 		&& (launch_data_get_type(tmp) == LAUNCH_DATA_STRING)) {
3205 		prog = launch_data_get_string(tmp);
3206 	}
3207 
3208 	int argc = 0;
3209 	if ((ldpa = launch_data_dict_lookup(pload, LAUNCH_JOBKEY_PROGRAMARGUMENTS))) {
3210 		size_t i, c;
3211 
3212 		if (launch_data_get_type(ldpa) != LAUNCH_DATA_ARRAY) {
3213 			errno = EINVAL;
3214 			return NULL;
3215 		}
3216 
3217 		c = launch_data_array_get_count(ldpa);
3218 
3219 		argv = alloca((c + 1) * sizeof(char *));
3220 
3221 		for (i = 0; i < c; i++) {
3222 			tmp = launch_data_array_get_index(ldpa, i);
3223 
3224 			if (launch_data_get_type(tmp) != LAUNCH_DATA_STRING) {
3225 				errno = EINVAL;
3226 				return NULL;
3227 			}
3228 
3229 			argv[i] = launch_data_get_string(tmp);
3230 		}
3231 
3232 		argv[i] = NULL;
3233 		argc = i;
3234 	}
3235 
3236 	if (!prog && argc == 0) {
3237 		jobmgr_log(jm, LOG_ERR, "Job specifies neither Program nor ProgramArguments: %s", label);
3238 		errno = EINVAL;
3239 		return NULL;
3240 	}
3241 
3242 	/* Find the requested session. You cannot load services into XPC domains in
3243 	 * this manner.
3244 	 */
3245 	launch_data_t session = launch_data_dict_lookup(pload, LAUNCH_JOBKEY_LIMITLOADTOSESSIONTYPE);
3246 	if (session) {
3247 		jobmgr_t jmt = NULL;
3248 		if (launch_data_get_type(session) == LAUNCH_DATA_STRING) {
3249 			jmt = jobmgr_find_by_name(jm, launch_data_get_string(session));
3250 			if (!jmt) {
3251 				jobmgr_log(jm, LOG_ERR, "Could not find requested session: %s", launch_data_get_string(session));
3252 			} else {
3253 				jm = jmt;
3254 			}
3255 		} else {
3256 			jobmgr_log(jm, LOG_ERR, "Session type is not a string.");
3257 		}
3258 
3259 		if (!jmt) {
3260 			errno = EINVAL;
3261 			return NULL;
3262 		}
3263 	}
3264 
3265 	/* For legacy reasons, we have a global hash of all labels in all job
3266 	 * managers. So rather than make it a global, we store it in the root job
3267 	 * manager. But for an XPC domain, we store a local hash of all services in
3268 	 * the domain.
3269 	 */
3270 	jobmgr_t where2look = (jm->properties & BOOTSTRAP_PROPERTY_XPC_DOMAIN) ? jm : root_jobmgr;
3271 	if (unlikely((j = job_find(where2look, label)) != NULL)) {
3272 		if (jm->xpc_singleton) {
3273 			/* There can (and probably will be) multiple attemtps to import the
3274 			 * same XPC service from the same framework. This is okay. It's
3275 			 * treated as a singleton, so just return the existing one so that
3276 			 * it may be aliased into the requesting process' XPC domain.
3277 			 */
3278 			errno = EEXIST;
3279 			return j;
3280 		} else {
3281 			/* If we're not a global XPC domain, then it's an error to try
3282 			 * importing the same job/service multiple times.
3283 			 */
3284 			errno = EEXIST;
3285 			return NULL;
3286 		}
3287 	} else if (unlikely(!jobmgr_label_test(where2look, label))) {
3288 		errno = EINVAL;
3289 		return NULL;
3290 	}
3291 	jobmgr_log(jm, LOG_DEBUG, "Importing %s.", label);
3292 
3293 	if (likely(j = job_new(jm, label, prog, argv))) {
3294 #if TARGET_OS_EMBEDDED
3295 		job_apply_defaults(j);
3296 #endif
3297 		launch_data_dict_iterate(pload, job_import_keys, j);
3298 		if (!uuid_is_null(j->expected_audit_uuid)) {
3299 			uuid_string_t uuid_str;
3300 			uuid_unparse(j->expected_audit_uuid, uuid_str);
3301 			job_log(j, LOG_DEBUG, "Imported job. Waiting for session for UUID %s.", uuid_str);
3302 			LIST_INSERT_HEAD(&s_needing_sessions, j, needing_session_sle);
3303 			errno = ENEEDAUTH;
3304 		} else {
3305 			job_log(j, LOG_DEBUG, "No security session specified.");
3306 			j->asport = MACH_PORT_NULL;
3307 		}
3308 
3309 		if (pid1_magic && !jm->parentmgr) {
3310 			/* Workaround reentrancy in CF. We don't make this a global variable
3311 			 * because we don't want per-user launchd's to inherit it. So we
3312 			 * just set it for every job that we import into the System session.
3313 			 *
3314 			 * See <rdar://problem/9468837>.
3315 			 */
3316 			envitem_new(j, "__CF_USER_TEXT_ENCODING", "0x0:0:0", false);
3317 		}
3318 
3319 		if (j->event_monitor) {
3320 			eventsystem_ping();
3321 		}
3322 
3323 #if TARGET_OS_EMBEDDED
3324 		/* SpringBoard and backboardd must run at elevated priority.
3325 		 *
3326 		 * See <rdar://problem/9539873> and <rdar://problem/10984383>.
3327 		 */
3328 		if (j->embedded_god || j->embedded_home) {
3329 			j->psproctype = POSIX_SPAWN_PROC_TYPE_APP_DEFAULT;
3330 		}
3331 #endif
3332 	}
3333 
3334 	return j;
3335 }
3336 
3337 bool
jobmgr_label_test(jobmgr_t jm,const char * str)3338 jobmgr_label_test(jobmgr_t jm, const char *str)
3339 {
3340 	const char *ptr;
3341 
3342 	if (str[0] == '\0') {
3343 		jobmgr_log(jm, LOG_ERR, "Empty job labels are not allowed");
3344 		return false;
3345 	}
3346 
3347 	for (ptr = str; *ptr; ptr++) {
3348 		if (iscntrl(*ptr)) {
3349 			jobmgr_log(jm, LOG_ERR, "ASCII control characters are not allowed in job labels. Index: %td Value: 0x%hhx", ptr - str, *ptr);
3350 			return false;
3351 		}
3352 	}
3353 
3354 	if ((strncasecmp(str, "com.apple.launchd", strlen("com.apple.launchd")) == 0)
3355 		|| (strncasecmp(str, "com.apple.launchctl", strlen("com.apple.launchctl")) == 0)) {
3356 		jobmgr_log(jm, LOG_ERR, "Job labels are not allowed to use a reserved prefix: %s", str);
3357 		return false;
3358 	}
3359 
3360 	return true;
3361 }
3362 
3363 job_t
job_find(jobmgr_t jm,const char * label)3364 job_find(jobmgr_t jm, const char *label)
3365 {
3366 	job_t ji;
3367 
3368 	if (!jm) {
3369 		jm = root_jobmgr;
3370 	}
3371 
3372 	LIST_FOREACH(ji, &jm->label_hash[hash_label(label)], label_hash_sle) {
3373 		if (unlikely(ji->removal_pending || ji->mgr->shutting_down)) {
3374 			// 5351245 and 5488633 respectively
3375 			continue;
3376 		}
3377 
3378 		if (strcmp(ji->label, label) == 0) {
3379 			return ji;
3380 		}
3381 	}
3382 
3383 	errno = ESRCH;
3384 	return NULL;
3385 }
3386 
3387 // Should try and consolidate with job_mig_intran2() and jobmgr_find_by_pid().
3388 job_t
jobmgr_find_by_pid_deep(jobmgr_t jm,pid_t p,bool anon_okay)3389 jobmgr_find_by_pid_deep(jobmgr_t jm, pid_t p, bool anon_okay)
3390 {
3391 	job_t ji = NULL;
3392 	LIST_FOREACH(ji, &jm->active_jobs[ACTIVE_JOB_HASH(p)], pid_hash_sle) {
3393 		if (ji->p == p && (!ji->anonymous || (ji->anonymous && anon_okay))) {
3394 			return ji;
3395 		}
3396 	}
3397 
3398 	jobmgr_t jmi = NULL;
3399 	SLIST_FOREACH(jmi, &jm->submgrs, sle) {
3400 		if ((ji = jobmgr_find_by_pid_deep(jmi, p, anon_okay))) {
3401 			break;
3402 		}
3403 	}
3404 
3405 	return ji;
3406 }
3407 
3408 job_t
jobmgr_find_by_pid(jobmgr_t jm,pid_t p,bool create_anon)3409 jobmgr_find_by_pid(jobmgr_t jm, pid_t p, bool create_anon)
3410 {
3411 	job_t ji;
3412 
3413 	LIST_FOREACH(ji, &jm->active_jobs[ACTIVE_JOB_HASH(p)], pid_hash_sle) {
3414 		if (ji->p == p) {
3415 			return ji;
3416 		}
3417 	}
3418 
3419 	return create_anon ? job_new_anonymous(jm, p) : NULL;
3420 }
3421 
3422 job_t
managed_job(pid_t p)3423 managed_job(pid_t p)
3424 {
3425 	job_t ji;
3426 
3427 	LIST_FOREACH(ji, &managed_actives[ACTIVE_JOB_HASH(p)], pid_hash_sle) {
3428 		if (ji->p == p) {
3429 			return ji;
3430 		}
3431 	}
3432 
3433 	return NULL;
3434 }
3435 
3436 job_t
job_mig_intran2(jobmgr_t jm,mach_port_t mport,pid_t upid)3437 job_mig_intran2(jobmgr_t jm, mach_port_t mport, pid_t upid)
3438 {
3439 	jobmgr_t jmi;
3440 	job_t ji;
3441 
3442 	if (jm->jm_port == mport) {
3443 		return jobmgr_find_by_pid(jm, upid, true);
3444 	}
3445 
3446 	SLIST_FOREACH(jmi, &jm->submgrs, sle) {
3447 		job_t jr;
3448 
3449 		if ((jr = job_mig_intran2(jmi, mport, upid))) {
3450 			return jr;
3451 		}
3452 	}
3453 
3454 	LIST_FOREACH(ji, &jm->jobs, sle) {
3455 		if (ji->j_port == mport) {
3456 			return ji;
3457 		}
3458 	}
3459 
3460 	return NULL;
3461 }
3462 
3463 job_t
job_mig_intran(mach_port_t p)3464 job_mig_intran(mach_port_t p)
3465 {
3466 	struct ldcred *ldc = runtime_get_caller_creds();
3467 	job_t jr;
3468 
3469 	jr = job_mig_intran2(root_jobmgr, p, ldc->pid);
3470 
3471 	if (!jr) {
3472 		struct proc_bsdshortinfo proc;
3473 		if (proc_pidinfo(ldc->pid, PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0) {
3474 			if (errno != ESRCH) {
3475 				(void)jobmgr_assumes_zero(root_jobmgr, errno);
3476 			} else {
3477 				jobmgr_log(root_jobmgr, LOG_ERR, "%s[%i] disappeared out from under us (UID: %u EUID: %u)", proc.pbsi_comm, ldc->pid, ldc->uid, ldc->euid);
3478 			}
3479 		}
3480 	}
3481 
3482 	return jr;
3483 }
3484 
3485 job_t
job_find_by_service_port(mach_port_t p)3486 job_find_by_service_port(mach_port_t p)
3487 {
3488 	struct machservice *ms;
3489 
3490 	LIST_FOREACH(ms, &port_hash[HASH_PORT(p)], port_hash_sle) {
3491 		if (ms->recv && (ms->port == p)) {
3492 			return ms->job;
3493 		}
3494 	}
3495 
3496 	return NULL;
3497 }
3498 
3499 void
job_mig_destructor(job_t j)3500 job_mig_destructor(job_t j)
3501 {
3502 	/* The job can go invalid before this point.
3503 	 *
3504 	 * <rdar://problem/5477111>
3505 	 */
3506 	if (unlikely(j && (j != workaround_5477111) && j->unload_at_mig_return)) {
3507 		job_log(j, LOG_NOTICE, "Unloading PID %u at MIG return.", j->p);
3508 		job_remove(j);
3509 	}
3510 
3511 	workaround_5477111 = NULL;
3512 
3513 	calendarinterval_sanity_check();
3514 }
3515 
3516 void
job_export_all2(jobmgr_t jm,launch_data_t where)3517 job_export_all2(jobmgr_t jm, launch_data_t where)
3518 {
3519 	jobmgr_t jmi;
3520 	job_t ji;
3521 
3522 	SLIST_FOREACH(jmi, &jm->submgrs, sle) {
3523 		job_export_all2(jmi, where);
3524 	}
3525 
3526 	LIST_FOREACH(ji, &jm->jobs, sle) {
3527 		launch_data_t tmp;
3528 
3529 		if (jobmgr_assumes(jm, (tmp = job_export(ji)) != NULL)) {
3530 			launch_data_dict_insert(where, tmp, ji->label);
3531 		}
3532 	}
3533 }
3534 
3535 launch_data_t
job_export_all(void)3536 job_export_all(void)
3537 {
3538 	launch_data_t resp = launch_data_alloc(LAUNCH_DATA_DICTIONARY);
3539 
3540 	if (resp != NULL) {
3541 		job_export_all2(root_jobmgr, resp);
3542 	} else {
3543 		(void)os_assumes_zero(errno);
3544 	}
3545 
3546 	return resp;
3547 }
3548 
3549 void
job_log_stray_pg(job_t j)3550 job_log_stray_pg(job_t j)
3551 {
3552 	pid_t *pids = NULL;
3553 	size_t len = sizeof(pid_t) * get_kern_max_proc();
3554 	int i = 0, kp_cnt = 0;
3555 
3556 	if (!launchd_apple_internal) {
3557 		return;
3558 	}
3559 
3560 	runtime_ktrace(RTKT_LAUNCHD_FINDING_STRAY_PG, j->p, 0, 0);
3561 
3562 	if (!job_assumes(j, (pids = malloc(len)) != NULL)) {
3563 		return;
3564 	}
3565 	if (job_assumes_zero_p(j, (kp_cnt = proc_listpgrppids(j->p, pids, len))) == -1) {
3566 		goto out;
3567 	}
3568 
3569 	for (i = 0; i < kp_cnt; i++) {
3570 		pid_t p_i = pids[i];
3571 		if (p_i == j->p) {
3572 			continue;
3573 		} else if (p_i == 0 || p_i == 1) {
3574 			continue;
3575 		}
3576 
3577 		struct proc_bsdshortinfo proc;
3578 		if (proc_pidinfo(p_i, PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0) {
3579 			if (errno != ESRCH) {
3580 				(void)job_assumes_zero(j, errno);
3581 			}
3582 			continue;
3583 		}
3584 
3585 		pid_t pp_i = proc.pbsi_ppid;
3586 		const char *z = (proc.pbsi_status == SZOMB) ? "zombie " : "";
3587 		const char *n = proc.pbsi_comm;
3588 
3589 		job_log(j, LOG_WARNING, "Stray %sprocess with PGID equal to this dead job: PID %u PPID %u PGID %u %s", z, p_i, pp_i, proc.pbsi_pgid, n);
3590 	}
3591 
3592 out:
3593 	free(pids);
3594 }
3595 
3596 #if HAVE_SYSTEMSTATS
3597 static void
systemstats_timer_callback(void)3598 systemstats_timer_callback(void)
3599 {
3600 	jobmgr_log_perf_statistics(root_jobmgr, true);
3601 }
3602 
3603 static bool
systemstats_is_enabled(void)3604 systemstats_is_enabled(void)
3605 {
3606 	static bool systemstats_enabled;
3607 
3608 	if (!systemstats_enabled) {
3609 		char *store = launchd_copy_persistent_store(LAUNCHD_PERSISTENT_STORE_LOGS, NULL);
3610 		systemstats_enabled = systemstats_init(SYSTEMSTATS_WRITER_launchd, store);
3611 		free(store);
3612 
3613 		uint64_t interval;
3614 		interval = systemstats_get_log_interval(SYSTEMSTATS_WRITER_launchd);
3615 
3616 		if (pid1_magic && systemstats_enabled && interval) {
3617 			jobmgr_assumes_zero_p(root_jobmgr, kevent_mod((uintptr_t)systemstats_timer_callback, EVFILT_TIMER, EV_ADD, NOTE_SECONDS, interval, root_jobmgr));
3618 		}
3619 	}
3620 
3621 	return systemstats_enabled;
3622 }
3623 #endif // HAVE_SYSTEMSTATS
3624 
3625 void
job_reap(job_t j)3626 job_reap(job_t j)
3627 {
3628 	bool is_system_bootstrapper = ((j->is_bootstrapper && pid1_magic) && !j->mgr->parentmgr);
3629 
3630 	job_log(j, LOG_DEBUG, "Reaping");
3631 
3632 	if (unlikely(j->weird_bootstrap)) {
3633 		int64_t junk = 0;
3634 		job_mig_swap_integer(j, VPROC_GSK_WEIRD_BOOTSTRAP, 0, 0, &junk);
3635 	}
3636 
3637 	if (j->fork_fd) {
3638 		(void)job_assumes_zero_p(j, runtime_close(j->fork_fd));
3639 		j->fork_fd = 0;
3640 	}
3641 
3642 	bool was_dirty = false;
3643 	if (!(j->anonymous || j->implicit_reap)) {
3644 		uint32_t flags = 0;
3645 #if 0
3646 		(void)job_assumes_zero(j, proc_get_dirty(j->p, &flags));
3647 #endif
3648 		j->idle_exit = (flags & PROC_DIRTY_ALLOWS_IDLE_EXIT);
3649 		was_dirty = (flags & PROC_DIRTY_IS_DIRTY);
3650 
3651 		job_log(j, LOG_DEBUG, "%sob exited %s.", j->idle_exit ? "Idle-exit j" : "J", was_dirty ? "while dirty" : "cleanly");
3652 	}
3653 
3654 	if (j->idle_exit && was_dirty) {
3655 		if (j->jettisoned) {
3656 			job_log(j, LOG_NOTICE, "Idle-exit job was jettisoned while dirty. Will respawn immediately.");
3657 			j->unthrottle = true;
3658 			j->start_pending = true;
3659 		} else {
3660 			job_log(j, LOG_INFO, "Idle-exit job exited while dirty.");
3661 		}
3662 	} else if (j->idle_exit && j->jettisoned) {
3663 		/* If an idle-exit job is jettisoned, then we shouldn't throttle its
3664 		 * next respawn because it could not help when it exited. If it ran for
3665 		 * the minimum runtime, then this doesn't really matter. If it ran for
3666 		 * less than the minimum runtime, it will not be throttled.
3667 		 *
3668 		 * <rdar://problem/12098667>
3669 		 */
3670 		job_log(j, LOG_NOTICE, "Idle-exit job was jettisoned. Will bypass throttle interval for next on-demand launch.");
3671 		j->unthrottle = true;
3672 	}
3673 
3674 	if (j->anonymous) {
3675 		j->last_exit_status = 0;
3676 	} else {
3677 		uint64_t rt = runtime_get_nanoseconds_since(j->start_time);
3678 		j->trt += rt;
3679 
3680 		job_log(j, LOG_PERF, "Last instance wall time: %06f", (double)rt / (double)NSEC_PER_SEC);
3681 		j->nruns++;
3682 
3683 		/* The job is dead. While the PID/PGID is still known to be valid, try
3684 		 * to kill abandoned descendant processes.
3685 		 */
3686 		job_log_stray_pg(j);
3687 		if (!j->abandon_pg) {
3688 			if (unlikely(killpg2(j->p, SIGTERM) == -1 && errno != ESRCH)) {
3689 				job_log(j, LOG_APPLEONLY, "Bug: 5487498");
3690 			}
3691 		}
3692 
3693 		int r = -1;
3694 		if (!j->implicit_reap) {
3695 			/* If the shutdown monitor has suspended a task and not resumed it
3696 			 * resumed it before exiting, the kernel will not clean up after the
3697 			 * shutdown monitor. It will, instead, leave the task suspended and
3698 			 * not process any pending signals on the event loop for the task.
3699 			 *
3700 			 * There are a variety of other kernel bugs that could prevent a
3701 			 * process from exiting, usually having to do with faulty hardware
3702 			 * or talking to misbehaving drivers that mark a thread as
3703 			 * uninterruptible and deadlock/hang before unmarking it as such. So
3704 			 * we have to work around that too.
3705 			 *
3706 			 * See <rdar://problem/9284889&9359725>.
3707 			 */
3708 			if (j->workaround9359725) {
3709 				job_log(j, LOG_NOTICE, "Simulated exit: <rdar://problem/9359725>");
3710 				j->last_exit_status = W_EXITCODE(-1, SIGSEGV);
3711 			} else {
3712 #if HAVE_SYSTEMSTATS
3713 				int r2;
3714 				struct rusage_info_v1 ri;
3715 				r2 = job_assumes_zero(j, proc_pid_rusage(j->p, RUSAGE_INFO_V1, (rusage_info_t)&ri));
3716 #endif
3717 				if ((r = wait4(j->p, &j->last_exit_status, 0, NULL)) == -1) {
3718 					job_log(j, LOG_ERR, "Reap failed. Assuming job exited: %d: %s", errno, strerror(errno));
3719 					j->last_exit_status = W_EXITCODE(-1, SIGSEGV);
3720 				}
3721 
3722 				if (j->idle_exit && j->jettisoned) {
3723 					// Treat idle-exit jettisons as successful exit.
3724 					//
3725 					// <rdar://problem/13338973>
3726 					(void)job_assumes_zero(j, WTERMSIG(j->last_exit_status));
3727 					j->last_exit_status = W_EXITCODE(0, 0);
3728 				}
3729 #if HAVE_SYSTEMSTATS
3730 				if (r2 == 0) {
3731 					job_log_perf_statistics(j, &ri, j->last_exit_status);
3732 				}
3733 #endif
3734 			}
3735 		} else {
3736 			job_log(j, LOG_INFO, "Job was implicitly reaped by the kernel.");
3737 		}
3738 	}
3739 
3740 	if (j->exit_timeout) {
3741 		(void)kevent_mod((uintptr_t)&j->exit_timeout, EVFILT_TIMER, EV_DELETE, 0, 0, NULL);
3742 	}
3743 
3744 	LIST_REMOVE(j, pid_hash_sle);
3745 	if (!j->anonymous) {
3746 		LIST_REMOVE(j, global_pid_hash_sle);
3747 	}
3748 
3749 	if (j->sent_signal_time) {
3750 		uint64_t td_sec, td_usec, td = runtime_get_nanoseconds_since(j->sent_signal_time);
3751 
3752 		td_sec = td / NSEC_PER_SEC;
3753 		td_usec = (td % NSEC_PER_SEC) / NSEC_PER_USEC;
3754 
3755 		job_log(j, LOG_DEBUG, "Exited %zu.%06zu seconds after the first signal was sent", td_sec, td_usec);
3756 	}
3757 
3758 	int exit_status = WEXITSTATUS(j->last_exit_status);
3759 	if (WIFEXITED(j->last_exit_status) && exit_status != 0) {
3760 		if (!j->did_exec && _launchd_support_system) {
3761 			xpc_object_t event = NULL;
3762 			switch (exit_status) {
3763 			case ENOENT:
3764 			case ENOTDIR:
3765 			case ESRCH:
3766 				job_log(j, LOG_NOTICE, "Job failed to exec(3). Setting up event to tell us when to try again: %d: %s", exit_status, strerror(exit_status));
3767 				event = xpc_dictionary_create(NULL, NULL, 0);
3768 				xpc_dictionary_set_string(event, "Executable", j->prog ? j->prog : j->argv[0]);
3769 				if (j->mach_uid) {
3770 					xpc_dictionary_set_uint64(event, "UID", j->mach_uid);
3771 				} else if (j->username) {
3772 					xpc_dictionary_set_string(event, "UserName", j->username);
3773 				}
3774 
3775 				if (j->groupname) {
3776 					xpc_dictionary_set_string(event, "GroupName", j->groupname);
3777 				}
3778 
3779 				(void)externalevent_new(j, _launchd_support_system, j->label, event, 0);
3780 				xpc_release(event);
3781 
3782 				j->waiting4ok = true;
3783 			default:
3784 				job_log(j, LOG_NOTICE, "Job failed to exec(3) for weird reason: %d", exit_status);
3785 			}
3786 		} else {
3787 			int level = LOG_INFO;
3788 			if (exit_status != 0) {
3789 				level = LOG_ERR;
3790 			}
3791 
3792 			job_log(j, level, "Exited with code: %d", exit_status);
3793 		}
3794 	}
3795 
3796 	if (WIFSIGNALED(j->last_exit_status)) {
3797 		int s = WTERMSIG(j->last_exit_status);
3798 		if ((SIGKILL == s || SIGTERM == s) && !j->stopped) {
3799 			job_log(j, LOG_NOTICE, "Exited: %s", strsignal(s));
3800 		} else if (!(j->stopped || j->clean_kill || j->jettisoned)) {
3801 			switch (s) {
3802 			// Signals which indicate a crash.
3803 			case SIGILL:
3804 			case SIGABRT:
3805 			case SIGFPE:
3806 			case SIGBUS:
3807 			case SIGSEGV:
3808 			case SIGSYS:
3809 			/* If the kernel has posted NOTE_EXIT and the signal sent to the process was
3810 			 * SIGTRAP, assume that it's a crash.
3811 			 */
3812 			case SIGTRAP:
3813 				j->crashed = true;
3814 				job_log(j, LOG_WARNING, "Job appears to have crashed: %s", strsignal(s));
3815 				break;
3816 			default:
3817 				job_log(j, LOG_WARNING, "Exited abnormally: %s", strsignal(s));
3818 				break;
3819 			}
3820 
3821 			if (is_system_bootstrapper && j->crashed) {
3822 				job_log(j, LOG_ERR | LOG_CONSOLE, "The %s bootstrapper has crashed: %s", j->mgr->name, strsignal(s));
3823 			}
3824 		}
3825 	}
3826 
3827 	j->reaped = true;
3828 
3829 	struct machservice *msi = NULL;
3830 	if (j->crashed || !(j->did_exec || j->anonymous)) {
3831 		SLIST_FOREACH(msi, &j->machservices, sle) {
3832 			if (j->crashed && !msi->isActive && (msi->drain_one_on_crash || msi->drain_all_on_crash)) {
3833 				machservice_drain_port(msi);
3834 			}
3835 
3836 			if (!j->did_exec && msi->reset && job_assumes(j, !msi->isActive)) {
3837 				machservice_resetport(j, msi);
3838 			}
3839 		}
3840 	}
3841 
3842 	/* HACK: Essentially duplicating the logic directly above. But this has
3843 	 * gotten really hairy, and I don't want to try consolidating it right now.
3844 	 */
3845 	if (j->xpc_service && !j->xpcproxy_did_exec) {
3846 		job_log(j, LOG_ERR, "XPC Service could not exec(3). Resetting port.");
3847 		SLIST_FOREACH(msi, &j->machservices, sle) {
3848 			/* Drain the messages but do not reset the port. If xpcproxy could
3849 			 * not exec(3), then we don't want to continue trying, since there
3850 			 * is very likely a serious configuration error with the service.
3851 			 *
3852 			 * The above comment is weird. I originally said we should drain
3853 			 * messages but not reset the port, but that's exactly what we do
3854 			 * below, and I'm not sure which is the mistake, the comment or the
3855 			 * actual behavior.
3856 			 *
3857 			 * Since it's always been this way, I'll assume that the comment is
3858 			 * incorrect, but I'll leave it in place just to remind myself to
3859 			 * actually look into it at some point.
3860 			 *
3861 			 * <rdar://problem/8986802>
3862 			 */
3863 			if (msi->upfront && job_assumes(j, !msi->isActive)) {
3864 				machservice_resetport(j, msi);
3865 			}
3866 		}
3867 	}
3868 
3869 	struct suspended_peruser *spi = NULL;
3870 	while ((spi = LIST_FIRST(&j->suspended_perusers))) {
3871 		job_log(j, LOG_ERR, "Job exited before resuming per-user launchd for UID %u. Will forcibly resume.", spi->j->mach_uid);
3872 		spi->j->peruser_suspend_count--;
3873 		if (spi->j->peruser_suspend_count == 0) {
3874 			job_dispatch(spi->j, false);
3875 		}
3876 		LIST_REMOVE(spi, sle);
3877 		free(spi);
3878 	}
3879 
3880 	if (j->exit_status_dest) {
3881 		errno = helper_downcall_wait(j->exit_status_dest, j->last_exit_status);
3882 		if (errno && errno != MACH_SEND_INVALID_DEST) {
3883 			(void)job_assumes_zero(j, errno);
3884 		}
3885 
3886 		j->exit_status_dest = MACH_PORT_NULL;
3887 	}
3888 
3889 	if (j->spawn_reply_port) {
3890 		/* If the child never called exec(3), we must send a spawn() reply so
3891 		 * that the requestor can get exit status from it. If we fail to send
3892 		 * the reply for some reason, we have to deallocate the exit status port
3893 		 * ourselves.
3894 		 */
3895 		kern_return_t kr = job_mig_spawn2_reply(j->spawn_reply_port, BOOTSTRAP_SUCCESS, j->p, j->exit_status_port);
3896 		if (kr) {
3897 			if (kr != MACH_SEND_INVALID_DEST) {
3898 				(void)job_assumes_zero(j, kr);
3899 			}
3900 
3901 			(void)job_assumes_zero(j, launchd_mport_close_recv(j->exit_status_port));
3902 		}
3903 
3904 		j->exit_status_port = MACH_PORT_NULL;
3905 		j->spawn_reply_port = MACH_PORT_NULL;
3906 	}
3907 
3908 	if (j->anonymous) {
3909 		total_anon_children--;
3910 		if (j->holds_ref) {
3911 			job_log(j, LOG_PERF, "Anonymous job exited holding reference.");
3912 			runtime_del_ref();
3913 		}
3914 	} else {
3915 		job_log(j, LOG_PERF, "Job exited.");
3916 		runtime_del_ref();
3917 		total_children--;
3918 	}
3919 
3920 	if (j->has_console) {
3921 		launchd_wsp = 0;
3922 	}
3923 
3924 	if (j->shutdown_monitor) {
3925 		job_log(j, LOG_NOTICE | LOG_CONSOLE, "Shutdown monitor has exited.");
3926 		_launchd_shutdown_monitor = NULL;
3927 		j->shutdown_monitor = false;
3928 	}
3929 
3930 	if (!j->anonymous) {
3931 		j->mgr->normal_active_cnt--;
3932 	}
3933 	j->sent_signal_time = 0;
3934 	j->sent_sigkill = false;
3935 	j->clean_kill = false;
3936 	j->event_monitor_ready2signal = false;
3937 	j->p = 0;
3938 	j->uniqueid = 0;
3939 }
3940 
3941 void
jobmgr_dispatch_all(jobmgr_t jm,bool newmounthack)3942 jobmgr_dispatch_all(jobmgr_t jm, bool newmounthack)
3943 {
3944 	jobmgr_t jmi, jmn;
3945 	job_t ji, jn;
3946 
3947 	if (jm->shutting_down) {
3948 		return;
3949 	}
3950 
3951 	SLIST_FOREACH_SAFE(jmi, &jm->submgrs, sle, jmn) {
3952 		jobmgr_dispatch_all(jmi, newmounthack);
3953 	}
3954 
3955 	LIST_FOREACH_SAFE(ji, &jm->jobs, sle, jn) {
3956 		if (newmounthack && ji->start_on_mount) {
3957 			ji->start_pending = true;
3958 		}
3959 
3960 		job_dispatch(ji, false);
3961 	}
3962 }
3963 
3964 void
job_dispatch_curious_jobs(job_t j)3965 job_dispatch_curious_jobs(job_t j)
3966 {
3967 	job_t ji = NULL, jt = NULL;
3968 	SLIST_FOREACH_SAFE(ji, &s_curious_jobs, curious_jobs_sle, jt) {
3969 		struct semaphoreitem *si = NULL;
3970 		SLIST_FOREACH(si, &ji->semaphores, sle) {
3971 			if (!(si->why == OTHER_JOB_ENABLED || si->why == OTHER_JOB_DISABLED)) {
3972 				continue;
3973 			}
3974 
3975 			if (strcmp(si->what, j->label) == 0) {
3976 				job_log(ji, LOG_DEBUG, "Dispatching out of interest in \"%s\".", j->label);
3977 
3978 				if (!ji->removing) {
3979 					job_dispatch(ji, false);
3980 				} else {
3981 					job_log(ji, LOG_NOTICE, "The following job is circularly dependent upon this one: %s", j->label);
3982 				}
3983 
3984 				/* ji could be removed here, so don't do anything with it or its semaphores
3985 				 * after this point.
3986 				 */
3987 				break;
3988 			}
3989 		}
3990 	}
3991 }
3992 
3993 job_t
job_dispatch(job_t j,bool kickstart)3994 job_dispatch(job_t j, bool kickstart)
3995 {
3996 	// Don't dispatch a job if it has no audit session set.
3997 	syslog(LOG_ERR, "dispatching job j=%p kickstart=%d", j, kickstart);
3998 	#ifdef notyet
3999 	if (!uuid_is_null(j->expected_audit_uuid)) {
4000 		job_log(j, LOG_DEBUG, "Job is still awaiting its audit session UUID. Not dispatching.");
4001 		return NULL;
4002 	}
4003 	#endif
4004 	if (j->alias) {
4005 		job_log(j, LOG_DEBUG, "Job is an alias. Not dispatching.");
4006 		return NULL;
4007 	}
4008 
4009 	if (j->waiting4ok) {
4010 		job_log(j, LOG_DEBUG, "Job cannot exec(3). Not dispatching.");
4011 		return NULL;
4012 	}
4013 
4014 #if TARGET_OS_EMBEDDED
4015 	if (launchd_embedded_handofgod && _launchd_embedded_god) {
4016 		if (!job_assumes(j, _launchd_embedded_god->username != NULL && j->username != NULL)) {
4017 			errno = EPERM;
4018 			return NULL;
4019 		}
4020 
4021 		if (strcmp(j->username, _launchd_embedded_god->username) != 0) {
4022 			errno = EPERM;
4023 			return NULL;
4024 		}
4025 	} else if (launchd_embedded_handofgod) {
4026 		errno = EINVAL;
4027 		return NULL;
4028 	}
4029 #endif
4030 
4031 	/*
4032 	 * The whole job removal logic needs to be consolidated. The fact that
4033 	 * a job can be removed from just about anywhere makes it easy to have
4034 	 * stale pointers left behind somewhere on the stack that might get
4035 	 * used after the deallocation. In particular, during job iteration.
4036 	 *
4037 	 * This is a classic example. The act of dispatching a job may delete it.
4038 	 */
4039 	if (!job_active(j)) {
4040 		if (job_useless(j)) {
4041 			job_log(j, LOG_DEBUG, "Job is useless. Removing.");
4042 			job_remove(j);
4043 			return NULL;
4044 		}
4045 		if (unlikely(j->per_user && j->peruser_suspend_count > 0)) {
4046 			job_log(j, LOG_DEBUG, "Per-user launchd is suspended. Not dispatching.");
4047 			return NULL;
4048 		}
4049 
4050 		if (kickstart || job_keepalive(j) || uflag) {
4051 			job_log(j, LOG_DEBUG, "%starting job", kickstart ? "Kicks" : "S");
4052 			job_start(j);
4053 		} else {
4054 			job_log(j, LOG_DEBUG, "Watching job.");
4055 			job_watch(j);
4056 		}
4057 	} else {
4058 		job_log(j, LOG_DEBUG, "Tried to dispatch an already active job: %s.", job_active(j));
4059 	}
4060 	syslog(LOG_ERR, "dispatched j=%p", j);
4061 	return j;
4062 }
4063 
4064 void
job_kill(job_t j)4065 job_kill(job_t j)
4066 {
4067 	if (unlikely(!j->p || j->anonymous)) {
4068 		return;
4069 	}
4070 
4071 	(void)job_assumes_zero_p(j, kill2(j->p, SIGKILL));
4072 
4073 	j->sent_sigkill = true;
4074 	(void)job_assumes_zero_p(j, kevent_mod((uintptr_t)&j->exit_timeout, EVFILT_TIMER, EV_ADD|EV_ONESHOT, NOTE_SECONDS, LAUNCHD_SIGKILL_TIMER, j));
4075 
4076 	job_log(j, LOG_DEBUG, "Sent SIGKILL signal");
4077 }
4078 
4079 void
job_open_shutdown_transaction(job_t j)4080 job_open_shutdown_transaction(job_t j)
4081 {
4082 	int rv = proc_set_dirty(j->p, true);
4083 	if (rv != 0) {
4084 		job_log(j, LOG_DEBUG, "Job wants to be dirty at shutdown, but it is not Instant Off-compliant. Treating normally.");
4085 		j->dirty_at_shutdown = false;
4086 	}
4087 }
4088 
4089 void
job_close_shutdown_transaction(job_t j)4090 job_close_shutdown_transaction(job_t j)
4091 {
4092 	if (j->dirty_at_shutdown) {
4093 		job_log(j, LOG_DEBUG, "Closing shutdown transaction for job.");
4094 		(void)job_assumes_zero(j, proc_set_dirty(j->p, false));
4095 		j->dirty_at_shutdown = false;
4096 	}
4097 }
4098 
4099 void
job_log_children_without_exec(job_t j)4100 job_log_children_without_exec(job_t j)
4101 {
4102 	pid_t *pids = NULL;
4103 	size_t len = sizeof(pid_t) * get_kern_max_proc();
4104 	int i = 0, kp_cnt = 0;
4105 
4106 	if (!launchd_apple_internal || j->anonymous || j->per_user) {
4107 		return;
4108 	}
4109 
4110 	if (!job_assumes(j, (pids = malloc(len)) != NULL)) {
4111 		return;
4112 	}
4113 	if (job_assumes_zero_p(j, (kp_cnt = proc_listchildpids(j->p, pids, len))) == -1) {
4114 		goto out;
4115 	}
4116 
4117 	for (i = 0; i < kp_cnt; i++) {
4118 		struct proc_bsdshortinfo proc;
4119 		if (proc_pidinfo(pids[i], PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0) {
4120 			if (errno != ESRCH) {
4121 				(void)job_assumes_zero(j, errno);
4122 			}
4123 			continue;
4124 		}
4125 		if (proc.pbsi_flags & P_EXEC) {
4126 			continue;
4127 		}
4128 
4129 		job_log(j, LOG_DEBUG, "Called *fork(). Please switch to posix_spawn*(), pthreads or launchd. Child PID %u", pids[i]);
4130 	}
4131 
4132 out:
4133 	free(pids);
4134 }
4135 
4136 void
job_callback_proc(job_t j,struct kevent * kev)4137 job_callback_proc(job_t j, struct kevent *kev)
4138 {
4139 	bool program_changed = false;
4140 	int fflags = kev->fflags;
4141 
4142 	job_log(j, LOG_DEBUG, "EVFILT_PROC event for job.");
4143 	log_kevent_struct(LOG_DEBUG, kev, 0);
4144 
4145 	if (fflags & NOTE_EXEC) {
4146 		program_changed = true;
4147 
4148 		if (j->anonymous) {
4149 			struct proc_bsdshortinfo proc;
4150 			if (proc_pidinfo(j->p, PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) > 0) {
4151 				char newlabel[1000];
4152 
4153 				snprintf(newlabel, sizeof(newlabel), "%p.anonymous.%s", j, proc.pbsi_comm);
4154 
4155 				job_log(j, LOG_INFO, "Program changed. Updating the label to: %s", newlabel);
4156 
4157 				LIST_REMOVE(j, label_hash_sle);
4158 				strcpy((char *)j->label, newlabel);
4159 
4160 				jobmgr_t where2put = root_jobmgr;
4161 				if (j->mgr->properties & BOOTSTRAP_PROPERTY_XPC_DOMAIN) {
4162 					where2put = j->mgr;
4163 				}
4164 				LIST_INSERT_HEAD(&where2put->label_hash[hash_label(j->label)], j, label_hash_sle);
4165 			} else if (errno != ESRCH) {
4166 				(void)job_assumes_zero(j, errno);
4167 			}
4168 		} else {
4169 			if (j->spawn_reply_port) {
4170 				errno = job_mig_spawn2_reply(j->spawn_reply_port, BOOTSTRAP_SUCCESS, j->p, j->exit_status_port);
4171 				if (errno) {
4172 					if (errno != MACH_SEND_INVALID_DEST) {
4173 						(void)job_assumes_zero(j, errno);
4174 					}
4175 					(void)job_assumes_zero(j, launchd_mport_close_recv(j->exit_status_port));
4176 				}
4177 
4178 				j->spawn_reply_port = MACH_PORT_NULL;
4179 				j->exit_status_port = MACH_PORT_NULL;
4180 			}
4181 
4182 			if (j->xpc_service && j->did_exec) {
4183 				j->xpcproxy_did_exec = true;
4184 			}
4185 
4186 			j->did_exec = true;
4187 			job_log(j, LOG_DEBUG, "Program changed");
4188 		}
4189 	}
4190 
4191 	if (fflags & NOTE_FORK) {
4192 		job_log(j, LOG_DEBUG, "fork()ed%s", program_changed ? ". For this message only: We don't know whether this event happened before or after execve()." : "");
4193 		job_log_children_without_exec(j);
4194 	}
4195 
4196 	if (fflags & NOTE_EXIT) {
4197 		if (kev->data & NOTE_EXIT_DECRYPTFAIL) {
4198 			j->fpfail = true;
4199 			job_log(j, LOG_WARNING, "FairPlay decryption failed on binary for job.");
4200 		} else if (kev->data & NOTE_EXIT_MEMORY) {
4201 			j->jettisoned = true;
4202 			job_log(j, LOG_INFO, "Job was killed due to memory pressure.");
4203 		}
4204 
4205 		job_reap(j);
4206 
4207 		if (j->anonymous) {
4208 			job_remove(j);
4209 			j = NULL;
4210 		} else {
4211 			struct waiting4attach *w4ai = NULL;
4212 			struct waiting4attach *w4ait = NULL;
4213 			LIST_FOREACH_SAFE(w4ai, &_launchd_domain_waiters, le, w4ait) {
4214 				if (w4ai->dest == (pid_t)kev->ident) {
4215 					waiting4attach_delete(j->mgr, w4ai);
4216 				}
4217 			}
4218 
4219 			(void)job_dispatch(j, false);
4220 		}
4221 	}
4222 }
4223 
4224 void
job_callback_timer(job_t j,void * ident)4225 job_callback_timer(job_t j, void *ident)
4226 {
4227 	if (j == ident) {
4228 		job_log(j, LOG_DEBUG, "j == ident (%p)", ident);
4229 		job_dispatch(j, true);
4230 	} else if (&j->semaphores == ident) {
4231 		job_log(j, LOG_DEBUG, "&j->semaphores == ident (%p)", ident);
4232 		job_dispatch(j, false);
4233 	} else if (&j->start_interval == ident) {
4234 		job_log(j, LOG_DEBUG, "&j->start_interval == ident (%p)", ident);
4235 		j->start_pending = true;
4236 		job_dispatch(j, false);
4237 	} else if (&j->exit_timeout == ident) {
4238 		if (!job_assumes(j, j->p != 0)) {
4239 			return;
4240 		}
4241 
4242 		if (j->sent_sigkill) {
4243 			uint64_t td = runtime_get_nanoseconds_since(j->sent_signal_time);
4244 
4245 			td /= NSEC_PER_SEC;
4246 			td -= j->clean_kill ? 0 : j->exit_timeout;
4247 
4248 			job_log(j, LOG_WARNING | LOG_CONSOLE, "Job has not died after being %skilled %zu seconds ago. Simulating exit.", j->clean_kill ? "cleanly " : "", td);
4249 			j->workaround9359725 = true;
4250 
4251 			// This basically has to be done off the main thread. We have no
4252 			// mechanism for draining the main queue in our run loop (like CF
4253 			// does), and the kevent mechanism wants an object to be associated
4254 			// as the callback. So we just create a dispatch source and reap the
4255 			// errant PID whenever we can. Note that it is not safe for us to do
4256 			// any logging in this block, since logging requires exclusive
4257 			// access to global data structures that is only protected by the
4258 			// main thread.
4259 			dispatch_source_t hack_13570156 = dispatch_source_create(DISPATCH_SOURCE_TYPE_PROC, j->p, DISPATCH_PROC_EXIT, dispatch_get_global_queue(0, 0));
4260 			dispatch_source_set_event_handler(hack_13570156, ^{
4261 				pid_t pid = (pid_t)dispatch_source_get_handle(hack_13570156);
4262 
4263 				int status = 0;
4264 				(void)waitpid(pid, &status, 0);
4265 				dispatch_release(hack_13570156);
4266 			});
4267 
4268 			dispatch_resume(hack_13570156);
4269 
4270 			if (launchd_trap_sigkill_bugs) {
4271 				job_log(j, LOG_NOTICE | LOG_CONSOLE, "Trapping into kernel debugger. You can continue the machine after it has been debugged, and shutdown will proceed normally.");
4272 				(void)job_assumes_zero(j, host_reboot(mach_host_self(), HOST_REBOOT_DEBUGGER));
4273 			}
4274 
4275 			struct kevent bogus_exit;
4276 			EV_SET(&bogus_exit, j->p, EVFILT_PROC, 0, NOTE_EXIT, 0, 0);
4277 			jobmgr_callback(j->mgr, &bogus_exit);
4278 		} else {
4279 			if (unlikely(j->debug_before_kill)) {
4280 				job_log(j, LOG_NOTICE, "Exit timeout elapsed. Entering the kernel debugger");
4281 				(void)job_assumes_zero(j, host_reboot(mach_host_self(), HOST_REBOOT_DEBUGGER));
4282 			}
4283 
4284 			job_log(j, LOG_WARNING | LOG_CONSOLE, "Exit timeout elapsed (%u seconds). Killing", j->exit_timeout);
4285 			job_kill(j);
4286 		}
4287 	} else {
4288 		job_log(j, LOG_ERR, "Unrecognized job timer callback: %p", ident);
4289 	}
4290 }
4291 
4292 void
job_callback_read(job_t j,int ident)4293 job_callback_read(job_t j, int ident)
4294 {
4295 	if (ident == j->stdin_fd) {
4296 		job_dispatch(j, true);
4297 	} else {
4298 		socketgroup_callback(j);
4299 	}
4300 }
4301 
4302 void
jobmgr_reap_bulk(jobmgr_t jm,struct kevent * kev)4303 jobmgr_reap_bulk(jobmgr_t jm, struct kevent *kev)
4304 {
4305 	jobmgr_t jmi;
4306 	job_t j;
4307 
4308 	SLIST_FOREACH(jmi, &jm->submgrs, sle) {
4309 		jobmgr_reap_bulk(jmi, kev);
4310 	}
4311 
4312 	if ((j = jobmgr_find_by_pid(jm, (pid_t)kev->ident, false))) {
4313 		kev->udata = j;
4314 		job_callback(j, kev);
4315 	}
4316 }
4317 
4318 void
jobmgr_callback(void * obj,struct kevent * kev)4319 jobmgr_callback(void *obj, struct kevent *kev)
4320 {
4321 	jobmgr_t jm = obj;
4322 
4323 #if TARGET_OS_EMBEDDED
4324 	int flag2check = VQ_MOUNT;
4325 #else
4326 	int flag2check = VQ_UPDATE;
4327 #endif
4328 
4329 	switch (kev->filter) {
4330 	case EVFILT_PROC:
4331 		jobmgr_reap_bulk(jm, kev);
4332 		root_jobmgr = jobmgr_do_garbage_collection(root_jobmgr);
4333 		break;
4334 	case EVFILT_SIGNAL:
4335 		switch (kev->ident) {
4336 		case SIGTERM:
4337 			jobmgr_log(jm, LOG_DEBUG, "Got SIGTERM. Shutting down.");
4338 			return launchd_shutdown();
4339 		case SIGUSR1:
4340 			return calendarinterval_callback();
4341 		case SIGUSR2:
4342 			// Turn on all logging.
4343 			launchd_log_perf = true;
4344 			launchd_log_debug = true;
4345 			launchd_log_shutdown = true;
4346 			/* Hopefully /var is available by this point. If not, uh, oh well.
4347 			 * It's just a debugging facility.
4348 			 */
4349 			return jobmgr_log_perf_statistics(jm, false);
4350 		case SIGINFO:
4351 			return jobmgr_log_perf_statistics(jm, true);
4352 		default:
4353 			jobmgr_log(jm, LOG_ERR, "Unrecognized signal: %lu: %s", kev->ident, strsignal(kev->ident));
4354 		}
4355 		break;
4356 	case EVFILT_FS:
4357 		if (kev->fflags & flag2check) {
4358 			if (!launchd_var_available) {
4359 				struct stat sb;
4360 				if (stat("/var/log", &sb) == 0 && (sb.st_mode & S_IWUSR)) {
4361 					launchd_var_available = true;
4362 				}
4363 			}
4364 		} else if (kev->fflags & VQ_MOUNT) {
4365 			jobmgr_dispatch_all(jm, true);
4366 		}
4367 		jobmgr_dispatch_all_semaphores(jm);
4368 		break;
4369 	case EVFILT_TIMER:
4370 		if (kev->ident == (uintptr_t)&sorted_calendar_events) {
4371 			calendarinterval_callback();
4372 		} else if (kev->ident == (uintptr_t)jm) {
4373 			jobmgr_log(jm, LOG_DEBUG, "Shutdown timer firing.");
4374 			jobmgr_still_alive_with_check(jm);
4375 		} else if (kev->ident == (uintptr_t)&jm->reboot_flags) {
4376 			jobmgr_do_garbage_collection(jm);
4377 		}
4378 		else if (kev->ident == (uintptr_t)&launchd_runtime_busy_time) {
4379 #if 0
4380 			jobmgr_log(jm, LOG_DEBUG, "Idle exit timer fired. Shutting down.");
4381 			if (jobmgr_assumes_zero(jm, runtime_busy_cnt) == 0) {
4382 				return launchd_shutdown();
4383 			}
4384 #endif
4385 #if HAVE_SYSTEMSTATS
4386 		} else if (kev->ident == (uintptr_t)systemstats_timer_callback) {
4387 			systemstats_timer_callback();
4388 #endif
4389 		}
4390 		break;
4391 	case EVFILT_VNODE:
4392 		if (kev->ident == (uintptr_t)s_no_hang_fd) {
4393 			int _no_hang_fd = open("/dev/autofs_nowait", O_EVTONLY | O_NONBLOCK);
4394 			if (unlikely(_no_hang_fd != -1)) {
4395 				jobmgr_log(root_jobmgr, LOG_DEBUG, "/dev/autofs_nowait has appeared!");
4396 				(void)jobmgr_assumes_zero_p(root_jobmgr, kevent_mod((uintptr_t)s_no_hang_fd, EVFILT_VNODE, EV_DELETE, 0, 0, NULL));
4397 				(void)jobmgr_assumes_zero_p(root_jobmgr, runtime_close(s_no_hang_fd));
4398 				s_no_hang_fd = _fd(_no_hang_fd);
4399 			}
4400 		} else if (pid1_magic && launchd_console && kev->ident == (uintptr_t)fileno(launchd_console)) {
4401 			int cfd = -1;
4402 			if (jobmgr_assumes_zero_p(jm, cfd = open(_PATH_CONSOLE, O_WRONLY | O_NOCTTY)) != -1) {
4403 				_fd(cfd);
4404 				if (!(launchd_console = fdopen(cfd, "w"))) {
4405 					(void)jobmgr_assumes_zero(jm, errno);
4406 					(void)close(cfd);
4407 				}
4408 			}
4409 		}
4410 		break;
4411 	default:
4412 		jobmgr_log(jm, LOG_ERR, "Unrecognized kevent filter: %hd", kev->filter);
4413 	}
4414 }
4415 
4416 void
job_callback(void * obj,struct kevent * kev)4417 job_callback(void *obj, struct kevent *kev)
4418 {
4419 	job_t j = obj;
4420 
4421 	job_log(j, LOG_DEBUG, "Dispatching kevent callback.");
4422 
4423 	switch (kev->filter) {
4424 	case EVFILT_PROC:
4425 		return job_callback_proc(j, kev);
4426 	case EVFILT_TIMER:
4427 		return job_callback_timer(j, (void *) kev->ident);
4428 	case EVFILT_READ:
4429 		return job_callback_read(j, (int) kev->ident);
4430 	case EVFILT_MACHPORT:
4431 		return (void)job_dispatch(j, true);
4432 	default:
4433 		job_log(j, LOG_ERR, "Unrecognized job callback filter: %hd", kev->filter);
4434 	}
4435 }
4436 
4437 void
job_start(job_t j)4438 job_start(job_t j)
4439 {
4440 	uint64_t td;
4441 	int spair[2];
4442 	int execspair[2];
4443 	char nbuf[64];
4444 	pid_t c;
4445 	bool sipc = false;
4446 	u_int proc_fflags = NOTE_EXIT|NOTE_FORK|NOTE_EXEC|NOTE_EXIT_DETAIL|NOTE_EXITSTATUS;
4447 
4448 	if (!job_assumes(j, j->mgr != NULL)) {
4449 		return;
4450 	}
4451 
4452 	if (unlikely(job_active(j))) {
4453 		job_log(j, LOG_DEBUG, "Already started");
4454 		return;
4455 	}
4456 
4457 	if (!LIST_EMPTY(&j->mgr->attaches)) {
4458 		job_log(j, LOG_DEBUG, "Looking for attachments for job: %s", j->label);
4459 		(void)waiting4attach_find(j->mgr, j);
4460 	}
4461 
4462 	/*
4463 	 * Some users adjust the wall-clock and then expect software to not notice.
4464 	 * Therefore, launchd must use an absolute clock instead of the wall clock
4465 	 * wherever possible.
4466 	 */
4467 	td = runtime_get_nanoseconds_since(j->start_time);
4468 	td /= NSEC_PER_SEC;
4469 
4470 	if (j->start_time && (td < j->min_run_time) && !j->legacy_mach_job && !j->inetcompat && !j->unthrottle) {
4471 		time_t respawn_delta = j->min_run_time - (uint32_t)td;
4472 		/* We technically should ref-count throttled jobs to prevent idle exit,
4473 		 * but we're not directly tracking the 'throttled' state at the moment.
4474 		 */
4475 		job_log(j, LOG_NOTICE, "Throttling respawn: Will start in %ld seconds", respawn_delta);
4476 		(void)job_assumes_zero_p(j, kevent_mod((uintptr_t)j, EVFILT_TIMER, EV_ADD|EV_ONESHOT, NOTE_SECONDS, respawn_delta, j));
4477 		job_ignore(j);
4478 		return;
4479 	}
4480 
4481 	if (likely(!j->legacy_mach_job)) {
4482 		sipc = ((!SLIST_EMPTY(&j->sockets) || !SLIST_EMPTY(&j->machservices)) && !j->deny_job_creation) || j->embedded_god;
4483 	}
4484 
4485 	if (sipc) {
4486 		(void)job_assumes_zero_p(j, socketpair(AF_UNIX, SOCK_STREAM, 0, spair));
4487 	}
4488 
4489 	(void)job_assumes_zero_p(j, socketpair(AF_UNIX, SOCK_STREAM, 0, execspair));
4490 
4491 	switch (c = runtime_fork(j->weird_bootstrap ? j->j_port : j->mgr->jm_port)) {
4492 	case -1:
4493 		job_log_error(j, LOG_ERR, "fork() failed, will try again in one second");
4494 		(void)job_assumes_zero_p(j, kevent_mod((uintptr_t)j, EVFILT_TIMER, EV_ADD|EV_ONESHOT, NOTE_SECONDS, 1, j));
4495 		job_ignore(j);
4496 
4497 		(void)job_assumes_zero(j, runtime_close(execspair[0]));
4498 		(void)job_assumes_zero(j, runtime_close(execspair[1]));
4499 		if (sipc) {
4500 			(void)job_assumes_zero(j, runtime_close(spair[0]));
4501 			(void)job_assumes_zero(j, runtime_close(spair[1]));
4502 		}
4503 		break;
4504 	case 0:
4505 		if (unlikely(_vproc_post_fork_ping())) {
4506 			syslog(LOG_ERR, "_vproc_post_fork_ping() fail");
4507 			DEBUG_EXIT(EXIT_FAILURE);
4508 		} else
4509 			syslog(LOG_ERR, "_vproc_post_fork_ping() success");
4510 
4511 		(void)job_assumes_zero(j, runtime_close(execspair[0]));
4512 		// wait for our parent to say they've attached a kevent to us
4513 		read(_fd(execspair[1]), &c, sizeof(c));
4514 		if (sipc) {
4515 			(void)job_assumes_zero(j, runtime_close(spair[0]));
4516 			snprintf(nbuf, sizeof(nbuf), "%d", spair[1]);
4517 			setenv(LAUNCHD_TRUSTED_FD_ENV, nbuf, 1);
4518 		}
4519 		job_start_child(j);
4520 		break;
4521 	default:
4522 		j->start_time = runtime_get_opaque_time();
4523 
4524 		job_log(j, LOG_DEBUG, "Started as PID: %u", c);
4525 
4526 		j->did_exec = false;
4527 		j->fpfail = false;
4528 		j->jettisoned = false;
4529 		j->xpcproxy_did_exec = false;
4530 		j->checkedin = false;
4531 		j->start_pending = false;
4532 		j->reaped = false;
4533 		j->crashed = false;
4534 		j->stopped = false;
4535 		j->workaround9359725 = false;
4536 		j->implicit_reap = false;
4537 		j->unthrottle = false;
4538 		if (j->needs_kickoff) {
4539 			j->needs_kickoff = false;
4540 
4541 			if (SLIST_EMPTY(&j->semaphores)) {
4542 				j->ondemand = false;
4543 			}
4544 		}
4545 
4546 		if (j->has_console) {
4547 			launchd_wsp = c;
4548 		}
4549 
4550 		job_log(j, LOG_PERF, "Job started.");
4551 		runtime_add_ref();
4552 		total_children++;
4553 		LIST_INSERT_HEAD(&j->mgr->active_jobs[ACTIVE_JOB_HASH(c)], j, pid_hash_sle);
4554 		LIST_INSERT_HEAD(&managed_actives[ACTIVE_JOB_HASH(c)], j, global_pid_hash_sle);
4555 		j->p = c;
4556 
4557 		struct proc_uniqidentifierinfo info;
4558 		if (proc_pidinfo(c, PROC_PIDUNIQIDENTIFIERINFO, 0, &info, PROC_PIDUNIQIDENTIFIERINFO_SIZE) != 0) {
4559 			// ignore errors here, kevent_mod below will catch them and clean up
4560 			j->uniqueid = info.p_uniqueid;
4561 		}
4562 
4563 		j->mgr->normal_active_cnt++;
4564 		j->fork_fd = _fd(execspair[0]);
4565 		(void)job_assumes_zero(j, runtime_close(execspair[1]));
4566 		if (sipc) {
4567 			(void)job_assumes_zero(j, runtime_close(spair[1]));
4568 			ipc_open(_fd(spair[0]), j);
4569 		}
4570 		if (kevent_mod(c, EVFILT_PROC, EV_ADD, proc_fflags, 0, root_jobmgr ? root_jobmgr : j->mgr) != -1) {
4571 			job_ignore(j);
4572 		} else {
4573 			if (errno == ESRCH) {
4574 				job_log(j, LOG_ERR, "Child was killed before we could attach a kevent.");
4575 			} else {
4576 				(void)job_assumes(j, errno == ESRCH);
4577 			}
4578 			job_reap(j);
4579 
4580 			/* If we have reaped this job within this same run loop pass, then
4581 			 * it will be currently ignored. So if there's a failure to attach a
4582 			 * kevent, we need to make sure that we watch the job so that we can
4583 			 * respawn it.
4584 			 *
4585 			 * See <rdar://problem/10140809>.
4586 			 */
4587 			job_watch(j);
4588 		}
4589 
4590 #if HAVE_SYSTEMSTATS
4591 		if (systemstats_is_enabled()) {
4592 			/* We don't really *need* to make the full rusage call -- it
4593 			 * will be mostly 0s and very small numbers. We only need
4594 			 * ri_proc_start_abstime, because that's how we disambiguiate
4595 			 * PIDs when they wrap around; and the UUID.
4596 			 * In the future we should use the 64-bit process unique ID,
4597 			 * so there's nothing to disambiguiate, and skip the full
4598 			 * rusage call here.
4599 			 *
4600 			 * Well, the future is now.
4601 			 */
4602 			if (_systemstats_get_property(SYSTEMSTATS_API_VERSION, SYSTEMSTATS_WRITER_launchd, SYSTEMSTATS_PROPERTY_LAUNCHD_SHOULD_LOG_JOB_START)) {
4603 				job_log_perf_statistics(j, NULL, -3);
4604 			}
4605 		}
4606 #endif
4607 		j->wait4debugger_oneshot = false;
4608 		if (likely(!j->stall_before_exec)) {
4609 			job_uncork_fork(j);
4610 		}
4611 		break;
4612 	}
4613 }
4614 
4615 void
job_start_child(job_t j)4616 job_start_child(job_t j)
4617 {
4618 	typeof(posix_spawn) *psf;
4619 	const char *file2exec = "/usr/libexec/launchproxy";
4620 	const char **argv;
4621 	posix_spawnattr_t spattr;
4622 	int gflags = GLOB_NOSORT|GLOB_NOCHECK|GLOB_TILDE|GLOB_DOOFFS;
4623 	glob_t g;
4624 	short spflags = POSIX_SPAWN_SETEXEC;
4625 	int psproctype = POSIX_SPAWN_PROC_TYPE_DAEMON_BACKGROUND;
4626 	size_t binpref_out_cnt = 0;
4627 	size_t i;
4628 
4629 	(void)job_assumes_zero(j, posix_spawnattr_init(&spattr));
4630 
4631 	job_setup_attributes(j);
4632 
4633 	bool use_xpcproxy = false;
4634 	struct waiting4attach *w4a = waiting4attach_find(j->mgr, j);
4635 	if (w4a) {
4636 		(void)setenv(XPC_SERVICE_ENV_ATTACHED, "1", 1);
4637 		if (!j->xpc_service) {
4638 			use_xpcproxy = true;
4639 		}
4640 	}
4641 
4642 	if (use_xpcproxy) {
4643 		argv = alloca(3 * sizeof(char *));
4644 		argv[0] = "/usr/libexec/xpcproxy";
4645 		argv[1] = "-debug";
4646 		argv[2] = NULL;
4647 
4648 		file2exec = argv[0];
4649 	} else if (unlikely(j->argv && j->globargv)) {
4650 		g.gl_offs = 1;
4651 		for (i = 0; i < j->argc; i++) {
4652 			if (i > 0) {
4653 				gflags |= GLOB_APPEND;
4654 			}
4655 			if (glob(j->argv[i], gflags, NULL, &g) != 0) {
4656 				job_log_error(j, LOG_ERR, "glob(\"%s\")", j->argv[i]);
4657 				syslog(LOG_ERR, "glob error");
4658 				DEBUG_EXIT(EXIT_FAILURE);
4659 			}
4660 		}
4661 		g.gl_pathv[0] = (char *)file2exec;
4662 		argv = (const char **)g.gl_pathv;
4663 	} else if (likely(j->argv)) {
4664 		argv = alloca((j->argc + 2) * sizeof(char *));
4665 		argv[0] = file2exec;
4666 		for (i = 0; i < j->argc; i++) {
4667 			argv[i + 1] = j->argv[i];
4668 		}
4669 		argv[i + 1] = NULL;
4670 	} else {
4671 		argv = alloca(3 * sizeof(char *));
4672 		argv[0] = file2exec;
4673 		argv[1] = j->prog;
4674 		argv[2] = NULL;
4675 	}
4676 
4677 	if (likely(!(j->inetcompat || use_xpcproxy))) {
4678 		argv++;
4679 	}
4680 
4681 	if (unlikely(j->wait4debugger || j->wait4debugger_oneshot)) {
4682 		if (!j->app) {
4683 			job_log(j, LOG_WARNING, "Spawned and waiting for the debugger to attach before continuing...");
4684 		}
4685 		spflags |= POSIX_SPAWN_START_SUSPENDED;
4686 	}
4687 
4688 #if !TARGET_OS_EMBEDDED
4689 	if (unlikely(j->disable_aslr)) {
4690 		spflags |= _POSIX_SPAWN_DISABLE_ASLR;
4691 	}
4692 #endif
4693 	spflags |= j->pstype;
4694 
4695 	(void)job_assumes_zero(j, posix_spawnattr_setflags(&spattr, spflags));
4696 	if (unlikely(j->j_binpref_cnt)) {
4697 		(void)job_assumes_zero(j, posix_spawnattr_setbinpref_np(&spattr, j->j_binpref_cnt, j->j_binpref, &binpref_out_cnt));
4698 		(void)job_assumes(j, binpref_out_cnt == j->j_binpref_cnt);
4699 	}
4700 
4701 	psproctype = j->psproctype;
4702 	(void)job_assumes_zero(j, posix_spawnattr_setprocesstype_np(&spattr, psproctype));
4703 
4704 #if TARGET_OS_EMBEDDED
4705 	/* Set jetsam attributes. POSIX_SPAWN_JETSAM_USE_EFFECTIVE_PRIORITY guards
4706 	 * against a race which arises if, during spawn, an initial jetsam property
4707 	 * update occurs before the values below are applied. In this case, the flag
4708 	 * ensures that the subsequent change is ignored; the explicit update should
4709 	 * be given priority.
4710 	 */
4711 	(void)job_assumes_zero(j, posix_spawnattr_setjetsam(&spattr,
4712 	        POSIX_SPAWN_JETSAM_USE_EFFECTIVE_PRIORITY | (j->jetsam_memory_limit_background ? POSIX_SPAWN_JETSAM_HIWATER_BACKGROUND : 0),
4713 	        j->jetsam_priority, j->jetsam_memlimit));
4714 #endif
4715 
4716 #ifdef notyet
4717 	/* XXX: not yet: https://bugs.freenas.org/issues/10186 */
4718 	mach_port_array_t sports = NULL;
4719 	mach_msg_type_number_t sports_cnt = 0;
4720 	kern_return_t kr = vproc_mig_get_listener_port_rights(bootstrap_port, &sports, &sports_cnt);
4721 	if (kr == 0 && sports_cnt) {
4722 		/* For some reason, this SPI takes a count as a signed quantity. */
4723 		(void)posix_spawnattr_set_importancewatch_port_np(&spattr, (int)sports_cnt, sports);
4724 
4725 		/* All "count" parameters in MIG are counts of the array. So an array of
4726 		 * mach_port_t containing 10 elements will have a count of ten, but it
4727 		 * will occupy 40 bytes. So we must do the multiplication here to pass
4728 		 * the correct size.
4729 		 *
4730 		 * Note that we do NOT release the send rights. We need them to be valid
4731 		 * at the time they are passed to posix_spawn(2). When we exec(3) using
4732 		 * posix_spawn(2), they'll be cleaned up anyway.
4733 		 */
4734 		mig_deallocate((vm_address_t)sports, sports_cnt * sizeof(sports[0]));
4735 	} else if (kr != BOOTSTRAP_UNKNOWN_SERVICE) {
4736 		(void)job_assumes_zero(j, kr);
4737 	}
4738 #endif
4739 
4740 #if TARGET_OS_EMBEDDED
4741 	if (!j->app || j->system_app) {
4742 		(void)job_assumes_zero(j, posix_spawnattr_setcpumonitor_default(&spattr));
4743 	}
4744 #else
4745 	(void)job_assumes_zero(j, posix_spawnattr_setcpumonitor_default(&spattr));
4746 #endif
4747 
4748 #if 0
4749 #if !TARGET_OS_EMBEDDED
4750 	struct task_qos_policy qosinfo = {
4751 		.task_latency_qos_tier = LATENCY_QOS_LAUNCH_DEFAULT_TIER,
4752 		.task_throughput_qos_tier = THROUGHPUT_QOS_LAUNCH_DEFAULT_TIER,
4753 	};
4754 
4755 	if (!j->legacy_timers) {
4756 		kr = task_policy_set(mach_task_self(), TASK_BASE_QOS_POLICY, (task_policy_t)&qosinfo, TASK_QOS_POLICY_COUNT);
4757 		(void)job_assumes_zero_p(j, kr);
4758 	}
4759 #endif
4760 #endif
4761 
4762 #if HAVE_RESPONSIBILITY
4763 	/* Specify which process is responsible for the new job.  Per-app XPC
4764 	 * services are the responsibility of the app.  Other processes are
4765 	 * responsible for themselves.  This decision is final and also applies
4766 	 * to the process's children, so don't initialize responsibility when
4767 	 * starting a per-user launchd.
4768 	 */
4769 	if (j->mgr->req_pid) {
4770 		responsibility_init2(j->mgr->req_pid, NULL);
4771 	} else if (!j->per_user) {
4772 		responsibility_init2(getpid(), j->prog ? j->prog : j->argv[0]);
4773 	}
4774 #endif
4775 
4776 #if HAVE_QUARANTINE
4777 	if (j->quarantine_data) {
4778 		qtn_proc_t qp;
4779 
4780 		if (job_assumes(j, qp = qtn_proc_alloc())) {
4781 			if (job_assumes_zero(j, qtn_proc_init_with_data(qp, j->quarantine_data, j->quarantine_data_sz) == 0)) {
4782 				(void)job_assumes_zero(j, qtn_proc_apply_to_self(qp));
4783 			}
4784 		}
4785 	}
4786 #endif
4787 
4788 #if HAVE_SANDBOX
4789 #if TARGET_OS_EMBEDDED
4790 	struct sandbox_spawnattrs sbattrs;
4791 	if (j->seatbelt_profile || j->container_identifier) {
4792 		sandbox_spawnattrs_init(&sbattrs);
4793 		if (j->seatbelt_profile) {
4794 			sandbox_spawnattrs_setprofilename(&sbattrs, j->seatbelt_profile);
4795 		}
4796 		if (j->container_identifier) {
4797 			sandbox_spawnattrs_setcontainer(&sbattrs, j->container_identifier);
4798 		}
4799 		(void)job_assumes_zero(j, posix_spawnattr_setmacpolicyinfo_np(&spattr, "Sandbox", &sbattrs, sizeof(sbattrs)));
4800 	}
4801 #else
4802 	if (j->seatbelt_profile) {
4803 		char *seatbelt_err_buf = NULL;
4804 
4805 		if (job_assumes_zero_p(j, sandbox_init(j->seatbelt_profile, j->seatbelt_flags, &seatbelt_err_buf)) == -1) {
4806 			if (seatbelt_err_buf) {
4807 				job_log(j, LOG_ERR, "Sandbox failed to init: %s", seatbelt_err_buf);
4808 			}
4809 			goto out_bad;
4810 		}
4811 	}
4812 #endif
4813 #endif
4814 
4815 	psf = j->prog ? posix_spawn : posix_spawnp;
4816 
4817 	if (likely(!(j->inetcompat || use_xpcproxy))) {
4818 		file2exec = j->prog ? j->prog : argv[0];
4819 	}
4820 
4821 	errno = psf(NULL, file2exec, NULL, &spattr, (char *const *)argv, environ);
4822 	syslog(LOG_ERR, "job_start failed %s\n", strerror(errno));
4823 	sleep(20);
4824 
4825 #if HAVE_SANDBOX && !TARGET_OS_EMBEDDED
4826 out_bad:
4827 #endif
4828 	syslog(LOG_ERR, "errno=%d", errno);
4829 	DEBUG_EXIT(errno);
4830 }
4831 
4832 void
jobmgr_export_env_from_other_jobs(jobmgr_t jm,launch_data_t dict)4833 jobmgr_export_env_from_other_jobs(jobmgr_t jm, launch_data_t dict)
4834 {
4835 	launch_data_t tmp;
4836 	struct envitem *ei;
4837 	job_t ji;
4838 
4839 	if (jm->parentmgr) {
4840 		jobmgr_export_env_from_other_jobs(jm->parentmgr, dict);
4841 	} else {
4842 		char **tmpenviron = environ;
4843 		for (; *tmpenviron; tmpenviron++) {
4844 			char envkey[1024];
4845 			launch_data_t s = launch_data_alloc(LAUNCH_DATA_STRING);
4846 			launch_data_set_string(s, strchr(*tmpenviron, '=') + 1);
4847 			strncpy(envkey, *tmpenviron, sizeof(envkey));
4848 			*(strchr(envkey, '=')) = '\0';
4849 			launch_data_dict_insert(dict, s, envkey);
4850 		}
4851 	}
4852 
4853 	LIST_FOREACH(ji, &jm->jobs, sle) {
4854 		SLIST_FOREACH(ei, &ji->global_env, sle) {
4855 			if ((tmp = launch_data_new_string(ei->value))) {
4856 				launch_data_dict_insert(dict, tmp, ei->key);
4857 			}
4858 		}
4859 	}
4860 }
4861 
4862 void
jobmgr_setup_env_from_other_jobs(jobmgr_t jm)4863 jobmgr_setup_env_from_other_jobs(jobmgr_t jm)
4864 {
4865 	struct envitem *ei;
4866 	job_t ji;
4867 
4868 	if (jm->parentmgr) {
4869 		jobmgr_setup_env_from_other_jobs(jm->parentmgr);
4870 	}
4871 
4872 	LIST_FOREACH(ji, &jm->global_env_jobs, global_env_sle) {
4873 		SLIST_FOREACH(ei, &ji->global_env, sle) {
4874 			setenv(ei->key, ei->value, 1);
4875 		}
4876 	}
4877 }
4878 
4879 void
job_log_pids_with_weird_uids(job_t j)4880 job_log_pids_with_weird_uids(job_t j)
4881 {
4882 	size_t len = sizeof(pid_t) * get_kern_max_proc();
4883 	pid_t *pids = NULL;
4884 	uid_t u = j->mach_uid;
4885 	int i = 0, kp_cnt = 0;
4886 
4887 	if (!launchd_apple_internal) {
4888 		return;
4889 	}
4890 
4891 	pids = malloc(len);
4892 	if (!job_assumes(j, pids != NULL)) {
4893 		return;
4894 	}
4895 
4896 	runtime_ktrace(RTKT_LAUNCHD_FINDING_WEIRD_UIDS, j->p, u, 0);
4897 
4898 	/* libproc actually has some serious performance drawbacks when used over sysctl(3) in
4899 	 * scenarios like this. Whereas sysctl(3) can give us back all the kinfo_proc's in
4900 	 * one kernel call, libproc requires that we get a list of PIDs we're interested in
4901 	 * (in this case, all PIDs on the system) and then get a single proc_bsdshortinfo
4902 	 * struct back in a single call for each one.
4903 	 *
4904 	 * This kind of thing is also more inherently racy than sysctl(3). While sysctl(3)
4905 	 * returns a snapshot, it returns the whole shebang at once. Any PIDs given to us by
4906 	 * libproc could go stale before we call proc_pidinfo().
4907 	 *
4908 	 * Note that proc_list*() APIs return the number of PIDs given back, not the number
4909 	 * of bytes written to the buffer.
4910 	 */
4911 	if (job_assumes_zero_p(j, (kp_cnt = proc_listallpids(pids, len))) == -1) {
4912 		goto out;
4913 	}
4914 
4915 	for (i = 0; i < kp_cnt; i++) {
4916 		struct proc_bsdshortinfo proc;
4917 		/* We perhaps should not log a bug here if we get ESRCH back, due to the race
4918 		 * detailed above.
4919 		 */
4920 		if (proc_pidinfo(pids[i], PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0) {
4921 			if (errno != ESRCH) {
4922 				(void)job_assumes_zero(j, errno);
4923 			}
4924 			continue;
4925 		}
4926 
4927 		uid_t i_euid = proc.pbsi_uid;
4928 		uid_t i_uid = proc.pbsi_ruid;
4929 		uid_t i_svuid = proc.pbsi_svuid;
4930 		pid_t i_pid = pids[i];
4931 
4932 		if (i_euid != u && i_uid != u && i_svuid != u) {
4933 			continue;
4934 		}
4935 
4936 		job_log(j, LOG_ERR, "PID %u \"%s\" has no account to back it! Real/effective/saved UIDs: %u/%u/%u", i_pid, proc.pbsi_comm, i_uid, i_euid, i_svuid);
4937 
4938 // Temporarily disabled due to 5423935 and 4946119.
4939 #if 0
4940 		// Ask the accountless process to exit.
4941 		(void)job_assumes_zero_p(j, kill2(i_pid, SIGTERM));
4942 #endif
4943 	}
4944 
4945 out:
4946 	free(pids);
4947 }
4948 
4949 static struct passwd *
job_getpwnam(job_t j,const char * name)4950 job_getpwnam(job_t j, const char *name)
4951 {
4952 	/*
4953 	 * methodology for system daemons
4954 	 *
4955 	 * first lookup user record without any opendirectoryd interaction,
4956 	 * we don't know what interprocess dependencies might be in flight.
4957 	 * if that fails, we re-enable opendirectoryd interaction and
4958 	 * re-issue the lookup.  We have to disable the libinfo L1 cache
4959 	 * otherwise libinfo will return the negative cache entry on the retry
4960 	 */
4961 #if !TARGET_OS_EMBEDDED
4962 	struct passwd *pw = NULL;
4963 
4964 	if (pid1_magic && j->mgr == root_jobmgr) {
4965 		// 1 == SEARCH_MODULE_FLAG_DISABLED
4966 		si_search_module_set_flags("ds", 1);
4967 		gL1CacheEnabled = false;
4968 
4969 		pw = getpwnam(name);
4970 		si_search_module_set_flags("ds", 0);
4971 	}
4972 
4973 	if (pw == NULL) {
4974 		pw = getpwnam(name);
4975 	}
4976 
4977 	return pw;
4978 #else
4979 #pragma unused (j)
4980 	return getpwnam(name);
4981 #endif
4982 }
4983 
4984 static struct group *
job_getgrnam(job_t j,const char * name)4985 job_getgrnam(job_t j, const char *name)
4986 {
4987 #if !TARGET_OS_EMBEDDED
4988     struct group *gr = NULL;
4989 
4990     if (pid1_magic && j->mgr == root_jobmgr) {
4991         si_search_module_set_flags("ds", 1);
4992         gL1CacheEnabled = false;
4993 
4994         gr = getgrnam(name);
4995 
4996         si_search_module_set_flags("ds", 0);
4997     }
4998 
4999     if (gr == NULL) {
5000         gr = getgrnam(name);
5001     }
5002 
5003     return gr;
5004 #else
5005 #pragma unused (j)
5006     return getgrnam(name);
5007 #endif
5008 }
5009 
5010 void
job_postfork_test_user(job_t j)5011 job_postfork_test_user(job_t j)
5012 {
5013 	// This function is all about 5201578
5014 
5015 	const char *home_env_var = getenv("HOME");
5016 	const char *user_env_var = getenv("USER");
5017 	const char *logname_env_var = getenv("LOGNAME");
5018 	uid_t tmp_uid, local_uid = getuid();
5019 	gid_t tmp_gid, local_gid = getgid();
5020 	char shellpath[PATH_MAX];
5021 	char homedir[PATH_MAX];
5022 	char loginname[2000];
5023 	struct passwd *pwe;
5024 
5025 
5026 	if (!job_assumes(j, home_env_var && user_env_var && logname_env_var
5027 				&& strcmp(user_env_var, logname_env_var) == 0)) {
5028 		goto out_bad;
5029 	}
5030 
5031 	if ((pwe = job_getpwnam(j, user_env_var)) == NULL) {
5032 		job_log(j, LOG_ERR, "The account \"%s\" has been deleted out from under us!", user_env_var);
5033 		goto out_bad;
5034 	}
5035 
5036 	/*
5037 	 * We must copy the results of getpw*().
5038 	 *
5039 	 * Why? Because subsequent API calls may call getpw*() as a part of
5040 	 * their implementation. Since getpw*() returns a [now thread scoped]
5041 	 * global, we must therefore cache the results before continuing.
5042 	 */
5043 
5044 	tmp_uid = pwe->pw_uid;
5045 	tmp_gid = pwe->pw_gid;
5046 
5047 	strlcpy(shellpath, pwe->pw_shell, sizeof(shellpath));
5048 	strlcpy(loginname, pwe->pw_name, sizeof(loginname));
5049 	strlcpy(homedir, pwe->pw_dir, sizeof(homedir));
5050 
5051 	if (strcmp(loginname, logname_env_var) != 0) {
5052 		job_log(j, LOG_ERR, "The %s environmental variable changed out from under us!", "USER");
5053 		goto out_bad;
5054 	}
5055 	if (strcmp(homedir, home_env_var) != 0) {
5056 		job_log(j, LOG_ERR, "The %s environmental variable changed out from under us!", "HOME");
5057 		goto out_bad;
5058 	}
5059 	if (local_uid != tmp_uid) {
5060 		job_log(j, LOG_ERR, "The %cID of the account (%u) changed out from under us (%u)!",
5061 				'U', tmp_uid, local_uid);
5062 		goto out_bad;
5063 	}
5064 	if (local_gid != tmp_gid) {
5065 		job_log(j, LOG_ERR, "The %cID of the account (%u) changed out from under us (%u)!",
5066 				'G', tmp_gid, local_gid);
5067 		goto out_bad;
5068 	}
5069 
5070 	return;
5071 out_bad:
5072 #if 0
5073 	(void)job_assumes_zero_p(j, kill2(getppid(), SIGTERM));
5074 	DEBUG_EXIT(EXIT_FAILURE);
5075 #else
5076 	job_log(j, LOG_WARNING, "In a future build of the OS, this error will be fatal.");
5077 #endif
5078 }
5079 
5080 void
job_postfork_become_user(job_t j)5081 job_postfork_become_user(job_t j)
5082 {
5083 	char loginname[2000];
5084 	char tmpdirpath[PATH_MAX];
5085 	char shellpath[PATH_MAX];
5086 	char homedir[PATH_MAX];
5087 	struct passwd *pwe;
5088 	size_t r;
5089 	gid_t desired_gid = -1;
5090 	uid_t desired_uid = -1;
5091 
5092 	if (getuid() != 0) {
5093 		return job_postfork_test_user(j);
5094 	}
5095 
5096 	/*
5097 	 * I contend that having UID == 0 and GID != 0 is of dubious value.
5098 	 * Nevertheless, this used to work in Tiger. See: 5425348
5099 	 */
5100 	if (j->groupname && !j->username) {
5101 		j->username = strdup("root");
5102 	}
5103 
5104 	if (j->username) {
5105 		if ((pwe = job_getpwnam(j, j->username)) == NULL) {
5106 			job_log(j, LOG_ERR, "getpwnam(\"%s\") failed", j->username);
5107 			DEBUG_EXIT(ESRCH);
5108 		}
5109 	} else if (j->mach_uid) {
5110 		if ((pwe = getpwuid(j->mach_uid)) == NULL) {
5111 			job_log(j, LOG_ERR, "getpwuid(\"%u\") failed", j->mach_uid);
5112 			job_log_pids_with_weird_uids(j);
5113 			DEBUG_EXIT(ESRCH);
5114 		}
5115 	} else {
5116 		return;
5117 	}
5118 
5119 	/*
5120 	 * We must copy the results of getpw*().
5121 	 *
5122 	 * Why? Because subsequent API calls may call getpw*() as a part of
5123 	 * their implementation. Since getpw*() returns a [now thread scoped]
5124 	 * global, we must therefore cache the results before continuing.
5125 	 */
5126 
5127 	desired_uid = pwe->pw_uid;
5128 	desired_gid = pwe->pw_gid;
5129 
5130 	strlcpy(shellpath, pwe->pw_shell, sizeof(shellpath));
5131 	strlcpy(loginname, pwe->pw_name, sizeof(loginname));
5132 	strlcpy(homedir, pwe->pw_dir, sizeof(homedir));
5133 
5134 	if (unlikely(pwe->pw_expire && time(NULL) >= pwe->pw_expire)) {
5135 		job_log(j, LOG_ERR, "Expired account");
5136 		DEBUG_EXIT(EXIT_FAILURE);
5137 	}
5138 
5139 
5140 	if (unlikely(j->username && strcmp(j->username, loginname) != 0)) {
5141 		job_log(j, LOG_WARNING, "Suspicious setup: User \"%s\" maps to user: %s", j->username, loginname);
5142 	} else if (unlikely(j->mach_uid && (j->mach_uid != desired_uid))) {
5143 		job_log(j, LOG_WARNING, "Suspicious setup: UID %u maps to UID %u", j->mach_uid, desired_uid);
5144 	}
5145 
5146 	if (j->groupname) {
5147 		struct group *gre;
5148 
5149 		if (unlikely((gre = job_getgrnam(j, j->groupname)) == NULL)) {
5150 			job_log(j, LOG_ERR, "getgrnam(\"%s\") failed", j->groupname);
5151 			DEBUG_EXIT(ESRCH);
5152 		}
5153 
5154 		desired_gid = gre->gr_gid;
5155 	}
5156 
5157 	if (job_assumes_zero_p(j, setlogin(loginname)) == -1) {
5158 		DEBUG_EXIT(EXIT_FAILURE);
5159 	}
5160 
5161 	if (job_assumes_zero_p(j, setgid(desired_gid)) == -1) {
5162 		DEBUG_EXIT(EXIT_FAILURE);
5163 	}
5164 
5165 	/*
5166 	 * The kernel team and the DirectoryServices team want initgroups()
5167 	 * called after setgid(). See 4616864 for more information.
5168 	 */
5169 
5170 	if (likely(!j->no_init_groups)) {
5171 #if 1
5172 		if (job_assumes_zero_p(j, initgroups(loginname, desired_gid)) == -1) {
5173 			DEBUG_EXIT(EXIT_FAILURE);
5174 		}
5175 #else
5176 		/* Do our own little initgroups(). We do this to guarantee that we're
5177 		 * always opted into dynamic group resolution in the kernel. initgroups(3)
5178 		 * does not make this guarantee.
5179 		 */
5180 		int groups[NGROUPS], ngroups;
5181 
5182 		// A failure here isn't fatal, and we'll still get data we can use.
5183 		(void)job_assumes_zero_p(j, getgrouplist(j->username, desired_gid, groups, &ngroups));
5184 
5185 		if (job_assumes_zero_p(j, syscall(SYS_initgroups, ngroups, groups, desired_uid)) == -1) {
5186 			DEBUG_EXIT(EXIT_FAILURE);
5187 		}
5188 #endif
5189 	}
5190 
5191 	if (job_assumes_zero_p(j, setuid(desired_uid)) == -1) {
5192 		DEBUG_EXIT(EXIT_FAILURE);
5193 	}
5194 
5195 	r = confstr(_CS_DARWIN_USER_TEMP_DIR, tmpdirpath, sizeof(tmpdirpath));
5196 
5197 	if (likely(r > 0 && r < sizeof(tmpdirpath))) {
5198 		setenv("TMPDIR", tmpdirpath, 0);
5199 	}
5200 
5201 	setenv("SHELL", shellpath, 0);
5202 	setenv("HOME", homedir, 0);
5203 	setenv("USER", loginname, 0);
5204 	setenv("LOGNAME", loginname, 0);
5205 }
5206 
5207 void
job_setup_attributes(job_t j)5208 job_setup_attributes(job_t j)
5209 {
5210 	struct limititem *li;
5211 	struct envitem *ei;
5212 
5213 	if (unlikely(j->setnice)) {
5214 		(void)job_assumes_zero_p(j, setpriority(PRIO_PROCESS, 0, j->nice));
5215 	}
5216 
5217 	SLIST_FOREACH(li, &j->limits, sle) {
5218 		struct rlimit rl;
5219 
5220 		if (job_assumes_zero_p(j, getrlimit(li->which, &rl) == -1)) {
5221 			continue;
5222 		}
5223 
5224 		if (li->sethard) {
5225 			rl.rlim_max = li->lim.rlim_max;
5226 		}
5227 		if (li->setsoft) {
5228 			rl.rlim_cur = li->lim.rlim_cur;
5229 		}
5230 
5231 		if (setrlimit(li->which, &rl) == -1) {
5232 			job_log_error(j, LOG_WARNING, "setrlimit()");
5233 		}
5234 	}
5235 
5236 	if (unlikely(!j->inetcompat && j->session_create)) {
5237 		launchd_SessionCreate();
5238 	}
5239 
5240 	if (unlikely(j->low_pri_io)) {
5241 		(void)job_assumes_zero_p(j, setiopolicy_np(IOPOL_TYPE_DISK, IOPOL_SCOPE_PROCESS, IOPOL_THROTTLE));
5242 	}
5243 	if (j->low_priority_background_io) {
5244 		(void)job_assumes_zero_p(j, setiopolicy_np(IOPOL_TYPE_DISK, IOPOL_SCOPE_DARWIN_BG, IOPOL_THROTTLE));
5245 	}
5246 	if (unlikely(j->rootdir)) {
5247 		(void)job_assumes_zero_p(j, chroot(j->rootdir));
5248 		(void)job_assumes_zero_p(j, chdir("."));
5249 	}
5250 
5251 	job_postfork_become_user(j);
5252 
5253 	if (unlikely(j->workingdir)) {
5254 		if (chdir(j->workingdir) == -1) {
5255 			if (errno == ENOENT || errno == ENOTDIR) {
5256 				job_log(j, LOG_ERR, "Job specified non-existent working directory: %s", j->workingdir);
5257 			} else {
5258 				(void)job_assumes_zero(j, errno);
5259 			}
5260 		}
5261 	}
5262 
5263 	if (unlikely(j->setmask)) {
5264 		umask(j->mask);
5265 	}
5266 
5267 	if (j->stdin_fd) {
5268 		(void)job_assumes_zero_p(j, dup2(j->stdin_fd, STDIN_FILENO));
5269 	} else {
5270 		job_setup_fd(j, STDIN_FILENO, j->stdinpath, O_RDONLY|O_CREAT);
5271 	}
5272 	job_setup_fd(j, STDOUT_FILENO, j->stdoutpath, O_WRONLY|O_CREAT|O_APPEND);
5273 	job_setup_fd(j, STDERR_FILENO, j->stderrpath, O_WRONLY|O_CREAT|O_APPEND);
5274 
5275 	jobmgr_setup_env_from_other_jobs(j->mgr);
5276 
5277 	SLIST_FOREACH(ei, &j->env, sle) {
5278 		setenv(ei->key, ei->value, 1);
5279 	}
5280 
5281 #if !TARGET_OS_EMBEDDED
5282 	if (j->jetsam_properties) {
5283 		(void)job_assumes_zero(j, proc_setpcontrol(PROC_SETPC_TERMINATE));
5284 	}
5285 #endif
5286 
5287 #if TARGET_OS_EMBEDDED
5288 	if (j->main_thread_priority != 0) {
5289 		struct sched_param params;
5290 		bzero(&params, sizeof(params));
5291 		params.sched_priority = j->main_thread_priority;
5292 		(void)job_assumes_zero_p(j, pthread_setschedparam(pthread_self(), SCHED_OTHER, &params));
5293 	}
5294 #endif
5295 
5296 	/*
5297 	 * We'd like to call setsid() unconditionally, but we have reason to
5298 	 * believe that prevents launchd from being able to send signals to
5299 	 * setuid children. We'll settle for process-groups.
5300 	 */
5301 	if (getppid() != 1) {
5302 		(void)job_assumes_zero_p(j, setpgid(0, 0));
5303 	} else {
5304 		(void)job_assumes_zero_p(j, setsid());
5305 	}
5306 }
5307 
5308 void
job_setup_fd(job_t j,int target_fd,const char * path,int flags)5309 job_setup_fd(job_t j, int target_fd, const char *path, int flags)
5310 {
5311 	int fd;
5312 
5313 	if (!path) {
5314 		return;
5315 	}
5316 
5317 	if ((fd = open(path, flags|O_NOCTTY, DEFFILEMODE)) == -1) {
5318 		job_log_error(j, LOG_WARNING, "open(\"%s\", ...)", path);
5319 		return;
5320 	}
5321 
5322 	(void)job_assumes_zero_p(j, dup2(fd, target_fd));
5323 	(void)job_assumes_zero(j, runtime_close(fd));
5324 }
5325 
5326 void
calendarinterval_setalarm(job_t j,struct calendarinterval * ci)5327 calendarinterval_setalarm(job_t j, struct calendarinterval *ci)
5328 {
5329 	struct calendarinterval *ci_iter, *ci_prev = NULL;
5330 	time_t later, head_later;
5331 
5332 	later = cronemu(ci->when.tm_mon, ci->when.tm_mday, ci->when.tm_hour, ci->when.tm_min);
5333 
5334 	if (ci->when.tm_wday != -1) {
5335 		time_t otherlater = cronemu_wday(ci->when.tm_wday, ci->when.tm_hour, ci->when.tm_min);
5336 
5337 		if (ci->when.tm_mday == -1) {
5338 			later = otherlater;
5339 		} else {
5340 			later = later < otherlater ? later : otherlater;
5341 		}
5342 	}
5343 
5344 	ci->when_next = later;
5345 
5346 	LIST_FOREACH(ci_iter, &sorted_calendar_events, global_sle) {
5347 		if (ci->when_next < ci_iter->when_next) {
5348 			LIST_INSERT_BEFORE(ci_iter, ci, global_sle);
5349 			break;
5350 		}
5351 
5352 		ci_prev = ci_iter;
5353 	}
5354 
5355 	if (ci_iter == NULL) {
5356 		// ci must want to fire after every other timer, or there are no timers
5357 
5358 		if (LIST_EMPTY(&sorted_calendar_events)) {
5359 			LIST_INSERT_HEAD(&sorted_calendar_events, ci, global_sle);
5360 		} else {
5361 			LIST_INSERT_AFTER(ci_prev, ci, global_sle);
5362 		}
5363 	}
5364 
5365 	head_later = LIST_FIRST(&sorted_calendar_events)->when_next;
5366 
5367 	if (job_assumes_zero_p(j, kevent_mod((uintptr_t)&sorted_calendar_events, EVFILT_TIMER, EV_ADD, NOTE_ABSOLUTE|NOTE_SECONDS, head_later, root_jobmgr)) != -1) {
5368 		char time_string[100];
5369 		size_t time_string_len;
5370 
5371 		ctime_r(&later, time_string);
5372 		time_string_len = strlen(time_string);
5373 
5374 		if (likely(time_string_len && time_string[time_string_len - 1] == '\n')) {
5375 			time_string[time_string_len - 1] = '\0';
5376 		}
5377 
5378 		job_log(j, LOG_INFO, "Scheduled to run again at %s", time_string);
5379 	}
5380 }
5381 
5382 bool
jobmgr_log_bug(_SIMPLE_STRING asl_message,void * ctx,const char * message)5383 jobmgr_log_bug(_SIMPLE_STRING asl_message __attribute__((unused)), void *ctx, const char *message)
5384 {
5385 	jobmgr_t jm = ctx;
5386 	jobmgr_log(jm, LOG_ERR, "%s", message);
5387 
5388 	return true;
5389 }
5390 
5391 bool
job_log_bug(_SIMPLE_STRING asl_message,void * ctx,const char * message)5392 job_log_bug(_SIMPLE_STRING asl_message __attribute__((unused)), void *ctx, const char *message)
5393 {
5394 	job_t j = ctx;
5395 	job_log(j, LOG_ERR, "%s", message);
5396 
5397 	return true;
5398 }
5399 
5400 // ri: NULL = please sample j->p; non-NULL = use this sample
5401 void
job_log_perf_statistics(job_t j,struct rusage_info_v1 * ri,int64_t exit_status)5402 job_log_perf_statistics(job_t j, struct rusage_info_v1 *ri, int64_t exit_status)
5403 {
5404 #if HAVE_SYSTEMSTATS
5405 	if (j->anonymous || !j->p) {
5406 		return;
5407 	}
5408 	if (!systemstats_is_enabled()) {
5409 		return;
5410 	}
5411 	const char *name;
5412 	if (j->cfbundleidentifier) {
5413 		name = j->cfbundleidentifier;
5414 	} else {
5415 		name = j->label;
5416 	}
5417 	int r = 0;
5418 	struct rusage_info_v1 ris;
5419 	if (ri == NULL) {
5420 		ri = &ris;
5421 		r = proc_pid_rusage(j->p, RUSAGE_INFO_V1, (rusage_info_t)ri);
5422 	}
5423 	if (r == -1) {
5424 		return;
5425 	}
5426 	job_log_systemstats(j->p, j->uniqueid, runtime_get_uniqueid(), j->mgr->req_pid, j->mgr->req_uniqueid, name, ri, exit_status);
5427 #else
5428 #pragma unused (j, ri, exit_status)
5429 #endif
5430 }
5431 
5432 #if HAVE_SYSTEMSTATS
5433 // ri: NULL = don't write fields from ri; non-NULL = use this sample
5434 static
5435 void
job_log_systemstats(pid_t pid,uint64_t uniqueid,uint64_t parent_uniqueid,pid_t req_pid,uint64_t req_uniqueid,const char * name,struct rusage_info_v1 * ri,int64_t exit_status)5436 job_log_systemstats(pid_t pid, uint64_t uniqueid, uint64_t parent_uniqueid, pid_t req_pid, uint64_t req_uniqueid, const char *name, struct rusage_info_v1 *ri, int64_t exit_status)
5437 {
5438 	if (!systemstats_is_enabled()) {
5439 		return;
5440 	}
5441 
5442 	struct systemstats_process_usage_s info;
5443 	bzero(&info, sizeof(info));
5444 	info.name = name;
5445 	info.pid = pid;
5446 	info.exit_status = exit_status;
5447 	info.uid = getuid();
5448 	info.ppid = getpid();
5449 	info.responsible_pid = req_pid;
5450 
5451 	if (likely(ri)) {
5452 		info.macho_uuid = (const uint8_t *)&ri->ri_uuid;
5453 		info.user_time = ri->ri_user_time;
5454 		info.system_time = ri->ri_system_time;
5455 		info.pkg_idle_wkups = ri->ri_pkg_idle_wkups;
5456 		info.interrupt_wkups = ri->ri_interrupt_wkups;
5457 		info.proc_start_abstime = ri->ri_proc_start_abstime;
5458 		info.proc_exit_abstime = ri->ri_proc_exit_abstime;
5459 #if SYSTEMSTATS_API_VERSION >= 20130319
5460 		info.pageins = ri->ri_pageins;
5461 		info.wired_size = ri->ri_wired_size;
5462 		info.resident_size = ri->ri_resident_size;
5463 		info.phys_footprint = ri->ri_phys_footprint;
5464 		// info.purgeablesize = ???
5465 #endif
5466 #if SYSTEMSTATS_API_VERSION >= 20130328
5467 		info.child_user_time = ri->ri_child_user_time;
5468 		info.child_system_time = ri->ri_child_system_time;
5469 		info.child_pkg_idle_wkups = ri->ri_child_pkg_idle_wkups;
5470 		info.child_interrupt_wkups = ri->ri_child_interrupt_wkups;
5471 		info.child_pageins = ri->ri_child_pageins;
5472 		info.child_elapsed_abstime = ri->ri_child_elapsed_abstime;
5473 #endif
5474 	}
5475 #if SYSTEMSTATS_API_VERSION >= 20130410
5476 	info.uniqueid = uniqueid;
5477 	info.parent_uniqueid = parent_uniqueid;
5478 	info.responsible_uniqueid = req_uniqueid;
5479 #endif
5480 	systemstats_write_process_usage(&info);
5481 }
5482 #endif /* HAVE_SYSTEMSTATS */
5483 
5484 struct waiting4attach *
waiting4attach_new(jobmgr_t jm,const char * name,mach_port_t port,pid_t dest,xpc_service_type_t type)5485 waiting4attach_new(jobmgr_t jm, const char *name, mach_port_t port, pid_t dest, xpc_service_type_t type)
5486 {
5487 	size_t xtra = strlen(name) + 1;
5488 
5489 	struct waiting4attach *w4a = malloc(sizeof(*w4a) + xtra);
5490 	if (!w4a) {
5491 		return NULL;
5492 	}
5493 
5494 	w4a->port = port;
5495 	w4a->dest = dest;
5496 	w4a->type = type;
5497 	(void)strcpy(w4a->name, name);
5498 
5499 	if (dest) {
5500 		LIST_INSERT_HEAD(&_launchd_domain_waiters, w4a, le);
5501 	} else {
5502 		LIST_INSERT_HEAD(&jm->attaches, w4a, le);
5503 	}
5504 
5505 
5506 	(void)jobmgr_assumes_zero(jm, launchd_mport_notify_req(port, MACH_NOTIFY_DEAD_NAME));
5507 	return w4a;
5508 }
5509 
5510 void
waiting4attach_delete(jobmgr_t jm,struct waiting4attach * w4a)5511 waiting4attach_delete(jobmgr_t jm, struct waiting4attach *w4a)
5512 {
5513 	jobmgr_log(jm, LOG_DEBUG, "Canceling dead-name notification for waiter port: 0x%x", w4a->port);
5514 
5515 	LIST_REMOVE(w4a, le);
5516 
5517 	mach_port_t previous = MACH_PORT_NULL;
5518 	(void)jobmgr_assumes_zero(jm, mach_port_request_notification(mach_task_self(), w4a->port, MACH_NOTIFY_DEAD_NAME, 0, MACH_PORT_NULL, MACH_MSG_TYPE_MOVE_SEND_ONCE, &previous));
5519 	if (previous) {
5520 		(void)jobmgr_assumes_zero(jm, launchd_mport_deallocate(previous));
5521 	}
5522 
5523 	jobmgr_assumes_zero(jm, launchd_mport_deallocate(w4a->port));
5524 	free(w4a);
5525 }
5526 
5527 struct waiting4attach *
waiting4attach_find(jobmgr_t jm,job_t j)5528 waiting4attach_find(jobmgr_t jm, job_t j)
5529 {
5530 	char *name2use = (char *)j->label;
5531 	if (j->app) {
5532 		struct envitem *ei = NULL;
5533 		SLIST_FOREACH(ei, &j->env, sle) {
5534 			if (strcmp(ei->key, XPC_SERVICE_RENDEZVOUS_TOKEN) == 0) {
5535 				name2use = ei->value;
5536 				break;
5537 			}
5538 		}
5539 	}
5540 
5541 	struct waiting4attach *w4ai = NULL;
5542 	LIST_FOREACH(w4ai, &jm->attaches, le) {
5543 		if (strcmp(name2use, w4ai->name) == 0) {
5544 			job_log(j, LOG_DEBUG, "Found attachment: %s", name2use);
5545 			break;
5546 		}
5547 	}
5548 
5549 	return w4ai;
5550 }
5551 
5552 void
job_logv(job_t j,int pri,int err,const char * msg,va_list ap)5553 job_logv(job_t j, int pri, int err, const char *msg, va_list ap)
5554 {
5555 	const char *label2use = j ? j->label : "com.apple.launchd.job-unknown";
5556 	const char *mgr2use = j ? j->mgr->name : "com.apple.launchd.jobmanager-unknown";
5557 	char *newmsg;
5558 	int oldmask = 0;
5559 	size_t newmsgsz;
5560 
5561 	struct launchd_syslog_attr attr = {
5562 		.from_name = launchd_label,
5563 		.about_name = label2use,
5564 		.session_name = mgr2use,
5565 		.priority = pri,
5566 		.from_uid = getuid(),
5567 		.from_pid = getpid(),
5568 		.about_pid = j ? j->p : 0,
5569 	};
5570 
5571 	/* Hack: If bootstrap_port is set, we must be on the child side of a
5572 	 * fork(2), but before the exec*(3). Let's route the log message back to
5573 	 * launchd proper.
5574 	 */
5575 	if (bootstrap_port && uflag == false) {
5576 		return _vproc_logv(pri, err, msg, ap);
5577 	}
5578 
5579 	newmsgsz = strlen(msg) + 200;
5580 	newmsg = alloca(newmsgsz);
5581 
5582 	if (err) {
5583 #if !TARGET_OS_EMBEDDED
5584 		snprintf(newmsg, newmsgsz, "%s: %d: %s", msg, err, strerror(err));
5585 #else
5586 		snprintf(newmsg, newmsgsz, "(%s) %s: %d: %s", label2use, msg, err, strerror(err));
5587 #endif
5588 	} else {
5589 #if !TARGET_OS_EMBEDDED
5590 		snprintf(newmsg, newmsgsz, "%s", msg);
5591 #else
5592 		snprintf(newmsg, newmsgsz, "(%s) %s", label2use, msg);
5593 #endif
5594 	}
5595 
5596 	if (j && unlikely(j->debug)) {
5597 		oldmask = setlogmask(LOG_UPTO(LOG_DEBUG));
5598 	}
5599 
5600 	launchd_vsyslog(&attr, newmsg, ap);
5601 
5602 	if (j && unlikely(j->debug)) {
5603 		setlogmask(oldmask);
5604 	}
5605 }
5606 
5607 void
job_log_error(job_t j,int pri,const char * msg,...)5608 job_log_error(job_t j, int pri, const char *msg, ...)
5609 {
5610 	va_list ap;
5611 
5612 	va_start(ap, msg);
5613 	job_logv(j, pri, errno, msg, ap);
5614 	va_end(ap);
5615 }
5616 
5617 void
job_log(job_t j,int pri,const char * msg,...)5618 job_log(job_t j, int pri, const char *msg, ...)
5619 {
5620 	va_list ap;
5621 
5622 	va_start(ap, msg);
5623 	job_logv(j, pri, 0, msg, ap);
5624 	va_end(ap);
5625 }
5626 
5627 #if 0
5628 void
5629 jobmgr_log_error(jobmgr_t jm, int pri, const char *msg, ...)
5630 {
5631 	va_list ap;
5632 
5633 	va_start(ap, msg);
5634 	jobmgr_logv(jm, pri, errno, msg, ap);
5635 	va_end(ap);
5636 }
5637 #endif
5638 
5639 void
jobmgr_log_perf_statistics(jobmgr_t jm,bool signal_children)5640 jobmgr_log_perf_statistics(jobmgr_t jm, bool signal_children)
5641 {
5642 #if HAVE_SYSTEMSTATS
5643 	// Log information for kernel_task and pid 1 launchd.
5644 	if (systemstats_is_enabled() && pid1_magic && jm == root_jobmgr) {
5645 #if SYSTEMSTATS_API_VERSION >= 20130328
5646 		if (_systemstats_get_property(SYSTEMSTATS_API_VERSION, SYSTEMSTATS_WRITER_launchd, SYSTEMSTATS_PROPERTY_SHOULD_LOG_ENERGY_STATISTICS)) {
5647 			systemstats_write_intel_energy_statistics(NULL);
5648 		}
5649 #else
5650 		systemstats_write_intel_energy_statistics(NULL);
5651 #endif
5652 		job_log_systemstats(0, 0, 0, 0, 0, "com.apple.kernel", NULL, -1);
5653 		job_log_systemstats(1, 1, 0, 1, 1, "com.apple.launchd", NULL, -1);
5654 	}
5655 #endif
5656 	jobmgr_t jmi = NULL;
5657 	SLIST_FOREACH(jmi, &jm->submgrs, sle) {
5658 		jobmgr_log_perf_statistics(jmi, signal_children);
5659 	}
5660 
5661 	if (jm->xpc_singleton) {
5662 		jobmgr_log(jm, LOG_PERF, "XPC Singleton Domain: %s", jm->shortdesc);
5663 	} else if (jm->properties & BOOTSTRAP_PROPERTY_XPC_DOMAIN) {
5664 		jobmgr_log(jm, LOG_PERF, "XPC Private Domain: %s", jm->owner);
5665 	} else if (jm->properties & BOOTSTRAP_PROPERTY_EXPLICITSUBSET) {
5666 		jobmgr_log(jm, LOG_PERF, "Created via bootstrap_subset()");
5667 	}
5668 
5669 	jobmgr_log(jm, LOG_PERF, "Jobs in job manager:");
5670 
5671 	job_t ji = NULL;
5672 	LIST_FOREACH(ji, &jm->jobs, sle) {
5673 		job_log_perf_statistics(ji, NULL, -1);
5674 		if (unlikely(signal_children) && unlikely(strstr(ji->label, "com.apple.launchd.peruser.") == ji->label)) {
5675 			jobmgr_log(jm, LOG_PERF, "Sending SIGINFO to peruser launchd %d", ji->p);
5676 			kill(ji->p, SIGINFO);
5677 		}
5678 	}
5679 
5680 	jobmgr_log(jm, LOG_PERF, "End of job list.");
5681 }
5682 
5683 void
jobmgr_log(jobmgr_t jm,int pri,const char * msg,...)5684 jobmgr_log(jobmgr_t jm, int pri, const char *msg, ...)
5685 {
5686 	va_list ap;
5687 
5688 	va_start(ap, msg);
5689 	jobmgr_logv(jm, pri, 0, msg, ap);
5690 	va_end(ap);
5691 }
5692 
5693 void
jobmgr_logv(jobmgr_t jm,int pri,int err,const char * msg,va_list ap)5694 jobmgr_logv(jobmgr_t jm, int pri, int err, const char *msg, va_list ap)
5695 {
5696 	if (!jm) {
5697 		jm = root_jobmgr;
5698 	}
5699 
5700 	char *newmsg;
5701 	char *newname;
5702 	size_t i, o, jmname_len = strlen(jm->name), newmsgsz;
5703 
5704 	newname = alloca((jmname_len + 1) * 2);
5705 	newmsgsz = (jmname_len + 1) * 2 + strlen(msg) + 100;
5706 	newmsg = alloca(newmsgsz);
5707 
5708 	for (i = 0, o = 0; i < jmname_len; i++, o++) {
5709 		if (jm->name[i] == '%') {
5710 			newname[o] = '%';
5711 			o++;
5712 		}
5713 		newname[o] = jm->name[i];
5714 	}
5715 	newname[o] = '\0';
5716 
5717 	if (err) {
5718 		snprintf(newmsg, newmsgsz, "%s: %s: %s", newname, msg, strerror(err));
5719 	} else {
5720 		snprintf(newmsg, newmsgsz, "%s: %s", newname, msg);
5721 	}
5722 
5723 	if (jm->parentmgr) {
5724 		jobmgr_logv(jm->parentmgr, pri, 0, newmsg, ap);
5725 	} else {
5726 		struct launchd_syslog_attr attr = {
5727 			.from_name = launchd_label,
5728 			.about_name = launchd_label,
5729 			.session_name = jm->name,
5730 			.priority = pri,
5731 			.from_uid = getuid(),
5732 			.from_pid = getpid(),
5733 			.about_pid = getpid(),
5734 		};
5735 
5736 		launchd_vsyslog(&attr, newmsg, ap);
5737 	}
5738 }
5739 
5740 struct cal_dict_walk {
5741 	job_t j;
5742 	struct tm tmptm;
5743 };
5744 
5745 void
calendarinterval_new_from_obj_dict_walk(launch_data_t obj,const char * key,void * context)5746 calendarinterval_new_from_obj_dict_walk(launch_data_t obj, const char *key, void *context)
5747 {
5748 	struct cal_dict_walk *cdw = context;
5749 	struct tm *tmptm = &cdw->tmptm;
5750 	job_t j = cdw->j;
5751 	int64_t val;
5752 
5753 	if (unlikely(LAUNCH_DATA_INTEGER != launch_data_get_type(obj))) {
5754 		// hack to let caller know something went wrong
5755 		tmptm->tm_sec = -1;
5756 		return;
5757 	}
5758 
5759 	val = launch_data_get_integer(obj);
5760 
5761 	if (val < 0) {
5762 		job_log(j, LOG_WARNING, "The interval for key \"%s\" is less than zero.", key);
5763 	} else if (strcasecmp(key, LAUNCH_JOBKEY_CAL_MINUTE) == 0) {
5764 		if (val > 59) {
5765 			job_log(j, LOG_WARNING, "The interval for key \"%s\" is not between 0 and 59 (inclusive).", key);
5766 			tmptm->tm_sec = -1;
5767 		} else {
5768 			tmptm->tm_min = (typeof(tmptm->tm_min)) val;
5769 		}
5770 	} else if (strcasecmp(key, LAUNCH_JOBKEY_CAL_HOUR) == 0) {
5771 		if (val > 23) {
5772 			job_log(j, LOG_WARNING, "The interval for key \"%s\" is not between 0 and 23 (inclusive).", key);
5773 			tmptm->tm_sec = -1;
5774 		} else {
5775 			tmptm->tm_hour = (typeof(tmptm->tm_hour)) val;
5776 		}
5777 	} else if (strcasecmp(key, LAUNCH_JOBKEY_CAL_DAY) == 0) {
5778 		if (val < 1 || val > 31) {
5779 			job_log(j, LOG_WARNING, "The interval for key \"%s\" is not between 1 and 31 (inclusive).", key);
5780 			tmptm->tm_sec = -1;
5781 		} else {
5782 			tmptm->tm_mday = (typeof(tmptm->tm_mday)) val;
5783 		}
5784 	} else if (strcasecmp(key, LAUNCH_JOBKEY_CAL_WEEKDAY) == 0) {
5785 		if (val > 7) {
5786 			job_log(j, LOG_WARNING, "The interval for key \"%s\" is not between 0 and 7 (inclusive).", key);
5787 			tmptm->tm_sec = -1;
5788 		} else {
5789 			tmptm->tm_wday = (typeof(tmptm->tm_wday)) val;
5790 		}
5791 	} else if (strcasecmp(key, LAUNCH_JOBKEY_CAL_MONTH) == 0) {
5792 		if (val > 12) {
5793 			job_log(j, LOG_WARNING, "The interval for key \"%s\" is not between 0 and 12 (inclusive).", key);
5794 			tmptm->tm_sec = -1;
5795 		} else {
5796 			tmptm->tm_mon = (typeof(tmptm->tm_mon)) val;
5797 			tmptm->tm_mon -= 1; // 4798263 cron compatibility
5798 		}
5799 	}
5800 }
5801 
5802 bool
calendarinterval_new_from_obj(job_t j,launch_data_t obj)5803 calendarinterval_new_from_obj(job_t j, launch_data_t obj)
5804 {
5805 	struct cal_dict_walk cdw;
5806 
5807 	cdw.j = j;
5808 	memset(&cdw.tmptm, 0, sizeof(0));
5809 
5810 	cdw.tmptm.tm_min = -1;
5811 	cdw.tmptm.tm_hour = -1;
5812 	cdw.tmptm.tm_mday = -1;
5813 	cdw.tmptm.tm_wday = -1;
5814 	cdw.tmptm.tm_mon = -1;
5815 
5816 	if (!job_assumes(j, obj != NULL)) {
5817 		return false;
5818 	}
5819 
5820 	if (unlikely(LAUNCH_DATA_DICTIONARY != launch_data_get_type(obj))) {
5821 		return false;
5822 	}
5823 
5824 	launch_data_dict_iterate(obj, calendarinterval_new_from_obj_dict_walk, &cdw);
5825 
5826 	if (unlikely(cdw.tmptm.tm_sec == -1)) {
5827 		return false;
5828 	}
5829 
5830 	return calendarinterval_new(j, &cdw.tmptm);
5831 }
5832 
5833 bool
calendarinterval_new(job_t j,struct tm * w)5834 calendarinterval_new(job_t j, struct tm *w)
5835 {
5836 	struct calendarinterval *ci = calloc(1, sizeof(struct calendarinterval));
5837 
5838 	if (!job_assumes(j, ci != NULL)) {
5839 		return false;
5840 	}
5841 
5842 	ci->when = *w;
5843 	ci->job = j;
5844 
5845 	SLIST_INSERT_HEAD(&j->cal_intervals, ci, sle);
5846 
5847 	calendarinterval_setalarm(j, ci);
5848 
5849 	runtime_add_weak_ref();
5850 
5851 	return true;
5852 }
5853 
5854 void
calendarinterval_delete(job_t j,struct calendarinterval * ci)5855 calendarinterval_delete(job_t j, struct calendarinterval *ci)
5856 {
5857 	SLIST_REMOVE(&j->cal_intervals, ci, calendarinterval, sle);
5858 	LIST_REMOVE(ci, global_sle);
5859 
5860 	free(ci);
5861 
5862 	runtime_del_weak_ref();
5863 }
5864 
5865 void
calendarinterval_sanity_check(void)5866 calendarinterval_sanity_check(void)
5867 {
5868 	struct calendarinterval *ci = LIST_FIRST(&sorted_calendar_events);
5869 	time_t now = time(NULL);
5870 
5871 	if (unlikely(ci && (ci->when_next < now))) {
5872 		(void)jobmgr_assumes_zero_p(root_jobmgr, raise(SIGUSR1));
5873 	}
5874 }
5875 
5876 void
calendarinterval_callback(void)5877 calendarinterval_callback(void)
5878 {
5879 	struct calendarinterval *ci, *ci_next;
5880 	time_t now = time(NULL);
5881 
5882 	LIST_FOREACH_SAFE(ci, &sorted_calendar_events, global_sle, ci_next) {
5883 		job_t j = ci->job;
5884 
5885 		if (ci->when_next > now) {
5886 			break;
5887 		}
5888 
5889 		LIST_REMOVE(ci, global_sle);
5890 		calendarinterval_setalarm(j, ci);
5891 
5892 		j->start_pending = true;
5893 		job_dispatch(j, false);
5894 	}
5895 }
5896 
5897 bool
socketgroup_new(job_t j,const char * name,int * fds,size_t fd_cnt)5898 socketgroup_new(job_t j, const char *name, int *fds, size_t fd_cnt)
5899 {
5900 	struct socketgroup *sg = calloc(1, sizeof(struct socketgroup) + strlen(name) + 1);
5901 
5902 	if (!job_assumes(j, sg != NULL)) {
5903 		return false;
5904 	}
5905 
5906 	sg->fds = calloc(1, fd_cnt * sizeof(int));
5907 	sg->fd_cnt = fd_cnt;
5908 
5909 	if (!job_assumes(j, sg->fds != NULL)) {
5910 		free(sg);
5911 		return false;
5912 	}
5913 
5914 	memcpy(sg->fds, fds, fd_cnt * sizeof(int));
5915 	strcpy(sg->name_init, name);
5916 
5917 	SLIST_INSERT_HEAD(&j->sockets, sg, sle);
5918 
5919 	runtime_add_weak_ref();
5920 
5921 	return true;
5922 }
5923 
5924 void
socketgroup_delete(job_t j,struct socketgroup * sg)5925 socketgroup_delete(job_t j, struct socketgroup *sg)
5926 {
5927 	unsigned int i;
5928 
5929 	for (i = 0; i < sg->fd_cnt; i++) {
5930 #if 0
5931 		struct sockaddr_storage ss;
5932 		struct sockaddr_un *sun = (struct sockaddr_un *)&ss;
5933 		socklen_t ss_len = sizeof(ss);
5934 
5935 		// 5480306
5936 		if (job_assumes_zero(j, getsockname(sg->fds[i], (struct sockaddr *)&ss, &ss_len) != -1)
5937 				&& job_assumes(j, ss_len > 0) && (ss.ss_family == AF_UNIX)) {
5938 			(void)job_assumes(j, unlink(sun->sun_path) != -1);
5939 			// We might conditionally need to delete a directory here
5940 		}
5941 #endif
5942 		(void)job_assumes_zero_p(j, runtime_close(sg->fds[i]));
5943 	}
5944 
5945 	SLIST_REMOVE(&j->sockets, sg, socketgroup, sle);
5946 
5947 	free(sg->fds);
5948 	free(sg);
5949 
5950 	runtime_del_weak_ref();
5951 }
5952 
5953 void
socketgroup_kevent_mod(job_t j,struct socketgroup * sg,bool do_add)5954 socketgroup_kevent_mod(job_t j, struct socketgroup *sg, bool do_add)
5955 {
5956 	struct kevent kev[sg->fd_cnt];
5957 	char buf[10000];
5958 	unsigned int i, buf_off = 0;
5959 
5960 	for (i = 0; i < sg->fd_cnt; i++) {
5961 		EV_SET(&kev[i], sg->fds[i], EVFILT_READ, do_add ? EV_ADD : EV_DELETE, 0, 0, j);
5962 		buf_off += snprintf(buf + buf_off, sizeof(buf) - buf_off, " %d", sg->fds[i]);
5963 	}
5964 
5965 	job_log(j, LOG_DEBUG, "%s Sockets:%s", do_add ? "Watching" : "Ignoring", buf);
5966 
5967 	(void)job_assumes_zero_p(j, kevent_bulk_mod(kev, sg->fd_cnt));
5968 
5969 	for (i = 0; i < sg->fd_cnt; i++) {
5970 		(void)job_assumes(j, kev[i].flags & EV_ERROR);
5971 		errno = (typeof(errno)) kev[i].data;
5972 		(void)job_assumes_zero(j, kev[i].data);
5973 	}
5974 }
5975 
5976 void
socketgroup_ignore(job_t j,struct socketgroup * sg)5977 socketgroup_ignore(job_t j, struct socketgroup *sg)
5978 {
5979 	socketgroup_kevent_mod(j, sg, false);
5980 }
5981 
5982 void
socketgroup_watch(job_t j,struct socketgroup * sg)5983 socketgroup_watch(job_t j, struct socketgroup *sg)
5984 {
5985 	socketgroup_kevent_mod(j, sg, true);
5986 }
5987 
5988 void
socketgroup_callback(job_t j)5989 socketgroup_callback(job_t j)
5990 {
5991 	job_dispatch(j, true);
5992 }
5993 
5994 bool
envitem_new(job_t j,const char * k,const char * v,bool global)5995 envitem_new(job_t j, const char *k, const char *v, bool global)
5996 {
5997 	if (global && !launchd_allow_global_dyld_envvars) {
5998 		if (strncmp("DYLD_", k, sizeof("DYLD_") - 1) == 0) {
5999 			job_log(j, LOG_ERR, "Ignoring global environment variable submitted by job (variable=value): %s=%s", k, v);
6000 			return false;
6001 		}
6002 	}
6003 
6004 	struct envitem *ei = calloc(1, sizeof(struct envitem) + strlen(k) + 1 + strlen(v) + 1);
6005 
6006 	if (!job_assumes(j, ei != NULL)) {
6007 		return false;
6008 	}
6009 
6010 	strcpy(ei->key_init, k);
6011 	ei->value = ei->key_init + strlen(k) + 1;
6012 	strcpy(ei->value, v);
6013 
6014 	if (global) {
6015 		if (SLIST_EMPTY(&j->global_env)) {
6016 			LIST_INSERT_HEAD(&j->mgr->global_env_jobs, j, global_env_sle);
6017 		}
6018 		SLIST_INSERT_HEAD(&j->global_env, ei, sle);
6019 	} else {
6020 		SLIST_INSERT_HEAD(&j->env, ei, sle);
6021 	}
6022 
6023 	job_log(j, LOG_DEBUG, "Added environmental variable: %s=%s", k, v);
6024 
6025 	return true;
6026 }
6027 
6028 void
envitem_delete(job_t j,struct envitem * ei,bool global)6029 envitem_delete(job_t j, struct envitem *ei, bool global)
6030 {
6031 	if (global) {
6032 		SLIST_REMOVE(&j->global_env, ei, envitem, sle);
6033 		if (SLIST_EMPTY(&j->global_env)) {
6034 			LIST_REMOVE(j, global_env_sle);
6035 		}
6036 	} else {
6037 		SLIST_REMOVE(&j->env, ei, envitem, sle);
6038 	}
6039 
6040 	free(ei);
6041 }
6042 
6043 void
envitem_setup(launch_data_t obj,const char * key,void * context)6044 envitem_setup(launch_data_t obj, const char *key, void *context)
6045 {
6046 	job_t j = context;
6047 
6048 	if (launch_data_get_type(obj) != LAUNCH_DATA_STRING) {
6049 		return;
6050 	}
6051 
6052 	if (strncmp(LAUNCHD_TRUSTED_FD_ENV, key, sizeof(LAUNCHD_TRUSTED_FD_ENV) - 1) != 0) {
6053 		envitem_new(j, key, launch_data_get_string(obj), j->importing_global_env);
6054 	} else {
6055 		job_log(j, LOG_DEBUG, "Ignoring reserved environmental variable: %s", key);
6056 	}
6057 }
6058 
6059 bool
limititem_update(job_t j,int w,rlim_t r)6060 limititem_update(job_t j, int w, rlim_t r)
6061 {
6062 	struct limititem *li;
6063 
6064 	SLIST_FOREACH(li, &j->limits, sle) {
6065 		if (li->which == w) {
6066 			break;
6067 		}
6068 	}
6069 
6070 	if (li == NULL) {
6071 		li = calloc(1, sizeof(struct limititem));
6072 
6073 		if (!job_assumes(j, li != NULL)) {
6074 			return false;
6075 		}
6076 
6077 		SLIST_INSERT_HEAD(&j->limits, li, sle);
6078 
6079 		li->which = w;
6080 	}
6081 
6082 	if (j->importing_hard_limits) {
6083 		li->lim.rlim_max = r;
6084 		li->sethard = true;
6085 	} else {
6086 		li->lim.rlim_cur = r;
6087 		li->setsoft = true;
6088 	}
6089 
6090 	return true;
6091 }
6092 
6093 void
limititem_delete(job_t j,struct limititem * li)6094 limititem_delete(job_t j, struct limititem *li)
6095 {
6096 	SLIST_REMOVE(&j->limits, li, limititem, sle);
6097 
6098 	free(li);
6099 }
6100 
6101 #if HAVE_SANDBOX
6102 void
seatbelt_setup_flags(launch_data_t obj,const char * key,void * context)6103 seatbelt_setup_flags(launch_data_t obj, const char *key, void *context)
6104 {
6105 	job_t j = context;
6106 
6107 	if (launch_data_get_type(obj) != LAUNCH_DATA_BOOL) {
6108 		job_log(j, LOG_WARNING, "Sandbox flag value must be boolean: %s", key);
6109 		return;
6110 	}
6111 
6112 	if (launch_data_get_bool(obj) == false) {
6113 		return;
6114 	}
6115 
6116 	if (strcasecmp(key, LAUNCH_JOBKEY_SANDBOX_NAMED) == 0) {
6117 		j->seatbelt_flags |= SANDBOX_NAMED;
6118 	}
6119 }
6120 #endif
6121 
6122 void
limititem_setup(launch_data_t obj,const char * key,void * context)6123 limititem_setup(launch_data_t obj, const char *key, void *context)
6124 {
6125 	job_t j = context;
6126 	size_t i, limits_cnt = (sizeof(launchd_keys2limits) / sizeof(launchd_keys2limits[0]));
6127 	rlim_t rl;
6128 
6129 	if (launch_data_get_type(obj) != LAUNCH_DATA_INTEGER) {
6130 		return;
6131 	}
6132 
6133 	rl = launch_data_get_integer(obj);
6134 
6135 	for (i = 0; i < limits_cnt; i++) {
6136 		if (strcasecmp(launchd_keys2limits[i].key, key) == 0) {
6137 			break;
6138 		}
6139 	}
6140 
6141 	if (i == limits_cnt) {
6142 		return;
6143 	}
6144 
6145 	limititem_update(j, launchd_keys2limits[i].val, rl);
6146 }
6147 
6148 bool
job_useless(job_t j)6149 job_useless(job_t j)
6150 {
6151 	if ((j->legacy_LS_job || j->only_once) && j->start_time != 0) {
6152 		if (j->legacy_LS_job && j->j_port) {
6153 			return false;
6154 		}
6155 		job_log(j, LOG_INFO, "Exited. Was only configured to run once.");
6156 		return true;
6157 	} else if (j->removal_pending) {
6158 		job_log(j, LOG_DEBUG, "Exited while removal was pending.");
6159 		return true;
6160 	} else if (j->shutdown_monitor) {
6161 		return false;
6162 	} else if (j->mgr->shutting_down && !j->mgr->parentmgr) {
6163 		job_log(j, LOG_DEBUG, "Exited while shutdown in progress. Processes remaining: %lu/%lu", total_children, total_anon_children);
6164 		if (total_children == 0 && !j->anonymous) {
6165 			job_log(j, LOG_DEBUG | LOG_CONSOLE, "Job was last to exit during shutdown of: %s.", j->mgr->name);
6166 		}
6167 		return true;
6168 	} else if (j->legacy_mach_job) {
6169 		if (SLIST_EMPTY(&j->machservices)) {
6170 			job_log(j, LOG_INFO, "Garbage collecting");
6171 			return true;
6172 		} else if (!j->checkedin) {
6173 			job_log(j, LOG_WARNING, "Failed to check-in!");
6174 			return true;
6175 		}
6176 	} else {
6177 		/* If the job's executable does not have any valid architectures (for
6178 		 * example, if it's a PowerPC-only job), then we don't even bother
6179 		 * trying to relaunch it, as we have no reasonable expectation that
6180 		 * the situation will change.
6181 		 *
6182 		 * <rdar://problem/9106979>
6183 		 */
6184 		if (!j->did_exec && WEXITSTATUS(j->last_exit_status) == EBADARCH) {
6185 			job_log(j, LOG_ERR, "Job executable does not contain supported architectures. Unloading it. Its plist should be removed.");
6186 			return true;
6187 		}
6188 	}
6189 
6190 	return false;
6191 }
6192 
6193 bool
job_keepalive(job_t j)6194 job_keepalive(job_t j)
6195 {
6196 	mach_msg_type_number_t statusCnt;
6197 	mach_port_status_t status;
6198 	struct semaphoreitem *si;
6199 	struct machservice *ms;
6200 	bool good_exit = (WIFEXITED(j->last_exit_status) && WEXITSTATUS(j->last_exit_status) == 0);
6201 	bool is_not_kextd = (launchd_apple_internal || (strcmp(j->label, "com.apple.kextd") != 0));
6202 
6203 	if (unlikely(j->mgr->shutting_down)) {
6204 		return false;
6205 	}
6206 
6207 	/*
6208 	 * 5066316
6209 	 *
6210 	 * We definitely need to revisit this after Leopard ships. Please see
6211 	 * launchctl.c for the other half of this hack.
6212 	 */
6213 	if (unlikely((j->mgr->global_on_demand_cnt > 0) && is_not_kextd)) {
6214 		return false;
6215 	}
6216 
6217 	if (unlikely(j->needs_kickoff)) {
6218 		job_log(j, LOG_DEBUG, "KeepAlive check: Job needs to be kicked off on-demand before KeepAlive sets in.");
6219 		return false;
6220 	}
6221 
6222 	if (j->start_pending) {
6223 		job_log(j, LOG_DEBUG, "KeepAlive check: Pent-up non-IPC launch criteria.");
6224 		return true;
6225 	}
6226 
6227 	if (!j->ondemand) {
6228 		job_log(j, LOG_DEBUG, "KeepAlive check: job configured to run continuously.");
6229 		return true;
6230 	}
6231 
6232 	SLIST_FOREACH(ms, &j->machservices, sle) {
6233 		statusCnt = MACH_PORT_RECEIVE_STATUS_COUNT;
6234 		if (mach_port_get_attributes(mach_task_self(), ms->port, MACH_PORT_RECEIVE_STATUS,
6235 					(mach_port_info_t)&status, &statusCnt) != KERN_SUCCESS) {
6236 			continue;
6237 		}
6238 		if (status.mps_msgcount) {
6239 			job_log(j, LOG_DEBUG, "KeepAlive check: %d queued Mach messages on service: %s",
6240 					status.mps_msgcount, ms->name);
6241 			return true;
6242 		}
6243 	}
6244 
6245 	/* TODO: Coalesce external events and semaphore items, since they're basically
6246 	 * the same thing.
6247 	 */
6248 	struct externalevent *ei = NULL;
6249 	LIST_FOREACH(ei, &j->events, job_le) {
6250 		if (ei->state == ei->wanted_state) {
6251 			return true;
6252 		}
6253 	}
6254 
6255 	SLIST_FOREACH(si, &j->semaphores, sle) {
6256 		bool wanted_state = false;
6257 		job_t other_j;
6258 
6259 		switch (si->why) {
6260 		case NETWORK_UP:
6261 			wanted_state = true;
6262 		case NETWORK_DOWN:
6263 			if (network_up == wanted_state) {
6264 				job_log(j, LOG_DEBUG, "KeepAlive: The network is %s.", wanted_state ? "up" : "down");
6265 				return true;
6266 			}
6267 			break;
6268 		case SUCCESSFUL_EXIT:
6269 			wanted_state = true;
6270 		case FAILED_EXIT:
6271 			if (good_exit == wanted_state) {
6272 				job_log(j, LOG_DEBUG, "KeepAlive: The exit state was %s.", wanted_state ? "successful" : "failure");
6273 				return true;
6274 			}
6275 			break;
6276 		case CRASHED:
6277 			wanted_state = true;
6278 		case DID_NOT_CRASH:
6279 			if (j->crashed == wanted_state) {
6280 				return true;
6281 			}
6282 			break;
6283 		case OTHER_JOB_ENABLED:
6284 			wanted_state = true;
6285 		case OTHER_JOB_DISABLED:
6286 			if ((bool)job_find(NULL, si->what) == wanted_state) {
6287 				job_log(j, LOG_DEBUG, "KeepAlive: The following job is %s: %s", wanted_state ? "enabled" : "disabled", si->what);
6288 				return true;
6289 			}
6290 			break;
6291 		case OTHER_JOB_ACTIVE:
6292 			wanted_state = true;
6293 		case OTHER_JOB_INACTIVE:
6294 			if ((other_j = job_find(NULL, si->what))) {
6295 				if ((bool)other_j->p == wanted_state) {
6296 					job_log(j, LOG_DEBUG, "KeepAlive: The following job is %s: %s", wanted_state ? "active" : "inactive", si->what);
6297 					return true;
6298 				}
6299 			}
6300 			break;
6301 		}
6302 	}
6303 
6304 	return false;
6305 }
6306 
6307 const char *
job_active(job_t j)6308 job_active(job_t j)
6309 {
6310 	if (j->p && j->shutdown_monitor) {
6311 		return "Monitoring shutdown";
6312 	}
6313 	if (j->p) {
6314 		return "PID is still valid";
6315 	}
6316 
6317 	if (j->priv_port_has_senders) {
6318 		return "Privileged Port still has outstanding senders";
6319 	}
6320 
6321 	struct machservice *ms;
6322 	SLIST_FOREACH(ms, &j->machservices, sle) {
6323 		/* If we've simulated an exit, we mark the job as non-active, even
6324 		 * though doing so will leave it in an unsafe state. We do this so that
6325 		 * shutdown can proceed. See <rdar://problem/11126530>.
6326 		 */
6327 		if (!j->workaround9359725 && ms->recv && machservice_active(ms)) {
6328 			job_log(j, LOG_INFO, "Mach service is still active despite being killed: %s", ms->name);
6329 			/*
6330 			 * It is not at all clear to me why this returns a string.  The process
6331 			 * has been killed, and the loop at this point doesn't do anything other
6332 			 * than wait.  Which is probably not going to do anything useful.
6333 			 */
6334 			return NULL;
6335 			// return "Mach service is still active despite being killed";
6336 		}
6337 	}
6338 
6339 	return NULL;
6340 }
6341 
6342 void
machservice_watch(job_t j,struct machservice * ms)6343 machservice_watch(job_t j, struct machservice *ms)
6344 {
6345 	if (ms->recv) {
6346 		if (job_assumes_zero(j, runtime_add_mport(ms->port, NULL)) == KERN_INVALID_RIGHT) {
6347 			ms->recv_race_hack = true;
6348 		}
6349 	}
6350 }
6351 
6352 void
machservice_ignore(job_t j,struct machservice * ms)6353 machservice_ignore(job_t j, struct machservice *ms)
6354 {
6355 	/* We only add ports whose receive rights we control into the port set, so
6356 	 * don't attempt to remove te service from the port set if we didn't put it
6357 	 * there in the first place. Otherwise, we could wind up trying to access a
6358 	 * bogus index (like MACH_PORT_DEAD) or zeroing a valid one out.
6359 	 *
6360 	 * <rdar://problem/10898014>
6361 	 */
6362 	if (ms->recv) {
6363 		(void)job_assumes_zero(j, runtime_remove_mport(ms->port));
6364 	}
6365 }
6366 
6367 void
machservice_resetport(job_t j,struct machservice * ms)6368 machservice_resetport(job_t j, struct machservice *ms)
6369 {
6370 	LIST_REMOVE(ms, port_hash_sle);
6371 	(void)job_assumes_zero(j, launchd_mport_close_recv(ms->port));
6372 	(void)job_assumes_zero(j, launchd_mport_deallocate(ms->port));
6373 
6374 	ms->gen_num++;
6375 	(void)job_assumes_zero(j, launchd_mport_create_recv(&ms->port));
6376 	(void)job_assumes_zero(j, launchd_mport_make_send(ms->port));
6377 	LIST_INSERT_HEAD(&port_hash[HASH_PORT(ms->port)], ms, port_hash_sle);
6378 }
6379 
6380 void
machservice_stamp_port(job_t j,struct machservice * ms)6381 machservice_stamp_port(job_t j, struct machservice *ms)
6382 {
6383 	mach_port_context_t ctx = 0;
6384 	char *where2get = j->prog ? j->prog : j->argv[0];
6385 
6386 	char *prog = NULL;
6387 	if ((prog = strrchr(where2get, '/'))) {
6388 		prog++;
6389 	} else {
6390 		prog = where2get;
6391 	}
6392 
6393 	(void)strncpy((char *)&ctx, prog, sizeof(ctx));
6394 #if __LITTLE_ENDIAN__
6395 #if __LP64__
6396 	ctx = be64toh(ctx);
6397 #else
6398 	ctx = be32toh(ctx);
6399 #endif
6400 #endif
6401 
6402 	(void)job_assumes_zero(j, mach_port_set_context(mach_task_self(), ms->port, ctx));
6403 }
6404 
6405 struct machservice *
machservice_new(job_t j,const char * name,mach_port_t * serviceport,bool pid_local)6406 machservice_new(job_t j, const char *name, mach_port_t *serviceport, bool pid_local)
6407 {
6408 	/* Don't create new MachServices for dead ports. This is primarily for
6409 	 * clients who use bootstrap_register2(). They can pass in a send right, but
6410 	 * then that port can immediately go dead. Hilarity ensues.
6411 	 *
6412 	 * <rdar://problem/10898014>
6413 	 */
6414 	if (*serviceport == MACH_PORT_DEAD) {
6415 		return NULL;
6416 	}
6417 
6418 	struct machservice *ms = calloc(1, sizeof(struct machservice) + strlen(name) + 1);
6419 	if (!job_assumes(j, ms != NULL)) {
6420 		return NULL;
6421 	}
6422 
6423 	strcpy((char *)ms->name, name);
6424 	ms->job = j;
6425 	ms->gen_num = 1;
6426 	ms->per_pid = pid_local;
6427 
6428 	if (likely(*serviceport == MACH_PORT_NULL)) {
6429 		if (job_assumes_zero(j, launchd_mport_create_recv(&ms->port)) != KERN_SUCCESS) {
6430 			goto out_bad;
6431 		}
6432 
6433 		if (job_assumes_zero(j, launchd_mport_make_send(ms->port)) != KERN_SUCCESS) {
6434 			goto out_bad2;
6435 		}
6436 		*serviceport = ms->port;
6437 		ms->recv = true;
6438 	} else {
6439 		ms->port = *serviceport;
6440 		ms->isActive = true;
6441 	}
6442 
6443 	SLIST_INSERT_HEAD(&j->machservices, ms, sle);
6444 
6445 	jobmgr_t where2put = j->mgr;
6446 	// XPC domains are separate from Mach bootstraps.
6447 	if (!(j->mgr->properties & BOOTSTRAP_PROPERTY_XPC_DOMAIN)) {
6448 		if (launchd_flat_mach_namespace && !(j->mgr->properties & BOOTSTRAP_PROPERTY_EXPLICITSUBSET)) {
6449 			where2put = root_jobmgr;
6450 		}
6451 	}
6452 
6453 	/* Don't allow MachServices added by multiple-instance jobs to be looked up
6454 	 * by others. We could just do this with a simple bit, but then we'd have to
6455 	 * uniquify the names ourselves to avoid collisions. This is just easier.
6456 	 */
6457 	if (!j->dedicated_instance) {
6458 		LIST_INSERT_HEAD(&where2put->ms_hash[hash_ms(ms->name)], ms, name_hash_sle);
6459 	}
6460 	LIST_INSERT_HEAD(&port_hash[HASH_PORT(ms->port)], ms, port_hash_sle);
6461 
6462 	if (ms->recv) {
6463 		machservice_stamp_port(j, ms);
6464 	}
6465 
6466 	job_log(j, LOG_DEBUG, "Mach service added%s: %s", (j->mgr->properties & BOOTSTRAP_PROPERTY_EXPLICITSUBSET) ? " to private namespace" : "", name);
6467 
6468 	return ms;
6469 out_bad2:
6470 	(void)job_assumes_zero(j, launchd_mport_close_recv(ms->port));
6471 out_bad:
6472 	free(ms);
6473 	return NULL;
6474 }
6475 
6476 struct machservice *
machservice_new_alias(job_t j,struct machservice * orig)6477 machservice_new_alias(job_t j, struct machservice *orig)
6478 {
6479 	struct machservice *ms = calloc(1, sizeof(struct machservice) + strlen(orig->name) + 1);
6480 	if (job_assumes(j, ms != NULL)) {
6481 		strcpy((char *)ms->name, orig->name);
6482 		ms->alias = orig;
6483 		ms->job = j;
6484 
6485 		LIST_INSERT_HEAD(&j->mgr->ms_hash[hash_ms(ms->name)], ms, name_hash_sle);
6486 		SLIST_INSERT_HEAD(&j->machservices, ms, sle);
6487 		jobmgr_log(j->mgr, LOG_DEBUG, "Service aliased into job manager: %s", orig->name);
6488 	}
6489 
6490 	return ms;
6491 }
6492 
6493 bootstrap_status_t
machservice_status(struct machservice * ms)6494 machservice_status(struct machservice *ms)
6495 {
6496 	ms = ms->alias ? ms->alias : ms;
6497 	if (ms->isActive) {
6498 		return BOOTSTRAP_STATUS_ACTIVE;
6499 	} else if (ms->job->ondemand) {
6500 		return BOOTSTRAP_STATUS_ON_DEMAND;
6501 	} else {
6502 		return BOOTSTRAP_STATUS_INACTIVE;
6503 	}
6504 }
6505 
6506 #include <sys/mach/thread_status.h>
6507 void
job_setup_exception_port(job_t j,task_t target_task)6508 job_setup_exception_port(job_t j, task_t target_task)
6509 {
6510 	struct machservice *ms;
6511 	thread_state_flavor_t f = 0;
6512 	mach_port_t exc_port = the_exception_server;
6513 
6514 	if (unlikely(j->alt_exc_handler)) {
6515 		ms = jobmgr_lookup_service(j->mgr, j->alt_exc_handler, true, 0);
6516 		if (likely(ms)) {
6517 			exc_port = machservice_port(ms);
6518 		} else {
6519 			job_log(j, LOG_WARNING, "Falling back to default Mach exception handler. Could not find: %s", j->alt_exc_handler);
6520 		}
6521 	} else if (unlikely(j->internal_exc_handler)) {
6522 		exc_port = runtime_get_kernel_port();
6523 	} else if (unlikely(!exc_port)) {
6524 		return;
6525 	}
6526 
6527 #if defined (__ppc__) || defined(__ppc64__)
6528 	f = PPC_THREAD_STATE64;
6529 #elif defined(__i386__) || defined(__x86_64__)
6530 	f = x86_THREAD_STATE;
6531 #elif defined(__arm__)
6532 	f = ARM_THREAD_STATE;
6533 #else
6534 #error "unknown architecture"
6535 #endif
6536 
6537 	if (likely(target_task)) {
6538 		kern_return_t kr = task_set_exception_ports(target_task, EXC_MASK_CRASH | EXC_MASK_GUARD | EXC_MASK_RESOURCE, exc_port, EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES, f);
6539 		if (kr) {
6540 			if (kr != MACH_SEND_INVALID_DEST) {
6541 				(void)job_assumes_zero(j, kr);
6542 			} else {
6543 				job_log(j, LOG_WARNING, "Task died before exception port could be set.");
6544 			}
6545 		}
6546 	} else if (pid1_magic && the_exception_server) {
6547 		mach_port_t mhp = mach_host_self();
6548 		(void)job_assumes_zero(j, host_set_exception_ports(mhp, EXC_MASK_CRASH | EXC_MASK_GUARD | EXC_MASK_RESOURCE, the_exception_server, EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES, f));
6549 		(void)job_assumes_zero(j, launchd_mport_deallocate(mhp));
6550 	}
6551 }
6552 
6553 void
job_set_exception_port(job_t j,mach_port_t port)6554 job_set_exception_port(job_t j, mach_port_t port)
6555 {
6556 	if (unlikely(!the_exception_server)) {
6557 		the_exception_server = port;
6558 		job_setup_exception_port(j, 0);
6559 	} else {
6560 		job_log(j, LOG_WARNING, "The exception server is already claimed!");
6561 	}
6562 }
6563 
6564 void
machservice_setup_options(launch_data_t obj,const char * key,void * context)6565 machservice_setup_options(launch_data_t obj, const char *key, void *context)
6566 {
6567 	struct machservice *ms = context;
6568 	mach_port_t mhp = mach_host_self();
6569 	int which_port;
6570 	bool b;
6571 
6572 	if (!job_assumes(ms->job, mhp != MACH_PORT_NULL)) {
6573 		return;
6574 	}
6575 
6576 	switch (launch_data_get_type(obj)) {
6577 	case LAUNCH_DATA_INTEGER:
6578 		which_port = (int)launch_data_get_integer(obj); // XXX we should bound check this...
6579 		if (strcasecmp(key, LAUNCH_JOBKEY_MACH_TASKSPECIALPORT) == 0) {
6580 			switch (which_port) {
6581 			case TASK_KERNEL_PORT:
6582 			case TASK_HOST_PORT:
6583 			case TASK_NAME_PORT:
6584 			case TASK_BOOTSTRAP_PORT:
6585 			/* I find it a little odd that zero isn't reserved in the header.
6586 			 * Normally Mach is fairly good about this convention...
6587 			 */
6588 			case 0:
6589 				job_log(ms->job, LOG_WARNING, "Tried to set a reserved task special port: %d", which_port);
6590 				break;
6591 			default:
6592 				ms->special_port_num = which_port;
6593 				SLIST_INSERT_HEAD(&special_ports, ms, special_port_sle);
6594 				break;
6595 			}
6596 		} else if (strcasecmp(key, LAUNCH_JOBKEY_MACH_HOSTSPECIALPORT) == 0 && pid1_magic) {
6597 			if (which_port > HOST_MAX_SPECIAL_KERNEL_PORT) {
6598 				(void)job_assumes_zero(ms->job, (errno = host_set_special_port(mhp, which_port, ms->port)));
6599 			} else {
6600 				job_log(ms->job, LOG_WARNING, "Tried to set a reserved host special port: %d", which_port);
6601 			}
6602 		}
6603 	case LAUNCH_DATA_BOOL:
6604 		b = launch_data_get_bool(obj);
6605 		if (strcasecmp(key, LAUNCH_JOBKEY_MACH_ENTERKERNELDEBUGGERONCLOSE) == 0) {
6606 			ms->debug_on_close = b;
6607 		} else if (strcasecmp(key, LAUNCH_JOBKEY_MACH_RESETATCLOSE) == 0) {
6608 			ms->reset = b;
6609 		} else if (strcasecmp(key, LAUNCH_JOBKEY_MACH_HIDEUNTILCHECKIN) == 0) {
6610 			ms->hide = b;
6611 		} else if (strcasecmp(key, LAUNCH_JOBKEY_MACH_EXCEPTIONSERVER) == 0) {
6612 			job_set_exception_port(ms->job, ms->port);
6613 		} else if (strcasecmp(key, LAUNCH_JOBKEY_MACH_KUNCSERVER) == 0) {
6614 			ms->kUNCServer = b;
6615 			(void)job_assumes_zero(ms->job, host_set_UNDServer(mhp, ms->port));
6616 		}
6617 		break;
6618 	case LAUNCH_DATA_STRING:
6619 		if (strcasecmp(key, LAUNCH_JOBKEY_MACH_DRAINMESSAGESONCRASH) == 0) {
6620 			const char *option = launch_data_get_string(obj);
6621 			if (strcasecmp(option, "One") == 0) {
6622 				ms->drain_one_on_crash = true;
6623 			} else if (strcasecmp(option, "All") == 0) {
6624 				ms->drain_all_on_crash = true;
6625 			}
6626 		}
6627 		break;
6628 	case LAUNCH_DATA_DICTIONARY:
6629 		if (launch_data_dict_get_count(obj) == 0) {
6630 			job_set_exception_port(ms->job, ms->port);
6631 		}
6632 		break;
6633 	default:
6634 		break;
6635 	}
6636 
6637 	(void)job_assumes_zero(ms->job, launchd_mport_deallocate(mhp));
6638 }
6639 
6640 void
machservice_setup(launch_data_t obj,const char * key,void * context)6641 machservice_setup(launch_data_t obj, const char *key, void *context)
6642 {
6643 	job_t j = context;
6644 	struct machservice *ms;
6645 	mach_port_t p = MACH_PORT_NULL;
6646 
6647 	if (unlikely(ms = jobmgr_lookup_service(j->mgr, key, false, 0))) {
6648 		job_log(j, LOG_WARNING, "Conflict with job: %s over Mach service: %s", ms->job->label, key);
6649 		return;
6650 	}
6651 
6652 	if (!job_assumes(j, (ms = machservice_new(j, key, &p, false)) != NULL)) {
6653 		return;
6654 	}
6655 
6656 	ms->isActive = false;
6657 	ms->upfront = true;
6658 
6659 	if (launch_data_get_type(obj) == LAUNCH_DATA_DICTIONARY) {
6660 		launch_data_dict_iterate(obj, machservice_setup_options, ms);
6661 	}
6662 
6663 	kern_return_t kr = mach_port_set_attributes(mach_task_self(), ms->port, MACH_PORT_TEMPOWNER, NULL, 0);
6664 	(void)job_assumes_zero(j, kr);
6665 }
6666 
6667 jobmgr_t
jobmgr_do_garbage_collection(jobmgr_t jm)6668 jobmgr_do_garbage_collection(jobmgr_t jm)
6669 {
6670 	jobmgr_t jmi = NULL, jmn = NULL;
6671 	SLIST_FOREACH_SAFE(jmi, &jm->submgrs, sle, jmn) {
6672 		jobmgr_do_garbage_collection(jmi);
6673 	}
6674 
6675 	if (!jm->shutting_down) {
6676 		return jm;
6677 	}
6678 
6679 	if (SLIST_EMPTY(&jm->submgrs)) {
6680 		jobmgr_log(jm, LOG_DEBUG, "No submanagers left.");
6681 	} else {
6682 		jobmgr_log(jm, LOG_DEBUG, "Still have submanagers.");
6683 		SLIST_FOREACH(jmi, &jm->submgrs, sle) {
6684 			jobmgr_log(jm, LOG_DEBUG, "Submanager: %s", jmi->name);
6685 		}
6686 	}
6687 
6688 	size_t actives = 0;
6689 	job_t ji = NULL, jn = NULL;
6690 	LIST_FOREACH_SAFE(ji, &jm->jobs, sle, jn) {
6691 		if (ji->anonymous) {
6692 			continue;
6693 		}
6694 
6695 		// Let the shutdown monitor be up until the very end.
6696 		if (ji->shutdown_monitor) {
6697 			continue;
6698 		}
6699 
6700 		/* On our first pass through, open a transaction for all the jobs that
6701 		 * need to be dirty at shutdown. We'll close these transactions once the
6702 		 * jobs that do not need to be dirty at shutdown have all exited.
6703 		 */
6704 		if (ji->dirty_at_shutdown && !jm->shutdown_jobs_dirtied) {
6705 			job_open_shutdown_transaction(ji);
6706 		}
6707 
6708 		const char *active = job_active(ji);
6709 		if (!active) {
6710 			job_remove(ji);
6711 		} else {
6712 			job_log(ji, LOG_DEBUG, "Job is active: %s", active);
6713 			job_stop(ji);
6714 
6715 			if (!ji->dirty_at_shutdown) {
6716 				actives++;
6717 			}
6718 
6719 			if (ji->clean_kill) {
6720 				job_log(ji, LOG_DEBUG, "Job was killed cleanly.");
6721 			} else {
6722 				job_log(ji, LOG_DEBUG, "Job was sent SIGTERM%s.", ji->sent_sigkill ? " and SIGKILL" : "");
6723 			}
6724 		}
6725 	}
6726 
6727 	jm->shutdown_jobs_dirtied = true;
6728 	if (actives == 0) {
6729 		if (!jm->shutdown_jobs_cleaned) {
6730 			/* Once all normal jobs have exited, we clean the dirty-at-shutdown
6731 			 * jobs and make them into normal jobs so that the above loop will
6732 			 * handle them appropriately.
6733 			 */
6734 			LIST_FOREACH(ji, &jm->jobs, sle) {
6735 				if (ji->anonymous) {
6736 					continue;
6737 				}
6738 
6739 				if (!job_active(ji)) {
6740 					continue;
6741 				}
6742 
6743 				if (ji->shutdown_monitor) {
6744 					continue;
6745 				}
6746 
6747 				job_close_shutdown_transaction(ji);
6748 				actives++;
6749 			}
6750 
6751 			jm->shutdown_jobs_cleaned = true;
6752 		}
6753 
6754 		if (SLIST_EMPTY(&jm->submgrs) && actives == 0) {
6755 			/* We may be in a situation where the shutdown monitor is all that's
6756 			 * left, in which case we want to stop it. Like dirty-at-shutdown
6757 			 * jobs, we turn it back into a normal job so that the main loop
6758 			 * treats it appropriately.
6759 			 *
6760 			 * See:
6761 			 * <rdar://problem/10756306>
6762 			 * <rdar://problem/11034971>
6763 			 * <rdar://problem/11549541>
6764 			 */
6765 			if (jm->monitor_shutdown && _launchd_shutdown_monitor) {
6766 				/* The rest of shutdown has completed, so we can kill the shutdown
6767 				 * monitor now like it was any other job.
6768 				 */
6769 				_launchd_shutdown_monitor->shutdown_monitor = false;
6770 
6771 				job_log(_launchd_shutdown_monitor, LOG_NOTICE | LOG_CONSOLE, "Stopping shutdown monitor.");
6772 				job_stop(_launchd_shutdown_monitor);
6773 				_launchd_shutdown_monitor = NULL;
6774 			} else {
6775 				jobmgr_log(jm, LOG_DEBUG, "Removing.");
6776 				jobmgr_remove(jm);
6777 				return NULL;
6778 			}
6779 		}
6780 	}
6781 
6782 	return jm;
6783 }
6784 
6785 void
jobmgr_kill_stray_children(jobmgr_t jm,pid_t * p,size_t np)6786 jobmgr_kill_stray_children(jobmgr_t jm, pid_t *p, size_t np)
6787 {
6788 	/* I maintain that stray processes should be at the mercy of launchd during
6789 	 * shutdown, but nevertheless, things like diskimages-helper can stick
6790 	 * around, and SIGKILLing them can result in data loss. So we send SIGTERM
6791 	 * to all the strays and don't wait for them to exit before moving on.
6792 	 *
6793 	 * See rdar://problem/6562592
6794 	 */
6795 	size_t i = 0;
6796 	for (i = 0; i < np; i++) {
6797 		if (p[i] != 0) {
6798 			jobmgr_log(jm, LOG_DEBUG | LOG_CONSOLE, "Sending SIGTERM to PID %u and continuing...", p[i]);
6799 			(void)jobmgr_assumes_zero_p(jm, kill2(p[i], SIGTERM));
6800 		}
6801 	}
6802 }
6803 
6804 void
jobmgr_log_stray_children(jobmgr_t jm,bool kill_strays)6805 jobmgr_log_stray_children(jobmgr_t jm, bool kill_strays)
6806 {
6807 	size_t kp_skipped = 0, len = sizeof(pid_t) * get_kern_max_proc();
6808 	pid_t *pids = NULL;
6809 	int i = 0, kp_cnt = 0;
6810 
6811 	if (likely(jm->parentmgr || !pid1_magic)) {
6812 		return;
6813 	}
6814 
6815 	if (!jobmgr_assumes(jm, (pids = malloc(len)) != NULL)) {
6816 		return;
6817 	}
6818 
6819 	runtime_ktrace0(RTKT_LAUNCHD_FINDING_ALL_STRAYS);
6820 
6821 	if (jobmgr_assumes_zero_p(jm, (kp_cnt = proc_listallpids(pids, len))) == -1) {
6822 		goto out;
6823 	}
6824 
6825 	pid_t *ps = (pid_t *)calloc(sizeof(pid_t), kp_cnt);
6826 	for (i = 0; i < kp_cnt; i++) {
6827 		struct proc_bsdshortinfo proc;
6828 		if (proc_pidinfo(pids[i], PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0) {
6829 			if (errno != ESRCH) {
6830 				(void)jobmgr_assumes_zero(jm, errno);
6831 			}
6832 
6833 			kp_skipped++;
6834 			continue;
6835 		}
6836 
6837 		pid_t p_i = pids[i];
6838 		pid_t pp_i = proc.pbsi_ppid;
6839 		pid_t pg_i = proc.pbsi_pgid;
6840 		const char *z = (proc.pbsi_status == SZOMB) ? "zombie " : "";
6841 		const char *n = proc.pbsi_comm;
6842 
6843 		if (unlikely(p_i == 0 || p_i == 1)) {
6844 			kp_skipped++;
6845 			continue;
6846 		}
6847 
6848 		if (_launchd_shutdown_monitor && pp_i == _launchd_shutdown_monitor->p) {
6849 			kp_skipped++;
6850 			continue;
6851 		}
6852 
6853 		// We might have some jobs hanging around that we've decided to shut down in spite of.
6854 		job_t j = jobmgr_find_by_pid(jm, p_i, false);
6855 		if (!j || (j && j->anonymous)) {
6856 			jobmgr_log(jm, LOG_INFO | LOG_CONSOLE, "Stray %s%s at shutdown: PID %u PPID %u PGID %u %s", z, j ? "anonymous job" : "process", p_i, pp_i, pg_i, n);
6857 
6858 			int status = 0;
6859 			if (pp_i == getpid() && !jobmgr_assumes(jm, proc.pbsi_status != SZOMB)) {
6860 				if (jobmgr_assumes_zero(jm, waitpid(p_i, &status, WNOHANG)) == 0) {
6861 					jobmgr_log(jm, LOG_INFO | LOG_CONSOLE, "Unreaped zombie stray exited with status %i.", WEXITSTATUS(status));
6862 				}
6863 				kp_skipped++;
6864 			} else {
6865 				job_t leader = jobmgr_find_by_pid(jm, pg_i, false);
6866 				/* See rdar://problem/6745714. Some jobs have child processes that back kernel state,
6867 				 * so we don't want to terminate them. Long-term, I'd really like to provide shutdown
6868 				 * hints to the kernel along the way, so that it could shutdown certain subsystems when
6869 				 * their userspace emissaries go away, before the call to reboot(2).
6870 				 */
6871 				if (leader && leader->ignore_pg_at_shutdown) {
6872 					kp_skipped++;
6873 				} else {
6874 					ps[i] = p_i;
6875 				}
6876 			}
6877 		} else {
6878 			kp_skipped++;
6879 		}
6880 	}
6881 
6882 	if ((kp_cnt - kp_skipped > 0) && kill_strays) {
6883 		jobmgr_kill_stray_children(jm, ps, kp_cnt - kp_skipped);
6884 	}
6885 
6886 	free(ps);
6887 out:
6888 	free(pids);
6889 }
6890 
6891 jobmgr_t
jobmgr_parent(jobmgr_t jm)6892 jobmgr_parent(jobmgr_t jm)
6893 {
6894 	return jm->parentmgr;
6895 }
6896 
6897 void
job_uncork_fork(job_t j)6898 job_uncork_fork(job_t j)
6899 {
6900 	pid_t c = j->p;
6901 
6902 	job_log(j, LOG_DEBUG, "Uncorking the fork().");
6903 	/* this unblocks the child and avoids a race
6904 	 * between the above fork() and the kevent_mod() */
6905 	(void)job_assumes(j, write(j->fork_fd, &c, sizeof(c)) == sizeof(c));
6906 	(void)job_assumes_zero_p(j, runtime_close(j->fork_fd));
6907 	j->fork_fd = 0;
6908 }
6909 
6910 jobmgr_t
jobmgr_new(jobmgr_t jm,mach_port_t requestorport,mach_port_t transfer_port,bool sflag,const char * name,bool skip_init,mach_port_t asport)6911 jobmgr_new(jobmgr_t jm, mach_port_t requestorport, mach_port_t transfer_port, bool sflag, const char *name, bool skip_init, mach_port_t asport)
6912 {
6913 	job_t bootstrapper = NULL;
6914 	jobmgr_t jmr;
6915 
6916 	__OS_COMPILETIME_ASSERT__(offsetof(struct jobmgr_s, kqjobmgr_callback) == 0);
6917 
6918 	if (unlikely(jm && requestorport == MACH_PORT_NULL)) {
6919 		syslog(LOG_ERR, "no requester port!!!!");
6920 		jobmgr_log(jm, LOG_ERR, "Mach sub-bootstrap create request requires a requester port");
6921 		return NULL;
6922 	}
6923 
6924 	jmr = calloc(1, sizeof(struct jobmgr_s) + (name ? (strlen(name) + 1) : NAME_MAX + 1));
6925 
6926 	if (!jobmgr_assumes(jm, jmr != NULL)) {
6927 		return NULL;
6928 	}
6929 
6930 	if (jm == NULL) {
6931 		root_jobmgr = jmr;
6932 	}
6933 
6934 	jmr->kqjobmgr_callback = jobmgr_callback;
6935 	strcpy(jmr->name_init, name ? name : "Under construction");
6936 
6937 	jmr->req_port = requestorport;
6938 
6939 	if ((jmr->parentmgr = jm)) {
6940 		SLIST_INSERT_HEAD(&jm->submgrs, jmr, sle);
6941 	}
6942 	syslog(LOG_ERR, "if jm=%p then launchd_mport_notify_req transfer_port=%d", jm, transfer_port);
6943 	if (jm && jobmgr_assumes_zero(jmr, launchd_mport_notify_req(jmr->req_port, MACH_NOTIFY_DEAD_NAME)) != KERN_SUCCESS) {
6944 		syslog(LOG_ERR, "launchd_mport_notify_req failed!!!");
6945 		sleep(1);
6946 		goto out_bad;
6947 	}
6948 
6949 	if (transfer_port != MACH_PORT_NULL) {
6950 		syslog(LOG_ERR, "transfer_port=%d\n", transfer_port);
6951 		(void)jobmgr_assumes(jmr, jm != NULL);
6952 		jmr->jm_port = transfer_port;
6953 	} else if (!jm && !pid1_magic && uflag == false) {
6954 		char *trusted_fd = getenv(LAUNCHD_TRUSTED_FD_ENV);
6955 		name_t service_buf;
6956 
6957 		snprintf(service_buf, sizeof(service_buf), "com.apple.launchd.peruser.%u", getuid());
6958 
6959 		if (uflag == false && jobmgr_assumes_zero(jmr, bootstrap_check_in(bootstrap_port, service_buf, &jmr->jm_port)) != 0) {
6960 			goto out_bad;
6961 		}
6962 
6963 		if (trusted_fd) {
6964 			int dfd, lfd = (int) strtol(trusted_fd, NULL, 10);
6965 
6966 			if ((dfd = dup(lfd)) >= 0) {
6967 				(void)jobmgr_assumes_zero_p(jmr, runtime_close(dfd));
6968 				(void)jobmgr_assumes_zero_p(jmr, runtime_close(lfd));
6969 			}
6970 
6971 			unsetenv(LAUNCHD_TRUSTED_FD_ENV);
6972 		}
6973 
6974 		// cut off the Libc cache, we don't want to deadlock against ourself
6975 		inherited_bootstrap_port = bootstrap_port;
6976 		bootstrap_port = MACH_PORT_NULL;
6977 		os_assert_zero(launchd_mport_notify_req(inherited_bootstrap_port, MACH_NOTIFY_DEAD_NAME));
6978 
6979 		// We set this explicitly as we start each child
6980 		os_assert_zero(launchd_set_bport(MACH_PORT_NULL));
6981 	} else if (jobmgr_assumes_zero(jmr, launchd_mport_create_recv(&jmr->jm_port)) != KERN_SUCCESS) {
6982 		syslog(LOG_ERR, "launchd_mport_create_recv failed");
6983 		goto out_bad;
6984 	}
6985 		syslog(LOG_ERR, "launchd_mport_create_recv(=%d)\n", jmr->jm_port);
6986 	if (!name) {
6987 		sprintf(jmr->name_init, "%u", MACH_PORT_INDEX(jmr->jm_port));
6988 	}
6989 
6990 	if (!jm) {
6991 		syslog(LOG_ERR, "kevent_moddding");
6992 		(void)jobmgr_assumes_zero_p(jmr, kevent_mod(SIGTERM, EVFILT_SIGNAL, EV_ADD, 0, 0, jmr));
6993 		(void)jobmgr_assumes_zero_p(jmr, kevent_mod(SIGUSR1, EVFILT_SIGNAL, EV_ADD, 0, 0, jmr));
6994 		(void)jobmgr_assumes_zero_p(jmr, kevent_mod(SIGUSR2, EVFILT_SIGNAL, EV_ADD, 0, 0, jmr));
6995 		(void)jobmgr_assumes_zero_p(jmr, kevent_mod(SIGINFO, EVFILT_SIGNAL, EV_ADD, 0, 0, jmr));
6996 		(void)jobmgr_assumes_zero_p(jmr, kevent_mod(0, EVFILT_FS, EV_ADD, VQ_MOUNT|VQ_UNMOUNT|VQ_UPDATE, 0, jmr));
6997 	}
6998 
6999 	if (name && !skip_init) {
7000 		syslog(LOG_ERR, "jobmgr_init_session");
7001 		bootstrapper = jobmgr_init_session(jmr, name, sflag);
7002 	}
7003 
7004 	if (!bootstrapper || !bootstrapper->weird_bootstrap || uflag == true) {
7005 		if (jobmgr_assumes_zero(jmr, runtime_add_mport(jmr->jm_port, job_server)) != KERN_SUCCESS) {
7006 			goto out_bad;
7007 		}
7008 	}
7009 	syslog(LOG_ERR, "jobmgr created!!!!");
7010 	jobmgr_log(jmr, LOG_DEBUG, "Created job manager%s%s", jm ? " with parent: " : ".", jm ? jm->name : "");
7011 
7012 	if (bootstrapper) {
7013 		bootstrapper->asport = asport;
7014 
7015 		jobmgr_log(jmr, LOG_DEBUG, "Bootstrapping new job manager with audit session %u", asport);
7016 		(void)jobmgr_assumes(jmr, job_dispatch(bootstrapper, true) != NULL);
7017 	} else {
7018 		jmr->req_asport = asport;
7019 	}
7020 
7021 	if (asport != MACH_PORT_NULL) {
7022 		(void)jobmgr_assumes_zero(jmr, launchd_mport_copy_send(asport));
7023 	}
7024 
7025 	if (jmr->parentmgr) {
7026 		runtime_add_weak_ref();
7027 	}
7028 
7029 	return jmr;
7030 
7031 out_bad:
7032 	if (jmr) {
7033 		jobmgr_remove(jmr);
7034 		if (jm == NULL) {
7035 			root_jobmgr = NULL;
7036 		}
7037 	}
7038 	return NULL;
7039 }
7040 
7041 jobmgr_t
jobmgr_new_xpc_singleton_domain(jobmgr_t jm,name_t name)7042 jobmgr_new_xpc_singleton_domain(jobmgr_t jm, name_t name)
7043 {
7044 	jobmgr_t new = NULL;
7045 
7046 	/* These job managers are basically singletons, so we use the root Mach
7047 	 * bootstrap port as their requestor ports so they'll never go away.
7048 	 */
7049 	mach_port_t req_port = root_jobmgr->jm_port;
7050 	if (jobmgr_assumes_zero(jm, launchd_mport_make_send(req_port)) == KERN_SUCCESS) {
7051 		new = jobmgr_new(root_jobmgr, req_port, MACH_PORT_NULL, false, name, true, MACH_PORT_NULL);
7052 		if (new) {
7053 			new->properties |= BOOTSTRAP_PROPERTY_XPC_SINGLETON;
7054 			new->properties |= BOOTSTRAP_PROPERTY_XPC_DOMAIN;
7055 			new->xpc_singleton = true;
7056 		}
7057 	}
7058 
7059 	return new;
7060 }
7061 
7062 jobmgr_t
jobmgr_find_xpc_per_user_domain(jobmgr_t jm,uid_t uid)7063 jobmgr_find_xpc_per_user_domain(jobmgr_t jm, uid_t uid)
7064 {
7065 	jobmgr_t jmi = NULL;
7066 	LIST_FOREACH(jmi, &_s_xpc_user_domains, xpc_le) {
7067 		if (jmi->req_euid == uid) {
7068 			return jmi;
7069 		}
7070 	}
7071 
7072 	name_t name;
7073 	(void)snprintf(name, sizeof(name), "com.apple.xpc.domain.peruser.%u", uid);
7074 	jmi = jobmgr_new_xpc_singleton_domain(jm, name);
7075 	if (jobmgr_assumes(jm, jmi != NULL)) {
7076 		/* We need to create a per-user launchd for this UID if there isn't one
7077 		 * already so we can grab the bootstrap port.
7078 		 */
7079 		job_t puj = jobmgr_lookup_per_user_context_internal(NULL, uid, &jmi->req_bsport);
7080 		if (jobmgr_assumes(jmi, puj != NULL)) {
7081 			(void)jobmgr_assumes_zero(jmi, launchd_mport_copy_send(puj->asport));
7082 			(void)jobmgr_assumes_zero(jmi, launchd_mport_copy_send(jmi->req_bsport));
7083 			jmi->shortdesc = "per-user";
7084 			jmi->req_asport = puj->asport;
7085 			jmi->req_asid = puj->asid;
7086 			jmi->req_euid = uid;
7087 			jmi->req_egid = -1;
7088 
7089 			LIST_INSERT_HEAD(&_s_xpc_user_domains, jmi, xpc_le);
7090 		} else {
7091 			jobmgr_remove(jmi);
7092 		}
7093 	}
7094 
7095 	return jmi;
7096 }
7097 
7098 jobmgr_t
jobmgr_find_xpc_per_session_domain(jobmgr_t jm,au_asid_t asid)7099 jobmgr_find_xpc_per_session_domain(jobmgr_t jm, au_asid_t asid)
7100 {
7101 	jobmgr_t jmi = NULL;
7102 	LIST_FOREACH(jmi, &_s_xpc_session_domains, xpc_le) {
7103 		if (jmi->req_asid == asid) {
7104 			return jmi;
7105 		}
7106 	}
7107 
7108 	name_t name;
7109 	(void)snprintf(name, sizeof(name), "com.apple.xpc.domain.persession.%i", asid);
7110 	jmi = jobmgr_new_xpc_singleton_domain(jm, name);
7111 	if (jobmgr_assumes(jm, jmi != NULL)) {
7112 		(void)jobmgr_assumes_zero(jmi, launchd_mport_make_send(root_jobmgr->jm_port));
7113 		jmi->shortdesc = "per-session";
7114 		jmi->req_bsport = root_jobmgr->jm_port;
7115 #ifdef notyet
7116 		(void)jobmgr_assumes_zero(jmi, audit_session_port(asid, &jmi->req_asport));
7117 #endif
7118 		jmi->req_asid = asid;
7119 		jmi->req_euid = -1;
7120 		jmi->req_egid = -1;
7121 
7122 		LIST_INSERT_HEAD(&_s_xpc_session_domains, jmi, xpc_le);
7123 	} else {
7124 		jobmgr_remove(jmi);
7125 	}
7126 
7127 	return jmi;
7128 }
7129 
7130 job_t
jobmgr_init_session(jobmgr_t jm,const char * session_type,bool sflag)7131 jobmgr_init_session(jobmgr_t jm, const char *session_type, bool sflag)
7132 {
7133 	const char *bootstrap_tool[] = { "/bin/launchctl", "bootstrap", "-S", session_type, sflag ? "-s" : NULL, NULL };
7134 	char thelabel[1000];
7135 	job_t bootstrapper;
7136 
7137 	snprintf(thelabel, sizeof(thelabel), "com.apple.launchctl.%s", session_type);
7138 	bootstrapper = job_new(jm, thelabel, NULL, bootstrap_tool);
7139 
7140 	if (jobmgr_assumes(jm, bootstrapper != NULL) && (jm->parentmgr || !pid1_magic)) {
7141 		bootstrapper->is_bootstrapper = true;
7142 		char buf[100];
7143 
7144 		// <rdar://problem/5042202> launchd-201: can't ssh in with AFP OD account (hangs)
7145 		snprintf(buf, sizeof(buf), "0x%X:0:0", getuid());
7146 		envitem_new(bootstrapper, "__CF_USER_TEXT_ENCODING", buf, false);
7147 		bootstrapper->weird_bootstrap = true;
7148 		(void)jobmgr_assumes(jm, job_setup_machport(bootstrapper));
7149 	} else if (bootstrapper && strncmp(session_type, VPROCMGR_SESSION_SYSTEM, sizeof(VPROCMGR_SESSION_SYSTEM)) == 0) {
7150 #if TARGET_OS_EMBEDDED
7151 		bootstrapper->psproctype = POSIX_SPAWN_PROC_TYPE_DAEMON_INTERACTIVE;
7152 #endif
7153 		bootstrapper->is_bootstrapper = true;
7154 		if (jobmgr_assumes(jm, pid1_magic)) {
7155 			// Have our system bootstrapper print out to the console.
7156 			bootstrapper->stdoutpath = strdup(_PATH_CONSOLE);
7157 			bootstrapper->stderrpath = strdup(_PATH_CONSOLE);
7158 
7159 			if (launchd_console) {
7160 				(void)jobmgr_assumes_zero_p(jm, kevent_mod((uintptr_t)fileno(launchd_console), EVFILT_VNODE, EV_ADD | EV_ONESHOT, NOTE_REVOKE, 0, jm));
7161 			}
7162 		}
7163 	}
7164 
7165 	jm->session_initialized = true;
7166 	return bootstrapper;
7167 }
7168 
7169 jobmgr_t
jobmgr_delete_anything_with_port(jobmgr_t jm,mach_port_t port)7170 jobmgr_delete_anything_with_port(jobmgr_t jm, mach_port_t port)
7171 {
7172 	struct machservice *ms, *next_ms;
7173 	jobmgr_t jmi, jmn;
7174 
7175 	/* Mach ports, unlike Unix descriptors, are reference counted. In other
7176 	 * words, when some program hands us a second or subsequent send right to a
7177 	 * port we already have open, the Mach kernel gives us the same port number
7178 	 * back and increments an reference count associated with the port. This
7179 	 * This forces us, when discovering that a receive right at the other end
7180 	 * has been deleted, to wander all of our objects to see what weird places
7181 	 * clients might have handed us the same send right to use.
7182 	 */
7183 
7184 	if (jm == root_jobmgr) {
7185 		if (port == inherited_bootstrap_port) {
7186 			(void)jobmgr_assumes_zero(jm, launchd_mport_deallocate(port));
7187 			inherited_bootstrap_port = MACH_PORT_NULL;
7188 
7189 			return jobmgr_shutdown(jm);
7190 		}
7191 
7192 		LIST_FOREACH_SAFE(ms, &port_hash[HASH_PORT(port)], port_hash_sle, next_ms) {
7193 			if (ms->port == port && !ms->recv) {
7194 				machservice_delete(ms->job, ms, true);
7195 			}
7196 		}
7197 	}
7198 
7199 	SLIST_FOREACH_SAFE(jmi, &jm->submgrs, sle, jmn) {
7200 		jobmgr_delete_anything_with_port(jmi, port);
7201 	}
7202 
7203 	if (jm->req_port == port) {
7204 		jobmgr_log(jm, LOG_DEBUG, "Request port died: %i", MACH_PORT_INDEX(port));
7205 		return jobmgr_shutdown(jm);
7206 	}
7207 
7208 	struct waiting4attach *w4ai = NULL;
7209 	struct waiting4attach *w4ait = NULL;
7210 	LIST_FOREACH_SAFE(w4ai, &jm->attaches, le, w4ait) {
7211 		if (port == w4ai->port) {
7212 			waiting4attach_delete(jm, w4ai);
7213 			break;
7214 		}
7215 	}
7216 
7217 	return jm;
7218 }
7219 
7220 void
jobmgr_reap_pid(jobmgr_t jm,pid_t pid)7221 jobmgr_reap_pid(jobmgr_t jm, pid_t pid)
7222 {
7223 	if (jobmgr_find_by_pid_deep(jm, pid, true) != NULL)
7224 		return;
7225 
7226 	waitpid(pid, (int *) 0, 0);
7227 	jobmgr_log(jm, LOG_DEBUG, "Reaping PID %d", pid);
7228 }
7229 
7230 struct machservice *
jobmgr_lookup_service(jobmgr_t jm,const char * name,bool check_parent,pid_t target_pid)7231 jobmgr_lookup_service(jobmgr_t jm, const char *name, bool check_parent, pid_t target_pid)
7232 {
7233 	struct machservice *ms;
7234 	job_t target_j;
7235 
7236 	jobmgr_log(jm, LOG_DEBUG, "Looking up %sservice %s", target_pid ? "per-PID " : "", name);
7237 
7238 	if (target_pid) {
7239 		/* This is a hack to let FileSyncAgent look up per-PID Mach services from the Background
7240 		 * bootstrap in other bootstraps.
7241 		 */
7242 
7243 		// Start in the given bootstrap.
7244 		if (unlikely((target_j = jobmgr_find_by_pid(jm, target_pid, false)) == NULL)) {
7245 			// If we fail, do a deep traversal.
7246 			if (unlikely((target_j = jobmgr_find_by_pid_deep(root_jobmgr, target_pid, true)) == NULL)) {
7247 				jobmgr_log(jm, LOG_DEBUG, "Didn't find PID %i", target_pid);
7248 				return NULL;
7249 			}
7250 		}
7251 
7252 		SLIST_FOREACH(ms, &target_j->machservices, sle) {
7253 			if (ms->per_pid && strcmp(name, ms->name) == 0) {
7254 				return ms;
7255 			}
7256 		}
7257 
7258 		job_log(target_j, LOG_DEBUG, "Didn't find per-PID Mach service: %s", name);
7259 		return NULL;
7260 	}
7261 
7262 	jobmgr_t where2look = jm;
7263 	// XPC domains are separate from Mach bootstraps.
7264 	if (!(jm->properties & BOOTSTRAP_PROPERTY_XPC_DOMAIN)) {
7265 		if (launchd_flat_mach_namespace && !(jm->properties & BOOTSTRAP_PROPERTY_EXPLICITSUBSET)) {
7266 			where2look = root_jobmgr;
7267 		}
7268 	}
7269 
7270 	LIST_FOREACH(ms, &where2look->ms_hash[hash_ms(name)], name_hash_sle) {
7271 		if (!ms->per_pid && strcmp(name, ms->name) == 0) {
7272 			return ms;
7273 		}
7274 	}
7275 
7276 	if (jm->parentmgr == NULL || !check_parent) {
7277 		return NULL;
7278 	}
7279 
7280 	return jobmgr_lookup_service(jm->parentmgr, name, true, 0);
7281 }
7282 
7283 mach_port_t
machservice_port(struct machservice * ms)7284 machservice_port(struct machservice *ms)
7285 {
7286 	return ms->port;
7287 }
7288 
7289 job_t
machservice_job(struct machservice * ms)7290 machservice_job(struct machservice *ms)
7291 {
7292 	return ms->job;
7293 }
7294 
7295 bool
machservice_hidden(struct machservice * ms)7296 machservice_hidden(struct machservice *ms)
7297 {
7298 	return ms->hide;
7299 }
7300 
7301 bool
machservice_active(struct machservice * ms)7302 machservice_active(struct machservice *ms)
7303 {
7304 	return ms->isActive;
7305 }
7306 
7307 const char *
machservice_name(struct machservice * ms)7308 machservice_name(struct machservice *ms)
7309 {
7310 	return ms->name;
7311 }
7312 
7313 void
machservice_drain_port(struct machservice * ms)7314 machservice_drain_port(struct machservice *ms)
7315 {
7316 	bool drain_one = ms->drain_one_on_crash;
7317 	bool drain_all = ms->drain_all_on_crash;
7318 
7319 
7320 	if (!job_assumes(ms->job, (drain_one || drain_all) == true)) {
7321 		return;
7322 	}
7323 
7324 	job_log(ms->job, LOG_INFO, "Draining %s...", ms->name);
7325 	char *req_buff = calloc(2, sizeof(union __RequestUnion__catch_mach_exc_subsystem));
7326 	char *rep_buff = calloc(1, sizeof(union __ReplyUnion__catch_mach_exc_subsystem));
7327 	mig_reply_error_t *req_hdr = (mig_reply_error_t *)&req_buff;
7328 	mig_reply_error_t *rep_hdr = (mig_reply_error_t *)&rep_buff;
7329 
7330 	mach_msg_return_t mr = ~MACH_MSG_SUCCESS;
7331 
7332 	do {
7333 		/* This should be a direct check on the Mach service to see if it's an exception-handling
7334 		 * port, and it will break things if ReportCrash or SafetyNet start advertising other
7335 		 * Mach services. But for now, it should be okay.
7336 		 */
7337 		if (ms->job->alt_exc_handler || ms->job->internal_exc_handler) {
7338 			mr = launchd_exc_runtime_once(ms->port, sizeof(req_buff), sizeof(rep_buff), req_hdr, rep_hdr, 0);
7339 		} else {
7340 			mach_msg_options_t options =	MACH_RCV_MSG		|
7341 											MACH_RCV_TIMEOUT	;
7342 
7343 			mr = mach_msg((mach_msg_header_t *)req_hdr, options, 0, sizeof(req_buff), ms->port, 0, MACH_PORT_NULL);
7344 			switch (mr) {
7345 			case MACH_MSG_SUCCESS:
7346 				mach_msg_destroy((mach_msg_header_t *)req_hdr);
7347 				break;
7348 			case MACH_RCV_TIMED_OUT:
7349 				break;
7350 			case MACH_RCV_TOO_LARGE:
7351 				launchd_syslog(LOG_WARNING, "Tried to receive message that was larger than %lu bytes", sizeof(req_buff));
7352 				break;
7353 			default:
7354 				break;
7355 			}
7356 		}
7357 	} while (drain_all && mr != MACH_RCV_TIMED_OUT);
7358 }
7359 
7360 void
machservice_delete(job_t j,struct machservice * ms,bool port_died)7361 machservice_delete(job_t j, struct machservice *ms, bool port_died)
7362 {
7363 	if (ms->alias) {
7364 		/* HACK: Egregious code duplication. But dealing with aliases is a
7365 		 * pretty simple affair since they can't and shouldn't have any complex
7366 		 * behaviors associated with them.
7367 		 */
7368 		LIST_REMOVE(ms, name_hash_sle);
7369 		SLIST_REMOVE(&j->machservices, ms, machservice, sle);
7370 		free(ms);
7371 		return;
7372 	}
7373 
7374 	if (unlikely(ms->debug_on_close)) {
7375 		job_log(j, LOG_NOTICE, "About to enter kernel debugger because of Mach port: 0x%x", ms->port);
7376 		(void)job_assumes_zero(j, host_reboot(mach_host_self(), HOST_REBOOT_DEBUGGER));
7377 	}
7378 
7379 	if (ms->recv && job_assumes(j, !machservice_active(ms))) {
7380 		job_log(j, LOG_DEBUG, "Closing receive right for %s", ms->name);
7381 		(void)job_assumes_zero(j, launchd_mport_close_recv(ms->port));
7382 	}
7383 
7384 	(void)job_assumes_zero(j, launchd_mport_deallocate(ms->port));
7385 
7386 	if (unlikely(ms->port == the_exception_server)) {
7387 		the_exception_server = 0;
7388 	}
7389 
7390 	job_log(j, LOG_DEBUG, "Mach service deleted%s: %s", port_died ? " (port died)" : "", ms->name);
7391 
7392 	if (ms->special_port_num) {
7393 		SLIST_REMOVE(&special_ports, ms, machservice, special_port_sle);
7394 	}
7395 	SLIST_REMOVE(&j->machservices, ms, machservice, sle);
7396 
7397 	if (!(j->dedicated_instance || ms->event_channel)) {
7398 		LIST_REMOVE(ms, name_hash_sle);
7399 	}
7400 	LIST_REMOVE(ms, port_hash_sle);
7401 
7402 	free(ms);
7403 }
7404 
7405 void
machservice_request_notifications(struct machservice * ms)7406 machservice_request_notifications(struct machservice *ms)
7407 {
7408 	mach_msg_id_t which = MACH_NOTIFY_DEAD_NAME;
7409 
7410 	ms->isActive = true;
7411 
7412 	if (ms->recv) {
7413 		which = MACH_NOTIFY_PORT_DESTROYED;
7414 		job_checkin(ms->job);
7415 	}
7416 
7417 	(void)job_assumes_zero(ms->job, launchd_mport_notify_req(ms->port, which));
7418 }
7419 
7420 #define NELEM(x) (sizeof(x)/sizeof(x[0]))
7421 #define END_OF(x) (&(x)[NELEM(x)])
7422 
7423 char **
mach_cmd2argv(const char * string)7424 mach_cmd2argv(const char *string)
7425 {
7426 	char *argv[100], args[1000];
7427 	const char *cp;
7428 	char *argp = args, term, **argv_ret, *co;
7429 	unsigned int nargs = 0, i;
7430 
7431 	for (cp = string; *cp;) {
7432 		while (isspace(*cp))
7433 			cp++;
7434 		term = (*cp == '"') ? *cp++ : '\0';
7435 		if (nargs < NELEM(argv)) {
7436 			argv[nargs++] = argp;
7437 		}
7438 		while (*cp && (term ? *cp != term : !isspace(*cp)) && argp < END_OF(args)) {
7439 			if (*cp == '\\') {
7440 				cp++;
7441 			}
7442 			*argp++ = *cp;
7443 			if (*cp) {
7444 				cp++;
7445 			}
7446 		}
7447 		*argp++ = '\0';
7448 	}
7449 	argv[nargs] = NULL;
7450 
7451 	if (nargs == 0) {
7452 		return NULL;
7453 	}
7454 
7455 	argv_ret = malloc((nargs + 1) * sizeof(char *) + strlen(string) + 1);
7456 
7457 	if (!argv_ret) {
7458 		(void)os_assumes_zero(errno);
7459 		return NULL;
7460 	}
7461 
7462 	co = (char *)argv_ret + (nargs + 1) * sizeof(char *);
7463 
7464 	for (i = 0; i < nargs; i++) {
7465 		strcpy(co, argv[i]);
7466 		argv_ret[i] = co;
7467 		co += strlen(argv[i]) + 1;
7468 	}
7469 	argv_ret[i] = NULL;
7470 
7471 	return argv_ret;
7472 }
7473 
7474 void
job_checkin(job_t j)7475 job_checkin(job_t j)
7476 {
7477 	j->checkedin = true;
7478 }
7479 
job_is_god(job_t j)7480 bool job_is_god(job_t j)
7481 {
7482 	return j->embedded_god;
7483 }
7484 
7485 bool
job_ack_port_destruction(mach_port_t p)7486 job_ack_port_destruction(mach_port_t p)
7487 {
7488 	struct machservice *ms;
7489 	job_t j;
7490 
7491 	LIST_FOREACH(ms, &port_hash[HASH_PORT(p)], port_hash_sle) {
7492 		if (ms->recv && (ms->port == p)) {
7493 			break;
7494 		}
7495 	}
7496 
7497 	if (!ms) {
7498 		launchd_syslog(LOG_WARNING, "Could not find MachService to match receive right: 0x%x", p);
7499 		return false;
7500 	}
7501 
7502 	j = ms->job;
7503 
7504 	jobmgr_log(root_jobmgr, LOG_DEBUG, "Receive right returned to us: %s", ms->name);
7505 
7506 	/* Without being the exception handler, NOTE_EXIT is our only way to tell if
7507 	 * the job  crashed, and we can't rely on NOTE_EXIT always being processed
7508 	 * after all the job's receive rights have been returned.
7509 	 *
7510 	 * So when we get receive rights back, check to see if the job has been
7511 	 * reaped yet. If not, then we add this service to a list of services to be
7512 	 * drained on crash if it's requested that behavior. So, for a job with N
7513 	 * receive rights all requesting that they be drained on crash, we can
7514 	 * safely handle the following sequence of events.
7515 	 *
7516 	 * ReceiveRight0Returned
7517 	 * ReceiveRight1Returned
7518 	 * ReceiveRight2Returned
7519 	 * NOTE_EXIT (reap, get exit status)
7520 	 * ReceiveRight3Returned
7521 	 * .
7522 	 * .
7523 	 * .
7524 	 * ReceiveRight(N - 1)Returned
7525 	 */
7526 	if (ms->drain_one_on_crash || ms->drain_all_on_crash) {
7527 		if (j->crashed && j->reaped) {
7528 			job_log(j, LOG_DEBUG, "Job has crashed. Draining port...");
7529 			machservice_drain_port(ms);
7530 		} else if (!(j->crashed || j->reaped)) {
7531 			job_log(j, LOG_DEBUG, "Job's exit status is still unknown. Deferring drain.");
7532 		}
7533 	}
7534 
7535 	ms->isActive = false;
7536 	if (ms->delete_on_destruction) {
7537 		machservice_delete(j, ms, false);
7538 	} else if (ms->reset) {
7539 		machservice_resetport(j, ms);
7540 	}
7541 
7542 	kern_return_t kr = mach_port_set_attributes(mach_task_self(), ms->port, MACH_PORT_TEMPOWNER, NULL, 0);
7543 	(void)job_assumes_zero(j, kr);
7544 	machservice_stamp_port(j, ms);
7545 	job_dispatch(j, false);
7546 
7547 	if (ms->recv_race_hack) {
7548 		ms->recv_race_hack = false;
7549 		machservice_watch(ms->job, ms);
7550 	}
7551 
7552 	root_jobmgr = jobmgr_do_garbage_collection(root_jobmgr);
7553 
7554 	return true;
7555 }
7556 
7557 void
job_ack_no_senders(job_t j)7558 job_ack_no_senders(job_t j)
7559 {
7560 	j->priv_port_has_senders = false;
7561 
7562 	(void)job_assumes_zero(j, launchd_mport_close_recv(j->j_port));
7563 	j->j_port = 0;
7564 
7565 	job_log(j, LOG_DEBUG, "No more senders on privileged Mach bootstrap port");
7566 
7567 	job_dispatch(j, false);
7568 }
7569 
7570 bool
semaphoreitem_new(job_t j,semaphore_reason_t why,const char * what)7571 semaphoreitem_new(job_t j, semaphore_reason_t why, const char *what)
7572 {
7573 	struct semaphoreitem *si;
7574 	size_t alloc_sz = sizeof(struct semaphoreitem);
7575 
7576 	if (what) {
7577 		alloc_sz += strlen(what) + 1;
7578 	}
7579 
7580 	if (job_assumes(j, si = calloc(1, alloc_sz)) == NULL) {
7581 		return false;
7582 	}
7583 
7584 	si->why = why;
7585 
7586 	if (what) {
7587 		strcpy(si->what_init, what);
7588 	}
7589 
7590 	SLIST_INSERT_HEAD(&j->semaphores, si, sle);
7591 
7592 	if ((why == OTHER_JOB_ENABLED || why == OTHER_JOB_DISABLED) && !j->nosy) {
7593 		job_log(j, LOG_DEBUG, "Job is interested in \"%s\".", what);
7594 		SLIST_INSERT_HEAD(&s_curious_jobs, j, curious_jobs_sle);
7595 		j->nosy = true;
7596 	}
7597 
7598 	semaphoreitem_runtime_mod_ref(si, true);
7599 
7600 	return true;
7601 }
7602 
7603 void
semaphoreitem_runtime_mod_ref(struct semaphoreitem * si,bool add)7604 semaphoreitem_runtime_mod_ref(struct semaphoreitem *si, bool add)
7605 {
7606 	/*
7607 	 * External events need to be tracked.
7608 	 * Internal events do NOT need to be tracked.
7609 	 */
7610 
7611 	switch (si->why) {
7612 	case SUCCESSFUL_EXIT:
7613 	case FAILED_EXIT:
7614 	case OTHER_JOB_ENABLED:
7615 	case OTHER_JOB_DISABLED:
7616 	case OTHER_JOB_ACTIVE:
7617 	case OTHER_JOB_INACTIVE:
7618 		return;
7619 	default:
7620 		break;
7621 	}
7622 
7623 	if (add) {
7624 		runtime_add_weak_ref();
7625 	} else {
7626 		runtime_del_weak_ref();
7627 	}
7628 }
7629 
7630 void
semaphoreitem_delete(job_t j,struct semaphoreitem * si)7631 semaphoreitem_delete(job_t j, struct semaphoreitem *si)
7632 {
7633 	semaphoreitem_runtime_mod_ref(si, false);
7634 
7635 	SLIST_REMOVE(&j->semaphores, si, semaphoreitem, sle);
7636 
7637 	// We'll need to rethink this if it ever becomes possible to dynamically add or remove semaphores.
7638 	if ((si->why == OTHER_JOB_ENABLED || si->why == OTHER_JOB_DISABLED) && j->nosy) {
7639 		j->nosy = false;
7640 		SLIST_REMOVE(&s_curious_jobs, j, job_s, curious_jobs_sle);
7641 	}
7642 
7643 	free(si);
7644 }
7645 
7646 void
semaphoreitem_setup_dict_iter(launch_data_t obj,const char * key,void * context)7647 semaphoreitem_setup_dict_iter(launch_data_t obj, const char *key, void *context)
7648 {
7649 	struct semaphoreitem_dict_iter_context *sdic = context;
7650 	semaphore_reason_t why;
7651 
7652 	why = launch_data_get_bool(obj) ? sdic->why_true : sdic->why_false;
7653 
7654 	semaphoreitem_new(sdic->j, why, key);
7655 }
7656 
7657 void
semaphoreitem_setup(launch_data_t obj,const char * key,void * context)7658 semaphoreitem_setup(launch_data_t obj, const char *key, void *context)
7659 {
7660 	struct semaphoreitem_dict_iter_context sdic = { context, 0, 0 };
7661 	job_t j = context;
7662 	semaphore_reason_t why;
7663 
7664 	switch (launch_data_get_type(obj)) {
7665 	case LAUNCH_DATA_BOOL:
7666 		if (strcasecmp(key, LAUNCH_JOBKEY_KEEPALIVE_NETWORKSTATE) == 0) {
7667 			why = launch_data_get_bool(obj) ? NETWORK_UP : NETWORK_DOWN;
7668 			semaphoreitem_new(j, why, NULL);
7669 		} else if (strcasecmp(key, LAUNCH_JOBKEY_KEEPALIVE_SUCCESSFULEXIT) == 0) {
7670 			why = launch_data_get_bool(obj) ? SUCCESSFUL_EXIT : FAILED_EXIT;
7671 			semaphoreitem_new(j, why, NULL);
7672 			j->start_pending = true;
7673 		} else if (strcasecmp(key, LAUNCH_JOBKEY_KEEPALIVE_AFTERINITIALDEMAND) == 0) {
7674 			j->needs_kickoff = launch_data_get_bool(obj);
7675 		} else if (strcasecmp(key, LAUNCH_JOBKEY_KEEPALIVE_CRASHED) == 0) {
7676 			why = launch_data_get_bool(obj) ? CRASHED : DID_NOT_CRASH;
7677 			semaphoreitem_new(j, why, NULL);
7678 			j->start_pending = true;
7679 		} else {
7680 			job_log(j, LOG_ERR, "Unrecognized KeepAlive attribute: %s", key);
7681 		}
7682 		break;
7683 	case LAUNCH_DATA_DICTIONARY:
7684 		if (strcasecmp(key, LAUNCH_JOBKEY_KEEPALIVE_OTHERJOBACTIVE) == 0) {
7685 			sdic.why_true = OTHER_JOB_ACTIVE;
7686 			sdic.why_false = OTHER_JOB_INACTIVE;
7687 		} else if (strcasecmp(key, LAUNCH_JOBKEY_KEEPALIVE_OTHERJOBENABLED) == 0) {
7688 			sdic.why_true = OTHER_JOB_ENABLED;
7689 			sdic.why_false = OTHER_JOB_DISABLED;
7690 		} else {
7691 			job_log(j, LOG_ERR, "Unrecognized KeepAlive attribute: %s", key);
7692 			break;
7693 		}
7694 
7695 		launch_data_dict_iterate(obj, semaphoreitem_setup_dict_iter, &sdic);
7696 		break;
7697 	default:
7698 		job_log(j, LOG_ERR, "Unrecognized KeepAlive type: %u", launch_data_get_type(obj));
7699 		break;
7700 	}
7701 }
7702 
7703 bool
externalevent_new(job_t j,struct eventsystem * sys,const char * evname,xpc_object_t event,uint64_t flags __unused)7704 externalevent_new(job_t j, struct eventsystem *sys, const char *evname, xpc_object_t event, uint64_t flags __unused)
7705 {
7706 	if (j->event_monitor) {
7707 		job_log(j, LOG_ERR, "The event monitor job cannot use LaunchEvents or XPC Events.");
7708 		return false;
7709 	}
7710 
7711 	struct externalevent *ee = (struct externalevent *)calloc(1, sizeof(struct externalevent) + strlen(evname) + 1);
7712 	if (!ee) {
7713 		return false;
7714 	}
7715 
7716 	ee->event = xpc_retain(event);
7717 	(void)strcpy(ee->name, evname);
7718 	ee->job = j;
7719 	ee->id = sys->curid;
7720 	ee->sys = sys;
7721 	ee->state = false;
7722 	ee->wanted_state = true;
7723 	sys->curid++;
7724 
7725 #ifdef notyet
7726 	if (flags & XPC_EVENT_FLAG_ENTITLEMENTS) {
7727 		struct ldcred *ldc = runtime_get_caller_creds();
7728 		if (ldc) {
7729 			ee->entitlements = xpc_copy_entitlements_for_pid(ldc->pid);
7730 		}
7731 	}
7732 #endif
7733 	if (sys == _launchd_support_system) {
7734 		ee->internal = true;
7735 	}
7736 
7737 	LIST_INSERT_HEAD(&j->events, ee, job_le);
7738 	LIST_INSERT_HEAD(&sys->events, ee, sys_le);
7739 
7740 	job_log(j, LOG_DEBUG, "New event: %s/%s", sys->name, evname);
7741 
7742 	eventsystem_ping();
7743 	return true;
7744 }
7745 
7746 void
externalevent_delete(struct externalevent * ee)7747 externalevent_delete(struct externalevent *ee)
7748 {
7749 	xpc_release(ee->event);
7750 	if (ee->entitlements) {
7751 		xpc_release(ee->entitlements);
7752 	}
7753 	LIST_REMOVE(ee, job_le);
7754 	LIST_REMOVE(ee, sys_le);
7755 
7756 	free(ee);
7757 
7758 	eventsystem_ping();
7759 }
7760 
7761 void
externalevent_setup(launch_data_t obj,const char * key,void * context)7762 externalevent_setup(launch_data_t obj, const char *key, void *context)
7763 {
7764 	/* This method can ONLY be called on the job_import() path, as it assumes
7765 	 * the input is a launch_data_t.
7766 	 */
7767 	struct externalevent_iter_ctx *ctx = (struct externalevent_iter_ctx *)context;
7768 
7769 	xpc_object_t xobj = ld2xpc(obj);
7770 	if (xobj) {
7771 		job_log(ctx->j, LOG_DEBUG, "Importing stream/event: %s/%s", ctx->sys->name, key);
7772 		externalevent_new(ctx->j, ctx->sys, key, xobj, 0);
7773 		xpc_release(xobj);
7774 	} else {
7775 		job_log(ctx->j, LOG_ERR, "Could not import event for job: %s", key);
7776 	}
7777 }
7778 
7779 struct externalevent *
externalevent_find(const char * sysname,uint64_t id)7780 externalevent_find(const char *sysname, uint64_t id)
7781 {
7782 	struct externalevent *ei = NULL;
7783 
7784 	struct eventsystem *es = eventsystem_find(sysname);
7785 	if (es != NULL) {
7786 		LIST_FOREACH(ei, &es->events, sys_le) {
7787 			if (ei->id == id) {
7788 				break;
7789 			}
7790 		}
7791 	} else {
7792 		launchd_syslog(LOG_ERR, "Could not find event system: %s", sysname);
7793 	}
7794 
7795 	return ei;
7796 }
7797 
7798 struct eventsystem *
eventsystem_new(const char * name)7799 eventsystem_new(const char *name)
7800 {
7801 	struct eventsystem *es = (struct eventsystem *)calloc(1, sizeof(struct eventsystem) + strlen(name) + 1);
7802 	if (es != NULL) {
7803 		es->curid = 1;
7804 		(void)strcpy(es->name, name);
7805 		LIST_INSERT_HEAD(&_s_event_systems, es, global_le);
7806 	} else {
7807 		(void)os_assumes_zero(errno);
7808 	}
7809 
7810 	return es;
7811 }
7812 
7813 void
eventsystem_delete(struct eventsystem * es)7814 eventsystem_delete(struct eventsystem *es)
7815 {
7816 	struct externalevent *ei = NULL;
7817 	while ((ei = LIST_FIRST(&es->events))) {
7818 		externalevent_delete(ei);
7819 	}
7820 
7821 	LIST_REMOVE(es, global_le);
7822 
7823 	free(es);
7824 }
7825 
7826 void
eventsystem_setup(launch_data_t obj,const char * key,void * context)7827 eventsystem_setup(launch_data_t obj, const char *key, void *context)
7828 {
7829 	job_t j = (job_t)context;
7830 	if (!job_assumes(j, launch_data_get_type(obj) == LAUNCH_DATA_DICTIONARY)) {
7831 		return;
7832 	}
7833 
7834 	struct eventsystem *sys = eventsystem_find(key);
7835 	if (unlikely(sys == NULL)) {
7836 		sys = eventsystem_new(key);
7837 		job_log(j, LOG_DEBUG, "New event system: %s", key);
7838 	}
7839 
7840 	if (job_assumes(j, sys != NULL)) {
7841 		struct externalevent_iter_ctx ctx = {
7842 			.j = j,
7843 			.sys = sys,
7844 		};
7845 
7846 		job_log(j, LOG_DEBUG, "Importing events for stream: %s", key);
7847 		launch_data_dict_iterate(obj, externalevent_setup, &ctx);
7848 	}
7849 }
7850 
7851 struct eventsystem *
eventsystem_find(const char * name)7852 eventsystem_find(const char *name)
7853 {
7854 	struct eventsystem *esi = NULL;
7855 	LIST_FOREACH(esi, &_s_event_systems, global_le) {
7856 		if (strcmp(name, esi->name) == 0) {
7857 			break;
7858 		}
7859 	}
7860 
7861 	return esi;
7862 }
7863 
7864 void
eventsystem_ping(void)7865 eventsystem_ping(void)
7866 {
7867 	if (!_launchd_event_monitor) {
7868 		return;
7869 	}
7870 
7871 	if (!_launchd_event_monitor->p) {
7872 		(void)job_dispatch(_launchd_event_monitor, true);
7873 	} else {
7874 		if (_launchd_event_monitor->event_monitor_ready2signal) {
7875 			(void)job_assumes_zero_p(_launchd_event_monitor, kill(_launchd_event_monitor->p, SIGUSR1));
7876 		}
7877 	}
7878 }
7879 
7880 void
jobmgr_dispatch_all_semaphores(jobmgr_t jm)7881 jobmgr_dispatch_all_semaphores(jobmgr_t jm)
7882 {
7883 	jobmgr_t jmi, jmn;
7884 	job_t ji, jn;
7885 
7886 
7887 	SLIST_FOREACH_SAFE(jmi, &jm->submgrs, sle, jmn) {
7888 		jobmgr_dispatch_all_semaphores(jmi);
7889 	}
7890 
7891 	LIST_FOREACH_SAFE(ji, &jm->jobs, sle, jn) {
7892 		if (!SLIST_EMPTY(&ji->semaphores)) {
7893 			job_dispatch(ji, false);
7894 		}
7895 	}
7896 }
7897 
7898 time_t
cronemu(int mon,int mday,int hour,int min)7899 cronemu(int mon, int mday, int hour, int min)
7900 {
7901 	struct tm workingtm;
7902 	time_t now;
7903 
7904 	now = time(NULL);
7905 	workingtm = *localtime(&now);
7906 
7907 	workingtm.tm_isdst = -1;
7908 	workingtm.tm_sec = 0;
7909 	workingtm.tm_min++;
7910 
7911 	while (!cronemu_mon(&workingtm, mon, mday, hour, min)) {
7912 		workingtm.tm_year++;
7913 		workingtm.tm_mon = 0;
7914 		workingtm.tm_mday = 1;
7915 		workingtm.tm_hour = 0;
7916 		workingtm.tm_min = 0;
7917 		mktime(&workingtm);
7918 	}
7919 
7920 	return mktime(&workingtm);
7921 }
7922 
7923 time_t
cronemu_wday(int wday,int hour,int min)7924 cronemu_wday(int wday, int hour, int min)
7925 {
7926 	struct tm workingtm;
7927 	time_t now;
7928 
7929 	now = time(NULL);
7930 	workingtm = *localtime(&now);
7931 
7932 	workingtm.tm_isdst = -1;
7933 	workingtm.tm_sec = 0;
7934 	workingtm.tm_min++;
7935 
7936 	if (wday == 7) {
7937 		wday = 0;
7938 	}
7939 
7940 	while (!(workingtm.tm_wday == wday && cronemu_hour(&workingtm, hour, min))) {
7941 		workingtm.tm_mday++;
7942 		workingtm.tm_hour = 0;
7943 		workingtm.tm_min = 0;
7944 		mktime(&workingtm);
7945 	}
7946 
7947 	return mktime(&workingtm);
7948 }
7949 
7950 bool
cronemu_mon(struct tm * wtm,int mon,int mday,int hour,int min)7951 cronemu_mon(struct tm *wtm, int mon, int mday, int hour, int min)
7952 {
7953 	if (mon == -1) {
7954 		struct tm workingtm = *wtm;
7955 		int carrytest;
7956 
7957 		while (!cronemu_mday(&workingtm, mday, hour, min)) {
7958 			workingtm.tm_mon++;
7959 			workingtm.tm_mday = 1;
7960 			workingtm.tm_hour = 0;
7961 			workingtm.tm_min = 0;
7962 			carrytest = workingtm.tm_mon;
7963 			mktime(&workingtm);
7964 			if (carrytest != workingtm.tm_mon) {
7965 				return false;
7966 			}
7967 		}
7968 		*wtm = workingtm;
7969 		return true;
7970 	}
7971 
7972 	if (mon < wtm->tm_mon) {
7973 		return false;
7974 	}
7975 
7976 	if (mon > wtm->tm_mon) {
7977 		wtm->tm_mon = mon;
7978 		wtm->tm_mday = 1;
7979 		wtm->tm_hour = 0;
7980 		wtm->tm_min = 0;
7981 	}
7982 
7983 	return cronemu_mday(wtm, mday, hour, min);
7984 }
7985 
7986 bool
cronemu_mday(struct tm * wtm,int mday,int hour,int min)7987 cronemu_mday(struct tm *wtm, int mday, int hour, int min)
7988 {
7989 	if (mday == -1) {
7990 		struct tm workingtm = *wtm;
7991 		int carrytest;
7992 
7993 		while (!cronemu_hour(&workingtm, hour, min)) {
7994 			workingtm.tm_mday++;
7995 			workingtm.tm_hour = 0;
7996 			workingtm.tm_min = 0;
7997 			carrytest = workingtm.tm_mday;
7998 			mktime(&workingtm);
7999 			if (carrytest != workingtm.tm_mday) {
8000 				return false;
8001 			}
8002 		}
8003 		*wtm = workingtm;
8004 		return true;
8005 	}
8006 
8007 	if (mday < wtm->tm_mday) {
8008 		return false;
8009 	}
8010 
8011 	if (mday > wtm->tm_mday) {
8012 		wtm->tm_mday = mday;
8013 		wtm->tm_hour = 0;
8014 		wtm->tm_min = 0;
8015 	}
8016 
8017 	return cronemu_hour(wtm, hour, min);
8018 }
8019 
8020 bool
cronemu_hour(struct tm * wtm,int hour,int min)8021 cronemu_hour(struct tm *wtm, int hour, int min)
8022 {
8023 	if (hour == -1) {
8024 		struct tm workingtm = *wtm;
8025 		int carrytest;
8026 
8027 		while (!cronemu_min(&workingtm, min)) {
8028 			workingtm.tm_hour++;
8029 			workingtm.tm_min = 0;
8030 			carrytest = workingtm.tm_hour;
8031 			mktime(&workingtm);
8032 			if (carrytest != workingtm.tm_hour) {
8033 				return false;
8034 			}
8035 		}
8036 		*wtm = workingtm;
8037 		return true;
8038 	}
8039 
8040 	if (hour < wtm->tm_hour) {
8041 		return false;
8042 	}
8043 
8044 	if (hour > wtm->tm_hour) {
8045 		wtm->tm_hour = hour;
8046 		wtm->tm_min = 0;
8047 	}
8048 
8049 	return cronemu_min(wtm, min);
8050 }
8051 
8052 bool
cronemu_min(struct tm * wtm,int min)8053 cronemu_min(struct tm *wtm, int min)
8054 {
8055 	if (min == -1) {
8056 		return true;
8057 	}
8058 
8059 	if (min < wtm->tm_min) {
8060 		return false;
8061 	}
8062 
8063 	if (min > wtm->tm_min) {
8064 		wtm->tm_min = min;
8065 	}
8066 
8067 	return true;
8068 }
8069 
8070 kern_return_t
job_mig_create_server(job_t j,cmd_t server_cmd,uid_t server_uid,boolean_t on_demand,mach_port_t * server_portp)8071 job_mig_create_server(job_t j, cmd_t server_cmd, uid_t server_uid, boolean_t on_demand, mach_port_t *server_portp)
8072 {
8073 	struct ldcred *ldc = runtime_get_caller_creds();
8074 	job_t js;
8075 
8076 	if (!j) {
8077 		return BOOTSTRAP_NO_MEMORY;
8078 	}
8079 
8080 	if (unlikely(j->deny_job_creation)) {
8081 		return BOOTSTRAP_NOT_PRIVILEGED;
8082 	}
8083 
8084 #if HAVE_SANDBOX
8085 	const char **argv = (const char **)mach_cmd2argv(server_cmd);
8086 	if (unlikely(argv == NULL)) {
8087 		return BOOTSTRAP_NO_MEMORY;
8088 	}
8089 	if (unlikely(sandbox_check(ldc->pid, "job-creation", SANDBOX_FILTER_PATH, argv[0]) > 0)) {
8090 		free(argv);
8091 		return BOOTSTRAP_NOT_PRIVILEGED;
8092 	}
8093 	free(argv);
8094 #endif
8095 
8096 	job_log(j, LOG_DEBUG, "Server create attempt: %s", server_cmd);
8097 
8098 	if (pid1_magic) {
8099 		if (ldc->euid || ldc->uid) {
8100 			job_log(j, LOG_WARNING, "Server create attempt moved to per-user launchd: %s", server_cmd);
8101 			return VPROC_ERR_TRY_PER_USER;
8102 		}
8103 	} else {
8104 		if (unlikely(server_uid != getuid())) {
8105 			job_log(j, LOG_WARNING, "Server create: \"%s\": As UID %d, we will not be able to switch to UID %d",
8106 					server_cmd, getuid(), server_uid);
8107 		}
8108 		server_uid = 0; // zero means "do nothing"
8109 	}
8110 
8111 	js = job_new_via_mach_init(j, server_cmd, server_uid, on_demand);
8112 
8113 	if (unlikely(js == NULL)) {
8114 		return BOOTSTRAP_NO_MEMORY;
8115 	}
8116 
8117 	*server_portp = js->j_port;
8118 	return BOOTSTRAP_SUCCESS;
8119 }
8120 
8121 kern_return_t
job_mig_send_signal(job_t j,mach_port_t srp,name_t targetlabel,int sig)8122 job_mig_send_signal(job_t j, mach_port_t srp, name_t targetlabel, int sig)
8123 {
8124 	struct ldcred *ldc = runtime_get_caller_creds();
8125 	job_t otherj;
8126 
8127 	if (!j) {
8128 		return BOOTSTRAP_NO_MEMORY;
8129 	}
8130 
8131 	if (unlikely(ldc->euid != 0 && ldc->euid != getuid()) || j->deny_job_creation) {
8132 #if TARGET_OS_EMBEDDED
8133 		if (!j->embedded_god) {
8134 			return BOOTSTRAP_NOT_PRIVILEGED;
8135 		}
8136 #else
8137 		return BOOTSTRAP_NOT_PRIVILEGED;
8138 #endif
8139 	}
8140 
8141 #if HAVE_SANDBOX
8142 	if (unlikely(sandbox_check(ldc->pid, "job-creation", SANDBOX_FILTER_NONE) > 0)) {
8143 		return BOOTSTRAP_NOT_PRIVILEGED;
8144 	}
8145 #endif
8146 
8147 	if (unlikely(!(otherj = job_find(NULL, targetlabel)))) {
8148 		return BOOTSTRAP_UNKNOWN_SERVICE;
8149 	}
8150 
8151 #if TARGET_OS_EMBEDDED
8152 	if (j->embedded_god) {
8153 		if (j->username && otherj->username) {
8154 			if (strcmp(j->username, otherj->username) != 0) {
8155 				return BOOTSTRAP_NOT_PRIVILEGED;
8156 			}
8157 		} else {
8158 			return BOOTSTRAP_NOT_PRIVILEGED;
8159 		}
8160 	}
8161 #endif
8162 
8163 	if (sig == VPROC_MAGIC_UNLOAD_SIGNAL) {
8164 		bool do_block = otherj->p;
8165 
8166 		if (otherj->anonymous) {
8167 			return BOOTSTRAP_NOT_PRIVILEGED;
8168 		}
8169 
8170 		job_remove(otherj);
8171 
8172 		if (do_block) {
8173 			job_log(j, LOG_DEBUG, "Blocking MIG return of job_remove(): %s", otherj->label);
8174 			// this is messy. We shouldn't access 'otherj' after job_remove(), but we check otherj->p first...
8175 			(void)job_assumes(otherj, waiting4removal_new(otherj, srp));
8176 			return MIG_NO_REPLY;
8177 		} else {
8178 			return 0;
8179 		}
8180 	} else if (otherj->p) {
8181 		(void)job_assumes_zero_p(j, kill2(otherj->p, sig));
8182 	}
8183 
8184 	return 0;
8185 }
8186 
8187 kern_return_t
job_mig_log_forward(job_t j,vm_offset_t inval,mach_msg_type_number_t invalCnt)8188 job_mig_log_forward(job_t j, vm_offset_t inval, mach_msg_type_number_t invalCnt)
8189 {
8190 	struct ldcred *ldc = runtime_get_caller_creds();
8191 
8192 	if (!j) {
8193 		return BOOTSTRAP_NO_MEMORY;
8194 	}
8195 
8196 	if (!job_assumes(j, j->per_user)) {
8197 		return BOOTSTRAP_NOT_PRIVILEGED;
8198 	}
8199 
8200 	return launchd_log_forward(ldc->euid, ldc->egid, inval, invalCnt);
8201 }
8202 
8203 kern_return_t
job_mig_log_drain(job_t j,mach_port_t srp,vm_offset_t * outval,mach_msg_type_number_t * outvalCnt)8204 job_mig_log_drain(job_t j, mach_port_t srp, vm_offset_t *outval, mach_msg_type_number_t *outvalCnt)
8205 {
8206 	struct ldcred *ldc = runtime_get_caller_creds();
8207 
8208 	if (!j) {
8209 		return BOOTSTRAP_NO_MEMORY;
8210 	}
8211 
8212 	if (unlikely(ldc->euid)) {
8213 		return BOOTSTRAP_NOT_PRIVILEGED;
8214 	}
8215 
8216 	return launchd_log_drain(srp, outval, outvalCnt);
8217 }
8218 
8219 kern_return_t
job_mig_swap_complex(job_t j,vproc_gsk_t inkey,vproc_gsk_t outkey,vm_offset_t inval,mach_msg_type_number_t invalCnt,vm_offset_t * outval,mach_msg_type_number_t * outvalCnt)8220 job_mig_swap_complex(job_t j, vproc_gsk_t inkey, vproc_gsk_t outkey,
8221 	vm_offset_t inval, mach_msg_type_number_t invalCnt, vm_offset_t *outval,
8222 	mach_msg_type_number_t *outvalCnt)
8223 {
8224 	const char *action;
8225 	launch_data_t input_obj = NULL, output_obj = NULL;
8226 	size_t data_offset = 0;
8227 	size_t packed_size;
8228 	struct ldcred *ldc = runtime_get_caller_creds();
8229 
8230 	if (!j) {
8231 		return BOOTSTRAP_NO_MEMORY;
8232 	}
8233 
8234 	if (inkey && ldc->pid != j->p) {
8235 		if (ldc->euid && ldc->euid != getuid()) {
8236 			return BOOTSTRAP_NOT_PRIVILEGED;
8237 		}
8238  	}
8239 
8240 	if (unlikely(inkey && outkey && !job_assumes(j, inkey == outkey))) {
8241 		return 1;
8242 	}
8243 
8244 	if (inkey && outkey) {
8245 		action = "Swapping";
8246 	} else if (inkey) {
8247 		action = "Setting";
8248 	} else {
8249 		action = "Getting";
8250 	}
8251 
8252 	job_log(j, LOG_DEBUG, "%s key: %u", action, inkey ? inkey : outkey);
8253 
8254 	*outvalCnt = 20 * 1024 * 1024;
8255 	mig_allocate(outval, *outvalCnt);
8256 	if (!job_assumes(j, *outval != 0)) {
8257 		return 1;
8258 	}
8259 
8260 	/* Note to future maintainers: launch_data_unpack() does NOT return a heap
8261 	 * object. The data is decoded in-place. So do not call launch_data_free()
8262 	 * on input_obj.
8263 	 */
8264 	runtime_ktrace0(RTKT_LAUNCHD_DATA_UNPACK);
8265 	if (unlikely(invalCnt && !job_assumes(j, (input_obj = launch_data_unpack((void *)inval, invalCnt, NULL, 0, &data_offset, NULL)) != NULL))) {
8266 		goto out_bad;
8267 	}
8268 
8269 	char *store = NULL;
8270 	switch (outkey) {
8271 	case VPROC_GSK_ENVIRONMENT:
8272 		if (!job_assumes(j, (output_obj = launch_data_alloc(LAUNCH_DATA_DICTIONARY)))) {
8273 			goto out_bad;
8274 		}
8275 		jobmgr_export_env_from_other_jobs(j->mgr, output_obj);
8276 		runtime_ktrace0(RTKT_LAUNCHD_DATA_PACK);
8277 		if (!job_assumes(j, launch_data_pack(output_obj, (void *)*outval, *outvalCnt, NULL, NULL) != 0)) {
8278 			goto out_bad;
8279 		}
8280 		launch_data_free(output_obj);
8281 		break;
8282 	case VPROC_GSK_ALLJOBS:
8283 		if (!job_assumes(j, (output_obj = job_export_all()) != NULL)) {
8284 			goto out_bad;
8285 		}
8286 		ipc_revoke_fds(output_obj);
8287 		runtime_ktrace0(RTKT_LAUNCHD_DATA_PACK);
8288 		packed_size = launch_data_pack(output_obj, (void *)*outval, *outvalCnt, NULL, NULL);
8289 		if (!job_assumes(j, packed_size != 0)) {
8290 			goto out_bad;
8291 		}
8292 		launch_data_free(output_obj);
8293 		break;
8294 	case VPROC_GSK_MGR_NAME:
8295 		if (!job_assumes(j, (output_obj = launch_data_new_string(j->mgr->name)) != NULL)) {
8296 			goto out_bad;
8297 		}
8298 		packed_size = launch_data_pack(output_obj, (void *)*outval, *outvalCnt, NULL, NULL);
8299 		if (!job_assumes(j, packed_size != 0)) {
8300 			goto out_bad;
8301 		}
8302 
8303 		launch_data_free(output_obj);
8304 		break;
8305 	case VPROC_GSK_JOB_OVERRIDES_DB:
8306 		store = launchd_copy_persistent_store(LAUNCHD_PERSISTENT_STORE_DB, "overrides.plist");
8307 		if (!store || !job_assumes(j, (output_obj = launch_data_new_string(store)) != NULL)) {
8308 			free(store);
8309 			goto out_bad;
8310 		}
8311 
8312 		free(store);
8313 		packed_size = launch_data_pack(output_obj, (void *)*outval, *outvalCnt, NULL, NULL);
8314 		if (!job_assumes(j, packed_size != 0)) {
8315 			goto out_bad;
8316 		}
8317 
8318 		launch_data_free(output_obj);
8319 		break;
8320 	case VPROC_GSK_ZERO:
8321 		mig_deallocate(*outval, *outvalCnt);
8322 		*outval = 0;
8323 		*outvalCnt = 0;
8324 		break;
8325 	default:
8326 		goto out_bad;
8327 	}
8328 
8329 	mig_deallocate(inval, invalCnt);
8330 	return 0;
8331 
8332 out_bad:
8333 	mig_deallocate(inval, invalCnt);
8334 	if (*outval) {
8335 		mig_deallocate(*outval, *outvalCnt);
8336 	}
8337 	if (output_obj) {
8338 		launch_data_free(output_obj);
8339 	}
8340 
8341 	return 1;
8342 }
8343 
8344 kern_return_t
job_mig_swap_integer(job_t j,vproc_gsk_t inkey,vproc_gsk_t outkey,int64_t inval,int64_t * outval)8345 job_mig_swap_integer(job_t j, vproc_gsk_t inkey, vproc_gsk_t outkey, int64_t inval, int64_t *outval)
8346 {
8347 	const char *action;
8348 	kern_return_t kr = 0;
8349 	struct ldcred *ldc = runtime_get_caller_creds();
8350 	int oldmask;
8351 
8352 	if (!j) {
8353 		return BOOTSTRAP_NO_MEMORY;
8354 	}
8355 
8356 	if (inkey && ldc->pid != j->p) {
8357 		if (ldc->euid && ldc->euid != getuid()) {
8358 			return BOOTSTRAP_NOT_PRIVILEGED;
8359 		}
8360  	}
8361 
8362 	if (unlikely(inkey && outkey && !job_assumes(j, inkey == outkey))) {
8363 		return 1;
8364 	}
8365 
8366 	if (inkey && outkey) {
8367 		action = "Swapping";
8368 	} else if (inkey) {
8369 		action = "Setting";
8370 	} else {
8371 		action = "Getting";
8372 	}
8373 
8374 	job_log(j, LOG_DEBUG, "%s key: %u", action, inkey ? inkey : outkey);
8375 
8376 	switch (outkey) {
8377 	case VPROC_GSK_ABANDON_PROCESS_GROUP:
8378 		*outval = j->abandon_pg;
8379 		break;
8380 	case VPROC_GSK_LAST_EXIT_STATUS:
8381 		*outval = j->last_exit_status;
8382 		break;
8383 	case VPROC_GSK_MGR_UID:
8384 		*outval = getuid();
8385 		break;
8386 	case VPROC_GSK_MGR_PID:
8387 		*outval = getpid();
8388 		break;
8389 	case VPROC_GSK_IS_MANAGED:
8390 		*outval = j->anonymous ? 0 : 1;
8391 		break;
8392 	case VPROC_GSK_BASIC_KEEPALIVE:
8393 		*outval = !j->ondemand;
8394 		break;
8395 	case VPROC_GSK_START_INTERVAL:
8396 		*outval = j->start_interval;
8397 		break;
8398 	case VPROC_GSK_IDLE_TIMEOUT:
8399 		*outval = j->timeout;
8400 		break;
8401 	case VPROC_GSK_EXIT_TIMEOUT:
8402 		*outval = j->exit_timeout;
8403 		break;
8404 	case VPROC_GSK_GLOBAL_LOG_MASK:
8405 		oldmask = runtime_setlogmask(LOG_UPTO(LOG_DEBUG));
8406 		*outval = oldmask;
8407 		runtime_setlogmask(oldmask);
8408 		break;
8409 	case VPROC_GSK_GLOBAL_UMASK:
8410 		oldmask = umask(0);
8411 		*outval = oldmask;
8412 		umask(oldmask);
8413 		break;
8414 	case VPROC_GSK_TRANSACTIONS_ENABLED:
8415 		job_log(j, LOG_DEBUG, "Reading EnableTransactions value.");
8416 		*outval = j->enable_transactions;
8417 		break;
8418 	case VPROC_GSK_WAITFORDEBUGGER:
8419 		*outval = j->wait4debugger;
8420 		break;
8421 	case VPROC_GSK_EMBEDDEDROOTEQUIVALENT:
8422 		*outval = j->embedded_god;
8423 		break;
8424 	case VPROC_GSK_ZERO:
8425 		*outval = 0;
8426 		break;
8427 	default:
8428 		kr = 1;
8429 		break;
8430 	}
8431 
8432 	switch (inkey) {
8433 	case VPROC_GSK_ABANDON_PROCESS_GROUP:
8434 		j->abandon_pg = (bool)inval;
8435 		break;
8436 	case VPROC_GSK_GLOBAL_ON_DEMAND:
8437 		job_log(j, LOG_DEBUG, "Job has set global on-demand mode to: %s", inval ? "true" : "false");
8438 		kr = job_set_global_on_demand(j, inval);
8439 		break;
8440 	case VPROC_GSK_BASIC_KEEPALIVE:
8441 		j->ondemand = !inval;
8442 		break;
8443 	case VPROC_GSK_START_INTERVAL:
8444 		if (inval > UINT32_MAX || inval < 0) {
8445 			kr = 1;
8446 		} else if (inval) {
8447 			if (j->start_interval == 0) {
8448 				runtime_add_weak_ref();
8449 			}
8450 			j->start_interval = (typeof(j->start_interval)) inval;
8451 			(void)job_assumes_zero_p(j, kevent_mod((uintptr_t)&j->start_interval, EVFILT_TIMER, EV_ADD, NOTE_SECONDS, j->start_interval, j));
8452 		} else if (j->start_interval) {
8453 			(void)job_assumes_zero_p(j, kevent_mod((uintptr_t)&j->start_interval, EVFILT_TIMER, EV_DELETE, 0, 0, NULL));
8454 			if (j->start_interval != 0) {
8455 				runtime_del_weak_ref();
8456 			}
8457 			j->start_interval = 0;
8458 		}
8459 		break;
8460 	case VPROC_GSK_IDLE_TIMEOUT:
8461 		if (inval < 0 || inval > UINT32_MAX) {
8462 			kr = 1;
8463 		} else {
8464 			j->timeout = (typeof(j->timeout)) inval;
8465 		}
8466 		break;
8467 	case VPROC_GSK_EXIT_TIMEOUT:
8468 		if (inval < 0 || inval > UINT32_MAX) {
8469 			kr = 1;
8470 		} else {
8471 			j->exit_timeout = (typeof(j->exit_timeout)) inval;
8472 		}
8473 		break;
8474 	case VPROC_GSK_GLOBAL_LOG_MASK:
8475 		if (inval < 0 || inval > UINT32_MAX) {
8476 			kr = 1;
8477 		} else {
8478 			runtime_setlogmask((int) inval);
8479 		}
8480 		break;
8481 	case VPROC_GSK_GLOBAL_UMASK:
8482 		__OS_COMPILETIME_ASSERT__(sizeof (mode_t) == 2);
8483 		if (inval < 0 || inval > UINT16_MAX) {
8484 			kr = 1;
8485 		} else {
8486 #if HAVE_SANDBOX
8487 			if (unlikely(sandbox_check(ldc->pid, "job-creation", SANDBOX_FILTER_NONE) > 0)) {
8488 				kr = 1;
8489 			} else {
8490 				umask((mode_t) inval);
8491 			}
8492 #endif
8493 		}
8494 		break;
8495 	case VPROC_GSK_TRANSACTIONS_ENABLED:
8496 		/* No-op. */
8497 		break;
8498 	case VPROC_GSK_WEIRD_BOOTSTRAP:
8499 		if (job_assumes(j, j->weird_bootstrap)) {
8500 			job_log(j, LOG_DEBUG, "Unsetting weird bootstrap.");
8501 
8502 			mach_msg_size_t mxmsgsz = (typeof(mxmsgsz)) sizeof(union __RequestUnion__job_mig_job_subsystem);
8503 
8504 			if (job_mig_job_subsystem.maxsize > mxmsgsz) {
8505 				mxmsgsz = job_mig_job_subsystem.maxsize;
8506 			}
8507 
8508 			(void)job_assumes_zero(j, runtime_add_mport(j->mgr->jm_port, job_server));
8509 			j->weird_bootstrap = false;
8510 		}
8511 		break;
8512 	case VPROC_GSK_WAITFORDEBUGGER:
8513 		j->wait4debugger_oneshot = inval;
8514 		break;
8515 	case VPROC_GSK_PERUSER_SUSPEND:
8516 		if (job_assumes(j, pid1_magic && ldc->euid == 0)) {
8517 			mach_port_t junk = MACH_PORT_NULL;
8518 			job_t jpu = jobmgr_lookup_per_user_context_internal(j, (uid_t)inval, &junk);
8519 			if (job_assumes(j, jpu != NULL)) {
8520 				struct suspended_peruser *spi = NULL;
8521 				LIST_FOREACH(spi, &j->suspended_perusers, sle) {
8522 					if ((int64_t)(spi->j->mach_uid) == inval) {
8523 						job_log(j, LOG_WARNING, "Job tried to suspend per-user launchd for UID %zi twice.", inval);
8524 						break;
8525 					}
8526 				}
8527 
8528 				if (spi == NULL) {
8529 					job_log(j, LOG_INFO, "Job is suspending the per-user launchd for UID %zi.", inval);
8530 					spi = (struct suspended_peruser *)calloc(sizeof(struct suspended_peruser), 1);
8531 					if (job_assumes(j, spi != NULL)) {
8532 						/* Stop listening for events.
8533 						 *
8534 						 * See <rdar://problem/9014146>.
8535 						 */
8536 						if (jpu->peruser_suspend_count == 0) {
8537 							job_ignore(jpu);
8538 						}
8539 
8540 						spi->j = jpu;
8541 						spi->j->peruser_suspend_count++;
8542 						LIST_INSERT_HEAD(&j->suspended_perusers, spi, sle);
8543 						job_stop(spi->j);
8544 						*outval = jpu->p;
8545 					} else {
8546 						kr = BOOTSTRAP_NO_MEMORY;
8547 					}
8548 				}
8549 			}
8550 		} else {
8551 			kr = 1;
8552 		}
8553 		break;
8554 	case VPROC_GSK_PERUSER_RESUME:
8555 		if (job_assumes(j, pid1_magic == true)) {
8556 			struct suspended_peruser *spi = NULL, *spt = NULL;
8557 			LIST_FOREACH_SAFE(spi, &j->suspended_perusers, sle, spt) {
8558 				if ((int64_t)(spi->j->mach_uid) == inval) {
8559 					spi->j->peruser_suspend_count--;
8560 					LIST_REMOVE(spi, sle);
8561 					job_log(j, LOG_INFO, "Job is resuming the per-user launchd for UID %zi.", inval);
8562 					break;
8563 				}
8564 			}
8565 
8566 			if (!job_assumes(j, spi != NULL)) {
8567 				job_log(j, LOG_WARNING, "Job tried to resume per-user launchd for UID %zi that it did not suspend.", inval);
8568 				kr = BOOTSTRAP_NOT_PRIVILEGED;
8569 			} else if (spi->j->peruser_suspend_count == 0) {
8570 				job_watch(spi->j);
8571 				job_dispatch(spi->j, false);
8572 				free(spi);
8573 			}
8574 		} else {
8575 			kr = 1;
8576 		}
8577 		break;
8578 	case VPROC_GSK_ZERO:
8579 		break;
8580 	default:
8581 		kr = 1;
8582 		break;
8583 	}
8584 
8585 	return kr;
8586 }
8587 
8588 kern_return_t
job_mig_post_fork_ping(job_t j,task_t child_task,mach_port_t * asport)8589 job_mig_post_fork_ping(job_t j, task_t child_task, mach_port_t *asport)
8590 {
8591 	if (!j) {
8592 		return BOOTSTRAP_NO_MEMORY;
8593 	}
8594 
8595 	job_log(j, LOG_DEBUG, "Post fork ping.");
8596 
8597 	struct machservice *ms;
8598 	job_setup_exception_port(j, child_task);
8599 	SLIST_FOREACH(ms, &special_ports, special_port_sle) {
8600 		if (j->per_user && (ms->special_port_num != TASK_ACCESS_PORT)) {
8601 			// The TASK_ACCESS_PORT funny business is to workaround 5325399.
8602 			continue;
8603 		}
8604 
8605 		errno = task_set_special_port(child_task, ms->special_port_num, ms->port);
8606 		if (errno) {
8607 			if (errno == MACH_SEND_INVALID_DEST) {
8608 				job_log(j, LOG_WARNING, "Task died before special ports could be set.");
8609 				break;
8610 			}
8611 
8612 			int desired_log_level = LOG_ERR;
8613 			if (j->anonymous) {
8614 				// 5338127
8615 
8616 				desired_log_level = LOG_WARNING;
8617 
8618 				if (ms->special_port_num == TASK_SEATBELT_PORT) {
8619 					desired_log_level = LOG_DEBUG;
8620 				}
8621 			}
8622 
8623 			job_log(j, desired_log_level, "Could not setup Mach task special port %u: %s", ms->special_port_num, mach_error_string(errno));
8624 		}
8625 	}
8626 
8627 	/* MIG will not zero-initialize this pointer, so we must always do so.
8628 	 *
8629 	 * <rdar://problem/8562593>.
8630 	 */
8631 	*asport = MACH_PORT_NULL;
8632 #if !TARGET_OS_EMBEDDED
8633 	if (!j->anonymous) {
8634 		/* XPC services will spawn into the root security session by default.
8635 		 * xpcproxy will switch them away if needed.
8636 		 */
8637 		if (!(j->mgr->properties & BOOTSTRAP_PROPERTY_XPC_DOMAIN)) {
8638 			job_log(j, LOG_DEBUG, "Returning session port: 0x%x", j->asport);
8639 			*asport = j->asport;
8640 		}
8641 	}
8642 #endif
8643 	(void)job_assumes_zero(j, launchd_mport_deallocate(child_task));
8644 
8645 	return 0;
8646 }
8647 
8648 kern_return_t
job_mig_get_listener_port_rights(job_t j,mach_port_array_t * sports,mach_msg_type_number_t * sports_cnt)8649 job_mig_get_listener_port_rights(job_t j, mach_port_array_t *sports, mach_msg_type_number_t *sports_cnt)
8650 {
8651 	if (!j) {
8652 		return BOOTSTRAP_NO_MEMORY;
8653 	}
8654 
8655 	size_t cnt = 0;
8656 	struct machservice *msi = NULL;
8657 	SLIST_FOREACH(msi, &j->machservices, sle) {
8658 		if (msi->upfront && job_assumes(j, msi->recv)) {
8659 			cnt++;
8660 		}
8661 	}
8662 
8663 	if (cnt == 0) {
8664 		return BOOTSTRAP_UNKNOWN_SERVICE;
8665 	}
8666 
8667 	mach_port_array_t sports2 = NULL;
8668 	mig_allocate((vm_address_t *)&sports2, cnt * sizeof(sports2[0]));
8669 	if (!sports2) {
8670 		return BOOTSTRAP_NO_MEMORY;
8671 	}
8672 
8673 	size_t i = 0;
8674 	SLIST_FOREACH(msi, &j->machservices, sle) {
8675 		if (msi->upfront && msi->recv) {
8676 			sports2[i] = msi->port;
8677 			i++;
8678 		}
8679 	}
8680 
8681 	*sports = sports2;
8682 	*sports_cnt = cnt;
8683 
8684 	return KERN_SUCCESS;
8685 }
8686 
8687 kern_return_t
job_mig_register_gui_session(job_t j,mach_port_t asport)8688 job_mig_register_gui_session(job_t j, mach_port_t asport)
8689 {
8690 	if (!j->per_user) {
8691 		return BOOTSTRAP_NOT_PRIVILEGED;
8692 	}
8693 
8694 	jobmgr_t jm = jobmgr_find_xpc_per_user_domain(root_jobmgr, j->mach_uid);
8695 	if (!jm) {
8696 		return BOOTSTRAP_UNKNOWN_SERVICE;
8697 	}
8698 
8699 	if (jm->req_gui_asport) {
8700 		// This job manager persists, so we need to allow the per-user launchd
8701 		// to update the GUI session as it comes and goes.
8702 		jobmgr_assumes_zero(jm, launchd_mport_deallocate(jm->req_gui_asport));
8703 	}
8704 
8705 	jm->req_gui_asport = asport;
8706 	return KERN_SUCCESS;
8707 }
8708 
8709 kern_return_t
job_mig_reboot2(job_t j,uint64_t flags)8710 job_mig_reboot2(job_t j, uint64_t flags)
8711 {
8712 	char who_started_the_reboot[2048] = "";
8713 	struct proc_bsdshortinfo proc;
8714 	struct ldcred *ldc = runtime_get_caller_creds();
8715 	pid_t pid_to_log;
8716 
8717 	if (!j) {
8718 		return BOOTSTRAP_NO_MEMORY;
8719 	}
8720 
8721 	if (unlikely(!pid1_magic)) {
8722 		return BOOTSTRAP_NOT_PRIVILEGED;
8723 	}
8724 
8725 #if !TARGET_OS_EMBEDDED
8726 	if (unlikely(ldc->euid)) {
8727 #else
8728 	if (unlikely(ldc->euid) && !j->embedded_god) {
8729 #endif
8730 		return BOOTSTRAP_NOT_PRIVILEGED;
8731 	}
8732 
8733 	for (pid_to_log = ldc->pid; pid_to_log; pid_to_log = proc.pbsi_ppid) {
8734 		size_t who_offset;
8735 		if (proc_pidinfo(pid_to_log, PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0) {
8736 			if (errno != ESRCH) {
8737 				(void)job_assumes_zero(j, errno);
8738 			}
8739 			return 1;
8740 		}
8741 
8742 		if (!job_assumes(j, pid_to_log != (pid_t)proc.pbsi_ppid)) {
8743 			job_log(j, LOG_WARNING, "Job which is its own parent started reboot.");
8744 			snprintf(who_started_the_reboot, sizeof(who_started_the_reboot), "%s[%u]->%s[%u]->%s[%u]->...", proc.pbsi_comm, pid_to_log, proc.pbsi_comm, pid_to_log, proc.pbsi_comm, pid_to_log);
8745 			break;
8746 		}
8747 
8748 		who_offset = strlen(who_started_the_reboot);
8749 		snprintf(who_started_the_reboot + who_offset, sizeof(who_started_the_reboot) - who_offset,
8750 				" %s[%u]%s", proc.pbsi_comm, pid_to_log, proc.pbsi_ppid ? " ->" : "");
8751 	}
8752 
8753 	root_jobmgr->reboot_flags = (int)flags;
8754 
8755 	job_log(j, LOG_DEBUG, "reboot2() initiated by:%s", who_started_the_reboot);
8756 	launchd_shutdown();
8757 
8758 	return 0;
8759 }
8760 
8761 kern_return_t
8762 job_mig_getsocket(job_t j, name_t spr)
8763 {
8764 	if (!j) {
8765 		return BOOTSTRAP_NO_MEMORY;
8766 	}
8767 
8768 	if (j->deny_job_creation) {
8769 		return BOOTSTRAP_NOT_PRIVILEGED;
8770 	}
8771 
8772 #if HAVE_SANDBOX
8773 	struct ldcred *ldc = runtime_get_caller_creds();
8774 	if (unlikely(sandbox_check(ldc->pid, "job-creation", SANDBOX_FILTER_NONE) > 0)) {
8775 		return BOOTSTRAP_NOT_PRIVILEGED;
8776 	}
8777 #endif
8778 
8779 	ipc_server_init();
8780 
8781 	if (unlikely(!sockpath)) {
8782 		return BOOTSTRAP_NO_MEMORY;
8783 	}
8784 
8785 	strncpy(spr, sockpath, sizeof(name_t));
8786 
8787 	return BOOTSTRAP_SUCCESS;
8788 }
8789 
8790 kern_return_t
8791 job_mig_log(job_t j, int pri, int err, logmsg_t msg)
8792 {
8793 	if (!j) {
8794 		return BOOTSTRAP_NO_MEMORY;
8795 	}
8796 
8797 	if ((errno = err)) {
8798 		job_log_error(j, pri, "%s", msg);
8799 	} else {
8800 		job_log(j, pri, "%s", msg);
8801 	}
8802 
8803 	return 0;
8804 }
8805 
8806 void
8807 job_setup_per_user_directory(job_t j, uid_t uid, const char *path)
8808 {
8809 	struct stat sb;
8810 
8811 	bool created = false;
8812 	int r = stat(path, &sb);
8813 	if ((r == -1 && errno == ENOENT) || (r == 0 && !S_ISDIR(sb.st_mode))) {
8814 		if (r == 0) {
8815 			job_log(j, LOG_NOTICE, "File at location of per-user launchd directory is not a directory. Moving aside: %s", path);
8816 
8817 			char old[PATH_MAX];
8818 			snprintf(old, sizeof(old), "%s.movedaside", path);
8819 			(void)job_assumes_zero_p(j, rename(path, old));
8820 		}
8821 
8822 		(void)job_assumes_zero_p(j, mkdir(path, S_IRWXU));
8823 		(void)job_assumes_zero_p(j, chown(path, uid, 0));
8824 		created = true;
8825 	}
8826 
8827 	if (!created) {
8828 		if (sb.st_uid != uid) {
8829 			job_log(j, LOG_NOTICE, "Per-user launchd directory has improper user ownership. Repairing: %s", path);
8830 			(void)job_assumes_zero_p(j, chown(path, uid, 0));
8831 		}
8832 		if (sb.st_gid != 0) {
8833 			job_log(j, LOG_NOTICE, "Per-user launchd directory has improper group ownership. Repairing: %s", path);
8834 			(void)job_assumes_zero_p(j, chown(path, uid, 0));
8835 		}
8836 		if (sb.st_mode != (S_IRWXU | S_IFDIR)) {
8837 			job_log(j, LOG_NOTICE, "Per-user launchd directory has improper mode. Repairing: %s", path);
8838 			(void)job_assumes_zero_p(j, chmod(path, S_IRWXU));
8839 		}
8840 	}
8841 }
8842 
8843 void
8844 job_setup_per_user_directories(job_t j, uid_t uid, const char *label)
8845 {
8846 	char path[PATH_MAX];
8847 
8848 	(void)snprintf(path, sizeof(path), LAUNCHD_DB_PREFIX "/%s", label);
8849 	job_setup_per_user_directory(j, uid, path);
8850 
8851 	(void)snprintf(path, sizeof(path), LAUNCHD_LOG_PREFIX "/%s", label);
8852 	job_setup_per_user_directory(j, uid, path);
8853 }
8854 
8855 job_t
8856 jobmgr_lookup_per_user_context_internal(job_t j, uid_t which_user, mach_port_t *mp)
8857 {
8858 	job_t ji = NULL;
8859 	LIST_FOREACH(ji, &root_jobmgr->jobs, sle) {
8860 		if (!ji->per_user) {
8861 			continue;
8862 		}
8863 		if (ji->mach_uid != which_user) {
8864 			continue;
8865 		}
8866 		if (SLIST_EMPTY(&ji->machservices)) {
8867 			continue;
8868 		}
8869 		if (!SLIST_FIRST(&ji->machservices)->per_user_hack) {
8870 			continue;
8871 		}
8872 		break;
8873 	}
8874 
8875 	if (unlikely(ji == NULL)) {
8876 		struct machservice *ms;
8877 		char lbuf[1024];
8878 
8879 		job_log(j, LOG_DEBUG, "Creating per user launchd job for UID: %u", which_user);
8880 
8881 		sprintf(lbuf, "com.apple.launchd.peruser.%u", which_user);
8882 
8883 		ji = job_new(root_jobmgr, lbuf, "/sbin/launchd", NULL);
8884 
8885 		if (ji != NULL) {
8886 			auditinfo_addr_t auinfo = {
8887 				.ai_termid = {
8888 					.at_type = AU_IPv4
8889 				},
8890 				.ai_auid = which_user,
8891 				.ai_asid = AU_ASSIGN_ASID,
8892 			};
8893 
8894 			if (setaudit_addr(&auinfo, sizeof(auinfo)) == 0) {
8895 				job_log(ji, LOG_DEBUG, "Created new security session for per-user launchd: %u", auinfo.ai_asid);
8896 #ifdef notyet
8897 				(void)job_assumes(ji, (ji->asport = audit_session_self()) != MACH_PORT_NULL);
8898 
8899 				/* Kinda lame that we have to do this, but we can't create an
8900 				 * audit session without joining it.
8901 				 */
8902 				(void)job_assumes(ji, audit_session_join(launchd_audit_port));
8903 #endif
8904 				ji->asid = auinfo.ai_asid;
8905 			} else {
8906 				job_log(ji, LOG_WARNING, "Could not set audit session!");
8907 				job_remove(ji);
8908 				return NULL;
8909 			}
8910 
8911 			ji->mach_uid = which_user;
8912 			ji->per_user = true;
8913 			ji->enable_transactions = true;
8914 			job_setup_per_user_directories(ji, which_user, lbuf);
8915 
8916 			if ((ms = machservice_new(ji, lbuf, mp, false)) == NULL) {
8917 				job_remove(ji);
8918 				ji = NULL;
8919 			} else {
8920 				ms->upfront = true;
8921 				ms->per_user_hack = true;
8922 				ms->hide = true;
8923 
8924 				ji = job_dispatch(ji, false);
8925 			}
8926 		}
8927 	} else {
8928 		*mp = machservice_port(SLIST_FIRST(&ji->machservices));
8929 		job_log(j, LOG_DEBUG, "Per user launchd job found for UID: %u", which_user);
8930 	}
8931 
8932 	return ji;
8933 }
8934 
8935 kern_return_t
8936 job_mig_lookup_per_user_context(job_t j, uid_t which_user, mach_port_t *up_cont)
8937 {
8938 	struct ldcred *ldc = runtime_get_caller_creds();
8939 	job_t jpu;
8940 
8941 	if (!j) {
8942 		return BOOTSTRAP_NO_MEMORY;
8943 	}
8944 
8945 	if (launchd_osinstaller) {
8946 		return BOOTSTRAP_UNKNOWN_SERVICE;
8947 	}
8948 
8949 #if TARGET_OS_EMBEDDED
8950 	// There is no need for per-user launchd's on embedded.
8951 	job_log(j, LOG_ERR, "Per-user launchds are not supported on this platform.");
8952 	return BOOTSTRAP_UNKNOWN_SERVICE;
8953 #endif
8954 
8955 #if HAVE_SANDBOX
8956 	if (unlikely(sandbox_check(ldc->pid, "mach-per-user-lookup", SANDBOX_FILTER_NONE) > 0)) {
8957 		return BOOTSTRAP_NOT_PRIVILEGED;
8958 	}
8959 #endif
8960 
8961 	job_log(j, LOG_INFO, "Looking up per user launchd for UID: %u", which_user);
8962 
8963 	if (unlikely(!pid1_magic)) {
8964 		job_log(j, LOG_ERR, "Only PID 1 supports per user launchd lookups.");
8965 		return BOOTSTRAP_NOT_PRIVILEGED;
8966 	}
8967 
8968 	if (ldc->euid || ldc->uid) {
8969 		which_user = ldc->euid ?: ldc->uid;
8970 	}
8971 
8972 	*up_cont = MACH_PORT_NULL;
8973 
8974 	jpu = jobmgr_lookup_per_user_context_internal(j, which_user, up_cont);
8975 
8976 	return 0;
8977 }
8978 
8979 kern_return_t
8980 job_mig_check_in2(job_t j, name_t servicename, mach_port_t *serviceportp, uuid_t instance_id, uint64_t flags)
8981 {
8982 	bool per_pid_service = flags & BOOTSTRAP_PER_PID_SERVICE;
8983 	bool strict = flags & BOOTSTRAP_STRICT_CHECKIN;
8984 	struct ldcred *ldc = runtime_get_caller_creds();
8985 	struct machservice *ms = NULL;
8986 	job_t jo;
8987 
8988 	if (!j) {
8989 		return BOOTSTRAP_NO_MEMORY;
8990 	}
8991 
8992 	if (j->dedicated_instance) {
8993 		struct machservice *msi = NULL;
8994 		SLIST_FOREACH(msi, &j->machservices, sle) {
8995 			if (strncmp(servicename, msi->name, sizeof(name_t) - 1) == 0) {
8996 				uuid_copy(instance_id, j->instance_id);
8997 				ms = msi;
8998 				break;
8999 			}
9000 		}
9001 	} else {
9002 		ms = jobmgr_lookup_service(j->mgr, servicename, false, per_pid_service ? ldc->pid : 0);
9003 	}
9004 
9005 	if (strict) {
9006 		if (likely(ms != NULL)) {
9007 			if (ms->job != j) {
9008 				return BOOTSTRAP_NOT_PRIVILEGED;
9009 			} else if (ms->isActive) {
9010 				return BOOTSTRAP_SERVICE_ACTIVE;
9011 			}
9012 		} else {
9013 			return BOOTSTRAP_UNKNOWN_SERVICE;
9014 		}
9015 	} else if (ms == NULL) {
9016 		if (job_assumes(j, !j->dedicated_instance)) {
9017 			*serviceportp = MACH_PORT_NULL;
9018 
9019 #if HAVE_SANDBOX
9020 			if (unlikely(sandbox_check(ldc->pid, "mach-register", per_pid_service ? SANDBOX_FILTER_LOCAL_NAME : SANDBOX_FILTER_GLOBAL_NAME, servicename) > 0)) {
9021 				return BOOTSTRAP_NOT_PRIVILEGED;
9022 			}
9023 #endif
9024 			if (unlikely((ms = machservice_new(j, servicename, serviceportp, per_pid_service)) == NULL)) {
9025 				return BOOTSTRAP_NO_MEMORY;
9026 			}
9027 
9028 			// Treat this like a legacy job.
9029 			if (!j->legacy_mach_job) {
9030 				ms->isActive = true;
9031 				ms->recv = false;
9032 			}
9033 
9034 			if (!(j->anonymous || j->legacy_LS_job || j->legacy_mach_job)) {
9035 				job_log(j, LOG_APPLEONLY, "Please add the following service to the configuration file for this job: %s", servicename);
9036 			}
9037 		} else {
9038 			return BOOTSTRAP_UNKNOWN_SERVICE;
9039 		}
9040 	} else {
9041 		if (unlikely((jo = machservice_job(ms)) != j)) {
9042 			static pid_t last_warned_pid;
9043 
9044 			if (last_warned_pid != ldc->pid) {
9045 				job_log(jo, LOG_WARNING, "The following job tried to hijack the service \"%s\" from this job: %s", servicename, j->label);
9046 				last_warned_pid = ldc->pid;
9047 			}
9048 
9049 			return BOOTSTRAP_NOT_PRIVILEGED;
9050 		}
9051 		if (unlikely(machservice_active(ms))) {
9052 			job_log(j, LOG_WARNING, "Check-in of Mach service failed. Already active: %s", servicename);
9053 			return BOOTSTRAP_SERVICE_ACTIVE;
9054 		}
9055 	}
9056 
9057 	job_checkin(j);
9058 	machservice_request_notifications(ms);
9059 
9060 	job_log(j, LOG_INFO, "Check-in of service: %s", servicename);
9061 
9062 	*serviceportp = machservice_port(ms);
9063 	return BOOTSTRAP_SUCCESS;
9064 }
9065 
9066 kern_return_t
9067 job_mig_register2(job_t j, name_t servicename, mach_port_t serviceport, uint64_t flags)
9068 {
9069 	struct machservice *ms;
9070 	struct ldcred *ldc = runtime_get_caller_creds();
9071 	bool per_pid_service = flags & BOOTSTRAP_PER_PID_SERVICE;
9072 
9073 	if (!j) {
9074 		return BOOTSTRAP_NO_MEMORY;
9075 	}
9076 
9077 	if (!per_pid_service && !j->legacy_LS_job) {
9078 		job_log(j, LOG_APPLEONLY, "Performance: bootstrap_register() is deprecated. Service: %s", servicename);
9079 	}
9080 
9081 	job_log(j, LOG_DEBUG, "%sMach service registration attempt: %s", flags & BOOTSTRAP_PER_PID_SERVICE ? "Per PID " : "", servicename);
9082 
9083 #if HAVE_SANDBOX
9084 	if (unlikely(sandbox_check(ldc->pid, "mach-register", per_pid_service ? SANDBOX_FILTER_LOCAL_NAME : SANDBOX_FILTER_GLOBAL_NAME, servicename) > 0)) {
9085 		return BOOTSTRAP_NOT_PRIVILEGED;
9086 	}
9087 #endif
9088 
9089 	// 5641783 for the embedded hack
9090 #if !TARGET_OS_EMBEDDED
9091 	/*
9092 	 * From a per-user/session launchd's perspective, SecurityAgent (UID
9093 	 * 92) is a rogue application (not our UID, not root and not a child of
9094 	 * us). We'll have to reconcile this design friction at a later date.
9095 	 */
9096 	if (unlikely(j->anonymous && j->mgr->parentmgr == NULL && ldc->uid != 0 && ldc->uid != getuid() && ldc->uid != 92)) {
9097 		if (pid1_magic) {
9098 			return VPROC_ERR_TRY_PER_USER;
9099 		} else {
9100 			return BOOTSTRAP_NOT_PRIVILEGED;
9101 		}
9102 	}
9103 #endif
9104 
9105 	ms = jobmgr_lookup_service(j->mgr, servicename, false, flags & BOOTSTRAP_PER_PID_SERVICE ? ldc->pid : 0);
9106 
9107 	if (unlikely(ms)) {
9108 		if (machservice_job(ms) != j) {
9109 			return BOOTSTRAP_NOT_PRIVILEGED;
9110 		}
9111 		if (machservice_active(ms)) {
9112 			job_log(j, LOG_DEBUG, "Mach service registration failed. Already active: %s", servicename);
9113 			return BOOTSTRAP_SERVICE_ACTIVE;
9114 		}
9115 		if (ms->recv && (serviceport != MACH_PORT_NULL)) {
9116 			job_log(j, LOG_ERR, "bootstrap_register() erroneously called instead of bootstrap_check_in(). Mach service: %s", servicename);
9117 			return BOOTSTRAP_NOT_PRIVILEGED;
9118 		}
9119 		job_checkin(j);
9120 		machservice_delete(j, ms, false);
9121 	}
9122 
9123 	if (likely(serviceport != MACH_PORT_NULL)) {
9124 		if (likely(ms = machservice_new(j, servicename, &serviceport, flags & BOOTSTRAP_PER_PID_SERVICE ? true : false))) {
9125 			machservice_request_notifications(ms);
9126 		} else {
9127 			return BOOTSTRAP_NO_MEMORY;
9128 		}
9129 	}
9130 
9131 
9132 	return BOOTSTRAP_SUCCESS;
9133 }
9134 
9135 kern_return_t
9136 job_mig_look_up2(job_t j, mach_port_t srp, name_t servicename, mach_port_t *serviceportp, pid_t target_pid, uuid_t instance_id, uint64_t flags)
9137 {
9138 	struct machservice *ms = NULL;
9139 	struct ldcred *ldc = runtime_get_caller_creds();
9140 	kern_return_t kr;
9141 	bool per_pid_lookup = flags & BOOTSTRAP_PER_PID_SERVICE;
9142 	bool specific_instance = flags & BOOTSTRAP_SPECIFIC_INSTANCE;
9143 	bool strict_lookup = flags & BOOTSTRAP_STRICT_LOOKUP;
9144 	bool privileged = flags & BOOTSTRAP_PRIVILEGED_SERVER;
9145 
9146 	if (!j) {
9147 		return BOOTSTRAP_NO_MEMORY;
9148 	}
9149 
9150 	bool xpc_req = (j->mgr->properties & BOOTSTRAP_PROPERTY_XPC_DOMAIN);
9151 
9152 	// 5641783 for the embedded hack
9153 #if !TARGET_OS_EMBEDDED
9154 	if (unlikely(pid1_magic && j->anonymous && j->mgr->parentmgr == NULL && ldc->uid != 0 && ldc->euid != 0)) {
9155 		return VPROC_ERR_TRY_PER_USER;
9156 	}
9157 #endif
9158 
9159 #if HAVE_SANDBOX
9160 	/* We don't do sandbox checking for XPC domains because, by definition, all
9161 	 * the services within your domain should be accessible to you.
9162 	 */
9163 	if (!xpc_req && unlikely(sandbox_check(ldc->pid, "mach-lookup", per_pid_lookup ? SANDBOX_FILTER_LOCAL_NAME : SANDBOX_FILTER_GLOBAL_NAME, servicename) > 0)) {
9164 		return BOOTSTRAP_NOT_PRIVILEGED;
9165 	}
9166 #endif
9167 
9168 	if (per_pid_lookup) {
9169 		ms = jobmgr_lookup_service(j->mgr, servicename, false, target_pid);
9170 	} else {
9171 		if (xpc_req) {
9172 			// Requests from XPC domains stay local.
9173 			ms = jobmgr_lookup_service(j->mgr, servicename, false, 0);
9174 		} else {
9175 			/* A strict lookup which is privileged won't even bother trying to
9176 			 * find a service if we're not hosting the root Mach bootstrap.
9177 			 */
9178 			if (strict_lookup && privileged) {
9179 				if (inherited_bootstrap_port == MACH_PORT_NULL) {
9180 					ms = jobmgr_lookup_service(j->mgr, servicename, true, 0);
9181 				}
9182 			} else {
9183 				ms = jobmgr_lookup_service(j->mgr, servicename, true, 0);
9184 			}
9185 		}
9186 	}
9187 
9188 	if (likely(ms)) {
9189 		ms = ms->alias ? ms->alias : ms;
9190 		if (unlikely(specific_instance && ms->job->multiple_instances)) {
9191 			job_t ji = NULL;
9192 			job_t instance = NULL;
9193 			LIST_FOREACH(ji, &ms->job->subjobs, subjob_sle) {
9194 				if (uuid_compare(instance_id, ji->instance_id) == 0) {
9195 					instance = ji;
9196 					break;
9197 				}
9198 			}
9199 
9200 			if (unlikely(instance == NULL)) {
9201 				job_log(ms->job, LOG_DEBUG, "Creating new instance of job based on lookup of service %s", ms->name);
9202 				instance = job_new_subjob(ms->job, instance_id);
9203 				if (job_assumes(j, instance != NULL)) {
9204 					/* Disable this support for now. We only support having
9205 					 * multi-instance jobs within private XPC domains.
9206 					 */
9207 #if 0
9208 					/* If the job is multi-instance, in a singleton XPC domain
9209 					 * and the request is not coming from within that singleton
9210 					 * domain, we need to alias the new job into the requesting
9211 					 * domain.
9212 					 */
9213 					if (!j->mgr->xpc_singleton && xpc_req) {
9214 						(void)job_assumes(instance, job_new_alias(j->mgr, instance));
9215 					}
9216 #endif
9217 					job_dispatch(instance, false);
9218 				}
9219 			}
9220 
9221 			ms = NULL;
9222 			if (job_assumes(j, instance != NULL)) {
9223 				struct machservice *msi = NULL;
9224 				SLIST_FOREACH(msi, &instance->machservices, sle) {
9225 					/* sizeof(servicename) will return the size of a pointer,
9226 					 * even though it's an array type, because when passing
9227 					 * arrays as parameters in C, they implicitly degrade to
9228 					 * pointers.
9229 					 */
9230 					if (strncmp(servicename, msi->name, sizeof(name_t) - 1) == 0) {
9231 						ms = msi;
9232 						break;
9233 					}
9234 				}
9235 			}
9236 		} else {
9237 			if (machservice_hidden(ms) && !machservice_active(ms)) {
9238 				ms = NULL;
9239 			} else if (unlikely(ms->per_user_hack)) {
9240 				ms = NULL;
9241 			}
9242 		}
9243 	}
9244 
9245 	if (likely(ms)) {
9246 		(void)job_assumes(j, machservice_port(ms) != MACH_PORT_NULL);
9247 		job_log(j, LOG_DEBUG, "%sMach service lookup: %s", per_pid_lookup ? "Per PID " : "", servicename);
9248 		*serviceportp = machservice_port(ms);
9249 
9250 		job_log(j, LOG_DEBUG, "Service port: <%d>\n", *serviceportp);
9251 
9252 		kr = BOOTSTRAP_SUCCESS;
9253 	} else if (strict_lookup && !privileged) {
9254 		/* Hack: We need to simulate XPC's desire not to establish a hierarchy.
9255 		 * So if XPC is doing the lookup, and it's not a privileged lookup, we
9256 		 * won't forward. But if it is a privileged lookup, then we must
9257 		 * forward.
9258 		 */
9259 		return BOOTSTRAP_UNKNOWN_SERVICE;
9260 	} else if (inherited_bootstrap_port != MACH_PORT_NULL) {
9261 		// Requests from within an XPC domain don't get forwarded.
9262 		job_log(j, LOG_DEBUG, "Mach service lookup forwarded: %s", servicename);
9263 		/* Clients potentially check the audit token of the reply to verify that
9264 		 * the returned send right is trustworthy.
9265 		 */
9266 		(void)job_assumes_zero(j, vproc_mig_look_up2_forward(inherited_bootstrap_port, srp, servicename, target_pid, instance_id, flags));
9267 		return MIG_NO_REPLY;
9268 	} else if (pid1_magic && j->anonymous && ldc->euid >= 500 && strcasecmp(j->mgr->name, VPROCMGR_SESSION_LOGINWINDOW) == 0) {
9269 		/* 5240036 Should start background session when a lookup of CCacheServer
9270 		 * occurs
9271 		 *
9272 		 * This is a total hack. We sniff out loginwindow session, and attempt
9273 		 * to guess what it is up to. If we find a EUID that isn't root, we
9274 		 * force it over to the per-user context.
9275 		 */
9276 		return VPROC_ERR_TRY_PER_USER;
9277 	} else {
9278 		job_log(j, LOG_DEBUG, "%sMach service lookup failed: %s", per_pid_lookup ? "Per PID " : "", servicename);
9279 		kr = BOOTSTRAP_UNKNOWN_SERVICE;
9280 	}
9281 
9282 	return kr;
9283 }
9284 
9285 kern_return_t
9286 job_mig_parent(job_t j, mach_port_t srp, mach_port_t *parentport)
9287 {
9288 	if (!j) {
9289 		return BOOTSTRAP_NO_MEMORY;
9290 	}
9291 
9292 	job_log(j, LOG_DEBUG, "Requested parent bootstrap port");
9293 	jobmgr_t jm = j->mgr;
9294 
9295 	if (jobmgr_parent(jm)) {
9296 		*parentport = jobmgr_parent(jm)->jm_port;
9297 	} else if (MACH_PORT_NULL == inherited_bootstrap_port) {
9298 		*parentport = jm->jm_port;
9299 	} else {
9300 		(void)job_assumes_zero(j, vproc_mig_parent_forward(inherited_bootstrap_port, srp));
9301 		// The previous routine moved the reply port, we're forced to return MIG_NO_REPLY now
9302 		return MIG_NO_REPLY;
9303 	}
9304 	return BOOTSTRAP_SUCCESS;
9305 }
9306 
9307 kern_return_t
9308 job_mig_get_root_bootstrap(job_t j, mach_port_t *rootbsp)
9309 {
9310 	if (!j) {
9311 		return BOOTSTRAP_NO_MEMORY;
9312 	}
9313 
9314 	if (inherited_bootstrap_port == MACH_PORT_NULL) {
9315 		*rootbsp = root_jobmgr->jm_port;
9316 		(void)job_assumes_zero(j, launchd_mport_make_send(root_jobmgr->jm_port));
9317 	} else {
9318 		*rootbsp = inherited_bootstrap_port;
9319 		(void)job_assumes_zero(j, launchd_mport_copy_send(inherited_bootstrap_port));
9320 	}
9321 
9322 	return BOOTSTRAP_SUCCESS;
9323 }
9324 
9325 kern_return_t
9326 job_mig_info(job_t j, name_array_t *servicenamesp,
9327 	unsigned int *servicenames_cnt, name_array_t *servicejobsp,
9328 	unsigned int *servicejobs_cnt, bootstrap_status_array_t *serviceactivesp,
9329 	unsigned int *serviceactives_cnt, uint64_t flags)
9330 {
9331 	name_array_t service_names = NULL;
9332 	name_array_t service_jobs = NULL;
9333 	bootstrap_status_array_t service_actives = NULL;
9334 	unsigned int cnt = 0, cnt2 = 0;
9335 	jobmgr_t jm;
9336 
9337 	if (!j) {
9338 		return BOOTSTRAP_NO_MEMORY;
9339 	}
9340 
9341 #if TARGET_OS_EMBEDDED
9342 	struct ldcred *ldc = runtime_get_caller_creds();
9343 	if (ldc->euid) {
9344 		return EPERM;
9345 	}
9346 #endif // TARGET_OS_EMBEDDED
9347 
9348 	if (launchd_flat_mach_namespace) {
9349 		if ((j->mgr->properties & BOOTSTRAP_PROPERTY_EXPLICITSUBSET) || (flags & BOOTSTRAP_FORCE_LOCAL)) {
9350 			jm = j->mgr;
9351 		} else {
9352 			jm = root_jobmgr;
9353 		}
9354 	} else {
9355 		jm = j->mgr;
9356 	}
9357 
9358 	unsigned int i = 0;
9359 	struct machservice *msi = NULL;
9360 	for (i = 0; i < MACHSERVICE_HASH_SIZE; i++) {
9361 		LIST_FOREACH(msi, &jm->ms_hash[i], name_hash_sle) {
9362 			cnt += !msi->per_pid ? 1 : 0;
9363 		}
9364 	}
9365 
9366 	if (cnt == 0) {
9367 		goto out;
9368 	}
9369 
9370 	mig_allocate((vm_address_t *)&service_names, cnt * sizeof(service_names[0]));
9371 	if (!job_assumes(j, service_names != NULL)) {
9372 		goto out_bad;
9373 	}
9374 
9375 	mig_allocate((vm_address_t *)&service_jobs, cnt * sizeof(service_jobs[0]));
9376 	if (!job_assumes(j, service_jobs != NULL)) {
9377 		goto out_bad;
9378 	}
9379 
9380 	mig_allocate((vm_address_t *)&service_actives, cnt * sizeof(service_actives[0]));
9381 	if (!job_assumes(j, service_actives != NULL)) {
9382 		goto out_bad;
9383 	}
9384 
9385 	for (i = 0; i < MACHSERVICE_HASH_SIZE; i++) {
9386 		LIST_FOREACH(msi, &jm->ms_hash[i], name_hash_sle) {
9387 			if (!msi->per_pid) {
9388 				strlcpy(service_names[cnt2], machservice_name(msi), sizeof(service_names[0]));
9389 				msi = msi->alias ? msi->alias : msi;
9390 				if (msi->job->mgr->shortdesc) {
9391 					strlcpy(service_jobs[cnt2], msi->job->mgr->shortdesc, sizeof(service_jobs[0]));
9392 				} else {
9393 					strlcpy(service_jobs[cnt2], msi->job->label, sizeof(service_jobs[0]));
9394 				}
9395 				service_actives[cnt2] = machservice_status(msi);
9396 				cnt2++;
9397 			}
9398 		}
9399 	}
9400 
9401 	(void)job_assumes(j, cnt == cnt2);
9402 
9403 out:
9404 	*servicenamesp = service_names;
9405 	*servicejobsp = service_jobs;
9406 	*serviceactivesp = service_actives;
9407 	*servicenames_cnt = *servicejobs_cnt = *serviceactives_cnt = cnt;
9408 
9409 	return BOOTSTRAP_SUCCESS;
9410 
9411 out_bad:
9412 	if (service_names) {
9413 		mig_deallocate((vm_address_t)service_names, cnt * sizeof(service_names[0]));
9414 	}
9415 	if (service_jobs) {
9416 		mig_deallocate((vm_address_t)service_jobs, cnt * sizeof(service_jobs[0]));
9417 	}
9418 	if (service_actives) {
9419 		mig_deallocate((vm_address_t)service_actives, cnt * sizeof(service_actives[0]));
9420 	}
9421 
9422 	return BOOTSTRAP_NO_MEMORY;
9423 }
9424 
9425 kern_return_t
9426 job_mig_lookup_children(job_t j, mach_port_array_t *child_ports,
9427 	mach_msg_type_number_t *child_ports_cnt, name_array_t *child_names,
9428 	mach_msg_type_number_t *child_names_cnt,
9429 	bootstrap_property_array_t *child_properties,
9430 	mach_msg_type_number_t *child_properties_cnt)
9431 {
9432 	kern_return_t kr = BOOTSTRAP_NO_MEMORY;
9433 	if (!j) {
9434 		return BOOTSTRAP_NO_MEMORY;
9435 	}
9436 
9437 	struct ldcred *ldc = runtime_get_caller_creds();
9438 
9439 	/* Only allow root processes to look up children, even if we're in the per-user launchd.
9440 	 * Otherwise, this could be used to cross sessions, which counts as a security vulnerability
9441 	 * in a non-flat namespace.
9442 	 */
9443 	if (ldc->euid != 0) {
9444 		job_log(j, LOG_WARNING, "Attempt to look up children of bootstrap by unprivileged job.");
9445 		return BOOTSTRAP_NOT_PRIVILEGED;
9446 	}
9447 
9448 	unsigned int cnt = 0;
9449 
9450 	jobmgr_t jmr = j->mgr;
9451 	jobmgr_t jmi = NULL;
9452 	SLIST_FOREACH(jmi, &jmr->submgrs, sle) {
9453 		cnt++;
9454 	}
9455 
9456 	// Find our per-user launchds if we're PID 1.
9457 	job_t ji = NULL;
9458 	if (pid1_magic) {
9459 		LIST_FOREACH(ji, &jmr->jobs, sle) {
9460 			cnt += ji->per_user ? 1 : 0;
9461 		}
9462 	}
9463 
9464 	if (cnt == 0) {
9465 		return BOOTSTRAP_NO_CHILDREN;
9466 	}
9467 
9468 	mach_port_array_t _child_ports = NULL;
9469 	name_array_t _child_names = NULL;
9470 	bootstrap_property_array_t _child_properties = NULL;
9471 
9472 	mig_allocate((vm_address_t *)&_child_ports, cnt * sizeof(_child_ports[0]));
9473 	if (!job_assumes(j, _child_ports != NULL)) {
9474 		kr = BOOTSTRAP_NO_MEMORY;
9475 		goto out_bad;
9476 	}
9477 
9478 	mig_allocate((vm_address_t *)&_child_names, cnt * sizeof(_child_names[0]));
9479 	if (!job_assumes(j, _child_names != NULL)) {
9480 		kr = BOOTSTRAP_NO_MEMORY;
9481 		goto out_bad;
9482 	}
9483 
9484 	mig_allocate((vm_address_t *)&_child_properties, cnt * sizeof(_child_properties[0]));
9485 	if (!job_assumes(j, _child_properties != NULL)) {
9486 		kr = BOOTSTRAP_NO_MEMORY;
9487 		goto out_bad;
9488 	}
9489 
9490 	unsigned int cnt2 = 0;
9491 	SLIST_FOREACH(jmi, &jmr->submgrs, sle) {
9492 		if (jobmgr_assumes_zero(jmi, launchd_mport_make_send(jmi->jm_port)) == KERN_SUCCESS) {
9493 			_child_ports[cnt2] = jmi->jm_port;
9494 		} else {
9495 			_child_ports[cnt2] = MACH_PORT_NULL;
9496 		}
9497 
9498 		strlcpy(_child_names[cnt2], jmi->name, sizeof(_child_names[0]));
9499 		_child_properties[cnt2] = jmi->properties;
9500 
9501 		cnt2++;
9502 	}
9503 
9504 	if (pid1_magic) LIST_FOREACH(ji, &jmr->jobs, sle) {
9505 		if (ji->per_user) {
9506 			if (job_assumes(ji, SLIST_FIRST(&ji->machservices)->per_user_hack == true)) {
9507 				mach_port_t port = machservice_port(SLIST_FIRST(&ji->machservices));
9508 
9509 				if (job_assumes_zero(ji, launchd_mport_copy_send(port)) == KERN_SUCCESS) {
9510 					_child_ports[cnt2] = port;
9511 				} else {
9512 					_child_ports[cnt2] = MACH_PORT_NULL;
9513 				}
9514 			} else {
9515 				_child_ports[cnt2] = MACH_PORT_NULL;
9516 			}
9517 
9518 			strlcpy(_child_names[cnt2], ji->label, sizeof(_child_names[0]));
9519 			_child_properties[cnt2] |= BOOTSTRAP_PROPERTY_PERUSER;
9520 
9521 			cnt2++;
9522 		}
9523 	}
9524 
9525 	*child_names_cnt = cnt;
9526 	*child_ports_cnt = cnt;
9527 	*child_properties_cnt = cnt;
9528 
9529 	*child_names = _child_names;
9530 	*child_ports = _child_ports;
9531 	*child_properties = _child_properties;
9532 
9533 	unsigned int i = 0;
9534 	for (i = 0; i < cnt; i++) {
9535 		job_log(j, LOG_DEBUG, "child_names[%u] = %s", i, (char *)_child_names[i]);
9536 	}
9537 
9538 	return BOOTSTRAP_SUCCESS;
9539 out_bad:
9540 	if (_child_ports) {
9541 		mig_deallocate((vm_address_t)_child_ports, cnt * sizeof(_child_ports[0]));
9542 	}
9543 
9544 	if (_child_names) {
9545 		mig_deallocate((vm_address_t)_child_names, cnt * sizeof(_child_names[0]));
9546 	}
9547 
9548 	if (_child_properties) {
9549 		mig_deallocate((vm_address_t)_child_properties, cnt * sizeof(_child_properties[0]));
9550 	}
9551 
9552 	return kr;
9553 }
9554 
9555 kern_return_t
9556 job_mig_pid_is_managed(job_t j __attribute__((unused)), pid_t p, boolean_t *managed)
9557 {
9558 	struct ldcred *ldc = runtime_get_caller_creds();
9559 	if ((ldc->euid != geteuid()) && (ldc->euid != 0)) {
9560 		return BOOTSTRAP_NOT_PRIVILEGED;
9561 	}
9562 
9563 	/* This is so loginwindow doesn't try to quit GUI apps that have been launched
9564 	 * directly by launchd as agents.
9565 	 */
9566 	job_t j_for_pid = jobmgr_find_by_pid_deep(root_jobmgr, p, false);
9567 	if (j_for_pid && !j_for_pid->anonymous && !j_for_pid->legacy_LS_job) {
9568 		*managed = true;
9569 	}
9570 
9571 	return BOOTSTRAP_SUCCESS;
9572 }
9573 
9574 kern_return_t
9575 job_mig_port_for_label(job_t j __attribute__((unused)), name_t label, mach_port_t *mp)
9576 {
9577 	if (!j) {
9578 		return BOOTSTRAP_NO_MEMORY;
9579 	}
9580 
9581 	struct ldcred *ldc = runtime_get_caller_creds();
9582 	kern_return_t kr = BOOTSTRAP_NOT_PRIVILEGED;
9583 
9584 #if HAVE_SANDBOX
9585 	if (unlikely(sandbox_check(ldc->pid, "job-creation", SANDBOX_FILTER_NONE) > 0)) {
9586 		return BOOTSTRAP_NOT_PRIVILEGED;
9587 	}
9588 #endif
9589 
9590 	mach_port_t _mp = MACH_PORT_NULL;
9591 	if (!j->deny_job_creation && (ldc->euid == 0 || ldc->euid == geteuid())) {
9592 		job_t target_j = job_find(NULL, label);
9593 		if (jobmgr_assumes(root_jobmgr, target_j != NULL)) {
9594 			if (target_j->j_port == MACH_PORT_NULL) {
9595 				(void)job_assumes(target_j, job_setup_machport(target_j) == true);
9596 			}
9597 
9598 			_mp = target_j->j_port;
9599 			kr = _mp != MACH_PORT_NULL ? BOOTSTRAP_SUCCESS : BOOTSTRAP_NO_MEMORY;
9600 		} else {
9601 			kr = BOOTSTRAP_NO_MEMORY;
9602 		}
9603 	}
9604 
9605 	*mp = _mp;
9606 	return kr;
9607 }
9608 
9609 kern_return_t
9610 job_mig_set_security_session(job_t j, uuid_t uuid, mach_port_t asport)
9611 {
9612 #if TARGET_OS_EMBEDDED
9613 	return KERN_SUCCESS;
9614 #endif
9615 
9616 	if (!j) {
9617 		return BOOTSTRAP_NO_MEMORY;
9618 	}
9619 
9620 	uuid_string_t uuid_str;
9621 	uuid_unparse(uuid, uuid_str);
9622 	job_log(j, LOG_DEBUG, "Setting session %u for UUID %s...", asport, uuid_str);
9623 
9624 	job_t ji = NULL, jt = NULL;
9625 	LIST_FOREACH_SAFE(ji, &s_needing_sessions, sle, jt) {
9626 		uuid_string_t uuid_str2;
9627 		uuid_unparse(ji->expected_audit_uuid, uuid_str2);
9628 
9629 		if (uuid_compare(uuid, ji->expected_audit_uuid) == 0) {
9630 			uuid_clear(ji->expected_audit_uuid);
9631 			if (asport != MACH_PORT_NULL) {
9632 				job_log(ji, LOG_DEBUG, "Job should join session with port 0x%x", asport);
9633 				(void)job_assumes_zero(j, launchd_mport_copy_send(asport));
9634 			} else {
9635 				job_log(ji, LOG_DEBUG, "No session to set for job. Using our session.");
9636 			}
9637 
9638 			ji->asport = asport;
9639 			LIST_REMOVE(ji, needing_session_sle);
9640 
9641 			if (ji->event_monitor) {
9642 				eventsystem_ping();
9643 			} else {
9644 				job_dispatch(ji, false);
9645 			}
9646 		}
9647 	}
9648 
9649 	/* Each job that the session port was set for holds a reference. At the end of
9650 	 * the loop, there will be one extra reference belonging to this MiG protocol.
9651 	 * We need to release it so that the session goes away when all the jobs
9652 	 * referencing it are unloaded.
9653 	 */
9654 	(void)job_assumes_zero(j, launchd_mport_deallocate(asport));
9655 
9656 	return KERN_SUCCESS;
9657 }
9658 
9659 jobmgr_t
9660 jobmgr_find_by_name(jobmgr_t jm, const char *where)
9661 {
9662 	jobmgr_t jmi, jmi2;
9663 
9664 	// NULL is only passed for our custom API for LaunchServices. If that is the case, we do magic.
9665 	if (where == NULL) {
9666 		if (strcasecmp(jm->name, VPROCMGR_SESSION_LOGINWINDOW) == 0) {
9667 			where = VPROCMGR_SESSION_LOGINWINDOW;
9668 		} else {
9669 			where = VPROCMGR_SESSION_AQUA;
9670 		}
9671 	}
9672 
9673 	if (strcasecmp(jm->name, where) == 0) {
9674 		return jm;
9675 	}
9676 
9677 	if (strcasecmp(where, VPROCMGR_SESSION_BACKGROUND) == 0 && !pid1_magic) {
9678 		jmi = root_jobmgr;
9679 		goto jm_found;
9680 	}
9681 
9682 	SLIST_FOREACH(jmi, &root_jobmgr->submgrs, sle) {
9683 		if (unlikely(jmi->shutting_down)) {
9684 			continue;
9685 		} else if (jmi->properties & BOOTSTRAP_PROPERTY_XPC_DOMAIN) {
9686 			continue;
9687 		} else if (strcasecmp(jmi->name, where) == 0) {
9688 			goto jm_found;
9689 		} else if (strcasecmp(jmi->name, VPROCMGR_SESSION_BACKGROUND) == 0 && pid1_magic) {
9690 			SLIST_FOREACH(jmi2, &jmi->submgrs, sle) {
9691 				if (strcasecmp(jmi2->name, where) == 0) {
9692 					jmi = jmi2;
9693 					goto jm_found;
9694 				}
9695 			}
9696 		}
9697 	}
9698 
9699 jm_found:
9700 	return jmi;
9701 }
9702 
9703 kern_return_t
9704 job_mig_move_subset(job_t j, mach_port_t target_subset, name_t session_type, mach_port_t asport, uint64_t flags)
9705 {
9706 	mach_msg_type_number_t l2l_i, l2l_port_cnt = 0;
9707 	mach_port_array_t l2l_ports = NULL;
9708 	mach_port_t reqport, rcvright;
9709 	kern_return_t kr = 1;
9710 	launch_data_t out_obj_array = NULL;
9711 	struct ldcred *ldc = runtime_get_caller_creds();
9712 	jobmgr_t jmr = NULL;
9713 
9714 	if (!j) {
9715 		return BOOTSTRAP_NO_MEMORY;
9716 	}
9717 
9718 	if (job_mig_intran2(root_jobmgr, target_subset, ldc->pid)) {
9719 		job_log(j, LOG_ERR, "Moving a session to ourself is bogus.");
9720 
9721 		kr = BOOTSTRAP_NOT_PRIVILEGED;
9722 		goto out;
9723 	}
9724 
9725 	job_log(j, LOG_DEBUG, "Move subset attempt: 0x%x", target_subset);
9726 
9727 	kr = _vproc_grab_subset(target_subset, &reqport, &rcvright, &out_obj_array, &l2l_ports, &l2l_port_cnt);
9728 	if (job_assumes_zero(j, kr) != 0) {
9729 		goto out;
9730 	}
9731 
9732 	if (launch_data_array_get_count(out_obj_array) != l2l_port_cnt) {
9733 		os_assert_zero(l2l_port_cnt);
9734 	}
9735 
9736 	if (!job_assumes(j, (jmr = jobmgr_new(j->mgr, reqport, rcvright, false, session_type, false, asport)) != NULL)) {
9737 		kr = BOOTSTRAP_NO_MEMORY;
9738 		goto out;
9739 	}
9740 
9741 	if (strcmp(session_type, VPROCMGR_SESSION_AQUA) == 0) {
9742 		jobmgr_log(jmr, LOG_NOTICE, "Registering new GUI session.");
9743 		kr = vproc_mig_register_gui_session(inherited_bootstrap_port, asport);
9744 		if (kr) {
9745 			jobmgr_log(jmr, LOG_ERR, "Failed to register GUI session with PID 1: 0x%x/0x%x", inherited_bootstrap_port, kr);
9746 		}
9747 	}
9748 
9749 	jmr->properties |= BOOTSTRAP_PROPERTY_MOVEDSUBSET;
9750 
9751 	/* This is a hack. We should be doing this in jobmgr_new(), but since we're in the middle of
9752 	 * processing an IPC request, we'll do this action before the new job manager can get any IPC
9753 	 * requests. This serialization is guaranteed since we are single-threaded in that respect.
9754 	 */
9755 	if (flags & LAUNCH_GLOBAL_ON_DEMAND) {
9756 		// This is so awful.
9757 		// Remove the job from its current job manager.
9758 		LIST_REMOVE(j, sle);
9759 		LIST_REMOVE(j, pid_hash_sle);
9760 
9761 		// Put the job into the target job manager.
9762 		LIST_INSERT_HEAD(&jmr->jobs, j, sle);
9763 		LIST_INSERT_HEAD(&jmr->active_jobs[ACTIVE_JOB_HASH(j->p)], j, pid_hash_sle);
9764 
9765 		j->mgr = jmr;
9766 		job_set_global_on_demand(j, true);
9767 
9768 		if (!j->holds_ref) {
9769 			job_log(j, LOG_PERF, "Job moved subset into: %s", j->mgr->name);
9770 			j->holds_ref = true;
9771 			runtime_add_ref();
9772 		}
9773 	}
9774 
9775 	for (l2l_i = 0; l2l_i < l2l_port_cnt; l2l_i++) {
9776 		launch_data_t tmp, obj_at_idx;
9777 		struct machservice *ms;
9778 		job_t j_for_service;
9779 		const char *serv_name;
9780 		pid_t target_pid;
9781 		bool serv_perpid;
9782 
9783 		(void)job_assumes(j, obj_at_idx = launch_data_array_get_index(out_obj_array, l2l_i));
9784 		(void)job_assumes(j, tmp = launch_data_dict_lookup(obj_at_idx, TAKE_SUBSET_PID));
9785 		target_pid = (pid_t)launch_data_get_integer(tmp);
9786 		(void)job_assumes(j, tmp = launch_data_dict_lookup(obj_at_idx, TAKE_SUBSET_PERPID));
9787 		serv_perpid = launch_data_get_bool(tmp);
9788 		(void)job_assumes(j, tmp = launch_data_dict_lookup(obj_at_idx, TAKE_SUBSET_NAME));
9789 		serv_name = launch_data_get_string(tmp);
9790 
9791 		j_for_service = jobmgr_find_by_pid(jmr, target_pid, true);
9792 
9793 		if (unlikely(!j_for_service)) {
9794 			// The PID probably exited
9795 			(void)job_assumes_zero(j, launchd_mport_deallocate(l2l_ports[l2l_i]));
9796 			continue;
9797 		}
9798 
9799 		if (likely(ms = machservice_new(j_for_service, serv_name, &l2l_ports[l2l_i], serv_perpid))) {
9800 			job_log(j, LOG_DEBUG, "Importing %s into new bootstrap.", serv_name);
9801 			machservice_request_notifications(ms);
9802 		}
9803 	}
9804 
9805 	kr = 0;
9806 
9807 out:
9808 	if (out_obj_array) {
9809 		launch_data_free(out_obj_array);
9810 	}
9811 
9812 	if (l2l_ports) {
9813 		mig_deallocate((vm_address_t)l2l_ports, l2l_port_cnt * sizeof(l2l_ports[0]));
9814 	}
9815 
9816 	if (kr == 0) {
9817 		if (target_subset) {
9818 			(void)job_assumes_zero(j, launchd_mport_deallocate(target_subset));
9819 		}
9820 		if (asport) {
9821 			(void)job_assumes_zero(j, launchd_mport_deallocate(asport));
9822 		}
9823 	} else if (jmr) {
9824 		jobmgr_shutdown(jmr);
9825 	}
9826 
9827 	return kr;
9828 }
9829 
9830 kern_return_t
9831 job_mig_init_session(job_t j, name_t session_type, mach_port_t asport)
9832 {
9833 	if (!j) {
9834 		return BOOTSTRAP_NO_MEMORY;
9835 	}
9836 
9837 	job_t j2;
9838 
9839 	kern_return_t kr = BOOTSTRAP_NO_MEMORY;
9840 	if (j->mgr->session_initialized) {
9841 		job_log(j, LOG_ERR, "Tried to initialize an already setup session!");
9842 		kr = BOOTSTRAP_NOT_PRIVILEGED;
9843 		return kr;
9844 	} else if (strcmp(session_type, VPROCMGR_SESSION_LOGINWINDOW) == 0) {
9845 		jobmgr_t jmi;
9846 
9847 		/*
9848 		 * 5330262
9849 		 *
9850 		 * We're working around LoginWindow and the WindowServer.
9851 		 *
9852 		 * In practice, there is only one LoginWindow session. Unfortunately, for certain
9853 		 * scenarios, the WindowServer spawns loginwindow, and in those cases, it frequently
9854 		 * spawns a replacement loginwindow session before cleaning up the previous one.
9855 		 *
9856 		 * We're going to use the creation of a new LoginWindow context as a clue that the
9857 		 * previous LoginWindow context is on the way out and therefore we should just
9858 		 * kick-start the shutdown of it.
9859 		 */
9860 
9861 		SLIST_FOREACH(jmi, &root_jobmgr->submgrs, sle) {
9862 			if (unlikely(jmi->shutting_down)) {
9863 				continue;
9864 			} else if (strcasecmp(jmi->name, session_type) == 0) {
9865 				jobmgr_shutdown(jmi);
9866 				break;
9867 			}
9868 		}
9869 	} else if (strcmp(session_type, VPROCMGR_SESSION_AQUA) == 0) {
9870 		(void)job_assumes_zero(j, runtime_remove_mport(j->mgr->jm_port));
9871  	}
9872 
9873 	jobmgr_log(j->mgr, LOG_DEBUG, "Initializing as %s", session_type);
9874 	strcpy(j->mgr->name_init, session_type);
9875 
9876 	if (job_assumes(j, (j2 = jobmgr_init_session(j->mgr, session_type, false)))) {
9877 		j2->asport = asport;
9878 		(void)job_assumes(j, job_dispatch(j2, true));
9879 		kr = BOOTSTRAP_SUCCESS;
9880 	}
9881 
9882 	return kr;
9883 }
9884 
9885 kern_return_t
9886 job_mig_switch_to_session(job_t j, mach_port_t requestor_port, name_t session_name, mach_port_t asport, mach_port_t *new_bsport)
9887 {
9888 	struct ldcred *ldc = runtime_get_caller_creds();
9889 	if (!jobmgr_assumes(root_jobmgr, j != NULL)) {
9890 		jobmgr_log(root_jobmgr, LOG_ERR, "%s() called with NULL job: PID %d", __func__, ldc->pid);
9891 		return BOOTSTRAP_NO_MEMORY;
9892 	}
9893 
9894 	if (j->mgr->shutting_down) {
9895 		return BOOTSTRAP_UNKNOWN_SERVICE;
9896 	}
9897 
9898 	job_log(j, LOG_DEBUG, "Job wants to move to %s session.", session_name);
9899 
9900 	if (!job_assumes(j, pid1_magic == false)) {
9901 		job_log(j, LOG_WARNING, "Switching sessions is not allowed in the system Mach bootstrap.");
9902 		return BOOTSTRAP_NOT_PRIVILEGED;
9903 	}
9904 
9905 	if (!j->anonymous) {
9906 		job_log(j, LOG_NOTICE, "Non-anonymous job tried to switch sessions. Please use LimitLoadToSessionType instead.");
9907 		return BOOTSTRAP_NOT_PRIVILEGED;
9908 	}
9909 
9910 	jobmgr_t target_jm = jobmgr_find_by_name(root_jobmgr, session_name);
9911 	if (target_jm == j->mgr) {
9912 		job_log(j, LOG_DEBUG, "Job is already in its desired session (%s).", session_name);
9913 		(void)job_assumes_zero(j, launchd_mport_deallocate(asport));
9914 		(void)job_assumes_zero(j, launchd_mport_deallocate(requestor_port));
9915 		*new_bsport = target_jm->jm_port;
9916 		return BOOTSTRAP_SUCCESS;
9917 	}
9918 
9919 	if (!target_jm) {
9920 		target_jm = jobmgr_new(j->mgr, requestor_port, MACH_PORT_NULL, false, session_name, false, asport);
9921 		if (target_jm) {
9922 			target_jm->properties |= BOOTSTRAP_PROPERTY_IMPLICITSUBSET;
9923 			(void)job_assumes_zero(j, launchd_mport_deallocate(asport));
9924 		}
9925 	}
9926 
9927 	if (!job_assumes(j, target_jm != NULL)) {
9928 		job_log(j, LOG_WARNING, "Could not find %s session!", session_name);
9929 		return BOOTSTRAP_NO_MEMORY;
9930 	}
9931 
9932 	// Remove the job from it's current job manager.
9933 	LIST_REMOVE(j, sle);
9934 	LIST_REMOVE(j, pid_hash_sle);
9935 
9936 	job_t ji = NULL, jit = NULL;
9937 	LIST_FOREACH_SAFE(ji, &j->mgr->global_env_jobs, global_env_sle, jit) {
9938 		if (ji == j) {
9939 			LIST_REMOVE(ji, global_env_sle);
9940 			break;
9941 		}
9942 	}
9943 
9944 	// Put the job into the target job manager.
9945 	LIST_INSERT_HEAD(&target_jm->jobs, j, sle);
9946 	LIST_INSERT_HEAD(&target_jm->active_jobs[ACTIVE_JOB_HASH(j->p)], j, pid_hash_sle);
9947 
9948 	if (ji) {
9949 		LIST_INSERT_HEAD(&target_jm->global_env_jobs, j, global_env_sle);
9950 	}
9951 
9952 	// Move our Mach services over if we're not in a flat namespace.
9953 	if (!launchd_flat_mach_namespace && !SLIST_EMPTY(&j->machservices)) {
9954 		struct machservice *msi = NULL, *msit = NULL;
9955 		SLIST_FOREACH_SAFE(msi, &j->machservices, sle, msit) {
9956 			LIST_REMOVE(msi, name_hash_sle);
9957 			LIST_INSERT_HEAD(&target_jm->ms_hash[hash_ms(msi->name)], msi, name_hash_sle);
9958 		}
9959 	}
9960 
9961 	j->mgr = target_jm;
9962 
9963 	if (!j->holds_ref) {
9964 		/* Anonymous jobs which move around are particularly interesting to us, so we want to
9965 		 * stick around while they're still around.
9966 		 * For example, login calls into the PAM launchd module, which moves the process into
9967 		 * the StandardIO session by default. So we'll hold a reference on that job to prevent
9968 		 * ourselves from going away.
9969 		 */
9970 		j->holds_ref = true;
9971 		job_log(j, LOG_PERF, "Job switched into manager: %s", j->mgr->name);
9972 		runtime_add_ref();
9973 	}
9974 
9975 	*new_bsport = target_jm->jm_port;
9976 
9977 	return KERN_SUCCESS;
9978 }
9979 
9980 kern_return_t
9981 job_mig_take_subset(job_t j, mach_port_t *reqport, mach_port_t *rcvright,
9982 		vm_offset_t *outdata, mach_msg_type_number_t *outdataCnt,
9983 		mach_port_array_t *portsp, unsigned int *ports_cnt)
9984 {
9985 	launch_data_t tmp_obj, tmp_dict, outdata_obj_array = NULL;
9986 	mach_port_array_t ports = NULL;
9987 	unsigned int cnt = 0, cnt2 = 0;
9988 	size_t packed_size;
9989 	struct machservice *ms;
9990 	jobmgr_t jm;
9991 	job_t ji;
9992 
9993 	if (!j) {
9994 		return BOOTSTRAP_NO_MEMORY;
9995 	}
9996 
9997 	jm = j->mgr;
9998 
9999 	if (unlikely(!pid1_magic)) {
10000 		job_log(j, LOG_ERR, "Only the system launchd will transfer Mach sub-bootstraps.");
10001 		return BOOTSTRAP_NOT_PRIVILEGED;
10002 	}
10003 	if (unlikely(jobmgr_parent(jm) == NULL)) {
10004 		job_log(j, LOG_ERR, "Root Mach bootstrap cannot be transferred.");
10005 		return BOOTSTRAP_NOT_PRIVILEGED;
10006 	}
10007 	if (unlikely(strcasecmp(jm->name, VPROCMGR_SESSION_AQUA) == 0)) {
10008 		job_log(j, LOG_ERR, "Cannot transfer a setup GUI session.");
10009 		return BOOTSTRAP_NOT_PRIVILEGED;
10010 	}
10011 	if (unlikely(!j->anonymous)) {
10012 		job_log(j, LOG_ERR, "Only the anonymous job can transfer Mach sub-bootstraps.");
10013 		return BOOTSTRAP_NOT_PRIVILEGED;
10014 	}
10015 
10016 	job_log(j, LOG_DEBUG, "Transferring sub-bootstrap to the per session launchd.");
10017 
10018 	outdata_obj_array = launch_data_alloc(LAUNCH_DATA_ARRAY);
10019 	if (!job_assumes(j, outdata_obj_array)) {
10020 		goto out_bad;
10021 	}
10022 
10023 	*outdataCnt = 20 * 1024 * 1024;
10024 	mig_allocate(outdata, *outdataCnt);
10025 	if (!job_assumes(j, *outdata != 0)) {
10026 		return 1;
10027 	}
10028 
10029 	LIST_FOREACH(ji, &j->mgr->jobs, sle) {
10030 		if (!ji->anonymous) {
10031 			continue;
10032 		}
10033 		SLIST_FOREACH(ms, &ji->machservices, sle) {
10034 			cnt++;
10035 		}
10036 	}
10037 
10038 	mig_allocate((vm_address_t *)&ports, cnt * sizeof(ports[0]));
10039 	if (!job_assumes(j, ports != NULL)) {
10040 		goto out_bad;
10041 	}
10042 
10043 	LIST_FOREACH(ji, &j->mgr->jobs, sle) {
10044 		if (!ji->anonymous) {
10045 			continue;
10046 		}
10047 
10048 		SLIST_FOREACH(ms, &ji->machservices, sle) {
10049 			if (job_assumes(j, (tmp_dict = launch_data_alloc(LAUNCH_DATA_DICTIONARY)))) {
10050 				(void)job_assumes(j, launch_data_array_set_index(outdata_obj_array, tmp_dict, cnt2));
10051 			} else {
10052 				goto out_bad;
10053 			}
10054 
10055 			if (job_assumes(j, (tmp_obj = launch_data_new_string(machservice_name(ms))))) {
10056 				(void)job_assumes(j, launch_data_dict_insert(tmp_dict, tmp_obj, TAKE_SUBSET_NAME));
10057 			} else {
10058 				goto out_bad;
10059 			}
10060 
10061 			if (job_assumes(j, (tmp_obj = launch_data_new_integer((ms->job->p))))) {
10062 				(void)job_assumes(j, launch_data_dict_insert(tmp_dict, tmp_obj, TAKE_SUBSET_PID));
10063 			} else {
10064 				goto out_bad;
10065 			}
10066 
10067 			if (job_assumes(j, (tmp_obj = launch_data_new_bool((ms->per_pid))))) {
10068 				(void)job_assumes(j, launch_data_dict_insert(tmp_dict, tmp_obj, TAKE_SUBSET_PERPID));
10069 			} else {
10070 				goto out_bad;
10071 			}
10072 
10073 			ports[cnt2] = machservice_port(ms);
10074 
10075 			// Increment the send right by one so we can shutdown the jobmgr cleanly
10076 			(void)jobmgr_assumes_zero(jm, launchd_mport_copy_send(ports[cnt2]));
10077 			cnt2++;
10078 		}
10079 	}
10080 
10081 	(void)job_assumes(j, cnt == cnt2);
10082 
10083 	runtime_ktrace0(RTKT_LAUNCHD_DATA_PACK);
10084 	packed_size = launch_data_pack(outdata_obj_array, (void *)*outdata, *outdataCnt, NULL, NULL);
10085 	if (!job_assumes(j, packed_size != 0)) {
10086 		goto out_bad;
10087 	}
10088 
10089 	launch_data_free(outdata_obj_array);
10090 
10091 	*portsp = ports;
10092 	*ports_cnt = cnt;
10093 
10094 	*reqport = jm->req_port;
10095 	*rcvright = jm->jm_port;
10096 
10097 	jm->req_port = 0;
10098 	jm->jm_port = 0;
10099 
10100 	workaround_5477111 = j;
10101 
10102 	jobmgr_shutdown(jm);
10103 
10104 	return BOOTSTRAP_SUCCESS;
10105 
10106 out_bad:
10107 	if (outdata_obj_array) {
10108 		launch_data_free(outdata_obj_array);
10109 	}
10110 	if (*outdata) {
10111 		mig_deallocate(*outdata, *outdataCnt);
10112 	}
10113 	if (ports) {
10114 		mig_deallocate((vm_address_t)ports, cnt * sizeof(ports[0]));
10115 	}
10116 
10117 	return BOOTSTRAP_NO_MEMORY;
10118 }
10119 
10120 kern_return_t
10121 job_mig_subset(job_t j, mach_port_t requestorport, mach_port_t *subsetportp)
10122 {
10123 	int bsdepth = 0;
10124 	jobmgr_t jmr;
10125 
10126 	if (!j) {
10127 		return BOOTSTRAP_NO_MEMORY;
10128 	}
10129 	if (j->mgr->shutting_down) {
10130 		return BOOTSTRAP_UNKNOWN_SERVICE;
10131 	}
10132 
10133 	jmr = j->mgr;
10134 
10135 	while ((jmr = jobmgr_parent(jmr)) != NULL) {
10136 		bsdepth++;
10137 	}
10138 
10139 	// Since we use recursion, we need an artificial depth for subsets
10140 	if (unlikely(bsdepth > 100)) {
10141 		job_log(j, LOG_ERR, "Mach sub-bootstrap create request failed. Depth greater than: %d", bsdepth);
10142 		return BOOTSTRAP_NO_MEMORY;
10143 	}
10144 
10145 	char name[NAME_MAX];
10146 	snprintf(name, sizeof(name), "%s[%i].subset.%i", j->anonymous ? j->prog : j->label, j->p, MACH_PORT_INDEX(requestorport));
10147 
10148 	if (!job_assumes(j, (jmr = jobmgr_new(j->mgr, requestorport, MACH_PORT_NULL, false, name, true, j->asport)) != NULL)) {
10149 		if (unlikely(requestorport == MACH_PORT_NULL)) {
10150 			return BOOTSTRAP_NOT_PRIVILEGED;
10151 		}
10152 		return BOOTSTRAP_NO_MEMORY;
10153 	}
10154 
10155 	*subsetportp = jmr->jm_port;
10156 	jmr->properties |= BOOTSTRAP_PROPERTY_EXPLICITSUBSET;
10157 
10158 	/* A job could create multiple subsets, so only add a reference the first time
10159 	 * it does so we don't have to keep a count.
10160 	 */
10161 	if (j->anonymous && !j->holds_ref) {
10162 		job_log(j, LOG_PERF, "Job created subset: %s", jmr->name);
10163 		j->holds_ref = true;
10164 		runtime_add_ref();
10165 	}
10166 
10167 	job_log(j, LOG_DEBUG, "Job created a subset named \"%s\"", jmr->name);
10168 	return BOOTSTRAP_SUCCESS;
10169 }
10170 
10171 job_t
10172 _xpc_domain_import_service(jobmgr_t jm, launch_data_t pload)
10173 {
10174 	jobmgr_t where2put = NULL;
10175 
10176 	if (launch_data_get_type(pload) != LAUNCH_DATA_DICTIONARY) {
10177 		errno = EINVAL;
10178 		return NULL;
10179 	}
10180 
10181 	launch_data_t ldlabel = launch_data_dict_lookup(pload, LAUNCH_JOBKEY_LABEL);
10182 	if (!ldlabel || launch_data_get_type(ldlabel) != LAUNCH_DATA_STRING) {
10183 		errno = EINVAL;
10184 		return NULL;
10185 	}
10186 
10187 	const char *label = launch_data_get_string(ldlabel);
10188 	jobmgr_log(jm, LOG_DEBUG, "Importing service: %s", label);
10189 
10190 	launch_data_t destname = launch_data_dict_lookup(pload, LAUNCH_JOBKEY_XPCDOMAIN);
10191 	if (destname) {
10192 		bool supported_domain = false;
10193 
10194 		if (launch_data_get_type(destname) == LAUNCH_DATA_STRING) {
10195 			const char *str = launch_data_get_string(destname);
10196 			if (strcmp(str, XPC_DOMAIN_TYPE_SYSTEM) == 0) {
10197 				where2put = _s_xpc_system_domain;
10198 			} else if (strcmp(str, XPC_DOMAIN_TYPE_PERUSER) == 0) {
10199 				where2put = jobmgr_find_xpc_per_user_domain(jm, jm->req_euid);
10200 				supported_domain = true;
10201 			} else if (strcmp(str, XPC_DOMAIN_TYPE_PERSESSION) == 0) {
10202 				where2put = jobmgr_find_xpc_per_session_domain(jm, jm->req_asid);
10203 			} else {
10204 				jobmgr_log(jm, LOG_ERR, "Invalid XPC domain type: %s", str);
10205 				errno = EINVAL;
10206 			}
10207 		} else {
10208 			jobmgr_log(jm, LOG_ERR, "XPC domain type is not a string.");
10209 			errno = EINVAL;
10210 		}
10211 
10212 		if (where2put && !supported_domain) {
10213 			launch_data_t mi = NULL;
10214 			if ((mi = launch_data_dict_lookup(pload, LAUNCH_JOBKEY_MULTIPLEINSTANCES))) {
10215 				if (launch_data_get_type(mi) == LAUNCH_DATA_BOOL && launch_data_get_bool(mi)) {
10216 					jobmgr_log(where2put, LOG_ERR, "Multiple-instance services are not supported in this domain.");
10217 					where2put = NULL;
10218 					errno = EINVAL;
10219 				}
10220 			}
10221 		}
10222 	} else {
10223 		where2put = jm;
10224 	}
10225 
10226 	job_t j = NULL;
10227 	if (where2put) {
10228 		/* Gross. If the service already exists in a singleton domain, then
10229 		 * jobmgr_import2() will return the existing job. But if we fail to alias
10230 		 * this job, we will normally want to remove it. But if we did not create
10231 		 * it in the first place, then we need to avoid removing it. So check
10232 		 * errno against EEXIST in the success case and if it's EEXIST, then do
10233 		 * not remove the original job in the event of a failed alias.
10234 		 *
10235 		 * This really needs to be re-thought, but I think it'll require a larger
10236 		 * evaluation of launchd's data structures. Right now, once a job is
10237 		 * imported into a singleton domain, it won't be removed until the system
10238 		 * shuts down, but that may not always be true. If it ever changes, we'll
10239 		 * have a problem because we'll have to account for all existing aliases
10240 		 * and clean them up somehow. Or just start ref-counting. I knew this
10241 		 * aliasing stuff would be trouble...
10242 		 *
10243 		 * <rdar://problem/10646503>
10244 		 */
10245 		jobmgr_log(where2put, LOG_DEBUG, "Importing service...");
10246 
10247 		errno = 0;
10248 		if ((j = jobmgr_import2(where2put, pload))) {
10249 			bool created = (errno != EEXIST);
10250 			j->xpc_service = true;
10251 
10252 			if (where2put->xpc_singleton) {
10253 				/* If the service was destined for one of the global domains,
10254 				 * then we have to alias it into our local domain to reserve the
10255 				 * name.
10256 				 */
10257 				job_t ja = NULL;
10258 				if (!(ja = job_new_alias(jm, j))) {
10259 					/* If we failed to alias the job because of a conflict over
10260 					 * the label, then we remove it from the global domain. We
10261 					 * don't want to risk having imported a malicious job into
10262 					 * one of the global domains.
10263 					 */
10264 					if (errno != EEXIST) {
10265 						job_log(j, LOG_ERR, "Failed to alias job into: %s: %d: %s", where2put->name, errno, strerror(errno));
10266 					} else {
10267 						errno = 0;
10268 					}
10269 
10270 					if (created) {
10271 						jobmgr_log(jm, LOG_WARNING, "Singleton service already existed in job-local namespace. Removing: %s", j->label);
10272 						job_remove(j);
10273 					}
10274 
10275 					j = NULL;
10276 				} else {
10277 					jobmgr_log(jm, LOG_DEBUG, "Aliased service into local domain: %s", j->label);
10278 					(void)job_dispatch(j, false);
10279 					ja->xpc_service = true;
10280 					j = ja;
10281 				}
10282 			} else {
10283 				(void)job_dispatch(j, false);
10284 			}
10285 		}
10286 	} else {
10287 		jobmgr_log(jm, LOG_DEBUG, "Could not find destination for service: %s", label);
10288 	}
10289 
10290 	return j;
10291 }
10292 
10293 int
10294 _xpc_domain_import_services(job_t j, launch_data_t services)
10295 {
10296 	int error = EINVAL;
10297 	if (launch_data_get_type(services) != LAUNCH_DATA_ARRAY) {
10298 		return error;
10299 	}
10300 
10301 	size_t i = 0;
10302 	size_t c = launch_data_array_get_count(services);
10303 	jobmgr_log(j->mgr, LOG_DEBUG, "Importing new services: %lu", c);
10304 
10305 	for (i = 0; i < c; i++) {
10306 		jobmgr_log(j->mgr, LOG_DEBUG, "Importing service at index: %lu", i);
10307 
10308 		job_t nj = NULL;
10309 		launch_data_t ploadi = launch_data_array_get_index(services, i);
10310 		if (!(nj = _xpc_domain_import_service(j->mgr, ploadi))) {
10311 			if (!j->mgr->session_initialized && errno) {
10312 				/* Service import failures are only fatal if the domain is being
10313 				 * initialized. If we're extending the domain, we can run into
10314 				 * errors with services already existing, so we just ignore them.
10315 				 * In the case of a domain extension, we don't want to halt the
10316 				 * operation if we run into an error with one service.
10317 				 *
10318 				 * <rdar://problem/10842779>
10319 				 */
10320 				jobmgr_log(j->mgr, LOG_ERR, "Failed to import service at index: %lu: %d: %s", i, errno, strerror(errno));
10321 				error = errno;
10322 				break;
10323 			}
10324 		} else {
10325 			jobmgr_log(j->mgr, LOG_DEBUG, "Imported service: %s", nj->label);
10326 		}
10327 	}
10328 
10329 	if (i == c) {
10330 		error = 0;
10331 	}
10332 
10333 	return error;
10334 }
10335 
10336 kern_return_t
10337 xpc_domain_import2(job_t j, mach_port_t reqport, mach_port_t dport)
10338 {
10339 	if (unlikely(!pid1_magic)) {
10340 		job_log(j, LOG_ERR, "XPC domains may only reside in PID 1.");
10341 		return BOOTSTRAP_NOT_PRIVILEGED;
10342 	}
10343 	if (!j || !MACH_PORT_VALID(reqport)) {
10344 		return BOOTSTRAP_UNKNOWN_SERVICE;
10345 	}
10346 	if (root_jobmgr->shutting_down) {
10347 		jobmgr_log(root_jobmgr, LOG_ERR, "Attempt to create new domain while shutting down.");
10348 		return BOOTSTRAP_NOT_PRIVILEGED;
10349 	}
10350 	if (!j->xpc_bootstrapper) {
10351 		job_log(j, LOG_ERR, "Attempt to create new XPC domain by unprivileged job.");
10352 		return BOOTSTRAP_NOT_PRIVILEGED;
10353 	}
10354 
10355 	kern_return_t kr = BOOTSTRAP_NO_MEMORY;
10356 	/* All XPC domains are children of the root job manager. What we're creating
10357 	 * here is really just a skeleton. By creating it, we're adding reqp to our
10358 	 * port set. It will have two messages on it. The first specifies the
10359 	 * environment of the originator. This is so we can cache it and hand it to
10360 	 * xpcproxy to bootstrap our services. The second is the set of jobs that is
10361 	 * to be bootstrapped in.
10362 	 */
10363 	jobmgr_t jm = jobmgr_new(root_jobmgr, reqport, dport, false, NULL, true, MACH_PORT_NULL);
10364 	if (job_assumes(j, jm != NULL)) {
10365 		jm->properties |= BOOTSTRAP_PROPERTY_XPC_DOMAIN;
10366 		jm->shortdesc = "private";
10367 		kr = BOOTSTRAP_SUCCESS;
10368 	}
10369 
10370 	return kr;
10371 }
10372 
10373 kern_return_t
10374 xpc_domain_set_environment(job_t j, mach_port_t rp, mach_port_t bsport, mach_port_t excport, vm_offset_t ctx, mach_msg_type_number_t ctx_sz)
10375 {
10376 	if (!j) {
10377 		/* Due to the whacky nature of XPC service bootstrapping, we can end up
10378 		 * getting this message long after the requesting process has gone away.
10379 		 * See <rdar://problem/8593143>.
10380 		 */
10381 		return BOOTSTRAP_UNKNOWN_SERVICE;
10382 	}
10383 
10384 	jobmgr_t jm = j->mgr;
10385 	if (!(jm->properties & BOOTSTRAP_PROPERTY_XPC_DOMAIN)) {
10386 		return BOOTSTRAP_NOT_PRIVILEGED;
10387 	}
10388 
10389 	if (jm->req_asport != MACH_PORT_NULL) {
10390 		return BOOTSTRAP_NOT_PRIVILEGED;
10391 	}
10392 
10393 	struct ldcred *ldc = runtime_get_caller_creds();
10394 	struct proc_bsdinfowithuniqid proc;
10395 	if (proc_pidinfo(ldc->pid, PROC_PIDT_BSDINFOWITHUNIQID, 1, &proc, PROC_PIDT_BSDINFOWITHUNIQID_SIZE) == 0) {
10396 		if (errno != ESRCH) {
10397 			(void)jobmgr_assumes_zero(jm, errno);
10398 		}
10399 
10400 		jm->error = errno;
10401 		jobmgr_remove(jm);
10402 		return BOOTSTRAP_NO_MEMORY;
10403 	}
10404 #ifdef notyet
10405 #if !TARGET_OS_EMBEDDED
10406 	if (jobmgr_assumes_zero(jm, audit_session_port(ldc->asid, &jm->req_asport)) != 0) {
10407 		jm->error = EPERM;
10408 		jobmgr_remove(jm);
10409 		job_log(j, LOG_ERR, "Failed to get port for ASID: %u", ldc->asid);
10410 		return BOOTSTRAP_NOT_PRIVILEGED;
10411 	}
10412 #else
10413 	jm->req_asport = MACH_PORT_DEAD;
10414 #endif
10415 #endif
10416 	struct waiting4attach *w4ai = NULL;
10417 	struct waiting4attach *w4ait = NULL;
10418 	LIST_FOREACH_SAFE(w4ai, &_launchd_domain_waiters, le, w4ait) {
10419 		if (w4ai->dest == ldc->pid) {
10420 			jobmgr_log(jm, LOG_DEBUG, "Migrating attach for: %s", w4ai->name);
10421 			LIST_REMOVE(w4ai, le);
10422 			LIST_INSERT_HEAD(&jm->attaches, w4ai, le);
10423 			w4ai->dest = 0;
10424 		}
10425 	}
10426 
10427 	(void)snprintf(jm->name_init, NAME_MAX, "com.apple.xpc.domain.%s.%d", proc.pbsd.pbi_comm, ldc->pid);
10428 	strlcpy(jm->owner, proc.pbsd.pbi_comm, sizeof(jm->owner));
10429 	jm->req_bsport = bsport;
10430 	jm->req_excport = excport;
10431 	jm->req_rport = rp;
10432 	jm->req_ctx = ctx;
10433 	jm->req_ctx_sz = ctx_sz;
10434 	jm->req_pid = ldc->pid;
10435 	jm->req_euid = ldc->euid;
10436 	jm->req_egid = ldc->egid;
10437 	jm->req_asid = ldc->asid;
10438 	jm->req_uniqueid = proc.p_uniqidentifier.p_uniqueid;
10439 
10440 	return KERN_SUCCESS;
10441 }
10442 
10443 kern_return_t
10444 xpc_domain_load_services(job_t j, vm_offset_t services_buff, mach_msg_type_number_t services_sz)
10445 {
10446 	if (!j) {
10447 		return BOOTSTRAP_UNKNOWN_SERVICE;
10448 	}
10449 
10450  	job_t rootj = jobmgr_find_by_pid(root_jobmgr, j->p, false);
10451  	if (!(rootj && rootj->xpc_bootstrapper)) {
10452 		job_log(j, LOG_ERR, "Attempt to load services into XPC domain by unprivileged job.");
10453 		return BOOTSTRAP_NOT_PRIVILEGED;
10454 	}
10455 
10456 	// This is just for XPC domains (for now).
10457 	if (!(j->mgr->properties & BOOTSTRAP_PROPERTY_XPC_DOMAIN)) {
10458 		return BOOTSTRAP_NOT_PRIVILEGED;
10459 	}
10460 	if (j->mgr->session_initialized) {
10461 		jobmgr_log(j->mgr, LOG_ERR, "Attempt to initialize an already-initialized XPC domain.");
10462 		return BOOTSTRAP_NOT_PRIVILEGED;
10463 	}
10464 
10465 	size_t offset = 0;
10466 	launch_data_t services = launch_data_unpack((void *)services_buff, services_sz, NULL, 0, &offset, NULL);
10467 	if (!services) {
10468 		return BOOTSTRAP_NO_MEMORY;
10469 	}
10470 
10471 	int error = _xpc_domain_import_services(j, services);
10472 	if (error) {
10473 		j->mgr->error = error;
10474 		jobmgr_log(j->mgr, LOG_ERR, "Obliterating domain.");
10475 		jobmgr_remove(j->mgr);
10476 	} else {
10477 		j->mgr->session_initialized = true;
10478 		(void)jobmgr_assumes_zero(j->mgr, xpc_call_wakeup(j->mgr->req_rport, BOOTSTRAP_SUCCESS));
10479 		j->mgr->req_rport = MACH_PORT_NULL;
10480 
10481 		/* Returning a failure code will destroy the message, whereas returning
10482 		 * success will not, so we need to clean up here.
10483 		 */
10484 		mig_deallocate(services_buff, services_sz);
10485 		error = BOOTSTRAP_SUCCESS;
10486 	}
10487 
10488 	return error;
10489 }
10490 
10491 kern_return_t
10492 xpc_domain_check_in(job_t j, mach_port_t *bsport, mach_port_t *sbsport,
10493 	mach_port_t *excport, mach_port_t *asport, uint32_t *uid, uint32_t *gid,
10494 	int32_t *asid, vm_offset_t *ctx, mach_msg_type_number_t *ctx_sz)
10495 {
10496 	if (!jobmgr_assumes(root_jobmgr, j != NULL)) {
10497 		return BOOTSTRAP_UNKNOWN_SERVICE;
10498 	}
10499 	jobmgr_t jm = j->mgr;
10500 	if (!(jm->properties & BOOTSTRAP_PROPERTY_XPC_DOMAIN)) {
10501 		return BOOTSTRAP_NOT_PRIVILEGED;
10502 	}
10503 
10504 	if (jm->req_asport == MACH_PORT_NULL) {
10505 		return BOOTSTRAP_NOT_PRIVILEGED;
10506 	}
10507 
10508 	*bsport = jm->req_bsport;
10509 	*sbsport = root_jobmgr->jm_port;
10510 	*excport = jm->req_excport;
10511 	if (j->joins_gui_session) {
10512 		if (jm->req_gui_asport) {
10513 			*asport = jm->req_gui_asport;
10514 		} else {
10515 			job_log(j, LOG_NOTICE, "No GUI session set for UID of user service. This service may not act properly.");
10516 			*asport = jm->req_asport;
10517 		}
10518 	} else {
10519 		*asport = jm->req_asport;
10520 	}
10521 
10522 	*uid = jm->req_euid;
10523 	*gid = jm->req_egid;
10524 	*asid = jm->req_asid;
10525 
10526 	*ctx = jm->req_ctx;
10527 	*ctx_sz = jm->req_ctx_sz;
10528 
10529 	return KERN_SUCCESS;
10530 }
10531 
10532 kern_return_t
10533 xpc_domain_get_service_name(job_t j, event_name_t name)
10534 {
10535 	if (!j) {
10536 		return BOOTSTRAP_NO_MEMORY;
10537 	}
10538 
10539 	if (!j->xpc_service) {
10540 		jobmgr_log(j->mgr, LOG_ERR, "Attempt to get service name by non-XPC service: %s", j->label);
10541 		return BOOTSTRAP_NOT_PRIVILEGED;
10542 	}
10543 
10544 	const char *what2find = j->label;
10545 	if (j->dedicated_instance) {
10546 		what2find = j->original->label;
10547 	}
10548 
10549 	struct machservice *msi = NULL;
10550 	SLIST_FOREACH(msi, &j->machservices, sle) {
10551 		if (strcmp(msi->name, what2find) == 0) {
10552 			break;
10553 		}
10554 	}
10555 
10556 	if (!msi) {
10557 		jobmgr_log(j->mgr, LOG_ERR, "Attempt to get service name that does not exist: %s", j->label);
10558 		return BOOTSTRAP_UNKNOWN_SERVICE;
10559 	}
10560 
10561 	(void)strlcpy(name, msi->name, sizeof(event_name_t));
10562 	return BOOTSTRAP_SUCCESS;
10563 }
10564 
10565 #if XPC_LPI_VERSION >= 20111216
10566 kern_return_t
10567 xpc_domain_add_services(job_t j, vm_offset_t services_buff, mach_msg_type_number_t services_sz)
10568 {
10569 	if (!j) {
10570 		return BOOTSTRAP_UNKNOWN_SERVICE;
10571 	}
10572 
10573  	job_t rootj = jobmgr_find_by_pid(root_jobmgr, j->p, false);
10574  	if (!(rootj && rootj->xpc_bootstrapper)) {
10575 		job_log(j, LOG_ERR, "Attempt to add service to XPC domain by unprivileged job.");
10576 		return BOOTSTRAP_NOT_PRIVILEGED;
10577 	}
10578 
10579 	if (!(j->mgr->properties & BOOTSTRAP_PROPERTY_XPC_DOMAIN)) {
10580 		return BOOTSTRAP_NOT_PRIVILEGED;
10581 	}
10582 
10583 	size_t offset = 0;
10584 	launch_data_t services = launch_data_unpack((void *)services_buff, services_sz, NULL, 0, &offset, NULL);
10585 	if (!services) {
10586 		return BOOTSTRAP_NO_MEMORY;
10587 	}
10588 
10589 	int error = _xpc_domain_import_services(j, services);
10590 	if (!error) {
10591 		mig_deallocate(services_buff, services_sz);
10592 	}
10593 
10594 	return error;
10595 }
10596 #endif
10597 
10598 #pragma mark XPC Events
10599 int
10600 xpc_event_find_channel(job_t j, const char *stream, struct machservice **ms)
10601 {
10602 	int error = EXNOMEM;
10603 	struct machservice *msi = NULL;
10604 	SLIST_FOREACH(msi, &j->machservices, sle) {
10605 		if (strcmp(stream, msi->name) == 0) {
10606 			break;
10607 		}
10608 	}
10609 
10610 	if (!msi) {
10611 		mach_port_t sp = MACH_PORT_NULL;
10612 		msi = machservice_new(j, stream, &sp, false);
10613 		if (!msi) {
10614 			return EXNOMEM;
10615 		}
10616 
10617 		job_log(j, LOG_DEBUG, "Creating new MachService for stream: %s", stream);
10618 		/* Hack to keep this from being publicly accessible through
10619 		 * bootstrap_look_up().
10620 		 */
10621 		if (!j->dedicated_instance) {
10622 			LIST_REMOVE(msi, name_hash_sle);
10623 		}
10624 		msi->event_channel = true;
10625 
10626 		/* If we call job_dispatch() here before the audit session for the job
10627 		 * has been set, we'll end up not watching this service. But we also have
10628 		 * to take care not to watch the port if the job is active.
10629 		 *
10630 		 * See <rdar://problem/10357855>.
10631 		 */
10632 		if (!j->currently_ignored) {
10633 			machservice_watch(j, msi);
10634 		}
10635 
10636 		error = 0;
10637 		*ms = msi;
10638 	} else if (!msi->event_channel) {
10639 		job_log(j, LOG_ERR, "This job registered a MachService name identical to the requested event channel name: %s", stream);
10640 		error = EEXIST;
10641 	} else {
10642 		error = 0;
10643 		*ms = msi;
10644 	}
10645 
10646 	return error;
10647 }
10648 
10649 int
10650 xpc_event_get_event_name(job_t j, xpc_object_t request, xpc_object_t *reply)
10651 {
10652 	const char *stream = xpc_dictionary_get_string(request, XPC_EVENT_ROUTINE_KEY_STREAM);
10653 	if (!stream) {
10654 		return EXINVAL;
10655 	}
10656 
10657 	uint64_t token = xpc_dictionary_get_uint64(request, XPC_EVENT_ROUTINE_KEY_TOKEN);
10658 	if (!token) {
10659 		return EXINVAL;
10660 	}
10661 
10662 	job_log(j, LOG_DEBUG, "Getting event name for stream/token: %s/0x%zu", stream, token);
10663 
10664 	int result = ESRCH;
10665 	struct externalevent *event = externalevent_find(stream, token);
10666 	if (event && j->event_monitor) {
10667 		xpc_object_t reply2 = xpc_dictionary_create_reply(request);
10668 		xpc_dictionary_set_string(reply2, XPC_EVENT_ROUTINE_KEY_NAME, event->name);
10669 		*reply = reply2;
10670 
10671 		job_log(j, LOG_DEBUG, "Found: %s", event->name);
10672 		result = 0;
10673 	}
10674 
10675 	return result;
10676 }
10677 
10678 static int
10679 xpc_event_copy_entitlements(job_t j, xpc_object_t request, xpc_object_t *reply)
10680 {
10681 	const char *stream = xpc_dictionary_get_string(request, XPC_EVENT_ROUTINE_KEY_STREAM);
10682 	if (!stream) {
10683 		return EXINVAL;
10684 	}
10685 
10686 	uint64_t token = xpc_dictionary_get_uint64(request, XPC_EVENT_ROUTINE_KEY_TOKEN);
10687 	if (!token) {
10688 		return EXINVAL;
10689 	}
10690 
10691 	job_log(j, LOG_DEBUG, "Getting entitlements for stream/token: %s/0x%zu", stream, token);
10692 
10693 	int result = ESRCH;
10694 	struct externalevent *event = externalevent_find(stream, token);
10695 	if (event && j->event_monitor) {
10696 		xpc_object_t reply2 = xpc_dictionary_create_reply(request);
10697 		xpc_dictionary_set_value(reply2, XPC_EVENT_ROUTINE_KEY_ENTITLEMENTS, event->entitlements);
10698 		*reply = reply2;
10699 
10700 		job_log(j, LOG_DEBUG, "Found: %s", event->name);
10701 		result = 0;
10702 	}
10703 
10704 	return result;
10705 }
10706 
10707 // TODO - can be removed with rdar://problem/12666150
10708 #ifndef XPC_EVENT_FLAG_ALLOW_UNMANAGED
10709 #define XPC_EVENT_FLAG_ALLOW_UNMANAGED (1 << 1)
10710 #endif
10711 
10712 int
10713 xpc_event_set_event(job_t j, xpc_object_t request, xpc_object_t *reply)
10714 {
10715 	const char *stream = xpc_dictionary_get_string(request, XPC_EVENT_ROUTINE_KEY_STREAM);
10716 	if (!stream) {
10717 		return EXINVAL;
10718 	}
10719 
10720 	const char *key = xpc_dictionary_get_string(request, XPC_EVENT_ROUTINE_KEY_NAME);
10721 	if (!key) {
10722 		return EXINVAL;
10723 	}
10724 
10725 	xpc_object_t event = xpc_dictionary_get_value(request, XPC_EVENT_ROUTINE_KEY_EVENT);
10726 	if (event && xpc_get_type(event) != XPC_TYPE_DICTIONARY) {
10727 		return EXINVAL;
10728 	}
10729 
10730 	uint64_t flags = xpc_dictionary_get_uint64(request, XPC_EVENT_ROUTINE_KEY_FLAGS);
10731 
10732 	/* Don't allow events to be set for anonymous jobs unless specifically
10733 	 * requested in the flags. Only permit this for internal development.
10734 	 */
10735 	if (j->anonymous && ((flags & XPC_EVENT_FLAG_ALLOW_UNMANAGED) == 0 || !launchd_apple_internal)) {
10736 		job_log(j, LOG_ERR, "Unmanaged jobs may not make XPC Events requests.");
10737 		return EPERM;
10738 	}
10739 
10740 	job_log(j, LOG_DEBUG, "%s event for stream/key: %s/%s", event ? "Setting" : "Removing", stream, key);
10741 
10742 	struct externalevent *eei = NULL;
10743 	LIST_FOREACH(eei, &j->events, job_le) {
10744 		/* If the event for the given key already exists for the job, we need to
10745 		 * remove the old one first.
10746 		 */
10747 		if (strcmp(eei->name, key) == 0 && strcmp(eei->sys->name, stream) == 0) {
10748 			job_log(j, LOG_DEBUG, "Event exists. Removing.");
10749 			externalevent_delete(eei);
10750 			break;
10751 		}
10752 	}
10753 
10754 	int result = EXNOMEM;
10755 	if (event) {
10756 		struct eventsystem *es = eventsystem_find(stream);
10757 		if (!es) {
10758 			job_log(j, LOG_DEBUG, "Creating stream.");
10759 			es = eventsystem_new(stream);
10760 		}
10761 
10762 		if (es) {
10763 			job_log(j, LOG_DEBUG, "Adding event.");
10764 			if (externalevent_new(j, es, key, event, flags)) {
10765 				job_log(j, LOG_DEBUG, "Added new event for key: %s", key);
10766 				result = 0;
10767 			} else {
10768 				job_log(j, LOG_ERR, "Could not create event for key: %s", key);
10769 			}
10770 		} else {
10771 			job_log(j, LOG_ERR, "Event stream could not be created: %s", stream);
10772 		}
10773 	} else {
10774 		/* If the event was NULL, then we just remove it and return. */
10775 		result = 0;
10776 	}
10777 
10778 	if (result == 0) {
10779 		xpc_object_t reply2 = xpc_dictionary_create_reply(request);
10780 		*reply = reply2;
10781 	}
10782 
10783 	return result;
10784 }
10785 
10786 int
10787 xpc_event_copy_event(job_t j, xpc_object_t request, xpc_object_t *reply)
10788 {
10789 	const char *stream = xpc_dictionary_get_string(request, XPC_EVENT_ROUTINE_KEY_STREAM);
10790 	const char *key = xpc_dictionary_get_string(request, XPC_EVENT_ROUTINE_KEY_NAME);
10791 
10792 	bool all_streams = (stream == NULL);
10793 	bool all_events = (key == NULL || strcmp(key, "") == 0); // strcmp for libxpc compatibility
10794 	xpc_object_t events = NULL;
10795 
10796 	if (all_streams && !all_events) {
10797 		return EXINVAL;
10798 	}
10799 
10800 	if (all_streams || all_events) {
10801 		job_log(j, LOG_DEBUG, "Fetching all events%s%s", stream ? " for stream: " : "", stream ? stream : "");
10802 		events = xpc_dictionary_create(NULL, NULL, 0);
10803 	} else {
10804 		job_log(j, LOG_DEBUG, "Fetching stream/key: %s/%s", stream, key);
10805 	}
10806 
10807 	int result = ESRCH;
10808 	struct externalevent *eei = NULL;
10809 	LIST_FOREACH(eei, &j->events, job_le) {
10810 		if (all_streams) {
10811 			xpc_object_t sub = xpc_dictionary_get_value(events, eei->sys->name);
10812 			if (sub == NULL) {
10813 				sub = xpc_dictionary_create(NULL, NULL, 0);
10814 				xpc_dictionary_set_value(events, eei->sys->name, sub);
10815 				xpc_release(sub);
10816 			}
10817 			xpc_dictionary_set_value(sub, eei->name, eei->event);
10818 		} else if (strcmp(eei->sys->name, stream) == 0) {
10819 			if (all_events) {
10820 				xpc_dictionary_set_value(events, eei->name, eei->event);
10821 			} else if (strcmp(eei->name, key) == 0) {
10822 				job_log(j, LOG_DEBUG, "Found event.");
10823 				events = xpc_retain(eei->event);
10824 				break;
10825 			}
10826 		}
10827 	}
10828 
10829 	if (events) {
10830 		xpc_object_t reply2 = xpc_dictionary_create_reply(request);
10831 		xpc_dictionary_set_value(reply2, XPC_EVENT_ROUTINE_KEY_EVENT, events);
10832 		xpc_release(events);
10833 
10834 		*reply = reply2;
10835 		result = 0;
10836 	}
10837 
10838 	return result;
10839 }
10840 
10841 int
10842 xpc_event_channel_check_in(job_t j, xpc_object_t request, xpc_object_t *reply)
10843 {
10844 	const char *stream = xpc_dictionary_get_string(request, XPC_EVENT_ROUTINE_KEY_STREAM);
10845 	if (!stream) {
10846 		return EXINVAL;
10847 	}
10848 
10849 	job_log(j, LOG_DEBUG, "Checking in stream: %s", stream);
10850 
10851 	struct machservice *ms = NULL;
10852 	int error = xpc_event_find_channel(j, stream, &ms);
10853 	if (error) {
10854 		job_log(j, LOG_ERR, "Failed to check in: 0x%x: %s", error, xpc_strerror(error));
10855 	} else if (ms->isActive) {
10856 		job_log(j, LOG_ERR, "Attempt to check in on event channel multiple times: %s", stream);
10857 		error = EBUSY;
10858 	} else {
10859 		machservice_request_notifications(ms);
10860 
10861 		xpc_object_t reply2 = xpc_dictionary_create_reply(request);
10862 		xpc_dictionary_set_mach_recv(reply2, XPC_EVENT_ROUTINE_KEY_PORT, ms->port);
10863 		*reply = reply2;
10864 		error = 0;
10865 	}
10866 
10867 	return error;
10868 }
10869 
10870 int
10871 xpc_event_channel_look_up(job_t j, xpc_object_t request, xpc_object_t *reply)
10872 {
10873 	if (!j->event_monitor) {
10874 		return EPERM;
10875 	}
10876 
10877 	const char *stream = xpc_dictionary_get_string(request, XPC_EVENT_ROUTINE_KEY_STREAM);
10878 	if (!stream) {
10879 		return EXINVAL;
10880 	}
10881 
10882 	uint64_t token = xpc_dictionary_get_uint64(request, XPC_EVENT_ROUTINE_KEY_TOKEN);
10883 	if (!token) {
10884 		return EXINVAL;
10885 	}
10886 
10887 	job_log(j, LOG_DEBUG, "Looking up channel for stream/token: %s/%zu", stream, token);
10888 
10889 	struct externalevent *ee = externalevent_find(stream, token);
10890 	if (!ee) {
10891 		return ESRCH;
10892 	}
10893 
10894 	struct machservice *ms = NULL;
10895 	int error = xpc_event_find_channel(ee->job, stream, &ms);
10896 	if (!error) {
10897 		job_log(j, LOG_DEBUG, "Found event channel port: 0x%x", ms->port);
10898 		xpc_object_t reply2 = xpc_dictionary_create_reply(request);
10899 		xpc_dictionary_set_mach_send(reply2, XPC_EVENT_ROUTINE_KEY_PORT, ms->port);
10900 		*reply = reply2;
10901 		error = 0;
10902 	} else {
10903 		job_log(j, LOG_ERR, "Could not find event channel for stream/token: %s/%zu: 0x%x: %s", stream, token, error, xpc_strerror(error));
10904 	}
10905 
10906 	return error;
10907 }
10908 
10909 int
10910 xpc_event_provider_check_in(job_t j, xpc_object_t request, xpc_object_t *reply)
10911 {
10912 	if (!j->event_monitor) {
10913 		return EPERM;
10914 	}
10915 
10916 	/* This indicates that the event monitor is now safe to signal. This state
10917 	 * is independent of whether this operation actually succeeds; we just need
10918 	 * it to ignore SIGUSR1.
10919 	 */
10920 	j->event_monitor_ready2signal = true;
10921 
10922 	const char *stream = xpc_dictionary_get_string(request, XPC_EVENT_ROUTINE_KEY_STREAM);
10923 	if (!stream) {
10924 		return EXINVAL;
10925 	}
10926 
10927 	job_log(j, LOG_DEBUG, "Provider checking in for stream: %s", stream);
10928 
10929 	xpc_object_t events = xpc_array_create(NULL, 0);
10930 	struct eventsystem *es = eventsystem_find(stream);
10931 	if (!es) {
10932 		/* If we had to create the event stream, there were no events, so just
10933 		 * give back the empty array.
10934 		 */
10935 		job_log(j, LOG_DEBUG, "Creating event stream.");
10936 		es = eventsystem_new(stream);
10937 		if (!job_assumes(j, es)) {
10938 			xpc_release(events);
10939 			return EXNOMEM;
10940 		}
10941 
10942 		if (strcmp(stream, "com.apple.launchd.helper") == 0) {
10943 			_launchd_support_system = es;
10944 		}
10945 	} else {
10946 		job_log(j, LOG_DEBUG, "Filling event array.");
10947 
10948 		struct externalevent *ei = NULL;
10949 		LIST_FOREACH(ei, &es->events, sys_le) {
10950 			xpc_array_set_uint64(events, XPC_ARRAY_APPEND, ei->id);
10951 			xpc_array_append_value(events, ei->event);
10952 		}
10953 	}
10954 
10955 	xpc_object_t reply2 = xpc_dictionary_create_reply(request);
10956 	xpc_dictionary_set_value(reply2, XPC_EVENT_ROUTINE_KEY_EVENTS, events);
10957 	xpc_release(events);
10958 	*reply = reply2;
10959 
10960 	return 0;
10961 }
10962 
10963 int
10964 xpc_event_provider_set_state(job_t j, xpc_object_t request, xpc_object_t *reply)
10965 {
10966 	job_t other_j = NULL;
10967 
10968 	if (!j->event_monitor) {
10969 		return EPERM;
10970 	}
10971 
10972 	const char *stream = xpc_dictionary_get_string(request, XPC_EVENT_ROUTINE_KEY_STREAM);
10973 	if (!stream) {
10974 		return EXINVAL;
10975 	}
10976 
10977 	uint64_t token = xpc_dictionary_get_uint64(request, XPC_EVENT_ROUTINE_KEY_TOKEN);
10978 	if (!token) {
10979 		return EXINVAL;
10980 	}
10981 
10982 	bool state = false;
10983 	xpc_object_t xstate = xpc_dictionary_get_value(request, XPC_EVENT_ROUTINE_KEY_STATE);
10984 	if (!xstate || xpc_get_type(xstate) != XPC_TYPE_BOOL) {
10985 		return EXINVAL;
10986 	} else {
10987 		state = xpc_bool_get_value(xstate);
10988 	}
10989 
10990 	job_log(j, LOG_DEBUG, "Setting event state to %s for stream/token: %s/%zu", state ? "true" : "false", stream, token);
10991 
10992 	struct externalevent *ei = externalevent_find(stream, token);
10993 	if (!ei) {
10994 		job_log(j, LOG_ERR, "Could not find stream/token: %s/%zu", stream, token);
10995 		return ESRCH;
10996 	}
10997 
10998 	other_j = ei->job;
10999 	ei->state = state;
11000 
11001 	if (ei->internal) {
11002 		job_log(ei->job, LOG_NOTICE, "Job should be able to exec(3) now.");
11003 		ei->job->waiting4ok = false;
11004 		externalevent_delete(ei);
11005 	}
11006 
11007 	(void)job_dispatch(other_j, false);
11008 
11009 	xpc_object_t reply2 = xpc_dictionary_create_reply(request);
11010 	*reply = reply2;
11011 
11012 	return 0;
11013 }
11014 
11015 bool
11016 xpc_event_demux(mach_port_t p, xpc_object_t request, xpc_object_t *reply)
11017 {
11018 	uint64_t op = xpc_dictionary_get_uint64(request, XPC_EVENT_ROUTINE_KEY_OP);
11019 	if (!op) {
11020 		return false;
11021 	}
11022 
11023 	audit_token_t token;
11024 	xpc_dictionary_get_audit_token(request, &token);
11025 	runtime_record_caller_creds(&token);
11026 
11027 	struct ldcred *ldc = runtime_get_caller_creds();
11028 	job_t j = managed_job(ldc->pid);
11029 	if (!j) {
11030 		j = job_mig_intran(p);
11031 		if (!j) {
11032 			op = -1;
11033 		}
11034 	}
11035 
11036 	job_log(j, LOG_DEBUG, "Incoming XPC event request: %zu", op);
11037 
11038 	int error = -1;
11039 	switch (op) {
11040 	case XPC_EVENT_GET_NAME:
11041 		error = xpc_event_get_event_name(j, request, reply);
11042 		break;
11043 	case XPC_EVENT_SET:
11044 		error = xpc_event_set_event(j, request, reply);
11045 		break;
11046 	case XPC_EVENT_COPY:
11047 		error = xpc_event_copy_event(j, request, reply);
11048 		break;
11049 	case XPC_EVENT_CHECK_IN:
11050 		error = xpc_event_channel_check_in(j, request, reply);
11051 		break;
11052 	case XPC_EVENT_LOOK_UP:
11053 		error = xpc_event_channel_look_up(j, request, reply);
11054 		break;
11055 	case XPC_EVENT_PROVIDER_CHECK_IN:
11056 		error = xpc_event_provider_check_in(j, request, reply);
11057 		break;
11058 	case XPC_EVENT_PROVIDER_SET_STATE:
11059 		error = xpc_event_provider_set_state(j, request, reply);
11060 		break;
11061 	case XPC_EVENT_COPY_ENTITLEMENTS:
11062 		error = xpc_event_copy_entitlements(j, request, reply);
11063 		break;
11064 	case -1:
11065 		error = EINVAL;
11066 		break;
11067 	default:
11068 		job_log(j, LOG_ERR, "Bogus opcode.");
11069 		error = EDOM;
11070 	}
11071 
11072 	if (error) {
11073 		xpc_object_t reply2 = xpc_dictionary_create_reply(request);
11074 		xpc_dictionary_set_uint64(reply2, XPC_EVENT_ROUTINE_KEY_ERROR, error);
11075 		*reply = reply2;
11076 	}
11077 
11078 	return true;
11079 }
11080 
11081 static uint64_t
11082 xpc_get_jetsam_entitlement(const char *key)
11083 {
11084 	uint64_t entitlement = 0;
11085 
11086 	audit_token_t *token = runtime_get_caller_token();
11087 	xpc_object_t value = xpc_copy_entitlement_for_token(key, token);
11088 	if (value) {
11089 		if (xpc_get_type(value) == XPC_TYPE_UINT64) {
11090 			entitlement = xpc_uint64_get_value(value);
11091 		}
11092 
11093 		xpc_release(value);
11094 	}
11095 
11096 	return entitlement;
11097 }
11098 
11099 int
11100 xpc_process_set_jetsam_band(job_t j, xpc_object_t request, xpc_object_t *reply)
11101 {
11102 	if (!j) {
11103 		return EINVAL;
11104 	}
11105 
11106 	const char *label = xpc_dictionary_get_string(request, XPC_PROCESS_ROUTINE_KEY_LABEL);
11107 	if (!label) {
11108 		return EXINVAL;
11109 	}
11110 
11111 	xpc_jetsam_band_t entitled_band = -1;
11112 	xpc_jetsam_band_t requested_band = (xpc_jetsam_band_t)xpc_dictionary_get_uint64(request, XPC_PROCESS_ROUTINE_KEY_PRIORITY_BAND);
11113 	if (!requested_band) {
11114 		return EXINVAL;
11115 	}
11116 
11117 	if (!(requested_band >= XPC_JETSAM_BAND_SUSPENDED && requested_band < XPC_JETSAM_BAND_LAST)) {
11118 		return EXINVAL;
11119 	}
11120 
11121 	uint64_t rcdata = xpc_dictionary_get_uint64(request, XPC_PROCESS_ROUTINE_KEY_RCDATA);
11122 
11123 	job_t tj = job_find(root_jobmgr, label);
11124 	if (!tj) {
11125 		return EXSRCH;
11126 	}
11127 
11128 	boolean_t allow = false;
11129 	if (j->embedded_god) {
11130 		allow = true;
11131 	} else {
11132 		entitled_band = xpc_get_jetsam_entitlement("com.apple.private.jetsam.modify-priority");
11133 		if (entitled_band >= requested_band) {
11134 			allow = true;
11135 		}
11136 	}
11137 
11138 	if (!allow) {
11139 		if (launchd_no_jetsam_perm_check) {
11140 			job_log(j, LOG_NOTICE, "Jetsam priority checks disabled; allowing job to set priority: %d", requested_band);
11141 		} else {
11142 			job_log(j, LOG_ERR, "Job cannot decrease Jetsam priority band (requested/maximum): %d/%d", requested_band, entitled_band);
11143 			return EPERM;
11144 		}
11145 	}
11146 
11147 	job_log(j, LOG_INFO, "Setting Jetsam band: %d.", requested_band);
11148 	job_update_jetsam_properties(tj, requested_band, rcdata);
11149 
11150 	xpc_object_t reply2 = xpc_dictionary_create_reply(request);
11151 	*reply = reply2;
11152 
11153 	return 0;
11154 }
11155 
11156 int
11157 xpc_process_set_jetsam_memory_limit(job_t j, xpc_object_t request, xpc_object_t *reply)
11158 {
11159 	if (!j) {
11160 		return EINVAL;
11161 	}
11162 
11163 	const char *label = xpc_dictionary_get_string(request, XPC_PROCESS_ROUTINE_KEY_LABEL);
11164 	if (!label) {
11165 		return EXINVAL;
11166 	}
11167 
11168 	int32_t entitlement_limit = 0;
11169 	int32_t requested_limit = (int32_t)xpc_dictionary_get_uint64(request, XPC_PROCESS_ROUTINE_KEY_MEMORY_LIMIT);
11170 
11171 	job_t tj = job_find(root_jobmgr, label);
11172 	if (!tj) {
11173 		return EXSRCH;
11174 	}
11175 
11176 	boolean_t allow = false;
11177 	if (j->embedded_god) {
11178 		allow = true;
11179 	} else {
11180 		entitlement_limit = (int32_t)xpc_get_jetsam_entitlement("com.apple.private.jetsam.memory_limit");
11181 		if (entitlement_limit >= requested_limit) {
11182 			allow = true;
11183 		}
11184 	}
11185 
11186 	if (!allow) {
11187 		if (launchd_no_jetsam_perm_check) {
11188 			job_log(j, LOG_NOTICE, "Jetsam priority checks disabled; allowing job to set memory limit: %d", requested_limit);
11189 		} else {
11190 			job_log(j, LOG_ERR, "Job cannot set Jetsam memory limit (requested/maximum): %d/%d", requested_limit, entitlement_limit);
11191 			return EPERM;
11192 		}
11193 	}
11194 
11195 	job_log(j, LOG_INFO, "Setting Jetsam memory limit: %d.", requested_limit);
11196 	job_update_jetsam_memory_limit(tj, requested_limit);
11197 
11198 	xpc_object_t reply2 = xpc_dictionary_create_reply(request);
11199 	*reply = reply2;
11200 
11201 	return 0;
11202 }
11203 
11204 static jobmgr_t
11205 _xpc_process_find_target_manager(job_t j, xpc_service_type_t type, pid_t pid)
11206 {
11207 	jobmgr_t target = NULL;
11208 	if (type == XPC_SERVICE_TYPE_BUNDLED) {
11209 		job_log(j, LOG_DEBUG, "Bundled service. Searching for XPC domains for PID: %d", pid);
11210 
11211 		jobmgr_t jmi = NULL;
11212 		SLIST_FOREACH(jmi, &root_jobmgr->submgrs, sle) {
11213 			if (jmi->req_pid && jmi->req_pid == pid) {
11214 				jobmgr_log(jmi, LOG_DEBUG, "Found job manager for PID.");
11215 				target = jmi;
11216 				break;
11217 			}
11218 		}
11219 	} else if (type == XPC_SERVICE_TYPE_LAUNCHD || type == XPC_SERVICE_TYPE_APP) {
11220 		target = j->mgr;
11221 	}
11222 
11223 	return target;
11224 }
11225 
11226 static int
11227 xpc_process_attach(job_t j, xpc_object_t request, xpc_object_t *reply)
11228 {
11229 	if (!j) {
11230 		return EINVAL;
11231 	}
11232 
11233 	audit_token_t *token = runtime_get_caller_token();
11234 	xpc_object_t entitlement = xpc_copy_entitlement_for_token(XPC_SERVICE_ENTITLEMENT_ATTACH, token);
11235 	if (!entitlement) {
11236 		job_log(j, LOG_ERR, "Job does not have entitlement: %s", XPC_SERVICE_ENTITLEMENT_ATTACH);
11237 		return EPERM;
11238 	}
11239 
11240 	if (entitlement != XPC_BOOL_TRUE) {
11241 		char *desc = xpc_copy_description(entitlement);
11242 		job_log(j, LOG_ERR, "Job has bad value for entitlement: %s:\n%s", XPC_SERVICE_ENTITLEMENT_ATTACH, desc);
11243 		free(desc);
11244 
11245 		xpc_release(entitlement);
11246 		return EPERM;
11247 	}
11248 
11249 	const char *name = xpc_dictionary_get_string(request, XPC_PROCESS_ROUTINE_KEY_NAME);
11250 	if (!name) {
11251 		return EXINVAL;
11252 	}
11253 
11254 	xpc_service_type_t type = xpc_dictionary_get_int64(request, XPC_PROCESS_ROUTINE_KEY_TYPE);
11255 	if (!type) {
11256 		return EXINVAL;
11257 	}
11258 
11259 	mach_port_t port = xpc_dictionary_copy_mach_send(request, XPC_PROCESS_ROUTINE_KEY_NEW_INSTANCE_PORT);
11260 	if (!MACH_PORT_VALID(port)) {
11261 		return EXINVAL;
11262 	}
11263 
11264 	pid_t pid = xpc_dictionary_get_int64(request, XPC_PROCESS_ROUTINE_KEY_HANDLE);
11265 
11266 	job_log(j, LOG_DEBUG, "Attaching to service: %s", name);
11267 
11268 	xpc_object_t reply2 = xpc_dictionary_create_reply(request);
11269 	jobmgr_t target = _xpc_process_find_target_manager(j, type, pid);
11270 	if (target) {
11271 		jobmgr_log(target, LOG_DEBUG, "Found target job manager for service: %s", name);
11272 		(void)jobmgr_assumes(target, waiting4attach_new(target, name, port, 0, type));
11273 
11274 		/* HACK: This is awful. For legacy reasons, launchd job labels are all
11275 		 * stored in a global namespace, which is stored in the root job
11276 		 * manager. But XPC domains have a per-domain namespace. So if we're
11277 		 * looking for a legacy launchd job, we have to redirect any attachment
11278 		 * attempts to the root job manager to find existing instances.
11279 		 *
11280 		 * But because we store attachments on a per-job manager basis, we have
11281 		 * to create the new attachment in the actual target job manager, hence
11282 		 * why we change the target only after we've created the attachment.
11283 		 */
11284 		if (strcmp(target->name, VPROCMGR_SESSION_AQUA) == 0) {
11285 			target = root_jobmgr;
11286 		}
11287 
11288 		job_t existing = job_find(target, name);
11289 		if (existing && existing->p) {
11290 			job_log(existing, LOG_DEBUG, "Found existing instance of service.");
11291 			xpc_dictionary_set_int64(reply2, XPC_PROCESS_ROUTINE_KEY_PID, existing->p);
11292 		} else {
11293 			xpc_dictionary_set_uint64(reply2, XPC_PROCESS_ROUTINE_KEY_ERROR, ESRCH);
11294 		}
11295 	} else if (type == XPC_SERVICE_TYPE_BUNDLED) {
11296 		(void)job_assumes(j, waiting4attach_new(target, name, port, pid, type));
11297 		xpc_dictionary_set_uint64(reply2, XPC_PROCESS_ROUTINE_KEY_ERROR, ESRCH);
11298 	} else {
11299 		xpc_dictionary_set_uint64(reply2, XPC_PROCESS_ROUTINE_KEY_ERROR, EXSRCH);
11300 	}
11301 
11302 	*reply = reply2;
11303 	return 0;
11304 }
11305 
11306 static int
11307 xpc_process_detach(job_t j, xpc_object_t request, xpc_object_t *reply __unused)
11308 {
11309 	if (!j) {
11310 		return EINVAL;
11311 	}
11312 
11313 	const char *name = xpc_dictionary_get_string(request, XPC_PROCESS_ROUTINE_KEY_NAME);
11314 	if (!name) {
11315 		return EXINVAL;
11316 	}
11317 
11318 	xpc_service_type_t type = xpc_dictionary_get_int64(request, XPC_PROCESS_ROUTINE_KEY_TYPE);
11319 	if (!type) {
11320 		return EXINVAL;
11321 	}
11322 
11323 	job_log(j, LOG_DEBUG, "Deatching from service: %s", name);
11324 
11325 	pid_t pid = xpc_dictionary_get_int64(request, XPC_PROCESS_ROUTINE_KEY_PID);
11326 	jobmgr_t target = _xpc_process_find_target_manager(j, type, pid);
11327 	if (target) {
11328 		jobmgr_log(target, LOG_DEBUG, "Found target job manager for service: %s", name);
11329 
11330 		struct waiting4attach *w4ai = NULL;
11331 		struct waiting4attach *w4ait = NULL;
11332 		LIST_FOREACH_SAFE(w4ai, &target->attaches, le, w4ait) {
11333 			if (strcmp(name, w4ai->name) == 0) {
11334 				jobmgr_log(target, LOG_DEBUG, "Found attachment. Deleting.");
11335 				waiting4attach_delete(target, w4ai);
11336 				break;
11337 			}
11338 		}
11339 	}
11340 
11341 	return 0;
11342 }
11343 
11344 static int
11345 xpc_process_get_properties(job_t j, xpc_object_t request, xpc_object_t *reply)
11346 {
11347 	if (j->anonymous) {
11348 		/* Total hack. libxpc will send requests to the pipe created out of the
11349 		 * process' bootstrap port, so when job_mig_intran() tries to resolve
11350 		 * the process into a job, it'll wind up creating an anonymous job if
11351 		 * the requestor was an XPC service, whose job manager is an XPC domain.
11352 		 */
11353 		pid_t pid = j->p;
11354 		jobmgr_t jmi = NULL;
11355 		SLIST_FOREACH(jmi, &root_jobmgr->submgrs, sle) {
11356 			if ((j = jobmgr_find_by_pid(jmi, pid, false))) {
11357 				break;
11358 			}
11359 		}
11360 	}
11361 
11362 	if (!j || j->anonymous) {
11363 		return EXINVAL;
11364 	}
11365 
11366 	struct waiting4attach *w4a = waiting4attach_find(j->mgr, j);
11367 	if (!w4a) {
11368 		return EXINVAL;
11369 	}
11370 
11371 	xpc_object_t reply2 = xpc_dictionary_create_reply(request);
11372 	xpc_dictionary_set_uint64(reply2, XPC_PROCESS_ROUTINE_KEY_TYPE, w4a->type);
11373 	xpc_dictionary_set_mach_send(reply2, XPC_PROCESS_ROUTINE_KEY_NEW_INSTANCE_PORT, w4a->port);
11374 	if (j->prog) {
11375 		xpc_dictionary_set_string(reply2, XPC_PROCESS_ROUTINE_KEY_PATH, j->prog);
11376 	} else {
11377 		xpc_dictionary_set_string(reply2, XPC_PROCESS_ROUTINE_KEY_PATH, j->argv[0]);
11378 	}
11379 
11380 	if (j->argv) {
11381 		xpc_object_t xargv = xpc_array_create(NULL, 0);
11382 
11383 		size_t i = 0;
11384 		for (i = 0; i < j->argc; i++) {
11385 			if (j->argv[i]) {
11386 				xpc_array_set_string(xargv, XPC_ARRAY_APPEND, j->argv[i]);
11387 			}
11388 		}
11389 
11390 		xpc_dictionary_set_value(reply2, XPC_PROCESS_ROUTINE_KEY_ARGV, xargv);
11391 		xpc_release(xargv);
11392 	}
11393 
11394 	*reply = reply2;
11395 	return 0;
11396 }
11397 
11398 static int
11399 xpc_process_service_kill(job_t j, xpc_object_t request, xpc_object_t *reply)
11400 {
11401 #if XPC_LPI_VERSION >= 20130426
11402 	if (!j) {
11403 		return ESRCH;
11404 	}
11405 
11406 	jobmgr_t jm = _xpc_process_find_target_manager(j, XPC_SERVICE_TYPE_BUNDLED, j->p);
11407 	if (!jm) {
11408 		return ENOENT;
11409 	}
11410 
11411 	const char *name = xpc_dictionary_get_string(request, XPC_PROCESS_ROUTINE_KEY_NAME);
11412 	if (!name) {
11413 		return EINVAL;
11414 	}
11415 
11416 	int64_t whichsig = xpc_dictionary_get_int64(request, XPC_PROCESS_ROUTINE_KEY_SIGNAL);
11417 	if (!whichsig) {
11418 		return EINVAL;
11419 	}
11420 
11421 	job_t j2kill = job_find(jm, name);
11422 	if (!j2kill) {
11423 		return ESRCH;
11424 	}
11425 
11426 	if (j2kill->alias) {
11427 		// Only allow for private instances to be killed.
11428 		return EPERM;
11429 	}
11430 
11431 	struct proc_bsdshortinfo proc;
11432 	if (proc_pidinfo(j2kill->p, PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0) {
11433 		if (errno != ESRCH) {
11434 			(void)jobmgr_assumes_zero(root_jobmgr, errno);
11435 		}
11436 
11437 		return errno;
11438 	}
11439 
11440 	struct ldcred *ldc = runtime_get_caller_creds();
11441 	if (proc.pbsi_uid != ldc->euid) {
11442 		// Do not allow non-root to kill RoleAccount services running as a
11443 		// different user.
11444 		return EPERM;
11445 	}
11446 
11447 	if (!j2kill->p) {
11448 		return EALREADY;
11449 	}
11450 
11451 	xpc_object_t reply2 = xpc_dictionary_create_reply(request);
11452 	if (!reply2) {
11453 		return EINVAL;
11454 	}
11455 
11456 	int error = 0;
11457 	int ret = kill(j2kill->p, whichsig);
11458 	if (ret) {
11459 		error = errno;
11460 	}
11461 
11462 	xpc_dictionary_set_int64(reply2, XPC_PROCESS_ROUTINE_KEY_ERROR, error);
11463 	*reply = reply2;
11464 	return 0;
11465 #else
11466 	return ENOTSUP;
11467 #endif
11468 }
11469 
11470 bool
11471 xpc_process_demux(mach_port_t p, xpc_object_t request, xpc_object_t *reply)
11472 {
11473 	uint64_t op = xpc_dictionary_get_uint64(request, XPC_PROCESS_ROUTINE_KEY_OP);
11474 	if (!op) {
11475 		return false;
11476 	}
11477 
11478 	audit_token_t token;
11479 	xpc_dictionary_get_audit_token(request, &token);
11480 	runtime_record_caller_creds(&token);
11481 
11482 	job_t j = job_mig_intran(p);
11483 	job_log(j, LOG_DEBUG, "Incoming XPC process request: %zu", op);
11484 
11485 	int error = -1;
11486 	switch (op) {
11487 	case XPC_PROCESS_JETSAM_SET_BAND:
11488 		error = xpc_process_set_jetsam_band(j, request, reply);
11489 		break;
11490 	case XPC_PROCESS_JETSAM_SET_MEMORY_LIMIT:
11491 		error = xpc_process_set_jetsam_memory_limit(j, request, reply);
11492 		break;
11493 	case XPC_PROCESS_SERVICE_ATTACH:
11494 		error = xpc_process_attach(j, request, reply);
11495 		break;
11496 	case XPC_PROCESS_SERVICE_DETACH:
11497 		error = xpc_process_detach(j, request, reply);
11498 		break;
11499 	case XPC_PROCESS_SERVICE_GET_PROPERTIES:
11500 		error = xpc_process_get_properties(j, request, reply);
11501 		break;
11502 	case XPC_PROCESS_SERVICE_KILL:
11503 		error = xpc_process_service_kill(j, request, reply);
11504 		break;
11505 	default:
11506 		job_log(j, LOG_ERR, "Bogus process opcode.");
11507 		error = EDOM;
11508 	}
11509 
11510 	if (error) {
11511 		xpc_object_t reply2 = xpc_dictionary_create_reply(request);
11512 		if (reply2) {
11513 			xpc_dictionary_set_uint64(reply2, XPC_PROCESS_ROUTINE_KEY_ERROR, error);
11514 		}
11515 
11516 		*reply = reply2;
11517 	}
11518 
11519 	return true;
11520 }
11521 
11522 kern_return_t
11523 job_mig_kickstart(job_t j, name_t targetlabel, pid_t *out_pid, unsigned int flags)
11524 {
11525 	struct ldcred *ldc = runtime_get_caller_creds();
11526 	job_t otherj;
11527 
11528 	if (!j) {
11529 		return BOOTSTRAP_NO_MEMORY;
11530 	}
11531 
11532 	if (unlikely(!(otherj = job_find(NULL, targetlabel)))) {
11533 		return BOOTSTRAP_UNKNOWN_SERVICE;
11534 	}
11535 
11536 #if TARGET_OS_EMBEDDED
11537 	bool allow_non_root_kickstart = j->username && otherj->username && (strcmp(j->username, otherj->username) == 0);
11538 #else
11539 	bool allow_non_root_kickstart = false;
11540 #endif
11541 
11542 	if (ldc->euid != 0 && ldc->euid != geteuid() && !allow_non_root_kickstart) {
11543 		return BOOTSTRAP_NOT_PRIVILEGED;
11544 	}
11545 
11546 #if HAVE_SANDBOX
11547 	if (unlikely(sandbox_check(ldc->pid, "job-creation", SANDBOX_FILTER_NONE) > 0)) {
11548 		return BOOTSTRAP_NOT_PRIVILEGED;
11549 	}
11550 #endif
11551 
11552 	if (otherj->p && (flags & VPROCFLAG_STALL_JOB_EXEC)) {
11553 		return BOOTSTRAP_SERVICE_ACTIVE;
11554 	}
11555 
11556 	otherj->stall_before_exec = (flags & VPROCFLAG_STALL_JOB_EXEC);
11557 	otherj = job_dispatch(otherj, true);
11558 
11559 	if (!job_assumes(j, otherj && otherj->p)) {
11560 		// <rdar://problem/6787083> Clear this flag if we failed to start the job.
11561 		otherj->stall_before_exec = false;
11562 		return BOOTSTRAP_NO_MEMORY;
11563 	}
11564 
11565 	*out_pid = otherj->p;
11566 
11567 	return 0;
11568 }
11569 
11570 kern_return_t
11571 job_mig_spawn_internal(job_t j, vm_offset_t indata, mach_msg_type_number_t indataCnt, mach_port_t asport, job_t *outj)
11572 {
11573 	launch_data_t jobdata = NULL;
11574 	size_t data_offset = 0;
11575 	struct ldcred *ldc = runtime_get_caller_creds();
11576 	job_t jr;
11577 
11578 	if (!j) {
11579 		return BOOTSTRAP_NO_MEMORY;
11580 	}
11581 
11582 	if (unlikely(j->deny_job_creation)) {
11583 		return BOOTSTRAP_NOT_PRIVILEGED;
11584 	}
11585 
11586 #if HAVE_SANDBOX
11587 	if (unlikely(sandbox_check(ldc->pid, "job-creation", SANDBOX_FILTER_NONE) > 0)) {
11588 		return BOOTSTRAP_NOT_PRIVILEGED;
11589 	}
11590 #endif
11591 
11592 	if (unlikely(pid1_magic && ldc->euid && ldc->uid)) {
11593 		job_log(j, LOG_DEBUG, "Punting spawn to per-user-context");
11594 		return VPROC_ERR_TRY_PER_USER;
11595 	}
11596 
11597 	if (!job_assumes(j, indataCnt != 0)) {
11598 		return 1;
11599 	}
11600 
11601 	runtime_ktrace0(RTKT_LAUNCHD_DATA_UNPACK);
11602 	if (!job_assumes(j, (jobdata = launch_data_unpack((void *)indata, indataCnt, NULL, 0, &data_offset, NULL)) != NULL)) {
11603 		return 1;
11604 	}
11605 
11606 	jobmgr_t target_jm = jobmgr_find_by_name(j->mgr, NULL);
11607 	if (!jobmgr_assumes(j->mgr, target_jm != NULL)) {
11608 		jobmgr_log(j->mgr, LOG_ERR, "This API can only be used by a process running within an Aqua session.");
11609 		return 1;
11610 	}
11611 
11612 	jr = jobmgr_import2(target_jm ?: j->mgr, jobdata);
11613 
11614 	launch_data_t label = NULL;
11615 	launch_data_t wait4debugger = NULL;
11616 	if (!jr) {
11617 		switch (errno) {
11618 		case EEXIST:
11619 			/* If EEXIST was returned, we know that there is a label string in
11620 			 * the dictionary. So we don't need to check the types here; that
11621 			 * has already been done.
11622 			 */
11623 			label = launch_data_dict_lookup(jobdata, LAUNCH_JOBKEY_LABEL);
11624 			jr = job_find(NULL, launch_data_get_string(label));
11625 			if (job_assumes(j, jr != NULL) && !jr->p) {
11626 				wait4debugger = launch_data_dict_lookup(jobdata, LAUNCH_JOBKEY_WAITFORDEBUGGER);
11627 				if (wait4debugger && launch_data_get_type(wait4debugger) == LAUNCH_DATA_BOOL) {
11628 					if (launch_data_get_bool(wait4debugger)) {
11629 						/* If the job exists, we're going to kick-start it, but
11630 						 * we need to give the caller the opportunity to start
11631 						 * it suspended if it so desires. But this will only
11632 						 * take effect if the job isn't running.
11633 						 */
11634 						jr->wait4debugger_oneshot = true;
11635 					}
11636 				}
11637 			}
11638 
11639 			*outj = jr;
11640 			return BOOTSTRAP_NAME_IN_USE;
11641 		default:
11642 			return BOOTSTRAP_NO_MEMORY;
11643 		}
11644 	}
11645 
11646 	if (pid1_magic) {
11647 		jr->mach_uid = ldc->uid;
11648 	}
11649 
11650 	// TODO: Consolidate the app and legacy_LS_job bits.
11651 	jr->legacy_LS_job = true;
11652 	jr->abandon_pg = true;
11653 	jr->asport = asport;
11654 	jr->app = true;
11655 	uuid_clear(jr->expected_audit_uuid);
11656 	jr = job_dispatch(jr, true);
11657 
11658 	if (!job_assumes(j, jr != NULL)) {
11659 		job_remove(jr);
11660 		return BOOTSTRAP_NO_MEMORY;
11661 	}
11662 
11663 	if (!job_assumes(jr, jr->p)) {
11664 		job_remove(jr);
11665 		return BOOTSTRAP_NO_MEMORY;
11666 	}
11667 
11668 	job_log(jr, LOG_DEBUG, "Spawned by PID %u: %s", j->p, j->label);
11669 	*outj = jr;
11670 
11671 	return BOOTSTRAP_SUCCESS;
11672 }
11673 
11674 kern_return_t
11675 job_mig_spawn2(job_t j, mach_port_t rp, vm_offset_t indata, mach_msg_type_number_t indataCnt, mach_port_t asport, pid_t *child_pid, mach_port_t *obsvr_port)
11676 {
11677 	job_t nj = NULL;
11678 	kern_return_t kr = job_mig_spawn_internal(j, indata, indataCnt, asport, &nj);
11679 	if (likely(kr == KERN_SUCCESS)) {
11680 		if (job_setup_exit_port(nj) != KERN_SUCCESS) {
11681 			job_remove(nj);
11682 			kr = BOOTSTRAP_NO_MEMORY;
11683 		} else {
11684 			/* Do not return until the job has called exec(3), thereby making it
11685 			 * safe for the caller to send it SIGCONT.
11686 			 *
11687 			 * <rdar://problem/9042798>
11688 			 */
11689 			nj->spawn_reply_port = rp;
11690 			kr = MIG_NO_REPLY;
11691 		}
11692 	} else if (kr == BOOTSTRAP_NAME_IN_USE) {
11693 		bool was_running = nj->p;
11694 		if (job_dispatch(nj, true)) {
11695 			if (!was_running) {
11696 				job_log(nj, LOG_DEBUG, "Job exists but is not running. Kick-starting.");
11697 
11698 				if (job_setup_exit_port(nj) == KERN_SUCCESS) {
11699 					nj->spawn_reply_port = rp;
11700 					kr = MIG_NO_REPLY;
11701 				} else {
11702 					kr = BOOTSTRAP_NO_MEMORY;
11703 				}
11704 			} else {
11705 				*obsvr_port = MACH_PORT_NULL;
11706 				*child_pid = nj->p;
11707 				kr = KERN_SUCCESS;
11708 			}
11709 		} else {
11710 			job_log(nj, LOG_ERR, "Failed to dispatch job, requestor: %s", j->label);
11711 			kr = BOOTSTRAP_UNKNOWN_SERVICE;
11712 		}
11713 	}
11714 
11715 	mig_deallocate(indata, indataCnt);
11716 	return kr;
11717 }
11718 
11719 #ifndef __FreeBSD__
11720 launch_data_t
11721 job_do_legacy_ipc_request(job_t j, launch_data_t request, mach_port_t asport __attribute__((unused)))
11722 {
11723 	launch_data_t reply = NULL;
11724 
11725 	errno = ENOTSUP;
11726 	if (launch_data_get_type(request) == LAUNCH_DATA_STRING) {
11727 		if (strcmp(launch_data_get_string(request), LAUNCH_KEY_CHECKIN) == 0) {
11728 			reply = job_export(j);
11729 			job_checkin(j);
11730 		}
11731 	}
11732 
11733 	return reply;
11734 }
11735 
11736 #define LAUNCHD_MAX_LEGACY_FDS 128
11737 #define countof(x) (sizeof((x)) / sizeof((x[0])))
11738 
11739 kern_return_t
11740 job_mig_legacy_ipc_request(job_t j, vm_offset_t request,
11741 	mach_msg_type_number_t requestCnt, mach_port_array_t request_fds,
11742 	mach_msg_type_number_t request_fdsCnt, vm_offset_t *reply,
11743 	mach_msg_type_number_t *replyCnt, mach_port_array_t *reply_fdps,
11744 	mach_msg_type_number_t *reply_fdsCnt, mach_port_t asport)
11745 {
11746 	if (!j) {
11747 		return BOOTSTRAP_NO_MEMORY;
11748 	}
11749 
11750 	/* TODO: Once we support actions other than checking in, we must check the
11751 	 * sandbox capabilities and EUID of the requestort.
11752 	 */
11753 	size_t nout_fdps = 0;
11754 	size_t nfds = request_fdsCnt / sizeof(request_fds[0]);
11755 	if (nfds > LAUNCHD_MAX_LEGACY_FDS) {
11756 		job_log(j, LOG_ERR, "Too many incoming descriptors: %lu", nfds);
11757 		return BOOTSTRAP_NO_MEMORY;
11758 	}
11759 
11760 	int in_fds[LAUNCHD_MAX_LEGACY_FDS];
11761 	size_t i = 0;
11762 	for (i = 0; i < nfds; i++) {
11763 		in_fds[i] = fileport_makefd(request_fds[i]);
11764 		if (in_fds[i] == -1) {
11765 			job_log(j, LOG_ERR, "Bad descriptor passed in legacy IPC request at index: %lu", i);
11766 		}
11767 	}
11768 
11769 	// DON'T goto outbad before this point.
11770 	*reply = 0;
11771 	*reply_fdps = NULL;
11772 	launch_data_t ldreply = NULL;
11773 
11774 	size_t dataoff = 0;
11775 	size_t fdoff = 0;
11776 	launch_data_t ldrequest = launch_data_unpack((void *)request, requestCnt, in_fds, nfds, &dataoff, &fdoff);
11777 	if (!ldrequest) {
11778 		job_log(j, LOG_ERR, "Invalid legacy IPC request passed.");
11779 		goto out_bad;
11780 	}
11781 
11782 	ldreply = job_do_legacy_ipc_request(j, ldrequest, asport);
11783 	if (!ldreply) {
11784 		ldreply = launch_data_new_errno(errno);
11785 		if (!ldreply) {
11786 			goto out_bad;
11787 		}
11788 	}
11789 
11790 	*replyCnt = 10 * 1024 * 1024;
11791 	mig_allocate(reply, *replyCnt);
11792 	if (!*reply) {
11793 		goto out_bad;
11794 	}
11795 
11796 	int out_fds[LAUNCHD_MAX_LEGACY_FDS];
11797 	size_t nout_fds = 0;
11798 	size_t sz = launch_data_pack(ldreply, (void *)*reply, *replyCnt, out_fds, &nout_fds);
11799 	if (!sz) {
11800 		job_log(j, LOG_ERR, "Could not pack legacy IPC reply.");
11801 		goto out_bad;
11802 	}
11803 
11804 	if (nout_fds) {
11805 		if (nout_fds > 128) {
11806 			job_log(j, LOG_ERR, "Too many outgoing descriptors: %lu", nout_fds);
11807 			goto out_bad;
11808 		}
11809 
11810 		*reply_fdsCnt = nout_fds * sizeof((*reply_fdps)[0]);
11811 		mig_allocate((vm_address_t *)reply_fdps, *reply_fdsCnt);
11812 		if (!*reply_fdps) {
11813 			goto out_bad;
11814 		}
11815 
11816 		for (i = 0; i < nout_fds; i++) {
11817 			mach_port_t fp = MACH_PORT_NULL;
11818 			/* Whatever. Worst case is that we insert MACH_PORT_NULL. Not a big
11819 			 * deal. Note, these get stuffed into an array whose disposition is
11820 			 * mach_port_move_send_t, so we don't have to worry about them after
11821 			 * returning.
11822 			 */
11823 			if (fileport_makeport(out_fds[i], &fp) != 0) {
11824 				job_log(j, LOG_ERR, "Could not pack response descriptor at index: %lu: %d: %s", i, errno, strerror(errno));
11825 			}
11826 			(*reply_fdps)[i] = fp;
11827 		}
11828 
11829 		nout_fdps = nout_fds;
11830 	} else {
11831 		*reply_fdsCnt = 0;
11832 	}
11833 
11834 	mig_deallocate(request, requestCnt);
11835 	launch_data_free(ldreply);
11836 	ldreply = NULL;
11837 
11838 	// Unused for now.
11839 	(void)launchd_mport_deallocate(asport);
11840 
11841 	return BOOTSTRAP_SUCCESS;
11842 
11843 out_bad:
11844 	for (i = 0; i < nfds; i++) {
11845 		(void)close(in_fds[i]);
11846 	}
11847 
11848 	for (i = 0; i < nout_fds; i++) {
11849 		(void)launchd_mport_deallocate((*reply_fdps)[i]);
11850 	}
11851 
11852 	if (*reply) {
11853 		mig_deallocate(*reply, *replyCnt);
11854 	}
11855 
11856 	/* We should never hit this since the last goto out is in the case that
11857 	 * allocating this fails.
11858 	 */
11859 	if (*reply_fdps) {
11860 		mig_deallocate((vm_address_t)*reply_fdps, *reply_fdsCnt);
11861 	}
11862 
11863 	if (ldreply) {
11864 		launch_data_free(ldreply);
11865 	}
11866 
11867 	return BOOTSTRAP_NO_MEMORY;
11868 }
11869 #endif
11870 
11871 void
11872 jobmgr_init(bool sflag)
11873 {
11874 	const char *root_session_type = pid1_magic ? VPROCMGR_SESSION_SYSTEM : VPROCMGR_SESSION_BACKGROUND;
11875 	SLIST_INIT(&s_curious_jobs);
11876 	LIST_INIT(&s_needing_sessions);
11877 	syslog(LOG_ERR, "starting root_jobmgr");
11878 	os_assert((root_jobmgr = jobmgr_new(NULL, MACH_PORT_NULL, MACH_PORT_NULL, sflag, root_session_type, false, MACH_PORT_NULL)) != NULL);
11879 #if 0
11880 	os_assert((_s_xpc_system_domain = jobmgr_new_xpc_singleton_domain(root_jobmgr, strdup("com.apple.xpc.system"))) != NULL);
11881 	_s_xpc_system_domain->req_asid = launchd_audit_session;
11882 	_s_xpc_system_domain->req_asport = launchd_audit_port;
11883 	_s_xpc_system_domain->shortdesc = "system";
11884 #endif
11885 	if (pid1_magic) {
11886 		root_jobmgr->monitor_shutdown = true;
11887 	}
11888 
11889 	uint32_t fflags = NOTE_ATTRIB | NOTE_LINK | NOTE_REVOKE | NOTE_EXTEND | NOTE_WRITE;
11890 	s_no_hang_fd = open("/dev/autofs_nowait", O_EVTONLY | O_NONBLOCK);
11891 	if (likely(s_no_hang_fd == -1)) {
11892 		if (jobmgr_assumes_zero_p(root_jobmgr, (s_no_hang_fd = open("/dev", O_EVTONLY | O_NONBLOCK))) != -1) {
11893 			(void)jobmgr_assumes_zero_p(root_jobmgr, kevent_mod((uintptr_t)s_no_hang_fd, EVFILT_VNODE, EV_ADD, fflags, 0, root_jobmgr));
11894 		}
11895 	}
11896 	s_no_hang_fd = _fd(s_no_hang_fd);
11897 }
11898 
11899 size_t
11900 our_strhash(const char *s)
11901 {
11902 	size_t c, r = 5381;
11903 
11904 	/* djb2
11905 	 * This algorithm was first reported by Dan Bernstein many years ago in comp.lang.c
11906 	 */
11907 
11908 	while ((c = *s++)) {
11909 		r = ((r << 5) + r) + c; // hash*33 + c
11910 	}
11911 
11912 	return r;
11913 }
11914 
11915 size_t
11916 hash_label(const char *label)
11917 {
11918 	return our_strhash(label) % LABEL_HASH_SIZE;
11919 }
11920 
11921 size_t
11922 hash_ms(const char *msstr)
11923 {
11924 	return our_strhash(msstr) % MACHSERVICE_HASH_SIZE;
11925 }
11926 
11927 bool
11928 waiting4removal_new(job_t j, mach_port_t rp)
11929 {
11930 	struct waiting_for_removal *w4r;
11931 
11932 	if (!job_assumes(j, (w4r = malloc(sizeof(struct waiting_for_removal))) != NULL)) {
11933 		return false;
11934 	}
11935 
11936 	w4r->reply_port = rp;
11937 
11938 	SLIST_INSERT_HEAD(&j->removal_watchers, w4r, sle);
11939 
11940 	return true;
11941 }
11942 
11943 void
11944 waiting4removal_delete(job_t j, struct waiting_for_removal *w4r)
11945 {
11946 	(void)job_assumes_zero(j, job_mig_send_signal_reply(w4r->reply_port, 0));
11947 
11948 	SLIST_REMOVE(&j->removal_watchers, w4r, waiting_for_removal, sle);
11949 
11950 	free(w4r);
11951 }
11952 
11953 size_t
11954 get_kern_max_proc(void)
11955 {
11956 	int mib[] = { CTL_KERN, KERN_MAXPROC };
11957 	int max = 100;
11958 	size_t max_sz = sizeof(max);
11959 
11960 	(void)posix_assumes_zero(sysctl(mib, 2, &max, &max_sz, NULL, 0));
11961 
11962 	return max;
11963 }
11964 
11965 // See rdar://problem/6271234
11966 void
11967 eliminate_double_reboot(void)
11968 {
11969 	if (unlikely(!pid1_magic)) {
11970 		return;
11971 	}
11972 
11973 	struct stat sb;
11974 	const char *argv[] = { _PATH_BSHELL, "/etc/rc.deferred_install", NULL };
11975 	int result = -1;
11976 
11977 	if (unlikely(stat(argv[1], &sb) != -1)) {
11978 		jobmgr_log(root_jobmgr, LOG_DEBUG | LOG_CONSOLE, "Going to run deferred install script.");
11979 
11980 		pid_t p = 0;
11981 		result = posix_spawnp(&p, argv[0], NULL, NULL, (char **)argv, environ);
11982 		if (result == -1) {
11983 			jobmgr_log(root_jobmgr, LOG_WARNING | LOG_CONSOLE, "Couldn't run deferred install script: %d: %s", result, strerror(result));
11984 			goto out;
11985 		}
11986 
11987 		int wstatus = 0;
11988 		result = waitpid(p, &wstatus, 0);
11989 		if (result == -1) {
11990 			jobmgr_log(root_jobmgr, LOG_WARNING | LOG_CONSOLE, "Failed to reap deferred install script: %d: %s", errno, strerror(errno));
11991 			goto out;
11992 		}
11993 
11994 		if (WIFEXITED(wstatus)) {
11995 			if ((result = WEXITSTATUS(wstatus)) == 0) {
11996 				jobmgr_log(root_jobmgr, LOG_DEBUG | LOG_CONSOLE, "Deferred install script completed successfully.");
11997 			} else {
11998 				jobmgr_log(root_jobmgr, LOG_WARNING | LOG_CONSOLE, "Deferred install script failed with status: %d", WEXITSTATUS(wstatus));
11999 			}
12000 		} else {
12001 			jobmgr_log(root_jobmgr, LOG_WARNING | LOG_CONSOLE, "Weirdness with install script: %d", wstatus);
12002 		}
12003 	}
12004 out:
12005 	if (result == 0) {
12006 		/* If the unlink(2) was to fail, it would be most likely fail with
12007 		 * EBUSY. All the other failure cases for unlink(2) don't apply when
12008 		 * we're running under PID 1 and have verified that the file exists.
12009 		 * Outside of someone deliberately messing with us (like if
12010 		 * /etc/rc.deferredinstall is actually a looping sym-link or a mount
12011 		 * point for a filesystem) and I/O errors, we should be good.
12012 		 */
12013 		if (unlink(argv[1]) == -1) {
12014 			jobmgr_log(root_jobmgr, LOG_WARNING | LOG_CONSOLE, "Failed to remove deferred install script: %d: %s", errno, strerror(errno));
12015 		}
12016 	}
12017 }
12018 
12019 void
12020 jetsam_property_setup(launch_data_t obj, const char *key, job_t j)
12021 {
12022 	job_log(j, LOG_DEBUG, "Setting Jetsam properties for job...");
12023 	if (strcasecmp(key, LAUNCH_JOBKEY_JETSAMPRIORITY) == 0 && launch_data_get_type(obj) == LAUNCH_DATA_INTEGER) {
12024 		j->jetsam_priority = (typeof(j->jetsam_priority))launch_data_get_integer(obj);
12025 
12026 #if XPC_LPI_VERSION >= 20120810
12027 		if (j->jetsam_priority > XPC_JETSAM_PRIORITY_RESERVED && j->jetsam_priority < XPC_JETSAM_PRIORITY_RESERVED + XPC_JETSAM_BAND_LAST) {
12028 			size_t band = j->jetsam_priority - XPC_JETSAM_PRIORITY_RESERVED;
12029 			j->jetsam_priority = _launchd_priority_map[band - 1].priority;
12030 		}
12031 #endif
12032 		job_log(j, LOG_DEBUG, "Priority: %d", j->jetsam_priority);
12033 	} else if (strcasecmp(key, LAUNCH_JOBKEY_JETSAMMEMORYLIMIT) == 0 && launch_data_get_type(obj) == LAUNCH_DATA_INTEGER) {
12034 		j->jetsam_memlimit = (typeof(j->jetsam_memlimit))launch_data_get_integer(obj);
12035 		job_log(j, LOG_DEBUG, "Memory limit: %d", j->jetsam_memlimit);
12036 	} else if (strcasecmp(key, LAUNCH_JOBKEY_JETSAMMEMORYLIMITBACKGROUND) == 0) {
12037 		j->jetsam_memory_limit_background = true;
12038 		job_log(j, LOG_DEBUG, "Memory limit is for background state only");
12039 	} else if (strcasecmp(key, LAUNCH_KEY_JETSAMFRONTMOST) == 0) {
12040 		/* Ignore. We only recognize this key so we don't complain when we get SpringBoard's request.
12041 		 * You can't set this in a plist.
12042 		 */
12043 	} else if (strcasecmp(key, LAUNCH_KEY_JETSAMACTIVE) == 0) {
12044 		// Ignore.
12045 	} else if (strcasecmp(key, LAUNCH_KEY_JETSAMLABEL) == 0) {
12046 		/* Ignore. This key is present in SpringBoard's request dictionary, so we don't want to
12047 		 * complain about it.
12048 		 */
12049 	} else {
12050 		job_log(j, LOG_ERR, "Unknown Jetsam key: %s", key);
12051 	}
12052 
12053 	if (unlikely(!j->jetsam_properties)) {
12054 		j->jetsam_properties = true;
12055 	}
12056 }
12057 
12058 void
12059 job_update_jetsam_properties(job_t j, xpc_jetsam_band_t band, uint64_t user_data)
12060 {
12061 #if TARGET_OS_EMBEDDED
12062 	j->jetsam_priority = _launchd_priority_map[band - 1].priority;
12063 	j->jetsam_properties = true;
12064 
12065 	memorystatus_priority_properties_t mjp;
12066 	mjp.priority = j->jetsam_priority;
12067 	mjp.user_data = user_data;
12068 
12069 	size_t size = sizeof(mjp);
12070 	int r = memorystatus_control(MEMORYSTATUS_CMD_SET_PRIORITY_PROPERTIES, j->p, 0, &mjp, size);
12071 	if (r == -1 && errno != ESRCH) {
12072 		(void)job_assumes_zero(j, errno);
12073 	}
12074 #else
12075 #pragma unused(j, band, user_data)
12076 #endif
12077 }
12078 
12079 void
12080 job_update_jetsam_memory_limit(job_t j, int32_t limit)
12081 {
12082 #if TARGET_OS_EMBEDDED
12083 	j->jetsam_memlimit = limit;
12084 	j->jetsam_properties = true;
12085 
12086 	int r = memorystatus_control(MEMORYSTATUS_CMD_SET_JETSAM_HIGH_WATER_MARK, j->p, limit, NULL, 0);
12087 	if (r == -1 && errno != ESRCH) {
12088 		(void)job_assumes_zero(j, errno);
12089 	}
12090 #else
12091 #pragma unused(j, limit)
12092 #endif
12093 }
12094 
12095 void
12096 _log_launchd_bug(const char *rcs_rev, const char *path, unsigned int line, const char *test)
12097 {
12098         int saved_errno = errno;
12099         char buf[100];
12100         const char *file = strrchr(path, '/');
12101         char *rcs_rev_tmp = strchr(rcs_rev, ' ');
12102 
12103         if (!file) {
12104                 file = path;
12105         } else {
12106                 file += 1;
12107         }
12108 
12109         if (!rcs_rev_tmp) {
12110                 strlcpy(buf, rcs_rev, sizeof(buf));
12111         } else {
12112                 strlcpy(buf, rcs_rev_tmp + 1, sizeof(buf));
12113                 rcs_rev_tmp = strchr(buf, ' ');
12114                 if (rcs_rev_tmp)
12115                         *rcs_rev_tmp = '\0';
12116         }
12117 
12118         syslog(LOG_NOTICE, "Bug: %s:%u (%s):%u: %s", file, line, buf, saved_errno, test);
12119 }
12120 
12121 pid_t
12122 launchd_fork(void)
12123 {
12124 
12125 	return (runtime_fork(root_jobmgr->jm_port));
12126 }
12127