]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/iscsid/iscsid.c
MFV r310115,310184:
[FreeBSD/FreeBSD.git] / usr.sbin / iscsid / iscsid.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/ioctl.h>
37 #include <sys/param.h>
38 #include <sys/linker.h>
39 #include <sys/socket.h>
40 #include <sys/capsicum.h>
41 #include <sys/wait.h>
42 #include <assert.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <libutil.h>
46 #include <netdb.h>
47 #include <signal.h>
48 #include <stdbool.h>
49 #include <stdint.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54
55 #include "iscsid.h"
56
57 static volatile bool sigalrm_received = false;
58
59 static int nchildren = 0;
60
61 static void
62 usage(void)
63 {
64
65         fprintf(stderr, "usage: iscsid [-P pidfile][-d][-m maxproc][-t timeout]\n");
66         exit(1);
67 }
68
69 char *
70 checked_strdup(const char *s)
71 {
72         char *c;
73
74         c = strdup(s);
75         if (c == NULL)
76                 log_err(1, "strdup");
77         return (c);
78 }
79
80 static void
81 resolve_addr(const struct connection *conn, const char *address,
82     struct addrinfo **ai, bool initiator_side)
83 {
84         struct addrinfo hints;
85         char *arg, *addr, *ch;
86         const char *port;
87         int error, colons = 0;
88
89         arg = checked_strdup(address);
90
91         if (arg[0] == '\0') {
92                 fail(conn, "empty address");
93                 log_errx(1, "empty address");
94         }
95         if (arg[0] == '[') {
96                 /*
97                  * IPv6 address in square brackets, perhaps with port.
98                  */
99                 arg++;
100                 addr = strsep(&arg, "]");
101                 if (arg == NULL) {
102                         fail(conn, "malformed address");
103                         log_errx(1, "malformed address %s", address);
104                 }
105                 if (arg[0] == '\0') {
106                         port = NULL;
107                 } else if (arg[0] == ':') {
108                         port = arg + 1;
109                 } else {
110                         fail(conn, "malformed address");
111                         log_errx(1, "malformed address %s", address);
112                 }
113         } else {
114                 /*
115                  * Either IPv6 address without brackets - and without
116                  * a port - or IPv4 address.  Just count the colons.
117                  */
118                 for (ch = arg; *ch != '\0'; ch++) {
119                         if (*ch == ':')
120                                 colons++;
121                 }
122                 if (colons > 1) {
123                         addr = arg;
124                         port = NULL;
125                 } else {
126                         addr = strsep(&arg, ":");
127                         if (arg == NULL)
128                                 port = NULL;
129                         else
130                                 port = arg;
131                 }
132         }
133
134         if (port == NULL && !initiator_side)
135                 port = "3260";
136
137         memset(&hints, 0, sizeof(hints));
138         hints.ai_family = PF_UNSPEC;
139         hints.ai_socktype = SOCK_STREAM;
140         hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV;
141         if (initiator_side)
142                 hints.ai_flags |= AI_PASSIVE;
143
144         error = getaddrinfo(addr, port, &hints, ai);
145         if (error != 0) {
146                 fail(conn, gai_strerror(error));
147                 log_errx(1, "getaddrinfo for %s failed: %s",
148                     address, gai_strerror(error));
149         }
150 }
151
152 static struct connection *
153 connection_new(int iscsi_fd, const struct iscsi_daemon_request *request)
154 {
155         struct connection *conn;
156         struct iscsi_session_limits *isl;
157         struct addrinfo *from_ai, *to_ai;
158         const char *from_addr, *to_addr;
159 #ifdef ICL_KERNEL_PROXY
160         struct iscsi_daemon_connect idc;
161 #endif
162         int error, sockbuf;
163
164         conn = calloc(1, sizeof(*conn));
165         if (conn == NULL)
166                 log_err(1, "calloc");
167
168         /*
169          * Default values, from RFC 3720, section 12.
170          */
171         conn->conn_header_digest = CONN_DIGEST_NONE;
172         conn->conn_data_digest = CONN_DIGEST_NONE;
173         conn->conn_initial_r2t = true;
174         conn->conn_immediate_data = true;
175         conn->conn_max_burst_length = MAX_BURST_LENGTH;
176         conn->conn_first_burst_length = FIRST_BURST_LENGTH;
177         conn->conn_iscsi_fd = iscsi_fd;
178
179         conn->conn_session_id = request->idr_session_id;
180         memcpy(&conn->conn_conf, &request->idr_conf, sizeof(conn->conn_conf));
181         memcpy(&conn->conn_isid, &request->idr_isid, sizeof(conn->conn_isid));
182         conn->conn_tsih = request->idr_tsih;
183
184         /*
185          * Read the driver limits and provide reasonable defaults for the ones
186          * the driver doesn't care about.  If a max_snd_dsl is not explicitly
187          * provided by the driver then we'll make sure both conn->max_snd_dsl
188          * and isl->max_snd_dsl are set to the rcv_dsl.  This preserves historic
189          * behavior.
190          */
191         isl = &conn->conn_limits;
192         memcpy(isl, &request->idr_limits, sizeof(*isl));
193         if (isl->isl_max_recv_data_segment_length == 0) {
194                 conn->conn_max_recv_data_segment_length = 8192;
195                 conn->conn_max_send_data_segment_length = 8192;
196                 isl->isl_max_recv_data_segment_length = 8192;
197         } else {
198                 conn->conn_max_recv_data_segment_length =
199                     isl->isl_max_recv_data_segment_length;
200                 conn->conn_max_send_data_segment_length =
201                     isl->isl_max_recv_data_segment_length;
202         }
203         if (isl->isl_max_send_data_segment_length == 0) {
204                 isl->isl_max_send_data_segment_length =
205                     isl->isl_max_recv_data_segment_length;
206         } else {
207                 conn->conn_max_send_data_segment_length =
208                     isl->isl_max_send_data_segment_length;
209         }
210         if (isl->isl_max_burst_length == 0)
211                 isl->isl_max_burst_length = conn->conn_max_burst_length;
212         if (isl->isl_first_burst_length == 0) {
213                 if (isl->isl_max_burst_length < (int)conn->conn_first_burst_length)
214                         isl->isl_first_burst_length = isl->isl_max_burst_length;
215                 else
216                         isl->isl_first_burst_length = conn->conn_first_burst_length;
217         }
218
219         from_addr = conn->conn_conf.isc_initiator_addr;
220         to_addr = conn->conn_conf.isc_target_addr;
221
222         if (from_addr[0] != '\0')
223                 resolve_addr(conn, from_addr, &from_ai, true);
224         else
225                 from_ai = NULL;
226
227         resolve_addr(conn, to_addr, &to_ai, false);
228
229 #ifdef ICL_KERNEL_PROXY
230         if (conn->conn_conf.isc_iser) {
231                 memset(&idc, 0, sizeof(idc));
232                 idc.idc_session_id = conn->conn_session_id;
233                 if (conn->conn_conf.isc_iser)
234                         idc.idc_iser = 1;
235                 idc.idc_domain = to_ai->ai_family;
236                 idc.idc_socktype = to_ai->ai_socktype;
237                 idc.idc_protocol = to_ai->ai_protocol;
238                 if (from_ai != NULL) {
239                         idc.idc_from_addr = from_ai->ai_addr;
240                         idc.idc_from_addrlen = from_ai->ai_addrlen;
241                 }
242                 idc.idc_to_addr = to_ai->ai_addr;
243                 idc.idc_to_addrlen = to_ai->ai_addrlen;
244
245                 log_debugx("connecting to %s using ICL kernel proxy", to_addr);
246                 error = ioctl(iscsi_fd, ISCSIDCONNECT, &idc);
247                 if (error != 0) {
248                         fail(conn, strerror(errno));
249                         log_err(1, "failed to connect to %s "
250                             "using ICL kernel proxy: ISCSIDCONNECT", to_addr);
251                 }
252
253                 return (conn);
254         }
255 #endif /* ICL_KERNEL_PROXY */
256
257         if (conn->conn_conf.isc_iser) {
258                 fail(conn, "iSER not supported");
259                 log_errx(1, "iscsid(8) compiled without ICL_KERNEL_PROXY "
260                     "does not support iSER");
261         }
262
263         conn->conn_socket = socket(to_ai->ai_family, to_ai->ai_socktype,
264             to_ai->ai_protocol);
265         if (conn->conn_socket < 0) {
266                 fail(conn, strerror(errno));
267                 log_err(1, "failed to create socket for %s", from_addr);
268         }
269         sockbuf = SOCKBUF_SIZE;
270         if (setsockopt(conn->conn_socket, SOL_SOCKET, SO_RCVBUF,
271             &sockbuf, sizeof(sockbuf)) == -1)
272                 log_warn("setsockopt(SO_RCVBUF) failed");
273         sockbuf = SOCKBUF_SIZE;
274         if (setsockopt(conn->conn_socket, SOL_SOCKET, SO_SNDBUF,
275             &sockbuf, sizeof(sockbuf)) == -1)
276                 log_warn("setsockopt(SO_SNDBUF) failed");
277         if (from_ai != NULL) {
278                 error = bind(conn->conn_socket, from_ai->ai_addr,
279                     from_ai->ai_addrlen);
280                 if (error != 0) {
281                         fail(conn, strerror(errno));
282                         log_err(1, "failed to bind to %s", from_addr);
283                 }
284         }
285         log_debugx("connecting to %s", to_addr);
286         error = connect(conn->conn_socket, to_ai->ai_addr, to_ai->ai_addrlen);
287         if (error != 0) {
288                 fail(conn, strerror(errno));
289                 log_err(1, "failed to connect to %s", to_addr);
290         }
291
292         return (conn);
293 }
294
295 static void
296 handoff(struct connection *conn)
297 {
298         struct iscsi_daemon_handoff idh;
299         int error;
300
301         log_debugx("handing off connection to the kernel");
302
303         memset(&idh, 0, sizeof(idh));
304         idh.idh_session_id = conn->conn_session_id;
305         idh.idh_socket = conn->conn_socket;
306         strlcpy(idh.idh_target_alias, conn->conn_target_alias,
307             sizeof(idh.idh_target_alias));
308         idh.idh_tsih = conn->conn_tsih;
309         idh.idh_statsn = conn->conn_statsn;
310         idh.idh_header_digest = conn->conn_header_digest;
311         idh.idh_data_digest = conn->conn_data_digest;
312         idh.idh_initial_r2t = conn->conn_initial_r2t;
313         idh.idh_immediate_data = conn->conn_immediate_data;
314         idh.idh_max_recv_data_segment_length =
315             conn->conn_max_recv_data_segment_length;
316         idh.idh_max_send_data_segment_length =
317             conn->conn_max_send_data_segment_length;
318         idh.idh_max_burst_length = conn->conn_max_burst_length;
319         idh.idh_first_burst_length = conn->conn_first_burst_length;
320
321         error = ioctl(conn->conn_iscsi_fd, ISCSIDHANDOFF, &idh);
322         if (error != 0)
323                 log_err(1, "ISCSIDHANDOFF");
324 }
325
326 void
327 fail(const struct connection *conn, const char *reason)
328 {
329         struct iscsi_daemon_fail idf;
330         int error, saved_errno;
331
332         saved_errno = errno;
333
334         memset(&idf, 0, sizeof(idf));
335         idf.idf_session_id = conn->conn_session_id;
336         strlcpy(idf.idf_reason, reason, sizeof(idf.idf_reason));
337
338         error = ioctl(conn->conn_iscsi_fd, ISCSIDFAIL, &idf);
339         if (error != 0)
340                 log_err(1, "ISCSIDFAIL");
341
342         errno = saved_errno;
343 }
344
345 /*
346  * XXX: I CANT INTO LATIN
347  */
348 static void
349 capsicate(struct connection *conn)
350 {
351         int error;
352         cap_rights_t rights;
353 #ifdef ICL_KERNEL_PROXY
354         const unsigned long cmds[] = { ISCSIDCONNECT, ISCSIDSEND, ISCSIDRECEIVE,
355             ISCSIDHANDOFF, ISCSIDFAIL, ISCSISADD, ISCSISREMOVE, ISCSISMODIFY };
356 #else
357         const unsigned long cmds[] = { ISCSIDHANDOFF, ISCSIDFAIL, ISCSISADD,
358             ISCSISREMOVE, ISCSISMODIFY };
359 #endif
360
361         cap_rights_init(&rights, CAP_IOCTL);
362         error = cap_rights_limit(conn->conn_iscsi_fd, &rights);
363         if (error != 0 && errno != ENOSYS)
364                 log_err(1, "cap_rights_limit");
365
366         error = cap_ioctls_limit(conn->conn_iscsi_fd, cmds,
367             sizeof(cmds) / sizeof(cmds[0]));
368         if (error != 0 && errno != ENOSYS)
369                 log_err(1, "cap_ioctls_limit");
370
371         error = cap_enter();
372         if (error != 0 && errno != ENOSYS)
373                 log_err(1, "cap_enter");
374
375         if (cap_sandboxed())
376                 log_debugx("Capsicum capability mode enabled");
377         else
378                 log_warnx("Capsicum capability mode not supported");
379 }
380
381 bool
382 timed_out(void)
383 {
384
385         return (sigalrm_received);
386 }
387
388 static void
389 sigalrm_handler(int dummy __unused)
390 {
391         /*
392          * It would be easiest to just log an error and exit.  We can't
393          * do this, though, because log_errx() is not signal safe, since
394          * it calls syslog(3).  Instead, set a flag checked by pdu_send()
395          * and pdu_receive(), to call log_errx() there.  Should they fail
396          * to notice, we'll exit here one second later.
397          */
398         if (sigalrm_received) {
399                 /*
400                  * Oh well.  Just give up and quit.
401                  */
402                 _exit(2);
403         }
404
405         sigalrm_received = true;
406 }
407
408 static void
409 set_timeout(int timeout)
410 {
411         struct sigaction sa;
412         struct itimerval itv;
413         int error;
414
415         if (timeout <= 0) {
416                 log_debugx("session timeout disabled");
417                 return;
418         }
419
420         bzero(&sa, sizeof(sa));
421         sa.sa_handler = sigalrm_handler;
422         sigfillset(&sa.sa_mask);
423         error = sigaction(SIGALRM, &sa, NULL);
424         if (error != 0)
425                 log_err(1, "sigaction");
426
427         /*
428          * First SIGALRM will arive after conf_timeout seconds.
429          * If we do nothing, another one will arrive a second later.
430          */
431         bzero(&itv, sizeof(itv));
432         itv.it_interval.tv_sec = 1;
433         itv.it_value.tv_sec = timeout;
434
435         log_debugx("setting session timeout to %d seconds",
436             timeout);
437         error = setitimer(ITIMER_REAL, &itv, NULL);
438         if (error != 0)
439                 log_err(1, "setitimer");
440 }
441
442 static void
443 sigchld_handler(int dummy __unused)
444 {
445
446         /*
447          * The only purpose of this handler is to make SIGCHLD
448          * interrupt the ISCSIDWAIT ioctl(2), so we can call
449          * wait_for_children().
450          */
451 }
452
453 static void
454 register_sigchld(void)
455 {
456         struct sigaction sa;
457         int error;
458
459         bzero(&sa, sizeof(sa));
460         sa.sa_handler = sigchld_handler;
461         sigfillset(&sa.sa_mask);
462         error = sigaction(SIGCHLD, &sa, NULL);
463         if (error != 0)
464                 log_err(1, "sigaction");
465
466 }
467
468 static void
469 handle_request(int iscsi_fd, const struct iscsi_daemon_request *request, int timeout)
470 {
471         struct connection *conn;
472
473         log_set_peer_addr(request->idr_conf.isc_target_addr);
474         if (request->idr_conf.isc_target[0] != '\0') {
475                 log_set_peer_name(request->idr_conf.isc_target);
476                 setproctitle("%s (%s)", request->idr_conf.isc_target_addr, request->idr_conf.isc_target);
477         } else {
478                 setproctitle("%s", request->idr_conf.isc_target_addr);
479         }
480
481         conn = connection_new(iscsi_fd, request);
482         set_timeout(timeout);
483         capsicate(conn);
484         login(conn);
485         if (conn->conn_conf.isc_discovery != 0)
486                 discovery(conn);
487         else
488                 handoff(conn);
489
490         log_debugx("nothing more to do; exiting");
491         exit (0);
492 }
493
494 static int
495 wait_for_children(bool block)
496 {
497         pid_t pid;
498         int status;
499         int num = 0;
500
501         for (;;) {
502                 /*
503                  * If "block" is true, wait for at least one process.
504                  */
505                 if (block && num == 0)
506                         pid = wait4(-1, &status, 0, NULL);
507                 else
508                         pid = wait4(-1, &status, WNOHANG, NULL);
509                 if (pid <= 0)
510                         break;
511                 if (WIFSIGNALED(status)) {
512                         log_warnx("child process %d terminated with signal %d",
513                             pid, WTERMSIG(status));
514                 } else if (WEXITSTATUS(status) != 0) {
515                         log_warnx("child process %d terminated with exit status %d",
516                             pid, WEXITSTATUS(status));
517                 } else {
518                         log_debugx("child process %d terminated gracefully", pid);
519                 }
520                 num++;
521         }
522
523         return (num);
524 }
525
526 int
527 main(int argc, char **argv)
528 {
529         int ch, debug = 0, error, iscsi_fd, maxproc = 30, retval, saved_errno,
530             timeout = 60;
531         bool dont_daemonize = false;
532         struct pidfh *pidfh;
533         pid_t pid, otherpid;
534         const char *pidfile_path = DEFAULT_PIDFILE;
535         struct iscsi_daemon_request request;
536
537         while ((ch = getopt(argc, argv, "P:dl:m:t:")) != -1) {
538                 switch (ch) {
539                 case 'P':
540                         pidfile_path = optarg;
541                         break;
542                 case 'd':
543                         dont_daemonize = true;
544                         debug++;
545                         break;
546                 case 'l':
547                         debug = atoi(optarg);
548                         break;
549                 case 'm':
550                         maxproc = atoi(optarg);
551                         break;
552                 case 't':
553                         timeout = atoi(optarg);
554                         break;
555                 case '?':
556                 default:
557                         usage();
558                 }
559         }
560         argc -= optind;
561         if (argc != 0)
562                 usage();
563
564         log_init(debug);
565
566         pidfh = pidfile_open(pidfile_path, 0600, &otherpid);
567         if (pidfh == NULL) {
568                 if (errno == EEXIST)
569                         log_errx(1, "daemon already running, pid: %jd.",
570                             (intmax_t)otherpid);
571                 log_err(1, "cannot open or create pidfile \"%s\"",
572                     pidfile_path);
573         }
574
575         iscsi_fd = open(ISCSI_PATH, O_RDWR);
576         if (iscsi_fd < 0 && errno == ENOENT) {
577                 saved_errno = errno;
578                 retval = kldload("iscsi");
579                 if (retval != -1)
580                         iscsi_fd = open(ISCSI_PATH, O_RDWR);
581                 else
582                         errno = saved_errno;
583         }
584         if (iscsi_fd < 0)
585                 log_err(1, "failed to open %s", ISCSI_PATH);
586
587         if (dont_daemonize == false) {
588                 if (daemon(0, 0) == -1) {
589                         log_warn("cannot daemonize");
590                         pidfile_remove(pidfh);
591                         exit(1);
592                 }
593         }
594
595         pidfile_write(pidfh);
596
597         register_sigchld();
598
599         for (;;) {
600                 log_debugx("waiting for request from the kernel");
601
602                 memset(&request, 0, sizeof(request));
603                 error = ioctl(iscsi_fd, ISCSIDWAIT, &request);
604                 if (error != 0) {
605                         if (errno == EINTR) {
606                                 nchildren -= wait_for_children(false);
607                                 assert(nchildren >= 0);
608                                 continue;
609                         }
610
611                         log_err(1, "ISCSIDWAIT");
612                 }
613
614                 if (dont_daemonize) {
615                         log_debugx("not forking due to -d flag; "
616                             "will exit after servicing a single request");
617                 } else {
618                         nchildren -= wait_for_children(false);
619                         assert(nchildren >= 0);
620
621                         while (maxproc > 0 && nchildren >= maxproc) {
622                                 log_debugx("maxproc limit of %d child processes hit; "
623                                     "waiting for child process to exit", maxproc);
624                                 nchildren -= wait_for_children(true);
625                                 assert(nchildren >= 0);
626                         }
627                         log_debugx("incoming connection; forking child process #%d",
628                             nchildren);
629                         nchildren++;
630
631                         pid = fork();
632                         if (pid < 0)
633                                 log_err(1, "fork");
634                         if (pid > 0)
635                                 continue;
636                 }
637
638                 pidfile_close(pidfh);
639                 handle_request(iscsi_fd, &request, timeout);
640         }
641
642         return (0);
643 }