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