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