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