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