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