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