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