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