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