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