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