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