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