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