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