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