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