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