]> git.proxmox.com Git - qemu.git/blame - qga/commands-posix.c
qemu-ga: use key-value store to avoid recycling fd handles after restart
[qemu.git] / qga / commands-posix.c
CommitLineData
e3d4d252 1/*
42074a9d 2 * QEMU Guest Agent POSIX-specific command implementations
e3d4d252
MR
3 *
4 * Copyright IBM Corp. 2011
5 *
6 * Authors:
7 * Michael Roth <mdroth@linux.vnet.ibm.com>
3424fc9f 8 * Michal Privoznik <mprivozn@redhat.com>
e3d4d252
MR
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 <glib.h>
e72c3f2e
MR
15#include <sys/types.h>
16#include <sys/ioctl.h>
2c02cbf6 17#include <sys/wait.h>
e72c3f2e
MR
18#include "qga/guest-agent-core.h"
19#include "qga-qmp-commands.h"
7b1b5d19 20#include "qapi/qmp/qerror.h"
1de7afc9
PB
21#include "qemu/queue.h"
22#include "qemu/host-utils.h"
4eb36d40 23
2c02cbf6 24#ifndef CONFIG_HAS_ENVIRON
eecae147
AF
25#ifdef __APPLE__
26#include <crt_externs.h>
27#define environ (*_NSGetEnviron())
28#else
2c02cbf6
LC
29extern char **environ;
30#endif
eecae147 31#endif
2c02cbf6 32
4eb36d40 33#if defined(__linux__)
e3d4d252 34#include <mntent.h>
7006b9cf 35#include <linux/fs.h>
3424fc9f
MP
36#include <ifaddrs.h>
37#include <arpa/inet.h>
38#include <sys/socket.h>
39#include <net/if.h>
e3d4d252 40
eab5fd59 41#ifdef FIFREEZE
e72c3f2e
MR
42#define CONFIG_FSFREEZE
43#endif
eab5fd59
PB
44#ifdef FITRIM
45#define CONFIG_FSTRIM
46#endif
e72c3f2e
MR
47#endif
48
d220a6df
LC
49static void ga_wait_child(pid_t pid, int *status, Error **err)
50{
51 pid_t rpid;
52
53 *status = 0;
54
55 do {
56 rpid = waitpid(pid, status, 0);
57 } while (rpid == -1 && errno == EINTR);
58
59 if (rpid == -1) {
60 error_setg_errno(err, errno, "failed to wait for child (pid: %d)", pid);
61 return;
62 }
63
64 g_assert(rpid == pid);
65}
66
e3d4d252
MR
67void qmp_guest_shutdown(bool has_mode, const char *mode, Error **err)
68{
e3d4d252 69 const char *shutdown_flag;
d220a6df
LC
70 Error *local_err = NULL;
71 pid_t pid;
3674838c 72 int status;
e3d4d252
MR
73
74 slog("guest-shutdown called, mode: %s", mode);
75 if (!has_mode || strcmp(mode, "powerdown") == 0) {
76 shutdown_flag = "-P";
77 } else if (strcmp(mode, "halt") == 0) {
78 shutdown_flag = "-H";
79 } else if (strcmp(mode, "reboot") == 0) {
80 shutdown_flag = "-r";
81 } else {
d220a6df
LC
82 error_setg(err,
83 "mode is invalid (valid values are: halt|powerdown|reboot");
e3d4d252
MR
84 return;
85 }
86
d5dd3498
LC
87 pid = fork();
88 if (pid == 0) {
e3d4d252
MR
89 /* child, start the shutdown */
90 setsid();
3674838c
LC
91 reopen_fd_to_null(0);
92 reopen_fd_to_null(1);
93 reopen_fd_to_null(2);
e3d4d252 94
3674838c
LC
95 execle("/sbin/shutdown", "shutdown", shutdown_flag, "+0",
96 "hypervisor initiated shutdown", (char*)NULL, environ);
97 _exit(EXIT_FAILURE);
d5dd3498 98 } else if (pid < 0) {
d220a6df
LC
99 error_setg_errno(err, errno, "failed to create child process");
100 return;
e3d4d252 101 }
d5dd3498 102
d220a6df
LC
103 ga_wait_child(pid, &status, &local_err);
104 if (error_is_set(&local_err)) {
105 error_propagate(err, local_err);
106 return;
107 }
108
109 if (!WIFEXITED(status)) {
110 error_setg(err, "child process has terminated abnormally");
111 return;
112 }
113
114 if (WEXITSTATUS(status)) {
115 error_setg(err, "child process has failed to shutdown");
d5dd3498
LC
116 return;
117 }
118
d220a6df 119 /* succeded */
e3d4d252
MR
120}
121
122typedef struct GuestFileHandle {
123 uint64_t id;
124 FILE *fh;
125 QTAILQ_ENTRY(GuestFileHandle) next;
126} GuestFileHandle;
127
128static struct {
129 QTAILQ_HEAD(, GuestFileHandle) filehandles;
130} guest_file_state;
131
39097daf 132static int64_t guest_file_handle_add(FILE *fh, Error **errp)
e3d4d252
MR
133{
134 GuestFileHandle *gfh;
39097daf
MR
135 int64_t handle;
136
137 handle = ga_get_fd_handle(ga_state, errp);
138 if (error_is_set(errp)) {
139 return 0;
140 }
e3d4d252 141
7267c094 142 gfh = g_malloc0(sizeof(GuestFileHandle));
39097daf 143 gfh->id = handle;
e3d4d252
MR
144 gfh->fh = fh;
145 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
39097daf
MR
146
147 return handle;
e3d4d252
MR
148}
149
a9de6d01 150static GuestFileHandle *guest_file_handle_find(int64_t id, Error **err)
e3d4d252
MR
151{
152 GuestFileHandle *gfh;
153
154 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next)
155 {
156 if (gfh->id == id) {
157 return gfh;
158 }
159 }
160
a9de6d01 161 error_setg(err, "handle '%" PRId64 "' has not been found", id);
e3d4d252
MR
162 return NULL;
163}
164
165int64_t qmp_guest_file_open(const char *path, bool has_mode, const char *mode, Error **err)
166{
167 FILE *fh;
168 int fd;
39097daf 169 int64_t ret = -1, handle;
e3d4d252
MR
170
171 if (!has_mode) {
172 mode = "r";
173 }
174 slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
175 fh = fopen(path, mode);
176 if (!fh) {
db3edb66
LC
177 error_setg_errno(err, errno, "failed to open file '%s' (mode: '%s')",
178 path, mode);
e3d4d252
MR
179 return -1;
180 }
181
182 /* set fd non-blocking to avoid common use cases (like reading from a
183 * named pipe) from hanging the agent
184 */
185 fd = fileno(fh);
186 ret = fcntl(fd, F_GETFL);
187 ret = fcntl(fd, F_SETFL, ret | O_NONBLOCK);
188 if (ret == -1) {
db3edb66
LC
189 error_setg_errno(err, errno, "failed to make file '%s' non-blocking",
190 path);
e3d4d252
MR
191 fclose(fh);
192 return -1;
193 }
194
39097daf
MR
195 handle = guest_file_handle_add(fh, err);
196 if (error_is_set(err)) {
197 fclose(fh);
198 return -1;
199 }
200
201 slog("guest-file-open, handle: %d", handle);
202 return handle;
e3d4d252
MR
203}
204
205void qmp_guest_file_close(int64_t handle, Error **err)
206{
a9de6d01 207 GuestFileHandle *gfh = guest_file_handle_find(handle, err);
e3d4d252
MR
208 int ret;
209
210 slog("guest-file-close called, handle: %ld", handle);
211 if (!gfh) {
e3d4d252
MR
212 return;
213 }
214
215 ret = fclose(gfh->fh);
3ac4b7c5 216 if (ret == EOF) {
db3edb66 217 error_setg_errno(err, errno, "failed to close handle");
e3d4d252
MR
218 return;
219 }
220
221 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
7267c094 222 g_free(gfh);
e3d4d252
MR
223}
224
225struct GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
226 int64_t count, Error **err)
227{
a9de6d01 228 GuestFileHandle *gfh = guest_file_handle_find(handle, err);
e3d4d252
MR
229 GuestFileRead *read_data = NULL;
230 guchar *buf;
231 FILE *fh;
232 size_t read_count;
233
234 if (!gfh) {
e3d4d252
MR
235 return NULL;
236 }
237
238 if (!has_count) {
239 count = QGA_READ_COUNT_DEFAULT;
240 } else if (count < 0) {
db3edb66
LC
241 error_setg(err, "value '%" PRId64 "' is invalid for argument count",
242 count);
e3d4d252
MR
243 return NULL;
244 }
245
246 fh = gfh->fh;
7267c094 247 buf = g_malloc0(count+1);
e3d4d252
MR
248 read_count = fread(buf, 1, count, fh);
249 if (ferror(fh)) {
db3edb66 250 error_setg_errno(err, errno, "failed to read file");
e3d4d252 251 slog("guest-file-read failed, handle: %ld", handle);
e3d4d252
MR
252 } else {
253 buf[read_count] = 0;
7267c094 254 read_data = g_malloc0(sizeof(GuestFileRead));
e3d4d252
MR
255 read_data->count = read_count;
256 read_data->eof = feof(fh);
257 if (read_count) {
258 read_data->buf_b64 = g_base64_encode(buf, read_count);
259 }
260 }
7267c094 261 g_free(buf);
e3d4d252
MR
262 clearerr(fh);
263
264 return read_data;
265}
266
267GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
268 bool has_count, int64_t count, Error **err)
269{
270 GuestFileWrite *write_data = NULL;
271 guchar *buf;
272 gsize buf_len;
273 int write_count;
a9de6d01 274 GuestFileHandle *gfh = guest_file_handle_find(handle, err);
e3d4d252
MR
275 FILE *fh;
276
277 if (!gfh) {
e3d4d252
MR
278 return NULL;
279 }
280
281 fh = gfh->fh;
282 buf = g_base64_decode(buf_b64, &buf_len);
283
284 if (!has_count) {
285 count = buf_len;
286 } else if (count < 0 || count > buf_len) {
db3edb66
LC
287 error_setg(err, "value '%" PRId64 "' is invalid for argument count",
288 count);
7267c094 289 g_free(buf);
e3d4d252
MR
290 return NULL;
291 }
292
293 write_count = fwrite(buf, 1, count, fh);
294 if (ferror(fh)) {
db3edb66 295 error_setg_errno(err, errno, "failed to write to file");
e3d4d252 296 slog("guest-file-write failed, handle: %ld", handle);
e3d4d252 297 } else {
7267c094 298 write_data = g_malloc0(sizeof(GuestFileWrite));
e3d4d252
MR
299 write_data->count = write_count;
300 write_data->eof = feof(fh);
301 }
7267c094 302 g_free(buf);
e3d4d252
MR
303 clearerr(fh);
304
305 return write_data;
306}
307
308struct GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
309 int64_t whence, Error **err)
310{
a9de6d01 311 GuestFileHandle *gfh = guest_file_handle_find(handle, err);
e3d4d252
MR
312 GuestFileSeek *seek_data = NULL;
313 FILE *fh;
314 int ret;
315
316 if (!gfh) {
e3d4d252
MR
317 return NULL;
318 }
319
320 fh = gfh->fh;
321 ret = fseek(fh, offset, whence);
322 if (ret == -1) {
db3edb66 323 error_setg_errno(err, errno, "failed to seek file");
e3d4d252 324 } else {
7267c094 325 seek_data = g_malloc0(sizeof(GuestFileRead));
e3d4d252
MR
326 seek_data->position = ftell(fh);
327 seek_data->eof = feof(fh);
328 }
329 clearerr(fh);
330
331 return seek_data;
332}
333
334void qmp_guest_file_flush(int64_t handle, Error **err)
335{
a9de6d01 336 GuestFileHandle *gfh = guest_file_handle_find(handle, err);
e3d4d252
MR
337 FILE *fh;
338 int ret;
339
340 if (!gfh) {
e3d4d252
MR
341 return;
342 }
343
344 fh = gfh->fh;
345 ret = fflush(fh);
346 if (ret == EOF) {
db3edb66 347 error_setg_errno(err, errno, "failed to flush file");
e3d4d252
MR
348 }
349}
350
351static void guest_file_init(void)
352{
353 QTAILQ_INIT(&guest_file_state.filehandles);
354}
355
e72c3f2e
MR
356/* linux-specific implementations. avoid this if at all possible. */
357#if defined(__linux__)
358
eab5fd59 359#if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
af02203f 360typedef struct FsMount {
e3d4d252
MR
361 char *dirname;
362 char *devtype;
af02203f
PB
363 QTAILQ_ENTRY(FsMount) next;
364} FsMount;
e3d4d252 365
af02203f 366typedef QTAILQ_HEAD(, FsMount) FsMountList;
9e8aded4 367
af02203f 368static void free_fs_mount_list(FsMountList *mounts)
9e8aded4 369{
af02203f 370 FsMount *mount, *temp;
9e8aded4
MR
371
372 if (!mounts) {
373 return;
374 }
375
376 QTAILQ_FOREACH_SAFE(mount, mounts, next, temp) {
377 QTAILQ_REMOVE(mounts, mount, next);
378 g_free(mount->dirname);
379 g_free(mount->devtype);
380 g_free(mount);
381 }
382}
383
e3d4d252
MR
384/*
385 * Walk the mount table and build a list of local file systems
386 */
261551d1 387static void build_fs_mount_list(FsMountList *mounts, Error **err)
e3d4d252
MR
388{
389 struct mntent *ment;
af02203f 390 FsMount *mount;
9e2fa418 391 char const *mtab = "/proc/self/mounts";
e3d4d252
MR
392 FILE *fp;
393
e3d4d252
MR
394 fp = setmntent(mtab, "r");
395 if (!fp) {
261551d1
LC
396 error_setg(err, "failed to open mtab file: '%s'", mtab);
397 return;
e3d4d252
MR
398 }
399
400 while ((ment = getmntent(fp))) {
401 /*
402 * An entry which device name doesn't start with a '/' is
403 * either a dummy file system or a network file system.
404 * Add special handling for smbfs and cifs as is done by
405 * coreutils as well.
406 */
407 if ((ment->mnt_fsname[0] != '/') ||
408 (strcmp(ment->mnt_type, "smbfs") == 0) ||
409 (strcmp(ment->mnt_type, "cifs") == 0)) {
410 continue;
411 }
412
af02203f 413 mount = g_malloc0(sizeof(FsMount));
7267c094
AL
414 mount->dirname = g_strdup(ment->mnt_dir);
415 mount->devtype = g_strdup(ment->mnt_type);
e3d4d252 416
9e8aded4 417 QTAILQ_INSERT_TAIL(mounts, mount, next);
e3d4d252
MR
418 }
419
420 endmntent(fp);
e3d4d252 421}
eab5fd59
PB
422#endif
423
424#if defined(CONFIG_FSFREEZE)
e3d4d252 425
ec0f694c
TS
426typedef enum {
427 FSFREEZE_HOOK_THAW = 0,
428 FSFREEZE_HOOK_FREEZE,
429} FsfreezeHookArg;
430
431const char *fsfreeze_hook_arg_string[] = {
432 "thaw",
433 "freeze",
434};
435
436static void execute_fsfreeze_hook(FsfreezeHookArg arg, Error **err)
437{
438 int status;
439 pid_t pid;
440 const char *hook;
441 const char *arg_str = fsfreeze_hook_arg_string[arg];
442 Error *local_err = NULL;
443
444 hook = ga_fsfreeze_hook(ga_state);
445 if (!hook) {
446 return;
447 }
448 if (access(hook, X_OK) != 0) {
449 error_setg_errno(err, errno, "can't access fsfreeze hook '%s'", hook);
450 return;
451 }
452
453 slog("executing fsfreeze hook with arg '%s'", arg_str);
454 pid = fork();
455 if (pid == 0) {
456 setsid();
457 reopen_fd_to_null(0);
458 reopen_fd_to_null(1);
459 reopen_fd_to_null(2);
460
461 execle(hook, hook, arg_str, NULL, environ);
462 _exit(EXIT_FAILURE);
463 } else if (pid < 0) {
464 error_setg_errno(err, errno, "failed to create child process");
465 return;
466 }
467
468 ga_wait_child(pid, &status, &local_err);
469 if (error_is_set(&local_err)) {
470 error_propagate(err, local_err);
471 return;
472 }
473
474 if (!WIFEXITED(status)) {
475 error_setg(err, "fsfreeze hook has terminated abnormally");
476 return;
477 }
478
479 status = WEXITSTATUS(status);
480 if (status) {
481 error_setg(err, "fsfreeze hook has failed with status %d", status);
482 return;
483 }
484}
485
e3d4d252
MR
486/*
487 * Return status of freeze/thaw
488 */
489GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **err)
490{
f22d85e9
MR
491 if (ga_is_frozen(ga_state)) {
492 return GUEST_FSFREEZE_STATUS_FROZEN;
493 }
494
495 return GUEST_FSFREEZE_STATUS_THAWED;
e3d4d252
MR
496}
497
498/*
499 * Walk list of mounted file systems in the guest, and freeze the ones which
500 * are real local file systems.
501 */
502int64_t qmp_guest_fsfreeze_freeze(Error **err)
503{
504 int ret = 0, i = 0;
af02203f
PB
505 FsMountList mounts;
506 struct FsMount *mount;
261551d1 507 Error *local_err = NULL;
e3d4d252 508 int fd;
e3d4d252
MR
509
510 slog("guest-fsfreeze called");
511
ec0f694c
TS
512 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE, &local_err);
513 if (error_is_set(&local_err)) {
514 error_propagate(err, local_err);
515 return -1;
516 }
517
9e8aded4 518 QTAILQ_INIT(&mounts);
261551d1
LC
519 build_fs_mount_list(&mounts, &local_err);
520 if (error_is_set(&local_err)) {
521 error_propagate(err, local_err);
522 return -1;
e3d4d252
MR
523 }
524
525 /* cannot risk guest agent blocking itself on a write in this state */
f22d85e9 526 ga_set_frozen(ga_state);
e3d4d252 527
9e8aded4 528 QTAILQ_FOREACH(mount, &mounts, next) {
e3d4d252
MR
529 fd = qemu_open(mount->dirname, O_RDONLY);
530 if (fd == -1) {
617fbbc1 531 error_setg_errno(err, errno, "failed to open %s", mount->dirname);
e3d4d252
MR
532 goto error;
533 }
534
535 /* we try to cull filesytems we know won't work in advance, but other
536 * filesytems may not implement fsfreeze for less obvious reasons.
9e8aded4
MR
537 * these will report EOPNOTSUPP. we simply ignore these when tallying
538 * the number of frozen filesystems.
539 *
540 * any other error means a failure to freeze a filesystem we
541 * expect to be freezable, so return an error in those cases
542 * and return system to thawed state.
e3d4d252
MR
543 */
544 ret = ioctl(fd, FIFREEZE);
9e8aded4
MR
545 if (ret == -1) {
546 if (errno != EOPNOTSUPP) {
617fbbc1
LC
547 error_setg_errno(err, errno, "failed to freeze %s",
548 mount->dirname);
9e8aded4
MR
549 close(fd);
550 goto error;
551 }
552 } else {
553 i++;
e3d4d252
MR
554 }
555 close(fd);
e3d4d252
MR
556 }
557
af02203f 558 free_fs_mount_list(&mounts);
e3d4d252
MR
559 return i;
560
561error:
af02203f 562 free_fs_mount_list(&mounts);
9e8aded4 563 qmp_guest_fsfreeze_thaw(NULL);
e3d4d252
MR
564 return 0;
565}
566
567/*
568 * Walk list of frozen file systems in the guest, and thaw them.
569 */
570int64_t qmp_guest_fsfreeze_thaw(Error **err)
571{
572 int ret;
af02203f
PB
573 FsMountList mounts;
574 FsMount *mount;
9e8aded4 575 int fd, i = 0, logged;
261551d1 576 Error *local_err = NULL;
9e8aded4
MR
577
578 QTAILQ_INIT(&mounts);
261551d1
LC
579 build_fs_mount_list(&mounts, &local_err);
580 if (error_is_set(&local_err)) {
581 error_propagate(err, local_err);
9e8aded4
MR
582 return 0;
583 }
e3d4d252 584
9e8aded4
MR
585 QTAILQ_FOREACH(mount, &mounts, next) {
586 logged = false;
e3d4d252
MR
587 fd = qemu_open(mount->dirname, O_RDONLY);
588 if (fd == -1) {
e3d4d252
MR
589 continue;
590 }
9e8aded4
MR
591 /* we have no way of knowing whether a filesystem was actually unfrozen
592 * as a result of a successful call to FITHAW, only that if an error
593 * was returned the filesystem was *not* unfrozen by that particular
594 * call.
595 *
a31f0531 596 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
9e8aded4
MR
597 * to unfreeze, continuing issuing FITHAW until an error is returned,
598 * in which case either the filesystem is in an unfreezable state, or,
599 * more likely, it was thawed previously (and remains so afterward).
600 *
601 * also, since the most recent successful call is the one that did
602 * the actual unfreeze, we can use this to provide an accurate count
603 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
604 * may * be useful for determining whether a filesystem was unfrozen
605 * during the freeze/thaw phase by a process other than qemu-ga.
606 */
607 do {
608 ret = ioctl(fd, FITHAW);
609 if (ret == 0 && !logged) {
610 i++;
611 logged = true;
612 }
613 } while (ret == 0);
e3d4d252 614 close(fd);
e3d4d252
MR
615 }
616
f22d85e9 617 ga_unset_frozen(ga_state);
af02203f 618 free_fs_mount_list(&mounts);
ec0f694c
TS
619
620 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW, err);
621
e3d4d252
MR
622 return i;
623}
624
e3d4d252
MR
625static void guest_fsfreeze_cleanup(void)
626{
e3d4d252
MR
627 Error *err = NULL;
628
f22d85e9 629 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
6f686749
MA
630 qmp_guest_fsfreeze_thaw(&err);
631 if (err) {
632 slog("failed to clean up frozen filesystems: %s",
633 error_get_pretty(err));
634 error_free(err);
e3d4d252
MR
635 }
636 }
637}
e72c3f2e 638#endif /* CONFIG_FSFREEZE */
e3d4d252 639
eab5fd59
PB
640#if defined(CONFIG_FSTRIM)
641/*
642 * Walk list of mounted file systems in the guest, and trim them.
643 */
644void qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **err)
645{
646 int ret = 0;
647 FsMountList mounts;
648 struct FsMount *mount;
649 int fd;
261551d1 650 Error *local_err = NULL;
eab5fd59
PB
651 struct fstrim_range r = {
652 .start = 0,
653 .len = -1,
654 .minlen = has_minimum ? minimum : 0,
655 };
656
657 slog("guest-fstrim called");
658
659 QTAILQ_INIT(&mounts);
261551d1
LC
660 build_fs_mount_list(&mounts, &local_err);
661 if (error_is_set(&local_err)) {
662 error_propagate(err, local_err);
eab5fd59
PB
663 return;
664 }
665
666 QTAILQ_FOREACH(mount, &mounts, next) {
667 fd = qemu_open(mount->dirname, O_RDONLY);
668 if (fd == -1) {
071673b0 669 error_setg_errno(err, errno, "failed to open %s", mount->dirname);
eab5fd59
PB
670 goto error;
671 }
672
673 /* We try to cull filesytems we know won't work in advance, but other
674 * filesytems may not implement fstrim for less obvious reasons. These
675 * will report EOPNOTSUPP; we simply ignore these errors. Any other
676 * error means an unexpected error, so return it in those cases. In
677 * some other cases ENOTTY will be reported (e.g. CD-ROMs).
678 */
679 ret = ioctl(fd, FITRIM, &r);
680 if (ret == -1) {
681 if (errno != ENOTTY && errno != EOPNOTSUPP) {
071673b0
LC
682 error_setg_errno(err, errno, "failed to trim %s",
683 mount->dirname);
eab5fd59
PB
684 close(fd);
685 goto error;
686 }
687 }
688 close(fd);
689 }
690
691error:
692 free_fs_mount_list(&mounts);
693}
694#endif /* CONFIG_FSTRIM */
695
696
11d0f125
LC
697#define LINUX_SYS_STATE_FILE "/sys/power/state"
698#define SUSPEND_SUPPORTED 0
699#define SUSPEND_NOT_SUPPORTED 1
700
11d0f125
LC
701static void bios_supports_mode(const char *pmutils_bin, const char *pmutils_arg,
702 const char *sysfile_str, Error **err)
703{
6b26e837 704 Error *local_err = NULL;
11d0f125 705 char *pmutils_path;
6b26e837 706 pid_t pid;
dc8764f0 707 int status;
11d0f125
LC
708
709 pmutils_path = g_find_program_in_path(pmutils_bin);
710
711 pid = fork();
712 if (!pid) {
dc8764f0
LC
713 char buf[32]; /* hopefully big enough */
714 ssize_t ret;
715 int fd;
11d0f125
LC
716
717 setsid();
11d0f125
LC
718 reopen_fd_to_null(0);
719 reopen_fd_to_null(1);
720 reopen_fd_to_null(2);
721
dc8764f0
LC
722 if (pmutils_path) {
723 execle(pmutils_path, pmutils_bin, pmutils_arg, NULL, environ);
724 }
11d0f125 725
dc8764f0
LC
726 /*
727 * If we get here either pm-utils is not installed or execle() has
728 * failed. Let's try the manual method if the caller wants it.
729 */
11d0f125 730
dc8764f0
LC
731 if (!sysfile_str) {
732 _exit(SUSPEND_NOT_SUPPORTED);
733 }
11d0f125 734
dc8764f0
LC
735 fd = open(LINUX_SYS_STATE_FILE, O_RDONLY);
736 if (fd < 0) {
11d0f125
LC
737 _exit(SUSPEND_NOT_SUPPORTED);
738 }
739
dc8764f0
LC
740 ret = read(fd, buf, sizeof(buf)-1);
741 if (ret <= 0) {
742 _exit(SUSPEND_NOT_SUPPORTED);
11d0f125 743 }
dc8764f0 744 buf[ret] = '\0';
11d0f125 745
dc8764f0
LC
746 if (strstr(buf, sysfile_str)) {
747 _exit(SUSPEND_SUPPORTED);
11d0f125
LC
748 }
749
dc8764f0 750 _exit(SUSPEND_NOT_SUPPORTED);
6b26e837
LC
751 } else if (pid < 0) {
752 error_setg_errno(err, errno, "failed to create child process");
753 goto out;
11d0f125
LC
754 }
755
6b26e837
LC
756 ga_wait_child(pid, &status, &local_err);
757 if (error_is_set(&local_err)) {
758 error_propagate(err, local_err);
759 goto out;
760 }
11d0f125 761
6b26e837
LC
762 if (!WIFEXITED(status)) {
763 error_setg(err, "child process has terminated abnormally");
764 goto out;
dc8764f0
LC
765 }
766
6b26e837
LC
767 switch (WEXITSTATUS(status)) {
768 case SUSPEND_SUPPORTED:
769 goto out;
770 case SUSPEND_NOT_SUPPORTED:
771 error_setg(err,
772 "the requested suspend mode is not supported by the guest");
773 goto out;
774 default:
775 error_setg(err,
776 "the helper program '%s' returned an unexpected exit status"
777 " code (%d)", pmutils_path, WEXITSTATUS(status));
778 goto out;
11d0f125
LC
779 }
780
6b26e837
LC
781out:
782 g_free(pmutils_path);
11d0f125
LC
783}
784
785static void guest_suspend(const char *pmutils_bin, const char *sysfile_str,
786 Error **err)
787{
7b376087 788 Error *local_err = NULL;
11d0f125 789 char *pmutils_path;
7b376087 790 pid_t pid;
dc8764f0 791 int status;
11d0f125
LC
792
793 pmutils_path = g_find_program_in_path(pmutils_bin);
794
795 pid = fork();
796 if (pid == 0) {
797 /* child */
798 int fd;
799
800 setsid();
801 reopen_fd_to_null(0);
802 reopen_fd_to_null(1);
803 reopen_fd_to_null(2);
804
805 if (pmutils_path) {
806 execle(pmutils_path, pmutils_bin, NULL, environ);
807 }
808
809 /*
810 * If we get here either pm-utils is not installed or execle() has
811 * failed. Let's try the manual method if the caller wants it.
812 */
813
814 if (!sysfile_str) {
815 _exit(EXIT_FAILURE);
816 }
817
818 fd = open(LINUX_SYS_STATE_FILE, O_WRONLY);
819 if (fd < 0) {
820 _exit(EXIT_FAILURE);
821 }
822
823 if (write(fd, sysfile_str, strlen(sysfile_str)) < 0) {
824 _exit(EXIT_FAILURE);
825 }
826
827 _exit(EXIT_SUCCESS);
7b376087
LC
828 } else if (pid < 0) {
829 error_setg_errno(err, errno, "failed to create child process");
830 goto out;
11d0f125
LC
831 }
832
7b376087
LC
833 ga_wait_child(pid, &status, &local_err);
834 if (error_is_set(&local_err)) {
835 error_propagate(err, local_err);
836 goto out;
837 }
11d0f125 838
7b376087
LC
839 if (!WIFEXITED(status)) {
840 error_setg(err, "child process has terminated abnormally");
841 goto out;
dc8764f0
LC
842 }
843
7b376087
LC
844 if (WEXITSTATUS(status)) {
845 error_setg(err, "child process has failed to suspend");
846 goto out;
11d0f125 847 }
dc8764f0 848
7b376087
LC
849out:
850 g_free(pmutils_path);
11d0f125
LC
851}
852
853void qmp_guest_suspend_disk(Error **err)
854{
855 bios_supports_mode("pm-is-supported", "--hibernate", "disk", err);
856 if (error_is_set(err)) {
857 return;
858 }
859
860 guest_suspend("pm-hibernate", "disk", err);
861}
862
fbf42210
LC
863void qmp_guest_suspend_ram(Error **err)
864{
865 bios_supports_mode("pm-is-supported", "--suspend", "mem", err);
866 if (error_is_set(err)) {
867 return;
868 }
869
870 guest_suspend("pm-suspend", "mem", err);
871}
872
95f4f404
LC
873void qmp_guest_suspend_hybrid(Error **err)
874{
875 bios_supports_mode("pm-is-supported", "--suspend-hybrid", NULL, err);
876 if (error_is_set(err)) {
877 return;
878 }
879
880 guest_suspend("pm-suspend-hybrid", NULL, err);
881}
882
3424fc9f
MP
883static GuestNetworkInterfaceList *
884guest_find_interface(GuestNetworkInterfaceList *head,
885 const char *name)
886{
887 for (; head; head = head->next) {
888 if (strcmp(head->value->name, name) == 0) {
889 break;
890 }
891 }
892
893 return head;
894}
895
896/*
897 * Build information about guest interfaces
898 */
899GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
900{
901 GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
902 struct ifaddrs *ifap, *ifa;
3424fc9f
MP
903
904 if (getifaddrs(&ifap) < 0) {
878a0ae0 905 error_setg_errno(errp, errno, "getifaddrs failed");
3424fc9f
MP
906 goto error;
907 }
908
909 for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
910 GuestNetworkInterfaceList *info;
911 GuestIpAddressList **address_list = NULL, *address_item = NULL;
912 char addr4[INET_ADDRSTRLEN];
913 char addr6[INET6_ADDRSTRLEN];
914 int sock;
915 struct ifreq ifr;
916 unsigned char *mac_addr;
917 void *p;
918
919 g_debug("Processing %s interface", ifa->ifa_name);
920
921 info = guest_find_interface(head, ifa->ifa_name);
922
923 if (!info) {
924 info = g_malloc0(sizeof(*info));
925 info->value = g_malloc0(sizeof(*info->value));
926 info->value->name = g_strdup(ifa->ifa_name);
927
928 if (!cur_item) {
929 head = cur_item = info;
930 } else {
931 cur_item->next = info;
932 cur_item = info;
933 }
934 }
935
936 if (!info->value->has_hardware_address &&
937 ifa->ifa_flags & SIOCGIFHWADDR) {
938 /* we haven't obtained HW address yet */
939 sock = socket(PF_INET, SOCK_STREAM, 0);
940 if (sock == -1) {
878a0ae0 941 error_setg_errno(errp, errno, "failed to create socket");
3424fc9f
MP
942 goto error;
943 }
944
945 memset(&ifr, 0, sizeof(ifr));
1ab516ed 946 pstrcpy(ifr.ifr_name, IF_NAMESIZE, info->value->name);
3424fc9f 947 if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {
878a0ae0
LC
948 error_setg_errno(errp, errno,
949 "failed to get MAC address of %s",
950 ifa->ifa_name);
10a2158f 951 close(sock);
3424fc9f
MP
952 goto error;
953 }
954
10a2158f 955 close(sock);
3424fc9f
MP
956 mac_addr = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
957
e4ada482
SW
958 info->value->hardware_address =
959 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
960 (int) mac_addr[0], (int) mac_addr[1],
961 (int) mac_addr[2], (int) mac_addr[3],
962 (int) mac_addr[4], (int) mac_addr[5]);
3424fc9f
MP
963
964 info->value->has_hardware_address = true;
3424fc9f
MP
965 }
966
967 if (ifa->ifa_addr &&
968 ifa->ifa_addr->sa_family == AF_INET) {
969 /* interface with IPv4 address */
3424fc9f
MP
970 p = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
971 if (!inet_ntop(AF_INET, p, addr4, sizeof(addr4))) {
878a0ae0 972 error_setg_errno(errp, errno, "inet_ntop failed");
3424fc9f
MP
973 goto error;
974 }
975
10a2158f
MA
976 address_item = g_malloc0(sizeof(*address_item));
977 address_item->value = g_malloc0(sizeof(*address_item->value));
3424fc9f
MP
978 address_item->value->ip_address = g_strdup(addr4);
979 address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
980
981 if (ifa->ifa_netmask) {
982 /* Count the number of set bits in netmask.
983 * This is safe as '1' and '0' cannot be shuffled in netmask. */
984 p = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
985 address_item->value->prefix = ctpop32(((uint32_t *) p)[0]);
986 }
987 } else if (ifa->ifa_addr &&
988 ifa->ifa_addr->sa_family == AF_INET6) {
989 /* interface with IPv6 address */
3424fc9f
MP
990 p = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
991 if (!inet_ntop(AF_INET6, p, addr6, sizeof(addr6))) {
878a0ae0 992 error_setg_errno(errp, errno, "inet_ntop failed");
3424fc9f
MP
993 goto error;
994 }
995
10a2158f
MA
996 address_item = g_malloc0(sizeof(*address_item));
997 address_item->value = g_malloc0(sizeof(*address_item->value));
3424fc9f
MP
998 address_item->value->ip_address = g_strdup(addr6);
999 address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
1000
1001 if (ifa->ifa_netmask) {
1002 /* Count the number of set bits in netmask.
1003 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1004 p = &((struct sockaddr_in6 *)ifa->ifa_netmask)->sin6_addr;
1005 address_item->value->prefix =
1006 ctpop32(((uint32_t *) p)[0]) +
1007 ctpop32(((uint32_t *) p)[1]) +
1008 ctpop32(((uint32_t *) p)[2]) +
1009 ctpop32(((uint32_t *) p)[3]);
1010 }
1011 }
1012
1013 if (!address_item) {
1014 continue;
1015 }
1016
1017 address_list = &info->value->ip_addresses;
1018
1019 while (*address_list && (*address_list)->next) {
1020 address_list = &(*address_list)->next;
1021 }
1022
1023 if (!*address_list) {
1024 *address_list = address_item;
1025 } else {
1026 (*address_list)->next = address_item;
1027 }
1028
1029 info->value->has_ip_addresses = true;
1030
1031
1032 }
1033
1034 freeifaddrs(ifap);
1035 return head;
1036
1037error:
1038 freeifaddrs(ifap);
1039 qapi_free_GuestNetworkInterfaceList(head);
1040 return NULL;
1041}
1042
e72c3f2e
MR
1043#else /* defined(__linux__) */
1044
d35d4cb5 1045void qmp_guest_suspend_disk(Error **err)
e72c3f2e
MR
1046{
1047 error_set(err, QERR_UNSUPPORTED);
e72c3f2e
MR
1048}
1049
d35d4cb5 1050void qmp_guest_suspend_ram(Error **err)
e72c3f2e
MR
1051{
1052 error_set(err, QERR_UNSUPPORTED);
e72c3f2e
MR
1053}
1054
d35d4cb5 1055void qmp_guest_suspend_hybrid(Error **err)
e72c3f2e
MR
1056{
1057 error_set(err, QERR_UNSUPPORTED);
e72c3f2e
MR
1058}
1059
d35d4cb5 1060GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
e72c3f2e 1061{
d35d4cb5
MR
1062 error_set(errp, QERR_UNSUPPORTED);
1063 return NULL;
e72c3f2e
MR
1064}
1065
d35d4cb5
MR
1066#endif
1067
1068#if !defined(CONFIG_FSFREEZE)
1069
1070GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **err)
e72c3f2e
MR
1071{
1072 error_set(err, QERR_UNSUPPORTED);
d35d4cb5
MR
1073
1074 return 0;
e72c3f2e
MR
1075}
1076
d35d4cb5 1077int64_t qmp_guest_fsfreeze_freeze(Error **err)
e72c3f2e
MR
1078{
1079 error_set(err, QERR_UNSUPPORTED);
d35d4cb5
MR
1080
1081 return 0;
e72c3f2e
MR
1082}
1083
d35d4cb5 1084int64_t qmp_guest_fsfreeze_thaw(Error **err)
e72c3f2e 1085{
d35d4cb5
MR
1086 error_set(err, QERR_UNSUPPORTED);
1087
1088 return 0;
e72c3f2e 1089}
eab5fd59
PB
1090#endif /* CONFIG_FSFREEZE */
1091
1092#if !defined(CONFIG_FSTRIM)
1093void qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **err)
1094{
1095 error_set(err, QERR_UNSUPPORTED);
eab5fd59 1096}
e72c3f2e
MR
1097#endif
1098
e3d4d252
MR
1099/* register init/cleanup routines for stateful command groups */
1100void ga_command_state_init(GAState *s, GACommandState *cs)
1101{
7006b9cf 1102#if defined(CONFIG_FSFREEZE)
f22d85e9 1103 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
7006b9cf 1104#endif
e3d4d252
MR
1105 ga_command_state_add(cs, guest_file_init, NULL);
1106}