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