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