]> wimlib.net Git - wimlib/blob - src/xml.c
Replace rename()
[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         utf8char  *product_name;
53         utf8char  *edition_id;
54         utf8char  *installation_type;
55         utf8char  *hal;
56         utf8char  *product_type;
57         utf8char  *product_suite;
58         utf8char **languages;
59         utf8char  *default_language;
60         size_t     num_languages;
61         utf8char  *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         utf8char *name;
77         utf8char *description;
78         utf8char *display_name;
79         utf8char *display_description;
80         union {
81                 utf8char *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 char *
90 get_arch(int arch)
91 {
92         switch (arch) {
93         case 0:
94                 return "x86";
95         case 6:
96                 return "ia64";
97         case 9:
98                 return "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         wimlib_printf("Architecture:           %s\n",
503                       get_arch(windows_info->arch) ?: "unknown");
504
505         if (windows_info->product_name)
506                 wimlib_printf("Product Name:           %U\n",
507                               windows_info->product_name);
508
509         if (windows_info->edition_id)
510                 wimlib_printf("Edition ID:             %U\n",
511                               windows_info->edition_id);
512
513         if (windows_info->installation_type)
514                 wimlib_printf("Installation Type:      %U\n",
515                               windows_info->installation_type);
516
517         if (windows_info->hal)
518                 wimlib_printf("HAL:                    %U\n",
519                               windows_info->hal);
520
521         if (windows_info->product_type)
522                 wimlib_printf("Product Type:           %U\n",
523                               windows_info->product_type);
524
525         if (windows_info->product_suite)
526                 wimlib_printf("Product Suite:          %U\n",
527                               windows_info->product_suite);
528
529         printf("Languages:              ");
530         for (size_t i = 0; i < windows_info->num_languages; i++) {
531                 wimlib_printf("%U", windows_info->languages[i]);
532                 putchar(' ');
533         }
534         putchar('\n');
535         if (windows_info->default_language)
536                 wimlib_printf("Default Language:       %U\n",
537                        windows_info->default_language);
538         if (windows_info->system_root)
539                 wimlib_printf("System Root:            %U\n",
540                               windows_info->system_root);
541         if (windows_info->windows_version_exists) {
542                 windows_version = &windows_info->windows_version;
543                 printf("Major Version:          %"PRIu64"\n",
544                        windows_version->major);
545                 printf("Minor Version:          %"PRIu64"\n",
546                        windows_version->minor);
547                 printf("Build:                  %"PRIu64"\n",
548                        windows_version->build);
549                 printf("Service Pack Build:     %"PRIu64"\n",
550                        windows_version->sp_build);
551                 printf("Service Pack Level:     %"PRIu64"\n",
552                        windows_version->sp_level);
553         }
554 }
555
556
557 /* Writes the information contained in a `struct windows_version' to the XML
558  * document being written.  This is the <VERSION> element inside the <WINDOWS>
559  * element. */
560 static int
561 xml_write_windows_version(xmlTextWriter *writer,
562                           const struct windows_version *version)
563 {
564         int rc;
565         rc = xmlTextWriterStartElement(writer, "VERSION");
566         if (rc < 0)
567                 return rc;
568
569         rc = xmlTextWriterWriteFormatElement(writer, "MAJOR", "%"PRIu64,
570                                              version->major);
571         if (rc < 0)
572                 return rc;
573
574         rc = xmlTextWriterWriteFormatElement(writer, "MINOR", "%"PRIu64,
575                                              version->minor);
576         if (rc < 0)
577                 return rc;
578
579         rc = xmlTextWriterWriteFormatElement(writer, "BUILD", "%"PRIu64,
580                                              version->build);
581         if (rc < 0)
582                 return rc;
583
584         rc = xmlTextWriterWriteFormatElement(writer, "SPBUILD", "%"PRIu64,
585                                              version->sp_build);
586         if (rc < 0)
587                 return rc;
588
589         rc = xmlTextWriterWriteFormatElement(writer, "SPLEVEL", "%"PRIu64,
590                                              version->sp_level);
591         if (rc < 0)
592                 return rc;
593
594         return xmlTextWriterEndElement(writer); /* </VERSION> */
595 }
596
597 /* Writes the information contained in a `struct windows_info' to the XML
598  * document being written. This is the <WINDOWS> element. */
599 static int
600 xml_write_windows_info(xmlTextWriter *writer,
601                        const struct windows_info *windows_info)
602 {
603         int rc;
604         rc = xmlTextWriterStartElement(writer, "WINDOWS");
605         if (rc < 0)
606                 return rc;
607
608         rc = xmlTextWriterWriteFormatElement(writer, "ARCH", "%"PRIu64,
609                                              windows_info->arch);
610         if (rc < 0)
611                 return rc;
612
613         if (windows_info->product_name) {
614                 rc = xmlTextWriterWriteElement(writer, "PRODUCTNAME",
615                                                windows_info->product_name);
616                 if (rc < 0)
617                         return rc;
618         }
619
620         if (windows_info->edition_id) {
621                 rc = xmlTextWriterWriteElement(writer, "EDITIONID",
622                                                windows_info->edition_id);
623                 if (rc < 0)
624                         return rc;
625         }
626
627         if (windows_info->installation_type) {
628                 rc = xmlTextWriterWriteElement(writer, "INSTALLATIONTYPE",
629                                                windows_info->installation_type);
630                 if (rc < 0)
631                         return rc;
632         }
633
634         if (windows_info->hal) {
635                 rc = xmlTextWriterWriteElement(writer, "HAL",
636                                                windows_info->hal);
637                 if (rc < 0)
638                         return rc;
639         }
640
641         if (windows_info->product_type) {
642                 rc = xmlTextWriterWriteElement(writer, "PRODUCTTYPE",
643                                                windows_info->product_type);
644                 if (rc < 0)
645                         return rc;
646         }
647
648         if (windows_info->product_suite) {
649                 rc = xmlTextWriterWriteElement(writer, "PRODUCTSUITE",
650                                                windows_info->product_suite);
651                 if (rc < 0)
652                         return rc;
653         }
654
655         if (windows_info->num_languages) {
656                 rc = xmlTextWriterStartElement(writer, "LANGUAGES");
657                 if (rc < 0)
658                         return rc;
659
660                 for (size_t i = 0; i < windows_info->num_languages; i++) {
661                         rc = xmlTextWriterWriteElement(writer, "LANGUAGE",
662                                                        windows_info->languages[i]);
663                         if (rc < 0)
664                                 return rc;
665                 }
666                 rc = xmlTextWriterWriteElement(writer, "DEFAULT",
667                                                windows_info->default_language);
668                 if (rc < 0)
669                         return rc;
670
671                 rc = xmlTextWriterEndElement(writer); /* </LANGUAGES> */
672                 if (rc < 0)
673                         return rc;
674         }
675
676         if (windows_info->windows_version_exists) {
677                 rc = xml_write_windows_version(writer, &windows_info->windows_version);
678                 if (rc < 0)
679                         return rc;
680         }
681
682         if (windows_info->system_root) {
683                 rc = xmlTextWriterWriteElement(writer, "SYSTEMROOT",
684                                                windows_info->system_root);
685                 if (rc < 0)
686                         return rc;
687         }
688
689         return xmlTextWriterEndElement(writer); /* </WINDOWS> */
690 }
691
692 /* Writes a time element to the XML document being constructed in memory. */
693 static int
694 xml_write_time(xmlTextWriter *writer, const utf8char *element_name, u64 time)
695 {
696         int rc;
697         rc = xmlTextWriterStartElement(writer, element_name);
698         if (rc < 0)
699                 return rc;
700
701         rc = xmlTextWriterWriteFormatElement(writer, "HIGHPART",
702                                              "0x%08"PRIX32, (u32)(time >> 32));
703         if (rc < 0)
704                 return rc;
705
706         rc = xmlTextWriterWriteFormatElement(writer, "LOWPART",
707                                              "0x%08"PRIX32, (u32)time);
708         if (rc < 0)
709                 return rc;
710
711         rc = xmlTextWriterEndElement(writer); /* </@element_name> */
712         if (rc < 0)
713                 return rc;
714         return 0;
715 }
716
717 /* Writes an <IMAGE> element to the XML document. */
718 static int
719 xml_write_image_info(xmlTextWriter *writer, const struct image_info *image_info)
720 {
721         int rc;
722         rc = xmlTextWriterStartElement(writer, "IMAGE");
723         if (rc < 0)
724                 return rc;
725
726         rc = xmlTextWriterWriteFormatAttribute(writer, "INDEX", "%d",
727                                                image_info->index);
728         if (rc < 0)
729                 return rc;
730
731         rc = xmlTextWriterWriteFormatElement(writer, "DIRCOUNT", "%"PRIu64,
732                                              image_info->dir_count);
733         if (rc < 0)
734                 return rc;
735
736         rc = xmlTextWriterWriteFormatElement(writer, "FILECOUNT", "%"PRIu64,
737                                              image_info->file_count);
738         if (rc < 0)
739                 return rc;
740
741         rc = xmlTextWriterWriteFormatElement(writer, "TOTALBYTES", "%"PRIu64,
742                                              image_info->total_bytes);
743         if (rc < 0)
744                 return rc;
745
746         rc = xmlTextWriterWriteFormatElement(writer, "HARDLINKBYTES", "%"PRIu64,
747                                              image_info->hard_link_bytes);
748         if (rc < 0)
749                 return rc;
750
751         rc = xml_write_time(writer, "CREATIONTIME", image_info->creation_time);
752         if (rc < 0)
753                 return rc;
754
755         rc = xml_write_time(writer, "LASTMODIFICATIONTIME",
756                             image_info->last_modification_time);
757         if (rc < 0)
758                 return rc;
759
760         if (image_info->windows_info_exists) {
761                 rc = xml_write_windows_info(writer, &image_info->windows_info);
762                 if (rc < 0)
763                         return rc;
764         }
765
766         if (image_info->name) {
767                 rc = xmlTextWriterWriteElement(writer, "NAME",
768                                                image_info->name);
769                 if (rc < 0)
770                         return rc;
771         }
772
773         if (image_info->description) {
774                 rc = xmlTextWriterWriteElement(writer, "DESCRIPTION",
775                                                image_info->description);
776                 if (rc < 0)
777                         return rc;
778         }
779         if (image_info->display_name) {
780                 rc = xmlTextWriterWriteElement(writer, "DISPLAYNAME",
781                                                image_info->display_name);
782                 if (rc < 0)
783                         return rc;
784         }
785         if (image_info->display_description) {
786                 rc = xmlTextWriterWriteElement(writer, "DISPLAYDESCRIPTION",
787                                                image_info->display_description);
788                 if (rc < 0)
789                         return rc;
790         }
791
792         if (image_info->flags) {
793                 rc = xmlTextWriterWriteElement(writer, "FLAGS",
794                                                image_info->flags);
795                 if (rc < 0)
796                         return rc;
797         }
798
799         return xmlTextWriterEndElement(writer); /* </IMAGE> */
800 }
801
802
803
804 /* Makes space for another image in the XML information and return a pointer to
805  * it.*/
806 static struct image_info *
807 add_image_info_struct(struct wim_info *wim_info)
808 {
809         struct image_info *images;
810
811         images = CALLOC(wim_info->num_images + 1, sizeof(struct image_info));
812         if (!images)
813                 return NULL;
814         memcpy(images, wim_info->images,
815                wim_info->num_images * sizeof(struct image_info));
816         FREE(wim_info->images);
817         wim_info->images = images;
818         wim_info->num_images++;
819         return &images[wim_info->num_images - 1];
820 }
821
822 static int
823 clone_windows_info(const struct windows_info *old, struct windows_info *new)
824 {
825         if (old->product_name && !(new->product_name = STRDUP(old->product_name)))
826                 return WIMLIB_ERR_NOMEM;
827         if (old->edition_id && !(new->edition_id = STRDUP(old->edition_id)))
828                 return WIMLIB_ERR_NOMEM;
829         if (old->installation_type && !(new->installation_type =
830                                         STRDUP(old->installation_type)))
831                 return WIMLIB_ERR_NOMEM;
832         if (old->hal && !(new->hal = STRDUP(old->hal)))
833                 return WIMLIB_ERR_NOMEM;
834         if (old->product_type && !(new->product_type = STRDUP(old->product_type)))
835                 return WIMLIB_ERR_NOMEM;
836         if (old->product_suite && !(new->product_suite = STRDUP(old->product_suite)))
837                 return WIMLIB_ERR_NOMEM;
838
839         if (old->languages) {
840                 new->languages = CALLOC(old->num_languages, sizeof(new->languages[0]));
841                 if (!new->languages)
842                         return WIMLIB_ERR_NOMEM;
843                 new->num_languages = old->num_languages;
844                 for (size_t i = 0; i < new->num_languages; i++) {
845                         if (!old->languages[i])
846                                 continue;
847                         new->languages[i] = STRDUP(old->languages[i]);
848                         if (!new->languages[i])
849                                 return WIMLIB_ERR_NOMEM;
850                 }
851         }
852         if (old->default_language &&
853                         !(new->default_language = STRDUP(old->default_language)))
854                 return WIMLIB_ERR_NOMEM;
855         if (old->system_root && !(new->system_root = STRDUP(old->system_root)))
856                 return WIMLIB_ERR_NOMEM;
857         if (old->windows_version_exists) {
858                 new->windows_version_exists = true;
859                 memcpy(&new->windows_version, &old->windows_version,
860                        sizeof(old->windows_version));
861         }
862         return 0;
863 }
864
865 static int
866 clone_image_info(const struct image_info *old, struct image_info *new)
867 {
868         new->dir_count              = old->dir_count;
869         new->file_count             = old->file_count;
870         new->total_bytes            = old->total_bytes;
871         new->hard_link_bytes        = old->hard_link_bytes;
872         new->creation_time          = old->creation_time;
873         new->last_modification_time = old->last_modification_time;
874
875         if (!(new->name = STRDUP(old->name)))
876                 return WIMLIB_ERR_NOMEM;
877
878         if (old->description)
879                 if (!(new->description = STRDUP(old->description)))
880                         return WIMLIB_ERR_NOMEM;
881
882         if (old->display_name)
883                 if (!(new->display_name = STRDUP(old->display_name)))
884                         return WIMLIB_ERR_NOMEM;
885
886         if (old->display_description)
887                 if (!(new->display_description = STRDUP(old->display_description)))
888                         return WIMLIB_ERR_NOMEM;
889
890         if (old->flags)
891                 if (!(new->flags = STRDUP(old->flags)))
892                         return WIMLIB_ERR_NOMEM;
893
894         if (old->windows_info_exists) {
895                 new->windows_info_exists = true;
896                 return clone_windows_info(&old->windows_info,
897                                           &new->windows_info);
898         }
899         return 0;
900 }
901
902 /* Copies the XML information for an image between WIM files.
903  *
904  * @dest_image_name and @dest_image_description are ignored if they are NULL;
905  * otherwise, they are used to override the image name and/or image description
906  * from the XML data in the source WIM file.
907  *
908  * On failure, WIMLIB_ERR_NOMEM is returned and no changes are made.  Otherwise,
909  * 0 is returned and the WIM information at *new_wim_info_p is modified.
910  */
911 int
912 xml_export_image(const struct wim_info *old_wim_info,
913                  int image,
914                  struct wim_info **new_wim_info_p,
915                  const utf8char *dest_image_name,
916                  const utf8char *dest_image_description)
917 {
918         struct wim_info *new_wim_info;
919         struct image_info *image_info;
920         int ret;
921
922         DEBUG("Copying XML data between WIM files for source image %d.", image);
923
924         wimlib_assert(old_wim_info != NULL);
925         wimlib_assert(image >= 1 && image <= old_wim_info->num_images);
926
927         if (*new_wim_info_p) {
928                 new_wim_info = *new_wim_info_p;
929         } else {
930                 new_wim_info = CALLOC(1, sizeof(struct wim_info));
931                 if (!new_wim_info)
932                         goto err;
933         }
934
935         image_info = add_image_info_struct(new_wim_info);
936         if (!image_info)
937                 goto err;
938
939         ret = clone_image_info(&old_wim_info->images[image - 1], image_info);
940         if (ret != 0)
941                 goto err_destroy_image_info;
942
943         image_info->index = new_wim_info->num_images;
944
945         if (dest_image_name) {
946                 FREE(image_info->name);
947                 image_info->name = STRDUP(dest_image_name);
948                 if (!image_info->name)
949                         goto err_destroy_image_info;
950         }
951         if (dest_image_description) {
952                 FREE(image_info->description);
953                 image_info->description = STRDUP(dest_image_description);
954                 if (!image_info->description)
955                         goto err_destroy_image_info;
956         }
957         *new_wim_info_p = new_wim_info;
958         return 0;
959 err_destroy_image_info:
960         destroy_image_info(image_info);
961 err:
962         if (new_wim_info != *new_wim_info_p)
963                 free_wim_info(new_wim_info);
964         return WIMLIB_ERR_NOMEM;
965 }
966
967 /* Removes an image from the XML information. */
968 void
969 xml_delete_image(struct wim_info **wim_info_p, int image)
970 {
971         struct wim_info *wim_info;
972
973         DEBUG("Deleting image %d from the XML data.", image);
974
975         wim_info = *wim_info_p;
976
977         destroy_image_info(&wim_info->images[image - 1]);
978
979         memmove(&wim_info->images[image - 1],
980                 &wim_info->images[image],
981                 (wim_info->num_images - image) * sizeof(struct image_info));
982
983         if (--wim_info->num_images == 0) {
984                 free_wim_info(wim_info);
985                 *wim_info_p = NULL;
986         } else {
987                 for (int i = image - 1; i < wim_info->num_images; i++)
988                         wim_info->images[i].index--;
989         }
990 }
991
992 size_t
993 xml_get_max_image_name_len(const WIMStruct *w)
994 {
995         size_t max_len = 0;
996         if (w->wim_info) {
997                 size_t len;
998                 for (int i = 0; i < w->wim_info->num_images; i++) {
999                         len = strlen(w->wim_info->images[i].name);
1000                         if (len > max_len)
1001                                 max_len = len;
1002                 }
1003         }
1004         return max_len;
1005 }
1006
1007 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
1008 void
1009 xml_set_memory_allocator(void *(*malloc_func)(size_t),
1010                          void (*free_func)(void *),
1011                          void *(*realloc_func)(void *, size_t))
1012 {
1013         xmlMemSetup(free_func, malloc_func, realloc_func, STRDUP);
1014 }
1015 #endif
1016
1017 static int
1018 calculate_dentry_statistics(struct wim_dentry *dentry, void *arg)
1019 {
1020         struct image_info *info = arg;
1021         struct wim_lookup_table *lookup_table = info->lookup_table;
1022         const struct wim_inode *inode = dentry->d_inode;
1023         struct wim_lookup_table_entry *lte;
1024
1025         /* Update directory count and file count.
1026          *
1027          * Each dentry counts as either a file or a directory, but not both.
1028          * The root directory is an exception: it is not counted at all.
1029          *
1030          * Symbolic links and junction points (and presumably other reparse
1031          * points) count as regular files.  This is despite the fact that
1032          * junction points have FILE_ATTRIBUTE_DIRECTORY set.
1033          */
1034         if (dentry_is_root(dentry))
1035                 return 0;
1036
1037         if (inode_is_directory(inode))
1038                 info->dir_count++;
1039         else
1040                 info->file_count++;
1041
1042         /*
1043          * Update total bytes and hard link bytes.
1044          *
1045          * Unfortunately there are some inconsistencies/bugs in the way this is
1046          * done.
1047          *
1048          * If there are no alternate data streams in the image, the "total
1049          * bytes" is the sum of the size of the un-named data stream of each
1050          * inode times the link count of that inode.  In other words, it would
1051          * be the total number of bytes of regular files you would have if you
1052          * extracted the full image without any hard-links.  The "hard link
1053          * bytes" is equal to the "total bytes" minus the size of the un-named
1054          * data stream of each inode.  In other words, the "hard link bytes"
1055          * counts the size of the un-named data stream for all the links to each
1056          * inode except the first one.
1057          *
1058          * Reparse points and directories don't seem to be counted in either the
1059          * total bytes or the hard link bytes.
1060          *
1061          * And now we get to the most confusing part, the alternate data
1062          * streams.  They are not counted in the "total bytes".  However, if the
1063          * link count of an inode with alternate data streams is 2 or greater,
1064          * the size of all the alternate data streams is included in the "hard
1065          * link bytes", and this size is multiplied by the link count (NOT one
1066          * less than the link count).
1067          */
1068         lte = inode_unnamed_lte(inode, info->lookup_table);
1069         if (lte) {
1070                 info->total_bytes += wim_resource_size(lte);
1071                 if (!dentry_is_first_in_inode(dentry))
1072                         info->hard_link_bytes += wim_resource_size(lte);
1073         }
1074
1075         if (inode->i_nlink >= 2 && dentry_is_first_in_inode(dentry)) {
1076                 for (unsigned i = 0; i < inode->i_num_ads; i++) {
1077                         if (inode->i_ads_entries[i].stream_name_nbytes) {
1078                                 lte = inode_stream_lte(inode, i + 1, lookup_table);
1079                                 if (lte) {
1080                                         info->hard_link_bytes += inode->i_nlink *
1081                                                                  wim_resource_size(lte);
1082                                 }
1083                         }
1084                 }
1085         }
1086         return 0;
1087 }
1088
1089 /*
1090  * Calculate what to put in the <FILECOUNT>, <DIRCOUNT>, <TOTALBYTES>, and
1091  * <HARDLINKBYTES> elements of each <IMAGE>.
1092  *
1093  * Please note there is no official documentation for exactly how this is done.
1094  * But, see calculate_dentry_statistics().
1095  */
1096 void
1097 xml_update_image_info(WIMStruct *w, int image)
1098 {
1099         struct image_info *image_info;
1100         utf8char *flags_save;
1101
1102         DEBUG("Updating the image info for image %d", image);
1103
1104         image_info = &w->wim_info->images[image - 1];
1105
1106         image_info->file_count      = 0;
1107         image_info->dir_count       = 0;
1108         image_info->total_bytes     = 0;
1109         image_info->hard_link_bytes = 0;
1110
1111         flags_save = image_info->flags;
1112         image_info->lookup_table = w->lookup_table;
1113         for_dentry_in_tree(w->image_metadata[image - 1].root_dentry,
1114                            calculate_dentry_statistics,
1115                            image_info);
1116         image_info->flags = flags_save;
1117         image_info->last_modification_time = get_wim_timestamp();
1118 }
1119
1120 /* Adds an image to the XML information. */
1121 int
1122 xml_add_image(WIMStruct *w, const utf8char *name)
1123 {
1124         struct wim_info *wim_info;
1125         struct image_info *image_info;
1126
1127         wimlib_assert(name != NULL);
1128
1129         /* If this is the first image, allocate the struct wim_info.  Otherwise
1130          * use the existing struct wim_info. */
1131         if (w->wim_info) {
1132                 wim_info = w->wim_info;
1133         } else {
1134                 wim_info = CALLOC(1, sizeof(struct wim_info));
1135                 if (!wim_info)
1136                         return WIMLIB_ERR_NOMEM;
1137         }
1138
1139         image_info = add_image_info_struct(wim_info);
1140         if (!image_info)
1141                 goto out_free_wim_info;
1142
1143         if (!(image_info->name = STRDUP(name)))
1144                 goto out_destroy_image_info;
1145
1146         w->wim_info = wim_info;
1147         image_info->index = wim_info->num_images;
1148         image_info->creation_time = get_wim_timestamp();
1149         xml_update_image_info(w, image_info->index);
1150         return 0;
1151
1152 out_destroy_image_info:
1153         destroy_image_info(image_info);
1154         wim_info->num_images--;
1155 out_free_wim_info:
1156         if (wim_info != w->wim_info)
1157                 FREE(wim_info);
1158         return WIMLIB_ERR_NOMEM;
1159 }
1160
1161 /* Prints information about the specified image from struct wim_info structure.
1162  * */
1163 void
1164 print_image_info(const struct wim_info *wim_info, int image)
1165 {
1166         const struct image_info *image_info;
1167         const utf8char *desc;
1168         char buf[50];
1169
1170         wimlib_assert(image >= 1 && image <= wim_info->num_images);
1171
1172         image_info = &wim_info->images[image - 1];
1173
1174         printf("Index:                  %d\n", image_info->index);
1175         wimlib_printf("Name:                   %U\n", image_info->name);
1176
1177         /* Always print the Description: part even if there is no
1178          * description. */
1179         if (image_info->description)
1180                 desc = image_info->description;
1181         else
1182                 desc = "";
1183         wimlib_printf("Description:            %U\n", desc);
1184
1185         if (image_info->display_name)
1186                 wimlib_printf("Display Name:           %U\n",
1187                               image_info->display_name);
1188
1189         if (image_info->display_description)
1190                 wimlib_printf("Display Description:    %U\n",
1191                               image_info->display_description);
1192
1193         printf("Directory Count:        %"PRIu64"\n", image_info->dir_count);
1194         printf("File Count:             %"PRIu64"\n", image_info->file_count);
1195         printf("Total Bytes:            %"PRIu64"\n", image_info->total_bytes);
1196         printf("Hard Link Bytes:        %"PRIu64"\n", image_info->hard_link_bytes);
1197
1198         wim_timestamp_to_str(image_info->creation_time, buf, sizeof(buf));
1199         printf("Creation Time:          %s\n", buf);
1200
1201         wim_timestamp_to_str(image_info->creation_time, buf, sizeof(buf));
1202         printf("Last Modification Time: %s\n", buf);
1203         if (image_info->windows_info_exists)
1204                 print_windows_info(&image_info->windows_info);
1205         if (image_info->flags)
1206                 printf("Flags:                  %s\n", image_info->flags);
1207         putchar('\n');
1208 }
1209
1210 void
1211 libxml_global_init()
1212 {
1213         xmlInitParser();
1214         xmlInitCharEncodingHandlers();
1215 }
1216
1217 void
1218 libxml_global_cleanup()
1219 {
1220         xmlCleanupParser();
1221         xmlCleanupCharEncodingHandlers();
1222 }
1223
1224 /*
1225  * Reads the XML data from a WIM file.
1226  */
1227 int
1228 read_xml_data(FILE *fp, const struct resource_entry *res_entry,
1229               utf16lechar **xml_data_ret, struct wim_info **info_ret)
1230 {
1231         utf16lechar *xml_data;
1232         xmlDoc *doc;
1233         xmlNode *root;
1234         int ret;
1235
1236         DEBUG("XML data is %"PRIu64" bytes at offset %"PRIu64"",
1237               (u64)res_entry->size, res_entry->offset);
1238
1239         if (resource_is_compressed(res_entry)) {
1240                 ERROR("XML data is supposed to be uncompressed");
1241                 ret = WIMLIB_ERR_XML;
1242                 goto out;
1243         }
1244
1245         if (res_entry->size < 2) {
1246                 ERROR("XML data must be at least 2 bytes long");
1247                 ret = WIMLIB_ERR_XML;
1248                 goto out;
1249         }
1250
1251         xml_data = MALLOC(res_entry->size + 3);
1252         if (!xml_data) {
1253                 ret = WIMLIB_ERR_NOMEM;
1254                 goto out;
1255         }
1256
1257         ret = read_uncompressed_resource(fp, res_entry->offset,
1258                                          res_entry->size, xml_data);
1259         if (ret != 0)
1260                 goto out_free_xml_data;
1261
1262         /* Null-terminate just in case */
1263         ((u8*)xml_data)[res_entry->size] = 0;
1264         ((u8*)xml_data)[res_entry->size + 1] = 0;
1265         ((u8*)xml_data)[res_entry->size + 2] = 0;
1266
1267         DEBUG("Parsing XML using libxml2 to create XML tree");
1268
1269         doc = xmlReadMemory((const char *)xml_data,
1270                             res_entry->size, "noname.xml", "UTF-16", 0);
1271
1272         if (!doc) {
1273                 ERROR("Failed to parse XML data");
1274                 ret = WIMLIB_ERR_XML;
1275                 goto out_free_xml_data;
1276         }
1277
1278         DEBUG("Constructing WIM information structure from XML tree.");
1279
1280         root = xmlDocGetRootElement(doc);
1281         if (!root) {
1282                 ERROR("WIM XML data is an empty XML document");
1283                 ret = WIMLIB_ERR_XML;
1284                 goto out_free_doc;
1285         }
1286
1287         if (!node_is_element(root) || !node_name_is(root, "WIM")) {
1288                 ERROR("Expected <WIM> for the root XML element (found <%s>)",
1289                       root->name);
1290                 ret = WIMLIB_ERR_XML;
1291                 goto out_free_doc;
1292         }
1293
1294         ret = xml_read_wim_info(root, info_ret);
1295         if (ret != 0)
1296                 goto out_free_doc;
1297
1298         *xml_data_ret = xml_data;
1299         xml_data = NULL;
1300 out_free_doc:
1301         DEBUG("Freeing XML tree.");
1302         xmlFreeDoc(doc);
1303 out_free_xml_data:
1304         FREE(xml_data);
1305 out:
1306         return ret;
1307 }
1308
1309 #define CHECK_RET  ({   if (ret < 0)  { \
1310                                 ERROR("Error writing XML data"); \
1311                                 ret = WIMLIB_ERR_WRITE; \
1312                                 goto out_free_text_writer; \
1313                         } })
1314
1315 /*
1316  * Writes XML data to a WIM file.
1317  *
1318  * If @total_bytes is non-zero, it specifies what to write to the TOTALBYTES
1319  * element in the XML data.  If zero, TOTALBYTES is given the default value of
1320  * the offset of the XML data.
1321  */
1322 int
1323 write_xml_data(const struct wim_info *wim_info, int image, FILE *out,
1324                u64 total_bytes, struct resource_entry *out_res_entry)
1325 {
1326         xmlCharEncodingHandler *encoding_handler;
1327         xmlOutputBuffer *out_buffer;
1328         xmlTextWriter *writer;
1329         int ret;
1330         off_t start_offset;
1331         off_t end_offset;
1332
1333         wimlib_assert(image == WIMLIB_ALL_IMAGES ||
1334                         (wim_info != NULL && image >= 1 &&
1335                          image <= wim_info->num_images));
1336
1337         start_offset = ftello(out);
1338         if (start_offset == -1)
1339                 return WIMLIB_ERR_WRITE;
1340
1341         DEBUG("Writing XML data for image %d at offset %"PRIu64,
1342               image, start_offset);
1343
1344         /* 2 bytes endianness marker for UTF-16LE.  This is _required_ for WIM
1345          * XML data. */
1346         if ((putc(0xff, out)) == EOF || (putc(0xfe, out) == EOF)) {
1347                 ERROR_WITH_ERRNO("Error writing XML data");
1348                 return WIMLIB_ERR_WRITE;
1349         }
1350
1351         /* The contents of the <TOTALBYTES> element in the XML data, under the
1352          * <WIM> element (not the <IMAGE> element), is for non-split WIMs the
1353          * size of the WIM file excluding the XML data and integrity table.
1354          * This should be equal to the current position in the output stream,
1355          * since the XML data and integrity table are the last elements of the
1356          * WIM.
1357          *
1358          * For split WIMs, <TOTALBYTES> takes into account the entire WIM, not
1359          * just the current part.  In that case, @total_bytes should be passed
1360          * in to this function. */
1361         if (total_bytes == 0)
1362                 total_bytes = start_offset;
1363
1364         /* The encoding of the XML data must be UTF-16LE. */
1365         encoding_handler = xmlGetCharEncodingHandler(XML_CHAR_ENCODING_UTF16LE);
1366         if (!encoding_handler) {
1367                 ERROR("Failed to get XML character encoding handler for UTF-16LE");
1368                 ret = WIMLIB_ERR_LIBXML_UTF16_HANDLER_NOT_AVAILABLE;
1369                 goto out;
1370         }
1371
1372         out_buffer = xmlOutputBufferCreateFile(out, encoding_handler);
1373         if (!out_buffer) {
1374                 ERROR("Failed to allocate xmlOutputBuffer");
1375                 ret = WIMLIB_ERR_NOMEM;
1376                 goto out;
1377         }
1378
1379         writer = xmlNewTextWriter(out_buffer);
1380         if (!writer) {
1381                 ERROR("Failed to allocate xmlTextWriter");
1382                 ret = WIMLIB_ERR_NOMEM;
1383                 goto out_output_buffer_close;
1384         }
1385
1386         DEBUG("Writing <WIM> element");
1387
1388         ret = xmlTextWriterStartElement(writer, "WIM");
1389         CHECK_RET;
1390
1391         ret = xmlTextWriterWriteFormatElement(writer, "TOTALBYTES", "%"PRIu64,
1392                                               total_bytes);
1393         CHECK_RET;
1394
1395         if (wim_info != NULL) {
1396                 int first, last;
1397                 if (image == WIMLIB_ALL_IMAGES) {
1398                         first = 1;
1399                         last = wim_info->num_images;
1400                 } else {
1401                         first = image;
1402                         last = image;
1403                 }
1404                 DEBUG("Writing %d <IMAGE> elements", last - first + 1);
1405                 for (int i = first; i <= last; i++) {
1406                         ret = xml_write_image_info(writer, &wim_info->images[i - 1]);
1407                         CHECK_RET;
1408                 }
1409         }
1410
1411         ret = xmlTextWriterEndElement(writer);
1412         CHECK_RET;
1413
1414         ret = xmlTextWriterEndDocument(writer);
1415         CHECK_RET;
1416
1417         DEBUG("Ended XML document");
1418
1419         /* Call xmlFreeTextWriter() before ftello() because the former will
1420          * flush the file stream. */
1421         xmlFreeTextWriter(writer);
1422         writer = NULL;
1423
1424         end_offset = ftello(out);
1425         if (end_offset == -1) {
1426                 ret = WIMLIB_ERR_WRITE;
1427         } else {
1428                 ret = 0;
1429                 out_res_entry->offset        = start_offset;
1430                 out_res_entry->size          = end_offset - start_offset;
1431                 out_res_entry->original_size = end_offset - start_offset;
1432                 out_res_entry->flags         = WIM_RESHDR_FLAG_METADATA;
1433         }
1434 out_free_text_writer:
1435         /* xmlFreeTextWriter will free the attached xmlOutputBuffer. */
1436         xmlFreeTextWriter(writer);
1437         out_buffer = NULL;
1438 out_output_buffer_close:
1439         if (out_buffer != NULL)
1440                 xmlOutputBufferClose(out_buffer);
1441 out:
1442         if (ret == 0)
1443                 DEBUG("Successfully wrote XML data");
1444         return ret;
1445 }
1446
1447 /* Returns the name of the specified image. */
1448 WIMLIBAPI const utf8char *
1449 wimlib_get_image_name(const WIMStruct *w, int image)
1450 {
1451         if (image < 1 || image > w->hdr.image_count)
1452                 return NULL;
1453         return w->wim_info->images[image - 1].name;
1454 }
1455
1456 /* Returns the description of the specified image. */
1457 WIMLIBAPI const utf8char *
1458 wimlib_get_image_description(const WIMStruct *w, int image)
1459 {
1460         if (image < 1 || image > w->hdr.image_count)
1461                 return NULL;
1462         return w->wim_info->images[image - 1].description;
1463 }
1464
1465 /* Determines if an image name is already used by some image in the WIM. */
1466 WIMLIBAPI bool
1467 wimlib_image_name_in_use(const WIMStruct *w, const utf8char *name)
1468 {
1469         if (!name || !*name)
1470                 return false;
1471         for (int i = 1; i <= w->hdr.image_count; i++)
1472                 if (strcmp(w->wim_info->images[i - 1].name, name) == 0)
1473                         return true;
1474         return false;
1475 }
1476
1477 /* Extracts the raw XML data to a file stream. */
1478 WIMLIBAPI int
1479 wimlib_extract_xml_data(WIMStruct *w, FILE *fp)
1480 {
1481         size_t bytes_written;
1482
1483         if (!w->xml_data)
1484                 return WIMLIB_ERR_INVALID_PARAM;
1485         bytes_written = fwrite(w->xml_data, 1, w->hdr.xml_res_entry.size, fp);
1486         if (bytes_written != w->hdr.xml_res_entry.size) {
1487                 ERROR_WITH_ERRNO("Failed to extract XML data");
1488                 return WIMLIB_ERR_WRITE;
1489         }
1490         return 0;
1491 }
1492
1493 /* Sets the name of an image in the WIM. */
1494 WIMLIBAPI int
1495 wimlib_set_image_name(WIMStruct *w, int image, const utf8char *name)
1496 {
1497         utf8char *p;
1498         int i;
1499
1500         DEBUG("Setting the name of image %d to %s", image, name);
1501
1502         if (!name || !*name) {
1503                 ERROR("Must specify a non-empty string for the image name");
1504                 return WIMLIB_ERR_INVALID_PARAM;
1505         }
1506
1507         if (image < 1 || image > w->hdr.image_count) {
1508                 ERROR("%d is not a valid image", image);
1509                 return WIMLIB_ERR_INVALID_IMAGE;
1510         }
1511
1512         for (i = 1; i <= w->hdr.image_count; i++) {
1513                 if (i == image)
1514                         continue;
1515                 if (strcmp(w->wim_info->images[i - 1].name, name) == 0) {
1516                         ERROR("The name `%U' is already in use in the WIM!",
1517                               name);
1518                         return WIMLIB_ERR_IMAGE_NAME_COLLISION;
1519                 }
1520         }
1521
1522         p = STRDUP(name);
1523         if (!p)
1524                 return WIMLIB_ERR_NOMEM;
1525
1526         FREE(w->wim_info->images[image - 1].name);
1527         w->wim_info->images[image - 1].name = p;
1528         return 0;
1529 }
1530
1531 /* Sets the description of an image in the WIM. */
1532 WIMLIBAPI int
1533 wimlib_set_image_descripton(WIMStruct *w, int image,
1534                             const utf8char *description)
1535 {
1536         utf8char *p;
1537
1538         if (image < 1 || image > w->hdr.image_count) {
1539                 ERROR("%d is not a valid image", image);
1540                 return WIMLIB_ERR_INVALID_IMAGE;
1541         }
1542         if (description) {
1543                 p = STRDUP(description);
1544                 if (!p)
1545                         return WIMLIB_ERR_NOMEM;
1546         } else {
1547                 p = NULL;
1548         }
1549         FREE(w->wim_info->images[image - 1].description);
1550         w->wim_info->images[image - 1].description = p;
1551         return 0;
1552 }
1553
1554 /* Set the <FLAGS> element of a WIM image */
1555 WIMLIBAPI int
1556 wimlib_set_image_flags(WIMStruct *w, int image, const utf8char *flags)
1557 {
1558         utf8char *p;
1559
1560         if (image < 1 || image > w->hdr.image_count) {
1561                 ERROR("%d is not a valid image", image);
1562                 return WIMLIB_ERR_INVALID_IMAGE;
1563         }
1564         if (flags) {
1565                 p = STRDUP(flags);
1566                 if (!p)
1567                         return WIMLIB_ERR_NOMEM;
1568         } else {
1569                 p = NULL;
1570         }
1571         FREE(w->wim_info->images[image - 1].flags);
1572         w->wim_info->images[image - 1].flags = p;
1573         return 0;
1574 }