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