xref: /freebsd/usr.sbin/ctld/ctld.c (revision 44a5953aa183aa8d3cc9514a1ef52a3e3bfe2856)
1 /*-
2  * Copyright (c) 2012 The FreeBSD Foundation
3  * All rights reserved.
4  *
5  * This software was developed by Edward Tomasz Napierala under sponsorship
6  * from the FreeBSD Foundation.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/types.h>
35 #include <sys/time.h>
36 #include <sys/socket.h>
37 #include <sys/wait.h>
38 #include <netinet/in.h>
39 #include <arpa/inet.h>
40 #include <assert.h>
41 #include <ctype.h>
42 #include <errno.h>
43 #include <netdb.h>
44 #include <signal.h>
45 #include <stdbool.h>
46 #include <stdio.h>
47 #include <stdint.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <unistd.h>
51 
52 #include "ctld.h"
53 
54 bool proxy_mode = false;
55 
56 static volatile bool sighup_received = false;
57 static volatile bool sigterm_received = false;
58 static volatile bool sigalrm_received = false;
59 
60 static int nchildren = 0;
61 
62 static void
63 usage(void)
64 {
65 
66 	fprintf(stderr, "usage: ctld [-d][-f config-file]\n");
67 	exit(1);
68 }
69 
70 char *
71 checked_strdup(const char *s)
72 {
73 	char *c;
74 
75 	c = strdup(s);
76 	if (c == NULL)
77 		log_err(1, "strdup");
78 	return (c);
79 }
80 
81 struct conf *
82 conf_new(void)
83 {
84 	struct conf *conf;
85 
86 	conf = calloc(1, sizeof(*conf));
87 	if (conf == NULL)
88 		log_err(1, "calloc");
89 	TAILQ_INIT(&conf->conf_targets);
90 	TAILQ_INIT(&conf->conf_auth_groups);
91 	TAILQ_INIT(&conf->conf_portal_groups);
92 
93 	conf->conf_debug = 0;
94 	conf->conf_timeout = 60;
95 	conf->conf_maxproc = 30;
96 
97 	return (conf);
98 }
99 
100 void
101 conf_delete(struct conf *conf)
102 {
103 	struct target *targ, *tmp;
104 	struct auth_group *ag, *cagtmp;
105 	struct portal_group *pg, *cpgtmp;
106 
107 	assert(conf->conf_pidfh == NULL);
108 
109 	TAILQ_FOREACH_SAFE(targ, &conf->conf_targets, t_next, tmp)
110 		target_delete(targ);
111 	TAILQ_FOREACH_SAFE(ag, &conf->conf_auth_groups, ag_next, cagtmp)
112 		auth_group_delete(ag);
113 	TAILQ_FOREACH_SAFE(pg, &conf->conf_portal_groups, pg_next, cpgtmp)
114 		portal_group_delete(pg);
115 	free(conf->conf_pidfile_path);
116 	free(conf);
117 }
118 
119 static struct auth *
120 auth_new(struct auth_group *ag)
121 {
122 	struct auth *auth;
123 
124 	auth = calloc(1, sizeof(*auth));
125 	if (auth == NULL)
126 		log_err(1, "calloc");
127 	auth->a_auth_group = ag;
128 	TAILQ_INSERT_TAIL(&ag->ag_auths, auth, a_next);
129 	return (auth);
130 }
131 
132 static void
133 auth_delete(struct auth *auth)
134 {
135 	TAILQ_REMOVE(&auth->a_auth_group->ag_auths, auth, a_next);
136 
137 	free(auth->a_user);
138 	free(auth->a_secret);
139 	free(auth->a_mutual_user);
140 	free(auth->a_mutual_secret);
141 	free(auth);
142 }
143 
144 const struct auth *
145 auth_find(const struct auth_group *ag, const char *user)
146 {
147 	const struct auth *auth;
148 
149 	TAILQ_FOREACH(auth, &ag->ag_auths, a_next) {
150 		if (strcmp(auth->a_user, user) == 0)
151 			return (auth);
152 	}
153 
154 	return (NULL);
155 }
156 
157 static void
158 auth_check_secret_length(struct auth *auth)
159 {
160 	size_t len;
161 
162 	len = strlen(auth->a_secret);
163 	if (len > 16) {
164 		if (auth->a_auth_group->ag_name != NULL)
165 			log_warnx("secret for user \"%s\", auth-group \"%s\", "
166 			    "is too long; it should be at most 16 characters "
167 			    "long", auth->a_user, auth->a_auth_group->ag_name);
168 		else
169 			log_warnx("secret for user \"%s\", target \"%s\", "
170 			    "is too long; it should be at most 16 characters "
171 			    "long", auth->a_user,
172 			    auth->a_auth_group->ag_target->t_name);
173 	}
174 	if (len < 12) {
175 		if (auth->a_auth_group->ag_name != NULL)
176 			log_warnx("secret for user \"%s\", auth-group \"%s\", "
177 			    "is too short; it should be at least 12 characters "
178 			    "long", auth->a_user,
179 			    auth->a_auth_group->ag_name);
180 		else
181 			log_warnx("secret for user \"%s\", target \"%s\", "
182 			    "is too short; it should be at least 16 characters "
183 			    "long", auth->a_user,
184 			    auth->a_auth_group->ag_target->t_name);
185 	}
186 
187 	if (auth->a_mutual_secret != NULL) {
188 		len = strlen(auth->a_secret);
189 		if (len > 16) {
190 			if (auth->a_auth_group->ag_name != NULL)
191 				log_warnx("mutual secret for user \"%s\", "
192 				    "auth-group \"%s\", is too long; it should "
193 				    "be at most 16 characters long",
194 				    auth->a_user, auth->a_auth_group->ag_name);
195 			else
196 				log_warnx("mutual secret for user \"%s\", "
197 				    "target \"%s\", is too long; it should "
198 				    "be at most 16 characters long",
199 				    auth->a_user,
200 				    auth->a_auth_group->ag_target->t_name);
201 		}
202 		if (len < 12) {
203 			if (auth->a_auth_group->ag_name != NULL)
204 				log_warnx("mutual secret for user \"%s\", "
205 				    "auth-group \"%s\", is too short; it "
206 				    "should be at least 12 characters long",
207 				    auth->a_user, auth->a_auth_group->ag_name);
208 			else
209 				log_warnx("mutual secret for user \"%s\", "
210 				    "target \"%s\", is too short; it should be "
211 				    "at least 16 characters long",
212 				    auth->a_user,
213 				    auth->a_auth_group->ag_target->t_name);
214 		}
215 	}
216 }
217 
218 const struct auth *
219 auth_new_chap(struct auth_group *ag, const char *user,
220     const char *secret)
221 {
222 	struct auth *auth;
223 
224 	if (ag->ag_type == AG_TYPE_UNKNOWN)
225 		ag->ag_type = AG_TYPE_CHAP;
226 	if (ag->ag_type != AG_TYPE_CHAP) {
227 		if (ag->ag_name != NULL)
228 			log_warnx("cannot mix \"chap\" authentication with "
229 			    "other types for auth-group \"%s\"", ag->ag_name);
230 		else
231 			log_warnx("cannot mix \"chap\" authentication with "
232 			    "other types for target \"%s\"",
233 			    ag->ag_target->t_name);
234 		return (NULL);
235 	}
236 
237 	auth = auth_new(ag);
238 	auth->a_user = checked_strdup(user);
239 	auth->a_secret = checked_strdup(secret);
240 
241 	auth_check_secret_length(auth);
242 
243 	return (auth);
244 }
245 
246 const struct auth *
247 auth_new_chap_mutual(struct auth_group *ag, const char *user,
248     const char *secret, const char *user2, const char *secret2)
249 {
250 	struct auth *auth;
251 
252 	if (ag->ag_type == AG_TYPE_UNKNOWN)
253 		ag->ag_type = AG_TYPE_CHAP_MUTUAL;
254 	if (ag->ag_type != AG_TYPE_CHAP_MUTUAL) {
255 		if (ag->ag_name != NULL)
256 			log_warnx("cannot mix \"chap-mutual\" authentication "
257 			    "with other types for auth-group \"%s\"",
258 			    ag->ag_name);
259 		else
260 			log_warnx("cannot mix \"chap-mutual\" authentication "
261 			    "with other types for target \"%s\"",
262 			    ag->ag_target->t_name);
263 		return (NULL);
264 	}
265 
266 	auth = auth_new(ag);
267 	auth->a_user = checked_strdup(user);
268 	auth->a_secret = checked_strdup(secret);
269 	auth->a_mutual_user = checked_strdup(user2);
270 	auth->a_mutual_secret = checked_strdup(secret2);
271 
272 	auth_check_secret_length(auth);
273 
274 	return (auth);
275 }
276 
277 const struct auth_name *
278 auth_name_new(struct auth_group *ag, const char *name)
279 {
280 	struct auth_name *an;
281 
282 	an = calloc(1, sizeof(*an));
283 	if (an == NULL)
284 		log_err(1, "calloc");
285 	an->an_auth_group = ag;
286 	an->an_initator_name = checked_strdup(name);
287 	TAILQ_INSERT_TAIL(&ag->ag_names, an, an_next);
288 	return (an);
289 }
290 
291 static void
292 auth_name_delete(struct auth_name *an)
293 {
294 	TAILQ_REMOVE(&an->an_auth_group->ag_names, an, an_next);
295 
296 	free(an->an_initator_name);
297 	free(an);
298 }
299 
300 bool
301 auth_name_defined(const struct auth_group *ag)
302 {
303 	if (TAILQ_EMPTY(&ag->ag_names))
304 		return (false);
305 	return (true);
306 }
307 
308 const struct auth_name *
309 auth_name_find(const struct auth_group *ag, const char *name)
310 {
311 	const struct auth_name *auth_name;
312 
313 	TAILQ_FOREACH(auth_name, &ag->ag_names, an_next) {
314 		if (strcmp(auth_name->an_initator_name, name) == 0)
315 			return (auth_name);
316 	}
317 
318 	return (NULL);
319 }
320 
321 const struct auth_portal *
322 auth_portal_new(struct auth_group *ag, const char *portal)
323 {
324 	struct auth_portal *ap;
325 	char *net, *mask, *str, *tmp;
326 	int len, dm, m;
327 
328 	ap = calloc(1, sizeof(*ap));
329 	if (ap == NULL)
330 		log_err(1, "calloc");
331 	ap->ap_auth_group = ag;
332 	ap->ap_initator_portal = checked_strdup(portal);
333 	mask = str = checked_strdup(portal);
334 	net = strsep(&mask, "/");
335 	if (net[0] == '[')
336 		net++;
337 	len = strlen(net);
338 	if (len == 0)
339 		goto error;
340 	if (net[len - 1] == ']')
341 		net[len - 1] = 0;
342 	if (strchr(net, ':') != NULL) {
343 		struct sockaddr_in6 *sin6 =
344 		    (struct sockaddr_in6 *)&ap->ap_sa;
345 
346 		sin6->sin6_len = sizeof(*sin6);
347 		sin6->sin6_family = AF_INET6;
348 		if (inet_pton(AF_INET6, net, &sin6->sin6_addr) <= 0)
349 			goto error;
350 		dm = 128;
351 	} else {
352 		struct sockaddr_in *sin =
353 		    (struct sockaddr_in *)&ap->ap_sa;
354 
355 		sin->sin_len = sizeof(*sin);
356 		sin->sin_family = AF_INET;
357 		if (inet_pton(AF_INET, net, &sin->sin_addr) <= 0)
358 			goto error;
359 		dm = 32;
360 	}
361 	if (mask != NULL) {
362 		m = strtol(mask, &tmp, 0);
363 		if (m < 0 || m > dm || tmp[0] != 0)
364 			goto error;
365 	} else
366 		m = dm;
367 	ap->ap_mask = m;
368 	free(str);
369 	TAILQ_INSERT_TAIL(&ag->ag_portals, ap, ap_next);
370 	return (ap);
371 
372 error:
373 	log_errx(1, "Incorrect initiator portal '%s'", portal);
374 	return (NULL);
375 }
376 
377 static void
378 auth_portal_delete(struct auth_portal *ap)
379 {
380 	TAILQ_REMOVE(&ap->ap_auth_group->ag_portals, ap, ap_next);
381 
382 	free(ap->ap_initator_portal);
383 	free(ap);
384 }
385 
386 bool
387 auth_portal_defined(const struct auth_group *ag)
388 {
389 	if (TAILQ_EMPTY(&ag->ag_portals))
390 		return (false);
391 	return (true);
392 }
393 
394 const struct auth_portal *
395 auth_portal_find(const struct auth_group *ag, const struct sockaddr_storage *ss)
396 {
397 	const struct auth_portal *ap;
398 	const uint8_t *a, *b;
399 	int i;
400 	uint8_t bmask;
401 
402 	TAILQ_FOREACH(ap, &ag->ag_portals, ap_next) {
403 		if (ap->ap_sa.ss_family != ss->ss_family)
404 			continue;
405 		if (ss->ss_family == AF_INET) {
406 			a = (const uint8_t *)
407 			    &((const struct sockaddr_in *)ss)->sin_addr;
408 			b = (const uint8_t *)
409 			    &((const struct sockaddr_in *)&ap->ap_sa)->sin_addr;
410 		} else {
411 			a = (const uint8_t *)
412 			    &((const struct sockaddr_in6 *)ss)->sin6_addr;
413 			b = (const uint8_t *)
414 			    &((const struct sockaddr_in6 *)&ap->ap_sa)->sin6_addr;
415 		}
416 		for (i = 0; i < ap->ap_mask / 8; i++) {
417 			if (a[i] != b[i])
418 				goto next;
419 		}
420 		if (ap->ap_mask % 8) {
421 			bmask = 0xff << (8 - (ap->ap_mask % 8));
422 			if ((a[i] & bmask) != (b[i] & bmask))
423 				goto next;
424 		}
425 		return (ap);
426 next:
427 		;
428 	}
429 
430 	return (NULL);
431 }
432 
433 struct auth_group *
434 auth_group_new(struct conf *conf, const char *name)
435 {
436 	struct auth_group *ag;
437 
438 	if (name != NULL) {
439 		ag = auth_group_find(conf, name);
440 		if (ag != NULL) {
441 			log_warnx("duplicated auth-group \"%s\"", name);
442 			return (NULL);
443 		}
444 	}
445 
446 	ag = calloc(1, sizeof(*ag));
447 	if (ag == NULL)
448 		log_err(1, "calloc");
449 	if (name != NULL)
450 		ag->ag_name = checked_strdup(name);
451 	TAILQ_INIT(&ag->ag_auths);
452 	TAILQ_INIT(&ag->ag_names);
453 	TAILQ_INIT(&ag->ag_portals);
454 	ag->ag_conf = conf;
455 	TAILQ_INSERT_TAIL(&conf->conf_auth_groups, ag, ag_next);
456 
457 	return (ag);
458 }
459 
460 void
461 auth_group_delete(struct auth_group *ag)
462 {
463 	struct auth *auth, *auth_tmp;
464 	struct auth_name *auth_name, *auth_name_tmp;
465 	struct auth_portal *auth_portal, *auth_portal_tmp;
466 
467 	TAILQ_REMOVE(&ag->ag_conf->conf_auth_groups, ag, ag_next);
468 
469 	TAILQ_FOREACH_SAFE(auth, &ag->ag_auths, a_next, auth_tmp)
470 		auth_delete(auth);
471 	TAILQ_FOREACH_SAFE(auth_name, &ag->ag_names, an_next, auth_name_tmp)
472 		auth_name_delete(auth_name);
473 	TAILQ_FOREACH_SAFE(auth_portal, &ag->ag_portals, ap_next,
474 	    auth_portal_tmp)
475 		auth_portal_delete(auth_portal);
476 	free(ag->ag_name);
477 	free(ag);
478 }
479 
480 struct auth_group *
481 auth_group_find(const struct conf *conf, const char *name)
482 {
483 	struct auth_group *ag;
484 
485 	TAILQ_FOREACH(ag, &conf->conf_auth_groups, ag_next) {
486 		if (ag->ag_name != NULL && strcmp(ag->ag_name, name) == 0)
487 			return (ag);
488 	}
489 
490 	return (NULL);
491 }
492 
493 static int
494 auth_group_set_type(struct auth_group *ag, int type)
495 {
496 
497 	if (ag->ag_type == AG_TYPE_UNKNOWN) {
498 		ag->ag_type = type;
499 		return (0);
500 	}
501 
502 	if (ag->ag_type == type)
503 		return (0);
504 
505 	return (1);
506 }
507 
508 int
509 auth_group_set_type_str(struct auth_group *ag, const char *str)
510 {
511 	int error, type;
512 
513 	if (strcmp(str, "none") == 0) {
514 		type = AG_TYPE_NO_AUTHENTICATION;
515 	} else if (strcmp(str, "deny") == 0) {
516 		type = AG_TYPE_DENY;
517 	} else if (strcmp(str, "chap") == 0) {
518 		type = AG_TYPE_CHAP;
519 	} else if (strcmp(str, "chap-mutual") == 0) {
520 		type = AG_TYPE_CHAP_MUTUAL;
521 	} else {
522 		if (ag->ag_name != NULL)
523 			log_warnx("invalid auth-type \"%s\" for auth-group "
524 			    "\"%s\"", str, ag->ag_name);
525 		else
526 			log_warnx("invalid auth-type \"%s\" for target "
527 			    "\"%s\"", str, ag->ag_target->t_name);
528 		return (1);
529 	}
530 
531 	error = auth_group_set_type(ag, type);
532 	if (error != 0) {
533 		if (ag->ag_name != NULL)
534 			log_warnx("cannot set auth-type to \"%s\" for "
535 			    "auth-group \"%s\"; already has a different "
536 			    "type", str, ag->ag_name);
537 		else
538 			log_warnx("cannot set auth-type to \"%s\" for target "
539 			    "\"%s\"; already has a different type",
540 			    str, ag->ag_target->t_name);
541 		return (1);
542 	}
543 
544 	return (error);
545 }
546 
547 static struct portal *
548 portal_new(struct portal_group *pg)
549 {
550 	struct portal *portal;
551 
552 	portal = calloc(1, sizeof(*portal));
553 	if (portal == NULL)
554 		log_err(1, "calloc");
555 	TAILQ_INIT(&portal->p_targets);
556 	portal->p_portal_group = pg;
557 	TAILQ_INSERT_TAIL(&pg->pg_portals, portal, p_next);
558 	return (portal);
559 }
560 
561 static void
562 portal_delete(struct portal *portal)
563 {
564 
565 	TAILQ_REMOVE(&portal->p_portal_group->pg_portals, portal, p_next);
566 	if (portal->p_ai != NULL)
567 		freeaddrinfo(portal->p_ai);
568 	free(portal->p_listen);
569 	free(portal);
570 }
571 
572 struct portal_group *
573 portal_group_new(struct conf *conf, const char *name)
574 {
575 	struct portal_group *pg;
576 
577 	pg = portal_group_find(conf, name);
578 	if (pg != NULL) {
579 		log_warnx("duplicated portal-group \"%s\"", name);
580 		return (NULL);
581 	}
582 
583 	pg = calloc(1, sizeof(*pg));
584 	if (pg == NULL)
585 		log_err(1, "calloc");
586 	pg->pg_name = checked_strdup(name);
587 	TAILQ_INIT(&pg->pg_portals);
588 	pg->pg_conf = conf;
589 	conf->conf_last_portal_group_tag++;
590 	pg->pg_tag = conf->conf_last_portal_group_tag;
591 	TAILQ_INSERT_TAIL(&conf->conf_portal_groups, pg, pg_next);
592 
593 	return (pg);
594 }
595 
596 void
597 portal_group_delete(struct portal_group *pg)
598 {
599 	struct portal *portal, *tmp;
600 
601 	TAILQ_REMOVE(&pg->pg_conf->conf_portal_groups, pg, pg_next);
602 
603 	TAILQ_FOREACH_SAFE(portal, &pg->pg_portals, p_next, tmp)
604 		portal_delete(portal);
605 	free(pg->pg_name);
606 	free(pg);
607 }
608 
609 struct portal_group *
610 portal_group_find(const struct conf *conf, const char *name)
611 {
612 	struct portal_group *pg;
613 
614 	TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
615 		if (strcmp(pg->pg_name, name) == 0)
616 			return (pg);
617 	}
618 
619 	return (NULL);
620 }
621 
622 int
623 portal_group_add_listen(struct portal_group *pg, const char *value, bool iser)
624 {
625 	struct addrinfo hints;
626 	struct portal *portal;
627 	char *addr, *ch, *arg;
628 	const char *port;
629 	int error, colons = 0;
630 
631 	portal = portal_new(pg);
632 	portal->p_listen = checked_strdup(value);
633 	portal->p_iser = iser;
634 
635 	arg = portal->p_listen;
636 	if (arg[0] == '\0') {
637 		log_warnx("empty listen address");
638 		portal_delete(portal);
639 		return (1);
640 	}
641 	if (arg[0] == '[') {
642 		/*
643 		 * IPv6 address in square brackets, perhaps with port.
644 		 */
645 		arg++;
646 		addr = strsep(&arg, "]");
647 		if (arg == NULL) {
648 			log_warnx("invalid listen address %s",
649 			    portal->p_listen);
650 			portal_delete(portal);
651 			return (1);
652 		}
653 		if (arg[0] == '\0') {
654 			port = "3260";
655 		} else if (arg[0] == ':') {
656 			port = arg + 1;
657 		} else {
658 			log_warnx("invalid listen address %s",
659 			    portal->p_listen);
660 			portal_delete(portal);
661 			return (1);
662 		}
663 	} else {
664 		/*
665 		 * Either IPv6 address without brackets - and without
666 		 * a port - or IPv4 address.  Just count the colons.
667 		 */
668 		for (ch = arg; *ch != '\0'; ch++) {
669 			if (*ch == ':')
670 				colons++;
671 		}
672 		if (colons > 1) {
673 			addr = arg;
674 			port = "3260";
675 		} else {
676 			addr = strsep(&arg, ":");
677 			if (arg == NULL)
678 				port = "3260";
679 			else
680 				port = arg;
681 		}
682 	}
683 
684 	memset(&hints, 0, sizeof(hints));
685 	hints.ai_family = PF_UNSPEC;
686 	hints.ai_socktype = SOCK_STREAM;
687 	hints.ai_flags = AI_PASSIVE;
688 
689 	error = getaddrinfo(addr, port, &hints, &portal->p_ai);
690 	if (error != 0) {
691 		log_warnx("getaddrinfo for %s failed: %s",
692 		    portal->p_listen, gai_strerror(error));
693 		portal_delete(portal);
694 		return (1);
695 	}
696 
697 	/*
698 	 * XXX: getaddrinfo(3) may return multiple addresses; we should turn
699 	 *	those into multiple portals.
700 	 */
701 
702 	return (0);
703 }
704 
705 static bool
706 valid_hex(const char ch)
707 {
708 	switch (ch) {
709 	case '0':
710 	case '1':
711 	case '2':
712 	case '3':
713 	case '4':
714 	case '5':
715 	case '6':
716 	case '7':
717 	case '8':
718 	case '9':
719 	case 'a':
720 	case 'A':
721 	case 'b':
722 	case 'B':
723 	case 'c':
724 	case 'C':
725 	case 'd':
726 	case 'D':
727 	case 'e':
728 	case 'E':
729 	case 'f':
730 	case 'F':
731 		return (true);
732 	default:
733 		return (false);
734 	}
735 }
736 
737 bool
738 valid_iscsi_name(const char *name)
739 {
740 	int i;
741 
742 	if (strlen(name) >= MAX_NAME_LEN) {
743 		log_warnx("overlong name for target \"%s\"; max length allowed "
744 		    "by iSCSI specification is %d characters",
745 		    name, MAX_NAME_LEN);
746 		return (false);
747 	}
748 
749 	/*
750 	 * In the cases below, we don't return an error, just in case the admin
751 	 * was right, and we're wrong.
752 	 */
753 	if (strncasecmp(name, "iqn.", strlen("iqn.")) == 0) {
754 		for (i = strlen("iqn."); name[i] != '\0'; i++) {
755 			/*
756 			 * XXX: We should verify UTF-8 normalisation, as defined
757 			 * 	by 3.2.6.2: iSCSI Name Encoding.
758 			 */
759 			if (isalnum(name[i]))
760 				continue;
761 			if (name[i] == '-' || name[i] == '.' || name[i] == ':')
762 				continue;
763 			log_warnx("invalid character \"%c\" in target name "
764 			    "\"%s\"; allowed characters are letters, digits, "
765 			    "'-', '.', and ':'", name[i], name);
766 			break;
767 		}
768 		/*
769 		 * XXX: Check more stuff: valid date and a valid reversed domain.
770 		 */
771 	} else if (strncasecmp(name, "eui.", strlen("eui.")) == 0) {
772 		if (strlen(name) != strlen("eui.") + 16)
773 			log_warnx("invalid target name \"%s\"; the \"eui.\" "
774 			    "should be followed by exactly 16 hexadecimal "
775 			    "digits", name);
776 		for (i = strlen("eui."); name[i] != '\0'; i++) {
777 			if (!valid_hex(name[i])) {
778 				log_warnx("invalid character \"%c\" in target "
779 				    "name \"%s\"; allowed characters are 1-9 "
780 				    "and A-F", name[i], name);
781 				break;
782 			}
783 		}
784 	} else if (strncasecmp(name, "naa.", strlen("naa.")) == 0) {
785 		if (strlen(name) > strlen("naa.") + 32)
786 			log_warnx("invalid target name \"%s\"; the \"naa.\" "
787 			    "should be followed by at most 32 hexadecimal "
788 			    "digits", name);
789 		for (i = strlen("naa."); name[i] != '\0'; i++) {
790 			if (!valid_hex(name[i])) {
791 				log_warnx("invalid character \"%c\" in target "
792 				    "name \"%s\"; allowed characters are 1-9 "
793 				    "and A-F", name[i], name);
794 				break;
795 			}
796 		}
797 	} else {
798 		log_warnx("invalid target name \"%s\"; should start with "
799 		    "either \".iqn\", \"eui.\", or \"naa.\"",
800 		    name);
801 	}
802 	return (true);
803 }
804 
805 struct target *
806 target_new(struct conf *conf, const char *name)
807 {
808 	struct target *targ;
809 	int i, len;
810 
811 	targ = target_find(conf, name);
812 	if (targ != NULL) {
813 		log_warnx("duplicated target \"%s\"", name);
814 		return (NULL);
815 	}
816 	if (valid_iscsi_name(name) == false) {
817 		log_warnx("target name \"%s\" is invalid", name);
818 		return (NULL);
819 	}
820 	targ = calloc(1, sizeof(*targ));
821 	if (targ == NULL)
822 		log_err(1, "calloc");
823 	targ->t_name = checked_strdup(name);
824 
825 	/*
826 	 * RFC 3722 requires us to normalize the name to lowercase.
827 	 */
828 	len = strlen(name);
829 	for (i = 0; i < len; i++)
830 		targ->t_name[i] = tolower(targ->t_name[i]);
831 
832 	TAILQ_INIT(&targ->t_luns);
833 	targ->t_conf = conf;
834 	TAILQ_INSERT_TAIL(&conf->conf_targets, targ, t_next);
835 
836 	return (targ);
837 }
838 
839 void
840 target_delete(struct target *targ)
841 {
842 	struct lun *lun, *tmp;
843 
844 	TAILQ_REMOVE(&targ->t_conf->conf_targets, targ, t_next);
845 
846 	TAILQ_FOREACH_SAFE(lun, &targ->t_luns, l_next, tmp)
847 		lun_delete(lun);
848 	free(targ->t_name);
849 	free(targ);
850 }
851 
852 struct target *
853 target_find(struct conf *conf, const char *name)
854 {
855 	struct target *targ;
856 
857 	TAILQ_FOREACH(targ, &conf->conf_targets, t_next) {
858 		if (strcasecmp(targ->t_name, name) == 0)
859 			return (targ);
860 	}
861 
862 	return (NULL);
863 }
864 
865 struct lun *
866 lun_new(struct target *targ, int lun_id)
867 {
868 	struct lun *lun;
869 
870 	lun = lun_find(targ, lun_id);
871 	if (lun != NULL) {
872 		log_warnx("duplicated lun %d for target \"%s\"",
873 		    lun_id, targ->t_name);
874 		return (NULL);
875 	}
876 
877 	lun = calloc(1, sizeof(*lun));
878 	if (lun == NULL)
879 		log_err(1, "calloc");
880 	lun->l_lun = lun_id;
881 	TAILQ_INIT(&lun->l_options);
882 	lun->l_target = targ;
883 	TAILQ_INSERT_TAIL(&targ->t_luns, lun, l_next);
884 
885 	return (lun);
886 }
887 
888 void
889 lun_delete(struct lun *lun)
890 {
891 	struct lun_option *lo, *tmp;
892 
893 	TAILQ_REMOVE(&lun->l_target->t_luns, lun, l_next);
894 
895 	TAILQ_FOREACH_SAFE(lo, &lun->l_options, lo_next, tmp)
896 		lun_option_delete(lo);
897 	free(lun->l_backend);
898 	free(lun->l_device_id);
899 	free(lun->l_path);
900 	free(lun->l_serial);
901 	free(lun);
902 }
903 
904 struct lun *
905 lun_find(const struct target *targ, int lun_id)
906 {
907 	struct lun *lun;
908 
909 	TAILQ_FOREACH(lun, &targ->t_luns, l_next) {
910 		if (lun->l_lun == lun_id)
911 			return (lun);
912 	}
913 
914 	return (NULL);
915 }
916 
917 void
918 lun_set_backend(struct lun *lun, const char *value)
919 {
920 	free(lun->l_backend);
921 	lun->l_backend = checked_strdup(value);
922 }
923 
924 void
925 lun_set_blocksize(struct lun *lun, size_t value)
926 {
927 
928 	lun->l_blocksize = value;
929 }
930 
931 void
932 lun_set_device_id(struct lun *lun, const char *value)
933 {
934 	free(lun->l_device_id);
935 	lun->l_device_id = checked_strdup(value);
936 }
937 
938 void
939 lun_set_path(struct lun *lun, const char *value)
940 {
941 	free(lun->l_path);
942 	lun->l_path = checked_strdup(value);
943 }
944 
945 void
946 lun_set_serial(struct lun *lun, const char *value)
947 {
948 	free(lun->l_serial);
949 	lun->l_serial = checked_strdup(value);
950 }
951 
952 void
953 lun_set_size(struct lun *lun, size_t value)
954 {
955 
956 	lun->l_size = value;
957 }
958 
959 void
960 lun_set_ctl_lun(struct lun *lun, uint32_t value)
961 {
962 
963 	lun->l_ctl_lun = value;
964 }
965 
966 struct lun_option *
967 lun_option_new(struct lun *lun, const char *name, const char *value)
968 {
969 	struct lun_option *lo;
970 
971 	lo = lun_option_find(lun, name);
972 	if (lo != NULL) {
973 		log_warnx("duplicated lun option %s for lun %d, target \"%s\"",
974 		    name, lun->l_lun, lun->l_target->t_name);
975 		return (NULL);
976 	}
977 
978 	lo = calloc(1, sizeof(*lo));
979 	if (lo == NULL)
980 		log_err(1, "calloc");
981 	lo->lo_name = checked_strdup(name);
982 	lo->lo_value = checked_strdup(value);
983 	lo->lo_lun = lun;
984 	TAILQ_INSERT_TAIL(&lun->l_options, lo, lo_next);
985 
986 	return (lo);
987 }
988 
989 void
990 lun_option_delete(struct lun_option *lo)
991 {
992 
993 	TAILQ_REMOVE(&lo->lo_lun->l_options, lo, lo_next);
994 
995 	free(lo->lo_name);
996 	free(lo->lo_value);
997 	free(lo);
998 }
999 
1000 struct lun_option *
1001 lun_option_find(const struct lun *lun, const char *name)
1002 {
1003 	struct lun_option *lo;
1004 
1005 	TAILQ_FOREACH(lo, &lun->l_options, lo_next) {
1006 		if (strcmp(lo->lo_name, name) == 0)
1007 			return (lo);
1008 	}
1009 
1010 	return (NULL);
1011 }
1012 
1013 void
1014 lun_option_set(struct lun_option *lo, const char *value)
1015 {
1016 
1017 	free(lo->lo_value);
1018 	lo->lo_value = checked_strdup(value);
1019 }
1020 
1021 static struct connection *
1022 connection_new(struct portal *portal, int fd, const char *host,
1023     const struct sockaddr *client_sa)
1024 {
1025 	struct connection *conn;
1026 
1027 	conn = calloc(1, sizeof(*conn));
1028 	if (conn == NULL)
1029 		log_err(1, "calloc");
1030 	conn->conn_portal = portal;
1031 	conn->conn_socket = fd;
1032 	conn->conn_initiator_addr = checked_strdup(host);
1033 	memcpy(&conn->conn_initiator_sa, client_sa, client_sa->sa_len);
1034 
1035 	/*
1036 	 * Default values, from RFC 3720, section 12.
1037 	 */
1038 	conn->conn_max_data_segment_length = 8192;
1039 	conn->conn_max_burst_length = 262144;
1040 	conn->conn_immediate_data = true;
1041 
1042 	return (conn);
1043 }
1044 
1045 #if 0
1046 static void
1047 conf_print(struct conf *conf)
1048 {
1049 	struct auth_group *ag;
1050 	struct auth *auth;
1051 	struct auth_name *auth_name;
1052 	struct auth_portal *auth_portal;
1053 	struct portal_group *pg;
1054 	struct portal *portal;
1055 	struct target *targ;
1056 	struct lun *lun;
1057 	struct lun_option *lo;
1058 
1059 	TAILQ_FOREACH(ag, &conf->conf_auth_groups, ag_next) {
1060 		fprintf(stderr, "auth-group %s {\n", ag->ag_name);
1061 		TAILQ_FOREACH(auth, &ag->ag_auths, a_next)
1062 			fprintf(stderr, "\t chap-mutual %s %s %s %s\n",
1063 			    auth->a_user, auth->a_secret,
1064 			    auth->a_mutual_user, auth->a_mutual_secret);
1065 		TAILQ_FOREACH(auth_name, &ag->ag_names, an_next)
1066 			fprintf(stderr, "\t initiator-name %s\n",
1067 			    auth_name->an_initator_name);
1068 		TAILQ_FOREACH(auth_portal, &ag->ag_portals, an_next)
1069 			fprintf(stderr, "\t initiator-portal %s\n",
1070 			    auth_portal->an_initator_portal);
1071 		fprintf(stderr, "}\n");
1072 	}
1073 	TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
1074 		fprintf(stderr, "portal-group %s {\n", pg->pg_name);
1075 		TAILQ_FOREACH(portal, &pg->pg_portals, p_next)
1076 			fprintf(stderr, "\t listen %s\n", portal->p_listen);
1077 		fprintf(stderr, "}\n");
1078 	}
1079 	TAILQ_FOREACH(targ, &conf->conf_targets, t_next) {
1080 		fprintf(stderr, "target %s {\n", targ->t_name);
1081 		if (targ->t_alias != NULL)
1082 			fprintf(stderr, "\t alias %s\n", targ->t_alias);
1083 		TAILQ_FOREACH(lun, &targ->t_luns, l_next) {
1084 			fprintf(stderr, "\tlun %d {\n", lun->l_lun);
1085 			fprintf(stderr, "\t\tpath %s\n", lun->l_path);
1086 			TAILQ_FOREACH(lo, &lun->l_options, lo_next)
1087 				fprintf(stderr, "\t\toption %s %s\n",
1088 				    lo->lo_name, lo->lo_value);
1089 			fprintf(stderr, "\t}\n");
1090 		}
1091 		fprintf(stderr, "}\n");
1092 	}
1093 }
1094 #endif
1095 
1096 static int
1097 conf_verify_lun(struct lun *lun)
1098 {
1099 	const struct lun *lun2;
1100 	const struct target *targ2;
1101 
1102 	if (lun->l_backend == NULL)
1103 		lun_set_backend(lun, "block");
1104 	if (strcmp(lun->l_backend, "block") == 0) {
1105 		if (lun->l_path == NULL) {
1106 			log_warnx("missing path for lun %d, target \"%s\"",
1107 			    lun->l_lun, lun->l_target->t_name);
1108 			return (1);
1109 		}
1110 	} else if (strcmp(lun->l_backend, "ramdisk") == 0) {
1111 		if (lun->l_size == 0) {
1112 			log_warnx("missing size for ramdisk-backed lun %d, "
1113 			    "target \"%s\"", lun->l_lun, lun->l_target->t_name);
1114 			return (1);
1115 		}
1116 		if (lun->l_path != NULL) {
1117 			log_warnx("path must not be specified "
1118 			    "for ramdisk-backed lun %d, target \"%s\"",
1119 			    lun->l_lun, lun->l_target->t_name);
1120 			return (1);
1121 		}
1122 	}
1123 	if (lun->l_lun < 0 || lun->l_lun > 255) {
1124 		log_warnx("invalid lun number for lun %d, target \"%s\"; "
1125 		    "must be between 0 and 255", lun->l_lun,
1126 		    lun->l_target->t_name);
1127 		return (1);
1128 	}
1129 	if (lun->l_blocksize == 0) {
1130 		lun_set_blocksize(lun, DEFAULT_BLOCKSIZE);
1131 	} else if (lun->l_blocksize < 0) {
1132 		log_warnx("invalid blocksize for lun %d, target \"%s\"; "
1133 		    "must be larger than 0", lun->l_lun, lun->l_target->t_name);
1134 		return (1);
1135 	}
1136 	if (lun->l_size != 0 && lun->l_size % lun->l_blocksize != 0) {
1137 		log_warnx("invalid size for lun %d, target \"%s\"; "
1138 		    "must be multiple of blocksize", lun->l_lun,
1139 		    lun->l_target->t_name);
1140 		return (1);
1141 	}
1142 	TAILQ_FOREACH(targ2, &lun->l_target->t_conf->conf_targets, t_next) {
1143 		TAILQ_FOREACH(lun2, &targ2->t_luns, l_next) {
1144 			if (lun == lun2)
1145 				continue;
1146 			if (lun->l_path != NULL && lun2->l_path != NULL &&
1147 			    strcmp(lun->l_path, lun2->l_path) == 0) {
1148 				log_debugx("WARNING: path \"%s\" duplicated "
1149 				    "between lun %d, target \"%s\", and "
1150 				    "lun %d, target \"%s\"", lun->l_path,
1151 				    lun->l_lun, lun->l_target->t_name,
1152 				    lun2->l_lun, lun2->l_target->t_name);
1153 			}
1154 		}
1155 	}
1156 
1157 	return (0);
1158 }
1159 
1160 int
1161 conf_verify(struct conf *conf)
1162 {
1163 	struct auth_group *ag;
1164 	struct portal_group *pg;
1165 	struct target *targ;
1166 	struct lun *lun;
1167 	bool found_lun;
1168 	int error;
1169 
1170 	if (conf->conf_pidfile_path == NULL)
1171 		conf->conf_pidfile_path = checked_strdup(DEFAULT_PIDFILE);
1172 
1173 	TAILQ_FOREACH(targ, &conf->conf_targets, t_next) {
1174 		if (targ->t_auth_group == NULL) {
1175 			targ->t_auth_group = auth_group_find(conf,
1176 			    "default");
1177 			assert(targ->t_auth_group != NULL);
1178 		}
1179 		if (targ->t_portal_group == NULL) {
1180 			targ->t_portal_group = portal_group_find(conf,
1181 			    "default");
1182 			assert(targ->t_portal_group != NULL);
1183 		}
1184 		found_lun = false;
1185 		TAILQ_FOREACH(lun, &targ->t_luns, l_next) {
1186 			error = conf_verify_lun(lun);
1187 			if (error != 0)
1188 				return (error);
1189 			found_lun = true;
1190 		}
1191 		if (!found_lun) {
1192 			log_warnx("no LUNs defined for target \"%s\"",
1193 			    targ->t_name);
1194 		}
1195 	}
1196 	TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
1197 		assert(pg->pg_name != NULL);
1198 		if (pg->pg_discovery_auth_group == NULL) {
1199 			pg->pg_discovery_auth_group =
1200 			    auth_group_find(conf, "default");
1201 			assert(pg->pg_discovery_auth_group != NULL);
1202 		}
1203 
1204 		TAILQ_FOREACH(targ, &conf->conf_targets, t_next) {
1205 			if (targ->t_portal_group == pg)
1206 				break;
1207 		}
1208 		if (targ == NULL) {
1209 			if (strcmp(pg->pg_name, "default") != 0)
1210 				log_warnx("portal-group \"%s\" not assigned "
1211 				    "to any target", pg->pg_name);
1212 			pg->pg_unassigned = true;
1213 		} else
1214 			pg->pg_unassigned = false;
1215 	}
1216 	TAILQ_FOREACH(ag, &conf->conf_auth_groups, ag_next) {
1217 		if (ag->ag_name == NULL)
1218 			assert(ag->ag_target != NULL);
1219 		else
1220 			assert(ag->ag_target == NULL);
1221 
1222 		TAILQ_FOREACH(targ, &conf->conf_targets, t_next) {
1223 			if (targ->t_auth_group == ag)
1224 				break;
1225 		}
1226 		if (targ == NULL && ag->ag_name != NULL &&
1227 		    strcmp(ag->ag_name, "default") != 0 &&
1228 		    strcmp(ag->ag_name, "no-authentication") != 0 &&
1229 		    strcmp(ag->ag_name, "no-access") != 0) {
1230 			log_warnx("auth-group \"%s\" not assigned "
1231 			    "to any target", ag->ag_name);
1232 		}
1233 	}
1234 
1235 	return (0);
1236 }
1237 
1238 static int
1239 conf_apply(struct conf *oldconf, struct conf *newconf)
1240 {
1241 	struct target *oldtarg, *newtarg, *tmptarg;
1242 	struct lun *oldlun, *newlun, *tmplun;
1243 	struct portal_group *oldpg, *newpg;
1244 	struct portal *oldp, *newp;
1245 	pid_t otherpid;
1246 	int changed, cumulated_error = 0, error;
1247 	int one = 1;
1248 
1249 	if (oldconf->conf_debug != newconf->conf_debug) {
1250 		log_debugx("changing debug level to %d", newconf->conf_debug);
1251 		log_init(newconf->conf_debug);
1252 	}
1253 
1254 	if (oldconf->conf_pidfh != NULL) {
1255 		assert(oldconf->conf_pidfile_path != NULL);
1256 		if (newconf->conf_pidfile_path != NULL &&
1257 		    strcmp(oldconf->conf_pidfile_path,
1258 		    newconf->conf_pidfile_path) == 0) {
1259 			newconf->conf_pidfh = oldconf->conf_pidfh;
1260 			oldconf->conf_pidfh = NULL;
1261 		} else {
1262 			log_debugx("removing pidfile %s",
1263 			    oldconf->conf_pidfile_path);
1264 			pidfile_remove(oldconf->conf_pidfh);
1265 			oldconf->conf_pidfh = NULL;
1266 		}
1267 	}
1268 
1269 	if (newconf->conf_pidfh == NULL && newconf->conf_pidfile_path != NULL) {
1270 		log_debugx("opening pidfile %s", newconf->conf_pidfile_path);
1271 		newconf->conf_pidfh =
1272 		    pidfile_open(newconf->conf_pidfile_path, 0600, &otherpid);
1273 		if (newconf->conf_pidfh == NULL) {
1274 			if (errno == EEXIST)
1275 				log_errx(1, "daemon already running, pid: %jd.",
1276 				    (intmax_t)otherpid);
1277 			log_err(1, "cannot open or create pidfile \"%s\"",
1278 			    newconf->conf_pidfile_path);
1279 		}
1280 	}
1281 
1282 	/*
1283 	 * XXX: If target or lun removal fails, we should somehow "move"
1284 	 * 	the old lun or target into newconf, so that subsequent
1285 	 * 	conf_apply() would try to remove them again.  That would
1286 	 * 	be somewhat hairy, though, and lun deletion failures don't
1287 	 * 	really happen, so leave it as it is for now.
1288 	 */
1289 	TAILQ_FOREACH_SAFE(oldtarg, &oldconf->conf_targets, t_next, tmptarg) {
1290 		/*
1291 		 * First, remove any targets present in the old configuration
1292 		 * and missing in the new one.
1293 		 */
1294 		newtarg = target_find(newconf, oldtarg->t_name);
1295 		if (newtarg == NULL) {
1296 			TAILQ_FOREACH_SAFE(oldlun, &oldtarg->t_luns, l_next,
1297 			    tmplun) {
1298 				log_debugx("target %s not found in new "
1299 				    "configuration; removing its lun %d, "
1300 				    "backed by CTL lun %d",
1301 				    oldtarg->t_name, oldlun->l_lun,
1302 				    oldlun->l_ctl_lun);
1303 				error = kernel_lun_remove(oldlun);
1304 				if (error != 0) {
1305 					log_warnx("failed to remove lun %d, "
1306 					    "target %s, CTL lun %d",
1307 					    oldlun->l_lun, oldtarg->t_name,
1308 					    oldlun->l_ctl_lun);
1309 					cumulated_error++;
1310 				}
1311 				lun_delete(oldlun);
1312 			}
1313 			kernel_port_remove(oldtarg);
1314 			target_delete(oldtarg);
1315 			continue;
1316 		}
1317 
1318 		/*
1319 		 * Second, remove any LUNs present in the old target
1320 		 * and missing in the new one.
1321 		 */
1322 		TAILQ_FOREACH_SAFE(oldlun, &oldtarg->t_luns, l_next, tmplun) {
1323 			newlun = lun_find(newtarg, oldlun->l_lun);
1324 			if (newlun == NULL) {
1325 				log_debugx("lun %d, target %s, CTL lun %d "
1326 				    "not found in new configuration; "
1327 				    "removing", oldlun->l_lun, oldtarg->t_name,
1328 				    oldlun->l_ctl_lun);
1329 				error = kernel_lun_remove(oldlun);
1330 				if (error != 0) {
1331 					log_warnx("failed to remove lun %d, "
1332 					    "target %s, CTL lun %d",
1333 					    oldlun->l_lun, oldtarg->t_name,
1334 					    oldlun->l_ctl_lun);
1335 					cumulated_error++;
1336 				}
1337 				lun_delete(oldlun);
1338 				continue;
1339 			}
1340 
1341 			/*
1342 			 * Also remove the LUNs changed by more than size.
1343 			 */
1344 			changed = 0;
1345 			assert(oldlun->l_backend != NULL);
1346 			assert(newlun->l_backend != NULL);
1347 			if (strcmp(newlun->l_backend, oldlun->l_backend) != 0) {
1348 				log_debugx("backend for lun %d, target %s, "
1349 				    "CTL lun %d changed; removing",
1350 				    oldlun->l_lun, oldtarg->t_name,
1351 				    oldlun->l_ctl_lun);
1352 				changed = 1;
1353 			}
1354 			if (oldlun->l_blocksize != newlun->l_blocksize) {
1355 				log_debugx("blocksize for lun %d, target %s, "
1356 				    "CTL lun %d changed; removing",
1357 				    oldlun->l_lun, oldtarg->t_name,
1358 				    oldlun->l_ctl_lun);
1359 				changed = 1;
1360 			}
1361 			if (newlun->l_device_id != NULL &&
1362 			    (oldlun->l_device_id == NULL ||
1363 			     strcmp(oldlun->l_device_id, newlun->l_device_id) !=
1364 			     0)) {
1365 				log_debugx("device-id for lun %d, target %s, "
1366 				    "CTL lun %d changed; removing",
1367 				    oldlun->l_lun, oldtarg->t_name,
1368 				    oldlun->l_ctl_lun);
1369 				changed = 1;
1370 			}
1371 			if (newlun->l_path != NULL &&
1372 			    (oldlun->l_path == NULL ||
1373 			     strcmp(oldlun->l_path, newlun->l_path) != 0)) {
1374 				log_debugx("path for lun %d, target %s, "
1375 				    "CTL lun %d, changed; removing",
1376 				    oldlun->l_lun, oldtarg->t_name,
1377 				    oldlun->l_ctl_lun);
1378 				changed = 1;
1379 			}
1380 			if (newlun->l_serial != NULL &&
1381 			    (oldlun->l_serial == NULL ||
1382 			     strcmp(oldlun->l_serial, newlun->l_serial) != 0)) {
1383 				log_debugx("serial for lun %d, target %s, "
1384 				    "CTL lun %d changed; removing",
1385 				    oldlun->l_lun, oldtarg->t_name,
1386 				    oldlun->l_ctl_lun);
1387 				changed = 1;
1388 			}
1389 			if (changed) {
1390 				error = kernel_lun_remove(oldlun);
1391 				if (error != 0) {
1392 					log_warnx("failed to remove lun %d, "
1393 					    "target %s, CTL lun %d",
1394 					    oldlun->l_lun, oldtarg->t_name,
1395 					    oldlun->l_ctl_lun);
1396 					cumulated_error++;
1397 				}
1398 				lun_delete(oldlun);
1399 				continue;
1400 			}
1401 
1402 			lun_set_ctl_lun(newlun, oldlun->l_ctl_lun);
1403 		}
1404 	}
1405 
1406 	/*
1407 	 * Now add new targets or modify existing ones.
1408 	 */
1409 	TAILQ_FOREACH(newtarg, &newconf->conf_targets, t_next) {
1410 		oldtarg = target_find(oldconf, newtarg->t_name);
1411 
1412 		TAILQ_FOREACH_SAFE(newlun, &newtarg->t_luns, l_next, tmplun) {
1413 			if (oldtarg != NULL) {
1414 				oldlun = lun_find(oldtarg, newlun->l_lun);
1415 				if (oldlun != NULL) {
1416 					if (newlun->l_size != oldlun->l_size) {
1417 						log_debugx("resizing lun %d, "
1418 						    "target %s, CTL lun %d",
1419 						    newlun->l_lun,
1420 						    newtarg->t_name,
1421 						    newlun->l_ctl_lun);
1422 						error =
1423 						    kernel_lun_resize(newlun);
1424 						if (error != 0) {
1425 							log_warnx("failed to "
1426 							    "resize lun %d, "
1427 							    "target %s, "
1428 							    "CTL lun %d",
1429 							    newlun->l_lun,
1430 							    newtarg->t_name,
1431 							    newlun->l_lun);
1432 							cumulated_error++;
1433 						}
1434 					}
1435 					continue;
1436 				}
1437 			}
1438 			log_debugx("adding lun %d, target %s",
1439 			    newlun->l_lun, newtarg->t_name);
1440 			error = kernel_lun_add(newlun);
1441 			if (error != 0) {
1442 				log_warnx("failed to add lun %d, target %s",
1443 				    newlun->l_lun, newtarg->t_name);
1444 				lun_delete(newlun);
1445 				cumulated_error++;
1446 			}
1447 		}
1448 		if (oldtarg == NULL)
1449 			kernel_port_add(newtarg);
1450 	}
1451 
1452 	/*
1453 	 * Go through the new portals, opening the sockets as neccessary.
1454 	 */
1455 	TAILQ_FOREACH(newpg, &newconf->conf_portal_groups, pg_next) {
1456 		if (newpg->pg_unassigned) {
1457 			log_debugx("not listening on portal-group \"%s\", "
1458 			    "not assigned to any target",
1459 			    newpg->pg_name);
1460 			continue;
1461 		}
1462 		TAILQ_FOREACH(newp, &newpg->pg_portals, p_next) {
1463 			/*
1464 			 * Try to find already open portal and reuse
1465 			 * the listening socket.  We don't care about
1466 			 * what portal or portal group that was, what
1467 			 * matters is the listening address.
1468 			 */
1469 			TAILQ_FOREACH(oldpg, &oldconf->conf_portal_groups,
1470 			    pg_next) {
1471 				TAILQ_FOREACH(oldp, &oldpg->pg_portals,
1472 				    p_next) {
1473 					if (strcmp(newp->p_listen,
1474 					    oldp->p_listen) == 0 &&
1475 					    oldp->p_socket > 0) {
1476 						newp->p_socket =
1477 						    oldp->p_socket;
1478 						oldp->p_socket = 0;
1479 						break;
1480 					}
1481 				}
1482 			}
1483 			if (newp->p_socket > 0) {
1484 				/*
1485 				 * We're done with this portal.
1486 				 */
1487 				continue;
1488 			}
1489 
1490 #ifdef ICL_KERNEL_PROXY
1491 			if (proxy_mode) {
1492 				newpg->pg_conf->conf_portal_id++;
1493 				newp->p_id = newpg->pg_conf->conf_portal_id;
1494 				log_debugx("listening on %s, portal-group "
1495 				    "\"%s\", portal id %d, using ICL proxy",
1496 				    newp->p_listen, newpg->pg_name, newp->p_id);
1497 				kernel_listen(newp->p_ai, newp->p_iser,
1498 				    newp->p_id);
1499 				continue;
1500 			}
1501 #endif
1502 			assert(proxy_mode == false);
1503 			assert(newp->p_iser == false);
1504 
1505 			log_debugx("listening on %s, portal-group \"%s\"",
1506 			    newp->p_listen, newpg->pg_name);
1507 			newp->p_socket = socket(newp->p_ai->ai_family,
1508 			    newp->p_ai->ai_socktype,
1509 			    newp->p_ai->ai_protocol);
1510 			if (newp->p_socket < 0) {
1511 				log_warn("socket(2) failed for %s",
1512 				    newp->p_listen);
1513 				cumulated_error++;
1514 				continue;
1515 			}
1516 			error = setsockopt(newp->p_socket, SOL_SOCKET,
1517 			    SO_REUSEADDR, &one, sizeof(one));
1518 			if (error != 0) {
1519 				log_warn("setsockopt(SO_REUSEADDR) failed "
1520 				    "for %s", newp->p_listen);
1521 				close(newp->p_socket);
1522 				newp->p_socket = 0;
1523 				cumulated_error++;
1524 				continue;
1525 			}
1526 			error = bind(newp->p_socket, newp->p_ai->ai_addr,
1527 			    newp->p_ai->ai_addrlen);
1528 			if (error != 0) {
1529 				log_warn("bind(2) failed for %s",
1530 				    newp->p_listen);
1531 				close(newp->p_socket);
1532 				newp->p_socket = 0;
1533 				cumulated_error++;
1534 				continue;
1535 			}
1536 			error = listen(newp->p_socket, -1);
1537 			if (error != 0) {
1538 				log_warn("listen(2) failed for %s",
1539 				    newp->p_listen);
1540 				close(newp->p_socket);
1541 				newp->p_socket = 0;
1542 				cumulated_error++;
1543 				continue;
1544 			}
1545 		}
1546 	}
1547 
1548 	/*
1549 	 * Go through the no longer used sockets, closing them.
1550 	 */
1551 	TAILQ_FOREACH(oldpg, &oldconf->conf_portal_groups, pg_next) {
1552 		TAILQ_FOREACH(oldp, &oldpg->pg_portals, p_next) {
1553 			if (oldp->p_socket <= 0)
1554 				continue;
1555 			log_debugx("closing socket for %s, portal-group \"%s\"",
1556 			    oldp->p_listen, oldpg->pg_name);
1557 			close(oldp->p_socket);
1558 			oldp->p_socket = 0;
1559 		}
1560 	}
1561 
1562 	return (cumulated_error);
1563 }
1564 
1565 bool
1566 timed_out(void)
1567 {
1568 
1569 	return (sigalrm_received);
1570 }
1571 
1572 static void
1573 sigalrm_handler(int dummy __unused)
1574 {
1575 	/*
1576 	 * It would be easiest to just log an error and exit.  We can't
1577 	 * do this, though, because log_errx() is not signal safe, since
1578 	 * it calls syslog(3).  Instead, set a flag checked by pdu_send()
1579 	 * and pdu_receive(), to call log_errx() there.  Should they fail
1580 	 * to notice, we'll exit here one second later.
1581 	 */
1582 	if (sigalrm_received) {
1583 		/*
1584 		 * Oh well.  Just give up and quit.
1585 		 */
1586 		_exit(2);
1587 	}
1588 
1589 	sigalrm_received = true;
1590 }
1591 
1592 static void
1593 set_timeout(const struct conf *conf)
1594 {
1595 	struct sigaction sa;
1596 	struct itimerval itv;
1597 	int error;
1598 
1599 	if (conf->conf_timeout <= 0) {
1600 		log_debugx("session timeout disabled");
1601 		return;
1602 	}
1603 
1604 	bzero(&sa, sizeof(sa));
1605 	sa.sa_handler = sigalrm_handler;
1606 	sigfillset(&sa.sa_mask);
1607 	error = sigaction(SIGALRM, &sa, NULL);
1608 	if (error != 0)
1609 		log_err(1, "sigaction");
1610 
1611 	/*
1612 	 * First SIGALRM will arive after conf_timeout seconds.
1613 	 * If we do nothing, another one will arrive a second later.
1614 	 */
1615 	bzero(&itv, sizeof(itv));
1616 	itv.it_interval.tv_sec = 1;
1617 	itv.it_value.tv_sec = conf->conf_timeout;
1618 
1619 	log_debugx("setting session timeout to %d seconds",
1620 	    conf->conf_timeout);
1621 	error = setitimer(ITIMER_REAL, &itv, NULL);
1622 	if (error != 0)
1623 		log_err(1, "setitimer");
1624 }
1625 
1626 static int
1627 wait_for_children(bool block)
1628 {
1629 	pid_t pid;
1630 	int status;
1631 	int num = 0;
1632 
1633 	for (;;) {
1634 		/*
1635 		 * If "block" is true, wait for at least one process.
1636 		 */
1637 		if (block && num == 0)
1638 			pid = wait4(-1, &status, 0, NULL);
1639 		else
1640 			pid = wait4(-1, &status, WNOHANG, NULL);
1641 		if (pid <= 0)
1642 			break;
1643 		if (WIFSIGNALED(status)) {
1644 			log_warnx("child process %d terminated with signal %d",
1645 			    pid, WTERMSIG(status));
1646 		} else if (WEXITSTATUS(status) != 0) {
1647 			log_warnx("child process %d terminated with exit status %d",
1648 			    pid, WEXITSTATUS(status));
1649 		} else {
1650 			log_debugx("child process %d terminated gracefully", pid);
1651 		}
1652 		num++;
1653 	}
1654 
1655 	return (num);
1656 }
1657 
1658 static void
1659 handle_connection(struct portal *portal, int fd,
1660     const struct sockaddr *client_sa, bool dont_fork)
1661 {
1662 	struct connection *conn;
1663 	int error;
1664 	pid_t pid;
1665 	char host[NI_MAXHOST + 1];
1666 	struct conf *conf;
1667 
1668 	conf = portal->p_portal_group->pg_conf;
1669 
1670 	if (dont_fork) {
1671 		log_debugx("incoming connection; not forking due to -d flag");
1672 	} else {
1673 		nchildren -= wait_for_children(false);
1674 		assert(nchildren >= 0);
1675 
1676 		while (conf->conf_maxproc > 0 && nchildren >= conf->conf_maxproc) {
1677 			log_debugx("maxproc limit of %d child processes hit; "
1678 			    "waiting for child process to exit", conf->conf_maxproc);
1679 			nchildren -= wait_for_children(true);
1680 			assert(nchildren >= 0);
1681 		}
1682 		log_debugx("incoming connection; forking child process #%d",
1683 		    nchildren);
1684 		nchildren++;
1685 		pid = fork();
1686 		if (pid < 0)
1687 			log_err(1, "fork");
1688 		if (pid > 0) {
1689 			close(fd);
1690 			return;
1691 		}
1692 	}
1693 	pidfile_close(conf->conf_pidfh);
1694 
1695 	error = getnameinfo(client_sa, client_sa->sa_len,
1696 	    host, sizeof(host), NULL, 0, NI_NUMERICHOST);
1697 	if (error != 0)
1698 		log_errx(1, "getnameinfo: %s", gai_strerror(error));
1699 
1700 	log_debugx("accepted connection from %s; portal group \"%s\"",
1701 	    host, portal->p_portal_group->pg_name);
1702 	log_set_peer_addr(host);
1703 	setproctitle("%s", host);
1704 
1705 	conn = connection_new(portal, fd, host, client_sa);
1706 	set_timeout(conf);
1707 	kernel_capsicate();
1708 	login(conn);
1709 	if (conn->conn_session_type == CONN_SESSION_TYPE_NORMAL) {
1710 		kernel_handoff(conn);
1711 		log_debugx("connection handed off to the kernel");
1712 	} else {
1713 		assert(conn->conn_session_type == CONN_SESSION_TYPE_DISCOVERY);
1714 		discovery(conn);
1715 	}
1716 	log_debugx("nothing more to do; exiting");
1717 	exit(0);
1718 }
1719 
1720 static int
1721 fd_add(int fd, fd_set *fdset, int nfds)
1722 {
1723 
1724 	/*
1725 	 * Skip sockets which we failed to bind.
1726 	 */
1727 	if (fd <= 0)
1728 		return (nfds);
1729 
1730 	FD_SET(fd, fdset);
1731 	if (fd > nfds)
1732 		nfds = fd;
1733 	return (nfds);
1734 }
1735 
1736 static void
1737 main_loop(struct conf *conf, bool dont_fork)
1738 {
1739 	struct portal_group *pg;
1740 	struct portal *portal;
1741 	struct sockaddr_storage client_sa;
1742 	socklen_t client_salen;
1743 #ifdef ICL_KERNEL_PROXY
1744 	int connection_id;
1745 	int portal_id;
1746 #endif
1747 	fd_set fdset;
1748 	int error, nfds, client_fd;
1749 
1750 	pidfile_write(conf->conf_pidfh);
1751 
1752 	for (;;) {
1753 		if (sighup_received || sigterm_received)
1754 			return;
1755 
1756 #ifdef ICL_KERNEL_PROXY
1757 		if (proxy_mode) {
1758 			client_salen = sizeof(client_sa);
1759 			kernel_accept(&connection_id, &portal_id,
1760 			    (struct sockaddr *)&client_sa, &client_salen);
1761 			assert(client_salen >= client_sa.ss_len);
1762 
1763 			log_debugx("incoming connection, id %d, portal id %d",
1764 			    connection_id, portal_id);
1765 			TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
1766 				TAILQ_FOREACH(portal, &pg->pg_portals, p_next) {
1767 					if (portal->p_id == portal_id) {
1768 						goto found;
1769 					}
1770 				}
1771 			}
1772 
1773 			log_errx(1, "kernel returned invalid portal_id %d",
1774 			    portal_id);
1775 
1776 found:
1777 			handle_connection(portal, connection_id,
1778 			    (struct sockaddr *)&client_sa, dont_fork);
1779 		} else {
1780 #endif
1781 			assert(proxy_mode == false);
1782 
1783 			FD_ZERO(&fdset);
1784 			nfds = 0;
1785 			TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
1786 				TAILQ_FOREACH(portal, &pg->pg_portals, p_next)
1787 					nfds = fd_add(portal->p_socket, &fdset, nfds);
1788 			}
1789 			error = select(nfds + 1, &fdset, NULL, NULL, NULL);
1790 			if (error <= 0) {
1791 				if (errno == EINTR)
1792 					return;
1793 				log_err(1, "select");
1794 			}
1795 			TAILQ_FOREACH(pg, &conf->conf_portal_groups, pg_next) {
1796 				TAILQ_FOREACH(portal, &pg->pg_portals, p_next) {
1797 					if (!FD_ISSET(portal->p_socket, &fdset))
1798 						continue;
1799 					client_salen = sizeof(client_sa);
1800 					client_fd = accept(portal->p_socket,
1801 					    (struct sockaddr *)&client_sa,
1802 					    &client_salen);
1803 					if (client_fd < 0)
1804 						log_err(1, "accept");
1805 					assert(client_salen >= client_sa.ss_len);
1806 
1807 					handle_connection(portal, client_fd,
1808 					    (struct sockaddr *)&client_sa,
1809 					    dont_fork);
1810 					break;
1811 				}
1812 			}
1813 #ifdef ICL_KERNEL_PROXY
1814 		}
1815 #endif
1816 	}
1817 }
1818 
1819 static void
1820 sighup_handler(int dummy __unused)
1821 {
1822 
1823 	sighup_received = true;
1824 }
1825 
1826 static void
1827 sigterm_handler(int dummy __unused)
1828 {
1829 
1830 	sigterm_received = true;
1831 }
1832 
1833 static void
1834 sigchld_handler(int dummy __unused)
1835 {
1836 
1837 	/*
1838 	 * The only purpose of this handler is to make SIGCHLD
1839 	 * interrupt the ISCSIDWAIT ioctl(2), so we can call
1840 	 * wait_for_children().
1841 	 */
1842 }
1843 
1844 static void
1845 register_signals(void)
1846 {
1847 	struct sigaction sa;
1848 	int error;
1849 
1850 	bzero(&sa, sizeof(sa));
1851 	sa.sa_handler = sighup_handler;
1852 	sigfillset(&sa.sa_mask);
1853 	error = sigaction(SIGHUP, &sa, NULL);
1854 	if (error != 0)
1855 		log_err(1, "sigaction");
1856 
1857 	sa.sa_handler = sigterm_handler;
1858 	error = sigaction(SIGTERM, &sa, NULL);
1859 	if (error != 0)
1860 		log_err(1, "sigaction");
1861 
1862 	sa.sa_handler = sigterm_handler;
1863 	error = sigaction(SIGINT, &sa, NULL);
1864 	if (error != 0)
1865 		log_err(1, "sigaction");
1866 
1867 	sa.sa_handler = sigchld_handler;
1868 	error = sigaction(SIGCHLD, &sa, NULL);
1869 	if (error != 0)
1870 		log_err(1, "sigaction");
1871 }
1872 
1873 int
1874 main(int argc, char **argv)
1875 {
1876 	struct conf *oldconf, *newconf, *tmpconf;
1877 	const char *config_path = DEFAULT_CONFIG_PATH;
1878 	int debug = 0, ch, error;
1879 	bool dont_daemonize = false;
1880 
1881 	while ((ch = getopt(argc, argv, "df:R")) != -1) {
1882 		switch (ch) {
1883 		case 'd':
1884 			dont_daemonize = true;
1885 			debug++;
1886 			break;
1887 		case 'f':
1888 			config_path = optarg;
1889 			break;
1890 		case 'R':
1891 #ifndef ICL_KERNEL_PROXY
1892 			log_errx(1, "ctld(8) compiled without ICL_KERNEL_PROXY "
1893 			    "does not support iSER protocol");
1894 #endif
1895 			proxy_mode = true;
1896 			break;
1897 		case '?':
1898 		default:
1899 			usage();
1900 		}
1901 	}
1902 	argc -= optind;
1903 	if (argc != 0)
1904 		usage();
1905 
1906 	log_init(debug);
1907 	kernel_init();
1908 
1909 	oldconf = conf_new_from_kernel();
1910 	newconf = conf_new_from_file(config_path);
1911 	if (newconf == NULL)
1912 		log_errx(1, "configuration error; exiting");
1913 	if (debug > 0) {
1914 		oldconf->conf_debug = debug;
1915 		newconf->conf_debug = debug;
1916 	}
1917 
1918 	error = conf_apply(oldconf, newconf);
1919 	if (error != 0)
1920 		log_errx(1, "failed to apply configuration; exiting");
1921 
1922 	conf_delete(oldconf);
1923 	oldconf = NULL;
1924 
1925 	register_signals();
1926 
1927 	if (dont_daemonize == false) {
1928 		log_debugx("daemonizing");
1929 		if (daemon(0, 0) == -1) {
1930 			log_warn("cannot daemonize");
1931 			pidfile_remove(newconf->conf_pidfh);
1932 			exit(1);
1933 		}
1934 	}
1935 
1936 	for (;;) {
1937 		main_loop(newconf, dont_daemonize);
1938 		if (sighup_received) {
1939 			sighup_received = false;
1940 			log_debugx("received SIGHUP, reloading configuration");
1941 			tmpconf = conf_new_from_file(config_path);
1942 			if (tmpconf == NULL) {
1943 				log_warnx("configuration error, "
1944 				    "continuing with old configuration");
1945 			} else {
1946 				if (debug > 0)
1947 					tmpconf->conf_debug = debug;
1948 				oldconf = newconf;
1949 				newconf = tmpconf;
1950 				error = conf_apply(oldconf, newconf);
1951 				if (error != 0)
1952 					log_warnx("failed to reload "
1953 					    "configuration");
1954 				conf_delete(oldconf);
1955 				oldconf = NULL;
1956 			}
1957 		} else if (sigterm_received) {
1958 			log_debugx("exiting on signal; "
1959 			    "reloading empty configuration");
1960 
1961 			log_debugx("disabling CTL iSCSI port "
1962 			    "and terminating all connections");
1963 
1964 			oldconf = newconf;
1965 			newconf = conf_new();
1966 			if (debug > 0)
1967 				newconf->conf_debug = debug;
1968 			error = conf_apply(oldconf, newconf);
1969 			if (error != 0)
1970 				log_warnx("failed to apply configuration");
1971 
1972 			log_warnx("exiting on signal");
1973 			exit(0);
1974 		} else {
1975 			nchildren -= wait_for_children(false);
1976 			assert(nchildren >= 0);
1977 		}
1978 	}
1979 	/* NOTREACHED */
1980 }
1981