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