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