xref: /freebsd/bin/ps/ps.c (revision 3ff369fed2a08f32dda232c10470b949bef9489f)
1 /*-
2  * Copyright (c) 1990, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #ifndef lint
38 static const char copyright[] =
39 "@(#) Copyright (c) 1990, 1993, 1994\n\
40 	The Regents of the University of California.  All rights reserved.\n";
41 #endif /* not lint */
42 
43 #if 0
44 #ifndef lint
45 static char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
46 #endif /* not lint */
47 #endif
48 
49 #include <sys/param.h>
50 #include <sys/user.h>
51 #include <sys/stat.h>
52 #include <sys/ioctl.h>
53 #include <sys/sysctl.h>
54 
55 #include <ctype.h>
56 #include <err.h>
57 #include <fcntl.h>
58 #include <kvm.h>
59 #include <limits.h>
60 #include <locale.h>
61 #include <paths.h>
62 #include <pwd.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <unistd.h>
67 #include <utmp.h>
68 
69 #include "lomac.h"
70 #include "ps.h"
71 
72 #define SEP ", \t"		/* username separators */
73 
74 static KINFO *kinfo;
75 struct varent *vhead;
76 
77 int	eval;			/* exit value */
78 int	cflag;			/* -c */
79 int	rawcpu;			/* -C */
80 int	sumrusage;		/* -S */
81 int	termwidth;		/* width of screen (0 == infinity) */
82 int	totwidth;		/* calculated width of requested variables */
83 
84 time_t	now;			/* current time(3) value */
85 
86 static int needuser, needcomm, needenv;
87 #if defined(LAZY_PS)
88 static int forceuread=0;
89 #else
90 static int forceuread=1;
91 #endif
92 
93 static enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
94 
95 static const	 char *fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
96 		    KINFO *, char *, int);
97 static char	*kludge_oldps_options(char *);
98 static int	 pscomp(const void *, const void *);
99 static void	 saveuser(KINFO *);
100 static void	 scanvars(void);
101 static void	 dynsizevars(KINFO *);
102 static void	 sizevars(void);
103 static void	 usage(void);
104 static uid_t	*getuids(const char *, int *);
105 
106 static char dfmt[] = "pid,tt,state,time,command";
107 static char jfmt[] = "user,pid,ppid,pgid,jobc,state,tt,time,command";
108 static char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,tt,time,command";
109 static char   o1[] = "pid";
110 static char   o2[] = "tt,state,time,command";
111 static char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
112 static char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,%cpu,%mem,command";
113 static char Zfmt[] = "lvl";
114 
115 static kvm_t *kd;
116 
117 int
118 main(int argc, char *argv[])
119 {
120 	struct kinfo_proc *kp;
121 	struct varent *vent;
122 	struct winsize ws;
123 	dev_t ttydev;
124 	pid_t pid;
125 	uid_t *uids;
126 	int all, ch, flag, i, _fmt, lineno, nentries, dropgid;
127 	int prtheader, wflag, what, xflg, uid, nuids;
128 	char *cols;
129 	char errbuf[_POSIX2_LINE_MAX];
130 	const char *nlistf, *memf;
131 
132 	(void) setlocale(LC_ALL, "");
133 	/* Set the time to what it is right now. */
134 	time(&now);
135 
136 	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
137 		termwidth = atoi(cols);
138 	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
139 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
140 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
141 	     ws.ws_col == 0)
142 		termwidth = 79;
143 	else
144 		termwidth = ws.ws_col - 1;
145 
146 	if (argc > 1)
147 		argv[1] = kludge_oldps_options(argv[1]);
148 
149 	all = _fmt = prtheader = wflag = xflg = 0;
150 	pid = -1;
151 	nuids = 0;
152 	uids = NULL;
153 	ttydev = NODEV;
154 	dropgid = 0;
155 	memf = nlistf = _PATH_DEVNULL;
156 	while ((ch = getopt(argc, argv,
157 #if defined(LAZY_PS)
158 	    "aCcefghjLlM:mN:O:o:p:rSTt:U:uvwxZ")) != -1)
159 #else
160 	    "aCceghjLlM:mN:O:o:p:rSTt:U:uvwxZ")) != -1)
161 #endif
162 		switch((char)ch) {
163 		case 'a':
164 			all = 1;
165 			break;
166 		case 'C':
167 			rawcpu = 1;
168 			break;
169 		case 'c':
170 			cflag = 1;
171 			break;
172 		case 'e':			/* XXX set ufmt */
173 			needenv = 1;
174 			break;
175 		case 'g':
176 			break;			/* no-op */
177 		case 'h':
178 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
179 			break;
180 		case 'j':
181 			parsefmt(jfmt);
182 			_fmt = 1;
183 			jfmt[0] = '\0';
184 			break;
185 		case 'L':
186 			showkey();
187 			exit(0);
188 		case 'l':
189 			parsefmt(lfmt);
190 			_fmt = 1;
191 			lfmt[0] = '\0';
192 			break;
193 		case 'M':
194 			memf = optarg;
195 			dropgid = 1;
196 			break;
197 		case 'm':
198 			sortby = SORTMEM;
199 			break;
200 		case 'N':
201 			nlistf = optarg;
202 			dropgid = 1;
203 			break;
204 		case 'O':
205 			parsefmt(o1);
206 			parsefmt(optarg);
207 			parsefmt(o2);
208 			o1[0] = o2[0] = '\0';
209 			_fmt = 1;
210 			break;
211 		case 'o':
212 			parsefmt(optarg);
213 			_fmt = 1;
214 			break;
215 #if defined(LAZY_PS)
216 		case 'f':
217 			if (getuid() == 0 || getgid() == 0)
218 			    forceuread = 1;
219 			break;
220 #endif
221 		case 'p':
222 			pid = atol(optarg);
223 			xflg = 1;
224 			break;
225 		case 'r':
226 			sortby = SORTCPU;
227 			break;
228 		case 'S':
229 			sumrusage = 1;
230 			break;
231 		case 'T':
232 			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
233 				errx(1, "stdin: not a terminal");
234 			/* FALLTHROUGH */
235 		case 't': {
236 			struct stat sb;
237 			char *ttypath, pathbuf[PATH_MAX];
238 
239 			if (strcmp(optarg, "co") == 0)
240 				ttypath = strdup(_PATH_CONSOLE);
241 			else if (*optarg != '/')
242 				(void)snprintf(ttypath = pathbuf,
243 				    sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
244 			else
245 				ttypath = optarg;
246 			if (stat(ttypath, &sb) == -1)
247 				err(1, "%s", ttypath);
248 			if (!S_ISCHR(sb.st_mode))
249 				errx(1, "%s: not a terminal", ttypath);
250 			ttydev = sb.st_rdev;
251 			break;
252 		}
253 		case 'U':
254 			uids = getuids(optarg, &nuids);
255 			xflg++;		/* XXX: intuitive? */
256 			break;
257 		case 'u':
258 			parsefmt(ufmt);
259 			sortby = SORTCPU;
260 			_fmt = 1;
261 			ufmt[0] = '\0';
262 			break;
263 		case 'v':
264 			parsefmt(vfmt);
265 			sortby = SORTMEM;
266 			_fmt = 1;
267 			vfmt[0] = '\0';
268 			break;
269 		case 'w':
270 			if (wflag)
271 				termwidth = UNLIMITED;
272 			else if (termwidth < 131)
273 				termwidth = 131;
274 			wflag++;
275 			break;
276 		case 'x':
277 			xflg = 1;
278 			break;
279 		case 'Z':
280 			parsefmt(Zfmt);
281 			Zfmt[0] = '\0';
282 			break;
283 		case '?':
284 		default:
285 			usage();
286 		}
287 	argc -= optind;
288 	argv += optind;
289 
290 #define	BACKWARD_COMPATIBILITY
291 #ifdef	BACKWARD_COMPATIBILITY
292 	if (*argv) {
293 		nlistf = *argv;
294 		if (*++argv) {
295 			memf = *argv;
296 		}
297 	}
298 #endif
299 	/*
300 	 * Discard setgid privileges if not the running kernel so that bad
301 	 * guys can't print interesting stuff from kernel memory.
302 	 */
303 	if (dropgid) {
304 		setgid(getgid());
305 		setuid(getuid());
306 	}
307 
308 	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
309 	if (kd == 0)
310 		errx(1, "%s", errbuf);
311 
312 	if (!_fmt)
313 		parsefmt(dfmt);
314 
315 	/* XXX - should be cleaner */
316 	if (!all && ttydev == NODEV && pid == -1 && !nuids) {
317 		if ((uids = malloc(sizeof (*uids))) == NULL)
318 			errx(1, "malloc failed");
319 		nuids = 1;
320 		*uids = getuid();
321 	}
322 
323 	/*
324 	 * scan requested variables, noting what structures are needed,
325 	 * and adjusting header widths as appropriate.
326 	 */
327 	scanvars();
328 	/*
329 	 * get proc list
330 	 */
331 	if (nuids == 1) {
332 		what = KERN_PROC_UID;
333 		flag = *uids;
334 	} else if (ttydev != NODEV) {
335 		what = KERN_PROC_TTY;
336 		flag = ttydev;
337 	} else if (pid != -1) {
338 		what = KERN_PROC_PID;
339 		flag = pid;
340 	} else {
341 		what = KERN_PROC_ALL;
342 		flag = 0;
343 	}
344 	/*
345 	 * select procs
346 	 */
347 	if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == 0 || nentries < 0)
348 		errx(1, "%s", kvm_geterr(kd));
349 	if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
350 		errx(1, "malloc failed");
351 	for (i = nentries; --i >= 0; ++kp) {
352 		kinfo[i].ki_p = kp;
353 		if (needuser)
354 			saveuser(&kinfo[i]);
355 		dynsizevars(&kinfo[i]);
356 	}
357 
358 	sizevars();
359 
360 	/*
361 	 * print header
362 	 */
363 	printheader();
364 	if (nentries == 0)
365 		exit(1);
366 	/*
367 	 * sort proc list
368 	 */
369 	qsort(kinfo, nentries, sizeof(KINFO), pscomp);
370 	/*
371 	 * for each proc, call each variable output function.
372 	 */
373 	for (i = lineno = 0; i < nentries; i++) {
374 		if (xflg == 0 && ((&kinfo[i])->ki_p->ki_tdev == NODEV ||
375 		    ((&kinfo[i])->ki_p->ki_flag & P_CONTROLT ) == 0))
376 			continue;
377 		if (nuids > 1) {
378 			for (uid = 0; uid < nuids; uid++)
379 				if ((&kinfo[i])->ki_p->ki_uid == uids[uid])
380 					break;
381 			if (uid == nuids)
382 				continue;
383 		}
384 		for (vent = vhead; vent; vent = vent->next) {
385 			(vent->var->oproc)(&kinfo[i], vent);
386 			if (vent->next != NULL)
387 				(void)putchar(' ');
388 		}
389 		(void)putchar('\n');
390 		if (prtheader && lineno++ == prtheader - 4) {
391 			(void)putchar('\n');
392 			printheader();
393 			lineno = 0;
394 		}
395 	}
396 	free(uids);
397 	lomac_stop();
398 
399 	exit(eval);
400 }
401 
402 uid_t *
403 getuids(const char *arg, int *nuids)
404 {
405 	char name[UT_NAMESIZE + 1];
406 	struct passwd *pwd;
407 	uid_t *uids, *moreuids;
408 	int alloc;
409 	size_t l;
410 
411 
412 	alloc = 0;
413 	*nuids = 0;
414 	uids = NULL;
415 	for (; (l = strcspn(arg, SEP)) > 0; arg += l + strspn(arg + l, SEP)) {
416 		if (l >= sizeof name) {
417 			warnx("%.*s: name too long", (int)l, arg);
418 			continue;
419 		}
420 		strncpy(name, arg, l);
421 		name[l] = '\0';
422 		if ((pwd = getpwnam(name)) == NULL) {
423 			warnx("%s: no such user", name);
424 			continue;
425 		}
426 		if (*nuids >= alloc) {
427 			alloc = (alloc + 1) << 1;
428 			moreuids = realloc(uids, alloc * sizeof (*uids));
429 			if (moreuids == NULL) {
430 				free(uids);
431 				errx(1, "realloc failed");
432 			}
433 			uids = moreuids;
434 		}
435 		uids[(*nuids)++] = pwd->pw_uid;
436 	}
437 	endpwent();
438 
439 	if (!*nuids)
440 		errx(1, "No users specified");
441 
442 	return uids;
443 }
444 
445 static void
446 scanvars(void)
447 {
448 	struct varent *vent;
449 	VAR *v;
450 
451 	for (vent = vhead; vent; vent = vent->next) {
452 		v = vent->var;
453 		if (v->flag & DSIZ) {
454 			v->dwidth = v->width;
455 			v->width = 0;
456 		}
457 		if (v->flag & USER)
458 			needuser = 1;
459 		if (v->flag & COMM)
460 			needcomm = 1;
461 	}
462 }
463 
464 static void
465 dynsizevars(KINFO *ki)
466 {
467 	struct varent *vent;
468 	VAR *v;
469 	int i;
470 
471 	for (vent = vhead; vent; vent = vent->next) {
472 		v = vent->var;
473 		if (!(v->flag & DSIZ))
474 			continue;
475 		i = (v->sproc)( ki);
476 		if (v->width < i)
477 			v->width = i;
478 		if (v->width > v->dwidth)
479 			v->width = v->dwidth;
480 	}
481 }
482 
483 static void
484 sizevars(void)
485 {
486 	struct varent *vent;
487 	VAR *v;
488 	int i;
489 
490 	for (vent = vhead; vent; vent = vent->next) {
491 		v = vent->var;
492 		i = strlen(v->header);
493 		if (v->width < i)
494 			v->width = i;
495 		totwidth += v->width + 1;	/* +1 for space */
496 	}
497 	totwidth--;
498 }
499 
500 static const char *
501 fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
502   char *comm, int maxlen)
503 {
504 	const char *s;
505 
506 	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
507 	return (s);
508 }
509 
510 #define UREADOK(ki)	(forceuread || (ki->ki_p->ki_sflag & PS_INMEM))
511 
512 static void
513 saveuser(KINFO *ki)
514 {
515 
516 	if (ki->ki_p->ki_sflag & PS_INMEM) {
517 		/*
518 		 * The u-area might be swapped out, and we can't get
519 		 * at it because we have a crashdump and no swap.
520 		 * If it's here fill in these fields, otherwise, just
521 		 * leave them 0.
522 		 */
523 		ki->ki_valid = 1;
524 	} else
525 		ki->ki_valid = 0;
526 	/*
527 	 * save arguments if needed
528 	 */
529 	if (needcomm && (UREADOK(ki) || (ki->ki_p->ki_args != NULL))) {
530 		ki->ki_args = strdup(fmt(kvm_getargv, ki, ki->ki_p->ki_comm,
531 		    MAXCOMLEN));
532 	} else if (needcomm) {
533 		asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
534 	} else {
535 		ki->ki_args = NULL;
536 	}
537 	if (needenv && UREADOK(ki)) {
538 		ki->ki_env = strdup(fmt(kvm_getenvv, ki, (char *)NULL, 0));
539 	} else if (needenv) {
540 		ki->ki_env = malloc(3);
541 		strcpy(ki->ki_env, "()");
542 	} else {
543 		ki->ki_env = NULL;
544 	}
545 }
546 
547 static int
548 pscomp(const void *a, const void *b)
549 {
550 	int i;
551 #define VSIZE(k) ((k)->ki_p->ki_dsize + (k)->ki_p->ki_ssize + \
552 		  (k)->ki_p->ki_tsize)
553 
554 	if (sortby == SORTCPU)
555 		return (getpcpu((const KINFO *)b) - getpcpu((const KINFO *)a));
556 	if (sortby == SORTMEM)
557 		return (VSIZE((const KINFO *)b) - VSIZE((const KINFO *)a));
558 	i =  (int)((const KINFO *)a)->ki_p->ki_tdev - (int)((const KINFO *)b)->ki_p->ki_tdev;
559 	if (i == 0)
560 		i = ((const KINFO *)a)->ki_p->ki_pid - ((const KINFO *)b)->ki_p->ki_pid;
561 	return (i);
562 }
563 
564 /*
565  * ICK (all for getopt), would rather hide the ugliness
566  * here than taint the main code.
567  *
568  *  ps foo -> ps -foo
569  *  ps 34 -> ps -p34
570  *
571  * The old convention that 't' with no trailing tty arg means the users
572  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
573  * feature is available with the option 'T', which takes no argument.
574  */
575 static char *
576 kludge_oldps_options(char *s)
577 {
578 	size_t len;
579 	char *newopts, *ns, *cp;
580 
581 	len = strlen(s);
582 	if ((newopts = ns = malloc(len + 2)) == NULL)
583 		errx(1, "malloc failed");
584 	/*
585 	 * options begin with '-'
586 	 */
587 	if (*s != '-')
588 		*ns++ = '-';	/* add option flag */
589 	/*
590 	 * gaze to end of argv[1]
591 	 */
592 	cp = s + len - 1;
593 	/*
594 	 * if last letter is a 't' flag with no argument (in the context
595 	 * of the oldps options -- option string NOT starting with a '-' --
596 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
597 	 *
598 	 * However, if a flag accepting a string argument is found in the
599 	 * option string, the remainder of the string is the argument to
600 	 * that flag; do not modify that argument.
601 	 */
602 	if (strcspn(s, "MNOoU") == len && *cp == 't' && *s != '-')
603 		*cp = 'T';
604 	else {
605 		/*
606 		 * otherwise check for trailing number, which *may* be a
607 		 * pid.
608 		 */
609 		while (cp >= s && isdigit(*cp))
610 			--cp;
611 	}
612 	cp++;
613 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
614 	ns += cp - s;
615 	/*
616 	 * if there's a trailing number, and not a preceding 'p' (pid) or
617 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
618 	 */
619 	if (isdigit(*cp) &&
620 	    (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
621 	    (cp - 1 == s || cp[-2] != 't'))
622 		*ns++ = 'p';
623 	(void)strcpy(ns, cp);		/* and append the number */
624 
625 	return (newopts);
626 }
627 
628 static void
629 usage(void)
630 {
631 
632 	(void)fprintf(stderr, "%s\n%s\n%s\n",
633 	    "usage: ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty] [-U user]",
634 	    "          [-M core] [-N system]",
635 	    "       ps [-L]");
636 	exit(1);
637 }
638