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