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