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