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