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