Delay xml_update_image_info() until write
[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 int
346 do_xml_path_walk(xmlNode *node, const xmlChar *path, bool create,
347                  xmlNode **result_ret)
348 {
349         size_t n = strlen(path) + 1;
350         xmlChar buf[n];
351         xmlChar *p;
352         xmlChar c;
353
354         *result_ret = NULL;
355
356         if (!node)
357                 return 0;
358
359         /* Copy the path to a temporary buffer.  */
360         memcpy(buf, path, n);
361         p = buf;
362
363         if (*p == '/')
364                 goto bad_syntax;
365         if (strchr(p, '[')) /* reserved for future use */
366                 goto bad_syntax;
367         c = *p;
368
369         while (c != '\0') {
370                 const xmlChar *name;
371                 xmlNode *child;
372
373                 /* We have another path component.  */
374
375                 /* Parse the element name.  */
376                 name = p;
377                 while (*p != '/' && *p != '\0')
378                         p++;
379                 if (p == name) /* empty name?  */
380                         goto bad_syntax;
381                 c = *p;
382                 *p = '\0';
383
384                 /* Look for a matching child.  */
385                 node_for_each_child(node, child)
386                         if (node_is_element(child, name))
387                                 goto next_step;
388
389                 /* No child matched the path.  If create=false, the lookup
390                  * failed.  If create=true, create the needed element.  */
391                 if (!create)
392                         return 0;
393                 child = xmlNewChild(node, NULL, name, NULL);
394                 if (!child)
395                         return WIMLIB_ERR_NOMEM;
396         next_step:
397                 /* Continue to the next path component, if there is one.  */
398                 node = child;
399                 p++;
400         }
401
402         *result_ret = node;
403         return 0;
404
405 bad_syntax:
406         ERROR("The XML path \"%s\" has invalid syntax.", path);
407         return WIMLIB_ERR_INVALID_PARAM;
408 }
409
410 /* Retrieve the XML element, if any, at the specified 'path'.  This supports a
411  * simple filesystem-like syntax.  If the element was found, returns a pointer
412  * to it; otherwise returns NULL.  */
413 static xmlNode *
414 xml_get_node_by_path(xmlNode *root, const xmlChar *path)
415 {
416         xmlNode *node;
417         do_xml_path_walk(root, path, false, &node);
418         return node;
419 }
420
421 /* Similar to xml_get_node_by_path(), but creates the element and any requisite
422  * ancestor elements as needed.   If successful, 0 is returned and *node_ret is
423  * set to a pointer to the resulting element.  If unsuccessful, an error code is
424  * returned and *node_ret is set to NULL.  */
425 static int
426 xml_ensure_node_by_path(xmlNode *root, const xmlChar *path, xmlNode **node_ret)
427 {
428         return do_xml_path_walk(root, path, true, node_ret);
429 }
430
431 static u64
432 xml_get_number_by_path(xmlNode *root, const xmlChar *path)
433 {
434         return node_get_number(xml_get_node_by_path(root, path), 10);
435 }
436
437 static u64
438 xml_get_timestamp_by_path(xmlNode *root, const xmlChar *path)
439 {
440         return node_get_timestamp(xml_get_node_by_path(root, path));
441 }
442
443 static const xmlChar *
444 xml_get_text_by_path(xmlNode *root, const xmlChar *path)
445 {
446         return node_get_text(xml_get_node_by_path(root, path));
447 }
448
449 static const tchar *
450 xml_get_ttext_by_path(struct wim_xml_info *info, xmlNode *root,
451                       const xmlChar *path)
452 {
453         return node_get_ttext(info, xml_get_node_by_path(root, path));
454 }
455
456 /* Creates/replaces (if ttext is not NULL and not empty) or removes (if ttext is
457  * NULL or empty) an element containing text.  */
458 static int
459 xml_set_ttext_by_path(xmlNode *root, const xmlChar *path, const tchar *ttext)
460 {
461         int ret;
462         xmlNode *node;
463
464         if (ttext && *ttext) {
465                 /* Create or replace  */
466                 ret = xml_ensure_node_by_path(root, path, &node);
467                 if (ret)
468                         return ret;
469                 return node_set_ttext(node, ttext);
470         } else {
471                 /* Remove  */
472                 node = xml_get_node_by_path(root, path);
473                 if (node)
474                         unlink_and_free_tree(node);
475                 return 0;
476         }
477 }
478
479 /* Sets a string property for the specified WIM image.  */
480 static int
481 set_image_property(WIMStruct *wim, int image, const xmlChar *name,
482                    const tchar *value)
483 {
484         struct wim_xml_info *info = wim->xml_info;
485
486         if (image < 1 || image > info->image_count)
487                 return WIMLIB_ERR_INVALID_IMAGE;
488
489         return xml_set_ttext_by_path(info->images[image - 1], name, value);
490 }
491
492 /* Gets a string property for the specified WIM image as a 'tchar' string.
493  * Returns a pointer to the property value if found; NULL if the image doesn't
494  * exist; or 'default_value' if the property doesn't exist in the image or if
495  * the property value could not be translated to a 'tchar' string.  */
496 static const tchar *
497 get_image_property(const WIMStruct *wim, int image, const xmlChar *name,
498                    const tchar *default_value)
499 {
500         struct wim_xml_info *info = wim->xml_info;
501         const tchar *value;
502
503         if (image < 1 || image > info->image_count)
504                 return NULL;
505
506         value = xml_get_ttext_by_path(info, info->images[image - 1], name);
507         return value ? value : default_value;
508 }
509
510 /* Unlink and return the node which represents the INDEX attribute of the
511  * specified IMAGE element.  */
512 static xmlAttr *
513 unlink_index_attribute(xmlNode *image_node)
514 {
515         xmlAttr *attr = xmlHasProp(image_node, "INDEX");
516         xmlUnlinkNode((xmlNode *)attr);
517         return attr;
518 }
519
520 /* Compute the total uncompressed size of the streams of the specified inode. */
521 static u64
522 inode_sum_stream_sizes(const struct wim_inode *inode,
523                        const struct blob_table *blob_table)
524 {
525         u64 total_size = 0;
526
527         for (unsigned i = 0; i < inode->i_num_streams; i++) {
528                 const struct blob_descriptor *blob;
529
530                 blob = stream_blob(&inode->i_streams[i], blob_table);
531                 if (blob)
532                         total_size += blob->size;
533         }
534         return total_size;
535 }
536
537 static int
538 append_image_node(struct wim_xml_info *info, xmlNode *image_node)
539 {
540         char buf[32];
541         xmlNode **images;
542
543         /* Limit exceeded?  */
544         if (unlikely(info->image_count >= MAX_IMAGES))
545                 return WIMLIB_ERR_IMAGE_COUNT;
546
547         /* Add the INDEX attribute.  */
548         sprintf(buf, "%d", info->image_count + 1);
549         if (!xmlNewProp(image_node, "INDEX", buf))
550                 return WIMLIB_ERR_NOMEM;
551
552         /* Append the IMAGE element to the 'images' array.  */
553         images = REALLOC(info->images,
554                          (info->image_count + 1) * sizeof(info->images[0]));
555         if (unlikely(!images))
556                 return WIMLIB_ERR_NOMEM;
557         info->images = images;
558         images[info->image_count++] = image_node;
559
560         /* Add the IMAGE element to the document.  */
561         xmlAddChild(info->root, image_node);
562         return 0;
563 }
564
565 /*----------------------------------------------------------------------------*
566  *                     Functions for internal library use                     *
567  *----------------------------------------------------------------------------*/
568
569 /* Allocate an empty 'struct wim_xml_info', containing no images.  */
570 struct wim_xml_info *
571 xml_new_info_struct(void)
572 {
573         struct wim_xml_info *info;
574
575         info = alloc_wim_xml_info();
576         if (!info)
577                 goto err;
578
579         info->doc = xmlNewDoc("1.0");
580         if (!info->doc)
581                 goto err_free_info;
582
583         info->root = xmlNewNode(NULL, "WIM");
584         if (!info->root)
585                 goto err_free_doc;
586         xmlDocSetRootElement(info->doc, info->root);
587
588         info->images = NULL;
589         info->image_count = 0;
590         return info;
591
592 err_free_doc:
593         xmlFreeDoc(info->doc);
594 err_free_info:
595         FREE(info);
596 err:
597         return NULL;
598 }
599
600 /* Free a 'struct wim_xml_info'.  */
601 void
602 xml_free_info_struct(struct wim_xml_info *info)
603 {
604         if (info) {
605                 xmlFreeDoc(info->doc);
606                 FREE(info->images);
607                 for (size_t i = 0; i < info->num_strings; i++)
608                         FREE(info->strings[i]);
609                 FREE(info);
610         }
611 }
612
613 /* Retrieve the number of images for which there exist IMAGE elements in the XML
614  * document.  */
615 int
616 xml_get_image_count(const struct wim_xml_info *info)
617 {
618         return info->image_count;
619 }
620
621 /* Retrieve the TOTALBYTES value for the WIM file, or 0 if this value is
622  * unavailable.  */
623 u64
624 xml_get_total_bytes(const struct wim_xml_info *info)
625 {
626         return xml_get_number_by_path(info->root, "TOTALBYTES");
627 }
628
629 /* Retrieve the TOTALBYTES value for the specified image, or 0 if this value is
630  * unavailable.  */
631 u64
632 xml_get_image_total_bytes(const struct wim_xml_info *info, int image)
633 {
634         return xml_get_number_by_path(info->images[image - 1], "TOTALBYTES");
635 }
636
637 /* Retrieve the HARDLINKBYTES value for the specified image, or 0 if this value
638  * is unavailable.  */
639 u64
640 xml_get_image_hard_link_bytes(const struct wim_xml_info *info, int image)
641 {
642         return xml_get_number_by_path(info->images[image - 1], "HARDLINKBYTES");
643 }
644
645 /* Retrieve the WIMBOOT value for the specified image, or false if this value is
646  * unavailable.  */
647 bool
648 xml_get_wimboot(const struct wim_xml_info *info, int image)
649 {
650         return xml_get_number_by_path(info->images[image - 1], "WIMBOOT");
651 }
652
653 /* Retrieve the Windows build number for the specified image, or 0 if this
654  * information is not available.  */
655 u64
656 xml_get_windows_build_number(const struct wim_xml_info *info, int image)
657 {
658         return xml_get_number_by_path(info->images[image - 1],
659                                       "WINDOWS/VERSION/BUILD");
660 }
661
662 /* Set the WIMBOOT value for the specified image.  */
663 int
664 xml_set_wimboot(struct wim_xml_info *info, int image)
665 {
666         return xml_set_ttext_by_path(info->images[image - 1], "WIMBOOT", T("1"));
667 }
668
669 /*
670  * Update the DIRCOUNT, FILECOUNT, TOTALBYTES, HARDLINKBYTES, and
671  * LASTMODIFICATIONTIME elements for the specified WIM image.
672  *
673  * Note: since these stats are likely to be used for display purposes only, we
674  * no longer attempt to duplicate WIMGAPI's weird bugs when calculating them.
675  */
676 int
677 xml_update_image_info(WIMStruct *wim, int image)
678 {
679         const struct wim_image_metadata *imd = wim->image_metadata[image - 1];
680         xmlNode *image_node = wim->xml_info->images[image - 1];
681         const struct wim_inode *inode;
682         u64 dir_count = 0;
683         u64 file_count = 0;
684         u64 total_bytes = 0;
685         u64 hard_link_bytes = 0;
686         u64 size;
687         xmlNode *dircount_node;
688         xmlNode *filecount_node;
689         xmlNode *totalbytes_node;
690         xmlNode *hardlinkbytes_node;
691         xmlNode *lastmodificationtime_node;
692
693         image_for_each_inode(inode, imd) {
694                 if (inode_is_directory(inode))
695                         dir_count += inode->i_nlink;
696                 else
697                         file_count += inode->i_nlink;
698                 size = inode_sum_stream_sizes(inode, wim->blob_table);
699                 total_bytes += size * inode->i_nlink;
700                 hard_link_bytes += size * (inode->i_nlink - 1);
701         }
702
703         dircount_node = new_element_with_u64(NULL, "DIRCOUNT", dir_count);
704         filecount_node = new_element_with_u64(NULL, "FILECOUNT", file_count);
705         totalbytes_node = new_element_with_u64(NULL, "TOTALBYTES", total_bytes);
706         hardlinkbytes_node = new_element_with_u64(NULL, "HARDLINKBYTES",
707                                                   hard_link_bytes);
708         lastmodificationtime_node =
709                 new_element_with_timestamp(NULL, "LASTMODIFICATIONTIME",
710                                            now_as_wim_timestamp());
711
712         if (unlikely(!dircount_node || !filecount_node || !totalbytes_node ||
713                      !hardlinkbytes_node || !lastmodificationtime_node)) {
714                 xmlFreeNode(dircount_node);
715                 xmlFreeNode(filecount_node);
716                 xmlFreeNode(totalbytes_node);
717                 xmlFreeNode(hardlinkbytes_node);
718                 xmlFreeNode(lastmodificationtime_node);
719                 return WIMLIB_ERR_NOMEM;
720         }
721
722         node_replace_child_element(image_node, dircount_node);
723         node_replace_child_element(image_node, filecount_node);
724         node_replace_child_element(image_node, totalbytes_node);
725         node_replace_child_element(image_node, hardlinkbytes_node);
726         node_replace_child_element(image_node, lastmodificationtime_node);
727         return 0;
728 }
729
730 /* Add an image to the XML information. */
731 int
732 xml_add_image(struct wim_xml_info *info, const tchar *name)
733 {
734         const u64 now = now_as_wim_timestamp();
735         xmlNode *image_node;
736         int ret;
737
738         ret = WIMLIB_ERR_NOMEM;
739         image_node = xmlNewNode(NULL, "IMAGE");
740         if (!image_node)
741                 goto err;
742
743         if (name && *name) {
744                 ret = new_element_with_ttext(image_node, "NAME", name, NULL);
745                 if (ret)
746                         goto err;
747         }
748         ret = WIMLIB_ERR_NOMEM;
749         if (!new_element_with_u64(image_node, "DIRCOUNT", 0))
750                 goto err;
751         if (!new_element_with_u64(image_node, "FILECOUNT", 0))
752                 goto err;
753         if (!new_element_with_u64(image_node, "TOTALBYTES", 0))
754                 goto err;
755         if (!new_element_with_u64(image_node, "HARDLINKBYTES", 0))
756                 goto err;
757         if (!new_element_with_timestamp(image_node, "CREATIONTIME", now))
758                 goto err;
759         if (!new_element_with_timestamp(image_node, "LASTMODIFICATIONTIME", now))
760                 goto err;
761         ret = append_image_node(info, image_node);
762         if (ret)
763                 goto err;
764         return 0;
765
766 err:
767         xmlFreeNode(image_node);
768         return ret;
769 }
770
771 /*
772  * Make a copy of the XML information for the image with index @src_image in the
773  * @src_info XML document and append it to the @dest_info XML document.
774  *
775  * In the process, change the image's name and description to the values
776  * specified by @dest_image_name and @dest_image_description.  Either or both
777  * may be NULL, which indicates that the corresponding element will not be
778  * included in the destination image.
779  */
780 int
781 xml_export_image(const struct wim_xml_info *src_info, int src_image,
782                  struct wim_xml_info *dest_info, const tchar *dest_image_name,
783                  const tchar *dest_image_description, bool wimboot)
784 {
785         xmlNode *dest_node;
786         int ret;
787
788         ret = WIMLIB_ERR_NOMEM;
789         dest_node = xmlDocCopyNode(src_info->images[src_image - 1],
790                                    dest_info->doc, 1);
791         if (!dest_node)
792                 goto err;
793
794         ret = xml_set_ttext_by_path(dest_node, "NAME", dest_image_name);
795         if (ret)
796                 goto err;
797
798         ret = xml_set_ttext_by_path(dest_node, "DESCRIPTION",
799                                     dest_image_description);
800         if (ret)
801                 goto err;
802
803         if (wimboot) {
804                 ret = xml_set_ttext_by_path(dest_node, "WIMBOOT", T("1"));
805                 if (ret)
806                         goto err;
807         }
808
809         xmlFreeProp(unlink_index_attribute(dest_node));
810
811         ret = append_image_node(dest_info, dest_node);
812         if (ret)
813                 goto err;
814         return 0;
815
816 err:
817         xmlFreeNode(dest_node);
818         return ret;
819 }
820
821 /* Remove the specified image from the XML document.  */
822 void
823 xml_delete_image(struct wim_xml_info *info, int image)
824 {
825         xmlNode *next_image;
826         xmlAttr *index_attr, *next_index_attr;
827
828         /* Free the IMAGE element for the deleted image.  Then, shift all
829          * higher-indexed IMAGE elements down by 1, in the process re-assigning
830          * their INDEX attributes.  */
831
832         next_image = info->images[image - 1];
833         next_index_attr = unlink_index_attribute(next_image);
834         unlink_and_free_tree(next_image);
835
836         while (image < info->image_count) {
837                 index_attr = next_index_attr;
838                 next_image = info->images[image];
839                 next_index_attr = unlink_index_attribute(next_image);
840                 xmlAddChild(next_image, (xmlNode *)index_attr);
841                 info->images[image - 1] = next_image;
842                 image++;
843         }
844
845         xmlFreeProp(next_index_attr);
846         info->image_count--;
847 }
848
849 /* Architecture constants are from w64 mingw winnt.h  */
850 #define PROCESSOR_ARCHITECTURE_INTEL            0
851 #define PROCESSOR_ARCHITECTURE_MIPS             1
852 #define PROCESSOR_ARCHITECTURE_ALPHA            2
853 #define PROCESSOR_ARCHITECTURE_PPC              3
854 #define PROCESSOR_ARCHITECTURE_SHX              4
855 #define PROCESSOR_ARCHITECTURE_ARM              5
856 #define PROCESSOR_ARCHITECTURE_IA64             6
857 #define PROCESSOR_ARCHITECTURE_ALPHA64          7
858 #define PROCESSOR_ARCHITECTURE_MSIL             8
859 #define PROCESSOR_ARCHITECTURE_AMD64            9
860 #define PROCESSOR_ARCHITECTURE_IA32_ON_WIN64    10
861
862 static const tchar *
863 describe_arch(u64 arch)
864 {
865         static const tchar * const descriptions[] = {
866                 [PROCESSOR_ARCHITECTURE_INTEL] = T("x86"),
867                 [PROCESSOR_ARCHITECTURE_MIPS]  = T("MIPS"),
868                 [PROCESSOR_ARCHITECTURE_ARM]   = T("ARM"),
869                 [PROCESSOR_ARCHITECTURE_IA64]  = T("ia64"),
870                 [PROCESSOR_ARCHITECTURE_AMD64] = T("x86_64"),
871         };
872
873         if (arch < ARRAY_LEN(descriptions) && descriptions[arch] != NULL)
874                 return descriptions[arch];
875
876         return T("unknown");
877 }
878
879 /* Print information from the WINDOWS element, if present.  */
880 static void
881 print_windows_info(struct wim_xml_info *info, xmlNode *image_node)
882 {
883         xmlNode *windows_node;
884         xmlNode *langs_node;
885         xmlNode *version_node;
886         const tchar *text;
887
888         windows_node = xml_get_node_by_path(image_node, "WINDOWS");
889         if (!windows_node)
890                 return;
891
892         tprintf(T("Architecture:           %"TS"\n"),
893                 describe_arch(xml_get_number_by_path(windows_node, "ARCH")));
894
895         text = xml_get_ttext_by_path(info, windows_node, "PRODUCTNAME");
896         if (text)
897                 tprintf(T("Product Name:           %"TS"\n"), text);
898
899         text = xml_get_ttext_by_path(info, windows_node, "EDITIONID");
900         if (text)
901                 tprintf(T("Edition ID:             %"TS"\n"), text);
902
903         text = xml_get_ttext_by_path(info, windows_node, "INSTALLATIONTYPE");
904         if (text)
905                 tprintf(T("Installation Type:      %"TS"\n"), text);
906
907         text = xml_get_ttext_by_path(info, windows_node, "HAL");
908         if (text)
909                 tprintf(T("HAL:                    %"TS"\n"), text);
910
911         text = xml_get_ttext_by_path(info, windows_node, "PRODUCTTYPE");
912         if (text)
913                 tprintf(T("Product Type:           %"TS"\n"), text);
914
915         text = xml_get_ttext_by_path(info, windows_node, "PRODUCTSUITE");
916         if (text)
917                 tprintf(T("Product Suite:          %"TS"\n"), text);
918
919         langs_node = xml_get_node_by_path(windows_node, "LANGUAGES");
920         if (langs_node) {
921                 xmlNode *lang_node;
922
923                 tprintf(T("Languages:              "));
924                 node_for_each_child(langs_node, lang_node) {
925                         if (!node_is_element(lang_node, "LANGUAGE"))
926                                 continue;
927                         text = node_get_ttext(info, lang_node);
928                         if (!text)
929                                 continue;
930                         tprintf(T("%"TS" "), text);
931                 }
932                 tputchar(T('\n'));
933
934                 text = xml_get_ttext_by_path(info, langs_node, "DEFAULT");
935                 if (text)
936                         tprintf(T("Default Language:       %"TS"\n"), text);
937         }
938
939         text = xml_get_ttext_by_path(info, windows_node, "SYSTEMROOT");
940         if (text)
941                 tprintf(T("System Root:            %"TS"\n"), text);
942
943         version_node = xml_get_node_by_path(windows_node, "VERSION");
944         if (version_node) {
945                 tprintf(T("Major Version:          %"PRIu64"\n"),
946                         xml_get_number_by_path(version_node, "MAJOR"));
947                 tprintf(T("Minor Version:          %"PRIu64"\n"),
948                         xml_get_number_by_path(version_node, "MINOR"));
949                 tprintf(T("Build:                  %"PRIu64"\n"),
950                         xml_get_number_by_path(version_node, "BUILD"));
951                 tprintf(T("Service Pack Build:     %"PRIu64"\n"),
952                         xml_get_number_by_path(version_node, "SPBUILD"));
953                 tprintf(T("Service Pack Level:     %"PRIu64"\n"),
954                         xml_get_number_by_path(version_node, "SPLEVEL"));
955         }
956 }
957
958 /* Prints information about the specified image.  */
959 void
960 xml_print_image_info(struct wim_xml_info *info, int image)
961 {
962         xmlNode * const image_node = info->images[image - 1];
963         const tchar *text;
964         tchar timebuf[64];
965
966         tprintf(T("Index:                  %d\n"), image);
967
968         /* Always print the Name and Description, even if the corresponding XML
969          * elements are not present.  */
970         text = xml_get_ttext_by_path(info, image_node, "NAME");
971         tprintf(T("Name:                   %"TS"\n"), text ? text : T(""));
972         text = xml_get_ttext_by_path(info, image_node, "DESCRIPTION");
973         tprintf(T("Description:            %"TS"\n"), text ? text : T(""));
974
975         text = xml_get_ttext_by_path(info, image_node, "DISPLAYNAME");
976         if (text)
977                 tprintf(T("Display Name:           %"TS"\n"), text);
978
979         text = xml_get_ttext_by_path(info, image_node, "DISPLAYDESCRIPTION");
980         if (text)
981                 tprintf(T("Display Description:    %"TS"\n"), text);
982
983         tprintf(T("Directory Count:        %"PRIu64"\n"),
984                 xml_get_number_by_path(image_node, "DIRCOUNT"));
985
986         tprintf(T("File Count:             %"PRIu64"\n"),
987                 xml_get_number_by_path(image_node, "FILECOUNT"));
988
989         tprintf(T("Total Bytes:            %"PRIu64"\n"),
990                 xml_get_number_by_path(image_node, "TOTALBYTES"));
991
992         tprintf(T("Hard Link Bytes:        %"PRIu64"\n"),
993                 xml_get_number_by_path(image_node, "HARDLINKBYTES"));
994
995         wim_timestamp_to_str(xml_get_timestamp_by_path(image_node,
996                                                        "CREATIONTIME"),
997                              timebuf, ARRAY_LEN(timebuf));
998         tprintf(T("Creation Time:          %"TS"\n"), timebuf);
999
1000         wim_timestamp_to_str(xml_get_timestamp_by_path(image_node,
1001                                                        "LASTMODIFICATIONTIME"),
1002                              timebuf, ARRAY_LEN(timebuf));
1003         tprintf(T("Last Modification Time: %"TS"\n"), timebuf);
1004
1005         print_windows_info(info, image_node);
1006
1007         text = xml_get_ttext_by_path(info, image_node, "FLAGS");
1008         if (text)
1009                 tprintf(T("Flags:                  %"TS"\n"), text);
1010
1011         tprintf(T("WIMBoot compatible:     %"TS"\n"),
1012                 xml_get_number_by_path(image_node, "WIMBOOT") ?
1013                         T("yes") : T("no"));
1014
1015         tputchar('\n');
1016 }
1017
1018 /*----------------------------------------------------------------------------*
1019  *                      Reading and writing the XML data                      *
1020  *----------------------------------------------------------------------------*/
1021
1022 static int
1023 image_node_get_index(const xmlNode *node)
1024 {
1025         u64 v = node_get_number((const xmlNode *)xmlHasProp(node, "INDEX"), 10);
1026         return min(v, INT_MAX);
1027 }
1028
1029 /* Prepare the 'images' array from the XML document tree.  */
1030 static int
1031 setup_images(struct wim_xml_info *info, xmlNode *root)
1032 {
1033         xmlNode *child;
1034         int index;
1035         int max_index = 0;
1036         int ret;
1037
1038         info->images = NULL;
1039         info->image_count = 0;
1040
1041         node_for_each_child(root, child) {
1042                 if (!node_is_element(child, "IMAGE"))
1043                         continue;
1044                 index = image_node_get_index(child);
1045                 if (unlikely(index < 1 || info->image_count >= MAX_IMAGES))
1046                         goto err_indices;
1047                 max_index = max(max_index, index);
1048                 info->image_count++;
1049         }
1050         if (unlikely(max_index != info->image_count))
1051                 goto err_indices;
1052         ret = WIMLIB_ERR_NOMEM;
1053         info->images = CALLOC(info->image_count, sizeof(info->images[0]));
1054         if (unlikely(!info->images))
1055                 goto err;
1056         node_for_each_child(root, child) {
1057                 if (!node_is_element(child, "IMAGE"))
1058                         continue;
1059                 index = image_node_get_index(child);
1060                 if (unlikely(info->images[index - 1]))
1061                         goto err_indices;
1062                 info->images[index - 1] = child;
1063         }
1064         return 0;
1065
1066 err_indices:
1067         ERROR("The WIM file's XML document does not contain exactly one IMAGE "
1068               "element per image!");
1069         ret = WIMLIB_ERR_XML;
1070 err:
1071         FREE(info->images);
1072         return ret;
1073 }
1074
1075 /* Reads the XML data from a WIM file.  */
1076 int
1077 read_wim_xml_data(WIMStruct *wim)
1078 {
1079         struct wim_xml_info *info;
1080         void *buf;
1081         size_t bufsize;
1082         xmlDoc *doc;
1083         xmlNode *root;
1084         int ret;
1085
1086         /* Allocate the 'struct wim_xml_info'.  */
1087         ret = WIMLIB_ERR_NOMEM;
1088         info = alloc_wim_xml_info();
1089         if (!info)
1090                 goto err;
1091
1092         /* Read the raw UTF-16LE bytes.  */
1093         ret = wimlib_get_xml_data(wim, &buf, &bufsize);
1094         if (ret)
1095                 goto err_free_info;
1096
1097         /* Parse the document with libxml2, creating the document tree.  */
1098         doc = xmlReadMemory(buf, bufsize, NULL, "UTF-16LE", XML_PARSE_NONET);
1099         FREE(buf);
1100         buf = NULL;
1101         if (!doc) {
1102                 ERROR("Unable to parse the WIM file's XML document!");
1103                 ret = WIMLIB_ERR_XML;
1104                 goto err_free_info;
1105         }
1106
1107         /* Verify the root element.  */
1108         root = xmlDocGetRootElement(doc);
1109         if (!node_is_element(root, "WIM")) {
1110                 ERROR("The WIM file's XML document has an unexpected format!");
1111                 ret = WIMLIB_ERR_XML;
1112                 goto err_free_doc;
1113         }
1114
1115         /* Verify the WIM file is not encrypted.  */
1116         if (xml_get_node_by_path(root, "ESD/ENCRYPTED")) {
1117                 ret = WIMLIB_ERR_WIM_IS_ENCRYPTED;
1118                 goto err_free_doc;
1119         }
1120
1121         /* Validate the image elements and set up the images[] array.  */
1122         ret = setup_images(info, root);
1123         if (ret)
1124                 goto err_free_doc;
1125
1126         /* Save the document and return.  */
1127         info->doc = doc;
1128         info->root = root;
1129         wim->xml_info = info;
1130         return 0;
1131
1132 err_free_doc:
1133         xmlFreeDoc(doc);
1134 err_free_info:
1135         FREE(info);
1136 err:
1137         return ret;
1138 }
1139
1140 /* Swap the INDEX attributes of two IMAGE elements.  */
1141 static void
1142 swap_index_attributes(xmlNode *image_node_1, xmlNode *image_node_2)
1143 {
1144         xmlAttr *attr_1, *attr_2;
1145
1146         if (image_node_1 != image_node_2) {
1147                 attr_1 = unlink_index_attribute(image_node_1);
1148                 attr_2 = unlink_index_attribute(image_node_2);
1149                 xmlAddChild(image_node_1, (xmlNode *)attr_2);
1150                 xmlAddChild(image_node_2, (xmlNode *)attr_1);
1151         }
1152 }
1153
1154 static int
1155 prepare_document_for_write(struct wim_xml_info *info, int image, u64 total_bytes,
1156                            xmlNode **orig_totalbytes_node_ret)
1157 {
1158         xmlNode *totalbytes_node = NULL;
1159
1160         /* Allocate the new TOTALBYTES element if needed.  */
1161         if (total_bytes != WIM_TOTALBYTES_USE_EXISTING &&
1162             total_bytes != WIM_TOTALBYTES_OMIT) {
1163                 totalbytes_node = new_element_with_u64(NULL, "TOTALBYTES",
1164                                                        total_bytes);
1165                 if (!totalbytes_node)
1166                         return WIMLIB_ERR_NOMEM;
1167         }
1168
1169         /* Adjust the IMAGE elements if needed.  */
1170         if (image != WIMLIB_ALL_IMAGES) {
1171                 /* We're writing a single image only.  Temporarily unlink all
1172                  * other IMAGE elements from the document.  */
1173                 for (int i = 0; i < info->image_count; i++)
1174                         if (i + 1 != image)
1175                                 xmlUnlinkNode(info->images[i]);
1176
1177                 /* Temporarily set the INDEX attribute of the needed IMAGE
1178                  * element to 1.  */
1179                 swap_index_attributes(info->images[0], info->images[image - 1]);
1180         }
1181
1182         /* Adjust (add, change, or remove) the TOTALBYTES element if needed.  */
1183         *orig_totalbytes_node_ret = NULL;
1184         if (total_bytes != WIM_TOTALBYTES_USE_EXISTING) {
1185                 /* Unlink the previous TOTALBYTES element, if any.  */
1186                 *orig_totalbytes_node_ret = xml_get_node_by_path(info->root,
1187                                                                  "TOTALBYTES");
1188                 if (*orig_totalbytes_node_ret)
1189                         xmlUnlinkNode(*orig_totalbytes_node_ret);
1190
1191                 /* Link in the new TOTALBYTES element, if any.  */
1192                 if (totalbytes_node)
1193                         xmlAddChild(info->root, totalbytes_node);
1194         }
1195         return 0;
1196 }
1197
1198 static void
1199 restore_document_after_write(struct wim_xml_info *info, int image,
1200                              xmlNode *orig_totalbytes_node)
1201 {
1202         /* Restore the IMAGE elements if needed.  */
1203         if (image != WIMLIB_ALL_IMAGES) {
1204                 /* We wrote a single image only.  Re-link all other IMAGE
1205                  * elements to the document.  */
1206                 for (int i = 0; i < info->image_count; i++)
1207                         if (i + 1 != image)
1208                                 xmlAddChild(info->root, info->images[i]);
1209
1210                 /* Restore the original INDEX attributes.  */
1211                 swap_index_attributes(info->images[0], info->images[image - 1]);
1212         }
1213
1214         /* Restore the original TOTALBYTES element if needed.  */
1215         if (orig_totalbytes_node)
1216                 node_replace_child_element(info->root, orig_totalbytes_node);
1217 }
1218
1219 /*
1220  * Writes the XML data to a WIM file.
1221  *
1222  * 'image' specifies the image(s) to include in the XML data.  Normally it is
1223  * WIMLIB_ALL_IMAGES, but it can also be a 1-based image index.
1224  *
1225  * 'total_bytes' is the number to use in the top-level TOTALBYTES element, or
1226  * WIM_TOTALBYTES_USE_EXISTING to use the existing value from the XML document
1227  * (if any), or WIM_TOTALBYTES_OMIT to omit the TOTALBYTES element entirely.
1228  */
1229 int
1230 write_wim_xml_data(WIMStruct *wim, int image, u64 total_bytes,
1231                    struct wim_reshdr *out_reshdr, int write_resource_flags)
1232 {
1233         struct wim_xml_info *info = wim->xml_info;
1234         long ret;
1235         long ret2;
1236         xmlBuffer *buffer;
1237         xmlNode *orig_totalbytes_node;
1238         xmlSaveCtxt *save_ctx;
1239
1240         /* Make any needed temporary changes to the document.  */
1241         ret = prepare_document_for_write(info, image, total_bytes,
1242                                          &orig_totalbytes_node);
1243         if (ret)
1244                 goto out;
1245
1246         /* Create an in-memory buffer to hold the encoded document.  */
1247         ret = WIMLIB_ERR_NOMEM;
1248         buffer = xmlBufferCreate();
1249         if (!buffer)
1250                 goto out_restore_document;
1251
1252         /* Encode the document in UTF-16LE, with a byte order mark, and with no
1253          * XML declaration.  Some other WIM software requires all of these
1254          * characteristics.  */
1255         ret = WIMLIB_ERR_NOMEM;
1256         if (xmlBufferCat(buffer, "\xff\xfe"))
1257                 goto out_free_buffer;
1258         save_ctx = xmlSaveToBuffer(buffer, "UTF-16LE", XML_SAVE_NO_DECL);
1259         if (!save_ctx)
1260                 goto out_free_buffer;
1261         ret = xmlSaveDoc(save_ctx, info->doc);
1262         ret2 = xmlSaveClose(save_ctx);
1263         if (ret < 0 || ret2 < 0) {
1264                 ERROR("Unable to serialize the WIM file's XML document!");
1265                 ret = WIMLIB_ERR_NOMEM;
1266                 goto out_free_buffer;
1267         }
1268
1269         /* Write the XML data uncompressed.  Although wimlib can handle
1270          * compressed XML data, some other WIM software cannot.  */
1271         ret = write_wim_resource_from_buffer(xmlBufferContent(buffer),
1272                                              xmlBufferLength(buffer),
1273                                              true,
1274                                              &wim->out_fd,
1275                                              WIMLIB_COMPRESSION_TYPE_NONE,
1276                                              0,
1277                                              out_reshdr,
1278                                              NULL,
1279                                              write_resource_flags);
1280 out_free_buffer:
1281         xmlBufferFree(buffer);
1282 out_restore_document:
1283         /* Revert any temporary changes we made to the document.  */
1284         restore_document_after_write(info, image, orig_totalbytes_node);
1285 out:
1286         return ret;
1287 }
1288
1289 /*----------------------------------------------------------------------------*
1290  *                           Global setup functions                           *
1291  *----------------------------------------------------------------------------*/
1292
1293 void
1294 xml_global_init(void)
1295 {
1296         xmlInitParser();
1297 }
1298
1299 void
1300 xml_global_cleanup(void)
1301 {
1302         xmlCleanupParser();
1303 }
1304
1305 void
1306 xml_set_memory_allocator(void *(*malloc_func)(size_t),
1307                          void (*free_func)(void *),
1308                          void *(*realloc_func)(void *, size_t))
1309 {
1310         xmlMemSetup(free_func, malloc_func, realloc_func, wimlib_strdup);
1311 }
1312
1313 /*----------------------------------------------------------------------------*
1314  *                           Library API functions                            *
1315  *----------------------------------------------------------------------------*/
1316
1317 WIMLIBAPI int
1318 wimlib_get_xml_data(WIMStruct *wim, void **buf_ret, size_t *bufsize_ret)
1319 {
1320         const struct wim_reshdr *xml_reshdr;
1321
1322         if (wim->filename == NULL && filedes_is_seekable(&wim->in_fd))
1323                 return WIMLIB_ERR_NO_FILENAME;
1324
1325         if (buf_ret == NULL || bufsize_ret == NULL)
1326                 return WIMLIB_ERR_INVALID_PARAM;
1327
1328         xml_reshdr = &wim->hdr.xml_data_reshdr;
1329
1330         *bufsize_ret = xml_reshdr->uncompressed_size;
1331         return wim_reshdr_to_data(xml_reshdr, wim, buf_ret);
1332 }
1333
1334 WIMLIBAPI int
1335 wimlib_extract_xml_data(WIMStruct *wim, FILE *fp)
1336 {
1337         int ret;
1338         void *buf;
1339         size_t bufsize;
1340
1341         ret = wimlib_get_xml_data(wim, &buf, &bufsize);
1342         if (ret)
1343                 return ret;
1344
1345         if (fwrite(buf, 1, bufsize, fp) != bufsize) {
1346                 ERROR_WITH_ERRNO("Failed to extract XML data");
1347                 ret = WIMLIB_ERR_WRITE;
1348         }
1349         FREE(buf);
1350         return ret;
1351 }
1352
1353 static bool
1354 image_name_in_use(const WIMStruct *wim, const tchar *name, int excluded_image)
1355 {
1356         const struct wim_xml_info *info = wim->xml_info;
1357         const xmlChar *name_utf8;
1358         bool found = false;
1359
1360         /* Any number of images can have "no name".  */
1361         if (!name || !*name)
1362                 return false;
1363
1364         /* Check for images that have the specified name.  */
1365         if (tstr_get_utf8(name, &name_utf8))
1366                 return false;
1367         for (int i = 0; i < info->image_count && !found; i++) {
1368                 if (i + 1 == excluded_image)
1369                         continue;
1370                 found = xmlStrEqual(name_utf8, xml_get_text_by_path(
1371                                                     info->images[i], "NAME"));
1372         }
1373         tstr_put_utf8(name_utf8);
1374         return found;
1375 }
1376
1377 WIMLIBAPI bool
1378 wimlib_image_name_in_use(const WIMStruct *wim, const tchar *name)
1379 {
1380         return image_name_in_use(wim, name, WIMLIB_NO_IMAGE);
1381 }
1382
1383 WIMLIBAPI const tchar *
1384 wimlib_get_image_name(const WIMStruct *wim, int image)
1385 {
1386         return get_image_property(wim, image, "NAME", T(""));
1387 }
1388
1389 WIMLIBAPI const tchar *
1390 wimlib_get_image_description(const WIMStruct *wim, int image)
1391 {
1392         return get_image_property(wim, image, "DESCRIPTION", NULL);
1393 }
1394
1395 WIMLIBAPI const tchar *
1396 wimlib_get_image_property(const WIMStruct *wim, int image,
1397                           const tchar *property_name)
1398 {
1399         const xmlChar *name;
1400         const tchar *value;
1401
1402         if (!property_name || !*property_name)
1403                 return NULL;
1404         if (tstr_get_utf8(property_name, &name))
1405                 return NULL;
1406         value = get_image_property(wim, image, name, NULL);
1407         tstr_put_utf8(name);
1408         return value;
1409 }
1410
1411 WIMLIBAPI int
1412 wimlib_set_image_name(WIMStruct *wim, int image, const tchar *name)
1413 {
1414         if (image_name_in_use(wim, name, image))
1415                 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
1416
1417         return set_image_property(wim, image, "NAME", name);
1418 }
1419
1420 WIMLIBAPI int
1421 wimlib_set_image_descripton(WIMStruct *wim, int image, const tchar *description)
1422 {
1423         return set_image_property(wim, image, "DESCRIPTION", description);
1424 }
1425
1426 WIMLIBAPI int
1427 wimlib_set_image_flags(WIMStruct *wim, int image, const tchar *flags)
1428 {
1429         return set_image_property(wim, image, "FLAGS", flags);
1430 }
1431
1432 WIMLIBAPI int
1433 wimlib_set_image_property(WIMStruct *wim, int image, const tchar *property_name,
1434                           const tchar *property_value)
1435 {
1436         const xmlChar *name;
1437         int ret;
1438
1439         if (!property_name || !*property_name)
1440                 return WIMLIB_ERR_INVALID_PARAM;
1441
1442         ret = tstr_get_utf8(property_name, &name);
1443         if (ret)
1444                 return ret;
1445         ret = set_image_property(wim, image, name, property_value);
1446         tstr_put_utf8(name);
1447         return ret;
1448 }