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