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