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