xref: /freebsd/sys/kern/sys_procdesc.c (revision 325151a3)
1 /*-
2  * Copyright (c) 2009 Robert N. M. Watson
3  * All rights reserved.
4  *
5  * This software was developed at the University of Cambridge Computer
6  * Laboratory with support from a grant from Google, Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 /*-
31  * FreeBSD process descriptor facility.
32  *
33  * Some processes are represented by a file descriptor, which will be used in
34  * preference to signaling and pids for the purposes of process management,
35  * and is, in effect, a form of capability.  When a process descriptor is
36  * used with a process, it ceases to be visible to certain traditional UNIX
37  * process facilities, such as waitpid(2).
38  *
39  * Some semantics:
40  *
41  * - At most one process descriptor will exist for any process, although
42  *   references to that descriptor may be held from many processes (or even
43  *   be in flight between processes over a local domain socket).
44  * - Last close on the process descriptor will terminate the process using
45  *   SIGKILL and reparent it to init so that there's a process to reap it
46  *   when it's done exiting.
47  * - If the process exits before the descriptor is closed, it will not
48  *   generate SIGCHLD on termination, or be picked up by waitpid().
49  * - The pdkill(2) system call may be used to deliver a signal to the process
50  *   using its process descriptor.
51  * - The pdwait4(2) system call may be used to block (or not) on a process
52  *   descriptor to collect termination information.
53  *
54  * Open questions:
55  *
56  * - How to handle ptrace(2)?
57  * - Will we want to add a pidtoprocdesc(2) system call to allow process
58  *   descriptors to be created for processes without pdfork(2)?
59  */
60 
61 #include <sys/cdefs.h>
62 __FBSDID("$FreeBSD$");
63 
64 #include <sys/param.h>
65 #include <sys/capsicum.h>
66 #include <sys/fcntl.h>
67 #include <sys/file.h>
68 #include <sys/filedesc.h>
69 #include <sys/kernel.h>
70 #include <sys/lock.h>
71 #include <sys/mutex.h>
72 #include <sys/poll.h>
73 #include <sys/proc.h>
74 #include <sys/procdesc.h>
75 #include <sys/resourcevar.h>
76 #include <sys/stat.h>
77 #include <sys/sysproto.h>
78 #include <sys/sysctl.h>
79 #include <sys/systm.h>
80 #include <sys/ucred.h>
81 #include <sys/user.h>
82 
83 #include <security/audit/audit.h>
84 
85 #include <vm/uma.h>
86 
87 FEATURE(process_descriptors, "Process Descriptors");
88 
89 static uma_zone_t procdesc_zone;
90 
91 static fo_poll_t	procdesc_poll;
92 static fo_kqfilter_t	procdesc_kqfilter;
93 static fo_stat_t	procdesc_stat;
94 static fo_close_t	procdesc_close;
95 static fo_fill_kinfo_t	procdesc_fill_kinfo;
96 
97 static struct fileops procdesc_ops = {
98 	.fo_read = invfo_rdwr,
99 	.fo_write = invfo_rdwr,
100 	.fo_truncate = invfo_truncate,
101 	.fo_ioctl = invfo_ioctl,
102 	.fo_poll = procdesc_poll,
103 	.fo_kqfilter = procdesc_kqfilter,
104 	.fo_stat = procdesc_stat,
105 	.fo_close = procdesc_close,
106 	.fo_chmod = invfo_chmod,
107 	.fo_chown = invfo_chown,
108 	.fo_sendfile = invfo_sendfile,
109 	.fo_fill_kinfo = procdesc_fill_kinfo,
110 	.fo_flags = DFLAG_PASSABLE,
111 };
112 
113 /*
114  * Initialize with VFS so that process descriptors are available along with
115  * other file descriptor types.  As long as it runs before init(8) starts,
116  * there shouldn't be a problem.
117  */
118 static void
119 procdesc_init(void *dummy __unused)
120 {
121 
122 	procdesc_zone = uma_zcreate("procdesc", sizeof(struct procdesc),
123 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
124 	if (procdesc_zone == NULL)
125 		panic("procdesc_init: procdesc_zone not initialized");
126 }
127 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_ANY, procdesc_init, NULL);
128 
129 /*
130  * Return a locked process given a process descriptor, or ESRCH if it has
131  * died.
132  */
133 int
134 procdesc_find(struct thread *td, int fd, cap_rights_t *rightsp,
135     struct proc **p)
136 {
137 	struct procdesc *pd;
138 	struct file *fp;
139 	int error;
140 
141 	error = fget(td, fd, rightsp, &fp);
142 	if (error)
143 		return (error);
144 	if (fp->f_type != DTYPE_PROCDESC) {
145 		error = EBADF;
146 		goto out;
147 	}
148 	pd = fp->f_data;
149 	sx_slock(&proctree_lock);
150 	if (pd->pd_proc != NULL) {
151 		*p = pd->pd_proc;
152 		PROC_LOCK(*p);
153 	} else
154 		error = ESRCH;
155 	sx_sunlock(&proctree_lock);
156 out:
157 	fdrop(fp, td);
158 	return (error);
159 }
160 
161 /*
162  * Function to be used by procstat(1) sysctls when returning procdesc
163  * information.
164  */
165 pid_t
166 procdesc_pid(struct file *fp_procdesc)
167 {
168 	struct procdesc *pd;
169 
170 	KASSERT(fp_procdesc->f_type == DTYPE_PROCDESC,
171 	   ("procdesc_pid: !procdesc"));
172 
173 	pd = fp_procdesc->f_data;
174 	return (pd->pd_pid);
175 }
176 
177 /*
178  * Retrieve the PID associated with a process descriptor.
179  */
180 int
181 kern_pdgetpid(struct thread *td, int fd, cap_rights_t *rightsp, pid_t *pidp)
182 {
183 	struct file *fp;
184 	int error;
185 
186 	error = fget(td, fd, rightsp, &fp);
187 	if (error)
188 		return (error);
189 	if (fp->f_type != DTYPE_PROCDESC) {
190 		error = EBADF;
191 		goto out;
192 	}
193 	*pidp = procdesc_pid(fp);
194 out:
195 	fdrop(fp, td);
196 	return (error);
197 }
198 
199 /*
200  * System call to return the pid of a process given its process descriptor.
201  */
202 int
203 sys_pdgetpid(struct thread *td, struct pdgetpid_args *uap)
204 {
205 	cap_rights_t rights;
206 	pid_t pid;
207 	int error;
208 
209 	AUDIT_ARG_FD(uap->fd);
210 	error = kern_pdgetpid(td, uap->fd,
211 	    cap_rights_init(&rights, CAP_PDGETPID), &pid);
212 	if (error == 0)
213 		error = copyout(&pid, uap->pidp, sizeof(pid));
214 	return (error);
215 }
216 
217 /*
218  * When a new process is forked by pdfork(), a file descriptor is allocated
219  * by the fork code first, then the process is forked, and then we get a
220  * chance to set up the process descriptor.  Failure is not permitted at this
221  * point, so procdesc_new() must succeed.
222  */
223 void
224 procdesc_new(struct proc *p, int flags)
225 {
226 	struct procdesc *pd;
227 
228 	pd = uma_zalloc(procdesc_zone, M_WAITOK | M_ZERO);
229 	pd->pd_proc = p;
230 	pd->pd_pid = p->p_pid;
231 	p->p_procdesc = pd;
232 	pd->pd_flags = 0;
233 	if (flags & PD_DAEMON)
234 		pd->pd_flags |= PDF_DAEMON;
235 	PROCDESC_LOCK_INIT(pd);
236 	knlist_init_mtx(&pd->pd_selinfo.si_note, &pd->pd_lock);
237 
238 	/*
239 	 * Process descriptors start out with two references: one from their
240 	 * struct file, and the other from their struct proc.
241 	 */
242 	refcount_init(&pd->pd_refcount, 2);
243 }
244 
245 /*
246  * Initialize a file with a process descriptor.
247  */
248 void
249 procdesc_finit(struct procdesc *pdp, struct file *fp)
250 {
251 
252 	finit(fp, FREAD | FWRITE, DTYPE_PROCDESC, pdp, &procdesc_ops);
253 }
254 
255 static void
256 procdesc_free(struct procdesc *pd)
257 {
258 
259 	/*
260 	 * When the last reference is released, we assert that the descriptor
261 	 * has been closed, but not that the process has exited, as we will
262 	 * detach the descriptor before the process dies if the descript is
263 	 * closed, as we can't wait synchronously.
264 	 */
265 	if (refcount_release(&pd->pd_refcount)) {
266 		KASSERT(pd->pd_proc == NULL,
267 		    ("procdesc_free: pd_proc != NULL"));
268 		KASSERT((pd->pd_flags & PDF_CLOSED),
269 		    ("procdesc_free: !PDF_CLOSED"));
270 
271 		knlist_destroy(&pd->pd_selinfo.si_note);
272 		PROCDESC_LOCK_DESTROY(pd);
273 		uma_zfree(procdesc_zone, pd);
274 	}
275 }
276 
277 /*
278  * procdesc_exit() - notify a process descriptor that its process is exiting.
279  * We use the proctree_lock to ensure that process exit either happens
280  * strictly before or strictly after a concurrent call to procdesc_close().
281  */
282 int
283 procdesc_exit(struct proc *p)
284 {
285 	struct procdesc *pd;
286 
287 	sx_assert(&proctree_lock, SA_XLOCKED);
288 	PROC_LOCK_ASSERT(p, MA_OWNED);
289 	KASSERT(p->p_procdesc != NULL, ("procdesc_exit: p_procdesc NULL"));
290 
291 	pd = p->p_procdesc;
292 
293 	PROCDESC_LOCK(pd);
294 	KASSERT((pd->pd_flags & PDF_CLOSED) == 0 || p->p_pptr == initproc,
295 	    ("procdesc_exit: closed && parent not init"));
296 
297 	pd->pd_flags |= PDF_EXITED;
298 	pd->pd_xstat = KW_EXITCODE(p->p_xexit, p->p_xsig);
299 
300 	/*
301 	 * If the process descriptor has been closed, then we have nothing
302 	 * to do; return 1 so that init will get SIGCHLD and do the reaping.
303 	 * Clean up the procdesc now rather than letting it happen during
304 	 * that reap.
305 	 */
306 	if (pd->pd_flags & PDF_CLOSED) {
307 		PROCDESC_UNLOCK(pd);
308 		pd->pd_proc = NULL;
309 		p->p_procdesc = NULL;
310 		procdesc_free(pd);
311 		return (1);
312 	}
313 	if (pd->pd_flags & PDF_SELECTED) {
314 		pd->pd_flags &= ~PDF_SELECTED;
315 		selwakeup(&pd->pd_selinfo);
316 	}
317 	KNOTE_LOCKED(&pd->pd_selinfo.si_note, NOTE_EXIT);
318 	PROCDESC_UNLOCK(pd);
319 	return (0);
320 }
321 
322 /*
323  * When a process descriptor is reaped, perhaps as a result of close() or
324  * pdwait4(), release the process's reference on the process descriptor.
325  */
326 void
327 procdesc_reap(struct proc *p)
328 {
329 	struct procdesc *pd;
330 
331 	sx_assert(&proctree_lock, SA_XLOCKED);
332 	KASSERT(p->p_procdesc != NULL, ("procdesc_reap: p_procdesc == NULL"));
333 
334 	pd = p->p_procdesc;
335 	pd->pd_proc = NULL;
336 	p->p_procdesc = NULL;
337 	procdesc_free(pd);
338 }
339 
340 /*
341  * procdesc_close() - last close on a process descriptor.  If the process is
342  * still running, terminate with SIGKILL (unless PDF_DAEMON is set) and let
343  * init(8) clean up the mess; if not, we have to clean up the zombie ourselves.
344  */
345 static int
346 procdesc_close(struct file *fp, struct thread *td)
347 {
348 	struct procdesc *pd;
349 	struct proc *p;
350 
351 	KASSERT(fp->f_type == DTYPE_PROCDESC, ("procdesc_close: !procdesc"));
352 
353 	pd = fp->f_data;
354 	fp->f_ops = &badfileops;
355 	fp->f_data = NULL;
356 
357 	sx_xlock(&proctree_lock);
358 	PROCDESC_LOCK(pd);
359 	pd->pd_flags |= PDF_CLOSED;
360 	PROCDESC_UNLOCK(pd);
361 	p = pd->pd_proc;
362 	if (p == NULL) {
363 		/*
364 		 * This is the case where process' exit status was already
365 		 * collected and procdesc_reap() was already called.
366 		 */
367 		sx_xunlock(&proctree_lock);
368 	} else {
369 		PROC_LOCK(p);
370 		if (p->p_state == PRS_ZOMBIE) {
371 			/*
372 			 * If the process is already dead and just awaiting
373 			 * reaping, do that now.  This will release the
374 			 * process's reference to the process descriptor when it
375 			 * calls back into procdesc_reap().
376 			 */
377 			PROC_SLOCK(p);
378 			proc_reap(curthread, p, NULL, 0);
379 		} else {
380 			/*
381 			 * If the process is not yet dead, we need to kill it,
382 			 * but we can't wait around synchronously for it to go
383 			 * away, as that path leads to madness (and deadlocks).
384 			 * First, detach the process from its descriptor so that
385 			 * its exit status will be reported normally.
386 			 */
387 			pd->pd_proc = NULL;
388 			p->p_procdesc = NULL;
389 			procdesc_free(pd);
390 
391 			/*
392 			 * Next, reparent it to init(8) so that there's someone
393 			 * to pick up the pieces; finally, terminate with
394 			 * prejudice.
395 			 */
396 			p->p_sigparent = SIGCHLD;
397 			proc_reparent(p, initproc);
398 			if ((pd->pd_flags & PDF_DAEMON) == 0)
399 				kern_psignal(p, SIGKILL);
400 			PROC_UNLOCK(p);
401 			sx_xunlock(&proctree_lock);
402 		}
403 	}
404 
405 	/*
406 	 * Release the file descriptor's reference on the process descriptor.
407 	 */
408 	procdesc_free(pd);
409 	return (0);
410 }
411 
412 static int
413 procdesc_poll(struct file *fp, int events, struct ucred *active_cred,
414     struct thread *td)
415 {
416 	struct procdesc *pd;
417 	int revents;
418 
419 	revents = 0;
420 	pd = fp->f_data;
421 	PROCDESC_LOCK(pd);
422 	if (pd->pd_flags & PDF_EXITED)
423 		revents |= POLLHUP;
424 	if (revents == 0) {
425 		selrecord(td, &pd->pd_selinfo);
426 		pd->pd_flags |= PDF_SELECTED;
427 	}
428 	PROCDESC_UNLOCK(pd);
429 	return (revents);
430 }
431 
432 static void
433 procdesc_kqops_detach(struct knote *kn)
434 {
435 	struct procdesc *pd;
436 
437 	pd = kn->kn_fp->f_data;
438 	knlist_remove(&pd->pd_selinfo.si_note, kn, 0);
439 }
440 
441 static int
442 procdesc_kqops_event(struct knote *kn, long hint)
443 {
444 	struct procdesc *pd;
445 	u_int event;
446 
447 	pd = kn->kn_fp->f_data;
448 	if (hint == 0) {
449 		/*
450 		 * Initial test after registration. Generate a NOTE_EXIT in
451 		 * case the process already terminated before registration.
452 		 */
453 		event = pd->pd_flags & PDF_EXITED ? NOTE_EXIT : 0;
454 	} else {
455 		/* Mask off extra data. */
456 		event = (u_int)hint & NOTE_PCTRLMASK;
457 	}
458 
459 	/* If the user is interested in this event, record it. */
460 	if (kn->kn_sfflags & event)
461 		kn->kn_fflags |= event;
462 
463 	/* Process is gone, so flag the event as finished. */
464 	if (event == NOTE_EXIT) {
465 		kn->kn_flags |= EV_EOF | EV_ONESHOT;
466 		if (kn->kn_fflags & NOTE_EXIT)
467 			kn->kn_data = pd->pd_xstat;
468 		if (kn->kn_fflags == 0)
469 			kn->kn_flags |= EV_DROP;
470 		return (1);
471 	}
472 
473 	return (kn->kn_fflags != 0);
474 }
475 
476 static struct filterops procdesc_kqops = {
477 	.f_isfd = 1,
478 	.f_detach = procdesc_kqops_detach,
479 	.f_event = procdesc_kqops_event,
480 };
481 
482 static int
483 procdesc_kqfilter(struct file *fp, struct knote *kn)
484 {
485 	struct procdesc *pd;
486 
487 	pd = fp->f_data;
488 	switch (kn->kn_filter) {
489 	case EVFILT_PROCDESC:
490 		kn->kn_fop = &procdesc_kqops;
491 		kn->kn_flags |= EV_CLEAR;
492 		knlist_add(&pd->pd_selinfo.si_note, kn, 0);
493 		return (0);
494 	default:
495 		return (EINVAL);
496 	}
497 }
498 
499 static int
500 procdesc_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
501     struct thread *td)
502 {
503 	struct procdesc *pd;
504 	struct timeval pstart;
505 
506 	/*
507 	 * XXXRW: Perhaps we should cache some more information from the
508 	 * process so that we can return it reliably here even after it has
509 	 * died.  For example, caching its credential data.
510 	 */
511 	bzero(sb, sizeof(*sb));
512 	pd = fp->f_data;
513 	sx_slock(&proctree_lock);
514 	if (pd->pd_proc != NULL) {
515 		PROC_LOCK(pd->pd_proc);
516 
517 		/* Set birth and [acm] times to process start time. */
518 		pstart = pd->pd_proc->p_stats->p_start;
519 		timevaladd(&pstart, &boottime);
520 		TIMEVAL_TO_TIMESPEC(&pstart, &sb->st_birthtim);
521 		sb->st_atim = sb->st_birthtim;
522 		sb->st_ctim = sb->st_birthtim;
523 		sb->st_mtim = sb->st_birthtim;
524 		if (pd->pd_proc->p_state != PRS_ZOMBIE)
525 			sb->st_mode = S_IFREG | S_IRWXU;
526 		else
527 			sb->st_mode = S_IFREG;
528 		sb->st_uid = pd->pd_proc->p_ucred->cr_ruid;
529 		sb->st_gid = pd->pd_proc->p_ucred->cr_rgid;
530 		PROC_UNLOCK(pd->pd_proc);
531 	} else
532 		sb->st_mode = S_IFREG;
533 	sx_sunlock(&proctree_lock);
534 	return (0);
535 }
536 
537 static int
538 procdesc_fill_kinfo(struct file *fp, struct kinfo_file *kif,
539     struct filedesc *fdp)
540 {
541 	struct procdesc *pdp;
542 
543 	kif->kf_type = KF_TYPE_PROCDESC;
544 	pdp = fp->f_data;
545 	kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
546 	return (0);
547 }
548