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