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