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