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