xref: /openbmc/qemu/scsi/qemu-pr-helper.c (revision dc41aa7d)
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 #ifdef CONFIG_MPATH
34 #include <libudev.h>
35 #include <mpath_cmd.h>
36 #include <mpath_persist.h>
37 #endif
38 
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"
53 
54 #include "block/aio.h"
55 #include "block/thread-pool.h"
56 
57 #include "scsi/constants.h"
58 #include "scsi/utils.h"
59 #include "pr-helper.h"
60 
61 #define PR_OUT_FIXED_PARAM_SIZE 24
62 
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;
71 
72 #ifdef CONFIG_LIBCAP
73 static int uid = -1;
74 static int gid = -1;
75 #endif
76 
77 static void usage(const char *name)
78 {
79     (printf) (
80 "Usage: %s [OPTIONS] FILE\n"
81 "Persistent Reservation helper program for QEMU\n"
82 "\n"
83 "  -h, --help                display this help and exit\n"
84 "  -V, --version             output version information and exit\n"
85 "\n"
86 "  -d, --daemon              run in the background\n"
87 "  -f, --pidfile=PATH        PID file when running as a daemon\n"
88 "                            (default '%s')\n"
89 "  -k, --socket=PATH         path to the unix socket\n"
90 "                            (default '%s')\n"
91 "  -T, --trace [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
92 "                            specify tracing options\n"
93 #ifdef CONFIG_LIBCAP
94 "  -u, --user=USER           user to drop privileges to\n"
95 "  -g, --group=GROUP         group to drop privileges to\n"
96 #endif
97 "\n"
98 QEMU_HELP_BOTTOM "\n"
99     , name, pidfile, socket_path);
100 }
101 
102 static void version(const char *name)
103 {
104     printf(
105 "%s " QEMU_VERSION QEMU_PKGVERSION "\n"
106 "Written by Paolo Bonzini.\n"
107 "\n"
108 QEMU_COPYRIGHT "\n"
109 "This is free software; see the source for copying conditions.  There is NO\n"
110 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
111     , name);
112 }
113 
114 static void write_pidfile(void)
115 {
116     int pidfd;
117     char pidstr[32];
118 
119     pidfd = qemu_open(pidfile, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR);
120     if (pidfd == -1) {
121         error_report("Cannot open pid file, %s", strerror(errno));
122         exit(EXIT_FAILURE);
123     }
124 
125     if (lockf(pidfd, F_TLOCK, 0)) {
126         error_report("Cannot lock pid file, %s", strerror(errno));
127         goto fail;
128     }
129     if (ftruncate(pidfd, 0)) {
130         error_report("Failed to truncate pid file");
131         goto fail;
132     }
133 
134     snprintf(pidstr, sizeof(pidstr), "%d\n", getpid());
135     if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
136         error_report("Failed to write pid file");
137         goto fail;
138     }
139     return;
140 
141 fail:
142     unlink(pidfile);
143     close(pidfd);
144     exit(EXIT_FAILURE);
145 }
146 
147 /* SG_IO support */
148 
149 typedef struct PRHelperSGIOData {
150     int fd;
151     const uint8_t *cdb;
152     uint8_t *sense;
153     uint8_t *buf;
154     int sz;              /* input/output */
155     int dir;
156 } PRHelperSGIOData;
157 
158 static int do_sgio_worker(void *opaque)
159 {
160     PRHelperSGIOData *data = opaque;
161     struct sg_io_hdr io_hdr;
162     int ret;
163     int status;
164     SCSISense sense_code;
165 
166     memset(data->sense, 0, PR_HELPER_SENSE_SIZE);
167     memset(&io_hdr, 0, sizeof(io_hdr));
168     io_hdr.interface_id = 'S';
169     io_hdr.cmd_len = PR_HELPER_CDB_SIZE;
170     io_hdr.cmdp = (uint8_t *)data->cdb;
171     io_hdr.sbp = data->sense;
172     io_hdr.mx_sb_len = PR_HELPER_SENSE_SIZE;
173     io_hdr.timeout = 1;
174     io_hdr.dxfer_direction = data->dir;
175     io_hdr.dxferp = (char *)data->buf;
176     io_hdr.dxfer_len = data->sz;
177     ret = ioctl(data->fd, SG_IO, &io_hdr);
178     status = sg_io_sense_from_errno(ret < 0 ? errno : 0, &io_hdr,
179                                     &sense_code);
180     if (status == GOOD) {
181         data->sz -= io_hdr.resid;
182     } else {
183         data->sz = 0;
184     }
185 
186     if (status == CHECK_CONDITION &&
187         !(io_hdr.driver_status & SG_ERR_DRIVER_SENSE)) {
188         scsi_build_sense(data->sense, sense_code);
189     }
190 
191     return status;
192 }
193 
194 static int do_sgio(int fd, const uint8_t *cdb, uint8_t *sense,
195                     uint8_t *buf, int *sz, int dir)
196 {
197     ThreadPool *pool = aio_get_thread_pool(qemu_get_aio_context());
198     int r;
199 
200     PRHelperSGIOData data = {
201         .fd = fd,
202         .cdb = cdb,
203         .sense = sense,
204         .buf = buf,
205         .sz = *sz,
206         .dir = dir,
207     };
208 
209     r = thread_pool_submit_co(pool, do_sgio_worker, &data);
210     *sz = data.sz;
211     return r;
212 }
213 
214 /* Device mapper interface */
215 
216 #ifdef CONFIG_MPATH
217 #define CONTROL_PATH "/dev/mapper/control"
218 
219 typedef struct DMData {
220     struct dm_ioctl dm;
221     uint8_t data[1024];
222 } DMData;
223 
224 static int control_fd;
225 
226 static void *dm_ioctl(int ioc, struct dm_ioctl *dm)
227 {
228     static DMData d;
229     memcpy(&d.dm, dm, sizeof(d.dm));
230     QEMU_BUILD_BUG_ON(sizeof(d.data) < sizeof(struct dm_target_spec));
231 
232     d.dm.version[0] = DM_VERSION_MAJOR;
233     d.dm.version[1] = 0;
234     d.dm.version[2] = 0;
235     d.dm.data_size = 1024;
236     d.dm.data_start = offsetof(DMData, data);
237     if (ioctl(control_fd, ioc, &d) < 0) {
238         return NULL;
239     }
240     memcpy(dm, &d.dm, sizeof(d.dm));
241     return &d.data;
242 }
243 
244 static void *dm_dev_ioctl(int fd, int ioc, struct dm_ioctl *dm)
245 {
246     struct stat st;
247     int r;
248 
249     r = fstat(fd, &st);
250     if (r < 0) {
251         perror("fstat");
252         exit(1);
253     }
254 
255     dm->dev = st.st_rdev;
256     return dm_ioctl(ioc, dm);
257 }
258 
259 static void dm_init(void)
260 {
261     control_fd = open(CONTROL_PATH, O_RDWR);
262     if (control_fd < 0) {
263         perror("Cannot open " CONTROL_PATH);
264         exit(1);
265     }
266     struct dm_ioctl dm = { 0 };
267     if (!dm_ioctl(DM_VERSION, &dm)) {
268         perror("ioctl");
269         exit(1);
270     }
271     if (dm.version[0] != DM_VERSION_MAJOR) {
272         fprintf(stderr, "Unsupported device mapper interface");
273         exit(1);
274     }
275 }
276 
277 /* Variables required by libmultipath and libmpathpersist.  */
278 QEMU_BUILD_BUG_ON(PR_HELPER_DATA_SIZE > MPATH_MAX_PARAM_LEN);
279 static struct config *multipath_conf;
280 unsigned mpath_mx_alloc_len = PR_HELPER_DATA_SIZE;
281 int logsink;
282 struct udev *udev;
283 
284 extern struct config *get_multipath_config(void);
285 struct config *get_multipath_config(void)
286 {
287     return multipath_conf;
288 }
289 
290 extern void put_multipath_config(struct config *conf);
291 void put_multipath_config(struct config *conf)
292 {
293 }
294 
295 static void multipath_pr_init(void)
296 {
297     udev = udev_new();
298     multipath_conf = mpath_lib_init();
299 }
300 
301 static int is_mpath(int fd)
302 {
303     struct dm_ioctl dm = { .flags = DM_NOFLUSH_FLAG };
304     struct dm_target_spec *tgt;
305 
306     tgt = dm_dev_ioctl(fd, DM_TABLE_STATUS, &dm);
307     if (!tgt) {
308         if (errno == ENXIO) {
309             return 0;
310         }
311         perror("ioctl");
312         exit(EXIT_FAILURE);
313     }
314     return !strncmp(tgt->target_type, "multipath", DM_MAX_TYPE_NAME);
315 }
316 
317 static int mpath_reconstruct_sense(int fd, int r, uint8_t *sense)
318 {
319     switch (r) {
320     case MPATH_PR_SUCCESS:
321         return GOOD;
322     case MPATH_PR_SENSE_NOT_READY:
323     case MPATH_PR_SENSE_MEDIUM_ERROR:
324     case MPATH_PR_SENSE_HARDWARE_ERROR:
325     case MPATH_PR_SENSE_ABORTED_COMMAND:
326         {
327             /* libmpathpersist ate the exact sense.  Try to find it by
328              * issuing TEST UNIT READY.
329              */
330             uint8_t cdb[6] = { TEST_UNIT_READY };
331             int sz = 0;
332             return do_sgio(fd, cdb, sense, NULL, &sz, SG_DXFER_NONE);
333         }
334 
335     case MPATH_PR_SENSE_UNIT_ATTENTION:
336         /* Congratulations libmpathpersist, you ruined the Unit Attention...
337          * Return a heavyweight one.
338          */
339         scsi_build_sense(sense, SENSE_CODE(SCSI_BUS_RESET));
340         return CHECK_CONDITION;
341     case MPATH_PR_SENSE_INVALID_OP:
342         /* Only one valid sense.  */
343         scsi_build_sense(sense, SENSE_CODE(INVALID_OPCODE));
344         return CHECK_CONDITION;
345     case MPATH_PR_ILLEGAL_REQ:
346         /* Guess.  */
347         scsi_build_sense(sense, SENSE_CODE(INVALID_PARAM));
348         return CHECK_CONDITION;
349     case MPATH_PR_NO_SENSE:
350         scsi_build_sense(sense, SENSE_CODE(NO_SENSE));
351         return CHECK_CONDITION;
352 
353     case MPATH_PR_RESERV_CONFLICT:
354         return RESERVATION_CONFLICT;
355 
356     case MPATH_PR_OTHER:
357     default:
358         scsi_build_sense(sense, SENSE_CODE(LUN_COMM_FAILURE));
359         return CHECK_CONDITION;
360     }
361 }
362 
363 static int multipath_pr_in(int fd, const uint8_t *cdb, uint8_t *sense,
364                            uint8_t *data, int sz)
365 {
366     int rq_servact = cdb[1];
367     struct prin_resp resp;
368     size_t written;
369     int r;
370 
371     switch (rq_servact) {
372     case MPATH_PRIN_RKEY_SA:
373     case MPATH_PRIN_RRES_SA:
374     case MPATH_PRIN_RCAP_SA:
375         break;
376     case MPATH_PRIN_RFSTAT_SA:
377         /* Nobody implements it anyway, so bail out. */
378     default:
379         /* Cannot parse any other output.  */
380         scsi_build_sense(sense, SENSE_CODE(INVALID_FIELD));
381         return CHECK_CONDITION;
382     }
383 
384     r = mpath_persistent_reserve_in(fd, rq_servact, &resp, noisy, verbose);
385     if (r == MPATH_PR_SUCCESS) {
386         switch (rq_servact) {
387         case MPATH_PRIN_RKEY_SA:
388         case MPATH_PRIN_RRES_SA: {
389             struct prin_readdescr *out = &resp.prin_descriptor.prin_readkeys;
390             assert(sz >= 8);
391             written = MIN(out->additional_length + 8, sz);
392             stl_be_p(&data[0], out->prgeneration);
393             stl_be_p(&data[4], out->additional_length);
394             memcpy(&data[8], out->key_list, written - 8);
395             break;
396         }
397         case MPATH_PRIN_RCAP_SA: {
398             struct prin_capdescr *out = &resp.prin_descriptor.prin_readcap;
399             assert(sz >= 6);
400             written = 6;
401             stw_be_p(&data[0], out->length);
402             data[2] = out->flags[0];
403             data[3] = out->flags[1];
404             stw_be_p(&data[4], out->pr_type_mask);
405             break;
406         }
407         default:
408             scsi_build_sense(sense, SENSE_CODE(INVALID_OPCODE));
409             return CHECK_CONDITION;
410         }
411         assert(written <= sz);
412         memset(data + written, 0, sz - written);
413     }
414 
415     return mpath_reconstruct_sense(fd, r, sense);
416 }
417 
418 static int multipath_pr_out(int fd, const uint8_t *cdb, uint8_t *sense,
419                             const uint8_t *param, int sz)
420 {
421     int rq_servact = cdb[1];
422     int rq_scope = cdb[2] >> 4;
423     int rq_type = cdb[2] & 0xf;
424     struct prout_param_descriptor paramp;
425     char transportids[PR_HELPER_DATA_SIZE];
426     int r;
427 
428     switch (rq_servact) {
429     case MPATH_PROUT_REG_SA:
430     case MPATH_PROUT_RES_SA:
431     case MPATH_PROUT_REL_SA:
432     case MPATH_PROUT_CLEAR_SA:
433     case MPATH_PROUT_PREE_SA:
434     case MPATH_PROUT_PREE_AB_SA:
435     case MPATH_PROUT_REG_IGN_SA:
436         break;
437     case MPATH_PROUT_REG_MOV_SA:
438         /* Not supported by struct prout_param_descriptor.  */
439     default:
440         /* Cannot parse any other input.  */
441         scsi_build_sense(sense, SENSE_CODE(INVALID_FIELD));
442         return CHECK_CONDITION;
443     }
444 
445     /* Convert input data, especially transport IDs, to the structs
446      * used by libmpathpersist (which, of course, will immediately
447      * do the opposite).
448      */
449     memset(&paramp, 0, sizeof(paramp));
450     memcpy(&paramp.key, &param[0], 8);
451     memcpy(&paramp.sa_key, &param[8], 8);
452     paramp.sa_flags = param[10];
453     if (sz > PR_OUT_FIXED_PARAM_SIZE) {
454         size_t transportid_len;
455         int i, j;
456         if (sz < PR_OUT_FIXED_PARAM_SIZE + 4) {
457             scsi_build_sense(sense, SENSE_CODE(INVALID_PARAM_LEN));
458             return CHECK_CONDITION;
459         }
460         transportid_len = ldl_be_p(&param[24]) + PR_OUT_FIXED_PARAM_SIZE + 4;
461         if (transportid_len > sz) {
462             scsi_build_sense(sense, SENSE_CODE(INVALID_PARAM));
463             return CHECK_CONDITION;
464         }
465         for (i = PR_OUT_FIXED_PARAM_SIZE + 4, j = 0; i < transportid_len; ) {
466             struct transportid *id = (struct transportid *) &transportids[j];
467             int len;
468 
469             id->format_code = param[i] & 0xc0;
470             id->protocol_id = param[i] & 0x0f;
471             switch (param[i] & 0xcf) {
472             case 0:
473                 /* FC transport.  */
474                 if (i + 24 > transportid_len) {
475                     goto illegal_req;
476                 }
477                 memcpy(id->n_port_name, &param[i + 8], 8);
478                 j += offsetof(struct transportid, n_port_name[8]);
479                 i += 24;
480                 break;
481             case 3:
482             case 0x43:
483                 /* iSCSI transport.  */
484                 len = lduw_be_p(&param[i + 2]);
485                 if (len > 252 || (len & 3) || i + len + 4 > transportid_len) {
486                     /* For format code 00, the standard says the maximum is 223
487                      * plus the NUL terminator.  For format code 01 there is no
488                      * maximum length, but libmpathpersist ignores the first
489                      * byte of id->iscsi_name so our maximum is 252.
490                      */
491                     goto illegal_req;
492                 }
493                 if (memchr(&param[i + 4], 0, len) == NULL) {
494                     goto illegal_req;
495                 }
496                 memcpy(id->iscsi_name, &param[i + 2], len + 2);
497                 j += offsetof(struct transportid, iscsi_name[len + 2]);
498                 i += len + 4;
499                 break;
500             case 6:
501                 /* SAS transport.  */
502                 if (i + 24 > transportid_len) {
503                     goto illegal_req;
504                 }
505                 memcpy(id->sas_address, &param[i + 4], 8);
506                 j += offsetof(struct transportid, sas_address[8]);
507                 i += 24;
508                 break;
509             default:
510             illegal_req:
511                 scsi_build_sense(sense, SENSE_CODE(INVALID_PARAM));
512                 return CHECK_CONDITION;
513             }
514 
515             paramp.trnptid_list[paramp.num_transportid++] = id;
516         }
517     }
518 
519     r = mpath_persistent_reserve_out(fd, rq_servact, rq_scope, rq_type,
520                                      &paramp, noisy, verbose);
521     return mpath_reconstruct_sense(fd, r, sense);
522 }
523 #endif
524 
525 static int do_pr_in(int fd, const uint8_t *cdb, uint8_t *sense,
526                     uint8_t *data, int *resp_sz)
527 {
528 #ifdef CONFIG_MPATH
529     if (is_mpath(fd)) {
530         /* multipath_pr_in fills the whole input buffer.  */
531         return multipath_pr_in(fd, cdb, sense, data, *resp_sz);
532     }
533 #endif
534 
535     return do_sgio(fd, cdb, sense, data, resp_sz,
536                    SG_DXFER_FROM_DEV);
537 }
538 
539 static int do_pr_out(int fd, const uint8_t *cdb, uint8_t *sense,
540                      const uint8_t *param, int sz)
541 {
542     int resp_sz;
543 #ifdef CONFIG_MPATH
544     if (is_mpath(fd)) {
545         return multipath_pr_out(fd, cdb, sense, param, sz);
546     }
547 #endif
548 
549     resp_sz = sz;
550     return do_sgio(fd, cdb, sense, (uint8_t *)param, &resp_sz,
551                    SG_DXFER_TO_DEV);
552 }
553 
554 /* Client */
555 
556 typedef struct PRHelperClient {
557     QIOChannelSocket *ioc;
558     Coroutine *co;
559     int fd;
560     uint8_t data[PR_HELPER_DATA_SIZE];
561 } PRHelperClient;
562 
563 typedef struct PRHelperRequest {
564     int fd;
565     size_t sz;
566     uint8_t cdb[PR_HELPER_CDB_SIZE];
567 } PRHelperRequest;
568 
569 static int coroutine_fn prh_read(PRHelperClient *client, void *buf, int sz,
570                                  Error **errp)
571 {
572     int ret = 0;
573 
574     while (sz > 0) {
575         int *fds = NULL;
576         size_t nfds = 0;
577         int i;
578         struct iovec iov;
579         ssize_t n_read;
580 
581         iov.iov_base = buf;
582         iov.iov_len = sz;
583         n_read = qio_channel_readv_full(QIO_CHANNEL(client->ioc), &iov, 1,
584                                         &fds, &nfds, errp);
585 
586         if (n_read == QIO_CHANNEL_ERR_BLOCK) {
587             qio_channel_yield(QIO_CHANNEL(client->ioc), G_IO_IN);
588             continue;
589         }
590         if (n_read <= 0) {
591             ret = n_read ? n_read : -1;
592             goto err;
593         }
594 
595         /* Stash one file descriptor per request.  */
596         if (nfds) {
597             bool too_many = false;
598             for (i = 0; i < nfds; i++) {
599                 if (client->fd == -1) {
600                     client->fd = fds[i];
601                 } else {
602                     close(fds[i]);
603                     too_many = true;
604                 }
605             }
606             g_free(fds);
607             if (too_many) {
608                 ret = -1;
609                 goto err;
610             }
611         }
612 
613         buf += n_read;
614         sz -= n_read;
615     }
616 
617     return 0;
618 
619 err:
620     if (client->fd != -1) {
621         close(client->fd);
622         client->fd = -1;
623     }
624     return ret;
625 }
626 
627 static int coroutine_fn prh_read_request(PRHelperClient *client,
628                                          PRHelperRequest *req,
629                                          PRHelperResponse *resp, Error **errp)
630 {
631     uint32_t sz;
632 
633     if (prh_read(client, req->cdb, sizeof(req->cdb), NULL) < 0) {
634         return -1;
635     }
636 
637     if (client->fd == -1) {
638         error_setg(errp, "No file descriptor in request.");
639         return -1;
640     }
641 
642     if (req->cdb[0] != PERSISTENT_RESERVE_OUT &&
643         req->cdb[0] != PERSISTENT_RESERVE_IN) {
644         error_setg(errp, "Invalid CDB, closing socket.");
645         goto out_close;
646     }
647 
648     sz = scsi_cdb_xfer(req->cdb);
649     if (sz > sizeof(client->data)) {
650         goto out_close;
651     }
652 
653     if (req->cdb[0] == PERSISTENT_RESERVE_OUT) {
654         if (qio_channel_read_all(QIO_CHANNEL(client->ioc),
655                                  (char *)client->data, sz,
656                                  errp) < 0) {
657             goto out_close;
658         }
659         if ((fcntl(client->fd, F_GETFL) & O_ACCMODE) == O_RDONLY) {
660             scsi_build_sense(resp->sense, SENSE_CODE(INVALID_OPCODE));
661             sz = 0;
662         } else if (sz < PR_OUT_FIXED_PARAM_SIZE) {
663             /* Illegal request, Parameter list length error.  This isn't fatal;
664              * we have read the data, send an error without closing the socket.
665              */
666             scsi_build_sense(resp->sense, SENSE_CODE(INVALID_PARAM_LEN));
667             sz = 0;
668         }
669         if (sz == 0) {
670             resp->result = CHECK_CONDITION;
671             close(client->fd);
672             client->fd = -1;
673         }
674     }
675 
676     req->fd = client->fd;
677     req->sz = sz;
678     client->fd = -1;
679     return sz;
680 
681 out_close:
682     close(client->fd);
683     client->fd = -1;
684     return -1;
685 }
686 
687 static int coroutine_fn prh_write_response(PRHelperClient *client,
688                                            PRHelperRequest *req,
689                                            PRHelperResponse *resp, Error **errp)
690 {
691     ssize_t r;
692     size_t sz;
693 
694     if (req->cdb[0] == PERSISTENT_RESERVE_IN && resp->result == GOOD) {
695         assert(resp->sz <= req->sz && resp->sz <= sizeof(client->data));
696     } else {
697         assert(resp->sz == 0);
698     }
699 
700     sz = resp->sz;
701 
702     resp->result = cpu_to_be32(resp->result);
703     resp->sz = cpu_to_be32(resp->sz);
704     r = qio_channel_write_all(QIO_CHANNEL(client->ioc),
705                               (char *) resp, sizeof(*resp), errp);
706     if (r < 0) {
707         return r;
708     }
709 
710     r = qio_channel_write_all(QIO_CHANNEL(client->ioc),
711                               (char *) client->data,
712                               sz, errp);
713     return r < 0 ? r : 0;
714 }
715 
716 static void coroutine_fn prh_co_entry(void *opaque)
717 {
718     PRHelperClient *client = opaque;
719     Error *local_err = NULL;
720     uint32_t flags;
721     int r;
722 
723     qio_channel_set_blocking(QIO_CHANNEL(client->ioc),
724                              false, NULL);
725     qio_channel_attach_aio_context(QIO_CHANNEL(client->ioc),
726                                    qemu_get_aio_context());
727 
728     /* A very simple negotiation for future extensibility.  No features
729      * are defined so write 0.
730      */
731     flags = cpu_to_be32(0);
732     r = qio_channel_write_all(QIO_CHANNEL(client->ioc),
733                              (char *) &flags, sizeof(flags), NULL);
734     if (r < 0) {
735         goto out;
736     }
737 
738     r = qio_channel_read_all(QIO_CHANNEL(client->ioc),
739                              (char *) &flags, sizeof(flags), NULL);
740     if (be32_to_cpu(flags) != 0 || r < 0) {
741         goto out;
742     }
743 
744     while (atomic_read(&state) == RUNNING) {
745         PRHelperRequest req;
746         PRHelperResponse resp;
747         int sz;
748 
749         sz = prh_read_request(client, &req, &resp, &local_err);
750         if (sz < 0) {
751             break;
752         }
753 
754         if (sz > 0) {
755             num_active_sockets++;
756             if (req.cdb[0] == PERSISTENT_RESERVE_OUT) {
757                 r = do_pr_out(req.fd, req.cdb, resp.sense,
758                               client->data, sz);
759                 resp.sz = 0;
760             } else {
761                 resp.sz = sizeof(client->data);
762                 r = do_pr_in(req.fd, req.cdb, resp.sense,
763                              client->data, &resp.sz);
764                 resp.sz = MIN(resp.sz, sz);
765             }
766             num_active_sockets--;
767             close(req.fd);
768             if (r == -1) {
769                 break;
770             }
771             resp.result = r;
772         }
773 
774         if (prh_write_response(client, &req, &resp, &local_err) < 0) {
775             break;
776         }
777     }
778 
779     if (local_err) {
780         if (verbose == 0) {
781             error_free(local_err);
782         } else {
783             error_report_err(local_err);
784         }
785     }
786 
787 out:
788     qio_channel_detach_aio_context(QIO_CHANNEL(client->ioc));
789     object_unref(OBJECT(client->ioc));
790     g_free(client);
791 }
792 
793 static gboolean accept_client(QIOChannel *ioc, GIOCondition cond, gpointer opaque)
794 {
795     QIOChannelSocket *cioc;
796     PRHelperClient *prh;
797 
798     cioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc),
799                                      NULL);
800     if (!cioc) {
801         return TRUE;
802     }
803 
804     prh = g_new(PRHelperClient, 1);
805     prh->ioc = cioc;
806     prh->fd = -1;
807     prh->co = qemu_coroutine_create(prh_co_entry, prh);
808     qemu_coroutine_enter(prh->co);
809 
810     return TRUE;
811 }
812 
813 
814 /*
815  * Check socket parameters compatibility when socket activation is used.
816  */
817 static const char *socket_activation_validate_opts(void)
818 {
819     if (socket_path != NULL) {
820         return "Unix socket can't be set when using socket activation";
821     }
822 
823     return NULL;
824 }
825 
826 static void compute_default_paths(void)
827 {
828     if (!socket_path) {
829         socket_path = qemu_get_local_state_pathname("run/qemu-pr-helper.sock");
830     }
831 }
832 
833 static void termsig_handler(int signum)
834 {
835     atomic_cmpxchg(&state, RUNNING, TERMINATE);
836     qemu_notify_event();
837 }
838 
839 static void close_server_socket(void)
840 {
841     assert(server_ioc);
842 
843     g_source_remove(server_watch);
844     server_watch = -1;
845     object_unref(OBJECT(server_ioc));
846     num_active_sockets--;
847 }
848 
849 #ifdef CONFIG_LIBCAP
850 static int drop_privileges(void)
851 {
852     /* clear all capabilities */
853     capng_clear(CAPNG_SELECT_BOTH);
854 
855     if (capng_update(CAPNG_ADD, CAPNG_EFFECTIVE | CAPNG_PERMITTED,
856                      CAP_SYS_RAWIO) < 0) {
857         return -1;
858     }
859 
860 #ifdef CONFIG_MPATH
861     /* For /dev/mapper/control ioctls */
862     if (capng_update(CAPNG_ADD, CAPNG_EFFECTIVE | CAPNG_PERMITTED,
863                      CAP_SYS_ADMIN) < 0) {
864         return -1;
865     }
866 #endif
867 
868     /* Change user/group id, retaining the capabilities.  Because file descriptors
869      * are passed via SCM_RIGHTS, we don't need supplementary groups (and in
870      * fact the helper can run as "nobody").
871      */
872     if (capng_change_id(uid != -1 ? uid : getuid(),
873                         gid != -1 ? gid : getgid(),
874                         CAPNG_DROP_SUPP_GRP | CAPNG_CLEAR_BOUNDING)) {
875         return -1;
876     }
877 
878     return 0;
879 }
880 #endif
881 
882 int main(int argc, char **argv)
883 {
884     const char *sopt = "hVk:fdT:u:g:vq";
885     struct option lopt[] = {
886         { "help", no_argument, NULL, 'h' },
887         { "version", no_argument, NULL, 'V' },
888         { "socket", required_argument, NULL, 'k' },
889         { "pidfile", no_argument, NULL, 'f' },
890         { "daemon", no_argument, NULL, 'd' },
891         { "trace", required_argument, NULL, 'T' },
892         { "user", required_argument, NULL, 'u' },
893         { "group", required_argument, NULL, 'g' },
894         { "verbose", no_argument, NULL, 'v' },
895         { "quiet", no_argument, NULL, 'q' },
896         { NULL, 0, NULL, 0 }
897     };
898     int opt_ind = 0;
899     int loglevel = 1;
900     int quiet = 0;
901     int ch;
902     Error *local_err = NULL;
903     char *trace_file = NULL;
904     bool daemonize = false;
905     unsigned socket_activation;
906 
907     struct sigaction sa_sigterm;
908     memset(&sa_sigterm, 0, sizeof(sa_sigterm));
909     sa_sigterm.sa_handler = termsig_handler;
910     sigaction(SIGTERM, &sa_sigterm, NULL);
911     sigaction(SIGINT, &sa_sigterm, NULL);
912     sigaction(SIGHUP, &sa_sigterm, NULL);
913 
914     signal(SIGPIPE, SIG_IGN);
915 
916     module_call_init(MODULE_INIT_TRACE);
917     module_call_init(MODULE_INIT_QOM);
918     qemu_add_opts(&qemu_trace_opts);
919     qemu_init_exec_dir(argv[0]);
920 
921     pidfile = qemu_get_local_state_pathname("run/qemu-pr-helper.pid");
922 
923     while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
924         switch (ch) {
925         case 'k':
926             socket_path = optarg;
927             if (socket_path[0] != '/') {
928                 error_report("socket path must be absolute");
929                 exit(EXIT_FAILURE);
930             }
931             break;
932         case 'f':
933             pidfile = optarg;
934             break;
935 #ifdef CONFIG_LIBCAP
936         case 'u': {
937             unsigned long res;
938             struct passwd *userinfo = getpwnam(optarg);
939             if (userinfo) {
940                 uid = userinfo->pw_uid;
941             } else if (qemu_strtoul(optarg, NULL, 10, &res) == 0 &&
942                        (uid_t)res == res) {
943                 uid = res;
944             } else {
945                 error_report("invalid user '%s'", optarg);
946                 exit(EXIT_FAILURE);
947             }
948             break;
949         }
950         case 'g': {
951             unsigned long res;
952             struct group *groupinfo = getgrnam(optarg);
953             if (groupinfo) {
954                 gid = groupinfo->gr_gid;
955             } else if (qemu_strtoul(optarg, NULL, 10, &res) == 0 &&
956                        (gid_t)res == res) {
957                 gid = res;
958             } else {
959                 error_report("invalid group '%s'", optarg);
960                 exit(EXIT_FAILURE);
961             }
962             break;
963         }
964 #else
965         case 'u':
966         case 'g':
967             error_report("-%c not supported by this %s", ch, argv[0]);
968             exit(1);
969 #endif
970         case 'd':
971             daemonize = true;
972             break;
973         case 'q':
974             quiet = 1;
975             break;
976         case 'v':
977             ++loglevel;
978             break;
979         case 'T':
980             g_free(trace_file);
981             trace_file = trace_opt_parse(optarg);
982             break;
983         case 'V':
984             version(argv[0]);
985             exit(EXIT_SUCCESS);
986             break;
987         case 'h':
988             usage(argv[0]);
989             exit(EXIT_SUCCESS);
990             break;
991         case '?':
992             error_report("Try `%s --help' for more information.", argv[0]);
993             exit(EXIT_FAILURE);
994         }
995     }
996 
997     /* set verbosity */
998     noisy = !quiet && (loglevel >= 3);
999     verbose = quiet ? 0 : MIN(loglevel, 3);
1000 
1001     if (!trace_init_backends()) {
1002         exit(EXIT_FAILURE);
1003     }
1004     trace_init_file(trace_file);
1005     qemu_set_log(LOG_TRACE);
1006 
1007 #ifdef CONFIG_MPATH
1008     dm_init();
1009     multipath_pr_init();
1010 #endif
1011 
1012     socket_activation = check_socket_activation();
1013     if (socket_activation == 0) {
1014         SocketAddress saddr;
1015         compute_default_paths();
1016         saddr = (SocketAddress){
1017             .type = SOCKET_ADDRESS_TYPE_UNIX,
1018             .u.q_unix.path = g_strdup(socket_path)
1019         };
1020         server_ioc = qio_channel_socket_new();
1021         if (qio_channel_socket_listen_sync(server_ioc, &saddr, &local_err) < 0) {
1022             object_unref(OBJECT(server_ioc));
1023             error_report_err(local_err);
1024             return 1;
1025         }
1026         g_free(saddr.u.q_unix.path);
1027     } else {
1028         /* Using socket activation - check user didn't use -p etc. */
1029         const char *err_msg = socket_activation_validate_opts();
1030         if (err_msg != NULL) {
1031             error_report("%s", err_msg);
1032             exit(EXIT_FAILURE);
1033         }
1034 
1035         /* Can only listen on a single socket.  */
1036         if (socket_activation > 1) {
1037             error_report("%s does not support socket activation with LISTEN_FDS > 1",
1038                          argv[0]);
1039             exit(EXIT_FAILURE);
1040         }
1041         server_ioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD,
1042                                                &local_err);
1043         if (server_ioc == NULL) {
1044             error_report("Failed to use socket activation: %s",
1045                          error_get_pretty(local_err));
1046             exit(EXIT_FAILURE);
1047         }
1048         socket_path = NULL;
1049     }
1050 
1051     if (qemu_init_main_loop(&local_err)) {
1052         error_report_err(local_err);
1053         exit(EXIT_FAILURE);
1054     }
1055 
1056     server_watch = qio_channel_add_watch(QIO_CHANNEL(server_ioc),
1057                                          G_IO_IN,
1058                                          accept_client,
1059                                          NULL, NULL);
1060 
1061 #ifdef CONFIG_LIBCAP
1062     if (drop_privileges() < 0) {
1063         error_report("Failed to drop privileges: %s", strerror(errno));
1064         exit(EXIT_FAILURE);
1065     }
1066 #endif
1067 
1068     if (daemonize) {
1069         if (daemon(0, 0) < 0) {
1070             error_report("Failed to daemonize: %s", strerror(errno));
1071             exit(EXIT_FAILURE);
1072         }
1073         write_pidfile();
1074     }
1075 
1076     state = RUNNING;
1077     do {
1078         main_loop_wait(false);
1079         if (state == TERMINATE) {
1080             state = TERMINATING;
1081             close_server_socket();
1082         }
1083     } while (num_active_sockets > 0);
1084 
1085     exit(EXIT_SUCCESS);
1086 }
1087