]> git.proxmox.com Git - mirror_qemu.git/blame - qga/commands-posix.c
qga: win32 qmp_guest_network_get_interfaces implementation
[mirror_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>
d2baff62
LE
18#include <unistd.h>
19#include <errno.h>
20#include <fcntl.h>
46d4c572 21#include <dirent.h>
c689b4f1
LE
22#include <stdio.h>
23#include <string.h>
24#include <sys/stat.h>
d2baff62 25#include <inttypes.h>
e72c3f2e
MR
26#include "qga/guest-agent-core.h"
27#include "qga-qmp-commands.h"
7b1b5d19 28#include "qapi/qmp/qerror.h"
1de7afc9
PB
29#include "qemu/queue.h"
30#include "qemu/host-utils.h"
4eb36d40 31
2c02cbf6 32#ifndef CONFIG_HAS_ENVIRON
eecae147
AF
33#ifdef __APPLE__
34#include <crt_externs.h>
35#define environ (*_NSGetEnviron())
36#else
2c02cbf6
LC
37extern char **environ;
38#endif
eecae147 39#endif
2c02cbf6 40
4eb36d40 41#if defined(__linux__)
e3d4d252 42#include <mntent.h>
7006b9cf 43#include <linux/fs.h>
3424fc9f
MP
44#include <ifaddrs.h>
45#include <arpa/inet.h>
46#include <sys/socket.h>
47#include <net/if.h>
e3d4d252 48
eab5fd59 49#ifdef FIFREEZE
e72c3f2e
MR
50#define CONFIG_FSFREEZE
51#endif
eab5fd59
PB
52#ifdef FITRIM
53#define CONFIG_FSTRIM
54#endif
e72c3f2e
MR
55#endif
56
77dbc81b 57static void ga_wait_child(pid_t pid, int *status, Error **errp)
d220a6df
LC
58{
59 pid_t rpid;
60
61 *status = 0;
62
63 do {
64 rpid = waitpid(pid, status, 0);
65 } while (rpid == -1 && errno == EINTR);
66
67 if (rpid == -1) {
77dbc81b
MA
68 error_setg_errno(errp, errno, "failed to wait for child (pid: %d)",
69 pid);
d220a6df
LC
70 return;
71 }
72
73 g_assert(rpid == pid);
74}
75
77dbc81b 76void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
e3d4d252 77{
e3d4d252 78 const char *shutdown_flag;
d220a6df
LC
79 Error *local_err = NULL;
80 pid_t pid;
3674838c 81 int status;
e3d4d252
MR
82
83 slog("guest-shutdown called, mode: %s", mode);
84 if (!has_mode || strcmp(mode, "powerdown") == 0) {
85 shutdown_flag = "-P";
86 } else if (strcmp(mode, "halt") == 0) {
87 shutdown_flag = "-H";
88 } else if (strcmp(mode, "reboot") == 0) {
89 shutdown_flag = "-r";
90 } else {
77dbc81b 91 error_setg(errp,
d220a6df 92 "mode is invalid (valid values are: halt|powerdown|reboot");
e3d4d252
MR
93 return;
94 }
95
d5dd3498
LC
96 pid = fork();
97 if (pid == 0) {
e3d4d252
MR
98 /* child, start the shutdown */
99 setsid();
3674838c
LC
100 reopen_fd_to_null(0);
101 reopen_fd_to_null(1);
102 reopen_fd_to_null(2);
e3d4d252 103
485e741c 104 execle("/sbin/shutdown", "shutdown", "-h", shutdown_flag, "+0",
3674838c
LC
105 "hypervisor initiated shutdown", (char*)NULL, environ);
106 _exit(EXIT_FAILURE);
d5dd3498 107 } else if (pid < 0) {
77dbc81b 108 error_setg_errno(errp, errno, "failed to create child process");
d220a6df 109 return;
e3d4d252 110 }
d5dd3498 111
d220a6df 112 ga_wait_child(pid, &status, &local_err);
84d18f06 113 if (local_err) {
77dbc81b 114 error_propagate(errp, local_err);
d220a6df
LC
115 return;
116 }
117
118 if (!WIFEXITED(status)) {
77dbc81b 119 error_setg(errp, "child process has terminated abnormally");
d220a6df
LC
120 return;
121 }
122
123 if (WEXITSTATUS(status)) {
77dbc81b 124 error_setg(errp, "child process has failed to shutdown");
d5dd3498
LC
125 return;
126 }
127
085d8134 128 /* succeeded */
e3d4d252
MR
129}
130
6912e6a9
LL
131int64_t qmp_guest_get_time(Error **errp)
132{
133 int ret;
134 qemu_timeval tq;
135 int64_t time_ns;
136
137 ret = qemu_gettimeofday(&tq);
138 if (ret < 0) {
139 error_setg_errno(errp, errno, "Failed to get time");
140 return -1;
141 }
142
143 time_ns = tq.tv_sec * 1000000000LL + tq.tv_usec * 1000;
144 return time_ns;
145}
146
2c958923 147void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
a1bca57f
LL
148{
149 int ret;
150 int status;
151 pid_t pid;
152 Error *local_err = NULL;
153 struct timeval tv;
154
2c958923
MP
155 /* If user has passed a time, validate and set it. */
156 if (has_time) {
157 /* year-2038 will overflow in case time_t is 32bit */
158 if (time_ns / 1000000000 != (time_t)(time_ns / 1000000000)) {
159 error_setg(errp, "Time %" PRId64 " is too large", time_ns);
160 return;
161 }
162
163 tv.tv_sec = time_ns / 1000000000;
164 tv.tv_usec = (time_ns % 1000000000) / 1000;
165
166 ret = settimeofday(&tv, NULL);
167 if (ret < 0) {
168 error_setg_errno(errp, errno, "Failed to set time to guest");
169 return;
170 }
a1bca57f
LL
171 }
172
2c958923
MP
173 /* Now, if user has passed a time to set and the system time is set, we
174 * just need to synchronize the hardware clock. However, if no time was
175 * passed, user is requesting the opposite: set the system time from the
1634df56 176 * hardware clock (RTC). */
a1bca57f
LL
177 pid = fork();
178 if (pid == 0) {
179 setsid();
180 reopen_fd_to_null(0);
181 reopen_fd_to_null(1);
182 reopen_fd_to_null(2);
183
2c958923
MP
184 /* Use '/sbin/hwclock -w' to set RTC from the system time,
185 * or '/sbin/hwclock -s' to set the system time from RTC. */
186 execle("/sbin/hwclock", "hwclock", has_time ? "-w" : "-s",
187 NULL, environ);
a1bca57f
LL
188 _exit(EXIT_FAILURE);
189 } else if (pid < 0) {
190 error_setg_errno(errp, errno, "failed to create child process");
191 return;
192 }
193
194 ga_wait_child(pid, &status, &local_err);
84d18f06 195 if (local_err) {
a1bca57f
LL
196 error_propagate(errp, local_err);
197 return;
198 }
199
200 if (!WIFEXITED(status)) {
201 error_setg(errp, "child process has terminated abnormally");
202 return;
203 }
204
205 if (WEXITSTATUS(status)) {
206 error_setg(errp, "hwclock failed to set hardware clock to system time");
207 return;
208 }
209}
210
e3d4d252
MR
211typedef struct GuestFileHandle {
212 uint64_t id;
213 FILE *fh;
214 QTAILQ_ENTRY(GuestFileHandle) next;
215} GuestFileHandle;
216
217static struct {
218 QTAILQ_HEAD(, GuestFileHandle) filehandles;
219} guest_file_state;
220
39097daf 221static int64_t guest_file_handle_add(FILE *fh, Error **errp)
e3d4d252
MR
222{
223 GuestFileHandle *gfh;
39097daf
MR
224 int64_t handle;
225
226 handle = ga_get_fd_handle(ga_state, errp);
a903f40c
MA
227 if (handle < 0) {
228 return -1;
39097daf 229 }
e3d4d252 230
7267c094 231 gfh = g_malloc0(sizeof(GuestFileHandle));
39097daf 232 gfh->id = handle;
e3d4d252
MR
233 gfh->fh = fh;
234 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
39097daf
MR
235
236 return handle;
e3d4d252
MR
237}
238
77dbc81b 239static GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
e3d4d252
MR
240{
241 GuestFileHandle *gfh;
242
243 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next)
244 {
245 if (gfh->id == id) {
246 return gfh;
247 }
248 }
249
77dbc81b 250 error_setg(errp, "handle '%" PRId64 "' has not been found", id);
e3d4d252
MR
251 return NULL;
252}
253
c689b4f1
LE
254typedef const char * const ccpc;
255
8fe6bbca
LE
256#ifndef O_BINARY
257#define O_BINARY 0
258#endif
259
c689b4f1
LE
260/* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
261static const struct {
262 ccpc *forms;
263 int oflag_base;
264} guest_file_open_modes[] = {
8fe6bbca
LE
265 { (ccpc[]){ "r", NULL }, O_RDONLY },
266 { (ccpc[]){ "rb", NULL }, O_RDONLY | O_BINARY },
267 { (ccpc[]){ "w", NULL }, O_WRONLY | O_CREAT | O_TRUNC },
268 { (ccpc[]){ "wb", NULL }, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY },
269 { (ccpc[]){ "a", NULL }, O_WRONLY | O_CREAT | O_APPEND },
270 { (ccpc[]){ "ab", NULL }, O_WRONLY | O_CREAT | O_APPEND | O_BINARY },
271 { (ccpc[]){ "r+", NULL }, O_RDWR },
272 { (ccpc[]){ "rb+", "r+b", NULL }, O_RDWR | O_BINARY },
273 { (ccpc[]){ "w+", NULL }, O_RDWR | O_CREAT | O_TRUNC },
274 { (ccpc[]){ "wb+", "w+b", NULL }, O_RDWR | O_CREAT | O_TRUNC | O_BINARY },
275 { (ccpc[]){ "a+", NULL }, O_RDWR | O_CREAT | O_APPEND },
276 { (ccpc[]){ "ab+", "a+b", NULL }, O_RDWR | O_CREAT | O_APPEND | O_BINARY }
c689b4f1
LE
277};
278
279static int
77dbc81b 280find_open_flag(const char *mode_str, Error **errp)
c689b4f1
LE
281{
282 unsigned mode;
283
284 for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
285 ccpc *form;
286
287 form = guest_file_open_modes[mode].forms;
288 while (*form != NULL && strcmp(*form, mode_str) != 0) {
289 ++form;
290 }
291 if (*form != NULL) {
292 break;
293 }
294 }
295
296 if (mode == ARRAY_SIZE(guest_file_open_modes)) {
77dbc81b 297 error_setg(errp, "invalid file open mode '%s'", mode_str);
c689b4f1
LE
298 return -1;
299 }
300 return guest_file_open_modes[mode].oflag_base | O_NOCTTY | O_NONBLOCK;
301}
302
303#define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
304 S_IRGRP | S_IWGRP | \
305 S_IROTH | S_IWOTH)
306
307static FILE *
77dbc81b 308safe_open_or_create(const char *path, const char *mode, Error **errp)
c689b4f1
LE
309{
310 Error *local_err = NULL;
311 int oflag;
312
313 oflag = find_open_flag(mode, &local_err);
314 if (local_err == NULL) {
315 int fd;
316
317 /* If the caller wants / allows creation of a new file, we implement it
318 * with a two step process: open() + (open() / fchmod()).
319 *
320 * First we insist on creating the file exclusively as a new file. If
321 * that succeeds, we're free to set any file-mode bits on it. (The
322 * motivation is that we want to set those file-mode bits independently
323 * of the current umask.)
324 *
325 * If the exclusive creation fails because the file already exists
326 * (EEXIST is not possible for any other reason), we just attempt to
327 * open the file, but in this case we won't be allowed to change the
328 * file-mode bits on the preexistent file.
329 *
330 * The pathname should never disappear between the two open()s in
331 * practice. If it happens, then someone very likely tried to race us.
332 * In this case just go ahead and report the ENOENT from the second
333 * open() to the caller.
334 *
335 * If the caller wants to open a preexistent file, then the first
336 * open() is decisive and its third argument is ignored, and the second
337 * open() and the fchmod() are never called.
338 */
339 fd = open(path, oflag | ((oflag & O_CREAT) ? O_EXCL : 0), 0);
340 if (fd == -1 && errno == EEXIST) {
341 oflag &= ~(unsigned)O_CREAT;
342 fd = open(path, oflag);
343 }
344
345 if (fd == -1) {
346 error_setg_errno(&local_err, errno, "failed to open file '%s' "
347 "(mode: '%s')", path, mode);
348 } else {
349 qemu_set_cloexec(fd);
350
351 if ((oflag & O_CREAT) && fchmod(fd, DEFAULT_NEW_FILE_MODE) == -1) {
352 error_setg_errno(&local_err, errno, "failed to set permission "
353 "0%03o on new file '%s' (mode: '%s')",
354 (unsigned)DEFAULT_NEW_FILE_MODE, path, mode);
355 } else {
356 FILE *f;
357
358 f = fdopen(fd, mode);
359 if (f == NULL) {
360 error_setg_errno(&local_err, errno, "failed to associate "
361 "stdio stream with file descriptor %d, "
362 "file '%s' (mode: '%s')", fd, path, mode);
363 } else {
364 return f;
365 }
366 }
367
368 close(fd);
2b720018
LE
369 if (oflag & O_CREAT) {
370 unlink(path);
371 }
c689b4f1
LE
372 }
373 }
374
77dbc81b 375 error_propagate(errp, local_err);
c689b4f1
LE
376 return NULL;
377}
378
85b6f6f5
SZ
379static int guest_file_toggle_flags(int fd, int flags, bool set, Error **err)
380{
381 int ret, old_flags;
382
383 old_flags = fcntl(fd, F_GETFL);
384 if (old_flags == -1) {
c6bd8c70
MA
385 error_setg_errno(err, errno, QERR_QGA_COMMAND_FAILED,
386 "failed to fetch filehandle flags");
85b6f6f5
SZ
387 return -1;
388 }
389
390 ret = fcntl(fd, F_SETFL, set ? (old_flags | flags) : (old_flags & ~flags));
391 if (ret == -1) {
c6bd8c70
MA
392 error_setg_errno(err, errno, QERR_QGA_COMMAND_FAILED,
393 "failed to set filehandle flags");
85b6f6f5
SZ
394 return -1;
395 }
396
397 return ret;
398}
399
77dbc81b
MA
400int64_t qmp_guest_file_open(const char *path, bool has_mode, const char *mode,
401 Error **errp)
e3d4d252
MR
402{
403 FILE *fh;
c689b4f1 404 Error *local_err = NULL;
85b6f6f5 405 int64_t handle;
e3d4d252
MR
406
407 if (!has_mode) {
408 mode = "r";
409 }
410 slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
c689b4f1
LE
411 fh = safe_open_or_create(path, mode, &local_err);
412 if (local_err != NULL) {
77dbc81b 413 error_propagate(errp, local_err);
e3d4d252
MR
414 return -1;
415 }
416
417 /* set fd non-blocking to avoid common use cases (like reading from a
418 * named pipe) from hanging the agent
419 */
85b6f6f5 420 if (guest_file_toggle_flags(fileno(fh), O_NONBLOCK, true, errp) < 0) {
e3d4d252
MR
421 fclose(fh);
422 return -1;
423 }
424
77dbc81b 425 handle = guest_file_handle_add(fh, errp);
a903f40c 426 if (handle < 0) {
39097daf
MR
427 fclose(fh);
428 return -1;
429 }
430
d607a523 431 slog("guest-file-open, handle: %" PRId64, handle);
39097daf 432 return handle;
e3d4d252
MR
433}
434
77dbc81b 435void qmp_guest_file_close(int64_t handle, Error **errp)
e3d4d252 436{
77dbc81b 437 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
e3d4d252
MR
438 int ret;
439
d607a523 440 slog("guest-file-close called, handle: %" PRId64, handle);
e3d4d252 441 if (!gfh) {
e3d4d252
MR
442 return;
443 }
444
445 ret = fclose(gfh->fh);
3ac4b7c5 446 if (ret == EOF) {
77dbc81b 447 error_setg_errno(errp, errno, "failed to close handle");
e3d4d252
MR
448 return;
449 }
450
451 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
7267c094 452 g_free(gfh);
e3d4d252
MR
453}
454
455struct GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
77dbc81b 456 int64_t count, Error **errp)
e3d4d252 457{
77dbc81b 458 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
e3d4d252
MR
459 GuestFileRead *read_data = NULL;
460 guchar *buf;
461 FILE *fh;
462 size_t read_count;
463
464 if (!gfh) {
e3d4d252
MR
465 return NULL;
466 }
467
468 if (!has_count) {
469 count = QGA_READ_COUNT_DEFAULT;
470 } else if (count < 0) {
77dbc81b 471 error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
db3edb66 472 count);
e3d4d252
MR
473 return NULL;
474 }
475
476 fh = gfh->fh;
7267c094 477 buf = g_malloc0(count+1);
e3d4d252
MR
478 read_count = fread(buf, 1, count, fh);
479 if (ferror(fh)) {
77dbc81b 480 error_setg_errno(errp, errno, "failed to read file");
d607a523 481 slog("guest-file-read failed, handle: %" PRId64, handle);
e3d4d252
MR
482 } else {
483 buf[read_count] = 0;
7267c094 484 read_data = g_malloc0(sizeof(GuestFileRead));
e3d4d252
MR
485 read_data->count = read_count;
486 read_data->eof = feof(fh);
487 if (read_count) {
488 read_data->buf_b64 = g_base64_encode(buf, read_count);
489 }
490 }
7267c094 491 g_free(buf);
e3d4d252
MR
492 clearerr(fh);
493
494 return read_data;
495}
496
497GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
77dbc81b
MA
498 bool has_count, int64_t count,
499 Error **errp)
e3d4d252
MR
500{
501 GuestFileWrite *write_data = NULL;
502 guchar *buf;
503 gsize buf_len;
504 int write_count;
77dbc81b 505 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
e3d4d252
MR
506 FILE *fh;
507
508 if (!gfh) {
e3d4d252
MR
509 return NULL;
510 }
511
512 fh = gfh->fh;
513 buf = g_base64_decode(buf_b64, &buf_len);
514
515 if (!has_count) {
516 count = buf_len;
517 } else if (count < 0 || count > buf_len) {
77dbc81b 518 error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
db3edb66 519 count);
7267c094 520 g_free(buf);
e3d4d252
MR
521 return NULL;
522 }
523
524 write_count = fwrite(buf, 1, count, fh);
525 if (ferror(fh)) {
77dbc81b 526 error_setg_errno(errp, errno, "failed to write to file");
d607a523 527 slog("guest-file-write failed, handle: %" PRId64, handle);
e3d4d252 528 } else {
7267c094 529 write_data = g_malloc0(sizeof(GuestFileWrite));
e3d4d252
MR
530 write_data->count = write_count;
531 write_data->eof = feof(fh);
532 }
7267c094 533 g_free(buf);
e3d4d252
MR
534 clearerr(fh);
535
536 return write_data;
537}
538
539struct GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
77dbc81b 540 int64_t whence, Error **errp)
e3d4d252 541{
77dbc81b 542 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
e3d4d252
MR
543 GuestFileSeek *seek_data = NULL;
544 FILE *fh;
545 int ret;
546
547 if (!gfh) {
e3d4d252
MR
548 return NULL;
549 }
550
551 fh = gfh->fh;
552 ret = fseek(fh, offset, whence);
553 if (ret == -1) {
77dbc81b 554 error_setg_errno(errp, errno, "failed to seek file");
e3d4d252 555 } else {
10b7c5dd 556 seek_data = g_new0(GuestFileSeek, 1);
e3d4d252
MR
557 seek_data->position = ftell(fh);
558 seek_data->eof = feof(fh);
559 }
560 clearerr(fh);
561
562 return seek_data;
563}
564
77dbc81b 565void qmp_guest_file_flush(int64_t handle, Error **errp)
e3d4d252 566{
77dbc81b 567 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
e3d4d252
MR
568 FILE *fh;
569 int ret;
570
571 if (!gfh) {
e3d4d252
MR
572 return;
573 }
574
575 fh = gfh->fh;
576 ret = fflush(fh);
577 if (ret == EOF) {
77dbc81b 578 error_setg_errno(errp, errno, "failed to flush file");
e3d4d252
MR
579 }
580}
581
582static void guest_file_init(void)
583{
584 QTAILQ_INIT(&guest_file_state.filehandles);
585}
586
e72c3f2e
MR
587/* linux-specific implementations. avoid this if at all possible. */
588#if defined(__linux__)
589
eab5fd59 590#if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
af02203f 591typedef struct FsMount {
e3d4d252
MR
592 char *dirname;
593 char *devtype;
46d4c572 594 unsigned int devmajor, devminor;
af02203f
PB
595 QTAILQ_ENTRY(FsMount) next;
596} FsMount;
e3d4d252 597
e5d9adbd 598typedef QTAILQ_HEAD(FsMountList, FsMount) FsMountList;
9e8aded4 599
af02203f 600static void free_fs_mount_list(FsMountList *mounts)
9e8aded4 601{
af02203f 602 FsMount *mount, *temp;
9e8aded4
MR
603
604 if (!mounts) {
605 return;
606 }
607
608 QTAILQ_FOREACH_SAFE(mount, mounts, next, temp) {
609 QTAILQ_REMOVE(mounts, mount, next);
610 g_free(mount->dirname);
611 g_free(mount->devtype);
612 g_free(mount);
613 }
614}
615
46d4c572
TS
616static int dev_major_minor(const char *devpath,
617 unsigned int *devmajor, unsigned int *devminor)
618{
619 struct stat st;
620
621 *devmajor = 0;
622 *devminor = 0;
623
624 if (stat(devpath, &st) < 0) {
625 slog("failed to stat device file '%s': %s", devpath, strerror(errno));
626 return -1;
627 }
628 if (S_ISDIR(st.st_mode)) {
629 /* It is bind mount */
630 return -2;
631 }
632 if (S_ISBLK(st.st_mode)) {
633 *devmajor = major(st.st_rdev);
634 *devminor = minor(st.st_rdev);
635 return 0;
636 }
637 return -1;
638}
639
e3d4d252
MR
640/*
641 * Walk the mount table and build a list of local file systems
642 */
46d4c572 643static void build_fs_mount_list_from_mtab(FsMountList *mounts, Error **errp)
e3d4d252
MR
644{
645 struct mntent *ment;
af02203f 646 FsMount *mount;
9e2fa418 647 char const *mtab = "/proc/self/mounts";
e3d4d252 648 FILE *fp;
46d4c572 649 unsigned int devmajor, devminor;
e3d4d252 650
e3d4d252
MR
651 fp = setmntent(mtab, "r");
652 if (!fp) {
77dbc81b 653 error_setg(errp, "failed to open mtab file: '%s'", mtab);
261551d1 654 return;
e3d4d252
MR
655 }
656
657 while ((ment = getmntent(fp))) {
658 /*
659 * An entry which device name doesn't start with a '/' is
660 * either a dummy file system or a network file system.
661 * Add special handling for smbfs and cifs as is done by
662 * coreutils as well.
663 */
664 if ((ment->mnt_fsname[0] != '/') ||
665 (strcmp(ment->mnt_type, "smbfs") == 0) ||
666 (strcmp(ment->mnt_type, "cifs") == 0)) {
667 continue;
668 }
46d4c572
TS
669 if (dev_major_minor(ment->mnt_fsname, &devmajor, &devminor) == -2) {
670 /* Skip bind mounts */
671 continue;
672 }
e3d4d252 673
af02203f 674 mount = g_malloc0(sizeof(FsMount));
7267c094
AL
675 mount->dirname = g_strdup(ment->mnt_dir);
676 mount->devtype = g_strdup(ment->mnt_type);
46d4c572
TS
677 mount->devmajor = devmajor;
678 mount->devminor = devminor;
e3d4d252 679
9e8aded4 680 QTAILQ_INSERT_TAIL(mounts, mount, next);
e3d4d252
MR
681 }
682
683 endmntent(fp);
e3d4d252 684}
46d4c572
TS
685
686static void decode_mntname(char *name, int len)
687{
688 int i, j = 0;
689 for (i = 0; i <= len; i++) {
690 if (name[i] != '\\') {
691 name[j++] = name[i];
692 } else if (name[i + 1] == '\\') {
693 name[j++] = '\\';
694 i++;
695 } else if (name[i + 1] >= '0' && name[i + 1] <= '3' &&
696 name[i + 2] >= '0' && name[i + 2] <= '7' &&
697 name[i + 3] >= '0' && name[i + 3] <= '7') {
698 name[j++] = (name[i + 1] - '0') * 64 +
699 (name[i + 2] - '0') * 8 +
700 (name[i + 3] - '0');
701 i += 3;
702 } else {
703 name[j++] = name[i];
704 }
705 }
706}
707
708static void build_fs_mount_list(FsMountList *mounts, Error **errp)
709{
710 FsMount *mount;
711 char const *mountinfo = "/proc/self/mountinfo";
712 FILE *fp;
713 char *line = NULL, *dash;
714 size_t n;
715 char check;
716 unsigned int devmajor, devminor;
717 int ret, dir_s, dir_e, type_s, type_e, dev_s, dev_e;
718
719 fp = fopen(mountinfo, "r");
720 if (!fp) {
721 build_fs_mount_list_from_mtab(mounts, errp);
722 return;
723 }
724
725 while (getline(&line, &n, fp) != -1) {
726 ret = sscanf(line, "%*u %*u %u:%u %*s %n%*s%n%c",
727 &devmajor, &devminor, &dir_s, &dir_e, &check);
728 if (ret < 3) {
729 continue;
730 }
731 dash = strstr(line + dir_e, " - ");
732 if (!dash) {
733 continue;
734 }
735 ret = sscanf(dash, " - %n%*s%n %n%*s%n%c",
736 &type_s, &type_e, &dev_s, &dev_e, &check);
737 if (ret < 1) {
738 continue;
739 }
740 line[dir_e] = 0;
741 dash[type_e] = 0;
742 dash[dev_e] = 0;
743 decode_mntname(line + dir_s, dir_e - dir_s);
744 decode_mntname(dash + dev_s, dev_e - dev_s);
745 if (devmajor == 0) {
746 /* btrfs reports major number = 0 */
747 if (strcmp("btrfs", dash + type_s) != 0 ||
748 dev_major_minor(dash + dev_s, &devmajor, &devminor) < 0) {
749 continue;
750 }
751 }
752
753 mount = g_malloc0(sizeof(FsMount));
754 mount->dirname = g_strdup(line + dir_s);
755 mount->devtype = g_strdup(dash + type_s);
756 mount->devmajor = devmajor;
757 mount->devminor = devminor;
758
759 QTAILQ_INSERT_TAIL(mounts, mount, next);
760 }
761 free(line);
762
763 fclose(fp);
764}
eab5fd59
PB
765#endif
766
767#if defined(CONFIG_FSFREEZE)
e3d4d252 768
46d4c572
TS
769static char *get_pci_driver(char const *syspath, int pathlen, Error **errp)
770{
771 char *path;
772 char *dpath;
773 char *driver = NULL;
774 char buf[PATH_MAX];
775 ssize_t len;
776
777 path = g_strndup(syspath, pathlen);
778 dpath = g_strdup_printf("%s/driver", path);
779 len = readlink(dpath, buf, sizeof(buf) - 1);
780 if (len != -1) {
781 buf[len] = 0;
782 driver = g_strdup(basename(buf));
783 }
784 g_free(dpath);
785 g_free(path);
786 return driver;
787}
788
789static int compare_uint(const void *_a, const void *_b)
790{
791 unsigned int a = *(unsigned int *)_a;
792 unsigned int b = *(unsigned int *)_b;
793
794 return a < b ? -1 : a > b ? 1 : 0;
795}
796
797/* Walk the specified sysfs and build a sorted list of host or ata numbers */
798static int build_hosts(char const *syspath, char const *host, bool ata,
799 unsigned int *hosts, int hosts_max, Error **errp)
800{
801 char *path;
802 DIR *dir;
803 struct dirent *entry;
804 int i = 0;
805
806 path = g_strndup(syspath, host - syspath);
807 dir = opendir(path);
808 if (!dir) {
809 error_setg_errno(errp, errno, "opendir(\"%s\")", path);
810 g_free(path);
811 return -1;
812 }
813
814 while (i < hosts_max) {
815 entry = readdir(dir);
816 if (!entry) {
817 break;
818 }
819 if (ata && sscanf(entry->d_name, "ata%d", hosts + i) == 1) {
820 ++i;
821 } else if (!ata && sscanf(entry->d_name, "host%d", hosts + i) == 1) {
822 ++i;
823 }
824 }
825
826 qsort(hosts, i, sizeof(hosts[0]), compare_uint);
827
828 g_free(path);
829 closedir(dir);
830 return i;
831}
832
833/* Store disk device info specified by @sysfs into @fs */
834static void build_guest_fsinfo_for_real_device(char const *syspath,
835 GuestFilesystemInfo *fs,
836 Error **errp)
837{
838 unsigned int pci[4], host, hosts[8], tgt[3];
839 int i, nhosts = 0, pcilen;
840 GuestDiskAddress *disk;
841 GuestPCIAddress *pciaddr;
842 GuestDiskAddressList *list = NULL;
843 bool has_ata = false, has_host = false, has_tgt = false;
844 char *p, *q, *driver = NULL;
845
846 p = strstr(syspath, "/devices/pci");
847 if (!p || sscanf(p + 12, "%*x:%*x/%x:%x:%x.%x%n",
848 pci, pci + 1, pci + 2, pci + 3, &pcilen) < 4) {
849 g_debug("only pci device is supported: sysfs path \"%s\"", syspath);
850 return;
851 }
852
853 driver = get_pci_driver(syspath, (p + 12 + pcilen) - syspath, errp);
854 if (!driver) {
855 goto cleanup;
856 }
857
858 p = strstr(syspath, "/target");
859 if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
860 tgt, tgt + 1, tgt + 2) == 3) {
861 has_tgt = true;
862 }
863
864 p = strstr(syspath, "/ata");
865 if (p) {
866 q = p + 4;
867 has_ata = true;
868 } else {
869 p = strstr(syspath, "/host");
870 q = p + 5;
871 }
872 if (p && sscanf(q, "%u", &host) == 1) {
873 has_host = true;
874 nhosts = build_hosts(syspath, p, has_ata, hosts,
875 sizeof(hosts) / sizeof(hosts[0]), errp);
876 if (nhosts < 0) {
877 goto cleanup;
878 }
879 }
880
881 pciaddr = g_malloc0(sizeof(*pciaddr));
882 pciaddr->domain = pci[0];
883 pciaddr->bus = pci[1];
884 pciaddr->slot = pci[2];
885 pciaddr->function = pci[3];
886
887 disk = g_malloc0(sizeof(*disk));
888 disk->pci_controller = pciaddr;
889
890 list = g_malloc0(sizeof(*list));
891 list->value = disk;
892
893 if (strcmp(driver, "ata_piix") == 0) {
894 /* a host per ide bus, target*:0:<unit>:0 */
895 if (!has_host || !has_tgt) {
896 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
897 goto cleanup;
898 }
899 for (i = 0; i < nhosts; i++) {
900 if (host == hosts[i]) {
901 disk->bus_type = GUEST_DISK_BUS_TYPE_IDE;
902 disk->bus = i;
903 disk->unit = tgt[1];
904 break;
905 }
906 }
907 if (i >= nhosts) {
908 g_debug("no host for '%s' (driver '%s')", syspath, driver);
909 goto cleanup;
910 }
911 } else if (strcmp(driver, "sym53c8xx") == 0) {
912 /* scsi(LSI Logic): target*:0:<unit>:0 */
913 if (!has_tgt) {
914 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
915 goto cleanup;
916 }
917 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
918 disk->unit = tgt[1];
919 } else if (strcmp(driver, "virtio-pci") == 0) {
920 if (has_tgt) {
921 /* virtio-scsi: target*:0:0:<unit> */
922 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
923 disk->unit = tgt[2];
924 } else {
925 /* virtio-blk: 1 disk per 1 device */
926 disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
927 }
928 } else if (strcmp(driver, "ahci") == 0) {
929 /* ahci: 1 host per 1 unit */
930 if (!has_host || !has_tgt) {
931 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
932 goto cleanup;
933 }
934 for (i = 0; i < nhosts; i++) {
935 if (host == hosts[i]) {
936 disk->unit = i;
937 disk->bus_type = GUEST_DISK_BUS_TYPE_SATA;
938 break;
939 }
940 }
941 if (i >= nhosts) {
942 g_debug("no host for '%s' (driver '%s')", syspath, driver);
943 goto cleanup;
944 }
945 } else {
946 g_debug("unknown driver '%s' (sysfs path '%s')", driver, syspath);
947 goto cleanup;
948 }
949
950 list->next = fs->disk;
951 fs->disk = list;
952 g_free(driver);
953 return;
954
955cleanup:
956 if (list) {
957 qapi_free_GuestDiskAddressList(list);
958 }
959 g_free(driver);
960}
961
962static void build_guest_fsinfo_for_device(char const *devpath,
963 GuestFilesystemInfo *fs,
964 Error **errp);
965
966/* Store a list of slave devices of virtual volume specified by @syspath into
967 * @fs */
968static void build_guest_fsinfo_for_virtual_device(char const *syspath,
969 GuestFilesystemInfo *fs,
970 Error **errp)
971{
972 DIR *dir;
973 char *dirpath;
e668d1b8 974 struct dirent *entry;
46d4c572
TS
975
976 dirpath = g_strdup_printf("%s/slaves", syspath);
977 dir = opendir(dirpath);
978 if (!dir) {
979 error_setg_errno(errp, errno, "opendir(\"%s\")", dirpath);
980 g_free(dirpath);
981 return;
982 }
46d4c572
TS
983
984 for (;;) {
e668d1b8
HZ
985 errno = 0;
986 entry = readdir(dir);
987 if (entry == NULL) {
988 if (errno) {
989 error_setg_errno(errp, errno, "readdir(\"%s\")", dirpath);
990 }
46d4c572
TS
991 break;
992 }
993
e668d1b8
HZ
994 if (entry->d_type == DT_LNK) {
995 char *path;
996
997 g_debug(" slave device '%s'", entry->d_name);
998 path = g_strdup_printf("%s/slaves/%s", syspath, entry->d_name);
999 build_guest_fsinfo_for_device(path, fs, errp);
1000 g_free(path);
46d4c572
TS
1001
1002 if (*errp) {
1003 break;
1004 }
1005 }
1006 }
1007
e668d1b8 1008 g_free(dirpath);
46d4c572
TS
1009 closedir(dir);
1010}
1011
1012/* Dispatch to functions for virtual/real device */
1013static void build_guest_fsinfo_for_device(char const *devpath,
1014 GuestFilesystemInfo *fs,
1015 Error **errp)
1016{
1017 char *syspath = realpath(devpath, NULL);
1018
1019 if (!syspath) {
1020 error_setg_errno(errp, errno, "realpath(\"%s\")", devpath);
1021 return;
1022 }
1023
1024 if (!fs->name) {
1025 fs->name = g_strdup(basename(syspath));
1026 }
1027
1028 g_debug(" parse sysfs path '%s'", syspath);
1029
1030 if (strstr(syspath, "/devices/virtual/block/")) {
1031 build_guest_fsinfo_for_virtual_device(syspath, fs, errp);
1032 } else {
1033 build_guest_fsinfo_for_real_device(syspath, fs, errp);
1034 }
1035
1036 free(syspath);
1037}
1038
1039/* Return a list of the disk device(s)' info which @mount lies on */
1040static GuestFilesystemInfo *build_guest_fsinfo(struct FsMount *mount,
1041 Error **errp)
1042{
1043 GuestFilesystemInfo *fs = g_malloc0(sizeof(*fs));
1044 char *devpath = g_strdup_printf("/sys/dev/block/%u:%u",
1045 mount->devmajor, mount->devminor);
1046
1047 fs->mountpoint = g_strdup(mount->dirname);
1048 fs->type = g_strdup(mount->devtype);
1049 build_guest_fsinfo_for_device(devpath, fs, errp);
1050
1051 g_free(devpath);
1052 return fs;
1053}
1054
1055GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
1056{
1057 FsMountList mounts;
1058 struct FsMount *mount;
1059 GuestFilesystemInfoList *new, *ret = NULL;
1060 Error *local_err = NULL;
1061
1062 QTAILQ_INIT(&mounts);
1063 build_fs_mount_list(&mounts, &local_err);
1064 if (local_err) {
1065 error_propagate(errp, local_err);
1066 return NULL;
1067 }
1068
1069 QTAILQ_FOREACH(mount, &mounts, next) {
1070 g_debug("Building guest fsinfo for '%s'", mount->dirname);
1071
1072 new = g_malloc0(sizeof(*ret));
1073 new->value = build_guest_fsinfo(mount, &local_err);
1074 new->next = ret;
1075 ret = new;
1076 if (local_err) {
1077 error_propagate(errp, local_err);
1078 qapi_free_GuestFilesystemInfoList(ret);
1079 ret = NULL;
1080 break;
1081 }
1082 }
1083
1084 free_fs_mount_list(&mounts);
1085 return ret;
1086}
1087
1088
ec0f694c
TS
1089typedef enum {
1090 FSFREEZE_HOOK_THAW = 0,
1091 FSFREEZE_HOOK_FREEZE,
1092} FsfreezeHookArg;
1093
13a439ec 1094static const char *fsfreeze_hook_arg_string[] = {
ec0f694c
TS
1095 "thaw",
1096 "freeze",
1097};
1098
77dbc81b 1099static void execute_fsfreeze_hook(FsfreezeHookArg arg, Error **errp)
ec0f694c
TS
1100{
1101 int status;
1102 pid_t pid;
1103 const char *hook;
1104 const char *arg_str = fsfreeze_hook_arg_string[arg];
1105 Error *local_err = NULL;
1106
1107 hook = ga_fsfreeze_hook(ga_state);
1108 if (!hook) {
1109 return;
1110 }
1111 if (access(hook, X_OK) != 0) {
77dbc81b 1112 error_setg_errno(errp, errno, "can't access fsfreeze hook '%s'", hook);
ec0f694c
TS
1113 return;
1114 }
1115
1116 slog("executing fsfreeze hook with arg '%s'", arg_str);
1117 pid = fork();
1118 if (pid == 0) {
1119 setsid();
1120 reopen_fd_to_null(0);
1121 reopen_fd_to_null(1);
1122 reopen_fd_to_null(2);
1123
1124 execle(hook, hook, arg_str, NULL, environ);
1125 _exit(EXIT_FAILURE);
1126 } else if (pid < 0) {
77dbc81b 1127 error_setg_errno(errp, errno, "failed to create child process");
ec0f694c
TS
1128 return;
1129 }
1130
1131 ga_wait_child(pid, &status, &local_err);
84d18f06 1132 if (local_err) {
77dbc81b 1133 error_propagate(errp, local_err);
ec0f694c
TS
1134 return;
1135 }
1136
1137 if (!WIFEXITED(status)) {
77dbc81b 1138 error_setg(errp, "fsfreeze hook has terminated abnormally");
ec0f694c
TS
1139 return;
1140 }
1141
1142 status = WEXITSTATUS(status);
1143 if (status) {
77dbc81b 1144 error_setg(errp, "fsfreeze hook has failed with status %d", status);
ec0f694c
TS
1145 return;
1146 }
1147}
1148
e3d4d252
MR
1149/*
1150 * Return status of freeze/thaw
1151 */
77dbc81b 1152GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
e3d4d252 1153{
f22d85e9
MR
1154 if (ga_is_frozen(ga_state)) {
1155 return GUEST_FSFREEZE_STATUS_FROZEN;
1156 }
1157
1158 return GUEST_FSFREEZE_STATUS_THAWED;
e3d4d252
MR
1159}
1160
e99bce20
TS
1161int64_t qmp_guest_fsfreeze_freeze(Error **errp)
1162{
1163 return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
1164}
1165
e3d4d252
MR
1166/*
1167 * Walk list of mounted file systems in the guest, and freeze the ones which
1168 * are real local file systems.
1169 */
e99bce20
TS
1170int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
1171 strList *mountpoints,
1172 Error **errp)
e3d4d252
MR
1173{
1174 int ret = 0, i = 0;
e99bce20 1175 strList *list;
af02203f
PB
1176 FsMountList mounts;
1177 struct FsMount *mount;
261551d1 1178 Error *local_err = NULL;
e3d4d252 1179 int fd;
e3d4d252
MR
1180
1181 slog("guest-fsfreeze called");
1182
ec0f694c 1183 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE, &local_err);
84d18f06 1184 if (local_err) {
77dbc81b 1185 error_propagate(errp, local_err);
ec0f694c
TS
1186 return -1;
1187 }
1188
9e8aded4 1189 QTAILQ_INIT(&mounts);
261551d1 1190 build_fs_mount_list(&mounts, &local_err);
84d18f06 1191 if (local_err) {
77dbc81b 1192 error_propagate(errp, local_err);
261551d1 1193 return -1;
e3d4d252
MR
1194 }
1195
1196 /* cannot risk guest agent blocking itself on a write in this state */
f22d85e9 1197 ga_set_frozen(ga_state);
e3d4d252 1198
e5d9adbd 1199 QTAILQ_FOREACH_REVERSE(mount, &mounts, FsMountList, next) {
e99bce20
TS
1200 /* To issue fsfreeze in the reverse order of mounts, check if the
1201 * mount is listed in the list here */
1202 if (has_mountpoints) {
1203 for (list = mountpoints; list; list = list->next) {
1204 if (strcmp(list->value, mount->dirname) == 0) {
1205 break;
1206 }
1207 }
1208 if (!list) {
1209 continue;
1210 }
1211 }
1212
e3d4d252
MR
1213 fd = qemu_open(mount->dirname, O_RDONLY);
1214 if (fd == -1) {
77dbc81b 1215 error_setg_errno(errp, errno, "failed to open %s", mount->dirname);
e3d4d252
MR
1216 goto error;
1217 }
1218
1219 /* we try to cull filesytems we know won't work in advance, but other
1220 * filesytems may not implement fsfreeze for less obvious reasons.
9e8aded4
MR
1221 * these will report EOPNOTSUPP. we simply ignore these when tallying
1222 * the number of frozen filesystems.
1223 *
1224 * any other error means a failure to freeze a filesystem we
1225 * expect to be freezable, so return an error in those cases
1226 * and return system to thawed state.
e3d4d252
MR
1227 */
1228 ret = ioctl(fd, FIFREEZE);
9e8aded4
MR
1229 if (ret == -1) {
1230 if (errno != EOPNOTSUPP) {
77dbc81b 1231 error_setg_errno(errp, errno, "failed to freeze %s",
617fbbc1 1232 mount->dirname);
9e8aded4
MR
1233 close(fd);
1234 goto error;
1235 }
1236 } else {
1237 i++;
e3d4d252
MR
1238 }
1239 close(fd);
e3d4d252
MR
1240 }
1241
af02203f 1242 free_fs_mount_list(&mounts);
e3d4d252
MR
1243 return i;
1244
1245error:
af02203f 1246 free_fs_mount_list(&mounts);
9e8aded4 1247 qmp_guest_fsfreeze_thaw(NULL);
e3d4d252
MR
1248 return 0;
1249}
1250
1251/*
1252 * Walk list of frozen file systems in the guest, and thaw them.
1253 */
77dbc81b 1254int64_t qmp_guest_fsfreeze_thaw(Error **errp)
e3d4d252
MR
1255{
1256 int ret;
af02203f
PB
1257 FsMountList mounts;
1258 FsMount *mount;
9e8aded4 1259 int fd, i = 0, logged;
261551d1 1260 Error *local_err = NULL;
9e8aded4
MR
1261
1262 QTAILQ_INIT(&mounts);
261551d1 1263 build_fs_mount_list(&mounts, &local_err);
84d18f06 1264 if (local_err) {
77dbc81b 1265 error_propagate(errp, local_err);
9e8aded4
MR
1266 return 0;
1267 }
e3d4d252 1268
9e8aded4
MR
1269 QTAILQ_FOREACH(mount, &mounts, next) {
1270 logged = false;
e3d4d252
MR
1271 fd = qemu_open(mount->dirname, O_RDONLY);
1272 if (fd == -1) {
e3d4d252
MR
1273 continue;
1274 }
9e8aded4
MR
1275 /* we have no way of knowing whether a filesystem was actually unfrozen
1276 * as a result of a successful call to FITHAW, only that if an error
1277 * was returned the filesystem was *not* unfrozen by that particular
1278 * call.
1279 *
a31f0531 1280 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
9e8aded4
MR
1281 * to unfreeze, continuing issuing FITHAW until an error is returned,
1282 * in which case either the filesystem is in an unfreezable state, or,
1283 * more likely, it was thawed previously (and remains so afterward).
1284 *
1285 * also, since the most recent successful call is the one that did
1286 * the actual unfreeze, we can use this to provide an accurate count
1287 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1288 * may * be useful for determining whether a filesystem was unfrozen
1289 * during the freeze/thaw phase by a process other than qemu-ga.
1290 */
1291 do {
1292 ret = ioctl(fd, FITHAW);
1293 if (ret == 0 && !logged) {
1294 i++;
1295 logged = true;
1296 }
1297 } while (ret == 0);
e3d4d252 1298 close(fd);
e3d4d252
MR
1299 }
1300
f22d85e9 1301 ga_unset_frozen(ga_state);
af02203f 1302 free_fs_mount_list(&mounts);
ec0f694c 1303
77dbc81b 1304 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW, errp);
ec0f694c 1305
e3d4d252
MR
1306 return i;
1307}
1308
e3d4d252
MR
1309static void guest_fsfreeze_cleanup(void)
1310{
e3d4d252
MR
1311 Error *err = NULL;
1312
f22d85e9 1313 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
6f686749
MA
1314 qmp_guest_fsfreeze_thaw(&err);
1315 if (err) {
1316 slog("failed to clean up frozen filesystems: %s",
1317 error_get_pretty(err));
1318 error_free(err);
e3d4d252
MR
1319 }
1320 }
1321}
e72c3f2e 1322#endif /* CONFIG_FSFREEZE */
e3d4d252 1323
eab5fd59
PB
1324#if defined(CONFIG_FSTRIM)
1325/*
1326 * Walk list of mounted file systems in the guest, and trim them.
1327 */
e82855d9
JO
1328GuestFilesystemTrimResponse *
1329qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
eab5fd59 1330{
e82855d9
JO
1331 GuestFilesystemTrimResponse *response;
1332 GuestFilesystemTrimResultList *list;
1333 GuestFilesystemTrimResult *result;
eab5fd59
PB
1334 int ret = 0;
1335 FsMountList mounts;
1336 struct FsMount *mount;
1337 int fd;
261551d1 1338 Error *local_err = NULL;
73a652a1 1339 struct fstrim_range r;
eab5fd59
PB
1340
1341 slog("guest-fstrim called");
1342
1343 QTAILQ_INIT(&mounts);
261551d1 1344 build_fs_mount_list(&mounts, &local_err);
84d18f06 1345 if (local_err) {
77dbc81b 1346 error_propagate(errp, local_err);
e82855d9 1347 return NULL;
eab5fd59
PB
1348 }
1349
e82855d9
JO
1350 response = g_malloc0(sizeof(*response));
1351
eab5fd59 1352 QTAILQ_FOREACH(mount, &mounts, next) {
e82855d9
JO
1353 result = g_malloc0(sizeof(*result));
1354 result->path = g_strdup(mount->dirname);
1355
1356 list = g_malloc0(sizeof(*list));
1357 list->value = result;
1358 list->next = response->paths;
1359 response->paths = list;
1360
eab5fd59
PB
1361 fd = qemu_open(mount->dirname, O_RDONLY);
1362 if (fd == -1) {
e82855d9
JO
1363 result->error = g_strdup_printf("failed to open: %s",
1364 strerror(errno));
1365 result->has_error = true;
1366 continue;
eab5fd59
PB
1367 }
1368
1369 /* We try to cull filesytems we know won't work in advance, but other
1370 * filesytems may not implement fstrim for less obvious reasons. These
e82855d9
JO
1371 * will report EOPNOTSUPP; while in some other cases ENOTTY will be
1372 * reported (e.g. CD-ROMs).
1373 * Any other error means an unexpected error.
eab5fd59 1374 */
73a652a1
JO
1375 r.start = 0;
1376 r.len = -1;
1377 r.minlen = has_minimum ? minimum : 0;
eab5fd59
PB
1378 ret = ioctl(fd, FITRIM, &r);
1379 if (ret == -1) {
e82855d9
JO
1380 result->has_error = true;
1381 if (errno == ENOTTY || errno == EOPNOTSUPP) {
1382 result->error = g_strdup("trim not supported");
1383 } else {
1384 result->error = g_strdup_printf("failed to trim: %s",
1385 strerror(errno));
eab5fd59 1386 }
e82855d9
JO
1387 close(fd);
1388 continue;
eab5fd59 1389 }
e82855d9
JO
1390
1391 result->has_minimum = true;
1392 result->minimum = r.minlen;
1393 result->has_trimmed = true;
1394 result->trimmed = r.len;
eab5fd59
PB
1395 close(fd);
1396 }
1397
eab5fd59 1398 free_fs_mount_list(&mounts);
e82855d9 1399 return response;
eab5fd59
PB
1400}
1401#endif /* CONFIG_FSTRIM */
1402
1403
11d0f125
LC
1404#define LINUX_SYS_STATE_FILE "/sys/power/state"
1405#define SUSPEND_SUPPORTED 0
1406#define SUSPEND_NOT_SUPPORTED 1
1407
11d0f125 1408static void bios_supports_mode(const char *pmutils_bin, const char *pmutils_arg,
77dbc81b 1409 const char *sysfile_str, Error **errp)
11d0f125 1410{
6b26e837 1411 Error *local_err = NULL;
11d0f125 1412 char *pmutils_path;
6b26e837 1413 pid_t pid;
dc8764f0 1414 int status;
11d0f125
LC
1415
1416 pmutils_path = g_find_program_in_path(pmutils_bin);
1417
1418 pid = fork();
1419 if (!pid) {
dc8764f0
LC
1420 char buf[32]; /* hopefully big enough */
1421 ssize_t ret;
1422 int fd;
11d0f125
LC
1423
1424 setsid();
11d0f125
LC
1425 reopen_fd_to_null(0);
1426 reopen_fd_to_null(1);
1427 reopen_fd_to_null(2);
1428
dc8764f0
LC
1429 if (pmutils_path) {
1430 execle(pmutils_path, pmutils_bin, pmutils_arg, NULL, environ);
1431 }
11d0f125 1432
dc8764f0
LC
1433 /*
1434 * If we get here either pm-utils is not installed or execle() has
1435 * failed. Let's try the manual method if the caller wants it.
1436 */
11d0f125 1437
dc8764f0
LC
1438 if (!sysfile_str) {
1439 _exit(SUSPEND_NOT_SUPPORTED);
1440 }
11d0f125 1441
dc8764f0
LC
1442 fd = open(LINUX_SYS_STATE_FILE, O_RDONLY);
1443 if (fd < 0) {
11d0f125
LC
1444 _exit(SUSPEND_NOT_SUPPORTED);
1445 }
1446
dc8764f0
LC
1447 ret = read(fd, buf, sizeof(buf)-1);
1448 if (ret <= 0) {
1449 _exit(SUSPEND_NOT_SUPPORTED);
11d0f125 1450 }
dc8764f0 1451 buf[ret] = '\0';
11d0f125 1452
dc8764f0
LC
1453 if (strstr(buf, sysfile_str)) {
1454 _exit(SUSPEND_SUPPORTED);
11d0f125
LC
1455 }
1456
dc8764f0 1457 _exit(SUSPEND_NOT_SUPPORTED);
6b26e837 1458 } else if (pid < 0) {
77dbc81b 1459 error_setg_errno(errp, errno, "failed to create child process");
6b26e837 1460 goto out;
11d0f125
LC
1461 }
1462
6b26e837 1463 ga_wait_child(pid, &status, &local_err);
84d18f06 1464 if (local_err) {
77dbc81b 1465 error_propagate(errp, local_err);
6b26e837
LC
1466 goto out;
1467 }
11d0f125 1468
6b26e837 1469 if (!WIFEXITED(status)) {
77dbc81b 1470 error_setg(errp, "child process has terminated abnormally");
6b26e837 1471 goto out;
dc8764f0
LC
1472 }
1473
6b26e837
LC
1474 switch (WEXITSTATUS(status)) {
1475 case SUSPEND_SUPPORTED:
1476 goto out;
1477 case SUSPEND_NOT_SUPPORTED:
77dbc81b 1478 error_setg(errp,
6b26e837
LC
1479 "the requested suspend mode is not supported by the guest");
1480 goto out;
1481 default:
77dbc81b 1482 error_setg(errp,
6b26e837
LC
1483 "the helper program '%s' returned an unexpected exit status"
1484 " code (%d)", pmutils_path, WEXITSTATUS(status));
1485 goto out;
11d0f125
LC
1486 }
1487
6b26e837
LC
1488out:
1489 g_free(pmutils_path);
11d0f125
LC
1490}
1491
1492static void guest_suspend(const char *pmutils_bin, const char *sysfile_str,
77dbc81b 1493 Error **errp)
11d0f125 1494{
7b376087 1495 Error *local_err = NULL;
11d0f125 1496 char *pmutils_path;
7b376087 1497 pid_t pid;
dc8764f0 1498 int status;
11d0f125
LC
1499
1500 pmutils_path = g_find_program_in_path(pmutils_bin);
1501
1502 pid = fork();
1503 if (pid == 0) {
1504 /* child */
1505 int fd;
1506
1507 setsid();
1508 reopen_fd_to_null(0);
1509 reopen_fd_to_null(1);
1510 reopen_fd_to_null(2);
1511
1512 if (pmutils_path) {
1513 execle(pmutils_path, pmutils_bin, NULL, environ);
1514 }
1515
1516 /*
1517 * If we get here either pm-utils is not installed or execle() has
1518 * failed. Let's try the manual method if the caller wants it.
1519 */
1520
1521 if (!sysfile_str) {
1522 _exit(EXIT_FAILURE);
1523 }
1524
1525 fd = open(LINUX_SYS_STATE_FILE, O_WRONLY);
1526 if (fd < 0) {
1527 _exit(EXIT_FAILURE);
1528 }
1529
1530 if (write(fd, sysfile_str, strlen(sysfile_str)) < 0) {
1531 _exit(EXIT_FAILURE);
1532 }
1533
1534 _exit(EXIT_SUCCESS);
7b376087 1535 } else if (pid < 0) {
77dbc81b 1536 error_setg_errno(errp, errno, "failed to create child process");
7b376087 1537 goto out;
11d0f125
LC
1538 }
1539
7b376087 1540 ga_wait_child(pid, &status, &local_err);
84d18f06 1541 if (local_err) {
77dbc81b 1542 error_propagate(errp, local_err);
7b376087
LC
1543 goto out;
1544 }
11d0f125 1545
7b376087 1546 if (!WIFEXITED(status)) {
77dbc81b 1547 error_setg(errp, "child process has terminated abnormally");
7b376087 1548 goto out;
dc8764f0
LC
1549 }
1550
7b376087 1551 if (WEXITSTATUS(status)) {
77dbc81b 1552 error_setg(errp, "child process has failed to suspend");
7b376087 1553 goto out;
11d0f125 1554 }
dc8764f0 1555
7b376087
LC
1556out:
1557 g_free(pmutils_path);
11d0f125
LC
1558}
1559
77dbc81b 1560void qmp_guest_suspend_disk(Error **errp)
11d0f125 1561{
0f230bf7
MA
1562 Error *local_err = NULL;
1563
1564 bios_supports_mode("pm-is-supported", "--hibernate", "disk", &local_err);
1565 if (local_err) {
1566 error_propagate(errp, local_err);
11d0f125
LC
1567 return;
1568 }
1569
77dbc81b 1570 guest_suspend("pm-hibernate", "disk", errp);
11d0f125
LC
1571}
1572
77dbc81b 1573void qmp_guest_suspend_ram(Error **errp)
fbf42210 1574{
0f230bf7
MA
1575 Error *local_err = NULL;
1576
1577 bios_supports_mode("pm-is-supported", "--suspend", "mem", &local_err);
1578 if (local_err) {
1579 error_propagate(errp, local_err);
fbf42210
LC
1580 return;
1581 }
1582
77dbc81b 1583 guest_suspend("pm-suspend", "mem", errp);
fbf42210
LC
1584}
1585
77dbc81b 1586void qmp_guest_suspend_hybrid(Error **errp)
95f4f404 1587{
0f230bf7
MA
1588 Error *local_err = NULL;
1589
1590 bios_supports_mode("pm-is-supported", "--suspend-hybrid", NULL,
1591 &local_err);
1592 if (local_err) {
1593 error_propagate(errp, local_err);
95f4f404
LC
1594 return;
1595 }
1596
77dbc81b 1597 guest_suspend("pm-suspend-hybrid", NULL, errp);
95f4f404
LC
1598}
1599
3424fc9f
MP
1600static GuestNetworkInterfaceList *
1601guest_find_interface(GuestNetworkInterfaceList *head,
1602 const char *name)
1603{
1604 for (; head; head = head->next) {
1605 if (strcmp(head->value->name, name) == 0) {
1606 break;
1607 }
1608 }
1609
1610 return head;
1611}
1612
1613/*
1614 * Build information about guest interfaces
1615 */
1616GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1617{
1618 GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
1619 struct ifaddrs *ifap, *ifa;
3424fc9f
MP
1620
1621 if (getifaddrs(&ifap) < 0) {
878a0ae0 1622 error_setg_errno(errp, errno, "getifaddrs failed");
3424fc9f
MP
1623 goto error;
1624 }
1625
1626 for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1627 GuestNetworkInterfaceList *info;
1628 GuestIpAddressList **address_list = NULL, *address_item = NULL;
1629 char addr4[INET_ADDRSTRLEN];
1630 char addr6[INET6_ADDRSTRLEN];
1631 int sock;
1632 struct ifreq ifr;
1633 unsigned char *mac_addr;
1634 void *p;
1635
1636 g_debug("Processing %s interface", ifa->ifa_name);
1637
1638 info = guest_find_interface(head, ifa->ifa_name);
1639
1640 if (!info) {
1641 info = g_malloc0(sizeof(*info));
1642 info->value = g_malloc0(sizeof(*info->value));
1643 info->value->name = g_strdup(ifa->ifa_name);
1644
1645 if (!cur_item) {
1646 head = cur_item = info;
1647 } else {
1648 cur_item->next = info;
1649 cur_item = info;
1650 }
1651 }
1652
1653 if (!info->value->has_hardware_address &&
1654 ifa->ifa_flags & SIOCGIFHWADDR) {
1655 /* we haven't obtained HW address yet */
1656 sock = socket(PF_INET, SOCK_STREAM, 0);
1657 if (sock == -1) {
878a0ae0 1658 error_setg_errno(errp, errno, "failed to create socket");
3424fc9f
MP
1659 goto error;
1660 }
1661
1662 memset(&ifr, 0, sizeof(ifr));
1ab516ed 1663 pstrcpy(ifr.ifr_name, IF_NAMESIZE, info->value->name);
3424fc9f 1664 if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {
878a0ae0
LC
1665 error_setg_errno(errp, errno,
1666 "failed to get MAC address of %s",
1667 ifa->ifa_name);
10a2158f 1668 close(sock);
3424fc9f
MP
1669 goto error;
1670 }
1671
10a2158f 1672 close(sock);
3424fc9f
MP
1673 mac_addr = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
1674
e4ada482
SW
1675 info->value->hardware_address =
1676 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1677 (int) mac_addr[0], (int) mac_addr[1],
1678 (int) mac_addr[2], (int) mac_addr[3],
1679 (int) mac_addr[4], (int) mac_addr[5]);
3424fc9f
MP
1680
1681 info->value->has_hardware_address = true;
3424fc9f
MP
1682 }
1683
1684 if (ifa->ifa_addr &&
1685 ifa->ifa_addr->sa_family == AF_INET) {
1686 /* interface with IPv4 address */
3424fc9f
MP
1687 p = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
1688 if (!inet_ntop(AF_INET, p, addr4, sizeof(addr4))) {
878a0ae0 1689 error_setg_errno(errp, errno, "inet_ntop failed");
3424fc9f
MP
1690 goto error;
1691 }
1692
10a2158f
MA
1693 address_item = g_malloc0(sizeof(*address_item));
1694 address_item->value = g_malloc0(sizeof(*address_item->value));
3424fc9f
MP
1695 address_item->value->ip_address = g_strdup(addr4);
1696 address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
1697
1698 if (ifa->ifa_netmask) {
1699 /* Count the number of set bits in netmask.
1700 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1701 p = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
1702 address_item->value->prefix = ctpop32(((uint32_t *) p)[0]);
1703 }
1704 } else if (ifa->ifa_addr &&
1705 ifa->ifa_addr->sa_family == AF_INET6) {
1706 /* interface with IPv6 address */
3424fc9f
MP
1707 p = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
1708 if (!inet_ntop(AF_INET6, p, addr6, sizeof(addr6))) {
878a0ae0 1709 error_setg_errno(errp, errno, "inet_ntop failed");
3424fc9f
MP
1710 goto error;
1711 }
1712
10a2158f
MA
1713 address_item = g_malloc0(sizeof(*address_item));
1714 address_item->value = g_malloc0(sizeof(*address_item->value));
3424fc9f
MP
1715 address_item->value->ip_address = g_strdup(addr6);
1716 address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
1717
1718 if (ifa->ifa_netmask) {
1719 /* Count the number of set bits in netmask.
1720 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1721 p = &((struct sockaddr_in6 *)ifa->ifa_netmask)->sin6_addr;
1722 address_item->value->prefix =
1723 ctpop32(((uint32_t *) p)[0]) +
1724 ctpop32(((uint32_t *) p)[1]) +
1725 ctpop32(((uint32_t *) p)[2]) +
1726 ctpop32(((uint32_t *) p)[3]);
1727 }
1728 }
1729
1730 if (!address_item) {
1731 continue;
1732 }
1733
1734 address_list = &info->value->ip_addresses;
1735
1736 while (*address_list && (*address_list)->next) {
1737 address_list = &(*address_list)->next;
1738 }
1739
1740 if (!*address_list) {
1741 *address_list = address_item;
1742 } else {
1743 (*address_list)->next = address_item;
1744 }
1745
1746 info->value->has_ip_addresses = true;
1747
1748
1749 }
1750
1751 freeifaddrs(ifap);
1752 return head;
1753
1754error:
1755 freeifaddrs(ifap);
1756 qapi_free_GuestNetworkInterfaceList(head);
1757 return NULL;
1758}
1759
77dbc81b 1760#define SYSCONF_EXACT(name, errp) sysconf_exact((name), #name, (errp))
d2baff62 1761
77dbc81b 1762static long sysconf_exact(int name, const char *name_str, Error **errp)
d2baff62
LE
1763{
1764 long ret;
1765
1766 errno = 0;
1767 ret = sysconf(name);
1768 if (ret == -1) {
1769 if (errno == 0) {
77dbc81b 1770 error_setg(errp, "sysconf(%s): value indefinite", name_str);
d2baff62 1771 } else {
77dbc81b 1772 error_setg_errno(errp, errno, "sysconf(%s)", name_str);
d2baff62
LE
1773 }
1774 }
1775 return ret;
1776}
1777
1778/* Transfer online/offline status between @vcpu and the guest system.
1779 *
1780 * On input either @errp or *@errp must be NULL.
1781 *
1782 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
1783 * - R: vcpu->logical_id
1784 * - W: vcpu->online
1785 * - W: vcpu->can_offline
1786 *
1787 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
1788 * - R: vcpu->logical_id
1789 * - R: vcpu->online
1790 *
1791 * Written members remain unmodified on error.
1792 */
1793static void transfer_vcpu(GuestLogicalProcessor *vcpu, bool sys2vcpu,
1794 Error **errp)
1795{
1796 char *dirpath;
1797 int dirfd;
1798
1799 dirpath = g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64 "/",
1800 vcpu->logical_id);
1801 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
1802 if (dirfd == -1) {
1803 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
1804 } else {
1805 static const char fn[] = "online";
1806 int fd;
1807 int res;
1808
1809 fd = openat(dirfd, fn, sys2vcpu ? O_RDONLY : O_RDWR);
1810 if (fd == -1) {
1811 if (errno != ENOENT) {
1812 error_setg_errno(errp, errno, "open(\"%s/%s\")", dirpath, fn);
1813 } else if (sys2vcpu) {
1814 vcpu->online = true;
1815 vcpu->can_offline = false;
1816 } else if (!vcpu->online) {
1817 error_setg(errp, "logical processor #%" PRId64 " can't be "
1818 "offlined", vcpu->logical_id);
1819 } /* otherwise pretend successful re-onlining */
1820 } else {
1821 unsigned char status;
1822
1823 res = pread(fd, &status, 1, 0);
1824 if (res == -1) {
1825 error_setg_errno(errp, errno, "pread(\"%s/%s\")", dirpath, fn);
1826 } else if (res == 0) {
1827 error_setg(errp, "pread(\"%s/%s\"): unexpected EOF", dirpath,
1828 fn);
1829 } else if (sys2vcpu) {
1830 vcpu->online = (status != '0');
1831 vcpu->can_offline = true;
1832 } else if (vcpu->online != (status != '0')) {
1833 status = '0' + vcpu->online;
1834 if (pwrite(fd, &status, 1, 0) == -1) {
1835 error_setg_errno(errp, errno, "pwrite(\"%s/%s\")", dirpath,
1836 fn);
1837 }
1838 } /* otherwise pretend successful re-(on|off)-lining */
1839
1840 res = close(fd);
1841 g_assert(res == 0);
1842 }
1843
1844 res = close(dirfd);
1845 g_assert(res == 0);
1846 }
1847
1848 g_free(dirpath);
1849}
1850
1851GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1852{
1853 int64_t current;
1854 GuestLogicalProcessorList *head, **link;
1855 long sc_max;
1856 Error *local_err = NULL;
1857
1858 current = 0;
1859 head = NULL;
1860 link = &head;
1861 sc_max = SYSCONF_EXACT(_SC_NPROCESSORS_CONF, &local_err);
1862
1863 while (local_err == NULL && current < sc_max) {
1864 GuestLogicalProcessor *vcpu;
1865 GuestLogicalProcessorList *entry;
1866
1867 vcpu = g_malloc0(sizeof *vcpu);
1868 vcpu->logical_id = current++;
1869 vcpu->has_can_offline = true; /* lolspeak ftw */
1870 transfer_vcpu(vcpu, true, &local_err);
1871
1872 entry = g_malloc0(sizeof *entry);
1873 entry->value = vcpu;
1874
1875 *link = entry;
1876 link = &entry->next;
1877 }
1878
1879 if (local_err == NULL) {
1880 /* there's no guest with zero VCPUs */
1881 g_assert(head != NULL);
1882 return head;
1883 }
1884
1885 qapi_free_GuestLogicalProcessorList(head);
1886 error_propagate(errp, local_err);
1887 return NULL;
1888}
1889
cbb65fc2
LE
1890int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1891{
1892 int64_t processed;
1893 Error *local_err = NULL;
1894
1895 processed = 0;
1896 while (vcpus != NULL) {
1897 transfer_vcpu(vcpus->value, false, &local_err);
1898 if (local_err != NULL) {
1899 break;
1900 }
1901 ++processed;
1902 vcpus = vcpus->next;
1903 }
1904
1905 if (local_err != NULL) {
1906 if (processed == 0) {
1907 error_propagate(errp, local_err);
1908 } else {
1909 error_free(local_err);
1910 }
1911 }
1912
1913 return processed;
1914}
1915
215a2771
DB
1916void qmp_guest_set_user_password(const char *username,
1917 const char *password,
1918 bool crypted,
1919 Error **errp)
1920{
1921 Error *local_err = NULL;
1922 char *passwd_path = NULL;
1923 pid_t pid;
1924 int status;
1925 int datafd[2] = { -1, -1 };
1926 char *rawpasswddata = NULL;
1927 size_t rawpasswdlen;
1928 char *chpasswddata = NULL;
1929 size_t chpasswdlen;
1930
1931 rawpasswddata = (char *)g_base64_decode(password, &rawpasswdlen);
1932 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1933 rawpasswddata[rawpasswdlen] = '\0';
1934
1935 if (strchr(rawpasswddata, '\n')) {
1936 error_setg(errp, "forbidden characters in raw password");
1937 goto out;
1938 }
1939
1940 if (strchr(username, '\n') ||
1941 strchr(username, ':')) {
1942 error_setg(errp, "forbidden characters in username");
1943 goto out;
1944 }
1945
1946 chpasswddata = g_strdup_printf("%s:%s\n", username, rawpasswddata);
1947 chpasswdlen = strlen(chpasswddata);
1948
1949 passwd_path = g_find_program_in_path("chpasswd");
1950
1951 if (!passwd_path) {
1952 error_setg(errp, "cannot find 'passwd' program in PATH");
1953 goto out;
1954 }
1955
1956 if (pipe(datafd) < 0) {
1957 error_setg(errp, "cannot create pipe FDs");
1958 goto out;
1959 }
1960
1961 pid = fork();
1962 if (pid == 0) {
1963 close(datafd[1]);
1964 /* child */
1965 setsid();
1966 dup2(datafd[0], 0);
1967 reopen_fd_to_null(1);
1968 reopen_fd_to_null(2);
1969
1970 if (crypted) {
1971 execle(passwd_path, "chpasswd", "-e", NULL, environ);
1972 } else {
1973 execle(passwd_path, "chpasswd", NULL, environ);
1974 }
1975 _exit(EXIT_FAILURE);
1976 } else if (pid < 0) {
1977 error_setg_errno(errp, errno, "failed to create child process");
1978 goto out;
1979 }
1980 close(datafd[0]);
1981 datafd[0] = -1;
1982
1983 if (qemu_write_full(datafd[1], chpasswddata, chpasswdlen) != chpasswdlen) {
1984 error_setg_errno(errp, errno, "cannot write new account password");
1985 goto out;
1986 }
1987 close(datafd[1]);
1988 datafd[1] = -1;
1989
1990 ga_wait_child(pid, &status, &local_err);
1991 if (local_err) {
1992 error_propagate(errp, local_err);
1993 goto out;
1994 }
1995
1996 if (!WIFEXITED(status)) {
1997 error_setg(errp, "child process has terminated abnormally");
1998 goto out;
1999 }
2000
2001 if (WEXITSTATUS(status)) {
2002 error_setg(errp, "child process has failed to set user password");
2003 goto out;
2004 }
2005
2006out:
2007 g_free(chpasswddata);
2008 g_free(rawpasswddata);
2009 g_free(passwd_path);
2010 if (datafd[0] != -1) {
2011 close(datafd[0]);
2012 }
2013 if (datafd[1] != -1) {
2014 close(datafd[1]);
2015 }
2016}
2017
bd240fca
HZ
2018static void ga_read_sysfs_file(int dirfd, const char *pathname, char *buf,
2019 int size, Error **errp)
2020{
2021 int fd;
2022 int res;
2023
2024 errno = 0;
2025 fd = openat(dirfd, pathname, O_RDONLY);
2026 if (fd == -1) {
2027 error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2028 return;
2029 }
2030
2031 res = pread(fd, buf, size, 0);
2032 if (res == -1) {
2033 error_setg_errno(errp, errno, "pread sysfs file \"%s\"", pathname);
2034 } else if (res == 0) {
2035 error_setg(errp, "pread sysfs file \"%s\": unexpected EOF", pathname);
2036 }
2037 close(fd);
2038}
2039
2040static void ga_write_sysfs_file(int dirfd, const char *pathname,
2041 const char *buf, int size, Error **errp)
2042{
2043 int fd;
2044
2045 errno = 0;
2046 fd = openat(dirfd, pathname, O_WRONLY);
2047 if (fd == -1) {
2048 error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2049 return;
2050 }
2051
2052 if (pwrite(fd, buf, size, 0) == -1) {
2053 error_setg_errno(errp, errno, "pwrite sysfs file \"%s\"", pathname);
2054 }
2055
2056 close(fd);
2057}
2058
2059/* Transfer online/offline status between @mem_blk and the guest system.
2060 *
2061 * On input either @errp or *@errp must be NULL.
2062 *
2063 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2064 * - R: mem_blk->phys_index
2065 * - W: mem_blk->online
2066 * - W: mem_blk->can_offline
2067 *
2068 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2069 * - R: mem_blk->phys_index
2070 * - R: mem_blk->online
2071 *- R: mem_blk->can_offline
2072 * Written members remain unmodified on error.
2073 */
2074static void transfer_memory_block(GuestMemoryBlock *mem_blk, bool sys2memblk,
2075 GuestMemoryBlockResponse *result,
2076 Error **errp)
2077{
2078 char *dirpath;
2079 int dirfd;
2080 char *status;
2081 Error *local_err = NULL;
2082
2083 if (!sys2memblk) {
2084 DIR *dp;
2085
2086 if (!result) {
2087 error_setg(errp, "Internal error, 'result' should not be NULL");
2088 return;
2089 }
2090 errno = 0;
2091 dp = opendir("/sys/devices/system/memory/");
2092 /* if there is no 'memory' directory in sysfs,
2093 * we think this VM does not support online/offline memory block,
2094 * any other solution?
2095 */
2096 if (!dp && errno == ENOENT) {
2097 result->response =
2098 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2099 goto out1;
2100 }
2101 closedir(dp);
2102 }
2103
2104 dirpath = g_strdup_printf("/sys/devices/system/memory/memory%" PRId64 "/",
2105 mem_blk->phys_index);
2106 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2107 if (dirfd == -1) {
2108 if (sys2memblk) {
2109 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2110 } else {
2111 if (errno == ENOENT) {
2112 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND;
2113 } else {
2114 result->response =
2115 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2116 }
2117 }
2118 g_free(dirpath);
2119 goto out1;
2120 }
2121 g_free(dirpath);
2122
2123 status = g_malloc0(10);
2124 ga_read_sysfs_file(dirfd, "state", status, 10, &local_err);
2125 if (local_err) {
2126 /* treat with sysfs file that not exist in old kernel */
2127 if (errno == ENOENT) {
2128 error_free(local_err);
2129 if (sys2memblk) {
2130 mem_blk->online = true;
2131 mem_blk->can_offline = false;
2132 } else if (!mem_blk->online) {
2133 result->response =
2134 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2135 }
2136 } else {
2137 if (sys2memblk) {
2138 error_propagate(errp, local_err);
2139 } else {
2140 result->response =
2141 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2142 }
2143 }
2144 goto out2;
2145 }
2146
2147 if (sys2memblk) {
2148 char removable = '0';
2149
2150 mem_blk->online = (strncmp(status, "online", 6) == 0);
2151
2152 ga_read_sysfs_file(dirfd, "removable", &removable, 1, &local_err);
2153 if (local_err) {
2154 /* if no 'removable' file, it does't support offline mem blk */
2155 if (errno == ENOENT) {
2156 error_free(local_err);
2157 mem_blk->can_offline = false;
2158 } else {
2159 error_propagate(errp, local_err);
2160 }
2161 } else {
2162 mem_blk->can_offline = (removable != '0');
2163 }
2164 } else {
2165 if (mem_blk->online != (strncmp(status, "online", 6) == 0)) {
2166 char *new_state = mem_blk->online ? g_strdup("online") :
2167 g_strdup("offline");
2168
2169 ga_write_sysfs_file(dirfd, "state", new_state, strlen(new_state),
2170 &local_err);
2171 g_free(new_state);
2172 if (local_err) {
2173 error_free(local_err);
2174 result->response =
2175 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2176 goto out2;
2177 }
2178
2179 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS;
2180 result->has_error_code = false;
2181 } /* otherwise pretend successful re-(on|off)-lining */
2182 }
2183 g_free(status);
2184 close(dirfd);
2185 return;
2186
2187out2:
2188 g_free(status);
2189 close(dirfd);
2190out1:
2191 if (!sys2memblk) {
2192 result->has_error_code = true;
2193 result->error_code = errno;
2194 }
2195}
2196
a065aaa9
HZ
2197GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2198{
bd240fca
HZ
2199 GuestMemoryBlockList *head, **link;
2200 Error *local_err = NULL;
2201 struct dirent *de;
2202 DIR *dp;
2203
2204 head = NULL;
2205 link = &head;
2206
2207 dp = opendir("/sys/devices/system/memory/");
2208 if (!dp) {
2209 error_setg_errno(errp, errno, "Can't open directory"
2210 "\"/sys/devices/system/memory/\"\n");
2211 return NULL;
2212 }
2213
2214 /* Note: the phys_index of memory block may be discontinuous,
2215 * this is because a memblk is the unit of the Sparse Memory design, which
2216 * allows discontinuous memory ranges (ex. NUMA), so here we should
2217 * traverse the memory block directory.
2218 */
2219 while ((de = readdir(dp)) != NULL) {
2220 GuestMemoryBlock *mem_blk;
2221 GuestMemoryBlockList *entry;
2222
2223 if ((strncmp(de->d_name, "memory", 6) != 0) ||
2224 !(de->d_type & DT_DIR)) {
2225 continue;
2226 }
2227
2228 mem_blk = g_malloc0(sizeof *mem_blk);
2229 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2230 mem_blk->phys_index = strtoul(&de->d_name[6], NULL, 10);
2231 mem_blk->has_can_offline = true; /* lolspeak ftw */
2232 transfer_memory_block(mem_blk, true, NULL, &local_err);
2233
2234 entry = g_malloc0(sizeof *entry);
2235 entry->value = mem_blk;
2236
2237 *link = entry;
2238 link = &entry->next;
2239 }
2240
2241 closedir(dp);
2242 if (local_err == NULL) {
2243 /* there's no guest with zero memory blocks */
2244 if (head == NULL) {
2245 error_setg(errp, "guest reported zero memory blocks!");
2246 }
2247 return head;
2248 }
2249
2250 qapi_free_GuestMemoryBlockList(head);
2251 error_propagate(errp, local_err);
a065aaa9
HZ
2252 return NULL;
2253}
2254
2255GuestMemoryBlockResponseList *
2256qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2257{
32ca7927
HZ
2258 GuestMemoryBlockResponseList *head, **link;
2259 Error *local_err = NULL;
2260
2261 head = NULL;
2262 link = &head;
2263
2264 while (mem_blks != NULL) {
2265 GuestMemoryBlockResponse *result;
2266 GuestMemoryBlockResponseList *entry;
2267 GuestMemoryBlock *current_mem_blk = mem_blks->value;
2268
2269 result = g_malloc0(sizeof(*result));
2270 result->phys_index = current_mem_blk->phys_index;
2271 transfer_memory_block(current_mem_blk, false, result, &local_err);
2272 if (local_err) { /* should never happen */
2273 goto err;
2274 }
2275 entry = g_malloc0(sizeof *entry);
2276 entry->value = result;
2277
2278 *link = entry;
2279 link = &entry->next;
2280 mem_blks = mem_blks->next;
2281 }
2282
2283 return head;
2284err:
2285 qapi_free_GuestMemoryBlockResponseList(head);
2286 error_propagate(errp, local_err);
a065aaa9
HZ
2287 return NULL;
2288}
2289
2290GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2291{
ef82b60b
HZ
2292 Error *local_err = NULL;
2293 char *dirpath;
2294 int dirfd;
2295 char *buf;
2296 GuestMemoryBlockInfo *info;
2297
2298 dirpath = g_strdup_printf("/sys/devices/system/memory/");
2299 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2300 if (dirfd == -1) {
2301 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2302 g_free(dirpath);
2303 return NULL;
2304 }
2305 g_free(dirpath);
2306
2307 buf = g_malloc0(20);
2308 ga_read_sysfs_file(dirfd, "block_size_bytes", buf, 20, &local_err);
8ce1ee46 2309 close(dirfd);
ef82b60b
HZ
2310 if (local_err) {
2311 g_free(buf);
2312 error_propagate(errp, local_err);
2313 return NULL;
2314 }
2315
2316 info = g_new0(GuestMemoryBlockInfo, 1);
2317 info->size = strtol(buf, NULL, 16); /* the unit is bytes */
2318
2319 g_free(buf);
2320
2321 return info;
a065aaa9
HZ
2322}
2323
e72c3f2e
MR
2324#else /* defined(__linux__) */
2325
77dbc81b 2326void qmp_guest_suspend_disk(Error **errp)
e72c3f2e 2327{
c6bd8c70 2328 error_setg(errp, QERR_UNSUPPORTED);
e72c3f2e
MR
2329}
2330
77dbc81b 2331void qmp_guest_suspend_ram(Error **errp)
e72c3f2e 2332{
c6bd8c70 2333 error_setg(errp, QERR_UNSUPPORTED);
e72c3f2e
MR
2334}
2335
77dbc81b 2336void qmp_guest_suspend_hybrid(Error **errp)
e72c3f2e 2337{
c6bd8c70 2338 error_setg(errp, QERR_UNSUPPORTED);
e72c3f2e
MR
2339}
2340
d35d4cb5 2341GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
e72c3f2e 2342{
c6bd8c70 2343 error_setg(errp, QERR_UNSUPPORTED);
d35d4cb5 2344 return NULL;
e72c3f2e
MR
2345}
2346
d2baff62
LE
2347GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
2348{
c6bd8c70 2349 error_setg(errp, QERR_UNSUPPORTED);
d2baff62
LE
2350 return NULL;
2351}
2352
cbb65fc2
LE
2353int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
2354{
c6bd8c70 2355 error_setg(errp, QERR_UNSUPPORTED);
cbb65fc2
LE
2356 return -1;
2357}
2358
215a2771
DB
2359void qmp_guest_set_user_password(const char *username,
2360 const char *password,
2361 bool crypted,
2362 Error **errp)
2363{
c6bd8c70 2364 error_setg(errp, QERR_UNSUPPORTED);
215a2771
DB
2365}
2366
a065aaa9
HZ
2367GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2368{
c6bd8c70 2369 error_setg(errp, QERR_UNSUPPORTED);
a065aaa9
HZ
2370 return NULL;
2371}
2372
2373GuestMemoryBlockResponseList *
2374qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2375{
c6bd8c70 2376 error_setg(errp, QERR_UNSUPPORTED);
a065aaa9
HZ
2377 return NULL;
2378}
2379
2380GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2381{
c6bd8c70 2382 error_setg(errp, QERR_UNSUPPORTED);
a065aaa9
HZ
2383 return NULL;
2384}
2385
d35d4cb5
MR
2386#endif
2387
2388#if !defined(CONFIG_FSFREEZE)
2389
46d4c572
TS
2390GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
2391{
c6bd8c70 2392 error_setg(errp, QERR_UNSUPPORTED);
46d4c572
TS
2393 return NULL;
2394}
2395
77dbc81b 2396GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
e72c3f2e 2397{
c6bd8c70 2398 error_setg(errp, QERR_UNSUPPORTED);
d35d4cb5
MR
2399
2400 return 0;
e72c3f2e
MR
2401}
2402
77dbc81b 2403int64_t qmp_guest_fsfreeze_freeze(Error **errp)
e72c3f2e 2404{
c6bd8c70 2405 error_setg(errp, QERR_UNSUPPORTED);
d35d4cb5
MR
2406
2407 return 0;
e72c3f2e
MR
2408}
2409
e99bce20
TS
2410int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
2411 strList *mountpoints,
2412 Error **errp)
2413{
c6bd8c70 2414 error_setg(errp, QERR_UNSUPPORTED);
e99bce20
TS
2415
2416 return 0;
2417}
2418
77dbc81b 2419int64_t qmp_guest_fsfreeze_thaw(Error **errp)
e72c3f2e 2420{
c6bd8c70 2421 error_setg(errp, QERR_UNSUPPORTED);
d35d4cb5
MR
2422
2423 return 0;
e72c3f2e 2424}
eab5fd59
PB
2425#endif /* CONFIG_FSFREEZE */
2426
2427#if !defined(CONFIG_FSTRIM)
e82855d9
JO
2428GuestFilesystemTrimResponse *
2429qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
eab5fd59 2430{
c6bd8c70 2431 error_setg(errp, QERR_UNSUPPORTED);
e82855d9 2432 return NULL;
eab5fd59 2433}
e72c3f2e
MR
2434#endif
2435
1281c08a
TS
2436/* add unsupported commands to the blacklist */
2437GList *ga_command_blacklist_init(GList *blacklist)
2438{
2439#if !defined(__linux__)
2440 {
2441 const char *list[] = {
2442 "guest-suspend-disk", "guest-suspend-ram",
2443 "guest-suspend-hybrid", "guest-network-get-interfaces",
0dd38a03
HZ
2444 "guest-get-vcpus", "guest-set-vcpus",
2445 "guest-get-memory-blocks", "guest-set-memory-blocks",
2446 "guest-get-memory-block-size", NULL};
1281c08a
TS
2447 char **p = (char **)list;
2448
2449 while (*p) {
2450 blacklist = g_list_append(blacklist, *p++);
2451 }
2452 }
2453#endif
2454
2455#if !defined(CONFIG_FSFREEZE)
2456 {
2457 const char *list[] = {
2458 "guest-get-fsinfo", "guest-fsfreeze-status",
2459 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
2460 "guest-fsfreeze-thaw", "guest-get-fsinfo", NULL};
2461 char **p = (char **)list;
2462
2463 while (*p) {
2464 blacklist = g_list_append(blacklist, *p++);
2465 }
2466 }
2467#endif
2468
2469#if !defined(CONFIG_FSTRIM)
2470 blacklist = g_list_append(blacklist, (char *)"guest-fstrim");
2471#endif
2472
2473 return blacklist;
2474}
2475
e3d4d252
MR
2476/* register init/cleanup routines for stateful command groups */
2477void ga_command_state_init(GAState *s, GACommandState *cs)
2478{
7006b9cf 2479#if defined(CONFIG_FSFREEZE)
f22d85e9 2480 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
7006b9cf 2481#endif
e3d4d252
MR
2482 ga_command_state_add(cs, guest_file_init, NULL);
2483}