]> wimlib.net Git - wimlib/blob - src/xml.c
Update progress functions
[wimlib] / src / xml.c
1 /*
2  * xml.c
3  *
4  * Deals with the XML information in WIM files.  Uses the C library libxml2.
5  */
6
7 /*
8  * Copyright (C) 2012, 2013 Eric Biggers
9  *
10  * This file is part of wimlib, a library for working with WIM files.
11  *
12  * wimlib is free software; you can redistribute it and/or modify it under the
13  * terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 3 of the License, or (at your option)
15  * any later version.
16  *
17  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19  * A PARTICULAR PURPOSE. See the GNU General Public License for more
20  * details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with wimlib; if not, see http://www.gnu.org/licenses/.
24  */
25
26 #ifdef HAVE_CONFIG_H
27 #  include "config.h"
28 #endif
29
30 #include "wimlib/dentry.h"
31 #include "wimlib/encoding.h"
32 #include "wimlib/error.h"
33 #include "wimlib/file_io.h"
34 #include "wimlib/lookup_table.h"
35 #include "wimlib/metadata.h"
36 #include "wimlib/resource.h"
37 #include "wimlib/timestamp.h"
38 #include "wimlib/xml.h"
39 #include "wimlib/write.h"
40
41 #include <libxml/encoding.h>
42 #include <libxml/parser.h>
43 #include <libxml/tree.h>
44 #include <libxml/xmlwriter.h>
45 #include <limits.h>
46 #include <string.h>
47 #include <unistd.h>
48
49 /* Structures used to form an in-memory representation of the XML data (other
50  * than the raw parse tree from libxml). */
51
52 struct windows_version {
53         u64 major;
54         u64 minor;
55         u64 build;
56         u64 sp_build;
57         u64 sp_level;
58 };
59
60 struct windows_info {
61         u64      arch;
62         tchar   *product_name;
63         tchar   *edition_id;
64         tchar   *installation_type;
65         tchar   *pkeyconfigversion;
66         tchar   *hal;
67         tchar   *product_type;
68         tchar   *product_suite;
69         tchar  **languages;
70         tchar   *default_language;
71         size_t   num_languages;
72         tchar   *system_root;
73         bool     windows_version_exists;
74         struct   windows_version windows_version;
75 };
76
77 struct image_info {
78         int index;
79         bool windows_info_exists;
80         u64 dir_count;
81         u64 file_count;
82         u64 total_bytes;
83         u64 hard_link_bytes;
84         u64 creation_time;
85         u64 last_modification_time;
86         struct windows_info windows_info;
87         tchar *name;
88         tchar *description;
89         tchar *display_name;
90         tchar *display_description;
91         tchar *flags;
92         bool wimboot;
93         struct wim_lookup_table *lookup_table; /* temporary field */
94 };
95
96 /* A struct wim_info structure corresponds to the entire XML data for a WIM file. */
97 struct wim_info {
98         u64 total_bytes;
99         int num_images;
100         /* Array of `struct image_info's, one for each image in the WIM that is
101          * mentioned in the XML data. */
102         struct image_info *images;
103 };
104
105 struct xml_string_spec {
106         const char *name;
107         size_t offset;
108 };
109
110 #define ELEM(STRING_NAME, MEMBER_NAME) \
111         {STRING_NAME, offsetof(struct image_info, MEMBER_NAME)}
112 static const struct xml_string_spec
113 image_info_xml_string_specs[] = {
114         ELEM("NAME", name),
115         ELEM("DESCRIPTION", description),
116         ELEM("DISPLAYNAME", display_name),
117         ELEM("DISPLAYDESCRIPTION", display_description),
118         ELEM("FLAGS", flags),
119 };
120 #undef ELEM
121
122 #define ELEM(STRING_NAME, MEMBER_NAME) \
123         {STRING_NAME, offsetof(struct windows_info, MEMBER_NAME)}
124 static const struct xml_string_spec
125 windows_info_xml_string_specs[] = {
126         ELEM("PRODUCTNAME", product_name),
127         ELEM("EDITIONID", edition_id),
128         ELEM("INSTALLATIONTYPE", installation_type),
129         ELEM("HAL", hal),
130         ELEM("PRODUCTTYPE", product_type),
131         ELEM("PRODUCTSUITE", product_suite),
132 };
133 #undef ELEM
134
135 u64
136 wim_info_get_total_bytes(const struct wim_info *info)
137 {
138         if (info)
139                 return info->total_bytes;
140         else
141                 return 0;
142 }
143
144 u64
145 wim_info_get_image_hard_link_bytes(const struct wim_info *info, int image)
146 {
147         if (info)
148                 return info->images[image - 1].hard_link_bytes;
149         else
150                 return 0;
151 }
152
153 u64
154 wim_info_get_image_total_bytes(const struct wim_info *info, int image)
155 {
156         if (info)
157                 return info->images[image - 1].total_bytes;
158         else
159                 return 0;
160 }
161
162 unsigned
163 wim_info_get_num_images(const struct wim_info *info)
164 {
165         if (info)
166                 return info->num_images;
167         else
168                 return 0;
169 }
170
171 void
172 wim_info_set_wimboot(struct wim_info *info, int image, bool value)
173 {
174         info->images[image - 1].wimboot = value;
175 }
176
177 bool
178 wim_info_get_wimboot(const struct wim_info *info, int image)
179 {
180         return info->images[image - 1].wimboot;
181 }
182
183 /* Architecture constants are from w64 mingw winnt.h  */
184 #define PROCESSOR_ARCHITECTURE_INTEL 0
185 #define PROCESSOR_ARCHITECTURE_MIPS 1
186 #define PROCESSOR_ARCHITECTURE_ALPHA 2
187 #define PROCESSOR_ARCHITECTURE_PPC 3
188 #define PROCESSOR_ARCHITECTURE_SHX 4
189 #define PROCESSOR_ARCHITECTURE_ARM 5
190 #define PROCESSOR_ARCHITECTURE_IA64 6
191 #define PROCESSOR_ARCHITECTURE_ALPHA64 7
192 #define PROCESSOR_ARCHITECTURE_MSIL 8
193 #define PROCESSOR_ARCHITECTURE_AMD64 9
194 #define PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 10
195
196 /* Returns a statically allocated string that is a string representation of the
197  * architecture number. */
198 static const tchar *
199 get_arch(int arch)
200 {
201         switch (arch) {
202         case PROCESSOR_ARCHITECTURE_INTEL:
203                 return T("x86");
204         case PROCESSOR_ARCHITECTURE_MIPS:
205                 return T("MIPS");
206         case PROCESSOR_ARCHITECTURE_ARM:
207                 return T("ARM");
208         case PROCESSOR_ARCHITECTURE_IA64:
209                 return T("ia64");
210         case PROCESSOR_ARCHITECTURE_AMD64:
211                 return T("x86_64");
212         default:
213                 return T("unknown");
214         }
215 }
216
217
218 /* Iterate through the children of an xmlNode. */
219 #define for_node_child(parent, child)   \
220         for (child = parent->children; child != NULL; child = child->next)
221
222 /* Utility functions for xmlNodes */
223 static inline bool
224 node_is_element(xmlNode *node)
225 {
226         return node->type == XML_ELEMENT_NODE;
227 }
228
229 static inline bool
230 node_is_text(xmlNode *node)
231 {
232         return node->type == XML_TEXT_NODE;
233 }
234
235 static inline bool
236 node_name_is(xmlNode *node, const char *name)
237 {
238         /* For now, both upper case and lower case element names are accepted. */
239         return strcasecmp((const char *)node->name, name) == 0;
240 }
241
242 static u64
243 node_get_number(const xmlNode *u64_node, int base)
244 {
245         xmlNode *child;
246         for_node_child(u64_node, child)
247                 if (node_is_text(child))
248                         return strtoull(child->content, NULL, base);
249         return 0;
250 }
251
252 /* Finds the text node that is a child of an element node and returns its
253  * content converted to a 64-bit unsigned integer.  Returns 0 if no text node is
254  * found. */
255 static u64
256 node_get_u64(const xmlNode *u64_node)
257 {
258         return node_get_number(u64_node, 10);
259 }
260
261 /* Like node_get_u64(), but expects a number in base 16. */
262 static u64
263 node_get_hex_u64(const xmlNode *u64_node)
264 {
265         return node_get_number(u64_node, 16);
266 }
267
268 static int
269 node_get_string(const xmlNode *string_node, tchar **tstr_ret)
270 {
271         xmlNode *child;
272         tchar *tstr = NULL;
273         int ret;
274
275         if (*tstr_ret)
276                 return 0;
277
278         for_node_child(string_node, child) {
279                 if (node_is_text(child) && child->content) {
280                         ret = utf8_to_tstr_simple(child->content, &tstr);
281                         if (ret)
282                                 return ret;
283                         break;
284                 }
285         }
286         *tstr_ret = tstr;
287         return 0;
288 }
289
290 /* Returns the timestamp from a time node.  It has child elements <HIGHPART> and
291  * <LOWPART> that are then used to construct a 64-bit timestamp. */
292 static u64
293 node_get_timestamp(const xmlNode *time_node)
294 {
295         u32 high_part = 0;
296         u32 low_part = 0;
297         xmlNode *child;
298         for_node_child(time_node, child) {
299                 if (!node_is_element(child))
300                         continue;
301                 if (node_name_is(child, "HIGHPART"))
302                         high_part = node_get_hex_u64(child);
303                 else if (node_name_is(child, "LOWPART"))
304                         low_part = node_get_hex_u64(child);
305         }
306         return (u64)low_part | ((u64)high_part << 32);
307 }
308
309 /* Used to sort an array of struct image_infos by their image indices. */
310 static int
311 sort_by_index(const void *p1, const void *p2)
312 {
313         int index_1 = ((const struct image_info*)p1)->index;
314         int index_2 = ((const struct image_info*)p2)->index;
315         if (index_1 < index_2)
316                 return -1;
317         else if (index_1 > index_2)
318                 return 1;
319         else
320                 return 0;
321 }
322
323
324 /* Frees memory allocated inside a struct windows_info structure. */
325 static void
326 destroy_windows_info(struct windows_info *windows_info)
327 {
328         FREE(windows_info->product_name);
329         FREE(windows_info->edition_id);
330         FREE(windows_info->installation_type);
331         FREE(windows_info->hal);
332         FREE(windows_info->product_type);
333         FREE(windows_info->product_suite);
334         FREE(windows_info->pkeyconfigversion);
335         for (size_t i = 0; i < windows_info->num_languages; i++)
336                 FREE(windows_info->languages[i]);
337         FREE(windows_info->languages);
338         FREE(windows_info->default_language);
339         FREE(windows_info->system_root);
340 }
341
342 /* Frees memory allocated inside a struct image_info structure. */
343 static void
344 destroy_image_info(struct image_info *image_info)
345 {
346         FREE(image_info->name);
347         FREE(image_info->description);
348         FREE(image_info->flags);
349         FREE(image_info->display_name);
350         FREE(image_info->display_description);
351         destroy_windows_info(&image_info->windows_info);
352         memset(image_info, 0, sizeof(struct image_info));
353 }
354
355 void
356 free_wim_info(struct wim_info *info)
357 {
358         if (info) {
359                 if (info->images) {
360                         for (int i = 0; i < info->num_images; i++)
361                                 destroy_image_info(&info->images[i]);
362                         FREE(info->images);
363                 }
364                 FREE(info);
365         }
366 }
367
368 /* Reads the information from a <VERSION> element inside the <WINDOWS> element.
369  * */
370 static void
371 xml_read_windows_version(const xmlNode *version_node,
372                          struct windows_version* windows_version)
373 {
374         xmlNode *child;
375         for_node_child(version_node, child) {
376                 if (!node_is_element(child))
377                         continue;
378                 if (node_name_is(child, "MAJOR"))
379                         windows_version->major = node_get_u64(child);
380                 else if (node_name_is(child, "MINOR"))
381                         windows_version->minor = node_get_u64(child);
382                 else if (node_name_is(child, "BUILD"))
383                         windows_version->build = node_get_u64(child);
384                 else if (node_name_is(child, "SPBUILD"))
385                         windows_version->sp_build = node_get_u64(child);
386                 else if (node_name_is(child, "SPLEVEL"))
387                         windows_version->sp_level = node_get_u64(child);
388         }
389 }
390
391 /* Reads the information from a <LANGUAGE> element inside a <WINDOWS> element.
392  * */
393 static int
394 xml_read_languages(const xmlNode *languages_node,
395                    tchar ***languages_ret,
396                    size_t *num_languages_ret,
397                    tchar **default_language_ret)
398 {
399         xmlNode *child;
400         size_t num_languages = 0;
401         tchar **languages;
402         int ret;
403
404         for_node_child(languages_node, child)
405                 if (node_is_element(child) && node_name_is(child, "LANGUAGE"))
406                         num_languages++;
407
408         languages = CALLOC(num_languages, sizeof(languages[0]));
409         if (!languages)
410                 return WIMLIB_ERR_NOMEM;
411
412         *languages_ret = languages;
413         *num_languages_ret = num_languages;
414
415         ret = 0;
416         for_node_child(languages_node, child) {
417                 if (!node_is_element(child))
418                         continue;
419                 if (node_name_is(child, "LANGUAGE"))
420                         ret = node_get_string(child, languages++);
421                 else if (node_name_is(child, "DEFAULT"))
422                         ret = node_get_string(child, default_language_ret);
423                 if (ret != 0)
424                         break;
425         }
426         return ret;
427 }
428
429 /* Reads the information from a <WINDOWS> element inside an <IMAGE> element. */
430 static int
431 xml_read_windows_info(const xmlNode *windows_node,
432                       struct windows_info *windows_info)
433 {
434         xmlNode *child;
435         int ret = 0;
436
437         for_node_child(windows_node, child) {
438                 if (!node_is_element(child))
439                         continue;
440                 if (node_name_is(child, "ARCH")) {
441                         windows_info->arch = node_get_u64(child);
442                 } else if (node_name_is(child, "PRODUCTNAME")) {
443                         ret = node_get_string(child,
444                                               &windows_info->product_name);
445                 } else if (node_name_is(child, "EDITIONID")) {
446                         ret = node_get_string(child,
447                                               &windows_info->edition_id);
448                 } else if (node_name_is(child, "INSTALLATIONTYPE")) {
449                         ret = node_get_string(child,
450                                               &windows_info->installation_type);
451                 } else if (node_name_is(child, "PRODUCTTYPE")) {
452                         ret = node_get_string(child,
453                                               &windows_info->product_type);
454                 } else if (node_name_is(child, "PRODUCTSUITE")) {
455                         ret = node_get_string(child,
456                                               &windows_info->product_suite);
457                 } else if (node_name_is(child, "LANGUAGES")) {
458                         ret = xml_read_languages(child,
459                                                  &windows_info->languages,
460                                                  &windows_info->num_languages,
461                                                  &windows_info->default_language);
462                 } else if (node_name_is(child, "VERSION")) {
463                         xml_read_windows_version(child,
464                                                 &windows_info->windows_version);
465                         windows_info->windows_version_exists = true;
466                 } else if (node_name_is(child, "SYSTEMROOT")) {
467                         ret = node_get_string(child, &windows_info->system_root);
468                 } else if (node_name_is(child, "HAL")) {
469                         ret = node_get_string(child, &windows_info->hal);
470                 } else if (node_name_is(child, "SERVICINGDATA")) {
471                         xmlNode *grandchild;
472
473                         for_node_child(child, grandchild) {
474                                 if (node_is_element(grandchild) &&
475                                     node_name_is(grandchild, "PKEYCONFIGVERSION"))
476                                 {
477                                         ret = node_get_string(grandchild,
478                                                               &windows_info->pkeyconfigversion);
479                                 }
480                         }
481                 }
482
483                 if (ret != 0)
484                         return ret;
485         }
486         return ret;
487 }
488
489 /* Reads the information from an <IMAGE> element. */
490 static int
491 xml_read_image_info(xmlNode *image_node, struct image_info *image_info)
492 {
493         xmlNode *child;
494         xmlChar *index_prop;
495         int ret;
496
497         index_prop = xmlGetProp(image_node, "INDEX");
498         if (index_prop) {
499                 image_info->index = atoi(index_prop);
500                 FREE(index_prop);
501         } else {
502                 image_info->index = 1;
503         }
504
505         ret = 0;
506         for_node_child(image_node, child) {
507                 if (!node_is_element(child))
508                         continue;
509                 if (node_name_is(child, "DIRCOUNT"))
510                         image_info->dir_count = node_get_u64(child);
511                 else if (node_name_is(child, "FILECOUNT"))
512                         image_info->file_count = node_get_u64(child);
513                 else if (node_name_is(child, "TOTALBYTES"))
514                         image_info->total_bytes = node_get_u64(child);
515                 else if (node_name_is(child, "HARDLINKBYTES"))
516                         image_info->hard_link_bytes = node_get_u64(child);
517                 else if (node_name_is(child, "CREATIONTIME"))
518                         image_info->creation_time = node_get_timestamp(child);
519                 else if (node_name_is(child, "LASTMODIFICATIONTIME"))
520                         image_info->last_modification_time = node_get_timestamp(child);
521                 else if (node_name_is(child, "WINDOWS")) {
522                         DEBUG("Found <WINDOWS> tag");
523                         ret = xml_read_windows_info(child,
524                                                     &image_info->windows_info);
525                         image_info->windows_info_exists = true;
526                 } else if (node_name_is(child, "NAME")) {
527                         ret = node_get_string(child, &image_info->name);
528                 } else if (node_name_is(child, "DESCRIPTION")) {
529                         ret = node_get_string(child, &image_info->description);
530                 } else if (node_name_is(child, "FLAGS")) {
531                         ret = node_get_string(child, &image_info->flags);
532                 } else if (node_name_is(child, "DISPLAYNAME")) {
533                         ret = node_get_string(child, &image_info->display_name);
534                 } else if (node_name_is(child, "DISPLAYDESCRIPTION")) {
535                         ret = node_get_string(child, &image_info->display_description);
536                 } else if (node_name_is(child, "WIMBOOT")) {
537                         if (node_get_u64(child) == 1) {
538                                 image_info->wimboot = true;
539                         }
540                 }
541                 if (ret != 0)
542                         return ret;
543         }
544         if (!image_info->name) {
545                 tchar *empty_name;
546                 /*WARNING("Image with index %d has no name", image_info->index);*/
547                 empty_name = MALLOC(sizeof(tchar));
548                 if (!empty_name)
549                         return WIMLIB_ERR_NOMEM;
550                 *empty_name = T('\0');
551                 image_info->name = empty_name;
552         }
553         return ret;
554 }
555
556 /* Reads the information from a <WIM> element, which should be the root element
557  * of the XML tree. */
558 static int
559 xml_read_wim_info(const xmlNode *wim_node, struct wim_info **wim_info_ret)
560 {
561         struct wim_info *wim_info;
562         xmlNode *child;
563         int ret;
564         int num_images;
565         int i;
566
567         wim_info = CALLOC(1, sizeof(struct wim_info));
568         if (!wim_info)
569                 return WIMLIB_ERR_NOMEM;
570
571         /* Count how many images there are. */
572         num_images = 0;
573         for_node_child(wim_node, child) {
574                 if (node_is_element(child) && node_name_is(child, "IMAGE")) {
575                         if (unlikely(num_images == MAX_IMAGES)) {
576                                 ret = WIMLIB_ERR_IMAGE_COUNT;
577                                 goto err;
578                         }
579                         num_images++;
580                 }
581         }
582
583         if (num_images > 0) {
584                 /* Allocate the array of struct image_infos and fill them in. */
585                 wim_info->images = CALLOC(num_images, sizeof(wim_info->images[0]));
586                 if (!wim_info->images) {
587                         ret = WIMLIB_ERR_NOMEM;
588                         goto err;
589                 }
590                 wim_info->num_images = num_images;
591                 i = 0;
592                 for_node_child(wim_node, child) {
593                         if (!node_is_element(child))
594                                 continue;
595                         if (node_name_is(child, "IMAGE")) {
596                                 DEBUG("Found <IMAGE> tag");
597                                 ret = xml_read_image_info(child,
598                                                           &wim_info->images[i]);
599                                 if (ret != 0)
600                                         goto err;
601                                 i++;
602                         } else if (node_name_is(child, "TOTALBYTES")) {
603                                 wim_info->total_bytes = node_get_u64(child);
604                         } else if (node_name_is(child, "ESD")) {
605                                 xmlNode *esdchild;
606                                 for_node_child(child, esdchild) {
607                                         if (node_is_element(esdchild) &&
608                                             node_name_is(esdchild, "ENCRYPTED"))
609                                         {
610                                                 ret = WIMLIB_ERR_WIM_IS_ENCRYPTED;
611                                                 goto err;
612                                         }
613                                 }
614                         }
615                 }
616
617                 /* Sort the array of image info by image index. */
618                 qsort(wim_info->images, num_images,
619                       sizeof(struct image_info), sort_by_index);
620
621                 /* Make sure the image indices make sense */
622                 for (i = 0; i < num_images; i++) {
623                         if (wim_info->images[i].index != i + 1) {
624                                 ERROR("WIM images are not indexed [1...%d] "
625                                       "in XML data as expected",
626                                       num_images);
627                                 ret = WIMLIB_ERR_IMAGE_COUNT;
628                                 goto err;
629                         }
630                 }
631
632         }
633         *wim_info_ret = wim_info;
634         return 0;
635 err:
636         free_wim_info(wim_info);
637         return ret;
638 }
639
640 /* Prints the information contained in a `struct windows_info'.
641  *
642  * Warning: any strings printed here are in UTF-8 encoding.  If the locale
643  * character encoding is not UTF-8, the printed strings may be garbled. */
644 static void
645 print_windows_info(const struct windows_info *windows_info)
646 {
647         const struct windows_version *windows_version;
648
649         tprintf(T("Architecture:           %"TS"\n"),
650                 get_arch(windows_info->arch));
651
652         if (windows_info->product_name) {
653                 tprintf(T("Product Name:           %"TS"\n"),
654                         windows_info->product_name);
655         }
656
657         if (windows_info->edition_id) {
658                 tprintf(T("Edition ID:             %"TS"\n"),
659                         windows_info->edition_id);
660         }
661
662         if (windows_info->installation_type) {
663                 tprintf(T("Installation Type:      %"TS"\n"),
664                         windows_info->installation_type);
665         }
666
667         if (windows_info->hal) {
668                 tprintf(T("HAL:                    %"TS"\n"),
669                               windows_info->hal);
670         }
671
672         if (windows_info->product_type) {
673                 tprintf(T("Product Type:           %"TS"\n"),
674                         windows_info->product_type);
675         }
676
677         if (windows_info->product_suite) {
678                 tprintf(T("Product Suite:          %"TS"\n"),
679                         windows_info->product_suite);
680         }
681
682         tprintf(T("Languages:              "));
683         for (size_t i = 0; i < windows_info->num_languages; i++) {
684
685                 tfputs(windows_info->languages[i], stdout);
686                 tputchar(T(' '));
687         }
688         tputchar(T('\n'));
689         if (windows_info->default_language) {
690                 tprintf(T("Default Language:       %"TS"\n"),
691                         windows_info->default_language);
692         }
693         if (windows_info->system_root) {
694                 tprintf(T("System Root:            %"TS"\n"),
695                               windows_info->system_root);
696         }
697
698         if (windows_info->windows_version_exists) {
699                 windows_version = &windows_info->windows_version;
700                 tprintf(T("Major Version:          %"PRIu64"\n"),
701                         windows_version->major);
702                 tprintf(T("Minor Version:          %"PRIu64"\n"),
703                         windows_version->minor);
704                 tprintf(T("Build:                  %"PRIu64"\n"),
705                         windows_version->build);
706                 tprintf(T("Service Pack Build:     %"PRIu64"\n"),
707                         windows_version->sp_build);
708                 tprintf(T("Service Pack Level:     %"PRIu64"\n"),
709                         windows_version->sp_level);
710         }
711 }
712
713 static int
714 xml_write_string(xmlTextWriter *writer, const char *name,
715                  const tchar *tstr)
716 {
717         if (tstr) {
718                 char *utf8_str;
719                 int rc = tstr_to_utf8_simple(tstr, &utf8_str);
720                 if (rc)
721                         return rc;
722                 rc = xmlTextWriterWriteElement(writer, name, utf8_str);
723                 FREE(utf8_str);
724                 if (rc < 0)
725                         return rc;
726         }
727         return 0;
728 }
729
730 static int
731 xml_write_strings_from_specs(xmlTextWriter *writer,
732                              const void *struct_with_strings,
733                              const struct xml_string_spec specs[],
734                              size_t num_specs)
735 {
736         for (size_t i = 0; i < num_specs; i++) {
737                 int rc = xml_write_string(writer, specs[i].name,
738                                       *(const tchar * const *)
739                                         (struct_with_strings + specs[i].offset));
740                 if (rc)
741                         return rc;
742         }
743         return 0;
744 }
745
746 static int
747 dup_strings_from_specs(const void *old_struct_with_strings,
748                        void *new_struct_with_strings,
749                        const struct xml_string_spec specs[],
750                        size_t num_specs)
751 {
752         for (size_t i = 0; i < num_specs; i++) {
753                 const tchar *old_str = *(const tchar * const *)
754                                         ((const void*)old_struct_with_strings + specs[i].offset);
755                 tchar **new_str_p = (tchar **)((void*)new_struct_with_strings + specs[i].offset);
756                 if (old_str) {
757                         *new_str_p = TSTRDUP(old_str);
758                         if (!*new_str_p)
759                                 return WIMLIB_ERR_NOMEM;
760                 }
761         }
762         return 0;
763 }
764
765 /* Writes the information contained in a `struct windows_version' to the XML
766  * document being written.  This is the <VERSION> element inside the <WINDOWS>
767  * element. */
768 static int
769 xml_write_windows_version(xmlTextWriter *writer,
770                           const struct windows_version *version)
771 {
772         int rc;
773         rc = xmlTextWriterStartElement(writer, "VERSION");
774         if (rc < 0)
775                 return rc;
776
777         rc = xmlTextWriterWriteFormatElement(writer, "MAJOR", "%"PRIu64,
778                                              version->major);
779         if (rc < 0)
780                 return rc;
781
782         rc = xmlTextWriterWriteFormatElement(writer, "MINOR", "%"PRIu64,
783                                              version->minor);
784         if (rc < 0)
785                 return rc;
786
787         rc = xmlTextWriterWriteFormatElement(writer, "BUILD", "%"PRIu64,
788                                              version->build);
789         if (rc < 0)
790                 return rc;
791
792         rc = xmlTextWriterWriteFormatElement(writer, "SPBUILD", "%"PRIu64,
793                                              version->sp_build);
794         if (rc < 0)
795                 return rc;
796
797         rc = xmlTextWriterWriteFormatElement(writer, "SPLEVEL", "%"PRIu64,
798                                              version->sp_level);
799         if (rc < 0)
800                 return rc;
801
802         rc = xmlTextWriterEndElement(writer); /* </VERSION> */
803         if (rc < 0)
804                 return rc;
805
806         return 0;
807 }
808
809 /* Writes the information contained in a `struct windows_info' to the XML
810  * document being written. This is the <WINDOWS> element. */
811 static int
812 xml_write_windows_info(xmlTextWriter *writer,
813                        const struct windows_info *windows_info)
814 {
815         int rc;
816         rc = xmlTextWriterStartElement(writer, "WINDOWS");
817         if (rc < 0)
818                 return rc;
819
820         rc = xmlTextWriterWriteFormatElement(writer, "ARCH", "%"PRIu64,
821                                              windows_info->arch);
822         if (rc < 0)
823                 return rc;
824
825         rc = xml_write_strings_from_specs(writer,
826                                           windows_info,
827                                           windows_info_xml_string_specs,
828                                           ARRAY_LEN(windows_info_xml_string_specs));
829         if (rc)
830                 return rc;
831
832         if (windows_info->num_languages) {
833                 rc = xmlTextWriterStartElement(writer, "LANGUAGES");
834                 if (rc < 0)
835                         return rc;
836
837                 for (size_t i = 0; i < windows_info->num_languages; i++) {
838                         rc = xml_write_string(writer, "LANGUAGE",
839                                               windows_info->languages[i]);
840                         if (rc)
841                                 return rc;
842                 }
843
844                 rc = xml_write_string(writer, "DEFAULT",
845                                       windows_info->default_language);
846                 if (rc)
847                         return rc;
848
849                 rc = xmlTextWriterEndElement(writer); /* </LANGUAGES> */
850                 if (rc < 0)
851                         return rc;
852         }
853
854         if (windows_info->pkeyconfigversion) {
855                 rc = xmlTextWriterStartElement(writer, "SERVICINGDATA");
856                 if (rc < 0)
857                         return rc;
858
859                 rc = xml_write_string(writer, "PKEYCONFIGVERSION",
860                                       windows_info->pkeyconfigversion);
861                 if (rc)
862                         return rc;
863
864                 rc = xmlTextWriterEndElement(writer);
865                 if (rc < 0)
866                         return rc;
867         }
868
869         if (windows_info->windows_version_exists) {
870                 rc = xml_write_windows_version(writer, &windows_info->windows_version);
871                 if (rc)
872                         return rc;
873         }
874
875         rc = xml_write_string(writer, "SYSTEMROOT", windows_info->system_root);
876         if (rc)
877                 return rc;
878
879         rc = xmlTextWriterEndElement(writer); /* </WINDOWS> */
880         if (rc < 0)
881                 return rc;
882
883         return 0;
884 }
885
886 /* Writes a time element to the XML document being constructed in memory. */
887 static int
888 xml_write_time(xmlTextWriter *writer, const char *element_name, u64 time)
889 {
890         int rc;
891         rc = xmlTextWriterStartElement(writer, element_name);
892         if (rc < 0)
893                 return rc;
894
895         rc = xmlTextWriterWriteFormatElement(writer, "HIGHPART",
896                                              "0x%08"PRIX32, (u32)(time >> 32));
897         if (rc < 0)
898                 return rc;
899
900         rc = xmlTextWriterWriteFormatElement(writer, "LOWPART",
901                                              "0x%08"PRIX32, (u32)time);
902         if (rc < 0)
903                 return rc;
904
905         rc = xmlTextWriterEndElement(writer); /* </@element_name> */
906         if (rc < 0)
907                 return rc;
908         return 0;
909 }
910
911 /* Writes an <IMAGE> element to the XML document. */
912 static int
913 xml_write_image_info(xmlTextWriter *writer, const struct image_info *image_info)
914 {
915         int rc;
916         rc = xmlTextWriterStartElement(writer, "IMAGE");
917         if (rc < 0)
918                 return rc;
919
920         rc = xmlTextWriterWriteFormatAttribute(writer, "INDEX", "%d",
921                                                image_info->index);
922         if (rc < 0)
923                 return rc;
924
925         rc = xmlTextWriterWriteFormatElement(writer, "DIRCOUNT", "%"PRIu64,
926                                              image_info->dir_count);
927         if (rc < 0)
928                 return rc;
929
930         rc = xmlTextWriterWriteFormatElement(writer, "FILECOUNT", "%"PRIu64,
931                                              image_info->file_count);
932         if (rc < 0)
933                 return rc;
934
935         rc = xmlTextWriterWriteFormatElement(writer, "TOTALBYTES", "%"PRIu64,
936                                              image_info->total_bytes);
937         if (rc < 0)
938                 return rc;
939
940         rc = xmlTextWriterWriteFormatElement(writer, "HARDLINKBYTES", "%"PRIu64,
941                                              image_info->hard_link_bytes);
942         if (rc < 0)
943                 return rc;
944
945         rc = xml_write_time(writer, "CREATIONTIME", image_info->creation_time);
946         if (rc < 0)
947                 return rc;
948
949         rc = xml_write_time(writer, "LASTMODIFICATIONTIME",
950                             image_info->last_modification_time);
951         if (rc < 0)
952                 return rc;
953
954         if (image_info->windows_info_exists) {
955                 rc = xml_write_windows_info(writer, &image_info->windows_info);
956                 if (rc)
957                         return rc;
958         }
959
960         rc = xml_write_strings_from_specs(writer, image_info,
961                                           image_info_xml_string_specs,
962                                           ARRAY_LEN(image_info_xml_string_specs));
963         if (rc)
964                 return rc;
965
966         if (image_info->wimboot) {
967                 rc = xmlTextWriterWriteFormatElement(writer, "WIMBOOT", "%d", 1);
968                 if (rc < 0)
969                         return rc;
970         }
971
972         rc = xmlTextWriterEndElement(writer); /* </IMAGE> */
973         if (rc < 0)
974                 return rc;
975
976         return 0;
977 }
978
979
980
981 /* Makes space for another image in the XML information and return a pointer to
982  * it.*/
983 static struct image_info *
984 add_image_info_struct(struct wim_info *wim_info)
985 {
986         struct image_info *images;
987
988         images = CALLOC(wim_info->num_images + 1, sizeof(struct image_info));
989         if (!images)
990                 return NULL;
991         memcpy(images, wim_info->images,
992                wim_info->num_images * sizeof(struct image_info));
993         FREE(wim_info->images);
994         wim_info->images = images;
995         wim_info->num_images++;
996         return &images[wim_info->num_images - 1];
997 }
998
999 static int
1000 clone_windows_info(const struct windows_info *old, struct windows_info *new)
1001 {
1002         int ret;
1003
1004         ret = dup_strings_from_specs(old, new, windows_info_xml_string_specs,
1005                                      ARRAY_LEN(windows_info_xml_string_specs));
1006         if (ret)
1007                 return ret;
1008
1009         if (old->pkeyconfigversion) {
1010                 new->pkeyconfigversion = TSTRDUP(old->pkeyconfigversion);
1011                 if (new->pkeyconfigversion == NULL)
1012                         return WIMLIB_ERR_NOMEM;
1013         }
1014
1015         if (old->languages) {
1016                 new->languages = CALLOC(old->num_languages, sizeof(new->languages[0]));
1017                 if (!new->languages)
1018                         return WIMLIB_ERR_NOMEM;
1019                 new->num_languages = old->num_languages;
1020                 for (size_t i = 0; i < new->num_languages; i++) {
1021                         if (!old->languages[i])
1022                                 continue;
1023                         new->languages[i] = TSTRDUP(old->languages[i]);
1024                         if (!new->languages[i])
1025                                 return WIMLIB_ERR_NOMEM;
1026                 }
1027         }
1028         if (old->default_language &&
1029                         !(new->default_language = TSTRDUP(old->default_language)))
1030                 return WIMLIB_ERR_NOMEM;
1031         if (old->system_root && !(new->system_root = TSTRDUP(old->system_root)))
1032                 return WIMLIB_ERR_NOMEM;
1033         if (old->windows_version_exists) {
1034                 new->windows_version_exists = true;
1035                 memcpy(&new->windows_version, &old->windows_version,
1036                        sizeof(old->windows_version));
1037         }
1038         return 0;
1039 }
1040
1041 static int
1042 clone_image_info(const struct image_info *old, struct image_info *new)
1043 {
1044         int ret;
1045
1046         new->dir_count              = old->dir_count;
1047         new->file_count             = old->file_count;
1048         new->total_bytes            = old->total_bytes;
1049         new->hard_link_bytes        = old->hard_link_bytes;
1050         new->creation_time          = old->creation_time;
1051         new->last_modification_time = old->last_modification_time;
1052
1053         ret = dup_strings_from_specs(old, new,
1054                                      image_info_xml_string_specs,
1055                                      ARRAY_LEN(image_info_xml_string_specs));
1056         if (ret)
1057                 return ret;
1058
1059         if (old->windows_info_exists) {
1060                 new->windows_info_exists = true;
1061                 ret = clone_windows_info(&old->windows_info,
1062                                          &new->windows_info);
1063                 if (ret)
1064                         return ret;
1065         }
1066         return 0;
1067 }
1068
1069 /* Copies the XML information for an image between WIM files.
1070  *
1071  * @dest_image_name and @dest_image_description are ignored if they are NULL;
1072  * otherwise, they are used to override the image name and/or image description
1073  * from the XML data in the source WIM file.
1074  *
1075  * On failure, WIMLIB_ERR_NOMEM is returned and no changes are made.  Otherwise,
1076  * 0 is returned and the WIM information at *new_wim_info_p is modified.
1077  */
1078 int
1079 xml_export_image(const struct wim_info *old_wim_info,
1080                  int image,
1081                  struct wim_info **new_wim_info_p,
1082                  const tchar *dest_image_name,
1083                  const tchar *dest_image_description)
1084 {
1085         struct wim_info *new_wim_info;
1086         struct image_info *image_info;
1087         int ret;
1088
1089         DEBUG("Copying XML data between WIM files for source image %d.", image);
1090
1091         wimlib_assert(old_wim_info != NULL);
1092         wimlib_assert(image >= 1 && image <= old_wim_info->num_images);
1093
1094         if (*new_wim_info_p) {
1095                 new_wim_info = *new_wim_info_p;
1096         } else {
1097                 new_wim_info = CALLOC(1, sizeof(struct wim_info));
1098                 if (!new_wim_info)
1099                         goto err;
1100         }
1101
1102         image_info = add_image_info_struct(new_wim_info);
1103         if (!image_info)
1104                 goto err;
1105
1106         ret = clone_image_info(&old_wim_info->images[image - 1], image_info);
1107         if (ret != 0)
1108                 goto err_destroy_image_info;
1109
1110         image_info->index = new_wim_info->num_images;
1111
1112         if (dest_image_name) {
1113                 FREE(image_info->name);
1114                 image_info->name = TSTRDUP(dest_image_name);
1115                 if (!image_info->name)
1116                         goto err_destroy_image_info;
1117         }
1118         if (dest_image_description) {
1119                 FREE(image_info->description);
1120                 image_info->description = TSTRDUP(dest_image_description);
1121                 if (!image_info->description)
1122                         goto err_destroy_image_info;
1123         }
1124         *new_wim_info_p = new_wim_info;
1125         return 0;
1126 err_destroy_image_info:
1127         destroy_image_info(image_info);
1128 err:
1129         if (new_wim_info != *new_wim_info_p)
1130                 free_wim_info(new_wim_info);
1131         return WIMLIB_ERR_NOMEM;
1132 }
1133
1134 /* Removes an image from the XML information. */
1135 void
1136 xml_delete_image(struct wim_info **wim_info_p, int image)
1137 {
1138         struct wim_info *wim_info;
1139
1140         wim_info = *wim_info_p;
1141         wimlib_assert(image >= 1 && image <= wim_info->num_images);
1142         DEBUG("Deleting image %d from the XML data.", image);
1143
1144         destroy_image_info(&wim_info->images[image - 1]);
1145
1146         memmove(&wim_info->images[image - 1],
1147                 &wim_info->images[image],
1148                 (wim_info->num_images - image) * sizeof(struct image_info));
1149
1150         if (--wim_info->num_images == 0) {
1151                 free_wim_info(wim_info);
1152                 *wim_info_p = NULL;
1153         } else {
1154                 for (int i = image - 1; i < wim_info->num_images; i++)
1155                         wim_info->images[i].index--;
1156         }
1157 }
1158
1159 size_t
1160 xml_get_max_image_name_len(const WIMStruct *wim)
1161 {
1162         size_t max_len = 0;
1163         for (u32 i = 0; i < wim->hdr.image_count; i++)
1164                 max_len = max(max_len, tstrlen(wim->wim_info->images[i].name));
1165         return max_len;
1166 }
1167
1168 void
1169 xml_set_memory_allocator(void *(*malloc_func)(size_t),
1170                          void (*free_func)(void *),
1171                          void *(*realloc_func)(void *, size_t))
1172 {
1173         xmlMemSetup(free_func, malloc_func, realloc_func, STRDUP);
1174 }
1175
1176 static int
1177 calculate_dentry_statistics(struct wim_dentry *dentry, void *arg)
1178 {
1179         struct image_info *info = arg;
1180         const struct wim_inode *inode = dentry->d_inode;
1181         struct wim_lookup_table_entry *lte;
1182
1183         /* Update directory count and file count.
1184          *
1185          * Each dentry counts as either a file or a directory, but not both.
1186          * The root directory is an exception: it is not counted at all.
1187          *
1188          * Symbolic links and junction points (and presumably other reparse
1189          * points) count as regular files.  This is despite the fact that
1190          * junction points have FILE_ATTRIBUTE_DIRECTORY set.
1191          */
1192         if (dentry_is_root(dentry))
1193                 return 0;
1194
1195         if (inode_is_directory(inode))
1196                 info->dir_count++;
1197         else
1198                 info->file_count++;
1199
1200         /*
1201          * Update total bytes and hard link bytes.
1202          *
1203          * Unfortunately there are some inconsistencies/bugs in the way this is
1204          * done.
1205          *
1206          * If there are no alternate data streams in the image, the "total
1207          * bytes" is the sum of the size of the un-named data stream of each
1208          * inode times the link count of that inode.  In other words, it would
1209          * be the total number of bytes of regular files you would have if you
1210          * extracted the full image without any hard-links.  The "hard link
1211          * bytes" is equal to the "total bytes" minus the size of the un-named
1212          * data stream of each inode.  In other words, the "hard link bytes"
1213          * counts the size of the un-named data stream for all the links to each
1214          * inode except the first one.
1215          *
1216          * Reparse points and directories don't seem to be counted in either the
1217          * total bytes or the hard link bytes.
1218          *
1219          * And now we get to the most confusing part, the alternate data
1220          * streams.  They are not counted in the "total bytes".  However, if the
1221          * link count of an inode with alternate data streams is 2 or greater,
1222          * the size of all the alternate data streams is included in the "hard
1223          * link bytes", and this size is multiplied by the link count (NOT one
1224          * less than the link count).
1225          */
1226         lte = inode_unnamed_lte(inode, info->lookup_table);
1227         if (lte) {
1228                 info->total_bytes += lte->size;
1229                 if (!dentry_is_first_in_inode(dentry))
1230                         info->hard_link_bytes += lte->size;
1231         }
1232
1233         if (inode->i_nlink >= 2 && dentry_is_first_in_inode(dentry)) {
1234                 for (unsigned i = 0; i < inode->i_num_ads; i++) {
1235                         if (inode->i_ads_entries[i].stream_name_nbytes) {
1236                                 lte = inode_stream_lte(inode, i + 1, info->lookup_table);
1237                                 if (lte) {
1238                                         info->hard_link_bytes += inode->i_nlink *
1239                                                                  lte->size;
1240                                 }
1241                         }
1242                 }
1243         }
1244         return 0;
1245 }
1246
1247 /*
1248  * Calculate what to put in the <FILECOUNT>, <DIRCOUNT>, <TOTALBYTES>, and
1249  * <HARDLINKBYTES> elements of each <IMAGE>.
1250  *
1251  * Please note there is no official documentation for exactly how this is done.
1252  * But, see calculate_dentry_statistics().
1253  */
1254 void
1255 xml_update_image_info(WIMStruct *wim, int image)
1256 {
1257         struct image_info *image_info;
1258
1259         DEBUG("Updating the image info for image %d", image);
1260
1261         image_info = &wim->wim_info->images[image - 1];
1262
1263         image_info->file_count      = 0;
1264         image_info->dir_count       = 0;
1265         image_info->total_bytes     = 0;
1266         image_info->hard_link_bytes = 0;
1267         image_info->lookup_table = wim->lookup_table;
1268
1269         for_dentry_in_tree(wim->image_metadata[image - 1]->root_dentry,
1270                            calculate_dentry_statistics,
1271                            image_info);
1272         image_info->last_modification_time = get_wim_timestamp();
1273 }
1274
1275 /* Adds an image to the XML information. */
1276 int
1277 xml_add_image(WIMStruct *wim, const tchar *name)
1278 {
1279         struct wim_info *wim_info;
1280         struct image_info *image_info;
1281
1282         wimlib_assert(name != NULL);
1283
1284         /* If this is the first image, allocate the struct wim_info.  Otherwise
1285          * use the existing struct wim_info. */
1286         if (wim->wim_info) {
1287                 wim_info = wim->wim_info;
1288         } else {
1289                 wim_info = CALLOC(1, sizeof(struct wim_info));
1290                 if (!wim_info)
1291                         return WIMLIB_ERR_NOMEM;
1292         }
1293
1294         image_info = add_image_info_struct(wim_info);
1295         if (!image_info)
1296                 goto out_free_wim_info;
1297
1298         if (!(image_info->name = TSTRDUP(name)))
1299                 goto out_destroy_image_info;
1300
1301         wim->wim_info = wim_info;
1302         image_info->index = wim_info->num_images;
1303         image_info->creation_time = get_wim_timestamp();
1304         xml_update_image_info(wim, image_info->index);
1305         return 0;
1306
1307 out_destroy_image_info:
1308         destroy_image_info(image_info);
1309         wim_info->num_images--;
1310 out_free_wim_info:
1311         if (wim_info != wim->wim_info)
1312                 FREE(wim_info);
1313         return WIMLIB_ERR_NOMEM;
1314 }
1315
1316 /* Prints information about the specified image from struct wim_info structure.
1317  * */
1318 void
1319 print_image_info(const struct wim_info *wim_info, int image)
1320 {
1321         const struct image_info *image_info;
1322         const tchar *desc;
1323         tchar buf[50];
1324
1325         wimlib_assert(image >= 1 && image <= wim_info->num_images);
1326
1327         image_info = &wim_info->images[image - 1];
1328
1329         tprintf(T("Index:                  %d\n"), image_info->index);
1330         tprintf(T("Name:                   %"TS"\n"), image_info->name);
1331
1332         /* Always print the Description: part even if there is no
1333          * description. */
1334         if (image_info->description)
1335                 desc = image_info->description;
1336         else
1337                 desc = T("");
1338         tprintf(T("Description:            %"TS"\n"), desc);
1339
1340         if (image_info->display_name) {
1341                 tprintf(T("Display Name:           %"TS"\n"),
1342                         image_info->display_name);
1343         }
1344
1345         if (image_info->display_description) {
1346                 tprintf(T("Display Description:    %"TS"\n"),
1347                         image_info->display_description);
1348         }
1349
1350         tprintf(T("Directory Count:        %"PRIu64"\n"), image_info->dir_count);
1351         tprintf(T("File Count:             %"PRIu64"\n"), image_info->file_count);
1352         tprintf(T("Total Bytes:            %"PRIu64"\n"), image_info->total_bytes);
1353         tprintf(T("Hard Link Bytes:        %"PRIu64"\n"), image_info->hard_link_bytes);
1354
1355         wim_timestamp_to_str(image_info->creation_time, buf, sizeof(buf));
1356         tprintf(T("Creation Time:          %"TS"\n"), buf);
1357
1358         wim_timestamp_to_str(image_info->last_modification_time, buf, sizeof(buf));
1359         tprintf(T("Last Modification Time: %"TS"\n"), buf);
1360         if (image_info->windows_info_exists)
1361                 print_windows_info(&image_info->windows_info);
1362         if (image_info->flags)
1363                 tprintf(T("Flags:                  %"TS"\n"), image_info->flags);
1364         tprintf(T("WIMBoot compatible:     %"TS"\n"),
1365                 image_info->wimboot ? T("yes") : T("no"));
1366         tputchar('\n');
1367 }
1368
1369 void
1370 libxml_global_init(void)
1371 {
1372         xmlInitParser();
1373         xmlInitCharEncodingHandlers();
1374 }
1375
1376 void
1377 libxml_global_cleanup(void)
1378 {
1379         xmlCleanupParser();
1380         xmlCleanupCharEncodingHandlers();
1381 }
1382
1383 /* Reads the XML data from a WIM file.  */
1384 int
1385 read_wim_xml_data(WIMStruct *wim)
1386 {
1387         void *buf;
1388         size_t bufsize;
1389         u8 *xml_data;
1390         xmlDoc *doc;
1391         xmlNode *root;
1392         int ret;
1393
1394         ret = wimlib_get_xml_data(wim, &buf, &bufsize);
1395         if (ret)
1396                 goto out;
1397         xml_data = buf;
1398
1399         doc = xmlReadMemory((const char *)xml_data, bufsize,
1400                             NULL, "UTF-16LE", 0);
1401         if (!doc) {
1402                 ERROR("Failed to parse XML data");
1403                 ret = WIMLIB_ERR_XML;
1404                 goto out_free_xml_data;
1405         }
1406
1407         root = xmlDocGetRootElement(doc);
1408         if (!root || !node_is_element(root) || !node_name_is(root, "WIM")) {
1409                 ERROR("WIM XML data is invalid");
1410                 ret = WIMLIB_ERR_XML;
1411                 goto out_free_doc;
1412         }
1413
1414         ret = xml_read_wim_info(root, &wim->wim_info);
1415 out_free_doc:
1416         xmlFreeDoc(doc);
1417 out_free_xml_data:
1418         FREE(xml_data);
1419 out:
1420         return ret;
1421 }
1422
1423 /* Prepares an in-memory buffer containing the UTF-16LE XML data for a WIM file.
1424  *
1425  * total_bytes is the number to write in <TOTALBYTES>, or
1426  * WIM_TOTALBYTES_USE_EXISTING to use the existing value in memory, or
1427  * WIM_TOTALBYTES_OMIT to omit <TOTALBYTES> entirely.
1428  */
1429 static int
1430 prepare_wim_xml_data(WIMStruct *wim, int image, u64 total_bytes,
1431                      u8 **xml_data_ret, size_t *xml_len_ret)
1432 {
1433         xmlCharEncodingHandler *encoding_handler;
1434         xmlBuffer *buf;
1435         xmlOutputBuffer *outbuf;
1436         xmlTextWriter *writer;
1437         int ret;
1438         int first, last;
1439         const xmlChar *content;
1440         int len;
1441         u8 *xml_data;
1442         size_t xml_len;
1443
1444         /* Open an xmlTextWriter that writes to an in-memory buffer using
1445          * UTF-16LE encoding.  */
1446
1447         encoding_handler = xmlGetCharEncodingHandler(XML_CHAR_ENCODING_UTF16LE);
1448         if (!encoding_handler) {
1449                 ERROR("Failed to get XML character encoding handler for UTF-16LE");
1450                 ret = WIMLIB_ERR_LIBXML_UTF16_HANDLER_NOT_AVAILABLE;
1451                 goto out;
1452         }
1453
1454         buf = xmlBufferCreate();
1455         if (!buf) {
1456                 ERROR("Failed to create xmlBuffer");
1457                 ret = WIMLIB_ERR_NOMEM;
1458                 goto out;
1459         }
1460
1461         outbuf = xmlOutputBufferCreateBuffer(buf, encoding_handler);
1462         if (!outbuf) {
1463                 ERROR("Failed to allocate xmlOutputBuffer");
1464                 ret = WIMLIB_ERR_NOMEM;
1465                 goto out_buffer_free;
1466         }
1467
1468         writer = xmlNewTextWriter(outbuf);
1469         if (!writer) {
1470                 ERROR("Failed to allocate xmlTextWriter");
1471                 ret = WIMLIB_ERR_NOMEM;
1472                 goto out_output_buffer_close;
1473         }
1474
1475         /* Write the XML document.  */
1476
1477         ret = xmlTextWriterStartElement(writer, "WIM");
1478         if (ret < 0)
1479                 goto out_write_error;
1480
1481         /* The contents of the <TOTALBYTES> element in the XML data, under the
1482          * <WIM> element (not the <IMAGE> element), is for non-split WIMs the
1483          * size of the WIM file excluding the XML data and integrity table.
1484          * For split WIMs, <TOTALBYTES> takes into account the entire WIM, not
1485          * just the current part.  */
1486         if (total_bytes != WIM_TOTALBYTES_OMIT) {
1487                 if (total_bytes == WIM_TOTALBYTES_USE_EXISTING) {
1488                         if (wim->wim_info)
1489                                 total_bytes = wim->wim_info->total_bytes;
1490                         else
1491                                 total_bytes = 0;
1492                 }
1493                 ret = xmlTextWriterWriteFormatElement(writer, "TOTALBYTES",
1494                                                       "%"PRIu64, total_bytes);
1495                 if (ret < 0)
1496                         goto out_write_error;
1497         }
1498
1499         if (image == WIMLIB_ALL_IMAGES) {
1500                 first = 1;
1501                 last = wim->hdr.image_count;
1502         } else {
1503                 first = image;
1504                 last = image;
1505         }
1506
1507         for (int i = first; i <= last; i++) {
1508                 ret = xml_write_image_info(writer, &wim->wim_info->images[i - 1]);
1509                 if (ret) {
1510                         if (ret < 0)
1511                                 goto out_write_error;
1512                         goto out_free_text_writer;
1513                 }
1514         }
1515
1516         ret = xmlTextWriterEndElement(writer);
1517         if (ret < 0)
1518                 goto out_write_error;
1519
1520         ret = xmlTextWriterEndDocument(writer);
1521         if (ret < 0)
1522                 goto out_write_error;
1523
1524         ret = xmlTextWriterFlush(writer);
1525         if (ret < 0)
1526                 goto out_write_error;
1527
1528         /* Retrieve the buffer into which the document was written.  */
1529
1530         content = xmlBufferContent(buf);
1531         len = xmlBufferLength(buf);
1532
1533         /* Copy the data into a new buffer, and prefix it with the UTF-16LE BOM
1534          * (byte order mark), which is required by MS's software to understand
1535          * the data.  */
1536
1537         xml_len = len + 2;
1538         xml_data = MALLOC(xml_len);
1539         if (!xml_data) {
1540                 ret = WIMLIB_ERR_NOMEM;
1541                 goto out_free_text_writer;
1542         }
1543         xml_data[0] = 0xff;
1544         xml_data[1] = 0xfe;
1545         memcpy(&xml_data[2], content, len);
1546
1547         /* Clean up libxml objects and return success.  */
1548         *xml_data_ret = xml_data;
1549         *xml_len_ret = xml_len;
1550         ret = 0;
1551 out_free_text_writer:
1552         /* xmlFreeTextWriter will free the attached xmlOutputBuffer.  */
1553         xmlFreeTextWriter(writer);
1554         goto out_buffer_free;
1555 out_output_buffer_close:
1556         xmlOutputBufferClose(outbuf);
1557 out_buffer_free:
1558         xmlBufferFree(buf);
1559 out:
1560         DEBUG("ret=%d", ret);
1561         return ret;
1562
1563 out_write_error:
1564         ERROR("Error writing XML data");
1565         ret = WIMLIB_ERR_WRITE;
1566         goto out_free_text_writer;
1567 }
1568
1569 /* Writes the XML data to a WIM file.  */
1570 int
1571 write_wim_xml_data(WIMStruct *wim, int image, u64 total_bytes,
1572                    struct wim_reshdr *out_reshdr,
1573                    int write_resource_flags)
1574 {
1575         int ret;
1576         u8 *xml_data;
1577         size_t xml_len;
1578
1579         DEBUG("Writing WIM XML data (image=%d, offset=%"PRIu64")",
1580               image, wim->out_fd.offset);
1581
1582         ret = prepare_wim_xml_data(wim, image, total_bytes,
1583                                    &xml_data, &xml_len);
1584         if (ret)
1585                 return ret;
1586
1587         /* Write the XML data uncompressed.  Although wimlib can handle
1588          * compressed XML data, MS software cannot.  */
1589         ret = write_wim_resource_from_buffer(xml_data,
1590                                              xml_len,
1591                                              WIM_RESHDR_FLAG_METADATA,
1592                                              &wim->out_fd,
1593                                              WIMLIB_COMPRESSION_TYPE_NONE,
1594                                              0,
1595                                              out_reshdr,
1596                                              NULL,
1597                                              write_resource_flags);
1598         FREE(xml_data);
1599         DEBUG("ret=%d", ret);
1600         return ret;
1601 }
1602
1603 /* API function documented in wimlib.h  */
1604 WIMLIBAPI const tchar *
1605 wimlib_get_image_name(const WIMStruct *wim, int image)
1606 {
1607         if (image < 1 || image > wim->hdr.image_count)
1608                 return NULL;
1609         return wim->wim_info->images[image - 1].name;
1610 }
1611
1612 /* API function documented in wimlib.h  */
1613 WIMLIBAPI const tchar *
1614 wimlib_get_image_description(const WIMStruct *wim, int image)
1615 {
1616         if (image < 1 || image > wim->hdr.image_count)
1617                 return NULL;
1618         return wim->wim_info->images[image - 1].description;
1619 }
1620
1621 /* API function documented in wimlib.h  */
1622 WIMLIBAPI bool
1623 wimlib_image_name_in_use(const WIMStruct *wim, const tchar *name)
1624 {
1625         if (!name || !*name)
1626                 return false;
1627         for (int i = 1; i <= wim->hdr.image_count; i++)
1628                 if (!tstrcmp(wim->wim_info->images[i - 1].name, name))
1629                         return true;
1630         return false;
1631 }
1632
1633
1634 /* API function documented in wimlib.h  */
1635 WIMLIBAPI int
1636 wimlib_get_xml_data(WIMStruct *wim, void **buf_ret, size_t *bufsize_ret)
1637 {
1638         const struct wim_reshdr *xml_reshdr;
1639
1640         if (wim->filename == NULL && filedes_is_seekable(&wim->in_fd))
1641                 return WIMLIB_ERR_INVALID_PARAM;
1642
1643         if (buf_ret == NULL || bufsize_ret == NULL)
1644                 return WIMLIB_ERR_INVALID_PARAM;
1645
1646         xml_reshdr = &wim->hdr.xml_data_reshdr;
1647
1648         DEBUG("Reading XML data.");
1649         *bufsize_ret = xml_reshdr->uncompressed_size;
1650         return wim_reshdr_to_data(xml_reshdr, wim, buf_ret);
1651 }
1652
1653 WIMLIBAPI int
1654 wimlib_extract_xml_data(WIMStruct *wim, FILE *fp)
1655 {
1656         int ret;
1657         void *buf;
1658         size_t bufsize;
1659
1660         ret = wimlib_get_xml_data(wim, &buf, &bufsize);
1661         if (ret)
1662                 return ret;
1663
1664         if (fwrite(buf, 1, bufsize, fp) != bufsize) {
1665                 ERROR_WITH_ERRNO("Failed to extract XML data");
1666                 ret = WIMLIB_ERR_WRITE;
1667         }
1668         FREE(buf);
1669         return ret;
1670 }
1671
1672 /* API function documented in wimlib.h  */
1673 WIMLIBAPI int
1674 wimlib_set_image_name(WIMStruct *wim, int image, const tchar *name)
1675 {
1676         tchar *p;
1677         int i;
1678         int ret;
1679
1680         DEBUG("Setting the name of image %d to %"TS, image, name);
1681
1682         ret = can_modify_wim(wim);
1683         if (ret)
1684                 return ret;
1685
1686         if (name == NULL)
1687                 name = T("");
1688
1689         if (image < 1 || image > wim->hdr.image_count) {
1690                 ERROR("%d is not a valid image", image);
1691                 return WIMLIB_ERR_INVALID_IMAGE;
1692         }
1693
1694         for (i = 1; i <= wim->hdr.image_count; i++) {
1695                 if (i == image)
1696                         continue;
1697                 if (!tstrcmp(wim->wim_info->images[i - 1].name, name)) {
1698                         ERROR("The name \"%"TS"\" is already in use in the WIM!",
1699                               name);
1700                         return WIMLIB_ERR_IMAGE_NAME_COLLISION;
1701                 }
1702         }
1703
1704         p = TSTRDUP(name);
1705         if (!p)
1706                 return WIMLIB_ERR_NOMEM;
1707
1708         FREE(wim->wim_info->images[image - 1].name);
1709         wim->wim_info->images[image - 1].name = p;
1710         return 0;
1711 }
1712
1713 static int
1714 do_set_image_info_str(WIMStruct *wim, int image, const tchar *tstr,
1715                       size_t offset)
1716 {
1717         tchar *tstr_copy;
1718         tchar **dest_tstr_p;
1719         int ret;
1720
1721         ret = can_modify_wim(wim);
1722         if (ret)
1723                 return ret;
1724
1725         if (image < 1 || image > wim->hdr.image_count) {
1726                 ERROR("%d is not a valid image", image);
1727                 return WIMLIB_ERR_INVALID_IMAGE;
1728         }
1729         if (tstr) {
1730                 tstr_copy = TSTRDUP(tstr);
1731                 if (!tstr_copy)
1732                         return WIMLIB_ERR_NOMEM;
1733         } else {
1734                 tstr_copy = NULL;
1735         }
1736         dest_tstr_p = (tchar**)((void*)&wim->wim_info->images[image - 1] + offset);
1737
1738         FREE(*dest_tstr_p);
1739         *dest_tstr_p = tstr_copy;
1740         return 0;
1741 }
1742
1743 /* API function documented in wimlib.h  */
1744 WIMLIBAPI int
1745 wimlib_set_image_descripton(WIMStruct *wim, int image,
1746                             const tchar *description)
1747 {
1748         return do_set_image_info_str(wim, image, description,
1749                                      offsetof(struct image_info, description));
1750 }
1751
1752 /* API function documented in wimlib.h  */
1753 WIMLIBAPI int
1754 wimlib_set_image_flags(WIMStruct *wim, int image, const tchar *flags)
1755 {
1756         return do_set_image_info_str(wim, image, flags,
1757                                      offsetof(struct image_info, flags));
1758 }