]> wimlib.net Git - wimlib/blob - src/mount_image.c
Mount: various cleanups and optimizations
[wimlib] / src / mount_image.c
1 /*
2  * mount_image.c
3  *
4  * This file implements mounting of WIM files using FUSE, which stands for
5  * Filesystem in Userspace.  FUSE allows a filesystem to be implemented in a
6  * userspace process by implementing the filesystem primitives--- read(),
7  * write(), readdir(), etc.
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 General Public License as published by the Free
17  * Software Foundation; either version 3 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 General Public License for more
23  * details.
24  *
25  * You should have received a copy of the GNU General Public License
26  * along with wimlib; if not, see http://www.gnu.org/licenses/.
27  */
28
29 #include "wimlib_internal.h"
30
31 #ifdef WITH_FUSE
32
33 #include "sha1.h"
34 #include "lookup_table.h"
35 #include "xml.h"
36 #include "buffer_io.h"
37 #include "timestamp.h"
38 #include <limits.h>
39 #include <stdlib.h>
40 #include <unistd.h>
41 #include <sys/wait.h>
42 #define FUSE_USE_VERSION 26
43 #include <errno.h>
44 #include <string.h>
45 #include <sys/time.h>
46 #include <fuse.h>
47 #include <ftw.h>
48 #include <mqueue.h>
49 #include <utime.h>
50
51 #ifdef ENABLE_XATTR
52 #include <attr/xattr.h>
53 #endif
54
55 /* File descriptor to a file open on the WIM filesystem. */
56 struct wimlib_fd {
57         struct inode *f_inode;
58         struct lookup_table_entry *f_lte;
59         int staging_fd;
60         u16 idx;
61         u32 stream_id;
62 };
63
64 struct wimfs_context {
65         /* The WIMStruct for the mounted WIM. */
66         WIMStruct *wim;
67
68         /* Name of the staging directory for a read-write mount.  Whenever a new file is
69          * created, it is done so in the staging directory.  Furthermore, whenever a
70          * file in the WIM is modified, it is extracted to the staging directory.  If
71          * changes are commited when the WIM is unmounted, the file resources are merged
72          * in from the staging directory when writing the new WIM. */
73         char *staging_dir_name;
74         size_t staging_dir_name_len;
75
76         /* Flags passed to wimlib_mount(). */
77         int mount_flags;
78
79         int default_lookup_flags;
80
81         /* Next inode number to be assigned. */
82         u64 next_ino;
83
84         /* List of lookup table entries in the staging directory */
85         struct list_head staging_list;
86
87         /* Name and message queue descriptors for message queues between the filesystem
88          * daemon process and the unmount process.  These are used when the filesystem
89          * is unmounted and the process running wimlib_mount() (i.e. the `imagex
90          * unmount' command) needs to communicate with the filesystem daemon running
91          * fuse_main() (i.e. that spawned by the `imagex mount' or `imagex mountrw'
92          * commands */
93         char *unmount_to_daemon_mq_name;
94         char *daemon_to_unmount_mq_name;
95         mqd_t unmount_to_daemon_mq;
96         mqd_t daemon_to_unmount_mq;
97 };
98
99 static void init_wimfs_context(struct wimfs_context *ctx)
100 {
101         memset(ctx, 0, sizeof(*ctx));
102         ctx->unmount_to_daemon_mq = (mqd_t)-1;
103         ctx->daemon_to_unmount_mq = (mqd_t)-1;
104         INIT_LIST_HEAD(&ctx->staging_list);
105 }
106
107 static inline struct wimfs_context *wimfs_get_context()
108 {
109         return (struct wimfs_context*)fuse_get_context()->private_data;
110 }
111
112 static inline WIMStruct *wimfs_get_WIMStruct()
113 {
114         return wimfs_get_context()->wim;
115 }
116
117 static inline bool wimfs_ctx_readonly(const struct wimfs_context *ctx)
118 {
119         return (ctx->mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) == 0;
120 }
121
122 static inline int get_lookup_flags(const struct wimfs_context *ctx)
123 {
124         return ctx->default_lookup_flags;
125 }
126
127 /* Returns nonzero if write permission is requested on the file open flags */
128 static inline int flags_writable(int open_flags)
129 {
130         return open_flags & (O_RDWR | O_WRONLY);
131 }
132
133 /*
134  * Allocate a file descriptor for a stream.
135  *
136  * @inode:      inode containing the stream we're opening
137  * @stream_id:  ID of the stream we're opening
138  * @lte:        Lookup table entry for the stream (may be NULL)
139  * @fd_ret:     Return the allocated file descriptor if successful.
140  * @readonly:   True if this is a read-only mount.
141  *
142  * Return 0 iff successful or error code if unsuccessful.
143  */
144 static int alloc_wimlib_fd(struct inode *inode,
145                            u32 stream_id,
146                            struct lookup_table_entry *lte,
147                            struct wimlib_fd **fd_ret,
148                            bool readonly)
149 {
150         static const u16 fds_per_alloc = 8;
151         static const u16 max_fds = 0xffff;
152         int ret;
153
154         pthread_mutex_lock(&inode->i_mutex);
155
156         DEBUG("Allocating fd for stream ID %u from inode %lx (open = %u, allocated = %u)",
157               stream_id, inode->ino, inode->num_opened_fds,
158               inode->num_allocated_fds);
159
160         if (inode->num_opened_fds == inode->num_allocated_fds) {
161                 struct wimlib_fd **fds;
162                 u16 num_new_fds;
163
164                 if (inode->num_allocated_fds == max_fds) {
165                         ret = -EMFILE;
166                         goto out;
167                 }
168                 num_new_fds = min(fds_per_alloc,
169                                   max_fds - inode->num_allocated_fds);
170
171                 fds = REALLOC(inode->fds,
172                               (inode->num_allocated_fds + num_new_fds) *
173                                 sizeof(inode->fds[0]));
174                 if (!fds) {
175                         ret = -ENOMEM;
176                         goto out;
177                 }
178                 memset(&fds[inode->num_allocated_fds], 0,
179                        num_new_fds * sizeof(fds[0]));
180                 inode->fds = fds;
181                 inode->num_allocated_fds += num_new_fds;
182         }
183         for (u16 i = 0; ; i++) {
184                 if (!inode->fds[i]) {
185                         struct wimlib_fd *fd = CALLOC(1, sizeof(*fd));
186                         if (!fd) {
187                                 ret = -ENOMEM;
188                                 break;
189                         }
190                         fd->f_inode    = inode;
191                         fd->f_lte      = lte;
192                         fd->staging_fd = -1;
193                         fd->idx        = i;
194                         fd->stream_id  = stream_id;
195                         *fd_ret        = fd;
196                         inode->fds[i]  = fd;
197                         inode->num_opened_fds++;
198                         if (lte && !readonly)
199                                 lte->num_opened_fds++;
200                         DEBUG("Allocated fd (idx = %u)", fd->idx);
201                         ret = 0;
202                         break;
203                 }
204         }
205 out:
206         pthread_mutex_unlock(&inode->i_mutex);
207         return ret;
208 }
209
210 static void inode_put_fd(struct inode *inode, struct wimlib_fd *fd)
211 {
212         wimlib_assert(inode != NULL);
213
214         pthread_mutex_lock(&inode->i_mutex);
215
216         wimlib_assert(fd->f_inode == inode);
217         wimlib_assert(inode->num_opened_fds != 0);
218         wimlib_assert(fd->idx < inode->num_allocated_fds);
219         wimlib_assert(inode->fds[fd->idx] == fd);
220
221         inode->fds[fd->idx] = NULL;
222         FREE(fd);
223         if (--inode->num_opened_fds == 0 && inode->link_count == 0) {
224                 pthread_mutex_unlock(&inode->i_mutex);
225                 free_inode(inode);
226         } else {
227                 pthread_mutex_unlock(&inode->i_mutex);
228         }
229 }
230
231 static int lte_put_fd(struct lookup_table_entry *lte, struct wimlib_fd *fd)
232 {
233         wimlib_assert(fd->f_lte == lte);
234
235         if (!lte) /* Empty stream with no lookup table entry */
236                 return 0;
237
238         /* Close staging file descriptor if needed. */
239
240         if (lte->resource_location == RESOURCE_IN_STAGING_FILE
241              && fd->staging_fd != -1)
242         {
243                 if (close(fd->staging_fd) != 0) {
244                         ERROR_WITH_ERRNO("Failed to close staging file");
245                         return -errno;
246                 }
247         }
248         lte_decrement_num_opened_fds(lte);
249         return 0;
250 }
251
252 /* Close a file descriptor. */
253 static int close_wimlib_fd(struct wimlib_fd *fd)
254 {
255         int ret;
256         DEBUG("Closing fd (inode = %lu, opened = %u, allocated = %u)",
257               fd->f_inode->ino, fd->f_inode->num_opened_fds,
258               fd->f_inode->num_allocated_fds);
259         ret = lte_put_fd(fd->f_lte, fd);
260         if (ret != 0)
261                 return ret;
262
263         inode_put_fd(fd->f_inode, fd);
264         return 0;
265 }
266
267 static int create_dentry(struct wimfs_context *ctx, const char *path,
268                          struct dentry **dentry_ret)
269 {
270         struct dentry *parent;
271         struct dentry *new;
272         const char *basename;
273
274         parent = get_parent_dentry(ctx->wim, path);
275         if (!parent)
276                 return -ENOENT;
277
278         if (!dentry_is_directory(parent))
279                 return -ENOTDIR;
280
281         basename = path_basename(path);
282         if (get_dentry_child_with_name(parent, basename))
283                 return -EEXIST;
284
285         new = new_dentry_with_inode(basename);
286         if (!new)
287                 return -ENOMEM;
288
289         new->d_inode->resolved = 1;
290         new->d_inode->ino = ctx->next_ino++;
291         dentry_add_child(parent, new);
292         *dentry_ret = new;
293         return 0;
294 }
295
296 /* Remove a dentry; i.e. remove a reference to the corresponding inode.
297  *
298  * If there are no remaining references to the inode either through dentries or
299  * open file descriptors, the inode is freed.  Otherwise, the inode is not
300  * removed, but the dentry is unlinked and freed.
301  *
302  * Either way, all lookup table entries referenced by the inode have their
303  * reference count decremented.  If a lookup table entry has no open file
304  * descriptors and no references remaining, it is freed, and the staging file is
305  * unlinked.
306  */
307 static void remove_dentry(struct dentry *dentry,
308                           struct lookup_table *lookup_table)
309 {
310         struct inode *inode = dentry->d_inode;
311         struct lookup_table_entry *lte;
312         unsigned i;
313
314         for (i = 0; i <= inode->num_ads; i++) {
315                 lte = inode_stream_lte_resolved(inode, i);
316                 if (lte)
317                         lte_decrement_refcnt(lte, lookup_table);
318         }
319         unlink_dentry(dentry);
320         put_dentry(dentry);
321 }
322
323 /* Transfers file attributes from a struct inode to a `stat' buffer.
324  *
325  * The lookup table entry tells us which stream in the inode we are statting.
326  * For a named data stream, everything returned is the same as the unnamed data
327  * stream except possibly the size and block count. */
328 static int inode_to_stbuf(const struct inode *inode,
329                           struct lookup_table_entry *lte, struct stat *stbuf)
330 {
331         if (inode_is_symlink(inode))
332                 stbuf->st_mode = S_IFLNK | 0777;
333         else if (inode_is_directory(inode))
334                 stbuf->st_mode = S_IFDIR | 0755;
335         else
336                 stbuf->st_mode = S_IFREG | 0755;
337
338         stbuf->st_ino   = (ino_t)inode->ino;
339         stbuf->st_nlink = inode->link_count;
340         stbuf->st_uid   = getuid();
341         stbuf->st_gid   = getgid();
342
343         if (lte) {
344                 if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
345                         struct stat native_stat;
346                         if (stat(lte->staging_file_name, &native_stat) != 0) {
347                                 DEBUG("Failed to stat `%s': %m",
348                                       lte->staging_file_name);
349                                 return -errno;
350                         }
351                         stbuf->st_size = native_stat.st_size;
352                 } else {
353                         stbuf->st_size = wim_resource_size(lte);
354                 }
355         } else {
356                 stbuf->st_size = 0;
357         }
358
359         stbuf->st_atime   = wim_timestamp_to_unix(inode->last_access_time);
360         stbuf->st_mtime   = wim_timestamp_to_unix(inode->last_write_time);
361         stbuf->st_ctime   = wim_timestamp_to_unix(inode->creation_time);
362         stbuf->st_blocks  = (stbuf->st_size + 511) / 512;
363         return 0;
364 }
365
366 /* Creates a new staging file and returns its file descriptor opened for
367  * writing.
368  *
369  * @name_ret: A location into which the a pointer to the newly allocated name of
370  *                      the staging file is stored.
371  * @return:  The file descriptor for the new file.  Returns -1 and sets errno on
372  *              error, for any reason possible from the creat() function.
373  */
374 static int create_staging_file(char **name_ret, int open_flags,
375                                struct wimfs_context *ctx)
376 {
377         size_t name_len;
378         char *name;
379         struct stat stbuf;
380         int fd;
381         int errno_save;
382
383         name_len = ctx->staging_dir_name_len + 1 + SHA1_HASH_SIZE;
384         name = MALLOC(name_len + 1);
385         if (!name) {
386                 errno = ENOMEM;
387                 return -1;
388         }
389
390         do {
391
392                 memcpy(name, ctx->staging_dir_name, ctx->staging_dir_name_len);
393                 name[ctx->staging_dir_name_len] = '/';
394                 randomize_char_array_with_alnum(name + ctx->staging_dir_name_len + 1,
395                                                 SHA1_HASH_SIZE);
396                 name[name_len] = '\0';
397
398
399         /* Just in case, verify that the randomly generated name doesn't name an
400          * existing file, and try again if so  */
401         } while (stat(name, &stbuf) == 0);
402
403         if (errno != ENOENT)
404                 /* other error! */
405                 return -1;
406
407         /* doesn't exist--- ok */
408
409         DEBUG("Creating staging file `%s'", name);
410
411         fd = open(name, open_flags | O_CREAT | O_TRUNC, 0600);
412         if (fd == -1) {
413                 errno_save = errno;
414                 FREE(name);
415                 errno = errno_save;
416         } else {
417                 *name_ret = name;
418         }
419         return fd;
420 }
421
422 /*
423  * Extract a WIM resource to the staging directory.
424  *
425  * @inode:  Inode that contains the stream we are extracting
426  *
427  * @stream_id: Identifier for the stream (it stays constant even if the indices
428  * of the stream entries are changed)
429  *
430  * @lte: Pointer to pointer to the lookup table entry for the stream we need to
431  * extract, or NULL if there was no lookup table entry present for the stream
432  *
433  * @size:  Number of bytes of the stream we want to extract (this supports the
434  * wimfs_truncate() function).  It may be more than the actual stream length, in
435  * which case the extra space is filled with zeroes.
436  *
437  * @ctx:  Context for the WIM filesystem.
438  *
439  * Returns 0 on success or a negative error code on failure.
440  */
441 static int extract_resource_to_staging_dir(struct inode *inode,
442                                            u32 stream_id,
443                                            struct lookup_table_entry **lte,
444                                            off_t size,
445                                            struct wimfs_context *ctx)
446 {
447         char *staging_file_name;
448         int ret;
449         int fd;
450         struct lookup_table_entry *old_lte, *new_lte;
451         off_t old_size;
452         off_t extract_size;
453
454         DEBUG("Extracting resource to staging dir: inode %"PRIu64", "
455               "stream id %"PRIu32, inode->ino, stream_id);
456
457         old_lte = *lte;
458
459         wimlib_assert(old_lte == NULL ||
460                       old_lte->resource_location != RESOURCE_IN_STAGING_FILE);
461
462         /* Create the staging file */
463         fd = create_staging_file(&staging_file_name, O_WRONLY, ctx);
464         if (fd == -1)
465                 return -errno;
466
467         /* Extract the stream to the staging file (possibly truncated) */
468         if (old_lte) {
469                 extract_size = min(wim_resource_size(old_lte), size);
470                 ret = extract_wim_resource_to_fd(old_lte, fd, extract_size);
471         } else {
472                 ret = 0;
473                 extract_size = 0;
474         }
475
476         /* In the case of truncate() to more than the file length, extend the
477          * file with zeroes by calling ftruncate() on the underlying staging
478          * file */
479         if (ret == 0 && size > extract_size)
480                 ret = ftruncate(fd, size);
481
482         /* Close the staging file descriptor and check for errors.  If there's
483          * an error, unlink the staging file. */
484         if (ret != 0 || close(fd) != 0) {
485                 if (errno != 0)
486                         ret = -errno;
487                 else
488                         ret = -EIO;
489                 close(fd);
490                 goto out_delete_staging_file;
491         }
492
493         /* Now deal with the lookup table entries.  We may be able to re-use the
494          * existing entry, but we may have to create a new one instead. */
495
496         if (old_lte && inode->link_count == old_lte->refcnt) {
497                 /* The reference count of the existing lookup table entry is the
498                  * same as the link count of the inode that contains the stream
499                  * we're opening.  Therefore, ALL the references to the lookup
500                  * table entry correspond to the stream we're trying to extract,
501                  * so the lookup table entry can be re-used.  */
502                 DEBUG("Re-using lookup table entry");
503                 lookup_table_unlink(ctx->wim->lookup_table, old_lte);
504                 new_lte = old_lte;
505         } else {
506                 if (old_lte) {
507                         /* There's an existing lookup table entry, but its
508                          * reference count is greater than the link count for
509                          * the inode containing a stream we're opening.
510                          * Therefore, we need to split the lookup table entry.
511                          */
512                         wimlib_assert(old_lte->refcnt > inode->link_count);
513                         DEBUG("Splitting lookup table entry "
514                               "(inode->link_count = %u, old_lte->refcnt = %u)",
515                               inode->link_count, old_lte->refcnt);
516                 }
517
518                 new_lte = new_lookup_table_entry();
519                 if (!new_lte) {
520                         ret = -ENOMEM;
521                         goto out_delete_staging_file;
522                 }
523
524                 /* There may already be open file descriptors to this stream if
525                  * it's previously been opened read-only, but just now we're
526                  * opening it read-write.  Identify those file descriptors and
527                  * change their lookup table entry pointers to point to the new
528                  * lookup table entry, and open staging file descriptors for
529                  * them.
530                  *
531                  * At the same time, we need to count the number of these opened
532                  * file descriptors to the new lookup table entry.  If there's
533                  * an old lookup table entry, this number needs to be subtracted
534                  * from the fd's opened to the old entry. */
535                 for (u16 i = 0, j = 0; j < inode->num_opened_fds; i++) {
536                         struct wimlib_fd *fd = inode->fds[i];
537                         if (fd) {
538                                 if (fd->stream_id == stream_id) {
539                                         wimlib_assert(fd->f_lte == old_lte);
540                                         wimlib_assert(fd->staging_fd == -1);
541                                         fd->f_lte = new_lte;
542                                         new_lte->num_opened_fds++;
543                                         fd->staging_fd = open(staging_file_name, O_RDONLY);
544                                         if (fd->staging_fd == -1) {
545                                                 ret = -errno;
546                                                 goto out_revert_fd_changes;
547                                         }
548                                 }
549                                 j++;
550                         }
551                 }
552                 DEBUG("%hu fd's were already opened to the file we extracted",
553                       new_lte->num_opened_fds);
554                 if (old_lte) {
555                         old_lte->num_opened_fds -= new_lte->num_opened_fds;
556                         old_lte->refcnt -= inode->link_count;
557                 }
558         }
559
560         new_lte->refcnt                       = inode->link_count;
561         new_lte->resource_location            = RESOURCE_IN_STAGING_FILE;
562         new_lte->staging_file_name            = staging_file_name;
563         new_lte->lte_inode                    = inode;
564         random_hash(new_lte->hash);
565
566         if (stream_id == 0)
567                 inode->lte = new_lte;
568         else
569                 for (u16 i = 0; i < inode->num_ads; i++)
570                         if (inode->ads_entries[i].stream_id == stream_id)
571                                 inode->ads_entries[i].lte = new_lte;
572
573         lookup_table_insert(ctx->wim->lookup_table, new_lte);
574         list_add(&new_lte->staging_list, &ctx->staging_list);
575         *lte = new_lte;
576         return 0;
577 out_revert_fd_changes:
578         for (u16 i = 0, j = 0; j < new_lte->num_opened_fds; i++) {
579                 struct wimlib_fd *fd = inode->fds[i];
580                 if (fd && fd->stream_id == stream_id && fd->f_lte == new_lte) {
581                         fd->f_lte = old_lte;
582                         if (fd->staging_fd != -1) {
583                                 close(fd->staging_fd);
584                                 fd->staging_fd = -1;
585                         }
586                         j++;
587                 }
588         }
589         free_lookup_table_entry(new_lte);
590 out_delete_staging_file:
591         unlink(staging_file_name);
592         FREE(staging_file_name);
593         return ret;
594 }
595
596 /*
597  * Creates a randomly named staging directory and saves its name in the
598  * filesystem context structure.
599  */
600 static int make_staging_dir(struct wimfs_context *ctx, const char *user_prefix)
601 {
602         static const size_t random_suffix_len = 10;
603         static const char *common_suffix = ".staging";
604         static const size_t common_suffix_len = 8;
605
606         char *staging_dir_name = NULL;
607         size_t staging_dir_name_len;
608         size_t prefix_len;
609         const char *wim_basename;
610         char *real_user_prefix = NULL;
611         int ret;
612
613         if (user_prefix) {
614                 real_user_prefix = realpath(user_prefix, NULL);
615                 if (!real_user_prefix) {
616                         ERROR_WITH_ERRNO("Could not resolve `%s'",
617                                          real_user_prefix);
618                         ret = WIMLIB_ERR_NOTDIR;
619                         goto out;
620                 }
621                 wim_basename = path_basename(ctx->wim->filename);
622                 prefix_len = strlen(real_user_prefix) + 1 + strlen(wim_basename);
623         } else {
624                 prefix_len = strlen(ctx->wim->filename);
625         }
626
627         staging_dir_name_len = prefix_len + common_suffix_len + random_suffix_len;
628
629         staging_dir_name = MALLOC(staging_dir_name_len + 1);
630         if (!staging_dir_name) {
631                 ret = WIMLIB_ERR_NOMEM;
632                 goto out;
633         }
634
635         if (real_user_prefix)
636                 sprintf(staging_dir_name, "%s/%s", real_user_prefix, wim_basename);
637         else
638                 strcpy(staging_dir_name, ctx->wim->filename);
639
640         strcat(staging_dir_name, common_suffix);
641
642         randomize_char_array_with_alnum(staging_dir_name + prefix_len + common_suffix_len,
643                                         random_suffix_len);
644
645         staging_dir_name[staging_dir_name_len] = '\0';
646
647         if (mkdir(staging_dir_name, 0700) != 0) {
648                 ERROR_WITH_ERRNO("Failed to create temporary directory `%s'",
649                                  staging_dir_name);
650                 ret = WIMLIB_ERR_MKDIR;
651         } else {
652                 ret = 0;
653         }
654 out:
655         FREE(real_user_prefix);
656         if (ret == 0) {
657                 ctx->staging_dir_name = staging_dir_name;
658                 ctx->staging_dir_name_len = staging_dir_name_len;
659         } else {
660                 FREE(staging_dir_name);
661         }
662         return ret;
663 }
664
665 static int remove_file_or_directory(const char *fpath, const struct stat *sb,
666                                     int typeflag, struct FTW *ftwbuf)
667 {
668         if (remove(fpath) == 0)
669                 return 0;
670         else {
671                 ERROR_WITH_ERRNO("Cannot remove `%s'", fpath);
672                 return WIMLIB_ERR_DELETE_STAGING_DIR;
673         }
674 }
675
676
677 /*
678  * Deletes the staging directory and all the files contained in it.
679  */
680 static int delete_staging_dir(struct wimfs_context *ctx)
681 {
682         int ret;
683         ret = nftw(ctx->staging_dir_name, remove_file_or_directory,
684                    10, FTW_DEPTH);
685         FREE(ctx->staging_dir_name);
686         ctx->staging_dir_name = NULL;
687         return ret;
688 }
689
690
691 /* Simple function that returns the concatenation of 2 strings. */
692 static char *strcat_dup(const char *s1, const char *s2, size_t max_len)
693 {
694         size_t len = strlen(s1) + strlen(s2);
695         if (len > max_len)
696                 len = max_len;
697         char *p = MALLOC(len + 1);
698         if (!p)
699                 return NULL;
700         snprintf(p, len + 1, "%s%s", s1, s2);
701         return p;
702 }
703
704 static int set_message_queue_names(struct wimfs_context *ctx,
705                                    const char *mount_dir)
706 {
707         static const char *u2d_prefix = "/wimlib-unmount-to-daemon-mq";
708         static const char *d2u_prefix = "/wimlib-daemon-to-unmount-mq";
709         char *dir_path;
710         char *p;
711         int ret;
712
713         dir_path = realpath(mount_dir, NULL);
714         if (!dir_path) {
715                 ERROR_WITH_ERRNO("Failed to resolve path \"%s\"", mount_dir);
716                 if (errno == ENOMEM)
717                         return WIMLIB_ERR_NOMEM;
718                 else
719                         return WIMLIB_ERR_NOTDIR;
720         }
721
722         p = dir_path;
723         while (*p) {
724                 if (*p == '/')
725                         *p = 0xff;
726                 p++;
727         }
728
729         ctx->unmount_to_daemon_mq_name = strcat_dup(u2d_prefix, dir_path,
730                                                     NAME_MAX);
731         if (!ctx->unmount_to_daemon_mq_name) {
732                 ret = WIMLIB_ERR_NOMEM;
733                 goto out_free_dir_path;
734         }
735         ctx->daemon_to_unmount_mq_name = strcat_dup(d2u_prefix, dir_path,
736                                                     NAME_MAX);
737         if (!ctx->daemon_to_unmount_mq_name) {
738                 ret = WIMLIB_ERR_NOMEM;
739                 goto out_free_unmount_to_daemon_mq_name;
740         }
741
742         ret = 0;
743         goto out_free_dir_path;
744 out_free_unmount_to_daemon_mq_name:
745         FREE(ctx->unmount_to_daemon_mq_name);
746         ctx->unmount_to_daemon_mq_name = NULL;
747 out_free_dir_path:
748         FREE(dir_path);
749         return ret;
750 }
751
752 static void free_message_queue_names(struct wimfs_context *ctx)
753 {
754         FREE(ctx->unmount_to_daemon_mq_name);
755         FREE(ctx->daemon_to_unmount_mq_name);
756         ctx->unmount_to_daemon_mq_name = NULL;
757         ctx->daemon_to_unmount_mq_name = NULL;
758 }
759
760 /*
761  * Opens two POSIX message queue: one for sending messages from the unmount
762  * process to the daemon process, and one to go the other way.  The names of the
763  * message queues, which must be system-wide unique, are be based on the mount
764  * point.  (There of course is still a possibility of a collision if one were to
765  * unmount two identically named directories simultaneously...)
766  *
767  * @daemon specifies whether the calling process is the filesystem daemon or the
768  * unmount process.
769  */
770 static int open_message_queues(struct wimfs_context *ctx, bool daemon)
771 {
772         int unmount_to_daemon_mq_flags = O_WRONLY | O_CREAT;
773         int daemon_to_unmount_mq_flags = O_RDONLY | O_CREAT;
774
775         if (daemon)
776                 swap(unmount_to_daemon_mq_flags, daemon_to_unmount_mq_flags);
777
778         DEBUG("Opening message queue \"%s\"", ctx->unmount_to_daemon_mq_name);
779         ctx->unmount_to_daemon_mq = mq_open(ctx->unmount_to_daemon_mq_name,
780                                             unmount_to_daemon_mq_flags, 0700, NULL);
781
782         if (ctx->unmount_to_daemon_mq == (mqd_t)-1) {
783                 ERROR_WITH_ERRNO("mq_open()");
784                 return WIMLIB_ERR_MQUEUE;
785         }
786
787         DEBUG("Opening message queue \"%s\"", ctx->daemon_to_unmount_mq_name);
788         ctx->daemon_to_unmount_mq = mq_open(ctx->daemon_to_unmount_mq_name,
789                                             daemon_to_unmount_mq_flags, 0700, NULL);
790
791         if (ctx->daemon_to_unmount_mq == (mqd_t)-1) {
792                 ERROR_WITH_ERRNO("mq_open()");
793                 mq_close(ctx->unmount_to_daemon_mq);
794                 mq_unlink(ctx->unmount_to_daemon_mq_name);
795                 ctx->unmount_to_daemon_mq = (mqd_t)-1;
796                 return WIMLIB_ERR_MQUEUE;
797         }
798         return 0;
799 }
800
801 /* Try to determine the maximum message size of a message queue.  The return
802  * value is the maximum message size, or a guess of 8192 bytes if it cannot be
803  * determined. */
804 static long mq_get_msgsize(mqd_t mq)
805 {
806         static const char *msgsize_max_file = "/proc/sys/fs/mqueue/msgsize_max";
807         FILE *fp;
808         struct mq_attr attr;
809         long msgsize;
810
811         if (mq_getattr(mq, &attr) == 0) {
812                 msgsize = attr.mq_msgsize;
813         } else {
814                 ERROR_WITH_ERRNO("mq_getattr()");
815                 ERROR("Attempting to read %s", msgsize_max_file);
816                 fp = fopen(msgsize_max_file, "rb");
817                 if (fp) {
818                         if (fscanf(fp, "%ld", &msgsize) != 1) {
819                                 ERROR("Assuming message size of 8192");
820                                 msgsize = 8192;
821                         }
822                         fclose(fp);
823                 } else {
824                         ERROR_WITH_ERRNO("Failed to open the file `%s'",
825                                          msgsize_max_file);
826                         ERROR("Assuming message size of 8192");
827                         msgsize = 8192;
828                 }
829         }
830         return msgsize;
831 }
832
833 static int get_mailbox(mqd_t mq, long needed_msgsize, long *msgsize_ret,
834                        void **mailbox_ret)
835 {
836         long msgsize;
837         char *mailbox;
838
839         msgsize = mq_get_msgsize(mq);
840
841         if (msgsize < needed_msgsize) {
842                 ERROR("Message queue max size must be at least %ld!",
843                       needed_msgsize);
844                 return WIMLIB_ERR_MQUEUE;
845         }
846
847         mailbox = MALLOC(msgsize);
848         if (!mailbox) {
849                 ERROR("Failed to allocate %ld bytes for mailbox", msgsize);
850                 return WIMLIB_ERR_NOMEM;
851         }
852         *msgsize_ret = msgsize;
853         *mailbox_ret = mailbox;
854         return 0;
855 }
856
857 static void unlink_message_queues(struct wimfs_context *ctx)
858 {
859         mq_unlink(ctx->unmount_to_daemon_mq_name);
860         mq_unlink(ctx->daemon_to_unmount_mq_name);
861 }
862
863 /* Closes the message queues, which are allocated in static variables */
864 static void close_message_queues(struct wimfs_context *ctx)
865 {
866         mq_close(ctx->unmount_to_daemon_mq);
867         ctx->unmount_to_daemon_mq = (mqd_t)(-1);
868         mq_close(ctx->daemon_to_unmount_mq);
869         ctx->daemon_to_unmount_mq = (mqd_t)(-1);
870         unlink_message_queues(ctx);
871 }
872
873 struct unmount_message_header {
874         u32 min_version;
875         u32 cur_version;
876         u32 data_size;
877 };
878
879 struct unmount_request {
880         struct unmount_message_header hdr;
881         struct {
882                 u32 unmount_flags;
883         } data;
884 };
885
886 struct unmount_response {
887         struct unmount_message_header hdr;
888         struct {
889                 int32_t status;
890                 u32 mount_flags;
891         } data;
892 };
893
894 static void inode_update_lte_ptr(struct inode *inode,
895                                  struct lookup_table_entry *old_lte,
896                                  struct lookup_table_entry *new_lte)
897 {
898         if (inode->lte == old_lte) {
899                 inode->lte = new_lte;
900         } else {
901                 for (unsigned i = 0; i < inode->num_ads; i++) {
902                         if (inode->ads_entries[i].lte == old_lte) {
903                                 inode->ads_entries[i].lte = new_lte;
904                                 break;
905                         }
906                 }
907         }
908 }
909
910 static int update_lte_of_staging_file(struct lookup_table_entry *lte,
911                                       struct lookup_table *table)
912 {
913         struct lookup_table_entry *duplicate_lte;
914         int ret;
915         u8 hash[SHA1_HASH_SIZE];
916         struct stat stbuf;
917
918         ret = sha1sum(lte->staging_file_name, hash);
919         if (ret != 0)
920                 return ret;
921         lookup_table_unlink(table, lte);
922         duplicate_lte = __lookup_resource(table, hash);
923         if (duplicate_lte) {
924                 /* Merge duplicate lookup table entries */
925                 duplicate_lte->refcnt += lte->refcnt;
926                 inode_update_lte_ptr(lte->lte_inode, lte, duplicate_lte);
927                 free_lookup_table_entry(lte);
928         } else {
929                 if (stat(lte->staging_file_name, &stbuf) != 0) {
930                         ERROR_WITH_ERRNO("Failed to stat `%s'", lte->staging_file_name);
931                         return WIMLIB_ERR_STAT;
932                 }
933                 if (stbuf.st_size == 0) {
934                         /* Zero-length stream.  No lookup table entry needed. */
935                         inode_update_lte_ptr(lte->lte_inode, lte, NULL);
936                         free_lookup_table_entry(lte);
937                 } else {
938                         wimlib_assert(&lte->file_on_disk == &lte->staging_file_name);
939                         lte->resource_entry.original_size = stbuf.st_size;
940                         lte->resource_entry.size = stbuf.st_size;
941                         lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
942                         lte->file_on_disk_fp = NULL;
943                         copy_hash(lte->hash, hash);
944                         lookup_table_insert(table, lte);
945                 }
946         }
947         return 0;
948 }
949
950 static int inode_close_fds(struct inode *inode)
951 {
952         u16 num_opened_fds = inode->num_opened_fds;
953         for (u16 i = 0, j = 0; j < num_opened_fds; i++) {
954                 struct wimlib_fd *fd = inode->fds[i];
955                 if (fd) {
956                         wimlib_assert(fd->f_inode == inode);
957                         int ret = close_wimlib_fd(fd);
958                         if (ret != 0)
959                                 return ret;
960                         j++;
961                 }
962         }
963         return 0;
964 }
965
966 /* Overwrites the WIM file, with changes saved. */
967 static int rebuild_wim(struct wimfs_context *ctx, int write_flags)
968 {
969         int ret;
970         struct lookup_table_entry *lte, *tmp;
971         WIMStruct *w = ctx->wim;
972
973         DEBUG("Closing all staging file descriptors.");
974         list_for_each_entry_safe(lte, tmp, &ctx->staging_list, staging_list) {
975                 ret = inode_close_fds(lte->lte_inode);
976                 if (ret != 0)
977                         return ret;
978         }
979
980         DEBUG("Calculating SHA1 checksums for all new staging files.");
981         list_for_each_entry(lte, &ctx->staging_list, staging_list) {
982                 ret = update_lte_of_staging_file(lte, w->lookup_table);
983                 if (ret != 0)
984                         return ret;
985         }
986
987         xml_update_image_info(w, w->current_image);
988         ret = wimlib_overwrite(w, write_flags, 0, NULL);
989         if (ret != 0)
990                 ERROR("Failed to commit changes to mounted WIM image");
991         return ret;
992 }
993
994 /* Send a message to the filesystem daemon saying whether to commit or not. */
995 static int send_unmount_request(struct wimfs_context *ctx, int unmount_flags)
996 {
997         int ret;
998         struct unmount_request msg;
999
1000         msg.hdr.min_version    = WIMLIB_MAKEVERSION(1, 2, 0);
1001         msg.hdr.cur_version    = WIMLIB_VERSION_CODE;
1002         msg.hdr.data_size      = sizeof(msg.data);
1003         msg.data.unmount_flags = unmount_flags;
1004
1005         ret = mq_send(ctx->unmount_to_daemon_mq, (void*)&msg,
1006                       sizeof(msg), 1);
1007         if (ret == -1) {
1008                 ERROR_WITH_ERRNO("Failed to notify filesystem daemon whether "
1009                                  "we want to commit changes or not");
1010                 return WIMLIB_ERR_MQUEUE;
1011         }
1012         return 0;
1013 }
1014
1015 static int receive_unmount_request(struct wimfs_context *ctx,
1016                                    int *unmount_flags)
1017 {
1018         void *mailbox;
1019         long msgsize;
1020         struct timeval now;
1021         struct timespec timeout;
1022         ssize_t bytes_received;
1023         struct unmount_request *msg;
1024         int ret;
1025
1026         ret = get_mailbox(ctx->unmount_to_daemon_mq,
1027                           sizeof(struct unmount_request),
1028                           &msgsize, &mailbox);
1029         if (ret != 0)
1030                 return ret;
1031
1032         /* Wait at most 3 seconds before giving up and discarding changes. */
1033         gettimeofday(&now, NULL);
1034         timeout.tv_sec = now.tv_sec + 3;
1035         timeout.tv_nsec = now.tv_usec * 1000;
1036
1037         bytes_received = mq_timedreceive(ctx->unmount_to_daemon_mq, mailbox,
1038                                          msgsize, NULL, &timeout);
1039         msg = mailbox;
1040         if (bytes_received == -1) {
1041                 ERROR_WITH_ERRNO("mq_timedreceive()");
1042                 ERROR("Not committing.");
1043                 ret = WIMLIB_ERR_MQUEUE;
1044         } else if (bytes_received < sizeof(struct unmount_message_header) ||
1045                    bytes_received != sizeof(struct unmount_message_header) + msg->hdr.data_size) {
1046                 ERROR("Received invalid unmount request");
1047                 ret = WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE;
1048         } else if (WIMLIB_VERSION_CODE < msg->hdr.min_version) {
1049                 ERROR("Cannot understand the unmount request. "
1050                       "Please upgrade wimlib to at least v%d.%d.%d",
1051                       WIMLIB_GET_MAJOR_VERSION(msg->hdr.min_version),
1052                       WIMLIB_GET_MINOR_VERSION(msg->hdr.min_version),
1053                       WIMLIB_GET_PATCH_VERSION(msg->hdr.min_version));
1054                 ret = WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE;
1055         } else {
1056                 *unmount_flags = msg->data.unmount_flags;
1057                 ret = 0;
1058         }
1059         FREE(mailbox);
1060         return ret;
1061 }
1062
1063 static void send_unmount_response(struct wimfs_context *ctx, int status)
1064 {
1065         struct unmount_response response;
1066         response.hdr.min_version  = WIMLIB_MAKEVERSION(1, 2, 0);
1067         response.hdr.cur_version  = WIMLIB_VERSION_CODE;
1068         response.hdr.data_size    = sizeof(response.data);
1069         response.data.status      = status;
1070         response.data.mount_flags = ctx->mount_flags;
1071         if (mq_send(ctx->daemon_to_unmount_mq, (void*)&response,
1072                     sizeof(response), 1))
1073                 ERROR_WITH_ERRNO("Failed to send status to unmount process");
1074 }
1075
1076 /* Wait for a message from the filesytem daemon indicating whether  the
1077  * filesystem was unmounted successfully.  This may
1078  * take a long time if a big WIM file needs to be rewritten.
1079  *
1080  * Wait at most 600??? seconds before giving up and returning an error.  Either
1081  * it's a really big WIM file, or (more likely) the filesystem daemon has
1082  * crashed or failed for some reason.
1083  *
1084  * XXX come up with some method to determine if the filesystem daemon has really
1085  * crashed or not.
1086  *
1087  * XXX Idea: have mount daemon write its PID into the WIM file header?  No, this
1088  * wouldn't work because we know the directory but not the WIM file...
1089  */
1090 static int receive_unmount_response(struct wimfs_context *ctx)
1091 {
1092         long msgsize;
1093         void *mailbox;
1094         struct timeval now;
1095         struct timespec timeout;
1096         ssize_t bytes_received;
1097         int ret;
1098         struct unmount_response *msg;
1099
1100         ret = get_mailbox(ctx->daemon_to_unmount_mq,
1101                           sizeof(struct unmount_response), &msgsize, &mailbox);
1102         if (ret != 0)
1103                 return ret;
1104
1105         DEBUG("Waiting for message telling us whether the unmount was "
1106               "successful or not.");
1107
1108         gettimeofday(&now, NULL);
1109         timeout.tv_sec = now.tv_sec + 600;
1110         timeout.tv_nsec = now.tv_usec * 1000;
1111         bytes_received = mq_timedreceive(ctx->daemon_to_unmount_mq,
1112                                          mailbox, msgsize, NULL, &timeout);
1113         msg = mailbox;
1114         if (bytes_received == -1) {
1115                 if (errno == ETIMEDOUT) {
1116                         ERROR("Timed out- probably the filesystem daemon "
1117                               "crashed and the WIM was not written "
1118                               "successfully.");
1119                         ret = WIMLIB_ERR_TIMEOUT;
1120                 } else {
1121                         ERROR_WITH_ERRNO("mq_receive()");
1122                         ret = WIMLIB_ERR_MQUEUE;
1123                 }
1124         } else if (bytes_received < sizeof(struct unmount_message_header) ||
1125                    bytes_received != sizeof(struct unmount_message_header) + msg->hdr.data_size ||
1126                    WIMLIB_VERSION_CODE < msg->hdr.min_version) {
1127                 ERROR("Received invalid unmount response");
1128                 ret = WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE;
1129         } else if (WIMLIB_VERSION_CODE < msg->hdr.min_version) {
1130                 ERROR("Cannot understand the unmount response. "
1131                       "Please upgrade wimlib to at least v%d.%d.%d",
1132                       WIMLIB_GET_MAJOR_VERSION(msg->hdr.min_version),
1133                       WIMLIB_GET_MINOR_VERSION(msg->hdr.min_version),
1134                       WIMLIB_GET_PATCH_VERSION(msg->hdr.min_version));
1135                 ret = WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE;
1136         } else {
1137                 ret = msg->data.status;
1138                 if (ret) {
1139                         ERROR("A failure status (%d) was returned "
1140                               "by the filesystem daemon", ret);
1141                 }
1142         }
1143         FREE(mailbox);
1144         return ret;
1145 }
1146
1147 /* Execute `fusermount -u', which is installed setuid root, to unmount the WIM.
1148  *
1149  * FUSE does not yet implement synchronous unmounts.  This means that fusermount
1150  * -u will return before the filesystem daemon returns from wimfs_destroy().
1151  *  This is partly what we want, because we need to send a message from this
1152  *  process to the filesystem daemon telling whether --commit was specified or
1153  *  not.  However, after that, the unmount process must wait for the filesystem
1154  *  daemon to finish writing the WIM file.
1155  */
1156 static int execute_fusermount(const char *dir)
1157 {
1158         pid_t pid;
1159         int ret;
1160         int status;
1161
1162         pid = fork();
1163         if (pid == -1) {
1164                 ERROR_WITH_ERRNO("Failed to fork()");
1165                 return WIMLIB_ERR_FORK;
1166         }
1167         if (pid == 0) {
1168                 /* Child */
1169                 execlp("fusermount", "fusermount", "-u", dir, NULL);
1170                 ERROR_WITH_ERRNO("Failed to execute `fusermount'");
1171                 exit(WIMLIB_ERR_FUSERMOUNT);
1172         }
1173
1174         /* Parent */
1175         ret = wait(&status);
1176         if (ret == -1) {
1177                 ERROR_WITH_ERRNO("Failed to wait for fusermount process to "
1178                                  "terminate");
1179                 return WIMLIB_ERR_FUSERMOUNT;
1180         }
1181
1182         if (status != 0) {
1183                 if (status == WIMLIB_ERR_FUSERMOUNT)
1184                         ERROR("Could not find the `fusermount' program");
1185                 else
1186                         ERROR("fusermount exited with status %d", status);
1187
1188                 /* Try again, but with the `umount' program.  This is required
1189                  * on other FUSE implementations such as FreeBSD's that do not
1190                  * have a `fusermount' program. */
1191
1192                 pid = fork();
1193                 if (pid == -1) {
1194                         ERROR_WITH_ERRNO("Failed to fork()");
1195                         return WIMLIB_ERR_FORK;
1196                 }
1197                 if (pid == 0) {
1198                         /* Child */
1199                         execlp("umount", "umount", dir, NULL);
1200                         ERROR_WITH_ERRNO("Failed to execute `umount'");
1201                         exit(WIMLIB_ERR_FUSERMOUNT);
1202                 }
1203
1204                 /* Parent */
1205                 ret = wait(&status);
1206                 if (ret == -1) {
1207                         ERROR_WITH_ERRNO("Failed to wait for `umount' process to "
1208                                          "terminate");
1209                         return WIMLIB_ERR_FUSERMOUNT;
1210                 }
1211                 if (status != 0) {
1212                         ERROR("`umount' exited with failure status");
1213                         return WIMLIB_ERR_FUSERMOUNT;
1214                 }
1215         }
1216         return 0;
1217 }
1218
1219 static int wimfs_access(const char *path, int mask)
1220 {
1221         /* Permissions not implemented */
1222         return 0;
1223 }
1224
1225 static int wimfs_chmod(const char *path, mode_t mask)
1226 {
1227         struct dentry *dentry;
1228         struct wimfs_context *ctx = wimfs_get_context();
1229         struct inode *inode;
1230         struct stat stbuf;
1231         int ret;
1232
1233         ret = lookup_resource(ctx->wim, path,
1234                               get_lookup_flags(ctx) | LOOKUP_FLAG_DIRECTORY_OK,
1235                               &dentry, NULL, NULL);
1236         if (ret != 0)
1237                 return ret;
1238         inode = dentry->d_inode;
1239         inode_to_stbuf(inode, NULL, &stbuf);
1240         if (mask == stbuf.st_mode)
1241                 return 0;
1242         else
1243                 return -EPERM;
1244 }
1245
1246 /* Called when the filesystem is unmounted. */
1247 static void wimfs_destroy(void *p)
1248 {
1249         /* The `imagex unmount' command, which is running in a separate process
1250          * and is executing the wimlib_unmount() function, will send this
1251          * process a `struct unmount_request' through a message queue that
1252          * specifies some unmount options, such as other to commit changes or
1253          * not. */
1254
1255         int ret;
1256         int unmount_flags;
1257         struct wimfs_context *ctx;
1258         int status;
1259
1260         ctx = wimfs_get_context();
1261         if (open_message_queues(ctx, true))
1262                 return;
1263
1264         ret = receive_unmount_request(ctx, &unmount_flags);
1265         status = ret;
1266         if (ret == 0) {
1267                 if (ctx->mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
1268                         if (unmount_flags & WIMLIB_UNMOUNT_FLAG_COMMIT) {
1269                                 int write_flags;
1270                                 if (unmount_flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY)
1271                                         write_flags = WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1272                                 else
1273                                         write_flags = 0;
1274                                 status = rebuild_wim(ctx, write_flags);
1275                         }
1276                         ret = delete_staging_dir(ctx);
1277                         if (ret != 0) {
1278                                 ERROR("Failed to delete the staging directory");
1279                                 if (status == 0)
1280                                         status = ret;
1281                         }
1282                 } else {
1283                         DEBUG("Read-only mount");
1284                 }
1285         }
1286         send_unmount_response(ctx, status);
1287         close_message_queues(ctx);
1288 }
1289
1290 #if 0
1291 static int wimfs_fallocate(const char *path, int mode,
1292                            off_t offset, off_t len, struct fuse_file_info *fi)
1293 {
1294         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1295         wimlib_assert(fd->staging_fd != -1);
1296         return fallocate(fd->staging_fd, mode, offset, len);
1297 }
1298
1299 #endif
1300
1301 static int wimfs_fgetattr(const char *path, struct stat *stbuf,
1302                           struct fuse_file_info *fi)
1303 {
1304         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1305         return inode_to_stbuf(fd->f_inode, fd->f_lte, stbuf);
1306 }
1307
1308 static int wimfs_ftruncate(const char *path, off_t size,
1309                            struct fuse_file_info *fi)
1310 {
1311         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1312         int ret = ftruncate(fd->staging_fd, size);
1313         if (ret != 0)
1314                 return -errno;
1315         if (fd->f_lte && size < fd->f_lte->resource_entry.original_size)
1316                 fd->f_lte->resource_entry.original_size = size;
1317         return 0;
1318 }
1319
1320 /*
1321  * Fills in a `struct stat' that corresponds to a file or directory in the WIM.
1322  */
1323 static int wimfs_getattr(const char *path, struct stat *stbuf)
1324 {
1325         struct dentry *dentry;
1326         struct lookup_table_entry *lte;
1327         int ret;
1328         struct wimfs_context *ctx = wimfs_get_context();
1329
1330         ret = lookup_resource(ctx->wim, path,
1331                               get_lookup_flags(ctx) | LOOKUP_FLAG_DIRECTORY_OK,
1332                               &dentry, &lte, NULL);
1333         if (ret != 0)
1334                 return ret;
1335         return inode_to_stbuf(dentry->d_inode, lte, stbuf);
1336 }
1337
1338 #ifdef ENABLE_XATTR
1339 /* Read an alternate data stream through the XATTR interface, or get its size */
1340 static int wimfs_getxattr(const char *path, const char *name, char *value,
1341                           size_t size)
1342 {
1343         int ret;
1344         struct inode *inode;
1345         struct ads_entry *ads_entry;
1346         size_t res_size;
1347         struct lookup_table_entry *lte;
1348         struct wimfs_context *ctx = wimfs_get_context();
1349
1350         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1351                 return -ENOTSUP;
1352
1353         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1354                 return -ENOATTR;
1355         name += 5;
1356
1357         inode = wim_pathname_to_inode(ctx->wim, path);
1358         if (!inode)
1359                 return -ENOENT;
1360
1361         ads_entry = inode_get_ads_entry(inode, name, NULL);
1362         if (!ads_entry)
1363                 return -ENOATTR;
1364
1365         lte = ads_entry->lte;
1366         res_size = wim_resource_size(lte);
1367
1368         if (size == 0)
1369                 return res_size;
1370
1371         if (res_size > size)
1372                 return -ERANGE;
1373
1374         ret = read_full_wim_resource(lte, (u8*)value,
1375                                      WIMLIB_RESOURCE_FLAG_MULTITHREADED);
1376         if (ret != 0)
1377                 return -EIO;
1378
1379         return res_size;
1380 }
1381 #endif
1382
1383 /* Create a hard link */
1384 static int wimfs_link(const char *to, const char *from)
1385 {
1386         struct dentry *from_dentry, *from_dentry_parent;
1387         const char *link_name;
1388         struct inode *inode;
1389         struct lookup_table_entry *lte;
1390         WIMStruct *w = wimfs_get_WIMStruct();
1391         u16 i;
1392
1393         inode = wim_pathname_to_inode(w, to);
1394         if (!inode)
1395                 return -ENOENT;
1396
1397         if (inode->attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1398                 return -EEXIST;
1399
1400         if (inode->attributes & FILE_ATTRIBUTE_DIRECTORY)
1401                 return -EPERM;
1402
1403         from_dentry_parent = get_parent_dentry(w, from);
1404         if (!from_dentry_parent)
1405                 return -ENOENT;
1406         if (!dentry_is_directory(from_dentry_parent))
1407                 return -ENOTDIR;
1408
1409         link_name = path_basename(from);
1410         if (get_dentry_child_with_name(from_dentry_parent, link_name))
1411                 return -EEXIST;
1412         from_dentry = new_dentry(link_name);
1413         if (!from_dentry)
1414                 return -ENOMEM;
1415
1416         inode_add_dentry(from_dentry, inode);
1417         from_dentry->d_inode = inode;
1418         inode->link_count++;
1419
1420         if (inode->lte)
1421                 inode->lte->refcnt++;
1422         for (i = 0; i <= inode->num_ads; i++) {
1423                 lte = inode_stream_lte_resolved(inode, i);
1424                 if (lte)
1425                         lte->refcnt++;
1426         }
1427         dentry_add_child(from_dentry_parent, from_dentry);
1428         return 0;
1429 }
1430
1431 #ifdef ENABLE_XATTR
1432 static int wimfs_listxattr(const char *path, char *list, size_t size)
1433 {
1434         size_t needed_size;
1435         struct inode *inode;
1436         struct wimfs_context *ctx = wimfs_get_context();
1437         u16 i;
1438         char *p;
1439
1440         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1441                 return -ENOTSUP;
1442
1443         /* List alternate data streams, or get the list size */
1444
1445         inode = wim_pathname_to_inode(ctx->wim, path);
1446         if (!inode)
1447                 return -ENOENT;
1448
1449         if (size == 0) {
1450                 needed_size = 0;
1451                 for (i = 0; i < inode->num_ads; i++)
1452                         needed_size += inode->ads_entries[i].stream_name_utf8_len + 6;
1453                 return needed_size;
1454         } else {
1455                 p = list;
1456                 for (i = 0; i < inode->num_ads; i++) {
1457                         needed_size = inode->ads_entries[i].stream_name_utf8_len + 6;
1458                         if (needed_size > size)
1459                                 return -ERANGE;
1460                         p += sprintf(p, "user.%s",
1461                                      inode->ads_entries[i].stream_name_utf8) + 1;
1462                         size -= needed_size;
1463                 }
1464                 return p - list;
1465         }
1466 }
1467 #endif
1468
1469
1470 /* Create a directory in the WIM.
1471  * @mode is currently ignored.  */
1472 static int wimfs_mkdir(const char *path, mode_t mode)
1473 {
1474         struct dentry *dentry;
1475         int ret;
1476
1477         ret = create_dentry(wimfs_get_context(), path, &dentry);
1478         if (ret == 0)
1479                 dentry->d_inode->attributes = FILE_ATTRIBUTE_DIRECTORY;
1480         return ret;
1481 }
1482
1483 /* Create a regular file in the WIM.
1484  * @mode is currently ignored.  */
1485 static int wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
1486 {
1487         const char *stream_name;
1488         struct wimfs_context *ctx = wimfs_get_context();
1489         if ((ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
1490              && (stream_name = path_stream_name(path))) {
1491                 /* Make an alternate data stream */
1492                 struct ads_entry *new_entry;
1493                 struct inode *inode;
1494
1495                 char *p = (char*)stream_name - 1;
1496                 wimlib_assert(*p == ':');
1497                 *p = '\0';
1498
1499                 inode = wim_pathname_to_inode(ctx->wim, path);
1500                 if (!inode)
1501                         return -ENOENT;
1502                 if (inode->attributes &
1503                     (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1504                         return -ENOENT;
1505                 if (inode_get_ads_entry(inode, stream_name, NULL))
1506                         return -EEXIST;
1507                 new_entry = inode_add_ads(inode, stream_name);
1508                 if (!new_entry)
1509                         return -ENOMEM;
1510                 return 0;
1511         } else {
1512                 struct dentry *dentry;
1513                 int ret;
1514
1515                 /* Make a normal file (not an alternate data stream) */
1516                 ret = create_dentry(ctx, path, &dentry);
1517                 if (ret == 0)
1518                         dentry->d_inode->attributes = FILE_ATTRIBUTE_NORMAL;
1519                 return ret;
1520         }
1521 }
1522
1523
1524 /* Open a file.  */
1525 static int wimfs_open(const char *path, struct fuse_file_info *fi)
1526 {
1527         struct dentry *dentry;
1528         struct lookup_table_entry *lte;
1529         int ret;
1530         struct wimlib_fd *fd;
1531         struct inode *inode;
1532         u16 stream_idx;
1533         u32 stream_id;
1534         struct wimfs_context *ctx = wimfs_get_context();
1535
1536         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1537                               &dentry, &lte, &stream_idx);
1538         if (ret != 0)
1539                 return ret;
1540
1541         inode = dentry->d_inode;
1542
1543         if (stream_idx == 0)
1544                 stream_id = 0;
1545         else
1546                 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
1547
1548         /* The file resource may be in the staging directory (read-write mounts
1549          * only) or in the WIM.  If it's in the staging directory, we need to
1550          * open a native file descriptor for the corresponding file.  Otherwise,
1551          * we can read the file resource directly from the WIM file if we are
1552          * opening it read-only, but we need to extract the resource to the
1553          * staging directory if we are opening it writable. */
1554
1555         if (flags_writable(fi->flags) &&
1556             (!lte || lte->resource_location != RESOURCE_IN_STAGING_FILE)) {
1557                 u64 size = (lte) ? wim_resource_size(lte) : 0;
1558                 ret = extract_resource_to_staging_dir(inode, stream_id,
1559                                                       &lte, size, ctx);
1560                 if (ret != 0)
1561                         return ret;
1562         }
1563
1564         ret = alloc_wimlib_fd(inode, stream_id, lte, &fd,
1565                               wimfs_ctx_readonly(ctx));
1566         if (ret != 0)
1567                 return ret;
1568
1569         if (lte && lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1570                 fd->staging_fd = open(lte->staging_file_name, fi->flags);
1571                 if (fd->staging_fd == -1) {
1572                         int errno_save = errno;
1573                         close_wimlib_fd(fd);
1574                         return -errno_save;
1575                 }
1576         }
1577         fi->fh = (uintptr_t)fd;
1578         return 0;
1579 }
1580
1581 /* Opens a directory. */
1582 static int wimfs_opendir(const char *path, struct fuse_file_info *fi)
1583 {
1584         struct inode *inode;
1585         int ret;
1586         struct wimlib_fd *fd = NULL;
1587         struct wimfs_context *ctx = wimfs_get_context();
1588         WIMStruct *w = ctx->wim;
1589
1590         inode = wim_pathname_to_inode(w, path);
1591         if (!inode)
1592                 return -ENOENT;
1593         if (!inode_is_directory(inode))
1594                 return -ENOTDIR;
1595         ret = alloc_wimlib_fd(inode, 0, NULL, &fd, wimfs_ctx_readonly(ctx));
1596         fi->fh = (uintptr_t)fd;
1597         return ret;
1598 }
1599
1600
1601 /*
1602  * Read data from a file in the WIM or in the staging directory.
1603  */
1604 static int wimfs_read(const char *path, char *buf, size_t size,
1605                       off_t offset, struct fuse_file_info *fi)
1606 {
1607         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1608         ssize_t ret;
1609
1610         if (!fd)
1611                 return -EBADF;
1612
1613         if (!fd->f_lte) /* Empty stream with no lookup table entry */
1614                 return 0;
1615
1616         if (fd->f_lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1617                 /* Read from staging file */
1618
1619                 wimlib_assert(fd->f_lte->staging_file_name);
1620                 wimlib_assert(fd->staging_fd != -1);
1621
1622                 DEBUG("Seek to offset %zu", offset);
1623
1624                 if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1625                         return -errno;
1626                 ret = read(fd->staging_fd, buf, size);
1627                 if (ret == -1)
1628                         return -errno;
1629                 return ret;
1630         } else {
1631                 /* Read from WIM */
1632                 u64 res_size = wim_resource_size(fd->f_lte);
1633                 if (offset > res_size)
1634                         return -EOVERFLOW;
1635                 size = min(size, res_size - offset);
1636                 if (read_wim_resource(fd->f_lte, (u8*)buf,
1637                                       size, offset,
1638                                       WIMLIB_RESOURCE_FLAG_MULTITHREADED) != 0)
1639                         return -EIO;
1640                 return size;
1641         }
1642 }
1643
1644 struct fill_params {
1645         void *buf;
1646         fuse_fill_dir_t filler;
1647 };
1648
1649 static int dentry_fuse_fill(struct dentry *dentry, void *arg)
1650 {
1651         struct fill_params *fill_params = arg;
1652         return fill_params->filler(fill_params->buf, dentry->file_name_utf8,
1653                                    NULL, 0);
1654 }
1655
1656 /* Fills in the entries of the directory specified by @path using the
1657  * FUSE-provided function @filler.  */
1658 static int wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
1659                          off_t offset, struct fuse_file_info *fi)
1660 {
1661         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1662         struct inode *inode;
1663
1664         if (!fd)
1665                 return -EBADF;
1666
1667         inode = fd->f_inode;
1668
1669         struct fill_params fill_params = {
1670                 .buf = buf,
1671                 .filler = filler,
1672         };
1673
1674         filler(buf, ".", NULL, 0);
1675         filler(buf, "..", NULL, 0);
1676
1677         return for_dentry_in_rbtree(inode->children.rb_node,
1678                                     dentry_fuse_fill, &fill_params);
1679 }
1680
1681
1682 static int wimfs_readlink(const char *path, char *buf, size_t buf_len)
1683 {
1684         struct wimfs_context *ctx = wimfs_get_context();
1685         struct inode *inode = wim_pathname_to_inode(ctx->wim, path);
1686         int ret;
1687         if (!inode)
1688                 return -ENOENT;
1689         if (!inode_is_symlink(inode))
1690                 return -EINVAL;
1691
1692         ret = inode_readlink(inode, buf, buf_len, ctx->wim,
1693                              WIMLIB_RESOURCE_FLAG_MULTITHREADED);
1694         if (ret > 0)
1695                 ret = 0;
1696         return ret;
1697 }
1698
1699 /* Close a file. */
1700 static int wimfs_release(const char *path, struct fuse_file_info *fi)
1701 {
1702         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1703         return close_wimlib_fd(fd);
1704 }
1705
1706 /* Close a directory */
1707 static int wimfs_releasedir(const char *path, struct fuse_file_info *fi)
1708 {
1709         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1710         return close_wimlib_fd(fd);
1711 }
1712
1713 #ifdef ENABLE_XATTR
1714 /* Remove an alternate data stream through the XATTR interface */
1715 static int wimfs_removexattr(const char *path, const char *name)
1716 {
1717         struct inode *inode;
1718         struct ads_entry *ads_entry;
1719         u16 ads_idx;
1720         struct wimfs_context *ctx = wimfs_get_context();
1721
1722         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1723                 return -ENOTSUP;
1724
1725         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1726                 return -ENOATTR;
1727         name += 5;
1728
1729         inode = wim_pathname_to_inode(ctx->wim, path);
1730         if (!inode)
1731                 return -ENOENT;
1732
1733         ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
1734         if (!ads_entry)
1735                 return -ENOATTR;
1736         inode_remove_ads(inode, ads_idx, ctx->wim->lookup_table);
1737         return 0;
1738 }
1739 #endif
1740
1741 /* Renames a file or directory.  See rename (3) */
1742 static int wimfs_rename(const char *from, const char *to)
1743 {
1744         struct dentry *src;
1745         struct dentry *dst;
1746         struct dentry *parent_of_dst;
1747         char *file_name_utf16 = NULL, *file_name_utf8 = NULL;
1748         u16 file_name_utf16_len, file_name_utf8_len;
1749         WIMStruct *w = wimfs_get_WIMStruct();
1750         int ret;
1751
1752         /* This rename() implementation currently only supports actual files
1753          * (not alternate data streams) */
1754
1755         src = get_dentry(w, from);
1756         if (!src)
1757                 return -ENOENT;
1758
1759         dst = get_dentry(w, to);
1760
1761         ret = get_names(&file_name_utf16, &file_name_utf8,
1762                         &file_name_utf16_len, &file_name_utf8_len,
1763                         path_basename(to));
1764         if (ret != 0)
1765                 return -ENOMEM;
1766
1767         if (dst) {
1768                 /* Destination file exists */
1769
1770                 if (src == dst) /* Same file */
1771                         return 0;
1772
1773                 if (!dentry_is_directory(src)) {
1774                         /* Cannot rename non-directory to directory. */
1775                         if (dentry_is_directory(dst))
1776                                 return -EISDIR;
1777                 } else {
1778                         /* Cannot rename directory to a non-directory or a non-empty
1779                          * directory */
1780                         if (!dentry_is_directory(dst))
1781                                 return -ENOTDIR;
1782                         if (inode_has_children(dst->d_inode))
1783                                 return -ENOTEMPTY;
1784                 }
1785                 parent_of_dst = dst->parent;
1786                 remove_dentry(dst, w->lookup_table);
1787         } else {
1788                 /* Destination does not exist */
1789                 parent_of_dst = get_parent_dentry(w, to);
1790                 if (!parent_of_dst)
1791                         return -ENOENT;
1792
1793                 if (!dentry_is_directory(parent_of_dst))
1794                         return -ENOTDIR;
1795         }
1796
1797         FREE(src->file_name);
1798         FREE(src->file_name_utf8);
1799         src->file_name          = file_name_utf16;
1800         src->file_name_utf8     = file_name_utf8;
1801         src->file_name_len      = file_name_utf16_len;
1802         src->file_name_utf8_len = file_name_utf8_len;
1803
1804         unlink_dentry(src);
1805         dentry_add_child(parent_of_dst, src);
1806         return 0;
1807 }
1808
1809 /* Remove a directory */
1810 static int wimfs_rmdir(const char *path)
1811 {
1812         struct dentry *dentry;
1813         WIMStruct *w = wimfs_get_WIMStruct();
1814
1815         dentry = get_dentry(w, path);
1816         if (!dentry)
1817                 return -ENOENT;
1818
1819         if (!dentry_is_empty_directory(dentry))
1820                 return -ENOTEMPTY;
1821
1822         remove_dentry(dentry, w->lookup_table);
1823         return 0;
1824 }
1825
1826 #ifdef ENABLE_XATTR
1827 /* Write an alternate data stream through the XATTR interface */
1828 static int wimfs_setxattr(const char *path, const char *name,
1829                           const char *value, size_t size, int flags)
1830 {
1831         struct ads_entry *existing_ads_entry;
1832         struct ads_entry *new_ads_entry;
1833         struct lookup_table_entry *existing_lte;
1834         struct lookup_table_entry *lte;
1835         struct inode *inode;
1836         u8 value_hash[SHA1_HASH_SIZE];
1837         u16 ads_idx;
1838         struct wimfs_context *ctx = wimfs_get_context();
1839
1840         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1841                 return -ENOTSUP;
1842
1843         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1844                 return -ENOATTR;
1845         name += 5;
1846
1847         inode = wim_pathname_to_inode(ctx->wim, path);
1848         if (!inode)
1849                 return -ENOENT;
1850
1851         existing_ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
1852         if (existing_ads_entry) {
1853                 if (flags & XATTR_CREATE)
1854                         return -EEXIST;
1855                 inode_remove_ads(inode, ads_idx, ctx->wim->lookup_table);
1856         } else {
1857                 if (flags & XATTR_REPLACE)
1858                         return -ENOATTR;
1859         }
1860         new_ads_entry = inode_add_ads(inode, name);
1861         if (!new_ads_entry)
1862                 return -ENOMEM;
1863
1864         sha1_buffer((const u8*)value, size, value_hash);
1865
1866         existing_lte = __lookup_resource(ctx->wim->lookup_table, value_hash);
1867
1868         if (existing_lte) {
1869                 lte = existing_lte;
1870                 lte->refcnt++;
1871         } else {
1872                 u8 *value_copy;
1873                 lte = new_lookup_table_entry();
1874                 if (!lte)
1875                         return -ENOMEM;
1876                 value_copy = MALLOC(size);
1877                 if (!value_copy) {
1878                         FREE(lte);
1879                         return -ENOMEM;
1880                 }
1881                 memcpy(value_copy, value, size);
1882                 lte->resource_location            = RESOURCE_IN_ATTACHED_BUFFER;
1883                 lte->attached_buffer              = value_copy;
1884                 lte->resource_entry.original_size = size;
1885                 lte->resource_entry.size          = size;
1886                 lte->resource_entry.flags         = 0;
1887                 copy_hash(lte->hash, value_hash);
1888                 lookup_table_insert(ctx->wim->lookup_table, lte);
1889         }
1890         new_ads_entry->lte = lte;
1891         return 0;
1892 }
1893 #endif
1894
1895 static int wimfs_symlink(const char *to, const char *from)
1896 {
1897         struct wimfs_context *ctx = wimfs_get_context();
1898         struct dentry *dentry;
1899         int ret;
1900
1901         ret = create_dentry(ctx, from, &dentry);
1902         if (ret == 0) {
1903                 dentry->d_inode->attributes = FILE_ATTRIBUTE_REPARSE_POINT;
1904                 dentry->d_inode->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
1905                 if (inode_set_symlink(dentry->d_inode, to,
1906                                       ctx->wim->lookup_table, NULL))
1907                 {
1908                         unlink_dentry(dentry);
1909                         free_dentry(dentry);
1910                         ret = -ENOMEM;
1911                 }
1912         }
1913         return ret;
1914 }
1915
1916
1917 /* Reduce the size of a file */
1918 static int wimfs_truncate(const char *path, off_t size)
1919 {
1920         struct dentry *dentry;
1921         struct lookup_table_entry *lte;
1922         int ret;
1923         u16 stream_idx;
1924         u32 stream_id;
1925         struct inode *inode;
1926         struct wimfs_context *ctx = wimfs_get_context();
1927
1928         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1929                               &dentry, &lte, &stream_idx);
1930
1931         if (ret != 0)
1932                 return ret;
1933
1934         if (lte == NULL && size == 0)
1935                 return 0;
1936
1937         inode = dentry->d_inode;
1938         if (stream_idx == 0)
1939                 stream_id = 0;
1940         else
1941                 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
1942
1943         if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1944                 ret = truncate(lte->staging_file_name, size);
1945                 if (ret != 0)
1946                         ret = -errno;
1947         } else {
1948                 /* File in WIM.  Extract it to the staging directory, but only
1949                  * the first @size bytes of it. */
1950                 ret = extract_resource_to_staging_dir(inode, stream_id,
1951                                                       &lte, size, ctx);
1952         }
1953         return ret;
1954 }
1955
1956 /* Unlink a non-directory or alternate data stream */
1957 static int wimfs_unlink(const char *path)
1958 {
1959         struct dentry *dentry;
1960         struct lookup_table_entry *lte;
1961         int ret;
1962         u16 stream_idx;
1963         struct wimfs_context *ctx = wimfs_get_context();
1964
1965         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1966                               &dentry, &lte, &stream_idx);
1967
1968         if (ret != 0)
1969                 return ret;
1970
1971         if (stream_idx == 0)
1972                 remove_dentry(dentry, ctx->wim->lookup_table);
1973         else
1974                 inode_remove_ads(dentry->d_inode, stream_idx - 1,
1975                                  ctx->wim->lookup_table);
1976         return 0;
1977 }
1978
1979 #ifdef HAVE_UTIMENSAT
1980 /*
1981  * Change the timestamp on a file dentry.
1982  *
1983  * Note that alternate data streams do not have their own timestamps.
1984  */
1985 static int wimfs_utimens(const char *path, const struct timespec tv[2])
1986 {
1987         struct dentry *dentry;
1988         struct inode *inode;
1989         WIMStruct *w = wimfs_get_WIMStruct();
1990
1991         dentry = get_dentry(w, path);
1992         if (!dentry)
1993                 return -ENOENT;
1994         inode = dentry->d_inode;
1995
1996         if (tv[0].tv_nsec != UTIME_OMIT) {
1997                 if (tv[0].tv_nsec == UTIME_NOW)
1998                         inode->last_access_time = get_wim_timestamp();
1999                 else
2000                         inode->last_access_time = timespec_to_wim_timestamp(&tv[0]);
2001         }
2002         if (tv[1].tv_nsec != UTIME_OMIT) {
2003                 if (tv[1].tv_nsec == UTIME_NOW)
2004                         inode->last_write_time = get_wim_timestamp();
2005                 else
2006                         inode->last_write_time = timespec_to_wim_timestamp(&tv[1]);
2007         }
2008         return 0;
2009 }
2010 #else
2011 static int wimfs_utime(const char *path, struct utimbuf *times)
2012 {
2013         struct dentry *dentry;
2014         struct inode *inode;
2015         WIMStruct *w = wimfs_get_WIMStruct();
2016
2017         dentry = get_dentry(w, path);
2018         if (!dentry)
2019                 return -ENOENT;
2020         inode = dentry->d_inode;
2021
2022         inode->last_write_time = unix_timestamp_to_wim(times->modtime);
2023         inode->last_access_time = unix_timestamp_to_wim(times->actime);
2024         return 0;
2025 }
2026 #endif
2027
2028 /* Writes to a file in the WIM filesystem.
2029  * It may be an alternate data stream, but here we don't even notice because we
2030  * just get a lookup table entry. */
2031 static int wimfs_write(const char *path, const char *buf, size_t size,
2032                        off_t offset, struct fuse_file_info *fi)
2033 {
2034         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
2035         int ret;
2036         u64 now;
2037
2038         if (!fd)
2039                 return -EBADF;
2040
2041         wimlib_assert(fd->f_lte);
2042         wimlib_assert(fd->f_lte->staging_file_name);
2043         wimlib_assert(fd->staging_fd != -1);
2044         wimlib_assert(fd->f_inode);
2045
2046         /* Seek to the requested position */
2047         if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
2048                 return -errno;
2049
2050         /* Write the data. */
2051         ret = write(fd->staging_fd, buf, size);
2052         if (ret == -1)
2053                 return -errno;
2054
2055         now = get_wim_timestamp();
2056         fd->f_inode->last_write_time = now;
2057         fd->f_inode->last_access_time = now;
2058         return ret;
2059 }
2060
2061 static struct fuse_operations wimfs_operations = {
2062         .access      = wimfs_access,
2063         .chmod       = wimfs_chmod,
2064         .destroy     = wimfs_destroy,
2065 #if 0
2066         .fallocate   = wimfs_fallocate,
2067 #endif
2068         .fgetattr    = wimfs_fgetattr,
2069         .ftruncate   = wimfs_ftruncate,
2070         .getattr     = wimfs_getattr,
2071 #ifdef ENABLE_XATTR
2072         .getxattr    = wimfs_getxattr,
2073 #endif
2074         .link        = wimfs_link,
2075 #ifdef ENABLE_XATTR
2076         .listxattr   = wimfs_listxattr,
2077 #endif
2078         .mkdir       = wimfs_mkdir,
2079         .mknod       = wimfs_mknod,
2080         .open        = wimfs_open,
2081         .opendir     = wimfs_opendir,
2082         .read        = wimfs_read,
2083         .readdir     = wimfs_readdir,
2084         .readlink    = wimfs_readlink,
2085         .release     = wimfs_release,
2086         .releasedir  = wimfs_releasedir,
2087 #ifdef ENABLE_XATTR
2088         .removexattr = wimfs_removexattr,
2089 #endif
2090         .rename      = wimfs_rename,
2091         .rmdir       = wimfs_rmdir,
2092 #ifdef ENABLE_XATTR
2093         .setxattr    = wimfs_setxattr,
2094 #endif
2095         .symlink     = wimfs_symlink,
2096         .truncate    = wimfs_truncate,
2097         .unlink      = wimfs_unlink,
2098 #ifdef HAVE_UTIMENSAT
2099         .utimens     = wimfs_utimens,
2100 #else
2101         .utime       = wimfs_utime,
2102 #endif
2103         .write       = wimfs_write,
2104
2105 #if FUSE_MAJOR_VERSION > 2 || (FUSE_MAJOR_VERSION == 2 && FUSE_MINOR_VERSION >= 8)
2106         .flag_nullpath_ok = 1,
2107 #endif
2108 #if FUSE_MAJOR_VERSION > 2 || (FUSE_MAJOR_VERSION == 2 && FUSE_MINOR_VERSION >= 9)
2109         .flag_nopath = 1,
2110         .flag_utime_omit_ok = 1,
2111 #endif
2112 };
2113
2114
2115 /* Mounts an image from a WIM file. */
2116 WIMLIBAPI int wimlib_mount_image(WIMStruct *wim, int image, const char *dir,
2117                                  int mount_flags, WIMStruct **additional_swms,
2118                                  unsigned num_additional_swms,
2119                                  const char *staging_dir)
2120 {
2121         int argc = 0;
2122         char *argv[16];
2123         int ret;
2124         char *dir_copy;
2125         struct lookup_table *joined_tab, *wim_tab_save;
2126         struct image_metadata *imd;
2127         struct wimfs_context ctx;
2128         struct hlist_node *cur_node;
2129         struct inode *inode;
2130
2131         DEBUG("Mount: wim = %p, image = %d, dir = %s, flags = %d, ",
2132               wim, image, dir, mount_flags);
2133
2134         if (!wim || !dir)
2135                 return WIMLIB_ERR_INVALID_PARAM;
2136
2137         ret = verify_swm_set(wim, additional_swms, num_additional_swms);
2138         if (ret != 0)
2139                 return ret;
2140
2141         if ((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) && (wim->hdr.total_parts != 1)) {
2142                 ERROR("Cannot mount a split WIM read-write");
2143                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2144         }
2145
2146         if (num_additional_swms) {
2147                 ret = new_joined_lookup_table(wim, additional_swms,
2148                                               num_additional_swms,
2149                                               &joined_tab);
2150                 if (ret != 0)
2151                         return ret;
2152                 wim_tab_save = wim->lookup_table;
2153                 wim->lookup_table = joined_tab;
2154         }
2155
2156         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2157                 ret = wim_run_full_verifications(wim);
2158                 if (ret != 0)
2159                         goto out;
2160         }
2161
2162         ret = select_wim_image(wim, image);
2163
2164         if (ret != 0)
2165                 goto out;
2166
2167         imd = &wim->image_metadata[image - 1];
2168
2169         DEBUG("Selected image %d", image);
2170
2171         if (imd->root_dentry->refcnt != 1) {
2172                 ERROR("Cannot mount image that was just exported with "
2173                       "wimlib_export_image()");
2174                 ret = WIMLIB_ERR_INVALID_PARAM;
2175                 goto out;
2176         }
2177
2178         if (imd->modified) {
2179                 ERROR("Cannot mount image that was added "
2180                       "with wimlib_add_image()");
2181                 ret = WIMLIB_ERR_INVALID_PARAM;
2182                 goto out;
2183         }
2184
2185         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2186                 ret = lock_wim(wim->fp, wim->filename);
2187                 if (ret != 0)
2188                         goto out;
2189         }
2190
2191         if (!(mount_flags & (WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
2192                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
2193                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)))
2194                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
2195
2196
2197         DEBUG("Initializing struct wimfs_context");
2198         init_wimfs_context(&ctx);
2199         ctx.wim = wim;
2200         ctx.mount_flags = mount_flags;
2201
2202         if (mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
2203                 ctx.default_lookup_flags = LOOKUP_FLAG_ADS_OK;
2204
2205         DEBUG("Unlinking message queues in case they already exist");
2206         ret = set_message_queue_names(&ctx, dir);
2207         if (ret != 0)
2208                 goto out;
2209         unlink_message_queues(&ctx);
2210
2211         DEBUG("Preparing arguments to fuse_main()");
2212
2213         dir_copy = STRDUP(dir);
2214         if (!dir_copy)
2215                 goto out_free_message_queue_names;
2216
2217         argv[argc++] = "imagex";
2218         argv[argc++] = dir_copy;
2219
2220         /* disable multi-threaded operation for read-write mounts */
2221         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2222                 argv[argc++] = "-s";
2223
2224         if (mount_flags & WIMLIB_MOUNT_FLAG_DEBUG)
2225                 argv[argc++] = "-d";
2226
2227         /*
2228          * We provide the use_ino option because we are going to assign inode
2229          * numbers oursides.  The inodes will be given unique numbers in the
2230          * assign_inode_numbers() function, and the static variable @next_ino is
2231          * set to the next available inode number.
2232          */
2233         char optstring[256] =
2234                 "use_ino"
2235                 ",subtype=wimfs"
2236                 ",attr_timeout=0"
2237 #if FUSE_MAJOR_VERSION > 2 || (FUSE_MAJOR_VERSION == 2 && FUSE_MINOR_VERSION >= 8)
2238                 ",hard_remove"
2239 #endif
2240                 ;
2241         argv[argc++] = "-o";
2242         argv[argc++] = optstring;
2243         if ((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
2244                 /* Read-write mount.  Make the staging directory */
2245                 ret = make_staging_dir(&ctx, staging_dir);
2246                 if (ret != 0)
2247                         goto out_free_dir_copy;
2248         } else {
2249                 /* Read-only mount */
2250                 strcat(optstring, ",ro");
2251         }
2252         argv[argc] = NULL;
2253
2254 #ifdef ENABLE_DEBUG
2255         {
2256                 int i;
2257                 DEBUG("FUSE command line (argc = %d): ", argc);
2258                 for (i = 0; i < argc; i++) {
2259                         fputs(argv[i], stdout);
2260                         putchar(' ');
2261                 }
2262                 putchar('\n');
2263                 fflush(stdout);
2264         }
2265 #endif
2266
2267         /* Mark dentry tree as modified if read-write mount. */
2268         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2269                 imd->modified = 1;
2270                 imd->has_been_mounted_rw = 1;
2271         }
2272
2273         /* Resolve the lookup table entries for every inode in the image, and
2274          * assign inode numbers */
2275         DEBUG("Resolving lookup table entries and assigning inode numbers");
2276
2277         ctx.next_ino = 1;
2278         hlist_for_each_entry(inode, cur_node, &imd->inode_list, hlist) {
2279                 inode_resolve_ltes(inode, wim->lookup_table);
2280                 inode->ino = ctx.next_ino++;
2281         }
2282         /*ctx.next_ino = assign_inode_numbers(&imd->inode_list);*/
2283         DEBUG("(next_ino = %"PRIu64")", ctx.next_ino);
2284
2285         DEBUG("Calling fuse_main()");
2286
2287         ret = fuse_main(argc, argv, &wimfs_operations, &ctx);
2288
2289         DEBUG("Returned from fuse_main() (ret = %d)", ret);
2290         if (ret)
2291                 ret = WIMLIB_ERR_FUSE;
2292 out_free_dir_copy:
2293         FREE(dir_copy);
2294 out_free_message_queue_names:
2295         free_message_queue_names(&ctx);
2296 out:
2297         if (num_additional_swms) {
2298                 free_lookup_table(wim->lookup_table);
2299                 wim->lookup_table = wim_tab_save;
2300         }
2301         return ret;
2302 }
2303
2304 /*
2305  * Unmounts the WIM file that was previously mounted on @dir by using
2306  * wimlib_mount_image().
2307  */
2308 WIMLIBAPI int wimlib_unmount_image(const char *dir, int unmount_flags,
2309                                    wimlib_progress_func_t progress_func)
2310 {
2311         int ret;
2312         struct wimfs_context ctx;
2313
2314         init_wimfs_context(&ctx);
2315
2316         ret = set_message_queue_names(&ctx, dir);
2317         if (ret != 0)
2318                 goto out;
2319
2320         ret = open_message_queues(&ctx, false);
2321         if (ret != 0)
2322                 goto out_free_message_queue_names;
2323
2324         ret = send_unmount_request(&ctx, unmount_flags);
2325         if (ret != 0)
2326                 goto out_close_message_queues;
2327
2328         ret = execute_fusermount(dir);
2329         if (ret != 0)
2330                 goto out_close_message_queues;
2331         ret = receive_unmount_response(&ctx);
2332 out_close_message_queues:
2333         close_message_queues(&ctx);
2334 out_free_message_queue_names:
2335         free_message_queue_names(&ctx);
2336 out:
2337         return ret;
2338 }
2339
2340 #else /* WITH_FUSE */
2341
2342
2343 static inline int mount_unsupported_error()
2344 {
2345         ERROR("wimlib was compiled with --without-fuse, which disables support "
2346               "for mounting WIMs.");
2347         return WIMLIB_ERR_UNSUPPORTED;
2348 }
2349
2350 WIMLIBAPI int wimlib_unmount_image(const char *dir, int unmount_flags,
2351                                    wimlib_progress_func_t progress_func)
2352 {
2353         return mount_unsupported_error();
2354 }
2355
2356 WIMLIBAPI int wimlib_mount_image(WIMStruct *wim_p, int image, const char *dir,
2357                                  int mount_flags, WIMStruct **additional_swms,
2358                                  unsigned num_additional_swms,
2359                                  const char *staging_dir)
2360 {
2361         return mount_unsupported_error();
2362 }
2363
2364 #endif /* WITH_FUSE */