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