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