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