xref: /freebsd/usr.bin/procstat/procstat_files.c (revision e796cc77c586c2955b2f3940dbf4991b31e8d289)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2007-2011 Robert N. M. Watson
5  * Copyright (c) 2015 Allan Jude <allanjude@freebsd.org>
6  * All rights reserved.
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  * $FreeBSD$
30  */
31 
32 #include <sys/param.h>
33 #include <sys/capsicum.h>
34 #include <sys/socket.h>
35 #include <sys/sysctl.h>
36 #include <sys/un.h>
37 #include <sys/user.h>
38 
39 #include <netinet/in.h>
40 
41 #include <arpa/inet.h>
42 
43 #include <err.h>
44 #include <libprocstat.h>
45 #include <inttypes.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 
50 #include "procstat.h"
51 
52 static const char *
53 protocol_to_string(int domain, int type, int protocol)
54 {
55 
56 	switch (domain) {
57 	case AF_INET:
58 	case AF_INET6:
59 		switch (protocol) {
60 		case IPPROTO_TCP:
61 			return ("TCP");
62 		case IPPROTO_UDP:
63 			return ("UDP");
64 		case IPPROTO_ICMP:
65 			return ("ICM");
66 		case IPPROTO_RAW:
67 			return ("RAW");
68 		case IPPROTO_SCTP:
69 			return ("SCT");
70 		case IPPROTO_DIVERT:
71 			return ("IPD");
72 		default:
73 			return ("IP?");
74 		}
75 
76 	case AF_LOCAL:
77 		switch (type) {
78 		case SOCK_STREAM:
79 			return ("UDS");
80 		case SOCK_DGRAM:
81 			return ("UDD");
82 		default:
83 			return ("UD?");
84 		}
85 	default:
86 		return ("?");
87 	}
88 }
89 
90 static void
91 addr_to_string(struct sockaddr_storage *ss, char *buffer, int buflen)
92 {
93 	char buffer2[INET6_ADDRSTRLEN];
94 	struct sockaddr_in6 *sin6;
95 	struct sockaddr_in *sin;
96 	struct sockaddr_un *sun;
97 
98 	switch (ss->ss_family) {
99 	case AF_LOCAL:
100 		sun = (struct sockaddr_un *)ss;
101 		if (strlen(sun->sun_path) == 0)
102 			strlcpy(buffer, "-", buflen);
103 		else
104 			strlcpy(buffer, sun->sun_path, buflen);
105 		break;
106 
107 	case AF_INET:
108 		sin = (struct sockaddr_in *)ss;
109 		snprintf(buffer, buflen, "%s:%d", inet_ntoa(sin->sin_addr),
110 		    ntohs(sin->sin_port));
111 		break;
112 
113 	case AF_INET6:
114 		sin6 = (struct sockaddr_in6 *)ss;
115 		if (inet_ntop(AF_INET6, &sin6->sin6_addr, buffer2,
116 		    sizeof(buffer2)) != NULL)
117 			snprintf(buffer, buflen, "%s.%d", buffer2,
118 			    ntohs(sin6->sin6_port));
119 		else
120 			strlcpy(buffer, "-", buflen);
121 		break;
122 
123 	default:
124 		strlcpy(buffer, "", buflen);
125 		break;
126 	}
127 }
128 
129 static struct cap_desc {
130 	uint64_t	 cd_right;
131 	const char	*cd_desc;
132 } cap_desc[] = {
133 	/* General file I/O. */
134 	{ CAP_READ,		"rd" },
135 	{ CAP_WRITE,		"wr" },
136 	{ CAP_SEEK,		"se" },
137 	{ CAP_MMAP,		"mm" },
138 	{ CAP_CREATE,		"cr" },
139 	{ CAP_FEXECVE,		"fe" },
140 	{ CAP_FSYNC,		"fy" },
141 	{ CAP_FTRUNCATE,	"ft" },
142 
143 	/* VFS methods. */
144 	{ CAP_FCHDIR,		"cd" },
145 	{ CAP_FCHFLAGS,		"cf" },
146 	{ CAP_FCHMOD,		"cm" },
147 	{ CAP_FCHOWN,		"cn" },
148 	{ CAP_FCNTL,		"fc" },
149 	{ CAP_FLOCK,		"fl" },
150 	{ CAP_FPATHCONF,	"fp" },
151 	{ CAP_FSCK,		"fk" },
152 	{ CAP_FSTAT,		"fs" },
153 	{ CAP_FSTATFS,		"sf" },
154 	{ CAP_FUTIMES,		"fu" },
155 	{ CAP_LINKAT_SOURCE,	"ls" },
156 	{ CAP_LINKAT_TARGET,	"lt" },
157 	{ CAP_MKDIRAT,		"md" },
158 	{ CAP_MKFIFOAT,		"mf" },
159 	{ CAP_MKNODAT,		"mn" },
160 	{ CAP_RENAMEAT_SOURCE,	"rs" },
161 	{ CAP_RENAMEAT_TARGET,	"rt" },
162 	{ CAP_SYMLINKAT,	"sl" },
163 	{ CAP_UNLINKAT,		"un" },
164 
165 	/* Lookups - used to constrain *at() calls. */
166 	{ CAP_LOOKUP,		"lo" },
167 
168 	/* Extended attributes. */
169 	{ CAP_EXTATTR_GET,	"eg" },
170 	{ CAP_EXTATTR_SET,	"es" },
171 	{ CAP_EXTATTR_DELETE,	"ed" },
172 	{ CAP_EXTATTR_LIST,	"el" },
173 
174 	/* Access Control Lists. */
175 	{ CAP_ACL_GET,		"ag" },
176 	{ CAP_ACL_SET,		"as" },
177 	{ CAP_ACL_DELETE,	"ad" },
178 	{ CAP_ACL_CHECK,	"ac" },
179 
180 	/* Socket operations. */
181 	{ CAP_ACCEPT,		"at" },
182 	{ CAP_BIND,		"bd" },
183 	{ CAP_CONNECT,		"co" },
184 	{ CAP_GETPEERNAME,	"pn" },
185 	{ CAP_GETSOCKNAME,	"sn" },
186 	{ CAP_GETSOCKOPT,	"gs" },
187 	{ CAP_LISTEN,		"ln" },
188 	{ CAP_PEELOFF,		"pf" },
189 	{ CAP_SETSOCKOPT,	"ss" },
190 	{ CAP_SHUTDOWN,		"sh" },
191 
192 	/* Mandatory Access Control. */
193 	{ CAP_MAC_GET,		"mg" },
194 	{ CAP_MAC_SET,		"ms" },
195 
196 	/* Methods on semaphores. */
197 	{ CAP_SEM_GETVALUE,	"sg" },
198 	{ CAP_SEM_POST,		"sp" },
199 	{ CAP_SEM_WAIT,		"sw" },
200 
201 	/* Event monitoring and posting. */
202 	{ CAP_EVENT,		"ev" },
203 	{ CAP_KQUEUE_EVENT,	"ke" },
204 	{ CAP_KQUEUE_CHANGE,	"kc" },
205 
206 	/* Strange and powerful rights that should not be given lightly. */
207 	{ CAP_IOCTL,		"io" },
208 	{ CAP_TTYHOOK,		"ty" },
209 
210 	/* Process management via process descriptors. */
211 	{ CAP_PDGETPID,		"pg" },
212 	{ CAP_PDWAIT,		"pw" },
213 	{ CAP_PDKILL,		"pk" },
214 
215 	/*
216 	 * Rights that allow to use bindat(2) and connectat(2) syscalls on a
217 	 * directory descriptor.
218 	 */
219 	{ CAP_BINDAT,		"ba" },
220 	{ CAP_CONNECTAT,	"ca" },
221 
222 	/* Aliases and defines that combine multiple rights. */
223 	{ CAP_PREAD,		"prd" },
224 	{ CAP_PWRITE,		"pwr" },
225 
226 	{ CAP_MMAP_R,		"mmr" },
227 	{ CAP_MMAP_W,		"mmw" },
228 	{ CAP_MMAP_X,		"mmx" },
229 	{ CAP_MMAP_RW,		"mrw" },
230 	{ CAP_MMAP_RX,		"mrx" },
231 	{ CAP_MMAP_WX,		"mwx" },
232 	{ CAP_MMAP_RWX,		"mma" },
233 
234 	{ CAP_RECV,		"re" },
235 	{ CAP_SEND,		"sd" },
236 
237 	{ CAP_SOCK_CLIENT,	"scl" },
238 	{ CAP_SOCK_SERVER,	"ssr" },
239 };
240 static const u_int	cap_desc_count = nitems(cap_desc);
241 
242 static u_int
243 width_capability(cap_rights_t *rightsp)
244 {
245 	u_int count, i, width;
246 
247 	count = 0;
248 	width = 0;
249 	for (i = 0; i < cap_desc_count; i++) {
250 		if (cap_rights_is_set(rightsp, cap_desc[i].cd_right)) {
251 			width += strlen(cap_desc[i].cd_desc);
252 			if (count)
253 				width++;
254 			count++;
255 		}
256 	}
257 	return (width);
258 }
259 
260 static void
261 print_capability(cap_rights_t *rightsp, u_int capwidth)
262 {
263 	u_int count, i, width;
264 
265 	count = 0;
266 	width = 0;
267 	for (i = width_capability(rightsp); i < capwidth; i++) {
268 		if (i != 0)
269 			xo_emit(" ");
270 		else
271 			xo_emit("-");
272 	}
273 	xo_open_list("capabilities");
274 	for (i = 0; i < cap_desc_count; i++) {
275 		if (cap_rights_is_set(rightsp, cap_desc[i].cd_right)) {
276 			xo_emit("{D:/%s}{l:capabilities/%s}", count ? "," : "",
277 			    cap_desc[i].cd_desc);
278 			width += strlen(cap_desc[i].cd_desc);
279 			if (count)
280 				width++;
281 			count++;
282 		}
283 	}
284 	xo_close_list("capabilities");
285 }
286 
287 void
288 procstat_files(struct procstat *procstat, struct kinfo_proc *kipp)
289 {
290 	struct sockstat sock;
291 	struct filestat_list *head;
292 	struct filestat *fst;
293 	const char *str;
294 	struct vnstat vn;
295 	u_int capwidth, width;
296 	int error;
297 	char src_addr[PATH_MAX];
298 	char dst_addr[PATH_MAX];
299 
300 	/*
301 	 * To print the header in capability mode, we need to know the width
302 	 * of the widest capability string.  Even if we get no processes
303 	 * back, we will print the header, so we defer aborting due to a lack
304 	 * of processes until after the header logic.
305 	 */
306 	capwidth = 0;
307 	head = procstat_getfiles(procstat, kipp, 0);
308 	if (head != NULL &&
309 	    (procstat_opts & PS_OPT_CAPABILITIES) != 0) {
310 		STAILQ_FOREACH(fst, head, next) {
311 			width = width_capability(&fst->fs_cap_rights);
312 			if (width > capwidth)
313 				capwidth = width;
314 		}
315 		if (capwidth < strlen("CAPABILITIES"))
316 			capwidth = strlen("CAPABILITIES");
317 	}
318 
319 	if ((procstat_opts & PS_OPT_NOHEADER) == 0) {
320 		if ((procstat_opts & PS_OPT_CAPABILITIES) != 0)
321 			xo_emit("{T:/%5s %-16s %5s %1s %-8s %-*s "
322 			    "%-3s %-12s}\n", "PID", "COMM", "FD", "T",
323 			    "FLAGS", capwidth, "CAPABILITIES", "PRO",
324 			    "NAME");
325 		else
326 			xo_emit("{T:/%5s %-16s %5s %1s %1s %-8s "
327 			    "%3s %7s %-3s %-12s}\n", "PID", "COMM", "FD", "T",
328 			    "V", "FLAGS", "REF", "OFFSET", "PRO", "NAME");
329 	}
330 
331 	if (head == NULL)
332 		return;
333 	xo_emit("{ek:process_id/%5d/%d}", kipp->ki_pid);
334 	xo_emit("{e:command/%-16s/%s}", kipp->ki_comm);
335 	xo_open_list("files");
336 	STAILQ_FOREACH(fst, head, next) {
337 		xo_open_instance("files");
338 		xo_emit("{dk:process_id/%5d/%d} ", kipp->ki_pid);
339 		xo_emit("{d:command/%-16s/%s} ", kipp->ki_comm);
340 		if (fst->fs_uflags & PS_FST_UFLAG_CTTY)
341 			xo_emit("{P: }{:fd/%s} ", "ctty");
342 		else if (fst->fs_uflags & PS_FST_UFLAG_CDIR)
343 			xo_emit("{P:  }{:fd/%s} ", "cwd");
344 		else if (fst->fs_uflags & PS_FST_UFLAG_JAIL)
345 			xo_emit("{P: }{:fd/%s} ", "jail");
346 		else if (fst->fs_uflags & PS_FST_UFLAG_RDIR)
347 			xo_emit("{P: }{:fd/%s} ", "root");
348 		else if (fst->fs_uflags & PS_FST_UFLAG_TEXT)
349 			xo_emit("{P: }{:fd/%s} ", "text");
350 		else if (fst->fs_uflags & PS_FST_UFLAG_TRACE)
351 			xo_emit("{:fd/%s} ", "trace");
352 		else
353 			xo_emit("{:fd/%5d} ", fst->fs_fd);
354 
355 		switch (fst->fs_type) {
356 		case PS_FST_TYPE_VNODE:
357 			str = "v";
358 			xo_emit("{eq:fd_type/vnode}");
359 			break;
360 
361 		case PS_FST_TYPE_SOCKET:
362 			str = "s";
363 			xo_emit("{eq:fd_type/socket}");
364 			break;
365 
366 		case PS_FST_TYPE_PIPE:
367 			str = "p";
368 			xo_emit("{eq:fd_type/pipe}");
369 			break;
370 
371 		case PS_FST_TYPE_FIFO:
372 			str = "f";
373 			xo_emit("{eq:fd_type/fifo}");
374 			break;
375 
376 		case PS_FST_TYPE_KQUEUE:
377 			str = "k";
378 			xo_emit("{eq:fd_type/kqueue}");
379 			break;
380 
381 		case PS_FST_TYPE_CRYPTO:
382 			str = "c";
383 			xo_emit("{eq:fd_type/crypto}");
384 			break;
385 
386 		case PS_FST_TYPE_MQUEUE:
387 			str = "m";
388 			xo_emit("{eq:fd_type/mqueue}");
389 			break;
390 
391 		case PS_FST_TYPE_SHM:
392 			str = "h";
393 			xo_emit("{eq:fd_type/shm}");
394 			break;
395 
396 		case PS_FST_TYPE_PTS:
397 			str = "t";
398 			xo_emit("{eq:fd_type/pts}");
399 			break;
400 
401 		case PS_FST_TYPE_SEM:
402 			str = "e";
403 			xo_emit("{eq:fd_type/sem}");
404 			break;
405 
406 		case PS_FST_TYPE_PROCDESC:
407 			str = "P";
408 			xo_emit("{eq:fd_type/procdesc}");
409 			break;
410 
411 		case PS_FST_TYPE_NONE:
412 			str = "?";
413 			xo_emit("{eq:fd_type/none}");
414 			break;
415 
416 		case PS_FST_TYPE_UNKNOWN:
417 		default:
418 			str = "?";
419 			xo_emit("{eq:fd_type/unknown}");
420 			break;
421 		}
422 		xo_emit("{d:fd_type/%1s/%s} ", str);
423 		if ((procstat_opts & PS_OPT_CAPABILITIES) == 0) {
424 			str = "-";
425 			if (fst->fs_type == PS_FST_TYPE_VNODE) {
426 				error = procstat_get_vnode_info(procstat, fst,
427 				    &vn, NULL);
428 				switch (vn.vn_type) {
429 				case PS_FST_VTYPE_VREG:
430 					str = "r";
431 					xo_emit("{eq:vode_type/regular}");
432 					break;
433 
434 				case PS_FST_VTYPE_VDIR:
435 					str = "d";
436 					xo_emit("{eq:vode_type/directory}");
437 					break;
438 
439 				case PS_FST_VTYPE_VBLK:
440 					str = "b";
441 					xo_emit("{eq:vode_type/block}");
442 					break;
443 
444 				case PS_FST_VTYPE_VCHR:
445 					str = "c";
446 					xo_emit("{eq:vode_type/character}");
447 					break;
448 
449 				case PS_FST_VTYPE_VLNK:
450 					str = "l";
451 					xo_emit("{eq:vode_type/link}");
452 					break;
453 
454 				case PS_FST_VTYPE_VSOCK:
455 					str = "s";
456 					xo_emit("{eq:vode_type/socket}");
457 					break;
458 
459 				case PS_FST_VTYPE_VFIFO:
460 					str = "f";
461 					xo_emit("{eq:vode_type/fifo}");
462 					break;
463 
464 				case PS_FST_VTYPE_VBAD:
465 					str = "x";
466 					xo_emit("{eq:vode_type/revoked_device}");
467 					break;
468 
469 				case PS_FST_VTYPE_VNON:
470 					str = "?";
471 					xo_emit("{eq:vode_type/non}");
472 					break;
473 
474 				case PS_FST_VTYPE_UNKNOWN:
475 				default:
476 					str = "?";
477 					xo_emit("{eq:vode_type/unknown}");
478 					break;
479 				}
480 			}
481 			xo_emit("{d:vnode_type/%1s/%s} ", str);
482 		}
483 
484 		xo_emit("{d:/%s}", fst->fs_fflags & PS_FST_FFLAG_READ ?
485 		    "r" : "-");
486 		xo_emit("{d:/%s}", fst->fs_fflags & PS_FST_FFLAG_WRITE ?
487 		    "w" : "-");
488 		xo_emit("{d:/%s}", fst->fs_fflags & PS_FST_FFLAG_APPEND ?
489 		    "a" : "-");
490 		xo_emit("{d:/%s}", fst->fs_fflags & PS_FST_FFLAG_ASYNC ?
491 		    "s" : "-");
492 		xo_emit("{d:/%s}", fst->fs_fflags & PS_FST_FFLAG_SYNC ?
493 		    "f" : "-");
494 		xo_emit("{d:/%s}", fst->fs_fflags & PS_FST_FFLAG_NONBLOCK ?
495 		    "n" : "-");
496 		xo_emit("{d:/%s}", fst->fs_fflags & PS_FST_FFLAG_DIRECT ?
497 		    "d" : "-");
498 		xo_emit("{d:/%s}", fst->fs_fflags & PS_FST_FFLAG_HASLOCK ?
499 		    "l" : "-");
500 		xo_emit(" ");
501 		xo_open_list("fd_flags");
502 		if (fst->fs_fflags & PS_FST_FFLAG_READ)
503 			xo_emit("{elq:fd_flags/read}");
504 		if (fst->fs_fflags & PS_FST_FFLAG_WRITE)
505 			xo_emit("{elq:fd_flags/write}");
506 		if (fst->fs_fflags & PS_FST_FFLAG_APPEND)
507 			xo_emit("{elq:fd_flags/append}");
508 		if (fst->fs_fflags & PS_FST_FFLAG_ASYNC)
509 			xo_emit("{elq:fd_flags/async}");
510 		if (fst->fs_fflags & PS_FST_FFLAG_SYNC)
511 			xo_emit("{elq:fd_flags/fsync}");
512 		if (fst->fs_fflags & PS_FST_FFLAG_NONBLOCK)
513 			xo_emit("{elq:fd_flags/nonblocking}");
514 		if (fst->fs_fflags & PS_FST_FFLAG_DIRECT)
515 			xo_emit("{elq:fd_flags/direct_io}");
516 		if (fst->fs_fflags & PS_FST_FFLAG_HASLOCK)
517 			xo_emit("{elq:fd_flags/lock_held}");
518 		xo_close_list("fd_flags");
519 
520 		if ((procstat_opts & PS_OPT_CAPABILITIES) == 0) {
521 			if (fst->fs_ref_count > -1)
522 				xo_emit("{:ref_count/%3d/%d} ",
523 				    fst->fs_ref_count);
524 			else
525 				xo_emit("{q:ref_count/%3c/%c} ", '-');
526 			if (fst->fs_offset > -1)
527 				xo_emit("{:offset/%7jd/%jd} ",
528 				    (intmax_t)fst->fs_offset);
529 			else
530 				xo_emit("{q:offset/%7c/%c} ", '-');
531 		}
532 		if ((procstat_opts & PS_OPT_CAPABILITIES) != 0) {
533 			print_capability(&fst->fs_cap_rights, capwidth);
534 			xo_emit(" ");
535 		}
536 		switch (fst->fs_type) {
537 		case PS_FST_TYPE_SOCKET:
538 			error = procstat_get_socket_info(procstat, fst, &sock,
539 			    NULL);
540 			if (error != 0)
541 				break;
542 			xo_emit("{:protocol/%-3s/%s} ",
543 			    protocol_to_string(sock.dom_family,
544 			    sock.type, sock.proto));
545 			if (sock.proto == IPPROTO_TCP ||
546 			    sock.proto == IPPROTO_SCTP ||
547 			    sock.type == SOCK_STREAM) {
548 				xo_emit("{:sendq/%u} ", sock.sendq);
549 				xo_emit("{:recvq/%u} ", sock.recvq);
550 			}
551 			/*
552 			 * While generally we like to print two addresses,
553 			 * local and peer, for sockets, it turns out to be
554 			 * more useful to print the first non-nul address for
555 			 * local sockets, as typically they aren't bound and
556 			 *  connected, and the path strings can get long.
557 			 */
558 			if (sock.dom_family == AF_LOCAL) {
559 				struct sockaddr_un *sun =
560 				    (struct sockaddr_un *)&sock.sa_local;
561 
562 				if (sun->sun_path[0] != 0)
563 					addr_to_string(&sock.sa_local,
564 					    src_addr, sizeof(src_addr));
565 				else
566 					addr_to_string(&sock.sa_peer,
567 					    src_addr, sizeof(src_addr));
568 				xo_emit("{:path/%s}", src_addr);
569 			} else {
570 				addr_to_string(&sock.sa_local, src_addr,
571 				    sizeof(src_addr));
572 				addr_to_string(&sock.sa_peer, dst_addr,
573 				    sizeof(dst_addr));
574 				xo_emit("{:path/%s %s}", src_addr, dst_addr);
575 			}
576 			break;
577 
578 		default:
579 			xo_emit("{:protocol/%-3s/%s} ", "-");
580 			xo_emit("{:path/%-18s/%s}", fst->fs_path != NULL ?
581 			    fst->fs_path : "-");
582 		}
583 
584 		xo_emit("\n");
585 		xo_close_instance("files");
586 	}
587 	xo_close_list("files");
588 	procstat_freefiles(procstat, head);
589 }
590