]> wimlib.net Git - wimlib/blob - src/wim.c
wimlib.h: Update docs and adjust error codes
[wimlib] / src / wim.c
1 /*
2  * wim.c - Stuff that doesn't fit into any other file
3  */
4
5 /*
6  * Copyright (C) 2012, 2013 Eric Biggers
7  *
8  * This file is part of wimlib, a library for working with WIM files.
9  *
10  * wimlib is free software; you can redistribute it and/or modify it under the
11  * terms of the GNU General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option)
13  * any later version.
14  *
15  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17  * A PARTICULAR PURPOSE. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with wimlib; if not, see http://www.gnu.org/licenses/.
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #  include "config.h"
26 #endif
27
28 #include "wimlib/error.h"
29 #include "wimlib/dentry.h"
30 #include "wimlib/encoding.h"
31 #include "wimlib/file_io.h"
32 #include "wimlib/integrity.h"
33 #include "wimlib/lookup_table.h"
34 #include "wimlib/metadata.h"
35 #ifdef WITH_NTFS_3G
36 #  include "wimlib/ntfs_3g.h" /* for do_ntfs_umount() */
37 #endif
38 #include "wimlib/security.h"
39 #include "wimlib/wim.h"
40 #include "wimlib/xml.h"
41
42 #ifdef __WIN32__
43 #  include "wimlib/win32.h" /* for realpath() replacement */
44 #endif
45
46 #include <errno.h>
47 #include <fcntl.h>
48 #ifndef __WIN32__
49 #  include <langinfo.h>
50 #endif
51 #include <limits.h>
52 #include <stdarg.h>
53 #include <stdlib.h>
54 #include <unistd.h>
55
56 static int
57 image_print_metadata(WIMStruct *wim)
58 {
59         DEBUG("Printing metadata for image %d", wim->current_image);
60         print_wim_security_data(wim_security_data(wim));
61         return for_dentry_in_tree(wim_root_dentry(wim), print_dentry,
62                                   wim->lookup_table);
63 }
64
65
66 static WIMStruct *
67 new_wim_struct(void)
68 {
69         WIMStruct *wim = CALLOC(1, sizeof(WIMStruct));
70         if (wim) {
71                 wim->in_fd.fd = -1;
72                 wim->out_fd.fd = -1;
73         }
74         return wim;
75 }
76
77 /*
78  * Calls a function on images in the WIM.  If @image is WIMLIB_ALL_IMAGES, @visitor
79  * is called on the WIM once for each image, with each image selected as the
80  * current image in turn.  If @image is a certain image, @visitor is called on
81  * the WIM only once, with that image selected.
82  */
83 int
84 for_image(WIMStruct *wim, int image, int (*visitor)(WIMStruct *))
85 {
86         int ret;
87         int start;
88         int end;
89         int i;
90
91         if (image == WIMLIB_ALL_IMAGES) {
92                 start = 1;
93                 end = wim->hdr.image_count;
94         } else if (image >= 1 && image <= wim->hdr.image_count) {
95                 start = image;
96                 end = image;
97         } else {
98                 return WIMLIB_ERR_INVALID_IMAGE;
99         }
100         for (i = start; i <= end; i++) {
101                 ret = select_wim_image(wim, i);
102                 if (ret != 0)
103                         return ret;
104                 ret = visitor(wim);
105                 if (ret != 0)
106                         return ret;
107         }
108         return 0;
109 }
110
111 /* API function documented in wimlib.h  */
112 WIMLIBAPI int
113 wimlib_create_new_wim(int ctype, WIMStruct **wim_ret)
114 {
115         WIMStruct *wim;
116         struct wim_lookup_table *table;
117         int ret;
118
119         wimlib_global_init(WIMLIB_INIT_FLAG_ASSUME_UTF8);
120
121         DEBUG("Creating new WIM with %"TS" compression.",
122               wimlib_get_compression_type_string(ctype));
123
124         /* Allocate the WIMStruct. */
125         wim = new_wim_struct();
126         if (!wim)
127                 return WIMLIB_ERR_NOMEM;
128
129         ret = init_wim_header(&wim->hdr, ctype);
130         if (ret != 0)
131                 goto out_free;
132
133         table = new_lookup_table(9001);
134         if (!table) {
135                 ret = WIMLIB_ERR_NOMEM;
136                 goto out_free;
137         }
138         wim->lookup_table = table;
139         wim->refcnts_ok = 1;
140         wim->compression_type = ctype;
141         *wim_ret = wim;
142         return 0;
143 out_free:
144         FREE(wim);
145         return ret;
146 }
147
148 int
149 select_wim_image(WIMStruct *wim, int image)
150 {
151         struct wim_image_metadata *imd;
152         int ret;
153
154         DEBUG("Selecting image %d", image);
155
156         if (image == WIMLIB_NO_IMAGE) {
157                 ERROR("Invalid image: %d", WIMLIB_NO_IMAGE);
158                 return WIMLIB_ERR_INVALID_IMAGE;
159         }
160
161         if (image == wim->current_image)
162                 return 0;
163
164         if (image < 1 || image > wim->hdr.image_count) {
165                 ERROR("Cannot select image %d: There are only %u images",
166                       image, wim->hdr.image_count);
167                 return WIMLIB_ERR_INVALID_IMAGE;
168         }
169
170         if (wim->hdr.part_number != 1) {
171                 ERROR("Cannot select an image from a non-first part of a split WIM");
172                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
173         }
174
175         /* If a valid image is currently selected, it can be freed if it is not
176          * modified.  */
177         if (wim->current_image != WIMLIB_NO_IMAGE) {
178                 imd = wim_get_current_image_metadata(wim);
179                 if (!imd->modified) {
180                         wimlib_assert(list_empty(&imd->unhashed_streams));
181                         DEBUG("Freeing image %u", wim->current_image);
182                         destroy_image_metadata(imd, NULL, false);
183                 }
184         }
185         wim->current_image = image;
186         imd = wim_get_current_image_metadata(wim);
187         if (imd->root_dentry || imd->modified) {
188                 ret = 0;
189         } else {
190                 #ifdef ENABLE_DEBUG
191                 DEBUG("Reading metadata resource specified by the following "
192                       "lookup table entry:");
193                 print_lookup_table_entry(imd->metadata_lte, stderr);
194                 #endif
195                 ret = read_metadata_resource(wim, imd);
196                 if (ret)
197                         wim->current_image = WIMLIB_NO_IMAGE;
198         }
199         return ret;
200 }
201
202
203 /* API function documented in wimlib.h  */
204 WIMLIBAPI const tchar *
205 wimlib_get_compression_type_string(int ctype)
206 {
207         switch (ctype) {
208                 case WIMLIB_COMPRESSION_TYPE_NONE:
209                         return T("None");
210                 case WIMLIB_COMPRESSION_TYPE_LZX:
211                         return T("LZX");
212                 case WIMLIB_COMPRESSION_TYPE_XPRESS:
213                         return T("XPRESS");
214                 default:
215                         return T("Invalid");
216         }
217 }
218
219 /* API function documented in wimlib.h  */
220 WIMLIBAPI int
221 wimlib_resolve_image(WIMStruct *wim, const tchar *image_name_or_num)
222 {
223         tchar *p;
224         long image;
225         int i;
226
227         if (!image_name_or_num || !*image_name_or_num)
228                 return WIMLIB_NO_IMAGE;
229
230         if (!tstrcasecmp(image_name_or_num, T("all"))
231             || !tstrcasecmp(image_name_or_num, T("*")))
232                 return WIMLIB_ALL_IMAGES;
233         image = tstrtol(image_name_or_num, &p, 10);
234         if (p != image_name_or_num && *p == T('\0') && image > 0) {
235                 if (image > wim->hdr.image_count)
236                         return WIMLIB_NO_IMAGE;
237                 return image;
238         } else {
239                 for (i = 1; i <= wim->hdr.image_count; i++) {
240                         if (!tstrcmp(image_name_or_num,
241                                      wimlib_get_image_name(wim, i)))
242                                 return i;
243                 }
244                 return WIMLIB_NO_IMAGE;
245         }
246 }
247
248 /* API function documented in wimlib.h  */
249 WIMLIBAPI void
250 wimlib_print_available_images(const WIMStruct *wim, int image)
251 {
252         int first;
253         int last;
254         int i;
255         int n;
256         if (image == WIMLIB_ALL_IMAGES) {
257                 n = tprintf(T("Available Images:\n"));
258                 first = 1;
259                 last = wim->hdr.image_count;
260         } else if (image >= 1 && image <= wim->hdr.image_count) {
261                 n = tprintf(T("Information for Image %d\n"), image);
262                 first = image;
263                 last = image;
264         } else {
265                 tprintf(T("wimlib_print_available_images(): Invalid image %d"),
266                         image);
267                 return;
268         }
269         for (i = 0; i < n - 1; i++)
270                 tputchar(T('-'));
271         tputchar(T('\n'));
272         for (i = first; i <= last; i++)
273                 print_image_info(wim->wim_info, i);
274 }
275
276
277 /* API function documented in wimlib.h  */
278 WIMLIBAPI int
279 wimlib_print_metadata(WIMStruct *wim, int image)
280 {
281         if (wim->hdr.part_number != 1) {
282                 ERROR("Cannot show the metadata from part %hu of a %hu-part split WIM!",
283                        wim->hdr.part_number, wim->hdr.total_parts);
284                 ERROR("Select the first part of the split WIM to see the metadata.");
285                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
286         }
287         return for_image(wim, image, image_print_metadata);
288 }
289
290 /* API function documented in wimlib.h  */
291 WIMLIBAPI int
292 wimlib_get_wim_info(WIMStruct *wim, struct wimlib_wim_info *info)
293 {
294         memset(info, 0, sizeof(struct wimlib_wim_info));
295         memcpy(info->guid, wim->hdr.guid, WIMLIB_GUID_LEN);
296         info->image_count = wim->hdr.image_count;
297         info->boot_index = wim->hdr.boot_idx;
298         info->wim_version = WIM_VERSION;
299         info->chunk_size = WIM_CHUNK_SIZE;
300         info->part_number = wim->hdr.part_number;
301         info->total_parts = wim->hdr.total_parts;
302         info->compression_type = wim->compression_type;
303         info->total_bytes = wim_info_get_total_bytes(wim->wim_info);
304         info->has_integrity_table = wim_has_integrity_table(wim);
305         info->opened_from_file = (wim->filename != NULL);
306         info->is_readonly = (wim->hdr.flags & WIM_HDR_FLAG_READONLY) ||
307                              (wim->hdr.total_parts != 1) ||
308                              (wim->filename && taccess(wim->filename, W_OK));
309         info->has_rpfix = (wim->hdr.flags & WIM_HDR_FLAG_RP_FIX) != 0;
310         info->is_marked_readonly = (wim->hdr.flags & WIM_HDR_FLAG_READONLY) != 0;
311         info->write_in_progress = (wim->hdr.flags & WIM_HDR_FLAG_WRITE_IN_PROGRESS) != 0;
312         info->metadata_only = (wim->hdr.flags & WIM_HDR_FLAG_METADATA_ONLY) != 0;
313         info->resource_only = (wim->hdr.flags & WIM_HDR_FLAG_RESOURCE_ONLY) != 0;
314         info->spanned = (wim->hdr.flags & WIM_HDR_FLAG_SPANNED) != 0;
315         info->pipable = wim_is_pipable(wim);
316         return 0;
317 }
318
319 /* API function documented in wimlib.h  */
320 WIMLIBAPI int
321 wimlib_set_wim_info(WIMStruct *wim, const struct wimlib_wim_info *info, int which)
322 {
323         int ret;
324
325         if (which & WIMLIB_CHANGE_READONLY_FLAG) {
326                 if (info->is_marked_readonly)
327                         wim->hdr.flags |= WIM_HDR_FLAG_READONLY;
328                 else
329                         wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
330         }
331
332         if ((which & ~WIMLIB_CHANGE_READONLY_FLAG) == 0)
333                 return 0;
334
335         ret = can_modify_wim(wim);
336         if (ret)
337                 return ret;
338
339         if (which & WIMLIB_CHANGE_GUID)
340                 memcpy(wim->hdr.guid, info->guid, WIM_GID_LEN);
341
342         if (which & WIMLIB_CHANGE_BOOT_INDEX) {
343                 if (info->boot_index > wim->hdr.image_count) {
344                         ERROR("%u is not 0 or a valid image in the WIM to mark as bootable",
345                               info->boot_index);
346                         return WIMLIB_ERR_INVALID_IMAGE;
347                 }
348                 wim->hdr.boot_idx = info->boot_index;
349         }
350
351         if (which & WIMLIB_CHANGE_RPFIX_FLAG) {
352                 if (info->has_rpfix)
353                         wim->hdr.flags |= WIM_HDR_FLAG_RP_FIX;
354                 else
355                         wim->hdr.flags &= ~WIM_HDR_FLAG_RP_FIX;
356         }
357         return 0;
358 }
359
360 static int
361 do_open_wim(const tchar *filename, struct filedes *fd_ret)
362 {
363         int raw_fd;
364
365         raw_fd = topen(filename, O_RDONLY | O_BINARY);
366         if (raw_fd < 0) {
367                 ERROR_WITH_ERRNO("Can't open \"%"TS"\" read-only", filename);
368                 return WIMLIB_ERR_OPEN;
369         }
370         filedes_init(fd_ret, raw_fd);
371         return 0;
372 }
373
374 int
375 reopen_wim(WIMStruct *wim)
376 {
377         wimlib_assert(!filedes_valid(&wim->in_fd));
378         return do_open_wim(wim->filename, &wim->in_fd);
379 }
380
381 int
382 close_wim(WIMStruct *wim)
383 {
384         if (filedes_valid(&wim->in_fd)) {
385                 filedes_close(&wim->in_fd);
386                 filedes_invalidate(&wim->in_fd);
387         }
388         return 0;
389 }
390
391 /*
392  * Begins the reading of a WIM file; opens the file and reads its header and
393  * lookup table, and optionally checks the integrity.
394  */
395 static int
396 begin_read(WIMStruct *wim, const void *wim_filename_or_fd,
397            int open_flags, wimlib_progress_func_t progress_func)
398 {
399         int ret;
400         int xml_num_images;
401         const tchar *wimfile;
402
403         if (open_flags & WIMLIB_OPEN_FLAG_FROM_PIPE) {
404                 wimfile = NULL;
405                 filedes_init(&wim->in_fd, *(const int*)wim_filename_or_fd);
406                 wim->in_fd.is_pipe = 1;
407         } else {
408                 wimfile = wim_filename_or_fd;
409                 DEBUG("Reading the WIM file `%"TS"'", wimfile);
410                 ret = do_open_wim(wimfile, &wim->in_fd);
411                 if (ret)
412                         return ret;
413
414                 /* The absolute path to the WIM is requested so that
415                  * wimlib_overwrite() still works even if the process changes
416                  * its working directory.  This actually happens if a WIM is
417                  * mounted read-write, since the FUSE thread changes directory
418                  * to "/", and it needs to be able to find the WIM file again.
419                  *
420                  * This will break if the full path to the WIM changes in the
421                  * intervening time...
422                  *
423                  * Warning: in Windows native builds, realpath() calls the
424                  * replacement function in win32.c.
425                  */
426                 wim->filename = realpath(wimfile, NULL);
427                 if (!wim->filename) {
428                         ERROR_WITH_ERRNO("Failed to resolve WIM filename");
429                         if (errno == ENOMEM)
430                                 return WIMLIB_ERR_NOMEM;
431                         else
432                                 return WIMLIB_ERR_OPEN;
433                 }
434         }
435
436         ret = read_wim_header(wim->filename, &wim->in_fd, &wim->hdr);
437         if (ret)
438                 return ret;
439
440         if (wim->hdr.flags & WIM_HDR_FLAG_WRITE_IN_PROGRESS) {
441                 WARNING("The WIM_HDR_FLAG_WRITE_IN_PROGRESS is set in the header of \"%"TS"\".\n"
442                         "          It may be being changed by another process, or a process\n"
443                         "          may have crashed while writing the WIM.", wimfile);
444         }
445
446         if (open_flags & WIMLIB_OPEN_FLAG_WRITE_ACCESS) {
447                 ret = can_modify_wim(wim);
448                 if (ret)
449                         return ret;
450         }
451
452         if (wim->hdr.total_parts != 1 && !(open_flags & WIMLIB_OPEN_FLAG_SPLIT_OK)) {
453                 ERROR("\"%"TS"\": This WIM is part %u of a %u-part WIM",
454                       wimfile, wim->hdr.part_number, wim->hdr.total_parts);
455                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
456         }
457
458         DEBUG("According to header, WIM contains %u images", wim->hdr.image_count);
459
460         /* If the boot index is invalid, print a warning and set it to 0 */
461         if (wim->hdr.boot_idx > wim->hdr.image_count) {
462                 WARNING("In `%"TS"', image %u is marked as bootable, "
463                         "but there are only %u images in the WIM",
464                         wimfile, wim->hdr.boot_idx, wim->hdr.image_count);
465                 wim->hdr.boot_idx = 0;
466         }
467
468         /* Check and cache the compression type */
469         if (wim->hdr.flags & WIM_HDR_FLAG_COMPRESSION) {
470                 if (wim->hdr.flags & WIM_HDR_FLAG_COMPRESS_LZX) {
471                         if (wim->hdr.flags & WIM_HDR_FLAG_COMPRESS_XPRESS) {
472                                 ERROR("Multiple compression flags are set in \"%"TS"\"",
473                                       wimfile);
474                                 return WIMLIB_ERR_INVALID_COMPRESSION_TYPE;
475                         }
476                         wim->compression_type = WIMLIB_COMPRESSION_TYPE_LZX;
477                 } else if (wim->hdr.flags & WIM_HDR_FLAG_COMPRESS_XPRESS) {
478                         wim->compression_type = WIMLIB_COMPRESSION_TYPE_XPRESS;
479                 } else {
480                         ERROR("The compression flag is set on \"%"TS"\", but "
481                               "neither the XPRESS nor LZX flag is set",
482                               wimfile);
483                         return WIMLIB_ERR_INVALID_COMPRESSION_TYPE;
484                 }
485         } else {
486                 wim->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
487         }
488
489         if (open_flags & WIMLIB_OPEN_FLAG_CHECK_INTEGRITY) {
490                 ret = check_wim_integrity(wim, progress_func);
491                 if (ret == WIM_INTEGRITY_NONEXISTENT) {
492                         WARNING("No integrity information for `%"TS"'; skipping "
493                                 "integrity check.", wimfile);
494                 } else if (ret == WIM_INTEGRITY_NOT_OK) {
495                         ERROR("WIM is not intact! (Failed integrity check)");
496                         return WIMLIB_ERR_INTEGRITY;
497                 } else if (ret != WIM_INTEGRITY_OK) {
498                         return ret;
499                 }
500         }
501
502         if (wim->hdr.image_count != 0 && wim->hdr.part_number == 1) {
503                 wim->image_metadata = new_image_metadata_array(wim->hdr.image_count);
504                 if (!wim->image_metadata)
505                         return WIMLIB_ERR_NOMEM;
506         }
507
508         if (open_flags & WIMLIB_OPEN_FLAG_FROM_PIPE) {
509                 wim->lookup_table = new_lookup_table(9001);
510                 if (!wim->lookup_table)
511                         return WIMLIB_ERR_NOMEM;
512         } else {
513                 ret = read_wim_lookup_table(wim);
514                 if (ret)
515                         return ret;
516
517                 ret = read_wim_xml_data(wim);
518                 if (ret)
519                         return ret;
520
521                 xml_num_images = wim_info_get_num_images(wim->wim_info);
522                 if (xml_num_images != wim->hdr.image_count) {
523                         ERROR("In the file `%"TS"', there are %u <IMAGE> elements "
524                               "in the XML data,", wimfile, xml_num_images);
525                         ERROR("but %u images in the WIM!  There must be exactly one "
526                               "<IMAGE> element per image.", wim->hdr.image_count);
527                         return WIMLIB_ERR_IMAGE_COUNT;
528                 }
529                 DEBUG("Done beginning read of WIM file `%"TS"'.", wimfile);
530         }
531         return 0;
532 }
533
534 int
535 open_wim_as_WIMStruct(const void *wim_filename_or_fd, int open_flags,
536                       WIMStruct **wim_ret, wimlib_progress_func_t progress_func)
537 {
538         WIMStruct *wim;
539         int ret;
540
541         wimlib_global_init(WIMLIB_INIT_FLAG_ASSUME_UTF8);
542
543         ret = WIMLIB_ERR_INVALID_PARAM;
544         if (!wim_ret)
545                 goto out;
546
547         ret = WIMLIB_ERR_NOMEM;
548         wim = new_wim_struct();
549         if (!wim)
550                 goto out;
551
552         ret = begin_read(wim, wim_filename_or_fd, open_flags, progress_func);
553         if (ret)
554                 goto out_wimlib_free;
555
556         ret = 0;
557         *wim_ret = wim;
558         goto out;
559 out_wimlib_free:
560         wimlib_free(wim);
561 out:
562         return ret;
563 }
564
565 /* API function documented in wimlib.h  */
566 WIMLIBAPI int
567 wimlib_open_wim(const tchar *wimfile, int open_flags,
568                 WIMStruct **wim_ret, wimlib_progress_func_t progress_func)
569 {
570         open_flags &= WIMLIB_OPEN_MASK_PUBLIC;
571         return open_wim_as_WIMStruct(wimfile, open_flags, wim_ret,
572                                      progress_func);
573 }
574
575 void
576 destroy_image_metadata(struct wim_image_metadata *imd,
577                        struct wim_lookup_table *table,
578                        bool free_metadata_lte)
579 {
580         free_dentry_tree(imd->root_dentry, table);
581         imd->root_dentry = NULL;
582         free_wim_security_data(imd->security_data);
583         imd->security_data = NULL;
584
585         if (free_metadata_lte) {
586                 free_lookup_table_entry(imd->metadata_lte);
587                 imd->metadata_lte = NULL;
588         }
589         if (!table) {
590                 struct wim_lookup_table_entry *lte, *tmp;
591                 list_for_each_entry_safe(lte, tmp, &imd->unhashed_streams, unhashed_list)
592                         free_lookup_table_entry(lte);
593         }
594         INIT_LIST_HEAD(&imd->unhashed_streams);
595         INIT_LIST_HEAD(&imd->inode_list);
596 #ifdef WITH_NTFS_3G
597         if (imd->ntfs_vol) {
598                 do_ntfs_umount(imd->ntfs_vol);
599                 imd->ntfs_vol = NULL;
600         }
601 #endif
602 }
603
604 void
605 put_image_metadata(struct wim_image_metadata *imd,
606                    struct wim_lookup_table *table)
607 {
608         if (imd && --imd->refcnt == 0) {
609                 destroy_image_metadata(imd, table, true);
610                 FREE(imd);
611         }
612 }
613
614 /* Appends the specified image metadata structure to the array of image metadata
615  * for a WIM, and increments the image count. */
616 int
617 append_image_metadata(WIMStruct *wim, struct wim_image_metadata *imd)
618 {
619         struct wim_image_metadata **imd_array;
620
621         DEBUG("Reallocating image metadata array for image_count = %u",
622               wim->hdr.image_count + 1);
623         imd_array = REALLOC(wim->image_metadata,
624                             sizeof(wim->image_metadata[0]) * (wim->hdr.image_count + 1));
625
626         if (!imd_array)
627                 return WIMLIB_ERR_NOMEM;
628         wim->image_metadata = imd_array;
629         imd_array[wim->hdr.image_count++] = imd;
630         return 0;
631 }
632
633
634 struct wim_image_metadata *
635 new_image_metadata(void)
636 {
637         struct wim_image_metadata *imd;
638
639         imd = CALLOC(1, sizeof(*imd));
640         if (imd) {
641                 imd->refcnt = 1;
642                 INIT_LIST_HEAD(&imd->inode_list);
643                 INIT_LIST_HEAD(&imd->unhashed_streams);
644                 DEBUG("Created new image metadata (refcnt=1)");
645         } else {
646                 ERROR_WITH_ERRNO("Failed to allocate new image metadata structure");
647         }
648         return imd;
649 }
650
651 struct wim_image_metadata **
652 new_image_metadata_array(unsigned num_images)
653 {
654         struct wim_image_metadata **imd_array;
655
656         DEBUG("Creating new image metadata array for %u images",
657               num_images);
658
659         imd_array = CALLOC(num_images, sizeof(imd_array[0]));
660
661         if (!imd_array) {
662                 ERROR("Failed to allocate memory for %u image metadata structures",
663                       num_images);
664                 return NULL;
665         }
666         for (unsigned i = 0; i < num_images; i++) {
667                 imd_array[i] = new_image_metadata();
668                 if (!imd_array[i]) {
669                         for (unsigned j = 0; j < i; j++)
670                                 put_image_metadata(imd_array[j], NULL);
671                         FREE(imd_array);
672                         return NULL;
673                 }
674         }
675         return imd_array;
676 }
677
678 /* Checksum all streams that are unhashed (other than the metadata streams),
679  * merging them into the lookup table as needed.  This is a no-op unless the
680  * library has previously used to add or mount an image using the same
681  * WIMStruct. */
682 int
683 wim_checksum_unhashed_streams(WIMStruct *wim)
684 {
685         int ret;
686         for (int i = 0; i < wim->hdr.image_count; i++) {
687                 struct wim_lookup_table_entry *lte, *tmp;
688                 struct wim_image_metadata *imd = wim->image_metadata[i];
689                 image_for_each_unhashed_stream_safe(lte, tmp, imd) {
690                         ret = hash_unhashed_stream(lte, wim->lookup_table, NULL);
691                         if (ret)
692                                 return ret;
693                 }
694         }
695         return 0;
696 }
697
698 /*
699  * can_modify_wim - Check if a given WIM is writeable.  This is only the case if
700  * it meets the following three conditions:
701  *
702  * 1. Write access is allowed to the underlying file (if any) at the filesystem level.
703  * 2. The WIM is not part of a spanned set.
704  * 3. The WIM_HDR_FLAG_READONLY flag is not set in the WIM header.
705  *
706  * Return value is 0 if writable; WIMLIB_ERR_WIM_IS_READONLY otherwise.
707  */
708 int
709 can_modify_wim(WIMStruct *wim)
710 {
711         if (wim->filename) {
712                 if (taccess(wim->filename, W_OK)) {
713                         ERROR_WITH_ERRNO("Can't modify \"%"TS"\"", wim->filename);
714                         return WIMLIB_ERR_WIM_IS_READONLY;
715                 }
716         }
717         if (wim->hdr.total_parts != 1) {
718                 ERROR("Cannot modify \"%"TS"\": is part of a spanned set",
719                       wim->filename);
720                 return WIMLIB_ERR_WIM_IS_READONLY;
721         }
722         if (wim->hdr.flags & WIM_HDR_FLAG_READONLY) {
723                 ERROR("Cannot modify \"%"TS"\": is marked read-only",
724                       wim->filename);
725                 return WIMLIB_ERR_WIM_IS_READONLY;
726         }
727         return 0;
728 }
729
730 /*
731  * can_delete_from_wim - Check if files or images can be deleted from a given
732  * WIM file.
733  *
734  * This theoretically should be exactly the same as can_modify_wim(), but
735  * unfortunately, due to bugs in Microsoft's software that generate incorrect
736  * reference counts for some WIM resources, we need to run expensive
737  * verifications to make sure the reference counts are correct on all WIM
738  * resources.  Otherwise we might delete a WIM resource whose reference count
739  * has fallen to 0, but is actually still referenced somewhere.
740  */
741 int
742 can_delete_from_wim(WIMStruct *wim)
743 {
744         int ret;
745
746         ret = can_modify_wim(wim);
747         if (ret)
748                 return ret;
749         if (!wim->refcnts_ok)
750                 wim_recalculate_refcnts(wim);
751         return 0;
752 }
753
754 /* API function documented in wimlib.h  */
755 WIMLIBAPI void
756 wimlib_free(WIMStruct *wim)
757 {
758         DEBUG("Freeing WIMStruct");
759
760         if (!wim)
761                 return;
762         if (filedes_valid(&wim->in_fd))
763                 filedes_close(&wim->in_fd);
764         if (filedes_valid(&wim->out_fd))
765                 filedes_close(&wim->out_fd);
766
767         free_lookup_table(wim->lookup_table);
768
769         FREE(wim->filename);
770         free_wim_info(wim->wim_info);
771         if (wim->image_metadata) {
772                 for (unsigned i = 0; i < wim->hdr.image_count; i++)
773                         put_image_metadata(wim->image_metadata[i], NULL);
774                 FREE(wim->image_metadata);
775         }
776         FREE(wim);
777         DEBUG("Freed WIMStruct");
778 }
779
780 static bool
781 test_locale_ctype_utf8(void)
782 {
783 #ifdef __WIN32__
784         return false;
785 #else
786         char *ctype = nl_langinfo(CODESET);
787
788         return (!strstr(ctype, "UTF-8") ||
789                 !strstr(ctype, "UTF8") ||
790                 !strstr(ctype, "utf8") ||
791                 !strstr(ctype, "utf-8"));
792 #endif
793 }
794
795 /* API function documented in wimlib.h  */
796 WIMLIBAPI int
797 wimlib_global_init(int init_flags)
798 {
799         static bool already_inited = false;
800
801         if (already_inited)
802                 return 0;
803         libxml_global_init();
804         if (!(init_flags & WIMLIB_INIT_FLAG_ASSUME_UTF8)) {
805                 wimlib_mbs_is_utf8 = test_locale_ctype_utf8();
806         #ifdef WITH_NTFS_3G
807                 if (!wimlib_mbs_is_utf8)
808                         libntfs3g_global_init();
809         #endif
810         }
811 #ifdef __WIN32__
812         win32_global_init(init_flags);
813 #endif
814         already_inited = true;
815         return 0;
816 }
817
818 /* API function documented in wimlib.h  */
819 WIMLIBAPI void
820 wimlib_global_cleanup(void)
821 {
822         libxml_global_cleanup();
823         iconv_global_cleanup();
824 #ifdef __WIN32__
825         win32_global_cleanup();
826 #endif
827 }