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