Fix autostart flag when loading running domains
[libvirt.git] / src / conf / domain_conf.c
1 /*
2  * domain_conf.c: domain XML processing
3  *
4  * Copyright (C) 2006-2011 Red Hat, Inc.
5  * Copyright (C) 2006-2008 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, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
20  *
21  * Author: Daniel P. Berrange <berrange@redhat.com>
22  */
23
24 #include <config.h>
25
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <unistd.h>
29 #include <fcntl.h>
30 #include <dirent.h>
31 #include <sys/time.h>
32
33 #include "virterror_internal.h"
34 #include "datatypes.h"
35 #include "domain_conf.h"
36 #include "memory.h"
37 #include "verify.h"
38 #include "xml.h"
39 #include "uuid.h"
40 #include "util.h"
41 #include "buf.h"
42 #include "c-ctype.h"
43 #include "logging.h"
44 #include "network.h"
45 #include "nwfilter_conf.h"
46 #include "ignore-value.h"
47 #include "storage_file.h"
48 #include "files.h"
49 #include "bitmap.h"
50
51 #define VIR_FROM_THIS VIR_FROM_DOMAIN
52
53 VIR_ENUM_IMPL(virDomainTaint, VIR_DOMAIN_TAINT_LAST,
54               "custom-argv",
55               "custom-monitor",
56               "high-privileges",
57               "shell-scripts",
58               "disk-probing");
59
60 VIR_ENUM_IMPL(virDomainVirt, VIR_DOMAIN_VIRT_LAST,
61               "qemu",
62               "kqemu",
63               "kvm",
64               "xen",
65               "lxc",
66               "uml",
67               "openvz",
68               "vserver",
69               "ldom",
70               "test",
71               "vmware",
72               "hyperv",
73               "vbox",
74               "one",
75               "phyp")
76
77 VIR_ENUM_IMPL(virDomainBoot, VIR_DOMAIN_BOOT_LAST,
78               "fd",
79               "cdrom",
80               "hd",
81               "network")
82
83 VIR_ENUM_IMPL(virDomainFeature, VIR_DOMAIN_FEATURE_LAST,
84               "acpi",
85               "apic",
86               "pae",
87               "hap")
88
89 VIR_ENUM_IMPL(virDomainLifecycle, VIR_DOMAIN_LIFECYCLE_LAST,
90               "destroy",
91               "restart",
92               "rename-restart",
93               "preserve")
94
95 VIR_ENUM_IMPL(virDomainLifecycleCrash, VIR_DOMAIN_LIFECYCLE_CRASH_LAST,
96               "destroy",
97               "restart",
98               "rename-restart",
99               "preserve",
100               "coredump-destroy",
101               "coredump-restart")
102
103 VIR_ENUM_IMPL(virDomainDevice, VIR_DOMAIN_DEVICE_LAST,
104               "disk",
105               "lease",
106               "filesystem",
107               "interface",
108               "input",
109               "sound",
110               "video",
111               "hostdev",
112               "watchdog",
113               "controller",
114               "graphics")
115
116 VIR_ENUM_IMPL(virDomainDeviceAddress, VIR_DOMAIN_DEVICE_ADDRESS_TYPE_LAST,
117               "none",
118               "pci",
119               "drive",
120               "virtio-serial",
121               "ccid")
122
123 VIR_ENUM_IMPL(virDomainDisk, VIR_DOMAIN_DISK_TYPE_LAST,
124               "block",
125               "file",
126               "dir",
127               "network")
128
129 VIR_ENUM_IMPL(virDomainDiskDevice, VIR_DOMAIN_DISK_DEVICE_LAST,
130               "disk",
131               "cdrom",
132               "floppy")
133
134 VIR_ENUM_IMPL(virDomainDiskBus, VIR_DOMAIN_DISK_BUS_LAST,
135               "ide",
136               "fdc",
137               "scsi",
138               "virtio",
139               "xen",
140               "usb",
141               "uml",
142               "sata")
143
144 VIR_ENUM_IMPL(virDomainDiskCache, VIR_DOMAIN_DISK_CACHE_LAST,
145               "default",
146               "none",
147               "writethrough",
148               "writeback")
149
150 VIR_ENUM_IMPL(virDomainDiskErrorPolicy, VIR_DOMAIN_DISK_ERROR_POLICY_LAST,
151               "default",
152               "stop",
153               "ignore",
154               "enospace")
155
156 VIR_ENUM_IMPL(virDomainDiskProtocol, VIR_DOMAIN_DISK_PROTOCOL_LAST,
157               "nbd",
158               "rbd",
159               "sheepdog")
160
161 VIR_ENUM_IMPL(virDomainDiskIo, VIR_DOMAIN_DISK_IO_LAST,
162               "default",
163               "native",
164               "threads")
165
166 VIR_ENUM_IMPL(virDomainController, VIR_DOMAIN_CONTROLLER_TYPE_LAST,
167               "ide",
168               "fdc",
169               "scsi",
170               "sata",
171               "virtio-serial",
172               "ccid")
173
174 VIR_ENUM_IMPL(virDomainControllerModel, VIR_DOMAIN_CONTROLLER_MODEL_LAST,
175               "auto",
176               "buslogic",
177               "lsilogic",
178               "lsisas1068",
179               "vmpvscsi")
180
181 VIR_ENUM_IMPL(virDomainFS, VIR_DOMAIN_FS_TYPE_LAST,
182               "mount",
183               "block",
184               "file",
185               "template")
186
187 VIR_ENUM_IMPL(virDomainFSAccessMode, VIR_DOMAIN_FS_ACCESSMODE_LAST,
188               "passthrough",
189               "mapped",
190               "squash")
191
192
193 VIR_ENUM_IMPL(virDomainNet, VIR_DOMAIN_NET_TYPE_LAST,
194               "user",
195               "ethernet",
196               "server",
197               "client",
198               "mcast",
199               "network",
200               "bridge",
201               "internal",
202               "direct")
203
204 VIR_ENUM_IMPL(virDomainNetBackend, VIR_DOMAIN_NET_BACKEND_TYPE_LAST,
205               "default",
206               "qemu",
207               "vhost")
208
209 VIR_ENUM_IMPL(virDomainNetVirtioTxMode, VIR_DOMAIN_NET_VIRTIO_TX_MODE_LAST,
210               "default",
211               "iothread",
212               "timer")
213
214 VIR_ENUM_IMPL(virDomainChrChannelTarget,
215               VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_LAST,
216               "guestfwd",
217               "virtio")
218
219 VIR_ENUM_IMPL(virDomainChrConsoleTarget,
220               VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_LAST,
221               "serial",
222               "xen",
223               "uml",
224               "virtio")
225
226 VIR_ENUM_IMPL(virDomainChrDevice, VIR_DOMAIN_CHR_DEVICE_TYPE_LAST,
227               "parallel",
228               "serial",
229               "console",
230               "channel")
231
232 VIR_ENUM_IMPL(virDomainChr, VIR_DOMAIN_CHR_TYPE_LAST,
233               "null",
234               "vc",
235               "pty",
236               "dev",
237               "file",
238               "pipe",
239               "stdio",
240               "udp",
241               "tcp",
242               "unix",
243               "spicevmc")
244
245 VIR_ENUM_IMPL(virDomainChrTcpProtocol, VIR_DOMAIN_CHR_TCP_PROTOCOL_LAST,
246               "raw",
247               "telnet",
248               "telnets",
249               "tls")
250
251 VIR_ENUM_IMPL(virDomainChrSpicevmc, VIR_DOMAIN_CHR_SPICEVMC_LAST,
252               "vdagent",
253               "smartcard")
254
255 VIR_ENUM_IMPL(virDomainSmartcard, VIR_DOMAIN_SMARTCARD_TYPE_LAST,
256               "host",
257               "host-certificates",
258               "passthrough")
259
260 VIR_ENUM_IMPL(virDomainSoundModel, VIR_DOMAIN_SOUND_MODEL_LAST,
261               "sb16",
262               "es1370",
263               "pcspk",
264               "ac97",
265               "ich6")
266
267 VIR_ENUM_IMPL(virDomainMemballoonModel, VIR_DOMAIN_MEMBALLOON_MODEL_LAST,
268               "virtio",
269               "xen",
270               "none")
271
272 VIR_ENUM_IMPL(virDomainSmbiosMode, VIR_DOMAIN_SMBIOS_LAST,
273               "none",
274               "emulate",
275               "host",
276               "sysinfo")
277
278 VIR_ENUM_IMPL(virDomainWatchdogModel, VIR_DOMAIN_WATCHDOG_MODEL_LAST,
279               "i6300esb",
280               "ib700")
281
282 VIR_ENUM_IMPL(virDomainWatchdogAction, VIR_DOMAIN_WATCHDOG_ACTION_LAST,
283               "reset",
284               "shutdown",
285               "poweroff",
286               "pause",
287               "dump",
288               "none")
289
290 VIR_ENUM_IMPL(virDomainVideo, VIR_DOMAIN_VIDEO_TYPE_LAST,
291               "vga",
292               "cirrus",
293               "vmvga",
294               "xen",
295               "vbox",
296               "qxl")
297
298 VIR_ENUM_IMPL(virDomainInput, VIR_DOMAIN_INPUT_TYPE_LAST,
299               "mouse",
300               "tablet")
301
302 VIR_ENUM_IMPL(virDomainInputBus, VIR_DOMAIN_INPUT_BUS_LAST,
303               "ps2",
304               "usb",
305               "xen")
306
307 VIR_ENUM_IMPL(virDomainGraphics, VIR_DOMAIN_GRAPHICS_TYPE_LAST,
308               "sdl",
309               "vnc",
310               "rdp",
311               "desktop",
312               "spice")
313
314 VIR_ENUM_IMPL(virDomainGraphicsSpiceChannelName,
315               VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_LAST,
316               "main",
317               "display",
318               "inputs",
319               "cursor",
320               "playback",
321               "record",
322               "smartcard");
323
324 VIR_ENUM_IMPL(virDomainGraphicsSpiceChannelMode,
325               VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_LAST,
326               "any",
327               "secure",
328               "insecure");
329
330 VIR_ENUM_IMPL(virDomainGraphicsSpiceImageCompression,
331               VIR_DOMAIN_GRAPHICS_SPICE_IMAGE_COMPRESSION_LAST,
332               "default",
333               "auto_glz",
334               "auto_lz",
335               "quic",
336               "glz",
337               "lz",
338               "off");
339
340 VIR_ENUM_IMPL(virDomainGraphicsSpiceJpegCompression,
341               VIR_DOMAIN_GRAPHICS_SPICE_JPEG_COMPRESSION_LAST,
342               "default",
343               "auto",
344               "never",
345               "always");
346
347 VIR_ENUM_IMPL(virDomainGraphicsSpiceZlibCompression,
348               VIR_DOMAIN_GRAPHICS_SPICE_ZLIB_COMPRESSION_LAST,
349               "default",
350               "auto",
351               "never",
352               "always");
353
354 VIR_ENUM_IMPL(virDomainGraphicsSpicePlaybackCompression,
355               VIR_DOMAIN_GRAPHICS_SPICE_PLAYBACK_COMPRESSION_LAST,
356               "default",
357               "on",
358               "off");
359
360 VIR_ENUM_IMPL(virDomainGraphicsSpiceStreamingMode,
361               VIR_DOMAIN_GRAPHICS_SPICE_STREAMING_MODE_LAST,
362               "default",
363               "filter",
364               "all",
365               "off");
366
367 VIR_ENUM_IMPL(virDomainHostdevMode, VIR_DOMAIN_HOSTDEV_MODE_LAST,
368               "subsystem",
369               "capabilities")
370
371 VIR_ENUM_IMPL(virDomainHostdevSubsys, VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_LAST,
372               "usb",
373               "pci")
374
375 VIR_ENUM_IMPL(virDomainState, VIR_DOMAIN_CRASHED+1,
376               "nostate",
377               "running",
378               "blocked",
379               "paused",
380               "shutdown",
381               "shutoff",
382               "crashed")
383
384 #define VIR_DOMAIN_NOSTATE_LAST (VIR_DOMAIN_NOSTATE_UNKNOWN + 1)
385 VIR_ENUM_IMPL(virDomainNostateReason, VIR_DOMAIN_NOSTATE_LAST,
386               "unknown")
387
388 #define VIR_DOMAIN_RUNNING_LAST (VIR_DOMAIN_RUNNING_SAVE_CANCELED + 1)
389 VIR_ENUM_IMPL(virDomainRunningReason, VIR_DOMAIN_RUNNING_LAST,
390               "unknown",
391               "booted",
392               "migrated",
393               "restored",
394               "from snapshot",
395               "unpaused",
396               "migration canceled",
397               "save canceled")
398
399 #define VIR_DOMAIN_BLOCKED_LAST (VIR_DOMAIN_BLOCKED_UNKNOWN + 1)
400 VIR_ENUM_IMPL(virDomainBlockedReason, VIR_DOMAIN_BLOCKED_LAST,
401               "unknown")
402
403 #define VIR_DOMAIN_PAUSED_LAST (VIR_DOMAIN_PAUSED_FROM_SNAPSHOT + 1)
404 VIR_ENUM_IMPL(virDomainPausedReason, VIR_DOMAIN_PAUSED_LAST,
405               "unknown",
406               "user",
407               "migration",
408               "save",
409               "dump",
410               "ioerror",
411               "watchdog",
412               "from snapshot")
413
414 #define VIR_DOMAIN_SHUTDOWN_LAST (VIR_DOMAIN_SHUTDOWN_USER + 1)
415 VIR_ENUM_IMPL(virDomainShutdownReason, VIR_DOMAIN_SHUTDOWN_LAST,
416               "unknown",
417               "user")
418
419 #define VIR_DOMAIN_SHUTOFF_LAST (VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT + 1)
420 VIR_ENUM_IMPL(virDomainShutoffReason, VIR_DOMAIN_SHUTOFF_LAST,
421               "unknown",
422               "shutdown",
423               "destroyed",
424               "crashed",
425               "migrated",
426               "saved",
427               "failed",
428               "from snapshot")
429
430 #define VIR_DOMAIN_CRASHED_LAST (VIR_DOMAIN_CRASHED_UNKNOWN + 1)
431 VIR_ENUM_IMPL(virDomainCrashedReason, VIR_DOMAIN_CRASHED_LAST,
432               "unknown")
433
434 VIR_ENUM_IMPL(virDomainSeclabel, VIR_DOMAIN_SECLABEL_LAST,
435               "dynamic",
436               "static")
437
438 VIR_ENUM_IMPL(virDomainNetdevMacvtap, VIR_DOMAIN_NETDEV_MACVTAP_MODE_LAST,
439               "vepa",
440               "private",
441               "bridge",
442               "passthrough")
443
444 VIR_ENUM_IMPL(virVirtualPort, VIR_VIRTUALPORT_TYPE_LAST,
445               "none",
446               "802.1Qbg",
447               "802.1Qbh")
448
449 VIR_ENUM_IMPL(virDomainClockOffset, VIR_DOMAIN_CLOCK_OFFSET_LAST,
450               "utc",
451               "localtime",
452               "variable",
453               "timezone");
454
455 VIR_ENUM_IMPL(virDomainTimerName, VIR_DOMAIN_TIMER_NAME_LAST,
456               "platform",
457               "pit",
458               "rtc",
459               "hpet",
460               "tsc");
461
462 VIR_ENUM_IMPL(virDomainTimerTrack, VIR_DOMAIN_TIMER_TRACK_LAST,
463               "boot",
464               "guest",
465               "wall");
466
467 VIR_ENUM_IMPL(virDomainTimerTickpolicy, VIR_DOMAIN_TIMER_TICKPOLICY_LAST,
468               "delay",
469               "catchup",
470               "merge",
471               "discard");
472
473 VIR_ENUM_IMPL(virDomainTimerMode, VIR_DOMAIN_TIMER_MODE_LAST,
474               "auto",
475               "native",
476               "emulate",
477               "paravirt",
478               "smpsafe");
479
480 #define virDomainReportError(code, ...)                              \
481     virReportErrorHelper(VIR_FROM_DOMAIN, code, __FILE__,            \
482                          __FUNCTION__, __LINE__, __VA_ARGS__)
483
484 #define VIR_DOMAIN_XML_WRITE_FLAGS  VIR_DOMAIN_XML_SECURE
485 #define VIR_DOMAIN_XML_READ_FLAGS   VIR_DOMAIN_XML_INACTIVE
486
487 static void
488 virDomainObjListDataFree(void *payload, const void *name ATTRIBUTE_UNUSED)
489 {
490     virDomainObjPtr obj = payload;
491     virDomainObjLock(obj);
492     if (virDomainObjUnref(obj) > 0)
493         virDomainObjUnlock(obj);
494 }
495
496 int virDomainObjListInit(virDomainObjListPtr doms)
497 {
498     doms->objs = virHashCreate(50, virDomainObjListDataFree);
499     if (!doms->objs)
500         return -1;
501     return 0;
502 }
503
504
505 void virDomainObjListDeinit(virDomainObjListPtr doms)
506 {
507     virHashFree(doms->objs);
508 }
509
510
511 static int virDomainObjListSearchID(const void *payload,
512                                     const void *name ATTRIBUTE_UNUSED,
513                                     const void *data)
514 {
515     virDomainObjPtr obj = (virDomainObjPtr)payload;
516     const int *id = data;
517     int want = 0;
518
519     virDomainObjLock(obj);
520     if (virDomainObjIsActive(obj) &&
521         obj->def->id == *id)
522         want = 1;
523     virDomainObjUnlock(obj);
524     return want;
525 }
526
527 virDomainObjPtr virDomainFindByID(const virDomainObjListPtr doms,
528                                   int id)
529 {
530     virDomainObjPtr obj;
531     obj = virHashSearch(doms->objs, virDomainObjListSearchID, &id);
532     if (obj)
533         virDomainObjLock(obj);
534     return obj;
535 }
536
537
538 virDomainObjPtr virDomainFindByUUID(const virDomainObjListPtr doms,
539                                     const unsigned char *uuid)
540 {
541     char uuidstr[VIR_UUID_STRING_BUFLEN];
542     virDomainObjPtr obj;
543
544     virUUIDFormat(uuid, uuidstr);
545
546     obj = virHashLookup(doms->objs, uuidstr);
547     if (obj)
548         virDomainObjLock(obj);
549     return obj;
550 }
551
552 static int virDomainObjListSearchName(const void *payload,
553                                       const void *name ATTRIBUTE_UNUSED,
554                                       const void *data)
555 {
556     virDomainObjPtr obj = (virDomainObjPtr)payload;
557     int want = 0;
558
559     virDomainObjLock(obj);
560     if (STREQ(obj->def->name, (const char *)data))
561         want = 1;
562     virDomainObjUnlock(obj);
563     return want;
564 }
565
566 virDomainObjPtr virDomainFindByName(const virDomainObjListPtr doms,
567                                     const char *name)
568 {
569     virDomainObjPtr obj;
570     obj = virHashSearch(doms->objs, virDomainObjListSearchName, name);
571     if (obj)
572         virDomainObjLock(obj);
573     return obj;
574 }
575
576
577 bool virDomainObjTaint(virDomainObjPtr obj,
578                        enum virDomainTaintFlags taint)
579 {
580     int flag = (1 << taint);
581
582     if (obj->taint & flag)
583         return false;
584
585     obj->taint |= flag;
586     return true;
587 }
588
589
590 static void
591 virDomainGraphicsAuthDefClear(virDomainGraphicsAuthDefPtr def)
592 {
593     if (!def)
594         return;
595
596     VIR_FREE(def->passwd);
597
598     /* Don't free def */
599 }
600
601 void virDomainGraphicsDefFree(virDomainGraphicsDefPtr def)
602 {
603     if (!def)
604         return;
605
606     switch (def->type) {
607     case VIR_DOMAIN_GRAPHICS_TYPE_VNC:
608         VIR_FREE(def->data.vnc.listenAddr);
609         VIR_FREE(def->data.vnc.socket);
610         VIR_FREE(def->data.vnc.keymap);
611         virDomainGraphicsAuthDefClear(&def->data.vnc.auth);
612         break;
613
614     case VIR_DOMAIN_GRAPHICS_TYPE_SDL:
615         VIR_FREE(def->data.sdl.display);
616         VIR_FREE(def->data.sdl.xauth);
617         break;
618
619     case VIR_DOMAIN_GRAPHICS_TYPE_RDP:
620         VIR_FREE(def->data.rdp.listenAddr);
621         break;
622
623     case VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP:
624         VIR_FREE(def->data.desktop.display);
625         break;
626
627     case VIR_DOMAIN_GRAPHICS_TYPE_SPICE:
628         VIR_FREE(def->data.spice.listenAddr);
629         VIR_FREE(def->data.spice.keymap);
630         virDomainGraphicsAuthDefClear(&def->data.spice.auth);
631         break;
632     }
633
634     VIR_FREE(def);
635 }
636
637 void virDomainInputDefFree(virDomainInputDefPtr def)
638 {
639     if (!def)
640         return;
641
642     virDomainDeviceInfoClear(&def->info);
643     VIR_FREE(def);
644 }
645
646 static void virDomainLeaseDefFree(virDomainLeaseDefPtr def)
647 {
648     if (!def)
649         return;
650
651     VIR_FREE(def->lockspace);
652     VIR_FREE(def->key);
653     VIR_FREE(def->path);
654
655     VIR_FREE(def);
656 }
657
658 void virDomainDiskDefFree(virDomainDiskDefPtr def)
659 {
660     unsigned int i;
661
662     if (!def)
663         return;
664
665     VIR_FREE(def->serial);
666     VIR_FREE(def->src);
667     VIR_FREE(def->dst);
668     VIR_FREE(def->driverName);
669     VIR_FREE(def->driverType);
670     virStorageEncryptionFree(def->encryption);
671     virDomainDeviceInfoClear(&def->info);
672
673     for (i = 0 ; i < def->nhosts ; i++)
674         virDomainDiskHostDefFree(&def->hosts[i]);
675     VIR_FREE(def->hosts);
676
677     VIR_FREE(def);
678 }
679
680 void virDomainDiskHostDefFree(virDomainDiskHostDefPtr def)
681 {
682     if (!def)
683         return;
684
685     VIR_FREE(def->name);
686     VIR_FREE(def->port);
687 }
688
689 void virDomainControllerDefFree(virDomainControllerDefPtr def)
690 {
691     if (!def)
692         return;
693
694     virDomainDeviceInfoClear(&def->info);
695
696     VIR_FREE(def);
697 }
698
699 void virDomainFSDefFree(virDomainFSDefPtr def)
700 {
701     if (!def)
702         return;
703
704     VIR_FREE(def->src);
705     VIR_FREE(def->dst);
706     virDomainDeviceInfoClear(&def->info);
707
708     VIR_FREE(def);
709 }
710
711 void virDomainNetDefFree(virDomainNetDefPtr def)
712 {
713     if (!def)
714         return;
715
716     VIR_FREE(def->model);
717
718     switch (def->type) {
719     case VIR_DOMAIN_NET_TYPE_ETHERNET:
720         VIR_FREE(def->data.ethernet.dev);
721         VIR_FREE(def->data.ethernet.script);
722         VIR_FREE(def->data.ethernet.ipaddr);
723         break;
724
725     case VIR_DOMAIN_NET_TYPE_SERVER:
726     case VIR_DOMAIN_NET_TYPE_CLIENT:
727     case VIR_DOMAIN_NET_TYPE_MCAST:
728         VIR_FREE(def->data.socket.address);
729         break;
730
731     case VIR_DOMAIN_NET_TYPE_NETWORK:
732         VIR_FREE(def->data.network.name);
733         break;
734
735     case VIR_DOMAIN_NET_TYPE_BRIDGE:
736         VIR_FREE(def->data.bridge.brname);
737         VIR_FREE(def->data.bridge.script);
738         VIR_FREE(def->data.bridge.ipaddr);
739         break;
740
741     case VIR_DOMAIN_NET_TYPE_INTERNAL:
742         VIR_FREE(def->data.internal.name);
743         break;
744
745     case VIR_DOMAIN_NET_TYPE_DIRECT:
746         VIR_FREE(def->data.direct.linkdev);
747         break;
748
749     case VIR_DOMAIN_NET_TYPE_USER:
750     case VIR_DOMAIN_NET_TYPE_LAST:
751         break;
752     }
753
754     VIR_FREE(def->ifname);
755
756     virDomainDeviceInfoClear(&def->info);
757
758     VIR_FREE(def->filter);
759     virNWFilterHashTableFree(def->filterparams);
760
761     VIR_FREE(def);
762 }
763
764 static void ATTRIBUTE_NONNULL(1)
765 virDomainChrSourceDefClear(virDomainChrSourceDefPtr def)
766 {
767     switch (def->type) {
768     case VIR_DOMAIN_CHR_TYPE_PTY:
769     case VIR_DOMAIN_CHR_TYPE_DEV:
770     case VIR_DOMAIN_CHR_TYPE_FILE:
771     case VIR_DOMAIN_CHR_TYPE_PIPE:
772         VIR_FREE(def->data.file.path);
773         break;
774
775     case VIR_DOMAIN_CHR_TYPE_UDP:
776         VIR_FREE(def->data.udp.bindHost);
777         VIR_FREE(def->data.udp.bindService);
778         VIR_FREE(def->data.udp.connectHost);
779         VIR_FREE(def->data.udp.connectService);
780         break;
781
782     case VIR_DOMAIN_CHR_TYPE_TCP:
783         VIR_FREE(def->data.tcp.host);
784         VIR_FREE(def->data.tcp.service);
785         break;
786
787     case VIR_DOMAIN_CHR_TYPE_UNIX:
788         VIR_FREE(def->data.nix.path);
789         break;
790     }
791 }
792
793 void virDomainChrSourceDefFree(virDomainChrSourceDefPtr def)
794 {
795     if (!def)
796         return;
797
798     virDomainChrSourceDefClear(def);
799
800     VIR_FREE(def);
801 }
802
803 void virDomainChrDefFree(virDomainChrDefPtr def)
804 {
805     if (!def)
806         return;
807
808     switch (def->deviceType) {
809     case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
810         switch (def->targetType) {
811         case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_GUESTFWD:
812             VIR_FREE(def->target.addr);
813             break;
814
815         case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO:
816             VIR_FREE(def->target.name);
817             break;
818         }
819         break;
820
821     default:
822         break;
823     }
824
825     virDomainChrSourceDefClear(&def->source);
826     virDomainDeviceInfoClear(&def->info);
827
828     VIR_FREE(def);
829 }
830
831 void virDomainSmartcardDefFree(virDomainSmartcardDefPtr def)
832 {
833     size_t i;
834     if (!def)
835         return;
836
837     switch (def->type) {
838     case VIR_DOMAIN_SMARTCARD_TYPE_HOST:
839         break;
840
841     case VIR_DOMAIN_SMARTCARD_TYPE_HOST_CERTIFICATES:
842         for (i = 0; i < VIR_DOMAIN_SMARTCARD_NUM_CERTIFICATES; i++)
843             VIR_FREE(def->data.cert.file[i]);
844         VIR_FREE(def->data.cert.database);
845         break;
846
847     case VIR_DOMAIN_SMARTCARD_TYPE_PASSTHROUGH:
848         virDomainChrSourceDefClear(&def->data.passthru);
849         break;
850
851     default:
852         break;
853     }
854
855     virDomainDeviceInfoClear(&def->info);
856
857     VIR_FREE(def);
858 }
859
860 void virDomainSoundDefFree(virDomainSoundDefPtr def)
861 {
862     if (!def)
863         return;
864
865     virDomainDeviceInfoClear(&def->info);
866
867     VIR_FREE(def);
868 }
869
870 void virDomainMemballoonDefFree(virDomainMemballoonDefPtr def)
871 {
872     if (!def)
873         return;
874
875     virDomainDeviceInfoClear(&def->info);
876
877     VIR_FREE(def);
878 }
879
880 void virDomainWatchdogDefFree(virDomainWatchdogDefPtr def)
881 {
882     if (!def)
883         return;
884
885     virDomainDeviceInfoClear(&def->info);
886
887     VIR_FREE(def);
888 }
889
890 void virDomainVideoDefFree(virDomainVideoDefPtr def)
891 {
892     if (!def)
893         return;
894
895     virDomainDeviceInfoClear(&def->info);
896
897     VIR_FREE(def->accel);
898     VIR_FREE(def);
899 }
900
901 void virDomainHostdevDefFree(virDomainHostdevDefPtr def)
902 {
903     if (!def)
904         return;
905
906     virDomainDeviceInfoClear(&def->info);
907     VIR_FREE(def);
908 }
909
910 void virDomainDeviceDefFree(virDomainDeviceDefPtr def)
911 {
912     if (!def)
913         return;
914
915     switch (def->type) {
916     case VIR_DOMAIN_DEVICE_DISK:
917         virDomainDiskDefFree(def->data.disk);
918         break;
919     case VIR_DOMAIN_DEVICE_LEASE:
920         virDomainLeaseDefFree(def->data.lease);
921         break;
922     case VIR_DOMAIN_DEVICE_NET:
923         virDomainNetDefFree(def->data.net);
924         break;
925     case VIR_DOMAIN_DEVICE_INPUT:
926         virDomainInputDefFree(def->data.input);
927         break;
928     case VIR_DOMAIN_DEVICE_SOUND:
929         virDomainSoundDefFree(def->data.sound);
930         break;
931     case VIR_DOMAIN_DEVICE_VIDEO:
932         virDomainVideoDefFree(def->data.video);
933         break;
934     case VIR_DOMAIN_DEVICE_HOSTDEV:
935         virDomainHostdevDefFree(def->data.hostdev);
936         break;
937     case VIR_DOMAIN_DEVICE_WATCHDOG:
938         virDomainWatchdogDefFree(def->data.watchdog);
939         break;
940     case VIR_DOMAIN_DEVICE_CONTROLLER:
941         virDomainControllerDefFree(def->data.controller);
942         break;
943     case VIR_DOMAIN_DEVICE_GRAPHICS:
944         virDomainGraphicsDefFree(def->data.graphics);
945         break;
946     }
947
948     VIR_FREE(def);
949 }
950
951 void virSecurityLabelDefFree(virDomainDefPtr def);
952
953 void virSecurityLabelDefFree(virDomainDefPtr def)
954 {
955     VIR_FREE(def->seclabel.model);
956     VIR_FREE(def->seclabel.label);
957     VIR_FREE(def->seclabel.imagelabel);
958 }
959
960 static void
961 virDomainClockDefClear(virDomainClockDefPtr def)
962 {
963     if (def->offset == VIR_DOMAIN_CLOCK_OFFSET_TIMEZONE)
964         VIR_FREE(def->data.timezone);
965
966     int i;
967     for (i = 0; i < def->ntimers; i++)
968         VIR_FREE(def->timers[i]);
969     VIR_FREE(def->timers);
970 }
971
972 static void
973 virDomainVcpupinDefFree(virDomainVcpupinDefPtr *def,
974                         int nvcpupin)
975 {
976     int i;
977
978     if (!def || !nvcpupin)
979         return;
980
981     for(i = 0; i < nvcpupin; i++) {
982         VIR_FREE(def[i]->cpumask);
983         VIR_FREE(def[i]);
984     }
985
986     VIR_FREE(def);
987 }
988
989 void virDomainDefFree(virDomainDefPtr def)
990 {
991     unsigned int i;
992
993     if (!def)
994         return;
995
996     for (i = 0 ; i < def->nleases ; i++)
997         virDomainLeaseDefFree(def->leases[i]);
998     VIR_FREE(def->leases);
999
1000     for (i = 0 ; i < def->ngraphics ; i++)
1001         virDomainGraphicsDefFree(def->graphics[i]);
1002     VIR_FREE(def->graphics);
1003
1004     for (i = 0 ; i < def->ninputs ; i++)
1005         virDomainInputDefFree(def->inputs[i]);
1006     VIR_FREE(def->inputs);
1007
1008     for (i = 0 ; i < def->ndisks ; i++)
1009         virDomainDiskDefFree(def->disks[i]);
1010     VIR_FREE(def->disks);
1011
1012     for (i = 0 ; i < def->ncontrollers ; i++)
1013         virDomainControllerDefFree(def->controllers[i]);
1014     VIR_FREE(def->controllers);
1015
1016     for (i = 0 ; i < def->nfss ; i++)
1017         virDomainFSDefFree(def->fss[i]);
1018     VIR_FREE(def->fss);
1019
1020     for (i = 0 ; i < def->nnets ; i++)
1021         virDomainNetDefFree(def->nets[i]);
1022     VIR_FREE(def->nets);
1023
1024     for (i = 0 ; i < def->nsmartcards ; i++)
1025         virDomainSmartcardDefFree(def->smartcards[i]);
1026     VIR_FREE(def->smartcards);
1027
1028     for (i = 0 ; i < def->nserials ; i++)
1029         virDomainChrDefFree(def->serials[i]);
1030     VIR_FREE(def->serials);
1031
1032     for (i = 0 ; i < def->nparallels ; i++)
1033         virDomainChrDefFree(def->parallels[i]);
1034     VIR_FREE(def->parallels);
1035
1036     for (i = 0 ; i < def->nchannels ; i++)
1037         virDomainChrDefFree(def->channels[i]);
1038     VIR_FREE(def->channels);
1039
1040     virDomainChrDefFree(def->console);
1041
1042     for (i = 0 ; i < def->nsounds ; i++)
1043         virDomainSoundDefFree(def->sounds[i]);
1044     VIR_FREE(def->sounds);
1045
1046     for (i = 0 ; i < def->nvideos ; i++)
1047         virDomainVideoDefFree(def->videos[i]);
1048     VIR_FREE(def->videos);
1049
1050     for (i = 0 ; i < def->nhostdevs ; i++)
1051         virDomainHostdevDefFree(def->hostdevs[i]);
1052     VIR_FREE(def->hostdevs);
1053
1054     VIR_FREE(def->os.type);
1055     VIR_FREE(def->os.arch);
1056     VIR_FREE(def->os.machine);
1057     VIR_FREE(def->os.init);
1058     VIR_FREE(def->os.kernel);
1059     VIR_FREE(def->os.initrd);
1060     VIR_FREE(def->os.cmdline);
1061     VIR_FREE(def->os.root);
1062     VIR_FREE(def->os.loader);
1063     VIR_FREE(def->os.bootloader);
1064     VIR_FREE(def->os.bootloaderArgs);
1065
1066     virDomainClockDefClear(&def->clock);
1067
1068     VIR_FREE(def->name);
1069     VIR_FREE(def->cpumask);
1070     VIR_FREE(def->emulator);
1071     VIR_FREE(def->description);
1072
1073     virDomainWatchdogDefFree(def->watchdog);
1074
1075     virDomainMemballoonDefFree(def->memballoon);
1076
1077     virSecurityLabelDefFree(def);
1078
1079     virCPUDefFree(def->cpu);
1080
1081     virDomainVcpupinDefFree(def->cputune.vcpupin, def->cputune.nvcpupin);
1082
1083     virSysinfoDefFree(def->sysinfo);
1084
1085     if (def->namespaceData && def->ns.free)
1086         (def->ns.free)(def->namespaceData);
1087
1088     VIR_FREE(def);
1089 }
1090
1091 static void virDomainSnapshotObjListDeinit(virDomainSnapshotObjListPtr snapshots);
1092 static void virDomainObjFree(virDomainObjPtr dom)
1093 {
1094     if (!dom)
1095         return;
1096
1097     VIR_DEBUG("obj=%p", dom);
1098     virDomainDefFree(dom->def);
1099     virDomainDefFree(dom->newDef);
1100
1101     if (dom->privateDataFreeFunc)
1102         (dom->privateDataFreeFunc)(dom->privateData);
1103
1104     virMutexDestroy(&dom->lock);
1105
1106     virDomainSnapshotObjListDeinit(&dom->snapshots);
1107
1108     VIR_FREE(dom);
1109 }
1110
1111 void virDomainObjRef(virDomainObjPtr dom)
1112 {
1113     dom->refs++;
1114     VIR_DEBUG("obj=%p refs=%d", dom, dom->refs);
1115 }
1116
1117
1118 int virDomainObjUnref(virDomainObjPtr dom)
1119 {
1120     dom->refs--;
1121     VIR_DEBUG("obj=%p refs=%d", dom, dom->refs);
1122     if (dom->refs == 0) {
1123         virDomainObjUnlock(dom);
1124         virDomainObjFree(dom);
1125         return 0;
1126     }
1127     return dom->refs;
1128 }
1129
1130 static virDomainObjPtr virDomainObjNew(virCapsPtr caps)
1131 {
1132     virDomainObjPtr domain;
1133
1134     if (VIR_ALLOC(domain) < 0) {
1135         virReportOOMError();
1136         return NULL;
1137     }
1138
1139     if (caps->privateDataAllocFunc &&
1140         !(domain->privateData = (caps->privateDataAllocFunc)())) {
1141         virReportOOMError();
1142         VIR_FREE(domain);
1143         return NULL;
1144     }
1145     domain->privateDataFreeFunc = caps->privateDataFreeFunc;
1146
1147     if (virMutexInit(&domain->lock) < 0) {
1148         virDomainReportError(VIR_ERR_INTERNAL_ERROR,
1149                              "%s", _("cannot initialize mutex"));
1150         if (domain->privateDataFreeFunc)
1151             (domain->privateDataFreeFunc)(domain->privateData);
1152         VIR_FREE(domain);
1153         return NULL;
1154     }
1155
1156     virDomainObjLock(domain);
1157     virDomainObjSetState(domain, VIR_DOMAIN_SHUTOFF,
1158                                  VIR_DOMAIN_SHUTOFF_UNKNOWN);
1159     domain->refs = 1;
1160
1161     virDomainSnapshotObjListInit(&domain->snapshots);
1162
1163     VIR_DEBUG("obj=%p", domain);
1164     return domain;
1165 }
1166
1167 void virDomainObjAssignDef(virDomainObjPtr domain,
1168                            const virDomainDefPtr def,
1169                            bool live)
1170 {
1171     if (!virDomainObjIsActive(domain)) {
1172         if (live) {
1173             /* save current configuration to be restored on domain shutdown */
1174             if (!domain->newDef)
1175                 domain->newDef = domain->def;
1176             domain->def = def;
1177         } else {
1178             virDomainDefFree(domain->def);
1179             domain->def = def;
1180         }
1181     } else {
1182         virDomainDefFree(domain->newDef);
1183         domain->newDef = def;
1184     }
1185 }
1186
1187 virDomainObjPtr virDomainAssignDef(virCapsPtr caps,
1188                                    virDomainObjListPtr doms,
1189                                    const virDomainDefPtr def,
1190                                    bool live)
1191 {
1192     virDomainObjPtr domain;
1193     char uuidstr[VIR_UUID_STRING_BUFLEN];
1194
1195     if ((domain = virDomainFindByUUID(doms, def->uuid))) {
1196         virDomainObjAssignDef(domain, def, live);
1197         return domain;
1198     }
1199
1200     if (!(domain = virDomainObjNew(caps)))
1201         return NULL;
1202     domain->def = def;
1203
1204     virUUIDFormat(def->uuid, uuidstr);
1205     if (virHashAddEntry(doms->objs, uuidstr, domain) < 0) {
1206         VIR_FREE(domain);
1207         return NULL;
1208     }
1209
1210     return domain;
1211 }
1212
1213 /*
1214  * Mark the running VM config as transient. Ensures transient hotplug
1215  * operations do not persist past shutdown.
1216  *
1217  * @param caps pointer to capabilities info
1218  * @param domain domain object pointer
1219  * @param live if true, run this operation even for an inactive domain.
1220  *   this allows freely updated domain->def with runtime defaults before
1221  *   starting the VM, which will be discarded on VM shutdown. Any cleanup
1222  *   paths need to be sure to handle newDef if the domain is never started.
1223  * @return 0 on success, -1 on failure
1224  */
1225 int
1226 virDomainObjSetDefTransient(virCapsPtr caps,
1227                             virDomainObjPtr domain,
1228                             bool live)
1229 {
1230     int ret = -1;
1231     char *xml = NULL;
1232     virDomainDefPtr newDef = NULL;
1233
1234     if (!virDomainObjIsActive(domain) && !live)
1235         return 0;
1236
1237     if (!domain->persistent)
1238         return 0;
1239
1240     if (domain->newDef)
1241         return 0;
1242
1243     if (!(xml = virDomainDefFormat(domain->def, VIR_DOMAIN_XML_WRITE_FLAGS)))
1244         goto out;
1245
1246     if (!(newDef = virDomainDefParseString(caps, xml,
1247                                            VIR_DOMAIN_XML_READ_FLAGS)))
1248         goto out;
1249
1250     domain->newDef = newDef;
1251     ret = 0;
1252 out:
1253     VIR_FREE(xml);
1254     return ret;
1255 }
1256
1257 /*
1258  * Return the persistent domain configuration. If domain is transient,
1259  * return the running config.
1260  *
1261  * @param caps pointer to capabilities info
1262  * @param domain domain object pointer
1263  * @return NULL on error, virDOmainDefPtr on success
1264  */
1265 virDomainDefPtr
1266 virDomainObjGetPersistentDef(virCapsPtr caps,
1267                              virDomainObjPtr domain)
1268 {
1269     if (virDomainObjSetDefTransient(caps, domain, false) < 0)
1270         return NULL;
1271
1272     if (domain->newDef)
1273         return domain->newDef;
1274     else
1275         return domain->def;
1276 }
1277
1278 /*
1279  * The caller must hold a lock  on the driver owning 'doms',
1280  * and must also have locked 'dom', to ensure no one else
1281  * is either waiting for 'dom' or still usingn it
1282  */
1283 void virDomainRemoveInactive(virDomainObjListPtr doms,
1284                              virDomainObjPtr dom)
1285 {
1286     char uuidstr[VIR_UUID_STRING_BUFLEN];
1287     virUUIDFormat(dom->def->uuid, uuidstr);
1288
1289     virDomainObjUnlock(dom);
1290
1291     virHashRemoveEntry(doms->objs, uuidstr);
1292 }
1293
1294
1295 int virDomainDeviceAddressIsValid(virDomainDeviceInfoPtr info,
1296                                   int type)
1297 {
1298     if (info->type != type)
1299         return 0;
1300
1301     switch (info->type) {
1302     case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI:
1303         return virDomainDevicePCIAddressIsValid(&info->addr.pci);
1304
1305     case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE:
1306         return virDomainDeviceDriveAddressIsValid(&info->addr.drive);
1307     }
1308
1309     return 0;
1310 }
1311
1312
1313 int virDomainDevicePCIAddressIsValid(virDomainDevicePCIAddressPtr addr)
1314 {
1315     /* PCI bus has 32 slots and 8 functions per slot */
1316     if (addr->slot >= 32 || addr->function >= 8)
1317         return 0;
1318     return addr->domain || addr->bus || addr->slot;
1319 }
1320
1321
1322 int virDomainDeviceDriveAddressIsValid(virDomainDeviceDriveAddressPtr addr ATTRIBUTE_UNUSED)
1323 {
1324     /*return addr->controller || addr->bus || addr->unit;*/
1325     return 1; /* 0 is valid for all fields, so any successfully parsed addr is valid */
1326 }
1327
1328
1329 int virDomainDeviceVirtioSerialAddressIsValid(
1330     virDomainDeviceVirtioSerialAddressPtr addr ATTRIBUTE_UNUSED)
1331 {
1332     return 1; /* 0 is valid for all fields, so any successfully parsed addr is valid */
1333 }
1334
1335
1336 int virDomainDeviceInfoIsSet(virDomainDeviceInfoPtr info)
1337 {
1338     if (info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
1339         return 1;
1340     if (info->alias)
1341         return 1;
1342     return 0;
1343 }
1344
1345
1346 void virDomainDeviceInfoClear(virDomainDeviceInfoPtr info)
1347 {
1348     VIR_FREE(info->alias);
1349     memset(&info->addr, 0, sizeof(info->addr));
1350     info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE;
1351 }
1352
1353
1354 static int virDomainDeviceInfoClearAlias(virDomainDefPtr def ATTRIBUTE_UNUSED,
1355                                          virDomainDeviceInfoPtr info,
1356                                          void *opaque ATTRIBUTE_UNUSED)
1357 {
1358     VIR_FREE(info->alias);
1359     return 0;
1360 }
1361
1362 static int virDomainDeviceInfoClearPCIAddress(virDomainDefPtr def ATTRIBUTE_UNUSED,
1363                                               virDomainDeviceInfoPtr info,
1364                                               void *opaque ATTRIBUTE_UNUSED)
1365 {
1366     if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
1367         memset(&info->addr, 0, sizeof(info->addr));
1368         info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE;
1369     }
1370     return 0;
1371 }
1372
1373 int virDomainDeviceInfoIterate(virDomainDefPtr def,
1374                                virDomainDeviceInfoCallback cb,
1375                                void *opaque)
1376 {
1377     int i;
1378
1379     for (i = 0; i < def->ndisks ; i++)
1380         if (cb(def, &def->disks[i]->info, opaque) < 0)
1381             return -1;
1382     for (i = 0; i < def->nnets ; i++)
1383         if (cb(def, &def->nets[i]->info, opaque) < 0)
1384             return -1;
1385     for (i = 0; i < def->nsounds ; i++)
1386         if (cb(def, &def->sounds[i]->info, opaque) < 0)
1387             return -1;
1388     for (i = 0; i < def->nhostdevs ; i++)
1389         if (cb(def, &def->hostdevs[i]->info, opaque) < 0)
1390             return -1;
1391     for (i = 0; i < def->nvideos ; i++)
1392         if (cb(def, &def->videos[i]->info, opaque) < 0)
1393             return -1;
1394     for (i = 0; i < def->ncontrollers ; i++)
1395         if (cb(def, &def->controllers[i]->info, opaque) < 0)
1396             return -1;
1397     for (i = 0; i < def->nsmartcards ; i++)
1398         if (cb(def, &def->smartcards[i]->info, opaque) < 0)
1399             return -1;
1400     for (i = 0; i < def->nserials ; i++)
1401         if (cb(def, &def->serials[i]->info, opaque) < 0)
1402             return -1;
1403     for (i = 0; i < def->nparallels ; i++)
1404         if (cb(def, &def->parallels[i]->info, opaque) < 0)
1405             return -1;
1406     for (i = 0; i < def->nchannels ; i++)
1407         if (cb(def, &def->channels[i]->info, opaque) < 0)
1408             return -1;
1409     for (i = 0; i < def->ninputs ; i++)
1410         if (cb(def, &def->inputs[i]->info, opaque) < 0)
1411             return -1;
1412     for (i = 0; i < def->nfss ; i++)
1413         if (cb(def, &def->fss[i]->info, opaque) < 0)
1414             return -1;
1415     if (def->watchdog)
1416         if (cb(def, &def->watchdog->info, opaque) < 0)
1417             return -1;
1418     if (def->memballoon)
1419         if (cb(def, &def->memballoon->info, opaque) < 0)
1420             return -1;
1421     if (def->console)
1422         if (cb(def, &def->console->info, opaque) < 0)
1423             return -1;
1424     return 0;
1425 }
1426
1427
1428 void virDomainDefClearPCIAddresses(virDomainDefPtr def)
1429 {
1430     virDomainDeviceInfoIterate(def, virDomainDeviceInfoClearPCIAddress, NULL);
1431 }
1432
1433 void virDomainDefClearDeviceAliases(virDomainDefPtr def)
1434 {
1435     virDomainDeviceInfoIterate(def, virDomainDeviceInfoClearAlias, NULL);
1436 }
1437
1438
1439 /* Generate a string representation of a device address
1440  * @param address Device address to stringify
1441  */
1442 static int ATTRIBUTE_NONNULL(2)
1443 virDomainDeviceInfoFormat(virBufferPtr buf,
1444                           virDomainDeviceInfoPtr info,
1445                           int flags)
1446 {
1447     if (info->alias &&
1448         !(flags & VIR_DOMAIN_XML_INACTIVE)) {
1449         virBufferAsprintf(buf, "      <alias name='%s'/>\n", info->alias);
1450     }
1451
1452     if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
1453         return 0;
1454
1455     /* We'll be in domain/devices/[device type]/ so 3 level indent */
1456     virBufferAsprintf(buf, "      <address type='%s'",
1457                       virDomainDeviceAddressTypeToString(info->type));
1458
1459     switch (info->type) {
1460     case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI:
1461         virBufferAsprintf(buf, " domain='0x%.4x' bus='0x%.2x' slot='0x%.2x' function='0x%.1x'",
1462                           info->addr.pci.domain,
1463                           info->addr.pci.bus,
1464                           info->addr.pci.slot,
1465                           info->addr.pci.function);
1466         break;
1467
1468     case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE:
1469         virBufferAsprintf(buf, " controller='%d' bus='%d' unit='%d'",
1470                           info->addr.drive.controller,
1471                           info->addr.drive.bus,
1472                           info->addr.drive.unit);
1473         break;
1474
1475     case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_SERIAL:
1476         virBufferAsprintf(buf, " controller='%d' bus='%d' port='%d'",
1477                           info->addr.vioserial.controller,
1478                           info->addr.vioserial.bus,
1479                           info->addr.vioserial.port);
1480         break;
1481
1482     case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCID:
1483         virBufferAsprintf(buf, " controller='%d' slot='%d'",
1484                           info->addr.ccid.controller,
1485                           info->addr.ccid.slot);
1486         break;
1487
1488     default:
1489         virDomainReportError(VIR_ERR_INTERNAL_ERROR,
1490                              _("unknown address type '%d'"), info->type);
1491         return -1;
1492     }
1493
1494     virBufferAddLit(buf, "/>\n");
1495
1496     return 0;
1497 }
1498
1499
1500 static int
1501 virDomainDevicePCIAddressParseXML(xmlNodePtr node,
1502                                   virDomainDevicePCIAddressPtr addr)
1503 {
1504     char *domain, *slot, *bus, *function;
1505     int ret = -1;
1506
1507     memset(addr, 0, sizeof(*addr));
1508
1509     domain   = virXMLPropString(node, "domain");
1510     bus      = virXMLPropString(node, "bus");
1511     slot     = virXMLPropString(node, "slot");
1512     function = virXMLPropString(node, "function");
1513
1514     if (domain &&
1515         virStrToLong_ui(domain, NULL, 0, &addr->domain) < 0) {
1516         virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1517                              _("Cannot parse <address> 'domain' attribute"));
1518         goto cleanup;
1519     }
1520
1521     if (bus &&
1522         virStrToLong_ui(bus, NULL, 0, &addr->bus) < 0) {
1523         virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1524                              _("Cannot parse <address> 'bus' attribute"));
1525         goto cleanup;
1526     }
1527
1528     if (slot &&
1529         virStrToLong_ui(slot, NULL, 0, &addr->slot) < 0) {
1530         virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1531                              _("Cannot parse <address> 'slot' attribute"));
1532         goto cleanup;
1533     }
1534
1535     if (function &&
1536         virStrToLong_ui(function, NULL, 0, &addr->function) < 0) {
1537         virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1538                              _("Cannot parse <address> 'function' attribute"));
1539         goto cleanup;
1540     }
1541
1542     if (!virDomainDevicePCIAddressIsValid(addr)) {
1543         virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1544                              _("Insufficient specification for PCI address"));
1545         goto cleanup;
1546     }
1547
1548     ret = 0;
1549
1550 cleanup:
1551     VIR_FREE(domain);
1552     VIR_FREE(bus);
1553     VIR_FREE(slot);
1554     VIR_FREE(function);
1555     return ret;
1556 }
1557
1558
1559 static int
1560 virDomainDeviceDriveAddressParseXML(xmlNodePtr node,
1561                                     virDomainDeviceDriveAddressPtr addr)
1562 {
1563     char *bus, *unit, *controller;
1564     int ret = -1;
1565
1566     memset(addr, 0, sizeof(*addr));
1567
1568     controller = virXMLPropString(node, "controller");
1569     bus = virXMLPropString(node, "bus");
1570     unit = virXMLPropString(node, "unit");
1571
1572     if (controller &&
1573         virStrToLong_ui(controller, NULL, 10, &addr->controller) < 0) {
1574         virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1575                              _("Cannot parse <address> 'controller' attribute"));
1576         goto cleanup;
1577     }
1578
1579     if (bus &&
1580         virStrToLong_ui(bus, NULL, 10, &addr->bus) < 0) {
1581         virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1582                              _("Cannot parse <address> 'bus' attribute"));
1583         goto cleanup;
1584     }
1585
1586     if (unit &&
1587         virStrToLong_ui(unit, NULL, 10, &addr->unit) < 0) {
1588         virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1589                              _("Cannot parse <address> 'unit' attribute"));
1590         goto cleanup;
1591     }
1592
1593     if (!virDomainDeviceDriveAddressIsValid(addr)) {
1594         virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1595                              _("Insufficient specification for drive address"));
1596         goto cleanup;
1597     }
1598
1599     ret = 0;
1600
1601 cleanup:
1602     VIR_FREE(controller);
1603     VIR_FREE(bus);
1604     VIR_FREE(unit);
1605     return ret;
1606 }
1607
1608
1609 static int
1610 virDomainDeviceVirtioSerialAddressParseXML(
1611     xmlNodePtr node,
1612     virDomainDeviceVirtioSerialAddressPtr addr
1613 )
1614 {
1615     char *controller, *bus, *port;
1616     int ret = -1;
1617
1618     memset(addr, 0, sizeof(*addr));
1619
1620     controller = virXMLPropString(node, "controller");
1621     bus = virXMLPropString(node, "bus");
1622     port = virXMLPropString(node, "port");
1623
1624     if (controller &&
1625         virStrToLong_ui(controller, NULL, 10, &addr->controller) < 0) {
1626         virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1627                              _("Cannot parse <address> 'controller' attribute"));
1628         goto cleanup;
1629     }
1630
1631     if (bus &&
1632         virStrToLong_ui(bus, NULL, 10, &addr->bus) < 0) {
1633         virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1634                              _("Cannot parse <address> 'bus' attribute"));
1635         goto cleanup;
1636     }
1637
1638     if (port &&
1639         virStrToLong_ui(port, NULL, 10, &addr->port) < 0) {
1640         virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1641                              _("Cannot parse <address> 'port' attribute"));
1642         goto cleanup;
1643     }
1644
1645     if (!virDomainDeviceVirtioSerialAddressIsValid(addr)) {
1646         virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1647                              _("Insufficient specification for "
1648                                "virtio serial address"));
1649         goto cleanup;
1650     }
1651
1652     ret = 0;
1653
1654 cleanup:
1655     VIR_FREE(controller);
1656     VIR_FREE(bus);
1657     VIR_FREE(port);
1658     return ret;
1659 }
1660
1661 static int
1662 virDomainDeviceCcidAddressParseXML(xmlNodePtr node,
1663                                    virDomainDeviceCcidAddressPtr addr)
1664 {
1665     char *controller, *slot;
1666     int ret = -1;
1667
1668     memset(addr, 0, sizeof(*addr));
1669
1670     controller = virXMLPropString(node, "controller");
1671     slot = virXMLPropString(node, "slot");
1672
1673     if (controller &&
1674         virStrToLong_ui(controller, NULL, 10, &addr->controller) < 0) {
1675         virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1676                              _("Cannot parse <address> 'controller' attribute"));
1677         goto cleanup;
1678     }
1679
1680     if (slot &&
1681         virStrToLong_ui(slot, NULL, 10, &addr->slot) < 0) {
1682         virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1683                              _("Cannot parse <address> 'slot' attribute"));
1684         goto cleanup;
1685     }
1686
1687     ret = 0;
1688
1689 cleanup:
1690     VIR_FREE(controller);
1691     VIR_FREE(slot);
1692     return ret;
1693 }
1694
1695 /* Parse the XML definition for a device address
1696  * @param node XML nodeset to parse for device address definition
1697  */
1698 static int
1699 virDomainDeviceInfoParseXML(xmlNodePtr node,
1700                             virDomainDeviceInfoPtr info,
1701                             int flags)
1702 {
1703     xmlNodePtr cur;
1704     xmlNodePtr address = NULL;
1705     xmlNodePtr alias = NULL;
1706     char *type = NULL;
1707     int ret = -1;
1708
1709     virDomainDeviceInfoClear(info);
1710
1711     cur = node->children;
1712     while (cur != NULL) {
1713         if (cur->type == XML_ELEMENT_NODE) {
1714             if (alias == NULL &&
1715                 !(flags & VIR_DOMAIN_XML_INACTIVE) &&
1716                 xmlStrEqual(cur->name, BAD_CAST "alias")) {
1717                 alias = cur;
1718             } else if (address == NULL &&
1719                        xmlStrEqual(cur->name, BAD_CAST "address")) {
1720                 address = cur;
1721             }
1722         }
1723         cur = cur->next;
1724     }
1725
1726     if (alias)
1727         info->alias = virXMLPropString(alias, "name");
1728
1729     if (!address)
1730         return 0;
1731
1732     type = virXMLPropString(address, "type");
1733
1734     if (type) {
1735         if ((info->type = virDomainDeviceAddressTypeFromString(type)) < 0) {
1736             virDomainReportError(VIR_ERR_INTERNAL_ERROR,
1737                                  _("unknown address type '%s'"), type);
1738             goto cleanup;
1739         }
1740     } else {
1741         virDomainReportError(VIR_ERR_INTERNAL_ERROR,
1742                              "%s", _("No type specified for device address"));
1743         goto cleanup;
1744     }
1745
1746     switch (info->type) {
1747     case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI:
1748         if (virDomainDevicePCIAddressParseXML(address, &info->addr.pci) < 0)
1749             goto cleanup;
1750         break;
1751
1752     case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE:
1753         if (virDomainDeviceDriveAddressParseXML(address, &info->addr.drive) < 0)
1754             goto cleanup;
1755         break;
1756
1757     case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_SERIAL:
1758         if (virDomainDeviceVirtioSerialAddressParseXML
1759                 (address, &info->addr.vioserial) < 0)
1760             goto cleanup;
1761         break;
1762
1763     case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCID:
1764         if (virDomainDeviceCcidAddressParseXML(address, &info->addr.ccid) < 0)
1765             goto cleanup;
1766         break;
1767
1768     default:
1769         /* Should not happen */
1770         virDomainReportError(VIR_ERR_INTERNAL_ERROR,
1771                              "%s", _("Unknown device address type"));
1772         goto cleanup;
1773     }
1774
1775     ret = 0;
1776
1777 cleanup:
1778     if (ret == -1)
1779         VIR_FREE(info->alias);
1780     VIR_FREE(type);
1781     return ret;
1782 }
1783
1784 static int
1785 virDomainDeviceBootParseXML(xmlNodePtr node,
1786                             int *bootIndex,
1787                             virBitmapPtr bootMap)
1788 {
1789     char *order;
1790     int boot;
1791     int ret = -1;
1792
1793     order = virXMLPropString(node, "order");
1794     if (!order) {
1795         virDomainReportError(VIR_ERR_INTERNAL_ERROR,
1796                             "%s", _("missing boot order attribute"));
1797         goto cleanup;
1798     } else if (virStrToLong_i(order, NULL, 10, &boot) < 0 ||
1799                boot <= 0) {
1800         virDomainReportError(VIR_ERR_INTERNAL_ERROR,
1801                 _("incorrect boot order '%s', expecting positive integer"),
1802                 order);
1803         goto cleanup;
1804     }
1805
1806     if (bootMap) {
1807         bool set;
1808         if (virBitmapGetBit(bootMap, boot - 1, &set) < 0) {
1809             virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1810                     _("boot orders have to be contiguous and starting from 1"));
1811             goto cleanup;
1812         } else if (set) {
1813             virDomainReportError(VIR_ERR_INTERNAL_ERROR,
1814                     _("boot order %d used for more than one device"), boot);
1815             goto cleanup;
1816         }
1817         ignore_value(virBitmapSetBit(bootMap, boot - 1));
1818     }
1819
1820     *bootIndex = boot;
1821     ret = 0;
1822
1823 cleanup:
1824     VIR_FREE(order);
1825     return ret;
1826 }
1827
1828 static int
1829 virDomainParseLegacyDeviceAddress(char *devaddr,
1830                                   virDomainDevicePCIAddressPtr pci)
1831 {
1832     char *tmp;
1833
1834     /* expected format: <domain>:<bus>:<slot> */
1835     if (/* domain */
1836         virStrToLong_ui(devaddr, &tmp, 16, &pci->domain) < 0 || *tmp != ':' ||
1837         /* bus */
1838         virStrToLong_ui(tmp + 1, &tmp, 16, &pci->bus) < 0 || *tmp != ':' ||
1839         /* slot */
1840         virStrToLong_ui(tmp + 1, NULL, 16, &pci->slot) < 0)
1841         return -1;
1842
1843     return 0;
1844 }
1845
1846 int
1847 virDomainDiskDefAssignAddress(virCapsPtr caps, virDomainDiskDefPtr def)
1848 {
1849     int idx = virDiskNameToIndex(def->dst);
1850     if (idx < 0)
1851         return -1;
1852
1853     switch (def->bus) {
1854     case VIR_DOMAIN_DISK_BUS_SCSI:
1855         def->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE;
1856
1857         if (caps->hasWideScsiBus) {
1858             /* For a wide SCSI bus we define the default mapping to be
1859              * 16 units per bus, 1 bus per controller, many controllers.
1860              * Unit 7 is the SCSI controller itself. Therefore unit 7
1861              * cannot be assigned to disks and is skipped.
1862              */
1863             def->info.addr.drive.controller = idx / 15;
1864             def->info.addr.drive.bus = 0;
1865             def->info.addr.drive.unit = idx % 15;
1866
1867             /* Skip the SCSI controller at unit 7 */
1868             if (def->info.addr.drive.unit >= 7) {
1869                 ++def->info.addr.drive.unit;
1870             }
1871         } else {
1872             /* For a narrow SCSI bus we define the default mapping to be
1873              * 7 units per bus, 1 bus per controller, many controllers */
1874             def->info.addr.drive.controller = idx / 7;
1875             def->info.addr.drive.bus = 0;
1876             def->info.addr.drive.unit = idx % 7;
1877         }
1878
1879         break;
1880
1881     case VIR_DOMAIN_DISK_BUS_IDE:
1882         /* For IDE we define the default mapping to be 2 units
1883          * per bus, 2 bus per controller, many controllers */
1884         def->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE;
1885         def->info.addr.drive.controller = idx / 4;
1886         def->info.addr.drive.bus = (idx % 4) / 2;
1887         def->info.addr.drive.unit = (idx % 2);
1888         break;
1889
1890     case VIR_DOMAIN_DISK_BUS_FDC:
1891         /* For FDC we define the default mapping to be 2 units
1892          * per bus, 1 bus per controller, many controllers */
1893         def->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE;
1894         def->info.addr.drive.controller = idx / 2;
1895         def->info.addr.drive.bus = 0;
1896         def->info.addr.drive.unit = idx % 2;
1897         break;
1898
1899     default:
1900         /* Other disk bus's aren't controller based */
1901         break;
1902     }
1903
1904     return 0;
1905 }
1906
1907 /* Parse the XML definition for a lease
1908  */
1909 static virDomainLeaseDefPtr
1910 virDomainLeaseDefParseXML(xmlNodePtr node)
1911 {
1912     virDomainLeaseDefPtr def;
1913     xmlNodePtr cur;
1914     char *lockspace = NULL;
1915     char *key = NULL;
1916     char *path = NULL;
1917     char *offset = NULL;
1918
1919     if (VIR_ALLOC(def) < 0) {
1920         virReportOOMError();
1921         return NULL;
1922     }
1923
1924     cur = node->children;
1925     while (cur != NULL) {
1926         if (cur->type == XML_ELEMENT_NODE) {
1927             if ((key == NULL) &&
1928                 (xmlStrEqual(cur->name, BAD_CAST "key"))) {
1929                 key = (char *)xmlNodeGetContent(cur);
1930             } else if ((lockspace == NULL) &&
1931                 (xmlStrEqual(cur->name, BAD_CAST "lockspace"))) {
1932                 lockspace = (char *)xmlNodeGetContent(cur);
1933             } else if ((path == NULL) &&
1934                        (xmlStrEqual(cur->name, BAD_CAST "target"))) {
1935                 path = virXMLPropString(cur, "path");
1936                 offset = virXMLPropString(cur, "offset");
1937             }
1938         }
1939         cur = cur->next;
1940     }
1941
1942     if (!key) {
1943         virDomainReportError(VIR_ERR_XML_ERROR, "%s",
1944                              _("Missing 'key' element for lease"));
1945         goto error;
1946     }
1947     if (!path) {
1948         virDomainReportError(VIR_ERR_XML_ERROR, "%s",
1949                              _("Missing 'target' element for lease"));
1950         goto error;
1951     }
1952
1953     if (offset &&
1954         virStrToLong_ull(offset, NULL, 10, &def->offset) < 0) {
1955         virDomainReportError(VIR_ERR_XML_ERROR,
1956                              _("Malformed lease target offset %s"), offset);
1957         goto error;
1958     }
1959
1960     def->key = key;
1961     def->lockspace = lockspace;
1962     def->path = path;
1963     path = key = lockspace = NULL;
1964
1965 cleanup:
1966     VIR_FREE(lockspace);
1967     VIR_FREE(key);
1968     VIR_FREE(path);
1969     VIR_FREE(offset);
1970
1971     return def;
1972
1973  error:
1974     virDomainLeaseDefFree(def);
1975     def = NULL;
1976     goto cleanup;
1977 }
1978
1979
1980 /* Parse the XML definition for a disk
1981  * @param node XML nodeset to parse for disk definition
1982  */
1983 static virDomainDiskDefPtr
1984 virDomainDiskDefParseXML(virCapsPtr caps,
1985                          xmlNodePtr node,
1986                          virBitmapPtr bootMap,
1987                          int flags)
1988 {
1989     virDomainDiskDefPtr def;
1990     xmlNodePtr cur, host;
1991     char *type = NULL;
1992     char *device = NULL;
1993     char *driverName = NULL;
1994     char *driverType = NULL;
1995     char *source = NULL;
1996     char *target = NULL;
1997     char *protocol = NULL;
1998     virDomainDiskHostDefPtr hosts = NULL;
1999     int nhosts = 0;
2000     char *bus = NULL;
2001     char *cachetag = NULL;
2002     char *error_policy = NULL;
2003     char *iotag = NULL;
2004     char *devaddr = NULL;
2005     virStorageEncryptionPtr encryption = NULL;
2006     char *serial = NULL;
2007
2008     if (VIR_ALLOC(def) < 0) {
2009         virReportOOMError();
2010         return NULL;
2011     }
2012
2013     type = virXMLPropString(node, "type");
2014     if (type) {
2015         if ((def->type = virDomainDiskTypeFromString(type)) < 0) {
2016             virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2017                                  _("unknown disk type '%s'"), type);
2018             goto error;
2019         }
2020     } else {
2021         def->type = VIR_DOMAIN_DISK_TYPE_FILE;
2022     }
2023
2024     cur = node->children;
2025     while (cur != NULL) {
2026         if (cur->type == XML_ELEMENT_NODE) {
2027             if ((source == NULL && hosts == NULL) &&
2028                 (xmlStrEqual(cur->name, BAD_CAST "source"))) {
2029
2030                 switch (def->type) {
2031                 case VIR_DOMAIN_DISK_TYPE_FILE:
2032                     source = virXMLPropString(cur, "file");
2033                     break;
2034                 case VIR_DOMAIN_DISK_TYPE_BLOCK:
2035                     source = virXMLPropString(cur, "dev");
2036                     break;
2037                 case VIR_DOMAIN_DISK_TYPE_DIR:
2038                     source = virXMLPropString(cur, "dir");
2039                     break;
2040                 case VIR_DOMAIN_DISK_TYPE_NETWORK:
2041                     protocol = virXMLPropString(cur, "protocol");
2042                     if (protocol == NULL) {
2043                         virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2044                                              "%s", _("missing protocol type"));
2045                         goto error;
2046                     }
2047                     def->protocol = virDomainDiskProtocolTypeFromString(protocol);
2048                     if (def->protocol < 0) {
2049                         virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2050                                              _("unknown protocol type '%s'"),
2051                                              protocol);
2052                         goto error;
2053                     }
2054                     if (!(source = virXMLPropString(cur, "name")) &&
2055                         def->protocol != VIR_DOMAIN_DISK_PROTOCOL_NBD) {
2056                         virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2057                                              _("missing name for disk source"));
2058                         goto error;
2059                     }
2060                     host = cur->children;
2061                     while (host != NULL) {
2062                         if (host->type == XML_ELEMENT_NODE &&
2063                             xmlStrEqual(host->name, BAD_CAST "host")) {
2064                             if (VIR_REALLOC_N(hosts, nhosts + 1) < 0) {
2065                                 virReportOOMError();
2066                                 goto error;
2067                             }
2068                             hosts[nhosts].name = NULL;
2069                             hosts[nhosts].port = NULL;
2070                             nhosts++;
2071
2072                             hosts[nhosts - 1].name = virXMLPropString(host, "name");
2073                             if (!hosts[nhosts - 1].name) {
2074                                 virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2075                                                      "%s", _("missing name for host"));
2076                                 goto error;
2077                             }
2078                             hosts[nhosts - 1].port = virXMLPropString(host, "port");
2079                             if (!hosts[nhosts - 1].port) {
2080                                 virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2081                                                      "%s", _("missing port for host"));
2082                                 goto error;
2083                             }
2084                         }
2085                         host = host->next;
2086                     }
2087                     break;
2088                 default:
2089                     virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2090                                          _("unexpected disk type %s"),
2091                                          virDomainDiskTypeToString(def->type));
2092                     goto error;
2093                 }
2094
2095                 /* People sometimes pass a bogus '' source path
2096                    when they mean to omit the source element
2097                    completely. eg CDROM without media. This is
2098                    just a little compatability check to help
2099                    those broken apps */
2100                 if (source && STREQ(source, ""))
2101                     VIR_FREE(source);
2102             } else if ((target == NULL) &&
2103                        (xmlStrEqual(cur->name, BAD_CAST "target"))) {
2104                 target = virXMLPropString(cur, "dev");
2105                 bus = virXMLPropString(cur, "bus");
2106
2107                 /* HACK: Work around for compat with Xen
2108                  * driver in previous libvirt releases */
2109                 if (target &&
2110                     STRPREFIX(target, "ioemu:"))
2111                     memmove(target, target+6, strlen(target)-5);
2112             } else if ((driverName == NULL) &&
2113                        (xmlStrEqual(cur->name, BAD_CAST "driver"))) {
2114                 driverName = virXMLPropString(cur, "name");
2115                 driverType = virXMLPropString(cur, "type");
2116                 cachetag = virXMLPropString(cur, "cache");
2117                 error_policy = virXMLPropString(cur, "error_policy");
2118                 iotag = virXMLPropString(cur, "io");
2119             } else if (xmlStrEqual(cur->name, BAD_CAST "readonly")) {
2120                 def->readonly = 1;
2121             } else if (xmlStrEqual(cur->name, BAD_CAST "shareable")) {
2122                 def->shared = 1;
2123             } else if ((flags & VIR_DOMAIN_XML_INTERNAL_STATUS) &&
2124                        xmlStrEqual(cur->name, BAD_CAST "state")) {
2125                 /* Legacy back-compat. Don't add any more attributes here */
2126                 devaddr = virXMLPropString(cur, "devaddr");
2127             } else if (encryption == NULL &&
2128                        xmlStrEqual(cur->name, BAD_CAST "encryption")) {
2129                 encryption = virStorageEncryptionParseNode(node->doc,
2130                                                            cur);
2131                 if (encryption == NULL)
2132                     goto error;
2133             } else if ((serial == NULL) &&
2134                        (xmlStrEqual(cur->name, BAD_CAST "serial"))) {
2135                 serial = (char *)xmlNodeGetContent(cur);
2136             } else if (xmlStrEqual(cur->name, BAD_CAST "boot")) {
2137                 if (virDomainDeviceBootParseXML(cur, &def->bootIndex,
2138                                                 bootMap))
2139                     goto error;
2140             }
2141         }
2142         cur = cur->next;
2143     }
2144
2145     device = virXMLPropString(node, "device");
2146     if (device) {
2147         if ((def->device = virDomainDiskDeviceTypeFromString(device)) < 0) {
2148             virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2149                                  _("unknown disk device '%s'"), device);
2150             goto error;
2151         }
2152     } else {
2153         def->device = VIR_DOMAIN_DISK_DEVICE_DISK;
2154     }
2155
2156     /* Only CDROM and Floppy devices are allowed missing source path
2157      * to indicate no media present */
2158     if (source == NULL && hosts == NULL &&
2159         def->device != VIR_DOMAIN_DISK_DEVICE_CDROM &&
2160         def->device != VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
2161         virDomainReportError(VIR_ERR_NO_SOURCE,
2162                              target ? "%s" : NULL, target);
2163         goto error;
2164     }
2165
2166     if (target == NULL) {
2167         virDomainReportError(VIR_ERR_NO_TARGET,
2168                              source ? "%s" : NULL, source);
2169         goto error;
2170     }
2171
2172     if (def->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY &&
2173         !STRPREFIX(target, "fd")) {
2174         virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2175                              _("Invalid floppy device name: %s"), target);
2176         goto error;
2177     }
2178
2179     /* Force CDROM to be listed as read only */
2180     if (def->device == VIR_DOMAIN_DISK_DEVICE_CDROM)
2181         def->readonly = 1;
2182
2183     if (def->device == VIR_DOMAIN_DISK_DEVICE_DISK &&
2184         !STRPREFIX((const char *)target, "hd") &&
2185         !STRPREFIX((const char *)target, "sd") &&
2186         !STRPREFIX((const char *)target, "vd") &&
2187         !STRPREFIX((const char *)target, "xvd") &&
2188         !STRPREFIX((const char *)target, "ubd")) {
2189         virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2190                              _("Invalid harddisk device name: %s"), target);
2191         goto error;
2192     }
2193
2194     if (bus) {
2195         if ((def->bus = virDomainDiskBusTypeFromString(bus)) < 0) {
2196             virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2197                                  _("unknown disk bus type '%s'"), bus);
2198             goto error;
2199         }
2200     } else {
2201         if (def->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
2202             def->bus = VIR_DOMAIN_DISK_BUS_FDC;
2203         } else {
2204             if (STRPREFIX(target, "hd"))
2205                 def->bus = VIR_DOMAIN_DISK_BUS_IDE;
2206             else if (STRPREFIX(target, "sd"))
2207                 def->bus = VIR_DOMAIN_DISK_BUS_SCSI;
2208             else if (STRPREFIX(target, "vd"))
2209                 def->bus = VIR_DOMAIN_DISK_BUS_VIRTIO;
2210             else if (STRPREFIX(target, "xvd"))
2211                 def->bus = VIR_DOMAIN_DISK_BUS_XEN;
2212             else if (STRPREFIX(target, "ubd"))
2213                 def->bus = VIR_DOMAIN_DISK_BUS_UML;
2214             else
2215                 def->bus = VIR_DOMAIN_DISK_BUS_IDE;
2216         }
2217     }
2218
2219     if (def->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY &&
2220         def->bus != VIR_DOMAIN_DISK_BUS_FDC) {
2221         virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2222                              _("Invalid bus type '%s' for floppy disk"), bus);
2223         goto error;
2224     }
2225     if (def->device != VIR_DOMAIN_DISK_DEVICE_FLOPPY &&
2226         def->bus == VIR_DOMAIN_DISK_BUS_FDC) {
2227         virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2228                              _("Invalid bus type '%s' for disk"), bus);
2229         goto error;
2230     }
2231
2232     if (cachetag &&
2233         (def->cachemode = virDomainDiskCacheTypeFromString(cachetag)) < 0) {
2234         virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2235                              _("unknown disk cache mode '%s'"), cachetag);
2236         goto error;
2237     }
2238
2239     if (error_policy &&
2240         (def->error_policy = virDomainDiskErrorPolicyTypeFromString(error_policy)) < 0) {
2241         virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2242                              _("unknown disk error policy '%s'"), error_policy);
2243         goto error;
2244     }
2245
2246     if (iotag) {
2247         if ((def->iomode = virDomainDiskIoTypeFromString(iotag)) < 0 ||
2248             def->iomode == VIR_DOMAIN_DISK_IO_DEFAULT) {
2249             virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2250                                  _("unknown disk io mode '%s'"), iotag);
2251             goto error;
2252         }
2253     }
2254
2255     if (devaddr) {
2256         if (virDomainParseLegacyDeviceAddress(devaddr,
2257                                               &def->info.addr.pci) < 0) {
2258             virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2259                                  _("Unable to parse devaddr parameter '%s'"),
2260                                  devaddr);
2261             goto error;
2262         }
2263         def->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
2264     } else {
2265         if (virDomainDeviceInfoParseXML(node, &def->info, flags) < 0)
2266             goto error;
2267     }
2268
2269     def->src = source;
2270     source = NULL;
2271     def->dst = target;
2272     target = NULL;
2273     def->hosts = hosts;
2274     hosts = NULL;
2275     def->nhosts = nhosts;
2276     nhosts = 0;
2277     def->driverName = driverName;
2278     driverName = NULL;
2279     def->driverType = driverType;
2280     driverType = NULL;
2281     def->encryption = encryption;
2282     encryption = NULL;
2283     def->serial = serial;
2284     serial = NULL;
2285
2286     if (!def->driverType &&
2287         caps->defaultDiskDriverType &&
2288         !(def->driverType = strdup(caps->defaultDiskDriverType)))
2289         goto no_memory;
2290
2291     if (!def->driverName &&
2292         caps->defaultDiskDriverName &&
2293         !(def->driverName = strdup(caps->defaultDiskDriverName)))
2294         goto no_memory;
2295
2296     if (def->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE
2297         && virDomainDiskDefAssignAddress(caps, def) < 0)
2298         goto error;
2299
2300 cleanup:
2301     VIR_FREE(bus);
2302     VIR_FREE(type);
2303     VIR_FREE(target);
2304     VIR_FREE(source);
2305     while (nhosts > 0) {
2306         virDomainDiskHostDefFree(&hosts[nhosts - 1]);
2307         nhosts--;
2308     }
2309     VIR_FREE(hosts);
2310     VIR_FREE(protocol);
2311     VIR_FREE(device);
2312     VIR_FREE(driverType);
2313     VIR_FREE(driverName);
2314     VIR_FREE(cachetag);
2315     VIR_FREE(error_policy);
2316     VIR_FREE(iotag);
2317     VIR_FREE(devaddr);
2318     VIR_FREE(serial);
2319     virStorageEncryptionFree(encryption);
2320
2321     return def;
2322
2323 no_memory:
2324     virReportOOMError();
2325
2326  error:
2327     virDomainDiskDefFree(def);
2328     def = NULL;
2329     goto cleanup;
2330 }
2331
2332
2333 /* Parse the XML definition for a controller
2334  * @param node XML nodeset to parse for controller definition
2335  */
2336 static virDomainControllerDefPtr
2337 virDomainControllerDefParseXML(xmlNodePtr node,
2338                                int flags)
2339 {
2340     virDomainControllerDefPtr def;
2341     char *type = NULL;
2342     char *idx = NULL;
2343     char *model = NULL;
2344
2345     if (VIR_ALLOC(def) < 0) {
2346         virReportOOMError();
2347         return NULL;
2348     }
2349
2350     type = virXMLPropString(node, "type");
2351     if (type) {
2352         if ((def->type = virDomainControllerTypeFromString(type)) < 0) {
2353             virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2354                                  _("Unknown controller type '%s'"), type);
2355             goto error;
2356         }
2357     }
2358
2359     idx = virXMLPropString(node, "index");
2360     if (idx) {
2361         if (virStrToLong_i(idx, NULL, 10, &def->idx) < 0) {
2362             virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2363                                  _("Cannot parse controller index %s"), idx);
2364             goto error;
2365         }
2366     }
2367
2368     model = virXMLPropString(node, "model");
2369     if (model) {
2370         if ((def->model = virDomainControllerModelTypeFromString(model)) < 0) {
2371             virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2372                                  _("Unknown model type '%s'"), model);
2373             goto error;
2374         }
2375     } else {
2376         def->model = -1;
2377     }
2378
2379     if (virDomainDeviceInfoParseXML(node, &def->info, flags) < 0)
2380         goto error;
2381
2382     switch (def->type) {
2383     case VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL: {
2384         char *ports = virXMLPropString(node, "ports");
2385         if (ports) {
2386             int r = virStrToLong_i(ports, NULL, 10,
2387                                    &def->opts.vioserial.ports);
2388             if (r != 0 || def->opts.vioserial.ports < 0) {
2389                 virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2390                                      _("Invalid ports: %s"), ports);
2391                 VIR_FREE(ports);
2392                 goto error;
2393             }
2394         } else {
2395             def->opts.vioserial.ports = -1;
2396         }
2397         VIR_FREE(ports);
2398
2399         char *vectors = virXMLPropString(node, "vectors");
2400         if (vectors) {
2401             int r = virStrToLong_i(vectors, NULL, 10,
2402                                    &def->opts.vioserial.vectors);
2403             if (r != 0 || def->opts.vioserial.vectors < 0) {
2404                 virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2405                                      _("Invalid vectors: %s"), vectors);
2406                 VIR_FREE(vectors);
2407                 goto error;
2408             }
2409         } else {
2410             def->opts.vioserial.vectors = -1;
2411         }
2412         VIR_FREE(vectors);
2413         break;
2414     }
2415
2416     default:
2417         break;
2418     }
2419
2420     if (def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
2421         def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
2422         virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2423                              _("Controllers must use the 'pci' address type"));
2424         goto error;
2425     }
2426
2427 cleanup:
2428     VIR_FREE(type);
2429     VIR_FREE(idx);
2430     VIR_FREE(model);
2431
2432     return def;
2433
2434  error:
2435     virDomainControllerDefFree(def);
2436     def = NULL;
2437     goto cleanup;
2438 }
2439
2440 /* Parse the XML definition for a disk
2441  * @param node XML nodeset to parse for disk definition
2442  */
2443 static virDomainFSDefPtr
2444 virDomainFSDefParseXML(xmlNodePtr node,
2445                        int flags) {
2446     virDomainFSDefPtr def;
2447     xmlNodePtr cur;
2448     char *type = NULL;
2449     char *source = NULL;
2450     char *target = NULL;
2451     char *accessmode = NULL;
2452
2453     if (VIR_ALLOC(def) < 0) {
2454         virReportOOMError();
2455         return NULL;
2456     }
2457
2458     type = virXMLPropString(node, "type");
2459     if (type) {
2460         if ((def->type = virDomainFSTypeFromString(type)) < 0) {
2461             virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2462                                  _("unknown filesystem type '%s'"), type);
2463             goto error;
2464         }
2465     } else {
2466         def->type = VIR_DOMAIN_FS_TYPE_MOUNT;
2467     }
2468
2469     accessmode = virXMLPropString(node, "accessmode");
2470     if (accessmode) {
2471         if ((def->accessmode = virDomainFSAccessModeTypeFromString(accessmode)) < 0) {
2472             virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2473                                  _("unknown accessmode '%s'"), accessmode);
2474             goto error;
2475         }
2476     } else {
2477         def->accessmode = VIR_DOMAIN_FS_ACCESSMODE_PASSTHROUGH;
2478     }
2479
2480     cur = node->children;
2481     while (cur != NULL) {
2482         if (cur->type == XML_ELEMENT_NODE) {
2483             if ((source == NULL) &&
2484                 (xmlStrEqual(cur->name, BAD_CAST "source"))) {
2485
2486                 if (def->type == VIR_DOMAIN_FS_TYPE_MOUNT)
2487                     source = virXMLPropString(cur, "dir");
2488                 else if (def->type == VIR_DOMAIN_FS_TYPE_FILE)
2489                     source = virXMLPropString(cur, "file");
2490                 else if (def->type == VIR_DOMAIN_FS_TYPE_BLOCK)
2491                     source = virXMLPropString(cur, "dev");
2492                 else if (def->type == VIR_DOMAIN_FS_TYPE_TEMPLATE)
2493                     source = virXMLPropString(cur, "name");
2494             } else if ((target == NULL) &&
2495                        (xmlStrEqual(cur->name, BAD_CAST "target"))) {
2496                 target = virXMLPropString(cur, "dir");
2497             } else if (xmlStrEqual(cur->name, BAD_CAST "readonly")) {
2498                 def->readonly = 1;
2499             }
2500         }
2501         cur = cur->next;
2502     }
2503
2504     if (source == NULL) {
2505         virDomainReportError(VIR_ERR_NO_SOURCE,
2506                              target ? "%s" : NULL, target);
2507         goto error;
2508     }
2509
2510     if (target == NULL) {
2511         virDomainReportError(VIR_ERR_NO_TARGET,
2512                              source ? "%s" : NULL, source);
2513         goto error;
2514     }
2515
2516     def->src = source;
2517     source = NULL;
2518     def->dst = target;
2519     target = NULL;
2520
2521     if (virDomainDeviceInfoParseXML(node, &def->info, flags) < 0)
2522         goto error;
2523
2524 cleanup:
2525     VIR_FREE(type);
2526     VIR_FREE(target);
2527     VIR_FREE(source);
2528     VIR_FREE(accessmode);
2529
2530     return def;
2531
2532  error:
2533     virDomainFSDefFree(def);
2534     def = NULL;
2535     goto cleanup;
2536 }
2537
2538
2539 static int
2540 virVirtualPortProfileParamsParseXML(xmlNodePtr node,
2541                                     virVirtualPortProfileParamsPtr virtPort)
2542 {
2543     int ret = -1;
2544     char *virtPortType;
2545     char *virtPortManagerID = NULL;
2546     char *virtPortTypeID = NULL;
2547     char *virtPortTypeIDVersion = NULL;
2548     char *virtPortInstanceID = NULL;
2549     char *virtPortProfileID = NULL;
2550     xmlNodePtr cur = node->children;
2551     const char *msg = NULL;
2552
2553     virtPortType = virXMLPropString(node, "type");
2554     if (!virtPortType)
2555         return -1;
2556
2557     while (cur != NULL) {
2558         if (xmlStrEqual(cur->name, BAD_CAST "parameters")) {
2559
2560             virtPortManagerID = virXMLPropString(cur, "managerid");
2561             virtPortTypeID = virXMLPropString(cur, "typeid");
2562             virtPortTypeIDVersion = virXMLPropString(cur, "typeidversion");
2563             virtPortInstanceID = virXMLPropString(cur, "instanceid");
2564             virtPortProfileID = virXMLPropString(cur, "profileid");
2565
2566             break;
2567         }
2568
2569         cur = cur->next;
2570     }
2571
2572     virtPort->virtPortType = VIR_VIRTUALPORT_NONE;
2573
2574     switch (virVirtualPortTypeFromString(virtPortType)) {
2575
2576     case VIR_VIRTUALPORT_8021QBG:
2577         if (virtPortManagerID     != NULL && virtPortTypeID     != NULL &&
2578             virtPortTypeIDVersion != NULL) {
2579             unsigned int val;
2580
2581             if (virStrToLong_ui(virtPortManagerID, NULL, 0, &val)) {
2582                 msg = _("cannot parse value of managerid parameter");
2583                 goto err_exit;
2584             }
2585
2586             if (val > 0xff) {
2587                 msg = _("value of managerid out of range");
2588                 goto err_exit;
2589             }
2590
2591             virtPort->u.virtPort8021Qbg.managerID = (uint8_t)val;
2592
2593             if (virStrToLong_ui(virtPortTypeID, NULL, 0, &val)) {
2594                 msg = _("cannot parse value of typeid parameter");
2595                 goto err_exit;
2596             }
2597
2598             if (val > 0xffffff) {
2599                 msg = _("value for typeid out of range");
2600                 goto err_exit;
2601             }
2602
2603             virtPort->u.virtPort8021Qbg.typeID = (uint32_t)val;
2604
2605             if (virStrToLong_ui(virtPortTypeIDVersion, NULL, 0, &val)) {
2606                 msg = _("cannot parse value of typeidversion parameter");
2607                 goto err_exit;
2608             }
2609
2610             if (val > 0xff) {
2611                 msg = _("value of typeidversion out of range");
2612                 goto err_exit;
2613             }
2614
2615             virtPort->u.virtPort8021Qbg.typeIDVersion = (uint8_t)val;
2616
2617             if (virtPortInstanceID != NULL) {
2618                 if (virUUIDParse(virtPortInstanceID,
2619                                  virtPort->u.virtPort8021Qbg.instanceID)) {
2620                     msg = _("cannot parse instanceid parameter as a uuid");
2621                     goto err_exit;
2622                 }
2623             } else {
2624                 if (virUUIDGenerate(virtPort->u.virtPort8021Qbg.instanceID)) {
2625                     msg = _("cannot generate a random uuid for instanceid");
2626                     goto err_exit;
2627                 }
2628             }
2629
2630             virtPort->virtPortType = VIR_VIRTUALPORT_8021QBG;
2631             ret = 0;
2632         } else {
2633             msg = _("a parameter is missing for 802.1Qbg description");
2634             goto err_exit;
2635         }
2636     break;
2637
2638     case VIR_VIRTUALPORT_8021QBH:
2639         if (virtPortProfileID != NULL) {
2640             if (virStrcpyStatic(virtPort->u.virtPort8021Qbh.profileID,
2641                                 virtPortProfileID) != NULL) {
2642                 virtPort->virtPortType = VIR_VIRTUALPORT_8021QBH;
2643                 ret = 0;
2644             } else {
2645                 msg = _("profileid parameter too long");
2646                 goto err_exit;
2647             }
2648         } else {
2649             msg = _("profileid parameter is missing for 802.1Qbh descripion");
2650             goto err_exit;
2651         }
2652     break;
2653
2654
2655     default:
2656     case VIR_VIRTUALPORT_NONE:
2657     case VIR_VIRTUALPORT_TYPE_LAST:
2658         msg = _("unknown virtualport type");
2659         goto err_exit;
2660     break;
2661     }
2662
2663 err_exit:
2664
2665     if (msg)
2666         virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s", msg);
2667
2668     VIR_FREE(virtPortManagerID);
2669     VIR_FREE(virtPortTypeID);
2670     VIR_FREE(virtPortTypeIDVersion);
2671     VIR_FREE(virtPortInstanceID);
2672     VIR_FREE(virtPortProfileID);
2673     VIR_FREE(virtPortType);
2674
2675     return ret;
2676 }
2677
2678
2679 /* Parse the XML definition for a network interface
2680  * @param node XML nodeset to parse for net definition
2681  * @return 0 on success, -1 on failure
2682  */
2683 static virDomainNetDefPtr
2684 virDomainNetDefParseXML(virCapsPtr caps,
2685                         xmlNodePtr node,
2686                         xmlXPathContextPtr ctxt,
2687                         virBitmapPtr bootMap,
2688                         int flags ATTRIBUTE_UNUSED)
2689 {
2690     virDomainNetDefPtr def;
2691     xmlNodePtr cur;
2692     char *macaddr = NULL;
2693     char *type = NULL;
2694     char *network = NULL;
2695     char *bridge = NULL;
2696     char *dev = NULL;
2697     char *ifname = NULL;
2698     char *script = NULL;
2699     char *address = NULL;
2700     char *port = NULL;
2701     char *model = NULL;
2702     char *backend = NULL;
2703     char *txmode = NULL;
2704     char *filter = NULL;
2705     char *internal = NULL;
2706     char *devaddr = NULL;
2707     char *mode = NULL;
2708     virNWFilterHashTablePtr filterparams = NULL;
2709     virVirtualPortProfileParams virtPort;
2710     bool virtPortParsed = false;
2711     xmlNodePtr oldnode = ctxt->node;
2712     int ret;
2713
2714     if (VIR_ALLOC(def) < 0) {
2715         virReportOOMError();
2716         return NULL;
2717     }
2718
2719     ctxt->node = node;
2720
2721     type = virXMLPropString(node, "type");
2722     if (type != NULL) {
2723         if ((int)(def->type = virDomainNetTypeFromString(type)) < 0) {
2724             virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2725                                  _("unknown interface type '%s'"), type);
2726             goto error;
2727         }
2728     } else {
2729         def->type = VIR_DOMAIN_NET_TYPE_USER;
2730     }
2731
2732     cur = node->children;
2733     while (cur != NULL) {
2734         if (cur->type == XML_ELEMENT_NODE) {
2735             if ((macaddr == NULL) &&
2736                 (xmlStrEqual(cur->name, BAD_CAST "mac"))) {
2737                 macaddr = virXMLPropString(cur, "address");
2738             } else if ((network == NULL) &&
2739                        (def->type == VIR_DOMAIN_NET_TYPE_NETWORK) &&
2740                        (xmlStrEqual(cur->name, BAD_CAST "source"))) {
2741                 network = virXMLPropString(cur, "network");
2742             } else if ((internal == NULL) &&
2743                        (def->type == VIR_DOMAIN_NET_TYPE_INTERNAL) &&
2744                        (xmlStrEqual(cur->name, BAD_CAST "source"))) {
2745                 internal = virXMLPropString(cur, "name");
2746             } else if ((network == NULL) &&
2747                        (def->type == VIR_DOMAIN_NET_TYPE_BRIDGE) &&
2748                        (xmlStrEqual(cur->name, BAD_CAST "source"))) {
2749                 bridge = virXMLPropString(cur, "bridge");
2750             } else if ((dev == NULL) &&
2751                        (def->type == VIR_DOMAIN_NET_TYPE_ETHERNET ||
2752                         def->type == VIR_DOMAIN_NET_TYPE_DIRECT) &&
2753                        xmlStrEqual(cur->name, BAD_CAST "source")) {
2754                 dev  = virXMLPropString(cur, "dev");
2755                 mode = virXMLPropString(cur, "mode");
2756             } else if (!virtPortParsed &&
2757                        (def->type == VIR_DOMAIN_NET_TYPE_DIRECT) &&
2758                        xmlStrEqual(cur->name, BAD_CAST "virtualport")) {
2759                 if (virVirtualPortProfileParamsParseXML(cur, &virtPort))
2760                     goto error;
2761                 virtPortParsed = true;
2762             } else if ((network == NULL) &&
2763                        ((def->type == VIR_DOMAIN_NET_TYPE_SERVER) ||
2764                         (def->type == VIR_DOMAIN_NET_TYPE_CLIENT) ||
2765                         (def->type == VIR_DOMAIN_NET_TYPE_MCAST)) &&
2766                        (xmlStrEqual(cur->name, BAD_CAST "source"))) {
2767                 address = virXMLPropString(cur, "address");
2768                 port = virXMLPropString(cur, "port");
2769             } else if ((address == NULL) &&
2770                        (def->type == VIR_DOMAIN_NET_TYPE_ETHERNET ||
2771                         def->type == VIR_DOMAIN_NET_TYPE_BRIDGE) &&
2772                        (xmlStrEqual(cur->name, BAD_CAST "ip"))) {
2773                 address = virXMLPropString(cur, "address");
2774             } else if ((ifname == NULL) &&
2775                        xmlStrEqual(cur->name, BAD_CAST "target")) {
2776                 ifname = virXMLPropString(cur, "dev");
2777                 if ((ifname != NULL) &&
2778                     ((flags & VIR_DOMAIN_XML_INACTIVE) &&
2779                       (STRPREFIX((const char*)ifname, "vnet")))) {
2780                     /* An auto-generated target name, blank it out */
2781                     VIR_FREE(ifname);
2782                 }
2783             } else if ((script == NULL) &&
2784                        (def->type == VIR_DOMAIN_NET_TYPE_ETHERNET ||
2785                         def->type == VIR_DOMAIN_NET_TYPE_BRIDGE) &&
2786                        xmlStrEqual(cur->name, BAD_CAST "script")) {
2787                 script = virXMLPropString(cur, "path");
2788             } else if (xmlStrEqual (cur->name, BAD_CAST "model")) {
2789                 model = virXMLPropString(cur, "type");
2790             } else if (xmlStrEqual (cur->name, BAD_CAST "driver")) {
2791                 backend = virXMLPropString(cur, "name");
2792                 txmode = virXMLPropString(cur, "txmode");
2793             } else if (xmlStrEqual (cur->name, BAD_CAST "filterref")) {
2794                 filter = virXMLPropString(cur, "filter");
2795                 VIR_FREE(filterparams);
2796                 filterparams = virNWFilterParseParamAttributes(cur);
2797             } else if ((flags & VIR_DOMAIN_XML_INTERNAL_STATUS) &&
2798                        xmlStrEqual(cur->name, BAD_CAST "state")) {
2799                 /* Legacy back-compat. Don't add any more attributes here */
2800                 devaddr = virXMLPropString(cur, "devaddr");
2801             } else if (xmlStrEqual(cur->name, BAD_CAST "boot")) {
2802                 if (virDomainDeviceBootParseXML(cur, &def->bootIndex,
2803                                                 bootMap))
2804                     goto error;
2805             }
2806         }
2807         cur = cur->next;
2808     }
2809
2810     if (macaddr) {
2811         if (virParseMacAddr((const char *)macaddr, def->mac) < 0) {
2812             virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2813                                  _("unable to parse mac address '%s'"),
2814                                  (const char *)macaddr);
2815             goto error;
2816         }
2817     } else {
2818         virCapabilitiesGenerateMac(caps, def->mac);
2819     }
2820
2821     if (devaddr) {
2822         if (virDomainParseLegacyDeviceAddress(devaddr,
2823                                               &def->info.addr.pci) < 0) {
2824             virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2825                                  _("Unable to parse devaddr parameter '%s'"),
2826                                  devaddr);
2827             goto error;
2828         }
2829         def->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
2830     } else {
2831         if (virDomainDeviceInfoParseXML(node, &def->info, flags) < 0)
2832             goto error;
2833     }
2834
2835     /* XXX what about ISA/USB based NIC models - once we support
2836      * them we should make sure address type is correct */
2837     if (def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
2838         def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
2839         virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2840                              _("Network interfaces must use 'pci' address type"));
2841         goto error;
2842     }
2843
2844     switch (def->type) {
2845     case VIR_DOMAIN_NET_TYPE_NETWORK:
2846         if (network == NULL) {
2847             virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2848     _("No <source> 'network' attribute specified with <interface type='network'/>"));
2849             goto error;
2850         }
2851         def->data.network.name = network;
2852         network = NULL;
2853         break;
2854
2855     case VIR_DOMAIN_NET_TYPE_ETHERNET:
2856
2857         if (script != NULL) {
2858             def->data.ethernet.script = script;
2859             script = NULL;
2860         }
2861         if (dev != NULL) {
2862             def->data.ethernet.dev = dev;
2863             dev = NULL;
2864         }
2865         if (address != NULL) {
2866             def->data.ethernet.ipaddr = address;
2867             address = NULL;
2868         }
2869         break;
2870
2871     case VIR_DOMAIN_NET_TYPE_BRIDGE:
2872         if (bridge == NULL) {
2873             virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2874     _("No <source> 'bridge' attribute specified with <interface type='bridge'/>"));
2875             goto error;
2876         }
2877         def->data.bridge.brname = bridge;
2878         bridge = NULL;
2879         if (script != NULL) {
2880             def->data.bridge.script = script;
2881             script = NULL;
2882         }
2883         if (address != NULL) {
2884             def->data.bridge.ipaddr = address;
2885             address = NULL;
2886         }
2887         break;
2888
2889     case VIR_DOMAIN_NET_TYPE_CLIENT:
2890     case VIR_DOMAIN_NET_TYPE_SERVER:
2891     case VIR_DOMAIN_NET_TYPE_MCAST:
2892         if (port == NULL) {
2893             virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2894             _("No <source> 'port' attribute specified with socket interface"));
2895             goto error;
2896         }
2897         if (virStrToLong_i(port, NULL, 10, &def->data.socket.port) < 0) {
2898             virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2899             _("Cannot parse <source> 'port' attribute with socket interface"));
2900             goto error;
2901         }
2902
2903         if (address == NULL) {
2904             if (def->type == VIR_DOMAIN_NET_TYPE_CLIENT ||
2905                 def->type == VIR_DOMAIN_NET_TYPE_MCAST) {
2906                 virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2907         _("No <source> 'address' attribute specified with socket interface"));
2908                 goto error;
2909             }
2910         } else {
2911             def->data.socket.address = address;
2912             address = NULL;
2913         }
2914         break;
2915
2916     case VIR_DOMAIN_NET_TYPE_INTERNAL:
2917         if (internal == NULL) {
2918             virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2919         _("No <source> 'name' attribute specified with <interface type='internal'/>"));
2920             goto error;
2921         }
2922         def->data.internal.name = internal;
2923         internal = NULL;
2924         break;
2925
2926     case VIR_DOMAIN_NET_TYPE_DIRECT:
2927         if (dev == NULL) {
2928             virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2929         _("No <source> 'dev' attribute specified with <interface type='direct'/>"));
2930             goto error;
2931         }
2932
2933         if (mode != NULL) {
2934             int m;
2935             if ((m = virDomainNetdevMacvtapTypeFromString(mode)) < 0) {
2936                 virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2937                                      _("Unkown mode has been specified"));
2938                 goto error;
2939             }
2940             def->data.direct.mode = m;
2941         } else
2942             def->data.direct.mode = VIR_DOMAIN_NETDEV_MACVTAP_MODE_VEPA;
2943
2944         if (virtPortParsed)
2945             def->data.direct.virtPortProfile = virtPort;
2946
2947         def->data.direct.linkdev = dev;
2948         dev = NULL;
2949
2950         if ((flags & VIR_DOMAIN_XML_INACTIVE))
2951             VIR_FREE(ifname);
2952
2953         break;
2954
2955     case VIR_DOMAIN_NET_TYPE_USER:
2956     case VIR_DOMAIN_NET_TYPE_LAST:
2957         break;
2958     }
2959
2960     if (ifname != NULL) {
2961         def->ifname = ifname;
2962         ifname = NULL;
2963     }
2964
2965     /* NIC model (see -net nic,model=?).  We only check that it looks
2966      * reasonable, not that it is a supported NIC type.  FWIW kvm
2967      * supports these types as of April 2008:
2968      * i82551 i82557b i82559er ne2k_pci pcnet rtl8139 e1000 virtio
2969      */
2970     if (model != NULL) {
2971         int i;
2972         for (i = 0 ; i < strlen(model) ; i++) {
2973             int char_ok = c_isalnum(model[i]) || model[i] == '_';
2974             if (!char_ok) {
2975                 virDomainReportError(VIR_ERR_INVALID_ARG, "%s",
2976                                      _("Model name contains invalid characters"));
2977                 goto error;
2978             }
2979         }
2980         def->model = model;
2981         model = NULL;
2982     }
2983
2984     if (def->model && STREQ(def->model, "virtio")) {
2985         if (backend != NULL) {
2986             int name;
2987             if (((name = virDomainNetBackendTypeFromString(backend)) < 0) ||
2988                 (name == VIR_DOMAIN_NET_BACKEND_TYPE_DEFAULT)) {
2989                 virDomainReportError(VIR_ERR_INTERNAL_ERROR,
2990                                      _("Unknown interface <driver name='%s'> "
2991                                        "has been specified"),
2992                                      backend);
2993                 goto error;
2994             }
2995             def->driver.virtio.name = name;
2996         }
2997         if (txmode != NULL) {
2998             int m;
2999             if (((m = virDomainNetVirtioTxModeTypeFromString(txmode)) < 0) ||
3000                 (m == VIR_DOMAIN_NET_VIRTIO_TX_MODE_DEFAULT)) {
3001                 virDomainReportError(VIR_ERR_INTERNAL_ERROR,
3002                                      _("Unknown interface <driver txmode='%s'> "
3003                                        "has been specified"),
3004                                      txmode);
3005                 goto error;
3006             }
3007             def->driver.virtio.txmode = m;
3008         }
3009     }
3010
3011     if (filter != NULL) {
3012         switch (def->type) {
3013         case VIR_DOMAIN_NET_TYPE_ETHERNET:
3014         case VIR_DOMAIN_NET_TYPE_NETWORK:
3015         case VIR_DOMAIN_NET_TYPE_BRIDGE:
3016             def->filter = filter;
3017             filter = NULL;
3018             def->filterparams = filterparams;
3019             filterparams = NULL;
3020         break;
3021         default:
3022         break;
3023         }
3024     }
3025
3026     ret = virXPathULong("string(./tune/sndbuf)", ctxt, &def->tune.sndbuf);
3027     if (ret >= 0) {
3028         def->tune.sndbuf_specified = true;
3029     } else if (ret == -2) {
3030         virDomainReportError(VIR_ERR_XML_ERROR, "%s",
3031                              _("sndbuf must be a positive integer"));
3032         goto error;
3033     }
3034
3035 cleanup:
3036     ctxt->node = oldnode;
3037     VIR_FREE(macaddr);
3038     VIR_FREE(network);
3039     VIR_FREE(address);
3040     VIR_FREE(port);
3041     VIR_FREE(ifname);
3042     VIR_FREE(dev);
3043     VIR_FREE(script);
3044     VIR_FREE(bridge);
3045     VIR_FREE(model);
3046     VIR_FREE(backend);
3047     VIR_FREE(txmode);
3048     VIR_FREE(filter);
3049     VIR_FREE(type);
3050     VIR_FREE(internal);
3051     VIR_FREE(devaddr);
3052     VIR_FREE(mode);
3053     virNWFilterHashTableFree(filterparams);
3054
3055     return def;
3056
3057 error:
3058     virDomainNetDefFree(def);
3059     def = NULL;
3060     goto cleanup;
3061 }
3062
3063 static int
3064 virDomainChrDefaultTargetType(virCapsPtr caps, int devtype) {
3065
3066     int target = -1;
3067
3068     switch (devtype) {
3069     case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
3070         virDomainReportError(VIR_ERR_XML_ERROR,
3071                              _("target type must be specified for %s device"),
3072                              virDomainChrDeviceTypeToString(devtype));
3073         break;
3074
3075     case VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE:
3076         target = caps->defaultConsoleTargetType;
3077         break;
3078
3079     case VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL:
3080     case VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL:
3081     default:
3082         /* No target type yet*/
3083         target = 0;
3084         break;
3085     }
3086
3087     return target;
3088 }
3089
3090 static int
3091 virDomainChrTargetTypeFromString(virCapsPtr caps,
3092                                  int devtype,
3093                                  const char *targetType)
3094 {
3095     int ret = -1;
3096     int target = 0;
3097
3098     if (!targetType) {
3099         target = virDomainChrDefaultTargetType(caps, devtype);
3100         goto out;
3101     }
3102
3103     switch (devtype) {
3104     case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
3105         target = virDomainChrChannelTargetTypeFromString(targetType);
3106         break;
3107
3108     case VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE:
3109         target = virDomainChrConsoleTargetTypeFromString(targetType);
3110         break;
3111
3112     case VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL:
3113     case VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL:
3114     default:
3115         /* No target type yet*/
3116         break;
3117     }
3118
3119 out:
3120     ret = target;
3121     return ret;
3122 }
3123
3124 static int
3125 virDomainChrDefParseTargetXML(virCapsPtr caps,
3126                               virDomainChrDefPtr def,
3127                               xmlNodePtr cur,
3128                               int flags ATTRIBUTE_UNUSED)
3129 {
3130     int ret = -1;
3131     unsigned int port;
3132     const char *targetType = virXMLPropString(cur, "type");
3133     const char *addrStr = NULL;
3134     const char *portStr = NULL;
3135
3136     if ((def->targetType =
3137         virDomainChrTargetTypeFromString(caps,
3138                                          def->deviceType, targetType)) < 0) {
3139         goto error;
3140     }
3141
3142     switch (def->deviceType) {
3143     case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
3144         switch (def->targetType) {
3145         case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_GUESTFWD:
3146             addrStr = virXMLPropString(cur, "address");
3147             portStr = virXMLPropString(cur, "port");
3148
3149             if (addrStr == NULL) {
3150                 virDomainReportError(VIR_ERR_XML_ERROR, "%s",
3151                                      _("guestfwd channel does not "
3152                                        "define a target address"));
3153                 goto error;
3154             }
3155
3156             if (VIR_ALLOC(def->target.addr) < 0) {
3157                 virReportOOMError();
3158                 goto error;
3159             }
3160
3161             if (virSocketParseAddr(addrStr, def->target.addr, AF_UNSPEC) < 0)
3162                 goto error;
3163
3164             if (def->target.addr->data.stor.ss_family != AF_INET) {
3165                 virDomainReportError(VIR_ERR_CONFIG_UNSUPPORTED,
3166                                      "%s", _("guestfwd channel only supports "
3167                                              "IPv4 addresses"));
3168                 goto error;
3169             }
3170
3171             if (portStr == NULL) {
3172                 virDomainReportError(VIR_ERR_XML_ERROR, "%s",
3173                                      _("guestfwd channel does "
3174                                        "not define a target port"));
3175                 goto error;
3176             }
3177
3178             if (virStrToLong_ui(portStr, NULL, 10, &port) < 0) {
3179                 virDomainReportError(VIR_ERR_XML_ERROR,
3180                                      _("Invalid port number: %s"),
3181                                      portStr);
3182                 goto error;
3183             }
3184
3185             virSocketSetPort(def->target.addr, port);
3186             break;
3187
3188         case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO:
3189             def->target.name = virXMLPropString(cur, "name");
3190             break;
3191         }
3192         break;
3193
3194     default:
3195         portStr = virXMLPropString(cur, "port");
3196         if (portStr == NULL) {
3197             /* Set to negative value to indicate we should set it later */
3198             def->target.port = -1;
3199             break;
3200         }
3201
3202         if (virStrToLong_ui(portStr, NULL, 10, &port) < 0) {
3203             virDomainReportError(VIR_ERR_XML_ERROR,
3204                                  _("Invalid port number: %s"),
3205                                  portStr);
3206             goto error;
3207         }
3208         def->target.port = port;
3209         break;
3210     }
3211
3212
3213     ret = 0;
3214 error:
3215     VIR_FREE(targetType);
3216     VIR_FREE(addrStr);
3217     VIR_FREE(portStr);
3218
3219     return ret;
3220 }
3221
3222 /* Parse the source half of the XML definition for a character device,
3223  * where node is the first element of node->children of the parent
3224  * element.  def->type must already be valid.  Return -1 on failure,
3225  * otherwise the number of ignored children (this intentionally skips
3226  * <target>, which is used by <serial> but not <smartcard>). */
3227 static int
3228 virDomainChrSourceDefParseXML(virDomainChrSourceDefPtr def,
3229                               xmlNodePtr cur)
3230 {
3231     char *bindHost = NULL;
3232     char *bindService = NULL;
3233     char *connectHost = NULL;
3234     char *connectService = NULL;
3235     char *path = NULL;
3236     char *mode = NULL;
3237     char *protocol = NULL;
3238     int remaining = 0;
3239
3240     while (cur != NULL) {
3241         if (cur->type == XML_ELEMENT_NODE) {
3242             if (xmlStrEqual(cur->name, BAD_CAST "source")) {
3243                 if (mode == NULL)
3244                     mode = virXMLPropString(cur, "mode");
3245
3246                 switch (def->type) {
3247                 case VIR_DOMAIN_CHR_TYPE_PTY:
3248                 case VIR_DOMAIN_CHR_TYPE_DEV:
3249                 case VIR_DOMAIN_CHR_TYPE_FILE:
3250                 case VIR_DOMAIN_CHR_TYPE_PIPE:
3251                 case VIR_DOMAIN_CHR_TYPE_UNIX:
3252                     if (path == NULL)
3253                         path = virXMLPropString(cur, "path");
3254
3255                     break;
3256
3257                 case VIR_DOMAIN_CHR_TYPE_UDP:
3258                 case VIR_DOMAIN_CHR_TYPE_TCP:
3259                     if (mode == NULL ||
3260                         STREQ((const char *)mode, "connect")) {
3261
3262                         if (connectHost == NULL)
3263                             connectHost = virXMLPropString(cur, "host");
3264                         if (connectService == NULL)
3265                             connectService = virXMLPropString(cur, "service");
3266                     } else if (STREQ((const char *)mode, "bind")) {
3267                         if (bindHost == NULL)
3268                             bindHost = virXMLPropString(cur, "host");
3269                         if (bindService == NULL)
3270                             bindService = virXMLPropString(cur, "service");
3271                     } else {
3272                         virDomainReportError(VIR_ERR_INTERNAL_ERROR,
3273                                              _("Unknown source mode '%s'"),
3274                                              mode);
3275                         goto error;
3276                     }
3277
3278                     if (def->type == VIR_DOMAIN_CHR_TYPE_UDP)
3279                         VIR_FREE(mode);
3280                 }
3281             } else if (xmlStrEqual(cur->name, BAD_CAST "protocol")) {
3282                 if (protocol == NULL)
3283                     protocol = virXMLPropString(cur, "type");
3284             } else {
3285                 remaining++;
3286             }
3287         }
3288         cur = cur->next;
3289     }
3290
3291     switch (def->type) {
3292     case VIR_DOMAIN_CHR_TYPE_NULL:
3293         /* Nada */
3294         break;
3295
3296     case VIR_DOMAIN_CHR_TYPE_VC:
3297         break;
3298
3299     case VIR_DOMAIN_CHR_TYPE_PTY:
3300     case VIR_DOMAIN_CHR_TYPE_DEV:
3301     case VIR_DOMAIN_CHR_TYPE_FILE:
3302     case VIR_DOMAIN_CHR_TYPE_PIPE:
3303         if (path == NULL &&
3304             def->type != VIR_DOMAIN_CHR_TYPE_PTY) {
3305             virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3306                        _("Missing source path attribute for char device"));
3307             goto error;
3308         }
3309
3310         def->data.file.path = path;
3311         path = NULL;
3312         break;
3313
3314     case VIR_DOMAIN_CHR_TYPE_STDIO:
3315     case VIR_DOMAIN_CHR_TYPE_SPICEVMC:
3316         /* Nada */
3317         break;
3318
3319     case VIR_DOMAIN_CHR_TYPE_TCP:
3320         if (mode == NULL ||
3321             STREQ(mode, "connect")) {
3322             if (connectHost == NULL) {
3323                 virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3324                         _("Missing source host attribute for char device"));
3325                 goto error;
3326             }
3327             if (connectService == NULL) {
3328                 virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3329                      _("Missing source service attribute for char device"));
3330                 goto error;
3331             }
3332
3333             def->data.tcp.host = connectHost;
3334             connectHost = NULL;
3335             def->data.tcp.service = connectService;
3336             connectService = NULL;
3337             def->data.tcp.listen = false;
3338         } else {
3339             if (bindHost == NULL) {
3340                 virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3341                         _("Missing source host attribute for char device"));
3342                 goto error;
3343             }
3344             if (bindService == NULL) {
3345                 virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3346                      _("Missing source service attribute for char device"));
3347                 goto error;
3348             }
3349
3350             def->data.tcp.host = bindHost;
3351             bindHost = NULL;
3352             def->data.tcp.service = bindService;
3353             bindService = NULL;
3354             def->data.tcp.listen = true;
3355         }
3356
3357         if (protocol == NULL)
3358             def->data.tcp.protocol = VIR_DOMAIN_CHR_TCP_PROTOCOL_RAW;
3359         else if ((def->data.tcp.protocol =
3360                   virDomainChrTcpProtocolTypeFromString(protocol)) < 0) {
3361             virDomainReportError(VIR_ERR_INTERNAL_ERROR,
3362                                  _("Unknown protocol '%s'"), protocol);
3363             goto error;
3364         }
3365
3366         break;
3367
3368     case VIR_DOMAIN_CHR_TYPE_UDP:
3369         if (connectService == NULL) {
3370             virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3371                    _("Missing source service attribute for char device"));
3372             goto error;
3373         }
3374
3375         def->data.udp.connectHost = connectHost;
3376         connectHost = NULL;
3377         def->data.udp.connectService = connectService;
3378         connectService = NULL;
3379
3380         def->data.udp.bindHost = bindHost;
3381         bindHost = NULL;
3382         def->data.udp.bindService = bindService;
3383         bindService = NULL;
3384         break;
3385
3386     case VIR_DOMAIN_CHR_TYPE_UNIX:
3387         if (path == NULL) {
3388             virDomainReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3389                          _("Missing source path attribute for char device"));
3390             goto error;
3391         }
3392
3393         def->data.nix.listen = mode != NULL && STRNEQ(mode, "connect");
3394
3395         def->data.nix.path = path;
3396         path = NULL;
3397         break;
3398     }
3399
3400 cleanup:
3401     VIR_FREE(mode);
3402     VIR_FREE(protocol);
3403     VIR_FREE(bindHost);
3404     VIR_FREE(bindService);
3405     VIR_FREE(connectHost);
3406     VIR_FREE(connectService);
3407     VIR_FREE(path);
3408
3409     return remaining;
3410
3411 error:
3412     virDomainChrSourceDefClear(def);
3413     remaining = -1;
3414     goto cleanup;
3415 }
3416
3417 /* Create a new character device definition and set
3418  * default port.
3419  */
3420 virDomainChrDefPtr
3421 virDomainChrDefNew(void) {
3422     virDomainChrDefPtr def = NULL;
3423
3424     if (VIR_ALLOC(def) < 0) {
3425         virReportOOMError();
3426         return NULL;
3427     }
3428
3429     def->target.port = -1;
3430     return def;
3431 }
3432
3433 /* Parse the XML definition for a character device
3434  * @param node XML nodeset to parse for net definition
3435  *
3436  * The XML we're dealing with looks like
3437  *
3438  * <serial type="pty">
3439  *   <source path="/dev/pts/3"/>
3440  *   <target port="1"/>
3441  * </serial>
3442  *
3443  * <serial type="dev">
3444  *   <source path="/dev/ttyS0"/>
3445  *   <target port="1"/>
3446  * </serial>
3447  *
3448  * <serial type="tcp">
3449  *   <source mode="connect" host="0.0.0.0" service="2445"/>
3450  *   <target port="1"/>
3451  * </serial>
3452  *
3453  * <serial type="tcp">
3454  *   <source mode="bind" host="0.0.0.0" service="2445"/>
3455  *   <target port="1"/>
3456  *   <protocol type='raw'/>
3457  * </serial>
3458  *
3459  * <serial type="udp">
3460  *   <source mode="bind" host="0.0.0.0" service="2445"/>
3461  *   <source mode="connect" host="0.0.0.0" service="2445"/>
3462  *   <target port="1"/>
3463  * </serial>
3464  *
3465  * <serial type="unix">
3466  *   <source mode="bind" path="/tmp/foo"/>
3467  *   <target port="1"/>
3468  * </serial>
3469  *
3470  */
3471 static virDomainChrDefPtr
3472 virDomainChrDefParseXML(virCapsPtr caps,
3473                         xmlNodePtr node,
3474                         int flags) {
3475     xmlNodePtr cur;
3476     char *type = NULL;
3477     const char *nodeName;
3478     virDomainChrDefPtr def;
3479     int remaining;
3480
3481     if (!(def = virDomainChrDefNew()))
3482         return NULL;
3483
3484     type = virXMLPropString(node, "type");
3485     if (type == NULL) {
3486         def->source.type = VIR_DOMAIN_CHR_TYPE_PTY;
3487     } else if ((def->source.type = virDomainChrTypeFromString(type)) < 0) {
3488         virDomainReportError(VIR_ERR_XML_ERROR,
3489                              _("unknown type presented to host for character device: %s"),
3490                              type);
3491         goto error;
3492     }
3493
3494     nodeName = (const char *) node->name;
3495     if ((def->deviceType = virDomainChrDeviceTypeFromString(nodeName)) < 0) {
3496         virDomainReportError(VIR_ERR_XML_ERROR,
3497                              _("unknown character device type: %s"),
3498                              nodeName);
3499     }
3500
3501     cur = node->children;
3502     remaining = virDomainChrSourceDefParseXML(&def->source, cur);
3503     if (remaining < 0)
3504         goto error;
3505     if (remaining) {
3506         while (cur != NULL) {
3507             if (cur->type == XML_ELEMENT_NODE) {
3508                 if (xmlStrEqual(cur->name, BAD_CAST "target")) {
3509                     if (virDomainChrDefParseTargetXML(caps, def, cur,
3510                                                       flags) < 0) {
3511                         goto error;
3512                     }
3513                 }
3514             }
3515             cur = cur->next;
3516         }
3517     }
3518
3519     if (def->source.type == VIR_DOMAIN_CHR_TYPE_SPICEVMC) {
3520         if (def->targetType != VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO) {
3521             virDomainReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3522                                  _("spicevmc device type only supports "
3523                                    "virtio"));
3524             goto error;
3525         } else {
3526             def->source.data.spicevmc = VIR_DOMAIN_CHR_SPICEVMC_VDAGENT;
3527         }
3528     }
3529
3530     if (virDomainDeviceInfoParseXML(node, &def->info, flags) < 0)
3531         goto error;
3532
3533 cleanup:
3534     VIR_FREE(type);
3535
3536     return def;
3537
3538 error:
3539     virDomainChrDefFree(def);
3540     def = NULL;
3541     goto cleanup;
3542 }
3543
3544 static virDomainSmartcardDefPtr
3545 virDomainSmartcardDefParseXML(xmlNodePtr node,
3546                               int flags)
3547 {
3548     xmlNodePtr cur;
3549     char *mode = NULL;
3550     char *type = NULL;
3551     virDomainSmartcardDefPtr def;
3552     int i;
3553
3554     if (VIR_ALLOC(def) < 0) {
3555         virReportOOMError();
3556         return NULL;
3557     }
3558
3559     mode = virXMLPropString(node, "mode");
3560     if (mode == NULL) {
3561         virDomainReportError(VIR_ERR_XML_ERROR, "%s",
3562                              _("missing smartcard device mode"));
3563         goto error;
3564     }
3565     if ((def->type = virDomainSmartcardTypeFromString(mode)) < 0) {
3566         virDomainReportError(VIR_ERR_XML_ERROR,
3567                              _("unknown smartcard device mode: %s"),
3568                              mode);
3569         goto error;
3570     }
3571
3572     switch (def->type) {
3573     case VIR_DOMAIN_SMARTCARD_TYPE_HOST:
3574         break;
3575
3576     case VIR_DOMAIN_SMARTCARD_TYPE_HOST_CERTIFICATES:
3577         i = 0;
3578         cur = node->children;
3579         while (cur) {
3580             if (cur->type == XML_ELEMENT_NODE &&
3581                 xmlStrEqual(cur->name, BAD_CAST "certificate")) {
3582                 if (i == 3) {
3583                     virDomainReportError(VIR_ERR_XML_ERROR, "%s",
3584                                          _("host-certificates mode needs "
3585                                            "exactly three certificates"));
3586                     goto error;
3587                 }
3588                 def->data.cert.file[i] = (char *)xmlNodeGetContent(cur);
3589                 i