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