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