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