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