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