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