1 /*
2 * vircommand.c: Child command execution
3 *
4 * Copyright (C) 2010-2014 Red Hat, Inc.
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library. If not, see
18 * <http://www.gnu.org/licenses/>.
19 *
20 */
21
22 #include <config.h>
23
24 #ifndef WIN32
25 # include <poll.h>
26 #endif
27 #include <signal.h>
28 #include <stdarg.h>
29 #include <sys/stat.h>
30 #ifndef WIN32
31 # include <sys/wait.h>
32 #endif
33 #include <fcntl.h>
34 #include <unistd.h>
35
36 #if WITH_CAPNG
37 # include <cap-ng.h>
38 #endif
39
40 #if defined(WITH_SECDRIVER_SELINUX)
41 # include <selinux/selinux.h>
42 #endif
43 #if defined(WITH_SECDRIVER_APPARMOR)
44 # include <sys/apparmor.h>
45 #endif
46
47 #define LIBVIRT_VIRCOMMANDPRIV_H_ALLOW
48 #include "viralloc.h"
49 #include "vircommandpriv.h"
50 #include "virerror.h"
51 #include "virutil.h"
52 #include "virlog.h"
53 #include "virfile.h"
54 #include "virpidfile.h"
55 #include "virprocess.h"
56 #include "virbuffer.h"
57 #include "virthread.h"
58 #include "virstring.h"
59
60 #define VIR_FROM_THIS VIR_FROM_NONE
61
62 VIR_LOG_INIT("util.command");
63
64 /* Flags for virExec */
65 enum {
66 VIR_EXEC_NONE = 0,
67 VIR_EXEC_NONBLOCK = (1 << 0),
68 VIR_EXEC_DAEMON = (1 << 1),
69 VIR_EXEC_CLEAR_CAPS = (1 << 2),
70 VIR_EXEC_RUN_SYNC = (1 << 3),
71 VIR_EXEC_ASYNC_IO = (1 << 4),
72 };
73
74 typedef struct _virCommandFD virCommandFD;
75 struct _virCommandFD {
76 int fd;
77 unsigned int flags;
78 };
79
80 typedef struct _virCommandSendBuffer virCommandSendBuffer;
81 struct _virCommandSendBuffer {
82 int fd;
83 unsigned char *buffer;
84 size_t buflen;
85 off_t offset;
86 };
87
88 struct _virCommand {
89 int has_error; /* 0 on success, -1 on error */
90
91 char **args;
92 size_t nargs;
93 size_t maxargs;
94
95 char **env;
96 size_t nenv;
97 size_t maxenv;
98
99 char *pwd;
100
101 size_t npassfd;
102 virCommandFD *passfd;
103
104 unsigned int flags;
105
106 char *inbuf;
107 char **outbuf;
108 char **errbuf;
109
110 int infd;
111 int inpipe;
112 int outfd;
113 int errfd;
114 int *outfdptr;
115 int *errfdptr;
116
117 virThread *asyncioThread;
118
119 bool handshake;
120 int handshakeWait[2];
121 int handshakeNotify[2];
122
123 virExecHook hook;
124 void *opaque;
125
126 pid_t pid;
127 char *pidfile;
128 bool reap;
129 bool rawStatus;
130
131 bool setMaxMemLock;
132 unsigned long long maxMemLock;
133 bool setMaxProcesses;
134 unsigned int maxProcesses;
135 bool setMaxFiles;
136 unsigned int maxFiles;
137 bool setMaxCore;
138 unsigned long long maxCore;
139
140 uid_t uid;
141 gid_t gid;
142 unsigned long long capabilities;
143 #if defined(WITH_SECDRIVER_SELINUX)
144 char *seLinuxLabel;
145 #endif
146 #if defined(WITH_SECDRIVER_APPARMOR)
147 char *appArmorProfile;
148 #endif
149 int mask;
150
151 virCommandSendBuffer *sendBuffers;
152 size_t numSendBuffers;
153 };
154
155 /* See virCommandSetDryRun for description for this variable */
156 static virBuffer *dryRunBuffer;
157 static bool dryRunBufferArgLinebreaks;
158 static bool dryRunBufferCommandStripPath;
159 static virCommandDryRunCallback dryRunCallback;
160 static void *dryRunOpaque;
161 #ifndef WIN32
162 static int dryRunStatus;
163 #endif /* !WIN32 */
164
165
166 static bool
virCommandHasError(virCommand * cmd)167 virCommandHasError(virCommand *cmd)
168 {
169 return !cmd || cmd->has_error != 0;
170 }
171
172
173 static int
virCommandRaiseError(virCommand * cmd)174 virCommandRaiseError(virCommand *cmd)
175 {
176 if (!cmd || cmd->has_error != 0) {
177 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
178 _("invalid use of command API"));
179 return -1;
180 }
181
182 return 0;
183 }
184
185
186 /*
187 * virCommandFDIsSet:
188 * @cmd: pointer to virCommand
189 * @fd: file descriptor to query
190 *
191 * Check if FD is already in @set or not.
192 *
193 * Returns true if @set contains @fd,
194 * false otherwise.
195 */
196 static bool
virCommandFDIsSet(virCommand * cmd,int fd)197 virCommandFDIsSet(virCommand *cmd,
198 int fd)
199 {
200 size_t i = 0;
201 if (!cmd)
202 return false;
203
204 while (i < cmd->npassfd)
205 if (cmd->passfd[i++].fd == fd)
206 return true;
207
208 return false;
209 }
210
211 /*
212 * virCommandFDSet:
213 * @cmd: pointer to virCommand
214 * @fd: file descriptor to pass
215 * @flags: extra flags; binary-OR of virCommandPassFDFlags
216 *
217 * This is practically generalized implementation
218 * of FD_SET() as we do not want to be limited
219 * by FD_SETSIZE.
220 */
221 static void
virCommandFDSet(virCommand * cmd,int fd,unsigned int flags)222 virCommandFDSet(virCommand *cmd,
223 int fd,
224 unsigned int flags)
225 {
226 if (virCommandFDIsSet(cmd, fd))
227 return;
228
229 VIR_EXPAND_N(cmd->passfd, cmd->npassfd, 1);
230
231 cmd->passfd[cmd->npassfd - 1].fd = fd;
232 cmd->passfd[cmd->npassfd - 1].flags = flags;
233 }
234
235 #ifndef WIN32
236
virDummyHandler(int sig G_GNUC_UNUSED)237 static void virDummyHandler(int sig G_GNUC_UNUSED)
238 {
239 }
240
241 /**
242 * virFork:
243 *
244 * Wrapper around fork() that avoids various race/deadlock conditions.
245 *
246 * Like fork(), there are several return possibilities:
247 * 1. No child was created: the return is -1, errno is set, and an error
248 * message has been reported. The semantics of virWaitProcess() recognize
249 * this to avoid clobbering the error message from here.
250 * 2. This is the parent: the return is > 0. The parent can now attempt
251 * to interact with the child (but be aware that unlike raw fork(), the
252 * child may not return - some failures in the child result in this
253 * function calling _exit(EXIT_CANCELED) if the child cannot be set up
254 * correctly).
255 * 3. This is the child: the return is 0. If this happens, the parent
256 * is also guaranteed to return.
257 */
258 pid_t
virFork(void)259 virFork(void)
260 {
261 sigset_t oldmask, newmask;
262 struct sigaction sig_action;
263 int saved_errno;
264 pid_t pid;
265
266 /*
267 * Need to block signals now, so that child process can safely
268 * kill off caller's signal handlers without a race.
269 */
270 sigfillset(&newmask);
271 if (pthread_sigmask(SIG_SETMASK, &newmask, &oldmask) != 0) {
272 virReportSystemError(errno,
273 "%s", _("cannot block signals"));
274 return -1;
275 }
276
277 /* Ensure we hold the logging lock, to protect child processes
278 * from deadlocking on another thread's inherited mutex state */
279 virLogLock();
280
281 pid = fork();
282 saved_errno = errno; /* save for caller */
283
284 /* Unlock for both parent and child process */
285 virLogUnlock();
286
287 if (pid < 0) {
288 /* attempt to restore signal mask, but ignore failure, to
289 * avoid obscuring the fork failure */
290 ignore_value(pthread_sigmask(SIG_SETMASK, &oldmask, NULL));
291 virReportSystemError(saved_errno,
292 "%s", _("cannot fork child process"));
293 errno = saved_errno;
294
295 } else if (pid) {
296 /* parent process */
297
298 /* Restore our original signal mask now that the child is
299 * safely running. Only documented failures are EFAULT (not
300 * possible, since we are using just-grabbed mask) or EINVAL
301 * (not possible, since we are using correct arguments). */
302 ignore_value(pthread_sigmask(SIG_SETMASK, &oldmask, NULL));
303
304 } else {
305 /* child process */
306
307 int logprio;
308 size_t i;
309
310 /* Remove any error callback so errors in child now get sent
311 * to stderr where they stand a fighting chance of being seen
312 * and logged */
313 virSetErrorFunc(NULL, NULL);
314 virSetErrorLogPriorityFunc(NULL);
315
316 /* Make sure any hook logging is sent to stderr, since child
317 * process may close the logfile FDs */
318 logprio = virLogGetDefaultPriority();
319 virLogReset();
320 virLogSetDefaultPriority(logprio);
321
322 /* Clear out all signal handlers from parent so nothing
323 * unexpected can happen in our child once we unblock
324 * signals */
325 sig_action.sa_handler = SIG_DFL;
326 sig_action.sa_flags = 0;
327 sigemptyset(&sig_action.sa_mask);
328
329 for (i = 1; i < NSIG; i++) {
330 /* Only possible errors are EFAULT or EINVAL The former
331 * won't happen, the latter we expect, so no need to check
332 * return value */
333 ignore_value(sigaction(i, &sig_action, NULL));
334 }
335
336 /* Code that runs between fork & execve might trigger
337 * SIG_PIPE, so we must explicitly set that to a no-op
338 * handler. This handler will get reset to SIG_DFL when
339 * execve() runs
340 */
341 sig_action.sa_handler = virDummyHandler;
342 ignore_value(sigaction(SIGPIPE, &sig_action, NULL));
343
344 /* Unmask all signals in child, since we've no idea what the
345 * caller's done with their signal mask and don't want to
346 * propagate that to children */
347 sigemptyset(&newmask);
348 if (pthread_sigmask(SIG_SETMASK, &newmask, NULL) != 0) {
349 virReportSystemError(errno, "%s", _("cannot unblock signals"));
350 virDispatchError(NULL);
351 _exit(EXIT_CANCELED);
352 }
353 }
354 return pid;
355 }
356
357 /*
358 * Ensure that *null is an fd visiting /dev/null. Return 0 on
359 * success, -1 on failure. Allows for lazy opening of shared
360 * /dev/null fd only as required.
361 */
362 static int
getDevNull(int * null)363 getDevNull(int *null)
364 {
365 if (*null == -1 && (*null = open("/dev/null", O_RDWR|O_CLOEXEC)) < 0) {
366 virReportSystemError(errno,
367 _("cannot open %s"),
368 "/dev/null");
369 return -1;
370 }
371 return 0;
372 }
373
374 /* Ensure that STD is an inheritable copy of FD. Return 0 on success,
375 * -1 on failure. */
376 static int
prepareStdFd(int fd,int std)377 prepareStdFd(int fd, int std)
378 {
379 if (fd == std)
380 return virSetInherit(fd, true);
381 if (dup2(fd, std) != std)
382 return -1;
383 return 0;
384 }
385
386 /* virCommandHandshakeChild:
387 *
388 * child side of handshake - called by child process in virExec() to
389 * indicate to parent that the child process has successfully
390 * completed its pre-exec initialization.
391 */
392 static int
virCommandHandshakeChild(virCommand * cmd)393 virCommandHandshakeChild(virCommand *cmd)
394 {
395 char c = '1';
396 int rv;
397
398 if (!cmd->handshake)
399 return true;
400
401 VIR_DEBUG("Notifying parent for handshake start on %d",
402 cmd->handshakeWait[1]);
403 if (safewrite(cmd->handshakeWait[1], &c, sizeof(c)) != sizeof(c)) {
404 virReportSystemError(errno, "%s",
405 _("Unable to notify parent process"));
406 return -1;
407 }
408
409 VIR_DEBUG("Waiting on parent for handshake complete on %d",
410 cmd->handshakeNotify[0]);
411 if ((rv = saferead(cmd->handshakeNotify[0], &c,
412 sizeof(c))) != sizeof(c)) {
413 if (rv < 0)
414 virReportSystemError(errno, "%s",
415 _("Unable to wait on parent process"));
416 else
417 virReportSystemError(EIO, "%s",
418 _("libvirtd quit during handshake"));
419 return -1;
420 }
421 if (c != '1') {
422 virReportSystemError(EINVAL,
423 _("Unexpected confirm code '%c' from parent"),
424 c);
425 return -1;
426 }
427 VIR_FORCE_CLOSE(cmd->handshakeWait[1]);
428 VIR_FORCE_CLOSE(cmd->handshakeNotify[0]);
429
430 VIR_DEBUG("Handshake with parent is done");
431 return 0;
432 }
433
434 static int
virExecCommon(virCommand * cmd,gid_t * groups,int ngroups)435 virExecCommon(virCommand *cmd, gid_t *groups, int ngroups)
436 {
437 if (cmd->uid != (uid_t)-1 || cmd->gid != (gid_t)-1 ||
438 cmd->capabilities || (cmd->flags & VIR_EXEC_CLEAR_CAPS)) {
439 VIR_DEBUG("Setting child uid:gid to %d:%d with caps %llx",
440 (int)cmd->uid, (int)cmd->gid, cmd->capabilities);
441 if (virSetUIDGIDWithCaps(cmd->uid, cmd->gid, groups, ngroups,
442 cmd->capabilities,
443 !!(cmd->flags & VIR_EXEC_CLEAR_CAPS)) < 0)
444 return -1;
445 }
446
447 if (cmd->pwd) {
448 VIR_DEBUG("Running child in %s", cmd->pwd);
449 if (chdir(cmd->pwd) < 0) {
450 virReportSystemError(errno,
451 _("Unable to change to %s"), cmd->pwd);
452 return -1;
453 }
454 }
455 return 0;
456 }
457
458 # ifdef __linux__
459 /* On Linux, we can utilize procfs and read the table of opened
460 * FDs and selectively close only those FDs we don't want to pass
461 * onto child process (well, the one we will exec soon since this
462 * is called from the child). */
463 static int
virCommandMassCloseGetFDsLinux(virCommand * cmd G_GNUC_UNUSED,virBitmap * fds)464 virCommandMassCloseGetFDsLinux(virCommand *cmd G_GNUC_UNUSED,
465 virBitmap *fds)
466 {
467 g_autoptr(DIR) dp = NULL;
468 struct dirent *entry;
469 const char *dirName = "/proc/self/fd";
470 int rc;
471
472 if (virDirOpen(&dp, dirName) < 0)
473 return -1;
474
475 while ((rc = virDirRead(dp, &entry, dirName)) > 0) {
476 int fd;
477
478 if (virStrToLong_i(entry->d_name, NULL, 10, &fd) < 0) {
479 virReportError(VIR_ERR_INTERNAL_ERROR,
480 _("unable to parse FD: %s"),
481 entry->d_name);
482 return -1;
483 }
484
485 ignore_value(virBitmapSetBit(fds, fd));
486 }
487
488 if (rc < 0)
489 return -1;
490
491 return 0;
492 }
493
494 # else /* !__linux__ */
495
496 static int
virCommandMassCloseGetFDsGeneric(virCommand * cmd G_GNUC_UNUSED,virBitmap * fds)497 virCommandMassCloseGetFDsGeneric(virCommand *cmd G_GNUC_UNUSED,
498 virBitmap *fds)
499 {
500 virBitmapSetAll(fds);
501 return 0;
502 }
503 # endif /* !__linux__ */
504
505 # ifdef __FreeBSD__
506
507 static int
virCommandMassClose(virCommand * cmd,int childin,int childout,int childerr)508 virCommandMassClose(virCommand *cmd,
509 int childin,
510 int childout,
511 int childerr)
512 {
513 int lastfd = -1;
514 int fd = -1;
515 size_t i;
516
517 /*
518 * Two phases of closing.
519 *
520 * The first (inefficient) phase iterates over FDs,
521 * preserving certain FDs we need to pass down, and
522 * closing others. The number of iterations is bounded
523 * to the number of the biggest FD we need to preserve.
524 *
525 * The second (speedy) phase uses closefrom() to cull
526 * all remaining FDs in the process.
527 *
528 * Usually the first phase will be fairly quick only
529 * processing a handful of low FD numbers, and thus using
530 * closefrom() is a massive win for high ulimit() NFILES
531 * values.
532 */
533 lastfd = MAX(lastfd, childin);
534 lastfd = MAX(lastfd, childout);
535 lastfd = MAX(lastfd, childerr);
536
537 for (i = 0; i < cmd->npassfd; i++)
538 lastfd = MAX(lastfd, cmd->passfd[i].fd);
539
540 for (fd = 0; fd <= lastfd; fd++) {
541 if (fd == childin || fd == childout || fd == childerr)
542 continue;
543 if (!virCommandFDIsSet(cmd, fd)) {
544 int tmpfd = fd;
545 VIR_MASS_CLOSE(tmpfd);
546 } else if (virSetInherit(fd, true) < 0) {
547 virReportSystemError(errno, _("failed to preserve fd %d"), fd);
548 return -1;
549 }
550 }
551
552 closefrom(lastfd + 1);
553
554 return 0;
555 }
556
557 # else /* ! __FreeBSD__ */
558
559 static int
virCommandMassClose(virCommand * cmd,int childin,int childout,int childerr)560 virCommandMassClose(virCommand *cmd,
561 int childin,
562 int childout,
563 int childerr)
564 {
565 g_autoptr(virBitmap) fds = NULL;
566 int openmax = sysconf(_SC_OPEN_MAX);
567 int fd = -1;
568
569 /* In general, it is not safe to call malloc() between fork() and exec()
570 * because the child might have forked at the worst possible time, i.e.
571 * when another thread was in malloc() and thus held its lock. That is to
572 * say, POSIX does not mandate malloc() to be async-safe. Fortunately,
573 * glibc developers are aware of this and made malloc() async-safe.
574 * Therefore we can safely allocate memory here (and transitively call
575 * opendir/readdir) without a deadlock. */
576
577 if (openmax < 0) {
578 virReportSystemError(errno, "%s", _("sysconf(_SC_OPEN_MAX) failed"));
579 return -1;
580 }
581
582 fds = virBitmapNew(openmax);
583
584 # ifdef __linux__
585 if (virCommandMassCloseGetFDsLinux(cmd, fds) < 0)
586 return -1;
587 # else
588 if (virCommandMassCloseGetFDsGeneric(cmd, fds) < 0)
589 return -1;
590 # endif
591
592 fd = virBitmapNextSetBit(fds, 2);
593 for (; fd >= 0; fd = virBitmapNextSetBit(fds, fd)) {
594 if (fd == childin || fd == childout || fd == childerr)
595 continue;
596 if (!virCommandFDIsSet(cmd, fd)) {
597 int tmpfd = fd;
598 VIR_MASS_CLOSE(tmpfd);
599 } else if (virSetInherit(fd, true) < 0) {
600 virReportSystemError(errno, _("failed to preserve fd %d"), fd);
601 return -1;
602 }
603 }
604
605 return 0;
606 }
607
608 # endif /* ! __FreeBSD__ */
609
610 /*
611 * virExec:
612 * @cmd virCommand * containing all information about the program to
613 * exec.
614 */
615 static int
virExec(virCommand * cmd)616 virExec(virCommand *cmd)
617 {
618 pid_t pid;
619 int null = -1;
620 int pipeout[2] = {-1, -1};
621 int pipeerr[2] = {-1, -1};
622 int pipesync[2] = {-1, -1};
623 int childin = cmd->infd;
624 int childout = -1;
625 int childerr = -1;
626 g_autofree char *binarystr = NULL;
627 const char *binary = NULL;
628 int ret;
629 g_autofree gid_t *groups = NULL;
630 int ngroups;
631
632 if (!g_path_is_absolute(cmd->args[0])) {
633 if (!(binary = binarystr = virFindFileInPath(cmd->args[0]))) {
634 virReportSystemError(ENOENT,
635 _("Cannot find '%s' in path"),
636 cmd->args[0]);
637 return -1;
638 }
639 } else {
640 binary = cmd->args[0];
641 }
642
643 if (childin < 0) {
644 if (getDevNull(&null) < 0)
645 goto cleanup;
646 childin = null;
647 }
648
649 if (cmd->outfdptr != NULL) {
650 if (*cmd->outfdptr == -1) {
651 if (virPipe(pipeout) < 0)
652 goto cleanup;
653
654 if ((cmd->flags & VIR_EXEC_NONBLOCK) &&
655 virSetNonBlock(pipeout[0]) == -1) {
656 virReportSystemError(errno, "%s",
657 _("Failed to set non-blocking file descriptor flag"));
658 goto cleanup;
659 }
660
661 childout = pipeout[1];
662 } else {
663 childout = *cmd->outfdptr;
664 }
665 } else {
666 if (getDevNull(&null) < 0)
667 goto cleanup;
668 childout = null;
669 }
670
671 if (cmd->errfdptr != NULL) {
672 if (cmd->errfdptr == cmd->outfdptr) {
673 childerr = childout;
674 } else if (*cmd->errfdptr == -1) {
675 if (virPipe(pipeerr) < 0)
676 goto cleanup;
677
678 if ((cmd->flags & VIR_EXEC_NONBLOCK) &&
679 virSetNonBlock(pipeerr[0]) == -1) {
680 virReportSystemError(errno, "%s",
681 _("Failed to set non-blocking file descriptor flag"));
682 goto cleanup;
683 }
684
685 childerr = pipeerr[1];
686 } else {
687 childerr = *cmd->errfdptr;
688 }
689 } else {
690 if (getDevNull(&null) < 0)
691 goto cleanup;
692 childerr = null;
693 }
694
695 if ((ngroups = virGetGroupList(cmd->uid, cmd->gid, &groups)) < 0)
696 goto cleanup;
697
698 pid = virFork();
699
700 if (pid < 0)
701 goto cleanup;
702
703 if (pid) { /* parent */
704 VIR_FORCE_CLOSE(null);
705 if (cmd->outfdptr && *cmd->outfdptr == -1) {
706 VIR_FORCE_CLOSE(pipeout[1]);
707 *cmd->outfdptr = pipeout[0];
708 }
709 if (cmd->errfdptr && *cmd->errfdptr == -1) {
710 VIR_FORCE_CLOSE(pipeerr[1]);
711 *cmd->errfdptr = pipeerr[0];
712 }
713
714 cmd->pid = pid;
715
716 return 0;
717 }
718
719 /* child */
720
721 if (cmd->mask)
722 umask(cmd->mask);
723 ret = EXIT_CANCELED;
724
725 if (virCommandMassClose(cmd, childin, childout, childerr) < 0)
726 goto fork_error;
727
728 if (prepareStdFd(childin, STDIN_FILENO) < 0) {
729 virReportSystemError(errno,
730 "%s", _("failed to setup stdin file handle"));
731 goto fork_error;
732 }
733 if (childout > 0 && prepareStdFd(childout, STDOUT_FILENO) < 0) {
734 virReportSystemError(errno,
735 "%s", _("failed to setup stdout file handle"));
736 goto fork_error;
737 }
738 if (childerr > 0 && prepareStdFd(childerr, STDERR_FILENO) < 0) {
739 virReportSystemError(errno,
740 "%s", _("failed to setup stderr file handle"));
741 goto fork_error;
742 }
743
744 if (childin != STDIN_FILENO && childin != null &&
745 childin != childerr && childin != childout)
746 VIR_FORCE_CLOSE(childin);
747 if (childout > STDERR_FILENO && childout != null && childout != childerr)
748 VIR_FORCE_CLOSE(childout);
749 if (childerr > STDERR_FILENO && childerr != null)
750 VIR_FORCE_CLOSE(childerr);
751 VIR_FORCE_CLOSE(null);
752
753 /* Initialize full logging for a while */
754 virLogSetFromEnv();
755
756 if (cmd->pidfile &&
757 virPipe(pipesync) < 0)
758 goto fork_error;
759
760 /* Daemonize as late as possible, so the parent process can detect
761 * the above errors with wait* */
762 if (cmd->flags & VIR_EXEC_DAEMON) {
763 char c;
764
765 if (setsid() < 0) {
766 virReportSystemError(errno,
767 "%s", _("cannot become session leader"));
768 goto fork_error;
769 }
770
771 if (chdir("/") < 0) {
772 virReportSystemError(errno,
773 "%s", _("cannot change to root directory"));
774 goto fork_error;
775 }
776
777 pid = fork();
778 if (pid < 0) {
779 virReportSystemError(errno,
780 "%s", _("cannot fork child process"));
781 goto fork_error;
782 }
783
784 if (pid > 0) {
785 /* At this point it's us and the child that holds the write end of
786 * the pipe open. Close the write end of the pipe, so that the pipe
787 * is fully closed if child dies prematurely. */
788 VIR_FORCE_CLOSE(pipesync[1]);
789 /* The parent expect us to have written the pid file before
790 * exiting. Wait here for the child to write it and signal us. */
791 if (cmd->pidfile &&
792 saferead(pipesync[0], &c, sizeof(c)) != sizeof(c)) {
793 virReportSystemError(errno, "%s",
794 _("Unable to wait for child process"));
795 _exit(EXIT_FAILURE);
796 }
797 _exit(EXIT_SUCCESS);
798 }
799 }
800
801 pid = getpid();
802
803 if (cmd->pidfile) {
804 int pidfilefd = -1;
805 char c;
806
807 pidfilefd = virPidFileAcquirePath(cmd->pidfile, false, pid);
808 if (pidfilefd < 0)
809 goto fork_error;
810 if (virSetInherit(pidfilefd, true) < 0) {
811 virReportSystemError(errno, "%s",
812 _("Cannot disable close-on-exec flag"));
813 goto fork_error;
814 }
815
816 c = '1';
817 if (safewrite(pipesync[1], &c, sizeof(c)) != sizeof(c)) {
818 virReportSystemError(errno, "%s", _("Unable to notify child process"));
819 goto fork_error;
820 }
821 VIR_FORCE_CLOSE(pipesync[0]);
822 VIR_FORCE_CLOSE(pipesync[1]);
823
824 /* pidfilefd is intentionally leaked. */
825 }
826
827 if (cmd->setMaxMemLock &&
828 virProcessSetMaxMemLock(pid, cmd->maxMemLock) < 0)
829 goto fork_error;
830 if (cmd->setMaxProcesses &&
831 virProcessSetMaxProcesses(pid, cmd->maxProcesses) < 0)
832 goto fork_error;
833 if (cmd->setMaxFiles &&
834 virProcessSetMaxFiles(pid, cmd->maxFiles) < 0)
835 goto fork_error;
836 if (cmd->setMaxCore &&
837 virProcessSetMaxCoreSize(pid, cmd->maxCore) < 0)
838 goto fork_error;
839
840 if (cmd->hook) {
841 VIR_DEBUG("Run hook %p %p", cmd->hook, cmd->opaque);
842 ret = cmd->hook(cmd->opaque);
843 VIR_DEBUG("Done hook %d", ret);
844 if (ret < 0)
845 goto fork_error;
846 }
847
848 # if defined(WITH_SECDRIVER_SELINUX)
849 if (cmd->seLinuxLabel) {
850 VIR_DEBUG("Setting child security label to %s", cmd->seLinuxLabel);
851 if (setexeccon_raw(cmd->seLinuxLabel) == -1) {
852 virReportSystemError(errno,
853 _("unable to set SELinux security context "
854 "'%s' for '%s'"),
855 cmd->seLinuxLabel, cmd->args[0]);
856 if (security_getenforce() == 1)
857 goto fork_error;
858 }
859 }
860 # endif
861 # if defined(WITH_SECDRIVER_APPARMOR)
862 if (cmd->appArmorProfile) {
863 VIR_DEBUG("Setting child AppArmor profile to %s", cmd->appArmorProfile);
864 if (aa_change_profile(cmd->appArmorProfile) < 0) {
865 virReportSystemError(errno,
866 _("unable to set AppArmor profile '%s' "
867 "for '%s'"),
868 cmd->appArmorProfile, cmd->args[0]);
869 goto fork_error;
870 }
871 }
872 # endif
873
874 if (virExecCommon(cmd, groups, ngroups) < 0)
875 goto fork_error;
876
877 if (virCommandHandshakeChild(cmd) < 0)
878 goto fork_error;
879
880 /* Close logging again to ensure no FDs leak to child */
881 virLogReset();
882
883 if (cmd->env)
884 execve(binary, cmd->args, cmd->env);
885 else
886 execv(binary, cmd->args);
887
888 ret = errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE;
889 virReportSystemError(errno,
890 _("cannot execute binary %s"),
891 cmd->args[0]);
892
893 fork_error:
894 virDispatchError(NULL);
895 _exit(ret);
896
897 cleanup:
898 /* This is cleanup of parent process only - child
899 should never jump here on error */
900
901 /* NB we don't virReportError() on any failures here
902 because the code which jumped here already raised
903 an error condition which we must not overwrite */
904 VIR_FORCE_CLOSE(pipeerr[0]);
905 VIR_FORCE_CLOSE(pipeerr[1]);
906 VIR_FORCE_CLOSE(pipeout[0]);
907 VIR_FORCE_CLOSE(pipeout[1]);
908 VIR_FORCE_CLOSE(null);
909 return -1;
910 }
911
912
913 #else /* WIN32 */
914
915 pid_t
virFork(void)916 virFork(void)
917 {
918 errno = ENOTSUP;
919
920 return -1;
921 }
922
923 #endif /* WIN32 */
924
925
926 /**
927 * virCommandNew:
928 * @binary: program to run
929 *
930 * Create a new command for named binary. If @binary is relative,
931 * it will be found via a PATH search of the parent's PATH (and not
932 * any altered PATH set by virCommandAddEnv* commands).
933 */
934 virCommand *
virCommandNew(const char * binary)935 virCommandNew(const char *binary)
936 {
937 const char *const args[] = { binary, NULL };
938
939 return virCommandNewArgs(args);
940 }
941
942 /**
943 * virCommandNewArgs:
944 * @args: array of arguments
945 *
946 * Create a new command with a NULL terminated
947 * set of args, taking binary from args[0]. More arguments can
948 * be added later. @args[0] is handled like @binary of virCommandNew.
949 */
950 virCommand *
virCommandNewArgs(const char * const * args)951 virCommandNewArgs(const char *const*args)
952 {
953 virCommand *cmd;
954
955 cmd = g_new0(virCommand, 1);
956
957 cmd->handshakeWait[0] = -1;
958 cmd->handshakeWait[1] = -1;
959 cmd->handshakeNotify[0] = -1;
960 cmd->handshakeNotify[1] = -1;
961
962 cmd->infd = cmd->inpipe = cmd->outfd = cmd->errfd = -1;
963 cmd->pid = -1;
964 cmd->uid = -1;
965 cmd->gid = -1;
966
967 virCommandAddArgSet(cmd, args);
968
969 return cmd;
970 }
971
972 /**
973 * virCommandNewArgList:
974 * @binary: program to run
975 * @...: additional arguments
976 *
977 * Create a new command with a NULL terminated
978 * list of args, starting with the binary to run. More arguments can
979 * be added later. @binary is handled as in virCommandNew.
980 */
981 virCommand *
virCommandNewArgList(const char * binary,...)982 virCommandNewArgList(const char *binary, ...)
983 {
984 virCommand *cmd;
985 va_list list;
986
987 va_start(list, binary);
988 cmd = virCommandNewVAList(binary, list);
989 va_end(list);
990
991 return cmd;
992 }
993
994 /**
995 * virCommandNewVAList:
996 * @binary: program to run
997 * @va_list: additional arguments
998 *
999 * Create a new command with a NULL terminated
1000 * variable argument list. @binary is handled as in virCommandNew.
1001 */
1002 virCommand *
virCommandNewVAList(const char * binary,va_list list)1003 virCommandNewVAList(const char *binary, va_list list)
1004 {
1005 virCommand *cmd = virCommandNew(binary);
1006 const char *arg;
1007
1008 if (virCommandHasError(cmd))
1009 return cmd;
1010
1011 while ((arg = va_arg(list, const char *)) != NULL)
1012 virCommandAddArg(cmd, arg);
1013 return cmd;
1014 }
1015
1016
1017 #define VIR_COMMAND_MAYBE_CLOSE_FD(fd, flags) \
1018 if ((fd > STDERR_FILENO) && \
1019 (flags & VIR_COMMAND_PASS_FD_CLOSE_PARENT)) \
1020 VIR_FORCE_CLOSE(fd)
1021
1022 /**
1023 * virCommandPassFDIndex:
1024 * @cmd: the command to modify
1025 * @fd: fd to reassign to the child
1026 * @flags: extra flags; binary-OR of virCommandPassFDFlags
1027 * @idx: pointer to fill with the index of the FD in the transfer set
1028 *
1029 * Transfer the specified file descriptor to the child, instead
1030 * of closing it on exec. @fd must not be one of the three
1031 * standard streams.
1032 *
1033 * If the flag VIR_COMMAND_PASS_FD_CLOSE_PARENT is set then fd will
1034 * be closed in the parent no later than Run/RunAsync/Free. The parent
1035 * should cease using the @fd when this call completes
1036 */
1037 void
virCommandPassFDIndex(virCommand * cmd,int fd,unsigned int flags,size_t * idx)1038 virCommandPassFDIndex(virCommand *cmd, int fd, unsigned int flags, size_t *idx)
1039 {
1040 if (!cmd) {
1041 VIR_COMMAND_MAYBE_CLOSE_FD(fd, flags);
1042 return;
1043 }
1044
1045 if (fd <= STDERR_FILENO) {
1046 VIR_DEBUG("invalid fd %d", fd);
1047 VIR_COMMAND_MAYBE_CLOSE_FD(fd, flags);
1048 if (!cmd->has_error)
1049 cmd->has_error = -1;
1050 return;
1051 }
1052
1053 virCommandFDSet(cmd, fd, flags);
1054
1055 if (idx)
1056 *idx = cmd->npassfd - 1;
1057 }
1058
1059 /**
1060 * virCommandPassFD:
1061 * @cmd: the command to modify
1062 * @fd: fd to reassign to the child
1063 * @flags: extra flags; binary-OR of virCommandPassFDFlags
1064 *
1065 * Transfer the specified file descriptor to the child, instead
1066 * of closing it on exec. @fd must not be one of the three
1067 * standard streams.
1068 *
1069 * If the flag VIR_COMMAND_PASS_FD_CLOSE_PARENT is set then fd will
1070 * be closed in the parent no later than Run/RunAsync/Free. The parent
1071 * should cease using the @fd when this call completes
1072 */
1073 void
virCommandPassFD(virCommand * cmd,int fd,unsigned int flags)1074 virCommandPassFD(virCommand *cmd, int fd, unsigned int flags)
1075 {
1076 virCommandPassFDIndex(cmd, fd, flags, NULL);
1077 }
1078
1079 /*
1080 * virCommandPassFDGetFDIndex:
1081 * @cmd: pointer to virCommand
1082 * @fd: FD to get index of
1083 *
1084 * Determine the index of the FD in the transfer set.
1085 *
1086 * Returns index >= 0 if @set contains @fd,
1087 * -1 otherwise.
1088 */
1089 int
virCommandPassFDGetFDIndex(virCommand * cmd,int fd)1090 virCommandPassFDGetFDIndex(virCommand *cmd, int fd)
1091 {
1092 size_t i = 0;
1093
1094 if (virCommandHasError(cmd))
1095 return -1;
1096
1097 while (i < cmd->npassfd) {
1098 if (cmd->passfd[i].fd == fd)
1099 return i;
1100 i++;
1101 }
1102
1103 return -1;
1104 }
1105
1106 /**
1107 * virCommandSetPidFile:
1108 * @cmd: the command to modify
1109 * @pidfile: filename to use
1110 *
1111 * Save the child PID in a pidfile. The pidfile will be populated before the
1112 * exec of the child and the child will inherit opened and locked FD to the
1113 * pidfile.
1114 */
1115 void
virCommandSetPidFile(virCommand * cmd,const char * pidfile)1116 virCommandSetPidFile(virCommand *cmd, const char *pidfile)
1117 {
1118 if (virCommandHasError(cmd))
1119 return;
1120
1121 VIR_FREE(cmd->pidfile);
1122 cmd->pidfile = g_strdup(pidfile);
1123 }
1124
1125
1126 gid_t
virCommandGetGID(virCommand * cmd)1127 virCommandGetGID(virCommand *cmd)
1128 {
1129 return cmd->gid;
1130 }
1131
1132
1133 uid_t
virCommandGetUID(virCommand * cmd)1134 virCommandGetUID(virCommand *cmd)
1135 {
1136 return cmd->uid;
1137 }
1138
1139
1140 void
virCommandSetGID(virCommand * cmd,gid_t gid)1141 virCommandSetGID(virCommand *cmd, gid_t gid)
1142 {
1143 if (virCommandHasError(cmd))
1144 return;
1145
1146 cmd->gid = gid;
1147 }
1148
1149 void
virCommandSetUID(virCommand * cmd,uid_t uid)1150 virCommandSetUID(virCommand *cmd, uid_t uid)
1151 {
1152 if (virCommandHasError(cmd))
1153 return;
1154
1155 cmd->uid = uid;
1156 }
1157
1158 void
virCommandSetMaxMemLock(virCommand * cmd,unsigned long long bytes)1159 virCommandSetMaxMemLock(virCommand *cmd, unsigned long long bytes)
1160 {
1161 if (virCommandHasError(cmd))
1162 return;
1163
1164 cmd->maxMemLock = bytes;
1165 cmd->setMaxMemLock = true;
1166 }
1167
1168 void
virCommandSetMaxProcesses(virCommand * cmd,unsigned int procs)1169 virCommandSetMaxProcesses(virCommand *cmd, unsigned int procs)
1170 {
1171 if (virCommandHasError(cmd))
1172 return;
1173
1174 cmd->maxProcesses = procs;
1175 cmd->setMaxProcesses = true;
1176 }
1177
1178 void
virCommandSetMaxFiles(virCommand * cmd,unsigned int files)1179 virCommandSetMaxFiles(virCommand *cmd, unsigned int files)
1180 {
1181 if (virCommandHasError(cmd))
1182 return;
1183
1184 cmd->maxFiles = files;
1185 cmd->setMaxFiles = true;
1186 }
1187
virCommandSetMaxCoreSize(virCommand * cmd,unsigned long long bytes)1188 void virCommandSetMaxCoreSize(virCommand *cmd, unsigned long long bytes)
1189 {
1190 if (virCommandHasError(cmd))
1191 return;
1192
1193 cmd->maxCore = bytes;
1194 cmd->setMaxCore = true;
1195 }
1196
virCommandSetUmask(virCommand * cmd,int mask)1197 void virCommandSetUmask(virCommand *cmd, int mask)
1198 {
1199 if (virCommandHasError(cmd))
1200 return;
1201
1202 cmd->mask = mask;
1203 }
1204
1205 /**
1206 * virCommandClearCaps:
1207 * @cmd: the command to modify
1208 *
1209 * Remove all capabilities from the child, after any hooks have been run.
1210 */
1211 void
virCommandClearCaps(virCommand * cmd)1212 virCommandClearCaps(virCommand *cmd)
1213 {
1214 if (virCommandHasError(cmd))
1215 return;
1216
1217 cmd->flags |= VIR_EXEC_CLEAR_CAPS;
1218 }
1219
1220 /**
1221 * virCommandAllowCap:
1222 * @cmd: the command to modify
1223 * @capability: what to allow
1224 *
1225 * Allow specific capabilities
1226 */
1227 void
virCommandAllowCap(virCommand * cmd,int capability)1228 virCommandAllowCap(virCommand *cmd,
1229 int capability)
1230 {
1231 if (virCommandHasError(cmd))
1232 return;
1233
1234 cmd->capabilities |= (1ULL << capability);
1235 }
1236
1237
1238 /**
1239 * virCommandSetSELinuxLabel:
1240 * @cmd: the command to modify
1241 * @label: the SELinux label to use for the child process
1242 *
1243 * Saves a copy of @label to use when setting the SELinux context
1244 * label (with setexeccon_raw()) after the child process has been
1245 * started. If SELinux isn't compiled into libvirt, or if label is
1246 * NULL, nothing will be done.
1247 */
1248 void
virCommandSetSELinuxLabel(virCommand * cmd,const char * label G_GNUC_UNUSED)1249 virCommandSetSELinuxLabel(virCommand *cmd,
1250 const char *label G_GNUC_UNUSED)
1251 {
1252 if (virCommandHasError(cmd))
1253 return;
1254
1255 #if defined(WITH_SECDRIVER_SELINUX)
1256 VIR_FREE(cmd->seLinuxLabel);
1257 cmd->seLinuxLabel = g_strdup(label);
1258 #endif
1259 return;
1260 }
1261
1262
1263 /**
1264 * virCommandSetAppArmorProfile:
1265 * @cmd: the command to modify
1266 * @profile: the AppArmor profile to use
1267 *
1268 * Saves a copy of @profile to use when aa_change_profile() after the
1269 * child process has been started. If AppArmor support isn't
1270 * configured into libvirt, or if profile is NULL, nothing will be done.
1271 */
1272 void
virCommandSetAppArmorProfile(virCommand * cmd,const char * profile G_GNUC_UNUSED)1273 virCommandSetAppArmorProfile(virCommand *cmd,
1274 const char *profile G_GNUC_UNUSED)
1275 {
1276 if (virCommandHasError(cmd))
1277 return;
1278
1279 #if defined(WITH_SECDRIVER_APPARMOR)
1280 VIR_FREE(cmd->appArmorProfile);
1281 cmd->appArmorProfile = g_strdup(profile);
1282 #endif
1283 return;
1284 }
1285
1286
1287 /**
1288 * virCommandDaemonize:
1289 * @cmd: the command to modify
1290 *
1291 * Daemonize the child process. The child will have a current working
1292 * directory of /, and must be started with virCommandRun, which will
1293 * complete as soon as the daemon grandchild has started.
1294 */
1295 void
virCommandDaemonize(virCommand * cmd)1296 virCommandDaemonize(virCommand *cmd)
1297 {
1298 if (virCommandHasError(cmd))
1299 return;
1300
1301 cmd->flags |= VIR_EXEC_DAEMON;
1302 }
1303
1304 /**
1305 * virCommandNonblockingFDs:
1306 * @cmd: the command to modify
1307 *
1308 * Set FDs created by virCommandSetOutputFD and virCommandSetErrorFD
1309 * as non-blocking in the parent.
1310 */
1311 void
virCommandNonblockingFDs(virCommand * cmd)1312 virCommandNonblockingFDs(virCommand *cmd)
1313 {
1314 if (virCommandHasError(cmd))
1315 return;
1316
1317 cmd->flags |= VIR_EXEC_NONBLOCK;
1318 }
1319
1320 /**
1321 * virCommandRawStatus:
1322 * @cmd: the command to modify
1323 *
1324 * Mark this command as returning raw exit status via virCommandRun() or
1325 * virCommandWait() (caller must use WIFEXITED() and friends, and can
1326 * detect death from signals) instead of the default of only allowing
1327 * normal exit status (caller must not use WEXITSTATUS(), and death from
1328 * signals returns -1).
1329 */
1330 void
virCommandRawStatus(virCommand * cmd)1331 virCommandRawStatus(virCommand *cmd)
1332 {
1333 if (virCommandHasError(cmd))
1334 return;
1335
1336 cmd->rawStatus = true;
1337 }
1338
1339 /* Add an environment variable to the cmd->env list. 'env' is a
1340 * string like "name=value". If the named environment variable is
1341 * already set, then it is replaced in the list.
1342 */
1343 static void
virCommandAddEnv(virCommand * cmd,char * envstr)1344 virCommandAddEnv(virCommand *cmd,
1345 char *envstr)
1346 {
1347 g_autofree char *env = envstr;
1348 size_t namelen;
1349 size_t i;
1350
1351 /* Search for the name in the existing environment. */
1352 namelen = strcspn(env, "=");
1353 for (i = 0; i < cmd->nenv; ++i) {
1354 /* + 1 because we want to match the '=' character too. */
1355 if (STREQLEN(cmd->env[i], env, namelen + 1)) {
1356 VIR_FREE(cmd->env[i]);
1357 cmd->env[i] = g_steal_pointer(&env);
1358 return;
1359 }
1360 }
1361
1362 /* Arg plus trailing NULL. */
1363 VIR_RESIZE_N(cmd->env, cmd->maxenv, cmd->nenv, 1 + 1);
1364
1365 cmd->env[cmd->nenv++] = g_steal_pointer(&env);
1366 }
1367
1368 /**
1369 * virCommandAddEnvFormat:
1370 * @cmd: the command to modify
1371 * @format: format of arguments, end result must be in name=value format
1372 * @...: arguments to be formatted
1373 *
1374 * Add an environment variable to the child created by a printf-style format.
1375 */
1376 void
virCommandAddEnvFormat(virCommand * cmd,const char * format,...)1377 virCommandAddEnvFormat(virCommand *cmd, const char *format, ...)
1378 {
1379 char *env;
1380 va_list list;
1381
1382 if (virCommandHasError(cmd))
1383 return;
1384
1385 va_start(list, format);
1386 env = g_strdup_vprintf(format, list);
1387 va_end(list);
1388
1389 virCommandAddEnv(cmd, env);
1390 }
1391
1392 /**
1393 * virCommandAddEnvPair:
1394 * @cmd: the command to modify
1395 * @name: variable name, must not contain =
1396 * @value: value to assign to name
1397 *
1398 * Add an environment variable to the child
1399 * using separate name & value strings
1400 */
1401 void
virCommandAddEnvPair(virCommand * cmd,const char * name,const char * value)1402 virCommandAddEnvPair(virCommand *cmd, const char *name, const char *value)
1403 {
1404 virCommandAddEnvFormat(cmd, "%s=%s", name, value);
1405 }
1406
1407
1408 /**
1409 * virCommandAddEnvString:
1410 * @cmd: the command to modify
1411 * @str: name=value format
1412 *
1413 * Add an environment variable to the child
1414 * using a preformatted env string FOO=BAR
1415 */
1416 void
virCommandAddEnvString(virCommand * cmd,const char * str)1417 virCommandAddEnvString(virCommand *cmd, const char *str)
1418 {
1419 char *env;
1420
1421 if (virCommandHasError(cmd))
1422 return;
1423
1424 env = g_strdup(str);
1425
1426 virCommandAddEnv(cmd, env);
1427 }
1428
1429
1430 /**
1431 * virCommandAddEnvPass:
1432 * @cmd: the command to modify
1433 * @name: the name to look up in current environment
1434 *
1435 * Pass an environment variable to the child
1436 * using current process's value
1437 */
1438 void
virCommandAddEnvPass(virCommand * cmd,const char * name)1439 virCommandAddEnvPass(virCommand *cmd, const char *name)
1440 {
1441 const char *value;
1442 if (virCommandHasError(cmd))
1443 return;
1444
1445 value = getenv(name);
1446 if (value)
1447 virCommandAddEnvPair(cmd, name, value);
1448 }
1449
1450
1451 /**
1452 * virCommandAddEnvPassCommon:
1453 * @cmd: the command to modify
1454 *
1455 * Set LC_ALL to C, and propagate other essential environment
1456 * variables (such as PATH) from the parent process.
1457 */
1458 void
virCommandAddEnvPassCommon(virCommand * cmd)1459 virCommandAddEnvPassCommon(virCommand *cmd)
1460 {
1461 if (virCommandHasError(cmd))
1462 return;
1463
1464 VIR_RESIZE_N(cmd->env, cmd->maxenv, cmd->nenv, 9);
1465
1466 virCommandAddEnvPair(cmd, "LC_ALL", "C");
1467
1468 virCommandAddEnvPass(cmd, "LD_PRELOAD");
1469 virCommandAddEnvPass(cmd, "LD_LIBRARY_PATH");
1470 virCommandAddEnvPass(cmd, "PATH");
1471 virCommandAddEnvPass(cmd, "HOME");
1472 virCommandAddEnvPass(cmd, "USER");
1473 virCommandAddEnvPass(cmd, "LOGNAME");
1474 virCommandAddEnvPass(cmd, "TMPDIR");
1475 }
1476
1477
1478 void
virCommandAddEnvXDG(virCommand * cmd,const char * baseDir)1479 virCommandAddEnvXDG(virCommand *cmd, const char *baseDir)
1480 {
1481 if (virCommandHasError(cmd))
1482 return;
1483
1484 VIR_RESIZE_N(cmd->env, cmd->maxenv, cmd->nenv, 3);
1485
1486 virCommandAddEnvFormat(cmd, "XDG_DATA_HOME=%s/%s",
1487 baseDir, ".local/share");
1488 virCommandAddEnvFormat(cmd, "XDG_CACHE_HOME=%s/%s",
1489 baseDir, ".cache");
1490 virCommandAddEnvFormat(cmd, "XDG_CONFIG_HOME=%s/%s",
1491 baseDir, ".config");
1492 }
1493
1494
1495 /**
1496 * virCommandAddArg:
1497 * @cmd: the command to modify
1498 * @val: the argument to add
1499 *
1500 * Add a command line argument to the child
1501 */
1502 void
virCommandAddArg(virCommand * cmd,const char * val)1503 virCommandAddArg(virCommand *cmd, const char *val)
1504 {
1505 if (virCommandHasError(cmd))
1506 return;
1507
1508 if (val == NULL) {
1509 cmd->has_error = EINVAL;
1510 return;
1511 }
1512
1513 /* Arg plus trailing NULL. */
1514 VIR_RESIZE_N(cmd->args, cmd->maxargs, cmd->nargs, 1 + 1);
1515
1516 cmd->args[cmd->nargs++] = g_strdup(val);
1517 }
1518
1519
1520 /**
1521 * virCommandAddArgBuffer:
1522 * @cmd: the command to modify
1523 * @buf: buffer that contains argument string, which will be reset on return
1524 *
1525 * Convert a buffer into a command line argument to the child.
1526 * Correctly transfers memory errors or contents from buf to cmd.
1527 */
1528 void
virCommandAddArgBuffer(virCommand * cmd,virBuffer * buf)1529 virCommandAddArgBuffer(virCommand *cmd, virBuffer *buf)
1530 {
1531 g_autofree char *str = virBufferContentAndReset(buf);
1532
1533 if (virCommandHasError(cmd))
1534 return;
1535
1536 if (!str)
1537 str = g_strdup("");
1538
1539 /* Arg plus trailing NULL. */
1540 VIR_RESIZE_N(cmd->args, cmd->maxargs, cmd->nargs, 1 + 1);
1541
1542 cmd->args[cmd->nargs] = g_steal_pointer(&str);
1543 cmd->nargs++;
1544 }
1545
1546
1547 /**
1548 * virCommandAddArgFormat:
1549 * @cmd: the command to modify
1550 * @format: format of arguments, end result must be in name=value format
1551 * @...: arguments to be formatted
1552 *
1553 * Add a command line argument created by a printf-style format.
1554 */
1555 void
virCommandAddArgFormat(virCommand * cmd,const char * format,...)1556 virCommandAddArgFormat(virCommand *cmd, const char *format, ...)
1557 {
1558 char *arg;
1559 va_list list;
1560
1561 if (virCommandHasError(cmd))
1562 return;
1563
1564 va_start(list, format);
1565 arg = g_strdup_vprintf(format, list);
1566 va_end(list);
1567
1568 /* Arg plus trailing NULL. */
1569 VIR_RESIZE_N(cmd->args, cmd->maxargs, cmd->nargs, 1 + 1);
1570
1571 cmd->args[cmd->nargs++] = arg;
1572 }
1573
1574 /**
1575 * virCommandAddArgPair:
1576 * @cmd: the command to modify
1577 * @name: left half of argument
1578 * @value: right half of argument
1579 *
1580 * Add "NAME=VAL" as a single command line argument to the child
1581 */
1582 void
virCommandAddArgPair(virCommand * cmd,const char * name,const char * val)1583 virCommandAddArgPair(virCommand *cmd, const char *name, const char *val)
1584 {
1585 if (name == NULL || val == NULL) {
1586 cmd->has_error = EINVAL;
1587 return;
1588 }
1589 virCommandAddArgFormat(cmd, "%s=%s", name, val);
1590 }
1591
1592 /**
1593 * virCommandAddArgSet:
1594 * @cmd: the command to modify
1595 * @vals: array of arguments to add
1596 *
1597 * Add a NULL terminated list of args
1598 */
1599 void
virCommandAddArgSet(virCommand * cmd,const char * const * vals)1600 virCommandAddArgSet(virCommand *cmd, const char *const*vals)
1601 {
1602 int narg = 0;
1603
1604 if (virCommandHasError(cmd))
1605 return;
1606
1607 if (vals[0] == NULL) {
1608 cmd->has_error = EINVAL;
1609 return;
1610 }
1611
1612 while (vals[narg] != NULL)
1613 narg++;
1614
1615 /* narg plus trailing NULL. */
1616 VIR_RESIZE_N(cmd->args, cmd->maxargs, cmd->nargs, narg + 1);
1617
1618 narg = 0;
1619 while (vals[narg] != NULL) {
1620 char *arg;
1621
1622 arg = g_strdup(vals[narg++]);
1623 cmd->args[cmd->nargs++] = arg;
1624 }
1625 }
1626
1627 /**
1628 * virCommandAddArgList:
1629 * @cmd: the command to modify
1630 * @...: list of arguments to add
1631 *
1632 * Add a NULL terminated list of args.
1633 */
1634 void
virCommandAddArgList(virCommand * cmd,...)1635 virCommandAddArgList(virCommand *cmd, ...)
1636 {
1637 va_list list;
1638 int narg = 0;
1639
1640 if (virCommandHasError(cmd))
1641 return;
1642
1643 va_start(list, cmd);
1644 while (va_arg(list, const char *) != NULL)
1645 narg++;
1646 va_end(list);
1647
1648 /* narg plus trailing NULL. */
1649 VIR_RESIZE_N(cmd->args, cmd->maxargs, cmd->nargs, narg + 1);
1650
1651 va_start(list, cmd);
1652 while (1) {
1653 char *arg = va_arg(list, char *);
1654 if (!arg)
1655 break;
1656 arg = g_strdup(arg);
1657 cmd->args[cmd->nargs++] = arg;
1658 }
1659 va_end(list);
1660 }
1661
1662 /**
1663 * virCommandSetWorkingDirectory:
1664 * @cmd: the command to modify
1665 * @pwd: directory to use
1666 *
1667 * Set the working directory of a non-daemon child process, rather
1668 * than the parent's working directory. Daemons automatically get /
1669 * without using this call.
1670 */
1671 void
virCommandSetWorkingDirectory(virCommand * cmd,const char * pwd)1672 virCommandSetWorkingDirectory(virCommand *cmd, const char *pwd)
1673 {
1674 if (virCommandHasError(cmd))
1675 return;
1676
1677 if (cmd->pwd) {
1678 cmd->has_error = -1;
1679 VIR_DEBUG("cannot set directory twice");
1680 } else {
1681 cmd->pwd = g_strdup(pwd);
1682 }
1683 }
1684
1685
1686 static int
virCommandGetNumSendBuffers(virCommand * cmd)1687 virCommandGetNumSendBuffers(virCommand *cmd)
1688 {
1689 return cmd->numSendBuffers;
1690 }
1691
1692
1693 static void
virCommandFreeSendBuffers(virCommand * cmd)1694 virCommandFreeSendBuffers(virCommand *cmd)
1695 {
1696 size_t i;
1697
1698 for (i = 0; i < virCommandGetNumSendBuffers(cmd); i++) {
1699 VIR_FORCE_CLOSE(cmd->sendBuffers[i].fd);
1700 VIR_FREE(cmd->sendBuffers[i].buffer);
1701 }
1702 VIR_FREE(cmd->sendBuffers);
1703 }
1704
1705
1706 #ifndef WIN32
1707 /**
1708 * virCommandSetSendBuffer
1709 * @cmd: the command to modify
1710 * @buffer: buffer to pass to the filedescriptror
1711 * @buflen: length of @buffer
1712 *
1713 * Registers @buffer as an input buffer for @cmd which will be accessible via
1714 * the returned file descriptor. The returned file descriptor is already
1715 * registered to be passed to @cmd, so callers must use it only to format the
1716 * appropriate argument of @cmd.
1717 *
1718 * @buffer is always stolen regardless of the return value. This function
1719 * doesn't raise a libvirt error, but rather propagates the error via virCommand.
1720 * Thus callers don't need to take a special action if -1 is returned.
1721 */
1722 int
virCommandSetSendBuffer(virCommand * cmd,unsigned char * buffer,size_t buflen)1723 virCommandSetSendBuffer(virCommand *cmd,
1724 unsigned char *buffer,
1725 size_t buflen)
1726 {
1727 g_autofree unsigned char *localbuf = g_steal_pointer(&buffer);
1728 int pipefd[2] = { -1, -1 };
1729 size_t i;
1730
1731 if (virCommandHasError(cmd))
1732 return -1;
1733
1734 if (virPipeQuiet(pipefd) < 0) {
1735 cmd->has_error = errno;
1736 return -1;
1737 }
1738
1739 if (fcntl(pipefd[1], F_SETFL, O_NONBLOCK) < 0) {
1740 cmd->has_error = errno;
1741 VIR_FORCE_CLOSE(pipefd[0]);
1742 VIR_FORCE_CLOSE(pipefd[1]);
1743 return -1;
1744 }
1745
1746 i = virCommandGetNumSendBuffers(cmd);
1747 VIR_REALLOC_N(cmd->sendBuffers, i + 1);
1748
1749 cmd->sendBuffers[i].fd = pipefd[1];
1750 cmd->sendBuffers[i].buffer = g_steal_pointer(&localbuf);
1751 cmd->sendBuffers[i].buflen = buflen;
1752 cmd->sendBuffers[i].offset = 0;
1753
1754 cmd->numSendBuffers++;
1755
1756 virCommandPassFD(cmd, pipefd[0], VIR_COMMAND_PASS_FD_CLOSE_PARENT);
1757
1758 return pipefd[0];
1759 }
1760
1761
1762 static int
virCommandSendBuffersFillPollfd(virCommand * cmd,struct pollfd * fds,int startidx)1763 virCommandSendBuffersFillPollfd(virCommand *cmd,
1764 struct pollfd *fds,
1765 int startidx)
1766 {
1767 size_t i, j;
1768
1769 for (i = 0, j = 0; i < virCommandGetNumSendBuffers(cmd); i++) {
1770 if (cmd->sendBuffers[i].fd >= 0) {
1771 fds[startidx + j].fd = cmd->sendBuffers[i].fd;
1772 fds[startidx + j].events = POLLOUT;
1773 fds[startidx + j].revents = 0;
1774 j++;
1775 }
1776 }
1777
1778 return j;
1779 }
1780
1781
1782 static int
virCommandSendBuffersHandlePoll(virCommand * cmd,struct pollfd * fds)1783 virCommandSendBuffersHandlePoll(virCommand *cmd,
1784 struct pollfd *fds)
1785 {
1786 size_t i;
1787 ssize_t done;
1788
1789 for (i = 0; i < virCommandGetNumSendBuffers(cmd); i++) {
1790 if (fds->fd == cmd->sendBuffers[i].fd)
1791 break;
1792 }
1793 if (i == virCommandGetNumSendBuffers(cmd))
1794 return 0;
1795
1796 done = write(fds->fd,
1797 cmd->sendBuffers[i].buffer + cmd->sendBuffers[i].offset,
1798 cmd->sendBuffers[i].buflen - cmd->sendBuffers[i].offset);
1799 if (done < 0) {
1800 if (errno == EPIPE) {
1801 VIR_DEBUG("child closed PIPE early, ignoring EPIPE "
1802 "on fd %d", cmd->sendBuffers[i].fd);
1803 VIR_FORCE_CLOSE(cmd->sendBuffers[i].fd);
1804 } else if (errno != EINTR && errno != EAGAIN) {
1805 virReportSystemError(errno, "%s",
1806 _("unable to write to child input"));
1807 return -1;
1808 }
1809 } else {
1810 cmd->sendBuffers[i].offset += done;
1811 if (cmd->sendBuffers[i].offset == cmd->sendBuffers[i].buflen)
1812 VIR_FORCE_CLOSE(cmd->sendBuffers[i].fd);
1813 }
1814 return 0;
1815 }
1816
1817 #endif /* !WIN32 */
1818
1819
1820 /**
1821 * virCommandSetInputBuffer:
1822 * @cmd: the command to modify
1823 * @inbuf: string to feed to stdin
1824 *
1825 * Feed the child's stdin from a string buffer. This requires the
1826 * use of virCommandRun() or combination of virCommandDoAsyncIO and
1827 * virCommandRunAsync. The buffer is forgotten after each @cmd run.
1828 */
1829 void
virCommandSetInputBuffer(virCommand * cmd,const char * inbuf)1830 virCommandSetInputBuffer(virCommand *cmd, const char *inbuf)
1831 {
1832 if (virCommandHasError(cmd))
1833 return;
1834
1835 if (cmd->infd != -1 || cmd->inbuf) {
1836 cmd->has_error = -1;
1837 VIR_DEBUG("cannot specify input twice");
1838 return;
1839 }
1840
1841 cmd->inbuf = g_strdup(inbuf);
1842 }
1843
1844
1845 /**
1846 * virCommandSetOutputBuffer:
1847 * @cmd: the command to modify
1848 * @outbuf: address of variable to store malloced result buffer
1849 *
1850 * Capture the child's stdout to a string buffer. *outbuf is
1851 * guaranteed to be allocated after successful virCommandRun or
1852 * virCommandWait, and is best-effort allocated after failed
1853 * virCommandRun or virCommandRunAsync; caller is responsible for
1854 * freeing *outbuf. This requires the use of virCommandRun() or
1855 * combination of virCommandDoAsyncIO and virCommandRunAsync. The
1856 * buffer is forgotten after each @cmd run.
1857 */
1858 void
virCommandSetOutputBuffer(virCommand * cmd,char ** outbuf)1859 virCommandSetOutputBuffer(virCommand *cmd, char **outbuf)
1860 {
1861 *outbuf = NULL;
1862 if (virCommandHasError(cmd))
1863 return;
1864
1865 if (cmd->outfdptr) {
1866 cmd->has_error = -1;
1867 VIR_DEBUG("cannot specify output twice");
1868 return;
1869 }
1870
1871 cmd->outbuf = outbuf;
1872 cmd->outfdptr = &cmd->outfd;
1873 }
1874
1875
1876 /**
1877 * virCommandSetErrorBuffer:
1878 * @cmd: the command to modify
1879 * @errbuf: address of variable to store malloced result buffer
1880 *
1881 * Capture the child's stderr to a string buffer. *errbuf is
1882 * guaranteed to be allocated after successful virCommandRun or
1883 * virCommandWait, and is best-effort allocated after failed
1884 * virCommandRun or virCommandRunAsync; caller is responsible for
1885 * freeing *errbuf. It is possible to pass the same pointer as
1886 * for virCommandSetOutputBuffer(), in which case the child
1887 * process will interleave all output into a single string. This
1888 * requires the use of virCommandRun() or combination of
1889 * virCommandDoAsyncIO and virCommandRunAsync.The buffer is
1890 * forgotten after each @cmd run.
1891 */
1892 void
virCommandSetErrorBuffer(virCommand * cmd,char ** errbuf)1893 virCommandSetErrorBuffer(virCommand *cmd, char **errbuf)
1894 {
1895 *errbuf = NULL;
1896 if (virCommandHasError(cmd))
1897 return;
1898
1899 if (cmd->errfdptr) {
1900 cmd->has_error = -1;
1901 VIR_DEBUG("cannot specify stderr twice");
1902 return;
1903 }
1904
1905 cmd->errbuf = errbuf;
1906 cmd->errfdptr = &cmd->errfd;
1907 }
1908
1909
1910 /**
1911 * virCommandSetInputFD:
1912 * @cmd: the command to modify
1913 * @infd: the descriptor to use
1914 *
1915 * Attach a file descriptor to the child's stdin
1916 */
1917 void
virCommandSetInputFD(virCommand * cmd,int infd)1918 virCommandSetInputFD(virCommand *cmd, int infd)
1919 {
1920 if (virCommandHasError(cmd))
1921 return;
1922
1923 if (cmd->infd != -1 || cmd->inbuf) {
1924 cmd->has_error = -1;
1925 VIR_DEBUG("cannot specify input twice");
1926 return;
1927 }
1928 if (infd < 0) {
1929 cmd->has_error = -1;
1930 VIR_DEBUG("cannot specify invalid input fd");
1931 return;
1932 }
1933
1934 cmd->infd = infd;
1935 }
1936
1937
1938 /**
1939 * virCommandSetOutputFD:
1940 * @cmd: the command to modify
1941 * @outfd: location of output fd
1942 *
1943 * Attach a file descriptor to the child's stdout. If *@outfd is -1 on
1944 * entry, then a pipe will be created and returned in this variable when
1945 * the child is run. Otherwise, *@outfd is used as the output.
1946 */
1947 void
virCommandSetOutputFD(virCommand * cmd,int * outfd)1948 virCommandSetOutputFD(virCommand *cmd, int *outfd)
1949 {
1950 if (virCommandHasError(cmd))
1951 return;
1952
1953 if (cmd->outfdptr) {
1954 cmd->has_error = -1;
1955 VIR_DEBUG("cannot specify output twice");
1956 return;
1957 }
1958
1959 cmd->outfdptr = outfd;
1960 }
1961
1962
1963 /**
1964 * virCommandSetErrorFD:
1965 * @cmd: the command to modify
1966 * @errfd: location of error fd
1967 *
1968 * Attach a file descriptor to the child's stderr. If *@errfd is -1 on
1969 * entry, then a pipe will be created and returned in this variable when
1970 * the child is run. Otherwise, *@errfd is used for error collection,
1971 * and may be the same as outfd given to virCommandSetOutputFD().
1972 */
1973 void
virCommandSetErrorFD(virCommand * cmd,int * errfd)1974 virCommandSetErrorFD(virCommand *cmd, int *errfd)
1975 {
1976 if (virCommandHasError(cmd))
1977 return;
1978
1979 if (cmd->errfdptr) {
1980 cmd->has_error = -1;
1981 VIR_DEBUG("cannot specify stderr twice");
1982 return;
1983 }
1984
1985 cmd->errfdptr = errfd;
1986 }
1987
1988
1989 /**
1990 * virCommandSetPreExecHook:
1991 * @cmd: the command to modify
1992 * @hook: the hook to run
1993 * @opaque: argument to pass to the hook
1994 *
1995 * Run HOOK(OPAQUE) in the child as the last thing before changing
1996 * directories, dropping capabilities, and executing the new process.
1997 * Force the child to fail if HOOK does not return zero.
1998 *
1999 * Since @hook runs in the child, it should be careful to avoid
2000 * any functions that are not async-signal-safe.
2001 */
2002 void
virCommandSetPreExecHook(virCommand * cmd,virExecHook hook,void * opaque)2003 virCommandSetPreExecHook(virCommand *cmd, virExecHook hook, void *opaque)
2004 {
2005 if (virCommandHasError(cmd))
2006 return;
2007
2008 if (cmd->hook) {
2009 cmd->has_error = -1;
2010 VIR_DEBUG("cannot specify hook twice");
2011 return;
2012 }
2013 cmd->hook = hook;
2014 cmd->opaque = opaque;
2015 }
2016
2017
2018 /**
2019 * virCommandWriteArgLog:
2020 * @cmd: the command to log
2021 * @logfd: where to log the results
2022 *
2023 * Call after adding all arguments and environment settings, but before
2024 * Run/RunAsync, to immediately output the environment and arguments of
2025 * cmd to logfd. If virCommandRun cannot succeed (because of an
2026 * out-of-memory condition while building cmd), nothing will be logged.
2027 */
2028 void
virCommandWriteArgLog(virCommand * cmd,int logfd)2029 virCommandWriteArgLog(virCommand *cmd, int logfd)
2030 {
2031 int ioError = 0;
2032 size_t i;
2033
2034 /* Any errors will be reported later by virCommandRun, which means
2035 * no command will be run, so there is nothing to log. */
2036 if (virCommandHasError(cmd))
2037 return;
2038
2039 for (i = 0; i < cmd->nenv; i++) {
2040 if (safewrite(logfd, cmd->env[i], strlen(cmd->env[i])) < 0)
2041 ioError = errno;
2042 if (safewrite(logfd, " ", 1) < 0)
2043 ioError = errno;
2044 }
2045 for (i = 0; i < cmd->nargs; i++) {
2046 if (safewrite(logfd, cmd->args[i], strlen(cmd->args[i])) < 0)
2047 ioError = errno;
2048 if (safewrite(logfd, i == cmd->nargs - 1 ? "\n" : " ", 1) < 0)
2049 ioError = errno;
2050 }
2051
2052 if (ioError) {
2053 VIR_WARN("Unable to write command %s args to logfile: %s",
2054 cmd->args[0], g_strerror(ioError));
2055 }
2056 }
2057
2058
2059 /**
2060 * virCommandToStringBuf:
2061 * @cmd: the command to convert
2062 * @buf: buffer to format @cmd into
2063 * @linebreaks: true to break line after each env var or option
2064 * @stripCommandPath: strip the path leading to the binary of @cmd
2065 *
2066 * Call after adding all arguments and environment settings, but
2067 * before Run/RunAsync, to return a string representation of the
2068 * environment and arguments of cmd, suitably quoted for pasting into
2069 * a shell. If virCommandRun cannot succeed (because of an
2070 * out-of-memory condition while building cmd), -1 will be returned.
2071 */
2072 int
virCommandToStringBuf(virCommand * cmd,virBuffer * buf,bool linebreaks,bool stripCommandPath)2073 virCommandToStringBuf(virCommand *cmd,
2074 virBuffer *buf,
2075 bool linebreaks,
2076 bool stripCommandPath)
2077 {
2078 size_t i;
2079 const char *command = cmd->args[0];
2080 g_autofree char *basename = NULL;
2081 bool had_option = false;
2082
2083 /* Cannot assume virCommandRun will be called; so report the error
2084 * now. If virCommandRun is called, it will report the same error. */
2085 if (virCommandHasError(cmd)) {
2086 virCommandRaiseError(cmd);
2087 return -1;
2088 }
2089
2090 for (i = 0; i < cmd->nenv; i++) {
2091 /* In shell, a='b c' has a different meaning than 'a=b c', so
2092 * we must determine where the '=' lives. */
2093 char *eq = strchr(cmd->env[i], '=');
2094
2095 if (!eq) {
2096 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2097 _("invalid use of command API"));
2098 return -1;
2099 }
2100 eq++;
2101 virBufferAdd(buf, cmd->env[i], eq - cmd->env[i]);
2102 virBufferEscapeShell(buf, eq);
2103 virBufferAddChar(buf, ' ');
2104 if (linebreaks)
2105 virBufferAddLit(buf, "\\\n");
2106 }
2107
2108 if (stripCommandPath)
2109 command = basename = g_path_get_basename(command);
2110
2111 virBufferEscapeShell(buf, command);
2112 for (i = 1; i < cmd->nargs; i++) {
2113 virBufferAddChar(buf, ' ');
2114
2115 if (linebreaks) {
2116 /* we don't want a linebreak only if
2117 * - the previous argument is an option (starts with '-')
2118 * - there was already an option and another option follows
2119 */
2120 bool linebreak = true;
2121
2122 if (cmd->args[i][0] != '-') {
2123 if (had_option) {
2124 size_t j;
2125 /* we know that arg[i - 1] is valid and arg[i] is not an option */
2126 for (j = i - 1; j < cmd->nargs; j++) {
2127 if (cmd->args[j][0] == '-') {
2128 linebreak = false;
2129 break;
2130 }
2131 }
2132 }
2133 } else {
2134 had_option = true;
2135 }
2136
2137 if (linebreak)
2138 virBufferAddLit(buf, "\\\n");
2139 }
2140 virBufferEscapeShell(buf, cmd->args[i]);
2141 }
2142
2143 return 0;
2144 }
2145
2146
2147 char *
virCommandToStringFull(virCommand * cmd,bool linebreaks,bool stripCommandPath)2148 virCommandToStringFull(virCommand *cmd,
2149 bool linebreaks,
2150 bool stripCommandPath)
2151 {
2152 g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
2153
2154 if (virCommandToStringBuf(cmd, &buf, linebreaks, stripCommandPath))
2155 return NULL;
2156
2157 return virBufferContentAndReset(&buf);
2158 }
2159
2160
2161 char *
virCommandToString(virCommand * cmd,bool linebreaks)2162 virCommandToString(virCommand *cmd,
2163 bool linebreaks)
2164 {
2165 return virCommandToStringFull(cmd, linebreaks, false);
2166 }
2167
2168
2169 int
virCommandGetArgList(virCommand * cmd,char *** args)2170 virCommandGetArgList(virCommand *cmd,
2171 char ***args)
2172 {
2173 size_t i;
2174
2175 if (virCommandHasError(cmd)) {
2176 virCommandRaiseError(cmd);
2177 return -1;
2178 }
2179
2180 *args = g_new0(char *, cmd->nargs);
2181
2182 for (i = 1; i < cmd->nargs; i++)
2183 (*args)[i - 1] = g_strdup(cmd->args[i]);
2184
2185 return 0;
2186 }
2187
2188
2189 #ifndef WIN32
2190 /*
2191 * Manage input and output to the child process.
2192 */
2193 static int
virCommandProcessIO(virCommand * cmd)2194 virCommandProcessIO(virCommand *cmd)
2195 {
2196 int outfd = -1, errfd = -1;
2197 size_t inlen = 0, outlen = 0, errlen = 0;
2198 size_t inoff = 0;
2199 int ret = 0;
2200 g_autofree struct pollfd *fds = NULL;
2201
2202 if (dryRunBuffer || dryRunCallback) {
2203 VIR_DEBUG("Dry run requested, skipping I/O processing");
2204 return 0;
2205 }
2206
2207 /* With an input buffer, feed data to child
2208 * via pipe */
2209 if (cmd->inbuf)
2210 inlen = strlen(cmd->inbuf);
2211
2212 /* With out/err buffer, the outfd/errfd have been filled with an
2213 * FD for us. Guarantee an allocated string with partial results
2214 * even if we encounter a later failure, as well as freeing any
2215 * results accumulated over a prior run of the same command. */
2216 if (cmd->outbuf) {
2217 outfd = cmd->outfd;
2218 VIR_FREE(*cmd->outbuf);
2219 *cmd->outbuf = g_new0(char, 1);
2220 }
2221 if (cmd->errbuf) {
2222 errfd = cmd->errfd;
2223 VIR_FREE(*cmd->errbuf);
2224 *cmd->errbuf = g_new0(char, 1);
2225 }
2226 if (ret == -1)
2227 goto cleanup;
2228 ret = -1;
2229
2230 fds = g_new0(struct pollfd, 3 + virCommandGetNumSendBuffers(cmd));
2231
2232 for (;;) {
2233 size_t i;
2234 int nfds = 0;
2235
2236 if (cmd->inpipe != -1) {
2237 fds[nfds].fd = cmd->inpipe;
2238 fds[nfds].events = POLLOUT;
2239 fds[nfds].revents = 0;
2240 nfds++;
2241 }
2242 if (outfd != -1) {
2243 fds[nfds].fd = outfd;
2244 fds[nfds].events = POLLIN;
2245 fds[nfds].revents = 0;
2246 nfds++;
2247 }
2248 if (errfd != -1) {
2249 fds[nfds].fd = errfd;
2250 fds[nfds].events = POLLIN;
2251 fds[nfds].revents = 0;
2252 nfds++;
2253 }
2254
2255 nfds += virCommandSendBuffersFillPollfd(cmd, fds, nfds);
2256
2257 if (nfds == 0)
2258 break;
2259
2260 if (poll(fds, nfds, -1) < 0) {
2261 if (errno == EAGAIN || errno == EINTR)
2262 continue;
2263 virReportSystemError(errno, "%s",
2264 _("unable to poll on child"));
2265 goto cleanup;
2266 }
2267
2268 for (i = 0; i < nfds; i++) {
2269 if (fds[i].revents & (POLLIN | POLLHUP | POLLERR) &&
2270 (fds[i].fd == errfd || fds[i].fd == outfd)) {
2271 char data[1024];
2272 char **buf;
2273 size_t *len;
2274 int done;
2275 if (fds[i].fd == outfd) {
2276 buf = cmd->outbuf;
2277 len = &outlen;
2278 } else {
2279 buf = cmd->errbuf;
2280 len = &errlen;
2281 }
2282 done = read(fds[i].fd, data, sizeof(data));
2283 if (done < 0) {
2284 if (errno != EINTR &&
2285 errno != EAGAIN) {
2286 virReportSystemError(errno, "%s",
2287 (fds[i].fd == outfd) ?
2288 _("unable to read child stdout") :
2289 _("unable to read child stderr"));
2290 goto cleanup;
2291 }
2292 } else if (done == 0) {
2293 if (fds[i].fd == outfd)
2294 outfd = -1;
2295 else
2296 errfd = -1;
2297 } else {
2298 VIR_REALLOC_N(*buf, *len + done + 1);
2299 memcpy(*buf + *len, data, done);
2300 *len += done;
2301 }
2302 }
2303
2304 if (fds[i].revents & (POLLOUT | POLLHUP | POLLERR) &&
2305 fds[i].fd == cmd->inpipe) {
2306 int done;
2307
2308 done = write(cmd->inpipe, cmd->inbuf + inoff,
2309 inlen - inoff);
2310 if (done < 0) {
2311 if (errno == EPIPE) {
2312 VIR_DEBUG("child closed stdin early, ignoring EPIPE "
2313 "on fd %d", cmd->inpipe);
2314 VIR_FORCE_CLOSE(cmd->inpipe);
2315 } else if (errno != EINTR && errno != EAGAIN) {
2316 virReportSystemError(errno, "%s",
2317 _("unable to write to child input"));
2318 goto cleanup;
2319 }
2320 } else {
2321 inoff += done;
2322 if (inoff == inlen)
2323 VIR_FORCE_CLOSE(cmd->inpipe);
2324 }
2325 } else if (fds[i].revents & (POLLOUT | POLLHUP | POLLERR)) {
2326 if (virCommandSendBuffersHandlePoll(cmd, &fds[i]) < 0)
2327 goto cleanup;
2328 }
2329 }
2330 }
2331
2332 ret = 0;
2333 cleanup:
2334 if (cmd->outbuf && *cmd->outbuf)
2335 (*cmd->outbuf)[outlen] = '\0';
2336 if (cmd->errbuf && *cmd->errbuf)
2337 (*cmd->errbuf)[errlen] = '\0';
2338 return ret;
2339 }
2340
2341 /**
2342 * virCommandExec:
2343 * @cmd: command to run
2344 * @groups: array of supplementary group IDs used for the command
2345 * @ngroups: number of group IDs in @groups
2346 *
2347 * Exec the command, replacing the current process. Meant to be called
2348 * in the hook after already forking / cloning, so does not attempt to
2349 * daemonize or preserve any FDs.
2350 *
2351 * Returns -1 on any error executing the command.
2352 * Will not return on success.
2353 */
virCommandExec(virCommand * cmd,gid_t * groups,int ngroups)2354 int virCommandExec(virCommand *cmd, gid_t *groups, int ngroups)
2355 {
2356 if (virCommandHasError(cmd)) {
2357 virCommandRaiseError(cmd);
2358 return -1;
2359 }
2360
2361 if (virExecCommon(cmd, groups, ngroups) < 0)
2362 return -1;
2363
2364 execve(cmd->args[0], cmd->args, cmd->env);
2365
2366 virReportSystemError(errno,
2367 _("cannot execute binary %s"),
2368 cmd->args[0]);
2369 return -1;
2370 }
2371
2372
2373 /**
2374 * virCommandRun:
2375 * @cmd: command to run
2376 * @exitstatus: optional status collection
2377 *
2378 * Run the command and wait for completion.
2379 * Returns -1 on any error executing the
2380 * command. Returns 0 if the command executed,
2381 * with the exit status set. If @exitstatus is NULL, then the
2382 * child must exit with status 0 for this to succeed. By default,
2383 * a non-NULL @exitstatus contains the normal exit status of the child
2384 * (death from a signal is treated as execution error); but if
2385 * virCommandRawStatus() was used, it instead contains the raw exit
2386 * status that the caller must then decipher using WIFEXITED() and friends.
2387 */
2388 int
virCommandRun(virCommand * cmd,int * exitstatus)2389 virCommandRun(virCommand *cmd, int *exitstatus)
2390 {
2391 int ret = 0;
2392 char *outbuf = NULL;
2393 char *errbuf = NULL;
2394 struct stat st;
2395 bool string_io;
2396 bool async_io = false;
2397 char *str;
2398 int tmpfd;
2399
2400 if (virCommandHasError(cmd)) {
2401 virCommandRaiseError(cmd);
2402 return -1;
2403 }
2404
2405 /* Avoid deadlock, by requiring that any open fd not under our
2406 * control must be visiting a regular file, or that we are
2407 * daemonized and no string io is required. */
2408 string_io = cmd->inbuf || cmd->outbuf || cmd->errbuf;
2409 if (cmd->infd != -1 &&
2410 (fstat(cmd->infd, &st) < 0 || !S_ISREG(st.st_mode)))
2411 async_io = true;
2412 if (cmd->outfdptr && cmd->outfdptr != &cmd->outfd &&
2413 (*cmd->outfdptr == -1 ||
2414 fstat(*cmd->outfdptr, &st) < 0 || !S_ISREG(st.st_mode)))
2415 async_io = true;
2416 if (cmd->errfdptr && cmd->errfdptr != &cmd->errfd &&
2417 (*cmd->errfdptr == -1 ||
2418 fstat(*cmd->errfdptr, &st) < 0 || !S_ISREG(st.st_mode)))
2419 async_io = true;
2420 if (async_io) {
2421 if (!(cmd->flags & VIR_EXEC_DAEMON) || string_io) {
2422 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2423 _("cannot mix caller fds with blocking execution"));
2424 return -1;
2425 }
2426 } else {
2427 if ((cmd->flags & VIR_EXEC_DAEMON) && string_io) {
2428 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2429 _("cannot mix string I/O with daemon"));
2430 return -1;
2431 }
2432 }
2433
2434 /* If caller requested the same string for stdout and stderr, then
2435 * merge those into one string. */
2436 if (cmd->outbuf && cmd->outbuf == cmd->errbuf) {
2437 cmd->errfdptr = &cmd->outfd;
2438 cmd->errbuf = NULL;
2439 }
2440
2441 /* If caller hasn't requested capture of stdout/err, then capture
2442 * it ourselves so we can log it. But the intermediate child for
2443 * a daemon has no expected output, and we don't want our
2444 * capturing pipes passed on to the daemon grandchild.
2445 */
2446 if (!(cmd->flags & VIR_EXEC_DAEMON)) {
2447 if (!cmd->outfdptr) {
2448 cmd->outfdptr = &cmd->outfd;
2449 cmd->outbuf = &outbuf;
2450 string_io = true;
2451 }
2452 if (!cmd->errfdptr) {
2453 cmd->errfdptr = &cmd->errfd;
2454 cmd->errbuf = &errbuf;
2455 string_io = true;
2456 }
2457 }
2458
2459 cmd->flags |= VIR_EXEC_RUN_SYNC;
2460 if (virCommandRunAsync(cmd, NULL) < 0) {
2461 cmd->has_error = -1;
2462 return -1;
2463 }
2464
2465 if (string_io) {
2466 VIR_FORCE_CLOSE(cmd->infd);
2467 ret = virCommandProcessIO(cmd);
2468 }
2469
2470 if (virCommandWait(cmd, exitstatus) < 0)
2471 ret = -1;
2472
2473 str = (exitstatus ? virProcessTranslateStatus(*exitstatus)
2474 : (char *) "status 0");
2475 VIR_DEBUG("Result %s, stdout: '%s' stderr: '%s'",
2476 NULLSTR(str),
2477 cmd->outbuf ? NULLSTR(*cmd->outbuf) : "(null)",
2478 cmd->errbuf ? NULLSTR(*cmd->errbuf) : "(null)");
2479 if (exitstatus)
2480 VIR_FREE(str);
2481
2482 /* Reset any capturing, in case caller runs
2483 * this identical command again */
2484 VIR_FORCE_CLOSE(cmd->inpipe);
2485 if (cmd->outbuf == &outbuf) {
2486 tmpfd = cmd->outfd;
2487 if (VIR_CLOSE(cmd->outfd) < 0)
2488 VIR_DEBUG("ignoring failed close on fd %d", tmpfd);
2489 cmd->outfdptr = NULL;
2490 cmd->outbuf = NULL;
2491 VIR_FREE(outbuf);
2492 }
2493 if (cmd->errbuf == &errbuf) {
2494 tmpfd = cmd->errfd;
2495 if (VIR_CLOSE(cmd->errfd) < 0)
2496 VIR_DEBUG("ignoring failed close on fd %d", tmpfd);
2497 cmd->errfdptr = NULL;
2498 cmd->errbuf = NULL;
2499 VIR_FREE(errbuf);
2500 }
2501
2502 return ret;
2503 }
2504
2505
2506 static void
virCommandDoAsyncIOHelper(void * opaque)2507 virCommandDoAsyncIOHelper(void *opaque)
2508 {
2509 virCommand *cmd = opaque;
2510 if (virCommandProcessIO(cmd) < 0) {
2511 /* If something went wrong, save errno or -1 */
2512 cmd->has_error = errno ? errno : -1;
2513 }
2514 }
2515
2516
2517 /**
2518 * virCommandRunAsync:
2519 * @cmd: command to start
2520 * @pid: optional variable to track child pid
2521 *
2522 * Run the command asynchronously
2523 * Returns -1 on any error executing the
2524 * command. Returns 0 if the command executed.
2525 *
2526 * There are two approaches to child process cleanup.
2527 * 1. Use auto-cleanup, by passing NULL for pid. The child will be
2528 * auto-reaped by virCommandFree, unless you reap it earlier via
2529 * virCommandWait or virCommandAbort. Good for where cmd is in
2530 * scope for the duration of the child process.
2531 * 2. Use manual cleanup, by passing the address of a pid_t variable
2532 * for pid. While cmd is still in scope, you may reap the child via
2533 * virCommandWait or virCommandAbort. But after virCommandFree, if
2534 * you have not yet reaped the child, then it continues to run until
2535 * you call virProcessWait or virProcessAbort.
2536 */
2537 int
virCommandRunAsync(virCommand * cmd,pid_t * pid)2538 virCommandRunAsync(virCommand *cmd, pid_t *pid)
2539 {
2540 int ret = -1;
2541 g_autofree char *str = NULL;
2542 size_t i;
2543 bool synchronous = false;
2544 int infd[2] = {-1, -1};
2545
2546 if (virCommandHasError(cmd)) {
2547 virCommandRaiseError(cmd);
2548 return -1;
2549 }
2550
2551 synchronous = cmd->flags & VIR_EXEC_RUN_SYNC;
2552 cmd->flags &= ~VIR_EXEC_RUN_SYNC;
2553
2554 /* Buffer management can only be requested via virCommandRun or
2555 * virCommandDoAsyncIO. */
2556 if (cmd->inbuf && cmd->infd == -1 &&
2557 (synchronous || cmd->flags & VIR_EXEC_ASYNC_IO)) {
2558 if (virPipe(infd) < 0) {
2559 cmd->has_error = -1;
2560 return -1;
2561 }
2562 cmd->infd = infd[0];
2563 cmd->inpipe = infd[1];
2564
2565 if (fcntl(cmd->inpipe, F_SETFL, O_NONBLOCK) < 0) {
2566 virReportSystemError(errno, "%s",
2567 _("fcntl failed to set O_NONBLOCK"));
2568 cmd->has_error = -1;
2569 ret = -1;
2570 goto cleanup;
2571 }
2572 } else if ((cmd->inbuf && cmd->infd == -1) ||
2573 (cmd->outbuf && cmd->outfdptr != &cmd->outfd) ||
2574 (cmd->errbuf && cmd->errfdptr != &cmd->errfd)) {
2575 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2576 _("cannot mix string I/O with asynchronous command"));
2577 return -1;
2578 }
2579
2580 if (cmd->pid != -1) {
2581 virReportError(VIR_ERR_INTERNAL_ERROR,
2582 _("command is already running as pid %lld"),
2583 (long long) cmd->pid);
2584 goto cleanup;
2585 }
2586
2587 if (!synchronous && (cmd->flags & VIR_EXEC_DAEMON)) {
2588 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2589 _("daemonized command cannot use virCommandRunAsync"));
2590 goto cleanup;
2591 }
2592 if (cmd->pwd && (cmd->flags & VIR_EXEC_DAEMON)) {
2593 virReportError(VIR_ERR_INTERNAL_ERROR,
2594 _("daemonized command cannot set working directory %s"),
2595 cmd->pwd);
2596 goto cleanup;
2597 }
2598 if (cmd->pidfile && !(cmd->flags & VIR_EXEC_DAEMON)) {
2599 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2600 _("creation of pid file requires daemonized command"));
2601 goto cleanup;
2602 }
2603
2604 if (dryRunBuffer || dryRunCallback) {
2605 g_autofree char *cmdstr = NULL;
2606 dryRunStatus = 0;
2607
2608 if (!(cmdstr = virCommandToStringFull(cmd, dryRunBufferArgLinebreaks,
2609 dryRunBufferCommandStripPath)))
2610 goto cleanup;
2611
2612 if (dryRunBuffer) {
2613 VIR_DEBUG("Dry run requested, appending stringified "
2614 "command to dryRunBuffer=%p", dryRunBuffer);
2615 virBufferAdd(dryRunBuffer, cmdstr, -1);
2616 virBufferAddChar(dryRunBuffer, '\n');
2617 }
2618 if (dryRunCallback) {
2619 dryRunCallback((const char *const*)cmd->args,
2620 (const char *const*)cmd->env,
2621 cmd->inbuf, cmd->outbuf, cmd->errbuf,
2622 &dryRunStatus, dryRunOpaque);
2623 }
2624 ret = 0;
2625 goto cleanup;
2626 }
2627
2628 str = virCommandToString(cmd, false);
2629 VIR_DEBUG("About to run %s", str ? str : cmd->args[0]);
2630 ret = virExec(cmd);
2631 VIR_DEBUG("Command result %d, with PID %d",
2632 ret, (int)cmd->pid);
2633
2634 for (i = 0; i < cmd->npassfd; i++) {
2635 if (cmd->passfd[i].flags & VIR_COMMAND_PASS_FD_CLOSE_PARENT)
2636 VIR_FORCE_CLOSE(cmd->passfd[i].fd);
2637 }
2638 cmd->npassfd = 0;
2639 VIR_FREE(cmd->passfd);
2640
2641 if (ret == 0 && pid)
2642 *pid = cmd->pid;
2643 else
2644 cmd->reap = true;
2645
2646 if (ret == 0 && cmd->flags & VIR_EXEC_ASYNC_IO) {
2647 if (cmd->inbuf)
2648 VIR_FORCE_CLOSE(cmd->infd);
2649 /* clear any error so we can catch if the helper thread reports one */
2650 cmd->has_error = 0;
2651 cmd->asyncioThread = g_new0(virThread, 1);
2652
2653 if (virThreadCreateFull(cmd->asyncioThread, true,
2654 virCommandDoAsyncIOHelper,
2655 "cmd-async-io", false, cmd) < 0) {
2656 virReportSystemError(errno, "%s",
2657 _("Unable to create thread "
2658 "to process command's IO"));
2659 VIR_FREE(cmd->asyncioThread);
2660 virCommandAbort(cmd);
2661 ret = -1;
2662 }
2663 }
2664
2665 cleanup:
2666 if (ret < 0) {
2667 VIR_FORCE_CLOSE(cmd->infd);
2668 VIR_FORCE_CLOSE(cmd->inpipe);
2669 }
2670 return ret;
2671 }
2672
2673
2674 /**
2675 * virCommandWait:
2676 * @cmd: command to wait on
2677 * @exitstatus: optional status collection
2678 *
2679 * Wait for the command previously started with virCommandRunAsync()
2680 * to complete. Return -1 on any error waiting for
2681 * completion. Returns 0 if the command
2682 * finished with the exit status set. If @exitstatus is NULL, then the
2683 * child must exit with status 0 for this to succeed. By default,
2684 * a non-NULL @exitstatus contains the normal exit status of the child
2685 * (death from a signal is treated as execution error); but if
2686 * virCommandRawStatus() was used, it instead contains the raw exit
2687 * status that the caller must then decipher using WIFEXITED() and friends.
2688 */
2689 int
virCommandWait(virCommand * cmd,int * exitstatus)2690 virCommandWait(virCommand *cmd, int *exitstatus)
2691 {
2692 int ret;
2693 int status = 0;
2694
2695 if (virCommandHasError(cmd)) {
2696 virCommandRaiseError(cmd);
2697 return -1;
2698 }
2699
2700 if (dryRunBuffer || dryRunCallback) {
2701 VIR_DEBUG("Dry run requested, returning status %d",
2702 dryRunStatus);
2703 if (exitstatus)
2704 *exitstatus = dryRunStatus;
2705 else if (dryRunStatus)
2706 return -1;
2707 return 0;
2708 }
2709
2710 if (cmd->pid == -1) {
2711 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2712 _("command is not yet running"));
2713 return -1;
2714 }
2715
2716 /* If virProcessWait reaps pid but then returns failure because
2717 * exitstatus was NULL, then a second virCommandWait would risk
2718 * calling waitpid on an unrelated process. Besides, that error
2719 * message is not as detailed as what we can provide. So, we
2720 * guarantee that virProcessWait only fails due to failure to wait,
2721 * and repeat the exitstatus check code ourselves. */
2722 ret = virProcessWait(cmd->pid, &status, true);
2723 if (cmd->flags & VIR_EXEC_ASYNC_IO) {
2724 cmd->flags &= ~VIR_EXEC_ASYNC_IO;
2725 virThreadJoin(cmd->asyncioThread);
2726 VIR_FREE(cmd->asyncioThread);
2727 VIR_FORCE_CLOSE(cmd->inpipe);
2728 if (cmd->has_error) {
2729 const char *msg = _("Error while processing command's IO");
2730 if (cmd->has_error < 0)
2731 virReportError(VIR_ERR_INTERNAL_ERROR, "%s", msg);
2732 else
2733 virReportSystemError(cmd->has_error, "%s", msg);
2734 ret = -1;
2735 }
2736 }
2737 if (ret == 0) {
2738 cmd->pid = -1;
2739 cmd->reap = false;
2740 if (exitstatus && (cmd->rawStatus || WIFEXITED(status))) {
2741 *exitstatus = cmd->rawStatus ? status : WEXITSTATUS(status);
2742 } else if (status) {
2743 g_autofree char *str = virCommandToString(cmd, false);
2744 g_autofree char *st = virProcessTranslateStatus(status);
2745 bool haveErrMsg = cmd->errbuf && *cmd->errbuf && (*cmd->errbuf)[0];
2746
2747 virReportError(VIR_ERR_INTERNAL_ERROR,
2748 _("Child process (%s) unexpected %s%s%s"),
2749 str ? str : cmd->args[0], NULLSTR(st),
2750 haveErrMsg ? ": " : "",
2751 haveErrMsg ? *cmd->errbuf : "");
2752 return -1;
2753 }
2754 }
2755
2756 return ret;
2757 }
2758
2759
2760 /**
2761 * virCommandAbort:
2762 * @cmd: command to abort
2763 *
2764 * Abort an async command if it is running, without issuing
2765 * any errors or affecting errno. Designed for error paths
2766 * where some but not all paths to the cleanup code might
2767 * have started the child process.
2768 */
2769 void
virCommandAbort(virCommand * cmd)2770 virCommandAbort(virCommand *cmd)
2771 {
2772 if (!cmd || cmd->pid == -1)
2773 return;
2774 virProcessAbort(cmd->pid);
2775 cmd->pid = -1;
2776 cmd->reap = false;
2777 }
2778
2779
2780 /**
2781 * virCommandRequireHandshake:
2782 * @cmd: command to modify
2783 *
2784 * Request that the child perform a handshake with
2785 * the parent when the hook function has completed
2786 * execution. The child will not exec() until the
2787 * parent has notified
2788 */
virCommandRequireHandshake(virCommand * cmd)2789 void virCommandRequireHandshake(virCommand *cmd)
2790 {
2791 if (virCommandHasError(cmd))
2792 return;
2793
2794 if (cmd->handshake) {
2795 cmd->has_error = -1;
2796 VIR_DEBUG("Cannot require handshake twice");
2797 return;
2798 }
2799
2800 if (virPipeQuiet(cmd->handshakeWait) < 0) {
2801 cmd->has_error = errno;
2802 return;
2803 }
2804 if (virPipeQuiet(cmd->handshakeNotify) < 0) {
2805 VIR_FORCE_CLOSE(cmd->handshakeWait[0]);
2806 VIR_FORCE_CLOSE(cmd->handshakeWait[1]);
2807 cmd->has_error = errno;
2808 return;
2809 }
2810
2811 VIR_DEBUG("Transfer handshake wait=%d notify=%d, "
2812 "keep handshake wait=%d notify=%d",
2813 cmd->handshakeWait[1], cmd->handshakeNotify[0],
2814 cmd->handshakeWait[0], cmd->handshakeNotify[1]);
2815 virCommandPassFD(cmd, cmd->handshakeWait[1],
2816 VIR_COMMAND_PASS_FD_CLOSE_PARENT);
2817 virCommandPassFD(cmd, cmd->handshakeNotify[0],
2818 VIR_COMMAND_PASS_FD_CLOSE_PARENT);
2819 cmd->handshake = true;
2820 }
2821
2822 /**
2823 * virCommandHandshakeWait:
2824 * @cmd: command to wait on
2825 *
2826 * Wait for the child to complete execution of its
2827 * hook function. To be called in the parent.
2828 */
virCommandHandshakeWait(virCommand * cmd)2829 int virCommandHandshakeWait(virCommand *cmd)
2830 {
2831 char c;
2832 int rv;
2833
2834 if (virCommandHasError(cmd)) {
2835 virCommandRaiseError(cmd);
2836 return -1;
2837 }
2838
2839 if (!cmd->handshake) {
2840 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2841 _("invalid use of command API"));
2842 return -1;
2843 }
2844
2845 if (cmd->handshakeWait[0] == -1) {
2846 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2847 _("Handshake is already complete"));
2848 return -1;
2849 }
2850
2851 VIR_DEBUG("Wait for handshake on %d", cmd->handshakeWait[0]);
2852 if ((rv = saferead(cmd->handshakeWait[0], &c, sizeof(c))) != sizeof(c)) {
2853 if (rv < 0)
2854 virReportSystemError(errno, "%s",
2855 _("Unable to wait for child process"));
2856 else
2857 virReportSystemError(EIO, "%s",
2858 _("Child quit during startup handshake"));
2859 VIR_FORCE_CLOSE(cmd->handshakeWait[0]);
2860 return -1;
2861 }
2862 if (c != '1') {
2863 g_autofree char *msg = NULL;
2864 ssize_t len;
2865 msg = g_new0(char, 1024);
2866 /* Close the handshakeNotify fd before trying to read anything
2867 * further on the handshakeWait pipe; so that a child waiting
2868 * on our acknowledgment will die rather than deadlock. */
2869 VIR_FORCE_CLOSE(cmd->handshakeNotify[1]);
2870
2871 if ((len = saferead(cmd->handshakeWait[0], msg, 1024)) < 0) {
2872 VIR_FORCE_CLOSE(cmd->handshakeWait[0]);
2873 virReportSystemError(errno, "%s",
2874 _("No error message from child failure"));
2875 return -1;
2876 }
2877 VIR_FORCE_CLOSE(cmd->handshakeWait[0]);
2878 msg[len-1] = '\0';
2879 virReportError(VIR_ERR_INTERNAL_ERROR, "%s", msg);
2880 return -1;
2881 }
2882 VIR_FORCE_CLOSE(cmd->handshakeWait[0]);
2883 return 0;
2884 }
2885
2886 /**
2887 * virCommandHandshakeNotify:
2888 * @cmd: command to resume
2889 *
2890 * Notify the child that it is OK to exec() the
2891 * real binary now. To be called in the parent.
2892 */
virCommandHandshakeNotify(virCommand * cmd)2893 int virCommandHandshakeNotify(virCommand *cmd)
2894 {
2895 char c = '1';
2896
2897 if (virCommandHasError(cmd)) {
2898 virCommandRaiseError(cmd);
2899 return -1;
2900 }
2901
2902 if (!cmd->handshake) {
2903 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2904 _("invalid use of command API"));
2905 return -1;
2906 }
2907
2908 if (cmd->handshakeNotify[1] == -1) {
2909 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2910 _("Handshake is already complete"));
2911 return -1;
2912 }
2913
2914 VIR_DEBUG("Notify handshake on %d", cmd->handshakeNotify[1]);
2915 if (safewrite(cmd->handshakeNotify[1], &c, sizeof(c)) != sizeof(c)) {
2916 virReportSystemError(errno, "%s", _("Unable to notify child process"));
2917 VIR_FORCE_CLOSE(cmd->handshakeNotify[1]);
2918 return -1;
2919 }
2920 VIR_FORCE_CLOSE(cmd->handshakeNotify[1]);
2921 return 0;
2922 }
2923 #else /* WIN32 */
2924 int
virCommandSetSendBuffer(virCommand * cmd,unsigned char * buffer G_GNUC_UNUSED,size_t buflen G_GNUC_UNUSED)2925 virCommandSetSendBuffer(virCommand *cmd,
2926 unsigned char *buffer G_GNUC_UNUSED,
2927 size_t buflen G_GNUC_UNUSED)
2928 {
2929 if (virCommandHasError(cmd))
2930 return -1;
2931
2932 cmd->has_error = ENOTSUP;
2933
2934 return -1;
2935 }
2936
2937
2938 int
virCommandExec(virCommand * cmd G_GNUC_UNUSED,gid_t * groups G_GNUC_UNUSED,int ngroups G_GNUC_UNUSED)2939 virCommandExec(virCommand *cmd G_GNUC_UNUSED, gid_t *groups G_GNUC_UNUSED,
2940 int ngroups G_GNUC_UNUSED)
2941 {
2942 virReportSystemError(ENOSYS, "%s",
2943 _("Executing new processes is not supported on Win32 platform"));
2944 return -1;
2945 }
2946
2947
2948 int
virCommandRun(virCommand * cmd G_GNUC_UNUSED,int * exitstatus G_GNUC_UNUSED)2949 virCommandRun(virCommand *cmd G_GNUC_UNUSED, int *exitstatus G_GNUC_UNUSED)
2950 {
2951 virReportSystemError(ENOSYS, "%s",
2952 _("Executing new processes is not supported on Win32 platform"));
2953 return -1;
2954 }
2955
2956
2957 int
virCommandRunAsync(virCommand * cmd G_GNUC_UNUSED,pid_t * pid G_GNUC_UNUSED)2958 virCommandRunAsync(virCommand *cmd G_GNUC_UNUSED, pid_t *pid G_GNUC_UNUSED)
2959 {
2960 virReportSystemError(ENOSYS, "%s",
2961 _("Executing new processes is not supported on Win32 platform"));
2962 return -1;
2963 }
2964
2965
2966 int
virCommandWait(virCommand * cmd G_GNUC_UNUSED,int * exitstatus G_GNUC_UNUSED)2967 virCommandWait(virCommand *cmd G_GNUC_UNUSED, int *exitstatus G_GNUC_UNUSED)
2968 {
2969 virReportSystemError(ENOSYS, "%s",
2970 _("Executing new processes is not supported on Win32 platform"));
2971 return -1;
2972 }
2973
2974
2975 void
virCommandAbort(virCommand * cmd G_GNUC_UNUSED)2976 virCommandAbort(virCommand *cmd G_GNUC_UNUSED)
2977 {
2978 /* Mingw lacks WNOHANG and kill(). But since we haven't ported
2979 * virExec to mingw yet, there's no process to be killed,
2980 * making this implementation trivially correct for now :) */
2981 }
2982
2983
virCommandRequireHandshake(virCommand * cmd)2984 void virCommandRequireHandshake(virCommand *cmd)
2985 {
2986 if (virCommandHasError(cmd))
2987 return;
2988
2989 cmd->has_error = ENOSYS;
2990 }
2991
2992
virCommandHandshakeWait(virCommand * cmd G_GNUC_UNUSED)2993 int virCommandHandshakeWait(virCommand *cmd G_GNUC_UNUSED)
2994 {
2995 virReportSystemError(ENOSYS, "%s",
2996 _("Executing new processes is not supported on Win32 platform"));
2997 return -1;
2998 }
2999
3000
virCommandHandshakeNotify(virCommand * cmd G_GNUC_UNUSED)3001 int virCommandHandshakeNotify(virCommand *cmd G_GNUC_UNUSED)
3002 {
3003 virReportSystemError(ENOSYS, "%s",
3004 _("Executing new processes is not supported on Win32 platform"));
3005 return -1;
3006 }
3007 #endif /* WIN32 */
3008
3009
3010 /**
3011 * virCommandFree:
3012 * @cmd: optional command to free
3013 *
3014 * Release all resources. The only exception is that if you called
3015 * virCommandRunAsync with a non-null pid, then the asynchronous child
3016 * is not reaped, and you must call virProcessWait() or virProcessAbort() yourself.
3017 */
3018 void
virCommandFree(virCommand * cmd)3019 virCommandFree(virCommand *cmd)
3020 {
3021 size_t i;
3022 if (!cmd)
3023 return;
3024
3025 for (i = 0; i < cmd->npassfd; i++) {
3026 if (cmd->passfd[i].flags & VIR_COMMAND_PASS_FD_CLOSE_PARENT)
3027 VIR_FORCE_CLOSE(cmd->passfd[i].fd);
3028 }
3029 cmd->npassfd = 0;
3030 g_free(cmd->passfd);
3031
3032 if (cmd->asyncioThread) {
3033 virThreadJoin(cmd->asyncioThread);
3034 g_free(cmd->asyncioThread);
3035 }
3036 g_free(cmd->inbuf);
3037 VIR_FORCE_CLOSE(cmd->outfd);
3038 VIR_FORCE_CLOSE(cmd->errfd);
3039
3040 for (i = 0; i < cmd->nargs; i++)
3041 g_free(cmd->args[i]);
3042 g_free(cmd->args);
3043
3044 for (i = 0; i < cmd->nenv; i++)
3045 g_free(cmd->env[i]);
3046 g_free(cmd->env);
3047
3048 g_free(cmd->pwd);
3049
3050 if (cmd->handshake) {
3051 /* The other 2 fds in these arrays are closed
3052 * due to use with virCommandPassFD
3053 */
3054 VIR_FORCE_CLOSE(cmd->handshakeWait[0]);
3055 VIR_FORCE_CLOSE(cmd->handshakeNotify[1]);
3056 }
3057
3058 g_free(cmd->pidfile);
3059
3060 if (cmd->reap)
3061 virCommandAbort(cmd);
3062
3063 #if defined(WITH_SECDRIVER_SELINUX)
3064 g_free(cmd->seLinuxLabel);
3065 #endif
3066 #if defined(WITH_SECDRIVER_APPARMOR)
3067 g_free(cmd->appArmorProfile);
3068 #endif
3069
3070 virCommandFreeSendBuffers(cmd);
3071
3072 g_free(cmd);
3073 }
3074
3075 /**
3076 * virCommandDoAsyncIO:
3077 * @cmd: command to do async IO on
3078 *
3079 * This requests asynchronous string IO on @cmd. It is useful in
3080 * combination with virCommandRunAsync():
3081 *
3082 * g_autoptr(virCommand) cmd = virCommandNew*(...);
3083 * g_autofree char *buf = NULL;
3084 *
3085 * ...
3086 *
3087 * virCommandSetOutputBuffer(cmd, &buf);
3088 * virCommandDoAsyncIO(cmd);
3089 *
3090 * if (virCommandRunAsync(cmd, NULL) < 0)
3091 * return;
3092 *
3093 * ...
3094 *
3095 * if (virCommandWait(cmd, NULL) < 0)
3096 * return;
3097 *
3098 * // @buf now contains @cmd's stdout
3099 * VIR_DEBUG("STDOUT: %s", NULLSTR(buf));
3100 *
3101 * ...
3102 *
3103 *
3104 * The libvirt's event loop is used for handling stdios of @cmd.
3105 * Since current implementation uses strlen to determine length
3106 * of data to be written to @cmd's stdin, don't pass any binary
3107 * data. If you want to re-run command, you need to call this and
3108 * buffer setting functions (virCommandSet.*Buffer) prior each run.
3109 */
3110 void
virCommandDoAsyncIO(virCommand * cmd)3111 virCommandDoAsyncIO(virCommand *cmd)
3112 {
3113 if (virCommandHasError(cmd))
3114 return;
3115
3116 cmd->flags |= VIR_EXEC_ASYNC_IO | VIR_EXEC_NONBLOCK;
3117 }
3118
3119
3120 struct _virCommandDryRunToken {
3121 int dummy;
3122 };
3123
3124
3125 /**
3126 * virCommandDryRunTokenNew:
3127 *
3128 * Returns a token which is used with virCommandSetDryRun. Freeing the token
3129 * with the appropriate automatic cleanup function ensures that the dry run
3130 * environment is reset.
3131 */
3132 virCommandDryRunToken *
virCommandDryRunTokenNew(void)3133 virCommandDryRunTokenNew(void)
3134 {
3135 return g_new0(virCommandDryRunToken, 1);
3136 }
3137
3138
3139 /**
3140 * virCommandDryRunTokenFree:
3141 *
3142 * Helper to free a virCommandDryRunToken. Do not use this function directly,
3143 * always declare virCommandDryRunToken as a g_autoptr.
3144 */
3145 void
virCommandDryRunTokenFree(virCommandDryRunToken * tok)3146 virCommandDryRunTokenFree(virCommandDryRunToken *tok)
3147 {
3148 dryRunBuffer = NULL;
3149 dryRunBufferArgLinebreaks = false;
3150 dryRunBufferCommandStripPath = false;
3151 dryRunCallback = NULL;
3152 dryRunOpaque = NULL;
3153 g_free(tok);
3154 }
3155
3156
3157 /**
3158 * virCommandSetDryRun:
3159 * @tok: a virCommandDryRunToken obtained from virCommandDryRunTokenNew
3160 * @buf: buffer to store stringified commands
3161 * @bufArgLinebreaks: add linebreaks after command and every argument or argument pair
3162 * @bufCommandStripPath: strip leading paths of command
3163 * @callback: callback to process input/output/args
3164 *
3165 * Sometimes it's desired to not actually run given command, but
3166 * see its string representation without having to change the
3167 * callee. Unit testing serves as a great example. In such cases,
3168 * the callee constructs the command and calls it via
3169 * virCommandRun* API. The virCommandSetDryRun allows you to
3170 * modify this behavior: once called, every call to
3171 * virCommandRun* results in command string representation being
3172 * appended to @buf instead of being executed. If @callback is
3173 * provided, then it is invoked with the argv, env and stdin
3174 * data string for the command. It is expected to fill the stdout
3175 * and stderr data strings and exit status variables.
3176 *
3177 * The strings stored in @buf are escaped for a shell and
3178 * separated by a newline. For example:
3179 *
3180 * virBuffer buffer = VIR_BUFFER_INITIALIZER;
3181 * virCommandSetDryRun(&buffer);
3182 *
3183 * virCommand *echocmd = virCommandNewArgList("/bin/echo", "Hello world", NULL);
3184 * virCommandRun(echocmd, NULL);
3185 *
3186 * After this, the @buffer should contain:
3187 *
3188 * /bin/echo 'Hello world'\n
3189 *
3190 * To cancel this effect pass NULL for @buf and @callback.
3191 */
3192 void
virCommandSetDryRun(virCommandDryRunToken * tok,virBuffer * buf,bool bufArgLinebreaks,bool bufCommandStripPath,virCommandDryRunCallback cb,void * opaque)3193 virCommandSetDryRun(virCommandDryRunToken *tok,
3194 virBuffer *buf,
3195 bool bufArgLinebreaks,
3196 bool bufCommandStripPath,
3197 virCommandDryRunCallback cb,
3198 void *opaque)
3199 {
3200 if (!tok)
3201 abort();
3202
3203 dryRunBuffer = buf;
3204 dryRunBufferArgLinebreaks = bufArgLinebreaks;
3205 dryRunBufferCommandStripPath = bufCommandStripPath;
3206 dryRunCallback = cb;
3207 dryRunOpaque = opaque;
3208 }
3209
3210 #ifndef WIN32
3211 /**
3212 * virCommandRunRegex:
3213 * @cmd: command to run
3214 * @nregex: number of regexes to apply
3215 * @regex: array of regexes to apply
3216 * @nvars: array of numbers of variables each regex will produce
3217 * @func: callback function that is called for every line of output,
3218 * needs to return 0 on success
3219 * @data: additional data that will be passed to the callback function
3220 * @prefix: prefix that will be skipped at the beginning of each line
3221 * @exitstatus: allows the caller to handle command run exit failures
3222 *
3223 * Run an external program.
3224 *
3225 * Read its output and apply a series of regexes to each line
3226 * When the entire set of regexes has matched consecutively
3227 * then run a callback passing in all the matches on the current line.
3228 *
3229 * Returns: 0 on success, -1 on memory allocation error, virCommandRun
3230 * error or callback function error
3231 */
3232 int
virCommandRunRegex(virCommand * cmd,int nregex,const char ** regex,int * nvars,virCommandRunRegexFunc func,void * data,const char * prefix,int * exitstatus)3233 virCommandRunRegex(virCommand *cmd,
3234 int nregex,
3235 const char **regex,
3236 int *nvars,
3237 virCommandRunRegexFunc func,
3238 void *data,
3239 const char *prefix,
3240 int *exitstatus)
3241 {
3242 GRegex **reg = NULL;
3243 size_t i, j, k;
3244 int totgroups = 0, ngroup = 0;
3245 char **groups;
3246 g_autofree char *outbuf = NULL;
3247 g_auto(GStrv) lines = NULL;
3248 int ret = -1;
3249
3250 /* Compile all regular expressions */
3251 reg = g_new0(GRegex *, nregex);
3252
3253 for (i = 0; i < nregex; i++) {
3254 g_autoptr(GError) err = NULL;
3255 reg[i] = g_regex_new(regex[i], G_REGEX_OPTIMIZE, 0, &err);
3256 if (!reg[i]) {
3257 virReportError(VIR_ERR_INTERNAL_ERROR,
3258 _("Failed to compile regex %s"), err->message);
3259 for (j = 0; j < i; j++)
3260 g_regex_unref(reg[j]);
3261 VIR_FREE(reg);
3262 return -1;
3263 }
3264
3265 totgroups += nvars[i];
3266 }
3267
3268 /* Storage for matched variables */
3269 groups = g_new0(char *, totgroups);
3270
3271 virCommandSetOutputBuffer(cmd, &outbuf);
3272 if (virCommandRun(cmd, exitstatus) < 0)
3273 goto cleanup;
3274
3275 if (!outbuf) {
3276 /* no output */
3277 ret = 0;
3278 goto cleanup;
3279 }
3280
3281 if (!(lines = g_strsplit(outbuf, "\n", 0)))
3282 goto cleanup;
3283
3284 for (k = 0; lines[k]; k++) {
3285 g_autoptr(GMatchInfo) info = NULL;
3286 const char *p = NULL;
3287
3288 /* ignore any command prefix */
3289 if (prefix)
3290 p = STRSKIP(lines[k], prefix);
3291 if (!p)
3292 p = lines[k];
3293
3294 ngroup = 0;
3295 for (i = 0; i < nregex; i++) {
3296 if (!(g_regex_match(reg[i], p, 0, &info)))
3297 break;
3298
3299 /* NB match #0 is the full pattern, so we offset j by 1 */
3300 for (j = 1; j <= nvars[i]; j++)
3301 groups[ngroup++] = g_match_info_fetch(info, j);
3302 }
3303 /* We've matched on the last regex, so callback time */
3304 if (i == nregex) {
3305 if (((*func)(groups, data)) < 0)
3306 goto cleanup;
3307 }
3308
3309 for (j = 0; j < ngroup; j++)
3310 VIR_FREE(groups[j]);
3311 }
3312
3313 ret = 0;
3314 cleanup:
3315 if (groups) {
3316 for (j = 0; j < totgroups; j++)
3317 VIR_FREE(groups[j]);
3318 VIR_FREE(groups);
3319 }
3320
3321 for (i = 0; i < nregex; i++)
3322 g_regex_unref(reg[i]);
3323
3324 VIR_FREE(reg);
3325 return ret;
3326 }
3327
3328 /*
3329 * Run an external program and read from its standard output
3330 * a stream of tokens from IN_STREAM, applying FUNC to
3331 * each successive sequence of N_COLUMNS tokens.
3332 * If FUNC returns < 0, stop processing input and return -1.
3333 * Return -1 if N_COLUMNS == 0.
3334 * Return -1 upon memory allocation error.
3335 * If the number of input tokens is not a multiple of N_COLUMNS,
3336 * then the final FUNC call will specify a number smaller than N_COLUMNS.
3337 * If there are no input tokens (empty input), call FUNC with N_COLUMNS == 0.
3338 */
3339 int
virCommandRunNul(virCommand * cmd,size_t n_columns,virCommandRunNulFunc func,void * data)3340 virCommandRunNul(virCommand *cmd,
3341 size_t n_columns,
3342 virCommandRunNulFunc func,
3343 void *data)
3344 {
3345 size_t n_tok = 0;
3346 int fd = -1;
3347 FILE *fp = NULL;
3348 char **v;
3349 int ret = -1;
3350 size_t i;
3351
3352 if (n_columns == 0)
3353 return -1;
3354
3355 v = g_new0(char *, n_columns);
3356 for (i = 0; i < n_columns; i++)
3357 v[i] = NULL;
3358
3359 virCommandSetOutputFD(cmd, &fd);
3360 if (virCommandRunAsync(cmd, NULL) < 0)
3361 goto cleanup;
3362
3363 if ((fp = VIR_FDOPEN(fd, "r")) == NULL) {
3364 virReportError(VIR_ERR_INTERNAL_ERROR,
3365 "%s", _("cannot open file using fd"));
3366 goto cleanup;
3367 }
3368
3369 while (1) {
3370 char *buf = NULL;
3371 size_t buf_len = 0;
3372 /* Be careful: even when it returns -1,
3373 this use of getdelim allocates memory. */
3374 ssize_t tok_len = getdelim(&buf, &buf_len, 0, fp);
3375 v[n_tok] = buf;
3376 if (tok_len < 0) {
3377 /* Maybe EOF, maybe an error.
3378 If n_tok > 0, then we know it's an error. */
3379 if (n_tok && func(n_tok, v, data) < 0)
3380 goto cleanup;
3381 break;
3382 }
3383 ++n_tok;
3384 if (n_tok == n_columns) {
3385 if (func(n_tok, v, data) < 0)
3386 goto cleanup;
3387 n_tok = 0;
3388 for (i = 0; i < n_columns; i++)
3389 VIR_FREE(v[i]);
3390 }
3391 }
3392
3393 if (feof(fp) < 0) {
3394 virReportSystemError(errno, "%s",
3395 _("read error on pipe"));
3396 goto cleanup;
3397 }
3398
3399 ret = virCommandWait(cmd, NULL);
3400 cleanup:
3401 for (i = 0; i < n_columns; i++)
3402 VIR_FREE(v[i]);
3403 VIR_FREE(v);
3404
3405 VIR_FORCE_FCLOSE(fp);
3406 VIR_FORCE_CLOSE(fd);
3407
3408 return ret;
3409 }
3410
3411 #else /* WIN32 */
3412
3413 int
virCommandRunRegex(virCommand * cmd G_GNUC_UNUSED,int nregex G_GNUC_UNUSED,const char ** regex G_GNUC_UNUSED,int * nvars G_GNUC_UNUSED,virCommandRunRegexFunc func G_GNUC_UNUSED,void * data G_GNUC_UNUSED,const char * prefix G_GNUC_UNUSED,int * exitstatus G_GNUC_UNUSED)3414 virCommandRunRegex(virCommand *cmd G_GNUC_UNUSED,
3415 int nregex G_GNUC_UNUSED,
3416 const char **regex G_GNUC_UNUSED,
3417 int *nvars G_GNUC_UNUSED,
3418 virCommandRunRegexFunc func G_GNUC_UNUSED,
3419 void *data G_GNUC_UNUSED,
3420 const char *prefix G_GNUC_UNUSED,
3421 int *exitstatus G_GNUC_UNUSED)
3422 {
3423 virReportError(VIR_ERR_INTERNAL_ERROR,
3424 _("%s not implemented on Win32"), __FUNCTION__);
3425 return -1;
3426 }
3427
3428 int
virCommandRunNul(virCommand * cmd G_GNUC_UNUSED,size_t n_columns G_GNUC_UNUSED,virCommandRunNulFunc func G_GNUC_UNUSED,void * data G_GNUC_UNUSED)3429 virCommandRunNul(virCommand *cmd G_GNUC_UNUSED,
3430 size_t n_columns G_GNUC_UNUSED,
3431 virCommandRunNulFunc func G_GNUC_UNUSED,
3432 void *data G_GNUC_UNUSED)
3433 {
3434 virReportError(VIR_ERR_INTERNAL_ERROR,
3435 _("%s not implemented on Win32"), __FUNCTION__);
3436 return -1;
3437 }
3438 #endif /* WIN32 */
3439