xref: /openbmc/qemu/qga/commands-posix.c (revision e69b2c67)
1 /*
2  * QEMU Guest Agent POSIX-specific command implementations
3  *
4  * Copyright IBM Corp. 2011
5  *
6  * Authors:
7  *  Michael Roth      <mdroth@linux.vnet.ibm.com>
8  *  Michal Privoznik  <mprivozn@redhat.com>
9  *
10  * This work is licensed under the terms of the GNU GPL, version 2 or later.
11  * See the COPYING file in the top-level directory.
12  */
13 
14 #include "qemu/osdep.h"
15 #include <sys/ioctl.h>
16 #include <sys/utsname.h>
17 #include <sys/wait.h>
18 #include <dirent.h>
19 #include "qga-qapi-commands.h"
20 #include "qapi/error.h"
21 #include "qapi/qmp/qerror.h"
22 #include "qemu/host-utils.h"
23 #include "qemu/sockets.h"
24 #include "qemu/base64.h"
25 #include "qemu/cutils.h"
26 #include "commands-common.h"
27 #include "cutils.h"
28 
29 #ifdef HAVE_UTMPX
30 #include <utmpx.h>
31 #endif
32 
33 #ifdef HAVE_GETIFADDRS
34 #include <arpa/inet.h>
35 #include <sys/socket.h>
36 #include <net/if.h>
37 #if defined(__NetBSD__) || defined(__OpenBSD__) || defined(CONFIG_SOLARIS)
38 #include <net/if_arp.h>
39 #include <netinet/if_ether.h>
40 #if !defined(ETHER_ADDR_LEN) && defined(ETHERADDRL)
41 #define ETHER_ADDR_LEN ETHERADDRL
42 #endif
43 #else
44 #include <net/ethernet.h>
45 #endif
46 #ifdef CONFIG_SOLARIS
47 #include <sys/sockio.h>
48 #endif
49 #endif
50 
51 static bool ga_wait_child(pid_t pid, int *status, Error **errp)
52 {
53     pid_t rpid;
54 
55     *status = 0;
56 
57     rpid = RETRY_ON_EINTR(waitpid(pid, status, 0));
58 
59     if (rpid == -1) {
60         error_setg_errno(errp, errno, "failed to wait for child (pid: %d)",
61                          pid);
62         return false;
63     }
64 
65     g_assert(rpid == pid);
66     return true;
67 }
68 
69 static ssize_t ga_pipe_read_str(int fd[2], char **str)
70 {
71     ssize_t n, len = 0;
72     char buf[1024];
73 
74     close(fd[1]);
75     fd[1] = -1;
76     while ((n = read(fd[0], buf, sizeof(buf))) != 0) {
77         if (n < 0) {
78             if (errno == EINTR) {
79                 continue;
80             } else {
81                 len = -errno;
82                 break;
83             }
84         }
85         *str = g_realloc(*str, len + n + 1);
86         memcpy(*str + len, buf, n);
87         len += n;
88         *str[len] = '\0';
89     }
90     close(fd[0]);
91     fd[0] = -1;
92 
93     return len;
94 }
95 
96 /*
97  * Helper to run command with input/output redirection,
98  * sending string to stdin and taking error message from
99  * stdout/err.
100  */
101 static int ga_run_command(const char *argv[], const char *in_str,
102                           const char *action, Error **errp)
103 {
104     pid_t pid;
105     int status;
106     int retcode = -1;
107     int infd[2] = { -1, -1 };
108     int outfd[2] = { -1, -1 };
109     char *str = NULL;
110     ssize_t len = 0;
111 
112     if ((in_str && !g_unix_open_pipe(infd, FD_CLOEXEC, NULL)) ||
113         !g_unix_open_pipe(outfd, FD_CLOEXEC, NULL)) {
114         error_setg(errp, "cannot create pipe FDs");
115         goto out;
116     }
117 
118     pid = fork();
119     if (pid == 0) {
120         char *cherr = NULL;
121 
122         setsid();
123 
124         if (in_str) {
125             /* Redirect stdin to infd. */
126             close(infd[1]);
127             dup2(infd[0], 0);
128             close(infd[0]);
129         } else {
130             reopen_fd_to_null(0);
131         }
132 
133         /* Redirect stdout/stderr to outfd. */
134         close(outfd[0]);
135         dup2(outfd[1], 1);
136         dup2(outfd[1], 2);
137         close(outfd[1]);
138 
139         execvp(argv[0], (char *const *)argv);
140 
141         /* Write the cause of failed exec to pipe for the parent to read it. */
142         cherr = g_strdup_printf("failed to exec '%s'", argv[0]);
143         perror(cherr);
144         g_free(cherr);
145         _exit(EXIT_FAILURE);
146     } else if (pid < 0) {
147         error_setg_errno(errp, errno, "failed to create child process");
148         goto out;
149     }
150 
151     if (in_str) {
152         close(infd[0]);
153         infd[0] = -1;
154         if (qemu_write_full(infd[1], in_str, strlen(in_str)) !=
155                 strlen(in_str)) {
156             error_setg_errno(errp, errno, "%s: cannot write to stdin pipe",
157                              action);
158             goto out;
159         }
160         close(infd[1]);
161         infd[1] = -1;
162     }
163 
164     len = ga_pipe_read_str(outfd, &str);
165     if (len < 0) {
166         error_setg_errno(errp, -len, "%s: cannot read from stdout/stderr pipe",
167                          action);
168         goto out;
169     }
170 
171     if (!ga_wait_child(pid, &status, errp)) {
172         goto out;
173     }
174 
175     if (!WIFEXITED(status)) {
176         if (len) {
177             error_setg(errp, "child process has terminated abnormally: %s",
178                        str);
179         } else {
180             error_setg(errp, "child process has terminated abnormally");
181         }
182         goto out;
183     }
184 
185     retcode = WEXITSTATUS(status);
186 
187     if (WEXITSTATUS(status)) {
188         if (len) {
189             error_setg(errp, "child process has failed to %s: %s",
190                        action, str);
191         } else {
192             error_setg(errp, "child process has failed to %s: exit status %d",
193                        action, WEXITSTATUS(status));
194         }
195         goto out;
196     }
197 
198 out:
199     g_free(str);
200 
201     if (infd[0] != -1) {
202         close(infd[0]);
203     }
204     if (infd[1] != -1) {
205         close(infd[1]);
206     }
207     if (outfd[0] != -1) {
208         close(outfd[0]);
209     }
210     if (outfd[1] != -1) {
211         close(outfd[1]);
212     }
213 
214     return retcode;
215 }
216 
217 void qmp_guest_shutdown(const char *mode, Error **errp)
218 {
219     const char *shutdown_flag;
220     Error *local_err = NULL;
221 
222 #ifdef CONFIG_SOLARIS
223     const char *powerdown_flag = "-i5";
224     const char *halt_flag = "-i0";
225     const char *reboot_flag = "-i6";
226 #elif defined(CONFIG_BSD)
227     const char *powerdown_flag = "-p";
228     const char *halt_flag = "-h";
229     const char *reboot_flag = "-r";
230 #else
231     const char *powerdown_flag = "-P";
232     const char *halt_flag = "-H";
233     const char *reboot_flag = "-r";
234 #endif
235 
236     slog("guest-shutdown called, mode: %s", mode);
237     if (!mode || strcmp(mode, "powerdown") == 0) {
238         shutdown_flag = powerdown_flag;
239     } else if (strcmp(mode, "halt") == 0) {
240         shutdown_flag = halt_flag;
241     } else if (strcmp(mode, "reboot") == 0) {
242         shutdown_flag = reboot_flag;
243     } else {
244         error_setg(errp,
245                    "mode is invalid (valid values are: halt|powerdown|reboot");
246         return;
247     }
248 
249     const char *argv[] = {"/sbin/shutdown",
250 #ifdef CONFIG_SOLARIS
251                           shutdown_flag, "-g0", "-y",
252 #elif defined(CONFIG_BSD)
253                           shutdown_flag, "+0",
254 #else
255                           "-h", shutdown_flag, "+0",
256 #endif
257                           "hypervisor initiated shutdown", (char *) NULL};
258 
259     ga_run_command(argv, NULL, "shutdown", &local_err);
260     if (local_err) {
261         error_propagate(errp, local_err);
262         return;
263     }
264 
265     /* succeeded */
266 }
267 
268 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
269 {
270     int ret;
271     Error *local_err = NULL;
272     struct timeval tv;
273     const char *argv[] = {"/sbin/hwclock", has_time ? "-w" : "-s", NULL};
274 
275     /* If user has passed a time, validate and set it. */
276     if (has_time) {
277         GDate date = { 0, };
278 
279         /* year-2038 will overflow in case time_t is 32bit */
280         if (time_ns / 1000000000 != (time_t)(time_ns / 1000000000)) {
281             error_setg(errp, "Time %" PRId64 " is too large", time_ns);
282             return;
283         }
284 
285         tv.tv_sec = time_ns / 1000000000;
286         tv.tv_usec = (time_ns % 1000000000) / 1000;
287         g_date_set_time_t(&date, tv.tv_sec);
288         if (date.year < 1970 || date.year >= 2070) {
289             error_setg_errno(errp, errno, "Invalid time");
290             return;
291         }
292 
293         ret = settimeofday(&tv, NULL);
294         if (ret < 0) {
295             error_setg_errno(errp, errno, "Failed to set time to guest");
296             return;
297         }
298     }
299 
300     /* Now, if user has passed a time to set and the system time is set, we
301      * just need to synchronize the hardware clock. However, if no time was
302      * passed, user is requesting the opposite: set the system time from the
303      * hardware clock (RTC). */
304     ga_run_command(argv, NULL, "set hardware clock to system time",
305                    &local_err);
306     if (local_err) {
307         error_propagate(errp, local_err);
308         return;
309     }
310 }
311 
312 typedef enum {
313     RW_STATE_NEW,
314     RW_STATE_READING,
315     RW_STATE_WRITING,
316 } RwState;
317 
318 struct GuestFileHandle {
319     uint64_t id;
320     FILE *fh;
321     RwState state;
322     QTAILQ_ENTRY(GuestFileHandle) next;
323 };
324 
325 static struct {
326     QTAILQ_HEAD(, GuestFileHandle) filehandles;
327 } guest_file_state = {
328     .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
329 };
330 
331 static int64_t guest_file_handle_add(FILE *fh, Error **errp)
332 {
333     GuestFileHandle *gfh;
334     int64_t handle;
335 
336     handle = ga_get_fd_handle(ga_state, errp);
337     if (handle < 0) {
338         return -1;
339     }
340 
341     gfh = g_new0(GuestFileHandle, 1);
342     gfh->id = handle;
343     gfh->fh = fh;
344     QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
345 
346     return handle;
347 }
348 
349 GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
350 {
351     GuestFileHandle *gfh;
352 
353     QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next)
354     {
355         if (gfh->id == id) {
356             return gfh;
357         }
358     }
359 
360     error_setg(errp, "handle '%" PRId64 "' has not been found", id);
361     return NULL;
362 }
363 
364 typedef const char * const ccpc;
365 
366 #ifndef O_BINARY
367 #define O_BINARY 0
368 #endif
369 
370 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
371 static const struct {
372     ccpc *forms;
373     int oflag_base;
374 } guest_file_open_modes[] = {
375     { (ccpc[]){ "r",          NULL }, O_RDONLY                                 },
376     { (ccpc[]){ "rb",         NULL }, O_RDONLY                      | O_BINARY },
377     { (ccpc[]){ "w",          NULL }, O_WRONLY | O_CREAT | O_TRUNC             },
378     { (ccpc[]){ "wb",         NULL }, O_WRONLY | O_CREAT | O_TRUNC  | O_BINARY },
379     { (ccpc[]){ "a",          NULL }, O_WRONLY | O_CREAT | O_APPEND            },
380     { (ccpc[]){ "ab",         NULL }, O_WRONLY | O_CREAT | O_APPEND | O_BINARY },
381     { (ccpc[]){ "r+",         NULL }, O_RDWR                                   },
382     { (ccpc[]){ "rb+", "r+b", NULL }, O_RDWR                        | O_BINARY },
383     { (ccpc[]){ "w+",         NULL }, O_RDWR   | O_CREAT | O_TRUNC             },
384     { (ccpc[]){ "wb+", "w+b", NULL }, O_RDWR   | O_CREAT | O_TRUNC  | O_BINARY },
385     { (ccpc[]){ "a+",         NULL }, O_RDWR   | O_CREAT | O_APPEND            },
386     { (ccpc[]){ "ab+", "a+b", NULL }, O_RDWR   | O_CREAT | O_APPEND | O_BINARY }
387 };
388 
389 static int
390 find_open_flag(const char *mode_str, Error **errp)
391 {
392     unsigned mode;
393 
394     for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
395         ccpc *form;
396 
397         form = guest_file_open_modes[mode].forms;
398         while (*form != NULL && strcmp(*form, mode_str) != 0) {
399             ++form;
400         }
401         if (*form != NULL) {
402             break;
403         }
404     }
405 
406     if (mode == ARRAY_SIZE(guest_file_open_modes)) {
407         error_setg(errp, "invalid file open mode '%s'", mode_str);
408         return -1;
409     }
410     return guest_file_open_modes[mode].oflag_base | O_NOCTTY | O_NONBLOCK;
411 }
412 
413 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
414                                S_IRGRP | S_IWGRP | \
415                                S_IROTH | S_IWOTH)
416 
417 static FILE *
418 safe_open_or_create(const char *path, const char *mode, Error **errp)
419 {
420     int oflag;
421     int fd = -1;
422     FILE *f = NULL;
423 
424     oflag = find_open_flag(mode, errp);
425     if (oflag < 0) {
426         goto end;
427     }
428 
429     /* If the caller wants / allows creation of a new file, we implement it
430      * with a two step process: open() + (open() / fchmod()).
431      *
432      * First we insist on creating the file exclusively as a new file. If
433      * that succeeds, we're free to set any file-mode bits on it. (The
434      * motivation is that we want to set those file-mode bits independently
435      * of the current umask.)
436      *
437      * If the exclusive creation fails because the file already exists
438      * (EEXIST is not possible for any other reason), we just attempt to
439      * open the file, but in this case we won't be allowed to change the
440      * file-mode bits on the preexistent file.
441      *
442      * The pathname should never disappear between the two open()s in
443      * practice. If it happens, then someone very likely tried to race us.
444      * In this case just go ahead and report the ENOENT from the second
445      * open() to the caller.
446      *
447      * If the caller wants to open a preexistent file, then the first
448      * open() is decisive and its third argument is ignored, and the second
449      * open() and the fchmod() are never called.
450      */
451     fd = qga_open_cloexec(path, oflag | ((oflag & O_CREAT) ? O_EXCL : 0), 0);
452     if (fd == -1 && errno == EEXIST) {
453         oflag &= ~(unsigned)O_CREAT;
454         fd = qga_open_cloexec(path, oflag, 0);
455     }
456     if (fd == -1) {
457         error_setg_errno(errp, errno,
458                          "failed to open file '%s' (mode: '%s')",
459                          path, mode);
460         goto end;
461     }
462 
463     if ((oflag & O_CREAT) && fchmod(fd, DEFAULT_NEW_FILE_MODE) == -1) {
464         error_setg_errno(errp, errno, "failed to set permission "
465                          "0%03o on new file '%s' (mode: '%s')",
466                          (unsigned)DEFAULT_NEW_FILE_MODE, path, mode);
467         goto end;
468     }
469 
470     f = fdopen(fd, mode);
471     if (f == NULL) {
472         error_setg_errno(errp, errno, "failed to associate stdio stream with "
473                          "file descriptor %d, file '%s' (mode: '%s')",
474                          fd, path, mode);
475     }
476 
477 end:
478     if (f == NULL && fd != -1) {
479         close(fd);
480         if (oflag & O_CREAT) {
481             unlink(path);
482         }
483     }
484     return f;
485 }
486 
487 int64_t qmp_guest_file_open(const char *path, const char *mode,
488                             Error **errp)
489 {
490     FILE *fh;
491     Error *local_err = NULL;
492     int64_t handle;
493 
494     if (!mode) {
495         mode = "r";
496     }
497     slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
498     fh = safe_open_or_create(path, mode, &local_err);
499     if (local_err != NULL) {
500         error_propagate(errp, local_err);
501         return -1;
502     }
503 
504     /* set fd non-blocking to avoid common use cases (like reading from a
505      * named pipe) from hanging the agent
506      */
507     if (!g_unix_set_fd_nonblocking(fileno(fh), true, NULL)) {
508         fclose(fh);
509         error_setg_errno(errp, errno, "Failed to set FD nonblocking");
510         return -1;
511     }
512 
513     handle = guest_file_handle_add(fh, errp);
514     if (handle < 0) {
515         fclose(fh);
516         return -1;
517     }
518 
519     slog("guest-file-open, handle: %" PRId64, handle);
520     return handle;
521 }
522 
523 void qmp_guest_file_close(int64_t handle, Error **errp)
524 {
525     GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
526     int ret;
527 
528     slog("guest-file-close called, handle: %" PRId64, handle);
529     if (!gfh) {
530         return;
531     }
532 
533     ret = fclose(gfh->fh);
534     if (ret == EOF) {
535         error_setg_errno(errp, errno, "failed to close handle");
536         return;
537     }
538 
539     QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
540     g_free(gfh);
541 }
542 
543 GuestFileRead *guest_file_read_unsafe(GuestFileHandle *gfh,
544                                       int64_t count, Error **errp)
545 {
546     GuestFileRead *read_data = NULL;
547     guchar *buf;
548     FILE *fh = gfh->fh;
549     size_t read_count;
550 
551     /* explicitly flush when switching from writing to reading */
552     if (gfh->state == RW_STATE_WRITING) {
553         int ret = fflush(fh);
554         if (ret == EOF) {
555             error_setg_errno(errp, errno, "failed to flush file");
556             return NULL;
557         }
558         gfh->state = RW_STATE_NEW;
559     }
560 
561     buf = g_malloc0(count + 1);
562     read_count = fread(buf, 1, count, fh);
563     if (ferror(fh)) {
564         error_setg_errno(errp, errno, "failed to read file");
565     } else {
566         buf[read_count] = 0;
567         read_data = g_new0(GuestFileRead, 1);
568         read_data->count = read_count;
569         read_data->eof = feof(fh);
570         if (read_count) {
571             read_data->buf_b64 = g_base64_encode(buf, read_count);
572         }
573         gfh->state = RW_STATE_READING;
574     }
575     g_free(buf);
576     clearerr(fh);
577 
578     return read_data;
579 }
580 
581 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
582                                      bool has_count, int64_t count,
583                                      Error **errp)
584 {
585     GuestFileWrite *write_data = NULL;
586     guchar *buf;
587     gsize buf_len;
588     int write_count;
589     GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
590     FILE *fh;
591 
592     if (!gfh) {
593         return NULL;
594     }
595 
596     fh = gfh->fh;
597 
598     if (gfh->state == RW_STATE_READING) {
599         int ret = fseek(fh, 0, SEEK_CUR);
600         if (ret == -1) {
601             error_setg_errno(errp, errno, "failed to seek file");
602             return NULL;
603         }
604         gfh->state = RW_STATE_NEW;
605     }
606 
607     buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
608     if (!buf) {
609         return NULL;
610     }
611 
612     if (!has_count) {
613         count = buf_len;
614     } else if (count < 0 || count > buf_len) {
615         error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
616                    count);
617         g_free(buf);
618         return NULL;
619     }
620 
621     write_count = fwrite(buf, 1, count, fh);
622     if (ferror(fh)) {
623         error_setg_errno(errp, errno, "failed to write to file");
624         slog("guest-file-write failed, handle: %" PRId64, handle);
625     } else {
626         write_data = g_new0(GuestFileWrite, 1);
627         write_data->count = write_count;
628         write_data->eof = feof(fh);
629         gfh->state = RW_STATE_WRITING;
630     }
631     g_free(buf);
632     clearerr(fh);
633 
634     return write_data;
635 }
636 
637 struct GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
638                                           GuestFileWhence *whence_code,
639                                           Error **errp)
640 {
641     GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
642     GuestFileSeek *seek_data = NULL;
643     FILE *fh;
644     int ret;
645     int whence;
646     Error *err = NULL;
647 
648     if (!gfh) {
649         return NULL;
650     }
651 
652     /* We stupidly exposed 'whence':'int' in our qapi */
653     whence = ga_parse_whence(whence_code, &err);
654     if (err) {
655         error_propagate(errp, err);
656         return NULL;
657     }
658 
659     fh = gfh->fh;
660     ret = fseek(fh, offset, whence);
661     if (ret == -1) {
662         error_setg_errno(errp, errno, "failed to seek file");
663         if (errno == ESPIPE) {
664             /* file is non-seekable, stdio shouldn't be buffering anyways */
665             gfh->state = RW_STATE_NEW;
666         }
667     } else {
668         seek_data = g_new0(GuestFileSeek, 1);
669         seek_data->position = ftell(fh);
670         seek_data->eof = feof(fh);
671         gfh->state = RW_STATE_NEW;
672     }
673     clearerr(fh);
674 
675     return seek_data;
676 }
677 
678 void qmp_guest_file_flush(int64_t handle, Error **errp)
679 {
680     GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
681     FILE *fh;
682     int ret;
683 
684     if (!gfh) {
685         return;
686     }
687 
688     fh = gfh->fh;
689     ret = fflush(fh);
690     if (ret == EOF) {
691         error_setg_errno(errp, errno, "failed to flush file");
692     } else {
693         gfh->state = RW_STATE_NEW;
694     }
695 }
696 
697 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
698 void free_fs_mount_list(FsMountList *mounts)
699 {
700      FsMount *mount, *temp;
701 
702      if (!mounts) {
703          return;
704      }
705 
706      QTAILQ_FOREACH_SAFE(mount, mounts, next, temp) {
707          QTAILQ_REMOVE(mounts, mount, next);
708          g_free(mount->dirname);
709          g_free(mount->devtype);
710          g_free(mount);
711      }
712 }
713 #endif
714 
715 #if defined(CONFIG_FSFREEZE)
716 typedef enum {
717     FSFREEZE_HOOK_THAW = 0,
718     FSFREEZE_HOOK_FREEZE,
719 } FsfreezeHookArg;
720 
721 static const char *fsfreeze_hook_arg_string[] = {
722     "thaw",
723     "freeze",
724 };
725 
726 static void execute_fsfreeze_hook(FsfreezeHookArg arg, Error **errp)
727 {
728     const char *hook;
729     const char *arg_str = fsfreeze_hook_arg_string[arg];
730     Error *local_err = NULL;
731 
732     hook = ga_fsfreeze_hook(ga_state);
733     if (!hook) {
734         return;
735     }
736 
737     const char *argv[] = {hook, arg_str, NULL};
738 
739     slog("executing fsfreeze hook with arg '%s'", arg_str);
740     ga_run_command(argv, NULL, "execute fsfreeze hook", &local_err);
741     if (local_err) {
742         error_propagate(errp, local_err);
743         return;
744     }
745 }
746 
747 /*
748  * Return status of freeze/thaw
749  */
750 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
751 {
752     if (ga_is_frozen(ga_state)) {
753         return GUEST_FSFREEZE_STATUS_FROZEN;
754     }
755 
756     return GUEST_FSFREEZE_STATUS_THAWED;
757 }
758 
759 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
760 {
761     return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
762 }
763 
764 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
765                                        strList *mountpoints,
766                                        Error **errp)
767 {
768     int ret;
769     FsMountList mounts;
770     Error *local_err = NULL;
771 
772     slog("guest-fsfreeze called");
773 
774     execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE, &local_err);
775     if (local_err) {
776         error_propagate(errp, local_err);
777         return -1;
778     }
779 
780     QTAILQ_INIT(&mounts);
781     if (!build_fs_mount_list(&mounts, &local_err)) {
782         error_propagate(errp, local_err);
783         return -1;
784     }
785 
786     /* cannot risk guest agent blocking itself on a write in this state */
787     ga_set_frozen(ga_state);
788 
789     ret = qmp_guest_fsfreeze_do_freeze_list(has_mountpoints, mountpoints,
790                                             mounts, errp);
791 
792     free_fs_mount_list(&mounts);
793     /* We may not issue any FIFREEZE here.
794      * Just unset ga_state here and ready for the next call.
795      */
796     if (ret == 0) {
797         ga_unset_frozen(ga_state);
798     } else if (ret < 0) {
799         qmp_guest_fsfreeze_thaw(NULL);
800     }
801     return ret;
802 }
803 
804 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
805 {
806     int ret;
807 
808     ret = qmp_guest_fsfreeze_do_thaw(errp);
809     if (ret >= 0) {
810         ga_unset_frozen(ga_state);
811         execute_fsfreeze_hook(FSFREEZE_HOOK_THAW, errp);
812     } else {
813         ret = 0;
814     }
815 
816     return ret;
817 }
818 
819 static void guest_fsfreeze_cleanup(void)
820 {
821     Error *err = NULL;
822 
823     if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
824         qmp_guest_fsfreeze_thaw(&err);
825         if (err) {
826             slog("failed to clean up frozen filesystems: %s",
827                  error_get_pretty(err));
828             error_free(err);
829         }
830     }
831 }
832 #endif
833 
834 #if defined(__linux__) || defined(__FreeBSD__)
835 void qmp_guest_set_user_password(const char *username,
836                                  const char *password,
837                                  bool crypted,
838                                  Error **errp)
839 {
840     Error *local_err = NULL;
841     g_autofree char *rawpasswddata = NULL;
842     size_t rawpasswdlen;
843 
844     rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
845     if (!rawpasswddata) {
846         return;
847     }
848     rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
849     rawpasswddata[rawpasswdlen] = '\0';
850 
851     if (strchr(rawpasswddata, '\n')) {
852         error_setg(errp, "forbidden characters in raw password");
853         return;
854     }
855 
856     if (strchr(username, '\n') ||
857         strchr(username, ':')) {
858         error_setg(errp, "forbidden characters in username");
859         return;
860     }
861 
862 #ifdef __FreeBSD__
863     g_autofree char *chpasswddata = g_strdup(rawpasswddata);
864     const char *crypt_flag = crypted ? "-H" : "-h";
865     const char *argv[] = {"pw", "usermod", "-n", username,
866                           crypt_flag, "0", NULL};
867 #else
868     g_autofree char *chpasswddata = g_strdup_printf("%s:%s\n", username,
869                                                     rawpasswddata);
870     const char *crypt_flag = crypted ? "-e" : NULL;
871     const char *argv[] = {"chpasswd", crypt_flag, NULL};
872 #endif
873 
874     ga_run_command(argv, chpasswddata, "set user password", &local_err);
875     if (local_err) {
876         error_propagate(errp, local_err);
877         return;
878     }
879 }
880 #endif /* __linux__ || __FreeBSD__ */
881 
882 #ifdef HAVE_GETIFADDRS
883 static GuestNetworkInterface *
884 guest_find_interface(GuestNetworkInterfaceList *head,
885                      const char *name)
886 {
887     for (; head; head = head->next) {
888         if (strcmp(head->value->name, name) == 0) {
889             return head->value;
890         }
891     }
892 
893     return NULL;
894 }
895 
896 static int guest_get_network_stats(const char *name,
897                        GuestNetworkInterfaceStat *stats)
898 {
899 #ifdef CONFIG_LINUX
900     int name_len;
901     char const *devinfo = "/proc/net/dev";
902     FILE *fp;
903     char *line = NULL, *colon;
904     size_t n = 0;
905     fp = fopen(devinfo, "r");
906     if (!fp) {
907         g_debug("failed to open network stats %s: %s", devinfo,
908                 g_strerror(errno));
909         return -1;
910     }
911     name_len = strlen(name);
912     while (getline(&line, &n, fp) != -1) {
913         long long dummy;
914         long long rx_bytes;
915         long long rx_packets;
916         long long rx_errs;
917         long long rx_dropped;
918         long long tx_bytes;
919         long long tx_packets;
920         long long tx_errs;
921         long long tx_dropped;
922         char *trim_line;
923         trim_line = g_strchug(line);
924         if (trim_line[0] == '\0') {
925             continue;
926         }
927         colon = strchr(trim_line, ':');
928         if (!colon) {
929             continue;
930         }
931         if (colon - name_len  == trim_line &&
932            strncmp(trim_line, name, name_len) == 0) {
933             if (sscanf(colon + 1,
934                 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
935                   &rx_bytes, &rx_packets, &rx_errs, &rx_dropped,
936                   &dummy, &dummy, &dummy, &dummy,
937                   &tx_bytes, &tx_packets, &tx_errs, &tx_dropped,
938                   &dummy, &dummy, &dummy, &dummy) != 16) {
939                 continue;
940             }
941             stats->rx_bytes = rx_bytes;
942             stats->rx_packets = rx_packets;
943             stats->rx_errs = rx_errs;
944             stats->rx_dropped = rx_dropped;
945             stats->tx_bytes = tx_bytes;
946             stats->tx_packets = tx_packets;
947             stats->tx_errs = tx_errs;
948             stats->tx_dropped = tx_dropped;
949             fclose(fp);
950             g_free(line);
951             return 0;
952         }
953     }
954     fclose(fp);
955     g_free(line);
956     g_debug("/proc/net/dev: Interface '%s' not found", name);
957 #else /* !CONFIG_LINUX */
958     g_debug("Network stats reporting available only for Linux");
959 #endif /* !CONFIG_LINUX */
960     return -1;
961 }
962 
963 #ifndef CONFIG_BSD
964 /*
965  * Fill "buf" with MAC address by ifaddrs. Pointer buf must point to a
966  * buffer with ETHER_ADDR_LEN length at least.
967  *
968  * Returns false in case of an error, otherwise true. "obtained" argument
969  * is true if a MAC address was obtained successful, otherwise false.
970  */
971 bool guest_get_hw_addr(struct ifaddrs *ifa, unsigned char *buf,
972                        bool *obtained, Error **errp)
973 {
974     struct ifreq ifr;
975     int sock;
976 
977     *obtained = false;
978 
979     /* we haven't obtained HW address yet */
980     sock = socket(PF_INET, SOCK_STREAM, 0);
981     if (sock == -1) {
982         error_setg_errno(errp, errno, "failed to create socket");
983         return false;
984     }
985 
986     memset(&ifr, 0, sizeof(ifr));
987     pstrcpy(ifr.ifr_name, IF_NAMESIZE, ifa->ifa_name);
988     if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {
989         /*
990          * We can't get the hw addr of this interface, but that's not a
991          * fatal error.
992          */
993         if (errno == EADDRNOTAVAIL) {
994             /* The interface doesn't have a hw addr (e.g. loopback). */
995             g_debug("failed to get MAC address of %s: %s",
996                     ifa->ifa_name, strerror(errno));
997         } else{
998             g_warning("failed to get MAC address of %s: %s",
999                       ifa->ifa_name, strerror(errno));
1000         }
1001     } else {
1002 #ifdef CONFIG_SOLARIS
1003         memcpy(buf, &ifr.ifr_addr.sa_data, ETHER_ADDR_LEN);
1004 #else
1005         memcpy(buf, &ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
1006 #endif
1007         *obtained = true;
1008     }
1009     close(sock);
1010     return true;
1011 }
1012 #endif /* CONFIG_BSD */
1013 
1014 /*
1015  * Build information about guest interfaces
1016  */
1017 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1018 {
1019     GuestNetworkInterfaceList *head = NULL, **tail = &head;
1020     struct ifaddrs *ifap, *ifa;
1021 
1022     if (getifaddrs(&ifap) < 0) {
1023         error_setg_errno(errp, errno, "getifaddrs failed");
1024         goto error;
1025     }
1026 
1027     for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1028         GuestNetworkInterface *info;
1029         GuestIpAddressList **address_tail;
1030         GuestIpAddress *address_item = NULL;
1031         GuestNetworkInterfaceStat *interface_stat = NULL;
1032         char addr4[INET_ADDRSTRLEN];
1033         char addr6[INET6_ADDRSTRLEN];
1034         unsigned char mac_addr[ETHER_ADDR_LEN];
1035         bool obtained;
1036         void *p;
1037 
1038         g_debug("Processing %s interface", ifa->ifa_name);
1039 
1040         info = guest_find_interface(head, ifa->ifa_name);
1041 
1042         if (!info) {
1043             info = g_malloc0(sizeof(*info));
1044             info->name = g_strdup(ifa->ifa_name);
1045 
1046             QAPI_LIST_APPEND(tail, info);
1047         }
1048 
1049         if (!info->hardware_address) {
1050             if (!guest_get_hw_addr(ifa, mac_addr, &obtained, errp)) {
1051                 goto error;
1052             }
1053             if (obtained) {
1054                 info->hardware_address =
1055                     g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1056                                     (int) mac_addr[0], (int) mac_addr[1],
1057                                     (int) mac_addr[2], (int) mac_addr[3],
1058                                     (int) mac_addr[4], (int) mac_addr[5]);
1059             }
1060         }
1061 
1062         if (ifa->ifa_addr &&
1063             ifa->ifa_addr->sa_family == AF_INET) {
1064             /* interface with IPv4 address */
1065             p = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
1066             if (!inet_ntop(AF_INET, p, addr4, sizeof(addr4))) {
1067                 error_setg_errno(errp, errno, "inet_ntop failed");
1068                 goto error;
1069             }
1070 
1071             address_item = g_malloc0(sizeof(*address_item));
1072             address_item->ip_address = g_strdup(addr4);
1073             address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
1074 
1075             if (ifa->ifa_netmask) {
1076                 /* Count the number of set bits in netmask.
1077                  * This is safe as '1' and '0' cannot be shuffled in netmask. */
1078                 p = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
1079                 address_item->prefix = ctpop32(((uint32_t *) p)[0]);
1080             }
1081         } else if (ifa->ifa_addr &&
1082                    ifa->ifa_addr->sa_family == AF_INET6) {
1083             /* interface with IPv6 address */
1084             p = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
1085             if (!inet_ntop(AF_INET6, p, addr6, sizeof(addr6))) {
1086                 error_setg_errno(errp, errno, "inet_ntop failed");
1087                 goto error;
1088             }
1089 
1090             address_item = g_malloc0(sizeof(*address_item));
1091             address_item->ip_address = g_strdup(addr6);
1092             address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
1093 
1094             if (ifa->ifa_netmask) {
1095                 /* Count the number of set bits in netmask.
1096                  * This is safe as '1' and '0' cannot be shuffled in netmask. */
1097                 p = &((struct sockaddr_in6 *)ifa->ifa_netmask)->sin6_addr;
1098                 address_item->prefix =
1099                     ctpop32(((uint32_t *) p)[0]) +
1100                     ctpop32(((uint32_t *) p)[1]) +
1101                     ctpop32(((uint32_t *) p)[2]) +
1102                     ctpop32(((uint32_t *) p)[3]);
1103             }
1104         }
1105 
1106         if (!address_item) {
1107             continue;
1108         }
1109 
1110         address_tail = &info->ip_addresses;
1111         while (*address_tail) {
1112             address_tail = &(*address_tail)->next;
1113         }
1114         QAPI_LIST_APPEND(address_tail, address_item);
1115 
1116         info->has_ip_addresses = true;
1117 
1118         if (!info->statistics) {
1119             interface_stat = g_malloc0(sizeof(*interface_stat));
1120             if (guest_get_network_stats(info->name, interface_stat) == -1) {
1121                 g_free(interface_stat);
1122             } else {
1123                 info->statistics = interface_stat;
1124             }
1125         }
1126     }
1127 
1128     freeifaddrs(ifap);
1129     return head;
1130 
1131 error:
1132     freeifaddrs(ifap);
1133     qapi_free_GuestNetworkInterfaceList(head);
1134     return NULL;
1135 }
1136 
1137 #endif /* HAVE_GETIFADDRS */
1138 
1139 /* register init/cleanup routines for stateful command groups */
1140 void ga_command_state_init(GAState *s, GACommandState *cs)
1141 {
1142 #if defined(CONFIG_FSFREEZE)
1143     ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
1144 #endif
1145 }
1146 
1147 #ifdef HAVE_UTMPX
1148 
1149 #define QGA_MICRO_SECOND_TO_SECOND 1000000
1150 
1151 static double ga_get_login_time(struct utmpx *user_info)
1152 {
1153     double seconds = (double)user_info->ut_tv.tv_sec;
1154     double useconds = (double)user_info->ut_tv.tv_usec;
1155     useconds /= QGA_MICRO_SECOND_TO_SECOND;
1156     return seconds + useconds;
1157 }
1158 
1159 GuestUserList *qmp_guest_get_users(Error **errp)
1160 {
1161     GHashTable *cache = NULL;
1162     GuestUserList *head = NULL, **tail = &head;
1163     struct utmpx *user_info = NULL;
1164     gpointer value = NULL;
1165     GuestUser *user = NULL;
1166     double login_time = 0;
1167 
1168     cache = g_hash_table_new(g_str_hash, g_str_equal);
1169     setutxent();
1170 
1171     for (;;) {
1172         user_info = getutxent();
1173         if (user_info == NULL) {
1174             break;
1175         } else if (user_info->ut_type != USER_PROCESS) {
1176             continue;
1177         } else if (g_hash_table_contains(cache, user_info->ut_user)) {
1178             value = g_hash_table_lookup(cache, user_info->ut_user);
1179             user = (GuestUser *)value;
1180             login_time = ga_get_login_time(user_info);
1181             /* We're ensuring the earliest login time to be sent */
1182             if (login_time < user->login_time) {
1183                 user->login_time = login_time;
1184             }
1185             continue;
1186         }
1187 
1188         user = g_new0(GuestUser, 1);
1189         user->user = g_strdup(user_info->ut_user);
1190         user->login_time = ga_get_login_time(user_info);
1191 
1192         g_hash_table_insert(cache, user->user, user);
1193 
1194         QAPI_LIST_APPEND(tail, user);
1195     }
1196     endutxent();
1197     g_hash_table_destroy(cache);
1198     return head;
1199 }
1200 
1201 #endif /* HAVE_UTMPX */
1202 
1203 /* Replace escaped special characters with their real values. The replacement
1204  * is done in place -- returned value is in the original string.
1205  */
1206 static void ga_osrelease_replace_special(gchar *value)
1207 {
1208     gchar *p, *p2, quote;
1209 
1210     /* Trim the string at first space or semicolon if it is not enclosed in
1211      * single or double quotes. */
1212     if ((value[0] != '"') || (value[0] == '\'')) {
1213         p = strchr(value, ' ');
1214         if (p != NULL) {
1215             *p = 0;
1216         }
1217         p = strchr(value, ';');
1218         if (p != NULL) {
1219             *p = 0;
1220         }
1221         return;
1222     }
1223 
1224     quote = value[0];
1225     p2 = value;
1226     p = value + 1;
1227     while (*p != 0) {
1228         if (*p == '\\') {
1229             p++;
1230             switch (*p) {
1231             case '$':
1232             case '\'':
1233             case '"':
1234             case '\\':
1235             case '`':
1236                 break;
1237             default:
1238                 /* Keep literal backslash followed by whatever is there */
1239                 p--;
1240                 break;
1241             }
1242         } else if (*p == quote) {
1243             *p2 = 0;
1244             break;
1245         }
1246         *(p2++) = *(p++);
1247     }
1248 }
1249 
1250 static GKeyFile *ga_parse_osrelease(const char *fname)
1251 {
1252     gchar *content = NULL;
1253     gchar *content2 = NULL;
1254     GError *err = NULL;
1255     GKeyFile *keys = g_key_file_new();
1256     const char *group = "[os-release]\n";
1257 
1258     if (!g_file_get_contents(fname, &content, NULL, &err)) {
1259         slog("failed to read '%s', error: %s", fname, err->message);
1260         goto fail;
1261     }
1262 
1263     if (!g_utf8_validate(content, -1, NULL)) {
1264         slog("file is not utf-8 encoded: %s", fname);
1265         goto fail;
1266     }
1267     content2 = g_strdup_printf("%s%s", group, content);
1268 
1269     if (!g_key_file_load_from_data(keys, content2, -1, G_KEY_FILE_NONE,
1270                                    &err)) {
1271         slog("failed to parse file '%s', error: %s", fname, err->message);
1272         goto fail;
1273     }
1274 
1275     g_free(content);
1276     g_free(content2);
1277     return keys;
1278 
1279 fail:
1280     g_error_free(err);
1281     g_free(content);
1282     g_free(content2);
1283     g_key_file_free(keys);
1284     return NULL;
1285 }
1286 
1287 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
1288 {
1289     GuestOSInfo *info = NULL;
1290     struct utsname kinfo;
1291     GKeyFile *osrelease = NULL;
1292     const char *qga_os_release = g_getenv("QGA_OS_RELEASE");
1293 
1294     info = g_new0(GuestOSInfo, 1);
1295 
1296     if (uname(&kinfo) != 0) {
1297         error_setg_errno(errp, errno, "uname failed");
1298     } else {
1299         info->kernel_version = g_strdup(kinfo.version);
1300         info->kernel_release = g_strdup(kinfo.release);
1301         info->machine = g_strdup(kinfo.machine);
1302     }
1303 
1304     if (qga_os_release != NULL) {
1305         osrelease = ga_parse_osrelease(qga_os_release);
1306     } else {
1307         osrelease = ga_parse_osrelease("/etc/os-release");
1308         if (osrelease == NULL) {
1309             osrelease = ga_parse_osrelease("/usr/lib/os-release");
1310         }
1311     }
1312 
1313     if (osrelease != NULL) {
1314         char *value;
1315 
1316 #define GET_FIELD(field, osfield) do { \
1317     value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
1318     if (value != NULL) { \
1319         ga_osrelease_replace_special(value); \
1320         info->field = value; \
1321     } \
1322 } while (0)
1323         GET_FIELD(id, "ID");
1324         GET_FIELD(name, "NAME");
1325         GET_FIELD(pretty_name, "PRETTY_NAME");
1326         GET_FIELD(version, "VERSION");
1327         GET_FIELD(version_id, "VERSION_ID");
1328         GET_FIELD(variant, "VARIANT");
1329         GET_FIELD(variant_id, "VARIANT_ID");
1330 #undef GET_FIELD
1331 
1332         g_key_file_free(osrelease);
1333     }
1334 
1335     return info;
1336 }
1337 
1338 #ifndef HOST_NAME_MAX
1339 # ifdef _POSIX_HOST_NAME_MAX
1340 #  define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
1341 # else
1342 #  define HOST_NAME_MAX 255
1343 # endif
1344 #endif
1345 
1346 char *qga_get_host_name(Error **errp)
1347 {
1348     long len = -1;
1349     g_autofree char *hostname = NULL;
1350 
1351 #ifdef _SC_HOST_NAME_MAX
1352     len = sysconf(_SC_HOST_NAME_MAX);
1353 #endif /* _SC_HOST_NAME_MAX */
1354 
1355     if (len < 0) {
1356         len = HOST_NAME_MAX;
1357     }
1358 
1359     /* Unfortunately, gethostname() below does not guarantee a
1360      * NULL terminated string. Therefore, allocate one byte more
1361      * to be sure. */
1362     hostname = g_new0(char, len + 1);
1363 
1364     if (gethostname(hostname, len) < 0) {
1365         error_setg_errno(errp, errno,
1366                          "cannot get hostname");
1367         return NULL;
1368     }
1369 
1370     return g_steal_pointer(&hostname);
1371 }
1372