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