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