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