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