]> wimlib.net Git - wimlib/blob - src/modify.c
6b1239da3c2b738f17e62b0456bca69db7ba0b97
[wimlib] / src / modify.c
1 /*
2  * modify.c
3  *
4  * Support for modifying WIM files with image-level operations (delete an image,
5  * add an image, export an imagex from one WIM to another.)  There is nothing
6  * here that lets you change individual files in the WIM; for that you will need
7  * to look at the filesystem implementation in mount.c.
8  */
9
10 /*
11  * Copyright (C) 2012 Eric Biggers
12  *
13  * This file is part of wimlib, a library for working with WIM files.
14  *
15  * wimlib is free software; you can redistribute it and/or modify it under the
16  * terms of the GNU Lesser General Public License as published by the Free
17  * Software Foundation; either version 2.1 of the License, or (at your option)
18  * any later version.
19  *
20  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
21  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
22  * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
23  * details.
24  *
25  * You should have received a copy of the GNU Lesser General Public License
26  * along with wimlib; if not, see http://www.gnu.org/licenses/.
27  */
28
29 #include "wimlib_internal.h"
30 #include "util.h"
31 #include "sha1.h"
32 #include "dentry.h"
33 #include "xml.h"
34 #include "lookup_table.h"
35 #include <sys/stat.h>
36 #include <dirent.h>
37 #include <string.h>
38 #include <errno.h>
39 #include <unistd.h>
40
41 /** Private flag: Used to mark that we currently adding the root directory of
42  * the WIM. */
43 #define WIMLIB_ADD_IMAGE_FLAG_ROOT 0x80000000
44
45 static void destroy_image_metadata(struct image_metadata *imd,
46                                    struct lookup_table *lt)
47 {
48         free_dentry_tree(imd->root_dentry, lt, true);
49         free_security_data(imd->security_data);
50
51         /* Get rid of the lookup table entry for this image's metadata resource
52          * */
53         lookup_table_remove(lt, imd->metadata_lte);
54 }
55
56 /* 
57  * Recursively builds a dentry tree from a directory tree on disk, outside the
58  * WIM file.
59  *
60  * @root:  A dentry that has already been created for the root of the dentry
61  *         tree.
62  * @source_path:  The path to the root of the tree on disk. 
63  * @root_stat:   A pointer to a `struct stat' that contains the metadata for the
64  *                      root of the tree on disk. 
65  * @lookup_table: The lookup table for the WIM file.  For each file added to the
66  *              dentry tree being built, an entry is added to the lookup table, 
67  *              unless an identical file is already in the lookup table.  These
68  *              lookup table entries that are added point to the file on disk.
69  *
70  * @return:     0 on success, nonzero on failure.  It is a failure if any of
71  *              the files cannot be `stat'ed, or if any of the needed
72  *              directories cannot be opened or read.  Failure to add the files
73  *              to the WIM may still occur later when trying to actually read 
74  *              the regular files in the tree into the WIM as file resources.
75  */
76 static int build_dentry_tree(struct dentry *root, const char *root_disk_path,
77                              struct lookup_table* lookup_table,
78                              int add_flags)
79 {
80         DEBUG("`%s'", root_disk_path);
81         struct stat root_stbuf;
82         int ret;
83         int (*stat_fn)(const char *restrict, struct stat *restrict);
84
85         if (add_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE)
86                 stat_fn = stat;
87         else
88                 stat_fn = lstat;
89
90
91         ret = (*stat_fn)(root_disk_path, &root_stbuf);
92         if (ret != 0) {
93                 ERROR_WITH_ERRNO("Failed to stat `%s'", root_disk_path);
94                 return WIMLIB_ERR_STAT;
95         }
96
97         if ((add_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) && 
98               !S_ISDIR(root_stbuf.st_mode)) {
99                 ERROR("`%s' is not a directory", root_disk_path);
100                 return WIMLIB_ERR_NOTDIR;
101         }
102         stbuf_to_dentry(&root_stbuf, root);
103         add_flags &= ~WIMLIB_ADD_IMAGE_FLAG_ROOT;
104
105         if (dentry_is_directory(root)) {
106                 /* Open the directory on disk */
107                 DIR *dir;
108                 struct dirent *p;
109                 struct dentry *child;
110
111                 dir = opendir(root_disk_path);
112                 if (!dir) {
113                         ERROR_WITH_ERRNO("Failed to open the directory `%s'",
114                                          root_disk_path);
115                         return WIMLIB_ERR_OPEN;
116                 }
117
118                 /* Buffer for names of files in directory. */
119                 size_t len = strlen(root_disk_path);
120                 char name[len + 1 + FILENAME_MAX + 1];
121                 memcpy(name, root_disk_path, len);
122                 name[len] = '/';
123
124                 /* Create a dentry for each entry in the directory on disk, and recurse
125                  * to any subdirectories. */
126                 while ((p = readdir(dir)) != NULL) {
127                         if (p->d_name[0] == '.' && (p->d_name[1] == '\0'
128                               || (p->d_name[1] == '.' && p->d_name[2] == '\0')))
129                                         continue;
130                         strcpy(name + len + 1, p->d_name);
131                         child = new_dentry(p->d_name);
132                         if (!child) {
133                                 ERROR("No memory to allocate new dentry");
134                                 return WIMLIB_ERR_NOMEM;
135                         }
136                         ret = build_dentry_tree(child, name, lookup_table,
137                                                 add_flags);
138                         link_dentry(child, root);
139                         if (ret != 0)
140                                 break;
141                 }
142                 closedir(dir);
143         } else if (dentry_is_symlink(root)) {
144                 /* Archiving a symbolic link */
145                 size_t symlink_buf_len;
146                 char deref_name_buf[4096];
147                 ssize_t ret = readlink(root_disk_path, deref_name_buf,
148                                        sizeof(deref_name_buf) - 1);
149                 if (ret == -1) {
150                         ERROR_WITH_ERRNO("Failed to read target of "
151                                          "symbolic link `%s'", root_disk_path);
152                         return WIMLIB_ERR_STAT;
153                 }
154                 deref_name_buf[ret] = '\0';
155                 DEBUG("Read symlink `%s'", deref_name_buf);
156                 void *symlink_buf = make_symlink_reparse_data_buf(deref_name_buf,
157                                                                   &symlink_buf_len);
158                 if (!symlink_buf)
159                         return WIMLIB_ERR_NOMEM;
160                 DEBUG("Made symlink reparse data buf (len = %zu, name len = %zu)",
161                                 symlink_buf_len, ret);
162                 
163                 u8 symlink_buf_hash[WIM_HASH_SIZE];
164                 sha1_buffer(symlink_buf, symlink_buf_len, symlink_buf_hash);
165
166                 ret = dentry_set_symlink_buf(root, symlink_buf_hash);
167
168                 if (ret != 0) {
169                         FREE(symlink_buf);
170                         return ret;
171                 }
172                 DEBUG("Created symlink buf");
173
174                 struct lookup_table_entry *lte;
175                 struct lookup_table_entry *existing_lte;
176
177                 existing_lte = lookup_resource(lookup_table, symlink_buf_hash);
178                 if (existing_lte) {
179                         existing_lte->refcnt++;
180                 } else {
181                         DEBUG("Creating new lookup table entry");
182                         lte = new_lookup_table_entry();
183                         if (!lte) {
184                                 FREE(symlink_buf);
185                                 return WIMLIB_ERR_NOMEM;
186                         }
187                         lte->symlink_buf = symlink_buf;
188                         lte->resource_entry.original_size = symlink_buf_len;
189                         lte->resource_entry.size = symlink_buf_len;
190                         lte->is_symlink = true;
191                         memcpy(lte->hash, symlink_buf_hash, WIM_HASH_SIZE);
192                         lookup_table_insert(lookup_table, lte);
193                 }
194         } else {
195                 struct lookup_table_entry *lte;
196
197                 /* For each non-directory, we must check to see if the file is
198                  * in the lookup table already; if it is, we increment its
199                  * refcnt; otherwise, we create a new lookup table entry and
200                  * insert it. */
201                 ret = sha1sum(root_disk_path, root->hash);
202                 if (ret != 0)
203                         return ret;
204
205                 lte = lookup_resource(lookup_table, root->hash);
206                 if (lte) {
207                         lte->refcnt++;
208                 } else {
209                         char *file_on_disk = STRDUP(root_disk_path);
210                         if (!file_on_disk) {
211                                 ERROR("Failed to allocate memory for file path");
212                                 return WIMLIB_ERR_NOMEM;
213                         }
214                         lte = new_lookup_table_entry();
215                         if (!lte) {
216                                 FREE(file_on_disk);
217                                 return WIMLIB_ERR_NOMEM;
218                         }
219                         lte->file_on_disk = file_on_disk;
220                         lte->resource_entry.original_size = root_stbuf.st_size;
221                         lte->resource_entry.size = root_stbuf.st_size;
222                         memcpy(lte->hash, root->hash, WIM_HASH_SIZE);
223                         lookup_table_insert(lookup_table, lte);
224                 }
225         }
226         return ret;
227 }
228
229 struct wim_pair {
230         WIMStruct *src_wim;
231         WIMStruct *dest_wim;
232 };
233
234 /* 
235  * This function takes in a dentry that was previously located only in image(s)
236  * in @src_wim, but now is being added to @dest_wim. If there is in fact already a
237  * lookup table entry for this file in the lookup table of the destination WIM
238  * file, we simply increment its reference count.  Otherwise, a new lookup table
239  * entry is created that references the location of the file resource in the
240  * source WIM file through the other_wim_fp field of the lookup table entry.
241  */
242 static int add_lookup_table_entry_to_dest_wim(struct dentry *dentry, void *arg)
243 {
244         WIMStruct *src_wim, *dest_wim;
245         struct lookup_table_entry *src_table_entry;
246         struct lookup_table_entry *dest_table_entry;
247
248         src_wim = ((struct wim_pair*)arg)->src_wim;
249         dest_wim = ((struct wim_pair*)arg)->dest_wim;
250
251         if (dentry_is_directory(dentry))
252                 return 0;
253
254         src_table_entry = wim_lookup_resource(src_wim, dentry);
255         if (!src_table_entry)
256                 return 0;
257
258         dest_table_entry = wim_lookup_resource(dest_wim, dentry);
259         if (dest_table_entry) {
260                 dest_table_entry->refcnt++;
261         } else {
262                 dest_table_entry = new_lookup_table_entry();
263                 if (!dest_table_entry)
264                         return WIMLIB_ERR_NOMEM;
265                 dest_table_entry->other_wim_fp = src_wim->fp;
266                 dest_table_entry->other_wim_ctype = 
267                                 wimlib_get_compression_type(src_wim);
268                 dest_table_entry->refcnt = 1;
269                 memcpy(&dest_table_entry->resource_entry, 
270                        &src_table_entry->resource_entry, 
271                        sizeof(struct resource_entry));
272                 memcpy(dest_table_entry->hash, dentry->hash, WIM_HASH_SIZE);
273                 lookup_table_insert(dest_wim->lookup_table, dest_table_entry);
274         }
275         return 0;
276 }
277
278 /*
279  * Adds an image (given by its dentry tree) to the image metadata array of a WIM
280  * file, adds an entry to the lookup table for the image metadata, updates the
281  * image count in the header, and selects the new image. 
282  *
283  * Does not update the XML data.
284  *
285  * @w:            The WIMStruct for the WIM file.
286  * @root_dentry:  The root of the directory tree for the image.
287  */
288 static int add_new_dentry_tree(WIMStruct *w, struct dentry *root_dentry)
289 {
290         struct lookup_table_entry *metadata_lte;
291         struct image_metadata *imd;
292         struct image_metadata *new_imd;
293         struct wim_security_data *sd;
294
295         DEBUG("Reallocating image metadata array for image_count = %u",
296               w->hdr.image_count + 1);
297         imd = CALLOC((w->hdr.image_count + 1), sizeof(struct image_metadata));
298
299         if (!imd) {
300                 ERROR("Failed to allocate memory for new image metadata array");
301                 return WIMLIB_ERR_NOMEM;
302         }
303
304         memcpy(imd, w->image_metadata, 
305                w->hdr.image_count * sizeof(struct image_metadata));
306         
307         metadata_lte = new_lookup_table_entry();
308         if (!metadata_lte)
309                 goto out_free_imd;
310         sd = CALLOC(1, sizeof(struct wim_security_data));
311         if (!sd)
312                 goto out_free_metadata_lte;
313         sd->refcnt = 1;
314         sd->total_length = 8;
315
316         metadata_lte->resource_entry.flags = WIM_RESHDR_FLAG_METADATA;
317         randomize_byte_array(metadata_lte->hash, WIM_HASH_SIZE);
318         lookup_table_insert(w->lookup_table, metadata_lte);
319
320         w->hdr.image_count++;
321
322         new_imd                 = &imd[w->hdr.image_count - 1];
323         new_imd->metadata_lte   = metadata_lte;
324         new_imd->modified       = true;
325         new_imd->root_dentry    = root_dentry;
326         new_imd->security_data  = sd;
327         FREE(w->image_metadata);
328         w->image_metadata       = imd;
329
330         /* Change the current image to the new one. */
331         return wimlib_select_image(w, w->hdr.image_count);
332 out_free_metadata_lte:
333         FREE(metadata_lte);
334 out_free_imd:
335         FREE(imd);
336         return WIMLIB_ERR_NOMEM;
337
338 }
339
340 /*
341  * Copies an image, or all the images, from a WIM file, into another WIM file.
342  */
343 WIMLIBAPI int wimlib_export_image(WIMStruct *src_wim, 
344                                   int src_image, 
345                                   WIMStruct *dest_wim, 
346                                   const char *dest_name, 
347                                   const char *dest_description, 
348                                   int flags)
349 {
350         int i;
351         int ret;
352         struct dentry *root;
353         struct wim_pair wims;
354
355         if (src_image == WIM_ALL_IMAGES) {
356                 if (src_wim->hdr.image_count > 1) {
357
358                         /* multi-image export. */
359
360                         if ((flags & WIMLIB_EXPORT_FLAG_BOOT) && 
361                               (src_wim->hdr.boot_idx == 0))
362                         {
363                                 /* Specifying the boot flag on a multi-image
364                                  * source WIM makes the boot index default to
365                                  * the bootable image in the source WIM.  It is
366                                  * an error if there is no such bootable image.
367                                  * */
368                                 ERROR("Cannot specify `boot' flag when "
369                                       "exporting multiple images from a WIM "
370                                       "with no bootable images");
371                                 return WIMLIB_ERR_INVALID_PARAM;
372                         }
373                         if (dest_name || dest_description) {
374                                 ERROR("Image name or image description was "
375                                       "specified, but we are exporting "
376                                       "multiple images");
377                                 return WIMLIB_ERR_INVALID_PARAM;
378                         }
379                         for (i = 1; i <= src_wim->hdr.image_count; i++) {
380                                 int export_flags = flags;
381
382                                 if (i != src_wim->hdr.boot_idx)
383                                         export_flags &= ~WIMLIB_EXPORT_FLAG_BOOT;
384
385                                 ret = wimlib_export_image(src_wim, i, dest_wim, 
386                                                           NULL,
387                                                           dest_description,
388                                                           export_flags);
389                                 if (ret != 0)
390                                         return ret;
391                         }
392                         return 0;
393                 } else {
394                         src_image = 1; 
395                 }
396         }
397
398         ret = wimlib_select_image(src_wim, src_image);
399         if (ret != 0) {
400                 ERROR("Could not select image %d from the WIM `%s' "
401                       "to export it", src_image, src_wim->filename);
402                 return ret;
403         }
404
405         if (!dest_name) {
406                 dest_name = wimlib_get_image_name(src_wim, src_image);
407                 DEBUG("Using name `%s' for source image %d",
408                       dest_name, src_image);
409         }
410
411         DEBUG("Exporting image %d from `%s'", src_image, src_wim->filename);
412
413         if (wimlib_image_name_in_use(dest_wim, dest_name)) {
414                 ERROR("There is already an image named `%s' in the "
415                       "destination WIM", dest_name);
416                 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
417         }
418
419
420         /* Cleaning up here on failure would be hard.  For example, we could
421          * fail to allocate memory in add_lookup_table_entry_to_dest_wim(),
422          * leaving the lookup table entries in the destination WIM in an
423          * inconsistent state.  Until these issues can be resolved,
424          * wimlib_export_image() is documented as leaving dest_wim is an
425          * indeterminate state.  */
426         root = wim_root_dentry(src_wim);
427         for_dentry_in_tree(root, increment_dentry_refcnt, NULL);
428         wims.src_wim = src_wim;
429         wims.dest_wim = dest_wim;
430         ret = for_dentry_in_tree(root, add_lookup_table_entry_to_dest_wim, &wims);
431         if (ret != 0)
432                 return ret;
433         ret = add_new_dentry_tree(dest_wim, root);
434         if (ret != 0)
435                 return ret;
436         /* Bring over old security data */
437         struct wim_security_data *sd = wim_security_data(src_wim);
438         struct image_metadata *new_imd = wim_get_current_image_metadata(dest_wim);
439         wimlib_assert(sd);
440         free_security_data(new_imd->security_data);
441         new_imd->security_data = sd;
442         sd->refcnt++;
443
444         if (flags & WIMLIB_EXPORT_FLAG_BOOT) {
445                 DEBUG("Setting boot_idx to %d", dest_wim->hdr.image_count);
446                 dest_wim->hdr.boot_idx = dest_wim->hdr.image_count;
447         }
448
449         return xml_export_image(src_wim->wim_info, src_image, &dest_wim->wim_info,
450                                 dest_name, dest_description);
451 }
452
453 /* 
454  * Deletes an image from the WIM. 
455  */
456 WIMLIBAPI int wimlib_delete_image(WIMStruct *w, int image)
457 {
458         int num_images;
459         int i;
460         int ret;
461
462         if (image == WIM_ALL_IMAGES) {
463                 num_images = w->hdr.image_count;
464                 for (i = 1; i <= num_images; i++) {
465                         /* Always delete the first image, since by the end
466                          * there won't be any more than that!  */
467                         ret = wimlib_delete_image(w, 1);
468                         if (ret != 0)
469                                 return ret;
470                 }
471                 return 0;
472         }
473
474         DEBUG("Deleting image %d", image);
475
476         /* Even if the dentry tree is not allocated, we must select it (and
477          * therefore allocate it) so that we can decrement the reference counts
478          * in the lookup table.  */
479         ret = wimlib_select_image(w, image);
480         if (ret != 0)
481                 return ret;
482
483         /* Free the dentry tree, any lookup table entries that have their
484          * refcnt decremented to 0, and the security data. */
485         destroy_image_metadata(wim_get_current_image_metadata(w),
486                                w->lookup_table);
487
488         /* Get rid of the empty slot in the image metadata array. */
489         memmove(&w->image_metadata[image - 1], &w->image_metadata[image],
490                 (w->hdr.image_count - image) * sizeof(struct image_metadata));
491
492         /* Decrement the image count. */
493         if (--w->hdr.image_count == 0) {
494                 FREE(w->image_metadata);
495                 w->image_metadata = NULL;
496         }
497
498         /* Fix the boot index. */
499         if (w->hdr.boot_idx == image)
500                 w->hdr.boot_idx = 0;
501         else if (w->hdr.boot_idx > image)
502                 w->hdr.boot_idx--;
503
504         w->current_image = WIM_NO_IMAGE;
505
506         /* Remove the image from the XML information. */
507         xml_delete_image(&w->wim_info, image);
508         return 0;
509 }
510
511 /*
512  * Adds an image to a WIM file from a directory tree on disk.
513  */
514 WIMLIBAPI int wimlib_add_image(WIMStruct *w, const char *dir, 
515                                const char *name, const char *description, 
516                                const char *flags_element, int flags)
517 {
518         struct dentry *root_dentry;
519         struct stat root_stat;
520         struct image_metadata *imd;
521         int ret;
522
523         DEBUG("Adding dentry tree from dir `%s'.", dir);
524
525         if (!name || !*name) {
526                 ERROR("Must specify a non-empty string for the image name");
527                 return WIMLIB_ERR_INVALID_PARAM;
528         }
529         if (!dir) {
530                 ERROR("Must specify the name of a directory");
531                 return WIMLIB_ERR_INVALID_PARAM;
532         }
533
534         if (wimlib_image_name_in_use(w, name)) {
535                 ERROR("There is already an image named \"%s\" in `%s'",
536                       name, w->filename);
537                 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
538         }
539
540         DEBUG("Creating root dentry.");
541
542         root_dentry = new_dentry("");
543         if (!root_dentry)
544                 return WIMLIB_ERR_NOMEM;
545         ret = calculate_dentry_full_path(root_dentry, NULL);
546
547         if (ret != 0)
548                 goto out_free_dentry_tree;
549
550         root_dentry->attributes |= FILE_ATTRIBUTE_DIRECTORY;
551
552         DEBUG("Building dentry tree.");
553         ret = build_dentry_tree(root_dentry, dir, w->lookup_table,
554                                 flags | WIMLIB_ADD_IMAGE_FLAG_ROOT);
555
556         if (ret != 0) {
557                 ERROR("Failed to build dentry tree for `%s'", dir);
558                 goto out_free_dentry_tree;
559         }
560
561         DEBUG("Recalculating full paths of dentries.");
562         ret = for_dentry_in_tree(root_dentry, calculate_dentry_full_path, NULL);
563         if (ret != 0)
564                 goto out_free_dentry_tree;
565
566         ret = add_new_dentry_tree(w, root_dentry);
567         if (ret != 0)
568                 goto out_free_dentry_tree;
569
570         if (flags & WIMLIB_ADD_IMAGE_FLAG_BOOT)
571                 wimlib_set_boot_idx(w, w->hdr.image_count);
572
573         ret = xml_add_image(w, root_dentry, name, description, flags_element);
574         if (ret != 0)
575                 goto out_destroy_imd;
576
577         return 0;
578 out_destroy_imd:
579         destroy_image_metadata(&w->image_metadata[w->hdr.image_count - 1],
580                                w->lookup_table);
581         return ret;
582 out_free_dentry_tree:
583         free_dentry_tree(root_dentry, w->lookup_table, true);
584         return ret;
585 }