xref: /freebsd/usr.sbin/ctld/ctld.c (revision 7937bfbc0ca53fe7cdd0d54414f9296e273a518e)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2012 The FreeBSD Foundation
5  *
6  * This software was developed by Edward Tomasz Napierala under sponsorship
7  * from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  */
31 
32 #include <sys/types.h>
33 #include <sys/time.h>
34 #include <sys/socket.h>
35 #include <sys/stat.h>
36 #include <sys/wait.h>
37 #include <netinet/in.h>
38 #include <arpa/inet.h>
39 #include <assert.h>
40 #include <ctype.h>
41 #include <errno.h>
42 #include <netdb.h>
43 #include <signal.h>
44 #include <stdbool.h>
45 #include <stdio.h>
46 #include <stdint.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <unistd.h>
50 
51 #include "ctld.h"
52 #include "isns.h"
53 
54 static bool	timed_out(void);
55 #ifdef ICL_KERNEL_PROXY
56 static void	pdu_receive_proxy(struct pdu *pdu);
57 static void	pdu_send_proxy(struct pdu *pdu);
58 #endif /* ICL_KERNEL_PROXY */
59 static void	pdu_fail(const struct connection *conn, const char *reason);
60 
61 bool proxy_mode = false;
62 
63 static volatile bool sighup_received = false;
64 static volatile bool sigterm_received = false;
65 static volatile bool sigalrm_received = false;
66 
67 static int nchildren = 0;
68 static uint16_t last_portal_group_tag = 0xff;
69 
70 static struct connection_ops conn_ops = {
71 	.timed_out = timed_out,
72 #ifdef ICL_KERNEL_PROXY
73 	.pdu_receive_proxy = pdu_receive_proxy,
74 	.pdu_send_proxy = pdu_send_proxy,
75 #endif
76 	.fail = pdu_fail,
77 };
78 
79 static void
80 usage(void)
81 {
82 
83 	fprintf(stderr, "usage: ctld [-d][-u][-f config-file]\n");
84 	fprintf(stderr, "       ctld -t [-u][-f config-file]\n");
85 	exit(1);
86 }
87 
88 struct conf *
89 conf_new(void)
90 {
91 	struct conf *conf;
92 
93 	conf = calloc(1, sizeof(*conf));
94 	if (conf == NULL)
95 		log_err(1, "calloc");
96 	TAILQ_INIT(&conf->conf_luns);
97 	TAILQ_INIT(&conf->conf_targets);
98 	TAILQ_INIT(&conf->conf_auth_groups);
99 	TAILQ_INIT(&conf->conf_ports);
100 	TAILQ_INIT(&conf->conf_portal_groups);
101 	TAILQ_INIT(&conf->conf_isns);
102 
103 	conf->conf_isns_period = 900;
104 	conf->conf_isns_timeout = 5;
105 	conf->conf_debug = 0;
106 	conf->conf_timeout = 60;
107 	conf->conf_maxproc = 30;
108 
109 	return (conf);
110 }
111 
112 void
113 conf_delete(struct conf *conf)
114 {
115 	struct lun *lun, *ltmp;
116 	struct target *targ, *tmp;
117 	struct auth_group *ag, *cagtmp;
118 	struct portal_group *pg, *cpgtmp;
119 	struct isns *is, *istmp;
120 
121 	assert(conf->conf_pidfh == NULL);
122 
123 	TAILQ_FOREACH_SAFE(lun, &conf->conf_luns, l_next, ltmp)
124 		lun_delete(lun);
125 	TAILQ_FOREACH_SAFE(targ, &conf->conf_targets, t_next, tmp)
126 		target_delete(targ);
127 	TAILQ_FOREACH_SAFE(ag, &conf->conf_auth_groups, ag_next, cagtmp)
128 		auth_group_delete(ag);
129 	TAILQ_FOREACH_SAFE(pg, &conf->conf_portal_groups, pg_next, cpgtmp)
130 		portal_group_delete(pg);
131 	TAILQ_FOREACH_SAFE(is, &conf->conf_isns, i_next, istmp)
132 		isns_delete(is);
133 	assert(TAILQ_EMPTY(&conf->conf_ports));
134 	free(conf->conf_pidfile_path);
135 	free(conf);
136 }
137 
138 static struct auth *
139 auth_new(struct auth_group *ag)
140 {
141 	struct auth *auth;
142 
143 	auth = calloc(1, sizeof(*auth));
144 	if (auth == NULL)
145 		log_err(1, "calloc");
146 	auth->a_auth_group = ag;
147 	TAILQ_INSERT_TAIL(&ag->ag_auths, auth, a_next);
148 	return (auth);
149 }
150 
151 static void
152 auth_delete(struct auth *auth)
153 {
154 	TAILQ_REMOVE(&auth->a_auth_group->ag_auths, auth, a_next);
155 
156 	free(auth->a_user);
157 	free(auth->a_secret);
158 	free(auth->a_mutual_user);
159 	free(auth->a_mutual_secret);
160 	free(auth);
161 }
162 
163 const struct auth *
164 auth_find(const struct auth_group *ag, const char *user)
165 {
166 	const struct auth *auth;
167 
168 	TAILQ_FOREACH(auth, &ag->ag_auths, a_next) {
169 		if (strcmp(auth->a_user, user) == 0)
170 			return (auth);
171 	}
172 
173 	return (NULL);
174 }
175 
176 static void
177 auth_check_secret_length(struct auth *auth)
178 {
179 	size_t len;
180 
181 	len = strlen(auth->a_secret);
182 	if (len > 16) {
183 		if (auth->a_auth_group->ag_name != NULL)
184 			log_warnx("secret for user \"%s\", auth-group \"%s\", "
185 			    "is too long; it should be at most 16 characters "
186 			    "long", auth->a_user, auth->a_auth_group->ag_name);
187 		else
188 			log_warnx("secret for user \"%s\", target \"%s\", "
189 			    "is too long; it should be at most 16 characters "
190 			    "long", auth->a_user,
191 			    auth->a_auth_group->ag_target->t_name);
192 	}
193 	if (len < 12) {
194 		if (auth->a_auth_group->ag_name != NULL)
195 			log_warnx("secret for user \"%s\", auth-group \"%s\", "
196 			    "is too short; it should be at least 12 characters "
197 			    "long", auth->a_user,
198 			    auth->a_auth_group->ag_name);
199 		else
200 			log_warnx("secret for user \"%s\", target \"%s\", "
201 			    "is too short; it should be at least 12 characters "
202 			    "long", auth->a_user,
203 			    auth->a_auth_group->ag_target->t_name);
204 	}
205 
206 	if (auth->a_mutual_secret != NULL) {
207 		len = strlen(auth->a_mutual_secret);
208 		if (len > 16) {
209 			if (auth->a_auth_group->ag_name != NULL)
210 				log_warnx("mutual secret for user \"%s\", "
211 				    "auth-group \"%s\", is too long; it should "
212 				    "be at most 16 characters long",
213 				    auth->a_user, auth->a_auth_group->ag_name);
214 			else
215 				log_warnx("mutual secret for user \"%s\", "
216 				    "target \"%s\", is too long; it should "
217 				    "be at most 16 characters long",
218 				    auth->a_user,
219 				    auth->a_auth_group->ag_target->t_name);
220 		}
221 		if (len < 12) {
222 			if (auth->a_auth_group->ag_name != NULL)
223 				log_warnx("mutual secret for user \"%s\", "
224 				    "auth-group \"%s\", is too short; it "
225 				    "should be at least 12 characters long",
226 				    auth->a_user, auth->a_auth_group->ag_name);
227 			else
228 				log_warnx("mutual secret for user \"%s\", "
229 				    "target \"%s\", is too short; it should be "
230 				    "at least 12 characters long",
231 				    auth->a_user,
232 				    auth->a_auth_group->ag_target->t_name);
233 		}
234 	}
235 }
236 
237 const struct auth *
238 auth_new_chap(struct auth_group *ag, const char *user,
239     const char *secret)
240 {
241 	struct auth *auth;
242 
243 	if (ag->ag_type == AG_TYPE_UNKNOWN)
244 		ag->ag_type = AG_TYPE_CHAP;
245 	if (ag->ag_type != AG_TYPE_CHAP) {
246 		if (ag->ag_name != NULL)
247 			log_warnx("cannot mix \"chap\" authentication with "
248 			    "other types for auth-group \"%s\"", ag->ag_name);
249 		else
250 			log_warnx("cannot mix \"chap\" authentication with "
251 			    "other types for target \"%s\"",
252 			    ag->ag_target->t_name);
253 		return (NULL);
254 	}
255 
256 	auth = auth_new(ag);
257 	auth->a_user = checked_strdup(user);
258 	auth->a_secret = checked_strdup(secret);
259 
260 	auth_check_secret_length(auth);
261 
262 	return (auth);
263 }
264 
265 const struct auth *
266 auth_new_chap_mutual(struct auth_group *ag, const char *user,
267     const char *secret, const char *user2, const char *secret2)
268 {
269 	struct auth *auth;
270 
271 	if (ag->ag_type == AG_TYPE_UNKNOWN)
272 		ag->ag_type = AG_TYPE_CHAP_MUTUAL;
273 	if (ag->ag_type != AG_TYPE_CHAP_MUTUAL) {
274 		if (ag->ag_name != NULL)
275 			log_warnx("cannot mix \"chap-mutual\" authentication "
276 			    "with other types for auth-group \"%s\"",
277 			    ag->ag_name);
278 		else
279 			log_warnx("cannot mix \"chap-mutual\" authentication "
280 			    "with other types for target \"%s\"",
281 			    ag->ag_target->t_name);
282 		return (NULL);
283 	}
284 
285 	auth = auth_new(ag);
286 	auth->a_user = checked_strdup(user);
287 	auth->a_secret = checked_strdup(secret);
288 	auth->a_mutual_user = checked_strdup(user2);
289 	auth->a_mutual_secret = checked_strdup(secret2);
290 
291 	auth_check_secret_length(auth);
292 
293 	return (auth);
294 }
295 
296 const struct auth_name *
297 auth_name_new(struct auth_group *ag, const char *name)
298 {
299 	struct auth_name *an;
300 
301 	an = calloc(1, sizeof(*an));
302 	if (an == NULL)
303 		log_err(1, "calloc");
304 	an->an_auth_group = ag;
305 	an->an_initiator_name = checked_strdup(name);
306 	TAILQ_INSERT_TAIL(&ag->ag_names, an, an_next);
307 	return (an);
308 }
309 
310 static void
311 auth_name_delete(struct auth_name *an)
312 {
313 	TAILQ_REMOVE(&an->an_auth_group->ag_names, an, an_next);
314 
315 	free(an->an_initiator_name);
316 	free(an);
317 }
318 
319 bool
320 auth_name_defined(const struct auth_group *ag)
321 {
322 	if (TAILQ_EMPTY(&ag->ag_names))
323 		return (false);
324 	return (true);
325 }
326 
327 const struct auth_name *
328 auth_name_find(const struct auth_group *ag, const char *name)
329 {
330 	const struct auth_name *auth_name;
331 
332 	TAILQ_FOREACH(auth_name, &ag->ag_names, an_next) {
333 		if (strcmp(auth_name->an_initiator_name, name) == 0)
334 			return (auth_name);
335 	}
336 
337 	return (NULL);
338 }
339 
340 int
341 auth_name_check(const struct auth_group *ag, const char *initiator_name)
342 {
343 	if (!auth_name_defined(ag))
344 		return (0);
345 
346 	if (auth_name_find(ag, initiator_name) == NULL)
347 		return (1);
348 
349 	return (0);
350 }
351 
352 const struct auth_portal *
353 auth_portal_new(struct auth_group *ag, const char *portal)
354 {
355 	struct auth_portal *ap;
356 	char *net, *mask, *str, *tmp;
357 	int len, dm, m;
358 
359 	ap = calloc(1, sizeof(*ap));
360 	if (ap == NULL)
361 		log_err(1, "calloc");
362 	ap->ap_auth_group = ag;
363 	ap->ap_initiator_portal = checked_strdup(portal);
364 	mask = str = checked_strdup(portal);
365 	net = strsep(&mask, "/");
366 	if (net[0] == '[')
367 		net++;
368 	len = strlen(net);
369 	if (len == 0)
370 		goto error;
371 	if (net[len - 1] == ']')
372 		net[len - 1] = 0;
373 	if (strchr(net, ':') != NULL) {
374 		struct sockaddr_in6 *sin6 =
375 		    (struct sockaddr_in6 *)&ap->ap_sa;
376 
377 		sin6->sin6_len = sizeof(*sin6);
378 		sin6->sin6_family = AF_INET6;
379 		if (inet_pton(AF_INET6, net, &sin6->sin6_addr) <= 0)
380 			goto error;
381 		dm = 128;
382 	} else {
383 		struct sockaddr_in *sin =
384 		    (struct sockaddr_in *)&ap->ap_sa;
385 
386 		sin->sin_len = sizeof(*sin);
387 		sin->sin_family = AF_INET;
388 		if (inet_pton(AF_INET, net, &sin->sin_addr) <= 0)
389 			goto error;
390 		dm = 32;
391 	}
392 	if (mask != NULL) {
393 		m = strtol(mask, &tmp, 0);
394 		if (m < 0 || m > dm || tmp[0] != 0)
395 			goto error;
396 	} else
397 		m = dm;
398 	ap->ap_mask = m;
399 	free(str);
400 	TAILQ_INSERT_TAIL(&ag->ag_portals, ap, ap_next);
401 	return (ap);
402 
403 error:
404 	free(str);
405 	free(ap);
406 	log_warnx("incorrect initiator portal \"%s\"", portal);
407 	return (NULL);
408 }
409 
410 static void
411 auth_portal_delete(struct auth_portal *ap)
412 {
413 	TAILQ_REMOVE(&ap->ap_auth_group->ag_portals, ap, ap_next);
414 
415 	free(ap->ap_initiator_portal);
416 	free(ap);
417 }
418 
419 bool
420 auth_portal_defined(const struct auth_group *ag)
421 {
422 	if (TAILQ_EMPTY(&ag->ag_portals))
423 		return (false);
424 	return (true);
425 }
426 
427 const struct auth_portal *
428 auth_portal_find(const struct auth_group *ag, const struct sockaddr_storage *ss)
429 {
430 	const struct auth_portal *ap;
431 	const uint8_t *a, *b;
432 	int i;
433 	uint8_t bmask;
434 
435 	TAILQ_FOREACH(ap, &ag->ag_portals, ap_next) {
436 		if (ap->ap_sa.ss_family != ss->ss_family)
437 			continue;
438 		if (ss->ss_family == AF_INET) {
439 			a = (const uint8_t *)
440 			    &((const struct sockaddr_in *)ss)->sin_addr;
441 			b = (const uint8_t *)
442 			    &((const struct sockaddr_in *)&ap->ap_sa)->sin_addr;
443 		} else {
444 			a = (const uint8_t *)
445 			    &((const struct sockaddr_in6 *)ss)->sin6_addr;
446 			b = (const uint8_t *)
447 			    &((const struct sockaddr_in6 *)&ap->ap_sa)->sin6_addr;
448 		}
449 		for (i = 0; i < ap->ap_mask / 8; i++) {
450 			if (a[i] != b[i])
451 				goto next;
452 		}
453 		if (ap->ap_mask % 8) {
454 			bmask = 0xff << (8 - (ap->ap_mask % 8));
455 			if ((a[i] & bmask) != (b[i] & bmask))
456 				goto next;
457 		}
458 		return (ap);
459 next:
460 		;
461 	}
462 
463 	return (NULL);
464 }
465 
466 int
467 auth_portal_check(const struct auth_group *ag, const struct sockaddr_storage *sa)
468 {
469 
470 	if (!auth_portal_defined(ag))
471 		return (0);
472 
473 	if (auth_portal_find(ag, sa) == NULL)
474 		return (1);
475 
476 	return (0);
477 }
478 
479 struct auth_group *
480 auth_group_new(struct conf *conf, const char *name)
481 {
482 	struct auth_group *ag;
483 
484 	if (name != NULL) {
485 		ag = auth_group_find(conf, name);
486 		if (ag != NULL) {
487 			log_warnx("duplicated auth-group \"%s\"", name);
488 			return (NULL);
489 		}
490 	}
491 
492 	ag = calloc(1, sizeof(*ag));
493 	if (ag == NULL)
494 		log_err(1, "calloc");
495 	if (name != NULL)
496 		ag->ag_name = checked_strdup(name);
497 	TAILQ_INIT(&ag->ag_auths);
498 	TAILQ_INIT(&ag->ag_names);
499 	TAILQ_INIT(&ag->ag_portals);
500 	ag->ag_conf = conf;
501 	TAILQ_INSERT_TAIL(&conf->conf_auth_groups, ag, ag_next);
502 
503 	return (ag);
504 }
505 
506 void
507 auth_group_delete(struct auth_group *ag)
508 {
509 	struct auth *auth, *auth_tmp;
510 	struct auth_name *auth_name, *auth_name_tmp;
511 	struct auth_portal *auth_portal, *auth_portal_tmp;
512 
513 	TAILQ_REMOVE(&ag->ag_conf->conf_auth_groups, ag, ag_next);
514 
515 	TAILQ_FOREACH_SAFE(auth, &ag->ag_auths, a_next, auth_tmp)
516 		auth_delete(auth);
517 	TAILQ_FOREACH_SAFE(auth_name, &ag->ag_names, an_next, auth_name_tmp)
518 		auth_name_delete(auth_name);
519 	TAILQ_FOREACH_SAFE(auth_portal, &ag->ag_portals, ap_next,
520 	    auth_portal_tmp)
521 		auth_portal_delete(auth_portal);
522 	free(ag->ag_name);
523 	free(ag);
524 }
525 
526 struct auth_group *
527 auth_group_find(const struct conf *conf, const char *name)
528 {
529 	struct auth_group *ag;
530 
531 	assert(name != NULL);
532 	TAILQ_FOREACH(ag, &conf->conf_auth_groups, ag_next) {
533 		if (ag->ag_name != NULL && strcmp(ag->ag_name, name) == 0)
534 			return (ag);
535 	}
536 
537 	return (NULL);
538 }
539 
540 int
541 auth_group_set_type(struct auth_group *ag, const char *str)
542 {
543 	int type;
544 
545 	if (strcmp(str, "none") == 0) {
546 		type = AG_TYPE_NO_AUTHENTICATION;
547 	} else if (strcmp(str, "deny") == 0) {
548 		type = AG_TYPE_DENY;
549 	} else if (strcmp(str, "chap") == 0) {
550 		type = AG_TYPE_CHAP;
551 	} else if (strcmp(str, "chap-mutual") == 0) {
552 		type = AG_TYPE_CHAP_MUTUAL;
553 	} else {
554 		if (ag->ag_name != NULL)
555 			log_warnx("invalid auth-type \"%s\" for auth-group "
556 			    "\"%s\"", str, ag->ag_name);
557 		else
558 			log_warnx("invalid auth-type \"%s\" for target "
559 			    "\"%s\"", str, ag->ag_target->t_name);
560 		return (1);
561 	}
562 
563 	if (ag->ag_type != AG_TYPE_UNKNOWN && ag->ag_type != type) {
564 		if (ag->ag_name != NULL) {
565 			log_warnx("cannot set auth-type to \"%s\" for "
566 			    "auth-group \"%s\"; already has a different "
567 			    "type", str, ag->ag_name);
568 		} else {
569 			log_warnx("cannot set auth-type to \"%s\" for target "
570 			    "\"%s\"; already has a different type",
571 			    str, ag->ag_target->t_name);
572 		}
573 		return (1);
574 	}
575 
576 	ag->ag_type = type;
577 
578 	return (0);
579 }
580 
581 static struct portal *
582 portal_new(struct portal_group *pg)
583 {
584 	struct portal *portal;
585 
586 	portal = calloc(1, sizeof(*portal));
587 	if (portal == NULL)
588 		log_err(1, "calloc");
589 	TAILQ_INIT(&portal->p_targets);
590 	portal->p_portal_group = pg;
591 	TAILQ_INSERT_TAIL(&pg->pg_portals, portal, p_next);
592 	return (portal);
593 }
594 
595 static void
596 portal_delete(struct portal *portal)
597 {
598 
599 	TAILQ_REMOVE(&portal->p_portal_group->pg_portals, portal, p_next);
600 	if (portal->p_ai != NULL)
601 		freeaddrinfo(portal->p_ai);
602 	free(portal->p_listen);
603 	free(portal);
604 }
605 
606 struct portal_group *
607 portal_group_new(struct conf *conf, const char *name)
608 {
609 	struct portal_group *pg;
610 
611 	pg = portal_group_find(conf, name);
612 	if (pg != NULL) {
613 		log_warnx("duplicated portal-group \"%s\"", name);
614 		return (NULL);
615 	}
616 
617 	pg = calloc(1, sizeof(*pg));
618 	if (pg == NULL)
619 		log_err(1, "calloc");
620 	pg->pg_name = checked_strdup(name);
621 	TAILQ_INIT(&pg->pg_options);
622 	TAILQ_INIT(&pg->pg_portals);
623 	TAILQ_INIT(&pg->pg_ports);
624 	pg->pg_conf = conf;
625 	pg->pg_tag = 0;		/* Assigned later in conf_apply(). */
626 	pg->pg_dscp = -1;
627 	pg->pg_pcp = -1;
628 	TAILQ_INSERT_TAIL(&conf->conf_portal_groups, pg, pg_next);
629 
630 	return (pg);
631 }
632 
633 void
634 portal_group_delete(struct portal_group *pg)
635 {
636 	struct portal *portal, *tmp;
637 	struct port *port, *tport;
638 	struct option *o, *otmp;
639 
640 	TAILQ_FOREACH_SAFE(port, &pg->pg_ports, p_pgs, tport)
641 		port_delete(port);
642 	TAILQ_REMOVE(&pg->pg_conf->conf_portal_groups, pg, pg_next);
643 
644 	TAILQ_FOREACH_SAFE(portal, &pg->pg_portals, p_next, tmp)
645 		portal_delete(portal);
646 	TAILQ_FOREACH_SAFE(o, &pg->pg_options, o_next, otmp)
647 		option_delete(&pg->pg_options, o);
648 	free(pg->pg_name);
649 	free(pg->pg_offload);
650 	free(pg->pg_redirection);
651 	free(pg);
652 }
653 
654 struct portal_group *
655 portal_group_find(const struct conf *conf, const char *name)
656 {
657 	struct portal_group *pg;
658 
659 	TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
660 		if (strcmp(pg->pg_name, name) == 0)
661 			return (pg);
662 	}
663 
664 	return (NULL);
665 }
666 
667 static int
668 parse_addr_port(char *arg, const char *def_port, struct addrinfo **ai)
669 {
670 	struct addrinfo hints;
671 	char *str, *addr, *ch;
672 	const char *port;
673 	int error, colons = 0;
674 
675 	str = arg = strdup(arg);
676 	if (arg[0] == '[') {
677 		/*
678 		 * IPv6 address in square brackets, perhaps with port.
679 		 */
680 		arg++;
681 		addr = strsep(&arg, "]");
682 		if (arg == NULL) {
683 			free(str);
684 			return (1);
685 		}
686 		if (arg[0] == '\0') {
687 			port = def_port;
688 		} else if (arg[0] == ':') {
689 			port = arg + 1;
690 		} else {
691 			free(str);
692 			return (1);
693 		}
694 	} else {
695 		/*
696 		 * Either IPv6 address without brackets - and without
697 		 * a port - or IPv4 address.  Just count the colons.
698 		 */
699 		for (ch = arg; *ch != '\0'; ch++) {
700 			if (*ch == ':')
701 				colons++;
702 		}
703 		if (colons > 1) {
704 			addr = arg;
705 			port = def_port;
706 		} else {
707 			addr = strsep(&arg, ":");
708 			if (arg == NULL)
709 				port = def_port;
710 			else
711 				port = arg;
712 		}
713 	}
714 
715 	memset(&hints, 0, sizeof(hints));
716 	hints.ai_family = PF_UNSPEC;
717 	hints.ai_socktype = SOCK_STREAM;
718 	hints.ai_flags = AI_PASSIVE;
719 	error = getaddrinfo(addr, port, &hints, ai);
720 	free(str);
721 	return ((error != 0) ? 1 : 0);
722 }
723 
724 int
725 portal_group_add_listen(struct portal_group *pg, const char *value, bool iser)
726 {
727 	struct portal *portal;
728 
729 	portal = portal_new(pg);
730 	portal->p_listen = checked_strdup(value);
731 	portal->p_iser = iser;
732 
733 	if (parse_addr_port(portal->p_listen, "3260", &portal->p_ai)) {
734 		log_warnx("invalid listen address %s", portal->p_listen);
735 		portal_delete(portal);
736 		return (1);
737 	}
738 
739 	/*
740 	 * XXX: getaddrinfo(3) may return multiple addresses; we should turn
741 	 *	those into multiple portals.
742 	 */
743 
744 	return (0);
745 }
746 
747 int
748 isns_new(struct conf *conf, const char *addr)
749 {
750 	struct isns *isns;
751 
752 	isns = calloc(1, sizeof(*isns));
753 	if (isns == NULL)
754 		log_err(1, "calloc");
755 	isns->i_conf = conf;
756 	TAILQ_INSERT_TAIL(&conf->conf_isns, isns, i_next);
757 	isns->i_addr = checked_strdup(addr);
758 
759 	if (parse_addr_port(isns->i_addr, "3205", &isns->i_ai)) {
760 		log_warnx("invalid iSNS address %s", isns->i_addr);
761 		isns_delete(isns);
762 		return (1);
763 	}
764 
765 	/*
766 	 * XXX: getaddrinfo(3) may return multiple addresses; we should turn
767 	 *	those into multiple servers.
768 	 */
769 
770 	return (0);
771 }
772 
773 void
774 isns_delete(struct isns *isns)
775 {
776 
777 	TAILQ_REMOVE(&isns->i_conf->conf_isns, isns, i_next);
778 	free(isns->i_addr);
779 	if (isns->i_ai != NULL)
780 		freeaddrinfo(isns->i_ai);
781 	free(isns);
782 }
783 
784 static int
785 isns_do_connect(struct isns *isns)
786 {
787 	int s;
788 
789 	s = socket(isns->i_ai->ai_family, isns->i_ai->ai_socktype,
790 	    isns->i_ai->ai_protocol);
791 	if (s < 0) {
792 		log_warn("socket(2) failed for %s", isns->i_addr);
793 		return (-1);
794 	}
795 	if (connect(s, isns->i_ai->ai_addr, isns->i_ai->ai_addrlen)) {
796 		log_warn("connect(2) failed for %s", isns->i_addr);
797 		close(s);
798 		return (-1);
799 	}
800 	return(s);
801 }
802 
803 static int
804 isns_do_register(struct isns *isns, int s, const char *hostname)
805 {
806 	struct conf *conf = isns->i_conf;
807 	struct target *target;
808 	struct portal *portal;
809 	struct portal_group *pg;
810 	struct port *port;
811 	struct isns_req *req;
812 	int res = 0;
813 	uint32_t error;
814 
815 	req = isns_req_create(ISNS_FUNC_DEVATTRREG, ISNS_FLAG_CLIENT);
816 	isns_req_add_str(req, 32, TAILQ_FIRST(&conf->conf_targets)->t_name);
817 	isns_req_add_delim(req);
818 	isns_req_add_str(req, 1, hostname);
819 	isns_req_add_32(req, 2, 2); /* 2 -- iSCSI */
820 	isns_req_add_32(req, 6, conf->conf_isns_period);
821 	TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
822 		if (pg->pg_unassigned)
823 			continue;
824 		TAILQ_FOREACH(portal, &pg->pg_portals, p_next) {
825 			isns_req_add_addr(req, 16, portal->p_ai);
826 			isns_req_add_port(req, 17, portal->p_ai);
827 		}
828 	}
829 	TAILQ_FOREACH(target, &conf->conf_targets, t_next) {
830 		isns_req_add_str(req, 32, target->t_name);
831 		isns_req_add_32(req, 33, 1); /* 1 -- Target*/
832 		if (target->t_alias != NULL)
833 			isns_req_add_str(req, 34, target->t_alias);
834 		TAILQ_FOREACH(port, &target->t_ports, p_ts) {
835 			if ((pg = port->p_portal_group) == NULL)
836 				continue;
837 			isns_req_add_32(req, 51, pg->pg_tag);
838 			TAILQ_FOREACH(portal, &pg->pg_portals, p_next) {
839 				isns_req_add_addr(req, 49, portal->p_ai);
840 				isns_req_add_port(req, 50, portal->p_ai);
841 			}
842 		}
843 	}
844 	res = isns_req_send(s, req);
845 	if (res < 0) {
846 		log_warn("send(2) failed for %s", isns->i_addr);
847 		goto quit;
848 	}
849 	res = isns_req_receive(s, req);
850 	if (res < 0) {
851 		log_warn("receive(2) failed for %s", isns->i_addr);
852 		goto quit;
853 	}
854 	error = isns_req_get_status(req);
855 	if (error != 0) {
856 		log_warnx("iSNS register error %d for %s", error, isns->i_addr);
857 		res = -1;
858 	}
859 quit:
860 	isns_req_free(req);
861 	return (res);
862 }
863 
864 static int
865 isns_do_check(struct isns *isns, int s, const char *hostname)
866 {
867 	struct conf *conf = isns->i_conf;
868 	struct isns_req *req;
869 	int res = 0;
870 	uint32_t error;
871 
872 	req = isns_req_create(ISNS_FUNC_DEVATTRQRY, ISNS_FLAG_CLIENT);
873 	isns_req_add_str(req, 32, TAILQ_FIRST(&conf->conf_targets)->t_name);
874 	isns_req_add_str(req, 1, hostname);
875 	isns_req_add_delim(req);
876 	isns_req_add(req, 2, 0, NULL);
877 	res = isns_req_send(s, req);
878 	if (res < 0) {
879 		log_warn("send(2) failed for %s", isns->i_addr);
880 		goto quit;
881 	}
882 	res = isns_req_receive(s, req);
883 	if (res < 0) {
884 		log_warn("receive(2) failed for %s", isns->i_addr);
885 		goto quit;
886 	}
887 	error = isns_req_get_status(req);
888 	if (error != 0) {
889 		log_warnx("iSNS check error %d for %s", error, isns->i_addr);
890 		res = -1;
891 	}
892 quit:
893 	isns_req_free(req);
894 	return (res);
895 }
896 
897 static int
898 isns_do_deregister(struct isns *isns, int s, const char *hostname)
899 {
900 	struct conf *conf = isns->i_conf;
901 	struct isns_req *req;
902 	int res = 0;
903 	uint32_t error;
904 
905 	req = isns_req_create(ISNS_FUNC_DEVDEREG, ISNS_FLAG_CLIENT);
906 	isns_req_add_str(req, 32, TAILQ_FIRST(&conf->conf_targets)->t_name);
907 	isns_req_add_delim(req);
908 	isns_req_add_str(req, 1, hostname);
909 	res = isns_req_send(s, req);
910 	if (res < 0) {
911 		log_warn("send(2) failed for %s", isns->i_addr);
912 		goto quit;
913 	}
914 	res = isns_req_receive(s, req);
915 	if (res < 0) {
916 		log_warn("receive(2) failed for %s", isns->i_addr);
917 		goto quit;
918 	}
919 	error = isns_req_get_status(req);
920 	if (error != 0) {
921 		log_warnx("iSNS deregister error %d for %s", error, isns->i_addr);
922 		res = -1;
923 	}
924 quit:
925 	isns_req_free(req);
926 	return (res);
927 }
928 
929 void
930 isns_register(struct isns *isns, struct isns *oldisns)
931 {
932 	struct conf *conf = isns->i_conf;
933 	int error, s;
934 	char hostname[256];
935 
936 	if (TAILQ_EMPTY(&conf->conf_targets) ||
937 	    TAILQ_EMPTY(&conf->conf_portal_groups))
938 		return;
939 	set_timeout(conf->conf_isns_timeout, false);
940 	s = isns_do_connect(isns);
941 	if (s < 0) {
942 		set_timeout(0, false);
943 		return;
944 	}
945 	error = gethostname(hostname, sizeof(hostname));
946 	if (error != 0)
947 		log_err(1, "gethostname");
948 
949 	if (oldisns == NULL || TAILQ_EMPTY(&oldisns->i_conf->conf_targets))
950 		oldisns = isns;
951 	isns_do_deregister(oldisns, s, hostname);
952 	isns_do_register(isns, s, hostname);
953 	close(s);
954 	set_timeout(0, false);
955 }
956 
957 void
958 isns_check(struct isns *isns)
959 {
960 	struct conf *conf = isns->i_conf;
961 	int error, s, res;
962 	char hostname[256];
963 
964 	if (TAILQ_EMPTY(&conf->conf_targets) ||
965 	    TAILQ_EMPTY(&conf->conf_portal_groups))
966 		return;
967 	set_timeout(conf->conf_isns_timeout, false);
968 	s = isns_do_connect(isns);
969 	if (s < 0) {
970 		set_timeout(0, false);
971 		return;
972 	}
973 	error = gethostname(hostname, sizeof(hostname));
974 	if (error != 0)
975 		log_err(1, "gethostname");
976 
977 	res = isns_do_check(isns, s, hostname);
978 	if (res < 0) {
979 		isns_do_deregister(isns, s, hostname);
980 		isns_do_register(isns, s, hostname);
981 	}
982 	close(s);
983 	set_timeout(0, false);
984 }
985 
986 void
987 isns_deregister(struct isns *isns)
988 {
989 	struct conf *conf = isns->i_conf;
990 	int error, s;
991 	char hostname[256];
992 
993 	if (TAILQ_EMPTY(&conf->conf_targets) ||
994 	    TAILQ_EMPTY(&conf->conf_portal_groups))
995 		return;
996 	set_timeout(conf->conf_isns_timeout, false);
997 	s = isns_do_connect(isns);
998 	if (s < 0)
999 		return;
1000 	error = gethostname(hostname, sizeof(hostname));
1001 	if (error != 0)
1002 		log_err(1, "gethostname");
1003 
1004 	isns_do_deregister(isns, s, hostname);
1005 	close(s);
1006 	set_timeout(0, false);
1007 }
1008 
1009 int
1010 portal_group_set_filter(struct portal_group *pg, const char *str)
1011 {
1012 	int filter;
1013 
1014 	if (strcmp(str, "none") == 0) {
1015 		filter = PG_FILTER_NONE;
1016 	} else if (strcmp(str, "portal") == 0) {
1017 		filter = PG_FILTER_PORTAL;
1018 	} else if (strcmp(str, "portal-name") == 0) {
1019 		filter = PG_FILTER_PORTAL_NAME;
1020 	} else if (strcmp(str, "portal-name-auth") == 0) {
1021 		filter = PG_FILTER_PORTAL_NAME_AUTH;
1022 	} else {
1023 		log_warnx("invalid discovery-filter \"%s\" for portal-group "
1024 		    "\"%s\"; valid values are \"none\", \"portal\", "
1025 		    "\"portal-name\", and \"portal-name-auth\"",
1026 		    str, pg->pg_name);
1027 		return (1);
1028 	}
1029 
1030 	if (pg->pg_discovery_filter != PG_FILTER_UNKNOWN &&
1031 	    pg->pg_discovery_filter != filter) {
1032 		log_warnx("cannot set discovery-filter to \"%s\" for "
1033 		    "portal-group \"%s\"; already has a different "
1034 		    "value", str, pg->pg_name);
1035 		return (1);
1036 	}
1037 
1038 	pg->pg_discovery_filter = filter;
1039 
1040 	return (0);
1041 }
1042 
1043 int
1044 portal_group_set_offload(struct portal_group *pg, const char *offload)
1045 {
1046 
1047 	if (pg->pg_offload != NULL) {
1048 		log_warnx("cannot set offload to \"%s\" for "
1049 		    "portal-group \"%s\"; already defined",
1050 		    offload, pg->pg_name);
1051 		return (1);
1052 	}
1053 
1054 	pg->pg_offload = checked_strdup(offload);
1055 
1056 	return (0);
1057 }
1058 
1059 int
1060 portal_group_set_redirection(struct portal_group *pg, const char *addr)
1061 {
1062 
1063 	if (pg->pg_redirection != NULL) {
1064 		log_warnx("cannot set redirection to \"%s\" for "
1065 		    "portal-group \"%s\"; already defined",
1066 		    addr, pg->pg_name);
1067 		return (1);
1068 	}
1069 
1070 	pg->pg_redirection = checked_strdup(addr);
1071 
1072 	return (0);
1073 }
1074 
1075 static bool
1076 valid_hex(const char ch)
1077 {
1078 	switch (ch) {
1079 	case '0':
1080 	case '1':
1081 	case '2':
1082 	case '3':
1083 	case '4':
1084 	case '5':
1085 	case '6':
1086 	case '7':
1087 	case '8':
1088 	case '9':
1089 	case 'a':
1090 	case 'A':
1091 	case 'b':
1092 	case 'B':
1093 	case 'c':
1094 	case 'C':
1095 	case 'd':
1096 	case 'D':
1097 	case 'e':
1098 	case 'E':
1099 	case 'f':
1100 	case 'F':
1101 		return (true);
1102 	default:
1103 		return (false);
1104 	}
1105 }
1106 
1107 bool
1108 valid_iscsi_name(const char *name)
1109 {
1110 	int i;
1111 
1112 	if (strlen(name) >= MAX_NAME_LEN) {
1113 		log_warnx("overlong name for target \"%s\"; max length allowed "
1114 		    "by iSCSI specification is %d characters",
1115 		    name, MAX_NAME_LEN);
1116 		return (false);
1117 	}
1118 
1119 	/*
1120 	 * In the cases below, we don't return an error, just in case the admin
1121 	 * was right, and we're wrong.
1122 	 */
1123 	if (strncasecmp(name, "iqn.", strlen("iqn.")) == 0) {
1124 		for (i = strlen("iqn."); name[i] != '\0'; i++) {
1125 			/*
1126 			 * XXX: We should verify UTF-8 normalisation, as defined
1127 			 *      by 3.2.6.2: iSCSI Name Encoding.
1128 			 */
1129 			if (isalnum(name[i]))
1130 				continue;
1131 			if (name[i] == '-' || name[i] == '.' || name[i] == ':')
1132 				continue;
1133 			log_warnx("invalid character \"%c\" in target name "
1134 			    "\"%s\"; allowed characters are letters, digits, "
1135 			    "'-', '.', and ':'", name[i], name);
1136 			break;
1137 		}
1138 		/*
1139 		 * XXX: Check more stuff: valid date and a valid reversed domain.
1140 		 */
1141 	} else if (strncasecmp(name, "eui.", strlen("eui.")) == 0) {
1142 		if (strlen(name) != strlen("eui.") + 16)
1143 			log_warnx("invalid target name \"%s\"; the \"eui.\" "
1144 			    "should be followed by exactly 16 hexadecimal "
1145 			    "digits", name);
1146 		for (i = strlen("eui."); name[i] != '\0'; i++) {
1147 			if (!valid_hex(name[i])) {
1148 				log_warnx("invalid character \"%c\" in target "
1149 				    "name \"%s\"; allowed characters are 1-9 "
1150 				    "and A-F", name[i], name);
1151 				break;
1152 			}
1153 		}
1154 	} else if (strncasecmp(name, "naa.", strlen("naa.")) == 0) {
1155 		if (strlen(name) > strlen("naa.") + 32)
1156 			log_warnx("invalid target name \"%s\"; the \"naa.\" "
1157 			    "should be followed by at most 32 hexadecimal "
1158 			    "digits", name);
1159 		for (i = strlen("naa."); name[i] != '\0'; i++) {
1160 			if (!valid_hex(name[i])) {
1161 				log_warnx("invalid character \"%c\" in target "
1162 				    "name \"%s\"; allowed characters are 1-9 "
1163 				    "and A-F", name[i], name);
1164 				break;
1165 			}
1166 		}
1167 	} else {
1168 		log_warnx("invalid target name \"%s\"; should start with "
1169 		    "either \"iqn.\", \"eui.\", or \"naa.\"",
1170 		    name);
1171 	}
1172 	return (true);
1173 }
1174 
1175 struct pport *
1176 pport_new(struct kports *kports, const char *name, uint32_t ctl_port)
1177 {
1178 	struct pport *pp;
1179 
1180 	pp = calloc(1, sizeof(*pp));
1181 	if (pp == NULL)
1182 		log_err(1, "calloc");
1183 	pp->pp_kports = kports;
1184 	pp->pp_name = checked_strdup(name);
1185 	pp->pp_ctl_port = ctl_port;
1186 	TAILQ_INIT(&pp->pp_ports);
1187 	TAILQ_INSERT_TAIL(&kports->pports, pp, pp_next);
1188 	return (pp);
1189 }
1190 
1191 struct pport *
1192 pport_find(const struct kports *kports, const char *name)
1193 {
1194 	struct pport *pp;
1195 
1196 	TAILQ_FOREACH(pp, &kports->pports, pp_next) {
1197 		if (strcasecmp(pp->pp_name, name) == 0)
1198 			return (pp);
1199 	}
1200 	return (NULL);
1201 }
1202 
1203 struct pport *
1204 pport_copy(struct pport *pp, struct kports *kports)
1205 {
1206 	struct pport *ppnew;
1207 
1208 	ppnew = pport_new(kports, pp->pp_name, pp->pp_ctl_port);
1209 	return (ppnew);
1210 }
1211 
1212 void
1213 pport_delete(struct pport *pp)
1214 {
1215 	struct port *port, *tport;
1216 
1217 	TAILQ_FOREACH_SAFE(port, &pp->pp_ports, p_ts, tport)
1218 		port_delete(port);
1219 	TAILQ_REMOVE(&pp->pp_kports->pports, pp, pp_next);
1220 	free(pp->pp_name);
1221 	free(pp);
1222 }
1223 
1224 struct port *
1225 port_new(struct conf *conf, struct target *target, struct portal_group *pg)
1226 {
1227 	struct port *port;
1228 	char *name;
1229 	int ret;
1230 
1231 	ret = asprintf(&name, "%s-%s", pg->pg_name, target->t_name);
1232 	if (ret <= 0)
1233 		log_err(1, "asprintf");
1234 	if (port_find(conf, name) != NULL) {
1235 		log_warnx("duplicate port \"%s\"", name);
1236 		free(name);
1237 		return (NULL);
1238 	}
1239 	port = calloc(1, sizeof(*port));
1240 	if (port == NULL)
1241 		log_err(1, "calloc");
1242 	port->p_conf = conf;
1243 	port->p_name = name;
1244 	port->p_ioctl_port = 0;
1245 	TAILQ_INSERT_TAIL(&conf->conf_ports, port, p_next);
1246 	TAILQ_INSERT_TAIL(&target->t_ports, port, p_ts);
1247 	port->p_target = target;
1248 	TAILQ_INSERT_TAIL(&pg->pg_ports, port, p_pgs);
1249 	port->p_portal_group = pg;
1250 	return (port);
1251 }
1252 
1253 struct port *
1254 port_new_ioctl(struct conf *conf, struct kports *kports, struct target *target,
1255     int pp, int vp)
1256 {
1257 	struct pport *pport;
1258 	struct port *port;
1259 	char *pname;
1260 	char *name;
1261 	int ret;
1262 
1263 	ret = asprintf(&pname, "ioctl/%d/%d", pp, vp);
1264 	if (ret <= 0) {
1265 		log_err(1, "asprintf");
1266 		return (NULL);
1267 	}
1268 
1269 	pport = pport_find(kports, pname);
1270 	if (pport != NULL) {
1271 		free(pname);
1272 		return (port_new_pp(conf, target, pport));
1273 	}
1274 
1275 	ret = asprintf(&name, "%s-%s", pname, target->t_name);
1276 	free(pname);
1277 
1278 	if (ret <= 0)
1279 		log_err(1, "asprintf");
1280 	if (port_find(conf, name) != NULL) {
1281 		log_warnx("duplicate port \"%s\"", name);
1282 		free(name);
1283 		return (NULL);
1284 	}
1285 	port = calloc(1, sizeof(*port));
1286 	if (port == NULL)
1287 		log_err(1, "calloc");
1288 	port->p_conf = conf;
1289 	port->p_name = name;
1290 	port->p_ioctl_port = 1;
1291 	port->p_ioctl_pp = pp;
1292 	port->p_ioctl_vp = vp;
1293 	TAILQ_INSERT_TAIL(&conf->conf_ports, port, p_next);
1294 	TAILQ_INSERT_TAIL(&target->t_ports, port, p_ts);
1295 	port->p_target = target;
1296 	return (port);
1297 }
1298 
1299 struct port *
1300 port_new_pp(struct conf *conf, struct target *target, struct pport *pp)
1301 {
1302 	struct port *port;
1303 	char *name;
1304 	int ret;
1305 
1306 	ret = asprintf(&name, "%s-%s", pp->pp_name, target->t_name);
1307 	if (ret <= 0)
1308 		log_err(1, "asprintf");
1309 	if (port_find(conf, name) != NULL) {
1310 		log_warnx("duplicate port \"%s\"", name);
1311 		free(name);
1312 		return (NULL);
1313 	}
1314 	port = calloc(1, sizeof(*port));
1315 	if (port == NULL)
1316 		log_err(1, "calloc");
1317 	port->p_conf = conf;
1318 	port->p_name = name;
1319 	TAILQ_INSERT_TAIL(&conf->conf_ports, port, p_next);
1320 	TAILQ_INSERT_TAIL(&target->t_ports, port, p_ts);
1321 	port->p_target = target;
1322 	TAILQ_INSERT_TAIL(&pp->pp_ports, port, p_pps);
1323 	port->p_pport = pp;
1324 	return (port);
1325 }
1326 
1327 struct port *
1328 port_find(const struct conf *conf, const char *name)
1329 {
1330 	struct port *port;
1331 
1332 	TAILQ_FOREACH(port, &conf->conf_ports, p_next) {
1333 		if (strcasecmp(port->p_name, name) == 0)
1334 			return (port);
1335 	}
1336 
1337 	return (NULL);
1338 }
1339 
1340 struct port *
1341 port_find_in_pg(const struct portal_group *pg, const char *target)
1342 {
1343 	struct port *port;
1344 
1345 	TAILQ_FOREACH(port, &pg->pg_ports, p_pgs) {
1346 		if (strcasecmp(port->p_target->t_name, target) == 0)
1347 			return (port);
1348 	}
1349 
1350 	return (NULL);
1351 }
1352 
1353 void
1354 port_delete(struct port *port)
1355 {
1356 
1357 	if (port->p_portal_group)
1358 		TAILQ_REMOVE(&port->p_portal_group->pg_ports, port, p_pgs);
1359 	if (port->p_pport)
1360 		TAILQ_REMOVE(&port->p_pport->pp_ports, port, p_pps);
1361 	if (port->p_target)
1362 		TAILQ_REMOVE(&port->p_target->t_ports, port, p_ts);
1363 	TAILQ_REMOVE(&port->p_conf->conf_ports, port, p_next);
1364 	free(port->p_name);
1365 	free(port);
1366 }
1367 
1368 int
1369 port_is_dummy(struct port *port)
1370 {
1371 
1372 	if (port->p_portal_group) {
1373 		if (port->p_portal_group->pg_foreign)
1374 			return (1);
1375 		if (TAILQ_EMPTY(&port->p_portal_group->pg_portals))
1376 			return (1);
1377 	}
1378 	return (0);
1379 }
1380 
1381 struct target *
1382 target_new(struct conf *conf, const char *name)
1383 {
1384 	struct target *targ;
1385 	int i, len;
1386 
1387 	targ = target_find(conf, name);
1388 	if (targ != NULL) {
1389 		log_warnx("duplicated target \"%s\"", name);
1390 		return (NULL);
1391 	}
1392 	if (valid_iscsi_name(name) == false) {
1393 		log_warnx("target name \"%s\" is invalid", name);
1394 		return (NULL);
1395 	}
1396 	targ = calloc(1, sizeof(*targ));
1397 	if (targ == NULL)
1398 		log_err(1, "calloc");
1399 	targ->t_name = checked_strdup(name);
1400 
1401 	/*
1402 	 * RFC 3722 requires us to normalize the name to lowercase.
1403 	 */
1404 	len = strlen(name);
1405 	for (i = 0; i < len; i++)
1406 		targ->t_name[i] = tolower(targ->t_name[i]);
1407 
1408 	targ->t_conf = conf;
1409 	TAILQ_INIT(&targ->t_ports);
1410 	TAILQ_INSERT_TAIL(&conf->conf_targets, targ, t_next);
1411 
1412 	return (targ);
1413 }
1414 
1415 void
1416 target_delete(struct target *targ)
1417 {
1418 	struct port *port, *tport;
1419 
1420 	TAILQ_FOREACH_SAFE(port, &targ->t_ports, p_ts, tport)
1421 		port_delete(port);
1422 	TAILQ_REMOVE(&targ->t_conf->conf_targets, targ, t_next);
1423 
1424 	free(targ->t_pport);
1425 	free(targ->t_name);
1426 	free(targ->t_redirection);
1427 	free(targ);
1428 }
1429 
1430 struct target *
1431 target_find(struct conf *conf, const char *name)
1432 {
1433 	struct target *targ;
1434 
1435 	TAILQ_FOREACH(targ, &conf->conf_targets, t_next) {
1436 		if (strcasecmp(targ->t_name, name) == 0)
1437 			return (targ);
1438 	}
1439 
1440 	return (NULL);
1441 }
1442 
1443 int
1444 target_set_redirection(struct target *target, const char *addr)
1445 {
1446 
1447 	if (target->t_redirection != NULL) {
1448 		log_warnx("cannot set redirection to \"%s\" for "
1449 		    "target \"%s\"; already defined",
1450 		    addr, target->t_name);
1451 		return (1);
1452 	}
1453 
1454 	target->t_redirection = checked_strdup(addr);
1455 
1456 	return (0);
1457 }
1458 
1459 struct lun *
1460 lun_new(struct conf *conf, const char *name)
1461 {
1462 	struct lun *lun;
1463 
1464 	lun = lun_find(conf, name);
1465 	if (lun != NULL) {
1466 		log_warnx("duplicated lun \"%s\"", name);
1467 		return (NULL);
1468 	}
1469 
1470 	lun = calloc(1, sizeof(*lun));
1471 	if (lun == NULL)
1472 		log_err(1, "calloc");
1473 	lun->l_conf = conf;
1474 	lun->l_name = checked_strdup(name);
1475 	TAILQ_INIT(&lun->l_options);
1476 	TAILQ_INSERT_TAIL(&conf->conf_luns, lun, l_next);
1477 	lun->l_ctl_lun = -1;
1478 
1479 	return (lun);
1480 }
1481 
1482 void
1483 lun_delete(struct lun *lun)
1484 {
1485 	struct target *targ;
1486 	struct option *o, *tmp;
1487 	int i;
1488 
1489 	TAILQ_FOREACH(targ, &lun->l_conf->conf_targets, t_next) {
1490 		for (i = 0; i < MAX_LUNS; i++) {
1491 			if (targ->t_luns[i] == lun)
1492 				targ->t_luns[i] = NULL;
1493 		}
1494 	}
1495 	TAILQ_REMOVE(&lun->l_conf->conf_luns, lun, l_next);
1496 
1497 	TAILQ_FOREACH_SAFE(o, &lun->l_options, o_next, tmp)
1498 		option_delete(&lun->l_options, o);
1499 	free(lun->l_name);
1500 	free(lun->l_backend);
1501 	free(lun->l_device_id);
1502 	free(lun->l_path);
1503 	free(lun->l_scsiname);
1504 	free(lun->l_serial);
1505 	free(lun);
1506 }
1507 
1508 struct lun *
1509 lun_find(const struct conf *conf, const char *name)
1510 {
1511 	struct lun *lun;
1512 
1513 	TAILQ_FOREACH(lun, &conf->conf_luns, l_next) {
1514 		if (strcmp(lun->l_name, name) == 0)
1515 			return (lun);
1516 	}
1517 
1518 	return (NULL);
1519 }
1520 
1521 void
1522 lun_set_backend(struct lun *lun, const char *value)
1523 {
1524 	free(lun->l_backend);
1525 	lun->l_backend = checked_strdup(value);
1526 }
1527 
1528 void
1529 lun_set_blocksize(struct lun *lun, size_t value)
1530 {
1531 
1532 	lun->l_blocksize = value;
1533 }
1534 
1535 void
1536 lun_set_device_type(struct lun *lun, uint8_t value)
1537 {
1538 
1539 	lun->l_device_type = value;
1540 }
1541 
1542 void
1543 lun_set_device_id(struct lun *lun, const char *value)
1544 {
1545 	free(lun->l_device_id);
1546 	lun->l_device_id = checked_strdup(value);
1547 }
1548 
1549 void
1550 lun_set_path(struct lun *lun, const char *value)
1551 {
1552 	free(lun->l_path);
1553 	lun->l_path = checked_strdup(value);
1554 }
1555 
1556 void
1557 lun_set_scsiname(struct lun *lun, const char *value)
1558 {
1559 	free(lun->l_scsiname);
1560 	lun->l_scsiname = checked_strdup(value);
1561 }
1562 
1563 void
1564 lun_set_serial(struct lun *lun, const char *value)
1565 {
1566 	free(lun->l_serial);
1567 	lun->l_serial = checked_strdup(value);
1568 }
1569 
1570 void
1571 lun_set_size(struct lun *lun, size_t value)
1572 {
1573 
1574 	lun->l_size = value;
1575 }
1576 
1577 void
1578 lun_set_ctl_lun(struct lun *lun, uint32_t value)
1579 {
1580 
1581 	lun->l_ctl_lun = value;
1582 }
1583 
1584 struct option *
1585 option_new(struct options *options, const char *name, const char *value)
1586 {
1587 	struct option *o;
1588 
1589 	o = option_find(options, name);
1590 	if (o != NULL) {
1591 		log_warnx("duplicated option \"%s\"", name);
1592 		return (NULL);
1593 	}
1594 
1595 	o = calloc(1, sizeof(*o));
1596 	if (o == NULL)
1597 		log_err(1, "calloc");
1598 	o->o_name = checked_strdup(name);
1599 	o->o_value = checked_strdup(value);
1600 	TAILQ_INSERT_TAIL(options, o, o_next);
1601 
1602 	return (o);
1603 }
1604 
1605 void
1606 option_delete(struct options *options, struct option *o)
1607 {
1608 
1609 	TAILQ_REMOVE(options, o, o_next);
1610 	free(o->o_name);
1611 	free(o->o_value);
1612 	free(o);
1613 }
1614 
1615 struct option *
1616 option_find(const struct options *options, const char *name)
1617 {
1618 	struct option *o;
1619 
1620 	TAILQ_FOREACH(o, options, o_next) {
1621 		if (strcmp(o->o_name, name) == 0)
1622 			return (o);
1623 	}
1624 
1625 	return (NULL);
1626 }
1627 
1628 void
1629 option_set(struct option *o, const char *value)
1630 {
1631 
1632 	free(o->o_value);
1633 	o->o_value = checked_strdup(value);
1634 }
1635 
1636 #ifdef ICL_KERNEL_PROXY
1637 
1638 static void
1639 pdu_receive_proxy(struct pdu *pdu)
1640 {
1641 	struct connection *conn;
1642 	size_t len;
1643 
1644 	assert(proxy_mode);
1645 	conn = pdu->pdu_connection;
1646 
1647 	kernel_receive(pdu);
1648 
1649 	len = pdu_ahs_length(pdu);
1650 	if (len > 0)
1651 		log_errx(1, "protocol error: non-empty AHS");
1652 
1653 	len = pdu_data_segment_length(pdu);
1654 	assert(len <= (size_t)conn->conn_max_recv_data_segment_length);
1655 	pdu->pdu_data_len = len;
1656 }
1657 
1658 static void
1659 pdu_send_proxy(struct pdu *pdu)
1660 {
1661 
1662 	assert(proxy_mode);
1663 
1664 	pdu_set_data_segment_length(pdu, pdu->pdu_data_len);
1665 	kernel_send(pdu);
1666 }
1667 
1668 #endif /* ICL_KERNEL_PROXY */
1669 
1670 static void
1671 pdu_fail(const struct connection *conn __unused, const char *reason __unused)
1672 {
1673 }
1674 
1675 static struct ctld_connection *
1676 connection_new(struct portal *portal, int fd, const char *host,
1677     const struct sockaddr *client_sa)
1678 {
1679 	struct ctld_connection *conn;
1680 
1681 	conn = calloc(1, sizeof(*conn));
1682 	if (conn == NULL)
1683 		log_err(1, "calloc");
1684 	connection_init(&conn->conn, &conn_ops, proxy_mode);
1685 	conn->conn.conn_socket = fd;
1686 	conn->conn_portal = portal;
1687 	conn->conn_initiator_addr = checked_strdup(host);
1688 	memcpy(&conn->conn_initiator_sa, client_sa, client_sa->sa_len);
1689 
1690 	return (conn);
1691 }
1692 
1693 #if 0
1694 static void
1695 conf_print(struct conf *conf)
1696 {
1697 	struct auth_group *ag;
1698 	struct auth *auth;
1699 	struct auth_name *auth_name;
1700 	struct auth_portal *auth_portal;
1701 	struct portal_group *pg;
1702 	struct portal *portal;
1703 	struct target *targ;
1704 	struct lun *lun;
1705 	struct option *o;
1706 
1707 	TAILQ_FOREACH(ag, &conf->conf_auth_groups, ag_next) {
1708 		fprintf(stderr, "auth-group %s {\n", ag->ag_name);
1709 		TAILQ_FOREACH(auth, &ag->ag_auths, a_next)
1710 			fprintf(stderr, "\t chap-mutual %s %s %s %s\n",
1711 			    auth->a_user, auth->a_secret,
1712 			    auth->a_mutual_user, auth->a_mutual_secret);
1713 		TAILQ_FOREACH(auth_name, &ag->ag_names, an_next)
1714 			fprintf(stderr, "\t initiator-name %s\n",
1715 			    auth_name->an_initiator_name);
1716 		TAILQ_FOREACH(auth_portal, &ag->ag_portals, ap_next)
1717 			fprintf(stderr, "\t initiator-portal %s\n",
1718 			    auth_portal->ap_initiator_portal);
1719 		fprintf(stderr, "}\n");
1720 	}
1721 	TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
1722 		fprintf(stderr, "portal-group %s {\n", pg->pg_name);
1723 		TAILQ_FOREACH(portal, &pg->pg_portals, p_next)
1724 			fprintf(stderr, "\t listen %s\n", portal->p_listen);
1725 		fprintf(stderr, "}\n");
1726 	}
1727 	TAILQ_FOREACH(lun, &conf->conf_luns, l_next) {
1728 		fprintf(stderr, "\tlun %s {\n", lun->l_name);
1729 		fprintf(stderr, "\t\tpath %s\n", lun->l_path);
1730 		TAILQ_FOREACH(o, &lun->l_options, o_next)
1731 			fprintf(stderr, "\t\toption %s %s\n",
1732 			    o->o_name, o->o_value);
1733 		fprintf(stderr, "\t}\n");
1734 	}
1735 	TAILQ_FOREACH(targ, &conf->conf_targets, t_next) {
1736 		fprintf(stderr, "target %s {\n", targ->t_name);
1737 		if (targ->t_alias != NULL)
1738 			fprintf(stderr, "\t alias %s\n", targ->t_alias);
1739 		fprintf(stderr, "}\n");
1740 	}
1741 }
1742 #endif
1743 
1744 static int
1745 conf_verify_lun(struct lun *lun)
1746 {
1747 	const struct lun *lun2;
1748 
1749 	if (lun->l_backend == NULL)
1750 		lun_set_backend(lun, "block");
1751 	if (strcmp(lun->l_backend, "block") == 0) {
1752 		if (lun->l_path == NULL) {
1753 			log_warnx("missing path for lun \"%s\"",
1754 			    lun->l_name);
1755 			return (1);
1756 		}
1757 	} else if (strcmp(lun->l_backend, "ramdisk") == 0) {
1758 		if (lun->l_size == 0) {
1759 			log_warnx("missing size for ramdisk-backed lun \"%s\"",
1760 			    lun->l_name);
1761 			return (1);
1762 		}
1763 		if (lun->l_path != NULL) {
1764 			log_warnx("path must not be specified "
1765 			    "for ramdisk-backed lun \"%s\"",
1766 			    lun->l_name);
1767 			return (1);
1768 		}
1769 	}
1770 	if (lun->l_blocksize == 0) {
1771 		if (lun->l_device_type == 5)
1772 			lun_set_blocksize(lun, DEFAULT_CD_BLOCKSIZE);
1773 		else
1774 			lun_set_blocksize(lun, DEFAULT_BLOCKSIZE);
1775 	} else if (lun->l_blocksize < 0) {
1776 		log_warnx("invalid blocksize for lun \"%s\"; "
1777 		    "must be larger than 0", lun->l_name);
1778 		return (1);
1779 	}
1780 	if (lun->l_size != 0 && lun->l_size % lun->l_blocksize != 0) {
1781 		log_warnx("invalid size for lun \"%s\"; "
1782 		    "must be multiple of blocksize", lun->l_name);
1783 		return (1);
1784 	}
1785 	TAILQ_FOREACH(lun2, &lun->l_conf->conf_luns, l_next) {
1786 		if (lun == lun2)
1787 			continue;
1788 		if (lun->l_path != NULL && lun2->l_path != NULL &&
1789 		    strcmp(lun->l_path, lun2->l_path) == 0) {
1790 			log_debugx("WARNING: path \"%s\" duplicated "
1791 			    "between lun \"%s\", and "
1792 			    "lun \"%s\"", lun->l_path,
1793 			    lun->l_name, lun2->l_name);
1794 		}
1795 	}
1796 
1797 	return (0);
1798 }
1799 
1800 int
1801 conf_verify(struct conf *conf)
1802 {
1803 	struct auth_group *ag;
1804 	struct portal_group *pg;
1805 	struct port *port;
1806 	struct target *targ;
1807 	struct lun *lun;
1808 	bool found;
1809 	int error, i;
1810 
1811 	if (conf->conf_pidfile_path == NULL)
1812 		conf->conf_pidfile_path = checked_strdup(DEFAULT_PIDFILE);
1813 
1814 	TAILQ_FOREACH(lun, &conf->conf_luns, l_next) {
1815 		error = conf_verify_lun(lun);
1816 		if (error != 0)
1817 			return (error);
1818 	}
1819 	TAILQ_FOREACH(targ, &conf->conf_targets, t_next) {
1820 		if (targ->t_auth_group == NULL) {
1821 			targ->t_auth_group = auth_group_find(conf,
1822 			    "default");
1823 			assert(targ->t_auth_group != NULL);
1824 		}
1825 		if (TAILQ_EMPTY(&targ->t_ports)) {
1826 			pg = portal_group_find(conf, "default");
1827 			assert(pg != NULL);
1828 			port_new(conf, targ, pg);
1829 		}
1830 		found = false;
1831 		for (i = 0; i < MAX_LUNS; i++) {
1832 			if (targ->t_luns[i] != NULL)
1833 				found = true;
1834 		}
1835 		if (!found && targ->t_redirection == NULL) {
1836 			log_warnx("no LUNs defined for target \"%s\"",
1837 			    targ->t_name);
1838 		}
1839 		if (found && targ->t_redirection != NULL) {
1840 			log_debugx("target \"%s\" contains luns, "
1841 			    " but configured for redirection",
1842 			    targ->t_name);
1843 		}
1844 	}
1845 	TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
1846 		assert(pg->pg_name != NULL);
1847 		if (pg->pg_discovery_auth_group == NULL) {
1848 			pg->pg_discovery_auth_group =
1849 			    auth_group_find(conf, "default");
1850 			assert(pg->pg_discovery_auth_group != NULL);
1851 		}
1852 
1853 		if (pg->pg_discovery_filter == PG_FILTER_UNKNOWN)
1854 			pg->pg_discovery_filter = PG_FILTER_NONE;
1855 
1856 		if (pg->pg_redirection != NULL) {
1857 			if (!TAILQ_EMPTY(&pg->pg_ports)) {
1858 				log_debugx("portal-group \"%s\" assigned "
1859 				    "to target, but configured "
1860 				    "for redirection",
1861 				    pg->pg_name);
1862 			}
1863 			pg->pg_unassigned = false;
1864 		} else if (!TAILQ_EMPTY(&pg->pg_ports)) {
1865 			pg->pg_unassigned = false;
1866 		} else {
1867 			if (strcmp(pg->pg_name, "default") != 0)
1868 				log_warnx("portal-group \"%s\" not assigned "
1869 				    "to any target", pg->pg_name);
1870 			pg->pg_unassigned = true;
1871 		}
1872 	}
1873 	TAILQ_FOREACH(ag, &conf->conf_auth_groups, ag_next) {
1874 		if (ag->ag_name == NULL)
1875 			assert(ag->ag_target != NULL);
1876 		else
1877 			assert(ag->ag_target == NULL);
1878 
1879 		found = false;
1880 		TAILQ_FOREACH(targ, &conf->conf_targets, t_next) {
1881 			if (targ->t_auth_group == ag) {
1882 				found = true;
1883 				break;
1884 			}
1885 		}
1886 		TAILQ_FOREACH(port, &conf->conf_ports, p_next) {
1887 			if (port->p_auth_group == ag) {
1888 				found = true;
1889 				break;
1890 			}
1891 		}
1892 		TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
1893 			if (pg->pg_discovery_auth_group == ag) {
1894 				found = true;
1895 				break;
1896 			}
1897 		}
1898 		if (!found && ag->ag_name != NULL &&
1899 		    strcmp(ag->ag_name, "default") != 0 &&
1900 		    strcmp(ag->ag_name, "no-authentication") != 0 &&
1901 		    strcmp(ag->ag_name, "no-access") != 0) {
1902 			log_warnx("auth-group \"%s\" not assigned "
1903 			    "to any target", ag->ag_name);
1904 		}
1905 	}
1906 
1907 	return (0);
1908 }
1909 
1910 static int
1911 conf_apply(struct conf *oldconf, struct conf *newconf)
1912 {
1913 	struct lun *oldlun, *newlun, *tmplun;
1914 	struct portal_group *oldpg, *newpg;
1915 	struct portal *oldp, *newp;
1916 	struct port *oldport, *newport, *tmpport;
1917 	struct isns *oldns, *newns;
1918 	int changed, cumulated_error = 0, error, sockbuf;
1919 	int one = 1;
1920 
1921 	if (oldconf->conf_debug != newconf->conf_debug) {
1922 		log_debugx("changing debug level to %d", newconf->conf_debug);
1923 		log_init(newconf->conf_debug);
1924 	}
1925 
1926 	if (oldconf->conf_pidfile_path != NULL &&
1927 	    newconf->conf_pidfile_path != NULL)
1928 	{
1929 		if (strcmp(oldconf->conf_pidfile_path,
1930 		           newconf->conf_pidfile_path) != 0)
1931 		{
1932 			/* pidfile has changed.  rename it */
1933 			log_debugx("moving pidfile to %s",
1934 				newconf->conf_pidfile_path);
1935 			if (rename(oldconf->conf_pidfile_path,
1936 				   newconf->conf_pidfile_path))
1937 			{
1938 				log_err(1, "renaming pidfile %s -> %s",
1939 					oldconf->conf_pidfile_path,
1940 					newconf->conf_pidfile_path);
1941 			}
1942 		}
1943 		newconf->conf_pidfh = oldconf->conf_pidfh;
1944 		oldconf->conf_pidfh = NULL;
1945 	}
1946 
1947 	/*
1948 	 * Go through the new portal groups, assigning tags or preserving old.
1949 	 */
1950 	TAILQ_FOREACH(newpg, &newconf->conf_portal_groups, pg_next) {
1951 		if (newpg->pg_tag != 0)
1952 			continue;
1953 		oldpg = portal_group_find(oldconf, newpg->pg_name);
1954 		if (oldpg != NULL)
1955 			newpg->pg_tag = oldpg->pg_tag;
1956 		else
1957 			newpg->pg_tag = ++last_portal_group_tag;
1958 	}
1959 
1960 	/* Deregister on removed iSNS servers. */
1961 	TAILQ_FOREACH(oldns, &oldconf->conf_isns, i_next) {
1962 		TAILQ_FOREACH(newns, &newconf->conf_isns, i_next) {
1963 			if (strcmp(oldns->i_addr, newns->i_addr) == 0)
1964 				break;
1965 		}
1966 		if (newns == NULL)
1967 			isns_deregister(oldns);
1968 	}
1969 
1970 	/*
1971 	 * XXX: If target or lun removal fails, we should somehow "move"
1972 	 *      the old lun or target into newconf, so that subsequent
1973 	 *      conf_apply() would try to remove them again.  That would
1974 	 *      be somewhat hairy, though, and lun deletion failures don't
1975 	 *      really happen, so leave it as it is for now.
1976 	 */
1977 	/*
1978 	 * First, remove any ports present in the old configuration
1979 	 * and missing in the new one.
1980 	 */
1981 	TAILQ_FOREACH_SAFE(oldport, &oldconf->conf_ports, p_next, tmpport) {
1982 		if (port_is_dummy(oldport))
1983 			continue;
1984 		newport = port_find(newconf, oldport->p_name);
1985 		if (newport != NULL && !port_is_dummy(newport))
1986 			continue;
1987 		log_debugx("removing port \"%s\"", oldport->p_name);
1988 		error = kernel_port_remove(oldport);
1989 		if (error != 0) {
1990 			log_warnx("failed to remove port %s",
1991 			    oldport->p_name);
1992 			/*
1993 			 * XXX: Uncomment after fixing the root cause.
1994 			 *
1995 			 * cumulated_error++;
1996 			 */
1997 		}
1998 	}
1999 
2000 	/*
2001 	 * Second, remove any LUNs present in the old configuration
2002 	 * and missing in the new one.
2003 	 */
2004 	TAILQ_FOREACH_SAFE(oldlun, &oldconf->conf_luns, l_next, tmplun) {
2005 		newlun = lun_find(newconf, oldlun->l_name);
2006 		if (newlun == NULL) {
2007 			log_debugx("lun \"%s\", CTL lun %d "
2008 			    "not found in new configuration; "
2009 			    "removing", oldlun->l_name, oldlun->l_ctl_lun);
2010 			error = kernel_lun_remove(oldlun);
2011 			if (error != 0) {
2012 				log_warnx("failed to remove lun \"%s\", "
2013 				    "CTL lun %d",
2014 				    oldlun->l_name, oldlun->l_ctl_lun);
2015 				cumulated_error++;
2016 			}
2017 			continue;
2018 		}
2019 
2020 		/*
2021 		 * Also remove the LUNs changed by more than size.
2022 		 */
2023 		changed = 0;
2024 		assert(oldlun->l_backend != NULL);
2025 		assert(newlun->l_backend != NULL);
2026 		if (strcmp(newlun->l_backend, oldlun->l_backend) != 0) {
2027 			log_debugx("backend for lun \"%s\", "
2028 			    "CTL lun %d changed; removing",
2029 			    oldlun->l_name, oldlun->l_ctl_lun);
2030 			changed = 1;
2031 		}
2032 		if (oldlun->l_blocksize != newlun->l_blocksize) {
2033 			log_debugx("blocksize for lun \"%s\", "
2034 			    "CTL lun %d changed; removing",
2035 			    oldlun->l_name, oldlun->l_ctl_lun);
2036 			changed = 1;
2037 		}
2038 		if (newlun->l_device_id != NULL &&
2039 		    (oldlun->l_device_id == NULL ||
2040 		     strcmp(oldlun->l_device_id, newlun->l_device_id) !=
2041 		     0)) {
2042 			log_debugx("device-id for lun \"%s\", "
2043 			    "CTL lun %d changed; removing",
2044 			    oldlun->l_name, oldlun->l_ctl_lun);
2045 			changed = 1;
2046 		}
2047 		if (newlun->l_path != NULL &&
2048 		    (oldlun->l_path == NULL ||
2049 		     strcmp(oldlun->l_path, newlun->l_path) != 0)) {
2050 			log_debugx("path for lun \"%s\", "
2051 			    "CTL lun %d, changed; removing",
2052 			    oldlun->l_name, oldlun->l_ctl_lun);
2053 			changed = 1;
2054 		}
2055 		if (newlun->l_serial != NULL &&
2056 		    (oldlun->l_serial == NULL ||
2057 		     strcmp(oldlun->l_serial, newlun->l_serial) != 0)) {
2058 			log_debugx("serial for lun \"%s\", "
2059 			    "CTL lun %d changed; removing",
2060 			    oldlun->l_name, oldlun->l_ctl_lun);
2061 			changed = 1;
2062 		}
2063 		if (changed) {
2064 			error = kernel_lun_remove(oldlun);
2065 			if (error != 0) {
2066 				log_warnx("failed to remove lun \"%s\", "
2067 				    "CTL lun %d",
2068 				    oldlun->l_name, oldlun->l_ctl_lun);
2069 				cumulated_error++;
2070 			}
2071 			lun_delete(oldlun);
2072 			continue;
2073 		}
2074 
2075 		lun_set_ctl_lun(newlun, oldlun->l_ctl_lun);
2076 	}
2077 
2078 	TAILQ_FOREACH_SAFE(newlun, &newconf->conf_luns, l_next, tmplun) {
2079 		oldlun = lun_find(oldconf, newlun->l_name);
2080 		if (oldlun != NULL) {
2081 			log_debugx("modifying lun \"%s\", CTL lun %d",
2082 			    newlun->l_name, newlun->l_ctl_lun);
2083 			error = kernel_lun_modify(newlun);
2084 			if (error != 0) {
2085 				log_warnx("failed to "
2086 				    "modify lun \"%s\", CTL lun %d",
2087 				    newlun->l_name, newlun->l_ctl_lun);
2088 				cumulated_error++;
2089 			}
2090 			continue;
2091 		}
2092 		log_debugx("adding lun \"%s\"", newlun->l_name);
2093 		error = kernel_lun_add(newlun);
2094 		if (error != 0) {
2095 			log_warnx("failed to add lun \"%s\"", newlun->l_name);
2096 			lun_delete(newlun);
2097 			cumulated_error++;
2098 		}
2099 	}
2100 
2101 	/*
2102 	 * Now add new ports or modify existing ones.
2103 	 */
2104 	TAILQ_FOREACH_SAFE(newport, &newconf->conf_ports, p_next, tmpport) {
2105 		if (port_is_dummy(newport))
2106 			continue;
2107 		oldport = port_find(oldconf, newport->p_name);
2108 
2109 		if (oldport == NULL || port_is_dummy(oldport)) {
2110 			log_debugx("adding port \"%s\"", newport->p_name);
2111 			error = kernel_port_add(newport);
2112 		} else {
2113 			log_debugx("updating port \"%s\"", newport->p_name);
2114 			newport->p_ctl_port = oldport->p_ctl_port;
2115 			error = kernel_port_update(newport, oldport);
2116 		}
2117 		if (error != 0) {
2118 			log_warnx("failed to %s port %s",
2119 			    (oldport == NULL) ? "add" : "update",
2120 			    newport->p_name);
2121 			if (oldport == NULL || port_is_dummy(oldport))
2122 				port_delete(newport);
2123 			/*
2124 			 * XXX: Uncomment after fixing the root cause.
2125 			 *
2126 			 * cumulated_error++;
2127 			 */
2128 		}
2129 	}
2130 
2131 	/*
2132 	 * Go through the new portals, opening the sockets as necessary.
2133 	 */
2134 	TAILQ_FOREACH(newpg, &newconf->conf_portal_groups, pg_next) {
2135 		if (newpg->pg_foreign)
2136 			continue;
2137 		if (newpg->pg_unassigned) {
2138 			log_debugx("not listening on portal-group \"%s\", "
2139 			    "not assigned to any target",
2140 			    newpg->pg_name);
2141 			continue;
2142 		}
2143 		TAILQ_FOREACH(newp, &newpg->pg_portals, p_next) {
2144 			/*
2145 			 * Try to find already open portal and reuse
2146 			 * the listening socket.  We don't care about
2147 			 * what portal or portal group that was, what
2148 			 * matters is the listening address.
2149 			 */
2150 			TAILQ_FOREACH(oldpg, &oldconf->conf_portal_groups,
2151 			    pg_next) {
2152 				TAILQ_FOREACH(oldp, &oldpg->pg_portals,
2153 				    p_next) {
2154 					if (strcmp(newp->p_listen,
2155 					    oldp->p_listen) == 0 &&
2156 					    oldp->p_socket > 0) {
2157 						newp->p_socket =
2158 						    oldp->p_socket;
2159 						oldp->p_socket = 0;
2160 						break;
2161 					}
2162 				}
2163 			}
2164 			if (newp->p_socket > 0) {
2165 				/*
2166 				 * We're done with this portal.
2167 				 */
2168 				continue;
2169 			}
2170 
2171 #ifdef ICL_KERNEL_PROXY
2172 			if (proxy_mode) {
2173 				newpg->pg_conf->conf_portal_id++;
2174 				newp->p_id = newpg->pg_conf->conf_portal_id;
2175 				log_debugx("listening on %s, portal-group "
2176 				    "\"%s\", portal id %d, using ICL proxy",
2177 				    newp->p_listen, newpg->pg_name, newp->p_id);
2178 				kernel_listen(newp->p_ai, newp->p_iser,
2179 				    newp->p_id);
2180 				continue;
2181 			}
2182 #endif
2183 			assert(proxy_mode == false);
2184 			assert(newp->p_iser == false);
2185 
2186 			log_debugx("listening on %s, portal-group \"%s\"",
2187 			    newp->p_listen, newpg->pg_name);
2188 			newp->p_socket = socket(newp->p_ai->ai_family,
2189 			    newp->p_ai->ai_socktype,
2190 			    newp->p_ai->ai_protocol);
2191 			if (newp->p_socket < 0) {
2192 				log_warn("socket(2) failed for %s",
2193 				    newp->p_listen);
2194 				cumulated_error++;
2195 				continue;
2196 			}
2197 			sockbuf = SOCKBUF_SIZE;
2198 			if (setsockopt(newp->p_socket, SOL_SOCKET, SO_RCVBUF,
2199 			    &sockbuf, sizeof(sockbuf)) == -1)
2200 				log_warn("setsockopt(SO_RCVBUF) failed "
2201 				    "for %s", newp->p_listen);
2202 			sockbuf = SOCKBUF_SIZE;
2203 			if (setsockopt(newp->p_socket, SOL_SOCKET, SO_SNDBUF,
2204 			    &sockbuf, sizeof(sockbuf)) == -1)
2205 				log_warn("setsockopt(SO_SNDBUF) failed "
2206 				    "for %s", newp->p_listen);
2207 			if (setsockopt(newp->p_socket, SOL_SOCKET, SO_NO_DDP,
2208 			    &one, sizeof(one)) == -1)
2209 				log_warn("setsockopt(SO_NO_DDP) failed "
2210 				    "for %s", newp->p_listen);
2211 			error = setsockopt(newp->p_socket, SOL_SOCKET,
2212 			    SO_REUSEADDR, &one, sizeof(one));
2213 			if (error != 0) {
2214 				log_warn("setsockopt(SO_REUSEADDR) failed "
2215 				    "for %s", newp->p_listen);
2216 				close(newp->p_socket);
2217 				newp->p_socket = 0;
2218 				cumulated_error++;
2219 				continue;
2220 			}
2221 			if (newpg->pg_dscp != -1) {
2222 				struct sockaddr sa;
2223 				int len = sizeof(sa);
2224 				getsockname(newp->p_socket, &sa, &len);
2225 				/*
2226 				 * Only allow the 6-bit DSCP
2227 				 * field to be modified
2228 				 */
2229 				int tos = newpg->pg_dscp << 2;
2230 				if (sa.sa_family == AF_INET) {
2231 					if (setsockopt(newp->p_socket,
2232 					    IPPROTO_IP, IP_TOS,
2233 					    &tos, sizeof(tos)) == -1)
2234 						log_warn("setsockopt(IP_TOS) "
2235 						    "failed for %s",
2236 						    newp->p_listen);
2237 				} else
2238 				if (sa.sa_family == AF_INET6) {
2239 					if (setsockopt(newp->p_socket,
2240 					    IPPROTO_IPV6, IPV6_TCLASS,
2241 					    &tos, sizeof(tos)) == -1)
2242 						log_warn("setsockopt(IPV6_TCLASS) "
2243 						    "failed for %s",
2244 						    newp->p_listen);
2245 				}
2246 			}
2247 			if (newpg->pg_pcp != -1) {
2248 				struct sockaddr sa;
2249 				int len = sizeof(sa);
2250 				getsockname(newp->p_socket, &sa, &len);
2251 				/*
2252 				 * Only allow the 6-bit DSCP
2253 				 * field to be modified
2254 				 */
2255 				int pcp = newpg->pg_pcp;
2256 				if (sa.sa_family == AF_INET) {
2257 					if (setsockopt(newp->p_socket,
2258 					    IPPROTO_IP, IP_VLAN_PCP,
2259 					    &pcp, sizeof(pcp)) == -1)
2260 						log_warn("setsockopt(IP_VLAN_PCP) "
2261 						    "failed for %s",
2262 						    newp->p_listen);
2263 				} else
2264 				if (sa.sa_family == AF_INET6) {
2265 					if (setsockopt(newp->p_socket,
2266 					    IPPROTO_IPV6, IPV6_VLAN_PCP,
2267 					    &pcp, sizeof(pcp)) == -1)
2268 						log_warn("setsockopt(IPV6_VLAN_PCP) "
2269 						    "failed for %s",
2270 						    newp->p_listen);
2271 				}
2272 			}
2273 			error = bind(newp->p_socket, newp->p_ai->ai_addr,
2274 			    newp->p_ai->ai_addrlen);
2275 			if (error != 0) {
2276 				log_warn("bind(2) failed for %s",
2277 				    newp->p_listen);
2278 				close(newp->p_socket);
2279 				newp->p_socket = 0;
2280 				cumulated_error++;
2281 				continue;
2282 			}
2283 			error = listen(newp->p_socket, -1);
2284 			if (error != 0) {
2285 				log_warn("listen(2) failed for %s",
2286 				    newp->p_listen);
2287 				close(newp->p_socket);
2288 				newp->p_socket = 0;
2289 				cumulated_error++;
2290 				continue;
2291 			}
2292 		}
2293 	}
2294 
2295 	/*
2296 	 * Go through the no longer used sockets, closing them.
2297 	 */
2298 	TAILQ_FOREACH(oldpg, &oldconf->conf_portal_groups, pg_next) {
2299 		TAILQ_FOREACH(oldp, &oldpg->pg_portals, p_next) {
2300 			if (oldp->p_socket <= 0)
2301 				continue;
2302 			log_debugx("closing socket for %s, portal-group \"%s\"",
2303 			    oldp->p_listen, oldpg->pg_name);
2304 			close(oldp->p_socket);
2305 			oldp->p_socket = 0;
2306 		}
2307 	}
2308 
2309 	/* (Re-)Register on remaining/new iSNS servers. */
2310 	TAILQ_FOREACH(newns, &newconf->conf_isns, i_next) {
2311 		TAILQ_FOREACH(oldns, &oldconf->conf_isns, i_next) {
2312 			if (strcmp(oldns->i_addr, newns->i_addr) == 0)
2313 				break;
2314 		}
2315 		isns_register(newns, oldns);
2316 	}
2317 
2318 	/* Schedule iSNS update */
2319 	if (!TAILQ_EMPTY(&newconf->conf_isns))
2320 		set_timeout((newconf->conf_isns_period + 2) / 3, false);
2321 
2322 	return (cumulated_error);
2323 }
2324 
2325 static bool
2326 timed_out(void)
2327 {
2328 
2329 	return (sigalrm_received);
2330 }
2331 
2332 static void
2333 sigalrm_handler_fatal(int dummy __unused)
2334 {
2335 	/*
2336 	 * It would be easiest to just log an error and exit.  We can't
2337 	 * do this, though, because log_errx() is not signal safe, since
2338 	 * it calls syslog(3).  Instead, set a flag checked by pdu_send()
2339 	 * and pdu_receive(), to call log_errx() there.  Should they fail
2340 	 * to notice, we'll exit here one second later.
2341 	 */
2342 	if (sigalrm_received) {
2343 		/*
2344 		 * Oh well.  Just give up and quit.
2345 		 */
2346 		_exit(2);
2347 	}
2348 
2349 	sigalrm_received = true;
2350 }
2351 
2352 static void
2353 sigalrm_handler(int dummy __unused)
2354 {
2355 
2356 	sigalrm_received = true;
2357 }
2358 
2359 void
2360 set_timeout(int timeout, int fatal)
2361 {
2362 	struct sigaction sa;
2363 	struct itimerval itv;
2364 	int error;
2365 
2366 	if (timeout <= 0) {
2367 		log_debugx("session timeout disabled");
2368 		bzero(&itv, sizeof(itv));
2369 		error = setitimer(ITIMER_REAL, &itv, NULL);
2370 		if (error != 0)
2371 			log_err(1, "setitimer");
2372 		sigalrm_received = false;
2373 		return;
2374 	}
2375 
2376 	sigalrm_received = false;
2377 	bzero(&sa, sizeof(sa));
2378 	if (fatal)
2379 		sa.sa_handler = sigalrm_handler_fatal;
2380 	else
2381 		sa.sa_handler = sigalrm_handler;
2382 	sigfillset(&sa.sa_mask);
2383 	error = sigaction(SIGALRM, &sa, NULL);
2384 	if (error != 0)
2385 		log_err(1, "sigaction");
2386 
2387 	/*
2388 	 * First SIGALRM will arive after conf_timeout seconds.
2389 	 * If we do nothing, another one will arrive a second later.
2390 	 */
2391 	log_debugx("setting session timeout to %d seconds", timeout);
2392 	bzero(&itv, sizeof(itv));
2393 	itv.it_interval.tv_sec = 1;
2394 	itv.it_value.tv_sec = timeout;
2395 	error = setitimer(ITIMER_REAL, &itv, NULL);
2396 	if (error != 0)
2397 		log_err(1, "setitimer");
2398 }
2399 
2400 static int
2401 wait_for_children(bool block)
2402 {
2403 	pid_t pid;
2404 	int status;
2405 	int num = 0;
2406 
2407 	for (;;) {
2408 		/*
2409 		 * If "block" is true, wait for at least one process.
2410 		 */
2411 		if (block && num == 0)
2412 			pid = wait4(-1, &status, 0, NULL);
2413 		else
2414 			pid = wait4(-1, &status, WNOHANG, NULL);
2415 		if (pid <= 0)
2416 			break;
2417 		if (WIFSIGNALED(status)) {
2418 			log_warnx("child process %d terminated with signal %d",
2419 			    pid, WTERMSIG(status));
2420 		} else if (WEXITSTATUS(status) != 0) {
2421 			log_warnx("child process %d terminated with exit status %d",
2422 			    pid, WEXITSTATUS(status));
2423 		} else {
2424 			log_debugx("child process %d terminated gracefully", pid);
2425 		}
2426 		num++;
2427 	}
2428 
2429 	return (num);
2430 }
2431 
2432 static void
2433 handle_connection(struct portal *portal, int fd,
2434     const struct sockaddr *client_sa, bool dont_fork)
2435 {
2436 	struct ctld_connection *conn;
2437 	int error;
2438 	pid_t pid;
2439 	char host[NI_MAXHOST + 1];
2440 	struct conf *conf;
2441 
2442 	conf = portal->p_portal_group->pg_conf;
2443 
2444 	if (dont_fork) {
2445 		log_debugx("incoming connection; not forking due to -d flag");
2446 	} else {
2447 		nchildren -= wait_for_children(false);
2448 		assert(nchildren >= 0);
2449 
2450 		while (conf->conf_maxproc > 0 && nchildren >= conf->conf_maxproc) {
2451 			log_debugx("maxproc limit of %d child processes hit; "
2452 			    "waiting for child process to exit", conf->conf_maxproc);
2453 			nchildren -= wait_for_children(true);
2454 			assert(nchildren >= 0);
2455 		}
2456 		log_debugx("incoming connection; forking child process #%d",
2457 		    nchildren);
2458 		nchildren++;
2459 		pid = fork();
2460 		if (pid < 0)
2461 			log_err(1, "fork");
2462 		if (pid > 0) {
2463 			close(fd);
2464 			return;
2465 		}
2466 		pidfile_close(conf->conf_pidfh);
2467 	}
2468 
2469 	error = getnameinfo(client_sa, client_sa->sa_len,
2470 	    host, sizeof(host), NULL, 0, NI_NUMERICHOST);
2471 	if (error != 0)
2472 		log_errx(1, "getnameinfo: %s", gai_strerror(error));
2473 
2474 	log_debugx("accepted connection from %s; portal group \"%s\"",
2475 	    host, portal->p_portal_group->pg_name);
2476 	log_set_peer_addr(host);
2477 	setproctitle("%s", host);
2478 
2479 	conn = connection_new(portal, fd, host, client_sa);
2480 	set_timeout(conf->conf_timeout, true);
2481 	kernel_capsicate();
2482 	login(conn);
2483 	if (conn->conn_session_type == CONN_SESSION_TYPE_NORMAL) {
2484 		kernel_handoff(conn);
2485 		log_debugx("connection handed off to the kernel");
2486 	} else {
2487 		assert(conn->conn_session_type == CONN_SESSION_TYPE_DISCOVERY);
2488 		discovery(conn);
2489 	}
2490 	log_debugx("nothing more to do; exiting");
2491 	exit(0);
2492 }
2493 
2494 static int
2495 fd_add(int fd, fd_set *fdset, int nfds)
2496 {
2497 
2498 	/*
2499 	 * Skip sockets which we failed to bind.
2500 	 */
2501 	if (fd <= 0)
2502 		return (nfds);
2503 
2504 	FD_SET(fd, fdset);
2505 	if (fd > nfds)
2506 		nfds = fd;
2507 	return (nfds);
2508 }
2509 
2510 static void
2511 main_loop(struct conf *conf, bool dont_fork)
2512 {
2513 	struct portal_group *pg;
2514 	struct portal *portal;
2515 	struct sockaddr_storage client_sa;
2516 	socklen_t client_salen;
2517 #ifdef ICL_KERNEL_PROXY
2518 	int connection_id;
2519 	int portal_id;
2520 #endif
2521 	fd_set fdset;
2522 	int error, nfds, client_fd;
2523 
2524 	pidfile_write(conf->conf_pidfh);
2525 
2526 	for (;;) {
2527 		if (sighup_received || sigterm_received || timed_out())
2528 			return;
2529 
2530 #ifdef ICL_KERNEL_PROXY
2531 		if (proxy_mode) {
2532 			client_salen = sizeof(client_sa);
2533 			kernel_accept(&connection_id, &portal_id,
2534 			    (struct sockaddr *)&client_sa, &client_salen);
2535 			assert(client_salen >= client_sa.ss_len);
2536 
2537 			log_debugx("incoming connection, id %d, portal id %d",
2538 			    connection_id, portal_id);
2539 			TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
2540 				TAILQ_FOREACH(portal, &pg->pg_portals, p_next) {
2541 					if (portal->p_id == portal_id) {
2542 						goto found;
2543 					}
2544 				}
2545 			}
2546 
2547 			log_errx(1, "kernel returned invalid portal_id %d",
2548 			    portal_id);
2549 
2550 found:
2551 			handle_connection(portal, connection_id,
2552 			    (struct sockaddr *)&client_sa, dont_fork);
2553 		} else {
2554 #endif
2555 			assert(proxy_mode == false);
2556 
2557 			FD_ZERO(&fdset);
2558 			nfds = 0;
2559 			TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
2560 				TAILQ_FOREACH(portal, &pg->pg_portals, p_next)
2561 					nfds = fd_add(portal->p_socket, &fdset, nfds);
2562 			}
2563 			error = select(nfds + 1, &fdset, NULL, NULL, NULL);
2564 			if (error <= 0) {
2565 				if (errno == EINTR)
2566 					return;
2567 				log_err(1, "select");
2568 			}
2569 			TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
2570 				TAILQ_FOREACH(portal, &pg->pg_portals, p_next) {
2571 					if (!FD_ISSET(portal->p_socket, &fdset))
2572 						continue;
2573 					client_salen = sizeof(client_sa);
2574 					client_fd = accept(portal->p_socket,
2575 					    (struct sockaddr *)&client_sa,
2576 					    &client_salen);
2577 					if (client_fd < 0) {
2578 						if (errno == ECONNABORTED)
2579 							continue;
2580 						log_err(1, "accept");
2581 					}
2582 					assert(client_salen >= client_sa.ss_len);
2583 
2584 					handle_connection(portal, client_fd,
2585 					    (struct sockaddr *)&client_sa,
2586 					    dont_fork);
2587 					break;
2588 				}
2589 			}
2590 #ifdef ICL_KERNEL_PROXY
2591 		}
2592 #endif
2593 	}
2594 }
2595 
2596 static void
2597 sighup_handler(int dummy __unused)
2598 {
2599 
2600 	sighup_received = true;
2601 }
2602 
2603 static void
2604 sigterm_handler(int dummy __unused)
2605 {
2606 
2607 	sigterm_received = true;
2608 }
2609 
2610 static void
2611 sigchld_handler(int dummy __unused)
2612 {
2613 
2614 	/*
2615 	 * The only purpose of this handler is to make SIGCHLD
2616 	 * interrupt the ISCSIDWAIT ioctl(2), so we can call
2617 	 * wait_for_children().
2618 	 */
2619 }
2620 
2621 static void
2622 register_signals(void)
2623 {
2624 	struct sigaction sa;
2625 	int error;
2626 
2627 	bzero(&sa, sizeof(sa));
2628 	sa.sa_handler = sighup_handler;
2629 	sigfillset(&sa.sa_mask);
2630 	error = sigaction(SIGHUP, &sa, NULL);
2631 	if (error != 0)
2632 		log_err(1, "sigaction");
2633 
2634 	sa.sa_handler = sigterm_handler;
2635 	error = sigaction(SIGTERM, &sa, NULL);
2636 	if (error != 0)
2637 		log_err(1, "sigaction");
2638 
2639 	sa.sa_handler = sigterm_handler;
2640 	error = sigaction(SIGINT, &sa, NULL);
2641 	if (error != 0)
2642 		log_err(1, "sigaction");
2643 
2644 	sa.sa_handler = sigchld_handler;
2645 	error = sigaction(SIGCHLD, &sa, NULL);
2646 	if (error != 0)
2647 		log_err(1, "sigaction");
2648 }
2649 
2650 static void
2651 check_perms(const char *path)
2652 {
2653 	struct stat sb;
2654 	int error;
2655 
2656 	error = stat(path, &sb);
2657 	if (error != 0) {
2658 		log_warn("stat");
2659 		return;
2660 	}
2661 	if (sb.st_mode & S_IWOTH) {
2662 		log_warnx("%s is world-writable", path);
2663 	} else if (sb.st_mode & S_IROTH) {
2664 		log_warnx("%s is world-readable", path);
2665 	} else if (sb.st_mode & S_IXOTH) {
2666 		/*
2667 		 * Ok, this one doesn't matter, but still do it,
2668 		 * just for consistency.
2669 		 */
2670 		log_warnx("%s is world-executable", path);
2671 	}
2672 
2673 	/*
2674 	 * XXX: Should we also check for owner != 0?
2675 	 */
2676 }
2677 
2678 static struct conf *
2679 conf_new_from_file(const char *path, bool ucl)
2680 {
2681 	struct conf *conf;
2682 	struct auth_group *ag;
2683 	struct portal_group *pg;
2684 	int error;
2685 
2686 	log_debugx("obtaining configuration from %s", path);
2687 
2688 	conf = conf_new();
2689 
2690 	ag = auth_group_new(conf, "default");
2691 	assert(ag != NULL);
2692 
2693 	ag = auth_group_new(conf, "no-authentication");
2694 	assert(ag != NULL);
2695 	ag->ag_type = AG_TYPE_NO_AUTHENTICATION;
2696 
2697 	ag = auth_group_new(conf, "no-access");
2698 	assert(ag != NULL);
2699 	ag->ag_type = AG_TYPE_DENY;
2700 
2701 	pg = portal_group_new(conf, "default");
2702 	assert(pg != NULL);
2703 
2704 	if (ucl)
2705 		error = uclparse_conf(conf, path);
2706 	else
2707 		error = parse_conf(conf, path);
2708 
2709 	if (error != 0) {
2710 		conf_delete(conf);
2711 		return (NULL);
2712 	}
2713 
2714 	check_perms(path);
2715 
2716 	if (conf->conf_default_ag_defined == false) {
2717 		log_debugx("auth-group \"default\" not defined; "
2718 		    "going with defaults");
2719 		ag = auth_group_find(conf, "default");
2720 		assert(ag != NULL);
2721 		ag->ag_type = AG_TYPE_DENY;
2722 	}
2723 
2724 	if (conf->conf_default_pg_defined == false) {
2725 		log_debugx("portal-group \"default\" not defined; "
2726 		    "going with defaults");
2727 		pg = portal_group_find(conf, "default");
2728 		assert(pg != NULL);
2729 		portal_group_add_listen(pg, "0.0.0.0:3260", false);
2730 		portal_group_add_listen(pg, "[::]:3260", false);
2731 	}
2732 
2733 	conf->conf_kernel_port_on = true;
2734 
2735 	error = conf_verify(conf);
2736 	if (error != 0) {
2737 		conf_delete(conf);
2738 		return (NULL);
2739 	}
2740 
2741 	return (conf);
2742 }
2743 
2744 /*
2745  * If the config file specifies physical ports for any target, associate them
2746  * with the config file.  If necessary, create them.
2747  */
2748 static int
2749 new_pports_from_conf(struct conf *conf, struct kports *kports)
2750 {
2751 	struct target *targ;
2752 	struct pport *pp;
2753 	struct port *tp;
2754 	int ret, i_pp, i_vp;
2755 
2756 	TAILQ_FOREACH(targ, &conf->conf_targets, t_next) {
2757 		if (!targ->t_pport)
2758 			continue;
2759 
2760 		ret = sscanf(targ->t_pport, "ioctl/%d/%d", &i_pp, &i_vp);
2761 		if (ret > 0) {
2762 			tp = port_new_ioctl(conf, kports, targ, i_pp, i_vp);
2763 			if (tp == NULL) {
2764 				log_warnx("can't create new ioctl port "
2765 				    "for target \"%s\"", targ->t_name);
2766 				return (1);
2767 			}
2768 
2769 			continue;
2770 		}
2771 
2772 		pp = pport_find(kports, targ->t_pport);
2773 		if (pp == NULL) {
2774 			log_warnx("unknown port \"%s\" for target \"%s\"",
2775 			    targ->t_pport, targ->t_name);
2776 			return (1);
2777 		}
2778 		if (!TAILQ_EMPTY(&pp->pp_ports)) {
2779 			log_warnx("can't link port \"%s\" to target \"%s\", "
2780 			    "port already linked to some target",
2781 			    targ->t_pport, targ->t_name);
2782 			return (1);
2783 		}
2784 		tp = port_new_pp(conf, targ, pp);
2785 		if (tp == NULL) {
2786 			log_warnx("can't link port \"%s\" to target \"%s\"",
2787 			    targ->t_pport, targ->t_name);
2788 			return (1);
2789 		}
2790 	}
2791 	return (0);
2792 }
2793 
2794 int
2795 main(int argc, char **argv)
2796 {
2797 	struct kports kports;
2798 	struct conf *oldconf, *newconf, *tmpconf;
2799 	struct isns *newns;
2800 	const char *config_path = DEFAULT_CONFIG_PATH;
2801 	int debug = 0, ch, error;
2802 	pid_t otherpid;
2803 	bool dont_daemonize = false;
2804 	bool test_config = false;
2805 	bool use_ucl = false;
2806 
2807 	while ((ch = getopt(argc, argv, "dtuf:R")) != -1) {
2808 		switch (ch) {
2809 		case 'd':
2810 			dont_daemonize = true;
2811 			debug++;
2812 			break;
2813 		case 't':
2814 			test_config = true;
2815 			break;
2816 		case 'u':
2817 			use_ucl = true;
2818 			break;
2819 		case 'f':
2820 			config_path = optarg;
2821 			break;
2822 		case 'R':
2823 #ifndef ICL_KERNEL_PROXY
2824 			log_errx(1, "ctld(8) compiled without ICL_KERNEL_PROXY "
2825 			    "does not support iSER protocol");
2826 #endif
2827 			proxy_mode = true;
2828 			break;
2829 		case '?':
2830 		default:
2831 			usage();
2832 		}
2833 	}
2834 	argc -= optind;
2835 	if (argc != 0)
2836 		usage();
2837 
2838 	log_init(debug);
2839 	kernel_init();
2840 
2841 	TAILQ_INIT(&kports.pports);
2842 	newconf = conf_new_from_file(config_path, use_ucl);
2843 
2844 	if (newconf == NULL)
2845 		log_errx(1, "configuration error; exiting");
2846 
2847 	if (test_config)
2848 		return (0);
2849 
2850 	assert(newconf->conf_pidfile_path != NULL);
2851 	log_debugx("opening pidfile %s", newconf->conf_pidfile_path);
2852 	newconf->conf_pidfh = pidfile_open(newconf->conf_pidfile_path, 0600,
2853 		&otherpid);
2854 	if (newconf->conf_pidfh == NULL) {
2855 		if (errno == EEXIST)
2856 			log_errx(1, "daemon already running, pid: %jd.",
2857 			    (intmax_t)otherpid);
2858 		log_err(1, "cannot open or create pidfile \"%s\"",
2859 		    newconf->conf_pidfile_path);
2860 	}
2861 
2862 	register_signals();
2863 
2864 	oldconf = conf_new_from_kernel(&kports);
2865 
2866 	if (debug > 0) {
2867 		oldconf->conf_debug = debug;
2868 		newconf->conf_debug = debug;
2869 	}
2870 
2871 	if (new_pports_from_conf(newconf, &kports))
2872 		log_errx(1, "Error associating physical ports; exiting");
2873 
2874 	error = conf_apply(oldconf, newconf);
2875 	if (error != 0)
2876 		log_errx(1, "failed to apply configuration; exiting");
2877 
2878 	conf_delete(oldconf);
2879 	oldconf = NULL;
2880 
2881 	if (dont_daemonize == false) {
2882 		log_debugx("daemonizing");
2883 		if (daemon(0, 0) == -1) {
2884 			log_warn("cannot daemonize");
2885 			pidfile_remove(newconf->conf_pidfh);
2886 			exit(1);
2887 		}
2888 	}
2889 
2890 	/* Schedule iSNS update */
2891 	if (!TAILQ_EMPTY(&newconf->conf_isns))
2892 		set_timeout((newconf->conf_isns_period + 2) / 3, false);
2893 
2894 	for (;;) {
2895 		main_loop(newconf, dont_daemonize);
2896 		if (sighup_received) {
2897 			sighup_received = false;
2898 			log_debugx("received SIGHUP, reloading configuration");
2899 			tmpconf = conf_new_from_file(config_path, use_ucl);
2900 
2901 			if (tmpconf == NULL) {
2902 				log_warnx("configuration error, "
2903 				    "continuing with old configuration");
2904 			} else if (new_pports_from_conf(tmpconf, &kports)) {
2905 				log_warnx("Error associating physical ports, "
2906 				    "continuing with old configuration");
2907 				conf_delete(tmpconf);
2908 			} else {
2909 				if (debug > 0)
2910 					tmpconf->conf_debug = debug;
2911 				oldconf = newconf;
2912 				newconf = tmpconf;
2913 
2914 				error = conf_apply(oldconf, newconf);
2915 				if (error != 0)
2916 					log_warnx("failed to reload "
2917 					    "configuration");
2918 				conf_delete(oldconf);
2919 				oldconf = NULL;
2920 			}
2921 		} else if (sigterm_received) {
2922 			log_debugx("exiting on signal; "
2923 			    "reloading empty configuration");
2924 
2925 			log_debugx("removing CTL iSCSI ports "
2926 			    "and terminating all connections");
2927 
2928 			oldconf = newconf;
2929 			newconf = conf_new();
2930 			if (debug > 0)
2931 				newconf->conf_debug = debug;
2932 			error = conf_apply(oldconf, newconf);
2933 			if (error != 0)
2934 				log_warnx("failed to apply configuration");
2935 			if (oldconf->conf_pidfh) {
2936 				pidfile_remove(oldconf->conf_pidfh);
2937 				oldconf->conf_pidfh = NULL;
2938 			}
2939 			conf_delete(newconf);
2940 			conf_delete(oldconf);
2941 			oldconf = NULL;
2942 
2943 			log_warnx("exiting on signal");
2944 			exit(0);
2945 		} else {
2946 			nchildren -= wait_for_children(false);
2947 			assert(nchildren >= 0);
2948 			if (timed_out()) {
2949 				set_timeout(0, false);
2950 				TAILQ_FOREACH(newns, &newconf->conf_isns, i_next)
2951 					isns_check(newns);
2952 				/* Schedule iSNS update */
2953 				if (!TAILQ_EMPTY(&newconf->conf_isns)) {
2954 					set_timeout((newconf->conf_isns_period
2955 					    + 2) / 3,
2956 					    false);
2957 				}
2958 			}
2959 		}
2960 	}
2961 	/* NOTREACHED */
2962 }
2963