xref: /freebsd/sys/kern/sys_procdesc.c (revision 38f0b757fd84d17d0fc24739a7cda160c4516d81)
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 
82 #include <security/audit/audit.h>
83 
84 #include <vm/uma.h>
85 
86 FEATURE(process_descriptors, "Process Descriptors");
87 
88 static uma_zone_t procdesc_zone;
89 
90 static fo_rdwr_t	procdesc_read;
91 static fo_rdwr_t	procdesc_write;
92 static fo_truncate_t	procdesc_truncate;
93 static fo_ioctl_t	procdesc_ioctl;
94 static fo_poll_t	procdesc_poll;
95 static fo_kqfilter_t	procdesc_kqfilter;
96 static fo_stat_t	procdesc_stat;
97 static fo_close_t	procdesc_close;
98 static fo_chmod_t	procdesc_chmod;
99 static fo_chown_t	procdesc_chown;
100 
101 static struct fileops procdesc_ops = {
102 	.fo_read = procdesc_read,
103 	.fo_write = procdesc_write,
104 	.fo_truncate = procdesc_truncate,
105 	.fo_ioctl = procdesc_ioctl,
106 	.fo_poll = procdesc_poll,
107 	.fo_kqfilter = procdesc_kqfilter,
108 	.fo_stat = procdesc_stat,
109 	.fo_close = procdesc_close,
110 	.fo_chmod = procdesc_chmod,
111 	.fo_chown = procdesc_chown,
112 	.fo_sendfile = invfo_sendfile,
113 	.fo_flags = DFLAG_PASSABLE,
114 };
115 
116 /*
117  * Initialize with VFS so that process descriptors are available along with
118  * other file descriptor types.  As long as it runs before init(8) starts,
119  * there shouldn't be a problem.
120  */
121 static void
122 procdesc_init(void *dummy __unused)
123 {
124 
125 	procdesc_zone = uma_zcreate("procdesc", sizeof(struct procdesc),
126 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
127 	if (procdesc_zone == NULL)
128 		panic("procdesc_init: procdesc_zone not initialized");
129 }
130 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_ANY, procdesc_init, NULL);
131 
132 /*
133  * Return a locked process given a process descriptor, or ESRCH if it has
134  * died.
135  */
136 int
137 procdesc_find(struct thread *td, int fd, cap_rights_t *rightsp,
138     struct proc **p)
139 {
140 	struct procdesc *pd;
141 	struct file *fp;
142 	int error;
143 
144 	error = fget(td, fd, rightsp, &fp);
145 	if (error)
146 		return (error);
147 	if (fp->f_type != DTYPE_PROCDESC) {
148 		error = EBADF;
149 		goto out;
150 	}
151 	pd = fp->f_data;
152 	sx_slock(&proctree_lock);
153 	if (pd->pd_proc != NULL) {
154 		*p = pd->pd_proc;
155 		PROC_LOCK(*p);
156 	} else
157 		error = ESRCH;
158 	sx_sunlock(&proctree_lock);
159 out:
160 	fdrop(fp, td);
161 	return (error);
162 }
163 
164 /*
165  * Function to be used by procstat(1) sysctls when returning procdesc
166  * information.
167  */
168 pid_t
169 procdesc_pid(struct file *fp_procdesc)
170 {
171 	struct procdesc *pd;
172 
173 	KASSERT(fp_procdesc->f_type == DTYPE_PROCDESC,
174 	   ("procdesc_pid: !procdesc"));
175 
176 	pd = fp_procdesc->f_data;
177 	return (pd->pd_pid);
178 }
179 
180 /*
181  * Retrieve the PID associated with a process descriptor.
182  */
183 int
184 kern_pdgetpid(struct thread *td, int fd, cap_rights_t *rightsp, pid_t *pidp)
185 {
186 	struct file *fp;
187 	int error;
188 
189 	error = fget(td, fd, rightsp, &fp);
190 	if (error)
191 		return (error);
192 	if (fp->f_type != DTYPE_PROCDESC) {
193 		error = EBADF;
194 		goto out;
195 	}
196 	*pidp = procdesc_pid(fp);
197 out:
198 	fdrop(fp, td);
199 	return (error);
200 }
201 
202 /*
203  * System call to return the pid of a process given its process descriptor.
204  */
205 int
206 sys_pdgetpid(struct thread *td, struct pdgetpid_args *uap)
207 {
208 	cap_rights_t rights;
209 	pid_t pid;
210 	int error;
211 
212 	AUDIT_ARG_FD(uap->fd);
213 	error = kern_pdgetpid(td, uap->fd,
214 	    cap_rights_init(&rights, CAP_PDGETPID), &pid);
215 	if (error == 0)
216 		error = copyout(&pid, uap->pidp, sizeof(pid));
217 	return (error);
218 }
219 
220 /*
221  * When a new process is forked by pdfork(), a file descriptor is allocated
222  * by the fork code first, then the process is forked, and then we get a
223  * chance to set up the process descriptor.  Failure is not permitted at this
224  * point, so procdesc_new() must succeed.
225  */
226 void
227 procdesc_new(struct proc *p, int flags)
228 {
229 	struct procdesc *pd;
230 
231 	pd = uma_zalloc(procdesc_zone, M_WAITOK | M_ZERO);
232 	pd->pd_proc = p;
233 	pd->pd_pid = p->p_pid;
234 	p->p_procdesc = pd;
235 	pd->pd_flags = 0;
236 	if (flags & PD_DAEMON)
237 		pd->pd_flags |= PDF_DAEMON;
238 	PROCDESC_LOCK_INIT(pd);
239 	knlist_init_mtx(&pd->pd_selinfo.si_note, &pd->pd_lock);
240 
241 	/*
242 	 * Process descriptors start out with two references: one from their
243 	 * struct file, and the other from their struct proc.
244 	 */
245 	refcount_init(&pd->pd_refcount, 2);
246 }
247 
248 /*
249  * Initialize a file with a process descriptor.
250  */
251 void
252 procdesc_finit(struct procdesc *pdp, struct file *fp)
253 {
254 
255 	finit(fp, FREAD | FWRITE, DTYPE_PROCDESC, pdp, &procdesc_ops);
256 }
257 
258 static void
259 procdesc_free(struct procdesc *pd)
260 {
261 
262 	/*
263 	 * When the last reference is released, we assert that the descriptor
264 	 * has been closed, but not that the process has exited, as we will
265 	 * detach the descriptor before the process dies if the descript is
266 	 * closed, as we can't wait synchronously.
267 	 */
268 	if (refcount_release(&pd->pd_refcount)) {
269 		KASSERT(pd->pd_proc == NULL,
270 		    ("procdesc_free: pd_proc != NULL"));
271 		KASSERT((pd->pd_flags & PDF_CLOSED),
272 		    ("procdesc_free: !PDF_CLOSED"));
273 
274 		knlist_destroy(&pd->pd_selinfo.si_note);
275 		PROCDESC_LOCK_DESTROY(pd);
276 		uma_zfree(procdesc_zone, pd);
277 	}
278 }
279 
280 /*
281  * procdesc_exit() - notify a process descriptor that its process is exiting.
282  * We use the proctree_lock to ensure that process exit either happens
283  * strictly before or strictly after a concurrent call to procdesc_close().
284  */
285 int
286 procdesc_exit(struct proc *p)
287 {
288 	struct procdesc *pd;
289 
290 	sx_assert(&proctree_lock, SA_XLOCKED);
291 	PROC_LOCK_ASSERT(p, MA_OWNED);
292 	KASSERT(p->p_procdesc != NULL, ("procdesc_exit: p_procdesc NULL"));
293 
294 	pd = p->p_procdesc;
295 
296 	PROCDESC_LOCK(pd);
297 	KASSERT((pd->pd_flags & PDF_CLOSED) == 0 || p->p_pptr == initproc,
298 	    ("procdesc_exit: closed && parent not init"));
299 
300 	pd->pd_flags |= PDF_EXITED;
301 	pd->pd_xstat = p->p_xstat;
302 
303 	/*
304 	 * If the process descriptor has been closed, then we have nothing
305 	 * to do; return 1 so that init will get SIGCHLD and do the reaping.
306 	 * Clean up the procdesc now rather than letting it happen during
307 	 * that reap.
308 	 */
309 	if (pd->pd_flags & PDF_CLOSED) {
310 		PROCDESC_UNLOCK(pd);
311 		pd->pd_proc = NULL;
312 		p->p_procdesc = NULL;
313 		procdesc_free(pd);
314 		return (1);
315 	}
316 	if (pd->pd_flags & PDF_SELECTED) {
317 		pd->pd_flags &= ~PDF_SELECTED;
318 		selwakeup(&pd->pd_selinfo);
319 	}
320 	KNOTE_LOCKED(&pd->pd_selinfo.si_note, NOTE_EXIT);
321 	PROCDESC_UNLOCK(pd);
322 	return (0);
323 }
324 
325 /*
326  * When a process descriptor is reaped, perhaps as a result of close() or
327  * pdwait4(), release the process's reference on the process descriptor.
328  */
329 void
330 procdesc_reap(struct proc *p)
331 {
332 	struct procdesc *pd;
333 
334 	sx_assert(&proctree_lock, SA_XLOCKED);
335 	KASSERT(p->p_procdesc != NULL, ("procdesc_reap: p_procdesc == NULL"));
336 
337 	pd = p->p_procdesc;
338 	pd->pd_proc = NULL;
339 	p->p_procdesc = NULL;
340 	procdesc_free(pd);
341 }
342 
343 /*
344  * procdesc_close() - last close on a process descriptor.  If the process is
345  * still running, terminate with SIGKILL (unless PDF_DAEMON is set) and let
346  * init(8) clean up the mess; if not, we have to clean up the zombie ourselves.
347  */
348 static int
349 procdesc_close(struct file *fp, struct thread *td)
350 {
351 	struct procdesc *pd;
352 	struct proc *p;
353 
354 	KASSERT(fp->f_type == DTYPE_PROCDESC, ("procdesc_close: !procdesc"));
355 
356 	pd = fp->f_data;
357 	fp->f_ops = &badfileops;
358 	fp->f_data = NULL;
359 
360 	sx_xlock(&proctree_lock);
361 	PROCDESC_LOCK(pd);
362 	pd->pd_flags |= PDF_CLOSED;
363 	PROCDESC_UNLOCK(pd);
364 	p = pd->pd_proc;
365 	if (p == NULL) {
366 		/*
367 		 * This is the case where process' exit status was already
368 		 * collected and procdesc_reap() was already called.
369 		 */
370 		sx_xunlock(&proctree_lock);
371 	} else {
372 		PROC_LOCK(p);
373 		if (p->p_state == PRS_ZOMBIE) {
374 			/*
375 			 * If the process is already dead and just awaiting
376 			 * reaping, do that now.  This will release the
377 			 * process's reference to the process descriptor when it
378 			 * calls back into procdesc_reap().
379 			 */
380 			PROC_SLOCK(p);
381 			proc_reap(curthread, p, NULL, 0);
382 		} else {
383 			/*
384 			 * If the process is not yet dead, we need to kill it,
385 			 * but we can't wait around synchronously for it to go
386 			 * away, as that path leads to madness (and deadlocks).
387 			 * First, detach the process from its descriptor so that
388 			 * its exit status will be reported normally.
389 			 */
390 			pd->pd_proc = NULL;
391 			p->p_procdesc = NULL;
392 			procdesc_free(pd);
393 
394 			/*
395 			 * Next, reparent it to init(8) so that there's someone
396 			 * to pick up the pieces; finally, terminate with
397 			 * prejudice.
398 			 */
399 			p->p_sigparent = SIGCHLD;
400 			proc_reparent(p, initproc);
401 			if ((pd->pd_flags & PDF_DAEMON) == 0)
402 				kern_psignal(p, SIGKILL);
403 			PROC_UNLOCK(p);
404 			sx_xunlock(&proctree_lock);
405 		}
406 	}
407 
408 	/*
409 	 * Release the file descriptor's reference on the process descriptor.
410 	 */
411 	procdesc_free(pd);
412 	return (0);
413 }
414 
415 static int
416 procdesc_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
417     int flags, struct thread *td)
418 {
419 
420 	return (EOPNOTSUPP);
421 }
422 
423 static int
424 procdesc_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
425     int flags, struct thread *td)
426 {
427 
428 	return (EOPNOTSUPP);
429 }
430 
431 static int
432 procdesc_truncate(struct file *fp, off_t length, struct ucred *active_cred,
433     struct thread *td)
434 {
435 
436 	return (EOPNOTSUPP);
437 }
438 
439 static int
440 procdesc_ioctl(struct file *fp, u_long com, void *data,
441     struct ucred *active_cred, struct thread *td)
442 {
443 
444 	return (EOPNOTSUPP);
445 }
446 
447 static int
448 procdesc_poll(struct file *fp, int events, struct ucred *active_cred,
449     struct thread *td)
450 {
451 	struct procdesc *pd;
452 	int revents;
453 
454 	revents = 0;
455 	pd = fp->f_data;
456 	PROCDESC_LOCK(pd);
457 	if (pd->pd_flags & PDF_EXITED)
458 		revents |= POLLHUP;
459 	if (revents == 0) {
460 		selrecord(td, &pd->pd_selinfo);
461 		pd->pd_flags |= PDF_SELECTED;
462 	}
463 	PROCDESC_UNLOCK(pd);
464 	return (revents);
465 }
466 
467 static void
468 procdesc_kqops_detach(struct knote *kn)
469 {
470 	struct procdesc *pd;
471 
472 	pd = kn->kn_fp->f_data;
473 	knlist_remove(&pd->pd_selinfo.si_note, kn, 0);
474 }
475 
476 static int
477 procdesc_kqops_event(struct knote *kn, long hint)
478 {
479 	struct procdesc *pd;
480 	u_int event;
481 
482 	pd = kn->kn_fp->f_data;
483 	if (hint == 0) {
484 		/*
485 		 * Initial test after registration. Generate a NOTE_EXIT in
486 		 * case the process already terminated before registration.
487 		 */
488 		event = pd->pd_flags & PDF_EXITED ? NOTE_EXIT : 0;
489 	} else {
490 		/* Mask off extra data. */
491 		event = (u_int)hint & NOTE_PCTRLMASK;
492 	}
493 
494 	/* If the user is interested in this event, record it. */
495 	if (kn->kn_sfflags & event)
496 		kn->kn_fflags |= event;
497 
498 	/* Process is gone, so flag the event as finished. */
499 	if (event == NOTE_EXIT) {
500 		kn->kn_flags |= EV_EOF | EV_ONESHOT;
501 		if (kn->kn_fflags & NOTE_EXIT)
502 			kn->kn_data = pd->pd_xstat;
503 		if (kn->kn_fflags == 0)
504 			kn->kn_flags |= EV_DROP;
505 		return (1);
506 	}
507 
508 	return (kn->kn_fflags != 0);
509 }
510 
511 static struct filterops procdesc_kqops = {
512 	.f_isfd = 1,
513 	.f_detach = procdesc_kqops_detach,
514 	.f_event = procdesc_kqops_event,
515 };
516 
517 static int
518 procdesc_kqfilter(struct file *fp, struct knote *kn)
519 {
520 	struct procdesc *pd;
521 
522 	pd = fp->f_data;
523 	switch (kn->kn_filter) {
524 	case EVFILT_PROCDESC:
525 		kn->kn_fop = &procdesc_kqops;
526 		kn->kn_flags |= EV_CLEAR;
527 		knlist_add(&pd->pd_selinfo.si_note, kn, 0);
528 		return (0);
529 	default:
530 		return (EINVAL);
531 	}
532 }
533 
534 static int
535 procdesc_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
536     struct thread *td)
537 {
538 	struct procdesc *pd;
539 	struct timeval pstart;
540 
541 	/*
542 	 * XXXRW: Perhaps we should cache some more information from the
543 	 * process so that we can return it reliably here even after it has
544 	 * died.  For example, caching its credential data.
545 	 */
546 	bzero(sb, sizeof(*sb));
547 	pd = fp->f_data;
548 	sx_slock(&proctree_lock);
549 	if (pd->pd_proc != NULL) {
550 		PROC_LOCK(pd->pd_proc);
551 
552 		/* Set birth and [acm] times to process start time. */
553 		pstart = pd->pd_proc->p_stats->p_start;
554 		timevaladd(&pstart, &boottime);
555 		TIMEVAL_TO_TIMESPEC(&pstart, &sb->st_birthtim);
556 		sb->st_atim = sb->st_birthtim;
557 		sb->st_ctim = sb->st_birthtim;
558 		sb->st_mtim = sb->st_birthtim;
559 		if (pd->pd_proc->p_state != PRS_ZOMBIE)
560 			sb->st_mode = S_IFREG | S_IRWXU;
561 		else
562 			sb->st_mode = S_IFREG;
563 		sb->st_uid = pd->pd_proc->p_ucred->cr_ruid;
564 		sb->st_gid = pd->pd_proc->p_ucred->cr_rgid;
565 		PROC_UNLOCK(pd->pd_proc);
566 	} else
567 		sb->st_mode = S_IFREG;
568 	sx_sunlock(&proctree_lock);
569 	return (0);
570 }
571 
572 static int
573 procdesc_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
574     struct thread *td)
575 {
576 
577 	return (EOPNOTSUPP);
578 }
579 
580 static int
581 procdesc_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
582     struct thread *td)
583 {
584 
585 	return (EOPNOTSUPP);
586 }
587