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