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