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