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