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