xref: /openbmc/qemu/scsi/qemu-pr-helper.c (revision d2dfe0b5)
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     multipath_conf = mpath_lib_init();
284 }
285 
286 static int is_mpath(int fd)
287 {
288     struct dm_ioctl dm = { .flags = DM_NOFLUSH_FLAG };
289     struct dm_target_spec *tgt;
290 
291     tgt = dm_dev_ioctl(fd, DM_TABLE_STATUS, &dm);
292     if (!tgt) {
293         if (errno == ENXIO) {
294             return 0;
295         }
296         perror("ioctl");
297         exit(EXIT_FAILURE);
298     }
299     return !strncmp(tgt->target_type, "multipath", DM_MAX_TYPE_NAME);
300 }
301 
302 static SCSISense mpath_generic_sense(int r)
303 {
304     switch (r) {
305     case MPATH_PR_SENSE_NOT_READY:
306          return SENSE_CODE(NOT_READY);
307     case MPATH_PR_SENSE_MEDIUM_ERROR:
308          return SENSE_CODE(READ_ERROR);
309     case MPATH_PR_SENSE_HARDWARE_ERROR:
310          return SENSE_CODE(TARGET_FAILURE);
311     case MPATH_PR_SENSE_ABORTED_COMMAND:
312          return SENSE_CODE(IO_ERROR);
313     default:
314          abort();
315     }
316 }
317 
318 static int coroutine_fn mpath_reconstruct_sense(int fd, int r, uint8_t *sense)
319 {
320     switch (r) {
321     case MPATH_PR_SUCCESS:
322         return GOOD;
323     case MPATH_PR_SENSE_NOT_READY:
324     case MPATH_PR_SENSE_MEDIUM_ERROR:
325     case MPATH_PR_SENSE_HARDWARE_ERROR:
326     case MPATH_PR_SENSE_ABORTED_COMMAND:
327         {
328             /* libmpathpersist ate the exact sense.  Try to find it by
329              * issuing TEST UNIT READY.
330              */
331             uint8_t cdb[6] = { TEST_UNIT_READY };
332             int sz = 0;
333             int ret = do_sgio(fd, cdb, sense, NULL, &sz, SG_DXFER_NONE);
334 
335             if (ret != GOOD) {
336                 return ret;
337             }
338             scsi_build_sense(sense, mpath_generic_sense(r));
339             return CHECK_CONDITION;
340         }
341 
342     case MPATH_PR_SENSE_UNIT_ATTENTION:
343         /* Congratulations libmpathpersist, you ruined the Unit Attention...
344          * Return a heavyweight one.
345          */
346         scsi_build_sense(sense, SENSE_CODE(SCSI_BUS_RESET));
347         return CHECK_CONDITION;
348     case MPATH_PR_SENSE_INVALID_OP:
349         /* Only one valid sense.  */
350         scsi_build_sense(sense, SENSE_CODE(INVALID_OPCODE));
351         return CHECK_CONDITION;
352     case MPATH_PR_ILLEGAL_REQ:
353         /* Guess.  */
354         scsi_build_sense(sense, SENSE_CODE(INVALID_PARAM));
355         return CHECK_CONDITION;
356     case MPATH_PR_NO_SENSE:
357         scsi_build_sense(sense, SENSE_CODE(NO_SENSE));
358         return CHECK_CONDITION;
359 
360     case MPATH_PR_RESERV_CONFLICT:
361         return RESERVATION_CONFLICT;
362 
363     case MPATH_PR_OTHER:
364     default:
365         scsi_build_sense(sense, SENSE_CODE(LUN_COMM_FAILURE));
366         return CHECK_CONDITION;
367     }
368 }
369 
370 static int coroutine_fn multipath_pr_in(int fd, const uint8_t *cdb, uint8_t *sense,
371                                         uint8_t *data, int sz)
372 {
373     int rq_servact = cdb[1];
374     struct prin_resp resp;
375     size_t written;
376     int r;
377 
378     switch (rq_servact) {
379     case MPATH_PRIN_RKEY_SA:
380     case MPATH_PRIN_RRES_SA:
381     case MPATH_PRIN_RCAP_SA:
382         break;
383     case MPATH_PRIN_RFSTAT_SA:
384         /* Nobody implements it anyway, so bail out. */
385     default:
386         /* Cannot parse any other output.  */
387         scsi_build_sense(sense, SENSE_CODE(INVALID_FIELD));
388         return CHECK_CONDITION;
389     }
390 
391     r = mpath_persistent_reserve_in(fd, rq_servact, &resp, noisy, verbose);
392     if (r == MPATH_PR_SUCCESS) {
393         switch (rq_servact) {
394         case MPATH_PRIN_RKEY_SA:
395         case MPATH_PRIN_RRES_SA: {
396             struct prin_readdescr *out = &resp.prin_descriptor.prin_readkeys;
397             assert(sz >= 8);
398             written = MIN(out->additional_length + 8, sz);
399             stl_be_p(&data[0], out->prgeneration);
400             stl_be_p(&data[4], out->additional_length);
401             memcpy(&data[8], out->key_list, written - 8);
402             break;
403         }
404         case MPATH_PRIN_RCAP_SA: {
405             struct prin_capdescr *out = &resp.prin_descriptor.prin_readcap;
406             assert(sz >= 6);
407             written = 6;
408             stw_be_p(&data[0], out->length);
409             data[2] = out->flags[0];
410             data[3] = out->flags[1];
411             stw_be_p(&data[4], out->pr_type_mask);
412             break;
413         }
414         default:
415             scsi_build_sense(sense, SENSE_CODE(INVALID_OPCODE));
416             return CHECK_CONDITION;
417         }
418         assert(written <= sz);
419         memset(data + written, 0, sz - written);
420     }
421 
422     return mpath_reconstruct_sense(fd, r, sense);
423 }
424 
425 static int coroutine_fn multipath_pr_out(int fd, const uint8_t *cdb, uint8_t *sense,
426                                          const uint8_t *param, int sz)
427 {
428     int rq_servact = cdb[1];
429     int rq_scope = cdb[2] >> 4;
430     int rq_type = cdb[2] & 0xf;
431     g_autofree struct prout_param_descriptor *paramp = NULL;
432     char transportids[PR_HELPER_DATA_SIZE];
433     int r;
434 
435     paramp = g_malloc0(sizeof(struct prout_param_descriptor)
436                        + sizeof(struct transportid *) * MPATH_MX_TIDS);
437 
438     if (sz < PR_OUT_FIXED_PARAM_SIZE) {
439         /* Illegal request, Parameter list length error.  This isn't fatal;
440          * we have read the data, send an error without closing the socket.
441          */
442         scsi_build_sense(sense, SENSE_CODE(INVALID_PARAM_LEN));
443         return CHECK_CONDITION;
444     }
445 
446     switch (rq_servact) {
447     case MPATH_PROUT_REG_SA:
448     case MPATH_PROUT_RES_SA:
449     case MPATH_PROUT_REL_SA:
450     case MPATH_PROUT_CLEAR_SA:
451     case MPATH_PROUT_PREE_SA:
452     case MPATH_PROUT_PREE_AB_SA:
453     case MPATH_PROUT_REG_IGN_SA:
454         break;
455     case MPATH_PROUT_REG_MOV_SA:
456         /* Not supported by struct prout_param_descriptor.  */
457     default:
458         /* Cannot parse any other input.  */
459         scsi_build_sense(sense, SENSE_CODE(INVALID_FIELD));
460         return CHECK_CONDITION;
461     }
462 
463     /* Convert input data, especially transport IDs, to the structs
464      * used by libmpathpersist (which, of course, will immediately
465      * do the opposite).
466      */
467     memcpy(&paramp->key, &param[0], 8);
468     memcpy(&paramp->sa_key, &param[8], 8);
469     paramp->sa_flags = param[20];
470     if (sz > PR_OUT_FIXED_PARAM_SIZE) {
471         size_t transportid_len;
472         int i, j;
473         if (sz < PR_OUT_FIXED_PARAM_SIZE + 4) {
474             scsi_build_sense(sense, SENSE_CODE(INVALID_PARAM_LEN));
475             return CHECK_CONDITION;
476         }
477         transportid_len = ldl_be_p(&param[24]) + PR_OUT_FIXED_PARAM_SIZE + 4;
478         if (transportid_len > sz) {
479             scsi_build_sense(sense, SENSE_CODE(INVALID_PARAM));
480             return CHECK_CONDITION;
481         }
482         for (i = PR_OUT_FIXED_PARAM_SIZE + 4, j = 0; i < transportid_len; ) {
483             struct transportid *id = (struct transportid *) &transportids[j];
484             int len;
485 
486             id->format_code = param[i] & 0xc0;
487             id->protocol_id = param[i] & 0x0f;
488             switch (param[i] & 0xcf) {
489             case 0:
490                 /* FC transport.  */
491                 if (i + 24 > transportid_len) {
492                     goto illegal_req;
493                 }
494                 memcpy(id->n_port_name, &param[i + 8], 8);
495                 j += offsetof(struct transportid, n_port_name[8]);
496                 i += 24;
497                 break;
498             case 5:
499             case 0x45:
500                 /* iSCSI transport.  */
501                 len = lduw_be_p(&param[i + 2]);
502                 if (len > 252 || (len & 3) || i + len + 4 > transportid_len) {
503                     /* For format code 00, the standard says the maximum is 223
504                      * plus the NUL terminator.  For format code 01 there is no
505                      * maximum length, but libmpathpersist ignores the first
506                      * byte of id->iscsi_name so our maximum is 252.
507                      */
508                     goto illegal_req;
509                 }
510                 if (memchr(&param[i + 4], 0, len) == NULL) {
511                     goto illegal_req;
512                 }
513                 memcpy(id->iscsi_name, &param[i + 2], len + 2);
514                 j += offsetof(struct transportid, iscsi_name[len + 2]);
515                 i += len + 4;
516                 break;
517             case 6:
518                 /* SAS transport.  */
519                 if (i + 24 > transportid_len) {
520                     goto illegal_req;
521                 }
522                 memcpy(id->sas_address, &param[i + 4], 8);
523                 j += offsetof(struct transportid, sas_address[8]);
524                 i += 24;
525                 break;
526             default:
527             illegal_req:
528                 scsi_build_sense(sense, SENSE_CODE(INVALID_PARAM));
529                 return CHECK_CONDITION;
530             }
531 
532             assert(paramp->num_transportid < MPATH_MX_TIDS);
533             paramp->trnptid_list[paramp->num_transportid++] = id;
534         }
535     }
536 
537     r = mpath_persistent_reserve_out(fd, rq_servact, rq_scope, rq_type,
538                                      paramp, noisy, verbose);
539     return mpath_reconstruct_sense(fd, r, sense);
540 }
541 #endif
542 
543 static int coroutine_fn do_pr_in(int fd, const uint8_t *cdb, uint8_t *sense,
544                                  uint8_t *data, int *resp_sz)
545 {
546 #ifdef CONFIG_MPATH
547     if (is_mpath(fd)) {
548         /* multipath_pr_in fills the whole input buffer.  */
549         int r = multipath_pr_in(fd, cdb, sense, data, *resp_sz);
550         if (r != GOOD) {
551             *resp_sz = 0;
552         }
553         return r;
554     }
555 #endif
556 
557     return do_sgio(fd, cdb, sense, data, resp_sz,
558                    SG_DXFER_FROM_DEV);
559 }
560 
561 static int coroutine_fn do_pr_out(int fd, const uint8_t *cdb, uint8_t *sense,
562                                   const uint8_t *param, int sz)
563 {
564     int resp_sz;
565 
566     if ((fcntl(fd, F_GETFL) & O_ACCMODE) == O_RDONLY) {
567         scsi_build_sense(sense, SENSE_CODE(INVALID_OPCODE));
568         return CHECK_CONDITION;
569     }
570 
571 #ifdef CONFIG_MPATH
572     if (is_mpath(fd)) {
573         return multipath_pr_out(fd, cdb, sense, param, sz);
574     }
575 #endif
576 
577     resp_sz = sz;
578     return do_sgio(fd, cdb, sense, (uint8_t *)param, &resp_sz,
579                    SG_DXFER_TO_DEV);
580 }
581 
582 /* Client */
583 
584 typedef struct PRHelperClient {
585     QIOChannelSocket *ioc;
586     Coroutine *co;
587     int fd;
588     uint8_t data[PR_HELPER_DATA_SIZE];
589 } PRHelperClient;
590 
591 typedef struct PRHelperRequest {
592     int fd;
593     size_t sz;
594     uint8_t cdb[PR_HELPER_CDB_SIZE];
595 } PRHelperRequest;
596 
597 static int coroutine_fn prh_read(PRHelperClient *client, void *buf, int sz,
598                                  Error **errp)
599 {
600     int ret = 0;
601 
602     while (sz > 0) {
603         int *fds = NULL;
604         size_t nfds = 0;
605         int i;
606         struct iovec iov;
607         ssize_t n_read;
608 
609         iov.iov_base = buf;
610         iov.iov_len = sz;
611         n_read = qio_channel_readv_full(QIO_CHANNEL(client->ioc), &iov, 1,
612                                         &fds, &nfds, 0, errp);
613 
614         if (n_read == QIO_CHANNEL_ERR_BLOCK) {
615             qio_channel_yield(QIO_CHANNEL(client->ioc), G_IO_IN);
616             continue;
617         }
618         if (n_read <= 0) {
619             ret = n_read ? n_read : -1;
620             goto err;
621         }
622 
623         /* Stash one file descriptor per request.  */
624         if (nfds) {
625             bool too_many = false;
626             for (i = 0; i < nfds; i++) {
627                 if (client->fd == -1) {
628                     client->fd = fds[i];
629                 } else {
630                     close(fds[i]);
631                     too_many = true;
632                 }
633             }
634             g_free(fds);
635             if (too_many) {
636                 ret = -1;
637                 goto err;
638             }
639         }
640 
641         buf += n_read;
642         sz -= n_read;
643     }
644 
645     return 0;
646 
647 err:
648     if (client->fd != -1) {
649         close(client->fd);
650         client->fd = -1;
651     }
652     return ret;
653 }
654 
655 static int coroutine_fn prh_read_request(PRHelperClient *client,
656                                          PRHelperRequest *req,
657                                          PRHelperResponse *resp, Error **errp)
658 {
659     uint32_t sz;
660 
661     if (prh_read(client, req->cdb, sizeof(req->cdb), NULL) < 0) {
662         return -1;
663     }
664 
665     if (client->fd == -1) {
666         error_setg(errp, "No file descriptor in request.");
667         return -1;
668     }
669 
670     if (req->cdb[0] != PERSISTENT_RESERVE_OUT &&
671         req->cdb[0] != PERSISTENT_RESERVE_IN) {
672         error_setg(errp, "Invalid CDB, closing socket.");
673         goto out_close;
674     }
675 
676     sz = scsi_cdb_xfer(req->cdb);
677     if (sz > sizeof(client->data)) {
678         goto out_close;
679     }
680 
681     if (req->cdb[0] == PERSISTENT_RESERVE_OUT) {
682         if (qio_channel_read_all(QIO_CHANNEL(client->ioc),
683                                  (char *)client->data, sz,
684                                  errp) < 0) {
685             goto out_close;
686         }
687     }
688 
689     req->fd = client->fd;
690     req->sz = sz;
691     client->fd = -1;
692     return sz;
693 
694 out_close:
695     close(client->fd);
696     client->fd = -1;
697     return -1;
698 }
699 
700 static int coroutine_fn prh_write_response(PRHelperClient *client,
701                                            PRHelperRequest *req,
702                                            PRHelperResponse *resp, Error **errp)
703 {
704     ssize_t r;
705     size_t sz;
706 
707     if (req->cdb[0] == PERSISTENT_RESERVE_IN && resp->result == GOOD) {
708         assert(resp->sz <= req->sz && resp->sz <= sizeof(client->data));
709     } else {
710         assert(resp->sz == 0);
711     }
712 
713     sz = resp->sz;
714 
715     resp->result = cpu_to_be32(resp->result);
716     resp->sz = cpu_to_be32(resp->sz);
717     r = qio_channel_write_all(QIO_CHANNEL(client->ioc),
718                               (char *) resp, sizeof(*resp), errp);
719     if (r < 0) {
720         return r;
721     }
722 
723     r = qio_channel_write_all(QIO_CHANNEL(client->ioc),
724                               (char *) client->data,
725                               sz, errp);
726     return r < 0 ? r : 0;
727 }
728 
729 static void coroutine_fn prh_co_entry(void *opaque)
730 {
731     PRHelperClient *client = opaque;
732     Error *local_err = NULL;
733     uint32_t flags;
734     int r;
735 
736     qio_channel_set_blocking(QIO_CHANNEL(client->ioc),
737                              false, NULL);
738     qio_channel_attach_aio_context(QIO_CHANNEL(client->ioc),
739                                    qemu_get_aio_context());
740 
741     /* A very simple negotiation for future extensibility.  No features
742      * are defined so write 0.
743      */
744     flags = cpu_to_be32(0);
745     r = qio_channel_write_all(QIO_CHANNEL(client->ioc),
746                              (char *) &flags, sizeof(flags), NULL);
747     if (r < 0) {
748         goto out;
749     }
750 
751     r = qio_channel_read_all(QIO_CHANNEL(client->ioc),
752                              (char *) &flags, sizeof(flags), NULL);
753     if (be32_to_cpu(flags) != 0 || r < 0) {
754         goto out;
755     }
756 
757     while (qatomic_read(&state) == RUNNING) {
758         PRHelperRequest req;
759         PRHelperResponse resp;
760         int sz;
761 
762         sz = prh_read_request(client, &req, &resp, &local_err);
763         if (sz < 0) {
764             break;
765         }
766 
767         num_active_sockets++;
768         if (req.cdb[0] == PERSISTENT_RESERVE_OUT) {
769             r = do_pr_out(req.fd, req.cdb, resp.sense,
770                           client->data, sz);
771             resp.sz = 0;
772         } else {
773             resp.sz = sizeof(client->data);
774             r = do_pr_in(req.fd, req.cdb, resp.sense,
775                          client->data, &resp.sz);
776             resp.sz = MIN(resp.sz, sz);
777         }
778         num_active_sockets--;
779         close(req.fd);
780         if (r == -1) {
781             break;
782         }
783         resp.result = r;
784 
785         if (prh_write_response(client, &req, &resp, &local_err) < 0) {
786             break;
787         }
788     }
789 
790     if (local_err) {
791         if (verbose == 0) {
792             error_free(local_err);
793         } else {
794             error_report_err(local_err);
795         }
796     }
797 
798 out:
799     qio_channel_detach_aio_context(QIO_CHANNEL(client->ioc));
800     object_unref(OBJECT(client->ioc));
801     g_free(client);
802 }
803 
804 static gboolean accept_client(QIOChannel *ioc, GIOCondition cond, gpointer opaque)
805 {
806     QIOChannelSocket *cioc;
807     PRHelperClient *prh;
808 
809     cioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc),
810                                      NULL);
811     if (!cioc) {
812         return TRUE;
813     }
814 
815     prh = g_new(PRHelperClient, 1);
816     prh->ioc = cioc;
817     prh->fd = -1;
818     prh->co = qemu_coroutine_create(prh_co_entry, prh);
819     qemu_coroutine_enter(prh->co);
820 
821     return TRUE;
822 }
823 
824 static void termsig_handler(int signum)
825 {
826     qatomic_cmpxchg(&state, RUNNING, TERMINATE);
827     qemu_notify_event();
828 }
829 
830 static void close_server_socket(void)
831 {
832     assert(server_ioc);
833 
834     g_source_remove(server_watch);
835     server_watch = -1;
836     object_unref(OBJECT(server_ioc));
837     num_active_sockets--;
838 }
839 
840 #ifdef CONFIG_LIBCAP_NG
841 static int drop_privileges(void)
842 {
843     /* clear all capabilities */
844     capng_clear(CAPNG_SELECT_BOTH);
845 
846     if (capng_update(CAPNG_ADD, CAPNG_EFFECTIVE | CAPNG_PERMITTED,
847                      CAP_SYS_RAWIO) < 0) {
848         return -1;
849     }
850 
851 #ifdef CONFIG_MPATH
852     /* For /dev/mapper/control ioctls */
853     if (capng_update(CAPNG_ADD, CAPNG_EFFECTIVE | CAPNG_PERMITTED,
854                      CAP_SYS_ADMIN) < 0) {
855         return -1;
856     }
857 #endif
858 
859     /* Change user/group id, retaining the capabilities.  Because file descriptors
860      * are passed via SCM_RIGHTS, we don't need supplementary groups (and in
861      * fact the helper can run as "nobody").
862      */
863     if (capng_change_id(uid != -1 ? uid : getuid(),
864                         gid != -1 ? gid : getgid(),
865                         CAPNG_DROP_SUPP_GRP | CAPNG_CLEAR_BOUNDING)) {
866         return -1;
867     }
868 
869     return 0;
870 }
871 #endif
872 
873 int main(int argc, char **argv)
874 {
875     const char *sopt = "hVk:f:dT:u:g:vq";
876     struct option lopt[] = {
877         { "help", no_argument, NULL, 'h' },
878         { "version", no_argument, NULL, 'V' },
879         { "socket", required_argument, NULL, 'k' },
880         { "pidfile", required_argument, NULL, 'f' },
881         { "daemon", no_argument, NULL, 'd' },
882         { "trace", required_argument, NULL, 'T' },
883         { "user", required_argument, NULL, 'u' },
884         { "group", required_argument, NULL, 'g' },
885         { "verbose", no_argument, NULL, 'v' },
886         { "quiet", no_argument, NULL, 'q' },
887         { NULL, 0, NULL, 0 }
888     };
889     int opt_ind = 0;
890     int loglevel = 1;
891     int quiet = 0;
892     int ch;
893     Error *local_err = NULL;
894     bool daemonize = false;
895     bool pidfile_specified = false;
896     bool socket_path_specified = false;
897     unsigned socket_activation;
898 
899     struct sigaction sa_sigterm;
900     memset(&sa_sigterm, 0, sizeof(sa_sigterm));
901     sa_sigterm.sa_handler = termsig_handler;
902     sigaction(SIGTERM, &sa_sigterm, NULL);
903     sigaction(SIGINT, &sa_sigterm, NULL);
904     sigaction(SIGHUP, &sa_sigterm, NULL);
905 
906     signal(SIGPIPE, SIG_IGN);
907 
908     error_init(argv[0]);
909     module_call_init(MODULE_INIT_TRACE);
910     module_call_init(MODULE_INIT_QOM);
911     qemu_add_opts(&qemu_trace_opts);
912     qemu_init_exec_dir(argv[0]);
913 
914     compute_default_paths();
915 
916     while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
917         switch (ch) {
918         case 'k':
919             g_free(socket_path);
920             socket_path = g_strdup(optarg);
921             socket_path_specified = true;
922             if (socket_path[0] != '/') {
923                 error_report("socket path must be absolute");
924                 exit(EXIT_FAILURE);
925             }
926             break;
927         case 'f':
928             g_free(pidfile);
929             pidfile = g_strdup(optarg);
930             pidfile_specified = true;
931             break;
932 #ifdef CONFIG_LIBCAP_NG
933         case 'u': {
934             unsigned long res;
935             struct passwd *userinfo = getpwnam(optarg);
936             if (userinfo) {
937                 uid = userinfo->pw_uid;
938             } else if (qemu_strtoul(optarg, NULL, 10, &res) == 0 &&
939                        (uid_t)res == res) {
940                 uid = res;
941             } else {
942                 error_report("invalid user '%s'", optarg);
943                 exit(EXIT_FAILURE);
944             }
945             break;
946         }
947         case 'g': {
948             unsigned long res;
949             struct group *groupinfo = getgrnam(optarg);
950             if (groupinfo) {
951                 gid = groupinfo->gr_gid;
952             } else if (qemu_strtoul(optarg, NULL, 10, &res) == 0 &&
953                        (gid_t)res == res) {
954                 gid = res;
955             } else {
956                 error_report("invalid group '%s'", optarg);
957                 exit(EXIT_FAILURE);
958             }
959             break;
960         }
961 #else
962         case 'u':
963         case 'g':
964             error_report("-%c not supported by this %s", ch, argv[0]);
965             exit(1);
966 #endif
967         case 'd':
968             daemonize = true;
969             break;
970         case 'q':
971             quiet = 1;
972             break;
973         case 'v':
974             ++loglevel;
975             break;
976         case 'T':
977             trace_opt_parse(optarg);
978             break;
979         case 'V':
980             version(argv[0]);
981             exit(EXIT_SUCCESS);
982             break;
983         case 'h':
984             usage(argv[0]);
985             exit(EXIT_SUCCESS);
986             break;
987         case '?':
988             error_report("Try `%s --help' for more information.", argv[0]);
989             exit(EXIT_FAILURE);
990         }
991     }
992 
993     /* set verbosity */
994     noisy = !quiet && (loglevel >= 3);
995     verbose = quiet ? 0 : MIN(loglevel, 3);
996 
997     if (!trace_init_backends()) {
998         exit(EXIT_FAILURE);
999     }
1000     trace_init_file();
1001     qemu_set_log(LOG_TRACE, &error_fatal);
1002 
1003 #ifdef CONFIG_MPATH
1004     dm_init();
1005     multipath_pr_init();
1006 #endif
1007 
1008     socket_activation = check_socket_activation();
1009     if (socket_activation == 0) {
1010         SocketAddress saddr;
1011         saddr = (SocketAddress){
1012             .type = SOCKET_ADDRESS_TYPE_UNIX,
1013             .u.q_unix.path = socket_path,
1014         };
1015         server_ioc = qio_channel_socket_new();
1016         if (qio_channel_socket_listen_sync(server_ioc, &saddr,
1017                                            1, &local_err) < 0) {
1018             object_unref(OBJECT(server_ioc));
1019             error_report_err(local_err);
1020             return 1;
1021         }
1022     } else {
1023         /* Using socket activation - check user didn't use -p etc. */
1024         if (socket_path_specified) {
1025             error_report("Unix socket can't be set when using socket activation");
1026             exit(EXIT_FAILURE);
1027         }
1028 
1029         /* Can only listen on a single socket.  */
1030         if (socket_activation > 1) {
1031             error_report("%s does not support socket activation with LISTEN_FDS > 1",
1032                          argv[0]);
1033             exit(EXIT_FAILURE);
1034         }
1035         server_ioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD,
1036                                                &local_err);
1037         if (server_ioc == NULL) {
1038             error_reportf_err(local_err,
1039                               "Failed to use socket activation: ");
1040             exit(EXIT_FAILURE);
1041         }
1042     }
1043 
1044     qemu_init_main_loop(&error_fatal);
1045 
1046     server_watch = qio_channel_add_watch(QIO_CHANNEL(server_ioc),
1047                                          G_IO_IN,
1048                                          accept_client,
1049                                          NULL, NULL);
1050 
1051     if (daemonize) {
1052         if (daemon(0, 0) < 0) {
1053             error_report("Failed to daemonize: %s", strerror(errno));
1054             exit(EXIT_FAILURE);
1055         }
1056     }
1057 
1058     if (daemonize || pidfile_specified) {
1059         qemu_write_pidfile(pidfile, &error_fatal);
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