xref: /openbmc/qemu/qga/commands-posix.c (revision 5b723a5d8df44b69b8ba350e643059c8fd889315)
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 "qemu-common.h"
20 #include "guest-agent-core.h"
21 #include "qga-qapi-commands.h"
22 #include "qapi/error.h"
23 #include "qapi/qmp/qerror.h"
24 #include "qemu/queue.h"
25 #include "qemu/host-utils.h"
26 #include "qemu/sockets.h"
27 #include "qemu/base64.h"
28 #include "qemu/cutils.h"
29 #include "commands-common.h"
30 
31 #ifdef HAVE_UTMPX
32 #include <utmpx.h>
33 #endif
34 
35 #ifndef CONFIG_HAS_ENVIRON
36 #ifdef __APPLE__
37 #include <crt_externs.h>
38 #define environ (*_NSGetEnviron())
39 #else
40 extern char **environ;
41 #endif
42 #endif
43 
44 #if defined(__linux__)
45 #include <mntent.h>
46 #include <linux/fs.h>
47 #include <ifaddrs.h>
48 #include <arpa/inet.h>
49 #include <sys/socket.h>
50 #include <net/if.h>
51 #include <sys/statvfs.h>
52 
53 #ifdef CONFIG_LIBUDEV
54 #include <libudev.h>
55 #endif
56 
57 #ifdef FIFREEZE
58 #define CONFIG_FSFREEZE
59 #endif
60 #ifdef FITRIM
61 #define CONFIG_FSTRIM
62 #endif
63 #endif
64 
65 static void ga_wait_child(pid_t pid, int *status, Error **errp)
66 {
67     pid_t rpid;
68 
69     *status = 0;
70 
71     do {
72         rpid = waitpid(pid, status, 0);
73     } while (rpid == -1 && errno == EINTR);
74 
75     if (rpid == -1) {
76         error_setg_errno(errp, errno, "failed to wait for child (pid: %d)",
77                          pid);
78         return;
79     }
80 
81     g_assert(rpid == pid);
82 }
83 
84 void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
85 {
86     const char *shutdown_flag;
87     Error *local_err = NULL;
88     pid_t pid;
89     int status;
90 
91     slog("guest-shutdown called, mode: %s", mode);
92     if (!has_mode || strcmp(mode, "powerdown") == 0) {
93         shutdown_flag = "-P";
94     } else if (strcmp(mode, "halt") == 0) {
95         shutdown_flag = "-H";
96     } else if (strcmp(mode, "reboot") == 0) {
97         shutdown_flag = "-r";
98     } else {
99         error_setg(errp,
100                    "mode is invalid (valid values are: halt|powerdown|reboot");
101         return;
102     }
103 
104     pid = fork();
105     if (pid == 0) {
106         /* child, start the shutdown */
107         setsid();
108         reopen_fd_to_null(0);
109         reopen_fd_to_null(1);
110         reopen_fd_to_null(2);
111 
112         execle("/sbin/shutdown", "shutdown", "-h", shutdown_flag, "+0",
113                "hypervisor initiated shutdown", (char*)NULL, environ);
114         _exit(EXIT_FAILURE);
115     } else if (pid < 0) {
116         error_setg_errno(errp, errno, "failed to create child process");
117         return;
118     }
119 
120     ga_wait_child(pid, &status, &local_err);
121     if (local_err) {
122         error_propagate(errp, local_err);
123         return;
124     }
125 
126     if (!WIFEXITED(status)) {
127         error_setg(errp, "child process has terminated abnormally");
128         return;
129     }
130 
131     if (WEXITSTATUS(status)) {
132         error_setg(errp, "child process has failed to shutdown");
133         return;
134     }
135 
136     /* succeeded */
137 }
138 
139 int64_t qmp_guest_get_time(Error **errp)
140 {
141    int ret;
142    qemu_timeval tq;
143 
144    ret = qemu_gettimeofday(&tq);
145    if (ret < 0) {
146        error_setg_errno(errp, errno, "Failed to get time");
147        return -1;
148    }
149 
150    return tq.tv_sec * 1000000000LL + tq.tv_usec * 1000;
151 }
152 
153 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
154 {
155     int ret;
156     int status;
157     pid_t pid;
158     Error *local_err = NULL;
159     struct timeval tv;
160     static const char hwclock_path[] = "/sbin/hwclock";
161     static int hwclock_available = -1;
162 
163     if (hwclock_available < 0) {
164         hwclock_available = (access(hwclock_path, X_OK) == 0);
165     }
166 
167     if (!hwclock_available) {
168         error_setg(errp, QERR_UNSUPPORTED);
169         return;
170     }
171 
172     /* If user has passed a time, validate and set it. */
173     if (has_time) {
174         GDate date = { 0, };
175 
176         /* year-2038 will overflow in case time_t is 32bit */
177         if (time_ns / 1000000000 != (time_t)(time_ns / 1000000000)) {
178             error_setg(errp, "Time %" PRId64 " is too large", time_ns);
179             return;
180         }
181 
182         tv.tv_sec = time_ns / 1000000000;
183         tv.tv_usec = (time_ns % 1000000000) / 1000;
184         g_date_set_time_t(&date, tv.tv_sec);
185         if (date.year < 1970 || date.year >= 2070) {
186             error_setg_errno(errp, errno, "Invalid time");
187             return;
188         }
189 
190         ret = settimeofday(&tv, NULL);
191         if (ret < 0) {
192             error_setg_errno(errp, errno, "Failed to set time to guest");
193             return;
194         }
195     }
196 
197     /* Now, if user has passed a time to set and the system time is set, we
198      * just need to synchronize the hardware clock. However, if no time was
199      * passed, user is requesting the opposite: set the system time from the
200      * hardware clock (RTC). */
201     pid = fork();
202     if (pid == 0) {
203         setsid();
204         reopen_fd_to_null(0);
205         reopen_fd_to_null(1);
206         reopen_fd_to_null(2);
207 
208         /* Use '/sbin/hwclock -w' to set RTC from the system time,
209          * or '/sbin/hwclock -s' to set the system time from RTC. */
210         execle(hwclock_path, "hwclock", has_time ? "-w" : "-s",
211                NULL, environ);
212         _exit(EXIT_FAILURE);
213     } else if (pid < 0) {
214         error_setg_errno(errp, errno, "failed to create child process");
215         return;
216     }
217 
218     ga_wait_child(pid, &status, &local_err);
219     if (local_err) {
220         error_propagate(errp, local_err);
221         return;
222     }
223 
224     if (!WIFEXITED(status)) {
225         error_setg(errp, "child process has terminated abnormally");
226         return;
227     }
228 
229     if (WEXITSTATUS(status)) {
230         error_setg(errp, "hwclock failed to set hardware clock to system time");
231         return;
232     }
233 }
234 
235 typedef enum {
236     RW_STATE_NEW,
237     RW_STATE_READING,
238     RW_STATE_WRITING,
239 } RwState;
240 
241 struct GuestFileHandle {
242     uint64_t id;
243     FILE *fh;
244     RwState state;
245     QTAILQ_ENTRY(GuestFileHandle) next;
246 };
247 
248 static struct {
249     QTAILQ_HEAD(, GuestFileHandle) filehandles;
250 } guest_file_state = {
251     .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
252 };
253 
254 static int64_t guest_file_handle_add(FILE *fh, Error **errp)
255 {
256     GuestFileHandle *gfh;
257     int64_t handle;
258 
259     handle = ga_get_fd_handle(ga_state, errp);
260     if (handle < 0) {
261         return -1;
262     }
263 
264     gfh = g_new0(GuestFileHandle, 1);
265     gfh->id = handle;
266     gfh->fh = fh;
267     QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
268 
269     return handle;
270 }
271 
272 GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
273 {
274     GuestFileHandle *gfh;
275 
276     QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next)
277     {
278         if (gfh->id == id) {
279             return gfh;
280         }
281     }
282 
283     error_setg(errp, "handle '%" PRId64 "' has not been found", id);
284     return NULL;
285 }
286 
287 typedef const char * const ccpc;
288 
289 #ifndef O_BINARY
290 #define O_BINARY 0
291 #endif
292 
293 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
294 static const struct {
295     ccpc *forms;
296     int oflag_base;
297 } guest_file_open_modes[] = {
298     { (ccpc[]){ "r",          NULL }, O_RDONLY                                 },
299     { (ccpc[]){ "rb",         NULL }, O_RDONLY                      | O_BINARY },
300     { (ccpc[]){ "w",          NULL }, O_WRONLY | O_CREAT | O_TRUNC             },
301     { (ccpc[]){ "wb",         NULL }, O_WRONLY | O_CREAT | O_TRUNC  | O_BINARY },
302     { (ccpc[]){ "a",          NULL }, O_WRONLY | O_CREAT | O_APPEND            },
303     { (ccpc[]){ "ab",         NULL }, O_WRONLY | O_CREAT | O_APPEND | O_BINARY },
304     { (ccpc[]){ "r+",         NULL }, O_RDWR                                   },
305     { (ccpc[]){ "rb+", "r+b", NULL }, O_RDWR                        | O_BINARY },
306     { (ccpc[]){ "w+",         NULL }, O_RDWR   | O_CREAT | O_TRUNC             },
307     { (ccpc[]){ "wb+", "w+b", NULL }, O_RDWR   | O_CREAT | O_TRUNC  | O_BINARY },
308     { (ccpc[]){ "a+",         NULL }, O_RDWR   | O_CREAT | O_APPEND            },
309     { (ccpc[]){ "ab+", "a+b", NULL }, O_RDWR   | O_CREAT | O_APPEND | O_BINARY }
310 };
311 
312 static int
313 find_open_flag(const char *mode_str, Error **errp)
314 {
315     unsigned mode;
316 
317     for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
318         ccpc *form;
319 
320         form = guest_file_open_modes[mode].forms;
321         while (*form != NULL && strcmp(*form, mode_str) != 0) {
322             ++form;
323         }
324         if (*form != NULL) {
325             break;
326         }
327     }
328 
329     if (mode == ARRAY_SIZE(guest_file_open_modes)) {
330         error_setg(errp, "invalid file open mode '%s'", mode_str);
331         return -1;
332     }
333     return guest_file_open_modes[mode].oflag_base | O_NOCTTY | O_NONBLOCK;
334 }
335 
336 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
337                                S_IRGRP | S_IWGRP | \
338                                S_IROTH | S_IWOTH)
339 
340 static FILE *
341 safe_open_or_create(const char *path, const char *mode, Error **errp)
342 {
343     Error *local_err = NULL;
344     int oflag;
345 
346     oflag = find_open_flag(mode, &local_err);
347     if (local_err == NULL) {
348         int fd;
349 
350         /* If the caller wants / allows creation of a new file, we implement it
351          * with a two step process: open() + (open() / fchmod()).
352          *
353          * First we insist on creating the file exclusively as a new file. If
354          * that succeeds, we're free to set any file-mode bits on it. (The
355          * motivation is that we want to set those file-mode bits independently
356          * of the current umask.)
357          *
358          * If the exclusive creation fails because the file already exists
359          * (EEXIST is not possible for any other reason), we just attempt to
360          * open the file, but in this case we won't be allowed to change the
361          * file-mode bits on the preexistent file.
362          *
363          * The pathname should never disappear between the two open()s in
364          * practice. If it happens, then someone very likely tried to race us.
365          * In this case just go ahead and report the ENOENT from the second
366          * open() to the caller.
367          *
368          * If the caller wants to open a preexistent file, then the first
369          * open() is decisive and its third argument is ignored, and the second
370          * open() and the fchmod() are never called.
371          */
372         fd = open(path, oflag | ((oflag & O_CREAT) ? O_EXCL : 0), 0);
373         if (fd == -1 && errno == EEXIST) {
374             oflag &= ~(unsigned)O_CREAT;
375             fd = open(path, oflag);
376         }
377 
378         if (fd == -1) {
379             error_setg_errno(&local_err, errno, "failed to open file '%s' "
380                              "(mode: '%s')", path, mode);
381         } else {
382             qemu_set_cloexec(fd);
383 
384             if ((oflag & O_CREAT) && fchmod(fd, DEFAULT_NEW_FILE_MODE) == -1) {
385                 error_setg_errno(&local_err, errno, "failed to set permission "
386                                  "0%03o on new file '%s' (mode: '%s')",
387                                  (unsigned)DEFAULT_NEW_FILE_MODE, path, mode);
388             } else {
389                 FILE *f;
390 
391                 f = fdopen(fd, mode);
392                 if (f == NULL) {
393                     error_setg_errno(&local_err, errno, "failed to associate "
394                                      "stdio stream with file descriptor %d, "
395                                      "file '%s' (mode: '%s')", fd, path, mode);
396                 } else {
397                     return f;
398                 }
399             }
400 
401             close(fd);
402             if (oflag & O_CREAT) {
403                 unlink(path);
404             }
405         }
406     }
407 
408     error_propagate(errp, local_err);
409     return NULL;
410 }
411 
412 int64_t qmp_guest_file_open(const char *path, bool has_mode, const char *mode,
413                             Error **errp)
414 {
415     FILE *fh;
416     Error *local_err = NULL;
417     int64_t handle;
418 
419     if (!has_mode) {
420         mode = "r";
421     }
422     slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
423     fh = safe_open_or_create(path, mode, &local_err);
424     if (local_err != NULL) {
425         error_propagate(errp, local_err);
426         return -1;
427     }
428 
429     /* set fd non-blocking to avoid common use cases (like reading from a
430      * named pipe) from hanging the agent
431      */
432     qemu_set_nonblock(fileno(fh));
433 
434     handle = guest_file_handle_add(fh, errp);
435     if (handle < 0) {
436         fclose(fh);
437         return -1;
438     }
439 
440     slog("guest-file-open, handle: %" PRId64, handle);
441     return handle;
442 }
443 
444 void qmp_guest_file_close(int64_t handle, Error **errp)
445 {
446     GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
447     int ret;
448 
449     slog("guest-file-close called, handle: %" PRId64, handle);
450     if (!gfh) {
451         return;
452     }
453 
454     ret = fclose(gfh->fh);
455     if (ret == EOF) {
456         error_setg_errno(errp, errno, "failed to close handle");
457         return;
458     }
459 
460     QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
461     g_free(gfh);
462 }
463 
464 GuestFileRead *guest_file_read_unsafe(GuestFileHandle *gfh,
465                                       int64_t count, Error **errp)
466 {
467     GuestFileRead *read_data = NULL;
468     guchar *buf;
469     FILE *fh = gfh->fh;
470     size_t read_count;
471 
472     /* explicitly flush when switching from writing to reading */
473     if (gfh->state == RW_STATE_WRITING) {
474         int ret = fflush(fh);
475         if (ret == EOF) {
476             error_setg_errno(errp, errno, "failed to flush file");
477             return NULL;
478         }
479         gfh->state = RW_STATE_NEW;
480     }
481 
482     buf = g_malloc0(count+1);
483     read_count = fread(buf, 1, count, fh);
484     if (ferror(fh)) {
485         error_setg_errno(errp, errno, "failed to read file");
486     } else {
487         buf[read_count] = 0;
488         read_data = g_new0(GuestFileRead, 1);
489         read_data->count = read_count;
490         read_data->eof = feof(fh);
491         if (read_count) {
492             read_data->buf_b64 = g_base64_encode(buf, read_count);
493         }
494         gfh->state = RW_STATE_READING;
495     }
496     g_free(buf);
497     clearerr(fh);
498 
499     return read_data;
500 }
501 
502 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
503                                      bool has_count, int64_t count,
504                                      Error **errp)
505 {
506     GuestFileWrite *write_data = NULL;
507     guchar *buf;
508     gsize buf_len;
509     int write_count;
510     GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
511     FILE *fh;
512 
513     if (!gfh) {
514         return NULL;
515     }
516 
517     fh = gfh->fh;
518 
519     if (gfh->state == RW_STATE_READING) {
520         int ret = fseek(fh, 0, SEEK_CUR);
521         if (ret == -1) {
522             error_setg_errno(errp, errno, "failed to seek file");
523             return NULL;
524         }
525         gfh->state = RW_STATE_NEW;
526     }
527 
528     buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
529     if (!buf) {
530         return NULL;
531     }
532 
533     if (!has_count) {
534         count = buf_len;
535     } else if (count < 0 || count > buf_len) {
536         error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
537                    count);
538         g_free(buf);
539         return NULL;
540     }
541 
542     write_count = fwrite(buf, 1, count, fh);
543     if (ferror(fh)) {
544         error_setg_errno(errp, errno, "failed to write to file");
545         slog("guest-file-write failed, handle: %" PRId64, handle);
546     } else {
547         write_data = g_new0(GuestFileWrite, 1);
548         write_data->count = write_count;
549         write_data->eof = feof(fh);
550         gfh->state = RW_STATE_WRITING;
551     }
552     g_free(buf);
553     clearerr(fh);
554 
555     return write_data;
556 }
557 
558 struct GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
559                                           GuestFileWhence *whence_code,
560                                           Error **errp)
561 {
562     GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
563     GuestFileSeek *seek_data = NULL;
564     FILE *fh;
565     int ret;
566     int whence;
567     Error *err = NULL;
568 
569     if (!gfh) {
570         return NULL;
571     }
572 
573     /* We stupidly exposed 'whence':'int' in our qapi */
574     whence = ga_parse_whence(whence_code, &err);
575     if (err) {
576         error_propagate(errp, err);
577         return NULL;
578     }
579 
580     fh = gfh->fh;
581     ret = fseek(fh, offset, whence);
582     if (ret == -1) {
583         error_setg_errno(errp, errno, "failed to seek file");
584         if (errno == ESPIPE) {
585             /* file is non-seekable, stdio shouldn't be buffering anyways */
586             gfh->state = RW_STATE_NEW;
587         }
588     } else {
589         seek_data = g_new0(GuestFileSeek, 1);
590         seek_data->position = ftell(fh);
591         seek_data->eof = feof(fh);
592         gfh->state = RW_STATE_NEW;
593     }
594     clearerr(fh);
595 
596     return seek_data;
597 }
598 
599 void qmp_guest_file_flush(int64_t handle, Error **errp)
600 {
601     GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
602     FILE *fh;
603     int ret;
604 
605     if (!gfh) {
606         return;
607     }
608 
609     fh = gfh->fh;
610     ret = fflush(fh);
611     if (ret == EOF) {
612         error_setg_errno(errp, errno, "failed to flush file");
613     } else {
614         gfh->state = RW_STATE_NEW;
615     }
616 }
617 
618 /* linux-specific implementations. avoid this if at all possible. */
619 #if defined(__linux__)
620 
621 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
622 typedef struct FsMount {
623     char *dirname;
624     char *devtype;
625     unsigned int devmajor, devminor;
626     QTAILQ_ENTRY(FsMount) next;
627 } FsMount;
628 
629 typedef QTAILQ_HEAD(FsMountList, FsMount) FsMountList;
630 
631 static void free_fs_mount_list(FsMountList *mounts)
632 {
633      FsMount *mount, *temp;
634 
635      if (!mounts) {
636          return;
637      }
638 
639      QTAILQ_FOREACH_SAFE(mount, mounts, next, temp) {
640          QTAILQ_REMOVE(mounts, mount, next);
641          g_free(mount->dirname);
642          g_free(mount->devtype);
643          g_free(mount);
644      }
645 }
646 
647 static int dev_major_minor(const char *devpath,
648                            unsigned int *devmajor, unsigned int *devminor)
649 {
650     struct stat st;
651 
652     *devmajor = 0;
653     *devminor = 0;
654 
655     if (stat(devpath, &st) < 0) {
656         slog("failed to stat device file '%s': %s", devpath, strerror(errno));
657         return -1;
658     }
659     if (S_ISDIR(st.st_mode)) {
660         /* It is bind mount */
661         return -2;
662     }
663     if (S_ISBLK(st.st_mode)) {
664         *devmajor = major(st.st_rdev);
665         *devminor = minor(st.st_rdev);
666         return 0;
667     }
668     return -1;
669 }
670 
671 /*
672  * Walk the mount table and build a list of local file systems
673  */
674 static void build_fs_mount_list_from_mtab(FsMountList *mounts, Error **errp)
675 {
676     struct mntent *ment;
677     FsMount *mount;
678     char const *mtab = "/proc/self/mounts";
679     FILE *fp;
680     unsigned int devmajor, devminor;
681 
682     fp = setmntent(mtab, "r");
683     if (!fp) {
684         error_setg(errp, "failed to open mtab file: '%s'", mtab);
685         return;
686     }
687 
688     while ((ment = getmntent(fp))) {
689         /*
690          * An entry which device name doesn't start with a '/' is
691          * either a dummy file system or a network file system.
692          * Add special handling for smbfs and cifs as is done by
693          * coreutils as well.
694          */
695         if ((ment->mnt_fsname[0] != '/') ||
696             (strcmp(ment->mnt_type, "smbfs") == 0) ||
697             (strcmp(ment->mnt_type, "cifs") == 0)) {
698             continue;
699         }
700         if (dev_major_minor(ment->mnt_fsname, &devmajor, &devminor) == -2) {
701             /* Skip bind mounts */
702             continue;
703         }
704 
705         mount = g_new0(FsMount, 1);
706         mount->dirname = g_strdup(ment->mnt_dir);
707         mount->devtype = g_strdup(ment->mnt_type);
708         mount->devmajor = devmajor;
709         mount->devminor = devminor;
710 
711         QTAILQ_INSERT_TAIL(mounts, mount, next);
712     }
713 
714     endmntent(fp);
715 }
716 
717 static void decode_mntname(char *name, int len)
718 {
719     int i, j = 0;
720     for (i = 0; i <= len; i++) {
721         if (name[i] != '\\') {
722             name[j++] = name[i];
723         } else if (name[i + 1] == '\\') {
724             name[j++] = '\\';
725             i++;
726         } else if (name[i + 1] >= '0' && name[i + 1] <= '3' &&
727                    name[i + 2] >= '0' && name[i + 2] <= '7' &&
728                    name[i + 3] >= '0' && name[i + 3] <= '7') {
729             name[j++] = (name[i + 1] - '0') * 64 +
730                         (name[i + 2] - '0') * 8 +
731                         (name[i + 3] - '0');
732             i += 3;
733         } else {
734             name[j++] = name[i];
735         }
736     }
737 }
738 
739 static void build_fs_mount_list(FsMountList *mounts, Error **errp)
740 {
741     FsMount *mount;
742     char const *mountinfo = "/proc/self/mountinfo";
743     FILE *fp;
744     char *line = NULL, *dash;
745     size_t n;
746     char check;
747     unsigned int devmajor, devminor;
748     int ret, dir_s, dir_e, type_s, type_e, dev_s, dev_e;
749 
750     fp = fopen(mountinfo, "r");
751     if (!fp) {
752         build_fs_mount_list_from_mtab(mounts, errp);
753         return;
754     }
755 
756     while (getline(&line, &n, fp) != -1) {
757         ret = sscanf(line, "%*u %*u %u:%u %*s %n%*s%n%c",
758                      &devmajor, &devminor, &dir_s, &dir_e, &check);
759         if (ret < 3) {
760             continue;
761         }
762         dash = strstr(line + dir_e, " - ");
763         if (!dash) {
764             continue;
765         }
766         ret = sscanf(dash, " - %n%*s%n %n%*s%n%c",
767                      &type_s, &type_e, &dev_s, &dev_e, &check);
768         if (ret < 1) {
769             continue;
770         }
771         line[dir_e] = 0;
772         dash[type_e] = 0;
773         dash[dev_e] = 0;
774         decode_mntname(line + dir_s, dir_e - dir_s);
775         decode_mntname(dash + dev_s, dev_e - dev_s);
776         if (devmajor == 0) {
777             /* btrfs reports major number = 0 */
778             if (strcmp("btrfs", dash + type_s) != 0 ||
779                 dev_major_minor(dash + dev_s, &devmajor, &devminor) < 0) {
780                 continue;
781             }
782         }
783 
784         mount = g_new0(FsMount, 1);
785         mount->dirname = g_strdup(line + dir_s);
786         mount->devtype = g_strdup(dash + type_s);
787         mount->devmajor = devmajor;
788         mount->devminor = devminor;
789 
790         QTAILQ_INSERT_TAIL(mounts, mount, next);
791     }
792     free(line);
793 
794     fclose(fp);
795 }
796 #endif
797 
798 #if defined(CONFIG_FSFREEZE)
799 
800 static char *get_pci_driver(char const *syspath, int pathlen, Error **errp)
801 {
802     char *path;
803     char *dpath;
804     char *driver = NULL;
805     char buf[PATH_MAX];
806     ssize_t len;
807 
808     path = g_strndup(syspath, pathlen);
809     dpath = g_strdup_printf("%s/driver", path);
810     len = readlink(dpath, buf, sizeof(buf) - 1);
811     if (len != -1) {
812         buf[len] = 0;
813         driver = g_path_get_basename(buf);
814     }
815     g_free(dpath);
816     g_free(path);
817     return driver;
818 }
819 
820 static int compare_uint(const void *_a, const void *_b)
821 {
822     unsigned int a = *(unsigned int *)_a;
823     unsigned int b = *(unsigned int *)_b;
824 
825     return a < b ? -1 : a > b ? 1 : 0;
826 }
827 
828 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
829 static int build_hosts(char const *syspath, char const *host, bool ata,
830                        unsigned int *hosts, int hosts_max, Error **errp)
831 {
832     char *path;
833     DIR *dir;
834     struct dirent *entry;
835     int i = 0;
836 
837     path = g_strndup(syspath, host - syspath);
838     dir = opendir(path);
839     if (!dir) {
840         error_setg_errno(errp, errno, "opendir(\"%s\")", path);
841         g_free(path);
842         return -1;
843     }
844 
845     while (i < hosts_max) {
846         entry = readdir(dir);
847         if (!entry) {
848             break;
849         }
850         if (ata && sscanf(entry->d_name, "ata%d", hosts + i) == 1) {
851             ++i;
852         } else if (!ata && sscanf(entry->d_name, "host%d", hosts + i) == 1) {
853             ++i;
854         }
855     }
856 
857     qsort(hosts, i, sizeof(hosts[0]), compare_uint);
858 
859     g_free(path);
860     closedir(dir);
861     return i;
862 }
863 
864 /*
865  * Store disk device info for devices on the PCI bus.
866  * Returns true if information has been stored, or false for failure.
867  */
868 static bool build_guest_fsinfo_for_pci_dev(char const *syspath,
869                                            GuestDiskAddress *disk,
870                                            Error **errp)
871 {
872     unsigned int pci[4], host, hosts[8], tgt[3];
873     int i, nhosts = 0, pcilen;
874     GuestPCIAddress *pciaddr = disk->pci_controller;
875     bool has_ata = false, has_host = false, has_tgt = false;
876     char *p, *q, *driver = NULL;
877     bool ret = false;
878 
879     p = strstr(syspath, "/devices/pci");
880     if (!p || sscanf(p + 12, "%*x:%*x/%x:%x:%x.%x%n",
881                      pci, pci + 1, pci + 2, pci + 3, &pcilen) < 4) {
882         g_debug("only pci device is supported: sysfs path '%s'", syspath);
883         return false;
884     }
885 
886     p += 12 + pcilen;
887     while (true) {
888         driver = get_pci_driver(syspath, p - syspath, errp);
889         if (driver && (g_str_equal(driver, "ata_piix") ||
890                        g_str_equal(driver, "sym53c8xx") ||
891                        g_str_equal(driver, "virtio-pci") ||
892                        g_str_equal(driver, "ahci"))) {
893             break;
894         }
895 
896         g_free(driver);
897         if (sscanf(p, "/%x:%x:%x.%x%n",
898                           pci, pci + 1, pci + 2, pci + 3, &pcilen) == 4) {
899             p += pcilen;
900             continue;
901         }
902 
903         g_debug("unsupported driver or sysfs path '%s'", syspath);
904         return false;
905     }
906 
907     p = strstr(syspath, "/target");
908     if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
909                     tgt, tgt + 1, tgt + 2) == 3) {
910         has_tgt = true;
911     }
912 
913     p = strstr(syspath, "/ata");
914     if (p) {
915         q = p + 4;
916         has_ata = true;
917     } else {
918         p = strstr(syspath, "/host");
919         q = p + 5;
920     }
921     if (p && sscanf(q, "%u", &host) == 1) {
922         has_host = true;
923         nhosts = build_hosts(syspath, p, has_ata, hosts,
924                              ARRAY_SIZE(hosts), errp);
925         if (nhosts < 0) {
926             goto cleanup;
927         }
928     }
929 
930     pciaddr->domain = pci[0];
931     pciaddr->bus = pci[1];
932     pciaddr->slot = pci[2];
933     pciaddr->function = pci[3];
934 
935     if (strcmp(driver, "ata_piix") == 0) {
936         /* a host per ide bus, target*:0:<unit>:0 */
937         if (!has_host || !has_tgt) {
938             g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
939             goto cleanup;
940         }
941         for (i = 0; i < nhosts; i++) {
942             if (host == hosts[i]) {
943                 disk->bus_type = GUEST_DISK_BUS_TYPE_IDE;
944                 disk->bus = i;
945                 disk->unit = tgt[1];
946                 break;
947             }
948         }
949         if (i >= nhosts) {
950             g_debug("no host for '%s' (driver '%s')", syspath, driver);
951             goto cleanup;
952         }
953     } else if (strcmp(driver, "sym53c8xx") == 0) {
954         /* scsi(LSI Logic): target*:0:<unit>:0 */
955         if (!has_tgt) {
956             g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
957             goto cleanup;
958         }
959         disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
960         disk->unit = tgt[1];
961     } else if (strcmp(driver, "virtio-pci") == 0) {
962         if (has_tgt) {
963             /* virtio-scsi: target*:0:0:<unit> */
964             disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
965             disk->unit = tgt[2];
966         } else {
967             /* virtio-blk: 1 disk per 1 device */
968             disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
969         }
970     } else if (strcmp(driver, "ahci") == 0) {
971         /* ahci: 1 host per 1 unit */
972         if (!has_host || !has_tgt) {
973             g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
974             goto cleanup;
975         }
976         for (i = 0; i < nhosts; i++) {
977             if (host == hosts[i]) {
978                 disk->unit = i;
979                 disk->bus_type = GUEST_DISK_BUS_TYPE_SATA;
980                 break;
981             }
982         }
983         if (i >= nhosts) {
984             g_debug("no host for '%s' (driver '%s')", syspath, driver);
985             goto cleanup;
986         }
987     } else {
988         g_debug("unknown driver '%s' (sysfs path '%s')", driver, syspath);
989         goto cleanup;
990     }
991 
992     ret = true;
993 
994 cleanup:
995     g_free(driver);
996     return ret;
997 }
998 
999 /*
1000  * Store disk device info for non-PCI virtio devices (for example s390x
1001  * channel I/O devices). Returns true if information has been stored, or
1002  * false for failure.
1003  */
1004 static bool build_guest_fsinfo_for_nonpci_virtio(char const *syspath,
1005                                                  GuestDiskAddress *disk,
1006                                                  Error **errp)
1007 {
1008     unsigned int tgt[3];
1009     char *p;
1010 
1011     if (!strstr(syspath, "/virtio") || !strstr(syspath, "/block")) {
1012         g_debug("Unsupported virtio device '%s'", syspath);
1013         return false;
1014     }
1015 
1016     p = strstr(syspath, "/target");
1017     if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
1018                     &tgt[0], &tgt[1], &tgt[2]) == 3) {
1019         /* virtio-scsi: target*:0:<target>:<unit> */
1020         disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
1021         disk->bus = tgt[0];
1022         disk->target = tgt[1];
1023         disk->unit = tgt[2];
1024     } else {
1025         /* virtio-blk: 1 disk per 1 device */
1026         disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
1027     }
1028 
1029     return true;
1030 }
1031 
1032 /*
1033  * Store disk device info for CCW devices (s390x channel I/O devices).
1034  * Returns true if information has been stored, or false for failure.
1035  */
1036 static bool build_guest_fsinfo_for_ccw_dev(char const *syspath,
1037                                            GuestDiskAddress *disk,
1038                                            Error **errp)
1039 {
1040     unsigned int cssid, ssid, subchno, devno;
1041     char *p;
1042 
1043     p = strstr(syspath, "/devices/css");
1044     if (!p || sscanf(p + 12, "%*x/%x.%x.%x/%*x.%*x.%x/",
1045                      &cssid, &ssid, &subchno, &devno) < 4) {
1046         g_debug("could not parse ccw device sysfs path: %s", syspath);
1047         return false;
1048     }
1049 
1050     disk->has_ccw_address = true;
1051     disk->ccw_address = g_new0(GuestCCWAddress, 1);
1052     disk->ccw_address->cssid = cssid;
1053     disk->ccw_address->ssid = ssid;
1054     disk->ccw_address->subchno = subchno;
1055     disk->ccw_address->devno = devno;
1056 
1057     if (strstr(p, "/virtio")) {
1058         build_guest_fsinfo_for_nonpci_virtio(syspath, disk, errp);
1059     }
1060 
1061     return true;
1062 }
1063 
1064 /* Store disk device info specified by @sysfs into @fs */
1065 static void build_guest_fsinfo_for_real_device(char const *syspath,
1066                                                GuestFilesystemInfo *fs,
1067                                                Error **errp)
1068 {
1069     GuestDiskAddress *disk;
1070     GuestPCIAddress *pciaddr;
1071     GuestDiskAddressList *list = NULL;
1072     bool has_hwinf;
1073 #ifdef CONFIG_LIBUDEV
1074     struct udev *udev = NULL;
1075     struct udev_device *udevice = NULL;
1076 #endif
1077 
1078     pciaddr = g_new0(GuestPCIAddress, 1);
1079     pciaddr->domain = -1;                       /* -1 means field is invalid */
1080     pciaddr->bus = -1;
1081     pciaddr->slot = -1;
1082     pciaddr->function = -1;
1083 
1084     disk = g_new0(GuestDiskAddress, 1);
1085     disk->pci_controller = pciaddr;
1086     disk->bus_type = GUEST_DISK_BUS_TYPE_UNKNOWN;
1087 
1088     list = g_new0(GuestDiskAddressList, 1);
1089     list->value = disk;
1090 
1091 #ifdef CONFIG_LIBUDEV
1092     udev = udev_new();
1093     udevice = udev_device_new_from_syspath(udev, syspath);
1094     if (udev == NULL || udevice == NULL) {
1095         g_debug("failed to query udev");
1096     } else {
1097         const char *devnode, *serial;
1098         devnode = udev_device_get_devnode(udevice);
1099         if (devnode != NULL) {
1100             disk->dev = g_strdup(devnode);
1101             disk->has_dev = true;
1102         }
1103         serial = udev_device_get_property_value(udevice, "ID_SERIAL");
1104         if (serial != NULL && *serial != 0) {
1105             disk->serial = g_strdup(serial);
1106             disk->has_serial = true;
1107         }
1108     }
1109 
1110     udev_unref(udev);
1111     udev_device_unref(udevice);
1112 #endif
1113 
1114     if (strstr(syspath, "/devices/pci")) {
1115         has_hwinf = build_guest_fsinfo_for_pci_dev(syspath, disk, errp);
1116     } else if (strstr(syspath, "/devices/css")) {
1117         has_hwinf = build_guest_fsinfo_for_ccw_dev(syspath, disk, errp);
1118     } else if (strstr(syspath, "/virtio")) {
1119         has_hwinf = build_guest_fsinfo_for_nonpci_virtio(syspath, disk, errp);
1120     } else {
1121         g_debug("Unsupported device type for '%s'", syspath);
1122         has_hwinf = false;
1123     }
1124 
1125     if (has_hwinf || disk->has_dev || disk->has_serial) {
1126         list->next = fs->disk;
1127         fs->disk = list;
1128     } else {
1129         qapi_free_GuestDiskAddressList(list);
1130     }
1131 }
1132 
1133 static void build_guest_fsinfo_for_device(char const *devpath,
1134                                           GuestFilesystemInfo *fs,
1135                                           Error **errp);
1136 
1137 /* Store a list of slave devices of virtual volume specified by @syspath into
1138  * @fs */
1139 static void build_guest_fsinfo_for_virtual_device(char const *syspath,
1140                                                   GuestFilesystemInfo *fs,
1141                                                   Error **errp)
1142 {
1143     Error *err = NULL;
1144     DIR *dir;
1145     char *dirpath;
1146     struct dirent *entry;
1147 
1148     dirpath = g_strdup_printf("%s/slaves", syspath);
1149     dir = opendir(dirpath);
1150     if (!dir) {
1151         if (errno != ENOENT) {
1152             error_setg_errno(errp, errno, "opendir(\"%s\")", dirpath);
1153         }
1154         g_free(dirpath);
1155         return;
1156     }
1157 
1158     for (;;) {
1159         errno = 0;
1160         entry = readdir(dir);
1161         if (entry == NULL) {
1162             if (errno) {
1163                 error_setg_errno(errp, errno, "readdir(\"%s\")", dirpath);
1164             }
1165             break;
1166         }
1167 
1168         if (entry->d_type == DT_LNK) {
1169             char *path;
1170 
1171             g_debug(" slave device '%s'", entry->d_name);
1172             path = g_strdup_printf("%s/slaves/%s", syspath, entry->d_name);
1173             build_guest_fsinfo_for_device(path, fs, &err);
1174             g_free(path);
1175 
1176             if (err) {
1177                 error_propagate(errp, err);
1178                 break;
1179             }
1180         }
1181     }
1182 
1183     g_free(dirpath);
1184     closedir(dir);
1185 }
1186 
1187 static bool is_disk_virtual(const char *devpath, Error **errp)
1188 {
1189     g_autofree char *syspath = realpath(devpath, NULL);
1190 
1191     if (!syspath) {
1192         error_setg_errno(errp, errno, "realpath(\"%s\")", devpath);
1193         return false;
1194     }
1195     return strstr(syspath, "/devices/virtual/block/") != NULL;
1196 }
1197 
1198 /* Dispatch to functions for virtual/real device */
1199 static void build_guest_fsinfo_for_device(char const *devpath,
1200                                           GuestFilesystemInfo *fs,
1201                                           Error **errp)
1202 {
1203     ERRP_GUARD();
1204     g_autofree char *syspath = NULL;
1205     bool is_virtual = false;
1206 
1207     syspath = realpath(devpath, NULL);
1208     if (!syspath) {
1209         error_setg_errno(errp, errno, "realpath(\"%s\")", devpath);
1210         return;
1211     }
1212 
1213     if (!fs->name) {
1214         fs->name = g_path_get_basename(syspath);
1215     }
1216 
1217     g_debug("  parse sysfs path '%s'", syspath);
1218     is_virtual = is_disk_virtual(syspath, errp);
1219     if (*errp != NULL) {
1220         return;
1221     }
1222     if (is_virtual) {
1223         build_guest_fsinfo_for_virtual_device(syspath, fs, errp);
1224     } else {
1225         build_guest_fsinfo_for_real_device(syspath, fs, errp);
1226     }
1227 }
1228 
1229 #ifdef CONFIG_LIBUDEV
1230 
1231 /*
1232  * Wrapper around build_guest_fsinfo_for_device() for getting just
1233  * the disk address.
1234  */
1235 static GuestDiskAddress *get_disk_address(const char *syspath, Error **errp)
1236 {
1237     g_autoptr(GuestFilesystemInfo) fs = NULL;
1238 
1239     fs = g_new0(GuestFilesystemInfo, 1);
1240     build_guest_fsinfo_for_device(syspath, fs, errp);
1241     if (fs->disk != NULL) {
1242         return g_steal_pointer(&fs->disk->value);
1243     }
1244     return NULL;
1245 }
1246 
1247 static char *get_alias_for_syspath(const char *syspath)
1248 {
1249     struct udev *udev = NULL;
1250     struct udev_device *udevice = NULL;
1251     char *ret = NULL;
1252 
1253     udev = udev_new();
1254     if (udev == NULL) {
1255         g_debug("failed to query udev");
1256         goto out;
1257     }
1258     udevice = udev_device_new_from_syspath(udev, syspath);
1259     if (udevice == NULL) {
1260         g_debug("failed to query udev for path: %s", syspath);
1261         goto out;
1262     } else {
1263         const char *alias = udev_device_get_property_value(
1264             udevice, "DM_NAME");
1265         /*
1266          * NULL means there was an error and empty string means there is no
1267          * alias. In case of no alias we return NULL instead of empty string.
1268          */
1269         if (alias == NULL) {
1270             g_debug("failed to query udev for device alias for: %s",
1271                 syspath);
1272         } else if (*alias != 0) {
1273             ret = g_strdup(alias);
1274         }
1275     }
1276 
1277 out:
1278     udev_unref(udev);
1279     udev_device_unref(udevice);
1280     return ret;
1281 }
1282 
1283 static char *get_device_for_syspath(const char *syspath)
1284 {
1285     struct udev *udev = NULL;
1286     struct udev_device *udevice = NULL;
1287     char *ret = NULL;
1288 
1289     udev = udev_new();
1290     if (udev == NULL) {
1291         g_debug("failed to query udev");
1292         goto out;
1293     }
1294     udevice = udev_device_new_from_syspath(udev, syspath);
1295     if (udevice == NULL) {
1296         g_debug("failed to query udev for path: %s", syspath);
1297         goto out;
1298     } else {
1299         ret = g_strdup(udev_device_get_devnode(udevice));
1300     }
1301 
1302 out:
1303     udev_unref(udev);
1304     udev_device_unref(udevice);
1305     return ret;
1306 }
1307 
1308 static void get_disk_deps(const char *disk_dir, GuestDiskInfo *disk)
1309 {
1310     g_autofree char *deps_dir = NULL;
1311     const gchar *dep;
1312     GDir *dp_deps = NULL;
1313 
1314     /* List dependent disks */
1315     deps_dir = g_strdup_printf("%s/slaves", disk_dir);
1316     g_debug("  listing entries in: %s", deps_dir);
1317     dp_deps = g_dir_open(deps_dir, 0, NULL);
1318     if (dp_deps == NULL) {
1319         g_debug("failed to list entries in %s", deps_dir);
1320         return;
1321     }
1322     disk->has_dependencies = true;
1323     while ((dep = g_dir_read_name(dp_deps)) != NULL) {
1324         g_autofree char *dep_dir = NULL;
1325         strList *dep_item = NULL;
1326         char *dev_name;
1327 
1328         /* Add dependent disks */
1329         dep_dir = g_strdup_printf("%s/%s", deps_dir, dep);
1330         dev_name = get_device_for_syspath(dep_dir);
1331         if (dev_name != NULL) {
1332             g_debug("  adding dependent device: %s", dev_name);
1333             dep_item = g_new0(strList, 1);
1334             dep_item->value = dev_name;
1335             dep_item->next = disk->dependencies;
1336             disk->dependencies = dep_item;
1337         }
1338     }
1339     g_dir_close(dp_deps);
1340 }
1341 
1342 /*
1343  * Detect partitions subdirectory, name is "<disk_name><number>" or
1344  * "<disk_name>p<number>"
1345  *
1346  * @disk_name -- last component of /sys path (e.g. sda)
1347  * @disk_dir -- sys path of the disk (e.g. /sys/block/sda)
1348  * @disk_dev -- device node of the disk (e.g. /dev/sda)
1349  */
1350 static GuestDiskInfoList *get_disk_partitions(
1351     GuestDiskInfoList *list,
1352     const char *disk_name, const char *disk_dir,
1353     const char *disk_dev)
1354 {
1355     GuestDiskInfoList *item, *ret = list;
1356     struct dirent *de_disk;
1357     DIR *dp_disk = NULL;
1358     size_t len = strlen(disk_name);
1359 
1360     dp_disk = opendir(disk_dir);
1361     while ((de_disk = readdir(dp_disk)) != NULL) {
1362         g_autofree char *partition_dir = NULL;
1363         char *dev_name;
1364         GuestDiskInfo *partition;
1365 
1366         if (!(de_disk->d_type & DT_DIR)) {
1367             continue;
1368         }
1369 
1370         if (!(strncmp(disk_name, de_disk->d_name, len) == 0 &&
1371             ((*(de_disk->d_name + len) == 'p' &&
1372             isdigit(*(de_disk->d_name + len + 1))) ||
1373                 isdigit(*(de_disk->d_name + len))))) {
1374             continue;
1375         }
1376 
1377         partition_dir = g_strdup_printf("%s/%s",
1378             disk_dir, de_disk->d_name);
1379         dev_name = get_device_for_syspath(partition_dir);
1380         if (dev_name == NULL) {
1381             g_debug("Failed to get device name for syspath: %s",
1382                 disk_dir);
1383             continue;
1384         }
1385         partition = g_new0(GuestDiskInfo, 1);
1386         partition->name = dev_name;
1387         partition->partition = true;
1388         /* Add parent disk as dependent for easier tracking of hierarchy */
1389         partition->dependencies = g_new0(strList, 1);
1390         partition->dependencies->value = g_strdup(disk_dev);
1391         partition->has_dependencies = true;
1392 
1393         item = g_new0(GuestDiskInfoList, 1);
1394         item->value = partition;
1395         item->next = ret;
1396         ret = item;
1397 
1398     }
1399     closedir(dp_disk);
1400 
1401     return ret;
1402 }
1403 
1404 GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
1405 {
1406     GuestDiskInfoList *item, *ret = NULL;
1407     GuestDiskInfo *disk;
1408     DIR *dp = NULL;
1409     struct dirent *de = NULL;
1410 
1411     g_debug("listing /sys/block directory");
1412     dp = opendir("/sys/block");
1413     if (dp == NULL) {
1414         error_setg_errno(errp, errno, "Can't open directory \"/sys/block\"");
1415         return NULL;
1416     }
1417     while ((de = readdir(dp)) != NULL) {
1418         g_autofree char *disk_dir = NULL, *line = NULL,
1419             *size_path = NULL;
1420         char *dev_name;
1421         Error *local_err = NULL;
1422         if (de->d_type != DT_LNK) {
1423             g_debug("  skipping entry: %s", de->d_name);
1424             continue;
1425         }
1426 
1427         /* Check size and skip zero-sized disks */
1428         g_debug("  checking disk size");
1429         size_path = g_strdup_printf("/sys/block/%s/size", de->d_name);
1430         if (!g_file_get_contents(size_path, &line, NULL, NULL)) {
1431             g_debug("  failed to read disk size");
1432             continue;
1433         }
1434         if (g_strcmp0(line, "0\n") == 0) {
1435             g_debug("  skipping zero-sized disk");
1436             continue;
1437         }
1438 
1439         g_debug("  adding %s", de->d_name);
1440         disk_dir = g_strdup_printf("/sys/block/%s", de->d_name);
1441         dev_name = get_device_for_syspath(disk_dir);
1442         if (dev_name == NULL) {
1443             g_debug("Failed to get device name for syspath: %s",
1444                 disk_dir);
1445             continue;
1446         }
1447         disk = g_new0(GuestDiskInfo, 1);
1448         disk->name = dev_name;
1449         disk->partition = false;
1450         disk->alias = get_alias_for_syspath(disk_dir);
1451         disk->has_alias = (disk->alias != NULL);
1452         item = g_new0(GuestDiskInfoList, 1);
1453         item->value = disk;
1454         item->next = ret;
1455         ret = item;
1456 
1457         /* Get address for non-virtual devices */
1458         bool is_virtual = is_disk_virtual(disk_dir, &local_err);
1459         if (local_err != NULL) {
1460             g_debug("  failed to check disk path, ignoring error: %s",
1461                 error_get_pretty(local_err));
1462             error_free(local_err);
1463             local_err = NULL;
1464             /* Don't try to get the address */
1465             is_virtual = true;
1466         }
1467         if (!is_virtual) {
1468             disk->address = get_disk_address(disk_dir, &local_err);
1469             if (local_err != NULL) {
1470                 g_debug("  failed to get device info, ignoring error: %s",
1471                     error_get_pretty(local_err));
1472                 error_free(local_err);
1473                 local_err = NULL;
1474             } else if (disk->address != NULL) {
1475                 disk->has_address = true;
1476             }
1477         }
1478 
1479         get_disk_deps(disk_dir, disk);
1480         ret = get_disk_partitions(ret, de->d_name, disk_dir, dev_name);
1481     }
1482 
1483     closedir(dp);
1484 
1485     return ret;
1486 }
1487 
1488 #else
1489 
1490 GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
1491 {
1492     error_setg(errp, QERR_UNSUPPORTED);
1493     return NULL;
1494 }
1495 
1496 #endif
1497 
1498 /* Return a list of the disk device(s)' info which @mount lies on */
1499 static GuestFilesystemInfo *build_guest_fsinfo(struct FsMount *mount,
1500                                                Error **errp)
1501 {
1502     GuestFilesystemInfo *fs = g_malloc0(sizeof(*fs));
1503     struct statvfs buf;
1504     unsigned long used, nonroot_total, fr_size;
1505     char *devpath = g_strdup_printf("/sys/dev/block/%u:%u",
1506                                     mount->devmajor, mount->devminor);
1507 
1508     fs->mountpoint = g_strdup(mount->dirname);
1509     fs->type = g_strdup(mount->devtype);
1510     build_guest_fsinfo_for_device(devpath, fs, errp);
1511 
1512     if (statvfs(fs->mountpoint, &buf) == 0) {
1513         fr_size = buf.f_frsize;
1514         used = buf.f_blocks - buf.f_bfree;
1515         nonroot_total = used + buf.f_bavail;
1516         fs->used_bytes = used * fr_size;
1517         fs->total_bytes = nonroot_total * fr_size;
1518 
1519         fs->has_total_bytes = true;
1520         fs->has_used_bytes = true;
1521     }
1522 
1523     g_free(devpath);
1524 
1525     return fs;
1526 }
1527 
1528 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
1529 {
1530     FsMountList mounts;
1531     struct FsMount *mount;
1532     GuestFilesystemInfoList *new, *ret = NULL;
1533     Error *local_err = NULL;
1534 
1535     QTAILQ_INIT(&mounts);
1536     build_fs_mount_list(&mounts, &local_err);
1537     if (local_err) {
1538         error_propagate(errp, local_err);
1539         return NULL;
1540     }
1541 
1542     QTAILQ_FOREACH(mount, &mounts, next) {
1543         g_debug("Building guest fsinfo for '%s'", mount->dirname);
1544 
1545         new = g_malloc0(sizeof(*ret));
1546         new->value = build_guest_fsinfo(mount, &local_err);
1547         new->next = ret;
1548         ret = new;
1549         if (local_err) {
1550             error_propagate(errp, local_err);
1551             qapi_free_GuestFilesystemInfoList(ret);
1552             ret = NULL;
1553             break;
1554         }
1555     }
1556 
1557     free_fs_mount_list(&mounts);
1558     return ret;
1559 }
1560 
1561 
1562 typedef enum {
1563     FSFREEZE_HOOK_THAW = 0,
1564     FSFREEZE_HOOK_FREEZE,
1565 } FsfreezeHookArg;
1566 
1567 static const char *fsfreeze_hook_arg_string[] = {
1568     "thaw",
1569     "freeze",
1570 };
1571 
1572 static void execute_fsfreeze_hook(FsfreezeHookArg arg, Error **errp)
1573 {
1574     int status;
1575     pid_t pid;
1576     const char *hook;
1577     const char *arg_str = fsfreeze_hook_arg_string[arg];
1578     Error *local_err = NULL;
1579 
1580     hook = ga_fsfreeze_hook(ga_state);
1581     if (!hook) {
1582         return;
1583     }
1584     if (access(hook, X_OK) != 0) {
1585         error_setg_errno(errp, errno, "can't access fsfreeze hook '%s'", hook);
1586         return;
1587     }
1588 
1589     slog("executing fsfreeze hook with arg '%s'", arg_str);
1590     pid = fork();
1591     if (pid == 0) {
1592         setsid();
1593         reopen_fd_to_null(0);
1594         reopen_fd_to_null(1);
1595         reopen_fd_to_null(2);
1596 
1597         execle(hook, hook, arg_str, NULL, environ);
1598         _exit(EXIT_FAILURE);
1599     } else if (pid < 0) {
1600         error_setg_errno(errp, errno, "failed to create child process");
1601         return;
1602     }
1603 
1604     ga_wait_child(pid, &status, &local_err);
1605     if (local_err) {
1606         error_propagate(errp, local_err);
1607         return;
1608     }
1609 
1610     if (!WIFEXITED(status)) {
1611         error_setg(errp, "fsfreeze hook has terminated abnormally");
1612         return;
1613     }
1614 
1615     status = WEXITSTATUS(status);
1616     if (status) {
1617         error_setg(errp, "fsfreeze hook has failed with status %d", status);
1618         return;
1619     }
1620 }
1621 
1622 /*
1623  * Return status of freeze/thaw
1624  */
1625 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
1626 {
1627     if (ga_is_frozen(ga_state)) {
1628         return GUEST_FSFREEZE_STATUS_FROZEN;
1629     }
1630 
1631     return GUEST_FSFREEZE_STATUS_THAWED;
1632 }
1633 
1634 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
1635 {
1636     return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
1637 }
1638 
1639 /*
1640  * Walk list of mounted file systems in the guest, and freeze the ones which
1641  * are real local file systems.
1642  */
1643 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
1644                                        strList *mountpoints,
1645                                        Error **errp)
1646 {
1647     int ret = 0, i = 0;
1648     strList *list;
1649     FsMountList mounts;
1650     struct FsMount *mount;
1651     Error *local_err = NULL;
1652     int fd;
1653 
1654     slog("guest-fsfreeze called");
1655 
1656     execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE, &local_err);
1657     if (local_err) {
1658         error_propagate(errp, local_err);
1659         return -1;
1660     }
1661 
1662     QTAILQ_INIT(&mounts);
1663     build_fs_mount_list(&mounts, &local_err);
1664     if (local_err) {
1665         error_propagate(errp, local_err);
1666         return -1;
1667     }
1668 
1669     /* cannot risk guest agent blocking itself on a write in this state */
1670     ga_set_frozen(ga_state);
1671 
1672     QTAILQ_FOREACH_REVERSE(mount, &mounts, next) {
1673         /* To issue fsfreeze in the reverse order of mounts, check if the
1674          * mount is listed in the list here */
1675         if (has_mountpoints) {
1676             for (list = mountpoints; list; list = list->next) {
1677                 if (strcmp(list->value, mount->dirname) == 0) {
1678                     break;
1679                 }
1680             }
1681             if (!list) {
1682                 continue;
1683             }
1684         }
1685 
1686         fd = qemu_open_old(mount->dirname, O_RDONLY);
1687         if (fd == -1) {
1688             error_setg_errno(errp, errno, "failed to open %s", mount->dirname);
1689             goto error;
1690         }
1691 
1692         /* we try to cull filesystems we know won't work in advance, but other
1693          * filesystems may not implement fsfreeze for less obvious reasons.
1694          * these will report EOPNOTSUPP. we simply ignore these when tallying
1695          * the number of frozen filesystems.
1696          * if a filesystem is mounted more than once (aka bind mount) a
1697          * consecutive attempt to freeze an already frozen filesystem will
1698          * return EBUSY.
1699          *
1700          * any other error means a failure to freeze a filesystem we
1701          * expect to be freezable, so return an error in those cases
1702          * and return system to thawed state.
1703          */
1704         ret = ioctl(fd, FIFREEZE);
1705         if (ret == -1) {
1706             if (errno != EOPNOTSUPP && errno != EBUSY) {
1707                 error_setg_errno(errp, errno, "failed to freeze %s",
1708                                  mount->dirname);
1709                 close(fd);
1710                 goto error;
1711             }
1712         } else {
1713             i++;
1714         }
1715         close(fd);
1716     }
1717 
1718     free_fs_mount_list(&mounts);
1719     /* We may not issue any FIFREEZE here.
1720      * Just unset ga_state here and ready for the next call.
1721      */
1722     if (i == 0) {
1723         ga_unset_frozen(ga_state);
1724     }
1725     return i;
1726 
1727 error:
1728     free_fs_mount_list(&mounts);
1729     qmp_guest_fsfreeze_thaw(NULL);
1730     return 0;
1731 }
1732 
1733 /*
1734  * Walk list of frozen file systems in the guest, and thaw them.
1735  */
1736 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
1737 {
1738     int ret;
1739     FsMountList mounts;
1740     FsMount *mount;
1741     int fd, i = 0, logged;
1742     Error *local_err = NULL;
1743 
1744     QTAILQ_INIT(&mounts);
1745     build_fs_mount_list(&mounts, &local_err);
1746     if (local_err) {
1747         error_propagate(errp, local_err);
1748         return 0;
1749     }
1750 
1751     QTAILQ_FOREACH(mount, &mounts, next) {
1752         logged = false;
1753         fd = qemu_open_old(mount->dirname, O_RDONLY);
1754         if (fd == -1) {
1755             continue;
1756         }
1757         /* we have no way of knowing whether a filesystem was actually unfrozen
1758          * as a result of a successful call to FITHAW, only that if an error
1759          * was returned the filesystem was *not* unfrozen by that particular
1760          * call.
1761          *
1762          * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1763          * to unfreeze, continuing issuing FITHAW until an error is returned,
1764          * in which case either the filesystem is in an unfreezable state, or,
1765          * more likely, it was thawed previously (and remains so afterward).
1766          *
1767          * also, since the most recent successful call is the one that did
1768          * the actual unfreeze, we can use this to provide an accurate count
1769          * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1770          * may * be useful for determining whether a filesystem was unfrozen
1771          * during the freeze/thaw phase by a process other than qemu-ga.
1772          */
1773         do {
1774             ret = ioctl(fd, FITHAW);
1775             if (ret == 0 && !logged) {
1776                 i++;
1777                 logged = true;
1778             }
1779         } while (ret == 0);
1780         close(fd);
1781     }
1782 
1783     ga_unset_frozen(ga_state);
1784     free_fs_mount_list(&mounts);
1785 
1786     execute_fsfreeze_hook(FSFREEZE_HOOK_THAW, errp);
1787 
1788     return i;
1789 }
1790 
1791 static void guest_fsfreeze_cleanup(void)
1792 {
1793     Error *err = NULL;
1794 
1795     if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
1796         qmp_guest_fsfreeze_thaw(&err);
1797         if (err) {
1798             slog("failed to clean up frozen filesystems: %s",
1799                  error_get_pretty(err));
1800             error_free(err);
1801         }
1802     }
1803 }
1804 #endif /* CONFIG_FSFREEZE */
1805 
1806 #if defined(CONFIG_FSTRIM)
1807 /*
1808  * Walk list of mounted file systems in the guest, and trim them.
1809  */
1810 GuestFilesystemTrimResponse *
1811 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
1812 {
1813     GuestFilesystemTrimResponse *response;
1814     GuestFilesystemTrimResultList *list;
1815     GuestFilesystemTrimResult *result;
1816     int ret = 0;
1817     FsMountList mounts;
1818     struct FsMount *mount;
1819     int fd;
1820     Error *local_err = NULL;
1821     struct fstrim_range r;
1822 
1823     slog("guest-fstrim called");
1824 
1825     QTAILQ_INIT(&mounts);
1826     build_fs_mount_list(&mounts, &local_err);
1827     if (local_err) {
1828         error_propagate(errp, local_err);
1829         return NULL;
1830     }
1831 
1832     response = g_malloc0(sizeof(*response));
1833 
1834     QTAILQ_FOREACH(mount, &mounts, next) {
1835         result = g_malloc0(sizeof(*result));
1836         result->path = g_strdup(mount->dirname);
1837 
1838         list = g_malloc0(sizeof(*list));
1839         list->value = result;
1840         list->next = response->paths;
1841         response->paths = list;
1842 
1843         fd = qemu_open_old(mount->dirname, O_RDONLY);
1844         if (fd == -1) {
1845             result->error = g_strdup_printf("failed to open: %s",
1846                                             strerror(errno));
1847             result->has_error = true;
1848             continue;
1849         }
1850 
1851         /* We try to cull filesystems we know won't work in advance, but other
1852          * filesystems may not implement fstrim for less obvious reasons.
1853          * These will report EOPNOTSUPP; while in some other cases ENOTTY
1854          * will be reported (e.g. CD-ROMs).
1855          * Any other error means an unexpected error.
1856          */
1857         r.start = 0;
1858         r.len = -1;
1859         r.minlen = has_minimum ? minimum : 0;
1860         ret = ioctl(fd, FITRIM, &r);
1861         if (ret == -1) {
1862             result->has_error = true;
1863             if (errno == ENOTTY || errno == EOPNOTSUPP) {
1864                 result->error = g_strdup("trim not supported");
1865             } else {
1866                 result->error = g_strdup_printf("failed to trim: %s",
1867                                                 strerror(errno));
1868             }
1869             close(fd);
1870             continue;
1871         }
1872 
1873         result->has_minimum = true;
1874         result->minimum = r.minlen;
1875         result->has_trimmed = true;
1876         result->trimmed = r.len;
1877         close(fd);
1878     }
1879 
1880     free_fs_mount_list(&mounts);
1881     return response;
1882 }
1883 #endif /* CONFIG_FSTRIM */
1884 
1885 
1886 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1887 #define SUSPEND_SUPPORTED 0
1888 #define SUSPEND_NOT_SUPPORTED 1
1889 
1890 typedef enum {
1891     SUSPEND_MODE_DISK = 0,
1892     SUSPEND_MODE_RAM = 1,
1893     SUSPEND_MODE_HYBRID = 2,
1894 } SuspendMode;
1895 
1896 /*
1897  * Executes a command in a child process using g_spawn_sync,
1898  * returning an int >= 0 representing the exit status of the
1899  * process.
1900  *
1901  * If the program wasn't found in path, returns -1.
1902  *
1903  * If a problem happened when creating the child process,
1904  * returns -1 and errp is set.
1905  */
1906 static int run_process_child(const char *command[], Error **errp)
1907 {
1908     int exit_status, spawn_flag;
1909     GError *g_err = NULL;
1910     bool success;
1911 
1912     spawn_flag = G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL |
1913                  G_SPAWN_STDERR_TO_DEV_NULL;
1914 
1915     success =  g_spawn_sync(NULL, (char **)command, environ, spawn_flag,
1916                             NULL, NULL, NULL, NULL,
1917                             &exit_status, &g_err);
1918 
1919     if (success) {
1920         return WEXITSTATUS(exit_status);
1921     }
1922 
1923     if (g_err && (g_err->code != G_SPAWN_ERROR_NOENT)) {
1924         error_setg(errp, "failed to create child process, error '%s'",
1925                    g_err->message);
1926     }
1927 
1928     g_error_free(g_err);
1929     return -1;
1930 }
1931 
1932 static bool systemd_supports_mode(SuspendMode mode, Error **errp)
1933 {
1934     const char *systemctl_args[3] = {"systemd-hibernate", "systemd-suspend",
1935                                      "systemd-hybrid-sleep"};
1936     const char *cmd[4] = {"systemctl", "status", systemctl_args[mode], NULL};
1937     int status;
1938 
1939     status = run_process_child(cmd, errp);
1940 
1941     /*
1942      * systemctl status uses LSB return codes so we can expect
1943      * status > 0 and be ok. To assert if the guest has support
1944      * for the selected suspend mode, status should be < 4. 4 is
1945      * the code for unknown service status, the return value when
1946      * the service does not exist. A common value is status = 3
1947      * (program is not running).
1948      */
1949     if (status > 0 && status < 4) {
1950         return true;
1951     }
1952 
1953     return false;
1954 }
1955 
1956 static void systemd_suspend(SuspendMode mode, Error **errp)
1957 {
1958     Error *local_err = NULL;
1959     const char *systemctl_args[3] = {"hibernate", "suspend", "hybrid-sleep"};
1960     const char *cmd[3] = {"systemctl", systemctl_args[mode], NULL};
1961     int status;
1962 
1963     status = run_process_child(cmd, &local_err);
1964 
1965     if (status == 0) {
1966         return;
1967     }
1968 
1969     if ((status == -1) && !local_err) {
1970         error_setg(errp, "the helper program 'systemctl %s' was not found",
1971                    systemctl_args[mode]);
1972         return;
1973     }
1974 
1975     if (local_err) {
1976         error_propagate(errp, local_err);
1977     } else {
1978         error_setg(errp, "the helper program 'systemctl %s' returned an "
1979                    "unexpected exit status code (%d)",
1980                    systemctl_args[mode], status);
1981     }
1982 }
1983 
1984 static bool pmutils_supports_mode(SuspendMode mode, Error **errp)
1985 {
1986     Error *local_err = NULL;
1987     const char *pmutils_args[3] = {"--hibernate", "--suspend",
1988                                    "--suspend-hybrid"};
1989     const char *cmd[3] = {"pm-is-supported", pmutils_args[mode], NULL};
1990     int status;
1991 
1992     status = run_process_child(cmd, &local_err);
1993 
1994     if (status == SUSPEND_SUPPORTED) {
1995         return true;
1996     }
1997 
1998     if ((status == -1) && !local_err) {
1999         return false;
2000     }
2001 
2002     if (local_err) {
2003         error_propagate(errp, local_err);
2004     } else {
2005         error_setg(errp,
2006                    "the helper program '%s' returned an unexpected exit"
2007                    " status code (%d)", "pm-is-supported", status);
2008     }
2009 
2010     return false;
2011 }
2012 
2013 static void pmutils_suspend(SuspendMode mode, Error **errp)
2014 {
2015     Error *local_err = NULL;
2016     const char *pmutils_binaries[3] = {"pm-hibernate", "pm-suspend",
2017                                        "pm-suspend-hybrid"};
2018     const char *cmd[2] = {pmutils_binaries[mode], NULL};
2019     int status;
2020 
2021     status = run_process_child(cmd, &local_err);
2022 
2023     if (status == 0) {
2024         return;
2025     }
2026 
2027     if ((status == -1) && !local_err) {
2028         error_setg(errp, "the helper program '%s' was not found",
2029                    pmutils_binaries[mode]);
2030         return;
2031     }
2032 
2033     if (local_err) {
2034         error_propagate(errp, local_err);
2035     } else {
2036         error_setg(errp,
2037                    "the helper program '%s' returned an unexpected exit"
2038                    " status code (%d)", pmutils_binaries[mode], status);
2039     }
2040 }
2041 
2042 static bool linux_sys_state_supports_mode(SuspendMode mode, Error **errp)
2043 {
2044     const char *sysfile_strs[3] = {"disk", "mem", NULL};
2045     const char *sysfile_str = sysfile_strs[mode];
2046     char buf[32]; /* hopefully big enough */
2047     int fd;
2048     ssize_t ret;
2049 
2050     if (!sysfile_str) {
2051         error_setg(errp, "unknown guest suspend mode");
2052         return false;
2053     }
2054 
2055     fd = open(LINUX_SYS_STATE_FILE, O_RDONLY);
2056     if (fd < 0) {
2057         return false;
2058     }
2059 
2060     ret = read(fd, buf, sizeof(buf) - 1);
2061     close(fd);
2062     if (ret <= 0) {
2063         return false;
2064     }
2065     buf[ret] = '\0';
2066 
2067     if (strstr(buf, sysfile_str)) {
2068         return true;
2069     }
2070     return false;
2071 }
2072 
2073 static void linux_sys_state_suspend(SuspendMode mode, Error **errp)
2074 {
2075     Error *local_err = NULL;
2076     const char *sysfile_strs[3] = {"disk", "mem", NULL};
2077     const char *sysfile_str = sysfile_strs[mode];
2078     pid_t pid;
2079     int status;
2080 
2081     if (!sysfile_str) {
2082         error_setg(errp, "unknown guest suspend mode");
2083         return;
2084     }
2085 
2086     pid = fork();
2087     if (!pid) {
2088         /* child */
2089         int fd;
2090 
2091         setsid();
2092         reopen_fd_to_null(0);
2093         reopen_fd_to_null(1);
2094         reopen_fd_to_null(2);
2095 
2096         fd = open(LINUX_SYS_STATE_FILE, O_WRONLY);
2097         if (fd < 0) {
2098             _exit(EXIT_FAILURE);
2099         }
2100 
2101         if (write(fd, sysfile_str, strlen(sysfile_str)) < 0) {
2102             _exit(EXIT_FAILURE);
2103         }
2104 
2105         _exit(EXIT_SUCCESS);
2106     } else if (pid < 0) {
2107         error_setg_errno(errp, errno, "failed to create child process");
2108         return;
2109     }
2110 
2111     ga_wait_child(pid, &status, &local_err);
2112     if (local_err) {
2113         error_propagate(errp, local_err);
2114         return;
2115     }
2116 
2117     if (WEXITSTATUS(status)) {
2118         error_setg(errp, "child process has failed to suspend");
2119     }
2120 
2121 }
2122 
2123 static void guest_suspend(SuspendMode mode, Error **errp)
2124 {
2125     Error *local_err = NULL;
2126     bool mode_supported = false;
2127 
2128     if (systemd_supports_mode(mode, &local_err)) {
2129         mode_supported = true;
2130         systemd_suspend(mode, &local_err);
2131     }
2132 
2133     if (!local_err) {
2134         return;
2135     }
2136 
2137     error_free(local_err);
2138     local_err = NULL;
2139 
2140     if (pmutils_supports_mode(mode, &local_err)) {
2141         mode_supported = true;
2142         pmutils_suspend(mode, &local_err);
2143     }
2144 
2145     if (!local_err) {
2146         return;
2147     }
2148 
2149     error_free(local_err);
2150     local_err = NULL;
2151 
2152     if (linux_sys_state_supports_mode(mode, &local_err)) {
2153         mode_supported = true;
2154         linux_sys_state_suspend(mode, &local_err);
2155     }
2156 
2157     if (!mode_supported) {
2158         error_free(local_err);
2159         error_setg(errp,
2160                    "the requested suspend mode is not supported by the guest");
2161     } else {
2162         error_propagate(errp, local_err);
2163     }
2164 }
2165 
2166 void qmp_guest_suspend_disk(Error **errp)
2167 {
2168     guest_suspend(SUSPEND_MODE_DISK, errp);
2169 }
2170 
2171 void qmp_guest_suspend_ram(Error **errp)
2172 {
2173     guest_suspend(SUSPEND_MODE_RAM, errp);
2174 }
2175 
2176 void qmp_guest_suspend_hybrid(Error **errp)
2177 {
2178     guest_suspend(SUSPEND_MODE_HYBRID, errp);
2179 }
2180 
2181 static GuestNetworkInterfaceList *
2182 guest_find_interface(GuestNetworkInterfaceList *head,
2183                      const char *name)
2184 {
2185     for (; head; head = head->next) {
2186         if (strcmp(head->value->name, name) == 0) {
2187             break;
2188         }
2189     }
2190 
2191     return head;
2192 }
2193 
2194 static int guest_get_network_stats(const char *name,
2195                        GuestNetworkInterfaceStat *stats)
2196 {
2197     int name_len;
2198     char const *devinfo = "/proc/net/dev";
2199     FILE *fp;
2200     char *line = NULL, *colon;
2201     size_t n = 0;
2202     fp = fopen(devinfo, "r");
2203     if (!fp) {
2204         return -1;
2205     }
2206     name_len = strlen(name);
2207     while (getline(&line, &n, fp) != -1) {
2208         long long dummy;
2209         long long rx_bytes;
2210         long long rx_packets;
2211         long long rx_errs;
2212         long long rx_dropped;
2213         long long tx_bytes;
2214         long long tx_packets;
2215         long long tx_errs;
2216         long long tx_dropped;
2217         char *trim_line;
2218         trim_line = g_strchug(line);
2219         if (trim_line[0] == '\0') {
2220             continue;
2221         }
2222         colon = strchr(trim_line, ':');
2223         if (!colon) {
2224             continue;
2225         }
2226         if (colon - name_len  == trim_line &&
2227            strncmp(trim_line, name, name_len) == 0) {
2228             if (sscanf(colon + 1,
2229                 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
2230                   &rx_bytes, &rx_packets, &rx_errs, &rx_dropped,
2231                   &dummy, &dummy, &dummy, &dummy,
2232                   &tx_bytes, &tx_packets, &tx_errs, &tx_dropped,
2233                   &dummy, &dummy, &dummy, &dummy) != 16) {
2234                 continue;
2235             }
2236             stats->rx_bytes = rx_bytes;
2237             stats->rx_packets = rx_packets;
2238             stats->rx_errs = rx_errs;
2239             stats->rx_dropped = rx_dropped;
2240             stats->tx_bytes = tx_bytes;
2241             stats->tx_packets = tx_packets;
2242             stats->tx_errs = tx_errs;
2243             stats->tx_dropped = tx_dropped;
2244             fclose(fp);
2245             g_free(line);
2246             return 0;
2247         }
2248     }
2249     fclose(fp);
2250     g_free(line);
2251     g_debug("/proc/net/dev: Interface '%s' not found", name);
2252     return -1;
2253 }
2254 
2255 /*
2256  * Build information about guest interfaces
2257  */
2258 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
2259 {
2260     GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
2261     struct ifaddrs *ifap, *ifa;
2262 
2263     if (getifaddrs(&ifap) < 0) {
2264         error_setg_errno(errp, errno, "getifaddrs failed");
2265         goto error;
2266     }
2267 
2268     for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
2269         GuestNetworkInterfaceList *info;
2270         GuestIpAddressList **address_list = NULL, *address_item = NULL;
2271         GuestNetworkInterfaceStat  *interface_stat = NULL;
2272         char addr4[INET_ADDRSTRLEN];
2273         char addr6[INET6_ADDRSTRLEN];
2274         int sock;
2275         struct ifreq ifr;
2276         unsigned char *mac_addr;
2277         void *p;
2278 
2279         g_debug("Processing %s interface", ifa->ifa_name);
2280 
2281         info = guest_find_interface(head, ifa->ifa_name);
2282 
2283         if (!info) {
2284             info = g_malloc0(sizeof(*info));
2285             info->value = g_malloc0(sizeof(*info->value));
2286             info->value->name = g_strdup(ifa->ifa_name);
2287 
2288             if (!cur_item) {
2289                 head = cur_item = info;
2290             } else {
2291                 cur_item->next = info;
2292                 cur_item = info;
2293             }
2294         }
2295 
2296         if (!info->value->has_hardware_address &&
2297             ifa->ifa_flags & SIOCGIFHWADDR) {
2298             /* we haven't obtained HW address yet */
2299             sock = socket(PF_INET, SOCK_STREAM, 0);
2300             if (sock == -1) {
2301                 error_setg_errno(errp, errno, "failed to create socket");
2302                 goto error;
2303             }
2304 
2305             memset(&ifr, 0, sizeof(ifr));
2306             pstrcpy(ifr.ifr_name, IF_NAMESIZE, info->value->name);
2307             if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {
2308                 error_setg_errno(errp, errno,
2309                                  "failed to get MAC address of %s",
2310                                  ifa->ifa_name);
2311                 close(sock);
2312                 goto error;
2313             }
2314 
2315             close(sock);
2316             mac_addr = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
2317 
2318             info->value->hardware_address =
2319                 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
2320                                 (int) mac_addr[0], (int) mac_addr[1],
2321                                 (int) mac_addr[2], (int) mac_addr[3],
2322                                 (int) mac_addr[4], (int) mac_addr[5]);
2323 
2324             info->value->has_hardware_address = true;
2325         }
2326 
2327         if (ifa->ifa_addr &&
2328             ifa->ifa_addr->sa_family == AF_INET) {
2329             /* interface with IPv4 address */
2330             p = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
2331             if (!inet_ntop(AF_INET, p, addr4, sizeof(addr4))) {
2332                 error_setg_errno(errp, errno, "inet_ntop failed");
2333                 goto error;
2334             }
2335 
2336             address_item = g_malloc0(sizeof(*address_item));
2337             address_item->value = g_malloc0(sizeof(*address_item->value));
2338             address_item->value->ip_address = g_strdup(addr4);
2339             address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
2340 
2341             if (ifa->ifa_netmask) {
2342                 /* Count the number of set bits in netmask.
2343                  * This is safe as '1' and '0' cannot be shuffled in netmask. */
2344                 p = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
2345                 address_item->value->prefix = ctpop32(((uint32_t *) p)[0]);
2346             }
2347         } else if (ifa->ifa_addr &&
2348                    ifa->ifa_addr->sa_family == AF_INET6) {
2349             /* interface with IPv6 address */
2350             p = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
2351             if (!inet_ntop(AF_INET6, p, addr6, sizeof(addr6))) {
2352                 error_setg_errno(errp, errno, "inet_ntop failed");
2353                 goto error;
2354             }
2355 
2356             address_item = g_malloc0(sizeof(*address_item));
2357             address_item->value = g_malloc0(sizeof(*address_item->value));
2358             address_item->value->ip_address = g_strdup(addr6);
2359             address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
2360 
2361             if (ifa->ifa_netmask) {
2362                 /* Count the number of set bits in netmask.
2363                  * This is safe as '1' and '0' cannot be shuffled in netmask. */
2364                 p = &((struct sockaddr_in6 *)ifa->ifa_netmask)->sin6_addr;
2365                 address_item->value->prefix =
2366                     ctpop32(((uint32_t *) p)[0]) +
2367                     ctpop32(((uint32_t *) p)[1]) +
2368                     ctpop32(((uint32_t *) p)[2]) +
2369                     ctpop32(((uint32_t *) p)[3]);
2370             }
2371         }
2372 
2373         if (!address_item) {
2374             continue;
2375         }
2376 
2377         address_list = &info->value->ip_addresses;
2378 
2379         while (*address_list && (*address_list)->next) {
2380             address_list = &(*address_list)->next;
2381         }
2382 
2383         if (!*address_list) {
2384             *address_list = address_item;
2385         } else {
2386             (*address_list)->next = address_item;
2387         }
2388 
2389         info->value->has_ip_addresses = true;
2390 
2391         if (!info->value->has_statistics) {
2392             interface_stat = g_malloc0(sizeof(*interface_stat));
2393             if (guest_get_network_stats(info->value->name,
2394                 interface_stat) == -1) {
2395                 info->value->has_statistics = false;
2396                 g_free(interface_stat);
2397             } else {
2398                 info->value->statistics = interface_stat;
2399                 info->value->has_statistics = true;
2400             }
2401         }
2402     }
2403 
2404     freeifaddrs(ifap);
2405     return head;
2406 
2407 error:
2408     freeifaddrs(ifap);
2409     qapi_free_GuestNetworkInterfaceList(head);
2410     return NULL;
2411 }
2412 
2413 #define SYSCONF_EXACT(name, errp) sysconf_exact((name), #name, (errp))
2414 
2415 static long sysconf_exact(int name, const char *name_str, Error **errp)
2416 {
2417     long ret;
2418 
2419     errno = 0;
2420     ret = sysconf(name);
2421     if (ret == -1) {
2422         if (errno == 0) {
2423             error_setg(errp, "sysconf(%s): value indefinite", name_str);
2424         } else {
2425             error_setg_errno(errp, errno, "sysconf(%s)", name_str);
2426         }
2427     }
2428     return ret;
2429 }
2430 
2431 /* Transfer online/offline status between @vcpu and the guest system.
2432  *
2433  * On input either @errp or *@errp must be NULL.
2434  *
2435  * In system-to-@vcpu direction, the following @vcpu fields are accessed:
2436  * - R: vcpu->logical_id
2437  * - W: vcpu->online
2438  * - W: vcpu->can_offline
2439  *
2440  * In @vcpu-to-system direction, the following @vcpu fields are accessed:
2441  * - R: vcpu->logical_id
2442  * - R: vcpu->online
2443  *
2444  * Written members remain unmodified on error.
2445  */
2446 static void transfer_vcpu(GuestLogicalProcessor *vcpu, bool sys2vcpu,
2447                           char *dirpath, Error **errp)
2448 {
2449     int fd;
2450     int res;
2451     int dirfd;
2452     static const char fn[] = "online";
2453 
2454     dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2455     if (dirfd == -1) {
2456         error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2457         return;
2458     }
2459 
2460     fd = openat(dirfd, fn, sys2vcpu ? O_RDONLY : O_RDWR);
2461     if (fd == -1) {
2462         if (errno != ENOENT) {
2463             error_setg_errno(errp, errno, "open(\"%s/%s\")", dirpath, fn);
2464         } else if (sys2vcpu) {
2465             vcpu->online = true;
2466             vcpu->can_offline = false;
2467         } else if (!vcpu->online) {
2468             error_setg(errp, "logical processor #%" PRId64 " can't be "
2469                        "offlined", vcpu->logical_id);
2470         } /* otherwise pretend successful re-onlining */
2471     } else {
2472         unsigned char status;
2473 
2474         res = pread(fd, &status, 1, 0);
2475         if (res == -1) {
2476             error_setg_errno(errp, errno, "pread(\"%s/%s\")", dirpath, fn);
2477         } else if (res == 0) {
2478             error_setg(errp, "pread(\"%s/%s\"): unexpected EOF", dirpath,
2479                        fn);
2480         } else if (sys2vcpu) {
2481             vcpu->online = (status != '0');
2482             vcpu->can_offline = true;
2483         } else if (vcpu->online != (status != '0')) {
2484             status = '0' + vcpu->online;
2485             if (pwrite(fd, &status, 1, 0) == -1) {
2486                 error_setg_errno(errp, errno, "pwrite(\"%s/%s\")", dirpath,
2487                                  fn);
2488             }
2489         } /* otherwise pretend successful re-(on|off)-lining */
2490 
2491         res = close(fd);
2492         g_assert(res == 0);
2493     }
2494 
2495     res = close(dirfd);
2496     g_assert(res == 0);
2497 }
2498 
2499 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
2500 {
2501     int64_t current;
2502     GuestLogicalProcessorList *head, **link;
2503     long sc_max;
2504     Error *local_err = NULL;
2505 
2506     current = 0;
2507     head = NULL;
2508     link = &head;
2509     sc_max = SYSCONF_EXACT(_SC_NPROCESSORS_CONF, &local_err);
2510 
2511     while (local_err == NULL && current < sc_max) {
2512         GuestLogicalProcessor *vcpu;
2513         GuestLogicalProcessorList *entry;
2514         int64_t id = current++;
2515         char *path = g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64 "/",
2516                                      id);
2517 
2518         if (g_file_test(path, G_FILE_TEST_EXISTS)) {
2519             vcpu = g_malloc0(sizeof *vcpu);
2520             vcpu->logical_id = id;
2521             vcpu->has_can_offline = true; /* lolspeak ftw */
2522             transfer_vcpu(vcpu, true, path, &local_err);
2523             entry = g_malloc0(sizeof *entry);
2524             entry->value = vcpu;
2525             *link = entry;
2526             link = &entry->next;
2527         }
2528         g_free(path);
2529     }
2530 
2531     if (local_err == NULL) {
2532         /* there's no guest with zero VCPUs */
2533         g_assert(head != NULL);
2534         return head;
2535     }
2536 
2537     qapi_free_GuestLogicalProcessorList(head);
2538     error_propagate(errp, local_err);
2539     return NULL;
2540 }
2541 
2542 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
2543 {
2544     int64_t processed;
2545     Error *local_err = NULL;
2546 
2547     processed = 0;
2548     while (vcpus != NULL) {
2549         char *path = g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64 "/",
2550                                      vcpus->value->logical_id);
2551 
2552         transfer_vcpu(vcpus->value, false, path, &local_err);
2553         g_free(path);
2554         if (local_err != NULL) {
2555             break;
2556         }
2557         ++processed;
2558         vcpus = vcpus->next;
2559     }
2560 
2561     if (local_err != NULL) {
2562         if (processed == 0) {
2563             error_propagate(errp, local_err);
2564         } else {
2565             error_free(local_err);
2566         }
2567     }
2568 
2569     return processed;
2570 }
2571 
2572 void qmp_guest_set_user_password(const char *username,
2573                                  const char *password,
2574                                  bool crypted,
2575                                  Error **errp)
2576 {
2577     Error *local_err = NULL;
2578     char *passwd_path = NULL;
2579     pid_t pid;
2580     int status;
2581     int datafd[2] = { -1, -1 };
2582     char *rawpasswddata = NULL;
2583     size_t rawpasswdlen;
2584     char *chpasswddata = NULL;
2585     size_t chpasswdlen;
2586 
2587     rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
2588     if (!rawpasswddata) {
2589         return;
2590     }
2591     rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
2592     rawpasswddata[rawpasswdlen] = '\0';
2593 
2594     if (strchr(rawpasswddata, '\n')) {
2595         error_setg(errp, "forbidden characters in raw password");
2596         goto out;
2597     }
2598 
2599     if (strchr(username, '\n') ||
2600         strchr(username, ':')) {
2601         error_setg(errp, "forbidden characters in username");
2602         goto out;
2603     }
2604 
2605     chpasswddata = g_strdup_printf("%s:%s\n", username, rawpasswddata);
2606     chpasswdlen = strlen(chpasswddata);
2607 
2608     passwd_path = g_find_program_in_path("chpasswd");
2609 
2610     if (!passwd_path) {
2611         error_setg(errp, "cannot find 'passwd' program in PATH");
2612         goto out;
2613     }
2614 
2615     if (pipe(datafd) < 0) {
2616         error_setg(errp, "cannot create pipe FDs");
2617         goto out;
2618     }
2619 
2620     pid = fork();
2621     if (pid == 0) {
2622         close(datafd[1]);
2623         /* child */
2624         setsid();
2625         dup2(datafd[0], 0);
2626         reopen_fd_to_null(1);
2627         reopen_fd_to_null(2);
2628 
2629         if (crypted) {
2630             execle(passwd_path, "chpasswd", "-e", NULL, environ);
2631         } else {
2632             execle(passwd_path, "chpasswd", NULL, environ);
2633         }
2634         _exit(EXIT_FAILURE);
2635     } else if (pid < 0) {
2636         error_setg_errno(errp, errno, "failed to create child process");
2637         goto out;
2638     }
2639     close(datafd[0]);
2640     datafd[0] = -1;
2641 
2642     if (qemu_write_full(datafd[1], chpasswddata, chpasswdlen) != chpasswdlen) {
2643         error_setg_errno(errp, errno, "cannot write new account password");
2644         goto out;
2645     }
2646     close(datafd[1]);
2647     datafd[1] = -1;
2648 
2649     ga_wait_child(pid, &status, &local_err);
2650     if (local_err) {
2651         error_propagate(errp, local_err);
2652         goto out;
2653     }
2654 
2655     if (!WIFEXITED(status)) {
2656         error_setg(errp, "child process has terminated abnormally");
2657         goto out;
2658     }
2659 
2660     if (WEXITSTATUS(status)) {
2661         error_setg(errp, "child process has failed to set user password");
2662         goto out;
2663     }
2664 
2665 out:
2666     g_free(chpasswddata);
2667     g_free(rawpasswddata);
2668     g_free(passwd_path);
2669     if (datafd[0] != -1) {
2670         close(datafd[0]);
2671     }
2672     if (datafd[1] != -1) {
2673         close(datafd[1]);
2674     }
2675 }
2676 
2677 static void ga_read_sysfs_file(int dirfd, const char *pathname, char *buf,
2678                                int size, Error **errp)
2679 {
2680     int fd;
2681     int res;
2682 
2683     errno = 0;
2684     fd = openat(dirfd, pathname, O_RDONLY);
2685     if (fd == -1) {
2686         error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2687         return;
2688     }
2689 
2690     res = pread(fd, buf, size, 0);
2691     if (res == -1) {
2692         error_setg_errno(errp, errno, "pread sysfs file \"%s\"", pathname);
2693     } else if (res == 0) {
2694         error_setg(errp, "pread sysfs file \"%s\": unexpected EOF", pathname);
2695     }
2696     close(fd);
2697 }
2698 
2699 static void ga_write_sysfs_file(int dirfd, const char *pathname,
2700                                 const char *buf, int size, Error **errp)
2701 {
2702     int fd;
2703 
2704     errno = 0;
2705     fd = openat(dirfd, pathname, O_WRONLY);
2706     if (fd == -1) {
2707         error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2708         return;
2709     }
2710 
2711     if (pwrite(fd, buf, size, 0) == -1) {
2712         error_setg_errno(errp, errno, "pwrite sysfs file \"%s\"", pathname);
2713     }
2714 
2715     close(fd);
2716 }
2717 
2718 /* Transfer online/offline status between @mem_blk and the guest system.
2719  *
2720  * On input either @errp or *@errp must be NULL.
2721  *
2722  * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2723  * - R: mem_blk->phys_index
2724  * - W: mem_blk->online
2725  * - W: mem_blk->can_offline
2726  *
2727  * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2728  * - R: mem_blk->phys_index
2729  * - R: mem_blk->online
2730  *-  R: mem_blk->can_offline
2731  * Written members remain unmodified on error.
2732  */
2733 static void transfer_memory_block(GuestMemoryBlock *mem_blk, bool sys2memblk,
2734                                   GuestMemoryBlockResponse *result,
2735                                   Error **errp)
2736 {
2737     char *dirpath;
2738     int dirfd;
2739     char *status;
2740     Error *local_err = NULL;
2741 
2742     if (!sys2memblk) {
2743         DIR *dp;
2744 
2745         if (!result) {
2746             error_setg(errp, "Internal error, 'result' should not be NULL");
2747             return;
2748         }
2749         errno = 0;
2750         dp = opendir("/sys/devices/system/memory/");
2751          /* if there is no 'memory' directory in sysfs,
2752          * we think this VM does not support online/offline memory block,
2753          * any other solution?
2754          */
2755         if (!dp) {
2756             if (errno == ENOENT) {
2757                 result->response =
2758                     GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2759             }
2760             goto out1;
2761         }
2762         closedir(dp);
2763     }
2764 
2765     dirpath = g_strdup_printf("/sys/devices/system/memory/memory%" PRId64 "/",
2766                               mem_blk->phys_index);
2767     dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2768     if (dirfd == -1) {
2769         if (sys2memblk) {
2770             error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2771         } else {
2772             if (errno == ENOENT) {
2773                 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND;
2774             } else {
2775                 result->response =
2776                     GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2777             }
2778         }
2779         g_free(dirpath);
2780         goto out1;
2781     }
2782     g_free(dirpath);
2783 
2784     status = g_malloc0(10);
2785     ga_read_sysfs_file(dirfd, "state", status, 10, &local_err);
2786     if (local_err) {
2787         /* treat with sysfs file that not exist in old kernel */
2788         if (errno == ENOENT) {
2789             error_free(local_err);
2790             if (sys2memblk) {
2791                 mem_blk->online = true;
2792                 mem_blk->can_offline = false;
2793             } else if (!mem_blk->online) {
2794                 result->response =
2795                     GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2796             }
2797         } else {
2798             if (sys2memblk) {
2799                 error_propagate(errp, local_err);
2800             } else {
2801                 error_free(local_err);
2802                 result->response =
2803                     GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2804             }
2805         }
2806         goto out2;
2807     }
2808 
2809     if (sys2memblk) {
2810         char removable = '0';
2811 
2812         mem_blk->online = (strncmp(status, "online", 6) == 0);
2813 
2814         ga_read_sysfs_file(dirfd, "removable", &removable, 1, &local_err);
2815         if (local_err) {
2816             /* if no 'removable' file, it doesn't support offline mem blk */
2817             if (errno == ENOENT) {
2818                 error_free(local_err);
2819                 mem_blk->can_offline = false;
2820             } else {
2821                 error_propagate(errp, local_err);
2822             }
2823         } else {
2824             mem_blk->can_offline = (removable != '0');
2825         }
2826     } else {
2827         if (mem_blk->online != (strncmp(status, "online", 6) == 0)) {
2828             const char *new_state = mem_blk->online ? "online" : "offline";
2829 
2830             ga_write_sysfs_file(dirfd, "state", new_state, strlen(new_state),
2831                                 &local_err);
2832             if (local_err) {
2833                 error_free(local_err);
2834                 result->response =
2835                     GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2836                 goto out2;
2837             }
2838 
2839             result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS;
2840             result->has_error_code = false;
2841         } /* otherwise pretend successful re-(on|off)-lining */
2842     }
2843     g_free(status);
2844     close(dirfd);
2845     return;
2846 
2847 out2:
2848     g_free(status);
2849     close(dirfd);
2850 out1:
2851     if (!sys2memblk) {
2852         result->has_error_code = true;
2853         result->error_code = errno;
2854     }
2855 }
2856 
2857 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2858 {
2859     GuestMemoryBlockList *head, **link;
2860     Error *local_err = NULL;
2861     struct dirent *de;
2862     DIR *dp;
2863 
2864     head = NULL;
2865     link = &head;
2866 
2867     dp = opendir("/sys/devices/system/memory/");
2868     if (!dp) {
2869         /* it's ok if this happens to be a system that doesn't expose
2870          * memory blocks via sysfs, but otherwise we should report
2871          * an error
2872          */
2873         if (errno != ENOENT) {
2874             error_setg_errno(errp, errno, "Can't open directory"
2875                              "\"/sys/devices/system/memory/\"");
2876         }
2877         return NULL;
2878     }
2879 
2880     /* Note: the phys_index of memory block may be discontinuous,
2881      * this is because a memblk is the unit of the Sparse Memory design, which
2882      * allows discontinuous memory ranges (ex. NUMA), so here we should
2883      * traverse the memory block directory.
2884      */
2885     while ((de = readdir(dp)) != NULL) {
2886         GuestMemoryBlock *mem_blk;
2887         GuestMemoryBlockList *entry;
2888 
2889         if ((strncmp(de->d_name, "memory", 6) != 0) ||
2890             !(de->d_type & DT_DIR)) {
2891             continue;
2892         }
2893 
2894         mem_blk = g_malloc0(sizeof *mem_blk);
2895         /* The d_name is "memoryXXX",  phys_index is block id, same as XXX */
2896         mem_blk->phys_index = strtoul(&de->d_name[6], NULL, 10);
2897         mem_blk->has_can_offline = true; /* lolspeak ftw */
2898         transfer_memory_block(mem_blk, true, NULL, &local_err);
2899         if (local_err) {
2900             break;
2901         }
2902 
2903         entry = g_malloc0(sizeof *entry);
2904         entry->value = mem_blk;
2905 
2906         *link = entry;
2907         link = &entry->next;
2908     }
2909 
2910     closedir(dp);
2911     if (local_err == NULL) {
2912         /* there's no guest with zero memory blocks */
2913         if (head == NULL) {
2914             error_setg(errp, "guest reported zero memory blocks!");
2915         }
2916         return head;
2917     }
2918 
2919     qapi_free_GuestMemoryBlockList(head);
2920     error_propagate(errp, local_err);
2921     return NULL;
2922 }
2923 
2924 GuestMemoryBlockResponseList *
2925 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2926 {
2927     GuestMemoryBlockResponseList *head, **link;
2928     Error *local_err = NULL;
2929 
2930     head = NULL;
2931     link = &head;
2932 
2933     while (mem_blks != NULL) {
2934         GuestMemoryBlockResponse *result;
2935         GuestMemoryBlockResponseList *entry;
2936         GuestMemoryBlock *current_mem_blk = mem_blks->value;
2937 
2938         result = g_malloc0(sizeof(*result));
2939         result->phys_index = current_mem_blk->phys_index;
2940         transfer_memory_block(current_mem_blk, false, result, &local_err);
2941         if (local_err) { /* should never happen */
2942             goto err;
2943         }
2944         entry = g_malloc0(sizeof *entry);
2945         entry->value = result;
2946 
2947         *link = entry;
2948         link = &entry->next;
2949         mem_blks = mem_blks->next;
2950     }
2951 
2952     return head;
2953 err:
2954     qapi_free_GuestMemoryBlockResponseList(head);
2955     error_propagate(errp, local_err);
2956     return NULL;
2957 }
2958 
2959 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2960 {
2961     Error *local_err = NULL;
2962     char *dirpath;
2963     int dirfd;
2964     char *buf;
2965     GuestMemoryBlockInfo *info;
2966 
2967     dirpath = g_strdup_printf("/sys/devices/system/memory/");
2968     dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2969     if (dirfd == -1) {
2970         error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2971         g_free(dirpath);
2972         return NULL;
2973     }
2974     g_free(dirpath);
2975 
2976     buf = g_malloc0(20);
2977     ga_read_sysfs_file(dirfd, "block_size_bytes", buf, 20, &local_err);
2978     close(dirfd);
2979     if (local_err) {
2980         g_free(buf);
2981         error_propagate(errp, local_err);
2982         return NULL;
2983     }
2984 
2985     info = g_new0(GuestMemoryBlockInfo, 1);
2986     info->size = strtol(buf, NULL, 16); /* the unit is bytes */
2987 
2988     g_free(buf);
2989 
2990     return info;
2991 }
2992 
2993 #else /* defined(__linux__) */
2994 
2995 void qmp_guest_suspend_disk(Error **errp)
2996 {
2997     error_setg(errp, QERR_UNSUPPORTED);
2998 }
2999 
3000 void qmp_guest_suspend_ram(Error **errp)
3001 {
3002     error_setg(errp, QERR_UNSUPPORTED);
3003 }
3004 
3005 void qmp_guest_suspend_hybrid(Error **errp)
3006 {
3007     error_setg(errp, QERR_UNSUPPORTED);
3008 }
3009 
3010 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
3011 {
3012     error_setg(errp, QERR_UNSUPPORTED);
3013     return NULL;
3014 }
3015 
3016 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
3017 {
3018     error_setg(errp, QERR_UNSUPPORTED);
3019     return NULL;
3020 }
3021 
3022 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
3023 {
3024     error_setg(errp, QERR_UNSUPPORTED);
3025     return -1;
3026 }
3027 
3028 void qmp_guest_set_user_password(const char *username,
3029                                  const char *password,
3030                                  bool crypted,
3031                                  Error **errp)
3032 {
3033     error_setg(errp, QERR_UNSUPPORTED);
3034 }
3035 
3036 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
3037 {
3038     error_setg(errp, QERR_UNSUPPORTED);
3039     return NULL;
3040 }
3041 
3042 GuestMemoryBlockResponseList *
3043 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
3044 {
3045     error_setg(errp, QERR_UNSUPPORTED);
3046     return NULL;
3047 }
3048 
3049 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
3050 {
3051     error_setg(errp, QERR_UNSUPPORTED);
3052     return NULL;
3053 }
3054 
3055 #endif
3056 
3057 #if !defined(CONFIG_FSFREEZE)
3058 
3059 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
3060 {
3061     error_setg(errp, QERR_UNSUPPORTED);
3062     return NULL;
3063 }
3064 
3065 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
3066 {
3067     error_setg(errp, QERR_UNSUPPORTED);
3068 
3069     return 0;
3070 }
3071 
3072 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
3073 {
3074     error_setg(errp, QERR_UNSUPPORTED);
3075 
3076     return 0;
3077 }
3078 
3079 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
3080                                        strList *mountpoints,
3081                                        Error **errp)
3082 {
3083     error_setg(errp, QERR_UNSUPPORTED);
3084 
3085     return 0;
3086 }
3087 
3088 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
3089 {
3090     error_setg(errp, QERR_UNSUPPORTED);
3091 
3092     return 0;
3093 }
3094 
3095 GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
3096 {
3097     error_setg(errp, QERR_UNSUPPORTED);
3098     return NULL;
3099 }
3100 
3101 #endif /* CONFIG_FSFREEZE */
3102 
3103 #if !defined(CONFIG_FSTRIM)
3104 GuestFilesystemTrimResponse *
3105 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
3106 {
3107     error_setg(errp, QERR_UNSUPPORTED);
3108     return NULL;
3109 }
3110 #endif
3111 
3112 /* add unsupported commands to the blacklist */
3113 GList *ga_command_blacklist_init(GList *blacklist)
3114 {
3115 #if !defined(__linux__)
3116     {
3117         const char *list[] = {
3118             "guest-suspend-disk", "guest-suspend-ram",
3119             "guest-suspend-hybrid", "guest-network-get-interfaces",
3120             "guest-get-vcpus", "guest-set-vcpus",
3121             "guest-get-memory-blocks", "guest-set-memory-blocks",
3122             "guest-get-memory-block-size", "guest-get-memory-block-info",
3123             NULL};
3124         char **p = (char **)list;
3125 
3126         while (*p) {
3127             blacklist = g_list_append(blacklist, g_strdup(*p++));
3128         }
3129     }
3130 #endif
3131 
3132 #if !defined(CONFIG_FSFREEZE)
3133     {
3134         const char *list[] = {
3135             "guest-get-fsinfo", "guest-fsfreeze-status",
3136             "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
3137             "guest-fsfreeze-thaw", "guest-get-fsinfo",
3138             "guest-get-disks", NULL};
3139         char **p = (char **)list;
3140 
3141         while (*p) {
3142             blacklist = g_list_append(blacklist, g_strdup(*p++));
3143         }
3144     }
3145 #endif
3146 
3147 #if !defined(CONFIG_FSTRIM)
3148     blacklist = g_list_append(blacklist, g_strdup("guest-fstrim"));
3149 #endif
3150 
3151     blacklist = g_list_append(blacklist, g_strdup("guest-get-devices"));
3152 
3153     return blacklist;
3154 }
3155 
3156 /* register init/cleanup routines for stateful command groups */
3157 void ga_command_state_init(GAState *s, GACommandState *cs)
3158 {
3159 #if defined(CONFIG_FSFREEZE)
3160     ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
3161 #endif
3162 }
3163 
3164 #ifdef HAVE_UTMPX
3165 
3166 #define QGA_MICRO_SECOND_TO_SECOND 1000000
3167 
3168 static double ga_get_login_time(struct utmpx *user_info)
3169 {
3170     double seconds = (double)user_info->ut_tv.tv_sec;
3171     double useconds = (double)user_info->ut_tv.tv_usec;
3172     useconds /= QGA_MICRO_SECOND_TO_SECOND;
3173     return seconds + useconds;
3174 }
3175 
3176 GuestUserList *qmp_guest_get_users(Error **errp)
3177 {
3178     GHashTable *cache = NULL;
3179     GuestUserList *head = NULL, *cur_item = NULL;
3180     struct utmpx *user_info = NULL;
3181     gpointer value = NULL;
3182     GuestUser *user = NULL;
3183     GuestUserList *item = NULL;
3184     double login_time = 0;
3185 
3186     cache = g_hash_table_new(g_str_hash, g_str_equal);
3187     setutxent();
3188 
3189     for (;;) {
3190         user_info = getutxent();
3191         if (user_info == NULL) {
3192             break;
3193         } else if (user_info->ut_type != USER_PROCESS) {
3194             continue;
3195         } else if (g_hash_table_contains(cache, user_info->ut_user)) {
3196             value = g_hash_table_lookup(cache, user_info->ut_user);
3197             user = (GuestUser *)value;
3198             login_time = ga_get_login_time(user_info);
3199             /* We're ensuring the earliest login time to be sent */
3200             if (login_time < user->login_time) {
3201                 user->login_time = login_time;
3202             }
3203             continue;
3204         }
3205 
3206         item = g_new0(GuestUserList, 1);
3207         item->value = g_new0(GuestUser, 1);
3208         item->value->user = g_strdup(user_info->ut_user);
3209         item->value->login_time = ga_get_login_time(user_info);
3210 
3211         g_hash_table_insert(cache, item->value->user, item->value);
3212 
3213         if (!cur_item) {
3214             head = cur_item = item;
3215         } else {
3216             cur_item->next = item;
3217             cur_item = item;
3218         }
3219     }
3220     endutxent();
3221     g_hash_table_destroy(cache);
3222     return head;
3223 }
3224 
3225 #else
3226 
3227 GuestUserList *qmp_guest_get_users(Error **errp)
3228 {
3229     error_setg(errp, QERR_UNSUPPORTED);
3230     return NULL;
3231 }
3232 
3233 #endif
3234 
3235 /* Replace escaped special characters with theire real values. The replacement
3236  * is done in place -- returned value is in the original string.
3237  */
3238 static void ga_osrelease_replace_special(gchar *value)
3239 {
3240     gchar *p, *p2, quote;
3241 
3242     /* Trim the string at first space or semicolon if it is not enclosed in
3243      * single or double quotes. */
3244     if ((value[0] != '"') || (value[0] == '\'')) {
3245         p = strchr(value, ' ');
3246         if (p != NULL) {
3247             *p = 0;
3248         }
3249         p = strchr(value, ';');
3250         if (p != NULL) {
3251             *p = 0;
3252         }
3253         return;
3254     }
3255 
3256     quote = value[0];
3257     p2 = value;
3258     p = value + 1;
3259     while (*p != 0) {
3260         if (*p == '\\') {
3261             p++;
3262             switch (*p) {
3263             case '$':
3264             case '\'':
3265             case '"':
3266             case '\\':
3267             case '`':
3268                 break;
3269             default:
3270                 /* Keep literal backslash followed by whatever is there */
3271                 p--;
3272                 break;
3273             }
3274         } else if (*p == quote) {
3275             *p2 = 0;
3276             break;
3277         }
3278         *(p2++) = *(p++);
3279     }
3280 }
3281 
3282 static GKeyFile *ga_parse_osrelease(const char *fname)
3283 {
3284     gchar *content = NULL;
3285     gchar *content2 = NULL;
3286     GError *err = NULL;
3287     GKeyFile *keys = g_key_file_new();
3288     const char *group = "[os-release]\n";
3289 
3290     if (!g_file_get_contents(fname, &content, NULL, &err)) {
3291         slog("failed to read '%s', error: %s", fname, err->message);
3292         goto fail;
3293     }
3294 
3295     if (!g_utf8_validate(content, -1, NULL)) {
3296         slog("file is not utf-8 encoded: %s", fname);
3297         goto fail;
3298     }
3299     content2 = g_strdup_printf("%s%s", group, content);
3300 
3301     if (!g_key_file_load_from_data(keys, content2, -1, G_KEY_FILE_NONE,
3302                                    &err)) {
3303         slog("failed to parse file '%s', error: %s", fname, err->message);
3304         goto fail;
3305     }
3306 
3307     g_free(content);
3308     g_free(content2);
3309     return keys;
3310 
3311 fail:
3312     g_error_free(err);
3313     g_free(content);
3314     g_free(content2);
3315     g_key_file_free(keys);
3316     return NULL;
3317 }
3318 
3319 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
3320 {
3321     GuestOSInfo *info = NULL;
3322     struct utsname kinfo;
3323     GKeyFile *osrelease = NULL;
3324     const char *qga_os_release = g_getenv("QGA_OS_RELEASE");
3325 
3326     info = g_new0(GuestOSInfo, 1);
3327 
3328     if (uname(&kinfo) != 0) {
3329         error_setg_errno(errp, errno, "uname failed");
3330     } else {
3331         info->has_kernel_version = true;
3332         info->kernel_version = g_strdup(kinfo.version);
3333         info->has_kernel_release = true;
3334         info->kernel_release = g_strdup(kinfo.release);
3335         info->has_machine = true;
3336         info->machine = g_strdup(kinfo.machine);
3337     }
3338 
3339     if (qga_os_release != NULL) {
3340         osrelease = ga_parse_osrelease(qga_os_release);
3341     } else {
3342         osrelease = ga_parse_osrelease("/etc/os-release");
3343         if (osrelease == NULL) {
3344             osrelease = ga_parse_osrelease("/usr/lib/os-release");
3345         }
3346     }
3347 
3348     if (osrelease != NULL) {
3349         char *value;
3350 
3351 #define GET_FIELD(field, osfield) do { \
3352     value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
3353     if (value != NULL) { \
3354         ga_osrelease_replace_special(value); \
3355         info->has_ ## field = true; \
3356         info->field = value; \
3357     } \
3358 } while (0)
3359         GET_FIELD(id, "ID");
3360         GET_FIELD(name, "NAME");
3361         GET_FIELD(pretty_name, "PRETTY_NAME");
3362         GET_FIELD(version, "VERSION");
3363         GET_FIELD(version_id, "VERSION_ID");
3364         GET_FIELD(variant, "VARIANT");
3365         GET_FIELD(variant_id, "VARIANT_ID");
3366 #undef GET_FIELD
3367 
3368         g_key_file_free(osrelease);
3369     }
3370 
3371     return info;
3372 }
3373 
3374 GuestDeviceInfoList *qmp_guest_get_devices(Error **errp)
3375 {
3376     error_setg(errp, QERR_UNSUPPORTED);
3377 
3378     return NULL;
3379 }
3380