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