xref: /openbmc/linux/tools/usb/usbip/src/usbipd.c (revision e9246c87)
1 /*
2  * Copyright (C) 2011 matt mooney <mfm@muteddisk.com>
3  *               2005-2007 Takahiro Hirofuchi
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 #ifdef HAVE_CONFIG_H
20 #include "../config.h"
21 #endif
22 
23 #define _GNU_SOURCE
24 #include <errno.h>
25 #include <unistd.h>
26 #include <netdb.h>
27 #include <string.h>
28 #include <stdlib.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <arpa/inet.h>
32 #include <sys/socket.h>
33 #include <netinet/in.h>
34 
35 #ifdef HAVE_LIBWRAP
36 #include <tcpd.h>
37 #endif
38 
39 #include <getopt.h>
40 #include <signal.h>
41 #include <poll.h>
42 
43 #include "usbip_host_driver.h"
44 #include "usbip_common.h"
45 #include "usbip_network.h"
46 #include "list.h"
47 
48 #undef  PROGNAME
49 #define PROGNAME "usbipd"
50 #define MAXSOCKFD 20
51 
52 #define MAIN_LOOP_TIMEOUT 10
53 
54 #define DEFAULT_PID_FILE "/var/run/" PROGNAME ".pid"
55 
56 static const char usbip_version_string[] = PACKAGE_STRING;
57 
58 static const char usbipd_help_string[] =
59 	"usage: usbipd [options]\n"
60 	"\n"
61 	"	-4, --ipv4\n"
62 	"		Bind to IPv4. Default is both.\n"
63 	"\n"
64 	"	-6, --ipv6\n"
65 	"		Bind to IPv6. Default is both.\n"
66 	"\n"
67 	"	-D, --daemon\n"
68 	"		Run as a daemon process.\n"
69 	"\n"
70 	"	-d, --debug\n"
71 	"		Print debugging information.\n"
72 	"\n"
73 	"	-PFILE, --pid FILE\n"
74 	"		Write process id to FILE.\n"
75 	"		If no FILE specified, use " DEFAULT_PID_FILE "\n"
76 	"\n"
77 	"	-tPORT, --tcp-port PORT\n"
78 	"		Listen on TCP/IP port PORT.\n"
79 	"\n"
80 	"	-h, --help\n"
81 	"		Print this help.\n"
82 	"\n"
83 	"	-v, --version\n"
84 	"		Show version.\n";
85 
86 static void usbipd_help(void)
87 {
88 	printf("%s\n", usbipd_help_string);
89 }
90 
91 static int recv_request_import(int sockfd)
92 {
93 	struct op_import_request req;
94 	struct op_common reply;
95 	struct usbip_exported_device *edev;
96 	struct usbip_usb_device pdu_udev;
97 	struct list_head *i;
98 	int found = 0;
99 	int error = 0;
100 	int rc;
101 
102 	memset(&req, 0, sizeof(req));
103 	memset(&reply, 0, sizeof(reply));
104 
105 	rc = usbip_net_recv(sockfd, &req, sizeof(req));
106 	if (rc < 0) {
107 		dbg("usbip_net_recv failed: import request");
108 		return -1;
109 	}
110 	PACK_OP_IMPORT_REQUEST(0, &req);
111 
112 	list_for_each(i, &host_driver->edev_list) {
113 		edev = list_entry(i, struct usbip_exported_device, node);
114 		if (!strncmp(req.busid, edev->udev.busid, SYSFS_BUS_ID_SIZE)) {
115 			info("found requested device: %s", req.busid);
116 			found = 1;
117 			break;
118 		}
119 	}
120 
121 	if (found) {
122 		/* should set TCP_NODELAY for usbip */
123 		usbip_net_set_nodelay(sockfd);
124 
125 		/* export device needs a TCP/IP socket descriptor */
126 		rc = usbip_host_export_device(edev, sockfd);
127 		if (rc < 0)
128 			error = 1;
129 	} else {
130 		info("requested device not found: %s", req.busid);
131 		error = 1;
132 	}
133 
134 	rc = usbip_net_send_op_common(sockfd, OP_REP_IMPORT,
135 				      (!error ? ST_OK : ST_NA));
136 	if (rc < 0) {
137 		dbg("usbip_net_send_op_common failed: %#0x", OP_REP_IMPORT);
138 		return -1;
139 	}
140 
141 	if (error) {
142 		dbg("import request busid %s: failed", req.busid);
143 		return -1;
144 	}
145 
146 	memcpy(&pdu_udev, &edev->udev, sizeof(pdu_udev));
147 	usbip_net_pack_usb_device(1, &pdu_udev);
148 
149 	rc = usbip_net_send(sockfd, &pdu_udev, sizeof(pdu_udev));
150 	if (rc < 0) {
151 		dbg("usbip_net_send failed: devinfo");
152 		return -1;
153 	}
154 
155 	dbg("import request busid %s: complete", req.busid);
156 
157 	return 0;
158 }
159 
160 static int send_reply_devlist(int connfd)
161 {
162 	struct usbip_exported_device *edev;
163 	struct usbip_usb_device pdu_udev;
164 	struct usbip_usb_interface pdu_uinf;
165 	struct op_devlist_reply reply;
166 	struct list_head *j;
167 	int rc, i;
168 
169 	reply.ndev = 0;
170 	/* number of exported devices */
171 	list_for_each(j, &host_driver->edev_list) {
172 		reply.ndev += 1;
173 	}
174 	info("exportable devices: %d", reply.ndev);
175 
176 	rc = usbip_net_send_op_common(connfd, OP_REP_DEVLIST, ST_OK);
177 	if (rc < 0) {
178 		dbg("usbip_net_send_op_common failed: %#0x", OP_REP_DEVLIST);
179 		return -1;
180 	}
181 	PACK_OP_DEVLIST_REPLY(1, &reply);
182 
183 	rc = usbip_net_send(connfd, &reply, sizeof(reply));
184 	if (rc < 0) {
185 		dbg("usbip_net_send failed: %#0x", OP_REP_DEVLIST);
186 		return -1;
187 	}
188 
189 	list_for_each(j, &host_driver->edev_list) {
190 		edev = list_entry(j, struct usbip_exported_device, node);
191 		dump_usb_device(&edev->udev);
192 		memcpy(&pdu_udev, &edev->udev, sizeof(pdu_udev));
193 		usbip_net_pack_usb_device(1, &pdu_udev);
194 
195 		rc = usbip_net_send(connfd, &pdu_udev, sizeof(pdu_udev));
196 		if (rc < 0) {
197 			dbg("usbip_net_send failed: pdu_udev");
198 			return -1;
199 		}
200 
201 		for (i = 0; i < edev->udev.bNumInterfaces; i++) {
202 			dump_usb_interface(&edev->uinf[i]);
203 			memcpy(&pdu_uinf, &edev->uinf[i], sizeof(pdu_uinf));
204 			usbip_net_pack_usb_interface(1, &pdu_uinf);
205 
206 			rc = usbip_net_send(connfd, &pdu_uinf,
207 					sizeof(pdu_uinf));
208 			if (rc < 0) {
209 				err("usbip_net_send failed: pdu_uinf");
210 				return -1;
211 			}
212 		}
213 	}
214 
215 	return 0;
216 }
217 
218 static int recv_request_devlist(int connfd)
219 {
220 	struct op_devlist_request req;
221 	int rc;
222 
223 	memset(&req, 0, sizeof(req));
224 
225 	rc = usbip_net_recv(connfd, &req, sizeof(req));
226 	if (rc < 0) {
227 		dbg("usbip_net_recv failed: devlist request");
228 		return -1;
229 	}
230 
231 	rc = send_reply_devlist(connfd);
232 	if (rc < 0) {
233 		dbg("send_reply_devlist failed");
234 		return -1;
235 	}
236 
237 	return 0;
238 }
239 
240 static int recv_pdu(int connfd)
241 {
242 	uint16_t code = OP_UNSPEC;
243 	int ret;
244 
245 	ret = usbip_net_recv_op_common(connfd, &code);
246 	if (ret < 0) {
247 		dbg("could not receive opcode: %#0x", code);
248 		return -1;
249 	}
250 
251 	ret = usbip_host_refresh_device_list();
252 	if (ret < 0) {
253 		dbg("could not refresh device list: %d", ret);
254 		return -1;
255 	}
256 
257 	info("received request: %#0x(%d)", code, connfd);
258 	switch (code) {
259 	case OP_REQ_DEVLIST:
260 		ret = recv_request_devlist(connfd);
261 		break;
262 	case OP_REQ_IMPORT:
263 		ret = recv_request_import(connfd);
264 		break;
265 	case OP_REQ_DEVINFO:
266 	case OP_REQ_CRYPKEY:
267 	default:
268 		err("received an unknown opcode: %#0x", code);
269 		ret = -1;
270 	}
271 
272 	if (ret == 0)
273 		info("request %#0x(%d): complete", code, connfd);
274 	else
275 		info("request %#0x(%d): failed", code, connfd);
276 
277 	return ret;
278 }
279 
280 #ifdef HAVE_LIBWRAP
281 static int tcpd_auth(int connfd)
282 {
283 	struct request_info request;
284 	int rc;
285 
286 	request_init(&request, RQ_DAEMON, PROGNAME, RQ_FILE, connfd, 0);
287 	fromhost(&request);
288 	rc = hosts_access(&request);
289 	if (rc == 0)
290 		return -1;
291 
292 	return 0;
293 }
294 #endif
295 
296 static int do_accept(int listenfd)
297 {
298 	int connfd;
299 	struct sockaddr_storage ss;
300 	socklen_t len = sizeof(ss);
301 	char host[NI_MAXHOST], port[NI_MAXSERV];
302 	int rc;
303 
304 	memset(&ss, 0, sizeof(ss));
305 
306 	connfd = accept(listenfd, (struct sockaddr *)&ss, &len);
307 	if (connfd < 0) {
308 		err("failed to accept connection");
309 		return -1;
310 	}
311 
312 	rc = getnameinfo((struct sockaddr *)&ss, len, host, sizeof(host),
313 			 port, sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV);
314 	if (rc)
315 		err("getnameinfo: %s", gai_strerror(rc));
316 
317 #ifdef HAVE_LIBWRAP
318 	rc = tcpd_auth(connfd);
319 	if (rc < 0) {
320 		info("denied access from %s", host);
321 		close(connfd);
322 		return -1;
323 	}
324 #endif
325 	info("connection from %s:%s", host, port);
326 
327 	return connfd;
328 }
329 
330 int process_request(int listenfd)
331 {
332 	pid_t childpid;
333 	int connfd;
334 
335 	connfd = do_accept(listenfd);
336 	if (connfd < 0)
337 		return -1;
338 	childpid = fork();
339 	if (childpid == 0) {
340 		close(listenfd);
341 		recv_pdu(connfd);
342 		exit(0);
343 	}
344 	close(connfd);
345 	return 0;
346 }
347 
348 static void addrinfo_to_text(struct addrinfo *ai, char buf[],
349 			     const size_t buf_size)
350 {
351 	char hbuf[NI_MAXHOST];
352 	char sbuf[NI_MAXSERV];
353 	int rc;
354 
355 	buf[0] = '\0';
356 
357 	rc = getnameinfo(ai->ai_addr, ai->ai_addrlen, hbuf, sizeof(hbuf),
358 			 sbuf, sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV);
359 	if (rc)
360 		err("getnameinfo: %s", gai_strerror(rc));
361 
362 	snprintf(buf, buf_size, "%s:%s", hbuf, sbuf);
363 }
364 
365 static int listen_all_addrinfo(struct addrinfo *ai_head, int sockfdlist[],
366 			     int maxsockfd)
367 {
368 	struct addrinfo *ai;
369 	int ret, nsockfd = 0;
370 	const size_t ai_buf_size = NI_MAXHOST + NI_MAXSERV + 2;
371 	char ai_buf[ai_buf_size];
372 
373 	for (ai = ai_head; ai && nsockfd < maxsockfd; ai = ai->ai_next) {
374 		int sock;
375 
376 		addrinfo_to_text(ai, ai_buf, ai_buf_size);
377 		dbg("opening %s", ai_buf);
378 		sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
379 		if (sock < 0) {
380 			err("socket: %s: %d (%s)",
381 			    ai_buf, errno, strerror(errno));
382 			continue;
383 		}
384 
385 		usbip_net_set_reuseaddr(sock);
386 		usbip_net_set_nodelay(sock);
387 		/* We use seperate sockets for IPv4 and IPv6
388 		 * (see do_standalone_mode()) */
389 		usbip_net_set_v6only(sock);
390 
391 		if (sock >= FD_SETSIZE) {
392 			err("FD_SETSIZE: %s: sock=%d, max=%d",
393 			    ai_buf, sock, FD_SETSIZE);
394 			close(sock);
395 			continue;
396 		}
397 
398 		ret = bind(sock, ai->ai_addr, ai->ai_addrlen);
399 		if (ret < 0) {
400 			err("bind: %s: %d (%s)",
401 			    ai_buf, errno, strerror(errno));
402 			close(sock);
403 			continue;
404 		}
405 
406 		ret = listen(sock, SOMAXCONN);
407 		if (ret < 0) {
408 			err("listen: %s: %d (%s)",
409 			    ai_buf, errno, strerror(errno));
410 			close(sock);
411 			continue;
412 		}
413 
414 		info("listening on %s", ai_buf);
415 		sockfdlist[nsockfd++] = sock;
416 	}
417 
418 	return nsockfd;
419 }
420 
421 static struct addrinfo *do_getaddrinfo(char *host, int ai_family)
422 {
423 	struct addrinfo hints, *ai_head;
424 	int rc;
425 
426 	memset(&hints, 0, sizeof(hints));
427 	hints.ai_family   = ai_family;
428 	hints.ai_socktype = SOCK_STREAM;
429 	hints.ai_flags    = AI_PASSIVE;
430 
431 	rc = getaddrinfo(host, usbip_port_string, &hints, &ai_head);
432 	if (rc) {
433 		err("failed to get a network address %s: %s", usbip_port_string,
434 		    gai_strerror(rc));
435 		return NULL;
436 	}
437 
438 	return ai_head;
439 }
440 
441 static void signal_handler(int i)
442 {
443 	dbg("received '%s' signal", strsignal(i));
444 }
445 
446 static void set_signal(void)
447 {
448 	struct sigaction act;
449 
450 	memset(&act, 0, sizeof(act));
451 	act.sa_handler = signal_handler;
452 	sigemptyset(&act.sa_mask);
453 	sigaction(SIGTERM, &act, NULL);
454 	sigaction(SIGINT, &act, NULL);
455 	act.sa_handler = SIG_IGN;
456 	sigaction(SIGCLD, &act, NULL);
457 }
458 
459 static const char *pid_file;
460 
461 static void write_pid_file(void)
462 {
463 	if (pid_file) {
464 		dbg("creating pid file %s", pid_file);
465 		FILE *fp;
466 
467 		fp = fopen(pid_file, "w");
468 		if (!fp) {
469 			err("pid_file: %s: %d (%s)",
470 			    pid_file, errno, strerror(errno));
471 			return;
472 		}
473 		fprintf(fp, "%d\n", getpid());
474 		fclose(fp);
475 	}
476 }
477 
478 static void remove_pid_file(void)
479 {
480 	if (pid_file) {
481 		dbg("removing pid file %s", pid_file);
482 		unlink(pid_file);
483 	}
484 }
485 
486 static int do_standalone_mode(int daemonize, int ipv4, int ipv6)
487 {
488 	struct addrinfo *ai_head;
489 	int sockfdlist[MAXSOCKFD];
490 	int nsockfd, family;
491 	int i, terminate;
492 	struct pollfd *fds;
493 	struct timespec timeout;
494 	sigset_t sigmask;
495 
496 	if (usbip_host_driver_open()) {
497 		err("please load " USBIP_CORE_MOD_NAME ".ko and "
498 		    USBIP_HOST_DRV_NAME ".ko!");
499 		return -1;
500 	}
501 
502 	if (daemonize) {
503 		if (daemon(0, 0) < 0) {
504 			err("daemonizing failed: %s", strerror(errno));
505 			usbip_host_driver_close();
506 			return -1;
507 		}
508 		umask(0);
509 		usbip_use_syslog = 1;
510 	}
511 	set_signal();
512 	write_pid_file();
513 
514 	info("starting " PROGNAME " (%s)", usbip_version_string);
515 
516 	/*
517 	 * To suppress warnings on systems with bindv6only disabled
518 	 * (default), we use seperate sockets for IPv6 and IPv4 and set
519 	 * IPV6_V6ONLY on the IPv6 sockets.
520 	 */
521 	if (ipv4 && ipv6)
522 		family = AF_UNSPEC;
523 	else if (ipv4)
524 		family = AF_INET;
525 	else
526 		family = AF_INET6;
527 
528 	ai_head = do_getaddrinfo(NULL, family);
529 	if (!ai_head) {
530 		usbip_host_driver_close();
531 		return -1;
532 	}
533 	nsockfd = listen_all_addrinfo(ai_head, sockfdlist,
534 		sizeof(sockfdlist) / sizeof(*sockfdlist));
535 	freeaddrinfo(ai_head);
536 	if (nsockfd <= 0) {
537 		err("failed to open a listening socket");
538 		usbip_host_driver_close();
539 		return -1;
540 	}
541 
542 	dbg("listening on %d address%s", nsockfd, (nsockfd == 1) ? "" : "es");
543 
544 	fds = calloc(nsockfd, sizeof(struct pollfd));
545 	for (i = 0; i < nsockfd; i++) {
546 		fds[i].fd = sockfdlist[i];
547 		fds[i].events = POLLIN;
548 	}
549 	timeout.tv_sec = MAIN_LOOP_TIMEOUT;
550 	timeout.tv_nsec = 0;
551 
552 	sigfillset(&sigmask);
553 	sigdelset(&sigmask, SIGTERM);
554 	sigdelset(&sigmask, SIGINT);
555 
556 	terminate = 0;
557 	while (!terminate) {
558 		int r;
559 
560 		r = ppoll(fds, nsockfd, &timeout, &sigmask);
561 		if (r < 0) {
562 			dbg("%s", strerror(errno));
563 			terminate = 1;
564 		} else if (r) {
565 			for (i = 0; i < nsockfd; i++) {
566 				if (fds[i].revents & POLLIN) {
567 					dbg("read event on fd[%d]=%d",
568 					    i, sockfdlist[i]);
569 					process_request(sockfdlist[i]);
570 				}
571 			}
572 		} else {
573 			dbg("heartbeat timeout on ppoll()");
574 		}
575 	}
576 
577 	info("shutting down " PROGNAME);
578 	free(fds);
579 	usbip_host_driver_close();
580 
581 	return 0;
582 }
583 
584 int main(int argc, char *argv[])
585 {
586 	static const struct option longopts[] = {
587 		{ "ipv4",     no_argument,       NULL, '4' },
588 		{ "ipv6",     no_argument,       NULL, '6' },
589 		{ "daemon",   no_argument,       NULL, 'D' },
590 		{ "daemon",   no_argument,       NULL, 'D' },
591 		{ "debug",    no_argument,       NULL, 'd' },
592 		{ "pid",      optional_argument, NULL, 'P' },
593 		{ "tcp-port", required_argument, NULL, 't' },
594 		{ "help",     no_argument,       NULL, 'h' },
595 		{ "version",  no_argument,       NULL, 'v' },
596 		{ NULL,	      0,                 NULL,  0  }
597 	};
598 
599 	enum {
600 		cmd_standalone_mode = 1,
601 		cmd_help,
602 		cmd_version
603 	} cmd;
604 
605 	int daemonize = 0;
606 	int ipv4 = 0, ipv6 = 0;
607 	int opt, rc = -1;
608 
609 	pid_file = NULL;
610 
611 	usbip_use_stderr = 1;
612 	usbip_use_syslog = 0;
613 
614 	if (geteuid() != 0)
615 		err("not running as root?");
616 
617 	cmd = cmd_standalone_mode;
618 	for (;;) {
619 		opt = getopt_long(argc, argv, "46DdP::t:hv", longopts, NULL);
620 
621 		if (opt == -1)
622 			break;
623 
624 		switch (opt) {
625 		case '4':
626 			ipv4 = 1;
627 			break;
628 		case '6':
629 			ipv6 = 1;
630 			break;
631 		case 'D':
632 			daemonize = 1;
633 			break;
634 		case 'd':
635 			usbip_use_debug = 1;
636 			break;
637 		case 'h':
638 			cmd = cmd_help;
639 			break;
640 		case 'P':
641 			pid_file = optarg ? optarg : DEFAULT_PID_FILE;
642 			break;
643 		case 't':
644 			usbip_setup_port_number(optarg);
645 			break;
646 		case 'v':
647 			cmd = cmd_version;
648 			break;
649 		case '?':
650 			usbipd_help();
651 		default:
652 			goto err_out;
653 		}
654 	}
655 
656 	if (!ipv4 && !ipv6)
657 		ipv4 = ipv6 = 1;
658 
659 	switch (cmd) {
660 	case cmd_standalone_mode:
661 		rc = do_standalone_mode(daemonize, ipv4, ipv6);
662 		remove_pid_file();
663 		break;
664 	case cmd_version:
665 		printf(PROGNAME " (%s)\n", usbip_version_string);
666 		rc = 0;
667 		break;
668 	case cmd_help:
669 		usbipd_help();
670 		rc = 0;
671 		break;
672 	default:
673 		usbipd_help();
674 		goto err_out;
675 	}
676 
677 err_out:
678 	return (rc > -1 ? EXIT_SUCCESS : EXIT_FAILURE);
679 }
680