xref: /freebsd/usr.sbin/jls/jls.c (revision 40a8ac8f62b535d30349faf28cf47106b7041b83)
1 /*-
2  * Copyright (c) 2003 Mike Barcroft <mike@FreeBSD.org>
3  * Copyright (c) 2008 Bjoern A. Zeeb <bz@FreeBSD.org>
4  * Copyright (c) 2009 James Gritton <jamie@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/jail.h>
34 #include <sys/socket.h>
35 #include <sys/sysctl.h>
36 
37 #include <arpa/inet.h>
38 #include <netinet/in.h>
39 
40 #include <err.h>
41 #include <errno.h>
42 #include <jail.h>
43 #include <limits.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48 
49 #define	JP_USER		0x01000000
50 #define	JP_OPT		0x02000000
51 
52 #define	PRINT_DEFAULT	0x01
53 #define	PRINT_HEADER	0x02
54 #define	PRINT_NAMEVAL	0x04
55 #define	PRINT_QUOTED	0x08
56 #define	PRINT_SKIP	0x10
57 #define	PRINT_VERBOSE	0x20
58 #define	PRINT_JAIL_NAME	0x40
59 
60 static struct jailparam *params;
61 static int *param_parent;
62 static int nparams;
63 #ifdef INET6
64 static int ip6_ok;
65 #endif
66 #ifdef INET
67 static int ip4_ok;
68 #endif
69 
70 static int add_param(const char *name, void *value, size_t valuelen,
71 		struct jailparam *source, unsigned flags);
72 static int sort_param(const void *a, const void *b);
73 static char *noname(const char *name);
74 static char *nononame(const char *name);
75 static int print_jail(int pflags, int jflags);
76 static void quoted_print(char *str);
77 
78 int
79 main(int argc, char **argv)
80 {
81 	char *dot, *ep, *jname;
82 	int c, i, jflags, jid, lastjid, pflags, spc;
83 
84 	jname = NULL;
85 	pflags = jflags = jid = 0;
86 	while ((c = getopt(argc, argv, "adj:hNnqsv")) >= 0)
87 		switch (c) {
88 		case 'a':
89 		case 'd':
90 			jflags |= JAIL_DYING;
91 			break;
92 		case 'j':
93 			jid = strtoul(optarg, &ep, 10);
94 			if (!jid || *ep) {
95 				jid = 0;
96 				jname = optarg;
97 			}
98 			break;
99 		case 'h':
100 			pflags = (pflags & ~(PRINT_SKIP | PRINT_VERBOSE)) |
101 			    PRINT_HEADER;
102 			break;
103 		case 'N':
104 			pflags |= PRINT_JAIL_NAME;
105 			break;
106 		case 'n':
107 			pflags = (pflags & ~PRINT_VERBOSE) | PRINT_NAMEVAL;
108 			break;
109 		case 'q':
110 			pflags |= PRINT_QUOTED;
111 			break;
112 		case 's':
113 			pflags = (pflags & ~(PRINT_HEADER | PRINT_VERBOSE)) |
114 			    PRINT_NAMEVAL | PRINT_QUOTED | PRINT_SKIP;
115 			break;
116 		case 'v':
117 			pflags = (pflags &
118 			    ~(PRINT_HEADER | PRINT_NAMEVAL | PRINT_SKIP)) |
119 			    PRINT_VERBOSE;
120 			break;
121 		default:
122 			errx(1, "usage: jls [-dhNnqv] [-j jail] [param ...]");
123 		}
124 
125 #ifdef INET6
126 	ip6_ok = feature_present("inet6");
127 #endif
128 #ifdef INET
129 	ip4_ok = feature_present("inet");
130 #endif
131 
132 	/* Add the parameters to print. */
133 	if (optind == argc) {
134 		if (pflags & (PRINT_HEADER | PRINT_NAMEVAL))
135 			add_param("all", NULL, (size_t)0, NULL, JP_USER);
136 		else if (pflags & PRINT_VERBOSE) {
137 			add_param("jid", NULL, (size_t)0, NULL, JP_USER);
138 			add_param("host.hostname", NULL, (size_t)0, NULL,
139 			    JP_USER);
140 			add_param("path", NULL, (size_t)0, NULL, JP_USER);
141 			add_param("name", NULL, (size_t)0, NULL, JP_USER);
142 			add_param("dying", NULL, (size_t)0, NULL, JP_USER);
143 			add_param("cpuset.id", NULL, (size_t)0, NULL, JP_USER);
144 #ifdef INET
145 			if (ip4_ok)
146 				add_param("ip4.addr", NULL, (size_t)0, NULL,
147 				    JP_USER);
148 #endif
149 #ifdef INET6
150 			if (ip6_ok)
151 				add_param("ip6.addr", NULL, (size_t)0, NULL,
152 				    JP_USER | JP_OPT);
153 #endif
154 		} else {
155 			pflags |= PRINT_DEFAULT;
156 			if (pflags & PRINT_JAIL_NAME)
157 				add_param("name", NULL, (size_t)0, NULL, JP_USER);
158 			else
159 				add_param("jid", NULL, (size_t)0, NULL, JP_USER);
160 #ifdef INET
161 			if (ip4_ok)
162 				add_param("ip4.addr", NULL, (size_t)0, NULL,
163 				    JP_USER);
164 #endif
165 			add_param("host.hostname", NULL, (size_t)0, NULL,
166 			    JP_USER);
167 			add_param("path", NULL, (size_t)0, NULL, JP_USER);
168 		}
169 	} else
170 		while (optind < argc)
171 			add_param(argv[optind++], NULL, (size_t)0, NULL,
172 			    JP_USER);
173 
174 	if (pflags & PRINT_SKIP) {
175 		/* Check for parameters with jailsys parents. */
176 		for (i = 0; i < nparams; i++) {
177 			if ((params[i].jp_flags & JP_USER) &&
178 			    (dot = strchr(params[i].jp_name, '.'))) {
179 				*dot = 0;
180 				param_parent[i] = add_param(params[i].jp_name,
181 				    NULL, (size_t)0, NULL, JP_OPT);
182 				*dot = '.';
183 			}
184 		}
185 	}
186 
187 	/* Add the index key parameters. */
188 	if (jid != 0)
189 		add_param("jid", &jid, sizeof(jid), NULL, 0);
190 	else if (jname != NULL)
191 		add_param("name", jname, strlen(jname), NULL, 0);
192 	else
193 		add_param("lastjid", &lastjid, sizeof(lastjid), NULL, 0);
194 
195 	/* Print a header line if requested. */
196 	if (pflags & PRINT_VERBOSE)
197 		printf("   JID  Hostname                      Path\n"
198 		       "        Name                          State\n"
199 		       "        CPUSetID\n"
200 		       "        IP Address(es)\n");
201 	else if (pflags & PRINT_DEFAULT)
202 		if (pflags & PRINT_JAIL_NAME)
203 			printf(" JID             IP Address      "
204 			    "Hostname                      Path\n");
205 		else
206 			printf("   JID  IP Address      "
207 			    "Hostname                      Path\n");
208 	else if (pflags & PRINT_HEADER) {
209 		for (i = spc = 0; i < nparams; i++)
210 			if (params[i].jp_flags & JP_USER) {
211 				if (spc)
212 					putchar(' ');
213 				else
214 					spc = 1;
215 				fputs(params[i].jp_name, stdout);
216 			}
217 		putchar('\n');
218 	}
219 
220 	/* Fetch the jail(s) and print the paramters. */
221 	if (jid != 0 || jname != NULL) {
222 		if (print_jail(pflags, jflags) < 0)
223 			errx(1, "%s", jail_errmsg);
224 	} else {
225 		for (lastjid = 0;
226 		     (lastjid = print_jail(pflags, jflags)) >= 0; )
227 			;
228 		if (errno != 0 && errno != ENOENT)
229 			errx(1, "%s", jail_errmsg);
230 	}
231 
232 	return (0);
233 }
234 
235 static int
236 add_param(const char *name, void *value, size_t valuelen,
237     struct jailparam *source, unsigned flags)
238 {
239 	struct jailparam *param, *tparams;
240 	int i, tnparams;
241 
242 	static int paramlistsize;
243 
244 	/* The pseudo-parameter "all" scans the list of available parameters. */
245 	if (!strcmp(name, "all")) {
246 		tnparams = jailparam_all(&tparams);
247 		if (tnparams < 0)
248 			errx(1, "%s", jail_errmsg);
249 		qsort(tparams, (size_t)tnparams, sizeof(struct jailparam),
250 		    sort_param);
251 		for (i = 0; i < tnparams; i++)
252 			add_param(tparams[i].jp_name, NULL, (size_t)0,
253 			    tparams + i, flags);
254 		free(tparams);
255 		return -1;
256 	}
257 
258 	/* Check for repeat parameters. */
259 	for (i = 0; i < nparams; i++)
260 		if (!strcmp(name, params[i].jp_name)) {
261 			if (value != NULL && jailparam_import_raw(params + i,
262 			    value, valuelen) < 0)
263 				errx(1, "%s", jail_errmsg);
264 			params[i].jp_flags |= flags;
265 			if (source != NULL)
266 				jailparam_free(source, 1);
267 			return i;
268 		}
269 
270 	/* Make sure there is room for the new param record. */
271 	if (!nparams) {
272 		paramlistsize = 32;
273 		params = malloc(paramlistsize * sizeof(*params));
274 		param_parent = malloc(paramlistsize * sizeof(*param_parent));
275 		if (params == NULL || param_parent == NULL)
276 			err(1, "malloc");
277 	} else if (nparams >= paramlistsize) {
278 		paramlistsize *= 2;
279 		params = realloc(params, paramlistsize * sizeof(*params));
280 		param_parent = realloc(param_parent,
281 		    paramlistsize * sizeof(*param_parent));
282 		if (params == NULL || param_parent == NULL)
283 			err(1, "realloc");
284 	}
285 
286 	/* Look up the parameter. */
287 	param_parent[nparams] = -1;
288 	param = params + nparams++;
289 	if (source != NULL) {
290 		*param = *source;
291 		param->jp_flags |= flags;
292 		return param - params;
293 	}
294 	if (jailparam_init(param, name) < 0)
295 		errx(1, "%s", jail_errmsg);
296 	param->jp_flags = flags;
297 	if ((value != NULL ? jailparam_import_raw(param, value, valuelen)
298 	     : jailparam_import(param, value)) < 0) {
299 		if (flags & JP_OPT) {
300 			nparams--;
301 			return (-1);
302 		}
303 		errx(1, "%s", jail_errmsg);
304 	}
305 	return param - params;
306 }
307 
308 static int
309 sort_param(const void *a, const void *b)
310 {
311 	const struct jailparam *parama, *paramb;
312 	char *ap, *bp;
313 
314 	/* Put top-level parameters first. */
315 	parama = a;
316 	paramb = b;
317 	ap = strchr(parama->jp_name, '.');
318 	bp = strchr(paramb->jp_name, '.');
319 	if (ap && !bp)
320 		return (1);
321 	if (bp && !ap)
322 		return (-1);
323 	return (strcmp(parama->jp_name, paramb->jp_name));
324 }
325 
326 static char *
327 noname(const char *name)
328 {
329 	char *nname, *p;
330 
331 	nname = malloc(strlen(name) + 3);
332 	if (nname == NULL)
333 		err(1, "malloc");
334 	p = strrchr(name, '.');
335 	if (p != NULL)
336 		sprintf(nname, "%.*s.no%s", (int)(p - name), name, p + 1);
337 	else
338 		sprintf(nname, "no%s", name);
339 	return nname;
340 }
341 
342 static char *
343 nononame(const char *name)
344 {
345 	char *nname, *p;
346 
347 	p = strrchr(name, '.');
348 	if (strncmp(p ? p + 1 : name, "no", 2))
349 		return NULL;
350 	nname = malloc(strlen(name) - 1);
351 	if (nname == NULL)
352 		err(1, "malloc");
353 	if (p != NULL)
354 		sprintf(nname, "%.*s.%s", (int)(p - name), name, p + 3);
355 	else
356 		strcpy(nname, name + 2);
357 	return nname;
358 }
359 
360 static int
361 print_jail(int pflags, int jflags)
362 {
363 	char *nname;
364 	char **param_values;
365 	int i, ai, jid, count, n, spc;
366 	char ipbuf[INET6_ADDRSTRLEN];
367 
368 	jid = jailparam_get(params, nparams, jflags);
369 	if (jid < 0)
370 		return jid;
371 	if (pflags & PRINT_VERBOSE) {
372 		printf("%6d  %-29.29s %.74s\n"
373 		       "%6s  %-29.29s %.74s\n"
374 		       "%6s  %-6d\n",
375 		    *(int *)params[0].jp_value,
376 		    (char *)params[1].jp_value,
377 		    (char *)params[2].jp_value,
378 		    "",
379 		    (char *)params[3].jp_value,
380 		    *(int *)params[4].jp_value ? "DYING" : "ACTIVE",
381 		    "",
382 		    *(int *)params[5].jp_value);
383 		n = 6;
384 #ifdef INET
385 		if (ip4_ok && !strcmp(params[n].jp_name, "ip4.addr")) {
386 			count = params[n].jp_valuelen / sizeof(struct in_addr);
387 			for (ai = 0; ai < count; ai++)
388 				if (inet_ntop(AF_INET,
389 				    &((struct in_addr *)params[n].jp_value)[ai],
390 				    ipbuf, sizeof(ipbuf)) == NULL)
391 					err(1, "inet_ntop");
392 				else
393 					printf("%6s  %-15.15s\n", "", ipbuf);
394 			n++;
395 		}
396 #endif
397 #ifdef INET6
398 		if (ip6_ok && !strcmp(params[n].jp_name, "ip6.addr")) {
399 			count = params[n].jp_valuelen / sizeof(struct in6_addr);
400 			for (ai = 0; ai < count; ai++)
401 				if (inet_ntop(AF_INET6,
402 				    &((struct in6_addr *)
403 					params[n].jp_value)[ai],
404 				    ipbuf, sizeof(ipbuf)) == NULL)
405 					err(1, "inet_ntop");
406 				else
407 					printf("%6s  %s\n", "", ipbuf);
408 			n++;
409 		}
410 #endif
411 	} else if (pflags & PRINT_DEFAULT) {
412 		if (pflags & PRINT_JAIL_NAME)
413 			printf(" %-15s ", (char *)params[0].jp_value);
414 		else
415 			printf("%6d  ", *(int *)params[0].jp_value);
416 		printf("%-15.15s %-29.29s %.74s\n",
417 #ifdef INET
418 		    (!ip4_ok || params[1].jp_valuelen == 0) ? "-"
419 		    : inet_ntoa(*(struct in_addr *)params[1].jp_value),
420 		    (char *)params[2-!ip4_ok].jp_value,
421 		    (char *)params[3-!ip4_ok].jp_value);
422 #else
423 		    "-",
424 		    (char *)params[1].jp_value,
425 		    (char *)params[2].jp_value);
426 #endif
427 	} else {
428 		param_values = alloca(nparams * sizeof(*param_values));
429 		for (i = 0; i < nparams; i++) {
430 			if (!(params[i].jp_flags & JP_USER))
431 				continue;
432 			param_values[i] = jailparam_export(params + i);
433 			if (param_values[i] == NULL)
434 				errx(1, "%s", jail_errmsg);
435 		}
436 		for (i = spc = 0; i < nparams; i++) {
437 			if (!(params[i].jp_flags & JP_USER))
438 				continue;
439 			if ((pflags & PRINT_SKIP) &&
440 			    ((!(params[i].jp_ctltype &
441 				(CTLFLAG_WR | CTLFLAG_TUN))) ||
442 			     (param_parent[i] >= 0 &&
443 			      *(int *)params[param_parent[i]].jp_value !=
444 			      JAIL_SYS_NEW)))
445 				continue;
446 			if (spc)
447 				putchar(' ');
448 			else
449 				spc = 1;
450 			if (pflags & PRINT_NAMEVAL) {
451 				/*
452 				 * Generally "name=value", but for booleans
453 				 * either "name" or "noname".
454 				 */
455 				if (params[i].jp_flags &
456 				    (JP_BOOL | JP_NOBOOL)) {
457 					if (*(int *)params[i].jp_value)
458 						printf("%s", params[i].jp_name);
459 					else {
460 						nname = (params[i].jp_flags &
461 						    JP_NOBOOL) ?
462 						    nononame(params[i].jp_name)
463 						    : noname(params[i].jp_name);
464 						printf("%s", nname);
465 						free(nname);
466 					}
467 					continue;
468 				}
469 				printf("%s=", params[i].jp_name);
470 			}
471 			if (params[i].jp_valuelen == 0) {
472 				if (pflags & PRINT_QUOTED)
473 					printf("\"\"");
474 				else if (!(pflags & PRINT_NAMEVAL))
475 					putchar('-');
476 			} else
477 				quoted_print(param_values[i]);
478 		}
479 		putchar('\n');
480 		for (i = 0; i < nparams; i++)
481 			if (params[i].jp_flags & JP_USER)
482 				free(param_values[i]);
483 	}
484 	return (jid);
485 }
486 
487 static void
488 quoted_print(char *str)
489 {
490 	int c, qc;
491 	char *p = str;
492 
493 	/* An empty string needs quoting. */
494 	if (!*p) {
495 		fputs("\"\"", stdout);
496 		return;
497 	}
498 
499 	/*
500 	 * The value will be surrounded by quotes if it contains spaces
501 	 * or quotes.
502 	 */
503 	qc = strchr(p, '\'') ? '"'
504 	    : strchr(p, '"') ? '\''
505 	    : strchr(p, ' ') || strchr(p, '\t') ? '"'
506 	    : 0;
507 	if (qc)
508 		putchar(qc);
509 	while ((c = *p++)) {
510 		if (c == '\\' || c == qc)
511 			putchar('\\');
512 		putchar(c);
513 	}
514 	if (qc)
515 		putchar(qc);
516 }
517