wimlib_apply_image_to_ntfs_volume() API function
[wimlib] / src / extract.c
1 /*
2  * extract.c
3  *
4  * Support for extracting WIM files.
5  */
6
7 /*
8  * Copyright (C) 2010 Carl Thijssen
9  * Copyright (C) 2012 Eric Biggers
10  *
11  * This file is part of wimlib, a library for working with WIM files.
12  *
13  * wimlib is free software; you can redistribute it and/or modify it under the
14  * terms of the GNU Lesser General Public License as published by the Free
15  * Software Foundation; either version 2.1 of the License, or (at your option)
16  * any later version.
17  *
18  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20  * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
21  * details.
22  *
23  * You should have received a copy of the GNU Lesser General Public License
24  * along with wimlib; if not, see http://www.gnu.org/licenses/.
25  */
26
27
28 #include <dirent.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <string.h>
32 #include <sys/stat.h>
33 #include <sys/time.h>
34 #include <unistd.h>
35
36 #include "config.h"
37 #include "dentry.h"
38 #include "lookup_table.h"
39 #include "timestamp.h"
40 #include "wimlib_internal.h"
41 #include "xml.h"
42
43 #ifdef WITH_NTFS_3G
44 #include <ntfs-3g/volume.h>
45 #include <ntfs-3g/security.h>
46 #endif
47
48
49 /* Internal */
50 #define WIMLIB_EXTRACT_FLAG_MULTI_IMAGE 0x80000000
51
52 static int extract_regular_file_linked(const struct dentry *dentry, 
53                                        const char *output_dir,
54                                        const char *output_path,
55                                        int extract_flags,
56                                        struct lookup_table_entry *lte)
57 {
58         /* This mode overrides the normal hard-link extraction and
59          * instead either symlinks or hardlinks *all* identical files in
60          * the WIM, even if they are in a different image (in the case
61          * of a multi-image extraction) */
62
63         wimlib_assert(lte->file_on_disk);
64
65
66         if (extract_flags & WIMLIB_EXTRACT_FLAG_HARDLINK) {
67                 if (link(lte->file_on_disk, output_path) != 0) {
68                         ERROR_WITH_ERRNO("Failed to hard link "
69                                          "`%s' to `%s'",
70                                          output_path, lte->file_on_disk);
71                         return WIMLIB_ERR_LINK;
72                 }
73         } else {
74                 int num_path_components;
75                 int num_output_dir_path_components;
76                 size_t file_on_disk_len;
77                 char *p;
78                 const char *p2;
79                 size_t i;
80
81                 wimlib_assert(extract_flags & WIMLIB_EXTRACT_FLAG_SYMLINK);
82
83                 num_path_components = 
84                         get_num_path_components(dentry->full_path_utf8) - 1;
85                 num_output_dir_path_components =
86                         get_num_path_components(output_dir);
87
88                 if (extract_flags & WIMLIB_EXTRACT_FLAG_MULTI_IMAGE) {
89                         num_path_components++;
90                         num_output_dir_path_components--;
91                 }
92                 file_on_disk_len = strlen(lte->file_on_disk);
93
94                 char buf[file_on_disk_len + 3 * num_path_components + 1];
95                 p = &buf[0];
96
97                 for (i = 0; i < num_path_components; i++) {
98                         *p++ = '.';
99                         *p++ = '.';
100                         *p++ = '/';
101                 }
102                 p2 = lte->file_on_disk;
103                 while (*p2 == '/')
104                         p2++;
105                 while (num_output_dir_path_components--)
106                         p2 = path_next_part(p2, NULL);
107                 strcpy(p, p2);
108                 if (symlink(buf, output_path) != 0) {
109                         ERROR_WITH_ERRNO("Failed to symlink `%s' to "
110                                          "`%s'",
111                                          buf, lte->file_on_disk);
112                         return WIMLIB_ERR_LINK;
113                 }
114
115         }
116         return 0;
117 }
118
119 static int extract_regular_file_unlinked(WIMStruct *w,
120                                          struct dentry *dentry, 
121                                          const char *output_path,
122                                          int extract_flags,
123                                          struct lookup_table_entry *lte)
124 {
125         /* Normal mode of extraction.  Regular files and hard links are
126          * extracted in the way that they appear in the WIM. */
127
128         int out_fd;
129         const struct resource_entry *res_entry;
130         int ret;
131         const struct list_head *head = &dentry->link_group_list;
132
133         if (head->next != head) {
134                 /* This dentry is one of a hard link set of at least 2 dentries.
135                  * If one of the other dentries has already been extracted, make
136                  * a hard link to the file corresponding to this
137                  * already-extracted directory.  Otherwise, extract the
138                  * file, and set the dentry->extracted_file field so that other
139                  * dentries in the hard link group can link to it. */
140                 struct dentry *other;
141                 list_for_each_entry(other, head, link_group_list) {
142                         if (other->extracted_file) {
143                                 DEBUG("Extracting hard link `%s' => `%s'",
144                                       output_path, other->extracted_file);
145                                 if (link(other->extracted_file, output_path) != 0) {
146                                         ERROR_WITH_ERRNO("Failed to hard link "
147                                                          "`%s' to `%s'",
148                                                          output_path,
149                                                          other->extracted_file);
150                                         return WIMLIB_ERR_LINK;
151                                 }
152                                 return 0;
153                         }
154                 }
155                 FREE(dentry->extracted_file);
156                 dentry->extracted_file = STRDUP(output_path);
157                 if (!dentry->extracted_file) {
158                         ERROR("Failed to allocate memory for filename");
159                         return WIMLIB_ERR_NOMEM;
160                 }
161         }
162
163         /* Extract the contents of the file to @output_path. */
164
165         out_fd = open(output_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
166         if (out_fd == -1) {
167                 ERROR_WITH_ERRNO("Failed to open the file `%s' for writing",
168                                  output_path);
169                 return WIMLIB_ERR_OPEN;
170         }
171
172         if (!lte) {
173                 /* Empty file with no lookup table entry */
174                 DEBUG("Empty file `%s'.", output_path);
175                 ret = 0;
176                 goto done;
177         }
178
179
180         res_entry = &lte->resource_entry;
181
182         ret = extract_resource_to_fd(w, res_entry, out_fd, 
183                                      res_entry->original_size);
184
185         if (ret != 0) {
186                 ERROR("Failed to extract resource to `%s'", output_path);
187                 goto done;
188         }
189
190         if (extract_flags & WIMLIB_EXTRACT_FLAG_MULTI_IMAGE) {
191                 /* Mark the lookup table entry to indicate this file has been
192                  * extracted. */
193                 lte->out_refcnt++;
194                 FREE(lte->file_on_disk);
195                 lte->file_on_disk = STRDUP(output_path);
196                 if (!lte->file_on_disk)
197                         ret = WIMLIB_ERR_NOMEM;
198         }
199 done:
200         if (close(out_fd) != 0) {
201                 ERROR_WITH_ERRNO("Failed to close file `%s'", output_path);
202                 ret = WIMLIB_ERR_WRITE;
203         }
204         return ret;
205 }
206
207 /* 
208  * Extracts a regular file from the WIM archive. 
209  */
210 static int extract_regular_file(WIMStruct *w, 
211                                 struct dentry *dentry, 
212                                 const char *output_dir,
213                                 const char *output_path,
214                                 int extract_flags)
215 {
216         struct lookup_table_entry *lte;
217
218         lte = dentry_first_lte(dentry, w->lookup_table);
219
220         if ((extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
221                               WIMLIB_EXTRACT_FLAG_HARDLINK)) && lte) {
222                 if (lte->out_refcnt++ != 0)
223                         return extract_regular_file_linked(dentry, output_dir,
224                                                            output_path,
225                                                            extract_flags, lte);
226                 lte->file_on_disk = STRDUP(output_path);
227                 if (!lte->file_on_disk)
228                         return WIMLIB_ERR_NOMEM;
229         }
230
231         return extract_regular_file_unlinked(w, dentry, output_path,
232                                              extract_flags, lte);
233
234 }
235
236 static int extract_symlink(const struct dentry *dentry, const char *output_path,
237                            const WIMStruct *w)
238 {
239         char target[4096];
240         ssize_t ret = dentry_readlink(dentry, target, sizeof(target), w);
241         if (ret <= 0) {
242                 ERROR("Could not read the symbolic link from dentry `%s'",
243                       dentry->full_path_utf8);
244                 return WIMLIB_ERR_INVALID_DENTRY;
245         }
246         ret = symlink(target, output_path);
247         if (ret != 0) {
248                 ERROR_WITH_ERRNO("Failed to symlink `%s' to `%s'",
249                                  output_path, target);
250                 return WIMLIB_ERR_LINK;
251         }
252         return 0;
253 }
254
255 /* 
256  * Extracts a directory from the WIM archive. 
257  *
258  * @dentry:             The directory entry for the directory.
259  * @output_path:        The path to which the directory is to be extracted to.
260  * @return:             True on success, false on failure. 
261  */
262 static int extract_directory(const char *output_path, bool is_root)
263 {
264         int ret;
265         struct stat stbuf;
266         ret = stat(output_path, &stbuf);
267         if (ret == 0) {
268                 if (S_ISDIR(stbuf.st_mode)) {
269                         if (!is_root)
270                                 WARNING("`%s' already exists", output_path);
271                         return 0;
272                 } else {
273                         ERROR("`%s' is not a directory", output_path);
274                         return WIMLIB_ERR_MKDIR;
275                 }
276         } else {
277                 if (errno != ENOENT) {
278                         ERROR_WITH_ERRNO("Failed to stat `%s'", output_path);
279                         return WIMLIB_ERR_STAT;
280                 }
281         }
282         /* Compute the output path directory to the directory. */
283         if (mkdir(output_path, S_IRWXU | S_IRGRP | S_IXGRP |
284                                S_IROTH | S_IXOTH) != 0) {
285                 ERROR_WITH_ERRNO("Cannot create directory `%s'",
286                                  output_path);
287                 return WIMLIB_ERR_MKDIR;
288         }
289         return 0;
290 }
291
292 struct extract_args {
293         WIMStruct *w;
294         int extract_flags;
295         const char *output_dir;
296 #ifdef WITH_NTFS_3G
297         struct SECURITY_API *scapi;
298 #endif
299 };
300
301 /* 
302  * Extracts a file, directory, or symbolic link from the WIM archive.  For use
303  * in for_dentry_in_tree().
304  */
305 static int extract_dentry(struct dentry *dentry, void *arg)
306 {
307         struct extract_args *args = arg;
308         WIMStruct *w = args->w;
309         int extract_flags = args->extract_flags;
310         size_t len = strlen(args->output_dir);
311         char output_path[len + dentry->full_path_utf8_len + 1];
312         int ret;
313
314         if (extract_flags & WIMLIB_EXTRACT_FLAG_VERBOSE) {
315                 wimlib_assert(dentry->full_path_utf8);
316                 puts(dentry->full_path_utf8);
317         }
318
319         memcpy(output_path, args->output_dir, len);
320         memcpy(output_path + len, dentry->full_path_utf8, dentry->full_path_utf8_len);
321         output_path[len + dentry->full_path_utf8_len] = '\0';
322
323         if (dentry_is_symlink(dentry))
324                 ret = extract_symlink(dentry, output_path, w);
325         else if (dentry_is_directory(dentry))
326                 ret = extract_directory(output_path, dentry_is_root(dentry));
327         else
328                 ret = extract_regular_file(w, dentry, args->output_dir,
329                                             output_path, extract_flags);
330         if (ret != 0)
331                 return ret;
332
333         return 0;
334 }
335
336 static int apply_dentry_timestamps(struct dentry *dentry, void *arg)
337 {
338         struct extract_args *args = arg;
339         size_t len = strlen(args->output_dir);
340         char output_path[len + dentry->full_path_utf8_len + 1];
341
342         memcpy(output_path, args->output_dir, len);
343         memcpy(output_path + len, dentry->full_path_utf8, dentry->full_path_utf8_len);
344         output_path[len + dentry->full_path_utf8_len] = '\0';
345
346         struct timeval tv[2];
347         wim_timestamp_to_timeval(dentry->last_access_time, &tv[0]);
348         wim_timestamp_to_timeval(dentry->last_write_time, &tv[1]);
349         if (lutimes(output_path, tv) != 0) {
350                 WARNING("Failed to set timestamp on file `%s': %s",
351                         output_path, strerror(errno));
352         }
353         return 0;
354 }
355
356
357 static int extract_single_image(WIMStruct *w, int image,
358                                 const char *output_dir, int extract_flags)
359 {
360         DEBUG("Extracting image %d", image);
361
362         int ret;
363         ret = wimlib_select_image(w, image);
364         if (ret != 0)
365                 return ret;
366
367         struct extract_args args = {
368                 .w = w,
369                 .extract_flags = extract_flags,
370                 .output_dir = output_dir,
371         #ifdef WITH_NTFS_3G
372                 .scapi = NULL
373         #endif
374         };
375
376         ret = for_dentry_in_tree(wim_root_dentry(w), extract_dentry, &args);
377         if (ret != 0)
378                 return ret;
379         return for_dentry_in_tree_depth(wim_root_dentry(w),
380                                         apply_dentry_timestamps, &args);
381
382 }
383
384
385 /* Extracts all images from the WIM to @output_dir, with the images placed in
386  * subdirectories named by their image names. */
387 static int extract_all_images(WIMStruct *w, const char *output_dir,
388                               int extract_flags)
389 {
390         size_t image_name_max_len = max(xml_get_max_image_name_len(w), 20);
391         size_t output_path_len = strlen(output_dir);
392         char buf[output_path_len + 1 + image_name_max_len + 1];
393         int ret;
394         int image;
395         const char *image_name;
396
397         DEBUG("Attempting to extract all images from `%s'", w->filename);
398
399         ret = extract_directory(output_dir, true);
400         if (ret != 0)
401                 return ret;
402
403         memcpy(buf, output_dir, output_path_len);
404         buf[output_path_len] = '/';
405         for (image = 1; image <= w->hdr.image_count; image++) {
406                 
407                 image_name = wimlib_get_image_name(w, image);
408                 if (*image_name) {
409                         strcpy(buf + output_path_len + 1, image_name);
410                 } else {
411                         /* Image name is empty. Use image number instead */
412                         sprintf(buf + output_path_len + 1, "%d", image);
413                 }
414                 ret = extract_single_image(w, image, buf, extract_flags);
415                 if (ret != 0)
416                         goto done;
417         }
418 done:
419         /* Restore original output directory */
420         buf[output_path_len + 1] = '\0';
421         return 0;
422 }
423
424 /* Extracts a single image or all images from a WIM file. */
425 WIMLIBAPI int wimlib_extract_image(WIMStruct *w, int image,
426                                    const char *output_dir, int flags)
427 {
428         if (!output_dir)
429                 return WIMLIB_ERR_INVALID_PARAM;
430
431         if ((flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
432                         == (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK))
433                 return WIMLIB_ERR_INVALID_PARAM;
434
435         for_lookup_table_entry(w->lookup_table, zero_out_refcnts, NULL);
436
437         if (image == WIM_ALL_IMAGES) {
438                 flags |= WIMLIB_EXTRACT_FLAG_MULTI_IMAGE;
439                 return extract_all_images(w, output_dir, flags);
440         } else {
441                 flags &= ~WIMLIB_EXTRACT_FLAG_MULTI_IMAGE;
442                 return extract_single_image(w, image, output_dir, flags);
443         }
444
445 }
446
447 WIMLIBAPI int wimlib_apply_image_to_ntfs_volume(WIMStruct *w, int image,
448                                                 const char *device, int flags)
449 {
450 #ifdef WITH_NTFS_3G
451         int ret;
452
453         if (!device)
454                 return WIMLIB_ERR_INVALID_PARAM;
455         if (image == WIM_ALL_IMAGES) {
456                 ERROR("Can only apply a single image when applying "
457                       "directly to a NTFS volume");
458                 return WIMLIB_ERR_INVALID_PARAM;
459         }
460         if (flags & (WIMLIB_EXTRACT_FLAG_SYMLINK | WIMLIB_EXTRACT_FLAG_HARDLINK)) {
461                 ERROR("Cannot specifcy symlink or hardlink flags when applying ");
462                 ERROR("directly to a NTFS volume");
463                 return WIMLIB_ERR_INVALID_PARAM;
464         }
465         ret = wimlib_select_image(w, image);
466         if (ret != 0)
467                 return ret;
468
469         if (getuid() != 0) {
470                 ERROR("We are not root, but NTFS-3g requires root privileges to set arbitrary");
471                 ERROR("security data on the NTFS filesystem.  Please run this program as root");
472                 ERROR("if you want to extract a WIM image while preserving NTFS-specific");
473                 ERROR("information.");
474
475                 return WIMLIB_ERR_NOT_ROOT;
476         }
477 #else /* WITH_NTFS_3G */
478         ERROR("wimlib was compiled without support for NTFS-3g, so");
479         ERROR("we cannot apply a WIM image directly to a NTFS volume");
480         return WIMLIB_ERR_UNSUPPORTED;
481 #endif /* !WITH_NTFS_3G */
482 }