]> git.proxmox.com Git - mirror_qemu.git/blob - scsi/qemu-pr-helper.c
scsi: build qemu-pr-helper
[mirror_qemu.git] / scsi / qemu-pr-helper.c
1 /*
2 * Privileged helper to handle persistent reservation commands for QEMU
3 *
4 * Copyright (C) 2017 Red Hat, Inc. <pbonzini@redhat.com>
5 *
6 * Author: Paolo Bonzini <pbonzini@redhat.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; under version 2 of the License.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "qemu/osdep.h"
22 #include <getopt.h>
23 #include <sys/ioctl.h>
24 #include <linux/dm-ioctl.h>
25 #include <scsi/sg.h>
26
27 #ifdef CONFIG_LIBCAP
28 #include <cap-ng.h>
29 #endif
30 #include <pwd.h>
31 #include <grp.h>
32
33 #include "qapi/error.h"
34 #include "qemu-common.h"
35 #include "qemu/cutils.h"
36 #include "qemu/main-loop.h"
37 #include "qemu/error-report.h"
38 #include "qemu/config-file.h"
39 #include "qemu/bswap.h"
40 #include "qemu/log.h"
41 #include "qemu/systemd.h"
42 #include "qapi/util.h"
43 #include "qapi/qmp/qstring.h"
44 #include "io/channel-socket.h"
45 #include "trace/control.h"
46 #include "qemu-version.h"
47
48 #include "block/aio.h"
49 #include "block/thread-pool.h"
50
51 #include "scsi/constants.h"
52 #include "scsi/utils.h"
53 #include "pr-helper.h"
54
55 #define PR_OUT_FIXED_PARAM_SIZE 24
56
57 static char *socket_path;
58 static char *pidfile;
59 static enum { RUNNING, TERMINATE, TERMINATING } state;
60 static QIOChannelSocket *server_ioc;
61 static int server_watch;
62 static int num_active_sockets = 1;
63 static int verbose;
64
65 #ifdef CONFIG_LIBCAP
66 static int uid = -1;
67 static int gid = -1;
68 #endif
69
70 static void usage(const char *name)
71 {
72 (printf) (
73 "Usage: %s [OPTIONS] FILE\n"
74 "Persistent Reservation helper program for QEMU\n"
75 "\n"
76 " -h, --help display this help and exit\n"
77 " -V, --version output version information and exit\n"
78 "\n"
79 " -d, --daemon run in the background\n"
80 " -f, --pidfile=PATH PID file when running as a daemon\n"
81 " (default '%s')\n"
82 " -k, --socket=PATH path to the unix socket\n"
83 " (default '%s')\n"
84 " -T, --trace [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
85 " specify tracing options\n"
86 #ifdef CONFIG_LIBCAP
87 " -u, --user=USER user to drop privileges to\n"
88 " -g, --group=GROUP group to drop privileges to\n"
89 #endif
90 "\n"
91 QEMU_HELP_BOTTOM "\n"
92 , name, pidfile, socket_path);
93 }
94
95 static void version(const char *name)
96 {
97 printf(
98 "%s " QEMU_VERSION QEMU_PKGVERSION "\n"
99 "Written by Paolo Bonzini.\n"
100 "\n"
101 QEMU_COPYRIGHT "\n"
102 "This is free software; see the source for copying conditions. There is NO\n"
103 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
104 , name);
105 }
106
107 static void write_pidfile(void)
108 {
109 int pidfd;
110 char pidstr[32];
111
112 pidfd = qemu_open(pidfile, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR);
113 if (pidfd == -1) {
114 error_report("Cannot open pid file, %s", strerror(errno));
115 exit(EXIT_FAILURE);
116 }
117
118 if (lockf(pidfd, F_TLOCK, 0)) {
119 error_report("Cannot lock pid file, %s", strerror(errno));
120 goto fail;
121 }
122 if (ftruncate(pidfd, 0)) {
123 error_report("Failed to truncate pid file");
124 goto fail;
125 }
126
127 snprintf(pidstr, sizeof(pidstr), "%d\n", getpid());
128 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
129 error_report("Failed to write pid file");
130 goto fail;
131 }
132 return;
133
134 fail:
135 unlink(pidfile);
136 close(pidfd);
137 exit(EXIT_FAILURE);
138 }
139
140 /* SG_IO support */
141
142 typedef struct PRHelperSGIOData {
143 int fd;
144 const uint8_t *cdb;
145 uint8_t *sense;
146 uint8_t *buf;
147 int sz; /* input/output */
148 int dir;
149 } PRHelperSGIOData;
150
151 static int do_sgio_worker(void *opaque)
152 {
153 PRHelperSGIOData *data = opaque;
154 struct sg_io_hdr io_hdr;
155 int ret;
156 int status;
157 SCSISense sense_code;
158
159 memset(data->sense, 0, PR_HELPER_SENSE_SIZE);
160 memset(&io_hdr, 0, sizeof(io_hdr));
161 io_hdr.interface_id = 'S';
162 io_hdr.cmd_len = PR_HELPER_CDB_SIZE;
163 io_hdr.cmdp = (uint8_t *)data->cdb;
164 io_hdr.sbp = data->sense;
165 io_hdr.mx_sb_len = PR_HELPER_SENSE_SIZE;
166 io_hdr.timeout = 1;
167 io_hdr.dxfer_direction = data->dir;
168 io_hdr.dxferp = (char *)data->buf;
169 io_hdr.dxfer_len = data->sz;
170 ret = ioctl(data->fd, SG_IO, &io_hdr);
171 status = sg_io_sense_from_errno(ret < 0 ? errno : 0, &io_hdr,
172 &sense_code);
173 if (status == GOOD) {
174 data->sz -= io_hdr.resid;
175 } else {
176 data->sz = 0;
177 }
178
179 if (status == CHECK_CONDITION &&
180 !(io_hdr.driver_status & SG_ERR_DRIVER_SENSE)) {
181 scsi_build_sense(data->sense, sense_code);
182 }
183
184 return status;
185 }
186
187 static int do_sgio(int fd, const uint8_t *cdb, uint8_t *sense,
188 uint8_t *buf, int *sz, int dir)
189 {
190 ThreadPool *pool = aio_get_thread_pool(qemu_get_aio_context());
191 int r;
192
193 PRHelperSGIOData data = {
194 .fd = fd,
195 .cdb = cdb,
196 .sense = sense,
197 .buf = buf,
198 .sz = *sz,
199 .dir = dir,
200 };
201
202 r = thread_pool_submit_co(pool, do_sgio_worker, &data);
203 *sz = data.sz;
204 return r;
205 }
206
207 static int do_pr_in(int fd, const uint8_t *cdb, uint8_t *sense,
208 uint8_t *data, int *resp_sz)
209 {
210 return do_sgio(fd, cdb, sense, data, resp_sz,
211 SG_DXFER_FROM_DEV);
212 }
213
214 static int do_pr_out(int fd, const uint8_t *cdb, uint8_t *sense,
215 const uint8_t *param, int sz)
216 {
217 int resp_sz = sz;
218 return do_sgio(fd, cdb, sense, (uint8_t *)param, &resp_sz,
219 SG_DXFER_TO_DEV);
220 }
221
222 /* Client */
223
224 typedef struct PRHelperClient {
225 QIOChannelSocket *ioc;
226 Coroutine *co;
227 int fd;
228 uint8_t data[PR_HELPER_DATA_SIZE];
229 } PRHelperClient;
230
231 typedef struct PRHelperRequest {
232 int fd;
233 size_t sz;
234 uint8_t cdb[PR_HELPER_CDB_SIZE];
235 } PRHelperRequest;
236
237 static int coroutine_fn prh_read(PRHelperClient *client, void *buf, int sz,
238 Error **errp)
239 {
240 int ret = 0;
241
242 while (sz > 0) {
243 int *fds = NULL;
244 size_t nfds = 0;
245 int i;
246 struct iovec iov;
247 ssize_t n_read;
248
249 iov.iov_base = buf;
250 iov.iov_len = sz;
251 n_read = qio_channel_readv_full(QIO_CHANNEL(client->ioc), &iov, 1,
252 &fds, &nfds, errp);
253
254 if (n_read == QIO_CHANNEL_ERR_BLOCK) {
255 qio_channel_yield(QIO_CHANNEL(client->ioc), G_IO_IN);
256 continue;
257 }
258 if (n_read <= 0) {
259 ret = n_read ? n_read : -1;
260 goto err;
261 }
262
263 /* Stash one file descriptor per request. */
264 if (nfds) {
265 bool too_many = false;
266 for (i = 0; i < nfds; i++) {
267 if (client->fd == -1) {
268 client->fd = fds[i];
269 } else {
270 close(fds[i]);
271 too_many = true;
272 }
273 }
274 g_free(fds);
275 if (too_many) {
276 ret = -1;
277 goto err;
278 }
279 }
280
281 buf += n_read;
282 sz -= n_read;
283 }
284
285 return 0;
286
287 err:
288 if (client->fd != -1) {
289 close(client->fd);
290 client->fd = -1;
291 }
292 return ret;
293 }
294
295 static int coroutine_fn prh_read_request(PRHelperClient *client,
296 PRHelperRequest *req,
297 PRHelperResponse *resp, Error **errp)
298 {
299 uint32_t sz;
300
301 if (prh_read(client, req->cdb, sizeof(req->cdb), NULL) < 0) {
302 return -1;
303 }
304
305 if (client->fd == -1) {
306 error_setg(errp, "No file descriptor in request.");
307 return -1;
308 }
309
310 if (req->cdb[0] != PERSISTENT_RESERVE_OUT &&
311 req->cdb[0] != PERSISTENT_RESERVE_IN) {
312 error_setg(errp, "Invalid CDB, closing socket.");
313 goto out_close;
314 }
315
316 sz = scsi_cdb_xfer(req->cdb);
317 if (sz > sizeof(client->data)) {
318 goto out_close;
319 }
320
321 if (req->cdb[0] == PERSISTENT_RESERVE_OUT) {
322 if (qio_channel_read_all(QIO_CHANNEL(client->ioc),
323 (char *)client->data, sz,
324 errp) < 0) {
325 goto out_close;
326 }
327 if ((fcntl(client->fd, F_GETFL) & O_ACCMODE) == O_RDONLY) {
328 scsi_build_sense(resp->sense, SENSE_CODE(INVALID_OPCODE));
329 sz = 0;
330 } else if (sz < PR_OUT_FIXED_PARAM_SIZE) {
331 /* Illegal request, Parameter list length error. This isn't fatal;
332 * we have read the data, send an error without closing the socket.
333 */
334 scsi_build_sense(resp->sense, SENSE_CODE(INVALID_PARAM_LEN));
335 sz = 0;
336 }
337 if (sz == 0) {
338 resp->result = CHECK_CONDITION;
339 close(client->fd);
340 client->fd = -1;
341 }
342 }
343
344 req->fd = client->fd;
345 req->sz = sz;
346 client->fd = -1;
347 return sz;
348
349 out_close:
350 close(client->fd);
351 client->fd = -1;
352 return -1;
353 }
354
355 static int coroutine_fn prh_write_response(PRHelperClient *client,
356 PRHelperRequest *req,
357 PRHelperResponse *resp, Error **errp)
358 {
359 ssize_t r;
360 size_t sz;
361
362 if (req->cdb[0] == PERSISTENT_RESERVE_IN && resp->result == GOOD) {
363 assert(resp->sz <= req->sz && resp->sz <= sizeof(client->data));
364 } else {
365 assert(resp->sz == 0);
366 }
367
368 sz = resp->sz;
369
370 resp->result = cpu_to_be32(resp->result);
371 resp->sz = cpu_to_be32(resp->sz);
372 r = qio_channel_write_all(QIO_CHANNEL(client->ioc),
373 (char *) resp, sizeof(*resp), errp);
374 if (r < 0) {
375 return r;
376 }
377
378 r = qio_channel_write_all(QIO_CHANNEL(client->ioc),
379 (char *) client->data,
380 sz, errp);
381 return r < 0 ? r : 0;
382 }
383
384 static void coroutine_fn prh_co_entry(void *opaque)
385 {
386 PRHelperClient *client = opaque;
387 Error *local_err = NULL;
388 uint32_t flags;
389 int r;
390
391 qio_channel_set_blocking(QIO_CHANNEL(client->ioc),
392 false, NULL);
393 qio_channel_attach_aio_context(QIO_CHANNEL(client->ioc),
394 qemu_get_aio_context());
395
396 /* A very simple negotiation for future extensibility. No features
397 * are defined so write 0.
398 */
399 flags = cpu_to_be32(0);
400 r = qio_channel_write_all(QIO_CHANNEL(client->ioc),
401 (char *) &flags, sizeof(flags), NULL);
402 if (r < 0) {
403 goto out;
404 }
405
406 r = qio_channel_read_all(QIO_CHANNEL(client->ioc),
407 (char *) &flags, sizeof(flags), NULL);
408 if (be32_to_cpu(flags) != 0 || r < 0) {
409 goto out;
410 }
411
412 while (atomic_read(&state) == RUNNING) {
413 PRHelperRequest req;
414 PRHelperResponse resp;
415 int sz;
416
417 sz = prh_read_request(client, &req, &resp, &local_err);
418 if (sz < 0) {
419 break;
420 }
421
422 if (sz > 0) {
423 num_active_sockets++;
424 if (req.cdb[0] == PERSISTENT_RESERVE_OUT) {
425 r = do_pr_out(req.fd, req.cdb, resp.sense,
426 client->data, sz);
427 resp.sz = 0;
428 } else {
429 resp.sz = sizeof(client->data);
430 r = do_pr_in(req.fd, req.cdb, resp.sense,
431 client->data, &resp.sz);
432 resp.sz = MIN(resp.sz, sz);
433 }
434 num_active_sockets--;
435 close(req.fd);
436 if (r == -1) {
437 break;
438 }
439 resp.result = r;
440 }
441
442 if (prh_write_response(client, &req, &resp, &local_err) < 0) {
443 break;
444 }
445 }
446
447 if (local_err) {
448 if (verbose == 0) {
449 error_free(local_err);
450 } else {
451 error_report_err(local_err);
452 }
453 }
454
455 out:
456 qio_channel_detach_aio_context(QIO_CHANNEL(client->ioc));
457 object_unref(OBJECT(client->ioc));
458 g_free(client);
459 }
460
461 static gboolean accept_client(QIOChannel *ioc, GIOCondition cond, gpointer opaque)
462 {
463 QIOChannelSocket *cioc;
464 PRHelperClient *prh;
465
466 cioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc),
467 NULL);
468 if (!cioc) {
469 return TRUE;
470 }
471
472 prh = g_new(PRHelperClient, 1);
473 prh->ioc = cioc;
474 prh->fd = -1;
475 prh->co = qemu_coroutine_create(prh_co_entry, prh);
476 qemu_coroutine_enter(prh->co);
477
478 return TRUE;
479 }
480
481
482 /*
483 * Check socket parameters compatibility when socket activation is used.
484 */
485 static const char *socket_activation_validate_opts(void)
486 {
487 if (socket_path != NULL) {
488 return "Unix socket can't be set when using socket activation";
489 }
490
491 return NULL;
492 }
493
494 static void compute_default_paths(void)
495 {
496 if (!socket_path) {
497 socket_path = qemu_get_local_state_pathname("run/qemu-pr-helper.sock");
498 }
499 }
500
501 static void termsig_handler(int signum)
502 {
503 atomic_cmpxchg(&state, RUNNING, TERMINATE);
504 qemu_notify_event();
505 }
506
507 static void close_server_socket(void)
508 {
509 assert(server_ioc);
510
511 g_source_remove(server_watch);
512 server_watch = -1;
513 object_unref(OBJECT(server_ioc));
514 num_active_sockets--;
515 }
516
517 #ifdef CONFIG_LIBCAP
518 static int drop_privileges(void)
519 {
520 /* clear all capabilities */
521 capng_clear(CAPNG_SELECT_BOTH);
522
523 if (capng_update(CAPNG_ADD, CAPNG_EFFECTIVE | CAPNG_PERMITTED,
524 CAP_SYS_RAWIO) < 0) {
525 return -1;
526 }
527
528 /* Change user/group id, retaining the capabilities. Because file descriptors
529 * are passed via SCM_RIGHTS, we don't need supplementary groups (and in
530 * fact the helper can run as "nobody").
531 */
532 if (capng_change_id(uid != -1 ? uid : getuid(),
533 gid != -1 ? gid : getgid(),
534 CAPNG_DROP_SUPP_GRP | CAPNG_CLEAR_BOUNDING)) {
535 return -1;
536 }
537
538 return 0;
539 }
540 #endif
541
542 int main(int argc, char **argv)
543 {
544 const char *sopt = "hVk:fdT:u:g:q";
545 struct option lopt[] = {
546 { "help", no_argument, NULL, 'h' },
547 { "version", no_argument, NULL, 'V' },
548 { "socket", required_argument, NULL, 'k' },
549 { "pidfile", no_argument, NULL, 'f' },
550 { "daemon", no_argument, NULL, 'd' },
551 { "trace", required_argument, NULL, 'T' },
552 { "user", required_argument, NULL, 'u' },
553 { "group", required_argument, NULL, 'g' },
554 { "quiet", no_argument, NULL, 'q' },
555 { NULL, 0, NULL, 0 }
556 };
557 int opt_ind = 0;
558 int quiet = 0;
559 int ch;
560 Error *local_err = NULL;
561 char *trace_file = NULL;
562 bool daemonize = false;
563 unsigned socket_activation;
564
565 struct sigaction sa_sigterm;
566 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
567 sa_sigterm.sa_handler = termsig_handler;
568 sigaction(SIGTERM, &sa_sigterm, NULL);
569 sigaction(SIGINT, &sa_sigterm, NULL);
570 sigaction(SIGHUP, &sa_sigterm, NULL);
571
572 signal(SIGPIPE, SIG_IGN);
573
574 module_call_init(MODULE_INIT_TRACE);
575 module_call_init(MODULE_INIT_QOM);
576 qemu_add_opts(&qemu_trace_opts);
577 qemu_init_exec_dir(argv[0]);
578
579 pidfile = qemu_get_local_state_pathname("run/qemu-pr-helper.pid");
580
581 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
582 switch (ch) {
583 case 'k':
584 socket_path = optarg;
585 if (socket_path[0] != '/') {
586 error_report("socket path must be absolute");
587 exit(EXIT_FAILURE);
588 }
589 break;
590 case 'f':
591 pidfile = optarg;
592 break;
593 #ifdef CONFIG_LIBCAP
594 case 'u': {
595 unsigned long res;
596 struct passwd *userinfo = getpwnam(optarg);
597 if (userinfo) {
598 uid = userinfo->pw_uid;
599 } else if (qemu_strtoul(optarg, NULL, 10, &res) == 0 &&
600 (uid_t)res == res) {
601 uid = res;
602 } else {
603 error_report("invalid user '%s'", optarg);
604 exit(EXIT_FAILURE);
605 }
606 break;
607 }
608 case 'g': {
609 unsigned long res;
610 struct group *groupinfo = getgrnam(optarg);
611 if (groupinfo) {
612 gid = groupinfo->gr_gid;
613 } else if (qemu_strtoul(optarg, NULL, 10, &res) == 0 &&
614 (gid_t)res == res) {
615 gid = res;
616 } else {
617 error_report("invalid group '%s'", optarg);
618 exit(EXIT_FAILURE);
619 }
620 break;
621 }
622 #else
623 case 'u':
624 case 'g':
625 error_report("-%c not supported by this %s", ch, argv[0]);
626 exit(1);
627 #endif
628 case 'd':
629 daemonize = true;
630 break;
631 case 'q':
632 quiet = 1;
633 break;
634 case 'T':
635 g_free(trace_file);
636 trace_file = trace_opt_parse(optarg);
637 break;
638 case 'V':
639 version(argv[0]);
640 exit(EXIT_SUCCESS);
641 break;
642 case 'h':
643 usage(argv[0]);
644 exit(EXIT_SUCCESS);
645 break;
646 case '?':
647 error_report("Try `%s --help' for more information.", argv[0]);
648 exit(EXIT_FAILURE);
649 }
650 }
651
652 /* set verbosity */
653 verbose = !quiet;
654
655 if (!trace_init_backends()) {
656 exit(EXIT_FAILURE);
657 }
658 trace_init_file(trace_file);
659 qemu_set_log(LOG_TRACE);
660
661 socket_activation = check_socket_activation();
662 if (socket_activation == 0) {
663 SocketAddress saddr;
664 compute_default_paths();
665 saddr = (SocketAddress){
666 .type = SOCKET_ADDRESS_TYPE_UNIX,
667 .u.q_unix.path = g_strdup(socket_path)
668 };
669 server_ioc = qio_channel_socket_new();
670 if (qio_channel_socket_listen_sync(server_ioc, &saddr, &local_err) < 0) {
671 object_unref(OBJECT(server_ioc));
672 error_report_err(local_err);
673 return 1;
674 }
675 g_free(saddr.u.q_unix.path);
676 } else {
677 /* Using socket activation - check user didn't use -p etc. */
678 const char *err_msg = socket_activation_validate_opts();
679 if (err_msg != NULL) {
680 error_report("%s", err_msg);
681 exit(EXIT_FAILURE);
682 }
683
684 /* Can only listen on a single socket. */
685 if (socket_activation > 1) {
686 error_report("%s does not support socket activation with LISTEN_FDS > 1",
687 argv[0]);
688 exit(EXIT_FAILURE);
689 }
690 server_ioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD,
691 &local_err);
692 if (server_ioc == NULL) {
693 error_report("Failed to use socket activation: %s",
694 error_get_pretty(local_err));
695 exit(EXIT_FAILURE);
696 }
697 socket_path = NULL;
698 }
699
700 if (qemu_init_main_loop(&local_err)) {
701 error_report_err(local_err);
702 exit(EXIT_FAILURE);
703 }
704
705 server_watch = qio_channel_add_watch(QIO_CHANNEL(server_ioc),
706 G_IO_IN,
707 accept_client,
708 NULL, NULL);
709
710 #ifdef CONFIG_LIBCAP
711 if (drop_privileges() < 0) {
712 error_report("Failed to drop privileges: %s", strerror(errno));
713 exit(EXIT_FAILURE);
714 }
715 #endif
716
717 if (daemonize) {
718 if (daemon(0, 0) < 0) {
719 error_report("Failed to daemonize: %s", strerror(errno));
720 exit(EXIT_FAILURE);
721 }
722 write_pidfile();
723 }
724
725 state = RUNNING;
726 do {
727 main_loop_wait(false);
728 if (state == TERMINATE) {
729 state = TERMINATING;
730 close_server_socket();
731 }
732 } while (num_active_sockets > 0);
733
734 exit(EXIT_SUCCESS);
735 }