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