pr-helper: avoid error on PR IN command with zero request size
[qemu/ericb.git] / scsi / qemu-pr-helper.c
blobc89a446a45ad61d6d224b7e25161cbe28ae97c35
1 /*
2 * Privileged helper to handle persistent reservation commands for QEMU
4 * Copyright (C) 2017 Red Hat, Inc. <pbonzini@redhat.com>
6 * Author: Paolo Bonzini <pbonzini@redhat.com>
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.
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.
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/>.
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>
27 #ifdef CONFIG_LIBCAP
28 #include <cap-ng.h>
29 #endif
30 #include <pwd.h>
31 #include <grp.h>
33 #ifdef CONFIG_MPATH
34 #include <libudev.h>
35 #include <mpath_cmd.h>
36 #include <mpath_persist.h>
37 #endif
39 #include "qapi/error.h"
40 #include "qemu-common.h"
41 #include "qemu/cutils.h"
42 #include "qemu/main-loop.h"
43 #include "qemu/error-report.h"
44 #include "qemu/config-file.h"
45 #include "qemu/bswap.h"
46 #include "qemu/log.h"
47 #include "qemu/systemd.h"
48 #include "qapi/util.h"
49 #include "qapi/qmp/qstring.h"
50 #include "io/channel-socket.h"
51 #include "trace/control.h"
52 #include "qemu-version.h"
54 #include "block/aio.h"
55 #include "block/thread-pool.h"
57 #include "scsi/constants.h"
58 #include "scsi/utils.h"
59 #include "pr-helper.h"
61 #define PR_OUT_FIXED_PARAM_SIZE 24
63 static char *socket_path;
64 static char *pidfile;
65 static enum { RUNNING, TERMINATE, TERMINATING } state;
66 static QIOChannelSocket *server_ioc;
67 static int server_watch;
68 static int num_active_sockets = 1;
69 static int noisy;
70 static int verbose;
72 #ifdef CONFIG_LIBCAP
73 static int uid = -1;
74 static int gid = -1;
75 #endif
77 static void compute_default_paths(void)
79 if (!socket_path) {
80 socket_path = qemu_get_local_state_pathname("run/qemu-pr-helper.sock");
84 static void usage(const char *name)
86 compute_default_paths();
87 (printf) (
88 "Usage: %s [OPTIONS] FILE\n"
89 "Persistent Reservation helper program for QEMU\n"
90 "\n"
91 " -h, --help display this help and exit\n"
92 " -V, --version output version information and exit\n"
93 "\n"
94 " -d, --daemon run in the background\n"
95 " -f, --pidfile=PATH PID file when running as a daemon\n"
96 " (default '%s')\n"
97 " -k, --socket=PATH path to the unix socket\n"
98 " (default '%s')\n"
99 " -T, --trace [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
100 " specify tracing options\n"
101 #ifdef CONFIG_LIBCAP
102 " -u, --user=USER user to drop privileges to\n"
103 " -g, --group=GROUP group to drop privileges to\n"
104 #endif
105 "\n"
106 QEMU_HELP_BOTTOM "\n"
107 , name, pidfile, socket_path);
110 static void version(const char *name)
112 printf(
113 "%s " QEMU_FULL_VERSION "\n"
114 "Written by Paolo Bonzini.\n"
115 "\n"
116 QEMU_COPYRIGHT "\n"
117 "This is free software; see the source for copying conditions. There is NO\n"
118 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
119 , name);
122 static void write_pidfile(void)
124 int pidfd;
125 char pidstr[32];
127 pidfd = qemu_open(pidfile, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR);
128 if (pidfd == -1) {
129 error_report("Cannot open pid file, %s", strerror(errno));
130 exit(EXIT_FAILURE);
133 if (lockf(pidfd, F_TLOCK, 0)) {
134 error_report("Cannot lock pid file, %s", strerror(errno));
135 goto fail;
137 if (ftruncate(pidfd, 0)) {
138 error_report("Failed to truncate pid file");
139 goto fail;
142 snprintf(pidstr, sizeof(pidstr), "%d\n", getpid());
143 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
144 error_report("Failed to write pid file");
145 goto fail;
147 return;
149 fail:
150 unlink(pidfile);
151 close(pidfd);
152 exit(EXIT_FAILURE);
155 /* SG_IO support */
157 typedef struct PRHelperSGIOData {
158 int fd;
159 const uint8_t *cdb;
160 uint8_t *sense;
161 uint8_t *buf;
162 int sz; /* input/output */
163 int dir;
164 } PRHelperSGIOData;
166 static int do_sgio_worker(void *opaque)
168 PRHelperSGIOData *data = opaque;
169 struct sg_io_hdr io_hdr;
170 int ret;
171 int status;
172 SCSISense sense_code;
174 memset(data->sense, 0, PR_HELPER_SENSE_SIZE);
175 memset(&io_hdr, 0, sizeof(io_hdr));
176 io_hdr.interface_id = 'S';
177 io_hdr.cmd_len = PR_HELPER_CDB_SIZE;
178 io_hdr.cmdp = (uint8_t *)data->cdb;
179 io_hdr.sbp = data->sense;
180 io_hdr.mx_sb_len = PR_HELPER_SENSE_SIZE;
181 io_hdr.timeout = 1;
182 io_hdr.dxfer_direction = data->dir;
183 io_hdr.dxferp = (char *)data->buf;
184 io_hdr.dxfer_len = data->sz;
185 ret = ioctl(data->fd, SG_IO, &io_hdr);
186 status = sg_io_sense_from_errno(ret < 0 ? errno : 0, &io_hdr,
187 &sense_code);
188 if (status == GOOD) {
189 data->sz -= io_hdr.resid;
190 } else {
191 data->sz = 0;
194 if (status == CHECK_CONDITION &&
195 !(io_hdr.driver_status & SG_ERR_DRIVER_SENSE)) {
196 scsi_build_sense(data->sense, sense_code);
199 return status;
202 static int do_sgio(int fd, const uint8_t *cdb, uint8_t *sense,
203 uint8_t *buf, int *sz, int dir)
205 ThreadPool *pool = aio_get_thread_pool(qemu_get_aio_context());
206 int r;
208 PRHelperSGIOData data = {
209 .fd = fd,
210 .cdb = cdb,
211 .sense = sense,
212 .buf = buf,
213 .sz = *sz,
214 .dir = dir,
217 r = thread_pool_submit_co(pool, do_sgio_worker, &data);
218 *sz = data.sz;
219 return r;
222 /* Device mapper interface */
224 #ifdef CONFIG_MPATH
225 #define CONTROL_PATH "/dev/mapper/control"
227 typedef struct DMData {
228 struct dm_ioctl dm;
229 uint8_t data[1024];
230 } DMData;
232 static int control_fd;
234 static void *dm_ioctl(int ioc, struct dm_ioctl *dm)
236 static DMData d;
237 memcpy(&d.dm, dm, sizeof(d.dm));
238 QEMU_BUILD_BUG_ON(sizeof(d.data) < sizeof(struct dm_target_spec));
240 d.dm.version[0] = DM_VERSION_MAJOR;
241 d.dm.version[1] = 0;
242 d.dm.version[2] = 0;
243 d.dm.data_size = 1024;
244 d.dm.data_start = offsetof(DMData, data);
245 if (ioctl(control_fd, ioc, &d) < 0) {
246 return NULL;
248 memcpy(dm, &d.dm, sizeof(d.dm));
249 return &d.data;
252 static void *dm_dev_ioctl(int fd, int ioc, struct dm_ioctl *dm)
254 struct stat st;
255 int r;
257 r = fstat(fd, &st);
258 if (r < 0) {
259 perror("fstat");
260 exit(1);
263 dm->dev = st.st_rdev;
264 return dm_ioctl(ioc, dm);
267 static void dm_init(void)
269 control_fd = open(CONTROL_PATH, O_RDWR);
270 if (control_fd < 0) {
271 perror("Cannot open " CONTROL_PATH);
272 exit(1);
274 struct dm_ioctl dm = { 0 };
275 if (!dm_ioctl(DM_VERSION, &dm)) {
276 perror("ioctl");
277 exit(1);
279 if (dm.version[0] != DM_VERSION_MAJOR) {
280 fprintf(stderr, "Unsupported device mapper interface");
281 exit(1);
285 /* Variables required by libmultipath and libmpathpersist. */
286 QEMU_BUILD_BUG_ON(PR_HELPER_DATA_SIZE > MPATH_MAX_PARAM_LEN);
287 static struct config *multipath_conf;
288 unsigned mpath_mx_alloc_len = PR_HELPER_DATA_SIZE;
289 int logsink;
290 struct udev *udev;
292 extern struct config *get_multipath_config(void);
293 struct config *get_multipath_config(void)
295 return multipath_conf;
298 extern void put_multipath_config(struct config *conf);
299 void put_multipath_config(struct config *conf)
303 static void multipath_pr_init(void)
305 udev = udev_new();
306 multipath_conf = mpath_lib_init();
309 static int is_mpath(int fd)
311 struct dm_ioctl dm = { .flags = DM_NOFLUSH_FLAG };
312 struct dm_target_spec *tgt;
314 tgt = dm_dev_ioctl(fd, DM_TABLE_STATUS, &dm);
315 if (!tgt) {
316 if (errno == ENXIO) {
317 return 0;
319 perror("ioctl");
320 exit(EXIT_FAILURE);
322 return !strncmp(tgt->target_type, "multipath", DM_MAX_TYPE_NAME);
325 static SCSISense mpath_generic_sense(int r)
327 switch (r) {
328 case MPATH_PR_SENSE_NOT_READY:
329 return SENSE_CODE(NOT_READY);
330 case MPATH_PR_SENSE_MEDIUM_ERROR:
331 return SENSE_CODE(READ_ERROR);
332 case MPATH_PR_SENSE_HARDWARE_ERROR:
333 return SENSE_CODE(TARGET_FAILURE);
334 case MPATH_PR_SENSE_ABORTED_COMMAND:
335 return SENSE_CODE(IO_ERROR);
336 default:
337 abort();
341 static int mpath_reconstruct_sense(int fd, int r, uint8_t *sense)
343 switch (r) {
344 case MPATH_PR_SUCCESS:
345 return GOOD;
346 case MPATH_PR_SENSE_NOT_READY:
347 case MPATH_PR_SENSE_MEDIUM_ERROR:
348 case MPATH_PR_SENSE_HARDWARE_ERROR:
349 case MPATH_PR_SENSE_ABORTED_COMMAND:
351 /* libmpathpersist ate the exact sense. Try to find it by
352 * issuing TEST UNIT READY.
354 uint8_t cdb[6] = { TEST_UNIT_READY };
355 int sz = 0;
356 int r = do_sgio(fd, cdb, sense, NULL, &sz, SG_DXFER_NONE);
358 if (r != GOOD) {
359 return r;
361 scsi_build_sense(sense, mpath_generic_sense(r));
362 return CHECK_CONDITION;
365 case MPATH_PR_SENSE_UNIT_ATTENTION:
366 /* Congratulations libmpathpersist, you ruined the Unit Attention...
367 * Return a heavyweight one.
369 scsi_build_sense(sense, SENSE_CODE(SCSI_BUS_RESET));
370 return CHECK_CONDITION;
371 case MPATH_PR_SENSE_INVALID_OP:
372 /* Only one valid sense. */
373 scsi_build_sense(sense, SENSE_CODE(INVALID_OPCODE));
374 return CHECK_CONDITION;
375 case MPATH_PR_ILLEGAL_REQ:
376 /* Guess. */
377 scsi_build_sense(sense, SENSE_CODE(INVALID_PARAM));
378 return CHECK_CONDITION;
379 case MPATH_PR_NO_SENSE:
380 scsi_build_sense(sense, SENSE_CODE(NO_SENSE));
381 return CHECK_CONDITION;
383 case MPATH_PR_RESERV_CONFLICT:
384 return RESERVATION_CONFLICT;
386 case MPATH_PR_OTHER:
387 default:
388 scsi_build_sense(sense, SENSE_CODE(LUN_COMM_FAILURE));
389 return CHECK_CONDITION;
393 static int multipath_pr_in(int fd, const uint8_t *cdb, uint8_t *sense,
394 uint8_t *data, int sz)
396 int rq_servact = cdb[1];
397 struct prin_resp resp;
398 size_t written;
399 int r;
401 switch (rq_servact) {
402 case MPATH_PRIN_RKEY_SA:
403 case MPATH_PRIN_RRES_SA:
404 case MPATH_PRIN_RCAP_SA:
405 break;
406 case MPATH_PRIN_RFSTAT_SA:
407 /* Nobody implements it anyway, so bail out. */
408 default:
409 /* Cannot parse any other output. */
410 scsi_build_sense(sense, SENSE_CODE(INVALID_FIELD));
411 return CHECK_CONDITION;
414 r = mpath_persistent_reserve_in(fd, rq_servact, &resp, noisy, verbose);
415 if (r == MPATH_PR_SUCCESS) {
416 switch (rq_servact) {
417 case MPATH_PRIN_RKEY_SA:
418 case MPATH_PRIN_RRES_SA: {
419 struct prin_readdescr *out = &resp.prin_descriptor.prin_readkeys;
420 assert(sz >= 8);
421 written = MIN(out->additional_length + 8, sz);
422 stl_be_p(&data[0], out->prgeneration);
423 stl_be_p(&data[4], out->additional_length);
424 memcpy(&data[8], out->key_list, written - 8);
425 break;
427 case MPATH_PRIN_RCAP_SA: {
428 struct prin_capdescr *out = &resp.prin_descriptor.prin_readcap;
429 assert(sz >= 6);
430 written = 6;
431 stw_be_p(&data[0], out->length);
432 data[2] = out->flags[0];
433 data[3] = out->flags[1];
434 stw_be_p(&data[4], out->pr_type_mask);
435 break;
437 default:
438 scsi_build_sense(sense, SENSE_CODE(INVALID_OPCODE));
439 return CHECK_CONDITION;
441 assert(written <= sz);
442 memset(data + written, 0, sz - written);
445 return mpath_reconstruct_sense(fd, r, sense);
448 static int multipath_pr_out(int fd, const uint8_t *cdb, uint8_t *sense,
449 const uint8_t *param, int sz)
451 int rq_servact = cdb[1];
452 int rq_scope = cdb[2] >> 4;
453 int rq_type = cdb[2] & 0xf;
454 struct prout_param_descriptor paramp;
455 char transportids[PR_HELPER_DATA_SIZE];
456 int r;
458 if (sz < PR_OUT_FIXED_PARAM_SIZE) {
459 /* Illegal request, Parameter list length error. This isn't fatal;
460 * we have read the data, send an error without closing the socket.
462 scsi_build_sense(sense, SENSE_CODE(INVALID_PARAM_LEN));
463 return CHECK_CONDITION;
466 switch (rq_servact) {
467 case MPATH_PROUT_REG_SA:
468 case MPATH_PROUT_RES_SA:
469 case MPATH_PROUT_REL_SA:
470 case MPATH_PROUT_CLEAR_SA:
471 case MPATH_PROUT_PREE_SA:
472 case MPATH_PROUT_PREE_AB_SA:
473 case MPATH_PROUT_REG_IGN_SA:
474 break;
475 case MPATH_PROUT_REG_MOV_SA:
476 /* Not supported by struct prout_param_descriptor. */
477 default:
478 /* Cannot parse any other input. */
479 scsi_build_sense(sense, SENSE_CODE(INVALID_FIELD));
480 return CHECK_CONDITION;
483 /* Convert input data, especially transport IDs, to the structs
484 * used by libmpathpersist (which, of course, will immediately
485 * do the opposite).
487 memset(&paramp, 0, sizeof(paramp));
488 memcpy(&paramp.key, &param[0], 8);
489 memcpy(&paramp.sa_key, &param[8], 8);
490 paramp.sa_flags = param[20];
491 if (sz > PR_OUT_FIXED_PARAM_SIZE) {
492 size_t transportid_len;
493 int i, j;
494 if (sz < PR_OUT_FIXED_PARAM_SIZE + 4) {
495 scsi_build_sense(sense, SENSE_CODE(INVALID_PARAM_LEN));
496 return CHECK_CONDITION;
498 transportid_len = ldl_be_p(&param[24]) + PR_OUT_FIXED_PARAM_SIZE + 4;
499 if (transportid_len > sz) {
500 scsi_build_sense(sense, SENSE_CODE(INVALID_PARAM));
501 return CHECK_CONDITION;
503 for (i = PR_OUT_FIXED_PARAM_SIZE + 4, j = 0; i < transportid_len; ) {
504 struct transportid *id = (struct transportid *) &transportids[j];
505 int len;
507 id->format_code = param[i] & 0xc0;
508 id->protocol_id = param[i] & 0x0f;
509 switch (param[i] & 0xcf) {
510 case 0:
511 /* FC transport. */
512 if (i + 24 > transportid_len) {
513 goto illegal_req;
515 memcpy(id->n_port_name, &param[i + 8], 8);
516 j += offsetof(struct transportid, n_port_name[8]);
517 i += 24;
518 break;
519 case 5:
520 case 0x45:
521 /* iSCSI transport. */
522 len = lduw_be_p(&param[i + 2]);
523 if (len > 252 || (len & 3) || i + len + 4 > transportid_len) {
524 /* For format code 00, the standard says the maximum is 223
525 * plus the NUL terminator. For format code 01 there is no
526 * maximum length, but libmpathpersist ignores the first
527 * byte of id->iscsi_name so our maximum is 252.
529 goto illegal_req;
531 if (memchr(&param[i + 4], 0, len) == NULL) {
532 goto illegal_req;
534 memcpy(id->iscsi_name, &param[i + 2], len + 2);
535 j += offsetof(struct transportid, iscsi_name[len + 2]);
536 i += len + 4;
537 break;
538 case 6:
539 /* SAS transport. */
540 if (i + 24 > transportid_len) {
541 goto illegal_req;
543 memcpy(id->sas_address, &param[i + 4], 8);
544 j += offsetof(struct transportid, sas_address[8]);
545 i += 24;
546 break;
547 default:
548 illegal_req:
549 scsi_build_sense(sense, SENSE_CODE(INVALID_PARAM));
550 return CHECK_CONDITION;
553 paramp.trnptid_list[paramp.num_transportid++] = id;
557 r = mpath_persistent_reserve_out(fd, rq_servact, rq_scope, rq_type,
558 &paramp, noisy, verbose);
559 return mpath_reconstruct_sense(fd, r, sense);
561 #endif
563 static int do_pr_in(int fd, const uint8_t *cdb, uint8_t *sense,
564 uint8_t *data, int *resp_sz)
566 #ifdef CONFIG_MPATH
567 if (is_mpath(fd)) {
568 /* multipath_pr_in fills the whole input buffer. */
569 int r = multipath_pr_in(fd, cdb, sense, data, *resp_sz);
570 if (r != GOOD) {
571 *resp_sz = 0;
573 return r;
575 #endif
577 return do_sgio(fd, cdb, sense, data, resp_sz,
578 SG_DXFER_FROM_DEV);
581 static int do_pr_out(int fd, const uint8_t *cdb, uint8_t *sense,
582 const uint8_t *param, int sz)
584 int resp_sz;
586 if ((fcntl(fd, F_GETFL) & O_ACCMODE) == O_RDONLY) {
587 scsi_build_sense(sense, SENSE_CODE(INVALID_OPCODE));
588 return CHECK_CONDITION;
591 #ifdef CONFIG_MPATH
592 if (is_mpath(fd)) {
593 return multipath_pr_out(fd, cdb, sense, param, sz);
595 #endif
597 resp_sz = sz;
598 return do_sgio(fd, cdb, sense, (uint8_t *)param, &resp_sz,
599 SG_DXFER_TO_DEV);
602 /* Client */
604 typedef struct PRHelperClient {
605 QIOChannelSocket *ioc;
606 Coroutine *co;
607 int fd;
608 uint8_t data[PR_HELPER_DATA_SIZE];
609 } PRHelperClient;
611 typedef struct PRHelperRequest {
612 int fd;
613 size_t sz;
614 uint8_t cdb[PR_HELPER_CDB_SIZE];
615 } PRHelperRequest;
617 static int coroutine_fn prh_read(PRHelperClient *client, void *buf, int sz,
618 Error **errp)
620 int ret = 0;
622 while (sz > 0) {
623 int *fds = NULL;
624 size_t nfds = 0;
625 int i;
626 struct iovec iov;
627 ssize_t n_read;
629 iov.iov_base = buf;
630 iov.iov_len = sz;
631 n_read = qio_channel_readv_full(QIO_CHANNEL(client->ioc), &iov, 1,
632 &fds, &nfds, errp);
634 if (n_read == QIO_CHANNEL_ERR_BLOCK) {
635 qio_channel_yield(QIO_CHANNEL(client->ioc), G_IO_IN);
636 continue;
638 if (n_read <= 0) {
639 ret = n_read ? n_read : -1;
640 goto err;
643 /* Stash one file descriptor per request. */
644 if (nfds) {
645 bool too_many = false;
646 for (i = 0; i < nfds; i++) {
647 if (client->fd == -1) {
648 client->fd = fds[i];
649 } else {
650 close(fds[i]);
651 too_many = true;
654 g_free(fds);
655 if (too_many) {
656 ret = -1;
657 goto err;
661 buf += n_read;
662 sz -= n_read;
665 return 0;
667 err:
668 if (client->fd != -1) {
669 close(client->fd);
670 client->fd = -1;
672 return ret;
675 static int coroutine_fn prh_read_request(PRHelperClient *client,
676 PRHelperRequest *req,
677 PRHelperResponse *resp, Error **errp)
679 uint32_t sz;
681 if (prh_read(client, req->cdb, sizeof(req->cdb), NULL) < 0) {
682 return -1;
685 if (client->fd == -1) {
686 error_setg(errp, "No file descriptor in request.");
687 return -1;
690 if (req->cdb[0] != PERSISTENT_RESERVE_OUT &&
691 req->cdb[0] != PERSISTENT_RESERVE_IN) {
692 error_setg(errp, "Invalid CDB, closing socket.");
693 goto out_close;
696 sz = scsi_cdb_xfer(req->cdb);
697 if (sz > sizeof(client->data)) {
698 goto out_close;
701 if (req->cdb[0] == PERSISTENT_RESERVE_OUT) {
702 if (qio_channel_read_all(QIO_CHANNEL(client->ioc),
703 (char *)client->data, sz,
704 errp) < 0) {
705 goto out_close;
709 req->fd = client->fd;
710 req->sz = sz;
711 client->fd = -1;
712 return sz;
714 out_close:
715 close(client->fd);
716 client->fd = -1;
717 return -1;
720 static int coroutine_fn prh_write_response(PRHelperClient *client,
721 PRHelperRequest *req,
722 PRHelperResponse *resp, Error **errp)
724 ssize_t r;
725 size_t sz;
727 if (req->cdb[0] == PERSISTENT_RESERVE_IN && resp->result == GOOD) {
728 assert(resp->sz <= req->sz && resp->sz <= sizeof(client->data));
729 } else {
730 assert(resp->sz == 0);
733 sz = resp->sz;
735 resp->result = cpu_to_be32(resp->result);
736 resp->sz = cpu_to_be32(resp->sz);
737 r = qio_channel_write_all(QIO_CHANNEL(client->ioc),
738 (char *) resp, sizeof(*resp), errp);
739 if (r < 0) {
740 return r;
743 r = qio_channel_write_all(QIO_CHANNEL(client->ioc),
744 (char *) client->data,
745 sz, errp);
746 return r < 0 ? r : 0;
749 static void coroutine_fn prh_co_entry(void *opaque)
751 PRHelperClient *client = opaque;
752 Error *local_err = NULL;
753 uint32_t flags;
754 int r;
756 qio_channel_set_blocking(QIO_CHANNEL(client->ioc),
757 false, NULL);
758 qio_channel_attach_aio_context(QIO_CHANNEL(client->ioc),
759 qemu_get_aio_context());
761 /* A very simple negotiation for future extensibility. No features
762 * are defined so write 0.
764 flags = cpu_to_be32(0);
765 r = qio_channel_write_all(QIO_CHANNEL(client->ioc),
766 (char *) &flags, sizeof(flags), NULL);
767 if (r < 0) {
768 goto out;
771 r = qio_channel_read_all(QIO_CHANNEL(client->ioc),
772 (char *) &flags, sizeof(flags), NULL);
773 if (be32_to_cpu(flags) != 0 || r < 0) {
774 goto out;
777 while (atomic_read(&state) == RUNNING) {
778 PRHelperRequest req;
779 PRHelperResponse resp;
780 int sz;
782 sz = prh_read_request(client, &req, &resp, &local_err);
783 if (sz < 0) {
784 break;
787 num_active_sockets++;
788 if (req.cdb[0] == PERSISTENT_RESERVE_OUT) {
789 r = do_pr_out(req.fd, req.cdb, resp.sense,
790 client->data, sz);
791 resp.sz = 0;
792 } else {
793 resp.sz = sizeof(client->data);
794 r = do_pr_in(req.fd, req.cdb, resp.sense,
795 client->data, &resp.sz);
796 resp.sz = MIN(resp.sz, sz);
798 num_active_sockets--;
799 close(req.fd);
800 if (r == -1) {
801 break;
803 resp.result = r;
805 if (prh_write_response(client, &req, &resp, &local_err) < 0) {
806 break;
810 if (local_err) {
811 if (verbose == 0) {
812 error_free(local_err);
813 } else {
814 error_report_err(local_err);
818 out:
819 qio_channel_detach_aio_context(QIO_CHANNEL(client->ioc));
820 object_unref(OBJECT(client->ioc));
821 g_free(client);
824 static gboolean accept_client(QIOChannel *ioc, GIOCondition cond, gpointer opaque)
826 QIOChannelSocket *cioc;
827 PRHelperClient *prh;
829 cioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc),
830 NULL);
831 if (!cioc) {
832 return TRUE;
835 prh = g_new(PRHelperClient, 1);
836 prh->ioc = cioc;
837 prh->fd = -1;
838 prh->co = qemu_coroutine_create(prh_co_entry, prh);
839 qemu_coroutine_enter(prh->co);
841 return TRUE;
846 * Check socket parameters compatibility when socket activation is used.
848 static const char *socket_activation_validate_opts(void)
850 if (socket_path != NULL) {
851 return "Unix socket can't be set when using socket activation";
854 return NULL;
857 static void termsig_handler(int signum)
859 atomic_cmpxchg(&state, RUNNING, TERMINATE);
860 qemu_notify_event();
863 static void close_server_socket(void)
865 assert(server_ioc);
867 g_source_remove(server_watch);
868 server_watch = -1;
869 object_unref(OBJECT(server_ioc));
870 num_active_sockets--;
873 #ifdef CONFIG_LIBCAP
874 static int drop_privileges(void)
876 /* clear all capabilities */
877 capng_clear(CAPNG_SELECT_BOTH);
879 if (capng_update(CAPNG_ADD, CAPNG_EFFECTIVE | CAPNG_PERMITTED,
880 CAP_SYS_RAWIO) < 0) {
881 return -1;
884 #ifdef CONFIG_MPATH
885 /* For /dev/mapper/control ioctls */
886 if (capng_update(CAPNG_ADD, CAPNG_EFFECTIVE | CAPNG_PERMITTED,
887 CAP_SYS_ADMIN) < 0) {
888 return -1;
890 #endif
892 /* Change user/group id, retaining the capabilities. Because file descriptors
893 * are passed via SCM_RIGHTS, we don't need supplementary groups (and in
894 * fact the helper can run as "nobody").
896 if (capng_change_id(uid != -1 ? uid : getuid(),
897 gid != -1 ? gid : getgid(),
898 CAPNG_DROP_SUPP_GRP | CAPNG_CLEAR_BOUNDING)) {
899 return -1;
902 return 0;
904 #endif
906 int main(int argc, char **argv)
908 const char *sopt = "hVk:f:dT:u:g:vq";
909 struct option lopt[] = {
910 { "help", no_argument, NULL, 'h' },
911 { "version", no_argument, NULL, 'V' },
912 { "socket", required_argument, NULL, 'k' },
913 { "pidfile", required_argument, NULL, 'f' },
914 { "daemon", no_argument, NULL, 'd' },
915 { "trace", required_argument, NULL, 'T' },
916 { "user", required_argument, NULL, 'u' },
917 { "group", required_argument, NULL, 'g' },
918 { "verbose", no_argument, NULL, 'v' },
919 { "quiet", no_argument, NULL, 'q' },
920 { NULL, 0, NULL, 0 }
922 int opt_ind = 0;
923 int loglevel = 1;
924 int quiet = 0;
925 int ch;
926 Error *local_err = NULL;
927 char *trace_file = NULL;
928 bool daemonize = false;
929 bool pidfile_specified = false;
930 unsigned socket_activation;
932 struct sigaction sa_sigterm;
933 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
934 sa_sigterm.sa_handler = termsig_handler;
935 sigaction(SIGTERM, &sa_sigterm, NULL);
936 sigaction(SIGINT, &sa_sigterm, NULL);
937 sigaction(SIGHUP, &sa_sigterm, NULL);
939 signal(SIGPIPE, SIG_IGN);
941 module_call_init(MODULE_INIT_TRACE);
942 module_call_init(MODULE_INIT_QOM);
943 qemu_add_opts(&qemu_trace_opts);
944 qemu_init_exec_dir(argv[0]);
946 pidfile = qemu_get_local_state_pathname("run/qemu-pr-helper.pid");
948 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
949 switch (ch) {
950 case 'k':
951 socket_path = optarg;
952 if (socket_path[0] != '/') {
953 error_report("socket path must be absolute");
954 exit(EXIT_FAILURE);
956 break;
957 case 'f':
958 g_free(pidfile);
959 pidfile = g_strdup(optarg);
960 pidfile_specified = true;
961 break;
962 #ifdef CONFIG_LIBCAP
963 case 'u': {
964 unsigned long res;
965 struct passwd *userinfo = getpwnam(optarg);
966 if (userinfo) {
967 uid = userinfo->pw_uid;
968 } else if (qemu_strtoul(optarg, NULL, 10, &res) == 0 &&
969 (uid_t)res == res) {
970 uid = res;
971 } else {
972 error_report("invalid user '%s'", optarg);
973 exit(EXIT_FAILURE);
975 break;
977 case 'g': {
978 unsigned long res;
979 struct group *groupinfo = getgrnam(optarg);
980 if (groupinfo) {
981 gid = groupinfo->gr_gid;
982 } else if (qemu_strtoul(optarg, NULL, 10, &res) == 0 &&
983 (gid_t)res == res) {
984 gid = res;
985 } else {
986 error_report("invalid group '%s'", optarg);
987 exit(EXIT_FAILURE);
989 break;
991 #else
992 case 'u':
993 case 'g':
994 error_report("-%c not supported by this %s", ch, argv[0]);
995 exit(1);
996 #endif
997 case 'd':
998 daemonize = true;
999 break;
1000 case 'q':
1001 quiet = 1;
1002 break;
1003 case 'v':
1004 ++loglevel;
1005 break;
1006 case 'T':
1007 g_free(trace_file);
1008 trace_file = trace_opt_parse(optarg);
1009 break;
1010 case 'V':
1011 version(argv[0]);
1012 exit(EXIT_SUCCESS);
1013 break;
1014 case 'h':
1015 usage(argv[0]);
1016 exit(EXIT_SUCCESS);
1017 break;
1018 case '?':
1019 error_report("Try `%s --help' for more information.", argv[0]);
1020 exit(EXIT_FAILURE);
1024 /* set verbosity */
1025 noisy = !quiet && (loglevel >= 3);
1026 verbose = quiet ? 0 : MIN(loglevel, 3);
1028 if (!trace_init_backends()) {
1029 exit(EXIT_FAILURE);
1031 trace_init_file(trace_file);
1032 qemu_set_log(LOG_TRACE);
1034 #ifdef CONFIG_MPATH
1035 dm_init();
1036 multipath_pr_init();
1037 #endif
1039 socket_activation = check_socket_activation();
1040 if (socket_activation == 0) {
1041 SocketAddress saddr;
1042 compute_default_paths();
1043 saddr = (SocketAddress){
1044 .type = SOCKET_ADDRESS_TYPE_UNIX,
1045 .u.q_unix.path = g_strdup(socket_path)
1047 server_ioc = qio_channel_socket_new();
1048 if (qio_channel_socket_listen_sync(server_ioc, &saddr, &local_err) < 0) {
1049 object_unref(OBJECT(server_ioc));
1050 error_report_err(local_err);
1051 return 1;
1053 g_free(saddr.u.q_unix.path);
1054 } else {
1055 /* Using socket activation - check user didn't use -p etc. */
1056 const char *err_msg = socket_activation_validate_opts();
1057 if (err_msg != NULL) {
1058 error_report("%s", err_msg);
1059 exit(EXIT_FAILURE);
1062 /* Can only listen on a single socket. */
1063 if (socket_activation > 1) {
1064 error_report("%s does not support socket activation with LISTEN_FDS > 1",
1065 argv[0]);
1066 exit(EXIT_FAILURE);
1068 server_ioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD,
1069 &local_err);
1070 if (server_ioc == NULL) {
1071 error_report("Failed to use socket activation: %s",
1072 error_get_pretty(local_err));
1073 exit(EXIT_FAILURE);
1075 socket_path = NULL;
1078 if (qemu_init_main_loop(&local_err)) {
1079 error_report_err(local_err);
1080 exit(EXIT_FAILURE);
1083 server_watch = qio_channel_add_watch(QIO_CHANNEL(server_ioc),
1084 G_IO_IN,
1085 accept_client,
1086 NULL, NULL);
1088 if (daemonize) {
1089 if (daemon(0, 0) < 0) {
1090 error_report("Failed to daemonize: %s", strerror(errno));
1091 exit(EXIT_FAILURE);
1095 if (daemonize || pidfile_specified)
1096 write_pidfile();
1098 #ifdef CONFIG_LIBCAP
1099 if (drop_privileges() < 0) {
1100 error_report("Failed to drop privileges: %s", strerror(errno));
1101 exit(EXIT_FAILURE);
1103 #endif
1105 state = RUNNING;
1106 do {
1107 main_loop_wait(false);
1108 if (state == TERMINATE) {
1109 state = TERMINATING;
1110 close_server_socket();
1112 } while (num_active_sockets > 0);
1114 exit(EXIT_SUCCESS);