xref: /openbmc/qemu/qga/commands-posix.c (revision 700784bf)
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     if (ret >= 0) {
809         ga_unset_frozen(ga_state);
810         execute_fsfreeze_hook(FSFREEZE_HOOK_THAW, errp);
811     } else {
812         ret = 0;
813     }
814 
815     return ret;
816 }
817 
818 static void guest_fsfreeze_cleanup(void)
819 {
820     Error *err = NULL;
821 
822     if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
823         qmp_guest_fsfreeze_thaw(&err);
824         if (err) {
825             slog("failed to clean up frozen filesystems: %s",
826                  error_get_pretty(err));
827             error_free(err);
828         }
829     }
830 }
831 #endif
832 
833 #if defined(__linux__) || defined(__FreeBSD__)
834 void qmp_guest_set_user_password(const char *username,
835                                  const char *password,
836                                  bool crypted,
837                                  Error **errp)
838 {
839     Error *local_err = NULL;
840     g_autofree char *rawpasswddata = NULL;
841     size_t rawpasswdlen;
842 
843     rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
844     if (!rawpasswddata) {
845         return;
846     }
847     rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
848     rawpasswddata[rawpasswdlen] = '\0';
849 
850     if (strchr(rawpasswddata, '\n')) {
851         error_setg(errp, "forbidden characters in raw password");
852         return;
853     }
854 
855     if (strchr(username, '\n') ||
856         strchr(username, ':')) {
857         error_setg(errp, "forbidden characters in username");
858         return;
859     }
860 
861 #ifdef __FreeBSD__
862     g_autofree char *chpasswddata = g_strdup(rawpasswddata);
863     const char *crypt_flag = crypted ? "-H" : "-h";
864     const char *argv[] = {"pw", "usermod", "-n", username,
865                           crypt_flag, "0", NULL};
866 #else
867     g_autofree char *chpasswddata = g_strdup_printf("%s:%s\n", username,
868                                                     rawpasswddata);
869     const char *crypt_flag = crypted ? "-e" : NULL;
870     const char *argv[] = {"chpasswd", crypt_flag, NULL};
871 #endif
872 
873     ga_run_command(argv, chpasswddata, "set user password", &local_err);
874     if (local_err) {
875         error_propagate(errp, local_err);
876         return;
877     }
878 }
879 #endif /* __linux__ || __FreeBSD__ */
880 
881 #ifdef HAVE_GETIFADDRS
882 static GuestNetworkInterface *
883 guest_find_interface(GuestNetworkInterfaceList *head,
884                      const char *name)
885 {
886     for (; head; head = head->next) {
887         if (strcmp(head->value->name, name) == 0) {
888             return head->value;
889         }
890     }
891 
892     return NULL;
893 }
894 
895 static int guest_get_network_stats(const char *name,
896                        GuestNetworkInterfaceStat *stats)
897 {
898 #ifdef CONFIG_LINUX
899     int name_len;
900     char const *devinfo = "/proc/net/dev";
901     FILE *fp;
902     char *line = NULL, *colon;
903     size_t n = 0;
904     fp = fopen(devinfo, "r");
905     if (!fp) {
906         g_debug("failed to open network stats %s: %s", devinfo,
907                 g_strerror(errno));
908         return -1;
909     }
910     name_len = strlen(name);
911     while (getline(&line, &n, fp) != -1) {
912         long long dummy;
913         long long rx_bytes;
914         long long rx_packets;
915         long long rx_errs;
916         long long rx_dropped;
917         long long tx_bytes;
918         long long tx_packets;
919         long long tx_errs;
920         long long tx_dropped;
921         char *trim_line;
922         trim_line = g_strchug(line);
923         if (trim_line[0] == '\0') {
924             continue;
925         }
926         colon = strchr(trim_line, ':');
927         if (!colon) {
928             continue;
929         }
930         if (colon - name_len  == trim_line &&
931            strncmp(trim_line, name, name_len) == 0) {
932             if (sscanf(colon + 1,
933                 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
934                   &rx_bytes, &rx_packets, &rx_errs, &rx_dropped,
935                   &dummy, &dummy, &dummy, &dummy,
936                   &tx_bytes, &tx_packets, &tx_errs, &tx_dropped,
937                   &dummy, &dummy, &dummy, &dummy) != 16) {
938                 continue;
939             }
940             stats->rx_bytes = rx_bytes;
941             stats->rx_packets = rx_packets;
942             stats->rx_errs = rx_errs;
943             stats->rx_dropped = rx_dropped;
944             stats->tx_bytes = tx_bytes;
945             stats->tx_packets = tx_packets;
946             stats->tx_errs = tx_errs;
947             stats->tx_dropped = tx_dropped;
948             fclose(fp);
949             g_free(line);
950             return 0;
951         }
952     }
953     fclose(fp);
954     g_free(line);
955     g_debug("/proc/net/dev: Interface '%s' not found", name);
956 #else /* !CONFIG_LINUX */
957     g_debug("Network stats reporting available only for Linux");
958 #endif /* !CONFIG_LINUX */
959     return -1;
960 }
961 
962 #ifndef CONFIG_BSD
963 /*
964  * Fill "buf" with MAC address by ifaddrs. Pointer buf must point to a
965  * buffer with ETHER_ADDR_LEN length at least.
966  *
967  * Returns false in case of an error, otherwise true. "obtained" argument
968  * is true if a MAC address was obtained successful, otherwise false.
969  */
970 bool guest_get_hw_addr(struct ifaddrs *ifa, unsigned char *buf,
971                        bool *obtained, Error **errp)
972 {
973     struct ifreq ifr;
974     int sock;
975 
976     *obtained = false;
977 
978     /* we haven't obtained HW address yet */
979     sock = socket(PF_INET, SOCK_STREAM, 0);
980     if (sock == -1) {
981         error_setg_errno(errp, errno, "failed to create socket");
982         return false;
983     }
984 
985     memset(&ifr, 0, sizeof(ifr));
986     pstrcpy(ifr.ifr_name, IF_NAMESIZE, ifa->ifa_name);
987     if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {
988         /*
989          * We can't get the hw addr of this interface, but that's not a
990          * fatal error.
991          */
992         if (errno == EADDRNOTAVAIL) {
993             /* The interface doesn't have a hw addr (e.g. loopback). */
994             g_debug("failed to get MAC address of %s: %s",
995                     ifa->ifa_name, strerror(errno));
996         } else{
997             g_warning("failed to get MAC address of %s: %s",
998                       ifa->ifa_name, strerror(errno));
999         }
1000     } else {
1001 #ifdef CONFIG_SOLARIS
1002         memcpy(buf, &ifr.ifr_addr.sa_data, ETHER_ADDR_LEN);
1003 #else
1004         memcpy(buf, &ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
1005 #endif
1006         *obtained = true;
1007     }
1008     close(sock);
1009     return true;
1010 }
1011 #endif /* CONFIG_BSD */
1012 
1013 /*
1014  * Build information about guest interfaces
1015  */
1016 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1017 {
1018     GuestNetworkInterfaceList *head = NULL, **tail = &head;
1019     struct ifaddrs *ifap, *ifa;
1020 
1021     if (getifaddrs(&ifap) < 0) {
1022         error_setg_errno(errp, errno, "getifaddrs failed");
1023         goto error;
1024     }
1025 
1026     for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1027         GuestNetworkInterface *info;
1028         GuestIpAddressList **address_tail;
1029         GuestIpAddress *address_item = NULL;
1030         GuestNetworkInterfaceStat *interface_stat = NULL;
1031         char addr4[INET_ADDRSTRLEN];
1032         char addr6[INET6_ADDRSTRLEN];
1033         unsigned char mac_addr[ETHER_ADDR_LEN];
1034         bool obtained;
1035         void *p;
1036 
1037         g_debug("Processing %s interface", ifa->ifa_name);
1038 
1039         info = guest_find_interface(head, ifa->ifa_name);
1040 
1041         if (!info) {
1042             info = g_malloc0(sizeof(*info));
1043             info->name = g_strdup(ifa->ifa_name);
1044 
1045             QAPI_LIST_APPEND(tail, info);
1046         }
1047 
1048         if (!info->hardware_address) {
1049             if (!guest_get_hw_addr(ifa, mac_addr, &obtained, errp)) {
1050                 goto error;
1051             }
1052             if (obtained) {
1053                 info->hardware_address =
1054                     g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1055                                     (int) mac_addr[0], (int) mac_addr[1],
1056                                     (int) mac_addr[2], (int) mac_addr[3],
1057                                     (int) mac_addr[4], (int) mac_addr[5]);
1058             }
1059         }
1060 
1061         if (ifa->ifa_addr &&
1062             ifa->ifa_addr->sa_family == AF_INET) {
1063             /* interface with IPv4 address */
1064             p = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
1065             if (!inet_ntop(AF_INET, p, addr4, sizeof(addr4))) {
1066                 error_setg_errno(errp, errno, "inet_ntop failed");
1067                 goto error;
1068             }
1069 
1070             address_item = g_malloc0(sizeof(*address_item));
1071             address_item->ip_address = g_strdup(addr4);
1072             address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
1073 
1074             if (ifa->ifa_netmask) {
1075                 /* Count the number of set bits in netmask.
1076                  * This is safe as '1' and '0' cannot be shuffled in netmask. */
1077                 p = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
1078                 address_item->prefix = ctpop32(((uint32_t *) p)[0]);
1079             }
1080         } else if (ifa->ifa_addr &&
1081                    ifa->ifa_addr->sa_family == AF_INET6) {
1082             /* interface with IPv6 address */
1083             p = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
1084             if (!inet_ntop(AF_INET6, p, addr6, sizeof(addr6))) {
1085                 error_setg_errno(errp, errno, "inet_ntop failed");
1086                 goto error;
1087             }
1088 
1089             address_item = g_malloc0(sizeof(*address_item));
1090             address_item->ip_address = g_strdup(addr6);
1091             address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
1092 
1093             if (ifa->ifa_netmask) {
1094                 /* Count the number of set bits in netmask.
1095                  * This is safe as '1' and '0' cannot be shuffled in netmask. */
1096                 p = &((struct sockaddr_in6 *)ifa->ifa_netmask)->sin6_addr;
1097                 address_item->prefix =
1098                     ctpop32(((uint32_t *) p)[0]) +
1099                     ctpop32(((uint32_t *) p)[1]) +
1100                     ctpop32(((uint32_t *) p)[2]) +
1101                     ctpop32(((uint32_t *) p)[3]);
1102             }
1103         }
1104 
1105         if (!address_item) {
1106             continue;
1107         }
1108 
1109         address_tail = &info->ip_addresses;
1110         while (*address_tail) {
1111             address_tail = &(*address_tail)->next;
1112         }
1113         QAPI_LIST_APPEND(address_tail, address_item);
1114 
1115         info->has_ip_addresses = true;
1116 
1117         if (!info->statistics) {
1118             interface_stat = g_malloc0(sizeof(*interface_stat));
1119             if (guest_get_network_stats(info->name, interface_stat) == -1) {
1120                 g_free(interface_stat);
1121             } else {
1122                 info->statistics = interface_stat;
1123             }
1124         }
1125     }
1126 
1127     freeifaddrs(ifap);
1128     return head;
1129 
1130 error:
1131     freeifaddrs(ifap);
1132     qapi_free_GuestNetworkInterfaceList(head);
1133     return NULL;
1134 }
1135 
1136 #endif /* HAVE_GETIFADDRS */
1137 
1138 /* register init/cleanup routines for stateful command groups */
1139 void ga_command_state_init(GAState *s, GACommandState *cs)
1140 {
1141 #if defined(CONFIG_FSFREEZE)
1142     ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
1143 #endif
1144 }
1145 
1146 #ifdef HAVE_UTMPX
1147 
1148 #define QGA_MICRO_SECOND_TO_SECOND 1000000
1149 
1150 static double ga_get_login_time(struct utmpx *user_info)
1151 {
1152     double seconds = (double)user_info->ut_tv.tv_sec;
1153     double useconds = (double)user_info->ut_tv.tv_usec;
1154     useconds /= QGA_MICRO_SECOND_TO_SECOND;
1155     return seconds + useconds;
1156 }
1157 
1158 GuestUserList *qmp_guest_get_users(Error **errp)
1159 {
1160     GHashTable *cache = NULL;
1161     GuestUserList *head = NULL, **tail = &head;
1162     struct utmpx *user_info = NULL;
1163     gpointer value = NULL;
1164     GuestUser *user = NULL;
1165     double login_time = 0;
1166 
1167     cache = g_hash_table_new(g_str_hash, g_str_equal);
1168     setutxent();
1169 
1170     for (;;) {
1171         user_info = getutxent();
1172         if (user_info == NULL) {
1173             break;
1174         } else if (user_info->ut_type != USER_PROCESS) {
1175             continue;
1176         } else if (g_hash_table_contains(cache, user_info->ut_user)) {
1177             value = g_hash_table_lookup(cache, user_info->ut_user);
1178             user = (GuestUser *)value;
1179             login_time = ga_get_login_time(user_info);
1180             /* We're ensuring the earliest login time to be sent */
1181             if (login_time < user->login_time) {
1182                 user->login_time = login_time;
1183             }
1184             continue;
1185         }
1186 
1187         user = g_new0(GuestUser, 1);
1188         user->user = g_strdup(user_info->ut_user);
1189         user->login_time = ga_get_login_time(user_info);
1190 
1191         g_hash_table_insert(cache, user->user, user);
1192 
1193         QAPI_LIST_APPEND(tail, user);
1194     }
1195     endutxent();
1196     g_hash_table_destroy(cache);
1197     return head;
1198 }
1199 
1200 #endif /* HAVE_UTMPX */
1201 
1202 /* Replace escaped special characters with their real values. The replacement
1203  * is done in place -- returned value is in the original string.
1204  */
1205 static void ga_osrelease_replace_special(gchar *value)
1206 {
1207     gchar *p, *p2, quote;
1208 
1209     /* Trim the string at first space or semicolon if it is not enclosed in
1210      * single or double quotes. */
1211     if ((value[0] != '"') || (value[0] == '\'')) {
1212         p = strchr(value, ' ');
1213         if (p != NULL) {
1214             *p = 0;
1215         }
1216         p = strchr(value, ';');
1217         if (p != NULL) {
1218             *p = 0;
1219         }
1220         return;
1221     }
1222 
1223     quote = value[0];
1224     p2 = value;
1225     p = value + 1;
1226     while (*p != 0) {
1227         if (*p == '\\') {
1228             p++;
1229             switch (*p) {
1230             case '$':
1231             case '\'':
1232             case '"':
1233             case '\\':
1234             case '`':
1235                 break;
1236             default:
1237                 /* Keep literal backslash followed by whatever is there */
1238                 p--;
1239                 break;
1240             }
1241         } else if (*p == quote) {
1242             *p2 = 0;
1243             break;
1244         }
1245         *(p2++) = *(p++);
1246     }
1247 }
1248 
1249 static GKeyFile *ga_parse_osrelease(const char *fname)
1250 {
1251     gchar *content = NULL;
1252     gchar *content2 = NULL;
1253     GError *err = NULL;
1254     GKeyFile *keys = g_key_file_new();
1255     const char *group = "[os-release]\n";
1256 
1257     if (!g_file_get_contents(fname, &content, NULL, &err)) {
1258         slog("failed to read '%s', error: %s", fname, err->message);
1259         goto fail;
1260     }
1261 
1262     if (!g_utf8_validate(content, -1, NULL)) {
1263         slog("file is not utf-8 encoded: %s", fname);
1264         goto fail;
1265     }
1266     content2 = g_strdup_printf("%s%s", group, content);
1267 
1268     if (!g_key_file_load_from_data(keys, content2, -1, G_KEY_FILE_NONE,
1269                                    &err)) {
1270         slog("failed to parse file '%s', error: %s", fname, err->message);
1271         goto fail;
1272     }
1273 
1274     g_free(content);
1275     g_free(content2);
1276     return keys;
1277 
1278 fail:
1279     g_error_free(err);
1280     g_free(content);
1281     g_free(content2);
1282     g_key_file_free(keys);
1283     return NULL;
1284 }
1285 
1286 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
1287 {
1288     GuestOSInfo *info = NULL;
1289     struct utsname kinfo;
1290     GKeyFile *osrelease = NULL;
1291     const char *qga_os_release = g_getenv("QGA_OS_RELEASE");
1292 
1293     info = g_new0(GuestOSInfo, 1);
1294 
1295     if (uname(&kinfo) != 0) {
1296         error_setg_errno(errp, errno, "uname failed");
1297     } else {
1298         info->kernel_version = g_strdup(kinfo.version);
1299         info->kernel_release = g_strdup(kinfo.release);
1300         info->machine = g_strdup(kinfo.machine);
1301     }
1302 
1303     if (qga_os_release != NULL) {
1304         osrelease = ga_parse_osrelease(qga_os_release);
1305     } else {
1306         osrelease = ga_parse_osrelease("/etc/os-release");
1307         if (osrelease == NULL) {
1308             osrelease = ga_parse_osrelease("/usr/lib/os-release");
1309         }
1310     }
1311 
1312     if (osrelease != NULL) {
1313         char *value;
1314 
1315 #define GET_FIELD(field, osfield) do { \
1316     value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
1317     if (value != NULL) { \
1318         ga_osrelease_replace_special(value); \
1319         info->field = value; \
1320     } \
1321 } while (0)
1322         GET_FIELD(id, "ID");
1323         GET_FIELD(name, "NAME");
1324         GET_FIELD(pretty_name, "PRETTY_NAME");
1325         GET_FIELD(version, "VERSION");
1326         GET_FIELD(version_id, "VERSION_ID");
1327         GET_FIELD(variant, "VARIANT");
1328         GET_FIELD(variant_id, "VARIANT_ID");
1329 #undef GET_FIELD
1330 
1331         g_key_file_free(osrelease);
1332     }
1333 
1334     return info;
1335 }
1336 
1337 #ifndef HOST_NAME_MAX
1338 # ifdef _POSIX_HOST_NAME_MAX
1339 #  define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
1340 # else
1341 #  define HOST_NAME_MAX 255
1342 # endif
1343 #endif
1344 
1345 char *qga_get_host_name(Error **errp)
1346 {
1347     long len = -1;
1348     g_autofree char *hostname = NULL;
1349 
1350 #ifdef _SC_HOST_NAME_MAX
1351     len = sysconf(_SC_HOST_NAME_MAX);
1352 #endif /* _SC_HOST_NAME_MAX */
1353 
1354     if (len < 0) {
1355         len = HOST_NAME_MAX;
1356     }
1357 
1358     /* Unfortunately, gethostname() below does not guarantee a
1359      * NULL terminated string. Therefore, allocate one byte more
1360      * to be sure. */
1361     hostname = g_new0(char, len + 1);
1362 
1363     if (gethostname(hostname, len) < 0) {
1364         error_setg_errno(errp, errno,
1365                          "cannot get hostname");
1366         return NULL;
1367     }
1368 
1369     return g_steal_pointer(&hostname);
1370 }
1371