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