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