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