]> wimlib.net Git - wimlib/blob - src/mount.c
wimlib_mount(): Refuse to mount split wim read-write
[wimlib] / src / mount.c
1 /*
2  * mount.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 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 "sha1.h"
34 #include "lookup_table.h"
35 #include "xml.h"
36 #include "io.h"
37 #include "timestamp.h"
38 #include <limits.h>
39 #include <stdlib.h>
40 #include <unistd.h>
41 #include <sys/wait.h>
42 #define FUSE_USE_VERSION 26
43 #include <errno.h>
44 #include <string.h>
45 #include <sys/time.h>
46 #include <fuse.h>
47 #include <ftw.h>
48 #include <mqueue.h>
49 #include <utime.h>
50
51 #ifdef ENABLE_XATTR
52 #include <attr/xattr.h>
53 #endif
54
55 /* File descriptor to a file open on the WIM filesystem. */
56 struct wimlib_fd {
57         struct inode *f_inode;
58         struct lookup_table_entry *f_lte;
59         int staging_fd;
60         u16 idx;
61         u32 stream_id;
62 };
63
64 struct wimfs_context {
65         /* The WIMStruct for the mounted WIM. */
66         WIMStruct *wim;
67
68         /* Working directory when `imagex mount' is run. */
69         char *working_directory;
70
71         /* Name of the staging directory for a read-write mount.  Whenever a new file is
72          * created, it is done so in the staging directory.  Furthermore, whenever a
73          * file in the WIM is modified, it is extracted to the staging directory.  If
74          * changes are commited when the WIM is unmounted, the file resources are merged
75          * in from the staging directory when writing the new WIM. */
76         char *staging_dir_name;
77         size_t staging_dir_name_len;
78
79         /* Flags passed to wimlib_mount(). */
80         int mount_flags;
81
82         /* Next inode number to be assigned. */
83         u64 next_ino;
84
85         /* List of lookup table entries in the staging directory */
86         struct list_head staging_list;
87
88         /* Name and message queue descriptors for message queues between the filesystem
89          * daemon process and the unmount process.  These are used when the filesystem
90          * is unmounted and the process running wimlib_mount() (i.e. the `imagex
91          * unmount' command) needs to communicate with the filesystem daemon running
92          * fuse_main() (i.e. that spawned by the `imagex mount' or `imagex mountrw'
93          * commands */
94         char *unmount_to_daemon_mq_name;
95         char *daemon_to_unmount_mq_name;
96         mqd_t unmount_to_daemon_mq;
97         mqd_t daemon_to_unmount_mq;
98 };
99
100 static void init_wimfs_context(struct wimfs_context *ctx)
101 {
102         memset(ctx, 0, sizeof(*ctx));
103         ctx->unmount_to_daemon_mq = (mqd_t)-1;
104         ctx->daemon_to_unmount_mq = (mqd_t)-1;
105         INIT_LIST_HEAD(&ctx->staging_list);
106 }
107
108 static inline struct wimfs_context *wimfs_get_context()
109 {
110         return (struct wimfs_context*)fuse_get_context()->private_data;
111 }
112
113 static inline WIMStruct *wimfs_get_WIMStruct()
114 {
115         return wimfs_get_context()->wim;
116 }
117
118 static inline int get_lookup_flags(const struct wimfs_context *ctx)
119 {
120         if (ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
121                 return LOOKUP_FLAG_ADS_OK;
122         else
123                 return 0;
124 }
125
126 /* Returns nonzero if write permission is requested on the file open flags */
127 static inline int flags_writable(int open_flags)
128 {
129         return open_flags & (O_RDWR | O_WRONLY);
130 }
131
132 /*
133  * Allocate a file descriptor for a stream.
134  *
135  * @inode:      inode containing the stream we're opening
136  * @stream_id:  ID of the stream we're opening
137  * @lte:        Lookup table entry for the stream (may be NULL)
138  * @fd_ret:     Return the allocated file descriptor if successful.
139  *
140  * Return 0 iff successful or error code if unsuccessful.
141  */
142 static int alloc_wimlib_fd(struct inode *inode,
143                            u32 stream_id,
144                            struct lookup_table_entry *lte,
145                            struct wimlib_fd **fd_ret)
146 {
147         static const u16 fds_per_alloc = 8;
148         static const u16 max_fds = 0xffff;
149         int ret;
150
151         pthread_mutex_lock(&inode->i_mutex);
152
153         DEBUG("Allocating fd for stream ID %u from inode %lx (open = %u, allocated = %u)",
154               stream_id, inode->ino, inode->num_opened_fds,
155               inode->num_allocated_fds);
156
157         if (inode->num_opened_fds == inode->num_allocated_fds) {
158                 struct wimlib_fd **fds;
159                 u16 num_new_fds;
160
161                 if (inode->num_allocated_fds == max_fds) {
162                         ret = -EMFILE;
163                         goto out;
164                 }
165                 num_new_fds = min(fds_per_alloc,
166                                   max_fds - inode->num_allocated_fds);
167
168                 fds = REALLOC(inode->fds,
169                               (inode->num_allocated_fds + num_new_fds) *
170                                 sizeof(inode->fds[0]));
171                 if (!fds) {
172                         ret = -ENOMEM;
173                         goto out;
174                 }
175                 memset(&fds[inode->num_allocated_fds], 0,
176                        num_new_fds * sizeof(fds[0]));
177                 inode->fds = fds;
178                 inode->num_allocated_fds += num_new_fds;
179         }
180         for (u16 i = 0; ; i++) {
181                 if (!inode->fds[i]) {
182                         struct wimlib_fd *fd = CALLOC(1, sizeof(*fd));
183                         if (!fd) {
184                                 ret = -ENOMEM;
185                                 break;
186                         }
187                         fd->f_inode    = inode;
188                         fd->f_lte      = lte;
189                         fd->staging_fd = -1;
190                         fd->idx        = i;
191                         fd->stream_id  = stream_id;
192                         *fd_ret        = fd;
193                         inode->fds[i]  = fd;
194                         inode->num_opened_fds++;
195                         if (lte)
196                                 atomic_inc(&lte->num_opened_fds);
197                         DEBUG("Allocated fd (idx = %u)", fd->idx);
198                         ret = 0;
199                         break;
200                 }
201         }
202 out:
203         pthread_mutex_unlock(&inode->i_mutex);
204         return ret;
205 }
206
207 static void inode_put_fd(struct inode *inode, struct wimlib_fd *fd)
208 {
209         wimlib_assert(fd != NULL);
210         wimlib_assert(inode != NULL);
211
212         pthread_mutex_lock(&inode->i_mutex);
213
214         wimlib_assert(fd->f_inode == inode);
215         wimlib_assert(inode->num_opened_fds != 0);
216         wimlib_assert(fd->idx < inode->num_allocated_fds);
217         wimlib_assert(inode->fds[fd->idx] == fd);
218
219         inode->fds[fd->idx] = NULL;
220         FREE(fd);
221         if (--inode->num_opened_fds == 0 && inode->link_count == 0) {
222                 pthread_mutex_unlock(&inode->i_mutex);
223                 free_inode(inode);
224         } else {
225                 pthread_mutex_unlock(&inode->i_mutex);
226         }
227 }
228
229 static int lte_put_fd(struct lookup_table_entry *lte, struct wimlib_fd *fd)
230 {
231         wimlib_assert(fd != NULL);
232         wimlib_assert(fd->f_lte == lte);
233
234         if (!lte) /* Empty stream with no lookup table entry */
235                 return 0;
236
237         /* Close staging file descriptor if needed. */
238
239         if (lte->resource_location == RESOURCE_IN_STAGING_FILE
240              && fd->staging_fd != -1)
241         {
242                 if (close(fd->staging_fd) != 0) {
243                         ERROR_WITH_ERRNO("Failed to close staging file");
244                         return -errno;
245                 }
246         }
247         lte_decrement_num_opened_fds(lte);
248         return 0;
249 }
250
251 /* Close a file descriptor. */
252 static int close_wimlib_fd(struct wimlib_fd *fd)
253 {
254         int ret;
255         wimlib_assert(fd != NULL);
256         DEBUG("Closing fd (inode = %lu, opened = %u, allocated = %u)",
257               fd->f_inode->ino, fd->f_inode->num_opened_fds,
258               fd->f_inode->num_allocated_fds);
259         ret = lte_put_fd(fd->f_lte, fd);
260         if (ret != 0)
261                 return ret;
262
263         inode_put_fd(fd->f_inode, fd);
264         return 0;
265 }
266
267 /* Remove a dentry; i.e. remove a reference to the corresponding inode.
268  *
269  * If there are no remaining references to the inode either through dentries or
270  * open file descriptors, the inode is freed.  Otherwise, the inode is not
271  * removed, but the dentry is unlinked and freed.
272  *
273  * Either way, all lookup table entries referenced by the inode have their
274  * reference count decremented.  If a lookup table entry has no open file
275  * descriptors and no references remaining, it is freed, and the staging file is
276  * unlinked.
277  */
278 static void remove_dentry(struct dentry *dentry,
279                           struct lookup_table *lookup_table)
280 {
281         struct inode *inode = dentry->d_inode;
282         struct lookup_table_entry *lte;
283         unsigned i;
284
285         for (i = 0; i <= inode->num_ads; i++) {
286                 lte = inode_stream_lte_resolved(inode, i);
287                 if (lte)
288                         lte_decrement_refcnt(lte, lookup_table);
289         }
290         unlink_dentry(dentry);
291         put_dentry(dentry);
292 }
293
294 /* Creates a new staging file and returns its file descriptor opened for
295  * writing.
296  *
297  * @name_ret: A location into which the a pointer to the newly allocated name of
298  *                      the staging file is stored.
299  * @return:  The file descriptor for the new file.  Returns -1 and sets errno on
300  *              error, for any reason possible from the creat() function.
301  */
302 static int create_staging_file(char **name_ret, int open_flags,
303                                struct wimfs_context *ctx)
304 {
305         size_t name_len;
306         char *name;
307         struct stat stbuf;
308         int fd;
309         int errno_save;
310
311         name_len = ctx->staging_dir_name_len + 1 + SHA1_HASH_SIZE;
312         name = MALLOC(name_len + 1);
313         if (!name) {
314                 errno = ENOMEM;
315                 return -1;
316         }
317
318         do {
319
320                 memcpy(name, ctx->staging_dir_name, ctx->staging_dir_name_len);
321                 name[ctx->staging_dir_name_len] = '/';
322                 randomize_char_array_with_alnum(name + ctx->staging_dir_name_len + 1,
323                                                 SHA1_HASH_SIZE);
324                 name[name_len] = '\0';
325
326
327         /* Just in case, verify that the randomly generated name doesn't name an
328          * existing file, and try again if so  */
329         } while (stat(name, &stbuf) == 0);
330
331         if (errno != ENOENT)
332                 /* other error! */
333                 return -1;
334
335         /* doesn't exist--- ok */
336
337         DEBUG("Creating staging file `%s'", name);
338
339         fd = open(name, open_flags | O_CREAT | O_TRUNC, 0600);
340         if (fd == -1) {
341                 errno_save = errno;
342                 FREE(name);
343                 errno = errno_save;
344         } else {
345                 *name_ret = name;
346         }
347         return fd;
348 }
349
350 /*
351  * Extract a WIM resource to the staging directory.
352  *
353  * @inode:  Inode that contains the stream we are extracting
354  *
355  * @stream_id: Identifier for the stream (it stays constant even if the indices
356  * of the stream entries are changed)
357  *
358  * @lte: Pointer to pointer to the lookup table entry for the stream we need to
359  * extract, or NULL if there was no lookup table entry present for the stream
360  *
361  * @size:  Number of bytes of the stream we want to extract (this supports the
362  * wimfs_truncate() function).
363  */
364 static int extract_resource_to_staging_dir(struct inode *inode,
365                                            u32 stream_id,
366                                            struct lookup_table_entry **lte,
367                                            off_t size,
368                                            struct wimfs_context *ctx)
369 {
370         char *staging_file_name;
371         int ret;
372         int fd;
373         struct lookup_table_entry *old_lte, *new_lte;
374
375         DEBUG("Extracting resource to staging dir: inode %"PRIu64", "
376               "stream id %"PRIu32, inode->ino, stream_id);
377
378         old_lte = *lte;
379         fd = create_staging_file(&staging_file_name, O_WRONLY, ctx);
380         if (fd == -1)
381                 return -errno;
382
383         if (old_lte)
384                 ret = extract_wim_resource_to_fd(old_lte, fd, size);
385         else
386                 ret = 0;
387         if (ret != 0 || close(fd) != 0) {
388                 if (errno != 0)
389                         ret = -errno;
390                 else
391                         ret = -EIO;
392                 close(fd);
393                 goto out_delete_staging_file;
394         }
395
396         if (old_lte && inode->link_count == old_lte->refcnt) {
397                 /* The reference count of the existing lookup table
398                  * entry is the same as the link count of the inode that
399                  * contains the stream we're opening.  Therefore, ALL
400                  * the references to the lookup table entry correspond
401                  * to the stream we're trying to extract, so the lookup
402                  * table entry can be re-used.  */
403                 DEBUG("Re-using lookup table entry");
404                 lookup_table_unlink(ctx->wim->lookup_table, old_lte);
405                 new_lte = old_lte;
406         } else {
407                 if (old_lte) {
408                         /* There's an existing lookup table entry, but its
409                          * reference count is creater than the link count for
410                          * the inode containing a stream we're opening.
411                          * Therefore, we need to split the lookup table entry.
412                          * */
413                         wimlib_assert(old_lte->refcnt > inode->link_count);
414                         DEBUG("Splitting lookup table entry "
415                               "(inode->link_count = %u, old_lte->refcnt = %u)",
416                               inode->link_count, old_lte->refcnt);
417
418                 }
419
420                 new_lte = new_lookup_table_entry();
421                 if (!new_lte) {
422                         ret = -ENOMEM;
423                         goto out_delete_staging_file;
424                 }
425
426                 /* There may already be open file descriptors to this stream if
427                  * it's previously been opened read-only, but just now we're
428                  * opening it read-write.  Identify those file descriptors and
429                  * change their lookup table entry pointers to point to the new
430                  * lookup table entry, and open staging file descriptors for
431                  * them.
432                  *
433                  * At the same time, we need to count the number of these opened
434                  * file descriptors to the new lookup table entry.  If there's
435                  * an old lookup table entry, this number needs to be subtracted
436                  * from the fd's opened to the old entry. */
437                 for (u16 i = 0, j = 0; j < inode->num_opened_fds; i++) {
438                         struct wimlib_fd *fd = inode->fds[i];
439                         if (fd) {
440                                 if (fd->stream_id == stream_id) {
441                                         wimlib_assert(fd->f_lte == old_lte);
442                                         wimlib_assert(fd->staging_fd == -1);
443                                         fd->f_lte = new_lte;
444                                         new_lte->num_opened_fds++;
445                                         fd->staging_fd = open(staging_file_name, O_RDONLY);
446                                         if (fd->staging_fd == -1) {
447                                                 ret = -errno;
448                                                 goto out_revert_fd_changes;
449                                         }
450                                 }
451                                 j++;
452                         }
453                 }
454                 DEBUG("%hu fd's were already opened to the file we extracted",
455                       new_lte->num_opened_fds);
456                 if (old_lte) {
457                         old_lte->num_opened_fds -= new_lte->num_opened_fds;
458                         old_lte->refcnt -= inode->link_count;
459                 }
460         }
461
462         new_lte->resource_entry.original_size = size;
463         new_lte->refcnt                       = inode->link_count;
464         new_lte->resource_location            = RESOURCE_IN_STAGING_FILE;
465         new_lte->staging_file_name            = staging_file_name;
466         new_lte->lte_inode                    = inode;
467         random_hash(new_lte->hash);
468
469         if (stream_id == 0)
470                 inode->lte = new_lte;
471         else
472                 for (u16 i = 0; i < inode->num_ads; i++)
473                         if (inode->ads_entries[i].stream_id == stream_id)
474                                 inode->ads_entries[i].lte = new_lte;
475
476         lookup_table_insert(ctx->wim->lookup_table, new_lte);
477         list_add(&new_lte->staging_list, &ctx->staging_list);
478         *lte = new_lte;
479         return 0;
480 out_revert_fd_changes:
481         for (u16 i = 0, j = 0; j < new_lte->num_opened_fds; i++) {
482                 struct wimlib_fd *fd = inode->fds[i];
483                 if (fd && fd->stream_id == stream_id && fd->f_lte == new_lte) {
484                         fd->f_lte = old_lte;
485                         if (fd->staging_fd != -1) {
486                                 close(fd->staging_fd);
487                                 fd->staging_fd = -1;
488                         }
489                         j++;
490                 }
491         }
492         free_lookup_table_entry(new_lte);
493 out_delete_staging_file:
494         unlink(staging_file_name);
495         FREE(staging_file_name);
496         return ret;
497 }
498
499 /*
500  * Creates a randomly named staging directory and saves its name in the
501  * filesystem context structure.
502  */
503 static int make_staging_dir(struct wimfs_context *ctx)
504 {
505         /* XXX Give the user an option of where to stage files */
506
507         static const char prefix[] = "wimlib-staging-";
508         static const size_t prefix_len = sizeof(prefix) - 1;
509         static const size_t random_suffix_len = 10;
510
511         size_t pwd_len = strlen(ctx->working_directory);
512
513         ctx->staging_dir_name_len = pwd_len + 1 + prefix_len + random_suffix_len;
514
515         ctx->staging_dir_name = MALLOC(ctx->staging_dir_name_len + 1);
516         if (!ctx->staging_dir_name)
517                 return WIMLIB_ERR_NOMEM;
518
519         memcpy(ctx->staging_dir_name, ctx->working_directory, pwd_len);
520         ctx->staging_dir_name[pwd_len] = '/';
521         memcpy(ctx->staging_dir_name + pwd_len + 1, prefix, prefix_len);
522         randomize_char_array_with_alnum(ctx->staging_dir_name + pwd_len +
523                                         1 + prefix_len, random_suffix_len);
524         ctx->staging_dir_name[ctx->staging_dir_name_len] = '\0';
525
526         if (mkdir(ctx->staging_dir_name, 0700) != 0) {
527                 ERROR_WITH_ERRNO("Failed to create temporary directory `%s'",
528                                  ctx->staging_dir_name);
529                 FREE(ctx->staging_dir_name);
530                 ctx->staging_dir_name = NULL;
531                 return WIMLIB_ERR_MKDIR;
532         }
533         return 0;
534 }
535
536 static int remove_file_or_directory(const char *fpath, const struct stat *sb,
537                                     int typeflag, struct FTW *ftwbuf)
538 {
539         if (remove(fpath) == 0)
540                 return 0;
541         else {
542                 ERROR_WITH_ERRNO("Cannot remove `%s'", fpath);
543                 return WIMLIB_ERR_DELETE_STAGING_DIR;
544         }
545 }
546
547
548 /*
549  * Deletes the staging directory and all the files contained in it.
550  */
551 static int delete_staging_dir(struct wimfs_context *ctx)
552 {
553         int ret;
554         wimlib_assert(ctx->staging_dir_name != NULL);
555         ret = nftw(ctx->staging_dir_name, remove_file_or_directory,
556                    10, FTW_DEPTH);
557         FREE(ctx->staging_dir_name);
558         ctx->staging_dir_name = NULL;
559         return ret;
560 }
561
562
563 /* Simple function that returns the concatenation of 2 strings. */
564 static char *strcat_dup(const char *s1, const char *s2, size_t max_len)
565 {
566         size_t len = strlen(s1) + strlen(s2);
567         if (len > max_len)
568                 len = max_len;
569         char *p = MALLOC(len + 1);
570         if (!p)
571                 return NULL;
572         snprintf(p, len + 1, "%s%s", s1, s2);
573         return p;
574 }
575
576 static int set_message_queue_names(struct wimfs_context *ctx,
577                                    const char *mount_dir)
578 {
579         static const char *u2d_prefix = "/wimlib-unmount-to-daemon-mq";
580         static const char *d2u_prefix = "/wimlib-daemon-to-unmount-mq";
581         char *dir_path;
582         char *p;
583         int ret;
584
585         dir_path = realpath(mount_dir, NULL);
586         if (!dir_path) {
587                 ERROR_WITH_ERRNO("Failed to resolve path \"%s\"", mount_dir);
588                 return WIMLIB_ERR_NOTDIR;
589         }
590
591         DEBUG("Using absolute dir_path = `%s'", dir_path);
592
593
594         p = dir_path;
595         while (*p) {
596                 if (*p == '/')
597                         *p = 0xff;
598                 p++;
599         }
600
601         ctx->unmount_to_daemon_mq_name = strcat_dup(u2d_prefix, dir_path,
602                                                     NAME_MAX);
603         if (!ctx->unmount_to_daemon_mq_name) {
604                 ret = WIMLIB_ERR_NOMEM;
605                 goto out_free_dir_path;
606         }
607         ctx->daemon_to_unmount_mq_name = strcat_dup(d2u_prefix, dir_path,
608                                                     NAME_MAX);
609         if (!ctx->daemon_to_unmount_mq_name) {
610                 ret = WIMLIB_ERR_NOMEM;
611                 goto out_free_unmount_to_daemon_mq_name;
612         }
613
614         ret = 0;
615         goto out_free_dir_path;
616 out_free_unmount_to_daemon_mq_name:
617         FREE(ctx->unmount_to_daemon_mq_name);
618         ctx->unmount_to_daemon_mq_name = NULL;
619 out_free_dir_path:
620         FREE(dir_path);
621         return ret;
622 }
623
624 static void free_message_queue_names(struct wimfs_context *ctx)
625 {
626         FREE(ctx->unmount_to_daemon_mq_name);
627         FREE(ctx->daemon_to_unmount_mq_name);
628         ctx->unmount_to_daemon_mq_name = NULL;
629         ctx->daemon_to_unmount_mq_name = NULL;
630 }
631
632 /*
633  * Opens two POSIX message queue: one for sending messages from the unmount
634  * process to the daemon process, and one to go the other way.  The names of the
635  * message queues, which must be system-wide unique, are be based on the mount
636  * point.  (There of course is still a possibility of a collision if one were to
637  * unmount two identically named directories simultaneously...)
638  *
639  * @daemon specifies whether the calling process is the filesystem daemon or the
640  * unmount process.
641  */
642 static int open_message_queues(struct wimfs_context *ctx, bool daemon)
643 {
644         int flags;
645         int ret;
646
647         wimlib_assert(ctx->unmount_to_daemon_mq_name != NULL &&
648                       ctx->daemon_to_unmount_mq_name != NULL);
649
650         if (daemon)
651                 flags = O_RDONLY | O_CREAT;
652         else
653                 flags = O_WRONLY | O_CREAT;
654
655         DEBUG("Opening message queue \"%s\"", ctx->unmount_to_daemon_mq_name);
656         ctx->unmount_to_daemon_mq = mq_open(ctx->unmount_to_daemon_mq_name,
657                                             flags, 0700, NULL);
658
659         if (ctx->unmount_to_daemon_mq == (mqd_t)-1) {
660                 ERROR_WITH_ERRNO("mq_open()");
661                 ret = WIMLIB_ERR_MQUEUE;
662                 goto out;
663         }
664
665         if (daemon)
666                 flags = O_WRONLY | O_CREAT;
667         else
668                 flags = O_RDONLY | O_CREAT;
669
670         DEBUG("Opening message queue \"%s\"", ctx->daemon_to_unmount_mq_name);
671         ctx->daemon_to_unmount_mq = mq_open(ctx->daemon_to_unmount_mq_name,
672                                             flags, 0700, NULL);
673
674         if (ctx->daemon_to_unmount_mq == (mqd_t)-1) {
675                 ERROR_WITH_ERRNO("mq_open()");
676                 ret = WIMLIB_ERR_MQUEUE;
677                 goto out_close_unmount_to_daemon_mq;
678         }
679         ret = 0;
680         goto out;
681 out_close_unmount_to_daemon_mq:
682         mq_close(ctx->unmount_to_daemon_mq);
683         mq_unlink(ctx->unmount_to_daemon_mq_name);
684         ctx->unmount_to_daemon_mq = (mqd_t)-1;
685 out:
686         return ret;
687 }
688
689 /* Try to determine the maximum message size of a message queue.  The return
690  * value is the maximum message size, or a guess of 8192 bytes if it cannot be
691  * determined. */
692 static long mq_get_msgsize(mqd_t mq)
693 {
694         static const char *msgsize_max_file = "/proc/sys/fs/mqueue/msgsize_max";
695         FILE *fp;
696         struct mq_attr attr;
697         long msgsize;
698
699         if (mq_getattr(mq, &attr) == 0) {
700                 msgsize = attr.mq_msgsize;
701         } else {
702                 ERROR_WITH_ERRNO("mq_getattr()");
703                 ERROR("Attempting to read %s", msgsize_max_file);
704                 fp = fopen(msgsize_max_file, "rb");
705                 if (fp) {
706                         if (fscanf(fp, "%ld", &msgsize) != 1) {
707                                 ERROR("Assuming message size of 8192");
708                                 msgsize = 8192;
709                         }
710                         fclose(fp);
711                 } else {
712                         ERROR_WITH_ERRNO("Failed to open the file `%s'",
713                                          msgsize_max_file);
714                         ERROR("Assuming message size of 8192");
715                         msgsize = 8192;
716                 }
717         }
718         return msgsize;
719 }
720
721 static int get_mailbox(mqd_t mq, long needed_msgsize, long *msgsize_ret,
722                        char **mailbox_ret)
723 {
724         long msgsize;
725         char *mailbox;
726
727         msgsize = mq_get_msgsize(mq);
728
729         if (msgsize < needed_msgsize) {
730                 ERROR("Message queue max size must be at least %ld!",
731                       needed_msgsize);
732                 return WIMLIB_ERR_MQUEUE;
733         }
734
735         mailbox = MALLOC(msgsize);
736         if (!mailbox) {
737                 ERROR("Failed to allocate %ld bytes for mailbox", msgsize);
738                 return WIMLIB_ERR_NOMEM;
739         }
740         *msgsize_ret = msgsize;
741         *mailbox_ret = mailbox;
742         return 0;
743 }
744
745 static void unlink_message_queues(struct wimfs_context *ctx)
746 {
747         mq_unlink(ctx->unmount_to_daemon_mq_name);
748         mq_unlink(ctx->daemon_to_unmount_mq_name);
749 }
750
751 /* Closes the message queues, which are allocated in static variables */
752 static void close_message_queues(struct wimfs_context *ctx)
753 {
754         mq_close(ctx->unmount_to_daemon_mq);
755         ctx->unmount_to_daemon_mq = (mqd_t)(-1);
756         mq_close(ctx->daemon_to_unmount_mq);
757         ctx->daemon_to_unmount_mq = (mqd_t)(-1);
758         unlink_message_queues(ctx);
759 }
760
761 static int wimfs_access(const char *path, int mask)
762 {
763         /* Permissions not implemented */
764         return 0;
765 }
766
767 static int wimfs_chmod(const char *path, mode_t mask)
768 {
769         struct dentry *dentry;
770         struct wimfs_context *ctx = wimfs_get_context();
771         struct inode *inode;
772         struct stat stbuf;
773         int ret;
774
775         ret = lookup_resource(ctx->wim, path,
776                               get_lookup_flags(ctx) | LOOKUP_FLAG_DIRECTORY_OK,
777                               &dentry, NULL, NULL);
778         if (ret != 0)
779                 return ret;
780         inode = dentry->d_inode;
781         inode_to_stbuf(inode, NULL, &stbuf);
782         if (mask == stbuf.st_mode)
783                 return 0;
784         else
785                 return -EPERM;
786
787 }
788
789 static void inode_update_lte_ptr(struct inode *inode,
790                                  struct lookup_table_entry *old_lte,
791                                  struct lookup_table_entry *new_lte)
792 {
793         if (inode->lte == old_lte) {
794                 inode->lte = new_lte;
795         } else {
796                 for (unsigned i = 0; i < inode->num_ads; i++) {
797                         if (inode->ads_entries[i].lte == old_lte) {
798                                 inode->ads_entries[i].lte = new_lte;
799                                 break;
800                         }
801                 }
802         }
803 }
804
805 static int update_lte_of_staging_file(struct lookup_table_entry *lte,
806                                       struct lookup_table *table)
807 {
808         struct lookup_table_entry *duplicate_lte;
809         int ret;
810         u8 hash[SHA1_HASH_SIZE];
811         struct stat stbuf;
812
813         wimlib_assert(lte->resource_location == RESOURCE_IN_STAGING_FILE);
814         wimlib_assert(lte->staging_file_name);
815
816         ret = sha1sum(lte->staging_file_name, hash);
817         if (ret != 0)
818                 return ret;
819
820         lookup_table_unlink(table, lte);
821
822         duplicate_lte = __lookup_resource(table, hash);
823
824         if (duplicate_lte) {
825                 /* Merge duplicate lookup table entries */
826                 duplicate_lte->refcnt += lte->refcnt;
827                 list_del(&lte->staging_list);
828                 inode_update_lte_ptr(lte->lte_inode, lte, duplicate_lte);
829                 free_lookup_table_entry(lte);
830         } else {
831                 if (stat(lte->staging_file_name, &stbuf) != 0) {
832                         ERROR_WITH_ERRNO("Failed to stat `%s'", lte->staging_file_name);
833                         return WIMLIB_ERR_STAT;
834                 }
835                 if (stbuf.st_size == 0) {
836                         /* Zero-length stream.  No lookup table entry needed. */
837                         inode_update_lte_ptr(lte->lte_inode, lte, NULL);
838                         free_lookup_table_entry(lte);
839                 } else {
840                         wimlib_assert(&lte->file_on_disk == &lte->staging_file_name);
841                         lte->resource_entry.original_size = stbuf.st_size;
842                         lte->resource_entry.size = stbuf.st_size;
843                         lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
844                         lte->lte_inode = NULL;
845                         copy_hash(lte->hash, hash);
846                         lookup_table_insert(table, lte);
847                 }
848         }
849         return 0;
850 }
851
852 static int inode_close_fds(struct inode *inode)
853 {
854         u16 num_opened_fds = inode->num_opened_fds;
855         for (u16 i = 0, j = 0; j < num_opened_fds; i++) {
856                 struct wimlib_fd *fd = inode->fds[i];
857                 if (fd) {
858                         wimlib_assert(fd->f_inode == inode);
859                         int ret = close_wimlib_fd(fd);
860                         if (ret != 0)
861                                 return ret;
862                         j++;
863                 }
864         }
865         return 0;
866 }
867
868 /* Overwrites the WIM file, with changes saved. */
869 static int rebuild_wim(struct wimfs_context *ctx, bool check_integrity)
870 {
871         int ret;
872         struct lookup_table_entry *lte, *tmp;
873         WIMStruct *w = ctx->wim;
874
875
876         DEBUG("Closing all staging file descriptors.");
877         list_for_each_entry_safe(lte, tmp, &ctx->staging_list, staging_list) {
878                 ret = inode_close_fds(lte->lte_inode);
879                 if (ret != 0)
880                         return ret;
881         }
882
883         DEBUG("Calculating SHA1 checksums for all new staging files.");
884         list_for_each_entry_safe(lte, tmp, &ctx->staging_list, staging_list) {
885                 ret = update_lte_of_staging_file(lte, ctx->wim->lookup_table);
886                 if (ret != 0)
887                         return ret;
888         }
889
890         xml_update_image_info(w, w->current_image);
891
892         ret = wimlib_overwrite(w, check_integrity);
893         if (ret != 0) {
894                 ERROR("Failed to commit changes");
895                 return ret;
896         }
897         return ret;
898 }
899
900 /* Called when the filesystem is unmounted. */
901 static void wimfs_destroy(void *p)
902 {
903         /* For read-write mounts, the `imagex unmount' command, which is
904          * running in a separate process and is executing the
905          * wimlib_unmount() function, will send this process a byte
906          * through a message queue that indicates whether the --commit
907          * option was specified or not. */
908
909         long msgsize;
910         struct timespec timeout;
911         struct timeval now;
912         ssize_t bytes_received;
913         int ret;
914         char commit;
915         char check_integrity;
916         char status;
917         char *mailbox;
918         struct wimfs_context *ctx = wimfs_get_context();
919
920         if (open_message_queues(ctx, true))
921                 return;
922
923         if (get_mailbox(ctx->unmount_to_daemon_mq, 2, &msgsize, &mailbox))
924                 goto out_close_message_queues;
925
926         /* Wait at most 3 seconds before giving up and discarding changes. */
927         gettimeofday(&now, NULL);
928         timeout.tv_sec = now.tv_sec + 3;
929         timeout.tv_nsec = now.tv_usec * 1000;
930         DEBUG("Waiting for message telling us whether to commit or not, and "
931               "whether to include integrity checks.");
932
933         bytes_received = mq_timedreceive(ctx->unmount_to_daemon_mq, mailbox,
934                                          msgsize, NULL, &timeout);
935         if (bytes_received == -1) {
936                 ERROR_WITH_ERRNO("mq_timedreceive()");
937                 ERROR("Not committing.");
938                 commit = 0;
939                 check_integrity = 0;
940         } else {
941                 DEBUG("Received message: [%d %d]", mailbox[0], mailbox[1]);
942                 commit = mailbox[0];
943                 check_integrity = mailbox[1];
944         }
945
946         status = 0;
947         if (ctx->mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
948                 if (commit) {
949                         ret = chdir(ctx->working_directory);
950                         if (ret == 0) {
951                                 status = rebuild_wim(ctx, (check_integrity != 0));
952                         } else {
953                                 ERROR_WITH_ERRNO("chdir()");
954                                 status = WIMLIB_ERR_NOTDIR;
955                         }
956                 }
957                 ret = delete_staging_dir(ctx);
958                 if (ret != 0) {
959                         ERROR("Failed to delete the staging directory");
960                         if (status == 0)
961                                 status = ret;
962                 }
963         } else {
964                 DEBUG("Read-only mount");
965         }
966         DEBUG("Sending status %hhd", status);
967         ret = mq_send(ctx->daemon_to_unmount_mq, &status, 1, 1);
968         if (ret == -1)
969                 ERROR_WITH_ERRNO("Failed to send status to unmount process");
970         FREE(mailbox);
971 out_close_message_queues:
972         close_message_queues(ctx);
973 }
974
975 #if 0
976 static int wimfs_fallocate(const char *path, int mode,
977                            off_t offset, off_t len, struct fuse_file_info *fi)
978 {
979         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
980         wimlib_assert(fd->staging_fd != -1);
981         return fallocate(fd->staging_fd, mode, offset, len);
982 }
983
984 #endif
985
986 static int wimfs_fgetattr(const char *path, struct stat *stbuf,
987                           struct fuse_file_info *fi)
988 {
989         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
990         return inode_to_stbuf(fd->f_inode, fd->f_lte, stbuf);
991 }
992
993 static int wimfs_ftruncate(const char *path, off_t size,
994                            struct fuse_file_info *fi)
995 {
996         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
997         int ret = ftruncate(fd->staging_fd, size);
998         if (ret != 0)
999                 return -errno;
1000         if (fd->f_lte && size < fd->f_lte->resource_entry.original_size)
1001                 fd->f_lte->resource_entry.original_size = size;
1002         return 0;
1003 }
1004
1005 /*
1006  * Fills in a `struct stat' that corresponds to a file or directory in the WIM.
1007  */
1008 static int wimfs_getattr(const char *path, struct stat *stbuf)
1009 {
1010         struct dentry *dentry;
1011         struct lookup_table_entry *lte;
1012         int ret;
1013         struct wimfs_context *ctx = wimfs_get_context();
1014
1015         ret = lookup_resource(ctx->wim, path,
1016                               get_lookup_flags(ctx) | LOOKUP_FLAG_DIRECTORY_OK,
1017                               &dentry, &lte, NULL);
1018         if (ret != 0)
1019                 return ret;
1020         return inode_to_stbuf(dentry->d_inode, lte, stbuf);
1021 }
1022
1023 #ifdef ENABLE_XATTR
1024 /* Read an alternate data stream through the XATTR interface, or get its size */
1025 static int wimfs_getxattr(const char *path, const char *name, char *value,
1026                           size_t size)
1027 {
1028         int ret;
1029         struct inode *inode;
1030         struct ads_entry *ads_entry;
1031         size_t res_size;
1032         struct lookup_table_entry *lte;
1033         struct wimfs_context *ctx = wimfs_get_context();
1034
1035         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1036                 return -ENOTSUP;
1037
1038         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1039                 return -ENOATTR;
1040         name += 5;
1041
1042         inode = wim_pathname_to_inode(ctx->wim, path);
1043         if (!inode)
1044                 return -ENOENT;
1045
1046         ads_entry = inode_get_ads_entry(inode, name, NULL);
1047         if (!ads_entry)
1048                 return -ENOATTR;
1049
1050         lte = ads_entry->lte;
1051         res_size = wim_resource_size(lte);
1052
1053         if (size == 0)
1054                 return res_size;
1055
1056         if (res_size > size)
1057                 return -ERANGE;
1058
1059         ret = read_full_wim_resource(lte, (u8*)value);
1060         if (ret != 0)
1061                 return -EIO;
1062
1063         return res_size;
1064 }
1065 #endif
1066
1067 /* Create a hard link */
1068 static int wimfs_link(const char *to, const char *from)
1069 {
1070         struct dentry *from_dentry, *from_dentry_parent;
1071         const char *link_name;
1072         struct inode *inode;
1073         struct lookup_table_entry *lte;
1074         WIMStruct *w = wimfs_get_WIMStruct();
1075
1076         inode = wim_pathname_to_inode(w, to);
1077         if (!inode)
1078                 return -ENOENT;
1079
1080         if (!inode_is_regular_file(inode))
1081                 return -EPERM;
1082
1083         from_dentry_parent = get_parent_dentry(w, from);
1084         if (!from_dentry_parent)
1085                 return -ENOENT;
1086         if (!dentry_is_directory(from_dentry_parent))
1087                 return -ENOTDIR;
1088
1089         link_name = path_basename(from);
1090         if (get_dentry_child_with_name(from_dentry_parent, link_name))
1091                 return -EEXIST;
1092         from_dentry = new_dentry(link_name);
1093         if (!from_dentry)
1094                 return -ENOMEM;
1095
1096
1097         inode_add_dentry(from_dentry, inode);
1098         from_dentry->d_inode = inode;
1099         inode->link_count++;
1100
1101         for (unsigned i = 0; i <= inode->num_ads; i++) {
1102                 lte = inode_stream_lte_resolved(inode, i);
1103                 if (lte)
1104                         lte->refcnt++;
1105         }
1106
1107         dentry_add_child(from_dentry_parent, from_dentry);
1108         return 0;
1109 }
1110
1111 #ifdef ENABLE_XATTR
1112 static int wimfs_listxattr(const char *path, char *list, size_t size)
1113 {
1114         size_t needed_size;
1115         struct inode *inode;
1116         struct wimfs_context *ctx = wimfs_get_context();
1117
1118         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1119                 return -ENOTSUP;
1120
1121         /* List alternate data streams, or get the list size */
1122
1123         inode = wim_pathname_to_inode(ctx->wim, path);
1124         if (!inode)
1125                 return -ENOENT;
1126
1127         if (size == 0) {
1128                 needed_size = 0;
1129                 for (u16 i = 0; i < inode->num_ads; i++)
1130                         needed_size += inode->ads_entries[i].stream_name_utf8_len + 6;
1131                 return needed_size;
1132         } else {
1133                 char *p = list;
1134                 for (u16 i = 0; i < inode->num_ads; i++) {
1135                         needed_size = inode->ads_entries[i].stream_name_utf8_len + 6;
1136                         if (needed_size > size)
1137                                 return -ERANGE;
1138                         p += sprintf(p, "user.%s",
1139                                      inode->ads_entries[i].stream_name_utf8) + 1;
1140                         size -= needed_size;
1141                 }
1142                 return p - list;
1143         }
1144 }
1145 #endif
1146
1147 /*
1148  * Create a directory in the WIM.
1149  * @mode is currently ignored.
1150  */
1151 static int wimfs_mkdir(const char *path, mode_t mode)
1152 {
1153         struct dentry *parent;
1154         struct dentry *newdir;
1155         const char *basename;
1156         struct wimfs_context *ctx = wimfs_get_context();
1157
1158         parent = get_parent_dentry(ctx->wim, path);
1159         if (!parent)
1160                 return -ENOENT;
1161
1162         if (!dentry_is_directory(parent))
1163                 return -ENOTDIR;
1164
1165         basename = path_basename(path);
1166         if (get_dentry_child_with_name(parent, basename))
1167                 return -EEXIST;
1168
1169         newdir = new_dentry_with_inode(basename);
1170         newdir->d_inode->attributes |= FILE_ATTRIBUTE_DIRECTORY;
1171         newdir->d_inode->resolved = true;
1172         newdir->d_inode->ino = ctx->next_ino++;
1173         dentry_add_child(parent, newdir);
1174         return 0;
1175 }
1176
1177 /* Creates a regular file. */
1178 static int wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
1179 {
1180         const char *stream_name;
1181         struct wimfs_context *ctx = wimfs_get_context();
1182         if ((ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
1183              && (stream_name = path_stream_name(path))) {
1184                 /* Make an alternate data stream */
1185                 struct ads_entry *new_entry;
1186                 struct inode *inode;
1187
1188                 char *p = (char*)stream_name - 1;
1189                 wimlib_assert(*p == ':');
1190                 *p = '\0';
1191
1192                 inode = wim_pathname_to_inode(ctx->wim, path);
1193                 if (!inode)
1194                         return -ENOENT;
1195                 if (!inode_is_regular_file(inode))
1196                         return -ENOENT;
1197                 if (inode_get_ads_entry(inode, stream_name, NULL))
1198                         return -EEXIST;
1199                 new_entry = inode_add_ads(inode, stream_name);
1200                 if (!new_entry)
1201                         return -ENOMEM;
1202         } else {
1203                 struct dentry *dentry, *parent;
1204                 const char *basename;
1205
1206                 /* Make a normal file (not an alternate data stream) */
1207
1208                 /* Make sure that the parent of @path exists and is a directory, and
1209                  * that the dentry named by @path does not already exist.  */
1210                 parent = get_parent_dentry(ctx->wim, path);
1211                 if (!parent)
1212                         return -ENOENT;
1213                 if (!dentry_is_directory(parent))
1214                         return -ENOTDIR;
1215
1216                 basename = path_basename(path);
1217                 if (get_dentry_child_with_name(parent, path))
1218                         return -EEXIST;
1219
1220                 dentry = new_dentry_with_inode(basename);
1221                 if (!dentry)
1222                         return -ENOMEM;
1223                 dentry->d_inode->resolved = true;
1224                 dentry->d_inode->ino = ctx->next_ino++;
1225                 dentry_add_child(parent, dentry);
1226         }
1227         return 0;
1228 }
1229
1230
1231 /* Open a file.  */
1232 static int wimfs_open(const char *path, struct fuse_file_info *fi)
1233 {
1234         struct dentry *dentry;
1235         struct lookup_table_entry *lte;
1236         int ret;
1237         struct wimlib_fd *fd;
1238         struct inode *inode;
1239         u16 stream_idx;
1240         u32 stream_id;
1241         struct wimfs_context *ctx = wimfs_get_context();
1242
1243         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1244                               &dentry, &lte, &stream_idx);
1245         if (ret != 0)
1246                 return ret;
1247
1248         inode = dentry->d_inode;
1249
1250         if (stream_idx == 0)
1251                 stream_id = 0;
1252         else
1253                 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
1254
1255         /* The file resource may be in the staging directory (read-write mounts
1256          * only) or in the WIM.  If it's in the staging directory, we need to
1257          * open a native file descriptor for the corresponding file.  Otherwise,
1258          * we can read the file resource directly from the WIM file if we are
1259          * opening it read-only, but we need to extract the resource to the
1260          * staging directory if we are opening it writable. */
1261
1262         if (flags_writable(fi->flags) &&
1263             (!lte || lte->resource_location != RESOURCE_IN_STAGING_FILE)) {
1264                 u64 size = (lte) ? wim_resource_size(lte) : 0;
1265                 ret = extract_resource_to_staging_dir(inode, stream_id,
1266                                                       &lte, size, ctx);
1267                 if (ret != 0)
1268                         return ret;
1269         }
1270
1271         ret = alloc_wimlib_fd(inode, stream_id, lte, &fd);
1272         if (ret != 0)
1273                 return ret;
1274
1275         if (lte && lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1276                 fd->staging_fd = open(lte->staging_file_name, fi->flags);
1277                 if (fd->staging_fd == -1) {
1278                         close_wimlib_fd(fd);
1279                         return -errno;
1280                 }
1281         }
1282         fi->fh = (uintptr_t)fd;
1283         return 0;
1284 }
1285
1286 /* Opens a directory. */
1287 static int wimfs_opendir(const char *path, struct fuse_file_info *fi)
1288 {
1289         struct inode *inode;
1290         int ret;
1291         struct wimlib_fd *fd = NULL;
1292         WIMStruct *w = wimfs_get_WIMStruct();
1293
1294         inode = wim_pathname_to_inode(w, path);
1295         if (!inode)
1296                 return -ENOENT;
1297         if (!inode_is_directory(inode))
1298                 return -ENOTDIR;
1299         ret = alloc_wimlib_fd(inode, 0, NULL, &fd);
1300         fi->fh = (uintptr_t)fd;
1301         return ret;
1302 }
1303
1304
1305 /*
1306  * Read data from a file in the WIM or in the staging directory.
1307  */
1308 static int wimfs_read(const char *path, char *buf, size_t size,
1309                       off_t offset, struct fuse_file_info *fi)
1310 {
1311         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1312
1313         if (!fd)
1314                 return -EBADF;
1315
1316         if (!fd->f_lte) /* Empty stream with no lookup table entry */
1317                 return 0;
1318
1319         if (fd->f_lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1320                 /* Read from staging file */
1321
1322                 wimlib_assert(fd->f_lte->staging_file_name);
1323                 wimlib_assert(fd->staging_fd != -1);
1324
1325                 ssize_t ret;
1326                 DEBUG("Seek to offset %zu", offset);
1327
1328                 if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1329                         return -errno;
1330                 ret = read(fd->staging_fd, buf, size);
1331                 if (ret == -1)
1332                         return -errno;
1333                 return ret;
1334         } else {
1335                 /* Read from WIM */
1336
1337                 u64 res_size = wim_resource_size(fd->f_lte);
1338
1339                 if (offset > res_size)
1340                         return -EOVERFLOW;
1341
1342                 size = min(size, res_size - offset);
1343
1344                 if (read_wim_resource(fd->f_lte, (u8*)buf,
1345                                       size, offset, false) != 0)
1346                         return -EIO;
1347                 return size;
1348         }
1349 }
1350
1351 struct fill_params {
1352         void *buf;
1353         fuse_fill_dir_t filler;
1354 };
1355
1356 static int dentry_fuse_fill(struct dentry *dentry, void *arg)
1357 {
1358         struct fill_params *fill_params = arg;
1359         return fill_params->filler(fill_params->buf, dentry->file_name_utf8,
1360                                    NULL, 0);
1361 }
1362
1363 /* Fills in the entries of the directory specified by @path using the
1364  * FUSE-provided function @filler.  */
1365 static int wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
1366                          off_t offset, struct fuse_file_info *fi)
1367 {
1368         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1369         struct inode *inode;
1370
1371         if (!fd)
1372                 return -EBADF;
1373
1374         inode = fd->f_inode;
1375
1376         struct fill_params fill_params = {
1377                 .buf = buf,
1378                 .filler = filler,
1379         };
1380
1381         filler(buf, ".", NULL, 0);
1382         filler(buf, "..", NULL, 0);
1383
1384         return for_dentry_in_rbtree(inode->children.rb_node,
1385                                     dentry_fuse_fill, &fill_params);
1386 }
1387
1388
1389 static int wimfs_readlink(const char *path, char *buf, size_t buf_len)
1390 {
1391         struct wimfs_context *ctx = wimfs_get_context();
1392         struct inode *inode = wim_pathname_to_inode(ctx->wim, path);
1393         int ret;
1394         if (!inode)
1395                 return -ENOENT;
1396         if (!inode_is_symlink(inode))
1397                 return -EINVAL;
1398
1399         ret = inode_readlink(inode, buf, buf_len, ctx->wim);
1400         if (ret > 0)
1401                 ret = 0;
1402         return ret;
1403 }
1404
1405 /* Close a file. */
1406 static int wimfs_release(const char *path, struct fuse_file_info *fi)
1407 {
1408         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1409         return close_wimlib_fd(fd);
1410 }
1411
1412 /* Close a directory */
1413 static int wimfs_releasedir(const char *path, struct fuse_file_info *fi)
1414 {
1415         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1416         return close_wimlib_fd(fd);
1417 }
1418
1419 #ifdef ENABLE_XATTR
1420 /* Remove an alternate data stream through the XATTR interface */
1421 static int wimfs_removexattr(const char *path, const char *name)
1422 {
1423         struct inode *inode;
1424         struct ads_entry *ads_entry;
1425         u16 ads_idx;
1426         struct wimfs_context *ctx = wimfs_get_context();
1427
1428         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1429                 return -ENOTSUP;
1430
1431         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1432                 return -ENOATTR;
1433         name += 5;
1434
1435         inode = wim_pathname_to_inode(ctx->wim, path);
1436         if (!inode)
1437                 return -ENOENT;
1438
1439         ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
1440         if (!ads_entry)
1441                 return -ENOATTR;
1442         inode_remove_ads(inode, ads_idx, ctx->wim->lookup_table);
1443         return 0;
1444 }
1445 #endif
1446
1447 /* Renames a file or directory.  See rename (3) */
1448 static int wimfs_rename(const char *from, const char *to)
1449 {
1450         struct dentry *src;
1451         struct dentry *dst;
1452         struct dentry *parent_of_dst;
1453         char *file_name_utf16 = NULL, *file_name_utf8 = NULL;
1454         u16 file_name_utf16_len, file_name_utf8_len;
1455         WIMStruct *w = wimfs_get_WIMStruct();
1456         int ret;
1457
1458         /* This rename() implementation currently only supports actual files
1459          * (not alternate data streams) */
1460
1461         src = get_dentry(w, from);
1462         if (!src)
1463                 return -ENOENT;
1464
1465         dst = get_dentry(w, to);
1466
1467
1468         ret = get_names(&file_name_utf16, &file_name_utf8,
1469                         &file_name_utf16_len, &file_name_utf8_len,
1470                         path_basename(to));
1471         if (ret != 0)
1472                 return -ENOMEM;
1473
1474         if (dst) {
1475                 /* Destination file exists */
1476
1477                 if (src == dst) /* Same file */
1478                         return 0;
1479
1480                 if (!dentry_is_directory(src)) {
1481                         /* Cannot rename non-directory to directory. */
1482                         if (dentry_is_directory(dst))
1483                                 return -EISDIR;
1484                 } else {
1485                         /* Cannot rename directory to a non-directory or a non-empty
1486                          * directory */
1487                         if (!dentry_is_directory(dst))
1488                                 return -ENOTDIR;
1489                         if (inode_has_children(dst->d_inode))
1490                                 return -ENOTEMPTY;
1491                 }
1492                 parent_of_dst = dst->parent;
1493                 remove_dentry(dst, w->lookup_table);
1494         } else {
1495                 /* Destination does not exist */
1496                 parent_of_dst = get_parent_dentry(w, to);
1497                 if (!parent_of_dst)
1498                         return -ENOENT;
1499
1500                 if (!dentry_is_directory(parent_of_dst))
1501                         return -ENOTDIR;
1502         }
1503
1504         FREE(src->file_name);
1505         FREE(src->file_name_utf8);
1506         src->file_name          = file_name_utf16;
1507         src->file_name_utf8     = file_name_utf8;
1508         src->file_name_len      = file_name_utf16_len;
1509         src->file_name_utf8_len = file_name_utf8_len;
1510
1511         unlink_dentry(src);
1512         dentry_add_child(parent_of_dst, src);
1513         return 0;
1514 }
1515
1516 /* Remove a directory */
1517 static int wimfs_rmdir(const char *path)
1518 {
1519         struct dentry *dentry;
1520         WIMStruct *w = wimfs_get_WIMStruct();
1521
1522         dentry = get_dentry(w, path);
1523         if (!dentry)
1524                 return -ENOENT;
1525
1526         if (!dentry_is_empty_directory(dentry))
1527                 return -ENOTEMPTY;
1528
1529         remove_dentry(dentry, w->lookup_table);
1530         return 0;
1531 }
1532
1533 #ifdef ENABLE_XATTR
1534 /* Write an alternate data stream through the XATTR interface */
1535 static int wimfs_setxattr(const char *path, const char *name,
1536                           const char *value, size_t size, int flags)
1537 {
1538         struct ads_entry *existing_ads_entry;
1539         struct ads_entry *new_ads_entry;
1540         struct lookup_table_entry *existing_lte;
1541         struct lookup_table_entry *lte;
1542         struct inode *inode;
1543         u8 value_hash[SHA1_HASH_SIZE];
1544         u16 ads_idx;
1545         struct wimfs_context *ctx = wimfs_get_context();
1546
1547         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1548                 return -ENOTSUP;
1549
1550         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1551                 return -ENOATTR;
1552         name += 5;
1553
1554         inode = wim_pathname_to_inode(ctx->wim, path);
1555         if (!inode)
1556                 return -ENOENT;
1557
1558         existing_ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
1559         if (existing_ads_entry) {
1560                 if (flags & XATTR_CREATE)
1561                         return -EEXIST;
1562                 inode_remove_ads(inode, ads_idx, ctx->wim->lookup_table);
1563         } else {
1564                 if (flags & XATTR_REPLACE)
1565                         return -ENOATTR;
1566         }
1567         new_ads_entry = inode_add_ads(inode, name);
1568         if (!new_ads_entry)
1569                 return -ENOMEM;
1570
1571         sha1_buffer((const u8*)value, size, value_hash);
1572
1573         existing_lte = __lookup_resource(ctx->wim->lookup_table, value_hash);
1574
1575         if (existing_lte) {
1576                 lte = existing_lte;
1577                 lte->refcnt++;
1578         } else {
1579                 u8 *value_copy;
1580                 lte = new_lookup_table_entry();
1581                 if (!lte)
1582                         return -ENOMEM;
1583                 value_copy = MALLOC(size);
1584                 if (!value_copy) {
1585                         FREE(lte);
1586                         return -ENOMEM;
1587                 }
1588                 memcpy(value_copy, value, size);
1589                 lte->resource_location            = RESOURCE_IN_ATTACHED_BUFFER;
1590                 lte->attached_buffer              = value_copy;
1591                 lte->resource_entry.original_size = size;
1592                 lte->resource_entry.size          = size;
1593                 lte->resource_entry.flags         = 0;
1594                 copy_hash(lte->hash, value_hash);
1595                 lookup_table_insert(ctx->wim->lookup_table, lte);
1596         }
1597         new_ads_entry->lte = lte;
1598         return 0;
1599 }
1600 #endif
1601
1602 static int wimfs_symlink(const char *to, const char *from)
1603 {
1604         struct dentry *dentry_parent, *dentry;
1605         const char *link_name;
1606         struct inode *inode;
1607         struct wimfs_context *ctx = wimfs_get_context();
1608
1609         dentry_parent = get_parent_dentry(ctx->wim, from);
1610         if (!dentry_parent)
1611                 return -ENOENT;
1612         if (!dentry_is_directory(dentry_parent))
1613                 return -ENOTDIR;
1614
1615         link_name = path_basename(from);
1616
1617         if (get_dentry_child_with_name(dentry_parent, link_name))
1618                 return -EEXIST;
1619         dentry = new_dentry_with_inode(link_name);
1620         if (!dentry)
1621                 return -ENOMEM;
1622         inode = dentry->d_inode;
1623
1624         inode->attributes  = FILE_ATTRIBUTE_REPARSE_POINT;
1625         inode->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
1626         inode->ino         = ctx->next_ino++;
1627         inode->resolved    = true;
1628
1629         if (inode_set_symlink(inode, to, ctx->wim->lookup_table, NULL) != 0)
1630                 goto out_free_dentry;
1631
1632         dentry_add_child(dentry_parent, dentry);
1633         return 0;
1634 out_free_dentry:
1635         free_dentry(dentry);
1636         return -ENOMEM;
1637 }
1638
1639
1640 /* Reduce the size of a file */
1641 static int wimfs_truncate(const char *path, off_t size)
1642 {
1643         struct dentry *dentry;
1644         struct lookup_table_entry *lte;
1645         int ret;
1646         u16 stream_idx;
1647         u32 stream_id;
1648         struct inode *inode;
1649         struct wimfs_context *ctx = wimfs_get_context();
1650
1651         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1652                               &dentry, &lte, &stream_idx);
1653
1654         if (ret != 0)
1655                 return ret;
1656
1657         if (!lte) /* Already a zero-length file */
1658                 return 0;
1659
1660         inode = dentry->d_inode;
1661
1662         if (stream_idx == 0)
1663                 stream_id = 0;
1664         else
1665                 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
1666
1667         if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1668                 wimlib_assert(lte->staging_file_name);
1669                 ret = truncate(lte->staging_file_name, size);
1670                 if (ret != 0)
1671                         return -errno;
1672                 lte->resource_entry.original_size = size;
1673         } else {
1674                 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
1675                 /* File in WIM.  Extract it to the staging directory, but only
1676                  * the first @size bytes of it. */
1677                 ret = extract_resource_to_staging_dir(inode, stream_id,
1678                                                       &lte, size, ctx);
1679         }
1680         return ret;
1681 }
1682
1683 /* Remove a regular file */
1684 static int wimfs_unlink(const char *path)
1685 {
1686         struct dentry *dentry;
1687         struct lookup_table_entry *lte;
1688         int ret;
1689         u16 stream_idx;
1690         struct wimfs_context *ctx = wimfs_get_context();
1691
1692         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1693                               &dentry, &lte, &stream_idx);
1694
1695         if (ret != 0)
1696                 return ret;
1697
1698         if (stream_idx == 0)
1699                 remove_dentry(dentry, ctx->wim->lookup_table);
1700         else
1701                 inode_remove_ads(dentry->d_inode, stream_idx - 1,
1702                                  ctx->wim->lookup_table);
1703         return 0;
1704 }
1705
1706 #ifdef HAVE_UTIMENSAT
1707 /*
1708  * Change the timestamp on a file dentry.
1709  *
1710  * Note that alternate data streams do not have their own timestamps.
1711  */
1712 static int wimfs_utimens(const char *path, const struct timespec tv[2])
1713 {
1714         struct dentry *dentry;
1715         struct inode *inode;
1716         WIMStruct *w = wimfs_get_WIMStruct();
1717
1718         dentry = get_dentry(w, path);
1719         if (!dentry)
1720                 return -ENOENT;
1721         inode = dentry->d_inode;
1722
1723         if (tv[0].tv_nsec != UTIME_OMIT) {
1724                 if (tv[0].tv_nsec == UTIME_NOW)
1725                         inode->last_access_time = get_wim_timestamp();
1726                 else
1727                         inode->last_access_time = timespec_to_wim_timestamp(&tv[0]);
1728         }
1729         if (tv[1].tv_nsec != UTIME_OMIT) {
1730                 if (tv[1].tv_nsec == UTIME_NOW)
1731                         inode->last_write_time = get_wim_timestamp();
1732                 else
1733                         inode->last_write_time = timespec_to_wim_timestamp(&tv[1]);
1734         }
1735         return 0;
1736 }
1737 #else
1738 static int wimfs_utime(const char *path, struct utimbuf *times)
1739 {
1740         struct dentry *dentry;
1741         struct inode *inode;
1742         WIMStruct *w = wimfs_get_WIMStruct();
1743
1744         dentry = get_dentry(w, path);
1745         if (!dentry)
1746                 return -ENOENT;
1747         inode = dentry->d_inode;
1748
1749         inode->last_write_time = unix_timestamp_to_wim(times->modtime);
1750         inode->last_access_time = unix_timestamp_to_wim(times->actime);
1751         return 0;
1752 }
1753 #endif
1754
1755 /* Writes to a file in the WIM filesystem.
1756  * It may be an alternate data stream, but here we don't even notice because we
1757  * just get a lookup table entry. */
1758 static int wimfs_write(const char *path, const char *buf, size_t size,
1759                        off_t offset, struct fuse_file_info *fi)
1760 {
1761         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1762         int ret;
1763         u64 now;
1764
1765         if (!fd)
1766                 return -EBADF;
1767
1768         wimlib_assert(fd->f_lte);
1769         wimlib_assert(fd->f_lte->staging_file_name);
1770         wimlib_assert(fd->staging_fd != -1);
1771         wimlib_assert(fd->f_inode);
1772
1773         /* Seek to the requested position */
1774         if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1775                 return -errno;
1776
1777         /* Write the data. */
1778         ret = write(fd->staging_fd, buf, size);
1779         if (ret == -1)
1780                 return -errno;
1781
1782         now = get_wim_timestamp();
1783         fd->f_inode->last_write_time = now;
1784         fd->f_inode->last_access_time = now;
1785         return ret;
1786 }
1787
1788 static struct fuse_operations wimfs_operations = {
1789         .access      = wimfs_access,
1790         .chmod       = wimfs_chmod,
1791         .destroy     = wimfs_destroy,
1792 #if 0
1793         .fallocate   = wimfs_fallocate,
1794 #endif
1795         .fgetattr    = wimfs_fgetattr,
1796         .ftruncate   = wimfs_ftruncate,
1797         .getattr     = wimfs_getattr,
1798 #ifdef ENABLE_XATTR
1799         .getxattr    = wimfs_getxattr,
1800 #endif
1801         .link        = wimfs_link,
1802 #ifdef ENABLE_XATTR
1803         .listxattr   = wimfs_listxattr,
1804 #endif
1805         .mkdir       = wimfs_mkdir,
1806         .mknod       = wimfs_mknod,
1807         .open        = wimfs_open,
1808         .opendir     = wimfs_opendir,
1809         .read        = wimfs_read,
1810         .readdir     = wimfs_readdir,
1811         .readlink    = wimfs_readlink,
1812         .release     = wimfs_release,
1813         .releasedir  = wimfs_releasedir,
1814 #ifdef ENABLE_XATTR
1815         .removexattr = wimfs_removexattr,
1816 #endif
1817         .rename      = wimfs_rename,
1818         .rmdir       = wimfs_rmdir,
1819 #ifdef ENABLE_XATTR
1820         .setxattr    = wimfs_setxattr,
1821 #endif
1822         .symlink     = wimfs_symlink,
1823         .truncate    = wimfs_truncate,
1824         .unlink      = wimfs_unlink,
1825 #ifdef HAVE_UTIMENSAT
1826         .utimens     = wimfs_utimens,
1827 #else
1828         .utime       = wimfs_utime,
1829 #endif
1830         .write       = wimfs_write,
1831 };
1832
1833
1834 /* Mounts a WIM file. */
1835 WIMLIBAPI int wimlib_mount(WIMStruct *wim, int image, const char *dir,
1836                            int flags, WIMStruct **additional_swms,
1837                            unsigned num_additional_swms)
1838 {
1839         int argc = 0;
1840         char *argv[16];
1841         int ret;
1842         char *dir_copy;
1843         struct lookup_table *joined_tab, *wim_tab_save;
1844         struct image_metadata *imd;
1845         struct wimfs_context ctx;
1846
1847         DEBUG("Mount: wim = %p, image = %d, dir = %s, flags = %d, ",
1848               wim, image, dir, flags);
1849
1850         if (!wim || !dir)
1851                 return WIMLIB_ERR_INVALID_PARAM;
1852
1853         ret = verify_swm_set(wim, additional_swms, num_additional_swms);
1854         if (ret != 0)
1855                 return ret;
1856
1857         if ((flags & WIMLIB_MOUNT_FLAG_READWRITE) && (wim->hdr.total_parts != 1)) {
1858                 ERROR("Cannot mount a split WIM read-write");
1859                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1860         }
1861
1862         if (num_additional_swms) {
1863                 ret = new_joined_lookup_table(wim, additional_swms,
1864                                               num_additional_swms,
1865                                               &joined_tab);
1866                 if (ret != 0)
1867                         return ret;
1868                 wim_tab_save = wim->lookup_table;
1869                 wim->lookup_table = joined_tab;
1870         }
1871
1872         ret = select_wim_image(wim, image);
1873
1874         if (ret != 0)
1875                 goto out;
1876
1877         imd = &wim->image_metadata[image - 1];
1878
1879         DEBUG("Selected image %d", image);
1880
1881         if (imd->root_dentry->refcnt != 1) {
1882                 ERROR("Cannot mount image that was just exported with "
1883                       "wimlib_export()");
1884                 ret = WIMLIB_ERR_INVALID_PARAM;
1885                 goto out;
1886         }
1887
1888         if (!(flags & (WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
1889                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
1890                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)))
1891                 flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
1892
1893
1894         DEBUG("Initializing struct wimfs_context");
1895         init_wimfs_context(&ctx);
1896
1897         DEBUG("Getting current directory");
1898         ctx.working_directory = getcwd(NULL, 0);
1899         if (!ctx.working_directory) {
1900                 ERROR_WITH_ERRNO("Could not determine current directory");
1901                 ret = WIMLIB_ERR_NOTDIR;
1902                 goto out;
1903         }
1904
1905         DEBUG("Unlinking message queues in case they already exist");
1906         ret = set_message_queue_names(&ctx, dir);
1907         if (ret != 0)
1908                 goto out_free_working_directory;
1909         unlink_message_queues(&ctx);
1910
1911         DEBUG("Preparing arguments to fuse_main()");
1912
1913         dir_copy = STRDUP(dir);
1914         if (!dir_copy)
1915                 goto out_free_message_queue_names;
1916
1917         argv[argc++] = "imagex";
1918         argv[argc++] = dir_copy;
1919
1920         /* disable multi-threaded operation for read-write mounts */
1921         if (flags & WIMLIB_MOUNT_FLAG_READWRITE)
1922                 argv[argc++] = "-s";
1923
1924         if (flags & WIMLIB_MOUNT_FLAG_DEBUG)
1925                 argv[argc++] = "-d";
1926
1927         /*
1928          * We provide the use_ino option because we are going to assign inode
1929          * numbers oursides.  The inodes will be given unique numbers in the
1930          * assign_inode_numbers() function, and the static variable @next_ino is
1931          * set to the next available inode number.
1932          */
1933         char optstring[256] = "use_ino,subtype=wimfs,attr_timeout=0";
1934         argv[argc++] = "-o";
1935         argv[argc++] = optstring;
1936         if ((flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
1937                 /* Read-write mount.  Make the staging directory */
1938                 ret = make_staging_dir(&ctx);
1939                 if (ret != 0)
1940                         goto out_free_dir_copy;
1941         } else {
1942                 /* Read-only mount */
1943                 strcat(optstring, ",ro");
1944         }
1945         argv[argc] = NULL;
1946
1947 #ifdef ENABLE_DEBUG
1948         {
1949                 int i;
1950                 DEBUG("FUSE command line (argc = %d): ", argc);
1951                 for (i = 0; i < argc; i++) {
1952                         fputs(argv[i], stdout);
1953                         putchar(' ');
1954                 }
1955                 putchar('\n');
1956                 fflush(stdout);
1957         }
1958 #endif
1959
1960         /* Mark dentry tree as modified if read-write mount. */
1961         if (flags & WIMLIB_MOUNT_FLAG_READWRITE)
1962                 imd->modified = true;
1963
1964         /* Resolve all the lookup table entries of the dentry tree */
1965         DEBUG("Resolving lookup table entries");
1966         for_dentry_in_tree(imd->root_dentry, dentry_resolve_ltes,
1967                            wim->lookup_table);
1968
1969         ctx.next_ino = assign_inode_numbers(&imd->inode_list);
1970         DEBUG("(next_ino = %"PRIu64")", ctx.next_ino);
1971
1972         /* Finish initializing the filesystem context. */
1973         ctx.wim = wim;
1974         ctx.mount_flags = flags;
1975
1976         DEBUG("Calling fuse_main()");
1977
1978         ret = fuse_main(argc, argv, &wimfs_operations, &ctx);
1979
1980         DEBUG("Returned from fuse_main() (ret = %d)", ret);
1981         if (ret)
1982                 ret = WIMLIB_ERR_FUSE;
1983 out_free_dir_copy:
1984         FREE(dir_copy);
1985 out_free_message_queue_names:
1986         free_message_queue_names(&ctx);
1987 out_free_working_directory:
1988         FREE(ctx.working_directory);
1989         ctx.working_directory = NULL;
1990 out:
1991         if (num_additional_swms) {
1992                 free_lookup_table(wim->lookup_table);
1993                 wim->lookup_table = wim_tab_save;
1994         }
1995         return ret;
1996 }
1997
1998
1999 /*
2000  * Unmounts the WIM file that was previously mounted on @dir by using
2001  * wimlib_mount().
2002  */
2003 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
2004 {
2005         pid_t pid;
2006         int status;
2007         int ret;
2008         char msg[2];
2009         struct timeval now;
2010         struct timespec timeout;
2011         long msgsize;
2012         struct wimfs_context ctx;
2013         char *mailbox;
2014
2015         init_wimfs_context(&ctx);
2016
2017         /* Open message queues between the unmount process and the
2018          * filesystem daemon. */
2019         ret = set_message_queue_names(&ctx, dir);
2020         if (ret != 0)
2021                 goto out;
2022
2023         ret = open_message_queues(&ctx, false);
2024         if (ret != 0)
2025                 goto out_free_message_queue_names;
2026
2027         /* Send a message to the filesystem daemon saying whether to commit or
2028          * not. */
2029         msg[0] = (flags & WIMLIB_UNMOUNT_FLAG_COMMIT) ? 1 : 0;
2030         msg[1] = (flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY) ? 1 : 0;
2031
2032         DEBUG("Sending message: %scommit, %scheck",
2033                         (msg[0] ? "" : "don't "),
2034                         (msg[1] ? "" : "don't "));
2035         ret = mq_send(ctx.unmount_to_daemon_mq, msg, 2, 1);
2036         if (ret == -1) {
2037                 ERROR_WITH_ERRNO("Failed to notify filesystem daemon whether "
2038                                  "we want to commit changes or not");
2039                 ret = WIMLIB_ERR_MQUEUE;
2040                 goto out_close_message_queues;
2041         }
2042
2043         /* Execute `fusermount -u', which is installed setuid root, to unmount
2044          * the WIM.
2045          *
2046          * FUSE does not yet implement synchronous unmounts.  This means that
2047          * fusermount -u will return before the filesystem daemon returns from
2048          * wimfs_destroy().  This is partly what we want, because we need to
2049          * send a message from this process to the filesystem daemon telling
2050          * whether --commit was specified or not.  However, after that, the
2051          * unmount process must wait for the filesystem daemon to finish writing
2052          * the WIM file.
2053          */
2054
2055         pid = fork();
2056         if (pid == -1) {
2057                 ERROR_WITH_ERRNO("Failed to fork()");
2058                 ret = WIMLIB_ERR_FORK;
2059                 goto out_close_message_queues;
2060         }
2061         if (pid == 0) {
2062                 /* Child */
2063                 execlp("fusermount", "fusermount", "-u", dir, NULL);
2064                 ERROR_WITH_ERRNO("Failed to execute `fusermount'");
2065                 exit(WIMLIB_ERR_FUSERMOUNT);
2066         }
2067
2068         /* Parent */
2069         ret = wait(&status);
2070         if (ret == -1) {
2071                 ERROR_WITH_ERRNO("Failed to wait for fusermount process to "
2072                                  "terminate");
2073                 ret = WIMLIB_ERR_FUSERMOUNT;
2074                 goto out_close_message_queues;
2075         }
2076
2077         if (status != 0) {
2078                 ERROR("fusermount exited with status %d", status);
2079
2080                 /* Try again, but with the `umount' program.  This is required
2081                  * on other FUSE implementations such as FreeBSD's that do not
2082                  * have a `fusermount' program. */
2083
2084                 pid = fork();
2085                 if (pid == -1) {
2086                         ERROR_WITH_ERRNO("Failed to fork()");
2087                         ret = WIMLIB_ERR_FORK;
2088                         goto out_close_message_queues;
2089                 }
2090                 if (pid == 0) {
2091                         /* Child */
2092                         execlp("umount", "umount", dir, NULL);
2093                         ERROR_WITH_ERRNO("Failed to execute `umount'");
2094                         exit(WIMLIB_ERR_FUSERMOUNT);
2095                 }
2096
2097                 /* Parent */
2098                 ret = wait(&status);
2099                 if (ret == -1) {
2100                         ERROR_WITH_ERRNO("Failed to wait for `umount' process to "
2101                                          "terminate");
2102                         ret = WIMLIB_ERR_FUSERMOUNT;
2103                         goto out_close_message_queues;
2104                 }
2105                 if (status != 0) {
2106                         ERROR("`umount' exited with failure status");
2107                         ret = WIMLIB_ERR_FUSERMOUNT;
2108                         goto out_close_message_queues;
2109                 }
2110         }
2111
2112         wimlib_assert(status == 0);
2113
2114         /* Wait for a message from the filesytem daemon indicating whether  the
2115          * filesystem was unmounted successfully (0) or an error occurred (1).
2116          * This may take a long time if a big WIM file needs to be rewritten. */
2117
2118         /* Wait at most 600??? seconds before giving up and returning false.
2119          * Either it's a really big WIM file, or (more likely) the
2120          * filesystem daemon has crashed or failed for some reason.
2121          *
2122          * XXX come up with some method to determine if the filesystem
2123          * daemon has really crashed or not.
2124          *
2125          * XXX Idea: have mount daemon write its PID into the WIM file header?
2126          * No, this wouldn't work because we know the directory but not the WIM
2127          * file...
2128          * */
2129
2130         gettimeofday(&now, NULL);
2131         timeout.tv_sec = now.tv_sec + 600;
2132         timeout.tv_nsec = now.tv_usec * 1000;
2133
2134         ret = get_mailbox(ctx.daemon_to_unmount_mq, 2, &msgsize, &mailbox);
2135         if (ret != 0)
2136                 goto out_close_message_queues;
2137
2138         mailbox[0] = 0;
2139         DEBUG("Waiting for message telling us whether the unmount was "
2140                         "successful or not.");
2141         ret = mq_timedreceive(ctx.daemon_to_unmount_mq, mailbox,
2142                               msgsize, NULL, &timeout);
2143         if (ret == -1) {
2144                 if (errno == ETIMEDOUT) {
2145                         ERROR("Timed out- probably the filesystem daemon "
2146                               "crashed and the WIM was not written "
2147                               "successfully.");
2148                         ret = WIMLIB_ERR_TIMEOUT;
2149                 } else {
2150                         ERROR_WITH_ERRNO("mq_receive()");
2151                         ret = WIMLIB_ERR_MQUEUE;
2152                 }
2153                 goto out_free_mailbox;
2154
2155         }
2156         DEBUG("Received message: Unmount %s", (mailbox[0] ? "Failed" : "Ok"));
2157         ret = mailbox[0];
2158         if (ret)
2159                 ERROR("Unmount failed");
2160 out_free_mailbox:
2161         FREE(mailbox);
2162 out_close_message_queues:
2163         close_message_queues(&ctx);
2164 out_free_message_queue_names:
2165         free_message_queue_names(&ctx);
2166 out:
2167         return ret;
2168 }
2169
2170 #else /* WITH_FUSE */
2171
2172
2173 static inline int mount_unsupported_error()
2174 {
2175         ERROR("wimlib was compiled with --without-fuse, which disables support "
2176               "for mounting WIMs.");
2177         return WIMLIB_ERR_UNSUPPORTED;
2178 }
2179
2180 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
2181 {
2182         return mount_unsupported_error();
2183 }
2184
2185 WIMLIBAPI int wimlib_mount(WIMStruct *wim_p, int image, const char *dir,
2186                            int flags, WIMStruct **additional_swms,
2187                            unsigned num_additional_swms)
2188 {
2189         return mount_unsupported_error();
2190 }
2191
2192 #endif /* WITH_FUSE */