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