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