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