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