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