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