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