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