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