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