CVE-2015-0236: qemu: Check ACLs when dumping security info from save image
[libvirt.git] / src / qemu / qemu_driver.c
1 /*
2  * qemu_driver.c: core driver methods for managing qemu guests
3  *
4  * Copyright (C) 2006-2013 Red Hat, Inc.
5  * Copyright (C) 2006 Daniel P. Berrange
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library.  If not, see
19  * <http://www.gnu.org/licenses/>.
20  *
21  * Author: Daniel P. Berrange <berrange@redhat.com>
22  */
23
24 #include <config.h>
25
26 #include <sys/types.h>
27 #include <sys/poll.h>
28 #include <sys/time.h>
29 #include <dirent.h>
30 #include <limits.h>
31 #include <string.h>
32 #include <stdio.h>
33 #include <stdarg.h>
34 #include <stdlib.h>
35 #include <unistd.h>
36 #include <errno.h>
37 #include <sys/stat.h>
38 #include <fcntl.h>
39 #include <signal.h>
40 #include <paths.h>
41 #include <sys/wait.h>
42 #include <sys/ioctl.h>
43 #include <sys/un.h>
44 #include <byteswap.h>
45
46
47 #include "qemu_driver.h"
48 #include "qemu_agent.h"
49 #include "qemu_conf.h"
50 #include "qemu_capabilities.h"
51 #include "qemu_command.h"
52 #include "qemu_cgroup.h"
53 #include "qemu_hostdev.h"
54 #include "qemu_hotplug.h"
55 #include "qemu_monitor.h"
56 #include "qemu_bridge_filter.h"
57 #include "qemu_process.h"
58 #include "qemu_migration.h"
59
60 #include "virerror.h"
61 #include "virlog.h"
62 #include "datatypes.h"
63 #include "virbuffer.h"
64 #include "nodeinfo.h"
65 #include "virstatslinux.h"
66 #include "capabilities.h"
67 #include "viralloc.h"
68 #include "viruuid.h"
69 #include "domain_conf.h"
70 #include "domain_audit.h"
71 #include "node_device_conf.h"
72 #include "virpci.h"
73 #include "virusb.h"
74 #include "virprocess.h"
75 #include "libvirt_internal.h"
76 #include "virxml.h"
77 #include "cpu/cpu.h"
78 #include "virsysinfo.h"
79 #include "domain_nwfilter.h"
80 #include "nwfilter_conf.h"
81 #include "virhook.h"
82 #include "virstoragefile.h"
83 #include "virfile.h"
84 #include "fdstream.h"
85 #include "configmake.h"
86 #include "virthreadpool.h"
87 #include "locking/lock_manager.h"
88 #include "locking/domain_lock.h"
89 #include "virkeycode.h"
90 #include "virnodesuspend.h"
91 #include "virtime.h"
92 #include "virtypedparam.h"
93 #include "virbitmap.h"
94 #include "virstring.h"
95 #include "viraccessapicheck.h"
96 #include "viraccessapicheckqemu.h"
97
98 #define VIR_FROM_THIS VIR_FROM_QEMU
99
100 #define QEMU_DRIVER_NAME "QEMU"
101
102 #define QEMU_NB_MEM_PARAM  3
103
104 #define QEMU_NB_BLOCK_IO_TUNE_PARAM  6
105
106 #define QEMU_NB_NUMA_PARAM 2
107
108 #define QEMU_NB_TOTAL_CPU_STAT_PARAM 3
109 #define QEMU_NB_PER_CPU_STAT_PARAM 2
110
111 #define QEMU_SCHED_MIN_PERIOD              1000LL
112 #define QEMU_SCHED_MAX_PERIOD           1000000LL
113 #define QEMU_SCHED_MIN_QUOTA               1000LL
114 #define QEMU_SCHED_MAX_QUOTA  18446744073709551LL
115
116 #if HAVE_LINUX_KVM_H
117 # include <linux/kvm.h>
118 #endif
119
120 /* device for kvm ioctls */
121 #define KVM_DEVICE "/dev/kvm"
122
123 /* add definitions missing in older linux/kvm.h */
124 #ifndef KVMIO
125 # define KVMIO 0xAE
126 #endif
127 #ifndef KVM_CHECK_EXTENSION
128 # define KVM_CHECK_EXTENSION       _IO(KVMIO,   0x03)
129 #endif
130 #ifndef KVM_CAP_NR_VCPUS
131 # define KVM_CAP_NR_VCPUS 9       /* returns max vcpus per vm */
132 #endif
133
134 #define QEMU_NB_BLKIO_PARAM  2
135
136 #define QEMU_NB_BANDWIDTH_PARAM 6
137
138 static void processWatchdogEvent(virQEMUDriverPtr driver,
139                                  virDomainObjPtr vm,
140                                  int action);
141
142 static void processGuestPanicEvent(virQEMUDriverPtr driver,
143                                    virDomainObjPtr vm,
144                                    int action);
145
146 static void qemuProcessEventHandler(void *data, void *opaque);
147
148 static int qemuStateCleanup(void);
149
150 static int qemuDomainObjStart(virConnectPtr conn,
151                               virQEMUDriverPtr driver,
152                               virDomainObjPtr vm,
153                               unsigned int flags);
154
155 static int qemuDomainGetMaxVcpus(virDomainPtr dom);
156
157 static int qemuDomainManagedSaveLoad(virDomainObjPtr vm,
158                                      void *opaque);
159
160 static int qemuOpenFile(virQEMUDriverPtr driver,
161                         virDomainObjPtr vm,
162                         const char *path, int oflags,
163                         bool *needUnlink, bool *bypassSecurityDriver);
164
165 static int qemuOpenFileAs(uid_t fallback_uid, gid_t fallback_gid,
166                           bool dynamicOwnership,
167                           const char *path, int oflags,
168                           bool *needUnlink, bool *bypassSecurityDriver);
169
170
171 virQEMUDriverPtr qemu_driver = NULL;
172
173
174 static void
175 qemuVMDriverLock(void) {}
176 static void
177 qemuVMDriverUnlock(void) {}
178
179 static int
180 qemuVMFilterRebuild(virDomainObjListIterator iter, void *data)
181 {
182     return virDomainObjListForEach(qemu_driver->domains, iter, data);
183 }
184
185 static virNWFilterCallbackDriver qemuCallbackDriver = {
186     .name = QEMU_DRIVER_NAME,
187     .vmFilterRebuild = qemuVMFilterRebuild,
188     .vmDriverLock = qemuVMDriverLock,
189     .vmDriverUnlock = qemuVMDriverUnlock,
190 };
191
192
193 struct qemuAutostartData {
194     virQEMUDriverPtr driver;
195     virConnectPtr conn;
196 };
197
198
199 /**
200  * qemuDomObjFromDomain:
201  * @domain: Domain pointer that has to be looked up
202  *
203  * This function looks up @domain and returns the appropriate
204  * virDomainObjPtr.
205  *
206  * Returns the domain object which is locked on success, NULL
207  * otherwise.
208  */
209 static virDomainObjPtr
210 qemuDomObjFromDomain(virDomainPtr domain)
211 {
212     virDomainObjPtr vm;
213     virQEMUDriverPtr driver = domain->conn->privateData;
214     char uuidstr[VIR_UUID_STRING_BUFLEN];
215
216     vm = virDomainObjListFindByUUID(driver->domains, domain->uuid);
217     if (!vm) {
218         virUUIDFormat(domain->uuid, uuidstr);
219         virReportError(VIR_ERR_NO_DOMAIN,
220                        _("no domain with matching uuid '%s' (%s)"),
221                        uuidstr, domain->name);
222         return NULL;
223     }
224
225     return vm;
226 }
227
228 /* Looks up the domain object from snapshot and unlocks the driver. The
229  * returned domain object is locked and the caller is responsible for
230  * unlocking it */
231 static virDomainObjPtr
232 qemuDomObjFromSnapshot(virDomainSnapshotPtr snapshot)
233 {
234     return qemuDomObjFromDomain(snapshot->domain);
235 }
236
237
238 /* Looks up snapshot object from VM and name */
239 static virDomainSnapshotObjPtr
240 qemuSnapObjFromName(virDomainObjPtr vm,
241                     const char *name)
242 {
243     virDomainSnapshotObjPtr snap = NULL;
244     snap = virDomainSnapshotFindByName(vm->snapshots, name);
245     if (!snap)
246         virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
247                        _("no domain snapshot with matching name '%s'"),
248                        name);
249
250     return snap;
251 }
252
253
254 /* Looks up snapshot object from VM and snapshotPtr */
255 static virDomainSnapshotObjPtr
256 qemuSnapObjFromSnapshot(virDomainObjPtr vm,
257                         virDomainSnapshotPtr snapshot)
258 {
259     return qemuSnapObjFromName(vm, snapshot->name);
260 }
261
262 static int
263 qemuAutostartDomain(virDomainObjPtr vm,
264                     void *opaque)
265 {
266     struct qemuAutostartData *data = opaque;
267     virErrorPtr err;
268     int flags = 0;
269     virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(data->driver);
270     int ret = -1;
271
272     if (cfg->autoStartBypassCache)
273         flags |= VIR_DOMAIN_START_BYPASS_CACHE;
274
275     virObjectLock(vm);
276     virResetLastError();
277     if (vm->autostart &&
278         !virDomainObjIsActive(vm)) {
279         if (qemuDomainObjBeginJob(data->driver, vm,
280                                   QEMU_JOB_MODIFY) < 0) {
281             err = virGetLastError();
282             VIR_ERROR(_("Failed to start job on VM '%s': %s"),
283                       vm->def->name,
284                       err ? err->message : _("unknown error"));
285             goto cleanup;
286         }
287
288         if (qemuDomainObjStart(data->conn, data->driver, vm, flags) < 0) {
289             err = virGetLastError();
290             VIR_ERROR(_("Failed to autostart VM '%s': %s"),
291                       vm->def->name,
292                       err ? err->message : _("unknown error"));
293         }
294
295         if (qemuDomainObjEndJob(data->driver, vm) == 0)
296             vm = NULL;
297     }
298
299     ret = 0;
300 cleanup:
301     if (vm)
302         virObjectUnlock(vm);
303     virObjectUnref(cfg);
304     return ret;
305 }
306
307
308 static void
309 qemuAutostartDomains(virQEMUDriverPtr driver)
310 {
311     virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
312     /* XXX: Figure out a better way todo this. The domain
313      * startup code needs a connection handle in order
314      * to lookup the bridge associated with a virtual
315      * network
316      */
317     virConnectPtr conn = virConnectOpen(cfg->uri);
318     /* Ignoring NULL conn which is mostly harmless here */
319     struct qemuAutostartData data = { driver, conn };
320
321     virDomainObjListForEach(driver->domains, qemuAutostartDomain, &data);
322
323     if (conn)
324         virConnectClose(conn);
325     virObjectUnref(cfg);
326 }
327
328 static int
329 qemuSecurityInit(virQEMUDriverPtr driver)
330 {
331     char **names;
332     virSecurityManagerPtr mgr = NULL;
333     virSecurityManagerPtr stack = NULL;
334     virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
335
336     if (cfg->securityDriverNames &&
337         cfg->securityDriverNames[0]) {
338         names = cfg->securityDriverNames;
339         while (names && *names) {
340             if (!(mgr = virSecurityManagerNew(*names,
341                                               QEMU_DRIVER_NAME,
342                                               cfg->allowDiskFormatProbing,
343                                               cfg->securityDefaultConfined,
344                                               cfg->securityRequireConfined)))
345                 goto error;
346             if (!stack) {
347                 if (!(stack = virSecurityManagerNewStack(mgr)))
348                     goto error;
349             } else {
350                 if (virSecurityManagerStackAddNested(stack, mgr) < 0)
351                     goto error;
352             }
353             mgr = NULL;
354             names++;
355         }
356     } else {
357         if (!(mgr = virSecurityManagerNew(NULL,
358                                           QEMU_DRIVER_NAME,
359                                           cfg->allowDiskFormatProbing,
360                                           cfg->securityDefaultConfined,
361                                           cfg->securityRequireConfined)))
362             goto error;
363         if (!(stack = virSecurityManagerNewStack(mgr)))
364             goto error;
365         mgr = NULL;
366     }
367
368     if (cfg->privileged) {
369         if (!(mgr = virSecurityManagerNewDAC(QEMU_DRIVER_NAME,
370                                              cfg->user,
371                                              cfg->group,
372                                              cfg->allowDiskFormatProbing,
373                                              cfg->securityDefaultConfined,
374                                              cfg->securityRequireConfined,
375                                              cfg->dynamicOwnership)))
376             goto error;
377         if (!stack) {
378             if (!(stack = virSecurityManagerNewStack(mgr)))
379                 goto error;
380         } else {
381             if (virSecurityManagerStackAddNested(stack, mgr) < 0)
382                 goto error;
383         }
384         mgr = NULL;
385     }
386
387     driver->securityManager = stack;
388     virObjectUnref(cfg);
389     return 0;
390
391 error:
392     VIR_ERROR(_("Failed to initialize security drivers"));
393     virObjectUnref(stack);
394     virObjectUnref(mgr);
395     virObjectUnref(cfg);
396     return -1;
397 }
398
399
400 static int
401 qemuDomainSnapshotLoad(virDomainObjPtr vm,
402                        void *data)
403 {
404     char *baseDir = (char *)data;
405     char *snapDir = NULL;
406     DIR *dir = NULL;
407     struct dirent *entry;
408     char *xmlStr;
409     char *fullpath;
410     virDomainSnapshotDefPtr def = NULL;
411     virDomainSnapshotObjPtr snap = NULL;
412     virDomainSnapshotObjPtr current = NULL;
413     char ebuf[1024];
414     unsigned int flags = (VIR_DOMAIN_SNAPSHOT_PARSE_REDEFINE |
415                           VIR_DOMAIN_SNAPSHOT_PARSE_DISKS |
416                           VIR_DOMAIN_SNAPSHOT_PARSE_INTERNAL);
417     int ret = -1;
418     virCapsPtr caps = NULL;
419
420     virObjectLock(vm);
421     if (virAsprintf(&snapDir, "%s/%s", baseDir, vm->def->name) < 0) {
422         VIR_ERROR(_("Failed to allocate memory for snapshot directory for domain %s"),
423                    vm->def->name);
424         goto cleanup;
425     }
426
427     if (!(caps = virQEMUDriverGetCapabilities(qemu_driver, false)))
428         goto cleanup;
429
430     VIR_INFO("Scanning for snapshots for domain %s in %s", vm->def->name,
431              snapDir);
432
433     if (!(dir = opendir(snapDir))) {
434         if (errno != ENOENT)
435             VIR_ERROR(_("Failed to open snapshot directory %s for domain %s: %s"),
436                       snapDir, vm->def->name,
437                       virStrerror(errno, ebuf, sizeof(ebuf)));
438         goto cleanup;
439     }
440
441     while ((entry = readdir(dir))) {
442         if (entry->d_name[0] == '.')
443             continue;
444
445         /* NB: ignoring errors, so one malformed config doesn't
446            kill the whole process */
447         VIR_INFO("Loading snapshot file '%s'", entry->d_name);
448
449         if (virAsprintf(&fullpath, "%s/%s", snapDir, entry->d_name) < 0) {
450             VIR_ERROR(_("Failed to allocate memory for path"));
451             continue;
452         }
453
454         if (virFileReadAll(fullpath, 1024*1024*1, &xmlStr) < 0) {
455             /* Nothing we can do here, skip this one */
456             VIR_ERROR(_("Failed to read snapshot file %s: %s"), fullpath,
457                       virStrerror(errno, ebuf, sizeof(ebuf)));
458             VIR_FREE(fullpath);
459             continue;
460         }
461
462         def = virDomainSnapshotDefParseString(xmlStr, caps,
463                                               qemu_driver->xmlopt,
464                                               QEMU_EXPECTED_VIRT_TYPES,
465                                               flags);
466         if (def == NULL) {
467             /* Nothing we can do here, skip this one */
468             VIR_ERROR(_("Failed to parse snapshot XML from file '%s'"),
469                       fullpath);
470             VIR_FREE(fullpath);
471             VIR_FREE(xmlStr);
472             continue;
473         }
474
475         snap = virDomainSnapshotAssignDef(vm->snapshots, def);
476         if (snap == NULL) {
477             virDomainSnapshotDefFree(def);
478         } else if (snap->def->current) {
479             current = snap;
480             if (!vm->current_snapshot)
481                 vm->current_snapshot = snap;
482         }
483
484         VIR_FREE(fullpath);
485         VIR_FREE(xmlStr);
486     }
487
488     if (vm->current_snapshot != current) {
489         VIR_ERROR(_("Too many snapshots claiming to be current for domain %s"),
490                   vm->def->name);
491         vm->current_snapshot = NULL;
492     }
493
494     if (virDomainSnapshotUpdateRelations(vm->snapshots) < 0)
495         VIR_ERROR(_("Snapshots have inconsistent relations for domain %s"),
496                   vm->def->name);
497
498     /* FIXME: qemu keeps internal track of snapshots.  We can get access
499      * to this info via the "info snapshots" monitor command for running
500      * domains, or via "qemu-img snapshot -l" for shutoff domains.  It would
501      * be nice to update our internal state based on that, but there is a
502      * a problem.  qemu doesn't track all of the same metadata that we do.
503      * In particular we wouldn't be able to fill in the <parent>, which is
504      * pretty important in our metadata.
505      */
506
507     virResetLastError();
508
509     ret = 0;
510 cleanup:
511     if (dir)
512         closedir(dir);
513     VIR_FREE(snapDir);
514     virObjectUnref(caps);
515     virObjectUnlock(vm);
516     return ret;
517 }
518
519
520 static int
521 qemuDomainNetsRestart(virDomainObjPtr vm,
522                       void *data ATTRIBUTE_UNUSED)
523 {
524     size_t i;
525     virDomainDefPtr def = vm->def;
526
527     virObjectLock(vm);
528
529     for (i = 0; i < def->nnets; i++) {
530         virDomainNetDefPtr net = def->nets[i];
531         if (virDomainNetGetActualType(net) == VIR_DOMAIN_NET_TYPE_DIRECT &&
532             virDomainNetGetActualDirectMode(net) == VIR_NETDEV_MACVLAN_MODE_VEPA) {
533             VIR_DEBUG("VEPA mode device %s active in domain %s. Reassociating.",
534                       net->ifname, def->name);
535             ignore_value(virNetDevMacVLanRestartWithVPortProfile(net->ifname,
536                                                                  &net->mac,
537                                                                  virDomainNetGetActualDirectDev(net),
538                                                                  def->uuid,
539                                                                  virDomainNetGetActualVirtPortProfile(net),
540                                                                  VIR_NETDEV_VPORT_PROFILE_OP_CREATE));
541         }
542     }
543
544     virObjectUnlock(vm);
545     return 0;
546 }
547
548
549 static int
550 qemuDomainFindMaxID(virDomainObjPtr vm,
551                     void *data)
552 {
553     int *driver_maxid = data;
554
555     if (vm->def->id >= *driver_maxid)
556         *driver_maxid = vm->def->id + 1;
557
558     return 0;
559 }
560
561
562 /**
563  * qemuStateInitialize:
564  *
565  * Initialization function for the QEmu daemon
566  */
567 static int
568 qemuStateInitialize(bool privileged,
569                     virStateInhibitCallback callback,
570                     void *opaque)
571 {
572     char *driverConf = NULL;
573     virConnectPtr conn = NULL;
574     char ebuf[1024];
575     char *membase = NULL;
576     char *mempath = NULL;
577     virQEMUDriverConfigPtr cfg;
578     uid_t run_uid = -1;
579     gid_t run_gid = -1;
580
581     if (VIR_ALLOC(qemu_driver) < 0)
582         return -1;
583
584     if (virMutexInit(&qemu_driver->lock) < 0) {
585         VIR_ERROR(_("cannot initialize mutex"));
586         VIR_FREE(qemu_driver);
587         return -1;
588     }
589
590     qemu_driver->inhibitCallback = callback;
591     qemu_driver->inhibitOpaque = opaque;
592
593     /* Don't have a dom0 so start from 1 */
594     qemu_driver->nextvmid = 1;
595
596     if (!(qemu_driver->domains = virDomainObjListNew()))
597         goto error;
598
599     /* Init domain events */
600     qemu_driver->domainEventState = virDomainEventStateNew();
601     if (!qemu_driver->domainEventState)
602         goto error;
603
604     /* read the host sysinfo */
605     if (privileged)
606         qemu_driver->hostsysinfo = virSysinfoRead();
607
608     if (!(qemu_driver->config = cfg = virQEMUDriverConfigNew(privileged)))
609         goto error;
610
611     if (virAsprintf(&driverConf, "%s/qemu.conf", cfg->configBaseDir) < 0)
612         goto error;
613
614     if (virQEMUDriverConfigLoadFile(cfg, driverConf) < 0)
615         goto error;
616     VIR_FREE(driverConf);
617
618     if (virFileMakePath(cfg->stateDir) < 0) {
619         VIR_ERROR(_("Failed to create state dir '%s': %s"),
620                   cfg->stateDir, virStrerror(errno, ebuf, sizeof(ebuf)));
621         goto error;
622     }
623     if (virFileMakePath(cfg->libDir) < 0) {
624         VIR_ERROR(_("Failed to create lib dir '%s': %s"),
625                   cfg->libDir, virStrerror(errno, ebuf, sizeof(ebuf)));
626         goto error;
627     }
628     if (virFileMakePath(cfg->cacheDir) < 0) {
629         VIR_ERROR(_("Failed to create cache dir '%s': %s"),
630                   cfg->cacheDir, virStrerror(errno, ebuf, sizeof(ebuf)));
631         goto error;
632     }
633     if (virFileMakePath(cfg->saveDir) < 0) {
634         VIR_ERROR(_("Failed to create save dir '%s': %s"),
635                   cfg->saveDir, virStrerror(errno, ebuf, sizeof(ebuf)));
636         goto error;
637     }
638     if (virFileMakePath(cfg->snapshotDir) < 0) {
639         VIR_ERROR(_("Failed to create save dir '%s': %s"),
640                   cfg->snapshotDir, virStrerror(errno, ebuf, sizeof(ebuf)));
641         goto error;
642     }
643     if (virFileMakePath(cfg->autoDumpPath) < 0) {
644         VIR_ERROR(_("Failed to create dump dir '%s': %s"),
645                   cfg->autoDumpPath, virStrerror(errno, ebuf, sizeof(ebuf)));
646         goto error;
647     }
648
649     qemu_driver->qemuImgBinary = virFindFileInPath("kvm-img");
650     if (!qemu_driver->qemuImgBinary)
651         qemu_driver->qemuImgBinary = virFindFileInPath("qemu-img");
652
653     if (!(qemu_driver->lockManager =
654           virLockManagerPluginNew(cfg->lockManagerName ?
655                                   cfg->lockManagerName : "nop",
656                                   "qemu",
657                                   cfg->configBaseDir,
658                                   0)))
659         goto error;
660
661    if (cfg->macFilter) {
662         if (!(qemu_driver->ebtables = ebtablesContextNew("qemu"))) {
663             virReportSystemError(errno,
664                                  _("failed to enable mac filter in '%s'"),
665                                  __FILE__);
666             goto error;
667         }
668
669         if ((errno = networkDisableAllFrames(qemu_driver))) {
670             virReportSystemError(errno,
671                                  _("failed to add rule to drop all frames in '%s'"),
672                                  __FILE__);
673             goto error;
674         }
675    }
676
677     /* Allocate bitmap for remote display port reservations. We cannot
678      * do this before the config is loaded properly, since the port
679      * numbers are configurable now */
680     if ((qemu_driver->remotePorts =
681          virPortAllocatorNew(cfg->remotePortMin,
682                              cfg->remotePortMax)) == NULL)
683         goto error;
684
685     if ((qemu_driver->webSocketPorts =
686          virPortAllocatorNew(cfg->webSocketPortMin,
687                              cfg->webSocketPortMax)) == NULL)
688         goto error;
689
690     if (qemuSecurityInit(qemu_driver) < 0)
691         goto error;
692
693     if ((qemu_driver->activePciHostdevs = virPCIDeviceListNew()) == NULL)
694         goto error;
695
696     if ((qemu_driver->activeUsbHostdevs = virUSBDeviceListNew()) == NULL)
697         goto error;
698
699     if ((qemu_driver->inactivePciHostdevs = virPCIDeviceListNew()) == NULL)
700         goto error;
701
702     if ((qemu_driver->activeScsiHostdevs = virSCSIDeviceListNew()) == NULL)
703         goto error;
704
705     if (!(qemu_driver->sharedDevices = virHashCreate(30, qemuSharedDeviceEntryFree)))
706         goto error;
707
708     if (privileged) {
709         if (chown(cfg->libDir, cfg->user, cfg->group) < 0) {
710             virReportSystemError(errno,
711                                  _("unable to set ownership of '%s' to user %d:%d"),
712                                  cfg->libDir, (int) cfg->user,
713                                  (int) cfg->group);
714             goto error;
715         }
716         if (chown(cfg->cacheDir, cfg->user, cfg->group) < 0) {
717             virReportSystemError(errno,
718                                  _("unable to set ownership of '%s' to %d:%d"),
719                                  cfg->cacheDir, (int) cfg->user,
720                                  (int) cfg->group);
721             goto error;
722         }
723         if (chown(cfg->saveDir, cfg->user, cfg->group) < 0) {
724             virReportSystemError(errno,
725                                  _("unable to set ownership of '%s' to %d:%d"),
726                                  cfg->saveDir, (int) cfg->user,
727                                  (int) cfg->group);
728             goto error;
729         }
730         if (chown(cfg->snapshotDir, cfg->user, cfg->group) < 0) {
731             virReportSystemError(errno,
732                                  _("unable to set ownership of '%s' to %d:%d"),
733                                  cfg->snapshotDir, (int) cfg->user,
734                                  (int) cfg->group);
735             goto error;
736         }
737         run_uid = cfg->user;
738         run_gid = cfg->group;
739     }
740
741     qemu_driver->qemuCapsCache = virQEMUCapsCacheNew(cfg->libDir,
742                                                      run_uid,
743                                                      run_gid);
744     if (!qemu_driver->qemuCapsCache)
745         goto error;
746
747     if ((qemu_driver->caps = virQEMUDriverCreateCapabilities(qemu_driver)) == NULL)
748         goto error;
749
750     if (!(qemu_driver->xmlopt = virQEMUDriverCreateXMLConf(qemu_driver)))
751         goto error;
752
753     /* If hugetlbfs is present, then we need to create a sub-directory within
754      * it, since we can't assume the root mount point has permissions that
755      * will let our spawned QEMU instances use it.
756      *
757      * NB the check for '/', since user may config "" to disable hugepages
758      * even when mounted
759      */
760     if (cfg->hugetlbfsMount &&
761         cfg->hugetlbfsMount[0] == '/') {
762         if (virAsprintf(&membase, "%s/libvirt",
763                         cfg->hugetlbfsMount) < 0 ||
764             virAsprintf(&mempath, "%s/qemu", membase) < 0)
765             goto error;
766
767         if (virFileMakePath(mempath) < 0) {
768             virReportSystemError(errno,
769                                  _("unable to create hugepage path %s"), mempath);
770             goto error;
771         }
772         if (cfg->privileged) {
773             if (virFileUpdatePerm(membase, 0, S_IXGRP | S_IXOTH) < 0)
774                 goto error;
775             if (chown(mempath, cfg->user, cfg->group) < 0) {
776                 virReportSystemError(errno,
777                                      _("unable to set ownership on %s to %d:%d"),
778                                      mempath, (int) cfg->user,
779                                      (int) cfg->group);
780                 goto error;
781             }
782         }
783         VIR_FREE(membase);
784
785         cfg->hugepagePath = mempath;
786     }
787
788     if (!(qemu_driver->closeCallbacks = virCloseCallbacksNew()))
789         goto error;
790
791     /* Get all the running persistent or transient configs first */
792     if (virDomainObjListLoadAllConfigs(qemu_driver->domains,
793                                        cfg->stateDir,
794                                        NULL, 1,
795                                        qemu_driver->caps,
796                                        qemu_driver->xmlopt,
797                                        QEMU_EXPECTED_VIRT_TYPES,
798                                        NULL, NULL) < 0)
799         goto error;
800
801     /* find the maximum ID from active and transient configs to initialize
802      * the driver with. This is to avoid race between autostart and reconnect
803      * threads */
804     virDomainObjListForEach(qemu_driver->domains,
805                             qemuDomainFindMaxID,
806                             &qemu_driver->nextvmid);
807
808     virDomainObjListForEach(qemu_driver->domains,
809                             qemuDomainNetsRestart,
810                             NULL);
811
812     conn = virConnectOpen(cfg->uri);
813
814     qemuProcessReconnectAll(conn, qemu_driver);
815
816     /* Then inactive persistent configs */
817     if (virDomainObjListLoadAllConfigs(qemu_driver->domains,
818                                        cfg->configDir,
819                                        cfg->autostartDir, 0,
820                                        qemu_driver->caps,
821                                        qemu_driver->xmlopt,
822                                        QEMU_EXPECTED_VIRT_TYPES,
823                                        NULL, NULL) < 0)
824         goto error;
825
826
827     virDomainObjListForEach(qemu_driver->domains,
828                             qemuDomainSnapshotLoad,
829                             cfg->snapshotDir);
830
831     virDomainObjListForEach(qemu_driver->domains,
832                             qemuDomainManagedSaveLoad,
833                             qemu_driver);
834
835     qemu_driver->workerPool = virThreadPoolNew(0, 1, 0, qemuProcessEventHandler, qemu_driver);
836     if (!qemu_driver->workerPool)
837         goto error;
838
839     if (conn)
840         virConnectClose(conn);
841
842     virNWFilterRegisterCallbackDriver(&qemuCallbackDriver);
843     return 0;
844
845 error:
846     if (conn)
847         virConnectClose(conn);
848     VIR_FREE(driverConf);
849     VIR_FREE(membase);
850     VIR_FREE(mempath);
851     qemuStateCleanup();
852     return -1;
853 }
854
855 /**
856  * qemuStateAutoStart:
857  *
858  * Function to auto start the QEmu daemons
859  */
860 static void
861 qemuStateAutoStart(void)
862 {
863     if (!qemu_driver)
864         return;
865
866     qemuAutostartDomains(qemu_driver);
867 }
868
869 static void qemuNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
870 {
871     virQEMUDriverPtr driver = opaque;
872
873     if (newVM) {
874         virDomainEventPtr event =
875             virDomainEventNewFromObj(vm,
876                                      VIR_DOMAIN_EVENT_DEFINED,
877                                      VIR_DOMAIN_EVENT_DEFINED_ADDED);
878         if (event)
879             qemuDomainEventQueue(driver, event);
880     }
881 }
882
883 /**
884  * qemuStateReload:
885  *
886  * Function to restart the QEmu daemon, it will recheck the configuration
887  * files and update its state and the networking
888  */
889 static int
890 qemuStateReload(void) {
891     virQEMUDriverConfigPtr cfg = NULL;
892     virCapsPtr caps = NULL;
893
894     if (!qemu_driver)
895         return 0;
896
897     if (!(caps = virQEMUDriverGetCapabilities(qemu_driver, false)))
898         goto cleanup;
899
900     cfg = virQEMUDriverGetConfig(qemu_driver);
901     virDomainObjListLoadAllConfigs(qemu_driver->domains,
902                                    cfg->configDir,
903                                    cfg->autostartDir, 0,
904                                    caps, qemu_driver->xmlopt,
905                                    QEMU_EXPECTED_VIRT_TYPES,
906                                    qemuNotifyLoadDomain, qemu_driver);
907 cleanup:
908     virObjectUnref(cfg);
909     virObjectUnref(caps);
910     return 0;
911 }
912
913
914 /*
915  * qemuStateStop:
916  *
917  * Save any VMs in preparation for shutdown
918  *
919  */
920 static int
921 qemuStateStop(void) {
922     int ret = -1;
923     virConnectPtr conn;
924     int numDomains = 0;
925     size_t i;
926     int state;
927     virDomainPtr *domains = NULL;
928     unsigned int *flags = NULL;
929     virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(qemu_driver);
930
931     if (!(conn = virConnectOpen(cfg->uri)))
932         goto cleanup;
933
934     if ((numDomains = virConnectListAllDomains(conn,
935                                                &domains,
936                                                VIR_CONNECT_LIST_DOMAINS_ACTIVE)) < 0)
937         goto cleanup;
938
939     if (VIR_ALLOC_N(flags, numDomains) < 0)
940         goto cleanup;
941
942     /* First we pause all VMs to make them stop dirtying
943        pages, etc. We remember if any VMs were paused so
944        we can restore that on resume. */
945     for (i = 0; i < numDomains; i++) {
946         flags[i] = VIR_DOMAIN_SAVE_RUNNING;
947         if (virDomainGetState(domains[i], &state, NULL, 0) == 0) {
948             if (state == VIR_DOMAIN_PAUSED) {
949                 flags[i] = VIR_DOMAIN_SAVE_PAUSED;
950             }
951         }
952         virDomainSuspend(domains[i]);
953     }
954
955     ret = 0;
956     /* Then we save the VMs to disk */
957     for (i = 0; i < numDomains; i++)
958         if (virDomainManagedSave(domains[i], flags[i]) < 0)
959             ret = -1;
960
961  cleanup:
962     for (i = 0; i < numDomains; i++)
963         virDomainFree(domains[i]);
964     VIR_FREE(domains);
965     VIR_FREE(flags);
966     if (conn)
967         virConnectClose(conn);
968     virObjectUnref(cfg);
969
970     return ret;
971 }
972
973 /**
974  * qemuStateCleanup:
975  *
976  * Shutdown the QEmu daemon, it will stop all active domains and networks
977  */
978 static int
979 qemuStateCleanup(void) {
980     if (!qemu_driver)
981         return -1;
982
983     virNWFilterUnRegisterCallbackDriver(&qemuCallbackDriver);
984     virObjectUnref(qemu_driver->config);
985     virObjectUnref(qemu_driver->activePciHostdevs);
986     virObjectUnref(qemu_driver->inactivePciHostdevs);
987     virObjectUnref(qemu_driver->activeUsbHostdevs);
988     virHashFree(qemu_driver->sharedDevices);
989     virObjectUnref(qemu_driver->caps);
990     virQEMUCapsCacheFree(qemu_driver->qemuCapsCache);
991
992     virObjectUnref(qemu_driver->domains);
993     virObjectUnref(qemu_driver->remotePorts);
994
995     virObjectUnref(qemu_driver->xmlopt);
996
997     virSysinfoDefFree(qemu_driver->hostsysinfo);
998
999     virObjectUnref(qemu_driver->closeCallbacks);
1000
1001     VIR_FREE(qemu_driver->qemuImgBinary);
1002
1003     virObjectUnref(qemu_driver->securityManager);
1004
1005     ebtablesContextFree(qemu_driver->ebtables);
1006
1007     /* Free domain callback list */
1008     virDomainEventStateFree(qemu_driver->domainEventState);
1009
1010     virLockManagerPluginUnref(qemu_driver->lockManager);
1011
1012     virMutexDestroy(&qemu_driver->lock);
1013     virThreadPoolFree(qemu_driver->workerPool);
1014     VIR_FREE(qemu_driver);
1015
1016     return 0;
1017 }
1018
1019
1020 static virDrvOpenStatus qemuConnectOpen(virConnectPtr conn,
1021                                         virConnectAuthPtr auth ATTRIBUTE_UNUSED,
1022                                         unsigned int flags)
1023 {
1024     virQEMUDriverConfigPtr cfg = NULL;
1025     virDrvOpenStatus ret = VIR_DRV_OPEN_ERROR;
1026     virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);
1027
1028     if (conn->uri == NULL) {
1029         if (qemu_driver == NULL) {
1030             ret = VIR_DRV_OPEN_DECLINED;
1031             goto cleanup;
1032         }
1033
1034         cfg = virQEMUDriverGetConfig(qemu_driver);
1035
1036         if (!(conn->uri = virURIParse(cfg->uri)))
1037             goto cleanup;
1038     } else {
1039         /* If URI isn't 'qemu' its definitely not for us */
1040         if (conn->uri->scheme == NULL ||
1041             STRNEQ(conn->uri->scheme, "qemu")) {
1042             ret = VIR_DRV_OPEN_DECLINED;
1043             goto cleanup;
1044         }
1045
1046         /* Allow remote driver to deal with URIs with hostname server */
1047         if (conn->uri->server != NULL) {
1048             ret = VIR_DRV_OPEN_DECLINED;
1049             goto cleanup;
1050         }
1051
1052         if (qemu_driver == NULL) {
1053             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1054                            _("qemu state driver is not active"));
1055             goto cleanup;
1056         }
1057
1058         cfg = virQEMUDriverGetConfig(qemu_driver);
1059         if (conn->uri->path == NULL) {
1060             virReportError(VIR_ERR_INTERNAL_ERROR,
1061                            _("no QEMU URI path given, try %s"),
1062                            cfg->uri);
1063             goto cleanup;
1064         }
1065
1066         if (cfg->privileged) {
1067             if (STRNEQ(conn->uri->path, "/system") &&
1068                 STRNEQ(conn->uri->path, "/session")) {
1069                 virReportError(VIR_ERR_INTERNAL_ERROR,
1070                                _("unexpected QEMU URI path '%s', try qemu:///system"),
1071                                conn->uri->path);
1072                 goto cleanup;
1073             }
1074         } else {
1075             if (STRNEQ(conn->uri->path, "/session")) {
1076                 virReportError(VIR_ERR_INTERNAL_ERROR,
1077                                _("unexpected QEMU URI path '%s', try qemu:///session"),
1078                                conn->uri->path);
1079                 goto cleanup;
1080             }
1081         }
1082     }
1083
1084     if (virConnectOpenEnsureACL(conn) < 0)
1085         goto cleanup;
1086
1087     conn->privateData = qemu_driver;
1088
1089     ret = VIR_DRV_OPEN_SUCCESS;
1090 cleanup:
1091     virObjectUnref(cfg);
1092     return ret;
1093 }
1094
1095 static int qemuConnectClose(virConnectPtr conn)
1096 {
1097     virQEMUDriverPtr driver = conn->privateData;
1098
1099     /* Get rid of callbacks registered for this conn */
1100     virCloseCallbacksRun(driver->closeCallbacks, conn, driver->domains, driver);
1101
1102     conn->privateData = NULL;
1103
1104     return 0;
1105 }
1106
1107 /* Which features are supported by this driver? */
1108 static int
1109 qemuConnectSupportsFeature(virConnectPtr conn, int feature)
1110 {
1111     if (virConnectSupportsFeatureEnsureACL(conn) < 0)
1112         return -1;
1113
1114     switch (feature) {
1115     case VIR_DRV_FEATURE_MIGRATION_V2:
1116     case VIR_DRV_FEATURE_MIGRATION_V3:
1117     case VIR_DRV_FEATURE_MIGRATION_P2P:
1118     case VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION:
1119     case VIR_DRV_FEATURE_FD_PASSING:
1120     case VIR_DRV_FEATURE_TYPED_PARAM_STRING:
1121     case VIR_DRV_FEATURE_XML_MIGRATABLE:
1122     case VIR_DRV_FEATURE_MIGRATION_OFFLINE:
1123     case VIR_DRV_FEATURE_MIGRATION_PARAMS:
1124         return 1;
1125     default:
1126         return 0;
1127     }
1128 }
1129
1130 static const char *qemuConnectGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
1131     if (virConnectGetTypeEnsureACL(conn) < 0)
1132         return NULL;
1133
1134     return "QEMU";
1135 }
1136
1137
1138 static int qemuConnectIsSecure(virConnectPtr conn ATTRIBUTE_UNUSED)
1139 {
1140     /* Trivially secure, since always inside the daemon */
1141     return 1;
1142 }
1143
1144 static int qemuConnectIsEncrypted(virConnectPtr conn ATTRIBUTE_UNUSED)
1145 {
1146     /* Not encrypted, but remote driver takes care of that */
1147     return 0;
1148 }
1149
1150 static int qemuConnectIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
1151 {
1152     return 1;
1153 }
1154
1155
1156 static int
1157 kvmGetMaxVCPUs(void) {
1158     int fd;
1159     int ret;
1160
1161     if ((fd = open(KVM_DEVICE, O_RDONLY)) < 0) {
1162         virReportSystemError(errno, _("Unable to open %s"), KVM_DEVICE);
1163         return -1;
1164     }
1165
1166 #ifdef KVM_CAP_MAX_VCPUS
1167     /* at first try KVM_CAP_MAX_VCPUS to determine the maximum count */
1168     if ((ret = ioctl(fd, KVM_CHECK_EXTENSION, KVM_CAP_MAX_VCPUS)) > 0)
1169         goto cleanup;
1170 #endif /* KVM_CAP_MAX_VCPUS */
1171
1172     /* as a fallback get KVM_CAP_NR_VCPUS (the recommended maximum number of
1173      * vcpus). Note that on most machines this is set to 160. */
1174     if ((ret = ioctl(fd, KVM_CHECK_EXTENSION, KVM_CAP_NR_VCPUS)) > 0)
1175         goto cleanup;
1176
1177     /* if KVM_CAP_NR_VCPUS doesn't exist either, kernel documentation states
1178      * that 4 should be used as the maximum number of cpus */
1179     ret = 4;
1180
1181 cleanup:
1182     VIR_FORCE_CLOSE(fd);
1183     return ret;
1184 }
1185
1186
1187 static char *
1188 qemuConnectGetSysinfo(virConnectPtr conn, unsigned int flags)
1189 {
1190     virQEMUDriverPtr driver = conn->privateData;
1191     virBuffer buf = VIR_BUFFER_INITIALIZER;
1192
1193     virCheckFlags(0, NULL);
1194
1195     if (virConnectGetSysinfoEnsureACL(conn) < 0)
1196         return NULL;
1197
1198     if (!driver->hostsysinfo) {
1199         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1200                        _("Host SMBIOS information is not available"));
1201         return NULL;
1202     }
1203
1204     if (virSysinfoFormat(&buf, driver->hostsysinfo) < 0)
1205         return NULL;
1206     if (virBufferError(&buf)) {
1207         virReportOOMError();
1208         return NULL;
1209     }
1210     return virBufferContentAndReset(&buf);
1211 }
1212
1213 static int qemuConnectGetMaxVcpus(virConnectPtr conn ATTRIBUTE_UNUSED, const char *type) {
1214     if (virConnectGetMaxVcpusEnsureACL(conn) < 0)
1215         return -1;
1216
1217     if (!type)
1218         return 16;
1219
1220     if (STRCASEEQ(type, "qemu"))
1221         return 16;
1222
1223     if (STRCASEEQ(type, "kvm"))
1224         return kvmGetMaxVCPUs();
1225
1226     if (STRCASEEQ(type, "kqemu"))
1227         return 1;
1228
1229     virReportError(VIR_ERR_INVALID_ARG,
1230                    _("unknown type '%s'"), type);
1231     return -1;
1232 }
1233
1234
1235 static char *qemuConnectGetCapabilities(virConnectPtr conn) {
1236     virQEMUDriverPtr driver = conn->privateData;
1237     virCapsPtr caps = NULL;
1238     char *xml = NULL;
1239
1240     if (virConnectGetCapabilitiesEnsureACL(conn) < 0)
1241         return NULL;
1242
1243     if (!(caps = virQEMUDriverGetCapabilities(driver, true)))
1244         goto cleanup;
1245
1246     if ((xml = virCapabilitiesFormatXML(caps)) == NULL)
1247         virReportOOMError();
1248     virObjectUnref(caps);
1249
1250 cleanup:
1251
1252     return xml;
1253 }
1254
1255
1256 static int
1257 qemuGetProcessInfo(unsigned long long *cpuTime, int *lastCpu, long *vm_rss,
1258                    pid_t pid, int tid)
1259 {
1260     char *proc;
1261     FILE *pidinfo;
1262     unsigned long long usertime, systime;
1263     long rss;
1264     int cpu;
1265     int ret;
1266
1267     /* In general, we cannot assume pid_t fits in int; but /proc parsing
1268      * is specific to Linux where int works fine.  */
1269     if (tid)
1270         ret = virAsprintf(&proc, "/proc/%d/task/%d/stat", (int) pid, tid);
1271     else
1272         ret = virAsprintf(&proc, "/proc/%d/stat", (int) pid);
1273     if (ret < 0)
1274         return -1;
1275
1276     if (!(pidinfo = fopen(proc, "r"))) {
1277         /* VM probably shut down, so fake 0 */
1278         if (cpuTime)
1279             *cpuTime = 0;
1280         if (lastCpu)
1281             *lastCpu = 0;
1282         if (vm_rss)
1283             *vm_rss = 0;
1284         VIR_FREE(proc);
1285         return 0;
1286     }
1287     VIR_FREE(proc);
1288
1289     /* See 'man proc' for information about what all these fields are. We're
1290      * only interested in a very few of them */
1291     if (fscanf(pidinfo,
1292                /* pid -> stime */
1293                "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %llu %llu"
1294                /* cutime -> endcode */
1295                "%*d %*d %*d %*d %*d %*d %*u %*u %ld %*u %*u %*u"
1296                /* startstack -> processor */
1297                "%*u %*u %*u %*u %*u %*u %*u %*u %*u %*u %*d %d",
1298                &usertime, &systime, &rss, &cpu) != 4) {
1299         VIR_FORCE_FCLOSE(pidinfo);
1300         VIR_WARN("cannot parse process status data");
1301         errno = -EINVAL;
1302         return -1;
1303     }
1304
1305     /* We got jiffies
1306      * We want nanoseconds
1307      * _SC_CLK_TCK is jiffies per second
1308      * So calulate thus....
1309      */
1310     if (cpuTime)
1311         *cpuTime = 1000ull * 1000ull * 1000ull * (usertime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK);
1312     if (lastCpu)
1313         *lastCpu = cpu;
1314
1315     /* We got pages
1316      * We want kiloBytes
1317      * _SC_PAGESIZE is page size in Bytes
1318      * So calculate, but first lower the pagesize so we don't get overflow */
1319     if (vm_rss)
1320         *vm_rss = rss * (sysconf(_SC_PAGESIZE) >> 10);
1321
1322
1323     VIR_DEBUG("Got status for %d/%d user=%llu sys=%llu cpu=%d rss=%ld",
1324               (int) pid, tid, usertime, systime, cpu, rss);
1325
1326     VIR_FORCE_FCLOSE(pidinfo);
1327
1328     return 0;
1329 }
1330
1331
1332 static virDomainPtr qemuDomainLookupByID(virConnectPtr conn,
1333                                          int id) {
1334     virQEMUDriverPtr driver = conn->privateData;
1335     virDomainObjPtr vm;
1336     virDomainPtr dom = NULL;
1337
1338     vm  = virDomainObjListFindByID(driver->domains, id);
1339
1340     if (!vm) {
1341         virReportError(VIR_ERR_NO_DOMAIN,
1342                        _("no domain with matching id %d"), id);
1343         goto cleanup;
1344     }
1345
1346     if (virDomainLookupByIDEnsureACL(conn, vm->def) < 0)
1347         goto cleanup;
1348
1349     dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1350     if (dom) dom->id = vm->def->id;
1351
1352 cleanup:
1353     if (vm)
1354         virObjectUnlock(vm);
1355     return dom;
1356 }
1357
1358 static virDomainPtr qemuDomainLookupByUUID(virConnectPtr conn,
1359                                            const unsigned char *uuid) {
1360     virQEMUDriverPtr driver = conn->privateData;
1361     virDomainObjPtr vm;
1362     virDomainPtr dom = NULL;
1363
1364     vm = virDomainObjListFindByUUID(driver->domains, uuid);
1365
1366     if (!vm) {
1367         char uuidstr[VIR_UUID_STRING_BUFLEN];
1368         virUUIDFormat(uuid, uuidstr);
1369         virReportError(VIR_ERR_NO_DOMAIN,
1370                        _("no domain with matching uuid '%s'"), uuidstr);
1371         goto cleanup;
1372     }
1373
1374     if (virDomainLookupByUUIDEnsureACL(conn, vm->def) < 0)
1375         goto cleanup;
1376
1377     dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1378     if (dom) dom->id = vm->def->id;
1379
1380 cleanup:
1381     if (vm)
1382         virObjectUnlock(vm);
1383     return dom;
1384 }
1385
1386 static virDomainPtr qemuDomainLookupByName(virConnectPtr conn,
1387                                            const char *name) {
1388     virQEMUDriverPtr driver = conn->privateData;
1389     virDomainObjPtr vm;
1390     virDomainPtr dom = NULL;
1391
1392     vm = virDomainObjListFindByName(driver->domains, name);
1393
1394     if (!vm) {
1395         virReportError(VIR_ERR_NO_DOMAIN,
1396                        _("no domain with matching name '%s'"), name);
1397         goto cleanup;
1398     }
1399
1400     if (virDomainLookupByNameEnsureACL(conn, vm->def) < 0)
1401         goto cleanup;
1402
1403     dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1404     if (dom) dom->id = vm->def->id;
1405
1406 cleanup:
1407     if (vm)
1408         virObjectUnlock(vm);
1409     return dom;
1410 }
1411
1412
1413 static int qemuDomainIsActive(virDomainPtr dom)
1414 {
1415     virDomainObjPtr obj;
1416     int ret = -1;
1417
1418     if (!(obj = qemuDomObjFromDomain(dom)))
1419         goto cleanup;
1420
1421     if (virDomainIsActiveEnsureACL(dom->conn, obj->def) < 0)
1422         goto cleanup;
1423
1424     ret = virDomainObjIsActive(obj);
1425
1426 cleanup:
1427     if (obj)
1428         virObjectUnlock(obj);
1429     return ret;
1430 }
1431
1432 static int qemuDomainIsPersistent(virDomainPtr dom)
1433 {
1434     virDomainObjPtr obj;
1435     int ret = -1;
1436
1437     if (!(obj = qemuDomObjFromDomain(dom)))
1438         goto cleanup;
1439
1440     if (virDomainIsPersistentEnsureACL(dom->conn, obj->def) < 0)
1441         goto cleanup;
1442
1443     ret = obj->persistent;
1444
1445 cleanup:
1446     if (obj)
1447         virObjectUnlock(obj);
1448     return ret;
1449 }
1450
1451 static int qemuDomainIsUpdated(virDomainPtr dom)
1452 {
1453     virDomainObjPtr obj;
1454     int ret = -1;
1455
1456     if (!(obj = qemuDomObjFromDomain(dom)))
1457         goto cleanup;
1458
1459     if (virDomainIsUpdatedEnsureACL(dom->conn, obj->def) < 0)
1460         goto cleanup;
1461
1462     ret = obj->updated;
1463
1464 cleanup:
1465     if (obj)
1466         virObjectUnlock(obj);
1467     return ret;
1468 }
1469
1470 static int qemuConnectGetVersion(virConnectPtr conn, unsigned long *version) {
1471     virQEMUDriverPtr driver = conn->privateData;
1472     int ret = -1;
1473     unsigned int qemuVersion = 0;
1474     virCapsPtr caps = NULL;
1475
1476     if (virConnectGetVersionEnsureACL(conn) < 0)
1477         return -1;
1478
1479     if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
1480         goto cleanup;
1481
1482     if (virQEMUCapsGetDefaultVersion(caps,
1483                                      driver->qemuCapsCache,
1484                                      &qemuVersion) < 0)
1485         goto cleanup;
1486
1487     *version = qemuVersion;
1488     ret = 0;
1489
1490 cleanup:
1491     virObjectUnref(caps);
1492     return ret;
1493 }
1494
1495
1496 static char *qemuConnectGetHostname(virConnectPtr conn)
1497 {
1498     if (virConnectGetHostnameEnsureACL(conn) < 0)
1499         return NULL;
1500
1501     return virGetHostname();
1502 }
1503
1504
1505 static int qemuConnectListDomains(virConnectPtr conn, int *ids, int nids) {
1506     virQEMUDriverPtr driver = conn->privateData;
1507     int n;
1508
1509     if (virConnectListDomainsEnsureACL(conn) < 0)
1510         return -1;
1511
1512     n = virDomainObjListGetActiveIDs(driver->domains, ids, nids,
1513                                      virConnectListDomainsCheckACL, conn);
1514
1515     return n;
1516 }
1517
1518 static int qemuConnectNumOfDomains(virConnectPtr conn) {
1519     virQEMUDriverPtr driver = conn->privateData;
1520     int n;
1521
1522     if (virConnectNumOfDomainsEnsureACL(conn) < 0)
1523         return -1;
1524
1525     n = virDomainObjListNumOfDomains(driver->domains, true,
1526                                      virConnectNumOfDomainsCheckACL, conn);
1527
1528     return n;
1529 }
1530
1531
1532 static int
1533 qemuCanonicalizeMachine(virDomainDefPtr def, virQEMUCapsPtr qemuCaps)
1534 {
1535     const char *canon;
1536
1537     if (!(canon = virQEMUCapsGetCanonicalMachine(qemuCaps, def->os.machine)))
1538         return 0;
1539
1540     if (STRNEQ(canon, def->os.machine)) {
1541         char *tmp;
1542         if (VIR_STRDUP(tmp, canon) < 0)
1543             return -1;
1544         VIR_FREE(def->os.machine);
1545         def->os.machine = tmp;
1546     }
1547
1548     return 0;
1549 }
1550
1551
1552 static virDomainPtr qemuDomainCreateXML(virConnectPtr conn,
1553                                         const char *xml,
1554                                         unsigned int flags) {
1555     virQEMUDriverPtr driver = conn->privateData;
1556     virDomainDefPtr def = NULL;
1557     virDomainObjPtr vm = NULL;
1558     virDomainPtr dom = NULL;
1559     virDomainEventPtr event = NULL;
1560     virDomainEventPtr event2 = NULL;
1561     unsigned int start_flags = VIR_QEMU_PROCESS_START_COLD;
1562     virQEMUCapsPtr qemuCaps = NULL;
1563     virCapsPtr caps = NULL;
1564
1565     virCheckFlags(VIR_DOMAIN_START_PAUSED |
1566                   VIR_DOMAIN_START_AUTODESTROY, NULL);
1567
1568     if (flags & VIR_DOMAIN_START_PAUSED)
1569         start_flags |= VIR_QEMU_PROCESS_START_PAUSED;
1570     if (flags & VIR_DOMAIN_START_AUTODESTROY)
1571         start_flags |= VIR_QEMU_PROCESS_START_AUTODESTROY;
1572
1573     virNWFilterReadLockFilterUpdates();
1574
1575     if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
1576         goto cleanup;
1577
1578     if (!(def = virDomainDefParseString(xml, caps, driver->xmlopt,
1579                                         QEMU_EXPECTED_VIRT_TYPES,
1580                                         VIR_DOMAIN_XML_INACTIVE)))
1581         goto cleanup;
1582
1583     if (virDomainCreateXMLEnsureACL(conn, def) < 0)
1584         goto cleanup;
1585
1586     if (virSecurityManagerVerify(driver->securityManager, def) < 0)
1587         goto cleanup;
1588
1589     if (!(qemuCaps = virQEMUCapsCacheLookup(driver->qemuCapsCache, def->emulator)))
1590         goto cleanup;
1591
1592     if (qemuCanonicalizeMachine(def, qemuCaps) < 0)
1593         goto cleanup;
1594
1595     if (qemuDomainAssignAddresses(def, qemuCaps, NULL) < 0)
1596         goto cleanup;
1597
1598     if (!(vm = virDomainObjListAdd(driver->domains, def,
1599                                    driver->xmlopt,
1600                                    VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
1601                                    NULL)))
1602         goto cleanup;
1603
1604     def = NULL;
1605
1606     if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
1607         goto cleanup; /* XXXX free the 'vm' we created ? */
1608
1609     if (qemuProcessStart(conn, driver, vm, NULL, -1, NULL, NULL,
1610                          VIR_NETDEV_VPORT_PROFILE_OP_CREATE,
1611                          start_flags) < 0) {
1612         virDomainAuditStart(vm, "booted", false);
1613         if (qemuDomainObjEndJob(driver, vm) > 0)
1614             qemuDomainRemoveInactive(driver, vm);
1615         vm = NULL;
1616         goto cleanup;
1617     }
1618
1619     event = virDomainEventNewFromObj(vm,
1620                                      VIR_DOMAIN_EVENT_STARTED,
1621                                      VIR_DOMAIN_EVENT_STARTED_BOOTED);
1622     if (event && (flags & VIR_DOMAIN_START_PAUSED)) {
1623         /* There are two classes of event-watching clients - those
1624          * that only care about on/off (and must see a started event
1625          * no matter what, but don't care about suspend events), and
1626          * those that also care about running/paused.  To satisfy both
1627          * client types, we have to send two events.  */
1628         event2 = virDomainEventNewFromObj(vm,
1629                                           VIR_DOMAIN_EVENT_SUSPENDED,
1630                                           VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
1631     }
1632     virDomainAuditStart(vm, "booted", true);
1633
1634     dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1635     if (dom) dom->id = vm->def->id;
1636
1637     if (vm &&
1638         qemuDomainObjEndJob(driver, vm) == 0)
1639         vm = NULL;
1640
1641 cleanup:
1642     virDomainDefFree(def);
1643     if (vm)
1644         virObjectUnlock(vm);
1645     if (event) {
1646         qemuDomainEventQueue(driver, event);
1647         if (event2)
1648             qemuDomainEventQueue(driver, event2);
1649     }
1650     virObjectUnref(caps);
1651     virObjectUnref(qemuCaps);
1652     virNWFilterUnlockFilterUpdates();
1653     return dom;
1654 }
1655
1656
1657 static int qemuDomainSuspend(virDomainPtr dom) {
1658     virQEMUDriverPtr driver = dom->conn->privateData;
1659     virDomainObjPtr vm;
1660     int ret = -1;
1661     virDomainEventPtr event = NULL;
1662     qemuDomainObjPrivatePtr priv;
1663     virDomainPausedReason reason;
1664     int eventDetail;
1665     int state;
1666     virQEMUDriverConfigPtr cfg = NULL;
1667
1668     if (!(vm = qemuDomObjFromDomain(dom)))
1669         return -1;
1670
1671     if (virDomainSuspendEnsureACL(dom->conn, vm->def) < 0)
1672         goto cleanup;
1673
1674     if (!virDomainObjIsActive(vm)) {
1675         virReportError(VIR_ERR_OPERATION_INVALID,
1676                        "%s", _("domain is not running"));
1677         goto cleanup;
1678     }
1679
1680     cfg = virQEMUDriverGetConfig(driver);
1681     priv = vm->privateData;
1682
1683     if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_SUSPEND) < 0)
1684         goto cleanup;
1685
1686     if (!virDomainObjIsActive(vm)) {
1687         virReportError(VIR_ERR_OPERATION_INVALID,
1688                        "%s", _("domain is not running"));
1689         goto endjob;
1690     }
1691
1692     if (priv->job.asyncJob == QEMU_ASYNC_JOB_MIGRATION_OUT) {
1693         reason = VIR_DOMAIN_PAUSED_MIGRATION;
1694         eventDetail = VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED;
1695     } else if (priv->job.asyncJob == QEMU_ASYNC_JOB_SNAPSHOT) {
1696         reason = VIR_DOMAIN_PAUSED_SNAPSHOT;
1697         eventDetail = -1; /* don't create lifecycle events when doing snapshot */
1698     } else {
1699         reason = VIR_DOMAIN_PAUSED_USER;
1700         eventDetail = VIR_DOMAIN_EVENT_SUSPENDED_PAUSED;
1701     }
1702
1703     state = virDomainObjGetState(vm, NULL);
1704     if (state == VIR_DOMAIN_PMSUSPENDED) {
1705         virReportError(VIR_ERR_OPERATION_INVALID,
1706                        "%s", _("domain is pmsuspended"));
1707         goto endjob;
1708     } else if (state != VIR_DOMAIN_PAUSED) {
1709         if (qemuProcessStopCPUs(driver, vm, reason, QEMU_ASYNC_JOB_NONE) < 0) {
1710             goto endjob;
1711         }
1712
1713         if (eventDetail >= 0) {
1714             event = virDomainEventNewFromObj(vm,
1715                                              VIR_DOMAIN_EVENT_SUSPENDED,
1716                                              eventDetail);
1717         }
1718     }
1719     if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
1720         goto endjob;
1721     ret = 0;
1722
1723 endjob:
1724     if (qemuDomainObjEndJob(driver, vm) == 0)
1725         vm = NULL;
1726
1727 cleanup:
1728     if (vm)
1729         virObjectUnlock(vm);
1730
1731     if (event)
1732         qemuDomainEventQueue(driver, event);
1733     virObjectUnref(cfg);
1734     return ret;
1735 }
1736
1737
1738 static int qemuDomainResume(virDomainPtr dom) {
1739     virQEMUDriverPtr driver = dom->conn->privateData;
1740     virDomainObjPtr vm;
1741     int ret = -1;
1742     virDomainEventPtr event = NULL;
1743     int state;
1744     virQEMUDriverConfigPtr cfg = NULL;
1745     virCapsPtr caps = NULL;
1746
1747     if (!(vm = qemuDomObjFromDomain(dom)))
1748         return -1;
1749
1750     cfg = virQEMUDriverGetConfig(driver);
1751
1752     if (virDomainResumeEnsureACL(dom->conn, vm->def) < 0)
1753         goto cleanup;
1754
1755     if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
1756         goto cleanup;
1757
1758     if (!virDomainObjIsActive(vm)) {
1759         virReportError(VIR_ERR_OPERATION_INVALID,
1760                        "%s", _("domain is not running"));
1761         goto endjob;
1762     }
1763
1764     state = virDomainObjGetState(vm, NULL);
1765     if (state == VIR_DOMAIN_PMSUSPENDED) {
1766         virReportError(VIR_ERR_OPERATION_INVALID,
1767                        "%s", _("domain is pmsuspended"));
1768         goto endjob;
1769     } else if (state == VIR_DOMAIN_PAUSED) {
1770         if (qemuProcessStartCPUs(driver, vm, dom->conn,
1771                                  VIR_DOMAIN_RUNNING_UNPAUSED,
1772                                  QEMU_ASYNC_JOB_NONE) < 0) {
1773             if (virGetLastError() == NULL)
1774                 virReportError(VIR_ERR_OPERATION_FAILED,
1775                                "%s", _("resume operation failed"));
1776             goto endjob;
1777         }
1778         event = virDomainEventNewFromObj(vm,
1779                                          VIR_DOMAIN_EVENT_RESUMED,
1780                                          VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
1781     }
1782     if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
1783         goto endjob;
1784     if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
1785         goto endjob;
1786     ret = 0;
1787
1788 endjob:
1789     if (qemuDomainObjEndJob(driver, vm) == 0)
1790         vm = NULL;
1791
1792 cleanup:
1793     if (vm)
1794         virObjectUnlock(vm);
1795     if (event)
1796         qemuDomainEventQueue(driver, event);
1797     virObjectUnref(caps);
1798     virObjectUnref(cfg);
1799     return ret;
1800 }
1801
1802 static int qemuDomainShutdownFlags(virDomainPtr dom, unsigned int flags) {
1803     virQEMUDriverPtr driver = dom->conn->privateData;
1804     virDomainObjPtr vm;
1805     int ret = -1;
1806     qemuDomainObjPrivatePtr priv;
1807     bool useAgent = false, agentRequested, acpiRequested;
1808     bool isReboot = false;
1809     int agentFlag = QEMU_AGENT_SHUTDOWN_POWERDOWN;
1810
1811     virCheckFlags(VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN |
1812                   VIR_DOMAIN_SHUTDOWN_GUEST_AGENT, -1);
1813
1814     if (!(vm = qemuDomObjFromDomain(dom)))
1815         goto cleanup;
1816
1817     if (vm->def->onPoweroff == VIR_DOMAIN_LIFECYCLE_RESTART ||
1818         vm->def->onPoweroff == VIR_DOMAIN_LIFECYCLE_RESTART_RENAME) {
1819         isReboot = true;
1820         agentFlag = QEMU_AGENT_SHUTDOWN_REBOOT;
1821         VIR_INFO("Domain on_poweroff setting overridden, attempting reboot");
1822     }
1823
1824     priv = vm->privateData;
1825     agentRequested = flags & VIR_DOMAIN_SHUTDOWN_GUEST_AGENT;
1826     acpiRequested  = flags & VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN;
1827
1828     /* Prefer agent unless we were requested to not to. */
1829     if (agentRequested || (!flags && priv->agent))
1830         useAgent = true;
1831
1832     if (virDomainShutdownFlagsEnsureACL(dom->conn, vm->def) < 0)
1833         goto cleanup;
1834
1835     if (priv->agentError) {
1836         if (agentRequested && !acpiRequested) {
1837             virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
1838                            _("QEMU guest agent is not "
1839                              "available due to an error"));
1840             goto cleanup;
1841         } else {
1842             useAgent = false;
1843         }
1844     }
1845
1846     if (!priv->agent) {
1847         if (agentRequested && !acpiRequested) {
1848             virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
1849                            _("QEMU guest agent is not configured"));
1850             goto cleanup;
1851         } else {
1852             useAgent = false;
1853         }
1854     }
1855
1856     if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
1857         goto cleanup;
1858
1859     if (!virDomainObjIsActive(vm)) {
1860         virReportError(VIR_ERR_OPERATION_INVALID,
1861                        "%s", _("domain is not running"));
1862         goto endjob;
1863     }
1864
1865     if (useAgent) {
1866         qemuDomainObjEnterAgent(vm);
1867         ret = qemuAgentShutdown(priv->agent, agentFlag);
1868         qemuDomainObjExitAgent(vm);
1869     }
1870
1871     /* If we are not enforced to use just an agent, try ACPI
1872      * shutdown as well in case agent did not succeed.
1873      */
1874     if (!useAgent ||
1875         (ret < 0 && (acpiRequested || !flags))) {
1876         qemuDomainSetFakeReboot(driver, vm, isReboot);
1877
1878         qemuDomainObjEnterMonitor(driver, vm);
1879         ret = qemuMonitorSystemPowerdown(priv->mon);
1880         qemuDomainObjExitMonitor(driver, vm);
1881     }
1882
1883 endjob:
1884     if (qemuDomainObjEndJob(driver, vm) == 0)
1885         vm = NULL;
1886
1887 cleanup:
1888     if (vm)
1889         virObjectUnlock(vm);
1890     return ret;
1891 }
1892
1893 static int qemuDomainShutdown(virDomainPtr dom)
1894 {
1895     return qemuDomainShutdownFlags(dom, 0);
1896 }
1897
1898
1899 static int
1900 qemuDomainReboot(virDomainPtr dom, unsigned int flags)
1901 {
1902     virQEMUDriverPtr driver = dom->conn->privateData;
1903     virDomainObjPtr vm;
1904     int ret = -1;
1905     qemuDomainObjPrivatePtr priv;
1906     bool useAgent = false;
1907     bool isReboot = true;
1908     int agentFlag = QEMU_AGENT_SHUTDOWN_REBOOT;
1909
1910     virCheckFlags(VIR_DOMAIN_REBOOT_ACPI_POWER_BTN |
1911                   VIR_DOMAIN_REBOOT_GUEST_AGENT , -1);
1912
1913     /* At most one of these two flags should be set.  */
1914     if ((flags & VIR_DOMAIN_REBOOT_ACPI_POWER_BTN) &&
1915         (flags & VIR_DOMAIN_REBOOT_GUEST_AGENT)) {
1916         virReportInvalidArg(flags, "%s",
1917                             _("flags for acpi power button and guest agent are mutually exclusive"));
1918         return -1;
1919     }
1920
1921     if (!(vm = qemuDomObjFromDomain(dom)))
1922         goto cleanup;
1923
1924     if (vm->def->onReboot == VIR_DOMAIN_LIFECYCLE_DESTROY ||
1925         vm->def->onReboot == VIR_DOMAIN_LIFECYCLE_PRESERVE) {
1926         agentFlag = QEMU_AGENT_SHUTDOWN_POWERDOWN;
1927         isReboot = false;
1928         VIR_INFO("Domain on_reboot setting overridden, shutting down");
1929     }
1930
1931     priv = vm->privateData;
1932
1933     if (virDomainRebootEnsureACL(dom->conn, vm->def) < 0)
1934         goto cleanup;
1935
1936     if ((flags & VIR_DOMAIN_REBOOT_GUEST_AGENT) ||
1937         (!(flags & VIR_DOMAIN_REBOOT_ACPI_POWER_BTN) &&
1938          priv->agent))
1939         useAgent = true;
1940
1941     if (useAgent) {
1942         if (priv->agentError) {
1943             virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
1944                            _("QEMU guest agent is not "
1945                              "available due to an error"));
1946             goto cleanup;
1947         }
1948         if (!priv->agent) {
1949             virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
1950                            _("QEMU guest agent is not configured"));
1951             goto cleanup;
1952         }
1953     } else {
1954 #if WITH_YAJL
1955         if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_MONITOR_JSON)) {
1956             if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_NO_SHUTDOWN)) {
1957                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1958                                _("Reboot is not supported with this QEMU binary"));
1959                 goto cleanup;
1960             }
1961         } else {
1962 #endif
1963             virReportError(VIR_ERR_OPERATION_INVALID, "%s",
1964                            _("Reboot is not supported without the JSON monitor"));
1965             goto cleanup;
1966 #if WITH_YAJL
1967         }
1968 #endif
1969     }
1970
1971     if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
1972         goto cleanup;
1973
1974     if (!virDomainObjIsActive(vm)) {
1975         virReportError(VIR_ERR_OPERATION_INVALID,
1976                        "%s", _("domain is not running"));
1977         goto endjob;
1978     }
1979
1980     if (useAgent) {
1981         qemuDomainObjEnterAgent(vm);
1982         ret = qemuAgentShutdown(priv->agent, agentFlag);
1983         qemuDomainObjExitAgent(vm);
1984     } else {
1985         qemuDomainObjEnterMonitor(driver, vm);
1986         ret = qemuMonitorSystemPowerdown(priv->mon);
1987         qemuDomainObjExitMonitor(driver, vm);
1988
1989         if (ret == 0)
1990             qemuDomainSetFakeReboot(driver, vm, isReboot);
1991     }
1992
1993 endjob:
1994     if (qemuDomainObjEndJob(driver, vm) == 0)
1995         vm = NULL;
1996
1997 cleanup:
1998     if (vm)
1999         virObjectUnlock(vm);
2000     return ret;
2001 }
2002
2003
2004 static int
2005 qemuDomainReset(virDomainPtr dom, unsigned int flags)
2006 {
2007     virQEMUDriverPtr driver = dom->conn->privateData;
2008     virDomainObjPtr vm;
2009     int ret = -1;
2010     qemuDomainObjPrivatePtr priv;
2011
2012     virCheckFlags(0, -1);
2013
2014     if (!(vm = qemuDomObjFromDomain(dom)))
2015         goto cleanup;
2016
2017     if (virDomainResetEnsureACL(dom->conn, vm->def) < 0)
2018         goto cleanup;
2019
2020     if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
2021         goto cleanup;
2022
2023     if (!virDomainObjIsActive(vm)) {
2024         virReportError(VIR_ERR_OPERATION_INVALID,
2025                        "%s", _("domain is not running"));
2026         goto endjob;
2027     }
2028
2029     priv = vm->privateData;
2030     qemuDomainObjEnterMonitor(driver, vm);
2031     ret = qemuMonitorSystemReset(priv->mon);
2032     qemuDomainObjExitMonitor(driver, vm);
2033
2034     priv->fakeReboot = false;
2035
2036 endjob:
2037     if (qemuDomainObjEndJob(driver, vm) == 0)
2038         vm = NULL;
2039
2040 cleanup:
2041     if (vm)
2042         virObjectUnlock(vm);
2043     return ret;
2044 }
2045
2046
2047 /* Count how many snapshots in a set are external snapshots or checkpoints.  */
2048 static void
2049 qemuDomainSnapshotCountExternal(void *payload,
2050                                 const void *name ATTRIBUTE_UNUSED,
2051                                 void *data)
2052 {
2053     virDomainSnapshotObjPtr snap = payload;
2054     int *count = data;
2055
2056     if (virDomainSnapshotIsExternal(snap))
2057         (*count)++;
2058 }
2059
2060 static int
2061 qemuDomainDestroyFlags(virDomainPtr dom,
2062                        unsigned int flags)
2063 {
2064     virQEMUDriverPtr driver = dom->conn->privateData;
2065     virDomainObjPtr vm;
2066     int ret = -1;
2067     virDomainEventPtr event = NULL;
2068     qemuDomainObjPrivatePtr priv;
2069
2070     virCheckFlags(VIR_DOMAIN_DESTROY_GRACEFUL, -1);
2071
2072     if (!(vm = qemuDomObjFromDomain(dom)))
2073         return -1;
2074
2075     priv = vm->privateData;
2076
2077     if (virDomainDestroyFlagsEnsureACL(dom->conn, vm->def) < 0)
2078         goto cleanup;
2079
2080     qemuDomainSetFakeReboot(driver, vm, false);
2081
2082
2083     /* We need to prevent monitor EOF callback from doing our work (and sending
2084      * misleading events) while the vm is unlocked inside BeginJob/ProcessKill API
2085      */
2086     priv->beingDestroyed = true;
2087
2088     /* Although qemuProcessStop does this already, there may
2089      * be an outstanding job active. We want to make sure we
2090      * can kill the process even if a job is active. Killing
2091      * it now means the job will be released
2092      */
2093     if (flags & VIR_DOMAIN_DESTROY_GRACEFUL) {
2094         if (qemuProcessKill(vm, 0) < 0) {
2095             priv->beingDestroyed = false;
2096             goto cleanup;
2097         }
2098     } else {
2099         if (qemuProcessKill(vm, VIR_QEMU_PROCESS_KILL_FORCE) < 0) {
2100             priv->beingDestroyed = false;
2101             goto cleanup;
2102         }
2103     }
2104
2105     if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_DESTROY) < 0)
2106         goto cleanup;
2107
2108     priv->beingDestroyed = false;
2109
2110     if (!virDomainObjIsActive(vm)) {
2111         virReportError(VIR_ERR_OPERATION_INVALID,
2112                        "%s", _("domain is not running"));
2113         goto endjob;
2114     }
2115
2116     qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_DESTROYED, 0);
2117     event = virDomainEventNewFromObj(vm,
2118                                      VIR_DOMAIN_EVENT_STOPPED,
2119                                      VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
2120     virDomainAuditStop(vm, "destroyed");
2121
2122     if (!vm->persistent) {
2123         if (qemuDomainObjEndJob(driver, vm) > 0)
2124             qemuDomainRemoveInactive(driver, vm);
2125         vm = NULL;
2126     }
2127     ret = 0;
2128
2129 endjob:
2130     if (vm &&
2131         qemuDomainObjEndJob(driver, vm) == 0)
2132         vm = NULL;
2133
2134 cleanup:
2135     if (vm)
2136         virObjectUnlock(vm);
2137     if (event)
2138         qemuDomainEventQueue(driver, event);
2139     return ret;
2140 }
2141
2142 static int
2143 qemuDomainDestroy(virDomainPtr dom)
2144 {
2145     return qemuDomainDestroyFlags(dom, 0);
2146 }
2147
2148 static char *qemuDomainGetOSType(virDomainPtr dom) {
2149     virDomainObjPtr vm;
2150     char *type = NULL;
2151
2152     if (!(vm = qemuDomObjFromDomain(dom)))
2153         goto cleanup;
2154
2155     if (virDomainGetOSTypeEnsureACL(dom->conn, vm->def) < 0)
2156         goto cleanup;
2157
2158     ignore_value(VIR_STRDUP(type, vm->def->os.type));
2159
2160 cleanup:
2161     if (vm)
2162         virObjectUnlock(vm);
2163     return type;
2164 }
2165
2166 /* Returns max memory in kb, 0 if error */
2167 static unsigned long long
2168 qemuDomainGetMaxMemory(virDomainPtr dom)
2169 {
2170     virDomainObjPtr vm;
2171     unsigned long long ret = 0;
2172
2173     if (!(vm = qemuDomObjFromDomain(dom)))
2174         goto cleanup;
2175
2176     if (virDomainGetMaxMemoryEnsureACL(dom->conn, vm->def) < 0)
2177         goto cleanup;
2178
2179     ret = vm->def->mem.max_balloon;
2180
2181 cleanup:
2182     if (vm)
2183         virObjectUnlock(vm);
2184     return ret;
2185 }
2186
2187 static int qemuDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
2188                                     unsigned int flags) {
2189     virQEMUDriverPtr driver = dom->conn->privateData;
2190     qemuDomainObjPrivatePtr priv;
2191     virDomainObjPtr vm;
2192     virDomainDefPtr persistentDef = NULL;
2193     int ret = -1, r;
2194     virQEMUDriverConfigPtr cfg = NULL;
2195     virCapsPtr caps = NULL;
2196
2197     virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
2198                   VIR_DOMAIN_AFFECT_CONFIG |
2199                   VIR_DOMAIN_MEM_MAXIMUM, -1);
2200
2201     if (!(vm = qemuDomObjFromDomain(dom)))
2202         goto cleanup;
2203
2204     cfg = virQEMUDriverGetConfig(driver);
2205
2206     if (virDomainSetMemoryFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
2207         goto cleanup;
2208
2209     if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
2210         goto cleanup;
2211
2212     if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
2213         goto endjob;
2214     if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
2215                                         &persistentDef) < 0)
2216         goto endjob;
2217
2218     if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
2219         /* resize the maximum memory */
2220
2221         if (flags & VIR_DOMAIN_AFFECT_LIVE) {
2222             virReportError(VIR_ERR_OPERATION_INVALID, "%s",
2223                            _("cannot resize the maximum memory on an "
2224                              "active domain"));
2225             goto endjob;
2226         }
2227
2228         if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
2229             /* Help clang 2.8 decipher the logic flow.  */
2230             sa_assert(persistentDef);
2231             persistentDef->mem.max_balloon = newmem;
2232             if (persistentDef->mem.cur_balloon > newmem)
2233                 persistentDef->mem.cur_balloon = newmem;
2234             ret = virDomainSaveConfig(cfg->configDir, persistentDef);
2235             goto endjob;
2236         }
2237
2238     } else {
2239         /* resize the current memory */
2240
2241         if (newmem > vm->def->mem.max_balloon) {
2242             virReportError(VIR_ERR_INVALID_ARG, "%s",
2243                            _("cannot set memory higher than max memory"));
2244             goto endjob;
2245         }
2246
2247         if (flags & VIR_DOMAIN_AFFECT_LIVE) {
2248             priv = vm->privateData;
2249             qemuDomainObjEnterMonitor(driver, vm);
2250             r = qemuMonitorSetBalloon(priv->mon, newmem);
2251             qemuDomainObjExitMonitor(driver, vm);
2252             virDomainAuditMemory(vm, vm->def->mem.cur_balloon, newmem, "update",
2253                                  r == 1);
2254             if (r < 0)
2255                 goto endjob;
2256
2257             /* Lack of balloon support is a fatal error */
2258             if (r == 0) {
2259                 virReportError(VIR_ERR_OPERATION_INVALID, "%s",
2260                                _("Unable to change memory of active domain without "
2261                                  "the balloon device and guest OS balloon driver"));
2262                 goto endjob;
2263             }
2264         }
2265
2266         if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
2267             sa_assert(persistentDef);
2268             persistentDef->mem.cur_balloon = newmem;
2269             ret = virDomainSaveConfig(cfg->configDir, persistentDef);
2270             goto endjob;
2271         }
2272     }
2273
2274     ret = 0;
2275 endjob:
2276     if (qemuDomainObjEndJob(driver, vm) == 0)
2277         vm = NULL;
2278
2279 cleanup:
2280     if (vm)
2281         virObjectUnlock(vm);
2282     virObjectUnref(caps);
2283     virObjectUnref(cfg);
2284     return ret;
2285 }
2286
2287 static int qemuDomainSetMemory(virDomainPtr dom, unsigned long newmem)
2288 {
2289     return qemuDomainSetMemoryFlags(dom, newmem, VIR_DOMAIN_AFFECT_LIVE);
2290 }
2291
2292 static int qemuDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
2293 {
2294     return qemuDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
2295 }
2296
2297 static int qemuDomainSetMemoryStatsPeriod(virDomainPtr dom, int period,
2298                                           unsigned int flags)
2299 {
2300     virQEMUDriverPtr driver = dom->conn->privateData;
2301     qemuDomainObjPrivatePtr priv;
2302     virDomainObjPtr vm;
2303     virDomainDefPtr persistentDef = NULL;
2304     int ret = -1, r;
2305     virQEMUDriverConfigPtr cfg = NULL;
2306     virCapsPtr caps = NULL;
2307
2308     virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
2309                   VIR_DOMAIN_AFFECT_CONFIG, -1);
2310
2311     if (!(vm = qemuDomObjFromDomain(dom)))
2312         goto cleanup;
2313
2314     cfg = virQEMUDriverGetConfig(driver);
2315
2316     if (virDomainSetMemoryStatsPeriodEnsureACL(dom->conn, vm->def, flags) < 0)
2317         goto cleanup;
2318
2319     if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
2320         goto cleanup;
2321
2322     if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
2323         goto endjob;
2324     if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
2325                                         &persistentDef) < 0)
2326         goto endjob;
2327
2328     /* Set the balloon driver collection interval */
2329     priv = vm->privateData;
2330
2331     if (flags & VIR_DOMAIN_AFFECT_LIVE) {
2332
2333         qemuDomainObjEnterMonitor(driver, vm);
2334         r = qemuMonitorSetMemoryStatsPeriod(priv->mon, period);
2335         qemuDomainObjExitMonitor(driver, vm);
2336         if (r < 0)
2337             virReportError(VIR_ERR_OPERATION_INVALID, "%s",
2338                            _("unable to set balloon driver collection period"));
2339     }
2340
2341     if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
2342         sa_assert(persistentDef);
2343         persistentDef->memballoon->period = period;
2344         ret = virDomainSaveConfig(cfg->configDir, persistentDef);
2345         goto endjob;
2346     }
2347
2348     ret = 0;
2349 endjob:
2350     if (qemuDomainObjEndJob(driver, vm) == 0)
2351         vm = NULL;
2352
2353 cleanup:
2354     if (vm)
2355         virObjectUnlock(vm);
2356     virObjectUnref(caps);
2357     virObjectUnref(cfg);
2358     return ret;
2359 }
2360
2361 static int qemuDomainInjectNMI(virDomainPtr domain, unsigned int flags)
2362 {
2363     virQEMUDriverPtr driver = domain->conn->privateData;
2364     virDomainObjPtr vm = NULL;
2365     int ret = -1;
2366     qemuDomainObjPrivatePtr priv;
2367
2368     virCheckFlags(0, -1);
2369
2370     if (!(vm = qemuDomObjFromDomain(domain)))
2371         return -1;
2372
2373     if (virDomainInjectNMIEnsureACL(domain->conn, vm->def) < 0)
2374         goto cleanup;
2375
2376     if (!virDomainObjIsActive(vm)) {
2377         virReportError(VIR_ERR_OPERATION_INVALID,
2378                        "%s", _("domain is not running"));
2379         goto cleanup;
2380     }
2381
2382     priv = vm->privateData;
2383
2384     if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
2385         goto cleanup;
2386
2387     if (!virDomainObjIsActive(vm)) {
2388         virReportError(VIR_ERR_OPERATION_INVALID,
2389                        "%s", _("domain is not running"));
2390         goto endjob;
2391     }
2392
2393     qemuDomainObjEnterMonitor(driver, vm);
2394     ret = qemuMonitorInjectNMI(priv->mon);
2395     qemuDomainObjExitMonitor(driver, vm);
2396
2397 endjob:
2398     if (qemuDomainObjEndJob(driver, vm) == 0) {
2399         vm = NULL;
2400         goto cleanup;
2401     }
2402
2403 cleanup:
2404     if (vm)
2405         virObjectUnlock(vm);
2406     return ret;
2407 }
2408
2409 static int qemuDomainSendKey(virDomainPtr domain,
2410                              unsigned int codeset,
2411                              unsigned int holdtime,
2412                              unsigned int *keycodes,
2413                              int nkeycodes,
2414                              unsigned int flags)
2415 {
2416     virQEMUDriverPtr driver = domain->conn->privateData;
2417     virDomainObjPtr vm = NULL;
2418     int ret = -1;
2419     qemuDomainObjPrivatePtr priv;
2420
2421     virCheckFlags(0, -1);
2422
2423     /* translate the keycode to RFB for qemu driver */
2424     if (codeset != VIR_KEYCODE_SET_RFB) {
2425         size_t i;
2426         int keycode;
2427
2428         for (i = 0; i < nkeycodes; i++) {
2429             keycode = virKeycodeValueTranslate(codeset, VIR_KEYCODE_SET_RFB,
2430                                                keycodes[i]);
2431             if (keycode < 0) {
2432                 virReportError(VIR_ERR_INTERNAL_ERROR,
2433                                _("cannot translate keycode %u of %s codeset to rfb keycode"),
2434                                keycodes[i],
2435                                virKeycodeSetTypeToString(codeset));
2436                 return -1;
2437             }
2438             keycodes[i] = keycode;
2439         }
2440     }
2441
2442     if (!(vm = qemuDomObjFromDomain(domain)))
2443         goto cleanup;
2444
2445     priv = vm->privateData;
2446
2447     if (virDomainSendKeyEnsureACL(domain->conn, vm->def) < 0)
2448         goto cleanup;
2449
2450     if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
2451         goto cleanup;
2452
2453     if (!virDomainObjIsActive(vm)) {
2454         virReportError(VIR_ERR_OPERATION_INVALID,
2455                        "%s", _("domain is not running"));
2456         goto endjob;
2457     }
2458
2459     qemuDomainObjEnterMonitor(driver, vm);
2460     ret = qemuMonitorSendKey(priv->mon, holdtime, keycodes, nkeycodes);
2461     qemuDomainObjExitMonitor(driver, vm);
2462
2463 endjob:
2464     if (qemuDomainObjEndJob(driver, vm) == 0)
2465         vm = NULL;
2466
2467 cleanup:
2468     if (vm)
2469         virObjectUnlock(vm);
2470     return ret;
2471 }
2472
2473 static int qemuDomainGetInfo(virDomainPtr dom,
2474                              virDomainInfoPtr info)
2475 {
2476     virQEMUDriverPtr driver = dom->conn->privateData;
2477     virDomainObjPtr vm;
2478     int ret = -1;
2479     int err;
2480     unsigned long long balloon;
2481
2482     if (!(vm = qemuDomObjFromDomain(dom)))
2483         goto cleanup;
2484
2485     if (virDomainGetInfoEnsureACL(dom->conn, vm->def) < 0)
2486         goto cleanup;
2487
2488     info->state = virDomainObjGetState(vm, NULL);
2489
2490     if (!virDomainObjIsActive(vm)) {
2491         info->cpuTime = 0;
2492     } else {
2493         if (qemuGetProcessInfo(&(info->cpuTime), NULL, NULL, vm->pid, 0) < 0) {
2494             virReportError(VIR_ERR_OPERATION_FAILED, "%s",
2495                            _("cannot read cputime for domain"));
2496             goto cleanup;
2497         }
2498     }
2499
2500     info->maxMem = vm->def->mem.max_balloon;
2501
2502     if (virDomainObjIsActive(vm)) {
2503         qemuDomainObjPrivatePtr priv = vm->privateData;
2504
2505         if ((vm->def->memballoon != NULL) &&
2506             (vm->def->memballoon->model == VIR_DOMAIN_MEMBALLOON_MODEL_NONE)) {
2507             info->memory = vm->def->mem.max_balloon;
2508         } else if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BALLOON_EVENT)) {
2509             info->memory = vm->def->mem.cur_balloon;
2510         } else if (qemuDomainJobAllowed(priv, QEMU_JOB_QUERY)) {
2511             if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
2512                 goto cleanup;
2513             if (!virDomainObjIsActive(vm))
2514                 err = 0;
2515             else {
2516                 qemuDomainObjEnterMonitor(driver, vm);
2517                 err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
2518                 qemuDomainObjExitMonitor(driver, vm);
2519             }
2520             if (qemuDomainObjEndJob(driver, vm) == 0) {
2521                 vm = NULL;
2522                 goto cleanup;
2523             }
2524
2525             if (err < 0) {
2526                 /* We couldn't get current memory allocation but that's not
2527                  * a show stopper; we wouldn't get it if there was a job
2528                  * active either
2529                  */
2530                 info->memory = vm->def->mem.cur_balloon;
2531             } else if (err == 0) {
2532                 /* Balloon not supported, so maxmem is always the allocation */
2533                 info->memory = vm->def->mem.max_balloon;
2534             } else {
2535                 info->memory = balloon;
2536             }
2537         } else {
2538             info->memory = vm->def->mem.cur_balloon;
2539         }
2540     } else {
2541         info->memory = vm->def->mem.cur_balloon;
2542     }
2543
2544     info->nrVirtCpu = vm->def->vcpus;
2545     ret = 0;
2546
2547 cleanup:
2548     if (vm)
2549         virObjectUnlock(vm);
2550     return ret;
2551 }
2552
2553 static int
2554 qemuDomainGetState(virDomainPtr dom,
2555                    int *state,
2556                    int *reason,
2557                    unsigned int flags)
2558 {
2559     virDomainObjPtr vm;
2560     int ret = -1;
2561
2562     virCheckFlags(0, -1);
2563
2564     if (!(vm = qemuDomObjFromDomain(dom)))
2565         goto cleanup;
2566
2567     if (virDomainGetStateEnsureACL(dom->conn, vm->def) < 0)
2568         goto cleanup;
2569
2570     *state = virDomainObjGetState(vm, reason);
2571     ret = 0;
2572
2573 cleanup:
2574     if (vm)
2575         virObjectUnlock(vm);
2576     return ret;
2577 }
2578
2579 static int
2580 qemuDomainGetControlInfo(virDomainPtr dom,
2581                           virDomainControlInfoPtr info,
2582                           unsigned int flags)
2583 {
2584     virDomainObjPtr vm;
2585     qemuDomainObjPrivatePtr priv;
2586     int ret = -1;
2587
2588     virCheckFlags(0, -1);
2589
2590     if (!(vm = qemuDomObjFromDomain(dom)))
2591         goto cleanup;
2592
2593     if (virDomainGetControlInfoEnsureACL(dom->conn, vm->def) < 0)
2594         goto cleanup;
2595
2596     if (!virDomainObjIsActive(vm)) {
2597         virReportError(VIR_ERR_OPERATION_INVALID,
2598                        "%s", _("domain is not running"));
2599         goto cleanup;
2600     }
2601
2602     priv = vm->privateData;
2603
2604     memset(info, 0, sizeof(*info));
2605
2606     if (priv->monError) {
2607         info->state = VIR_DOMAIN_CONTROL_ERROR;
2608     } else if (priv->job.active) {
2609         if (!priv->monStart) {
2610             info->state = VIR_DOMAIN_CONTROL_JOB;
2611             if (virTimeMillisNow(&info->stateTime) < 0)
2612                 goto cleanup;
2613             info->stateTime -= priv->job.start;
2614         } else {
2615             info->state = VIR_DOMAIN_CONTROL_OCCUPIED;
2616             if (virTimeMillisNow(&info->stateTime) < 0)
2617                 goto cleanup;
2618             info->stateTime -= priv->monStart;
2619         }
2620     } else {
2621         info->state = VIR_DOMAIN_CONTROL_OK;
2622     }
2623
2624     ret = 0;
2625
2626 cleanup:
2627     if (vm)
2628         virObjectUnlock(vm);
2629     return ret;
2630 }
2631
2632
2633 /* It would be nice to replace 'Qemud' with 'Qemu' but
2634  * this magic string is ABI, so it can't be changed
2635  */
2636 #define QEMU_SAVE_MAGIC   "LibvirtQemudSave"
2637 #define QEMU_SAVE_PARTIAL "LibvirtQemudPart"
2638 #define QEMU_SAVE_VERSION 2
2639
2640 verify(sizeof(QEMU_SAVE_MAGIC) == sizeof(QEMU_SAVE_PARTIAL));
2641
2642 typedef enum {
2643     QEMU_SAVE_FORMAT_RAW = 0,
2644     QEMU_SAVE_FORMAT_GZIP = 1,
2645     QEMU_SAVE_FORMAT_BZIP2 = 2,
2646     /*
2647      * Deprecated by xz and never used as part of a release
2648      * QEMU_SAVE_FORMAT_LZMA
2649      */
2650     QEMU_SAVE_FORMAT_XZ = 3,
2651     QEMU_SAVE_FORMAT_LZOP = 4,
2652     /* Note: add new members only at the end.
2653        These values are used in the on-disk format.
2654        Do not change or re-use numbers. */
2655
2656     QEMU_SAVE_FORMAT_LAST
2657 } virQEMUSaveFormat;
2658
2659 VIR_ENUM_DECL(qemuSaveCompression)
2660 VIR_ENUM_IMPL(qemuSaveCompression, QEMU_SAVE_FORMAT_LAST,
2661               "raw",
2662               "gzip",
2663               "bzip2",
2664               "xz",
2665               "lzop")
2666
2667 typedef struct _virQEMUSaveHeader virQEMUSaveHeader;
2668 typedef virQEMUSaveHeader *virQEMUSaveHeaderPtr;
2669 struct _virQEMUSaveHeader {
2670     char magic[sizeof(QEMU_SAVE_MAGIC)-1];
2671     uint32_t version;
2672     uint32_t xml_len;
2673     uint32_t was_running;
2674     uint32_t compressed;
2675     uint32_t unused[15];
2676 };
2677
2678 static inline void
2679 bswap_header(virQEMUSaveHeaderPtr hdr) {
2680     hdr->version = bswap_32(hdr->version);
2681     hdr->xml_len = bswap_32(hdr->xml_len);
2682     hdr->was_running = bswap_32(hdr->was_running);
2683     hdr->compressed = bswap_32(hdr->compressed);
2684 }
2685
2686
2687 /* return -errno on failure, or 0 on success */
2688 static int
2689 qemuDomainSaveHeader(int fd, const char *path, const char *xml,
2690                      virQEMUSaveHeaderPtr header)
2691 {
2692     int ret = 0;
2693
2694     if (safewrite(fd, header, sizeof(*header)) != sizeof(*header)) {
2695         ret = -errno;
2696         virReportError(VIR_ERR_OPERATION_FAILED,
2697                        _("failed to write header to domain save file '%s'"),
2698                        path);
2699         goto endjob;
2700     }
2701
2702     if (safewrite(fd, xml, header->xml_len) != header->xml_len) {
2703         ret = -errno;
2704         virReportError(VIR_ERR_OPERATION_FAILED,
2705                        _("failed to write xml to '%s'"), path);
2706         goto endjob;
2707     }
2708 endjob:
2709     return ret;
2710 }
2711
2712 /* Given a virQEMUSaveFormat compression level, return the name
2713  * of the program to run, or NULL if no program is needed.  */
2714 static const char *
2715 qemuCompressProgramName(int compress)
2716 {
2717     return (compress == QEMU_SAVE_FORMAT_RAW ? NULL :
2718             qemuSaveCompressionTypeToString(compress));
2719 }
2720
2721 static virCommandPtr
2722 qemuCompressGetCommand(virQEMUSaveFormat compression)
2723 {
2724     virCommandPtr ret = NULL;
2725     const char *prog = qemuSaveCompressionTypeToString(compression);
2726
2727     if (!prog) {
2728         virReportError(VIR_ERR_OPERATION_FAILED,
2729                        _("Invalid compressed save format %d"),
2730                        compression);
2731         return NULL;
2732     }
2733
2734     ret = virCommandNew(prog);
2735     virCommandAddArg(ret, "-dc");
2736
2737     switch (compression) {
2738     case QEMU_SAVE_FORMAT_LZOP:
2739         virCommandAddArg(ret, "--ignore-warn");
2740         break;
2741     default:
2742         break;
2743     }
2744
2745     return ret;
2746 }
2747
2748 /* Internal function to properly create or open existing files, with
2749  * ownership affected by qemu driver setup and domain DAC label.  */
2750 static int
2751 qemuOpenFile(virQEMUDriverPtr driver,
2752              virDomainObjPtr vm,
2753              const char *path, int oflags,
2754              bool *needUnlink, bool *bypassSecurityDriver)
2755 {
2756     int ret = -1;
2757     virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2758     uid_t user = cfg->user;
2759     gid_t group = cfg->group;
2760     bool dynamicOwnership = cfg->dynamicOwnership;
2761     virSecurityLabelDefPtr seclabel;
2762
2763     virObjectUnref(cfg);
2764
2765     /* TODO: Take imagelabel into account? */
2766     if (vm &&
2767         (seclabel = virDomainDefGetSecurityLabelDef(vm->def, "dac")) != NULL &&
2768         (virParseOwnershipIds(seclabel->label, &user, &group) < 0))
2769         goto cleanup;
2770
2771     ret = qemuOpenFileAs(user, group, dynamicOwnership,
2772                          path, oflags, needUnlink, bypassSecurityDriver);
2773
2774  cleanup:
2775     return ret;
2776 }
2777
2778 static int
2779 qemuOpenFileAs(uid_t fallback_uid, gid_t fallback_gid,
2780                bool dynamicOwnership,
2781                const char *path, int oflags,
2782                bool *needUnlink, bool *bypassSecurityDriver)
2783 {
2784     struct stat sb;
2785     bool is_reg = true;
2786     bool need_unlink = false;
2787     bool bypass_security = false;
2788     unsigned int vfoflags = 0;
2789     int fd = -1;
2790     int path_shared = virStorageFileIsSharedFS(path);
2791     uid_t uid = geteuid();
2792     gid_t gid = getegid();
2793
2794     /* path might be a pre-existing block dev, in which case
2795      * we need to skip the create step, and also avoid unlink
2796      * in the failure case */
2797     if (oflags & O_CREAT) {
2798         need_unlink = true;
2799
2800         /* Don't force chown on network-shared FS
2801          * as it is likely to fail. */
2802         if (path_shared <= 0 || dynamicOwnership)
2803             vfoflags |= VIR_FILE_OPEN_FORCE_OWNER;
2804
2805         if (stat(path, &sb) == 0) {
2806             is_reg = !!S_ISREG(sb.st_mode);
2807             /* If the path is regular file which exists
2808              * already and dynamic_ownership is off, we don't
2809              * want to change it's ownership, just open it as-is */
2810             if (is_reg && !dynamicOwnership) {
2811                 uid = sb.st_uid;
2812                 gid = sb.st_gid;
2813             }
2814         }
2815     }
2816
2817     /* First try creating the file as root */
2818     if (!is_reg) {
2819         if ((fd = open(path, oflags & ~O_CREAT)) < 0) {
2820             fd = -errno;
2821             goto error;
2822         }
2823     } else {
2824         if ((fd = virFileOpenAs(path, oflags, S_IRUSR | S_IWUSR, uid, gid,
2825                                 vfoflags | VIR_FILE_OPEN_NOFORK)) < 0) {
2826             /* If we failed as root, and the error was permission-denied
2827                (EACCES or EPERM), assume it's on a network-connected share
2828                where root access is restricted (eg, root-squashed NFS). If the
2829                qemu user is non-root, just set a flag to
2830                bypass security driver shenanigans, and retry the operation
2831                after doing setuid to qemu user */
2832             if ((fd != -EACCES && fd != -EPERM) || fallback_uid == geteuid())
2833                 goto error;
2834
2835             /* On Linux we can also verify the FS-type of the directory. */
2836             switch (path_shared) {
2837                 case 1:
2838                     /* it was on a network share, so we'll continue
2839                      * as outlined above
2840                      */
2841                     break;
2842
2843                 case -1:
2844                     virReportSystemError(-fd, oflags & O_CREAT
2845                                          ? _("Failed to create file "
2846                                              "'%s': couldn't determine fs type")
2847                                          : _("Failed to open file "
2848                                              "'%s': couldn't determine fs type"),
2849                                          path);
2850                     goto cleanup;
2851
2852                 case 0:
2853                 default:
2854                     /* local file - log the error returned by virFileOpenAs */
2855                     goto error;
2856             }
2857
2858             /* Retry creating the file as qemu user */
2859
2860             if ((fd = virFileOpenAs(path, oflags,
2861                                     S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP,
2862                                     fallback_uid, fallback_gid,
2863                                     vfoflags | VIR_FILE_OPEN_FORK)) < 0) {
2864                 virReportSystemError(-fd, oflags & O_CREAT
2865                                      ? _("Error from child process creating '%s'")
2866                                      : _("Error from child process opening '%s'"),
2867                                      path);
2868                 goto cleanup;
2869             }
2870
2871             /* Since we had to setuid to create the file, and the fstype
2872                is NFS, we assume it's a root-squashing NFS share, and that
2873                the security driver stuff would have failed anyway */
2874
2875             bypass_security = true;
2876         }
2877     }
2878 cleanup:
2879     if (needUnlink)
2880         *needUnlink = need_unlink;
2881     if (bypassSecurityDriver)
2882         *bypassSecurityDriver = bypass_security;
2883     return fd;
2884
2885 error:
2886     virReportSystemError(-fd, oflags & O_CREAT
2887                          ? _("Failed to create file '%s'")
2888                          : _("Failed to open file '%s'"),
2889                          path);
2890     goto cleanup;
2891 }
2892
2893 /* Helper function to execute a migration to file with a correct save header
2894  * the caller needs to make sure that the processors are stopped and do all other
2895  * actions besides saving memory */
2896 static int
2897 qemuDomainSaveMemory(virQEMUDriverPtr driver,
2898                      virDomainObjPtr vm,
2899                      const char *path,
2900                      const char *domXML,
2901                      int compressed,
2902                      bool was_running,
2903                      unsigned int flags,
2904                      enum qemuDomainAsyncJob asyncJob)
2905 {
2906     virQEMUSaveHeader header;
2907     bool bypassSecurityDriver = false;
2908     bool needUnlink = false;
2909     int ret = -1;
2910     int fd = -1;
2911     int directFlag = 0;
2912     virFileWrapperFdPtr wrapperFd = NULL;
2913     unsigned int wrapperFlags = VIR_FILE_WRAPPER_NON_BLOCKING;
2914     unsigned long long pad;
2915     unsigned long long offset;
2916     size_t len;
2917     char *xml = NULL;
2918
2919     memset(&header, 0, sizeof(header));
2920     memcpy(header.magic, QEMU_SAVE_PARTIAL, sizeof(header.magic));
2921     header.version = QEMU_SAVE_VERSION;
2922     header.was_running = was_running ? 1 : 0;
2923
2924     header.compressed = compressed;
2925
2926     len = strlen(domXML) + 1;
2927     offset = sizeof(header) + len;
2928
2929     /* Due to way we append QEMU state on our header with dd,
2930      * we need to ensure there's a 512 byte boundary. Unfortunately
2931      * we don't have an explicit offset in the header, so we fake
2932      * it by padding the XML string with NUL bytes.  Additionally,
2933      * we want to ensure that virDomainSaveImageDefineXML can supply
2934      * slightly larger XML, so we add a miminum padding prior to
2935      * rounding out to page boundaries.
2936      */
2937     pad = 1024;
2938     pad += (QEMU_MONITOR_MIGRATE_TO_FILE_BS -
2939             ((offset + pad) % QEMU_MONITOR_MIGRATE_TO_FILE_BS));
2940     if (VIR_ALLOC_N(xml, len + pad) < 0)
2941         goto cleanup;
2942     strcpy(xml, domXML);
2943
2944     offset += pad;
2945     header.xml_len = len;
2946
2947     /* Obtain the file handle.  */
2948     if ((flags & VIR_DOMAIN_SAVE_BYPASS_CACHE)) {
2949         wrapperFlags |= VIR_FILE_WRAPPER_BYPASS_CACHE;
2950         directFlag = virFileDirectFdFlag();
2951         if (directFlag < 0) {
2952             virReportError(VIR_ERR_OPERATION_FAILED, "%s",
2953                            _("bypass cache unsupported by this system"));
2954             goto cleanup;
2955         }
2956     }
2957     fd = qemuOpenFile(driver, vm, path,
2958                       O_WRONLY | O_TRUNC | O_CREAT | directFlag,
2959                       &needUnlink, &bypassSecurityDriver);
2960     if (fd < 0)
2961         goto cleanup;
2962
2963     if (!(wrapperFd = virFileWrapperFdNew(&fd, path, wrapperFlags)))
2964         goto cleanup;
2965
2966     /* Write header to file, followed by XML */
2967     if (qemuDomainSaveHeader(fd, path, xml, &header) < 0)
2968         goto cleanup;
2969
2970     /* Perform the migration */
2971     if (qemuMigrationToFile(driver, vm, fd, offset, path,
2972                             qemuCompressProgramName(compressed),
2973                             bypassSecurityDriver,
2974                             asyncJob) < 0)
2975         goto cleanup;
2976
2977     /* Touch up file header to mark image complete. */
2978
2979     /* Reopen the file to touch up the header, since we aren't set
2980      * up to seek backwards on wrapperFd.  The reopened fd will
2981      * trigger a single page of file system cache pollution, but
2982      * that's acceptable.  */
2983     if (VIR_CLOSE(fd) < 0) {
2984         virReportSystemError(errno, _("unable to close %s"), path);
2985         goto cleanup;
2986     }
2987
2988     if (virFileWrapperFdClose(wrapperFd) < 0)
2989         goto cleanup;
2990
2991     if ((fd = qemuOpenFile(driver, vm, path, O_WRONLY, NULL, NULL)) < 0)
2992         goto cleanup;
2993
2994     memcpy(header.magic, QEMU_SAVE_MAGIC, sizeof(header.magic));
2995
2996     if (safewrite(fd, &header, sizeof(header)) != sizeof(header)) {
2997         virReportSystemError(errno, _("unable to write %s"), path);
2998         goto cleanup;
2999     }
3000
3001     if (VIR_CLOSE(fd) < 0) {
3002         virReportSystemError(errno, _("unable to close %s"), path);
3003         goto cleanup;
3004     }
3005
3006     ret = 0;
3007
3008 cleanup:
3009     VIR_FORCE_CLOSE(fd);
3010     virFileWrapperFdFree(wrapperFd);
3011     VIR_FREE(xml);
3012
3013     if (ret != 0 && needUnlink)
3014         unlink(path);
3015
3016     return ret;
3017 }
3018
3019 /* The vm must be active + locked. Vm will be unlocked and
3020  * potentially free'd after this returns (eg transient VMs are freed
3021  * shutdown). So 'vm' must not be referenced by the caller after
3022  * this returns (whether returning success or failure).
3023  */
3024 static int
3025 qemuDomainSaveInternal(virQEMUDriverPtr driver, virDomainPtr dom,
3026                        virDomainObjPtr vm, const char *path,
3027                        int compressed, const char *xmlin, unsigned int flags)
3028 {
3029     char *xml = NULL;
3030     bool was_running = false;
3031     int ret = -1;
3032     int rc;
3033     virDomainEventPtr event = NULL;
3034     qemuDomainObjPrivatePtr priv = vm->privateData;
3035     virCapsPtr caps;
3036
3037     if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
3038         goto cleanup;
3039
3040     if (!qemuMigrationIsAllowed(driver, vm, vm->def, false, false))
3041         goto cleanup;
3042
3043     if (qemuDomainObjBeginAsyncJob(driver, vm, QEMU_ASYNC_JOB_SAVE) < 0)
3044         goto cleanup;
3045
3046     memset(&priv->job.info, 0, sizeof(priv->job.info));
3047     priv->job.info.type = VIR_DOMAIN_JOB_UNBOUNDED;
3048
3049     /* Pause */
3050     if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
3051         was_running = true;
3052         if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE,
3053                                 QEMU_ASYNC_JOB_SAVE) < 0)
3054             goto endjob;
3055
3056         if (!virDomainObjIsActive(vm)) {
3057             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3058                            _("guest unexpectedly quit"));
3059             goto endjob;
3060         }
3061     }
3062
3063    /* libvirt.c already guaranteed these two flags are exclusive.  */
3064     if (flags & VIR_DOMAIN_SAVE_RUNNING)
3065         was_running = true;
3066     else if (flags & VIR_DOMAIN_SAVE_PAUSED)
3067         was_running = false;
3068
3069     /* Get XML for the domain.  Restore needs only the inactive xml,
3070      * including secure.  We should get the same result whether xmlin
3071      * is NULL or whether it was the live xml of the domain moments
3072      * before.  */
3073     if (xmlin) {
3074         virDomainDefPtr def = NULL;
3075
3076         if (!(def = virDomainDefParseString(xmlin, caps, driver->xmlopt,
3077                                             QEMU_EXPECTED_VIRT_TYPES,
3078                                             VIR_DOMAIN_XML_INACTIVE))) {
3079             goto endjob;
3080         }
3081         if (!virDomainDefCheckABIStability(vm->def, def)) {
3082             virDomainDefFree(def);
3083             goto endjob;
3084         }
3085         xml = qemuDomainDefFormatLive(driver, def, true, true);
3086     } else {
3087         xml = qemuDomainDefFormatLive(driver, vm->def, true, true);
3088     }
3089     if (!xml) {
3090         virReportError(VIR_ERR_OPERATION_FAILED,
3091                        "%s", _("failed to get domain xml"));
3092         goto endjob;
3093     }
3094
3095     ret = qemuDomainSaveMemory(driver, vm, path, xml, compressed,
3096                                was_running, flags, QEMU_ASYNC_JOB_SAVE);
3097     if (ret < 0)
3098         goto endjob;
3099
3100     /* Shut it down */
3101     qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_SAVED, 0);
3102     virDomainAuditStop(vm, "saved");
3103     event = virDomainEventNewFromObj(vm,
3104                                      VIR_DOMAIN_EVENT_STOPPED,
3105                                      VIR_DOMAIN_EVENT_STOPPED_SAVED);
3106     if (!vm->persistent) {
3107         if (qemuDomainObjEndAsyncJob(driver, vm) > 0)
3108             qemuDomainRemoveInactive(driver, vm);
3109         vm = NULL;
3110     }
3111
3112 endjob:
3113     if (vm) {
3114         if (ret != 0) {
3115             if (was_running && virDomainObjIsActive(vm)) {
3116                 rc = qemuProcessStartCPUs(driver, vm, dom->conn,
3117                                           VIR_DOMAIN_RUNNING_SAVE_CANCELED,
3118                                           QEMU_ASYNC_JOB_SAVE);
3119                 if (rc < 0) {
3120                     VIR_WARN("Unable to resume guest CPUs after save failure");
3121                     event = virDomainEventNewFromObj(vm,
3122                                                      VIR_DOMAIN_EVENT_SUSPENDED,
3123                                                      VIR_DOMAIN_EVENT_SUSPENDED_API_ERROR);
3124                 }
3125             }
3126         }
3127         if (qemuDomainObjEndAsyncJob(driver, vm) == 0)
3128             vm = NULL;
3129     }
3130
3131 cleanup:
3132     VIR_FREE(xml);
3133     if (event)
3134         qemuDomainEventQueue(driver, event);
3135     if (vm)
3136         virObjectUnlock(vm);
3137     virObjectUnref(caps);
3138     return ret;
3139 }
3140
3141 /* Returns true if a compression program is available in PATH */
3142 static bool qemuCompressProgramAvailable(virQEMUSaveFormat compress)
3143 {
3144     const char *prog;
3145     char *c;
3146
3147     if (compress == QEMU_SAVE_FORMAT_RAW)
3148         return true;
3149     prog = qemuSaveCompressionTypeToString(compress);
3150     c = virFindFileInPath(prog);
3151     if (!c)
3152         return false;
3153     VIR_FREE(c);
3154     return true;
3155 }
3156
3157 static int
3158 qemuDomainSaveFlags(virDomainPtr dom, const char *path, const char *dxml,
3159                     unsigned int flags)
3160 {
3161     virQEMUDriverPtr driver = dom->conn->privateData;
3162     int compressed;
3163     int ret = -1;
3164     virDomainObjPtr vm = NULL;
3165     virQEMUDriverConfigPtr cfg = NULL;
3166
3167     virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE |
3168                   VIR_DOMAIN_SAVE_RUNNING |
3169                   VIR_DOMAIN_SAVE_PAUSED, -1);
3170
3171     cfg = virQEMUDriverGetConfig(driver);
3172     if (cfg->saveImageFormat == NULL)
3173         compressed = QEMU_SAVE_FORMAT_RAW;
3174     else {
3175         compressed = qemuSaveCompressionTypeFromString(cfg->saveImageFormat);
3176         if (compressed < 0) {
3177             virReportError(VIR_ERR_OPERATION_FAILED,
3178                            "%s", _("Invalid save image format specified "
3179                                    "in configuration file"));
3180             goto cleanup;
3181         }
3182         if (!qemuCompressProgramAvailable(compressed)) {
3183             virReportError(VIR_ERR_OPERATION_FAILED,
3184                            "%s", _("Compression program for image format "
3185                                    "in configuration file isn't available"));
3186             goto cleanup;
3187         }
3188     }
3189
3190     if (!(vm = qemuDomObjFromDomain(dom)))
3191         goto cleanup;
3192
3193     if (virDomainSaveFlagsEnsureACL(dom->conn, vm->def) < 0)
3194         goto cleanup;
3195
3196     if (!virDomainObjIsActive(vm)) {
3197         virReportError(VIR_ERR_OPERATION_INVALID,
3198                        "%s", _("domain is not running"));
3199         goto cleanup;
3200     }
3201
3202     ret = qemuDomainSaveInternal(driver, dom, vm, path, compressed,
3203                                  dxml, flags);
3204     vm = NULL;
3205
3206 cleanup:
3207     if (vm)
3208         virObjectUnlock(vm);
3209     virObjectUnref(cfg);
3210     return ret;
3211 }
3212
3213 static int
3214 qemuDomainSave(virDomainPtr dom, const char *path)
3215 {
3216     return qemuDomainSaveFlags(dom, path, NULL, 0);
3217 }
3218
3219 static char *
3220 qemuDomainManagedSavePath(virQEMUDriverPtr driver, virDomainObjPtr vm)
3221 {
3222     char *ret;
3223     virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
3224
3225     if (virAsprintf(&ret, "%s/%s.save", cfg->saveDir, vm->def->name) < 0) {
3226         virObjectUnref(cfg);
3227         return NULL;
3228     }
3229
3230     virObjectUnref(cfg);
3231     return ret;
3232 }
3233
3234 static int
3235 qemuDomainManagedSave(virDomainPtr dom, unsigned int flags)
3236 {
3237     virQEMUDriverPtr driver = dom->conn->privateData;
3238     virDomainObjPtr vm;
3239     char *name = NULL;
3240     int ret = -1;
3241
3242     virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE |
3243                   VIR_DOMAIN_SAVE_RUNNING |
3244                   VIR_DOMAIN_SAVE_PAUSED, -1);
3245
3246     if (!(vm = qemuDomObjFromDomain(dom)))
3247         return -1;
3248
3249     if (virDomainManagedSaveEnsureACL(dom->conn, vm->def) < 0)
3250         goto cleanup;
3251
3252     if (!virDomainObjIsActive(vm)) {
3253         virReportError(VIR_ERR_OPERATION_INVALID,
3254                        "%s", _("domain is not running"));
3255         goto cleanup;
3256     }
3257     if (!vm->persistent) {
3258         virReportError(VIR_ERR_OPERATION_INVALID, "%s",
3259                        _("cannot do managed save for transient domain"));
3260         goto cleanup;
3261     }
3262
3263     if (!(name = qemuDomainManagedSavePath(driver, vm)))
3264         goto cleanup;
3265
3266     VIR_INFO("Saving state of domain '%s' to '%s'", vm->def->name, name);
3267
3268     if ((ret = qemuDomainSaveInternal(driver, dom, vm, name,
3269                                       QEMU_SAVE_FORMAT_RAW,
3270                                       NULL, flags)) == 0)
3271         vm->hasManagedSave = true;
3272
3273     vm = NULL;
3274
3275 cleanup:
3276     if (vm)
3277         virObjectUnlock(vm);
3278     VIR_FREE(name);
3279
3280     return ret;
3281 }
3282
3283 static int
3284 qemuDomainManagedSaveLoad(virDomainObjPtr vm,
3285                           void *opaque)
3286 {
3287     virQEMUDriverPtr driver = opaque;
3288     char *name;
3289     int ret = -1;
3290
3291     virObjectLock(vm);
3292
3293     if (!(name = qemuDomainManagedSavePath(driver, vm)))
3294         goto cleanup;
3295
3296     vm->hasManagedSave = virFileExists(name);
3297
3298     ret = 0;
3299 cleanup:
3300     virObjectUnlock(vm);
3301     VIR_FREE(name);
3302     return ret;
3303 }
3304
3305
3306 static int
3307 qemuDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
3308 {
3309     virDomainObjPtr vm = NULL;
3310     int ret = -1;
3311
3312     virCheckFlags(0, -1);
3313
3314     if (!(vm = qemuDomObjFromDomain(dom)))
3315         return -1;
3316
3317     if (virDomainHasManagedSaveImageEnsureACL(dom->conn, vm->def) < 0)
3318         goto cleanup;
3319
3320     ret = vm->hasManagedSave;
3321
3322 cleanup:
3323     virObjectUnlock(vm);
3324     return ret;
3325 }
3326
3327 static int
3328 qemuDomainManagedSaveRemove(virDomainPtr dom, unsigned int flags)
3329 {
3330     virQEMUDriverPtr driver = dom->conn->privateData;
3331     virDomainObjPtr vm;
3332     int ret = -1;
3333     char *name = NULL;
3334
3335     virCheckFlags(0, -1);
3336
3337     if (!(vm = qemuDomObjFromDomain(dom)))
3338         return -1;
3339
3340     if (virDomainManagedSaveRemoveEnsureACL(dom->conn, vm->def) < 0)
3341         goto cleanup;
3342
3343     if (!(name = qemuDomainManagedSavePath(driver, vm)))
3344         goto cleanup;
3345
3346     if (unlink(name) < 0) {
3347         virReportSystemError(errno,
3348                              _("Failed to remove managed save file '%s'"),
3349                              name);
3350         goto cleanup;
3351     }
3352
3353     vm->hasManagedSave = false;
3354     ret = 0;
3355
3356 cleanup:
3357     VIR_FREE(name);
3358     virObjectUnlock(vm);
3359     return ret;
3360 }
3361
3362 static int qemuDumpToFd(virQEMUDriverPtr driver, virDomainObjPtr vm,
3363                         int fd, enum qemuDomainAsyncJob asyncJob)
3364 {
3365     qemuDomainObjPrivatePtr priv = vm->privateData;
3366     int ret = -1;
3367
3368     if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DUMP_GUEST_MEMORY)) {
3369         virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
3370                        _("dump-guest-memory is not supported"));
3371         return -1;
3372     }
3373
3374     if (virSecurityManagerSetImageFDLabel(driver->securityManager, vm->def,
3375                                           fd) < 0)
3376         return -1;
3377
3378     priv->job.dump_memory_only = true;
3379
3380     if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
3381         return -1;
3382
3383     ret = qemuMonitorDumpToFd(priv->mon, fd);
3384     qemuDomainObjExitMonitor(driver, vm);
3385
3386     return ret;
3387 }
3388
3389 static int
3390 doCoreDump(virQEMUDriverPtr driver,
3391            virDomainObjPtr vm,
3392            const char *path,
3393            virQEMUSaveFormat compress,
3394            unsigned int dump_flags)
3395 {
3396     int fd = -1;
3397     int ret = -1;
3398     virFileWrapperFdPtr wrapperFd = NULL;
3399     int directFlag = 0;
3400     unsigned int flags = VIR_FILE_WRAPPER_NON_BLOCKING;
3401
3402     /* Create an empty file with appropriate ownership.  */
3403     if (dump_flags & VIR_DUMP_BYPASS_CACHE) {
3404         flags |= VIR_FILE_WRAPPER_BYPASS_CACHE;
3405         directFlag = virFileDirectFdFlag();
3406         if (directFlag < 0) {
3407             virReportError(VIR_ERR_OPERATION_FAILED, "%s",
3408                            _("bypass cache unsupported by this system"));
3409             goto cleanup;
3410         }
3411     }
3412     /* Core dumps usually imply last-ditch analysis efforts are
3413      * desired, so we intentionally do not unlink even if a file was
3414      * created.  */
3415     if ((fd = qemuOpenFile(driver, vm, path,
3416                            O_CREAT | O_TRUNC | O_WRONLY | directFlag,
3417                            NULL, NULL)) < 0)
3418         goto cleanup;
3419
3420     if (!(wrapperFd = virFileWrapperFdNew(&fd, path, flags)))
3421         goto cleanup;
3422
3423     if (dump_flags & VIR_DUMP_MEMORY_ONLY) {
3424         ret = qemuDumpToFd(driver, vm, fd, QEMU_ASYNC_JOB_DUMP);
3425     } else {
3426         ret = qemuMigrationToFile(driver, vm, fd, 0, path,
3427                                   qemuCompressProgramName(compress), false,
3428                                   QEMU_ASYNC_JOB_DUMP);
3429     }
3430
3431     if (ret < 0)
3432         goto cleanup;
3433
3434     if (VIR_CLOSE(fd) < 0) {
3435         virReportSystemError(errno,
3436                              _("unable to close file %s"),
3437                              path);
3438         goto cleanup;
3439     }
3440     if (virFileWrapperFdClose(wrapperFd) < 0)
3441         goto cleanup;
3442
3443     ret = 0;
3444
3445 cleanup:
3446     VIR_FORCE_CLOSE(fd);
3447     if (ret != 0)
3448         unlink(path);
3449     virFileWrapperFdFree(wrapperFd);
3450     return ret;
3451 }
3452
3453 static virQEMUSaveFormat
3454 getCompressionType(virQEMUDriverPtr driver)
3455 {
3456     int ret = QEMU_SAVE_FORMAT_RAW;
3457     virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
3458
3459     /*
3460      * We reuse "save" flag for "dump" here. Then, we can support the same
3461      * format in "save" and "dump".
3462      */
3463     if (cfg->dumpImageFormat) {
3464         ret = qemuSaveCompressionTypeFromString(cfg->dumpImageFormat);
3465         /* Use "raw" as the format if the specified format is not valid,
3466          * or the compress program is not available.
3467          */
3468         if (ret < 0) {
3469             VIR_WARN("%s", _("Invalid dump image format specified in "
3470                              "configuration file, using raw"));
3471             ret = QEMU_SAVE_FORMAT_RAW;
3472             goto cleanup;
3473         }
3474         if (!qemuCompressProgramAvailable(ret)) {
3475             VIR_WARN("%s", _("Compression program for dump image format "
3476                              "in configuration file isn't available, "
3477                              "using raw"));
3478             ret = QEMU_SAVE_FORMAT_RAW;
3479             goto cleanup;
3480         }
3481     }
3482 cleanup:
3483     virObjectUnref(cfg);
3484     return ret;
3485 }
3486
3487 static int qemuDomainCoreDump(virDomainPtr dom,
3488                               const char *path,
3489                               unsigned int flags)
3490 {
3491     virQEMUDriverPtr driver = dom->conn->privateData;
3492     virDomainObjPtr vm;
3493     qemuDomainObjPrivatePtr priv;
3494     bool resume = false, paused = false;
3495     int ret = -1;
3496     virDomainEventPtr event = NULL;
3497
3498     virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH |
3499                   VIR_DUMP_BYPASS_CACHE | VIR_DUMP_RESET |
3500                   VIR_DUMP_MEMORY_ONLY, -1);
3501
3502     if (!(vm = qemuDomObjFromDomain(dom)))
3503         return -1;
3504
3505     if (virDomainCoreDumpEnsureACL(dom->conn, vm->def) < 0)
3506         goto cleanup;
3507
3508     if (qemuDomainObjBeginAsyncJob(driver, vm,
3509                                    QEMU_ASYNC_JOB_DUMP) < 0)
3510         goto cleanup;
3511
3512     if (!virDomainObjIsActive(vm)) {
3513         virReportError(VIR_ERR_OPERATION_INVALID,
3514                        "%s", _("domain is not running"));
3515         goto endjob;
3516     }
3517
3518     /* Migrate will always stop the VM, so the resume condition is
3519        independent of whether the stop command is issued.  */
3520     resume = virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING;
3521
3522     /* Pause domain for non-live dump */
3523     if (!(flags & VIR_DUMP_LIVE) &&
3524         virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
3525         if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_DUMP,
3526                                 QEMU_ASYNC_JOB_DUMP) < 0)
3527             goto endjob;
3528         paused = true;
3529
3530         if (!virDomainObjIsActive(vm)) {
3531             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3532                            _("guest unexpectedly quit"));
3533             goto endjob;
3534         }
3535     }
3536
3537     ret = doCoreDump(driver, vm, path, getCompressionType(driver), flags);
3538     if (ret < 0)
3539         goto endjob;
3540
3541     paused = true;
3542
3543 endjob:
3544     if ((ret == 0) && (flags & VIR_DUMP_CRASH)) {
3545         qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_CRASHED, 0);
3546         virDomainAuditStop(vm, "crashed");
3547         event = virDomainEventNewFromObj(vm,
3548                                          VIR_DOMAIN_EVENT_STOPPED,
3549                                          VIR_DOMAIN_EVENT_STOPPED_CRASHED);
3550     }
3551
3552     /* Since the monitor is always attached to a pty for libvirt, it
3553        will support synchronous operations so we always get here after
3554        the migration is complete.  */
3555     else if (((resume && paused) || (flags & VIR_DUMP_RESET)) &&
3556              virDomainObjIsActive(vm)) {
3557         if ((ret == 0) && (flags & VIR_DUMP_RESET)) {
3558             priv =  vm->privateData;
3559             qemuDomainObjEnterMonitor(driver, vm);
3560             ret = qemuMonitorSystemReset(priv->mon);
3561             qemuDomainObjExitMonitor(driver, vm);
3562         }
3563
3564         if (resume && qemuProcessStartCPUs(driver, vm, dom->conn,
3565                                            VIR_DOMAIN_RUNNING_UNPAUSED,
3566                                            QEMU_ASYNC_JOB_DUMP) < 0) {
3567             event = virDomainEventNewFromObj(vm,
3568                                              VIR_DOMAIN_EVENT_SUSPENDED,
3569                                              VIR_DOMAIN_EVENT_SUSPENDED_API_ERROR);
3570             if (virGetLastError() == NULL)
3571                 virReportError(VIR_ERR_OPERATION_FAILED,
3572                                "%s", _("resuming after dump failed"));
3573         }
3574     }
3575
3576     if (qemuDomainObjEndAsyncJob(driver, vm) == 0)
3577         vm = NULL;
3578     else if ((ret == 0) && (flags & VIR_DUMP_CRASH) && !vm->persistent) {
3579         qemuDomainRemoveInactive(driver, vm);
3580         vm = NULL;
3581     }
3582
3583 cleanup:
3584     if (vm)
3585         virObjectUnlock(vm);
3586     if (event)
3587         qemuDomainEventQueue(driver, event);
3588     return ret;
3589 }
3590
3591 static char *
3592 qemuDomainScreenshot(virDomainPtr dom,
3593                      virStreamPtr st,
3594                      unsigned int screen,
3595                      unsigned int flags)
3596 {
3597     virQEMUDriverPtr driver = dom->conn->privateData;
3598     virDomainObjPtr vm;
3599     qemuDomainObjPrivatePtr priv;
3600     char *tmp = NULL;
3601     int tmp_fd = -1;
3602     char *ret = NULL;
3603     bool unlink_tmp = false;
3604     virQEMUDriverConfigPtr cfg = NULL;
3605
3606     virCheckFlags(0, NULL);
3607
3608     if (!(vm = qemuDomObjFromDomain(dom)))
3609         goto cleanup;
3610
3611     priv = vm->privateData;
3612     cfg = virQEMUDriverGetConfig(driver);
3613
3614     if (virDomainScreenshotEnsureACL(dom->conn, vm->def) < 0)
3615         goto cleanup;
3616
3617     if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
3618         goto cleanup;
3619
3620     if (!virDomainObjIsActive(vm)) {
3621         virReportError(VIR_ERR_OPERATION_INVALID,
3622                        "%s", _("domain is not running"));
3623         goto endjob;
3624     }
3625
3626     /* Well, even if qemu allows multiple graphic cards, heads, whatever,
3627      * screenshot command does not */
3628     if (screen) {
3629         virReportError(VIR_ERR_INVALID_ARG,
3630                        "%s", _("currently is supported only taking "
3631                                "screenshots of screen ID 0"));
3632         goto endjob;
3633     }
3634
3635     if (virAsprintf(&tmp, "%s/qemu.screendump.XXXXXX", cfg->cacheDir) < 0)
3636         goto endjob;
3637
3638     if ((tmp_fd = mkostemp(tmp, O_CLOEXEC)) == -1) {
3639         virReportSystemError(errno, _("mkostemp(\"%s\") failed"), tmp);
3640         goto endjob;
3641     }
3642     unlink_tmp = true;
3643
3644     virSecurityManagerSetSavedStateLabel(qemu_driver->securityManager, vm->def, tmp);
3645
3646     qemuDomainObjEnterMonitor(driver, vm);