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