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