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