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