xref: /freebsd/usr.sbin/jail/jail.c (revision 2284664ef9fcb0baaf59f1ef7df877c0b0f2b187)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 1999 Poul-Henning Kamp.
5  * Copyright (c) 2009-2012 James Gritton
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 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <sys/socket.h>
36 #include <sys/sysctl.h>
37 
38 #include <arpa/inet.h>
39 #include <netinet/in.h>
40 
41 #include <err.h>
42 #include <errno.h>
43 #include <stdarg.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48 
49 #include "jailp.h"
50 
51 #define JP_RDTUN(jp)	(((jp)->jp_ctltype & CTLFLAG_RDTUN) == CTLFLAG_RDTUN)
52 
53 struct permspec {
54 	const char	*name;
55 	enum intparam	ipnum;
56 	int		rev;
57 };
58 
59 const char *cfname;
60 int iflag;
61 int note_remove;
62 int verbose;
63 
64 static void clear_persist(struct cfjail *j);
65 static int update_jail(struct cfjail *j);
66 static int rdtun_params(struct cfjail *j, int dofail);
67 static void running_jid(struct cfjail *j, int dflag);
68 static void jail_quoted_warnx(const struct cfjail *j, const char *name_msg,
69     const char *noname_msg);
70 static int jailparam_set_note(const struct cfjail *j, struct jailparam *jp,
71     unsigned njp, int flags);
72 static void print_jail(FILE *fp, struct cfjail *j, int oldcl);
73 static void print_param(FILE *fp, const struct cfparam *p, int sep, int doname);
74 static void quoted_print(FILE *fp, char *str);
75 static void usage(void);
76 
77 static struct permspec perm_sysctl[] = {
78     { "security.jail.set_hostname_allowed", KP_ALLOW_SET_HOSTNAME, 0 },
79     { "security.jail.sysvipc_allowed", KP_ALLOW_SYSVIPC, 0 },
80     { "security.jail.allow_raw_sockets", KP_ALLOW_RAW_SOCKETS, 0 },
81     { "security.jail.chflags_allowed", KP_ALLOW_CHFLAGS, 0 },
82     { "security.jail.mount_allowed", KP_ALLOW_MOUNT, 0 },
83     { "security.jail.socket_unixiproute_only", KP_ALLOW_SOCKET_AF, 1 },
84 };
85 
86 static const enum intparam startcommands[] = {
87     IP__NULL,
88 #ifdef INET
89     IP__IP4_IFADDR,
90 #endif
91 #ifdef INET6
92     IP__IP6_IFADDR,
93 #endif
94     IP_MOUNT,
95     IP__MOUNT_FROM_FSTAB,
96     IP_MOUNT_DEVFS,
97     IP_MOUNT_FDESCFS,
98     IP_MOUNT_PROCFS,
99     IP_EXEC_PRESTART,
100     IP__OP,
101     IP_EXEC_CREATED,
102     IP_VNET_INTERFACE,
103     IP_EXEC_START,
104     IP_COMMAND,
105     IP_EXEC_POSTSTART,
106     IP__NULL
107 };
108 
109 static const enum intparam stopcommands[] = {
110     IP__NULL,
111     IP_EXEC_PRESTOP,
112     IP_EXEC_STOP,
113     IP_STOP_TIMEOUT,
114     IP__OP,
115     IP_EXEC_POSTSTOP,
116     IP_MOUNT_PROCFS,
117     IP_MOUNT_FDESCFS,
118     IP_MOUNT_DEVFS,
119     IP__MOUNT_FROM_FSTAB,
120     IP_MOUNT,
121 #ifdef INET6
122     IP__IP6_IFADDR,
123 #endif
124 #ifdef INET
125     IP__IP4_IFADDR,
126 #endif
127     IP__NULL
128 };
129 
130 int
131 main(int argc, char **argv)
132 {
133 	struct stat st;
134 	FILE *jfp;
135 	struct cfjail *j;
136 	char *JidFile;
137 	size_t sysvallen;
138 	unsigned op, pi;
139 	int ch, docf, error, i, oldcl, sysval;
140 	int dflag, Rflag;
141 #if defined(INET) || defined(INET6)
142 	char *cs, *ncs;
143 #endif
144 #if defined(INET) && defined(INET6)
145 	struct in6_addr addr6;
146 #endif
147 
148 	op = 0;
149 	dflag = Rflag = 0;
150 	docf = 1;
151 	cfname = CONF_FILE;
152 	JidFile = NULL;
153 
154 	while ((ch = getopt(argc, argv, "cdf:hiJ:lmn:p:qrRs:u:U:v")) != -1) {
155 		switch (ch) {
156 		case 'c':
157 			op |= JF_START;
158 			break;
159 		case 'd':
160 			dflag = 1;
161 			break;
162 		case 'f':
163 			cfname = optarg;
164 			break;
165 		case 'h':
166 #if defined(INET) || defined(INET6)
167 			add_param(NULL, NULL, IP_IP_HOSTNAME, NULL);
168 #endif
169 			docf = 0;
170 			break;
171 		case 'i':
172 			iflag = 1;
173 			verbose = -1;
174 			break;
175 		case 'J':
176 			JidFile = optarg;
177 			break;
178 		case 'l':
179 			add_param(NULL, NULL, IP_EXEC_CLEAN, NULL);
180 			docf = 0;
181 			break;
182 		case 'm':
183 			op |= JF_SET;
184 			break;
185 		case 'n':
186 			add_param(NULL, NULL, KP_NAME, optarg);
187 			docf = 0;
188 			break;
189 		case 'p':
190 			paralimit = strtol(optarg, NULL, 10);
191 			if (paralimit == 0)
192 				paralimit = -1;
193 			break;
194 		case 'q':
195 			verbose = -1;
196 			break;
197 		case 'r':
198 			op |= JF_STOP;
199 			break;
200 		case 'R':
201 			op |= JF_STOP;
202 			Rflag = 1;
203 			break;
204 		case 's':
205 			add_param(NULL, NULL, KP_SECURELEVEL, optarg);
206 			docf = 0;
207 			break;
208 		case 'u':
209 			add_param(NULL, NULL, IP_EXEC_JAIL_USER, optarg);
210 			add_param(NULL, NULL, IP_EXEC_SYSTEM_JAIL_USER, NULL);
211 			docf = 0;
212 			break;
213 		case 'U':
214 			add_param(NULL, NULL, IP_EXEC_JAIL_USER, optarg);
215 			add_param(NULL, NULL, IP_EXEC_SYSTEM_JAIL_USER,
216 			    "false");
217 			docf = 0;
218 			break;
219 		case 'v':
220 			verbose = 1;
221 			break;
222 		default:
223 			usage();
224 		}
225 	}
226 	argc -= optind;
227 	argv += optind;
228 
229 	/* Find out which of the four command line styles this is. */
230 	oldcl = 0;
231 	if (!op) {
232 		/* Old-style command line with four fixed parameters */
233 		if (argc < 4 || argv[0][0] != '/')
234 			usage();
235 		op = JF_START;
236 		docf = 0;
237 		oldcl = 1;
238 		add_param(NULL, NULL, KP_PATH, argv[0]);
239 		add_param(NULL, NULL, KP_HOST_HOSTNAME, argv[1]);
240 #if defined(INET) || defined(INET6)
241 		if (argv[2][0] != '\0') {
242 			for (cs = argv[2];; cs = ncs + 1) {
243 				ncs = strchr(cs, ',');
244 				if (ncs)
245 					*ncs = '\0';
246 				add_param(NULL, NULL,
247 #if defined(INET) && defined(INET6)
248 				    inet_pton(AF_INET6, cs, &addr6) == 1
249 				    ? KP_IP6_ADDR : KP_IP4_ADDR,
250 #elif defined(INET)
251 				    KP_IP4_ADDR,
252 #elif defined(INET6)
253 				    KP_IP6_ADDR,
254 #endif
255 				    cs);
256 				if (!ncs)
257 					break;
258 			}
259 		}
260 #endif
261 		for (i = 3; i < argc; i++)
262 			add_param(NULL, NULL, IP_COMMAND, argv[i]);
263 		/* Emulate the defaults from security.jail.* sysctls. */
264 		sysvallen = sizeof(sysval);
265 		if (sysctlbyname("security.jail.jailed", &sysval, &sysvallen,
266 		    NULL, 0) == 0 && sysval == 0) {
267 			for (pi = 0; pi < sizeof(perm_sysctl) /
268 			     sizeof(perm_sysctl[0]); pi++) {
269 				sysvallen = sizeof(sysval);
270 				if (sysctlbyname(perm_sysctl[pi].name,
271 				    &sysval, &sysvallen, NULL, 0) == 0)
272 					add_param(NULL, NULL,
273 					    perm_sysctl[pi].ipnum,
274 					    (sysval ? 1 : 0) ^
275 					    perm_sysctl[pi].rev
276 					    ? NULL : "false");
277 			}
278 		}
279 	} else if (op == JF_STOP) {
280 		/* Jail remove, perhaps using the config file */
281 		if (!docf || argc == 0)
282 			usage();
283 		if (!Rflag)
284 			for (i = 0; i < argc; i++)
285 				if (strchr(argv[i], '='))
286 					usage();
287 		if ((docf = !Rflag &&
288 		     (!strcmp(cfname, "-") || stat(cfname, &st) == 0)))
289 			load_config();
290 		note_remove = docf || argc > 1 || wild_jail_name(argv[0]);
291 	} else if (argc > 1 || (argc == 1 && strchr(argv[0], '='))) {
292 		/* Single jail specified on the command line */
293 		if (Rflag)
294 			usage();
295 		docf = 0;
296 		for (i = 0; i < argc; i++) {
297 			if (!strncmp(argv[i], "command", 7) &&
298 			    (argv[i][7] == '\0' || argv[i][7] == '=')) {
299 				if (argv[i][7]  == '=')
300 					add_param(NULL, NULL, IP_COMMAND,
301 					    argv[i] + 8);
302 				for (i++; i < argc; i++)
303 					add_param(NULL, NULL, IP_COMMAND,
304 					    argv[i]);
305 			}
306 #ifdef INET
307 			else if (!strncmp(argv[i], "ip4.addr=", 9)) {
308 				for (cs = argv[i] + 9;; cs = ncs + 1) {
309 					ncs = strchr(cs, ',');
310 					if (ncs)
311 						*ncs = '\0';
312 					add_param(NULL, NULL, KP_IP4_ADDR, cs);
313 					if (!ncs)
314 						break;
315 				}
316 			}
317 #endif
318 #ifdef INET6
319 			else if (!strncmp(argv[i], "ip6.addr=", 9)) {
320 				for (cs = argv[i] + 9;; cs = ncs + 1) {
321 					ncs = strchr(cs, ',');
322 					if (ncs)
323 						*ncs = '\0';
324 					add_param(NULL, NULL, KP_IP6_ADDR, cs);
325 					if (!ncs)
326 						break;
327 				}
328 			}
329 #endif
330 			else
331 				add_param(NULL, NULL, 0, argv[i]);
332 		}
333 	} else {
334 		/* From the config file, perhaps with a specified jail */
335 		if (Rflag || !docf)
336 			usage();
337 		load_config();
338 	}
339 
340 	/* Find out which jails will be run. */
341 	dep_setup(docf);
342 	error = 0;
343 	if (op == JF_STOP) {
344 		for (i = 0; i < argc; i++)
345 			if (start_state(argv[i], docf, op, Rflag) < 0)
346 				error = 1;
347 	} else {
348 		if (start_state(argv[0], docf, op, 0) < 0)
349 			exit(1);
350 	}
351 
352 	jfp = NULL;
353 	if (JidFile != NULL) {
354 		jfp = fopen(JidFile, "w");
355 		if (jfp == NULL)
356 			err(1, "open %s", JidFile);
357 		setlinebuf(jfp);
358 	}
359 	setlinebuf(stdout);
360 
361 	/*
362 	 * The main loop: Get an available jail and perform the required
363 	 * operation on it.  When that is done, the jail may be finished,
364 	 * or it may go back for the next step.
365 	 */
366 	while ((j = next_jail()))
367 	{
368 		if (j->flags & JF_FAILED) {
369 			error = 1;
370 			if (j->comparam == NULL) {
371 				dep_done(j, 0);
372 				continue;
373 			}
374 		}
375 		if (!(j->flags & JF_PARAMS))
376 		{
377 			j->flags |= JF_PARAMS;
378 			if (dflag)
379 				add_param(j, NULL, IP_ALLOW_DYING, NULL);
380 			if (check_intparams(j) < 0)
381 				continue;
382 			if ((j->flags & (JF_START | JF_SET)) &&
383 			    import_params(j) < 0)
384 				continue;
385 		}
386 		if (!j->jid)
387 			running_jid(j,
388 			    (j->flags & (JF_SET | JF_DEPEND)) == JF_SET
389 			    ? dflag || bool_param(j->intparams[IP_ALLOW_DYING])
390 			    : 0);
391 		if (finish_command(j))
392 			continue;
393 
394 		switch (j->flags & JF_OP_MASK) {
395 			/*
396 			 * These operations just turn into a different op
397 			 * depending on the jail's current status.
398 			 */
399 		case JF_START_SET:
400 			j->flags = j->jid < 0 ? JF_START : JF_SET;
401 			break;
402 		case JF_SET_RESTART:
403 			if (j->jid < 0) {
404 				jail_quoted_warnx(j, "not found",
405 				    "no jail specified");
406 				failed(j);
407 				continue;
408 			}
409 			j->flags = rdtun_params(j, 0) ? JF_RESTART : JF_SET;
410 			if (j->flags == JF_RESTART)
411 				dep_reset(j);
412 			break;
413 		case JF_START_SET_RESTART:
414 			j->flags = j->jid < 0 ? JF_START
415 			    : rdtun_params(j, 0) ? JF_RESTART : JF_SET;
416 			if (j->flags == JF_RESTART)
417 				dep_reset(j);
418 		}
419 
420 		switch (j->flags & JF_OP_MASK) {
421 		case JF_START:
422 			if (j->comparam == NULL) {
423 				if (j->jid > 0 &&
424 				    !(j->flags & (JF_DEPEND | JF_WILD))) {
425 					jail_quoted_warnx(j, "already exists",
426 					    NULL);
427 					failed(j);
428 					continue;
429 				}
430 				if (dep_check(j))
431 					continue;
432 				if (j->jid > 0)
433 					goto jail_create_done;
434 				j->comparam = startcommands;
435 				j->comstring = NULL;
436 			}
437 			if (next_command(j))
438 				continue;
439 		jail_create_done:
440 			clear_persist(j);
441 			if (jfp != NULL)
442 				print_jail(jfp, j, oldcl);
443 			dep_done(j, 0);
444 			break;
445 
446 		case JF_SET:
447 			if (j->jid < 0 && !(j->flags & JF_DEPEND)) {
448 				jail_quoted_warnx(j, "not found",
449 				    "no jail specified");
450 				failed(j);
451 				continue;
452 			}
453 			if (dep_check(j))
454 				continue;
455 			if (!(j->flags & JF_DEPEND)) {
456 				if (rdtun_params(j, 1) < 0 ||
457 				    update_jail(j) < 0)
458 					continue;
459 				if (verbose >= 0 && (j->name || verbose > 0))
460 					jail_note(j, "updated\n");
461 			}
462 			dep_done(j, 0);
463 			break;
464 
465 		case JF_STOP:
466 		case JF_RESTART:
467 			if (j->comparam == NULL) {
468 				if (dep_check(j))
469 					continue;
470 				if (j->jid < 0) {
471 					if (!(j->flags & (JF_DEPEND|JF_WILD))) {
472 						if (verbose >= 0)
473 							jail_quoted_warnx(j,
474 							    "not found", NULL);
475 						failed(j);
476 					}
477 					goto jail_remove_done;
478 				}
479 				j->comparam = stopcommands;
480 				j->comstring = NULL;
481 			} else if ((j->flags & JF_FAILED) && j->jid > 0)
482 				goto jail_remove_done;
483 			if (next_command(j))
484 				continue;
485 		jail_remove_done:
486 			dep_done(j, 0);
487 			if ((j->flags & (JF_START | JF_FAILED)) == JF_START) {
488 				j->comparam = NULL;
489 				j->flags &= ~JF_STOP;
490 				dep_reset(j);
491 				requeue(j, j->ndeps ? &depend : &ready);
492 			}
493 			break;
494 		}
495 	}
496 
497 	if (jfp != NULL)
498 		fclose(jfp);
499 	exit(error);
500 }
501 
502 /*
503  * Mark a jail's failure for future handling.
504  */
505 void
506 failed(struct cfjail *j)
507 {
508 	j->flags |= JF_FAILED;
509 	TAILQ_REMOVE(j->queue, j, tq);
510 	TAILQ_INSERT_HEAD(&ready, j, tq);
511 	j->queue = &ready;
512 }
513 
514 /*
515  * Exit slightly more gracefully when out of memory.
516  */
517 void *
518 emalloc(size_t size)
519 {
520 	void *p;
521 
522 	p = malloc(size);
523 	if (!p)
524 		err(1, "malloc");
525 	return p;
526 }
527 
528 void *
529 erealloc(void *ptr, size_t size)
530 {
531 	void *p;
532 
533 	p = realloc(ptr, size);
534 	if (!p)
535 		err(1, "malloc");
536 	return p;
537 }
538 
539 char *
540 estrdup(const char *str)
541 {
542 	char *ns;
543 
544 	ns = strdup(str);
545 	if (!ns)
546 		err(1, "malloc");
547 	return ns;
548 }
549 
550 /*
551  * Print a message including an optional jail name.
552  */
553 void
554 jail_note(const struct cfjail *j, const char *fmt, ...)
555 {
556 	va_list ap, tap;
557 	char *cs;
558 	size_t len;
559 
560 	va_start(ap, fmt);
561 	va_copy(tap, ap);
562 	len = vsnprintf(NULL, 0, fmt, tap);
563 	va_end(tap);
564 	cs = alloca(len + 1);
565 	(void)vsnprintf(cs, len + 1, fmt, ap);
566 	va_end(ap);
567 	if (j->name)
568 		printf("%s: %s", j->name, cs);
569 	else
570 		printf("%s", cs);
571 }
572 
573 /*
574  * Print a warning message including an optional jail name.
575  */
576 void
577 jail_warnx(const struct cfjail *j, const char *fmt, ...)
578 {
579 	va_list ap, tap;
580 	char *cs;
581 	size_t len;
582 
583 	va_start(ap, fmt);
584 	va_copy(tap, ap);
585 	len = vsnprintf(NULL, 0, fmt, tap);
586 	va_end(tap);
587 	cs = alloca(len + 1);
588 	(void)vsnprintf(cs, len + 1, fmt, ap);
589 	va_end(ap);
590 	if (j->name)
591 		warnx("%s: %s", j->name, cs);
592 	else
593 		warnx("%s", cs);
594 }
595 
596 /*
597  * Create a new jail.
598  */
599 int
600 create_jail(struct cfjail *j)
601 {
602 	struct iovec jiov[4];
603 	struct stat st;
604 	struct jailparam *jp, *setparams, *setparams2, *sjp;
605 	const char *path;
606 	int dopersist, ns, jid, dying, didfail;
607 
608 	/*
609 	 * Check the jail's path, with a better error message than jail_set
610 	 * gives.
611 	 */
612 	if ((path = string_param(j->intparams[KP_PATH]))) {
613 		if (j->name != NULL && path[0] != '/') {
614 			jail_warnx(j, "path %s: not an absolute pathname",
615 			    path);
616 			return -1;
617 		}
618 		if (stat(path, &st) < 0) {
619 			jail_warnx(j, "path %s: %s", path, strerror(errno));
620 			return -1;
621 		}
622 		if (!S_ISDIR(st.st_mode)) {
623 			jail_warnx(j, "path %s: %s", path, strerror(ENOTDIR));
624 			return -1;
625 		}
626 	}
627 
628 	/*
629 	 * Copy all the parameters, except that "persist" is always set when
630 	 * there are commands to run later.
631 	 */
632 	dopersist = !bool_param(j->intparams[KP_PERSIST]) &&
633 	    (j->intparams[IP_EXEC_START] || j->intparams[IP_COMMAND] ||
634 	     j->intparams[IP_EXEC_POSTSTART]);
635 	sjp = setparams =
636 	    alloca((j->njp + dopersist) * sizeof(struct jailparam));
637 	if (dopersist && jailparam_init(sjp++, "persist") < 0) {
638 		jail_warnx(j, "%s", jail_errmsg);
639 		return -1;
640 	}
641 	for (jp = j->jp; jp < j->jp + j->njp; jp++)
642 		if (!dopersist || !equalopts(jp->jp_name, "persist"))
643 			*sjp++ = *jp;
644 	ns = sjp - setparams;
645 
646 	didfail = 0;
647 	j->jid = jailparam_set_note(j, setparams, ns, JAIL_CREATE);
648 	if (j->jid < 0 && errno == EEXIST &&
649 	    bool_param(j->intparams[IP_ALLOW_DYING]) &&
650 	    int_param(j->intparams[KP_JID], &jid) && jid != 0) {
651 		/*
652 		 * The jail already exists, but may be dying.
653 		 * Make sure it is, in which case an update is appropriate.
654 		 */
655 		jiov[0].iov_base = __DECONST(char *, "jid");
656 		jiov[0].iov_len = sizeof("jid");
657 		jiov[1].iov_base = &jid;
658 		jiov[1].iov_len = sizeof(jid);
659 		jiov[2].iov_base = __DECONST(char *, "dying");
660 		jiov[2].iov_len = sizeof("dying");
661 		jiov[3].iov_base = &dying;
662 		jiov[3].iov_len = sizeof(dying);
663 		if (jail_get(jiov, 4, JAIL_DYING) < 0) {
664 			/*
665 			 * It could be that the jail just barely finished
666 			 * dying, or it could be that the jid never existed
667 			 * but the name does.  In either case, another try
668 			 * at creating the jail should do the right thing.
669 			 */
670 			if (errno == ENOENT)
671 				j->jid = jailparam_set_note(j, setparams, ns,
672 				    JAIL_CREATE);
673 		} else if (dying) {
674 			j->jid = jid;
675 			if (rdtun_params(j, 1) < 0) {
676 				j->jid = -1;
677 				didfail = 1;
678 			} else {
679 				sjp = setparams2 = alloca((j->njp + dopersist) *
680 				    sizeof(struct jailparam));
681 				for (jp = setparams; jp < setparams + ns; jp++)
682 					if (!JP_RDTUN(jp) ||
683 					    !strcmp(jp->jp_name, "jid"))
684 						*sjp++ = *jp;
685 				j->jid = jailparam_set_note(j, setparams2,
686 				    sjp - setparams2, JAIL_UPDATE | JAIL_DYING);
687 				/*
688 				 * Again, perhaps the jail just finished dying.
689 				 */
690 				if (j->jid < 0 && errno == ENOENT)
691 					j->jid = jailparam_set_note(j,
692 					    setparams, ns, JAIL_CREATE);
693 			}
694 		}
695 	}
696 	if (j->jid < 0 && !didfail) {
697 		jail_warnx(j, "%s", jail_errmsg);
698 		failed(j);
699 	}
700 	if (dopersist) {
701 		jailparam_free(setparams, 1);
702 		if (j->jid > 0)
703 			j->flags |= JF_PERSIST;
704 	}
705 	return j->jid;
706 }
707 
708 /*
709  * Remove a temporarily set "persist" parameter.
710  */
711 static void
712 clear_persist(struct cfjail *j)
713 {
714 	struct iovec jiov[4];
715 	int jid;
716 
717 	if (!(j->flags & JF_PERSIST))
718 		return;
719 	j->flags &= ~JF_PERSIST;
720 	jiov[0].iov_base = __DECONST(char *, "jid");
721 	jiov[0].iov_len = sizeof("jid");
722 	jiov[1].iov_base = &j->jid;
723 	jiov[1].iov_len = sizeof(j->jid);
724 	jiov[2].iov_base = __DECONST(char *, "nopersist");
725 	jiov[2].iov_len = sizeof("nopersist");
726 	jiov[3].iov_base = NULL;
727 	jiov[3].iov_len = 0;
728 	jid = jail_set(jiov, 4, JAIL_UPDATE);
729 	if (verbose > 0)
730 		jail_note(j, "jail_set(JAIL_UPDATE) jid=%d nopersist%s%s\n",
731 		    j->jid, jid < 0 ? ": " : "",
732 		    jid < 0 ? strerror(errno) : "");
733 }
734 
735 /*
736  * Set a jail's parameters.
737  */
738 static int
739 update_jail(struct cfjail *j)
740 {
741 	struct jailparam *jp, *setparams, *sjp;
742 	int ns, jid;
743 
744 	ns = 0;
745 	for (jp = j->jp; jp < j->jp + j->njp; jp++)
746 		if (!JP_RDTUN(jp))
747 			ns++;
748 	if (ns == 0)
749 		return 0;
750 	sjp = setparams = alloca(++ns * sizeof(struct jailparam));
751 	if (jailparam_init(sjp, "jid") < 0 ||
752 	    jailparam_import_raw(sjp, &j->jid, sizeof j->jid) < 0) {
753 		jail_warnx(j, "%s", jail_errmsg);
754 		failed(j);
755 		return -1;
756 	}
757 	for (jp = j->jp; jp < j->jp + j->njp; jp++)
758 		if (!JP_RDTUN(jp))
759 			*++sjp = *jp;
760 
761 	jid = jailparam_set_note(j, setparams, ns,
762 	    bool_param(j->intparams[IP_ALLOW_DYING])
763 	    ? JAIL_UPDATE | JAIL_DYING : JAIL_UPDATE);
764 	if (jid < 0) {
765 		jail_warnx(j, "%s", jail_errmsg);
766 		failed(j);
767 	}
768 	jailparam_free(setparams, 1);
769 	return jid;
770 }
771 
772 /*
773  * Return if a jail set would change any create-only parameters.
774  */
775 static int
776 rdtun_params(struct cfjail *j, int dofail)
777 {
778 	struct jailparam *jp, *rtparams, *rtjp;
779 	int nrt, rval;
780 
781 	if (j->flags & JF_RDTUN)
782 		return 0;
783 	j->flags |= JF_RDTUN;
784 	nrt = 0;
785 	for (jp = j->jp; jp < j->jp + j->njp; jp++)
786 		if (JP_RDTUN(jp) && strcmp(jp->jp_name, "jid"))
787 			nrt++;
788 	if (nrt == 0)
789 		return 0;
790 	rtjp = rtparams = alloca(++nrt * sizeof(struct jailparam));
791 	if (jailparam_init(rtjp, "jid") < 0 ||
792 	    jailparam_import_raw(rtjp, &j->jid, sizeof j->jid) < 0) {
793 		jail_warnx(j, "%s", jail_errmsg);
794 		exit(1);
795 	}
796 	for (jp = j->jp; jp < j->jp + j->njp; jp++)
797 		if (JP_RDTUN(jp) && strcmp(jp->jp_name, "jid")) {
798 			*++rtjp = *jp;
799 			rtjp->jp_value = NULL;
800 		}
801 	rval = 0;
802 	if (jailparam_get(rtparams, nrt,
803 	    bool_param(j->intparams[IP_ALLOW_DYING]) ? JAIL_DYING : 0) > 0) {
804 		rtjp = rtparams + 1;
805 		for (jp = j->jp; rtjp < rtparams + nrt; jp++) {
806 			if (JP_RDTUN(jp) && strcmp(jp->jp_name, "jid")) {
807 				if (!((jp->jp_flags & (JP_BOOL | JP_NOBOOL)) &&
808 				    jp->jp_valuelen == 0 &&
809 				    *(int *)jp->jp_value) &&
810 				    !(rtjp->jp_valuelen == jp->jp_valuelen &&
811 				    !((jp->jp_ctltype & CTLTYPE) ==
812 				    CTLTYPE_STRING ? strncmp(rtjp->jp_value,
813 				    jp->jp_value, jp->jp_valuelen) :
814 				    memcmp(rtjp->jp_value, jp->jp_value,
815 				    jp->jp_valuelen)))) {
816 					if (dofail) {
817 						jail_warnx(j, "%s cannot be "
818 						    "changed after creation",
819 						    jp->jp_name);
820 						failed(j);
821 						rval = -1;
822 					} else
823 						rval = 1;
824 					break;
825 				}
826 				rtjp++;
827 			}
828 		}
829 	}
830 	for (rtjp = rtparams + 1; rtjp < rtparams + nrt; rtjp++)
831 		rtjp->jp_name = NULL;
832 	jailparam_free(rtparams, nrt);
833 	return rval;
834 }
835 
836 /*
837  * Get the jail's jid if it is running.
838  */
839 static void
840 running_jid(struct cfjail *j, int dflag)
841 {
842 	struct iovec jiov[2];
843 	const char *pval;
844 	char *ep;
845 	int jid;
846 
847 	if ((pval = string_param(j->intparams[KP_JID]))) {
848 		if (!(jid = strtol(pval, &ep, 10)) || *ep) {
849 			j->jid = -1;
850 			return;
851 		}
852 		jiov[0].iov_base = __DECONST(char *, "jid");
853 		jiov[0].iov_len = sizeof("jid");
854 		jiov[1].iov_base = &jid;
855 		jiov[1].iov_len = sizeof(jid);
856 	} else if ((pval = string_param(j->intparams[KP_NAME]))) {
857 		jiov[0].iov_base = __DECONST(char *, "name");
858 		jiov[0].iov_len = sizeof("name");
859 		jiov[1].iov_len = strlen(pval) + 1;
860 		jiov[1].iov_base = alloca(jiov[1].iov_len);
861 		strcpy(jiov[1].iov_base, pval);
862 	} else {
863 		j->jid = -1;
864 		return;
865 	}
866 	j->jid = jail_get(jiov, 2, dflag ? JAIL_DYING : 0);
867 }
868 
869 static void
870 jail_quoted_warnx(const struct cfjail *j, const char *name_msg,
871     const char *noname_msg)
872 {
873 	const char *pval;
874 
875 	if ((pval = j->name) || (pval = string_param(j->intparams[KP_JID])) ||
876 	    (pval = string_param(j->intparams[KP_NAME])))
877 		warnx("\"%s\" %s", pval, name_msg);
878 	else
879 		warnx("%s", noname_msg);
880 }
881 
882 /*
883  * Set jail parameters and possibly print them out.
884  */
885 static int
886 jailparam_set_note(const struct cfjail *j, struct jailparam *jp, unsigned njp,
887     int flags)
888 {
889 	char *value;
890 	int jid;
891 	unsigned i;
892 
893 	jid = jailparam_set(jp, njp, flags);
894 	if (verbose > 0) {
895 		jail_note(j, "jail_set(%s%s)",
896 		    (flags & (JAIL_CREATE | JAIL_UPDATE)) == JAIL_CREATE
897 		    ? "JAIL_CREATE" : "JAIL_UPDATE",
898 		    (flags & JAIL_DYING) ? " | JAIL_DYING" : "");
899 		for (i = 0; i < njp; i++) {
900 			printf(" %s", jp[i].jp_name);
901 			if (jp[i].jp_value == NULL)
902 				continue;
903 			putchar('=');
904 			value = jailparam_export(jp + i);
905 			if (value == NULL)
906 				err(1, "jailparam_export");
907 			quoted_print(stdout, value);
908 			free(value);
909 		}
910 		if (jid < 0)
911 			printf(": %s", strerror(errno));
912 		printf("\n");
913 	}
914 	return jid;
915 }
916 
917 /*
918  * Print a jail record.
919  */
920 static void
921 print_jail(FILE *fp, struct cfjail *j, int oldcl)
922 {
923 	struct cfparam *p;
924 
925 	if (oldcl) {
926 		fprintf(fp, "%d\t", j->jid);
927 		print_param(fp, j->intparams[KP_PATH], ',', 0);
928 		putc('\t', fp);
929 		print_param(fp, j->intparams[KP_HOST_HOSTNAME], ',', 0);
930 		putc('\t', fp);
931 #ifdef INET
932 		print_param(fp, j->intparams[KP_IP4_ADDR], ',', 0);
933 #ifdef INET6
934 		if (j->intparams[KP_IP4_ADDR] &&
935 		    !TAILQ_EMPTY(&j->intparams[KP_IP4_ADDR]->val) &&
936 		    j->intparams[KP_IP6_ADDR] &&
937 		    !TAILQ_EMPTY(&j->intparams[KP_IP6_ADDR]->val))
938 		    putc(',', fp);
939 #endif
940 #endif
941 #ifdef INET6
942 		print_param(fp, j->intparams[KP_IP6_ADDR], ',', 0);
943 #endif
944 		putc('\t', fp);
945 		print_param(fp, j->intparams[IP_COMMAND], ' ', 0);
946 	} else {
947 		fprintf(fp, "jid=%d", j->jid);
948 		TAILQ_FOREACH(p, &j->params, tq)
949 			if (strcmp(p->name, "jid")) {
950 				putc(' ', fp);
951 				print_param(fp, p, ',', 1);
952 			}
953 	}
954 	putc('\n', fp);
955 }
956 
957 /*
958  * Print a parameter value, or a name=value pair.
959  */
960 static void
961 print_param(FILE *fp, const struct cfparam *p, int sep, int doname)
962 {
963 	const struct cfstring *s, *ts;
964 
965 	if (doname)
966 		fputs(p->name, fp);
967 	if (p == NULL || TAILQ_EMPTY(&p->val))
968 		return;
969 	if (doname)
970 		putc('=', fp);
971 	TAILQ_FOREACH_SAFE(s, &p->val, tq, ts) {
972 		quoted_print(fp, s->s);
973 		if (ts != NULL)
974 			putc(sep, fp);
975 	}
976 }
977 
978 /*
979  * Print a string with quotes around spaces.
980  */
981 static void
982 quoted_print(FILE *fp, char *str)
983 {
984 	int c, qc;
985 	char *p = str;
986 
987 	qc = !*p ? '"'
988 	    : strchr(p, '\'') ? '"'
989 	    : strchr(p, '"') ? '\''
990 	    : strchr(p, ' ') || strchr(p, '\t') ? '"'
991 	    : 0;
992 	if (qc)
993 		putc(qc, fp);
994 	while ((c = *p++)) {
995 		if (c == '\\' || c == qc)
996 			putc('\\', fp);
997 		putc(c, fp);
998 	}
999 	if (qc)
1000 		putc(qc, fp);
1001 }
1002 
1003 static void
1004 usage(void)
1005 {
1006 
1007 	(void)fprintf(stderr,
1008 	    "usage: jail [-dhilqv] [-J jid_file] [-u username] [-U username]\n"
1009 	    "            -[cmr] param=value ... [command=command ...]\n"
1010 	    "       jail [-dqv] [-f file] -[cmr] [jail]\n"
1011 	    "       jail [-qv] [-f file] -[rR] ['*' | jail ...]\n"
1012 	    "       jail [-dhilqv] [-J jid_file] [-u username] [-U username]\n"
1013 	    "            [-n jailname] [-s securelevel]\n"
1014 	    "            path hostname [ip[,...]] command ...\n");
1015 	exit(1);
1016 }
1017