blob: 9f51faea802f0fd92f38ee87c5955313b1dd4ea2 [file] [log] [blame]
Michael Rothe3d4d252011-07-19 15:41:55 -05001/*
Michael Roth42074a92012-01-19 22:19:27 -06002 * QEMU Guest Agent POSIX-specific command implementations
Michael Rothe3d4d252011-07-19 15:41:55 -05003 *
4 * Copyright IBM Corp. 2011
5 *
6 * Authors:
7 * Michael Roth <mdroth@linux.vnet.ibm.com>
Michal Privoznik3424fc92012-02-29 17:02:23 +01008 * Michal Privoznik <mprivozn@redhat.com>
Michael Rothe3d4d252011-07-19 15:41:55 -05009 *
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
Peter Maydell4459bf32016-01-29 17:49:58 +000014#include "qemu/osdep.h"
Michael Rothe3d4d252011-07-19 15:41:55 -050015#include <glib.h>
Michael Rothe3d4d252011-07-19 15:41:55 -050016#include <sys/ioctl.h>
Luiz Capitulino2c02cbf2012-05-23 15:48:05 -030017#include <sys/wait.h>
Tomoki Sekiyama46d4c572014-06-30 17:51:34 -040018#include <dirent.h>
Michael Rothe3d4d252011-07-19 15:41:55 -050019#include "qga/guest-agent-core.h"
20#include "qga-qmp-commands.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010021#include "qapi/qmp/qerror.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010022#include "qemu/queue.h"
23#include "qemu/host-utils.h"
Denis V. Lunev12505392015-10-28 18:13:55 +030024#include "qemu/sockets.h"
Daniel P. Berrange920639c2015-11-23 15:37:07 +000025#include "qemu/base64.h"
Michael Rothe3d4d252011-07-19 15:41:55 -050026
Luiz Capitulino2c02cbf2012-05-23 15:48:05 -030027#ifndef CONFIG_HAS_ENVIRON
Andreas Färbereecae142012-05-27 17:02:20 +020028#ifdef __APPLE__
29#include <crt_externs.h>
30#define environ (*_NSGetEnviron())
31#else
Luiz Capitulino2c02cbf2012-05-23 15:48:05 -030032extern char **environ;
33#endif
Andreas Färbereecae142012-05-27 17:02:20 +020034#endif
Luiz Capitulino2c02cbf2012-05-23 15:48:05 -030035
Michael Rothe72c3f22012-03-25 13:59:41 -050036#if defined(__linux__)
37#include <mntent.h>
38#include <linux/fs.h>
39#include <ifaddrs.h>
40#include <arpa/inet.h>
41#include <sys/socket.h>
42#include <net/if.h>
Michael Rothe72c3f22012-03-25 13:59:41 -050043
Paolo Bonzinieab5fd52012-06-13 07:41:28 +020044#ifdef FIFREEZE
Michael Rothe72c3f22012-03-25 13:59:41 -050045#define CONFIG_FSFREEZE
46#endif
Paolo Bonzinieab5fd52012-06-13 07:41:28 +020047#ifdef FITRIM
48#define CONFIG_FSTRIM
49#endif
Michael Rothe72c3f22012-03-25 13:59:41 -050050#endif
51
Markus Armbruster77dbc812014-05-02 13:26:30 +020052static void ga_wait_child(pid_t pid, int *status, Error **errp)
Luiz Capitulinod220a6d2012-11-27 11:01:58 -020053{
54 pid_t rpid;
55
56 *status = 0;
57
58 do {
59 rpid = waitpid(pid, status, 0);
60 } while (rpid == -1 && errno == EINTR);
61
62 if (rpid == -1) {
Markus Armbruster77dbc812014-05-02 13:26:30 +020063 error_setg_errno(errp, errno, "failed to wait for child (pid: %d)",
64 pid);
Luiz Capitulinod220a6d2012-11-27 11:01:58 -020065 return;
66 }
67
68 g_assert(rpid == pid);
69}
70
Markus Armbruster77dbc812014-05-02 13:26:30 +020071void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
Michael Rothe3d4d252011-07-19 15:41:55 -050072{
Michael Rothe3d4d252011-07-19 15:41:55 -050073 const char *shutdown_flag;
Luiz Capitulinod220a6d2012-11-27 11:01:58 -020074 Error *local_err = NULL;
75 pid_t pid;
Luiz Capitulino36748382012-05-14 15:25:20 -030076 int status;
Michael Rothe3d4d252011-07-19 15:41:55 -050077
78 slog("guest-shutdown called, mode: %s", mode);
79 if (!has_mode || strcmp(mode, "powerdown") == 0) {
80 shutdown_flag = "-P";
81 } else if (strcmp(mode, "halt") == 0) {
82 shutdown_flag = "-H";
83 } else if (strcmp(mode, "reboot") == 0) {
84 shutdown_flag = "-r";
85 } else {
Markus Armbruster77dbc812014-05-02 13:26:30 +020086 error_setg(errp,
Luiz Capitulinod220a6d2012-11-27 11:01:58 -020087 "mode is invalid (valid values are: halt|powerdown|reboot");
Michael Rothe3d4d252011-07-19 15:41:55 -050088 return;
89 }
90
Luiz Capitulinod5dd3492012-05-11 16:19:47 -030091 pid = fork();
92 if (pid == 0) {
Michael Rothe3d4d252011-07-19 15:41:55 -050093 /* child, start the shutdown */
94 setsid();
Luiz Capitulino36748382012-05-14 15:25:20 -030095 reopen_fd_to_null(0);
96 reopen_fd_to_null(1);
97 reopen_fd_to_null(2);
Michael Rothe3d4d252011-07-19 15:41:55 -050098
whitearchey485e7412013-11-06 10:54:04 +090099 execle("/sbin/shutdown", "shutdown", "-h", shutdown_flag, "+0",
Luiz Capitulino36748382012-05-14 15:25:20 -0300100 "hypervisor initiated shutdown", (char*)NULL, environ);
101 _exit(EXIT_FAILURE);
Luiz Capitulinod5dd3492012-05-11 16:19:47 -0300102 } else if (pid < 0) {
Markus Armbruster77dbc812014-05-02 13:26:30 +0200103 error_setg_errno(errp, errno, "failed to create child process");
Luiz Capitulinod5dd3492012-05-11 16:19:47 -0300104 return;
105 }
106
Luiz Capitulinod220a6d2012-11-27 11:01:58 -0200107 ga_wait_child(pid, &status, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100108 if (local_err) {
Markus Armbruster77dbc812014-05-02 13:26:30 +0200109 error_propagate(errp, local_err);
Luiz Capitulinod220a6d2012-11-27 11:01:58 -0200110 return;
111 }
112
113 if (!WIFEXITED(status)) {
Markus Armbruster77dbc812014-05-02 13:26:30 +0200114 error_setg(errp, "child process has terminated abnormally");
Luiz Capitulinod220a6d2012-11-27 11:01:58 -0200115 return;
116 }
117
118 if (WEXITSTATUS(status)) {
Markus Armbruster77dbc812014-05-02 13:26:30 +0200119 error_setg(errp, "child process has failed to shutdown");
Luiz Capitulinod220a6d2012-11-27 11:01:58 -0200120 return;
121 }
122
Peter Maydell085d8132013-03-18 17:20:07 +0000123 /* succeeded */
Michael Rothe3d4d252011-07-19 15:41:55 -0500124}
125
Lei Li6912e6a2013-03-05 17:39:11 +0800126int64_t qmp_guest_get_time(Error **errp)
127{
128 int ret;
129 qemu_timeval tq;
130 int64_t time_ns;
131
132 ret = qemu_gettimeofday(&tq);
133 if (ret < 0) {
134 error_setg_errno(errp, errno, "Failed to get time");
135 return -1;
136 }
137
138 time_ns = tq.tv_sec * 1000000000LL + tq.tv_usec * 1000;
139 return time_ns;
140}
141
Michal Privoznik2c958922014-01-31 11:29:51 +0100142void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
Lei Lia1bca572013-03-05 17:39:12 +0800143{
144 int ret;
145 int status;
146 pid_t pid;
147 Error *local_err = NULL;
148 struct timeval tv;
149
Michal Privoznik2c958922014-01-31 11:29:51 +0100150 /* If user has passed a time, validate and set it. */
151 if (has_time) {
Marc-André Lureau00d2f372015-07-05 16:28:58 +0200152 GDate date = { 0, };
153
Michal Privoznik2c958922014-01-31 11:29:51 +0100154 /* year-2038 will overflow in case time_t is 32bit */
155 if (time_ns / 1000000000 != (time_t)(time_ns / 1000000000)) {
156 error_setg(errp, "Time %" PRId64 " is too large", time_ns);
157 return;
158 }
159
160 tv.tv_sec = time_ns / 1000000000;
161 tv.tv_usec = (time_ns % 1000000000) / 1000;
Marc-André Lureau00d2f372015-07-05 16:28:58 +0200162 g_date_set_time_t(&date, tv.tv_sec);
163 if (date.year < 1970 || date.year >= 2070) {
164 error_setg_errno(errp, errno, "Invalid time");
165 return;
166 }
Michal Privoznik2c958922014-01-31 11:29:51 +0100167
168 ret = settimeofday(&tv, NULL);
169 if (ret < 0) {
170 error_setg_errno(errp, errno, "Failed to set time to guest");
171 return;
172 }
Lei Lia1bca572013-03-05 17:39:12 +0800173 }
174
Michal Privoznik2c958922014-01-31 11:29:51 +0100175 /* Now, if user has passed a time to set and the system time is set, we
176 * just need to synchronize the hardware clock. However, if no time was
177 * passed, user is requesting the opposite: set the system time from the
Amos Kong1634df52014-04-04 23:25:02 +0800178 * hardware clock (RTC). */
Lei Lia1bca572013-03-05 17:39:12 +0800179 pid = fork();
180 if (pid == 0) {
181 setsid();
182 reopen_fd_to_null(0);
183 reopen_fd_to_null(1);
184 reopen_fd_to_null(2);
185
Michal Privoznik2c958922014-01-31 11:29:51 +0100186 /* Use '/sbin/hwclock -w' to set RTC from the system time,
187 * or '/sbin/hwclock -s' to set the system time from RTC. */
188 execle("/sbin/hwclock", "hwclock", has_time ? "-w" : "-s",
189 NULL, environ);
Lei Lia1bca572013-03-05 17:39:12 +0800190 _exit(EXIT_FAILURE);
191 } else if (pid < 0) {
192 error_setg_errno(errp, errno, "failed to create child process");
193 return;
194 }
195
196 ga_wait_child(pid, &status, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100197 if (local_err) {
Lei Lia1bca572013-03-05 17:39:12 +0800198 error_propagate(errp, local_err);
199 return;
200 }
201
202 if (!WIFEXITED(status)) {
203 error_setg(errp, "child process has terminated abnormally");
204 return;
205 }
206
207 if (WEXITSTATUS(status)) {
208 error_setg(errp, "hwclock failed to set hardware clock to system time");
209 return;
210 }
211}
212
Marc-André Lureau895b00f2015-11-25 13:59:11 +0100213typedef enum {
214 RW_STATE_NEW,
215 RW_STATE_READING,
216 RW_STATE_WRITING,
217} RwState;
218
Michael Rothe3d4d252011-07-19 15:41:55 -0500219typedef struct GuestFileHandle {
220 uint64_t id;
221 FILE *fh;
Marc-André Lureau895b00f2015-11-25 13:59:11 +0100222 RwState state;
Michael Rothe3d4d252011-07-19 15:41:55 -0500223 QTAILQ_ENTRY(GuestFileHandle) next;
224} GuestFileHandle;
225
226static struct {
227 QTAILQ_HEAD(, GuestFileHandle) filehandles;
Denis V. Lunevb4fe97c2015-10-13 18:41:19 +0300228} guest_file_state = {
229 .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
230};
Michael Rothe3d4d252011-07-19 15:41:55 -0500231
Michael Roth39097da2013-03-01 11:40:27 -0600232static int64_t guest_file_handle_add(FILE *fh, Error **errp)
Michael Rothe3d4d252011-07-19 15:41:55 -0500233{
234 GuestFileHandle *gfh;
Michael Roth39097da2013-03-01 11:40:27 -0600235 int64_t handle;
236
237 handle = ga_get_fd_handle(ga_state, errp);
Markus Armbrustera903f402014-05-02 13:26:33 +0200238 if (handle < 0) {
239 return -1;
Michael Roth39097da2013-03-01 11:40:27 -0600240 }
Michael Rothe3d4d252011-07-19 15:41:55 -0500241
Markus Armbrusterf3a06402015-09-14 13:50:44 +0200242 gfh = g_new0(GuestFileHandle, 1);
Michael Roth39097da2013-03-01 11:40:27 -0600243 gfh->id = handle;
Michael Rothe3d4d252011-07-19 15:41:55 -0500244 gfh->fh = fh;
245 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
Michael Roth39097da2013-03-01 11:40:27 -0600246
247 return handle;
Michael Rothe3d4d252011-07-19 15:41:55 -0500248}
249
Markus Armbruster77dbc812014-05-02 13:26:30 +0200250static GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
Michael Rothe3d4d252011-07-19 15:41:55 -0500251{
252 GuestFileHandle *gfh;
253
254 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next)
255 {
256 if (gfh->id == id) {
257 return gfh;
258 }
259 }
260
Markus Armbruster77dbc812014-05-02 13:26:30 +0200261 error_setg(errp, "handle '%" PRId64 "' has not been found", id);
Michael Rothe3d4d252011-07-19 15:41:55 -0500262 return NULL;
263}
264
Laszlo Ersekc689b4f2013-04-24 13:13:18 +0200265typedef const char * const ccpc;
266
Laszlo Ersek8fe6bbc2013-05-08 17:31:35 +0200267#ifndef O_BINARY
268#define O_BINARY 0
269#endif
270
Laszlo Ersekc689b4f2013-04-24 13:13:18 +0200271/* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
272static const struct {
273 ccpc *forms;
274 int oflag_base;
275} guest_file_open_modes[] = {
Laszlo Ersek8fe6bbc2013-05-08 17:31:35 +0200276 { (ccpc[]){ "r", NULL }, O_RDONLY },
277 { (ccpc[]){ "rb", NULL }, O_RDONLY | O_BINARY },
278 { (ccpc[]){ "w", NULL }, O_WRONLY | O_CREAT | O_TRUNC },
279 { (ccpc[]){ "wb", NULL }, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY },
280 { (ccpc[]){ "a", NULL }, O_WRONLY | O_CREAT | O_APPEND },
281 { (ccpc[]){ "ab", NULL }, O_WRONLY | O_CREAT | O_APPEND | O_BINARY },
282 { (ccpc[]){ "r+", NULL }, O_RDWR },
283 { (ccpc[]){ "rb+", "r+b", NULL }, O_RDWR | O_BINARY },
284 { (ccpc[]){ "w+", NULL }, O_RDWR | O_CREAT | O_TRUNC },
285 { (ccpc[]){ "wb+", "w+b", NULL }, O_RDWR | O_CREAT | O_TRUNC | O_BINARY },
286 { (ccpc[]){ "a+", NULL }, O_RDWR | O_CREAT | O_APPEND },
287 { (ccpc[]){ "ab+", "a+b", NULL }, O_RDWR | O_CREAT | O_APPEND | O_BINARY }
Laszlo Ersekc689b4f2013-04-24 13:13:18 +0200288};
289
290static int
Markus Armbruster77dbc812014-05-02 13:26:30 +0200291find_open_flag(const char *mode_str, Error **errp)
Laszlo Ersekc689b4f2013-04-24 13:13:18 +0200292{
293 unsigned mode;
294
295 for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
296 ccpc *form;
297
298 form = guest_file_open_modes[mode].forms;
299 while (*form != NULL && strcmp(*form, mode_str) != 0) {
300 ++form;
301 }
302 if (*form != NULL) {
303 break;
304 }
305 }
306
307 if (mode == ARRAY_SIZE(guest_file_open_modes)) {
Markus Armbruster77dbc812014-05-02 13:26:30 +0200308 error_setg(errp, "invalid file open mode '%s'", mode_str);
Laszlo Ersekc689b4f2013-04-24 13:13:18 +0200309 return -1;
310 }
311 return guest_file_open_modes[mode].oflag_base | O_NOCTTY | O_NONBLOCK;
312}
313
314#define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
315 S_IRGRP | S_IWGRP | \
316 S_IROTH | S_IWOTH)
317
318static FILE *
Markus Armbruster77dbc812014-05-02 13:26:30 +0200319safe_open_or_create(const char *path, const char *mode, Error **errp)
Laszlo Ersekc689b4f2013-04-24 13:13:18 +0200320{
321 Error *local_err = NULL;
322 int oflag;
323
324 oflag = find_open_flag(mode, &local_err);
325 if (local_err == NULL) {
326 int fd;
327
328 /* If the caller wants / allows creation of a new file, we implement it
329 * with a two step process: open() + (open() / fchmod()).
330 *
331 * First we insist on creating the file exclusively as a new file. If
332 * that succeeds, we're free to set any file-mode bits on it. (The
333 * motivation is that we want to set those file-mode bits independently
334 * of the current umask.)
335 *
336 * If the exclusive creation fails because the file already exists
337 * (EEXIST is not possible for any other reason), we just attempt to
338 * open the file, but in this case we won't be allowed to change the
339 * file-mode bits on the preexistent file.
340 *
341 * The pathname should never disappear between the two open()s in
342 * practice. If it happens, then someone very likely tried to race us.
343 * In this case just go ahead and report the ENOENT from the second
344 * open() to the caller.
345 *
346 * If the caller wants to open a preexistent file, then the first
347 * open() is decisive and its third argument is ignored, and the second
348 * open() and the fchmod() are never called.
349 */
350 fd = open(path, oflag | ((oflag & O_CREAT) ? O_EXCL : 0), 0);
351 if (fd == -1 && errno == EEXIST) {
352 oflag &= ~(unsigned)O_CREAT;
353 fd = open(path, oflag);
354 }
355
356 if (fd == -1) {
357 error_setg_errno(&local_err, errno, "failed to open file '%s' "
358 "(mode: '%s')", path, mode);
359 } else {
360 qemu_set_cloexec(fd);
361
362 if ((oflag & O_CREAT) && fchmod(fd, DEFAULT_NEW_FILE_MODE) == -1) {
363 error_setg_errno(&local_err, errno, "failed to set permission "
364 "0%03o on new file '%s' (mode: '%s')",
365 (unsigned)DEFAULT_NEW_FILE_MODE, path, mode);
366 } else {
367 FILE *f;
368
369 f = fdopen(fd, mode);
370 if (f == NULL) {
371 error_setg_errno(&local_err, errno, "failed to associate "
372 "stdio stream with file descriptor %d, "
373 "file '%s' (mode: '%s')", fd, path, mode);
374 } else {
375 return f;
376 }
377 }
378
379 close(fd);
Laszlo Ersek2b720012013-05-08 17:31:36 +0200380 if (oflag & O_CREAT) {
381 unlink(path);
382 }
Laszlo Ersekc689b4f2013-04-24 13:13:18 +0200383 }
384 }
385
Markus Armbruster77dbc812014-05-02 13:26:30 +0200386 error_propagate(errp, local_err);
Laszlo Ersekc689b4f2013-04-24 13:13:18 +0200387 return NULL;
388}
389
Markus Armbruster77dbc812014-05-02 13:26:30 +0200390int64_t qmp_guest_file_open(const char *path, bool has_mode, const char *mode,
391 Error **errp)
Michael Rothe3d4d252011-07-19 15:41:55 -0500392{
393 FILE *fh;
Laszlo Ersekc689b4f2013-04-24 13:13:18 +0200394 Error *local_err = NULL;
Simon Zolin85b6f6f2015-02-06 20:59:54 +0300395 int64_t handle;
Michael Rothe3d4d252011-07-19 15:41:55 -0500396
397 if (!has_mode) {
398 mode = "r";
399 }
400 slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
Laszlo Ersekc689b4f2013-04-24 13:13:18 +0200401 fh = safe_open_or_create(path, mode, &local_err);
402 if (local_err != NULL) {
Markus Armbruster77dbc812014-05-02 13:26:30 +0200403 error_propagate(errp, local_err);
Michael Rothe3d4d252011-07-19 15:41:55 -0500404 return -1;
405 }
406
407 /* set fd non-blocking to avoid common use cases (like reading from a
408 * named pipe) from hanging the agent
409 */
Denis V. Lunev12505392015-10-28 18:13:55 +0300410 qemu_set_nonblock(fileno(fh));
Michael Rothe3d4d252011-07-19 15:41:55 -0500411
Markus Armbruster77dbc812014-05-02 13:26:30 +0200412 handle = guest_file_handle_add(fh, errp);
Markus Armbrustera903f402014-05-02 13:26:33 +0200413 if (handle < 0) {
Michael Roth39097da2013-03-01 11:40:27 -0600414 fclose(fh);
415 return -1;
416 }
417
Stefan Weild607a522013-11-17 19:19:52 +0100418 slog("guest-file-open, handle: %" PRId64, handle);
Michael Roth39097da2013-03-01 11:40:27 -0600419 return handle;
Michael Rothe3d4d252011-07-19 15:41:55 -0500420}
421
Markus Armbruster77dbc812014-05-02 13:26:30 +0200422void qmp_guest_file_close(int64_t handle, Error **errp)
Michael Rothe3d4d252011-07-19 15:41:55 -0500423{
Markus Armbruster77dbc812014-05-02 13:26:30 +0200424 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
Michael Rothe3d4d252011-07-19 15:41:55 -0500425 int ret;
426
Stefan Weild607a522013-11-17 19:19:52 +0100427 slog("guest-file-close called, handle: %" PRId64, handle);
Michael Rothe3d4d252011-07-19 15:41:55 -0500428 if (!gfh) {
Michael Rothe3d4d252011-07-19 15:41:55 -0500429 return;
430 }
431
432 ret = fclose(gfh->fh);
Luiz Capitulino3ac4b7c2012-11-27 11:01:56 -0200433 if (ret == EOF) {
Markus Armbruster77dbc812014-05-02 13:26:30 +0200434 error_setg_errno(errp, errno, "failed to close handle");
Michael Rothe3d4d252011-07-19 15:41:55 -0500435 return;
436 }
437
438 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
Anthony Liguori7267c092011-08-20 22:09:37 -0500439 g_free(gfh);
Michael Rothe3d4d252011-07-19 15:41:55 -0500440}
441
442struct GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
Markus Armbruster77dbc812014-05-02 13:26:30 +0200443 int64_t count, Error **errp)
Michael Rothe3d4d252011-07-19 15:41:55 -0500444{
Markus Armbruster77dbc812014-05-02 13:26:30 +0200445 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
Michael Rothe3d4d252011-07-19 15:41:55 -0500446 GuestFileRead *read_data = NULL;
447 guchar *buf;
448 FILE *fh;
449 size_t read_count;
450
451 if (!gfh) {
Michael Rothe3d4d252011-07-19 15:41:55 -0500452 return NULL;
453 }
454
455 if (!has_count) {
456 count = QGA_READ_COUNT_DEFAULT;
457 } else if (count < 0) {
Markus Armbruster77dbc812014-05-02 13:26:30 +0200458 error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
Luiz Capitulinodb3edb62012-11-27 11:01:57 -0200459 count);
Michael Rothe3d4d252011-07-19 15:41:55 -0500460 return NULL;
461 }
462
463 fh = gfh->fh;
Marc-André Lureau895b00f2015-11-25 13:59:11 +0100464
465 /* explicitly flush when switching from writing to reading */
466 if (gfh->state == RW_STATE_WRITING) {
467 int ret = fflush(fh);
468 if (ret == EOF) {
469 error_setg_errno(errp, errno, "failed to flush file");
470 return NULL;
471 }
472 gfh->state = RW_STATE_NEW;
473 }
474
Anthony Liguori7267c092011-08-20 22:09:37 -0500475 buf = g_malloc0(count+1);
Michael Rothe3d4d252011-07-19 15:41:55 -0500476 read_count = fread(buf, 1, count, fh);
477 if (ferror(fh)) {
Markus Armbruster77dbc812014-05-02 13:26:30 +0200478 error_setg_errno(errp, errno, "failed to read file");
Stefan Weild607a522013-11-17 19:19:52 +0100479 slog("guest-file-read failed, handle: %" PRId64, handle);
Michael Rothe3d4d252011-07-19 15:41:55 -0500480 } else {
481 buf[read_count] = 0;
Markus Armbrusterf3a06402015-09-14 13:50:44 +0200482 read_data = g_new0(GuestFileRead, 1);
Michael Rothe3d4d252011-07-19 15:41:55 -0500483 read_data->count = read_count;
484 read_data->eof = feof(fh);
485 if (read_count) {
486 read_data->buf_b64 = g_base64_encode(buf, read_count);
487 }
Marc-André Lureau895b00f2015-11-25 13:59:11 +0100488 gfh->state = RW_STATE_READING;
Michael Rothe3d4d252011-07-19 15:41:55 -0500489 }
Anthony Liguori7267c092011-08-20 22:09:37 -0500490 g_free(buf);
Michael Rothe3d4d252011-07-19 15:41:55 -0500491 clearerr(fh);
492
493 return read_data;
494}
495
496GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
Markus Armbruster77dbc812014-05-02 13:26:30 +0200497 bool has_count, int64_t count,
498 Error **errp)
Michael Rothe3d4d252011-07-19 15:41:55 -0500499{
500 GuestFileWrite *write_data = NULL;
501 guchar *buf;
502 gsize buf_len;
503 int write_count;
Markus Armbruster77dbc812014-05-02 13:26:30 +0200504 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
Michael Rothe3d4d252011-07-19 15:41:55 -0500505 FILE *fh;
506
507 if (!gfh) {
Michael Rothe3d4d252011-07-19 15:41:55 -0500508 return NULL;
509 }
510
511 fh = gfh->fh;
Marc-André Lureau895b00f2015-11-25 13:59:11 +0100512
513 if (gfh->state == RW_STATE_READING) {
514 int ret = fseek(fh, 0, SEEK_CUR);
515 if (ret == -1) {
516 error_setg_errno(errp, errno, "failed to seek file");
517 return NULL;
518 }
519 gfh->state = RW_STATE_NEW;
520 }
521
Daniel P. Berrange920639c2015-11-23 15:37:07 +0000522 buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
523 if (!buf) {
524 return NULL;
525 }
Michael Rothe3d4d252011-07-19 15:41:55 -0500526
527 if (!has_count) {
528 count = buf_len;
529 } else if (count < 0 || count > buf_len) {
Markus Armbruster77dbc812014-05-02 13:26:30 +0200530 error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
Luiz Capitulinodb3edb62012-11-27 11:01:57 -0200531 count);
Anthony Liguori7267c092011-08-20 22:09:37 -0500532 g_free(buf);
Michael Rothe3d4d252011-07-19 15:41:55 -0500533 return NULL;
534 }
535
536 write_count = fwrite(buf, 1, count, fh);
537 if (ferror(fh)) {
Markus Armbruster77dbc812014-05-02 13:26:30 +0200538 error_setg_errno(errp, errno, "failed to write to file");
Stefan Weild607a522013-11-17 19:19:52 +0100539 slog("guest-file-write failed, handle: %" PRId64, handle);
Michael Rothe3d4d252011-07-19 15:41:55 -0500540 } else {
Markus Armbrusterf3a06402015-09-14 13:50:44 +0200541 write_data = g_new0(GuestFileWrite, 1);
Michael Rothe3d4d252011-07-19 15:41:55 -0500542 write_data->count = write_count;
543 write_data->eof = feof(fh);
Marc-André Lureau895b00f2015-11-25 13:59:11 +0100544 gfh->state = RW_STATE_WRITING;
Michael Rothe3d4d252011-07-19 15:41:55 -0500545 }
Anthony Liguori7267c092011-08-20 22:09:37 -0500546 g_free(buf);
Michael Rothe3d4d252011-07-19 15:41:55 -0500547 clearerr(fh);
548
549 return write_data;
550}
551
552struct GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
Eric Blake0b4b4932016-02-09 14:27:16 -0700553 GuestFileWhence *whence_code,
554 Error **errp)
Michael Rothe3d4d252011-07-19 15:41:55 -0500555{
Markus Armbruster77dbc812014-05-02 13:26:30 +0200556 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
Michael Rothe3d4d252011-07-19 15:41:55 -0500557 GuestFileSeek *seek_data = NULL;
558 FILE *fh;
559 int ret;
Eric Blake0a982b12015-11-25 10:37:15 -0700560 int whence;
Eric Blake0b4b4932016-02-09 14:27:16 -0700561 Error *err = NULL;
Michael Rothe3d4d252011-07-19 15:41:55 -0500562
563 if (!gfh) {
Michael Rothe3d4d252011-07-19 15:41:55 -0500564 return NULL;
565 }
566
Eric Blake0a982b12015-11-25 10:37:15 -0700567 /* We stupidly exposed 'whence':'int' in our qapi */
Eric Blake0b4b4932016-02-09 14:27:16 -0700568 whence = ga_parse_whence(whence_code, &err);
569 if (err) {
570 error_propagate(errp, err);
Eric Blake0a982b12015-11-25 10:37:15 -0700571 return NULL;
572 }
573
Michael Rothe3d4d252011-07-19 15:41:55 -0500574 fh = gfh->fh;
575 ret = fseek(fh, offset, whence);
576 if (ret == -1) {
Markus Armbruster77dbc812014-05-02 13:26:30 +0200577 error_setg_errno(errp, errno, "failed to seek file");
Marc-André Lureau895b00f2015-11-25 13:59:11 +0100578 if (errno == ESPIPE) {
579 /* file is non-seekable, stdio shouldn't be buffering anyways */
580 gfh->state = RW_STATE_NEW;
581 }
Michael Rothe3d4d252011-07-19 15:41:55 -0500582 } else {
Markus Armbruster10b7c5d2014-02-21 13:36:49 +0100583 seek_data = g_new0(GuestFileSeek, 1);
Michael Rothe3d4d252011-07-19 15:41:55 -0500584 seek_data->position = ftell(fh);
585 seek_data->eof = feof(fh);
Marc-André Lureau895b00f2015-11-25 13:59:11 +0100586 gfh->state = RW_STATE_NEW;
Michael Rothe3d4d252011-07-19 15:41:55 -0500587 }
588 clearerr(fh);
589
590 return seek_data;
591}
592
Markus Armbruster77dbc812014-05-02 13:26:30 +0200593void qmp_guest_file_flush(int64_t handle, Error **errp)
Michael Rothe3d4d252011-07-19 15:41:55 -0500594{
Markus Armbruster77dbc812014-05-02 13:26:30 +0200595 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
Michael Rothe3d4d252011-07-19 15:41:55 -0500596 FILE *fh;
597 int ret;
598
599 if (!gfh) {
Michael Rothe3d4d252011-07-19 15:41:55 -0500600 return;
601 }
602
603 fh = gfh->fh;
604 ret = fflush(fh);
605 if (ret == EOF) {
Markus Armbruster77dbc812014-05-02 13:26:30 +0200606 error_setg_errno(errp, errno, "failed to flush file");
Marc-André Lureau895b00f2015-11-25 13:59:11 +0100607 } else {
608 gfh->state = RW_STATE_NEW;
Michael Rothe3d4d252011-07-19 15:41:55 -0500609 }
610}
611
Michael Rothe72c3f22012-03-25 13:59:41 -0500612/* linux-specific implementations. avoid this if at all possible. */
613#if defined(__linux__)
614
Paolo Bonzinieab5fd52012-06-13 07:41:28 +0200615#if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
Paolo Bonziniaf022032012-06-13 07:41:27 +0200616typedef struct FsMount {
Michael Rothe3d4d252011-07-19 15:41:55 -0500617 char *dirname;
618 char *devtype;
Tomoki Sekiyama46d4c572014-06-30 17:51:34 -0400619 unsigned int devmajor, devminor;
Paolo Bonziniaf022032012-06-13 07:41:27 +0200620 QTAILQ_ENTRY(FsMount) next;
621} FsMount;
Michael Rothe3d4d252011-07-19 15:41:55 -0500622
Tomoki Sekiyamae5d9adb2013-10-01 17:09:53 -0400623typedef QTAILQ_HEAD(FsMountList, FsMount) FsMountList;
Michael Roth9e8aded432012-04-16 19:52:17 -0500624
Paolo Bonziniaf022032012-06-13 07:41:27 +0200625static void free_fs_mount_list(FsMountList *mounts)
Michael Roth9e8aded432012-04-16 19:52:17 -0500626{
Paolo Bonziniaf022032012-06-13 07:41:27 +0200627 FsMount *mount, *temp;
Michael Roth9e8aded432012-04-16 19:52:17 -0500628
629 if (!mounts) {
630 return;
631 }
632
633 QTAILQ_FOREACH_SAFE(mount, mounts, next, temp) {
634 QTAILQ_REMOVE(mounts, mount, next);
635 g_free(mount->dirname);
636 g_free(mount->devtype);
637 g_free(mount);
638 }
639}
640
Tomoki Sekiyama46d4c572014-06-30 17:51:34 -0400641static int dev_major_minor(const char *devpath,
642 unsigned int *devmajor, unsigned int *devminor)
643{
644 struct stat st;
645
646 *devmajor = 0;
647 *devminor = 0;
648
649 if (stat(devpath, &st) < 0) {
650 slog("failed to stat device file '%s': %s", devpath, strerror(errno));
651 return -1;
652 }
653 if (S_ISDIR(st.st_mode)) {
654 /* It is bind mount */
655 return -2;
656 }
657 if (S_ISBLK(st.st_mode)) {
658 *devmajor = major(st.st_rdev);
659 *devminor = minor(st.st_rdev);
660 return 0;
661 }
662 return -1;
663}
664
Michael Rothe3d4d252011-07-19 15:41:55 -0500665/*
666 * Walk the mount table and build a list of local file systems
667 */
Tomoki Sekiyama46d4c572014-06-30 17:51:34 -0400668static void build_fs_mount_list_from_mtab(FsMountList *mounts, Error **errp)
Michael Rothe3d4d252011-07-19 15:41:55 -0500669{
670 struct mntent *ment;
Paolo Bonziniaf022032012-06-13 07:41:27 +0200671 FsMount *mount;
Michael Roth9e2fa412012-05-29 10:08:50 -0500672 char const *mtab = "/proc/self/mounts";
Michael Rothe3d4d252011-07-19 15:41:55 -0500673 FILE *fp;
Tomoki Sekiyama46d4c572014-06-30 17:51:34 -0400674 unsigned int devmajor, devminor;
Michael Rothe3d4d252011-07-19 15:41:55 -0500675
Michael Rothe3d4d252011-07-19 15:41:55 -0500676 fp = setmntent(mtab, "r");
677 if (!fp) {
Markus Armbruster77dbc812014-05-02 13:26:30 +0200678 error_setg(errp, "failed to open mtab file: '%s'", mtab);
Luiz Capitulino261551d2012-11-29 15:29:11 -0200679 return;
Michael Rothe3d4d252011-07-19 15:41:55 -0500680 }
681
682 while ((ment = getmntent(fp))) {
683 /*
684 * An entry which device name doesn't start with a '/' is
685 * either a dummy file system or a network file system.
686 * Add special handling for smbfs and cifs as is done by
687 * coreutils as well.
688 */
689 if ((ment->mnt_fsname[0] != '/') ||
690 (strcmp(ment->mnt_type, "smbfs") == 0) ||
691 (strcmp(ment->mnt_type, "cifs") == 0)) {
692 continue;
693 }
Tomoki Sekiyama46d4c572014-06-30 17:51:34 -0400694 if (dev_major_minor(ment->mnt_fsname, &devmajor, &devminor) == -2) {
695 /* Skip bind mounts */
696 continue;
697 }
Michael Rothe3d4d252011-07-19 15:41:55 -0500698
Markus Armbrusterf3a06402015-09-14 13:50:44 +0200699 mount = g_new0(FsMount, 1);
Anthony Liguori7267c092011-08-20 22:09:37 -0500700 mount->dirname = g_strdup(ment->mnt_dir);
701 mount->devtype = g_strdup(ment->mnt_type);
Tomoki Sekiyama46d4c572014-06-30 17:51:34 -0400702 mount->devmajor = devmajor;
703 mount->devminor = devminor;
Michael Rothe3d4d252011-07-19 15:41:55 -0500704
Michael Roth9e8aded432012-04-16 19:52:17 -0500705 QTAILQ_INSERT_TAIL(mounts, mount, next);
Michael Rothe3d4d252011-07-19 15:41:55 -0500706 }
707
708 endmntent(fp);
Michael Rothe3d4d252011-07-19 15:41:55 -0500709}
Tomoki Sekiyama46d4c572014-06-30 17:51:34 -0400710
711static void decode_mntname(char *name, int len)
712{
713 int i, j = 0;
714 for (i = 0; i <= len; i++) {
715 if (name[i] != '\\') {
716 name[j++] = name[i];
717 } else if (name[i + 1] == '\\') {
718 name[j++] = '\\';
719 i++;
720 } else if (name[i + 1] >= '0' && name[i + 1] <= '3' &&
721 name[i + 2] >= '0' && name[i + 2] <= '7' &&
722 name[i + 3] >= '0' && name[i + 3] <= '7') {
723 name[j++] = (name[i + 1] - '0') * 64 +
724 (name[i + 2] - '0') * 8 +
725 (name[i + 3] - '0');
726 i += 3;
727 } else {
728 name[j++] = name[i];
729 }
730 }
731}
732
733static void build_fs_mount_list(FsMountList *mounts, Error **errp)
734{
735 FsMount *mount;
736 char const *mountinfo = "/proc/self/mountinfo";
737 FILE *fp;
738 char *line = NULL, *dash;
739 size_t n;
740 char check;
741 unsigned int devmajor, devminor;
742 int ret, dir_s, dir_e, type_s, type_e, dev_s, dev_e;
743
744 fp = fopen(mountinfo, "r");
745 if (!fp) {
746 build_fs_mount_list_from_mtab(mounts, errp);
747 return;
748 }
749
750 while (getline(&line, &n, fp) != -1) {
751 ret = sscanf(line, "%*u %*u %u:%u %*s %n%*s%n%c",
752 &devmajor, &devminor, &dir_s, &dir_e, &check);
753 if (ret < 3) {
754 continue;
755 }
756 dash = strstr(line + dir_e, " - ");
757 if (!dash) {
758 continue;
759 }
760 ret = sscanf(dash, " - %n%*s%n %n%*s%n%c",
761 &type_s, &type_e, &dev_s, &dev_e, &check);
762 if (ret < 1) {
763 continue;
764 }
765 line[dir_e] = 0;
766 dash[type_e] = 0;
767 dash[dev_e] = 0;
768 decode_mntname(line + dir_s, dir_e - dir_s);
769 decode_mntname(dash + dev_s, dev_e - dev_s);
770 if (devmajor == 0) {
771 /* btrfs reports major number = 0 */
772 if (strcmp("btrfs", dash + type_s) != 0 ||
773 dev_major_minor(dash + dev_s, &devmajor, &devminor) < 0) {
774 continue;
775 }
776 }
777
Markus Armbrusterf3a06402015-09-14 13:50:44 +0200778 mount = g_new0(FsMount, 1);
Tomoki Sekiyama46d4c572014-06-30 17:51:34 -0400779 mount->dirname = g_strdup(line + dir_s);
780 mount->devtype = g_strdup(dash + type_s);
781 mount->devmajor = devmajor;
782 mount->devminor = devminor;
783
784 QTAILQ_INSERT_TAIL(mounts, mount, next);
785 }
786 free(line);
787
788 fclose(fp);
789}
Paolo Bonzinieab5fd52012-06-13 07:41:28 +0200790#endif
791
792#if defined(CONFIG_FSFREEZE)
Michael Rothe3d4d252011-07-19 15:41:55 -0500793
Tomoki Sekiyama46d4c572014-06-30 17:51:34 -0400794static char *get_pci_driver(char const *syspath, int pathlen, Error **errp)
795{
796 char *path;
797 char *dpath;
798 char *driver = NULL;
799 char buf[PATH_MAX];
800 ssize_t len;
801
802 path = g_strndup(syspath, pathlen);
803 dpath = g_strdup_printf("%s/driver", path);
804 len = readlink(dpath, buf, sizeof(buf) - 1);
805 if (len != -1) {
806 buf[len] = 0;
807 driver = g_strdup(basename(buf));
808 }
809 g_free(dpath);
810 g_free(path);
811 return driver;
812}
813
814static int compare_uint(const void *_a, const void *_b)
815{
816 unsigned int a = *(unsigned int *)_a;
817 unsigned int b = *(unsigned int *)_b;
818
819 return a < b ? -1 : a > b ? 1 : 0;
820}
821
822/* Walk the specified sysfs and build a sorted list of host or ata numbers */
823static int build_hosts(char const *syspath, char const *host, bool ata,
824 unsigned int *hosts, int hosts_max, Error **errp)
825{
826 char *path;
827 DIR *dir;
828 struct dirent *entry;
829 int i = 0;
830
831 path = g_strndup(syspath, host - syspath);
832 dir = opendir(path);
833 if (!dir) {
834 error_setg_errno(errp, errno, "opendir(\"%s\")", path);
835 g_free(path);
836 return -1;
837 }
838
839 while (i < hosts_max) {
840 entry = readdir(dir);
841 if (!entry) {
842 break;
843 }
844 if (ata && sscanf(entry->d_name, "ata%d", hosts + i) == 1) {
845 ++i;
846 } else if (!ata && sscanf(entry->d_name, "host%d", hosts + i) == 1) {
847 ++i;
848 }
849 }
850
851 qsort(hosts, i, sizeof(hosts[0]), compare_uint);
852
853 g_free(path);
854 closedir(dir);
855 return i;
856}
857
858/* Store disk device info specified by @sysfs into @fs */
859static void build_guest_fsinfo_for_real_device(char const *syspath,
860 GuestFilesystemInfo *fs,
861 Error **errp)
862{
863 unsigned int pci[4], host, hosts[8], tgt[3];
864 int i, nhosts = 0, pcilen;
865 GuestDiskAddress *disk;
866 GuestPCIAddress *pciaddr;
867 GuestDiskAddressList *list = NULL;
868 bool has_ata = false, has_host = false, has_tgt = false;
869 char *p, *q, *driver = NULL;
870
871 p = strstr(syspath, "/devices/pci");
872 if (!p || sscanf(p + 12, "%*x:%*x/%x:%x:%x.%x%n",
873 pci, pci + 1, pci + 2, pci + 3, &pcilen) < 4) {
874 g_debug("only pci device is supported: sysfs path \"%s\"", syspath);
875 return;
876 }
877
878 driver = get_pci_driver(syspath, (p + 12 + pcilen) - syspath, errp);
879 if (!driver) {
880 goto cleanup;
881 }
882
883 p = strstr(syspath, "/target");
884 if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
885 tgt, tgt + 1, tgt + 2) == 3) {
886 has_tgt = true;
887 }
888
889 p = strstr(syspath, "/ata");
890 if (p) {
891 q = p + 4;
892 has_ata = true;
893 } else {
894 p = strstr(syspath, "/host");
895 q = p + 5;
896 }
897 if (p && sscanf(q, "%u", &host) == 1) {
898 has_host = true;
899 nhosts = build_hosts(syspath, p, has_ata, hosts,
900 sizeof(hosts) / sizeof(hosts[0]), errp);
901 if (nhosts < 0) {
902 goto cleanup;
903 }
904 }
905
906 pciaddr = g_malloc0(sizeof(*pciaddr));
907 pciaddr->domain = pci[0];
908 pciaddr->bus = pci[1];
909 pciaddr->slot = pci[2];
910 pciaddr->function = pci[3];
911
912 disk = g_malloc0(sizeof(*disk));
913 disk->pci_controller = pciaddr;
914
915 list = g_malloc0(sizeof(*list));
916 list->value = disk;
917
918 if (strcmp(driver, "ata_piix") == 0) {
919 /* a host per ide bus, target*:0:<unit>:0 */
920 if (!has_host || !has_tgt) {
921 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
922 goto cleanup;
923 }
924 for (i = 0; i < nhosts; i++) {
925 if (host == hosts[i]) {
926 disk->bus_type = GUEST_DISK_BUS_TYPE_IDE;
927 disk->bus = i;
928 disk->unit = tgt[1];
929 break;
930 }
931 }
932 if (i >= nhosts) {
933 g_debug("no host for '%s' (driver '%s')", syspath, driver);
934 goto cleanup;
935 }
936 } else if (strcmp(driver, "sym53c8xx") == 0) {
937 /* scsi(LSI Logic): target*:0:<unit>:0 */
938 if (!has_tgt) {
939 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
940 goto cleanup;
941 }
942 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
943 disk->unit = tgt[1];
944 } else if (strcmp(driver, "virtio-pci") == 0) {
945 if (has_tgt) {
946 /* virtio-scsi: target*:0:0:<unit> */
947 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
948 disk->unit = tgt[2];
949 } else {
950 /* virtio-blk: 1 disk per 1 device */
951 disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
952 }
953 } else if (strcmp(driver, "ahci") == 0) {
954 /* ahci: 1 host per 1 unit */
955 if (!has_host || !has_tgt) {
956 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
957 goto cleanup;
958 }
959 for (i = 0; i < nhosts; i++) {
960 if (host == hosts[i]) {
961 disk->unit = i;
962 disk->bus_type = GUEST_DISK_BUS_TYPE_SATA;
963 break;
964 }
965 }
966 if (i >= nhosts) {
967 g_debug("no host for '%s' (driver '%s')", syspath, driver);
968 goto cleanup;
969 }
970 } else {
971 g_debug("unknown driver '%s' (sysfs path '%s')", driver, syspath);
972 goto cleanup;
973 }
974
975 list->next = fs->disk;
976 fs->disk = list;
977 g_free(driver);
978 return;
979
980cleanup:
981 if (list) {
982 qapi_free_GuestDiskAddressList(list);
983 }
984 g_free(driver);
985}
986
987static void build_guest_fsinfo_for_device(char const *devpath,
988 GuestFilesystemInfo *fs,
989 Error **errp);
990
991/* Store a list of slave devices of virtual volume specified by @syspath into
992 * @fs */
993static void build_guest_fsinfo_for_virtual_device(char const *syspath,
994 GuestFilesystemInfo *fs,
995 Error **errp)
996{
997 DIR *dir;
998 char *dirpath;
zhanghailiange668d1b2014-09-19 11:09:10 +0800999 struct dirent *entry;
Tomoki Sekiyama46d4c572014-06-30 17:51:34 -04001000
1001 dirpath = g_strdup_printf("%s/slaves", syspath);
1002 dir = opendir(dirpath);
1003 if (!dir) {
1004 error_setg_errno(errp, errno, "opendir(\"%s\")", dirpath);
1005 g_free(dirpath);
1006 return;
1007 }
Tomoki Sekiyama46d4c572014-06-30 17:51:34 -04001008
1009 for (;;) {
zhanghailiange668d1b2014-09-19 11:09:10 +08001010 errno = 0;
1011 entry = readdir(dir);
1012 if (entry == NULL) {
1013 if (errno) {
1014 error_setg_errno(errp, errno, "readdir(\"%s\")", dirpath);
1015 }
Tomoki Sekiyama46d4c572014-06-30 17:51:34 -04001016 break;
1017 }
1018
zhanghailiange668d1b2014-09-19 11:09:10 +08001019 if (entry->d_type == DT_LNK) {
1020 char *path;
1021
1022 g_debug(" slave device '%s'", entry->d_name);
1023 path = g_strdup_printf("%s/slaves/%s", syspath, entry->d_name);
1024 build_guest_fsinfo_for_device(path, fs, errp);
1025 g_free(path);
Tomoki Sekiyama46d4c572014-06-30 17:51:34 -04001026
1027 if (*errp) {
1028 break;
1029 }
1030 }
1031 }
1032
zhanghailiange668d1b2014-09-19 11:09:10 +08001033 g_free(dirpath);
Tomoki Sekiyama46d4c572014-06-30 17:51:34 -04001034 closedir(dir);
1035}
1036
1037/* Dispatch to functions for virtual/real device */
1038static void build_guest_fsinfo_for_device(char const *devpath,
1039 GuestFilesystemInfo *fs,
1040 Error **errp)
1041{
1042 char *syspath = realpath(devpath, NULL);
1043
1044 if (!syspath) {
1045 error_setg_errno(errp, errno, "realpath(\"%s\")", devpath);
1046 return;
1047 }
1048
1049 if (!fs->name) {
1050 fs->name = g_strdup(basename(syspath));
1051 }
1052
1053 g_debug(" parse sysfs path '%s'", syspath);
1054
1055 if (strstr(syspath, "/devices/virtual/block/")) {
1056 build_guest_fsinfo_for_virtual_device(syspath, fs, errp);
1057 } else {
1058 build_guest_fsinfo_for_real_device(syspath, fs, errp);
1059 }
1060
1061 free(syspath);
1062}
1063
1064/* Return a list of the disk device(s)' info which @mount lies on */
1065static GuestFilesystemInfo *build_guest_fsinfo(struct FsMount *mount,
1066 Error **errp)
1067{
1068 GuestFilesystemInfo *fs = g_malloc0(sizeof(*fs));
1069 char *devpath = g_strdup_printf("/sys/dev/block/%u:%u",
1070 mount->devmajor, mount->devminor);
1071
1072 fs->mountpoint = g_strdup(mount->dirname);
1073 fs->type = g_strdup(mount->devtype);
1074 build_guest_fsinfo_for_device(devpath, fs, errp);
1075
1076 g_free(devpath);
1077 return fs;
1078}
1079
1080GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
1081{
1082 FsMountList mounts;
1083 struct FsMount *mount;
1084 GuestFilesystemInfoList *new, *ret = NULL;
1085 Error *local_err = NULL;
1086
1087 QTAILQ_INIT(&mounts);
1088 build_fs_mount_list(&mounts, &local_err);
1089 if (local_err) {
1090 error_propagate(errp, local_err);
1091 return NULL;
1092 }
1093
1094 QTAILQ_FOREACH(mount, &mounts, next) {
1095 g_debug("Building guest fsinfo for '%s'", mount->dirname);
1096
1097 new = g_malloc0(sizeof(*ret));
1098 new->value = build_guest_fsinfo(mount, &local_err);
1099 new->next = ret;
1100 ret = new;
1101 if (local_err) {
1102 error_propagate(errp, local_err);
1103 qapi_free_GuestFilesystemInfoList(ret);
1104 ret = NULL;
1105 break;
1106 }
1107 }
1108
1109 free_fs_mount_list(&mounts);
1110 return ret;
1111}
1112
1113
Tomoki Sekiyamaec0f6942012-12-12 12:55:55 +09001114typedef enum {
1115 FSFREEZE_HOOK_THAW = 0,
1116 FSFREEZE_HOOK_FREEZE,
1117} FsfreezeHookArg;
1118
Stefan Weil13a439e2014-07-07 21:07:29 +02001119static const char *fsfreeze_hook_arg_string[] = {
Tomoki Sekiyamaec0f6942012-12-12 12:55:55 +09001120 "thaw",
1121 "freeze",
1122};
1123
Markus Armbruster77dbc812014-05-02 13:26:30 +02001124static void execute_fsfreeze_hook(FsfreezeHookArg arg, Error **errp)
Tomoki Sekiyamaec0f6942012-12-12 12:55:55 +09001125{
1126 int status;
1127 pid_t pid;
1128 const char *hook;
1129 const char *arg_str = fsfreeze_hook_arg_string[arg];
1130 Error *local_err = NULL;
1131
1132 hook = ga_fsfreeze_hook(ga_state);
1133 if (!hook) {
1134 return;
1135 }
1136 if (access(hook, X_OK) != 0) {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001137 error_setg_errno(errp, errno, "can't access fsfreeze hook '%s'", hook);
Tomoki Sekiyamaec0f6942012-12-12 12:55:55 +09001138 return;
1139 }
1140
1141 slog("executing fsfreeze hook with arg '%s'", arg_str);
1142 pid = fork();
1143 if (pid == 0) {
1144 setsid();
1145 reopen_fd_to_null(0);
1146 reopen_fd_to_null(1);
1147 reopen_fd_to_null(2);
1148
1149 execle(hook, hook, arg_str, NULL, environ);
1150 _exit(EXIT_FAILURE);
1151 } else if (pid < 0) {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001152 error_setg_errno(errp, errno, "failed to create child process");
Tomoki Sekiyamaec0f6942012-12-12 12:55:55 +09001153 return;
1154 }
1155
1156 ga_wait_child(pid, &status, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01001157 if (local_err) {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001158 error_propagate(errp, local_err);
Tomoki Sekiyamaec0f6942012-12-12 12:55:55 +09001159 return;
1160 }
1161
1162 if (!WIFEXITED(status)) {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001163 error_setg(errp, "fsfreeze hook has terminated abnormally");
Tomoki Sekiyamaec0f6942012-12-12 12:55:55 +09001164 return;
1165 }
1166
1167 status = WEXITSTATUS(status);
1168 if (status) {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001169 error_setg(errp, "fsfreeze hook has failed with status %d", status);
Tomoki Sekiyamaec0f6942012-12-12 12:55:55 +09001170 return;
1171 }
1172}
1173
Michael Rothe3d4d252011-07-19 15:41:55 -05001174/*
1175 * Return status of freeze/thaw
1176 */
Markus Armbruster77dbc812014-05-02 13:26:30 +02001177GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
Michael Rothe3d4d252011-07-19 15:41:55 -05001178{
Michael Rothf22d85e2012-04-17 19:01:45 -05001179 if (ga_is_frozen(ga_state)) {
1180 return GUEST_FSFREEZE_STATUS_FROZEN;
1181 }
1182
1183 return GUEST_FSFREEZE_STATUS_THAWED;
Michael Rothe3d4d252011-07-19 15:41:55 -05001184}
1185
Tomoki Sekiyamae99bce22014-06-30 17:51:27 -04001186int64_t qmp_guest_fsfreeze_freeze(Error **errp)
1187{
1188 return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
1189}
1190
Michael Rothe3d4d252011-07-19 15:41:55 -05001191/*
1192 * Walk list of mounted file systems in the guest, and freeze the ones which
1193 * are real local file systems.
1194 */
Tomoki Sekiyamae99bce22014-06-30 17:51:27 -04001195int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
1196 strList *mountpoints,
1197 Error **errp)
Michael Rothe3d4d252011-07-19 15:41:55 -05001198{
1199 int ret = 0, i = 0;
Tomoki Sekiyamae99bce22014-06-30 17:51:27 -04001200 strList *list;
Paolo Bonziniaf022032012-06-13 07:41:27 +02001201 FsMountList mounts;
1202 struct FsMount *mount;
Luiz Capitulino261551d2012-11-29 15:29:11 -02001203 Error *local_err = NULL;
Michael Rothe3d4d252011-07-19 15:41:55 -05001204 int fd;
Michael Rothe3d4d252011-07-19 15:41:55 -05001205
1206 slog("guest-fsfreeze called");
1207
Tomoki Sekiyamaec0f6942012-12-12 12:55:55 +09001208 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01001209 if (local_err) {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001210 error_propagate(errp, local_err);
Tomoki Sekiyamaec0f6942012-12-12 12:55:55 +09001211 return -1;
1212 }
1213
Michael Roth9e8aded432012-04-16 19:52:17 -05001214 QTAILQ_INIT(&mounts);
Luiz Capitulino261551d2012-11-29 15:29:11 -02001215 build_fs_mount_list(&mounts, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01001216 if (local_err) {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001217 error_propagate(errp, local_err);
Luiz Capitulino261551d2012-11-29 15:29:11 -02001218 return -1;
Michael Rothe3d4d252011-07-19 15:41:55 -05001219 }
1220
1221 /* cannot risk guest agent blocking itself on a write in this state */
Michael Rothf22d85e2012-04-17 19:01:45 -05001222 ga_set_frozen(ga_state);
Michael Rothe3d4d252011-07-19 15:41:55 -05001223
Tomoki Sekiyamae5d9adb2013-10-01 17:09:53 -04001224 QTAILQ_FOREACH_REVERSE(mount, &mounts, FsMountList, next) {
Tomoki Sekiyamae99bce22014-06-30 17:51:27 -04001225 /* To issue fsfreeze in the reverse order of mounts, check if the
1226 * mount is listed in the list here */
1227 if (has_mountpoints) {
1228 for (list = mountpoints; list; list = list->next) {
1229 if (strcmp(list->value, mount->dirname) == 0) {
1230 break;
1231 }
1232 }
1233 if (!list) {
1234 continue;
1235 }
1236 }
1237
Michael Rothe3d4d252011-07-19 15:41:55 -05001238 fd = qemu_open(mount->dirname, O_RDONLY);
1239 if (fd == -1) {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001240 error_setg_errno(errp, errno, "failed to open %s", mount->dirname);
Michael Rothe3d4d252011-07-19 15:41:55 -05001241 goto error;
1242 }
1243
1244 /* we try to cull filesytems we know won't work in advance, but other
1245 * filesytems may not implement fsfreeze for less obvious reasons.
Michael Roth9e8aded432012-04-16 19:52:17 -05001246 * these will report EOPNOTSUPP. we simply ignore these when tallying
1247 * the number of frozen filesystems.
1248 *
1249 * any other error means a failure to freeze a filesystem we
1250 * expect to be freezable, so return an error in those cases
1251 * and return system to thawed state.
Michael Rothe3d4d252011-07-19 15:41:55 -05001252 */
1253 ret = ioctl(fd, FIFREEZE);
Michael Roth9e8aded432012-04-16 19:52:17 -05001254 if (ret == -1) {
1255 if (errno != EOPNOTSUPP) {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001256 error_setg_errno(errp, errno, "failed to freeze %s",
Luiz Capitulino617fbbc2012-11-27 11:02:00 -02001257 mount->dirname);
Michael Roth9e8aded432012-04-16 19:52:17 -05001258 close(fd);
1259 goto error;
1260 }
1261 } else {
1262 i++;
Michael Rothe3d4d252011-07-19 15:41:55 -05001263 }
1264 close(fd);
Michael Rothe3d4d252011-07-19 15:41:55 -05001265 }
1266
Paolo Bonziniaf022032012-06-13 07:41:27 +02001267 free_fs_mount_list(&mounts);
Michael Rothe3d4d252011-07-19 15:41:55 -05001268 return i;
1269
1270error:
Paolo Bonziniaf022032012-06-13 07:41:27 +02001271 free_fs_mount_list(&mounts);
Michael Roth9e8aded432012-04-16 19:52:17 -05001272 qmp_guest_fsfreeze_thaw(NULL);
Michael Rothe3d4d252011-07-19 15:41:55 -05001273 return 0;
1274}
1275
1276/*
1277 * Walk list of frozen file systems in the guest, and thaw them.
1278 */
Markus Armbruster77dbc812014-05-02 13:26:30 +02001279int64_t qmp_guest_fsfreeze_thaw(Error **errp)
Michael Rothe3d4d252011-07-19 15:41:55 -05001280{
1281 int ret;
Paolo Bonziniaf022032012-06-13 07:41:27 +02001282 FsMountList mounts;
1283 FsMount *mount;
Michael Roth9e8aded432012-04-16 19:52:17 -05001284 int fd, i = 0, logged;
Luiz Capitulino261551d2012-11-29 15:29:11 -02001285 Error *local_err = NULL;
Michael Rothe3d4d252011-07-19 15:41:55 -05001286
Michael Roth9e8aded432012-04-16 19:52:17 -05001287 QTAILQ_INIT(&mounts);
Luiz Capitulino261551d2012-11-29 15:29:11 -02001288 build_fs_mount_list(&mounts, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01001289 if (local_err) {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001290 error_propagate(errp, local_err);
Michael Roth9e8aded432012-04-16 19:52:17 -05001291 return 0;
1292 }
1293
1294 QTAILQ_FOREACH(mount, &mounts, next) {
1295 logged = false;
Michael Rothe3d4d252011-07-19 15:41:55 -05001296 fd = qemu_open(mount->dirname, O_RDONLY);
1297 if (fd == -1) {
Michael Rothe3d4d252011-07-19 15:41:55 -05001298 continue;
1299 }
Michael Roth9e8aded432012-04-16 19:52:17 -05001300 /* we have no way of knowing whether a filesystem was actually unfrozen
1301 * as a result of a successful call to FITHAW, only that if an error
1302 * was returned the filesystem was *not* unfrozen by that particular
1303 * call.
1304 *
Jim Meyeringa31f0532012-05-09 05:12:04 +00001305 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
Michael Roth9e8aded432012-04-16 19:52:17 -05001306 * to unfreeze, continuing issuing FITHAW until an error is returned,
1307 * in which case either the filesystem is in an unfreezable state, or,
1308 * more likely, it was thawed previously (and remains so afterward).
1309 *
1310 * also, since the most recent successful call is the one that did
1311 * the actual unfreeze, we can use this to provide an accurate count
1312 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1313 * may * be useful for determining whether a filesystem was unfrozen
1314 * during the freeze/thaw phase by a process other than qemu-ga.
1315 */
1316 do {
1317 ret = ioctl(fd, FITHAW);
1318 if (ret == 0 && !logged) {
1319 i++;
1320 logged = true;
1321 }
1322 } while (ret == 0);
Michael Rothe3d4d252011-07-19 15:41:55 -05001323 close(fd);
Michael Rothe3d4d252011-07-19 15:41:55 -05001324 }
1325
Michael Rothf22d85e2012-04-17 19:01:45 -05001326 ga_unset_frozen(ga_state);
Paolo Bonziniaf022032012-06-13 07:41:27 +02001327 free_fs_mount_list(&mounts);
Tomoki Sekiyamaec0f6942012-12-12 12:55:55 +09001328
Markus Armbruster77dbc812014-05-02 13:26:30 +02001329 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW, errp);
Tomoki Sekiyamaec0f6942012-12-12 12:55:55 +09001330
Michael Rothe3d4d252011-07-19 15:41:55 -05001331 return i;
1332}
1333
Michael Rothe3d4d252011-07-19 15:41:55 -05001334static void guest_fsfreeze_cleanup(void)
1335{
Michael Rothe3d4d252011-07-19 15:41:55 -05001336 Error *err = NULL;
1337
Michael Rothf22d85e2012-04-17 19:01:45 -05001338 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
Markus Armbruster6f686742013-01-16 18:15:08 +01001339 qmp_guest_fsfreeze_thaw(&err);
1340 if (err) {
1341 slog("failed to clean up frozen filesystems: %s",
1342 error_get_pretty(err));
1343 error_free(err);
Michael Rothe3d4d252011-07-19 15:41:55 -05001344 }
1345 }
1346}
Michael Rothe72c3f22012-03-25 13:59:41 -05001347#endif /* CONFIG_FSFREEZE */
Michael Rothe3d4d252011-07-19 15:41:55 -05001348
Paolo Bonzinieab5fd52012-06-13 07:41:28 +02001349#if defined(CONFIG_FSTRIM)
1350/*
1351 * Walk list of mounted file systems in the guest, and trim them.
1352 */
Justin Ossevoorte82855d2015-05-11 08:58:45 +02001353GuestFilesystemTrimResponse *
1354qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
Paolo Bonzinieab5fd52012-06-13 07:41:28 +02001355{
Justin Ossevoorte82855d2015-05-11 08:58:45 +02001356 GuestFilesystemTrimResponse *response;
1357 GuestFilesystemTrimResultList *list;
1358 GuestFilesystemTrimResult *result;
Paolo Bonzinieab5fd52012-06-13 07:41:28 +02001359 int ret = 0;
1360 FsMountList mounts;
1361 struct FsMount *mount;
1362 int fd;
Luiz Capitulino261551d2012-11-29 15:29:11 -02001363 Error *local_err = NULL;
Justin Ossevoort73a652a2015-05-11 08:58:44 +02001364 struct fstrim_range r;
Paolo Bonzinieab5fd52012-06-13 07:41:28 +02001365
1366 slog("guest-fstrim called");
1367
1368 QTAILQ_INIT(&mounts);
Luiz Capitulino261551d2012-11-29 15:29:11 -02001369 build_fs_mount_list(&mounts, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01001370 if (local_err) {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001371 error_propagate(errp, local_err);
Justin Ossevoorte82855d2015-05-11 08:58:45 +02001372 return NULL;
Paolo Bonzinieab5fd52012-06-13 07:41:28 +02001373 }
1374
Justin Ossevoorte82855d2015-05-11 08:58:45 +02001375 response = g_malloc0(sizeof(*response));
1376
Paolo Bonzinieab5fd52012-06-13 07:41:28 +02001377 QTAILQ_FOREACH(mount, &mounts, next) {
Justin Ossevoorte82855d2015-05-11 08:58:45 +02001378 result = g_malloc0(sizeof(*result));
1379 result->path = g_strdup(mount->dirname);
1380
1381 list = g_malloc0(sizeof(*list));
1382 list->value = result;
1383 list->next = response->paths;
1384 response->paths = list;
1385
Paolo Bonzinieab5fd52012-06-13 07:41:28 +02001386 fd = qemu_open(mount->dirname, O_RDONLY);
1387 if (fd == -1) {
Justin Ossevoorte82855d2015-05-11 08:58:45 +02001388 result->error = g_strdup_printf("failed to open: %s",
1389 strerror(errno));
1390 result->has_error = true;
1391 continue;
Paolo Bonzinieab5fd52012-06-13 07:41:28 +02001392 }
1393
1394 /* We try to cull filesytems we know won't work in advance, but other
1395 * filesytems may not implement fstrim for less obvious reasons. These
Justin Ossevoorte82855d2015-05-11 08:58:45 +02001396 * will report EOPNOTSUPP; while in some other cases ENOTTY will be
1397 * reported (e.g. CD-ROMs).
1398 * Any other error means an unexpected error.
Paolo Bonzinieab5fd52012-06-13 07:41:28 +02001399 */
Justin Ossevoort73a652a2015-05-11 08:58:44 +02001400 r.start = 0;
1401 r.len = -1;
1402 r.minlen = has_minimum ? minimum : 0;
Paolo Bonzinieab5fd52012-06-13 07:41:28 +02001403 ret = ioctl(fd, FITRIM, &r);
1404 if (ret == -1) {
Justin Ossevoorte82855d2015-05-11 08:58:45 +02001405 result->has_error = true;
1406 if (errno == ENOTTY || errno == EOPNOTSUPP) {
1407 result->error = g_strdup("trim not supported");
1408 } else {
1409 result->error = g_strdup_printf("failed to trim: %s",
1410 strerror(errno));
Paolo Bonzinieab5fd52012-06-13 07:41:28 +02001411 }
Justin Ossevoorte82855d2015-05-11 08:58:45 +02001412 close(fd);
1413 continue;
Paolo Bonzinieab5fd52012-06-13 07:41:28 +02001414 }
Justin Ossevoorte82855d2015-05-11 08:58:45 +02001415
1416 result->has_minimum = true;
1417 result->minimum = r.minlen;
1418 result->has_trimmed = true;
1419 result->trimmed = r.len;
Paolo Bonzinieab5fd52012-06-13 07:41:28 +02001420 close(fd);
1421 }
1422
Paolo Bonzinieab5fd52012-06-13 07:41:28 +02001423 free_fs_mount_list(&mounts);
Justin Ossevoorte82855d2015-05-11 08:58:45 +02001424 return response;
Paolo Bonzinieab5fd52012-06-13 07:41:28 +02001425}
1426#endif /* CONFIG_FSTRIM */
1427
1428
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001429#define LINUX_SYS_STATE_FILE "/sys/power/state"
1430#define SUSPEND_SUPPORTED 0
1431#define SUSPEND_NOT_SUPPORTED 1
1432
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001433static void bios_supports_mode(const char *pmutils_bin, const char *pmutils_arg,
Markus Armbruster77dbc812014-05-02 13:26:30 +02001434 const char *sysfile_str, Error **errp)
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001435{
Luiz Capitulino6b26e832012-11-27 11:02:03 -02001436 Error *local_err = NULL;
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001437 char *pmutils_path;
Luiz Capitulino6b26e832012-11-27 11:02:03 -02001438 pid_t pid;
Luiz Capitulinodc8764f02012-05-11 16:19:46 -03001439 int status;
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001440
1441 pmutils_path = g_find_program_in_path(pmutils_bin);
1442
1443 pid = fork();
1444 if (!pid) {
Luiz Capitulinodc8764f02012-05-11 16:19:46 -03001445 char buf[32]; /* hopefully big enough */
1446 ssize_t ret;
1447 int fd;
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001448
1449 setsid();
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001450 reopen_fd_to_null(0);
1451 reopen_fd_to_null(1);
1452 reopen_fd_to_null(2);
1453
Luiz Capitulinodc8764f02012-05-11 16:19:46 -03001454 if (pmutils_path) {
1455 execle(pmutils_path, pmutils_bin, pmutils_arg, NULL, environ);
1456 }
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001457
Luiz Capitulinodc8764f02012-05-11 16:19:46 -03001458 /*
1459 * If we get here either pm-utils is not installed or execle() has
1460 * failed. Let's try the manual method if the caller wants it.
1461 */
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001462
Luiz Capitulinodc8764f02012-05-11 16:19:46 -03001463 if (!sysfile_str) {
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001464 _exit(SUSPEND_NOT_SUPPORTED);
1465 }
1466
Luiz Capitulinodc8764f02012-05-11 16:19:46 -03001467 fd = open(LINUX_SYS_STATE_FILE, O_RDONLY);
1468 if (fd < 0) {
1469 _exit(SUSPEND_NOT_SUPPORTED);
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001470 }
1471
Luiz Capitulinodc8764f02012-05-11 16:19:46 -03001472 ret = read(fd, buf, sizeof(buf)-1);
1473 if (ret <= 0) {
1474 _exit(SUSPEND_NOT_SUPPORTED);
1475 }
1476 buf[ret] = '\0';
1477
1478 if (strstr(buf, sysfile_str)) {
1479 _exit(SUSPEND_SUPPORTED);
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001480 }
1481
Luiz Capitulinodc8764f02012-05-11 16:19:46 -03001482 _exit(SUSPEND_NOT_SUPPORTED);
Luiz Capitulino6b26e832012-11-27 11:02:03 -02001483 } else if (pid < 0) {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001484 error_setg_errno(errp, errno, "failed to create child process");
Luiz Capitulino6b26e832012-11-27 11:02:03 -02001485 goto out;
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001486 }
1487
Luiz Capitulino6b26e832012-11-27 11:02:03 -02001488 ga_wait_child(pid, &status, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01001489 if (local_err) {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001490 error_propagate(errp, local_err);
Luiz Capitulino6b26e832012-11-27 11:02:03 -02001491 goto out;
1492 }
1493
1494 if (!WIFEXITED(status)) {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001495 error_setg(errp, "child process has terminated abnormally");
Luiz Capitulino6b26e832012-11-27 11:02:03 -02001496 goto out;
1497 }
1498
1499 switch (WEXITSTATUS(status)) {
1500 case SUSPEND_SUPPORTED:
1501 goto out;
1502 case SUSPEND_NOT_SUPPORTED:
Markus Armbruster77dbc812014-05-02 13:26:30 +02001503 error_setg(errp,
Luiz Capitulino6b26e832012-11-27 11:02:03 -02001504 "the requested suspend mode is not supported by the guest");
1505 goto out;
1506 default:
Markus Armbruster77dbc812014-05-02 13:26:30 +02001507 error_setg(errp,
Luiz Capitulino6b26e832012-11-27 11:02:03 -02001508 "the helper program '%s' returned an unexpected exit status"
1509 " code (%d)", pmutils_path, WEXITSTATUS(status));
1510 goto out;
1511 }
1512
1513out:
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001514 g_free(pmutils_path);
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001515}
1516
1517static void guest_suspend(const char *pmutils_bin, const char *sysfile_str,
Markus Armbruster77dbc812014-05-02 13:26:30 +02001518 Error **errp)
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001519{
Luiz Capitulino7b376082012-11-27 11:02:04 -02001520 Error *local_err = NULL;
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001521 char *pmutils_path;
Luiz Capitulino7b376082012-11-27 11:02:04 -02001522 pid_t pid;
Luiz Capitulinodc8764f02012-05-11 16:19:46 -03001523 int status;
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001524
1525 pmutils_path = g_find_program_in_path(pmutils_bin);
1526
1527 pid = fork();
1528 if (pid == 0) {
1529 /* child */
1530 int fd;
1531
1532 setsid();
1533 reopen_fd_to_null(0);
1534 reopen_fd_to_null(1);
1535 reopen_fd_to_null(2);
1536
1537 if (pmutils_path) {
1538 execle(pmutils_path, pmutils_bin, NULL, environ);
1539 }
1540
1541 /*
1542 * If we get here either pm-utils is not installed or execle() has
1543 * failed. Let's try the manual method if the caller wants it.
1544 */
1545
1546 if (!sysfile_str) {
1547 _exit(EXIT_FAILURE);
1548 }
1549
1550 fd = open(LINUX_SYS_STATE_FILE, O_WRONLY);
1551 if (fd < 0) {
1552 _exit(EXIT_FAILURE);
1553 }
1554
1555 if (write(fd, sysfile_str, strlen(sysfile_str)) < 0) {
1556 _exit(EXIT_FAILURE);
1557 }
1558
1559 _exit(EXIT_SUCCESS);
Luiz Capitulino7b376082012-11-27 11:02:04 -02001560 } else if (pid < 0) {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001561 error_setg_errno(errp, errno, "failed to create child process");
Luiz Capitulino7b376082012-11-27 11:02:04 -02001562 goto out;
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001563 }
1564
Luiz Capitulino7b376082012-11-27 11:02:04 -02001565 ga_wait_child(pid, &status, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01001566 if (local_err) {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001567 error_propagate(errp, local_err);
Luiz Capitulino7b376082012-11-27 11:02:04 -02001568 goto out;
1569 }
1570
1571 if (!WIFEXITED(status)) {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001572 error_setg(errp, "child process has terminated abnormally");
Luiz Capitulino7b376082012-11-27 11:02:04 -02001573 goto out;
1574 }
1575
1576 if (WEXITSTATUS(status)) {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001577 error_setg(errp, "child process has failed to suspend");
Luiz Capitulino7b376082012-11-27 11:02:04 -02001578 goto out;
1579 }
1580
1581out:
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001582 g_free(pmutils_path);
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001583}
1584
Markus Armbruster77dbc812014-05-02 13:26:30 +02001585void qmp_guest_suspend_disk(Error **errp)
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001586{
Markus Armbruster0f230bf2014-05-02 13:26:38 +02001587 Error *local_err = NULL;
1588
1589 bios_supports_mode("pm-is-supported", "--hibernate", "disk", &local_err);
1590 if (local_err) {
1591 error_propagate(errp, local_err);
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001592 return;
1593 }
1594
Markus Armbruster77dbc812014-05-02 13:26:30 +02001595 guest_suspend("pm-hibernate", "disk", errp);
Luiz Capitulino11d0f122012-02-28 11:03:03 -03001596}
1597
Markus Armbruster77dbc812014-05-02 13:26:30 +02001598void qmp_guest_suspend_ram(Error **errp)
Luiz Capitulinofbf42212012-02-28 11:03:04 -03001599{
Markus Armbruster0f230bf2014-05-02 13:26:38 +02001600 Error *local_err = NULL;
1601
1602 bios_supports_mode("pm-is-supported", "--suspend", "mem", &local_err);
1603 if (local_err) {
1604 error_propagate(errp, local_err);
Luiz Capitulinofbf42212012-02-28 11:03:04 -03001605 return;
1606 }
1607
Markus Armbruster77dbc812014-05-02 13:26:30 +02001608 guest_suspend("pm-suspend", "mem", errp);
Luiz Capitulinofbf42212012-02-28 11:03:04 -03001609}
1610
Markus Armbruster77dbc812014-05-02 13:26:30 +02001611void qmp_guest_suspend_hybrid(Error **errp)
Luiz Capitulino95f4f402012-02-28 11:03:05 -03001612{
Markus Armbruster0f230bf2014-05-02 13:26:38 +02001613 Error *local_err = NULL;
1614
1615 bios_supports_mode("pm-is-supported", "--suspend-hybrid", NULL,
1616 &local_err);
1617 if (local_err) {
1618 error_propagate(errp, local_err);
Luiz Capitulino95f4f402012-02-28 11:03:05 -03001619 return;
1620 }
1621
Markus Armbruster77dbc812014-05-02 13:26:30 +02001622 guest_suspend("pm-suspend-hybrid", NULL, errp);
Luiz Capitulino95f4f402012-02-28 11:03:05 -03001623}
1624
Michal Privoznik3424fc92012-02-29 17:02:23 +01001625static GuestNetworkInterfaceList *
1626guest_find_interface(GuestNetworkInterfaceList *head,
1627 const char *name)
1628{
1629 for (; head; head = head->next) {
1630 if (strcmp(head->value->name, name) == 0) {
1631 break;
1632 }
1633 }
1634
1635 return head;
1636}
1637
1638/*
1639 * Build information about guest interfaces
1640 */
1641GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1642{
1643 GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
1644 struct ifaddrs *ifap, *ifa;
Michal Privoznik3424fc92012-02-29 17:02:23 +01001645
1646 if (getifaddrs(&ifap) < 0) {
Luiz Capitulino878a0ae2012-11-27 11:02:02 -02001647 error_setg_errno(errp, errno, "getifaddrs failed");
Michal Privoznik3424fc92012-02-29 17:02:23 +01001648 goto error;
1649 }
1650
1651 for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1652 GuestNetworkInterfaceList *info;
1653 GuestIpAddressList **address_list = NULL, *address_item = NULL;
1654 char addr4[INET_ADDRSTRLEN];
1655 char addr6[INET6_ADDRSTRLEN];
1656 int sock;
1657 struct ifreq ifr;
1658 unsigned char *mac_addr;
1659 void *p;
1660
1661 g_debug("Processing %s interface", ifa->ifa_name);
1662
1663 info = guest_find_interface(head, ifa->ifa_name);
1664
1665 if (!info) {
1666 info = g_malloc0(sizeof(*info));
1667 info->value = g_malloc0(sizeof(*info->value));
1668 info->value->name = g_strdup(ifa->ifa_name);
1669
1670 if (!cur_item) {
1671 head = cur_item = info;
1672 } else {
1673 cur_item->next = info;
1674 cur_item = info;
1675 }
1676 }
1677
1678 if (!info->value->has_hardware_address &&
1679 ifa->ifa_flags & SIOCGIFHWADDR) {
1680 /* we haven't obtained HW address yet */
1681 sock = socket(PF_INET, SOCK_STREAM, 0);
1682 if (sock == -1) {
Luiz Capitulino878a0ae2012-11-27 11:02:02 -02001683 error_setg_errno(errp, errno, "failed to create socket");
Michal Privoznik3424fc92012-02-29 17:02:23 +01001684 goto error;
1685 }
1686
1687 memset(&ifr, 0, sizeof(ifr));
Jim Meyering1ab516e2012-10-04 13:09:58 +02001688 pstrcpy(ifr.ifr_name, IF_NAMESIZE, info->value->name);
Michal Privoznik3424fc92012-02-29 17:02:23 +01001689 if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {
Luiz Capitulino878a0ae2012-11-27 11:02:02 -02001690 error_setg_errno(errp, errno,
1691 "failed to get MAC address of %s",
1692 ifa->ifa_name);
Markus Armbruster10a21582013-01-16 18:15:09 +01001693 close(sock);
Michal Privoznik3424fc92012-02-29 17:02:23 +01001694 goto error;
1695 }
1696
Markus Armbruster10a21582013-01-16 18:15:09 +01001697 close(sock);
Michal Privoznik3424fc92012-02-29 17:02:23 +01001698 mac_addr = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
1699
Stefan Weile4ada482013-01-16 18:37:23 +01001700 info->value->hardware_address =
1701 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1702 (int) mac_addr[0], (int) mac_addr[1],
1703 (int) mac_addr[2], (int) mac_addr[3],
1704 (int) mac_addr[4], (int) mac_addr[5]);
Michal Privoznik3424fc92012-02-29 17:02:23 +01001705
1706 info->value->has_hardware_address = true;
Michal Privoznik3424fc92012-02-29 17:02:23 +01001707 }
1708
1709 if (ifa->ifa_addr &&
1710 ifa->ifa_addr->sa_family == AF_INET) {
1711 /* interface with IPv4 address */
Michal Privoznik3424fc92012-02-29 17:02:23 +01001712 p = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
1713 if (!inet_ntop(AF_INET, p, addr4, sizeof(addr4))) {
Luiz Capitulino878a0ae2012-11-27 11:02:02 -02001714 error_setg_errno(errp, errno, "inet_ntop failed");
Michal Privoznik3424fc92012-02-29 17:02:23 +01001715 goto error;
1716 }
1717
Markus Armbruster10a21582013-01-16 18:15:09 +01001718 address_item = g_malloc0(sizeof(*address_item));
1719 address_item->value = g_malloc0(sizeof(*address_item->value));
Michal Privoznik3424fc92012-02-29 17:02:23 +01001720 address_item->value->ip_address = g_strdup(addr4);
1721 address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
1722
1723 if (ifa->ifa_netmask) {
1724 /* Count the number of set bits in netmask.
1725 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1726 p = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
1727 address_item->value->prefix = ctpop32(((uint32_t *) p)[0]);
1728 }
1729 } else if (ifa->ifa_addr &&
1730 ifa->ifa_addr->sa_family == AF_INET6) {
1731 /* interface with IPv6 address */
Michal Privoznik3424fc92012-02-29 17:02:23 +01001732 p = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
1733 if (!inet_ntop(AF_INET6, p, addr6, sizeof(addr6))) {
Luiz Capitulino878a0ae2012-11-27 11:02:02 -02001734 error_setg_errno(errp, errno, "inet_ntop failed");
Michal Privoznik3424fc92012-02-29 17:02:23 +01001735 goto error;
1736 }
1737
Markus Armbruster10a21582013-01-16 18:15:09 +01001738 address_item = g_malloc0(sizeof(*address_item));
1739 address_item->value = g_malloc0(sizeof(*address_item->value));
Michal Privoznik3424fc92012-02-29 17:02:23 +01001740 address_item->value->ip_address = g_strdup(addr6);
1741 address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
1742
1743 if (ifa->ifa_netmask) {
1744 /* Count the number of set bits in netmask.
1745 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1746 p = &((struct sockaddr_in6 *)ifa->ifa_netmask)->sin6_addr;
1747 address_item->value->prefix =
1748 ctpop32(((uint32_t *) p)[0]) +
1749 ctpop32(((uint32_t *) p)[1]) +
1750 ctpop32(((uint32_t *) p)[2]) +
1751 ctpop32(((uint32_t *) p)[3]);
1752 }
1753 }
1754
1755 if (!address_item) {
1756 continue;
1757 }
1758
1759 address_list = &info->value->ip_addresses;
1760
1761 while (*address_list && (*address_list)->next) {
1762 address_list = &(*address_list)->next;
1763 }
1764
1765 if (!*address_list) {
1766 *address_list = address_item;
1767 } else {
1768 (*address_list)->next = address_item;
1769 }
1770
1771 info->value->has_ip_addresses = true;
1772
1773
1774 }
1775
1776 freeifaddrs(ifap);
1777 return head;
1778
1779error:
1780 freeifaddrs(ifap);
1781 qapi_free_GuestNetworkInterfaceList(head);
1782 return NULL;
1783}
1784
Markus Armbruster77dbc812014-05-02 13:26:30 +02001785#define SYSCONF_EXACT(name, errp) sysconf_exact((name), #name, (errp))
Laszlo Ersekd2baff62013-03-06 22:59:30 +01001786
Markus Armbruster77dbc812014-05-02 13:26:30 +02001787static long sysconf_exact(int name, const char *name_str, Error **errp)
Laszlo Ersekd2baff62013-03-06 22:59:30 +01001788{
1789 long ret;
1790
1791 errno = 0;
1792 ret = sysconf(name);
1793 if (ret == -1) {
1794 if (errno == 0) {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001795 error_setg(errp, "sysconf(%s): value indefinite", name_str);
Laszlo Ersekd2baff62013-03-06 22:59:30 +01001796 } else {
Markus Armbruster77dbc812014-05-02 13:26:30 +02001797 error_setg_errno(errp, errno, "sysconf(%s)", name_str);
Laszlo Ersekd2baff62013-03-06 22:59:30 +01001798 }
1799 }
1800 return ret;
1801}
1802
1803/* Transfer online/offline status between @vcpu and the guest system.
1804 *
1805 * On input either @errp or *@errp must be NULL.
1806 *
1807 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
1808 * - R: vcpu->logical_id
1809 * - W: vcpu->online
1810 * - W: vcpu->can_offline
1811 *
1812 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
1813 * - R: vcpu->logical_id
1814 * - R: vcpu->online
1815 *
1816 * Written members remain unmodified on error.
1817 */
1818static void transfer_vcpu(GuestLogicalProcessor *vcpu, bool sys2vcpu,
1819 Error **errp)
1820{
1821 char *dirpath;
1822 int dirfd;
1823
1824 dirpath = g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64 "/",
1825 vcpu->logical_id);
1826 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
1827 if (dirfd == -1) {
1828 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
1829 } else {
1830 static const char fn[] = "online";
1831 int fd;
1832 int res;
1833
1834 fd = openat(dirfd, fn, sys2vcpu ? O_RDONLY : O_RDWR);
1835 if (fd == -1) {
1836 if (errno != ENOENT) {
1837 error_setg_errno(errp, errno, "open(\"%s/%s\")", dirpath, fn);
1838 } else if (sys2vcpu) {
1839 vcpu->online = true;
1840 vcpu->can_offline = false;
1841 } else if (!vcpu->online) {
1842 error_setg(errp, "logical processor #%" PRId64 " can't be "
1843 "offlined", vcpu->logical_id);
1844 } /* otherwise pretend successful re-onlining */
1845 } else {
1846 unsigned char status;
1847
1848 res = pread(fd, &status, 1, 0);
1849 if (res == -1) {
1850 error_setg_errno(errp, errno, "pread(\"%s/%s\")", dirpath, fn);
1851 } else if (res == 0) {
1852 error_setg(errp, "pread(\"%s/%s\"): unexpected EOF", dirpath,
1853 fn);
1854 } else if (sys2vcpu) {
1855 vcpu->online = (status != '0');
1856 vcpu->can_offline = true;
1857 } else if (vcpu->online != (status != '0')) {
1858 status = '0' + vcpu->online;
1859 if (pwrite(fd, &status, 1, 0) == -1) {
1860 error_setg_errno(errp, errno, "pwrite(\"%s/%s\")", dirpath,
1861 fn);
1862 }
1863 } /* otherwise pretend successful re-(on|off)-lining */
1864
1865 res = close(fd);
1866 g_assert(res == 0);
1867 }
1868
1869 res = close(dirfd);
1870 g_assert(res == 0);
1871 }
1872
1873 g_free(dirpath);
1874}
1875
1876GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1877{
1878 int64_t current;
1879 GuestLogicalProcessorList *head, **link;
1880 long sc_max;
1881 Error *local_err = NULL;
1882
1883 current = 0;
1884 head = NULL;
1885 link = &head;
1886 sc_max = SYSCONF_EXACT(_SC_NPROCESSORS_CONF, &local_err);
1887
1888 while (local_err == NULL && current < sc_max) {
1889 GuestLogicalProcessor *vcpu;
1890 GuestLogicalProcessorList *entry;
1891
1892 vcpu = g_malloc0(sizeof *vcpu);
1893 vcpu->logical_id = current++;
1894 vcpu->has_can_offline = true; /* lolspeak ftw */
1895 transfer_vcpu(vcpu, true, &local_err);
1896
1897 entry = g_malloc0(sizeof *entry);
1898 entry->value = vcpu;
1899
1900 *link = entry;
1901 link = &entry->next;
1902 }
1903
1904 if (local_err == NULL) {
1905 /* there's no guest with zero VCPUs */
1906 g_assert(head != NULL);
1907 return head;
1908 }
1909
1910 qapi_free_GuestLogicalProcessorList(head);
1911 error_propagate(errp, local_err);
1912 return NULL;
1913}
1914
Laszlo Ersekcbb65fc2013-03-06 22:59:31 +01001915int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1916{
1917 int64_t processed;
1918 Error *local_err = NULL;
1919
1920 processed = 0;
1921 while (vcpus != NULL) {
1922 transfer_vcpu(vcpus->value, false, &local_err);
1923 if (local_err != NULL) {
1924 break;
1925 }
1926 ++processed;
1927 vcpus = vcpus->next;
1928 }
1929
1930 if (local_err != NULL) {
1931 if (processed == 0) {
1932 error_propagate(errp, local_err);
1933 } else {
1934 error_free(local_err);
1935 }
1936 }
1937
1938 return processed;
1939}
1940
Daniel P. Berrange215a2772015-02-11 11:26:12 +00001941void qmp_guest_set_user_password(const char *username,
1942 const char *password,
1943 bool crypted,
1944 Error **errp)
1945{
1946 Error *local_err = NULL;
1947 char *passwd_path = NULL;
1948 pid_t pid;
1949 int status;
1950 int datafd[2] = { -1, -1 };
1951 char *rawpasswddata = NULL;
1952 size_t rawpasswdlen;
1953 char *chpasswddata = NULL;
1954 size_t chpasswdlen;
1955
Daniel P. Berrange920639c2015-11-23 15:37:07 +00001956 rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
1957 if (!rawpasswddata) {
1958 return;
1959 }
Daniel P. Berrange215a2772015-02-11 11:26:12 +00001960 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1961 rawpasswddata[rawpasswdlen] = '\0';
1962
1963 if (strchr(rawpasswddata, '\n')) {
1964 error_setg(errp, "forbidden characters in raw password");
1965 goto out;
1966 }
1967
1968 if (strchr(username, '\n') ||
1969 strchr(username, ':')) {
1970 error_setg(errp, "forbidden characters in username");
1971 goto out;
1972 }
1973
1974 chpasswddata = g_strdup_printf("%s:%s\n", username, rawpasswddata);
1975 chpasswdlen = strlen(chpasswddata);
1976
1977 passwd_path = g_find_program_in_path("chpasswd");
1978
1979 if (!passwd_path) {
1980 error_setg(errp, "cannot find 'passwd' program in PATH");
1981 goto out;
1982 }
1983
1984 if (pipe(datafd) < 0) {
1985 error_setg(errp, "cannot create pipe FDs");
1986 goto out;
1987 }
1988
1989 pid = fork();
1990 if (pid == 0) {
1991 close(datafd[1]);
1992 /* child */
1993 setsid();
1994 dup2(datafd[0], 0);
1995 reopen_fd_to_null(1);
1996 reopen_fd_to_null(2);
1997
1998 if (crypted) {
1999 execle(passwd_path, "chpasswd", "-e", NULL, environ);
2000 } else {
2001 execle(passwd_path, "chpasswd", NULL, environ);
2002 }
2003 _exit(EXIT_FAILURE);
2004 } else if (pid < 0) {
2005 error_setg_errno(errp, errno, "failed to create child process");
2006 goto out;
2007 }
2008 close(datafd[0]);
2009 datafd[0] = -1;
2010
2011 if (qemu_write_full(datafd[1], chpasswddata, chpasswdlen) != chpasswdlen) {
2012 error_setg_errno(errp, errno, "cannot write new account password");
2013 goto out;
2014 }
2015 close(datafd[1]);
2016 datafd[1] = -1;
2017
2018 ga_wait_child(pid, &status, &local_err);
2019 if (local_err) {
2020 error_propagate(errp, local_err);
2021 goto out;
2022 }
2023
2024 if (!WIFEXITED(status)) {
2025 error_setg(errp, "child process has terminated abnormally");
2026 goto out;
2027 }
2028
2029 if (WEXITSTATUS(status)) {
2030 error_setg(errp, "child process has failed to set user password");
2031 goto out;
2032 }
2033
2034out:
2035 g_free(chpasswddata);
2036 g_free(rawpasswddata);
2037 g_free(passwd_path);
2038 if (datafd[0] != -1) {
2039 close(datafd[0]);
2040 }
2041 if (datafd[1] != -1) {
2042 close(datafd[1]);
2043 }
2044}
2045
zhanghailiangbd240fc2015-01-22 10:40:03 +08002046static void ga_read_sysfs_file(int dirfd, const char *pathname, char *buf,
2047 int size, Error **errp)
2048{
2049 int fd;
2050 int res;
2051
2052 errno = 0;
2053 fd = openat(dirfd, pathname, O_RDONLY);
2054 if (fd == -1) {
2055 error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2056 return;
2057 }
2058
2059 res = pread(fd, buf, size, 0);
2060 if (res == -1) {
2061 error_setg_errno(errp, errno, "pread sysfs file \"%s\"", pathname);
2062 } else if (res == 0) {
2063 error_setg(errp, "pread sysfs file \"%s\": unexpected EOF", pathname);
2064 }
2065 close(fd);
2066}
2067
2068static void ga_write_sysfs_file(int dirfd, const char *pathname,
2069 const char *buf, int size, Error **errp)
2070{
2071 int fd;
2072
2073 errno = 0;
2074 fd = openat(dirfd, pathname, O_WRONLY);
2075 if (fd == -1) {
2076 error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2077 return;
2078 }
2079
2080 if (pwrite(fd, buf, size, 0) == -1) {
2081 error_setg_errno(errp, errno, "pwrite sysfs file \"%s\"", pathname);
2082 }
2083
2084 close(fd);
2085}
2086
2087/* Transfer online/offline status between @mem_blk and the guest system.
2088 *
2089 * On input either @errp or *@errp must be NULL.
2090 *
2091 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2092 * - R: mem_blk->phys_index
2093 * - W: mem_blk->online
2094 * - W: mem_blk->can_offline
2095 *
2096 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2097 * - R: mem_blk->phys_index
2098 * - R: mem_blk->online
2099 *- R: mem_blk->can_offline
2100 * Written members remain unmodified on error.
2101 */
2102static void transfer_memory_block(GuestMemoryBlock *mem_blk, bool sys2memblk,
2103 GuestMemoryBlockResponse *result,
2104 Error **errp)
2105{
2106 char *dirpath;
2107 int dirfd;
2108 char *status;
2109 Error *local_err = NULL;
2110
2111 if (!sys2memblk) {
2112 DIR *dp;
2113
2114 if (!result) {
2115 error_setg(errp, "Internal error, 'result' should not be NULL");
2116 return;
2117 }
2118 errno = 0;
2119 dp = opendir("/sys/devices/system/memory/");
2120 /* if there is no 'memory' directory in sysfs,
2121 * we think this VM does not support online/offline memory block,
2122 * any other solution?
2123 */
2124 if (!dp && errno == ENOENT) {
2125 result->response =
2126 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2127 goto out1;
2128 }
2129 closedir(dp);
2130 }
2131
2132 dirpath = g_strdup_printf("/sys/devices/system/memory/memory%" PRId64 "/",
2133 mem_blk->phys_index);
2134 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2135 if (dirfd == -1) {
2136 if (sys2memblk) {
2137 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2138 } else {
2139 if (errno == ENOENT) {
2140 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND;
2141 } else {
2142 result->response =
2143 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2144 }
2145 }
2146 g_free(dirpath);
2147 goto out1;
2148 }
2149 g_free(dirpath);
2150
2151 status = g_malloc0(10);
2152 ga_read_sysfs_file(dirfd, "state", status, 10, &local_err);
2153 if (local_err) {
2154 /* treat with sysfs file that not exist in old kernel */
2155 if (errno == ENOENT) {
2156 error_free(local_err);
2157 if (sys2memblk) {
2158 mem_blk->online = true;
2159 mem_blk->can_offline = false;
2160 } else if (!mem_blk->online) {
2161 result->response =
2162 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2163 }
2164 } else {
2165 if (sys2memblk) {
2166 error_propagate(errp, local_err);
2167 } else {
2168 result->response =
2169 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2170 }
2171 }
2172 goto out2;
2173 }
2174
2175 if (sys2memblk) {
2176 char removable = '0';
2177
2178 mem_blk->online = (strncmp(status, "online", 6) == 0);
2179
2180 ga_read_sysfs_file(dirfd, "removable", &removable, 1, &local_err);
2181 if (local_err) {
Veres Lajos67cc32e2015-09-08 22:45:14 +01002182 /* if no 'removable' file, it doesn't support offline mem blk */
zhanghailiangbd240fc2015-01-22 10:40:03 +08002183 if (errno == ENOENT) {
2184 error_free(local_err);
2185 mem_blk->can_offline = false;
2186 } else {
2187 error_propagate(errp, local_err);
2188 }
2189 } else {
2190 mem_blk->can_offline = (removable != '0');
2191 }
2192 } else {
2193 if (mem_blk->online != (strncmp(status, "online", 6) == 0)) {
2194 char *new_state = mem_blk->online ? g_strdup("online") :
2195 g_strdup("offline");
2196
2197 ga_write_sysfs_file(dirfd, "state", new_state, strlen(new_state),
2198 &local_err);
2199 g_free(new_state);
2200 if (local_err) {
2201 error_free(local_err);
2202 result->response =
2203 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2204 goto out2;
2205 }
2206
2207 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS;
2208 result->has_error_code = false;
2209 } /* otherwise pretend successful re-(on|off)-lining */
2210 }
2211 g_free(status);
2212 close(dirfd);
2213 return;
2214
2215out2:
2216 g_free(status);
2217 close(dirfd);
2218out1:
2219 if (!sys2memblk) {
2220 result->has_error_code = true;
2221 result->error_code = errno;
2222 }
2223}
2224
zhanghailianga065aaa2015-01-22 10:40:02 +08002225GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2226{
zhanghailiangbd240fc2015-01-22 10:40:03 +08002227 GuestMemoryBlockList *head, **link;
2228 Error *local_err = NULL;
2229 struct dirent *de;
2230 DIR *dp;
2231
2232 head = NULL;
2233 link = &head;
2234
2235 dp = opendir("/sys/devices/system/memory/");
2236 if (!dp) {
Michael Rothf693fe62015-10-19 16:38:25 -05002237 /* it's ok if this happens to be a system that doesn't expose
2238 * memory blocks via sysfs, but otherwise we should report
2239 * an error
2240 */
2241 if (errno != ENOENT) {
2242 error_setg_errno(errp, errno, "Can't open directory"
Markus Armbruster9af9e0f2015-12-18 16:35:19 +01002243 "\"/sys/devices/system/memory/\"");
Michael Rothf693fe62015-10-19 16:38:25 -05002244 }
zhanghailiangbd240fc2015-01-22 10:40:03 +08002245 return NULL;
2246 }
2247
2248 /* Note: the phys_index of memory block may be discontinuous,
2249 * this is because a memblk is the unit of the Sparse Memory design, which
2250 * allows discontinuous memory ranges (ex. NUMA), so here we should
2251 * traverse the memory block directory.
2252 */
2253 while ((de = readdir(dp)) != NULL) {
2254 GuestMemoryBlock *mem_blk;
2255 GuestMemoryBlockList *entry;
2256
2257 if ((strncmp(de->d_name, "memory", 6) != 0) ||
2258 !(de->d_type & DT_DIR)) {
2259 continue;
2260 }
2261
2262 mem_blk = g_malloc0(sizeof *mem_blk);
2263 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2264 mem_blk->phys_index = strtoul(&de->d_name[6], NULL, 10);
2265 mem_blk->has_can_offline = true; /* lolspeak ftw */
2266 transfer_memory_block(mem_blk, true, NULL, &local_err);
2267
2268 entry = g_malloc0(sizeof *entry);
2269 entry->value = mem_blk;
2270
2271 *link = entry;
2272 link = &entry->next;
2273 }
2274
2275 closedir(dp);
2276 if (local_err == NULL) {
2277 /* there's no guest with zero memory blocks */
2278 if (head == NULL) {
2279 error_setg(errp, "guest reported zero memory blocks!");
2280 }
2281 return head;
2282 }
2283
2284 qapi_free_GuestMemoryBlockList(head);
2285 error_propagate(errp, local_err);
zhanghailianga065aaa2015-01-22 10:40:02 +08002286 return NULL;
2287}
2288
2289GuestMemoryBlockResponseList *
2290qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2291{
zhanghailiang32ca7922015-01-22 10:40:04 +08002292 GuestMemoryBlockResponseList *head, **link;
2293 Error *local_err = NULL;
2294
2295 head = NULL;
2296 link = &head;
2297
2298 while (mem_blks != NULL) {
2299 GuestMemoryBlockResponse *result;
2300 GuestMemoryBlockResponseList *entry;
2301 GuestMemoryBlock *current_mem_blk = mem_blks->value;
2302
2303 result = g_malloc0(sizeof(*result));
2304 result->phys_index = current_mem_blk->phys_index;
2305 transfer_memory_block(current_mem_blk, false, result, &local_err);
2306 if (local_err) { /* should never happen */
2307 goto err;
2308 }
2309 entry = g_malloc0(sizeof *entry);
2310 entry->value = result;
2311
2312 *link = entry;
2313 link = &entry->next;
2314 mem_blks = mem_blks->next;
2315 }
2316
2317 return head;
2318err:
2319 qapi_free_GuestMemoryBlockResponseList(head);
2320 error_propagate(errp, local_err);
zhanghailianga065aaa2015-01-22 10:40:02 +08002321 return NULL;
2322}
2323
2324GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2325{
zhanghailiangef82b602015-01-22 10:40:05 +08002326 Error *local_err = NULL;
2327 char *dirpath;
2328 int dirfd;
2329 char *buf;
2330 GuestMemoryBlockInfo *info;
2331
2332 dirpath = g_strdup_printf("/sys/devices/system/memory/");
2333 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2334 if (dirfd == -1) {
2335 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2336 g_free(dirpath);
2337 return NULL;
2338 }
2339 g_free(dirpath);
2340
2341 buf = g_malloc0(20);
2342 ga_read_sysfs_file(dirfd, "block_size_bytes", buf, 20, &local_err);
Shannon Zhao8ce1ee42015-03-14 17:52:15 +08002343 close(dirfd);
zhanghailiangef82b602015-01-22 10:40:05 +08002344 if (local_err) {
2345 g_free(buf);
2346 error_propagate(errp, local_err);
2347 return NULL;
2348 }
2349
2350 info = g_new0(GuestMemoryBlockInfo, 1);
2351 info->size = strtol(buf, NULL, 16); /* the unit is bytes */
2352
2353 g_free(buf);
2354
2355 return info;
zhanghailianga065aaa2015-01-22 10:40:02 +08002356}
2357
Michael Rothe72c3f22012-03-25 13:59:41 -05002358#else /* defined(__linux__) */
2359
Markus Armbruster77dbc812014-05-02 13:26:30 +02002360void qmp_guest_suspend_disk(Error **errp)
Michael Rothe72c3f22012-03-25 13:59:41 -05002361{
Markus Armbrusterc6bd8c72015-03-17 11:54:50 +01002362 error_setg(errp, QERR_UNSUPPORTED);
Michael Rothe72c3f22012-03-25 13:59:41 -05002363}
2364
Markus Armbruster77dbc812014-05-02 13:26:30 +02002365void qmp_guest_suspend_ram(Error **errp)
Michael Rothe72c3f22012-03-25 13:59:41 -05002366{
Markus Armbrusterc6bd8c72015-03-17 11:54:50 +01002367 error_setg(errp, QERR_UNSUPPORTED);
Michael Rothe72c3f22012-03-25 13:59:41 -05002368}
2369
Markus Armbruster77dbc812014-05-02 13:26:30 +02002370void qmp_guest_suspend_hybrid(Error **errp)
Michael Rothe72c3f22012-03-25 13:59:41 -05002371{
Markus Armbrusterc6bd8c72015-03-17 11:54:50 +01002372 error_setg(errp, QERR_UNSUPPORTED);
Michael Rothe72c3f22012-03-25 13:59:41 -05002373}
2374
2375GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
2376{
Markus Armbrusterc6bd8c72015-03-17 11:54:50 +01002377 error_setg(errp, QERR_UNSUPPORTED);
Michael Rothe72c3f22012-03-25 13:59:41 -05002378 return NULL;
2379}
2380
Laszlo Ersekd2baff62013-03-06 22:59:30 +01002381GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
2382{
Markus Armbrusterc6bd8c72015-03-17 11:54:50 +01002383 error_setg(errp, QERR_UNSUPPORTED);
Laszlo Ersekd2baff62013-03-06 22:59:30 +01002384 return NULL;
2385}
2386
Laszlo Ersekcbb65fc2013-03-06 22:59:31 +01002387int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
2388{
Markus Armbrusterc6bd8c72015-03-17 11:54:50 +01002389 error_setg(errp, QERR_UNSUPPORTED);
Laszlo Ersekcbb65fc2013-03-06 22:59:31 +01002390 return -1;
2391}
2392
Daniel P. Berrange215a2772015-02-11 11:26:12 +00002393void qmp_guest_set_user_password(const char *username,
2394 const char *password,
2395 bool crypted,
2396 Error **errp)
2397{
Markus Armbrusterc6bd8c72015-03-17 11:54:50 +01002398 error_setg(errp, QERR_UNSUPPORTED);
Daniel P. Berrange215a2772015-02-11 11:26:12 +00002399}
2400
zhanghailianga065aaa2015-01-22 10:40:02 +08002401GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2402{
Markus Armbrusterc6bd8c72015-03-17 11:54:50 +01002403 error_setg(errp, QERR_UNSUPPORTED);
zhanghailianga065aaa2015-01-22 10:40:02 +08002404 return NULL;
2405}
2406
2407GuestMemoryBlockResponseList *
2408qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2409{
Markus Armbrusterc6bd8c72015-03-17 11:54:50 +01002410 error_setg(errp, QERR_UNSUPPORTED);
zhanghailianga065aaa2015-01-22 10:40:02 +08002411 return NULL;
2412}
2413
2414GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2415{
Markus Armbrusterc6bd8c72015-03-17 11:54:50 +01002416 error_setg(errp, QERR_UNSUPPORTED);
zhanghailianga065aaa2015-01-22 10:40:02 +08002417 return NULL;
2418}
2419
Michael Rothe72c3f22012-03-25 13:59:41 -05002420#endif
2421
Michael Rothd35d4cb2012-04-13 21:07:36 -05002422#if !defined(CONFIG_FSFREEZE)
2423
Tomoki Sekiyama46d4c572014-06-30 17:51:34 -04002424GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
2425{
Markus Armbrusterc6bd8c72015-03-17 11:54:50 +01002426 error_setg(errp, QERR_UNSUPPORTED);
Tomoki Sekiyama46d4c572014-06-30 17:51:34 -04002427 return NULL;
2428}
2429
Markus Armbruster77dbc812014-05-02 13:26:30 +02002430GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
Michael Rothd35d4cb2012-04-13 21:07:36 -05002431{
Markus Armbrusterc6bd8c72015-03-17 11:54:50 +01002432 error_setg(errp, QERR_UNSUPPORTED);
Michael Rothd35d4cb2012-04-13 21:07:36 -05002433
2434 return 0;
2435}
2436
Markus Armbruster77dbc812014-05-02 13:26:30 +02002437int64_t qmp_guest_fsfreeze_freeze(Error **errp)
Michael Rothd35d4cb2012-04-13 21:07:36 -05002438{
Markus Armbrusterc6bd8c72015-03-17 11:54:50 +01002439 error_setg(errp, QERR_UNSUPPORTED);
Michael Rothd35d4cb2012-04-13 21:07:36 -05002440
2441 return 0;
2442}
2443
Tomoki Sekiyamae99bce22014-06-30 17:51:27 -04002444int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
2445 strList *mountpoints,
2446 Error **errp)
2447{
Markus Armbrusterc6bd8c72015-03-17 11:54:50 +01002448 error_setg(errp, QERR_UNSUPPORTED);
Tomoki Sekiyamae99bce22014-06-30 17:51:27 -04002449
2450 return 0;
2451}
2452
Markus Armbruster77dbc812014-05-02 13:26:30 +02002453int64_t qmp_guest_fsfreeze_thaw(Error **errp)
Michael Rothd35d4cb2012-04-13 21:07:36 -05002454{
Markus Armbrusterc6bd8c72015-03-17 11:54:50 +01002455 error_setg(errp, QERR_UNSUPPORTED);
Michael Rothd35d4cb2012-04-13 21:07:36 -05002456
2457 return 0;
2458}
Paolo Bonzinieab5fd52012-06-13 07:41:28 +02002459#endif /* CONFIG_FSFREEZE */
Michael Rothd35d4cb2012-04-13 21:07:36 -05002460
Paolo Bonzinieab5fd52012-06-13 07:41:28 +02002461#if !defined(CONFIG_FSTRIM)
Justin Ossevoorte82855d2015-05-11 08:58:45 +02002462GuestFilesystemTrimResponse *
2463qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
Paolo Bonzinieab5fd52012-06-13 07:41:28 +02002464{
Markus Armbrusterc6bd8c72015-03-17 11:54:50 +01002465 error_setg(errp, QERR_UNSUPPORTED);
Justin Ossevoorte82855d2015-05-11 08:58:45 +02002466 return NULL;
Paolo Bonzinieab5fd52012-06-13 07:41:28 +02002467}
Michael Rothd35d4cb2012-04-13 21:07:36 -05002468#endif
2469
Tomoki Sekiyama1281c082014-06-30 17:51:40 -04002470/* add unsupported commands to the blacklist */
2471GList *ga_command_blacklist_init(GList *blacklist)
2472{
2473#if !defined(__linux__)
2474 {
2475 const char *list[] = {
2476 "guest-suspend-disk", "guest-suspend-ram",
2477 "guest-suspend-hybrid", "guest-network-get-interfaces",
zhanghailiang0dd38a02015-01-22 10:40:06 +08002478 "guest-get-vcpus", "guest-set-vcpus",
2479 "guest-get-memory-blocks", "guest-set-memory-blocks",
2480 "guest-get-memory-block-size", NULL};
Tomoki Sekiyama1281c082014-06-30 17:51:40 -04002481 char **p = (char **)list;
2482
2483 while (*p) {
Marc-André Lureau4bca81c2015-08-27 01:34:50 +02002484 blacklist = g_list_append(blacklist, g_strdup(*p++));
Tomoki Sekiyama1281c082014-06-30 17:51:40 -04002485 }
2486 }
2487#endif
2488
2489#if !defined(CONFIG_FSFREEZE)
2490 {
2491 const char *list[] = {
2492 "guest-get-fsinfo", "guest-fsfreeze-status",
2493 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
2494 "guest-fsfreeze-thaw", "guest-get-fsinfo", NULL};
2495 char **p = (char **)list;
2496
2497 while (*p) {
Marc-André Lureau4bca81c2015-08-27 01:34:50 +02002498 blacklist = g_list_append(blacklist, g_strdup(*p++));
Tomoki Sekiyama1281c082014-06-30 17:51:40 -04002499 }
2500 }
2501#endif
2502
2503#if !defined(CONFIG_FSTRIM)
Marc-André Lureau4bca81c2015-08-27 01:34:50 +02002504 blacklist = g_list_append(blacklist, g_strdup("guest-fstrim"));
Tomoki Sekiyama1281c082014-06-30 17:51:40 -04002505#endif
2506
2507 return blacklist;
2508}
2509
Michael Rothe3d4d252011-07-19 15:41:55 -05002510/* register init/cleanup routines for stateful command groups */
2511void ga_command_state_init(GAState *s, GACommandState *cs)
2512{
Anthony Liguori7006b9c2011-07-22 14:14:17 -05002513#if defined(CONFIG_FSFREEZE)
Michael Rothf22d85e2012-04-17 19:01:45 -05002514 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
Anthony Liguori7006b9c2011-07-22 14:14:17 -05002515#endif
Michael Rothe3d4d252011-07-19 15:41:55 -05002516}