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