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