xref: /freebsd/usr.sbin/ctld/ctld.c (revision 49b49cda41feabe3439f7318e8bf40e3896c7bf4)
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_options);
619 	TAILQ_INIT(&pg->pg_portals);
620 	TAILQ_INIT(&pg->pg_ports);
621 	pg->pg_conf = conf;
622 	pg->pg_tag = 0;		/* Assigned later in conf_apply(). */
623 	TAILQ_INSERT_TAIL(&conf->conf_portal_groups, pg, pg_next);
624 
625 	return (pg);
626 }
627 
628 void
629 portal_group_delete(struct portal_group *pg)
630 {
631 	struct portal *portal, *tmp;
632 	struct port *port, *tport;
633 	struct option *o, *otmp;
634 
635 	TAILQ_FOREACH_SAFE(port, &pg->pg_ports, p_pgs, tport)
636 		port_delete(port);
637 	TAILQ_REMOVE(&pg->pg_conf->conf_portal_groups, pg, pg_next);
638 
639 	TAILQ_FOREACH_SAFE(portal, &pg->pg_portals, p_next, tmp)
640 		portal_delete(portal);
641 	TAILQ_FOREACH_SAFE(o, &pg->pg_options, o_next, otmp)
642 		option_delete(&pg->pg_options, o);
643 	free(pg->pg_name);
644 	free(pg->pg_offload);
645 	free(pg->pg_redirection);
646 	free(pg);
647 }
648 
649 struct portal_group *
650 portal_group_find(const struct conf *conf, const char *name)
651 {
652 	struct portal_group *pg;
653 
654 	TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
655 		if (strcmp(pg->pg_name, name) == 0)
656 			return (pg);
657 	}
658 
659 	return (NULL);
660 }
661 
662 static int
663 parse_addr_port(char *arg, const char *def_port, struct addrinfo **ai)
664 {
665 	struct addrinfo hints;
666 	char *str, *addr, *ch;
667 	const char *port;
668 	int error, colons = 0;
669 
670 	str = arg = strdup(arg);
671 	if (arg[0] == '[') {
672 		/*
673 		 * IPv6 address in square brackets, perhaps with port.
674 		 */
675 		arg++;
676 		addr = strsep(&arg, "]");
677 		if (arg == NULL)
678 			return (1);
679 		if (arg[0] == '\0') {
680 			port = def_port;
681 		} else if (arg[0] == ':') {
682 			port = arg + 1;
683 		} else {
684 			free(str);
685 			return (1);
686 		}
687 	} else {
688 		/*
689 		 * Either IPv6 address without brackets - and without
690 		 * a port - or IPv4 address.  Just count the colons.
691 		 */
692 		for (ch = arg; *ch != '\0'; ch++) {
693 			if (*ch == ':')
694 				colons++;
695 		}
696 		if (colons > 1) {
697 			addr = arg;
698 			port = def_port;
699 		} else {
700 			addr = strsep(&arg, ":");
701 			if (arg == NULL)
702 				port = def_port;
703 			else
704 				port = arg;
705 		}
706 	}
707 
708 	memset(&hints, 0, sizeof(hints));
709 	hints.ai_family = PF_UNSPEC;
710 	hints.ai_socktype = SOCK_STREAM;
711 	hints.ai_flags = AI_PASSIVE;
712 	error = getaddrinfo(addr, port, &hints, ai);
713 	free(str);
714 	return ((error != 0) ? 1 : 0);
715 }
716 
717 int
718 portal_group_add_listen(struct portal_group *pg, const char *value, bool iser)
719 {
720 	struct portal *portal;
721 
722 	portal = portal_new(pg);
723 	portal->p_listen = checked_strdup(value);
724 	portal->p_iser = iser;
725 
726 	if (parse_addr_port(portal->p_listen, "3260", &portal->p_ai)) {
727 		log_warnx("invalid listen address %s", portal->p_listen);
728 		portal_delete(portal);
729 		return (1);
730 	}
731 
732 	/*
733 	 * XXX: getaddrinfo(3) may return multiple addresses; we should turn
734 	 *	those into multiple portals.
735 	 */
736 
737 	return (0);
738 }
739 
740 int
741 isns_new(struct conf *conf, const char *addr)
742 {
743 	struct isns *isns;
744 
745 	isns = calloc(1, sizeof(*isns));
746 	if (isns == NULL)
747 		log_err(1, "calloc");
748 	isns->i_conf = conf;
749 	TAILQ_INSERT_TAIL(&conf->conf_isns, isns, i_next);
750 	isns->i_addr = checked_strdup(addr);
751 
752 	if (parse_addr_port(isns->i_addr, "3205", &isns->i_ai)) {
753 		log_warnx("invalid iSNS address %s", isns->i_addr);
754 		isns_delete(isns);
755 		return (1);
756 	}
757 
758 	/*
759 	 * XXX: getaddrinfo(3) may return multiple addresses; we should turn
760 	 *	those into multiple servers.
761 	 */
762 
763 	return (0);
764 }
765 
766 void
767 isns_delete(struct isns *isns)
768 {
769 
770 	TAILQ_REMOVE(&isns->i_conf->conf_isns, isns, i_next);
771 	free(isns->i_addr);
772 	if (isns->i_ai != NULL)
773 		freeaddrinfo(isns->i_ai);
774 	free(isns);
775 }
776 
777 static int
778 isns_do_connect(struct isns *isns)
779 {
780 	int s;
781 
782 	s = socket(isns->i_ai->ai_family, isns->i_ai->ai_socktype,
783 	    isns->i_ai->ai_protocol);
784 	if (s < 0) {
785 		log_warn("socket(2) failed for %s", isns->i_addr);
786 		return (-1);
787 	}
788 	if (connect(s, isns->i_ai->ai_addr, isns->i_ai->ai_addrlen)) {
789 		log_warn("connect(2) failed for %s", isns->i_addr);
790 		close(s);
791 		return (-1);
792 	}
793 	return(s);
794 }
795 
796 static int
797 isns_do_register(struct isns *isns, int s, const char *hostname)
798 {
799 	struct conf *conf = isns->i_conf;
800 	struct target *target;
801 	struct portal *portal;
802 	struct portal_group *pg;
803 	struct port *port;
804 	struct isns_req *req;
805 	int res = 0;
806 	uint32_t error;
807 
808 	req = isns_req_create(ISNS_FUNC_DEVATTRREG, ISNS_FLAG_CLIENT);
809 	isns_req_add_str(req, 32, TAILQ_FIRST(&conf->conf_targets)->t_name);
810 	isns_req_add_delim(req);
811 	isns_req_add_str(req, 1, hostname);
812 	isns_req_add_32(req, 2, 2); /* 2 -- iSCSI */
813 	isns_req_add_32(req, 6, conf->conf_isns_period);
814 	TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
815 		if (pg->pg_unassigned)
816 			continue;
817 		TAILQ_FOREACH(portal, &pg->pg_portals, p_next) {
818 			isns_req_add_addr(req, 16, portal->p_ai);
819 			isns_req_add_port(req, 17, portal->p_ai);
820 		}
821 	}
822 	TAILQ_FOREACH(target, &conf->conf_targets, t_next) {
823 		isns_req_add_str(req, 32, target->t_name);
824 		isns_req_add_32(req, 33, 1); /* 1 -- Target*/
825 		if (target->t_alias != NULL)
826 			isns_req_add_str(req, 34, target->t_alias);
827 		TAILQ_FOREACH(port, &target->t_ports, p_ts) {
828 			if ((pg = port->p_portal_group) == NULL)
829 				continue;
830 			isns_req_add_32(req, 51, pg->pg_tag);
831 			TAILQ_FOREACH(portal, &pg->pg_portals, p_next) {
832 				isns_req_add_addr(req, 49, portal->p_ai);
833 				isns_req_add_port(req, 50, portal->p_ai);
834 			}
835 		}
836 	}
837 	res = isns_req_send(s, req);
838 	if (res < 0) {
839 		log_warn("send(2) failed for %s", isns->i_addr);
840 		goto quit;
841 	}
842 	res = isns_req_receive(s, req);
843 	if (res < 0) {
844 		log_warn("receive(2) failed for %s", isns->i_addr);
845 		goto quit;
846 	}
847 	error = isns_req_get_status(req);
848 	if (error != 0) {
849 		log_warnx("iSNS register error %d for %s", error, isns->i_addr);
850 		res = -1;
851 	}
852 quit:
853 	isns_req_free(req);
854 	return (res);
855 }
856 
857 static int
858 isns_do_check(struct isns *isns, int s, const char *hostname)
859 {
860 	struct conf *conf = isns->i_conf;
861 	struct isns_req *req;
862 	int res = 0;
863 	uint32_t error;
864 
865 	req = isns_req_create(ISNS_FUNC_DEVATTRQRY, ISNS_FLAG_CLIENT);
866 	isns_req_add_str(req, 32, TAILQ_FIRST(&conf->conf_targets)->t_name);
867 	isns_req_add_str(req, 1, hostname);
868 	isns_req_add_delim(req);
869 	isns_req_add(req, 2, 0, NULL);
870 	res = isns_req_send(s, req);
871 	if (res < 0) {
872 		log_warn("send(2) failed for %s", isns->i_addr);
873 		goto quit;
874 	}
875 	res = isns_req_receive(s, req);
876 	if (res < 0) {
877 		log_warn("receive(2) failed for %s", isns->i_addr);
878 		goto quit;
879 	}
880 	error = isns_req_get_status(req);
881 	if (error != 0) {
882 		log_warnx("iSNS check error %d for %s", error, isns->i_addr);
883 		res = -1;
884 	}
885 quit:
886 	isns_req_free(req);
887 	return (res);
888 }
889 
890 static int
891 isns_do_deregister(struct isns *isns, int s, const char *hostname)
892 {
893 	struct conf *conf = isns->i_conf;
894 	struct isns_req *req;
895 	int res = 0;
896 	uint32_t error;
897 
898 	req = isns_req_create(ISNS_FUNC_DEVDEREG, ISNS_FLAG_CLIENT);
899 	isns_req_add_str(req, 32, TAILQ_FIRST(&conf->conf_targets)->t_name);
900 	isns_req_add_delim(req);
901 	isns_req_add_str(req, 1, hostname);
902 	res = isns_req_send(s, req);
903 	if (res < 0) {
904 		log_warn("send(2) failed for %s", isns->i_addr);
905 		goto quit;
906 	}
907 	res = isns_req_receive(s, req);
908 	if (res < 0) {
909 		log_warn("receive(2) failed for %s", isns->i_addr);
910 		goto quit;
911 	}
912 	error = isns_req_get_status(req);
913 	if (error != 0) {
914 		log_warnx("iSNS deregister error %d for %s", error, isns->i_addr);
915 		res = -1;
916 	}
917 quit:
918 	isns_req_free(req);
919 	return (res);
920 }
921 
922 void
923 isns_register(struct isns *isns, struct isns *oldisns)
924 {
925 	struct conf *conf = isns->i_conf;
926 	int s;
927 	char hostname[256];
928 
929 	if (TAILQ_EMPTY(&conf->conf_targets) ||
930 	    TAILQ_EMPTY(&conf->conf_portal_groups))
931 		return;
932 	set_timeout(conf->conf_isns_timeout, false);
933 	s = isns_do_connect(isns);
934 	if (s < 0) {
935 		set_timeout(0, false);
936 		return;
937 	}
938 	gethostname(hostname, sizeof(hostname));
939 
940 	if (oldisns == NULL || TAILQ_EMPTY(&oldisns->i_conf->conf_targets))
941 		oldisns = isns;
942 	isns_do_deregister(oldisns, s, hostname);
943 	isns_do_register(isns, s, hostname);
944 	close(s);
945 	set_timeout(0, false);
946 }
947 
948 void
949 isns_check(struct isns *isns)
950 {
951 	struct conf *conf = isns->i_conf;
952 	int s, res;
953 	char hostname[256];
954 
955 	if (TAILQ_EMPTY(&conf->conf_targets) ||
956 	    TAILQ_EMPTY(&conf->conf_portal_groups))
957 		return;
958 	set_timeout(conf->conf_isns_timeout, false);
959 	s = isns_do_connect(isns);
960 	if (s < 0) {
961 		set_timeout(0, false);
962 		return;
963 	}
964 	gethostname(hostname, sizeof(hostname));
965 
966 	res = isns_do_check(isns, s, hostname);
967 	if (res < 0) {
968 		isns_do_deregister(isns, s, hostname);
969 		isns_do_register(isns, s, hostname);
970 	}
971 	close(s);
972 	set_timeout(0, false);
973 }
974 
975 void
976 isns_deregister(struct isns *isns)
977 {
978 	struct conf *conf = isns->i_conf;
979 	int s;
980 	char hostname[256];
981 
982 	if (TAILQ_EMPTY(&conf->conf_targets) ||
983 	    TAILQ_EMPTY(&conf->conf_portal_groups))
984 		return;
985 	set_timeout(conf->conf_isns_timeout, false);
986 	s = isns_do_connect(isns);
987 	if (s < 0)
988 		return;
989 	gethostname(hostname, sizeof(hostname));
990 
991 	isns_do_deregister(isns, s, hostname);
992 	close(s);
993 	set_timeout(0, false);
994 }
995 
996 int
997 portal_group_set_filter(struct portal_group *pg, const char *str)
998 {
999 	int filter;
1000 
1001 	if (strcmp(str, "none") == 0) {
1002 		filter = PG_FILTER_NONE;
1003 	} else if (strcmp(str, "portal") == 0) {
1004 		filter = PG_FILTER_PORTAL;
1005 	} else if (strcmp(str, "portal-name") == 0) {
1006 		filter = PG_FILTER_PORTAL_NAME;
1007 	} else if (strcmp(str, "portal-name-auth") == 0) {
1008 		filter = PG_FILTER_PORTAL_NAME_AUTH;
1009 	} else {
1010 		log_warnx("invalid discovery-filter \"%s\" for portal-group "
1011 		    "\"%s\"; valid values are \"none\", \"portal\", "
1012 		    "\"portal-name\", and \"portal-name-auth\"",
1013 		    str, pg->pg_name);
1014 		return (1);
1015 	}
1016 
1017 	if (pg->pg_discovery_filter != PG_FILTER_UNKNOWN &&
1018 	    pg->pg_discovery_filter != filter) {
1019 		log_warnx("cannot set discovery-filter to \"%s\" for "
1020 		    "portal-group \"%s\"; already has a different "
1021 		    "value", str, pg->pg_name);
1022 		return (1);
1023 	}
1024 
1025 	pg->pg_discovery_filter = filter;
1026 
1027 	return (0);
1028 }
1029 
1030 int
1031 portal_group_set_offload(struct portal_group *pg, const char *offload)
1032 {
1033 
1034 	if (pg->pg_offload != NULL) {
1035 		log_warnx("cannot set offload to \"%s\" for "
1036 		    "portal-group \"%s\"; already defined",
1037 		    offload, pg->pg_name);
1038 		return (1);
1039 	}
1040 
1041 	pg->pg_offload = checked_strdup(offload);
1042 
1043 	return (0);
1044 }
1045 
1046 int
1047 portal_group_set_redirection(struct portal_group *pg, const char *addr)
1048 {
1049 
1050 	if (pg->pg_redirection != NULL) {
1051 		log_warnx("cannot set redirection to \"%s\" for "
1052 		    "portal-group \"%s\"; already defined",
1053 		    addr, pg->pg_name);
1054 		return (1);
1055 	}
1056 
1057 	pg->pg_redirection = checked_strdup(addr);
1058 
1059 	return (0);
1060 }
1061 
1062 static bool
1063 valid_hex(const char ch)
1064 {
1065 	switch (ch) {
1066 	case '0':
1067 	case '1':
1068 	case '2':
1069 	case '3':
1070 	case '4':
1071 	case '5':
1072 	case '6':
1073 	case '7':
1074 	case '8':
1075 	case '9':
1076 	case 'a':
1077 	case 'A':
1078 	case 'b':
1079 	case 'B':
1080 	case 'c':
1081 	case 'C':
1082 	case 'd':
1083 	case 'D':
1084 	case 'e':
1085 	case 'E':
1086 	case 'f':
1087 	case 'F':
1088 		return (true);
1089 	default:
1090 		return (false);
1091 	}
1092 }
1093 
1094 bool
1095 valid_iscsi_name(const char *name)
1096 {
1097 	int i;
1098 
1099 	if (strlen(name) >= MAX_NAME_LEN) {
1100 		log_warnx("overlong name for target \"%s\"; max length allowed "
1101 		    "by iSCSI specification is %d characters",
1102 		    name, MAX_NAME_LEN);
1103 		return (false);
1104 	}
1105 
1106 	/*
1107 	 * In the cases below, we don't return an error, just in case the admin
1108 	 * was right, and we're wrong.
1109 	 */
1110 	if (strncasecmp(name, "iqn.", strlen("iqn.")) == 0) {
1111 		for (i = strlen("iqn."); name[i] != '\0'; i++) {
1112 			/*
1113 			 * XXX: We should verify UTF-8 normalisation, as defined
1114 			 *      by 3.2.6.2: iSCSI Name Encoding.
1115 			 */
1116 			if (isalnum(name[i]))
1117 				continue;
1118 			if (name[i] == '-' || name[i] == '.' || name[i] == ':')
1119 				continue;
1120 			log_warnx("invalid character \"%c\" in target name "
1121 			    "\"%s\"; allowed characters are letters, digits, "
1122 			    "'-', '.', and ':'", name[i], name);
1123 			break;
1124 		}
1125 		/*
1126 		 * XXX: Check more stuff: valid date and a valid reversed domain.
1127 		 */
1128 	} else if (strncasecmp(name, "eui.", strlen("eui.")) == 0) {
1129 		if (strlen(name) != strlen("eui.") + 16)
1130 			log_warnx("invalid target name \"%s\"; the \"eui.\" "
1131 			    "should be followed by exactly 16 hexadecimal "
1132 			    "digits", name);
1133 		for (i = strlen("eui."); name[i] != '\0'; i++) {
1134 			if (!valid_hex(name[i])) {
1135 				log_warnx("invalid character \"%c\" in target "
1136 				    "name \"%s\"; allowed characters are 1-9 "
1137 				    "and A-F", name[i], name);
1138 				break;
1139 			}
1140 		}
1141 	} else if (strncasecmp(name, "naa.", strlen("naa.")) == 0) {
1142 		if (strlen(name) > strlen("naa.") + 32)
1143 			log_warnx("invalid target name \"%s\"; the \"naa.\" "
1144 			    "should be followed by at most 32 hexadecimal "
1145 			    "digits", name);
1146 		for (i = strlen("naa."); name[i] != '\0'; i++) {
1147 			if (!valid_hex(name[i])) {
1148 				log_warnx("invalid character \"%c\" in target "
1149 				    "name \"%s\"; allowed characters are 1-9 "
1150 				    "and A-F", name[i], name);
1151 				break;
1152 			}
1153 		}
1154 	} else {
1155 		log_warnx("invalid target name \"%s\"; should start with "
1156 		    "either \"iqn.\", \"eui.\", or \"naa.\"",
1157 		    name);
1158 	}
1159 	return (true);
1160 }
1161 
1162 struct pport *
1163 pport_new(struct conf *conf, const char *name, uint32_t ctl_port)
1164 {
1165 	struct pport *pp;
1166 
1167 	pp = calloc(1, sizeof(*pp));
1168 	if (pp == NULL)
1169 		log_err(1, "calloc");
1170 	pp->pp_conf = conf;
1171 	pp->pp_name = checked_strdup(name);
1172 	pp->pp_ctl_port = ctl_port;
1173 	TAILQ_INIT(&pp->pp_ports);
1174 	TAILQ_INSERT_TAIL(&conf->conf_pports, pp, pp_next);
1175 	return (pp);
1176 }
1177 
1178 struct pport *
1179 pport_find(const struct conf *conf, const char *name)
1180 {
1181 	struct pport *pp;
1182 
1183 	TAILQ_FOREACH(pp, &conf->conf_pports, pp_next) {
1184 		if (strcasecmp(pp->pp_name, name) == 0)
1185 			return (pp);
1186 	}
1187 	return (NULL);
1188 }
1189 
1190 struct pport *
1191 pport_copy(struct pport *pp, struct conf *conf)
1192 {
1193 	struct pport *ppnew;
1194 
1195 	ppnew = pport_new(conf, pp->pp_name, pp->pp_ctl_port);
1196 	return (ppnew);
1197 }
1198 
1199 void
1200 pport_delete(struct pport *pp)
1201 {
1202 	struct port *port, *tport;
1203 
1204 	TAILQ_FOREACH_SAFE(port, &pp->pp_ports, p_ts, tport)
1205 		port_delete(port);
1206 	TAILQ_REMOVE(&pp->pp_conf->conf_pports, pp, pp_next);
1207 	free(pp->pp_name);
1208 	free(pp);
1209 }
1210 
1211 struct port *
1212 port_new(struct conf *conf, struct target *target, struct portal_group *pg)
1213 {
1214 	struct port *port;
1215 	char *name;
1216 	int ret;
1217 
1218 	ret = asprintf(&name, "%s-%s", pg->pg_name, target->t_name);
1219 	if (ret <= 0)
1220 		log_err(1, "asprintf");
1221 	if (port_find(conf, name) != NULL) {
1222 		log_warnx("duplicate port \"%s\"", name);
1223 		free(name);
1224 		return (NULL);
1225 	}
1226 	port = calloc(1, sizeof(*port));
1227 	if (port == NULL)
1228 		log_err(1, "calloc");
1229 	port->p_conf = conf;
1230 	port->p_name = name;
1231 	TAILQ_INSERT_TAIL(&conf->conf_ports, port, p_next);
1232 	TAILQ_INSERT_TAIL(&target->t_ports, port, p_ts);
1233 	port->p_target = target;
1234 	TAILQ_INSERT_TAIL(&pg->pg_ports, port, p_pgs);
1235 	port->p_portal_group = pg;
1236 	port->p_foreign = pg->pg_foreign;
1237 	return (port);
1238 }
1239 
1240 struct port *
1241 port_new_pp(struct conf *conf, struct target *target, struct pport *pp)
1242 {
1243 	struct port *port;
1244 	char *name;
1245 	int ret;
1246 
1247 	ret = asprintf(&name, "%s-%s", pp->pp_name, target->t_name);
1248 	if (ret <= 0)
1249 		log_err(1, "asprintf");
1250 	if (port_find(conf, name) != NULL) {
1251 		log_warnx("duplicate port \"%s\"", name);
1252 		free(name);
1253 		return (NULL);
1254 	}
1255 	port = calloc(1, sizeof(*port));
1256 	if (port == NULL)
1257 		log_err(1, "calloc");
1258 	port->p_conf = conf;
1259 	port->p_name = name;
1260 	TAILQ_INSERT_TAIL(&conf->conf_ports, port, p_next);
1261 	TAILQ_INSERT_TAIL(&target->t_ports, port, p_ts);
1262 	port->p_target = target;
1263 	TAILQ_INSERT_TAIL(&pp->pp_ports, port, p_pps);
1264 	port->p_pport = pp;
1265 	return (port);
1266 }
1267 
1268 struct port *
1269 port_find(const struct conf *conf, const char *name)
1270 {
1271 	struct port *port;
1272 
1273 	TAILQ_FOREACH(port, &conf->conf_ports, p_next) {
1274 		if (strcasecmp(port->p_name, name) == 0)
1275 			return (port);
1276 	}
1277 
1278 	return (NULL);
1279 }
1280 
1281 struct port *
1282 port_find_in_pg(const struct portal_group *pg, const char *target)
1283 {
1284 	struct port *port;
1285 
1286 	TAILQ_FOREACH(port, &pg->pg_ports, p_pgs) {
1287 		if (strcasecmp(port->p_target->t_name, target) == 0)
1288 			return (port);
1289 	}
1290 
1291 	return (NULL);
1292 }
1293 
1294 void
1295 port_delete(struct port *port)
1296 {
1297 
1298 	if (port->p_portal_group)
1299 		TAILQ_REMOVE(&port->p_portal_group->pg_ports, port, p_pgs);
1300 	if (port->p_pport)
1301 		TAILQ_REMOVE(&port->p_pport->pp_ports, port, p_pps);
1302 	if (port->p_target)
1303 		TAILQ_REMOVE(&port->p_target->t_ports, port, p_ts);
1304 	TAILQ_REMOVE(&port->p_conf->conf_ports, port, p_next);
1305 	free(port->p_name);
1306 	free(port);
1307 }
1308 
1309 struct target *
1310 target_new(struct conf *conf, const char *name)
1311 {
1312 	struct target *targ;
1313 	int i, len;
1314 
1315 	targ = target_find(conf, name);
1316 	if (targ != NULL) {
1317 		log_warnx("duplicated target \"%s\"", name);
1318 		return (NULL);
1319 	}
1320 	if (valid_iscsi_name(name) == false) {
1321 		log_warnx("target name \"%s\" is invalid", name);
1322 		return (NULL);
1323 	}
1324 	targ = calloc(1, sizeof(*targ));
1325 	if (targ == NULL)
1326 		log_err(1, "calloc");
1327 	targ->t_name = checked_strdup(name);
1328 
1329 	/*
1330 	 * RFC 3722 requires us to normalize the name to lowercase.
1331 	 */
1332 	len = strlen(name);
1333 	for (i = 0; i < len; i++)
1334 		targ->t_name[i] = tolower(targ->t_name[i]);
1335 
1336 	targ->t_conf = conf;
1337 	TAILQ_INIT(&targ->t_ports);
1338 	TAILQ_INSERT_TAIL(&conf->conf_targets, targ, t_next);
1339 
1340 	return (targ);
1341 }
1342 
1343 void
1344 target_delete(struct target *targ)
1345 {
1346 	struct port *port, *tport;
1347 
1348 	TAILQ_FOREACH_SAFE(port, &targ->t_ports, p_ts, tport)
1349 		port_delete(port);
1350 	TAILQ_REMOVE(&targ->t_conf->conf_targets, targ, t_next);
1351 
1352 	free(targ->t_name);
1353 	free(targ->t_redirection);
1354 	free(targ);
1355 }
1356 
1357 struct target *
1358 target_find(struct conf *conf, const char *name)
1359 {
1360 	struct target *targ;
1361 
1362 	TAILQ_FOREACH(targ, &conf->conf_targets, t_next) {
1363 		if (strcasecmp(targ->t_name, name) == 0)
1364 			return (targ);
1365 	}
1366 
1367 	return (NULL);
1368 }
1369 
1370 int
1371 target_set_redirection(struct target *target, const char *addr)
1372 {
1373 
1374 	if (target->t_redirection != NULL) {
1375 		log_warnx("cannot set redirection to \"%s\" for "
1376 		    "target \"%s\"; already defined",
1377 		    addr, target->t_name);
1378 		return (1);
1379 	}
1380 
1381 	target->t_redirection = checked_strdup(addr);
1382 
1383 	return (0);
1384 }
1385 
1386 struct lun *
1387 lun_new(struct conf *conf, const char *name)
1388 {
1389 	struct lun *lun;
1390 
1391 	lun = lun_find(conf, name);
1392 	if (lun != NULL) {
1393 		log_warnx("duplicated lun \"%s\"", name);
1394 		return (NULL);
1395 	}
1396 
1397 	lun = calloc(1, sizeof(*lun));
1398 	if (lun == NULL)
1399 		log_err(1, "calloc");
1400 	lun->l_conf = conf;
1401 	lun->l_name = checked_strdup(name);
1402 	TAILQ_INIT(&lun->l_options);
1403 	TAILQ_INSERT_TAIL(&conf->conf_luns, lun, l_next);
1404 	lun->l_ctl_lun = -1;
1405 
1406 	return (lun);
1407 }
1408 
1409 void
1410 lun_delete(struct lun *lun)
1411 {
1412 	struct target *targ;
1413 	struct option *o, *tmp;
1414 	int i;
1415 
1416 	TAILQ_FOREACH(targ, &lun->l_conf->conf_targets, t_next) {
1417 		for (i = 0; i < MAX_LUNS; i++) {
1418 			if (targ->t_luns[i] == lun)
1419 				targ->t_luns[i] = NULL;
1420 		}
1421 	}
1422 	TAILQ_REMOVE(&lun->l_conf->conf_luns, lun, l_next);
1423 
1424 	TAILQ_FOREACH_SAFE(o, &lun->l_options, o_next, tmp)
1425 		option_delete(&lun->l_options, o);
1426 	free(lun->l_name);
1427 	free(lun->l_backend);
1428 	free(lun->l_device_id);
1429 	free(lun->l_path);
1430 	free(lun->l_scsiname);
1431 	free(lun->l_serial);
1432 	free(lun);
1433 }
1434 
1435 struct lun *
1436 lun_find(const struct conf *conf, const char *name)
1437 {
1438 	struct lun *lun;
1439 
1440 	TAILQ_FOREACH(lun, &conf->conf_luns, l_next) {
1441 		if (strcmp(lun->l_name, name) == 0)
1442 			return (lun);
1443 	}
1444 
1445 	return (NULL);
1446 }
1447 
1448 void
1449 lun_set_backend(struct lun *lun, const char *value)
1450 {
1451 	free(lun->l_backend);
1452 	lun->l_backend = checked_strdup(value);
1453 }
1454 
1455 void
1456 lun_set_blocksize(struct lun *lun, size_t value)
1457 {
1458 
1459 	lun->l_blocksize = value;
1460 }
1461 
1462 void
1463 lun_set_device_type(struct lun *lun, uint8_t value)
1464 {
1465 
1466 	lun->l_device_type = value;
1467 }
1468 
1469 void
1470 lun_set_device_id(struct lun *lun, const char *value)
1471 {
1472 	free(lun->l_device_id);
1473 	lun->l_device_id = checked_strdup(value);
1474 }
1475 
1476 void
1477 lun_set_path(struct lun *lun, const char *value)
1478 {
1479 	free(lun->l_path);
1480 	lun->l_path = checked_strdup(value);
1481 }
1482 
1483 void
1484 lun_set_scsiname(struct lun *lun, const char *value)
1485 {
1486 	free(lun->l_scsiname);
1487 	lun->l_scsiname = checked_strdup(value);
1488 }
1489 
1490 void
1491 lun_set_serial(struct lun *lun, const char *value)
1492 {
1493 	free(lun->l_serial);
1494 	lun->l_serial = checked_strdup(value);
1495 }
1496 
1497 void
1498 lun_set_size(struct lun *lun, size_t value)
1499 {
1500 
1501 	lun->l_size = value;
1502 }
1503 
1504 void
1505 lun_set_ctl_lun(struct lun *lun, uint32_t value)
1506 {
1507 
1508 	lun->l_ctl_lun = value;
1509 }
1510 
1511 struct option *
1512 option_new(struct options *options, const char *name, const char *value)
1513 {
1514 	struct option *o;
1515 
1516 	o = option_find(options, name);
1517 	if (o != NULL) {
1518 		log_warnx("duplicated option \"%s\"", name);
1519 		return (NULL);
1520 	}
1521 
1522 	o = calloc(1, sizeof(*o));
1523 	if (o == NULL)
1524 		log_err(1, "calloc");
1525 	o->o_name = checked_strdup(name);
1526 	o->o_value = checked_strdup(value);
1527 	TAILQ_INSERT_TAIL(options, o, o_next);
1528 
1529 	return (o);
1530 }
1531 
1532 void
1533 option_delete(struct options *options, struct option *o)
1534 {
1535 
1536 	TAILQ_REMOVE(options, o, o_next);
1537 	free(o->o_name);
1538 	free(o->o_value);
1539 	free(o);
1540 }
1541 
1542 struct option *
1543 option_find(const struct options *options, const char *name)
1544 {
1545 	struct option *o;
1546 
1547 	TAILQ_FOREACH(o, options, o_next) {
1548 		if (strcmp(o->o_name, name) == 0)
1549 			return (o);
1550 	}
1551 
1552 	return (NULL);
1553 }
1554 
1555 void
1556 option_set(struct option *o, const char *value)
1557 {
1558 
1559 	free(o->o_value);
1560 	o->o_value = checked_strdup(value);
1561 }
1562 
1563 static struct connection *
1564 connection_new(struct portal *portal, int fd, const char *host,
1565     const struct sockaddr *client_sa)
1566 {
1567 	struct connection *conn;
1568 
1569 	conn = calloc(1, sizeof(*conn));
1570 	if (conn == NULL)
1571 		log_err(1, "calloc");
1572 	conn->conn_portal = portal;
1573 	conn->conn_socket = fd;
1574 	conn->conn_initiator_addr = checked_strdup(host);
1575 	memcpy(&conn->conn_initiator_sa, client_sa, client_sa->sa_len);
1576 
1577 	/*
1578 	 * Default values, from RFC 3720, section 12.
1579 	 */
1580 	conn->conn_max_data_segment_length = 8192;
1581 	conn->conn_max_burst_length = 262144;
1582 	conn->conn_immediate_data = true;
1583 
1584 	return (conn);
1585 }
1586 
1587 #if 0
1588 static void
1589 conf_print(struct conf *conf)
1590 {
1591 	struct auth_group *ag;
1592 	struct auth *auth;
1593 	struct auth_name *auth_name;
1594 	struct auth_portal *auth_portal;
1595 	struct portal_group *pg;
1596 	struct portal *portal;
1597 	struct target *targ;
1598 	struct lun *lun;
1599 	struct option *o;
1600 
1601 	TAILQ_FOREACH(ag, &conf->conf_auth_groups, ag_next) {
1602 		fprintf(stderr, "auth-group %s {\n", ag->ag_name);
1603 		TAILQ_FOREACH(auth, &ag->ag_auths, a_next)
1604 			fprintf(stderr, "\t chap-mutual %s %s %s %s\n",
1605 			    auth->a_user, auth->a_secret,
1606 			    auth->a_mutual_user, auth->a_mutual_secret);
1607 		TAILQ_FOREACH(auth_name, &ag->ag_names, an_next)
1608 			fprintf(stderr, "\t initiator-name %s\n",
1609 			    auth_name->an_initator_name);
1610 		TAILQ_FOREACH(auth_portal, &ag->ag_portals, an_next)
1611 			fprintf(stderr, "\t initiator-portal %s\n",
1612 			    auth_portal->an_initator_portal);
1613 		fprintf(stderr, "}\n");
1614 	}
1615 	TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
1616 		fprintf(stderr, "portal-group %s {\n", pg->pg_name);
1617 		TAILQ_FOREACH(portal, &pg->pg_portals, p_next)
1618 			fprintf(stderr, "\t listen %s\n", portal->p_listen);
1619 		fprintf(stderr, "}\n");
1620 	}
1621 	TAILQ_FOREACH(lun, &conf->conf_luns, l_next) {
1622 		fprintf(stderr, "\tlun %s {\n", lun->l_name);
1623 		fprintf(stderr, "\t\tpath %s\n", lun->l_path);
1624 		TAILQ_FOREACH(o, &lun->l_options, o_next)
1625 			fprintf(stderr, "\t\toption %s %s\n",
1626 			    lo->o_name, lo->o_value);
1627 		fprintf(stderr, "\t}\n");
1628 	}
1629 	TAILQ_FOREACH(targ, &conf->conf_targets, t_next) {
1630 		fprintf(stderr, "target %s {\n", targ->t_name);
1631 		if (targ->t_alias != NULL)
1632 			fprintf(stderr, "\t alias %s\n", targ->t_alias);
1633 		fprintf(stderr, "}\n");
1634 	}
1635 }
1636 #endif
1637 
1638 static int
1639 conf_verify_lun(struct lun *lun)
1640 {
1641 	const struct lun *lun2;
1642 
1643 	if (lun->l_backend == NULL)
1644 		lun_set_backend(lun, "block");
1645 	if (strcmp(lun->l_backend, "block") == 0) {
1646 		if (lun->l_path == NULL) {
1647 			log_warnx("missing path for lun \"%s\"",
1648 			    lun->l_name);
1649 			return (1);
1650 		}
1651 	} else if (strcmp(lun->l_backend, "ramdisk") == 0) {
1652 		if (lun->l_size == 0) {
1653 			log_warnx("missing size for ramdisk-backed lun \"%s\"",
1654 			    lun->l_name);
1655 			return (1);
1656 		}
1657 		if (lun->l_path != NULL) {
1658 			log_warnx("path must not be specified "
1659 			    "for ramdisk-backed lun \"%s\"",
1660 			    lun->l_name);
1661 			return (1);
1662 		}
1663 	}
1664 	if (lun->l_blocksize == 0) {
1665 		if (lun->l_device_type == 5)
1666 			lun_set_blocksize(lun, DEFAULT_CD_BLOCKSIZE);
1667 		else
1668 			lun_set_blocksize(lun, DEFAULT_BLOCKSIZE);
1669 	} else if (lun->l_blocksize < 0) {
1670 		log_warnx("invalid blocksize for lun \"%s\"; "
1671 		    "must be larger than 0", lun->l_name);
1672 		return (1);
1673 	}
1674 	if (lun->l_size != 0 && lun->l_size % lun->l_blocksize != 0) {
1675 		log_warnx("invalid size for lun \"%s\"; "
1676 		    "must be multiple of blocksize", lun->l_name);
1677 		return (1);
1678 	}
1679 	TAILQ_FOREACH(lun2, &lun->l_conf->conf_luns, l_next) {
1680 		if (lun == lun2)
1681 			continue;
1682 		if (lun->l_path != NULL && lun2->l_path != NULL &&
1683 		    strcmp(lun->l_path, lun2->l_path) == 0) {
1684 			log_debugx("WARNING: path \"%s\" duplicated "
1685 			    "between lun \"%s\", and "
1686 			    "lun \"%s\"", lun->l_path,
1687 			    lun->l_name, lun2->l_name);
1688 		}
1689 	}
1690 
1691 	return (0);
1692 }
1693 
1694 int
1695 conf_verify(struct conf *conf)
1696 {
1697 	struct auth_group *ag;
1698 	struct portal_group *pg;
1699 	struct port *port;
1700 	struct target *targ;
1701 	struct lun *lun;
1702 	bool found;
1703 	int error, i;
1704 
1705 	if (conf->conf_pidfile_path == NULL)
1706 		conf->conf_pidfile_path = checked_strdup(DEFAULT_PIDFILE);
1707 
1708 	TAILQ_FOREACH(lun, &conf->conf_luns, l_next) {
1709 		error = conf_verify_lun(lun);
1710 		if (error != 0)
1711 			return (error);
1712 	}
1713 	TAILQ_FOREACH(targ, &conf->conf_targets, t_next) {
1714 		if (targ->t_auth_group == NULL) {
1715 			targ->t_auth_group = auth_group_find(conf,
1716 			    "default");
1717 			assert(targ->t_auth_group != NULL);
1718 		}
1719 		if (TAILQ_EMPTY(&targ->t_ports)) {
1720 			pg = portal_group_find(conf, "default");
1721 			assert(pg != NULL);
1722 			port_new(conf, targ, pg);
1723 		}
1724 		found = false;
1725 		for (i = 0; i < MAX_LUNS; i++) {
1726 			if (targ->t_luns[i] != NULL)
1727 				found = true;
1728 		}
1729 		if (!found && targ->t_redirection == NULL) {
1730 			log_warnx("no LUNs defined for target \"%s\"",
1731 			    targ->t_name);
1732 		}
1733 		if (found && targ->t_redirection != NULL) {
1734 			log_debugx("target \"%s\" contains luns, "
1735 			    " but configured for redirection",
1736 			    targ->t_name);
1737 		}
1738 	}
1739 	TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
1740 		assert(pg->pg_name != NULL);
1741 		if (pg->pg_discovery_auth_group == NULL) {
1742 			pg->pg_discovery_auth_group =
1743 			    auth_group_find(conf, "default");
1744 			assert(pg->pg_discovery_auth_group != NULL);
1745 		}
1746 
1747 		if (pg->pg_discovery_filter == PG_FILTER_UNKNOWN)
1748 			pg->pg_discovery_filter = PG_FILTER_NONE;
1749 
1750 		if (pg->pg_redirection != NULL) {
1751 			if (!TAILQ_EMPTY(&pg->pg_ports)) {
1752 				log_debugx("portal-group \"%s\" assigned "
1753 				    "to target, but configured "
1754 				    "for redirection",
1755 				    pg->pg_name);
1756 			}
1757 			pg->pg_unassigned = false;
1758 		} else if (!TAILQ_EMPTY(&pg->pg_ports)) {
1759 			pg->pg_unassigned = false;
1760 		} else {
1761 			if (strcmp(pg->pg_name, "default") != 0)
1762 				log_warnx("portal-group \"%s\" not assigned "
1763 				    "to any target", pg->pg_name);
1764 			pg->pg_unassigned = true;
1765 		}
1766 	}
1767 	TAILQ_FOREACH(ag, &conf->conf_auth_groups, ag_next) {
1768 		if (ag->ag_name == NULL)
1769 			assert(ag->ag_target != NULL);
1770 		else
1771 			assert(ag->ag_target == NULL);
1772 
1773 		found = false;
1774 		TAILQ_FOREACH(targ, &conf->conf_targets, t_next) {
1775 			if (targ->t_auth_group == ag) {
1776 				found = true;
1777 				break;
1778 			}
1779 		}
1780 		TAILQ_FOREACH(port, &conf->conf_ports, p_next) {
1781 			if (port->p_auth_group == ag) {
1782 				found = true;
1783 				break;
1784 			}
1785 		}
1786 		TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
1787 			if (pg->pg_discovery_auth_group == ag) {
1788 				found = true;
1789 				break;
1790 			}
1791 		}
1792 		if (!found && ag->ag_name != NULL &&
1793 		    strcmp(ag->ag_name, "default") != 0 &&
1794 		    strcmp(ag->ag_name, "no-authentication") != 0 &&
1795 		    strcmp(ag->ag_name, "no-access") != 0) {
1796 			log_warnx("auth-group \"%s\" not assigned "
1797 			    "to any target", ag->ag_name);
1798 		}
1799 	}
1800 
1801 	return (0);
1802 }
1803 
1804 static int
1805 conf_apply(struct conf *oldconf, struct conf *newconf)
1806 {
1807 	struct lun *oldlun, *newlun, *tmplun;
1808 	struct portal_group *oldpg, *newpg;
1809 	struct portal *oldp, *newp;
1810 	struct port *oldport, *newport, *tmpport;
1811 	struct isns *oldns, *newns;
1812 	pid_t otherpid;
1813 	int changed, cumulated_error = 0, error, sockbuf;
1814 	int one = 1;
1815 
1816 	if (oldconf->conf_debug != newconf->conf_debug) {
1817 		log_debugx("changing debug level to %d", newconf->conf_debug);
1818 		log_init(newconf->conf_debug);
1819 	}
1820 
1821 	if (oldconf->conf_pidfh != NULL) {
1822 		assert(oldconf->conf_pidfile_path != NULL);
1823 		if (newconf->conf_pidfile_path != NULL &&
1824 		    strcmp(oldconf->conf_pidfile_path,
1825 		    newconf->conf_pidfile_path) == 0) {
1826 			newconf->conf_pidfh = oldconf->conf_pidfh;
1827 			oldconf->conf_pidfh = NULL;
1828 		} else {
1829 			log_debugx("removing pidfile %s",
1830 			    oldconf->conf_pidfile_path);
1831 			pidfile_remove(oldconf->conf_pidfh);
1832 			oldconf->conf_pidfh = NULL;
1833 		}
1834 	}
1835 
1836 	if (newconf->conf_pidfh == NULL && newconf->conf_pidfile_path != NULL) {
1837 		log_debugx("opening pidfile %s", newconf->conf_pidfile_path);
1838 		newconf->conf_pidfh =
1839 		    pidfile_open(newconf->conf_pidfile_path, 0600, &otherpid);
1840 		if (newconf->conf_pidfh == NULL) {
1841 			if (errno == EEXIST)
1842 				log_errx(1, "daemon already running, pid: %jd.",
1843 				    (intmax_t)otherpid);
1844 			log_err(1, "cannot open or create pidfile \"%s\"",
1845 			    newconf->conf_pidfile_path);
1846 		}
1847 	}
1848 
1849 	/*
1850 	 * Go through the new portal groups, assigning tags or preserving old.
1851 	 */
1852 	TAILQ_FOREACH(newpg, &newconf->conf_portal_groups, pg_next) {
1853 		if (newpg->pg_tag != 0)
1854 			continue;
1855 		oldpg = portal_group_find(oldconf, newpg->pg_name);
1856 		if (oldpg != NULL)
1857 			newpg->pg_tag = oldpg->pg_tag;
1858 		else
1859 			newpg->pg_tag = ++last_portal_group_tag;
1860 	}
1861 
1862 	/* Deregister on removed iSNS servers. */
1863 	TAILQ_FOREACH(oldns, &oldconf->conf_isns, i_next) {
1864 		TAILQ_FOREACH(newns, &newconf->conf_isns, i_next) {
1865 			if (strcmp(oldns->i_addr, newns->i_addr) == 0)
1866 				break;
1867 		}
1868 		if (newns == NULL)
1869 			isns_deregister(oldns);
1870 	}
1871 
1872 	/*
1873 	 * XXX: If target or lun removal fails, we should somehow "move"
1874 	 *      the old lun or target into newconf, so that subsequent
1875 	 *      conf_apply() would try to remove them again.  That would
1876 	 *      be somewhat hairy, though, and lun deletion failures don't
1877 	 *      really happen, so leave it as it is for now.
1878 	 */
1879 	/*
1880 	 * First, remove any ports present in the old configuration
1881 	 * and missing in the new one.
1882 	 */
1883 	TAILQ_FOREACH_SAFE(oldport, &oldconf->conf_ports, p_next, tmpport) {
1884 		if (oldport->p_foreign)
1885 			continue;
1886 		newport = port_find(newconf, oldport->p_name);
1887 		if (newport != NULL && !newport->p_foreign)
1888 			continue;
1889 		log_debugx("removing port \"%s\"", oldport->p_name);
1890 		error = kernel_port_remove(oldport);
1891 		if (error != 0) {
1892 			log_warnx("failed to remove port %s",
1893 			    oldport->p_name);
1894 			/*
1895 			 * XXX: Uncomment after fixing the root cause.
1896 			 *
1897 			 * cumulated_error++;
1898 			 */
1899 		}
1900 	}
1901 
1902 	/*
1903 	 * Second, remove any LUNs present in the old configuration
1904 	 * and missing in the new one.
1905 	 */
1906 	TAILQ_FOREACH_SAFE(oldlun, &oldconf->conf_luns, l_next, tmplun) {
1907 		newlun = lun_find(newconf, oldlun->l_name);
1908 		if (newlun == NULL) {
1909 			log_debugx("lun \"%s\", CTL lun %d "
1910 			    "not found in new configuration; "
1911 			    "removing", oldlun->l_name, oldlun->l_ctl_lun);
1912 			error = kernel_lun_remove(oldlun);
1913 			if (error != 0) {
1914 				log_warnx("failed to remove lun \"%s\", "
1915 				    "CTL lun %d",
1916 				    oldlun->l_name, oldlun->l_ctl_lun);
1917 				cumulated_error++;
1918 			}
1919 			continue;
1920 		}
1921 
1922 		/*
1923 		 * Also remove the LUNs changed by more than size.
1924 		 */
1925 		changed = 0;
1926 		assert(oldlun->l_backend != NULL);
1927 		assert(newlun->l_backend != NULL);
1928 		if (strcmp(newlun->l_backend, oldlun->l_backend) != 0) {
1929 			log_debugx("backend for lun \"%s\", "
1930 			    "CTL lun %d changed; removing",
1931 			    oldlun->l_name, oldlun->l_ctl_lun);
1932 			changed = 1;
1933 		}
1934 		if (oldlun->l_blocksize != newlun->l_blocksize) {
1935 			log_debugx("blocksize for lun \"%s\", "
1936 			    "CTL lun %d changed; removing",
1937 			    oldlun->l_name, oldlun->l_ctl_lun);
1938 			changed = 1;
1939 		}
1940 		if (newlun->l_device_id != NULL &&
1941 		    (oldlun->l_device_id == NULL ||
1942 		     strcmp(oldlun->l_device_id, newlun->l_device_id) !=
1943 		     0)) {
1944 			log_debugx("device-id for lun \"%s\", "
1945 			    "CTL lun %d changed; removing",
1946 			    oldlun->l_name, oldlun->l_ctl_lun);
1947 			changed = 1;
1948 		}
1949 		if (newlun->l_path != NULL &&
1950 		    (oldlun->l_path == NULL ||
1951 		     strcmp(oldlun->l_path, newlun->l_path) != 0)) {
1952 			log_debugx("path for lun \"%s\", "
1953 			    "CTL lun %d, changed; removing",
1954 			    oldlun->l_name, oldlun->l_ctl_lun);
1955 			changed = 1;
1956 		}
1957 		if (newlun->l_serial != NULL &&
1958 		    (oldlun->l_serial == NULL ||
1959 		     strcmp(oldlun->l_serial, newlun->l_serial) != 0)) {
1960 			log_debugx("serial for lun \"%s\", "
1961 			    "CTL lun %d changed; removing",
1962 			    oldlun->l_name, oldlun->l_ctl_lun);
1963 			changed = 1;
1964 		}
1965 		if (changed) {
1966 			error = kernel_lun_remove(oldlun);
1967 			if (error != 0) {
1968 				log_warnx("failed to remove lun \"%s\", "
1969 				    "CTL lun %d",
1970 				    oldlun->l_name, oldlun->l_ctl_lun);
1971 				cumulated_error++;
1972 			}
1973 			lun_delete(oldlun);
1974 			continue;
1975 		}
1976 
1977 		lun_set_ctl_lun(newlun, oldlun->l_ctl_lun);
1978 	}
1979 
1980 	TAILQ_FOREACH_SAFE(newlun, &newconf->conf_luns, l_next, tmplun) {
1981 		oldlun = lun_find(oldconf, newlun->l_name);
1982 		if (oldlun != NULL) {
1983 			log_debugx("modifying lun \"%s\", CTL lun %d",
1984 			    newlun->l_name, newlun->l_ctl_lun);
1985 			error = kernel_lun_modify(newlun);
1986 			if (error != 0) {
1987 				log_warnx("failed to "
1988 				    "modify lun \"%s\", CTL lun %d",
1989 				    newlun->l_name, newlun->l_ctl_lun);
1990 				cumulated_error++;
1991 			}
1992 			continue;
1993 		}
1994 		log_debugx("adding lun \"%s\"", newlun->l_name);
1995 		error = kernel_lun_add(newlun);
1996 		if (error != 0) {
1997 			log_warnx("failed to add lun \"%s\"", newlun->l_name);
1998 			lun_delete(newlun);
1999 			cumulated_error++;
2000 		}
2001 	}
2002 
2003 	/*
2004 	 * Now add new ports or modify existing ones.
2005 	 */
2006 	TAILQ_FOREACH(newport, &newconf->conf_ports, p_next) {
2007 		if (newport->p_foreign)
2008 			continue;
2009 		oldport = port_find(oldconf, newport->p_name);
2010 
2011 		if (oldport == NULL || oldport->p_foreign) {
2012 			log_debugx("adding port \"%s\"", newport->p_name);
2013 			error = kernel_port_add(newport);
2014 		} else {
2015 			log_debugx("updating port \"%s\"", newport->p_name);
2016 			newport->p_ctl_port = oldport->p_ctl_port;
2017 			error = kernel_port_update(newport, oldport);
2018 		}
2019 		if (error != 0) {
2020 			log_warnx("failed to %s port %s",
2021 			    (oldport == NULL) ? "add" : "update",
2022 			    newport->p_name);
2023 			/*
2024 			 * XXX: Uncomment after fixing the root cause.
2025 			 *
2026 			 * cumulated_error++;
2027 			 */
2028 		}
2029 	}
2030 
2031 	/*
2032 	 * Go through the new portals, opening the sockets as necessary.
2033 	 */
2034 	TAILQ_FOREACH(newpg, &newconf->conf_portal_groups, pg_next) {
2035 		if (newpg->pg_foreign)
2036 			continue;
2037 		if (newpg->pg_unassigned) {
2038 			log_debugx("not listening on portal-group \"%s\", "
2039 			    "not assigned to any target",
2040 			    newpg->pg_name);
2041 			continue;
2042 		}
2043 		TAILQ_FOREACH(newp, &newpg->pg_portals, p_next) {
2044 			/*
2045 			 * Try to find already open portal and reuse
2046 			 * the listening socket.  We don't care about
2047 			 * what portal or portal group that was, what
2048 			 * matters is the listening address.
2049 			 */
2050 			TAILQ_FOREACH(oldpg, &oldconf->conf_portal_groups,
2051 			    pg_next) {
2052 				TAILQ_FOREACH(oldp, &oldpg->pg_portals,
2053 				    p_next) {
2054 					if (strcmp(newp->p_listen,
2055 					    oldp->p_listen) == 0 &&
2056 					    oldp->p_socket > 0) {
2057 						newp->p_socket =
2058 						    oldp->p_socket;
2059 						oldp->p_socket = 0;
2060 						break;
2061 					}
2062 				}
2063 			}
2064 			if (newp->p_socket > 0) {
2065 				/*
2066 				 * We're done with this portal.
2067 				 */
2068 				continue;
2069 			}
2070 
2071 #ifdef ICL_KERNEL_PROXY
2072 			if (proxy_mode) {
2073 				newpg->pg_conf->conf_portal_id++;
2074 				newp->p_id = newpg->pg_conf->conf_portal_id;
2075 				log_debugx("listening on %s, portal-group "
2076 				    "\"%s\", portal id %d, using ICL proxy",
2077 				    newp->p_listen, newpg->pg_name, newp->p_id);
2078 				kernel_listen(newp->p_ai, newp->p_iser,
2079 				    newp->p_id);
2080 				continue;
2081 			}
2082 #endif
2083 			assert(proxy_mode == false);
2084 			assert(newp->p_iser == false);
2085 
2086 			log_debugx("listening on %s, portal-group \"%s\"",
2087 			    newp->p_listen, newpg->pg_name);
2088 			newp->p_socket = socket(newp->p_ai->ai_family,
2089 			    newp->p_ai->ai_socktype,
2090 			    newp->p_ai->ai_protocol);
2091 			if (newp->p_socket < 0) {
2092 				log_warn("socket(2) failed for %s",
2093 				    newp->p_listen);
2094 				cumulated_error++;
2095 				continue;
2096 			}
2097 			sockbuf = SOCKBUF_SIZE;
2098 			if (setsockopt(newp->p_socket, SOL_SOCKET, SO_RCVBUF,
2099 			    &sockbuf, sizeof(sockbuf)) == -1)
2100 				log_warn("setsockopt(SO_RCVBUF) failed "
2101 				    "for %s", newp->p_listen);
2102 			sockbuf = SOCKBUF_SIZE;
2103 			if (setsockopt(newp->p_socket, SOL_SOCKET, SO_SNDBUF,
2104 			    &sockbuf, sizeof(sockbuf)) == -1)
2105 				log_warn("setsockopt(SO_SNDBUF) failed "
2106 				    "for %s", newp->p_listen);
2107 			error = setsockopt(newp->p_socket, SOL_SOCKET,
2108 			    SO_REUSEADDR, &one, sizeof(one));
2109 			if (error != 0) {
2110 				log_warn("setsockopt(SO_REUSEADDR) failed "
2111 				    "for %s", newp->p_listen);
2112 				close(newp->p_socket);
2113 				newp->p_socket = 0;
2114 				cumulated_error++;
2115 				continue;
2116 			}
2117 			error = bind(newp->p_socket, newp->p_ai->ai_addr,
2118 			    newp->p_ai->ai_addrlen);
2119 			if (error != 0) {
2120 				log_warn("bind(2) failed for %s",
2121 				    newp->p_listen);
2122 				close(newp->p_socket);
2123 				newp->p_socket = 0;
2124 				cumulated_error++;
2125 				continue;
2126 			}
2127 			error = listen(newp->p_socket, -1);
2128 			if (error != 0) {
2129 				log_warn("listen(2) failed for %s",
2130 				    newp->p_listen);
2131 				close(newp->p_socket);
2132 				newp->p_socket = 0;
2133 				cumulated_error++;
2134 				continue;
2135 			}
2136 		}
2137 	}
2138 
2139 	/*
2140 	 * Go through the no longer used sockets, closing them.
2141 	 */
2142 	TAILQ_FOREACH(oldpg, &oldconf->conf_portal_groups, pg_next) {
2143 		TAILQ_FOREACH(oldp, &oldpg->pg_portals, p_next) {
2144 			if (oldp->p_socket <= 0)
2145 				continue;
2146 			log_debugx("closing socket for %s, portal-group \"%s\"",
2147 			    oldp->p_listen, oldpg->pg_name);
2148 			close(oldp->p_socket);
2149 			oldp->p_socket = 0;
2150 		}
2151 	}
2152 
2153 	/* (Re-)Register on remaining/new iSNS servers. */
2154 	TAILQ_FOREACH(newns, &newconf->conf_isns, i_next) {
2155 		TAILQ_FOREACH(oldns, &oldconf->conf_isns, i_next) {
2156 			if (strcmp(oldns->i_addr, newns->i_addr) == 0)
2157 				break;
2158 		}
2159 		isns_register(newns, oldns);
2160 	}
2161 
2162 	/* Schedule iSNS update */
2163 	if (!TAILQ_EMPTY(&newconf->conf_isns))
2164 		set_timeout((newconf->conf_isns_period + 2) / 3, false);
2165 
2166 	return (cumulated_error);
2167 }
2168 
2169 bool
2170 timed_out(void)
2171 {
2172 
2173 	return (sigalrm_received);
2174 }
2175 
2176 static void
2177 sigalrm_handler_fatal(int dummy __unused)
2178 {
2179 	/*
2180 	 * It would be easiest to just log an error and exit.  We can't
2181 	 * do this, though, because log_errx() is not signal safe, since
2182 	 * it calls syslog(3).  Instead, set a flag checked by pdu_send()
2183 	 * and pdu_receive(), to call log_errx() there.  Should they fail
2184 	 * to notice, we'll exit here one second later.
2185 	 */
2186 	if (sigalrm_received) {
2187 		/*
2188 		 * Oh well.  Just give up and quit.
2189 		 */
2190 		_exit(2);
2191 	}
2192 
2193 	sigalrm_received = true;
2194 }
2195 
2196 static void
2197 sigalrm_handler(int dummy __unused)
2198 {
2199 
2200 	sigalrm_received = true;
2201 }
2202 
2203 void
2204 set_timeout(int timeout, int fatal)
2205 {
2206 	struct sigaction sa;
2207 	struct itimerval itv;
2208 	int error;
2209 
2210 	if (timeout <= 0) {
2211 		log_debugx("session timeout disabled");
2212 		bzero(&itv, sizeof(itv));
2213 		error = setitimer(ITIMER_REAL, &itv, NULL);
2214 		if (error != 0)
2215 			log_err(1, "setitimer");
2216 		sigalrm_received = false;
2217 		return;
2218 	}
2219 
2220 	sigalrm_received = false;
2221 	bzero(&sa, sizeof(sa));
2222 	if (fatal)
2223 		sa.sa_handler = sigalrm_handler_fatal;
2224 	else
2225 		sa.sa_handler = sigalrm_handler;
2226 	sigfillset(&sa.sa_mask);
2227 	error = sigaction(SIGALRM, &sa, NULL);
2228 	if (error != 0)
2229 		log_err(1, "sigaction");
2230 
2231 	/*
2232 	 * First SIGALRM will arive after conf_timeout seconds.
2233 	 * If we do nothing, another one will arrive a second later.
2234 	 */
2235 	log_debugx("setting session timeout to %d seconds", timeout);
2236 	bzero(&itv, sizeof(itv));
2237 	itv.it_interval.tv_sec = 1;
2238 	itv.it_value.tv_sec = timeout;
2239 	error = setitimer(ITIMER_REAL, &itv, NULL);
2240 	if (error != 0)
2241 		log_err(1, "setitimer");
2242 }
2243 
2244 static int
2245 wait_for_children(bool block)
2246 {
2247 	pid_t pid;
2248 	int status;
2249 	int num = 0;
2250 
2251 	for (;;) {
2252 		/*
2253 		 * If "block" is true, wait for at least one process.
2254 		 */
2255 		if (block && num == 0)
2256 			pid = wait4(-1, &status, 0, NULL);
2257 		else
2258 			pid = wait4(-1, &status, WNOHANG, NULL);
2259 		if (pid <= 0)
2260 			break;
2261 		if (WIFSIGNALED(status)) {
2262 			log_warnx("child process %d terminated with signal %d",
2263 			    pid, WTERMSIG(status));
2264 		} else if (WEXITSTATUS(status) != 0) {
2265 			log_warnx("child process %d terminated with exit status %d",
2266 			    pid, WEXITSTATUS(status));
2267 		} else {
2268 			log_debugx("child process %d terminated gracefully", pid);
2269 		}
2270 		num++;
2271 	}
2272 
2273 	return (num);
2274 }
2275 
2276 static void
2277 handle_connection(struct portal *portal, int fd,
2278     const struct sockaddr *client_sa, bool dont_fork)
2279 {
2280 	struct connection *conn;
2281 	int error;
2282 	pid_t pid;
2283 	char host[NI_MAXHOST + 1];
2284 	struct conf *conf;
2285 
2286 	conf = portal->p_portal_group->pg_conf;
2287 
2288 	if (dont_fork) {
2289 		log_debugx("incoming connection; not forking due to -d flag");
2290 	} else {
2291 		nchildren -= wait_for_children(false);
2292 		assert(nchildren >= 0);
2293 
2294 		while (conf->conf_maxproc > 0 && nchildren >= conf->conf_maxproc) {
2295 			log_debugx("maxproc limit of %d child processes hit; "
2296 			    "waiting for child process to exit", conf->conf_maxproc);
2297 			nchildren -= wait_for_children(true);
2298 			assert(nchildren >= 0);
2299 		}
2300 		log_debugx("incoming connection; forking child process #%d",
2301 		    nchildren);
2302 		nchildren++;
2303 		pid = fork();
2304 		if (pid < 0)
2305 			log_err(1, "fork");
2306 		if (pid > 0) {
2307 			close(fd);
2308 			return;
2309 		}
2310 	}
2311 	pidfile_close(conf->conf_pidfh);
2312 
2313 	error = getnameinfo(client_sa, client_sa->sa_len,
2314 	    host, sizeof(host), NULL, 0, NI_NUMERICHOST);
2315 	if (error != 0)
2316 		log_errx(1, "getnameinfo: %s", gai_strerror(error));
2317 
2318 	log_debugx("accepted connection from %s; portal group \"%s\"",
2319 	    host, portal->p_portal_group->pg_name);
2320 	log_set_peer_addr(host);
2321 	setproctitle("%s", host);
2322 
2323 	conn = connection_new(portal, fd, host, client_sa);
2324 	set_timeout(conf->conf_timeout, true);
2325 	kernel_capsicate();
2326 	login(conn);
2327 	if (conn->conn_session_type == CONN_SESSION_TYPE_NORMAL) {
2328 		kernel_handoff(conn);
2329 		log_debugx("connection handed off to the kernel");
2330 	} else {
2331 		assert(conn->conn_session_type == CONN_SESSION_TYPE_DISCOVERY);
2332 		discovery(conn);
2333 	}
2334 	log_debugx("nothing more to do; exiting");
2335 	exit(0);
2336 }
2337 
2338 static int
2339 fd_add(int fd, fd_set *fdset, int nfds)
2340 {
2341 
2342 	/*
2343 	 * Skip sockets which we failed to bind.
2344 	 */
2345 	if (fd <= 0)
2346 		return (nfds);
2347 
2348 	FD_SET(fd, fdset);
2349 	if (fd > nfds)
2350 		nfds = fd;
2351 	return (nfds);
2352 }
2353 
2354 static void
2355 main_loop(struct conf *conf, bool dont_fork)
2356 {
2357 	struct portal_group *pg;
2358 	struct portal *portal;
2359 	struct sockaddr_storage client_sa;
2360 	socklen_t client_salen;
2361 #ifdef ICL_KERNEL_PROXY
2362 	int connection_id;
2363 	int portal_id;
2364 #endif
2365 	fd_set fdset;
2366 	int error, nfds, client_fd;
2367 
2368 	pidfile_write(conf->conf_pidfh);
2369 
2370 	for (;;) {
2371 		if (sighup_received || sigterm_received || timed_out())
2372 			return;
2373 
2374 #ifdef ICL_KERNEL_PROXY
2375 		if (proxy_mode) {
2376 			client_salen = sizeof(client_sa);
2377 			kernel_accept(&connection_id, &portal_id,
2378 			    (struct sockaddr *)&client_sa, &client_salen);
2379 			assert(client_salen >= client_sa.ss_len);
2380 
2381 			log_debugx("incoming connection, id %d, portal id %d",
2382 			    connection_id, portal_id);
2383 			TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
2384 				TAILQ_FOREACH(portal, &pg->pg_portals, p_next) {
2385 					if (portal->p_id == portal_id) {
2386 						goto found;
2387 					}
2388 				}
2389 			}
2390 
2391 			log_errx(1, "kernel returned invalid portal_id %d",
2392 			    portal_id);
2393 
2394 found:
2395 			handle_connection(portal, connection_id,
2396 			    (struct sockaddr *)&client_sa, dont_fork);
2397 		} else {
2398 #endif
2399 			assert(proxy_mode == false);
2400 
2401 			FD_ZERO(&fdset);
2402 			nfds = 0;
2403 			TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
2404 				TAILQ_FOREACH(portal, &pg->pg_portals, p_next)
2405 					nfds = fd_add(portal->p_socket, &fdset, nfds);
2406 			}
2407 			error = select(nfds + 1, &fdset, NULL, NULL, NULL);
2408 			if (error <= 0) {
2409 				if (errno == EINTR)
2410 					return;
2411 				log_err(1, "select");
2412 			}
2413 			TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
2414 				TAILQ_FOREACH(portal, &pg->pg_portals, p_next) {
2415 					if (!FD_ISSET(portal->p_socket, &fdset))
2416 						continue;
2417 					client_salen = sizeof(client_sa);
2418 					client_fd = accept(portal->p_socket,
2419 					    (struct sockaddr *)&client_sa,
2420 					    &client_salen);
2421 					if (client_fd < 0) {
2422 						if (errno == ECONNABORTED)
2423 							continue;
2424 						log_err(1, "accept");
2425 					}
2426 					assert(client_salen >= client_sa.ss_len);
2427 
2428 					handle_connection(portal, client_fd,
2429 					    (struct sockaddr *)&client_sa,
2430 					    dont_fork);
2431 					break;
2432 				}
2433 			}
2434 #ifdef ICL_KERNEL_PROXY
2435 		}
2436 #endif
2437 	}
2438 }
2439 
2440 static void
2441 sighup_handler(int dummy __unused)
2442 {
2443 
2444 	sighup_received = true;
2445 }
2446 
2447 static void
2448 sigterm_handler(int dummy __unused)
2449 {
2450 
2451 	sigterm_received = true;
2452 }
2453 
2454 static void
2455 sigchld_handler(int dummy __unused)
2456 {
2457 
2458 	/*
2459 	 * The only purpose of this handler is to make SIGCHLD
2460 	 * interrupt the ISCSIDWAIT ioctl(2), so we can call
2461 	 * wait_for_children().
2462 	 */
2463 }
2464 
2465 static void
2466 register_signals(void)
2467 {
2468 	struct sigaction sa;
2469 	int error;
2470 
2471 	bzero(&sa, sizeof(sa));
2472 	sa.sa_handler = sighup_handler;
2473 	sigfillset(&sa.sa_mask);
2474 	error = sigaction(SIGHUP, &sa, NULL);
2475 	if (error != 0)
2476 		log_err(1, "sigaction");
2477 
2478 	sa.sa_handler = sigterm_handler;
2479 	error = sigaction(SIGTERM, &sa, NULL);
2480 	if (error != 0)
2481 		log_err(1, "sigaction");
2482 
2483 	sa.sa_handler = sigterm_handler;
2484 	error = sigaction(SIGINT, &sa, NULL);
2485 	if (error != 0)
2486 		log_err(1, "sigaction");
2487 
2488 	sa.sa_handler = sigchld_handler;
2489 	error = sigaction(SIGCHLD, &sa, NULL);
2490 	if (error != 0)
2491 		log_err(1, "sigaction");
2492 }
2493 
2494 int
2495 main(int argc, char **argv)
2496 {
2497 	struct conf *oldconf, *newconf, *tmpconf;
2498 	struct isns *newns;
2499 	const char *config_path = DEFAULT_CONFIG_PATH;
2500 	int debug = 0, ch, error;
2501 	bool dont_daemonize = false;
2502 
2503 	while ((ch = getopt(argc, argv, "df:R")) != -1) {
2504 		switch (ch) {
2505 		case 'd':
2506 			dont_daemonize = true;
2507 			debug++;
2508 			break;
2509 		case 'f':
2510 			config_path = optarg;
2511 			break;
2512 		case 'R':
2513 #ifndef ICL_KERNEL_PROXY
2514 			log_errx(1, "ctld(8) compiled without ICL_KERNEL_PROXY "
2515 			    "does not support iSER protocol");
2516 #endif
2517 			proxy_mode = true;
2518 			break;
2519 		case '?':
2520 		default:
2521 			usage();
2522 		}
2523 	}
2524 	argc -= optind;
2525 	if (argc != 0)
2526 		usage();
2527 
2528 	log_init(debug);
2529 	kernel_init();
2530 
2531 	oldconf = conf_new_from_kernel();
2532 	newconf = conf_new_from_file(config_path, oldconf);
2533 	if (newconf == NULL)
2534 		log_errx(1, "configuration error; exiting");
2535 	if (debug > 0) {
2536 		oldconf->conf_debug = debug;
2537 		newconf->conf_debug = debug;
2538 	}
2539 
2540 	error = conf_apply(oldconf, newconf);
2541 	if (error != 0)
2542 		log_errx(1, "failed to apply configuration; exiting");
2543 
2544 	conf_delete(oldconf);
2545 	oldconf = NULL;
2546 
2547 	register_signals();
2548 
2549 	if (dont_daemonize == false) {
2550 		log_debugx("daemonizing");
2551 		if (daemon(0, 0) == -1) {
2552 			log_warn("cannot daemonize");
2553 			pidfile_remove(newconf->conf_pidfh);
2554 			exit(1);
2555 		}
2556 	}
2557 
2558 	/* Schedule iSNS update */
2559 	if (!TAILQ_EMPTY(&newconf->conf_isns))
2560 		set_timeout((newconf->conf_isns_period + 2) / 3, false);
2561 
2562 	for (;;) {
2563 		main_loop(newconf, dont_daemonize);
2564 		if (sighup_received) {
2565 			sighup_received = false;
2566 			log_debugx("received SIGHUP, reloading configuration");
2567 			tmpconf = conf_new_from_file(config_path, newconf);
2568 			if (tmpconf == NULL) {
2569 				log_warnx("configuration error, "
2570 				    "continuing with old configuration");
2571 			} else {
2572 				if (debug > 0)
2573 					tmpconf->conf_debug = debug;
2574 				oldconf = newconf;
2575 				newconf = tmpconf;
2576 				error = conf_apply(oldconf, newconf);
2577 				if (error != 0)
2578 					log_warnx("failed to reload "
2579 					    "configuration");
2580 				conf_delete(oldconf);
2581 				oldconf = NULL;
2582 			}
2583 		} else if (sigterm_received) {
2584 			log_debugx("exiting on signal; "
2585 			    "reloading empty configuration");
2586 
2587 			log_debugx("removing CTL iSCSI ports "
2588 			    "and terminating all connections");
2589 
2590 			oldconf = newconf;
2591 			newconf = conf_new();
2592 			if (debug > 0)
2593 				newconf->conf_debug = debug;
2594 			error = conf_apply(oldconf, newconf);
2595 			if (error != 0)
2596 				log_warnx("failed to apply configuration");
2597 			conf_delete(oldconf);
2598 			oldconf = NULL;
2599 
2600 			log_warnx("exiting on signal");
2601 			exit(0);
2602 		} else {
2603 			nchildren -= wait_for_children(false);
2604 			assert(nchildren >= 0);
2605 			if (timed_out()) {
2606 				set_timeout(0, false);
2607 				TAILQ_FOREACH(newns, &newconf->conf_isns, i_next)
2608 					isns_check(newns);
2609 				/* Schedule iSNS update */
2610 				if (!TAILQ_EMPTY(&newconf->conf_isns)) {
2611 					set_timeout((newconf->conf_isns_period
2612 					    + 2) / 3,
2613 					    false);
2614 				}
2615 			}
2616 		}
2617 	}
2618 	/* NOTREACHED */
2619 }
2620