Minor cleanups
[wimlib] / src / unix_apply.c
1 /*
2  * unix_apply.c - Code to apply files from a WIM image on UNIX.
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 #include "config.h"
25
26 #ifdef HAVE_UTIME_H
27 #  include <utime.h>
28 #endif
29 #include <dirent.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <string.h>
33 #include <sys/stat.h>
34 #include <sys/time.h>
35 #include <unistd.h>
36
37 #include "timestamp.h"
38 #include "wimlib_internal.h"
39 #include "lookup_table.h"
40
41 /* Returns the number of components of @path.  */
42 static unsigned
43 get_num_path_components(const char *path)
44 {
45         unsigned num_components = 0;
46         while (*path) {
47                 while (*path == '/')
48                         path++;
49                 if (*path)
50                         num_components++;
51                 while (*path && *path != '/')
52                         path++;
53         }
54         return num_components;
55 }
56
57 static const char *
58 path_next_part(const char *path)
59 {
60         while (*path && *path != '/')
61                 path++;
62         while (*path && *path == '/')
63                 path++;
64         return path;
65 }
66
67 static int
68 unix_extract_regular_file_linked(struct wim_dentry *dentry,
69                                  const char *output_path,
70                                  struct apply_args *args,
71                                  struct wim_lookup_table_entry *lte)
72 {
73         /* This mode overrides the normal hard-link extraction and
74          * instead either symlinks or hardlinks *all* identical files in
75          * the WIM, even if they are in a different image (in the case
76          * of a multi-image extraction) */
77
78         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_HARDLINK) {
79                 if (link(lte->extracted_file, output_path) != 0) {
80                         ERROR_WITH_ERRNO("Failed to hard link "
81                                          "`%s' to `%s'",
82                                          output_path, lte->extracted_file);
83                         return WIMLIB_ERR_LINK;
84                 }
85         } else {
86                 int num_path_components;
87                 int num_output_dir_path_components;
88                 size_t extracted_file_len;
89                 char *p;
90                 const char *p2;
91                 size_t i;
92
93                 num_path_components = get_num_path_components(dentry->_full_path) - 1;
94                 num_output_dir_path_components = get_num_path_components(args->target);
95
96                 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_MULTI_IMAGE) {
97                         num_path_components++;
98                         num_output_dir_path_components--;
99                 }
100                 extracted_file_len = strlen(lte->extracted_file);
101
102                 char buf[extracted_file_len + 3 * num_path_components + 1];
103                 p = &buf[0];
104
105                 for (i = 0; i < num_path_components; i++) {
106                         *p++ = '.';
107                         *p++ = '.';
108                         *p++ = '/';
109                 }
110                 p2 = lte->extracted_file;
111                 while (*p2 == '/')
112                         p2++;
113                 while (num_output_dir_path_components > 0) {
114                         p2 = path_next_part(p2);
115                         num_output_dir_path_components--;
116                 }
117                 strcpy(p, p2);
118                 if (symlink(buf, output_path) != 0) {
119                         ERROR_WITH_ERRNO("Failed to symlink `%s' to `%s'",
120                                          buf, lte->extracted_file);
121                         return WIMLIB_ERR_LINK;
122                 }
123         }
124         return 0;
125 }
126
127 static int
128 symlink_apply_unix_data(const char *link,
129                         const struct wimlib_unix_data *unix_data)
130 {
131         if (lchown(link, unix_data->uid, unix_data->gid)) {
132                 if (errno == EPERM) {
133                         /* Ignore */
134                         WARNING_WITH_ERRNO("failed to set symlink UNIX "
135                                            "owner/group on \"%s\"", link);
136                 } else {
137                         ERROR_WITH_ERRNO("failed to set symlink UNIX "
138                                          "owner/group on \"%s\"", link);
139                         return WIMLIB_ERR_INVALID_DENTRY;
140                 }
141         }
142         return 0;
143 }
144
145 static int
146 fd_apply_unix_data(int fd, const char *path,
147                    const struct wimlib_unix_data *unix_data,
148                    int extract_flags)
149 {
150         if (extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS)
151                 return 0;
152
153         if (fchown(fd, unix_data->uid, unix_data->gid)) {
154                 if (errno == EPERM &&
155                     !(extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
156                 {
157                         WARNING_WITH_ERRNO("failed to set file UNIX "
158                                            "owner/group on \"%s\"", path);
159                 } else {
160                         ERROR_WITH_ERRNO("failed to set file UNIX "
161                                          "owner/group on \"%s\"", path);
162                         return (errno == EPERM) ? WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT :
163                                 WIMLIB_ERR_WRITE;
164                 }
165         }
166
167         if (fchmod(fd, unix_data->mode)) {
168                 if (errno == EPERM &&
169                     !(extract_flags & WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
170                 {
171                         WARNING_WITH_ERRNO("failed to set UNIX file mode "
172                                            "on \"%s\"", path);
173                 } else {
174                         ERROR_WITH_ERRNO("failed to set UNIX file mode "
175                                          "on \"%s\"", path);
176                         return (errno == EPERM) ? WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT :
177                                 WIMLIB_ERR_WRITE;
178                 }
179         }
180         return 0;
181 }
182
183 static int
184 dir_apply_unix_data(const char *dir, const struct wimlib_unix_data *unix_data,
185                     int extract_flags)
186 {
187         int dfd = open(dir, O_RDONLY);
188         int ret;
189         if (dfd >= 0) {
190                 ret = fd_apply_unix_data(dfd, dir, unix_data, extract_flags);
191                 if (close(dfd) && ret == 0) {
192                         ERROR_WITH_ERRNO("can't close directory `%s'", dir);
193                         ret = WIMLIB_ERR_WRITE;
194                 }
195         } else {
196                 ERROR_WITH_ERRNO("can't open directory `%s'", dir);
197                 ret = WIMLIB_ERR_OPENDIR;
198         }
199         return ret;
200 }
201
202 static int
203 unix_extract_regular_file_unlinked(struct wim_dentry *dentry,
204                                    struct apply_args *args,
205                                    const char *output_path,
206                                    struct wim_lookup_table_entry *lte)
207 {
208         /* Normal mode of extraction.  Regular files and hard links are
209          * extracted in the way that they appear in the WIM. */
210
211         int out_fd;
212         int ret;
213         struct wim_inode *inode = dentry->d_inode;
214
215         if (!((args->extract_flags & WIMLIB_EXTRACT_FLAG_MULTI_IMAGE)
216                 && (args->extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
217                                      WIMLIB_EXTRACT_FLAG_HARDLINK))))
218         {
219                 /* If the dentry is part of a hard link set of at least 2
220                  * dentries and one of the other dentries has already been
221                  * extracted, make a hard link to the file corresponding to this
222                  * already-extracted directory.  Otherwise, extract the file and
223                  * set the inode->i_extracted_file field so that other dentries
224                  * in the hard link group can link to it. */
225                 if (inode->i_nlink > 1) {
226                         if (inode->i_extracted_file) {
227                                 DEBUG("Extracting hard link `%s' => `%s'",
228                                       output_path, inode->i_extracted_file);
229                                 if (link(inode->i_extracted_file, output_path) != 0) {
230                                         ERROR_WITH_ERRNO("Failed to hard link "
231                                                          "`%s' to `%s'",
232                                                          output_path,
233                                                          inode->i_extracted_file);
234                                         return WIMLIB_ERR_LINK;
235                                 }
236                                 return 0;
237                         }
238                         FREE(inode->i_extracted_file);
239                         inode->i_extracted_file = STRDUP(output_path);
240                         if (!inode->i_extracted_file) {
241                                 ERROR("Failed to allocate memory for filename");
242                                 return WIMLIB_ERR_NOMEM;
243                         }
244                 }
245         }
246
247         /* Extract the contents of the file to @output_path. */
248
249         out_fd = open(output_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
250         if (out_fd == -1) {
251                 ERROR_WITH_ERRNO("Failed to open the file `%s' for writing",
252                                  output_path);
253                 return WIMLIB_ERR_OPEN;
254         }
255
256         if (!lte) {
257                 /* Empty file with no lookup table entry */
258                 DEBUG("Empty file `%s'.", output_path);
259                 ret = 0;
260                 goto out_extract_unix_data;
261         }
262
263         ret = extract_wim_resource_to_fd(lte, out_fd, wim_resource_size(lte));
264         if (ret) {
265                 ERROR("Failed to extract resource to `%s'", output_path);
266                 goto out;
267         }
268
269 out_extract_unix_data:
270         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
271                 struct wimlib_unix_data unix_data;
272                 ret = inode_get_unix_data(inode, &unix_data, NULL);
273                 if (ret > 0)
274                         ;
275                 else if (ret < 0)
276                         ret = 0;
277                 else
278                         ret = fd_apply_unix_data(out_fd, output_path, &unix_data,
279                                                  args->extract_flags);
280                 if (ret)
281                         goto out;
282         }
283         if (lte)
284                 args->progress.extract.completed_bytes += wim_resource_size(lte);
285 out:
286         if (close(out_fd) != 0) {
287                 ERROR_WITH_ERRNO("Failed to close file `%s'", output_path);
288                 if (ret == 0)
289                         ret = WIMLIB_ERR_WRITE;
290         }
291         return ret;
292 }
293
294 static int
295 unix_extract_regular_file(struct wim_dentry *dentry,
296                           struct apply_args *args,
297                           const char *output_path)
298 {
299         struct wim_lookup_table_entry *lte;
300         const struct wim_inode *inode = dentry->d_inode;
301
302         lte = inode_unnamed_lte_resolved(inode);
303
304         if (lte && (args->extract_flags & (WIMLIB_EXTRACT_FLAG_SYMLINK |
305                                            WIMLIB_EXTRACT_FLAG_HARDLINK)))
306         {
307                 if (lte->extracted_file) {
308                         return unix_extract_regular_file_linked(dentry,
309                                                                 output_path,
310                                                                 args, lte);
311                 } else {
312                         lte->extracted_file = STRDUP(output_path);
313                         if (!lte->extracted_file)
314                                 return WIMLIB_ERR_NOMEM;
315                 }
316         }
317         return unix_extract_regular_file_unlinked(dentry, args, output_path, lte);
318 }
319
320 static int
321 unix_extract_symlink(struct wim_dentry *dentry,
322                      struct apply_args *args,
323                      const char *output_path)
324 {
325         char target[4096 + args->target_realpath_len];
326         char *fixed_target;
327         const struct wim_inode *inode = dentry->d_inode;
328
329         ssize_t ret = wim_inode_readlink(inode,
330                                          target + args->target_realpath_len,
331                                          sizeof(target) - args->target_realpath_len - 1);
332         struct wim_lookup_table_entry *lte;
333
334         if (ret <= 0) {
335                 ERROR("Could not read the symbolic link from dentry `%s'",
336                       dentry->_full_path);
337                 return WIMLIB_ERR_INVALID_DENTRY;
338         }
339         target[args->target_realpath_len + ret] = '\0';
340         if (target[args->target_realpath_len] == '/' &&
341             args->extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX)
342         {
343                 /* Fix absolute symbolic link target to point into the actual
344                  * extraction destination */
345                 memcpy(target, args->target_realpath,
346                        args->target_realpath_len);
347                 fixed_target = target;
348         } else {
349                 /* Keep same link target */
350                 fixed_target = target + args->target_realpath_len;
351         }
352         ret = symlink(fixed_target, output_path);
353         if (ret) {
354                 ERROR_WITH_ERRNO("Failed to symlink `%s' to `%s'",
355                                  output_path, fixed_target);
356                 return WIMLIB_ERR_LINK;
357         }
358         if (args->extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
359                 struct wimlib_unix_data unix_data;
360                 ret = inode_get_unix_data(inode, &unix_data, NULL);
361                 if (ret > 0)
362                         ;
363                 else if (ret < 0)
364                         ret = 0;
365                 else
366                         ret = symlink_apply_unix_data(output_path, &unix_data);
367                 if (ret)
368                         return ret;
369         }
370         lte = inode_unnamed_lte_resolved(inode);
371         wimlib_assert(lte != NULL);
372         args->progress.extract.completed_bytes += wim_resource_size(lte);
373         return 0;
374 }
375
376 static int
377 unix_extract_directory(struct wim_dentry *dentry, const tchar *output_path,
378                        int extract_flags)
379 {
380         int ret;
381         struct stat stbuf;
382
383         ret = tstat(output_path, &stbuf);
384         if (ret == 0) {
385                 if (S_ISDIR(stbuf.st_mode)) {
386                         goto dir_exists;
387                 } else {
388                         ERROR("`%"TS"' is not a directory", output_path);
389                         return WIMLIB_ERR_MKDIR;
390                 }
391         } else {
392                 if (errno != ENOENT) {
393                         ERROR_WITH_ERRNO("Failed to stat `%"TS"'", output_path);
394                         return WIMLIB_ERR_STAT;
395                 }
396         }
397
398         if (tmkdir(output_path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH))
399         {
400                 ERROR_WITH_ERRNO("Cannot create directory `%"TS"'", output_path);
401                 return WIMLIB_ERR_MKDIR;
402         }
403 dir_exists:
404         ret = 0;
405 #ifndef __WIN32__
406         if (extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
407                 struct wimlib_unix_data unix_data;
408                 ret = inode_get_unix_data(dentry->d_inode, &unix_data, NULL);
409                 if (ret > 0)
410                         ;
411                 else if (ret < 0)
412                         ret = 0;
413                 else
414                         ret = dir_apply_unix_data(output_path, &unix_data,
415                                                   extract_flags);
416         }
417 #endif
418         return ret;
419 }
420
421 int
422 unix_do_apply_dentry(const char *output_path, size_t output_path_len,
423                      struct wim_dentry *dentry, struct apply_args *args)
424 {
425         const struct wim_inode *inode = dentry->d_inode;
426
427         if (inode_is_symlink(inode))
428                 return unix_extract_symlink(dentry, args, output_path);
429         else if (inode_is_directory(inode))
430                 return unix_extract_directory(dentry, output_path, args->extract_flags);
431         else
432                 return unix_extract_regular_file(dentry, args, output_path);
433 }
434
435 int
436 unix_do_apply_dentry_timestamps(const char *output_path,
437                                 size_t output_path_len,
438                                 struct wim_dentry *dentry,
439                                 struct apply_args *args)
440 {
441         int ret;
442         const struct wim_inode *inode = dentry->d_inode;
443
444 #ifdef HAVE_UTIMENSAT
445         /* Convert the WIM timestamps, which are accurate to 100 nanoseconds,
446          * into `struct timespec's for passing to utimensat(), which is accurate
447          * to 1 nanosecond. */
448
449         struct timespec ts[2];
450         ts[0] = wim_timestamp_to_timespec(inode->i_last_access_time);
451         ts[1] = wim_timestamp_to_timespec(inode->i_last_write_time);
452         ret = utimensat(AT_FDCWD, output_path, ts, AT_SYMLINK_NOFOLLOW);
453         if (ret)
454                 ret = errno;
455 #else
456         ret = ENOSYS;
457 #endif
458
459         if (ret == ENOSYS) {
460                 /* utimensat() not implemented or not available */
461         #ifdef HAVE_LUTIMES
462                 /* Convert the WIM timestamps, which are accurate to 100
463                  * nanoseconds, into `struct timeval's for passing to lutimes(),
464                  * which is accurate to 1 microsecond. */
465                 struct timeval tv[2];
466                 tv[0] = wim_timestamp_to_timeval(inode->i_last_access_time);
467                 tv[1] = wim_timestamp_to_timeval(inode->i_last_write_time);
468                 ret = lutimes(output_path, tv);
469                 if (ret)
470                         ret = errno;
471         #endif
472         }
473
474         if (ret == ENOSYS) {
475                 /* utimensat() and lutimes() both not implemented or not
476                  * available */
477         #ifdef HAVE_UTIME
478                 /* Convert the WIM timestamps, which are accurate to 100
479                  * nanoseconds, into a `struct utimbuf's for passing to
480                  * utime(), which is accurate to 1 second. */
481                 struct utimbuf buf;
482                 buf.actime = wim_timestamp_to_unix(inode->i_last_access_time);
483                 buf.modtime = wim_timestamp_to_unix(inode->i_last_write_time);
484                 ret = utime(output_path, &buf);
485         #endif
486         }
487         if (ret && args->num_utime_warnings < 10) {
488                 WARNING_WITH_ERRNO("Failed to set timestamp on file `%s'",
489                                     output_path);
490                 args->num_utime_warnings++;
491         }
492         return 0;
493 }