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