5c806cb46d06d9c41dd9776512a2262095206682
[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, 2015 Eric Biggers
9  *
10  * This file is free software; you can redistribute it and/or modify it under
11  * the terms of the GNU Lesser General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option) any
13  * later version.
14  *
15  * This file is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this file; if not, see http://www.gnu.org/licenses/.
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #  include "config.h"
26 #endif
27
28 #include <libxml/parser.h>
29 #include <libxml/tree.h>
30 #include <libxml/xmlsave.h>
31 #include <string.h>
32
33 #include "wimlib/blob_table.h"
34 #include "wimlib/dentry.h"
35 #include "wimlib/encoding.h"
36 #include "wimlib/error.h"
37 #include "wimlib/file_io.h"
38 #include "wimlib/metadata.h"
39 #include "wimlib/resource.h"
40 #include "wimlib/timestamp.h"
41 #include "wimlib/xml.h"
42 #include "wimlib/write.h"
43
44 /*
45  * A wrapper around a WIM file's XML document.  The XML document contains
46  * metadata about each image in the WIM file as well as metadata about the WIM
47  * file itself.
48  */
49 struct wim_xml_info {
50
51         /* The parsed XML document as a libxml2 document tree  */
52         xmlDocPtr doc;
53
54         /* The root element of the document.  This is a cached value, equal to
55          * xmlDocGetRootElement(doc).  */
56         xmlNode *root;
57
58         /* A malloc()ed array containing a pointer to the IMAGE element for each
59          * WIM image.  The image with 1-based index 'i' is at index 'i - 1' in
60          * this array.  Note: these pointers are cached values, since they could
61          * also be found by searching the document.  */
62         xmlNode **images;
63
64         /* The number of WIM images (the length of 'images')  */
65         int image_count;
66
67         /* Temporary memory for UTF-8 => 'tchar' string translations.  When an
68          * API function needs to return a 'tchar' string, it uses one of these
69          * array slots to hold the string and returns a pointer to it.  */
70         tchar *strings[128];
71         size_t next_string_idx;
72         size_t num_strings;
73 };
74
75 /*----------------------------------------------------------------------------*
76  *                            Internal functions                              *
77  *----------------------------------------------------------------------------*/
78
79 /* Iterate through the children of an xmlNode.  */
80 #define node_for_each_child(parent, child)      \
81         for (child = (parent)->children; child != NULL; child = child->next)
82
83 /* Is the specified node an element of the specified name?  */
84 static bool
85 node_is_element(const xmlNode *node, const xmlChar *name)
86 {
87         return node->type == XML_ELEMENT_NODE && xmlStrEqual(node->name, name);
88 }
89
90 /* Retrieve a pointer to the UTF-8 text contents of the specified node, or NULL
91  * if the node has no text contents.  This assumes the simple case where the
92  * node has a single TEXT child node.  */
93 static const xmlChar *
94 node_get_text(const xmlNode *node)
95 {
96         const xmlNode *child;
97
98         if (!node)
99                 return NULL;
100         node_for_each_child(node, child)
101                 if (child->type == XML_TEXT_NODE && child->content)
102                         return child->content;
103         return NULL;
104 }
105
106 /* Retrieve an unsigned integer from the contents of the specified node,
107  * decoding it using the specified base.  If the node has no contents or does
108  * not contain a valid number, returns 0.  */
109 static u64
110 node_get_number(const xmlNode *node, int base)
111 {
112         const xmlChar *str = node_get_text(node);
113         char *end;
114         unsigned long long v;
115
116         if (!str)
117                 return 0;
118         v = strtoull(str, &end, base);
119         if ((xmlChar *)end == str || *end || v >= UINT64_MAX)
120                 return 0;
121         return v;
122 }
123
124 /* Retrieve the timestamp from a time node.  This node should have child
125  * elements HIGHPART and LOWPART; these elements will be used to construct a
126  * Windows-style timestamp.  */
127 static u64
128 node_get_timestamp(const xmlNode *node)
129 {
130         u64 timestamp = 0;
131         xmlNode *child;
132
133         if (!node)
134                 return 0;
135         node_for_each_child(node, child) {
136                 if (node_is_element(child, "HIGHPART"))
137                         timestamp |= node_get_number(child, 16) << 32;
138                 else if (node_is_element(child, "LOWPART"))
139                         timestamp |= node_get_number(child, 16);
140         }
141         return timestamp;
142 }
143
144 static int
145 tstr_get_utf8(const tchar *tstr, const xmlChar **utf8_ret)
146 {
147         if (wimlib_mbs_is_utf8) {
148                 *utf8_ret = (xmlChar *)tstr;
149                 return 0;
150         }
151         return tstr_to_utf8_simple(tstr, (char **)utf8_ret);
152 }
153
154 static void
155 tstr_put_utf8(const xmlChar *utf8)
156 {
157         if (!wimlib_mbs_is_utf8)
158                 FREE((void *)utf8);
159 }
160
161 /* Retrieve the text contents of an XML element as a 'tchar' string.  If not
162  * found or if the text could not be translated, returns NULL.  */
163 static const tchar *
164 node_get_ttext(struct wim_xml_info *info, xmlNode *node)
165 {
166         const xmlChar *text;
167         tchar **ttext_p;
168
169         text = node_get_text(node);
170
171         if (!text || wimlib_mbs_is_utf8)
172                 return (const tchar *)text;
173
174         ttext_p = &info->strings[info->next_string_idx];
175         if (info->num_strings >= ARRAY_LEN(info->strings)) {
176                 FREE(*ttext_p);
177                 *ttext_p = NULL;
178         }
179         if (utf8_to_tstr_simple(text, ttext_p))
180                 return NULL;
181         if (info->num_strings < ARRAY_LEN(info->strings))
182                 info->num_strings++;
183         info->next_string_idx++;
184         info->next_string_idx %= ARRAY_LEN(info->strings);
185         return *ttext_p;
186 }
187
188 /* Unlink the specified node from its parent, then free it (recursively).  */
189 static void
190 unlink_and_free_tree(xmlNode *node)
191 {
192         xmlUnlinkNode(node);
193         xmlFreeNode(node);
194 }
195
196 /* Unlink and free (recursively) all children of the specified node.  */
197 static void
198 unlink_and_free_children(xmlNode *node)
199 {
200         xmlNode *child;
201
202         while ((child = node->last) != NULL)
203                 unlink_and_free_tree(child);
204 }
205
206 /* Add the new child element 'replacement' to 'parent', replacing any same-named
207  * element that may already exist.  */
208 static void
209 node_replace_child_element(xmlNode *parent, xmlNode *replacement)
210 {
211         xmlNode *child;
212
213         node_for_each_child(parent, child) {
214                 if (node_is_element(child, replacement->name)) {
215                         xmlReplaceNode(child, replacement);
216                         xmlFreeNode(child);
217                         return;
218                 }
219         }
220
221         xmlAddChild(parent, replacement);
222 }
223
224 /* Set the text contents of the specified element to the specified string,
225  * replacing the existing contents (if any).  The string is "raw" and is
226  * permitted to contain characters that have special meaning in XML.  */
227 static int
228 node_set_text(xmlNode *node, const xmlChar *text)
229 {
230         xmlNode *text_node = xmlNewText(text);
231         if (!text_node)
232                 return WIMLIB_ERR_NOMEM;
233         unlink_and_free_children(node);
234         xmlAddChild(node, text_node);
235         return 0;
236 }
237
238 /* Like 'node_set_text()', but takes in a 'tchar' string.  */
239 static int
240 node_set_ttext(xmlNode *node, const tchar *ttext)
241 {
242         const xmlChar *text;
243         int ret;
244
245         ret = tstr_get_utf8(ttext, &text);
246         if (ret)
247                 return ret;
248         ret = node_set_text(node, text);
249         tstr_put_utf8(text);
250         return ret;
251 }
252
253 /* Create a new element containing text and optionally link it into a tree.  */
254 static xmlNode *
255 new_element_with_text(xmlNode *parent, const xmlChar *name, const xmlChar *text)
256 {
257         xmlNode *node;
258
259         node = xmlNewNode(NULL, name);
260         if (!node)
261                 return NULL;
262
263         if (node_set_text(node, text)) {
264                 xmlFreeNode(node);
265                 return NULL;
266         }
267
268         if (parent)
269                 xmlAddChild(parent, node);
270         return node;
271 }
272
273 /* Create a new element containing text and optionally link it into a tree.  */
274 static int
275 new_element_with_ttext(xmlNode *parent, const xmlChar *name, const tchar *ttext,
276                        xmlNode **node_ret)
277 {
278         const xmlChar *text;
279         int ret;
280         xmlNode *node;
281
282         ret = tstr_get_utf8(ttext, &text);
283         if (ret)
284                 return ret;
285         node = new_element_with_text(parent, name, text);
286         tstr_put_utf8(text);
287         if (!node)
288                 return WIMLIB_ERR_NOMEM;
289         if (node_ret)
290                 *node_ret = node;
291         return 0;
292 }
293
294 /* Create a new timestamp element and optionally link it into a tree.  */
295 static xmlNode *
296 new_element_with_timestamp(xmlNode *parent, const xmlChar *name, u64 timestamp)
297 {
298         xmlNode *node;
299         char buf[32];
300
301         node = xmlNewNode(NULL, name);
302         if (!node)
303                 goto err;
304
305         sprintf(buf, "0x%08"PRIX32, (u32)(timestamp >> 32));
306         if (!new_element_with_text(node, "HIGHPART", buf))
307                 goto err;
308
309         sprintf(buf, "0x%08"PRIX32, (u32)timestamp);
310         if (!new_element_with_text(node, "LOWPART", buf))
311                 goto err;
312
313         if (parent)
314                 xmlAddChild(parent, node);
315         return node;
316
317 err:
318         xmlFreeNode(node);
319         return NULL;
320 }
321
322 /* Create a new number element and optionally link it into a tree.  */
323 static xmlNode *
324 new_element_with_u64(xmlNode *parent, const xmlChar *name, u64 value)
325 {
326         char buf[32];
327
328         sprintf(buf, "%"PRIu64, value);
329         return new_element_with_text(parent, name, buf);
330 }
331
332 /* Allocate a 'struct wim_xml_info'.  The caller is responsible for initializing
333  * the document and the images array.  */
334 static struct wim_xml_info *
335 alloc_wim_xml_info(void)
336 {
337         struct wim_xml_info *info = MALLOC(sizeof(*info));
338         if (info) {
339                 info->next_string_idx = 0;
340                 info->num_strings = 0;
341         }
342         return info;
343 }
344
345 static bool
346 parse_index(xmlChar **pp, u32 *index_ret)
347 {
348         xmlChar *p = *pp;
349         u32 index = 0;
350
351         *p++ = '\0'; /* overwrite '[' */
352         while (*p >= '0' && *p <= '9') {
353                 u32 n = (index * 10) + (*p++ - '0');
354                 if (n < index)
355                         return false;
356                 index = n;
357         }
358         if (index == 0)
359                 return false;
360         if (*p != ']')
361                 return false;
362         p++;
363         if (*p != '/' && *p != '\0')
364                 return false;
365
366         *pp = p;
367         *index_ret = index;
368         return true;
369 }
370
371 static int
372 do_xml_path_walk(xmlNode *node, const xmlChar *path, bool create,
373                  xmlNode **result_ret)
374 {
375         size_t n = strlen(path) + 1;
376         xmlChar buf[n];
377         xmlChar *p;
378         xmlChar c;
379
380         *result_ret = NULL;
381
382         if (!node)
383                 return 0;
384
385         /* Copy the path to a temporary buffer.  */
386         memcpy(buf, path, n);
387         p = buf;
388
389         if (*p == '/')
390                 goto bad_syntax;
391         c = *p;
392
393         while (c != '\0') {
394                 const xmlChar *name;
395                 xmlNode *child;
396                 u32 index = 1;
397
398                 /* We have another path component.  */
399
400                 /* Parse the element name.  */
401                 name = p;
402                 while (*p != '/' && *p != '\0' && *p != '[')
403                         p++;
404                 if (p == name) /* empty name?  */
405                         goto bad_syntax;
406
407                 /* Handle a bracketed index, if one was specified.  */
408                 if (*p == '[' && !parse_index(&p, &index))
409                         goto bad_syntax;
410
411                 c = *p;
412                 *p = '\0';
413
414                 /* Look for a matching child.  */
415                 node_for_each_child(node, child)
416                         if (node_is_element(child, name) && !--index)
417                                 goto next_step;
418
419                 /* No child matched the path.  If create=false, the lookup
420                  * failed.  If create=true, create the needed element.  */
421                 if (!create)
422                         return 0;
423
424                 /* We can't create an element at index 'n' if indices 1...n-1
425                  * didn't already exist.  */
426                 if (index != 1)
427                         return WIMLIB_ERR_INVALID_PARAM;
428
429                 child = xmlNewChild(node, NULL, name, NULL);
430                 if (!child)
431                         return WIMLIB_ERR_NOMEM;
432         next_step:
433                 /* Continue to the next path component, if there is one.  */
434                 node = child;
435                 p++;
436         }
437
438         *result_ret = node;
439         return 0;
440
441 bad_syntax:
442         ERROR("The XML path \"%s\" has invalid syntax.", path);
443         return WIMLIB_ERR_INVALID_PARAM;
444 }
445
446 /* Retrieve the XML element, if any, at the specified 'path'.  This supports a
447  * simple filesystem-like syntax.  If the element was found, returns a pointer
448  * to it; otherwise returns NULL.  */
449 static xmlNode *
450 xml_get_node_by_path(xmlNode *root, const xmlChar *path)
451 {
452         xmlNode *node;
453         do_xml_path_walk(root, path, false, &node);
454         return node;
455 }
456
457 /* Similar to xml_get_node_by_path(), but creates the element and any requisite
458  * ancestor elements as needed.   If successful, 0 is returned and *node_ret is
459  * set to a pointer to the resulting element.  If unsuccessful, an error code is
460  * returned and *node_ret is set to NULL.  */
461 static int
462 xml_ensure_node_by_path(xmlNode *root, const xmlChar *path, xmlNode **node_ret)
463 {
464         return do_xml_path_walk(root, path, true, node_ret);
465 }
466
467 static u64
468 xml_get_number_by_path(xmlNode *root, const xmlChar *path)
469 {
470         return node_get_number(xml_get_node_by_path(root, path), 10);
471 }
472
473 static u64
474 xml_get_timestamp_by_path(xmlNode *root, const xmlChar *path)
475 {
476         return node_get_timestamp(xml_get_node_by_path(root, path));
477 }
478
479 static const xmlChar *
480 xml_get_text_by_path(xmlNode *root, const xmlChar *path)
481 {
482         return node_get_text(xml_get_node_by_path(root, path));
483 }
484
485 static const tchar *
486 xml_get_ttext_by_path(struct wim_xml_info *info, xmlNode *root,
487                       const xmlChar *path)
488 {
489         return node_get_ttext(info, xml_get_node_by_path(root, path));
490 }
491
492 /* Creates/replaces (if ttext is not NULL and not empty) or removes (if ttext is
493  * NULL or empty) an element containing text.  */
494 static int
495 xml_set_ttext_by_path(xmlNode *root, const xmlChar *path, const tchar *ttext)
496 {
497         int ret;
498         xmlNode *node;
499
500         if (ttext && *ttext) {
501                 /* Create or replace  */
502                 ret = xml_ensure_node_by_path(root, path, &node);
503                 if (ret)
504                         return ret;
505                 return node_set_ttext(node, ttext);
506         } else {
507                 /* Remove  */
508                 node = xml_get_node_by_path(root, path);
509                 if (node)
510                         unlink_and_free_tree(node);
511                 return 0;
512         }
513 }
514
515 /* Unlink and return the node which represents the INDEX attribute of the
516  * specified IMAGE element.  */
517 static xmlAttr *
518 unlink_index_attribute(xmlNode *image_node)
519 {
520         xmlAttr *attr = xmlHasProp(image_node, "INDEX");
521         xmlUnlinkNode((xmlNode *)attr);
522         return attr;
523 }
524
525 /* Compute the total uncompressed size of the streams of the specified inode. */
526 static u64
527 inode_sum_stream_sizes(const struct wim_inode *inode,
528                        const struct blob_table *blob_table)
529 {
530         u64 total_size = 0;
531
532         for (unsigned i = 0; i < inode->i_num_streams; i++) {
533                 const struct blob_descriptor *blob;
534
535                 blob = stream_blob(&inode->i_streams[i], blob_table);
536                 if (blob)
537                         total_size += blob->size;
538         }
539         return total_size;
540 }
541
542 static int
543 append_image_node(struct wim_xml_info *info, xmlNode *image_node)
544 {
545         char buf[32];
546         xmlNode **images;
547
548         /* Limit exceeded?  */
549         if (unlikely(info->image_count >= MAX_IMAGES))
550                 return WIMLIB_ERR_IMAGE_COUNT;
551
552         /* Add the INDEX attribute.  */
553         sprintf(buf, "%d", info->image_count + 1);
554         if (!xmlNewProp(image_node, "INDEX", buf))
555                 return WIMLIB_ERR_NOMEM;
556
557         /* Append the IMAGE element to the 'images' array.  */
558         images = REALLOC(info->images,
559                          (info->image_count + 1) * sizeof(info->images[0]));
560         if (unlikely(!images))
561                 return WIMLIB_ERR_NOMEM;
562         info->images = images;
563         images[info->image_count++] = image_node;
564
565         /* Add the IMAGE element to the document.  */
566         xmlAddChild(info->root, image_node);
567         return 0;
568 }
569
570 /*----------------------------------------------------------------------------*
571  *                     Functions for internal library use                     *
572  *----------------------------------------------------------------------------*/
573
574 /* Allocate an empty 'struct wim_xml_info', containing no images.  */
575 struct wim_xml_info *
576 xml_new_info_struct(void)
577 {
578         struct wim_xml_info *info;
579
580         info = alloc_wim_xml_info();
581         if (!info)
582                 goto err;
583
584         info->doc = xmlNewDoc("1.0");
585         if (!info->doc)
586                 goto err_free_info;
587
588         info->root = xmlNewNode(NULL, "WIM");
589         if (!info->root)
590                 goto err_free_doc;
591         xmlDocSetRootElement(info->doc, info->root);
592
593         info->images = NULL;
594         info->image_count = 0;
595         return info;
596
597 err_free_doc:
598         xmlFreeDoc(info->doc);
599 err_free_info:
600         FREE(info);
601 err:
602         return NULL;
603 }
604
605 /* Free a 'struct wim_xml_info'.  */
606 void
607 xml_free_info_struct(struct wim_xml_info *info)
608 {
609         if (info) {
610                 xmlFreeDoc(info->doc);
611                 FREE(info->images);
612                 for (size_t i = 0; i < info->num_strings; i++)
613                         FREE(info->strings[i]);
614                 FREE(info);
615         }
616 }
617
618 /* Retrieve the number of images for which there exist IMAGE elements in the XML
619  * document.  */
620 int
621 xml_get_image_count(const struct wim_xml_info *info)
622 {
623         return info->image_count;
624 }
625
626 /* Retrieve the TOTALBYTES value for the WIM file, or 0 if this value is
627  * unavailable.  */
628 u64
629 xml_get_total_bytes(const struct wim_xml_info *info)
630 {
631         return xml_get_number_by_path(info->root, "TOTALBYTES");
632 }
633
634 /* Retrieve the TOTALBYTES value for the specified image, or 0 if this value is
635  * unavailable.  */
636 u64
637 xml_get_image_total_bytes(const struct wim_xml_info *info, int image)
638 {
639         return xml_get_number_by_path(info->images[image - 1], "TOTALBYTES");
640 }
641
642 /* Retrieve the HARDLINKBYTES value for the specified image, or 0 if this value
643  * is unavailable.  */
644 u64
645 xml_get_image_hard_link_bytes(const struct wim_xml_info *info, int image)
646 {
647         return xml_get_number_by_path(info->images[image - 1], "HARDLINKBYTES");
648 }
649
650 /* Retrieve the WIMBOOT value for the specified image, or false if this value is
651  * unavailable.  */
652 bool
653 xml_get_wimboot(const struct wim_xml_info *info, int image)
654 {
655         return xml_get_number_by_path(info->images[image - 1], "WIMBOOT");
656 }
657
658 /* Retrieve the Windows build number for the specified image, or 0 if this
659  * information is not available.  */
660 u64
661 xml_get_windows_build_number(const struct wim_xml_info *info, int image)
662 {
663         return xml_get_number_by_path(info->images[image - 1],
664                                       "WINDOWS/VERSION/BUILD");
665 }
666
667 /* Set the WIMBOOT value for the specified image.  */
668 int
669 xml_set_wimboot(struct wim_xml_info *info, int image)
670 {
671         return xml_set_ttext_by_path(info->images[image - 1], "WIMBOOT", T("1"));
672 }
673
674 /*
675  * Update the DIRCOUNT, FILECOUNT, TOTALBYTES, HARDLINKBYTES, and
676  * LASTMODIFICATIONTIME elements for the specified WIM image.
677  *
678  * Note: since these stats are likely to be used for display purposes only, we
679  * no longer attempt to duplicate WIMGAPI's weird bugs when calculating them.
680  */
681 int
682 xml_update_image_info(WIMStruct *wim, int image)
683 {
684         const struct wim_image_metadata *imd = wim->image_metadata[image - 1];
685         xmlNode *image_node = wim->xml_info->images[image - 1];
686         const struct wim_inode *inode;
687         u64 dir_count = 0;
688         u64 file_count = 0;
689         u64 total_bytes = 0;
690         u64 hard_link_bytes = 0;
691         u64 size;
692         xmlNode *dircount_node;
693         xmlNode *filecount_node;
694         xmlNode *totalbytes_node;
695         xmlNode *hardlinkbytes_node;
696         xmlNode *lastmodificationtime_node;
697
698         image_for_each_inode(inode, imd) {
699                 if (inode_is_directory(inode))
700                         dir_count += inode->i_nlink;
701                 else
702                         file_count += inode->i_nlink;
703                 size = inode_sum_stream_sizes(inode, wim->blob_table);
704                 total_bytes += size * inode->i_nlink;
705                 hard_link_bytes += size * (inode->i_nlink - 1);
706         }
707
708         dircount_node = new_element_with_u64(NULL, "DIRCOUNT", dir_count);
709         filecount_node = new_element_with_u64(NULL, "FILECOUNT", file_count);
710         totalbytes_node = new_element_with_u64(NULL, "TOTALBYTES", total_bytes);
711         hardlinkbytes_node = new_element_with_u64(NULL, "HARDLINKBYTES",
712                                                   hard_link_bytes);
713         lastmodificationtime_node =
714                 new_element_with_timestamp(NULL, "LASTMODIFICATIONTIME",
715                                            now_as_wim_timestamp());
716
717         if (unlikely(!dircount_node || !filecount_node || !totalbytes_node ||
718                      !hardlinkbytes_node || !lastmodificationtime_node)) {
719                 xmlFreeNode(dircount_node);
720                 xmlFreeNode(filecount_node);
721                 xmlFreeNode(totalbytes_node);
722                 xmlFreeNode(hardlinkbytes_node);
723                 xmlFreeNode(lastmodificationtime_node);
724                 return WIMLIB_ERR_NOMEM;
725         }
726
727         node_replace_child_element(image_node, dircount_node);
728         node_replace_child_element(image_node, filecount_node);
729         node_replace_child_element(image_node, totalbytes_node);
730         node_replace_child_element(image_node, hardlinkbytes_node);
731         node_replace_child_element(image_node, lastmodificationtime_node);
732         return 0;
733 }
734
735 /* Add an image to the XML information. */
736 int
737 xml_add_image(struct wim_xml_info *info, const tchar *name)
738 {
739         const u64 now = now_as_wim_timestamp();
740         xmlNode *image_node;
741         int ret;
742
743         ret = WIMLIB_ERR_NOMEM;
744         image_node = xmlNewNode(NULL, "IMAGE");
745         if (!image_node)
746                 goto err;
747
748         if (name && *name) {
749                 ret = new_element_with_ttext(image_node, "NAME", name, NULL);
750                 if (ret)
751                         goto err;
752         }
753         ret = WIMLIB_ERR_NOMEM;
754         if (!new_element_with_u64(image_node, "DIRCOUNT", 0))
755                 goto err;
756         if (!new_element_with_u64(image_node, "FILECOUNT", 0))
757                 goto err;
758         if (!new_element_with_u64(image_node, "TOTALBYTES", 0))
759                 goto err;
760         if (!new_element_with_u64(image_node, "HARDLINKBYTES", 0))
761                 goto err;
762         if (!new_element_with_timestamp(image_node, "CREATIONTIME", now))
763                 goto err;
764         if (!new_element_with_timestamp(image_node, "LASTMODIFICATIONTIME", now))
765                 goto err;
766         ret = append_image_node(info, image_node);
767         if (ret)
768                 goto err;
769         return 0;
770
771 err:
772         xmlFreeNode(image_node);
773         return ret;
774 }
775
776 /*
777  * Make a copy of the XML information for the image with index @src_image in the
778  * @src_info XML document and append it to the @dest_info XML document.
779  *
780  * In the process, change the image's name and description to the values
781  * specified by @dest_image_name and @dest_image_description.  Either or both
782  * may be NULL, which indicates that the corresponding element will not be
783  * included in the destination image.
784  */
785 int
786 xml_export_image(const struct wim_xml_info *src_info, int src_image,
787                  struct wim_xml_info *dest_info, const tchar *dest_image_name,
788                  const tchar *dest_image_description, bool wimboot)
789 {
790         xmlNode *dest_node;
791         int ret;
792
793         ret = WIMLIB_ERR_NOMEM;
794         dest_node = xmlDocCopyNode(src_info->images[src_image - 1],
795                                    dest_info->doc, 1);
796         if (!dest_node)
797                 goto err;
798
799         ret = xml_set_ttext_by_path(dest_node, "NAME", dest_image_name);
800         if (ret)
801                 goto err;
802
803         ret = xml_set_ttext_by_path(dest_node, "DESCRIPTION",
804                                     dest_image_description);
805         if (ret)
806                 goto err;
807
808         if (wimboot) {
809                 ret = xml_set_ttext_by_path(dest_node, "WIMBOOT", T("1"));
810                 if (ret)
811                         goto err;
812         }
813
814         xmlFreeProp(unlink_index_attribute(dest_node));
815
816         ret = append_image_node(dest_info, dest_node);
817         if (ret)
818                 goto err;
819         return 0;
820
821 err:
822         xmlFreeNode(dest_node);
823         return ret;
824 }
825
826 /* Remove the specified image from the XML document.  */
827 void
828 xml_delete_image(struct wim_xml_info *info, int image)
829 {
830         xmlNode *next_image;
831         xmlAttr *index_attr, *next_index_attr;
832
833         /* Free the IMAGE element for the deleted image.  Then, shift all
834          * higher-indexed IMAGE elements down by 1, in the process re-assigning
835          * their INDEX attributes.  */
836
837         next_image = info->images[image - 1];
838         next_index_attr = unlink_index_attribute(next_image);
839         unlink_and_free_tree(next_image);
840
841         while (image < info->image_count) {
842                 index_attr = next_index_attr;
843                 next_image = info->images[image];
844                 next_index_attr = unlink_index_attribute(next_image);
845                 xmlAddChild(next_image, (xmlNode *)index_attr);
846                 info->images[image - 1] = next_image;
847                 image++;
848         }
849
850         xmlFreeProp(next_index_attr);
851         info->image_count--;
852 }
853
854 /* Architecture constants are from w64 mingw winnt.h  */
855 #define PROCESSOR_ARCHITECTURE_INTEL            0
856 #define PROCESSOR_ARCHITECTURE_MIPS             1
857 #define PROCESSOR_ARCHITECTURE_ALPHA            2
858 #define PROCESSOR_ARCHITECTURE_PPC              3
859 #define PROCESSOR_ARCHITECTURE_SHX              4
860 #define PROCESSOR_ARCHITECTURE_ARM              5
861 #define PROCESSOR_ARCHITECTURE_IA64             6
862 #define PROCESSOR_ARCHITECTURE_ALPHA64          7
863 #define PROCESSOR_ARCHITECTURE_MSIL             8
864 #define PROCESSOR_ARCHITECTURE_AMD64            9
865 #define PROCESSOR_ARCHITECTURE_IA32_ON_WIN64    10
866 #define PROCESSOR_ARCHITECTURE_ARM64            12
867
868 static const tchar *
869 describe_arch(u64 arch)
870 {
871         static const tchar * const descriptions[] = {
872                 [PROCESSOR_ARCHITECTURE_INTEL] = T("x86"),
873                 [PROCESSOR_ARCHITECTURE_MIPS]  = T("MIPS"),
874                 [PROCESSOR_ARCHITECTURE_ARM]   = T("ARM"),
875                 [PROCESSOR_ARCHITECTURE_IA64]  = T("ia64"),
876                 [PROCESSOR_ARCHITECTURE_AMD64] = T("x86_64"),
877                 [PROCESSOR_ARCHITECTURE_ARM64] = T("ARM64"),
878         };
879
880         if (arch < ARRAY_LEN(descriptions) && descriptions[arch] != NULL)
881                 return descriptions[arch];
882
883         return T("unknown");
884 }
885
886 /* Print information from the WINDOWS element, if present.  */
887 static void
888 print_windows_info(struct wim_xml_info *info, xmlNode *image_node)
889 {
890         xmlNode *windows_node;
891         xmlNode *langs_node;
892         xmlNode *version_node;
893         const tchar *text;
894
895         windows_node = xml_get_node_by_path(image_node, "WINDOWS");
896         if (!windows_node)
897                 return;
898
899         tprintf(T("Architecture:           %"TS"\n"),
900                 describe_arch(xml_get_number_by_path(windows_node, "ARCH")));
901
902         text = xml_get_ttext_by_path(info, windows_node, "PRODUCTNAME");
903         if (text)
904                 tprintf(T("Product Name:           %"TS"\n"), text);
905
906         text = xml_get_ttext_by_path(info, windows_node, "EDITIONID");
907         if (text)
908                 tprintf(T("Edition ID:             %"TS"\n"), text);
909
910         text = xml_get_ttext_by_path(info, windows_node, "INSTALLATIONTYPE");
911         if (text)
912                 tprintf(T("Installation Type:      %"TS"\n"), text);
913
914         text = xml_get_ttext_by_path(info, windows_node, "HAL");
915         if (text)
916                 tprintf(T("HAL:                    %"TS"\n"), text);
917
918         text = xml_get_ttext_by_path(info, windows_node, "PRODUCTTYPE");
919         if (text)
920                 tprintf(T("Product Type:           %"TS"\n"), text);
921
922         text = xml_get_ttext_by_path(info, windows_node, "PRODUCTSUITE");
923         if (text)
924                 tprintf(T("Product Suite:          %"TS"\n"), text);
925
926         langs_node = xml_get_node_by_path(windows_node, "LANGUAGES");
927         if (langs_node) {
928                 xmlNode *lang_node;
929
930                 tprintf(T("Languages:              "));
931                 node_for_each_child(langs_node, lang_node) {
932                         if (!node_is_element(lang_node, "LANGUAGE"))
933                                 continue;
934                         text = node_get_ttext(info, lang_node);
935                         if (!text)
936                                 continue;
937                         tprintf(T("%"TS" "), text);
938                 }
939                 tputchar(T('\n'));
940
941                 text = xml_get_ttext_by_path(info, langs_node, "DEFAULT");
942                 if (text)
943                         tprintf(T("Default Language:       %"TS"\n"), text);
944         }
945
946         text = xml_get_ttext_by_path(info, windows_node, "SYSTEMROOT");
947         if (text)
948                 tprintf(T("System Root:            %"TS"\n"), text);
949
950         version_node = xml_get_node_by_path(windows_node, "VERSION");
951         if (version_node) {
952                 tprintf(T("Major Version:          %"PRIu64"\n"),
953                         xml_get_number_by_path(version_node, "MAJOR"));
954                 tprintf(T("Minor Version:          %"PRIu64"\n"),
955                         xml_get_number_by_path(version_node, "MINOR"));
956                 tprintf(T("Build:                  %"PRIu64"\n"),
957                         xml_get_number_by_path(version_node, "BUILD"));
958                 tprintf(T("Service Pack Build:     %"PRIu64"\n"),
959                         xml_get_number_by_path(version_node, "SPBUILD"));
960                 tprintf(T("Service Pack Level:     %"PRIu64"\n"),
961                         xml_get_number_by_path(version_node, "SPLEVEL"));
962         }
963 }
964
965 /* Prints information about the specified image.  */
966 void
967 xml_print_image_info(struct wim_xml_info *info, int image)
968 {
969         xmlNode * const image_node = info->images[image - 1];
970         const tchar *text;
971         tchar timebuf[64];
972
973         tprintf(T("Index:                  %d\n"), image);
974
975         /* Always print the Name and Description, even if the corresponding XML
976          * elements are not present.  */
977         text = xml_get_ttext_by_path(info, image_node, "NAME");
978         tprintf(T("Name:                   %"TS"\n"), text ? text : T(""));
979         text = xml_get_ttext_by_path(info, image_node, "DESCRIPTION");
980         tprintf(T("Description:            %"TS"\n"), text ? text : T(""));
981
982         text = xml_get_ttext_by_path(info, image_node, "DISPLAYNAME");
983         if (text)
984                 tprintf(T("Display Name:           %"TS"\n"), text);
985
986         text = xml_get_ttext_by_path(info, image_node, "DISPLAYDESCRIPTION");
987         if (text)
988                 tprintf(T("Display Description:    %"TS"\n"), text);
989
990         tprintf(T("Directory Count:        %"PRIu64"\n"),
991                 xml_get_number_by_path(image_node, "DIRCOUNT"));
992
993         tprintf(T("File Count:             %"PRIu64"\n"),
994                 xml_get_number_by_path(image_node, "FILECOUNT"));
995
996         tprintf(T("Total Bytes:            %"PRIu64"\n"),
997                 xml_get_number_by_path(image_node, "TOTALBYTES"));
998
999         tprintf(T("Hard Link Bytes:        %"PRIu64"\n"),
1000                 xml_get_number_by_path(image_node, "HARDLINKBYTES"));
1001
1002         wim_timestamp_to_str(xml_get_timestamp_by_path(image_node,
1003                                                        "CREATIONTIME"),
1004                              timebuf, ARRAY_LEN(timebuf));
1005         tprintf(T("Creation Time:          %"TS"\n"), timebuf);
1006
1007         wim_timestamp_to_str(xml_get_timestamp_by_path(image_node,
1008                                                        "LASTMODIFICATIONTIME"),
1009                              timebuf, ARRAY_LEN(timebuf));
1010         tprintf(T("Last Modification Time: %"TS"\n"), timebuf);
1011
1012         print_windows_info(info, image_node);
1013
1014         text = xml_get_ttext_by_path(info, image_node, "FLAGS");
1015         if (text)
1016                 tprintf(T("Flags:                  %"TS"\n"), text);
1017
1018         tprintf(T("WIMBoot compatible:     %"TS"\n"),
1019                 xml_get_number_by_path(image_node, "WIMBOOT") ?
1020                         T("yes") : T("no"));
1021
1022         tputchar('\n');
1023 }
1024
1025 /*----------------------------------------------------------------------------*
1026  *                      Reading and writing the XML data                      *
1027  *----------------------------------------------------------------------------*/
1028
1029 static int
1030 image_node_get_index(const xmlNode *node)
1031 {
1032         u64 v = node_get_number((const xmlNode *)xmlHasProp(node, "INDEX"), 10);
1033         return min(v, INT_MAX);
1034 }
1035
1036 /* Prepare the 'images' array from the XML document tree.  */
1037 static int
1038 setup_images(struct wim_xml_info *info, xmlNode *root)
1039 {
1040         xmlNode *child;
1041         int index;
1042         int max_index = 0;
1043         int ret;
1044
1045         info->images = NULL;
1046         info->image_count = 0;
1047
1048         node_for_each_child(root, child) {
1049                 if (!node_is_element(child, "IMAGE"))
1050                         continue;
1051                 index = image_node_get_index(child);
1052                 if (unlikely(index < 1 || info->image_count >= MAX_IMAGES))
1053                         goto err_indices;
1054                 max_index = max(max_index, index);
1055                 info->image_count++;
1056         }
1057         if (unlikely(max_index != info->image_count))
1058                 goto err_indices;
1059         ret = WIMLIB_ERR_NOMEM;
1060         info->images = CALLOC(info->image_count, sizeof(info->images[0]));
1061         if (unlikely(!info->images))
1062                 goto err;
1063         node_for_each_child(root, child) {
1064                 if (!node_is_element(child, "IMAGE"))
1065                         continue;
1066                 index = image_node_get_index(child);
1067                 if (unlikely(info->images[index - 1]))
1068                         goto err_indices;
1069                 info->images[index - 1] = child;
1070         }
1071         return 0;
1072
1073 err_indices:
1074         ERROR("The WIM file's XML document does not contain exactly one IMAGE "
1075               "element per image!");
1076         ret = WIMLIB_ERR_XML;
1077 err:
1078         FREE(info->images);
1079         return ret;
1080 }
1081
1082 /* Reads the XML data from a WIM file.  */
1083 int
1084 read_wim_xml_data(WIMStruct *wim)
1085 {
1086         struct wim_xml_info *info;
1087         void *buf;
1088         size_t bufsize;
1089         xmlDoc *doc;
1090         xmlNode *root;
1091         int ret;
1092
1093         /* Allocate the 'struct wim_xml_info'.  */
1094         ret = WIMLIB_ERR_NOMEM;
1095         info = alloc_wim_xml_info();
1096         if (!info)
1097                 goto err;
1098
1099         /* Read the raw UTF-16LE bytes.  */
1100         ret = wimlib_get_xml_data(wim, &buf, &bufsize);
1101         if (ret)
1102                 goto err_free_info;
1103
1104         /* Parse the document with libxml2, creating the document tree.  */
1105         doc = xmlReadMemory(buf, bufsize, NULL, "UTF-16LE", XML_PARSE_NONET);
1106         FREE(buf);
1107         buf = NULL;
1108         if (!doc) {
1109                 ERROR("Unable to parse the WIM file's XML document!");
1110                 ret = WIMLIB_ERR_XML;
1111                 goto err_free_info;
1112         }
1113
1114         /* Verify the root element.  */
1115         root = xmlDocGetRootElement(doc);
1116         if (!node_is_element(root, "WIM")) {
1117                 ERROR("The WIM file's XML document has an unexpected format!");
1118                 ret = WIMLIB_ERR_XML;
1119                 goto err_free_doc;
1120         }
1121
1122         /* Verify the WIM file is not encrypted.  */
1123         if (xml_get_node_by_path(root, "ESD/ENCRYPTED")) {
1124                 ret = WIMLIB_ERR_WIM_IS_ENCRYPTED;
1125                 goto err_free_doc;
1126         }
1127
1128         /* Validate the image elements and set up the images[] array.  */
1129         ret = setup_images(info, root);
1130         if (ret)
1131                 goto err_free_doc;
1132
1133         /* Save the document and return.  */
1134         info->doc = doc;
1135         info->root = root;
1136         wim->xml_info = info;
1137         return 0;
1138
1139 err_free_doc:
1140         xmlFreeDoc(doc);
1141 err_free_info:
1142         FREE(info);
1143 err:
1144         return ret;
1145 }
1146
1147 /* Swap the INDEX attributes of two IMAGE elements.  */
1148 static void
1149 swap_index_attributes(xmlNode *image_node_1, xmlNode *image_node_2)
1150 {
1151         xmlAttr *attr_1, *attr_2;
1152
1153         if (image_node_1 != image_node_2) {
1154                 attr_1 = unlink_index_attribute(image_node_1);
1155                 attr_2 = unlink_index_attribute(image_node_2);
1156                 xmlAddChild(image_node_1, (xmlNode *)attr_2);
1157                 xmlAddChild(image_node_2, (xmlNode *)attr_1);
1158         }
1159 }
1160
1161 static int
1162 prepare_document_for_write(struct wim_xml_info *info, int image, u64 total_bytes,
1163                            xmlNode **orig_totalbytes_node_ret)
1164 {
1165         xmlNode *totalbytes_node = NULL;
1166
1167         /* Allocate the new TOTALBYTES element if needed.  */
1168         if (total_bytes != WIM_TOTALBYTES_USE_EXISTING &&
1169             total_bytes != WIM_TOTALBYTES_OMIT) {
1170                 totalbytes_node = new_element_with_u64(NULL, "TOTALBYTES",
1171                                                        total_bytes);
1172                 if (!totalbytes_node)
1173                         return WIMLIB_ERR_NOMEM;
1174         }
1175
1176         /* Adjust the IMAGE elements if needed.  */
1177         if (image != WIMLIB_ALL_IMAGES) {
1178                 /* We're writing a single image only.  Temporarily unlink all
1179                  * other IMAGE elements from the document.  */
1180                 for (int i = 0; i < info->image_count; i++)
1181                         if (i + 1 != image)
1182                                 xmlUnlinkNode(info->images[i]);
1183
1184                 /* Temporarily set the INDEX attribute of the needed IMAGE
1185                  * element to 1.  */
1186                 swap_index_attributes(info->images[0], info->images[image - 1]);
1187         }
1188
1189         /* Adjust (add, change, or remove) the TOTALBYTES element if needed.  */
1190         *orig_totalbytes_node_ret = NULL;
1191         if (total_bytes != WIM_TOTALBYTES_USE_EXISTING) {
1192                 /* Unlink the previous TOTALBYTES element, if any.  */
1193                 *orig_totalbytes_node_ret = xml_get_node_by_path(info->root,
1194                                                                  "TOTALBYTES");
1195                 if (*orig_totalbytes_node_ret)
1196                         xmlUnlinkNode(*orig_totalbytes_node_ret);
1197
1198                 /* Link in the new TOTALBYTES element, if any.  */
1199                 if (totalbytes_node)
1200                         xmlAddChild(info->root, totalbytes_node);
1201         }
1202         return 0;
1203 }
1204
1205 static void
1206 restore_document_after_write(struct wim_xml_info *info, int image,
1207                              xmlNode *orig_totalbytes_node)
1208 {
1209         /* Restore the IMAGE elements if needed.  */
1210         if (image != WIMLIB_ALL_IMAGES) {
1211                 /* We wrote a single image only.  Re-link all other IMAGE
1212                  * elements to the document.  */
1213                 for (int i = 0; i < info->image_count; i++)
1214                         if (i + 1 != image)
1215                                 xmlAddChild(info->root, info->images[i]);
1216
1217                 /* Restore the original INDEX attributes.  */
1218                 swap_index_attributes(info->images[0], info->images[image - 1]);
1219         }
1220
1221         /* Restore the original TOTALBYTES element if needed.  */
1222         if (orig_totalbytes_node)
1223                 node_replace_child_element(info->root, orig_totalbytes_node);
1224 }
1225
1226 /*
1227  * Writes the XML data to a WIM file.
1228  *
1229  * 'image' specifies the image(s) to include in the XML data.  Normally it is
1230  * WIMLIB_ALL_IMAGES, but it can also be a 1-based image index.
1231  *
1232  * 'total_bytes' is the number to use in the top-level TOTALBYTES element, or
1233  * WIM_TOTALBYTES_USE_EXISTING to use the existing value from the XML document
1234  * (if any), or WIM_TOTALBYTES_OMIT to omit the TOTALBYTES element entirely.
1235  */
1236 int
1237 write_wim_xml_data(WIMStruct *wim, int image, u64 total_bytes,
1238                    struct wim_reshdr *out_reshdr, int write_resource_flags)
1239 {
1240         struct wim_xml_info *info = wim->xml_info;
1241         long ret;
1242         long ret2;
1243         xmlBuffer *buffer;
1244         xmlNode *orig_totalbytes_node;
1245         xmlSaveCtxt *save_ctx;
1246
1247         /* Make any needed temporary changes to the document.  */
1248         ret = prepare_document_for_write(info, image, total_bytes,
1249                                          &orig_totalbytes_node);
1250         if (ret)
1251                 goto out;
1252
1253         /* Create an in-memory buffer to hold the encoded document.  */
1254         ret = WIMLIB_ERR_NOMEM;
1255         buffer = xmlBufferCreate();
1256         if (!buffer)
1257                 goto out_restore_document;
1258
1259         /* Encode the document in UTF-16LE, with a byte order mark, and with no
1260          * XML declaration.  Some other WIM software requires all of these
1261          * characteristics.  */
1262         ret = WIMLIB_ERR_NOMEM;
1263         if (xmlBufferCat(buffer, "\xff\xfe"))
1264                 goto out_free_buffer;
1265         save_ctx = xmlSaveToBuffer(buffer, "UTF-16LE", XML_SAVE_NO_DECL);
1266         if (!save_ctx)
1267                 goto out_free_buffer;
1268         ret = xmlSaveDoc(save_ctx, info->doc);
1269         ret2 = xmlSaveClose(save_ctx);
1270         if (ret < 0 || ret2 < 0) {
1271                 ERROR("Unable to serialize the WIM file's XML document!");
1272                 ret = WIMLIB_ERR_NOMEM;
1273                 goto out_free_buffer;
1274         }
1275
1276         /* Write the XML data uncompressed.  Although wimlib can handle
1277          * compressed XML data, some other WIM software cannot.  */
1278         ret = write_wim_resource_from_buffer(xmlBufferContent(buffer),
1279                                              xmlBufferLength(buffer),
1280                                              true,
1281                                              &wim->out_fd,
1282                                              WIMLIB_COMPRESSION_TYPE_NONE,
1283                                              0,
1284                                              out_reshdr,
1285                                              NULL,
1286                                              write_resource_flags);
1287 out_free_buffer:
1288         xmlBufferFree(buffer);
1289 out_restore_document:
1290         /* Revert any temporary changes we made to the document.  */
1291         restore_document_after_write(info, image, orig_totalbytes_node);
1292 out:
1293         return ret;
1294 }
1295
1296 /*----------------------------------------------------------------------------*
1297  *                           Global setup functions                           *
1298  *----------------------------------------------------------------------------*/
1299
1300 void
1301 xml_global_init(void)
1302 {
1303         xmlInitParser();
1304 }
1305
1306 void
1307 xml_global_cleanup(void)
1308 {
1309         xmlCleanupParser();
1310 }
1311
1312 void
1313 xml_set_memory_allocator(void *(*malloc_func)(size_t),
1314                          void (*free_func)(void *),
1315                          void *(*realloc_func)(void *, size_t))
1316 {
1317         xmlMemSetup(free_func, malloc_func, realloc_func, wimlib_strdup);
1318 }
1319
1320 /*----------------------------------------------------------------------------*
1321  *                           Library API functions                            *
1322  *----------------------------------------------------------------------------*/
1323
1324 WIMLIBAPI int
1325 wimlib_get_xml_data(WIMStruct *wim, void **buf_ret, size_t *bufsize_ret)
1326 {
1327         const struct wim_reshdr *xml_reshdr;
1328
1329         if (wim->filename == NULL && filedes_is_seekable(&wim->in_fd))
1330                 return WIMLIB_ERR_NO_FILENAME;
1331
1332         if (buf_ret == NULL || bufsize_ret == NULL)
1333                 return WIMLIB_ERR_INVALID_PARAM;
1334
1335         xml_reshdr = &wim->hdr.xml_data_reshdr;
1336
1337         *bufsize_ret = xml_reshdr->uncompressed_size;
1338         return wim_reshdr_to_data(xml_reshdr, wim, buf_ret);
1339 }
1340
1341 WIMLIBAPI int
1342 wimlib_extract_xml_data(WIMStruct *wim, FILE *fp)
1343 {
1344         int ret;
1345         void *buf;
1346         size_t bufsize;
1347
1348         ret = wimlib_get_xml_data(wim, &buf, &bufsize);
1349         if (ret)
1350                 return ret;
1351
1352         if (fwrite(buf, 1, bufsize, fp) != bufsize) {
1353                 ERROR_WITH_ERRNO("Failed to extract XML data");
1354                 ret = WIMLIB_ERR_WRITE;
1355         }
1356         FREE(buf);
1357         return ret;
1358 }
1359
1360 static bool
1361 image_name_in_use(const WIMStruct *wim, const tchar *name, int excluded_image)
1362 {
1363         const struct wim_xml_info *info = wim->xml_info;
1364         const xmlChar *name_utf8;
1365         bool found = false;
1366
1367         /* Any number of images can have "no name".  */
1368         if (!name || !*name)
1369                 return false;
1370
1371         /* Check for images that have the specified name.  */
1372         if (tstr_get_utf8(name, &name_utf8))
1373                 return false;
1374         for (int i = 0; i < info->image_count && !found; i++) {
1375                 if (i + 1 == excluded_image)
1376                         continue;
1377                 found = xmlStrEqual(name_utf8, xml_get_text_by_path(
1378                                                     info->images[i], "NAME"));
1379         }
1380         tstr_put_utf8(name_utf8);
1381         return found;
1382 }
1383
1384 WIMLIBAPI bool
1385 wimlib_image_name_in_use(const WIMStruct *wim, const tchar *name)
1386 {
1387         return image_name_in_use(wim, name, WIMLIB_NO_IMAGE);
1388 }
1389
1390 WIMLIBAPI const tchar *
1391 wimlib_get_image_name(const WIMStruct *wim, int image)
1392 {
1393         const struct wim_xml_info *info = wim->xml_info;
1394         const tchar *name;
1395
1396         if (image < 1 || image > info->image_count)
1397                 return NULL;
1398         name = wimlib_get_image_property(wim, image, T("NAME"));
1399         return name ? name : T("");
1400 }
1401
1402 WIMLIBAPI const tchar *
1403 wimlib_get_image_description(const WIMStruct *wim, int image)
1404 {
1405         return wimlib_get_image_property(wim, image, T("DESCRIPTION"));
1406 }
1407
1408 WIMLIBAPI const tchar *
1409 wimlib_get_image_property(const WIMStruct *wim, int image,
1410                           const tchar *property_name)
1411 {
1412         const xmlChar *name;
1413         const tchar *value;
1414         struct wim_xml_info *info = wim->xml_info;
1415
1416         if (!property_name || !*property_name)
1417                 return NULL;
1418         if (image < 1 || image > info->image_count)
1419                 return NULL;
1420         if (tstr_get_utf8(property_name, &name))
1421                 return NULL;
1422         value = xml_get_ttext_by_path(info, info->images[image - 1], name);
1423         tstr_put_utf8(name);
1424         return value;
1425 }
1426
1427 WIMLIBAPI int
1428 wimlib_set_image_name(WIMStruct *wim, int image, const tchar *name)
1429 {
1430         return wimlib_set_image_property(wim, image, T("NAME"), name);
1431 }
1432
1433 WIMLIBAPI int
1434 wimlib_set_image_descripton(WIMStruct *wim, int image, const tchar *description)
1435 {
1436         return wimlib_set_image_property(wim, image, T("DESCRIPTION"), description);
1437 }
1438
1439 WIMLIBAPI int
1440 wimlib_set_image_flags(WIMStruct *wim, int image, const tchar *flags)
1441 {
1442         return wimlib_set_image_property(wim, image, T("FLAGS"), flags);
1443 }
1444
1445 WIMLIBAPI int
1446 wimlib_set_image_property(WIMStruct *wim, int image, const tchar *property_name,
1447                           const tchar *property_value)
1448 {
1449         const xmlChar *name;
1450         struct wim_xml_info *info = wim->xml_info;
1451         int ret;
1452
1453         if (!property_name || !*property_name)
1454                 return WIMLIB_ERR_INVALID_PARAM;
1455
1456         if (image < 1 || image > info->image_count)
1457                 return WIMLIB_ERR_INVALID_IMAGE;
1458
1459         if (!tstrcmp(property_name, T("NAME")) &&
1460             image_name_in_use(wim, property_value, image))
1461                 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
1462
1463         ret = tstr_get_utf8(property_name, &name);
1464         if (ret)
1465                 return ret;
1466         ret = xml_set_ttext_by_path(info->images[image - 1], name, property_value);
1467         tstr_put_utf8(name);
1468         return ret;
1469 }