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