]> wimlib.net Git - wimlib/blob - src/mount.c
imagex.c: Minor usability improvements
[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 (idx = %u)", fd->idx);
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 != NULL);
197         wimlib_assert(inode != NULL);
198         wimlib_assert(fd->f_inode == inode);
199         wimlib_assert(inode->num_opened_fds != 0);
200         wimlib_assert(fd->idx < inode->num_allocated_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 int wimfs_chmod(const char *path, mode_t mask)
750 {
751         struct dentry *dentry;
752         struct wimfs_context *ctx = wimfs_get_context();
753         struct inode *inode;
754         struct stat stbuf;
755         int ret;
756
757         ret = lookup_resource(ctx->wim, path,
758                               get_lookup_flags(ctx) | LOOKUP_FLAG_DIRECTORY_OK,
759                               &dentry, NULL, NULL);
760         if (ret != 0)
761                 return ret;
762         inode = dentry->d_inode;
763         inode_to_stbuf(inode, NULL, &stbuf);
764         if (mask == stbuf.st_mode)
765                 return 0;
766         else
767                 return -EPERM;
768
769 }
770
771 static void inode_update_lte_ptr(struct inode *inode,
772                                  struct lookup_table_entry *old_lte,
773                                  struct lookup_table_entry *new_lte)
774 {
775         if (inode->lte == old_lte) {
776                 inode->lte = new_lte;
777         } else {
778                 for (unsigned i = 0; i < inode->num_ads; i++) {
779                         if (inode->ads_entries[i].lte == old_lte) {
780                                 inode->ads_entries[i].lte = new_lte;
781                                 break;
782                         }
783                 }
784         }
785 }
786
787 static int update_lte_of_staging_file(struct lookup_table_entry *lte,
788                                       struct lookup_table *table)
789 {
790         struct lookup_table_entry *duplicate_lte;
791         int ret;
792         u8 hash[SHA1_HASH_SIZE];
793         struct stat stbuf;
794
795         wimlib_assert(lte->resource_location == RESOURCE_IN_STAGING_FILE);
796         wimlib_assert(lte->staging_file_name);
797
798         ret = sha1sum(lte->staging_file_name, hash);
799         if (ret != 0)
800                 return ret;
801
802         lookup_table_unlink(table, lte);
803
804         duplicate_lte = __lookup_resource(table, hash);
805
806         if (duplicate_lte) {
807                 /* Merge duplicate lookup table entries */
808                 duplicate_lte->refcnt += lte->refcnt;
809                 list_del(&lte->staging_list);
810                 inode_update_lte_ptr(lte->lte_inode, lte, duplicate_lte);
811                 free_lookup_table_entry(lte);
812         } else {
813                 if (stat(lte->staging_file_name, &stbuf) != 0) {
814                         ERROR_WITH_ERRNO("Failed to stat `%s'", lte->staging_file_name);
815                         return WIMLIB_ERR_STAT;
816                 }
817                 if (stbuf.st_size == 0) {
818                         /* Zero-length stream.  No lookup table entry needed. */
819                         inode_update_lte_ptr(lte->lte_inode, lte, NULL);
820                         free_lookup_table_entry(lte);
821                 } else {
822                         wimlib_assert(&lte->file_on_disk == &lte->staging_file_name);
823                         lte->resource_entry.original_size = stbuf.st_size;
824                         lte->resource_entry.size = stbuf.st_size;
825                         lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
826                         lte->lte_inode = NULL;
827                         copy_hash(lte->hash, hash);
828                         lookup_table_insert(table, lte);
829                 }
830         }
831         return 0;
832 }
833
834 static int inode_close_fds(struct inode *inode)
835 {
836         u16 num_opened_fds = inode->num_opened_fds;
837         for (u16 i = 0, j = 0; j < num_opened_fds; i++) {
838                 struct wimlib_fd *fd = inode->fds[i];
839                 if (fd) {
840                         wimlib_assert(fd->f_inode == inode);
841                         int ret = close_wimlib_fd(fd);
842                         if (ret != 0)
843                                 return ret;
844                         j++;
845                 }
846         }
847         return 0;
848 }
849
850 /* Overwrites the WIM file, with changes saved. */
851 static int rebuild_wim(struct wimfs_context *ctx, bool check_integrity)
852 {
853         int ret;
854         struct lookup_table_entry *lte, *tmp;
855         WIMStruct *w = ctx->wim;
856
857
858         DEBUG("Closing all staging file descriptors.");
859         list_for_each_entry(lte, &ctx->staging_list, staging_list) {
860                 ret = inode_close_fds(lte->lte_inode);
861                 if (ret != 0)
862                         return ret;
863         }
864
865         DEBUG("Calculating SHA1 checksums for all new staging files.");
866         list_for_each_entry_safe(lte, tmp, &ctx->staging_list, staging_list) {
867                 ret = update_lte_of_staging_file(lte, ctx->wim->lookup_table);
868                 if (ret != 0)
869                         return ret;
870         }
871
872         xml_update_image_info(w, w->current_image);
873
874         ret = wimlib_overwrite(w, check_integrity);
875         if (ret != 0) {
876                 ERROR("Failed to commit changes");
877                 return ret;
878         }
879         return ret;
880 }
881
882 /* Called when the filesystem is unmounted. */
883 static void wimfs_destroy(void *p)
884 {
885         /* For read-write mounts, the `imagex unmount' command, which is
886          * running in a separate process and is executing the
887          * wimlib_unmount() function, will send this process a byte
888          * through a message queue that indicates whether the --commit
889          * option was specified or not. */
890
891         long msgsize;
892         struct timespec timeout;
893         struct timeval now;
894         ssize_t bytes_received;
895         int ret;
896         char commit;
897         char check_integrity;
898         char status;
899         char *mailbox;
900         struct wimfs_context *ctx = wimfs_get_context();
901
902         if (open_message_queues(ctx, true))
903                 return;
904
905         if (get_mailbox(ctx->unmount_to_daemon_mq, 2, &msgsize, &mailbox))
906                 goto out_close_message_queues;
907
908         /* Wait at most 3 seconds before giving up and discarding changes. */
909         gettimeofday(&now, NULL);
910         timeout.tv_sec = now.tv_sec + 3;
911         timeout.tv_nsec = now.tv_usec * 1000;
912         DEBUG("Waiting for message telling us whether to commit or not, and "
913               "whether to include integrity checks.");
914
915         bytes_received = mq_timedreceive(ctx->unmount_to_daemon_mq, mailbox,
916                                          msgsize, NULL, &timeout);
917         if (bytes_received == -1) {
918                 ERROR_WITH_ERRNO("mq_timedreceive()");
919                 ERROR("Not committing.");
920                 commit = 0;
921                 check_integrity = 0;
922         } else {
923                 DEBUG("Received message: [%d %d]", mailbox[0], mailbox[1]);
924                 commit = mailbox[0];
925                 check_integrity = mailbox[1];
926         }
927
928         status = 0;
929         if (ctx->mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
930                 if (commit) {
931                         ret = chdir(ctx->working_directory);
932                         if (ret == 0) {
933                                 status = rebuild_wim(ctx, (check_integrity != 0));
934                         } else {
935                                 ERROR_WITH_ERRNO("chdir()");
936                                 status = WIMLIB_ERR_NOTDIR;
937                         }
938                 }
939                 ret = delete_staging_dir(ctx);
940                 if (ret != 0) {
941                         ERROR("Failed to delete the staging directory");
942                         if (status == 0)
943                                 status = ret;
944                 }
945         } else {
946                 DEBUG("Read-only mount");
947         }
948         DEBUG("Sending status %hhd", status);
949         ret = mq_send(ctx->daemon_to_unmount_mq, &status, 1, 1);
950         if (ret == -1)
951                 ERROR_WITH_ERRNO("Failed to send status to unmount process");
952         FREE(mailbox);
953 out_close_message_queues:
954         close_message_queues(ctx);
955 }
956
957 #if 0
958 static int wimfs_fallocate(const char *path, int mode,
959                            off_t offset, off_t len, struct fuse_file_info *fi)
960 {
961         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
962         wimlib_assert(fd->staging_fd != -1);
963         return fallocate(fd->staging_fd, mode, offset, len);
964 }
965
966 #endif
967
968 static int wimfs_fgetattr(const char *path, struct stat *stbuf,
969                           struct fuse_file_info *fi)
970 {
971         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
972         return inode_to_stbuf(fd->f_inode, fd->f_lte, stbuf);
973 }
974
975 static int wimfs_ftruncate(const char *path, off_t size,
976                            struct fuse_file_info *fi)
977 {
978         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
979         int ret = ftruncate(fd->staging_fd, size);
980         if (ret != 0)
981                 return -errno;
982         if (fd->f_lte && size < fd->f_lte->resource_entry.original_size)
983                 fd->f_lte->resource_entry.original_size = size;
984         return 0;
985 }
986
987 /*
988  * Fills in a `struct stat' that corresponds to a file or directory in the WIM.
989  */
990 static int wimfs_getattr(const char *path, struct stat *stbuf)
991 {
992         struct dentry *dentry;
993         struct lookup_table_entry *lte;
994         int ret;
995         struct wimfs_context *ctx = wimfs_get_context();
996
997         ret = lookup_resource(ctx->wim, path,
998                               get_lookup_flags(ctx) | LOOKUP_FLAG_DIRECTORY_OK,
999                               &dentry, &lte, NULL);
1000         if (ret != 0)
1001                 return ret;
1002         return inode_to_stbuf(dentry->d_inode, lte, stbuf);
1003 }
1004
1005 #ifdef ENABLE_XATTR
1006 /* Read an alternate data stream through the XATTR interface, or get its size */
1007 static int wimfs_getxattr(const char *path, const char *name, char *value,
1008                           size_t size)
1009 {
1010         int ret;
1011         struct inode *inode;
1012         struct ads_entry *ads_entry;
1013         size_t res_size;
1014         struct lookup_table_entry *lte;
1015         struct wimfs_context *ctx = wimfs_get_context();
1016
1017         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1018                 return -ENOTSUP;
1019
1020         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1021                 return -ENOATTR;
1022         name += 5;
1023
1024         inode = wim_pathname_to_inode(ctx->wim, path);
1025         if (!inode)
1026                 return -ENOENT;
1027
1028         ads_entry = inode_get_ads_entry(inode, name, NULL);
1029         if (!ads_entry)
1030                 return -ENOATTR;
1031
1032         lte = ads_entry->lte;
1033         res_size = wim_resource_size(lte);
1034
1035         if (size == 0)
1036                 return res_size;
1037
1038         if (res_size > size)
1039                 return -ERANGE;
1040
1041         ret = read_full_wim_resource(lte, (u8*)value);
1042         if (ret != 0)
1043                 return -EIO;
1044
1045         return res_size;
1046 }
1047 #endif
1048
1049 /* Create a hard link */
1050 static int wimfs_link(const char *to, const char *from)
1051 {
1052         struct dentry *from_dentry, *from_dentry_parent;
1053         const char *link_name;
1054         struct inode *inode;
1055         struct lookup_table_entry *lte;
1056         WIMStruct *w = wimfs_get_WIMStruct();
1057
1058         inode = wim_pathname_to_inode(w, to);
1059         if (!inode)
1060                 return -ENOENT;
1061
1062         if (!inode_is_regular_file(inode))
1063                 return -EPERM;
1064
1065         from_dentry_parent = get_parent_dentry(w, from);
1066         if (!from_dentry_parent)
1067                 return -ENOENT;
1068         if (!dentry_is_directory(from_dentry_parent))
1069                 return -ENOTDIR;
1070
1071         link_name = path_basename(from);
1072         if (get_dentry_child_with_name(from_dentry_parent, link_name))
1073                 return -EEXIST;
1074         from_dentry = new_dentry(link_name);
1075         if (!from_dentry)
1076                 return -ENOMEM;
1077
1078
1079         inode_add_dentry(from_dentry, inode);
1080         from_dentry->d_inode = inode;
1081         inode->link_count++;
1082
1083         for (unsigned i = 0; i <= inode->num_ads; i++) {
1084                 lte = inode_stream_lte_resolved(inode, i);
1085                 if (lte)
1086                         lte->refcnt++;
1087         }
1088
1089         link_dentry(from_dentry, from_dentry_parent);
1090         return 0;
1091 }
1092
1093 #ifdef ENABLE_XATTR
1094 static int wimfs_listxattr(const char *path, char *list, size_t size)
1095 {
1096         size_t needed_size;
1097         struct inode *inode;
1098         struct wimfs_context *ctx = wimfs_get_context();
1099
1100         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1101                 return -ENOTSUP;
1102
1103         /* List alternate data streams, or get the list size */
1104
1105         inode = wim_pathname_to_inode(ctx->wim, path);
1106         if (!inode)
1107                 return -ENOENT;
1108
1109         if (size == 0) {
1110                 needed_size = 0;
1111                 for (u16 i = 0; i < inode->num_ads; i++)
1112                         needed_size += inode->ads_entries[i].stream_name_utf8_len + 6;
1113                 return needed_size;
1114         } else {
1115                 char *p = list;
1116                 for (u16 i = 0; i < inode->num_ads; i++) {
1117                         needed_size = inode->ads_entries[i].stream_name_utf8_len + 6;
1118                         if (needed_size > size)
1119                                 return -ERANGE;
1120                         p += sprintf(p, "user.%s",
1121                                      inode->ads_entries[i].stream_name_utf8) + 1;
1122                         size -= needed_size;
1123                 }
1124                 return p - list;
1125         }
1126 }
1127 #endif
1128
1129 /*
1130  * Create a directory in the WIM.
1131  * @mode is currently ignored.
1132  */
1133 static int wimfs_mkdir(const char *path, mode_t mode)
1134 {
1135         struct dentry *parent;
1136         struct dentry *newdir;
1137         const char *basename;
1138         struct wimfs_context *ctx = wimfs_get_context();
1139
1140         parent = get_parent_dentry(ctx->wim, path);
1141         if (!parent)
1142                 return -ENOENT;
1143
1144         if (!dentry_is_directory(parent))
1145                 return -ENOTDIR;
1146
1147         basename = path_basename(path);
1148         if (get_dentry_child_with_name(parent, basename))
1149                 return -EEXIST;
1150
1151         newdir = new_dentry_with_inode(basename);
1152         newdir->d_inode->attributes |= FILE_ATTRIBUTE_DIRECTORY;
1153         newdir->d_inode->resolved = true;
1154         newdir->d_inode->ino = ctx->next_ino++;
1155         link_dentry(newdir, parent);
1156         return 0;
1157 }
1158
1159 /* Creates a regular file. */
1160 static int wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
1161 {
1162         const char *stream_name;
1163         struct wimfs_context *ctx = wimfs_get_context();
1164         if ((ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
1165              && (stream_name = path_stream_name(path))) {
1166                 /* Make an alternate data stream */
1167                 struct ads_entry *new_entry;
1168                 struct inode *inode;
1169
1170                 char *p = (char*)stream_name - 1;
1171                 wimlib_assert(*p == ':');
1172                 *p = '\0';
1173
1174                 inode = wim_pathname_to_inode(ctx->wim, path);
1175                 if (!inode)
1176                         return -ENOENT;
1177                 if (!inode_is_regular_file(inode))
1178                         return -ENOENT;
1179                 if (inode_get_ads_entry(inode, stream_name, NULL))
1180                         return -EEXIST;
1181                 new_entry = inode_add_ads(inode, stream_name);
1182                 if (!new_entry)
1183                         return -ENOMEM;
1184         } else {
1185                 struct dentry *dentry, *parent;
1186                 const char *basename;
1187
1188                 /* Make a normal file (not an alternate data stream) */
1189
1190                 /* Make sure that the parent of @path exists and is a directory, and
1191                  * that the dentry named by @path does not already exist.  */
1192                 parent = get_parent_dentry(ctx->wim, path);
1193                 if (!parent)
1194                         return -ENOENT;
1195                 if (!dentry_is_directory(parent))
1196                         return -ENOTDIR;
1197
1198                 basename = path_basename(path);
1199                 if (get_dentry_child_with_name(parent, path))
1200                         return -EEXIST;
1201
1202                 dentry = new_dentry_with_inode(basename);
1203                 if (!dentry)
1204                         return -ENOMEM;
1205                 dentry->d_inode->resolved = true;
1206                 dentry->d_inode->ino = ctx->next_ino++;
1207                 link_dentry(dentry, parent);
1208         }
1209         return 0;
1210 }
1211
1212
1213 /* Open a file.  */
1214 static int wimfs_open(const char *path, struct fuse_file_info *fi)
1215 {
1216         struct dentry *dentry;
1217         struct lookup_table_entry *lte;
1218         int ret;
1219         struct wimlib_fd *fd;
1220         struct inode *inode;
1221         u16 stream_idx;
1222         u32 stream_id;
1223         struct wimfs_context *ctx = wimfs_get_context();
1224
1225         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1226                               &dentry, &lte, &stream_idx);
1227         if (ret != 0)
1228                 return ret;
1229
1230         inode = dentry->d_inode;
1231
1232         if (stream_idx == 0)
1233                 stream_id = 0;
1234         else
1235                 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
1236
1237         /* The file resource may be in the staging directory (read-write mounts
1238          * only) or in the WIM.  If it's in the staging directory, we need to
1239          * open a native file descriptor for the corresponding file.  Otherwise,
1240          * we can read the file resource directly from the WIM file if we are
1241          * opening it read-only, but we need to extract the resource to the
1242          * staging directory if we are opening it writable. */
1243
1244         if (flags_writable(fi->flags) &&
1245             (!lte || lte->resource_location != RESOURCE_IN_STAGING_FILE)) {
1246                 u64 size = (lte) ? wim_resource_size(lte) : 0;
1247                 ret = extract_resource_to_staging_dir(inode, stream_id,
1248                                                       &lte, size, ctx);
1249                 if (ret != 0)
1250                         return ret;
1251         }
1252
1253         ret = alloc_wimlib_fd(inode, stream_id, lte, &fd);
1254         if (ret != 0)
1255                 return ret;
1256
1257         if (lte && lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1258                 fd->staging_fd = open(lte->staging_file_name, fi->flags);
1259                 if (fd->staging_fd == -1) {
1260                         close_wimlib_fd(fd);
1261                         return -errno;
1262                 }
1263         }
1264         fi->fh = (uintptr_t)fd;
1265         return 0;
1266 }
1267
1268 /* Opens a directory. */
1269 static int wimfs_opendir(const char *path, struct fuse_file_info *fi)
1270 {
1271         struct inode *inode;
1272         int ret;
1273         struct wimlib_fd *fd = NULL;
1274         WIMStruct *w = wimfs_get_WIMStruct();
1275
1276         inode = wim_pathname_to_inode(w, path);
1277         if (!inode)
1278                 return -ENOENT;
1279         if (!inode_is_directory(inode))
1280                 return -ENOTDIR;
1281         ret = alloc_wimlib_fd(inode, 0, NULL, &fd);
1282         fi->fh = (uintptr_t)fd;
1283         return ret;
1284 }
1285
1286
1287 /*
1288  * Read data from a file in the WIM or in the staging directory.
1289  */
1290 static int wimfs_read(const char *path, char *buf, size_t size,
1291                       off_t offset, struct fuse_file_info *fi)
1292 {
1293         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1294
1295         if (!fd)
1296                 return -EBADF;
1297
1298         if (!fd->f_lte) /* Empty stream with no lookup table entry */
1299                 return 0;
1300
1301         if (fd->f_lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1302                 /* Read from staging file */
1303
1304                 wimlib_assert(fd->f_lte->staging_file_name);
1305                 wimlib_assert(fd->staging_fd != -1);
1306
1307                 ssize_t ret;
1308                 DEBUG("Seek to offset %zu", offset);
1309
1310                 if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1311                         return -errno;
1312                 ret = read(fd->staging_fd, buf, size);
1313                 if (ret == -1)
1314                         return -errno;
1315                 return ret;
1316         } else {
1317                 /* Read from WIM */
1318
1319                 u64 res_size = wim_resource_size(fd->f_lte);
1320
1321                 if (offset > res_size)
1322                         return -EOVERFLOW;
1323
1324                 size = min(size, res_size - offset);
1325
1326                 if (read_wim_resource(fd->f_lte, (u8*)buf,
1327                                       size, offset, false) != 0)
1328                         return -EIO;
1329                 return size;
1330         }
1331 }
1332
1333 struct fill_params {
1334         void *buf;
1335         fuse_fill_dir_t filler;
1336 };
1337
1338 static int dentry_fuse_fill(struct dentry *dentry, void *arg)
1339 {
1340         struct fill_params *fill_params = arg;
1341         return fill_params->filler(fill_params->buf, dentry->file_name_utf8,
1342                                    NULL, 0);
1343 }
1344
1345 /* Fills in the entries of the directory specified by @path using the
1346  * FUSE-provided function @filler.  */
1347 static int wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
1348                          off_t offset, struct fuse_file_info *fi)
1349 {
1350         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1351         struct inode *inode;
1352
1353         if (!fd)
1354                 return -EBADF;
1355
1356         inode = fd->f_inode;
1357
1358         struct fill_params fill_params = {
1359                 .buf = buf,
1360                 .filler = filler,
1361         };
1362
1363         filler(buf, ".", NULL, 0);
1364         filler(buf, "..", NULL, 0);
1365
1366         return for_dentry_in_rbtree(inode->children.rb_node,
1367                                     dentry_fuse_fill, &fill_params);
1368 }
1369
1370
1371 static int wimfs_readlink(const char *path, char *buf, size_t buf_len)
1372 {
1373         struct wimfs_context *ctx = wimfs_get_context();
1374         struct inode *inode = wim_pathname_to_inode(ctx->wim, path);
1375         int ret;
1376         if (!inode)
1377                 return -ENOENT;
1378         if (!inode_is_symlink(inode))
1379                 return -EINVAL;
1380
1381         ret = inode_readlink(inode, buf, buf_len, ctx->wim);
1382         if (ret > 0)
1383                 ret = 0;
1384         return ret;
1385 }
1386
1387 /* Close a file. */
1388 static int wimfs_release(const char *path, struct fuse_file_info *fi)
1389 {
1390         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1391         return close_wimlib_fd(fd);
1392 }
1393
1394 /* Close a directory */
1395 static int wimfs_releasedir(const char *path, struct fuse_file_info *fi)
1396 {
1397         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1398         return close_wimlib_fd(fd);
1399 }
1400
1401 #ifdef ENABLE_XATTR
1402 /* Remove an alternate data stream through the XATTR interface */
1403 static int wimfs_removexattr(const char *path, const char *name)
1404 {
1405         struct inode *inode;
1406         struct ads_entry *ads_entry;
1407         u16 ads_idx;
1408         struct wimfs_context *ctx = wimfs_get_context();
1409
1410         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1411                 return -ENOTSUP;
1412
1413         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1414                 return -ENOATTR;
1415         name += 5;
1416
1417         inode = wim_pathname_to_inode(ctx->wim, path);
1418         if (!inode)
1419                 return -ENOENT;
1420
1421         ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
1422         if (!ads_entry)
1423                 return -ENOATTR;
1424         inode_remove_ads(inode, ads_idx, ctx->wim->lookup_table);
1425         return 0;
1426 }
1427 #endif
1428
1429 /* Renames a file or directory.  See rename (3) */
1430 static int wimfs_rename(const char *from, const char *to)
1431 {
1432         struct dentry *src;
1433         struct dentry *dst;
1434         struct dentry *parent_of_dst;
1435         char *file_name_utf16 = NULL, *file_name_utf8 = NULL;
1436         u16 file_name_utf16_len, file_name_utf8_len;
1437         WIMStruct *w = wimfs_get_WIMStruct();
1438         int ret;
1439
1440         /* This rename() implementation currently only supports actual files
1441          * (not alternate data streams) */
1442
1443         src = get_dentry(w, from);
1444         if (!src)
1445                 return -ENOENT;
1446
1447         dst = get_dentry(w, to);
1448
1449
1450         ret = get_names(&file_name_utf16, &file_name_utf8,
1451                         &file_name_utf16_len, &file_name_utf8_len,
1452                         path_basename(to));
1453         if (ret != 0)
1454                 return -ENOMEM;
1455
1456         if (dst) {
1457                 /* Destination file exists */
1458
1459                 if (src == dst) /* Same file */
1460                         return 0;
1461
1462                 if (!dentry_is_directory(src)) {
1463                         /* Cannot rename non-directory to directory. */
1464                         if (dentry_is_directory(dst))
1465                                 return -EISDIR;
1466                 } else {
1467                         /* Cannot rename directory to a non-directory or a non-empty
1468                          * directory */
1469                         if (!dentry_is_directory(dst))
1470                                 return -ENOTDIR;
1471                         if (inode_has_children(dst->d_inode))
1472                                 return -ENOTEMPTY;
1473                 }
1474                 parent_of_dst = dst->parent;
1475                 remove_dentry(dst, w->lookup_table);
1476         } else {
1477                 /* Destination does not exist */
1478                 parent_of_dst = get_parent_dentry(w, to);
1479                 if (!parent_of_dst)
1480                         return -ENOENT;
1481
1482                 if (!dentry_is_directory(parent_of_dst))
1483                         return -ENOTDIR;
1484         }
1485
1486         FREE(src->file_name);
1487         FREE(src->file_name_utf8);
1488         src->file_name          = file_name_utf16;
1489         src->file_name_utf8     = file_name_utf8;
1490         src->file_name_len      = file_name_utf16_len;
1491         src->file_name_utf8_len = file_name_utf8_len;
1492
1493         unlink_dentry(src);
1494         link_dentry(src, parent_of_dst);
1495         return 0;
1496 }
1497
1498 /* Remove a directory */
1499 static int wimfs_rmdir(const char *path)
1500 {
1501         struct dentry *dentry;
1502         WIMStruct *w = wimfs_get_WIMStruct();
1503
1504         dentry = get_dentry(w, path);
1505         if (!dentry)
1506                 return -ENOENT;
1507
1508         if (!dentry_is_empty_directory(dentry))
1509                 return -ENOTEMPTY;
1510
1511         remove_dentry(dentry, w->lookup_table);
1512         return 0;
1513 }
1514
1515 #ifdef ENABLE_XATTR
1516 /* Write an alternate data stream through the XATTR interface */
1517 static int wimfs_setxattr(const char *path, const char *name,
1518                           const char *value, size_t size, int flags)
1519 {
1520         struct ads_entry *existing_ads_entry;
1521         struct ads_entry *new_ads_entry;
1522         struct lookup_table_entry *existing_lte;
1523         struct lookup_table_entry *lte;
1524         struct inode *inode;
1525         u8 value_hash[SHA1_HASH_SIZE];
1526         u16 ads_idx;
1527         struct wimfs_context *ctx = wimfs_get_context();
1528
1529         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1530                 return -ENOTSUP;
1531
1532         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1533                 return -ENOATTR;
1534         name += 5;
1535
1536         inode = wim_pathname_to_inode(ctx->wim, path);
1537         if (!inode)
1538                 return -ENOENT;
1539
1540         existing_ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
1541         if (existing_ads_entry) {
1542                 if (flags & XATTR_CREATE)
1543                         return -EEXIST;
1544                 inode_remove_ads(inode, ads_idx, ctx->wim->lookup_table);
1545         } else {
1546                 if (flags & XATTR_REPLACE)
1547                         return -ENOATTR;
1548         }
1549         new_ads_entry = inode_add_ads(inode, name);
1550         if (!new_ads_entry)
1551                 return -ENOMEM;
1552
1553         sha1_buffer((const u8*)value, size, value_hash);
1554
1555         existing_lte = __lookup_resource(ctx->wim->lookup_table, value_hash);
1556
1557         if (existing_lte) {
1558                 lte = existing_lte;
1559                 lte->refcnt++;
1560         } else {
1561                 u8 *value_copy;
1562                 lte = new_lookup_table_entry();
1563                 if (!lte)
1564                         return -ENOMEM;
1565                 value_copy = MALLOC(size);
1566                 if (!value_copy) {
1567                         FREE(lte);
1568                         return -ENOMEM;
1569                 }
1570                 memcpy(value_copy, value, size);
1571                 lte->resource_location            = RESOURCE_IN_ATTACHED_BUFFER;
1572                 lte->attached_buffer              = value_copy;
1573                 lte->resource_entry.original_size = size;
1574                 lte->resource_entry.size          = size;
1575                 lte->resource_entry.flags         = 0;
1576                 copy_hash(lte->hash, value_hash);
1577                 lookup_table_insert(ctx->wim->lookup_table, lte);
1578         }
1579         new_ads_entry->lte = lte;
1580         return 0;
1581 }
1582 #endif
1583
1584 static int wimfs_symlink(const char *to, const char *from)
1585 {
1586         struct dentry *dentry_parent, *dentry;
1587         const char *link_name;
1588         struct inode *inode;
1589         struct wimfs_context *ctx = wimfs_get_context();
1590
1591         dentry_parent = get_parent_dentry(ctx->wim, from);
1592         if (!dentry_parent)
1593                 return -ENOENT;
1594         if (!dentry_is_directory(dentry_parent))
1595                 return -ENOTDIR;
1596
1597         link_name = path_basename(from);
1598
1599         if (get_dentry_child_with_name(dentry_parent, link_name))
1600                 return -EEXIST;
1601         dentry = new_dentry_with_inode(link_name);
1602         if (!dentry)
1603                 return -ENOMEM;
1604         inode = dentry->d_inode;
1605
1606         inode->attributes  = FILE_ATTRIBUTE_REPARSE_POINT;
1607         inode->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
1608         inode->ino         = ctx->next_ino++;
1609         inode->resolved    = true;
1610
1611         if (inode_set_symlink(inode, to, ctx->wim->lookup_table, NULL) != 0)
1612                 goto out_free_dentry;
1613
1614         link_dentry(dentry, dentry_parent);
1615         return 0;
1616 out_free_dentry:
1617         free_dentry(dentry);
1618         return -ENOMEM;
1619 }
1620
1621
1622 /* Reduce the size of a file */
1623 static int wimfs_truncate(const char *path, off_t size)
1624 {
1625         struct dentry *dentry;
1626         struct lookup_table_entry *lte;
1627         int ret;
1628         u16 stream_idx;
1629         u32 stream_id;
1630         struct inode *inode;
1631         struct wimfs_context *ctx = wimfs_get_context();
1632
1633         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1634                               &dentry, &lte, &stream_idx);
1635
1636         if (ret != 0)
1637                 return ret;
1638
1639         if (!lte) /* Already a zero-length file */
1640                 return 0;
1641
1642         inode = dentry->d_inode;
1643
1644         if (stream_idx == 0)
1645                 stream_id = 0;
1646         else
1647                 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
1648
1649         if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1650                 wimlib_assert(lte->staging_file_name);
1651                 ret = truncate(lte->staging_file_name, size);
1652                 if (ret != 0)
1653                         return -errno;
1654                 lte->resource_entry.original_size = size;
1655         } else {
1656                 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
1657                 /* File in WIM.  Extract it to the staging directory, but only
1658                  * the first @size bytes of it. */
1659                 ret = extract_resource_to_staging_dir(inode, stream_id,
1660                                                       &lte, size, ctx);
1661         }
1662         return ret;
1663 }
1664
1665 /* Remove a regular file */
1666 static int wimfs_unlink(const char *path)
1667 {
1668         struct dentry *dentry;
1669         struct lookup_table_entry *lte;
1670         int ret;
1671         u16 stream_idx;
1672         struct wimfs_context *ctx = wimfs_get_context();
1673
1674         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1675                               &dentry, &lte, &stream_idx);
1676
1677         if (ret != 0)
1678                 return ret;
1679
1680         if (stream_idx == 0)
1681                 remove_dentry(dentry, ctx->wim->lookup_table);
1682         else
1683                 inode_remove_ads(dentry->d_inode, stream_idx - 1,
1684                                  ctx->wim->lookup_table);
1685         return 0;
1686 }
1687
1688 #ifdef HAVE_UTIMENSAT
1689 /*
1690  * Change the timestamp on a file dentry.
1691  *
1692  * Note that alternate data streams do not have their own timestamps.
1693  */
1694 static int wimfs_utimens(const char *path, const struct timespec tv[2])
1695 {
1696         struct dentry *dentry;
1697         struct inode *inode;
1698         WIMStruct *w = wimfs_get_WIMStruct();
1699
1700         dentry = get_dentry(w, path);
1701         if (!dentry)
1702                 return -ENOENT;
1703         inode = dentry->d_inode;
1704
1705         if (tv[0].tv_nsec != UTIME_OMIT) {
1706                 if (tv[0].tv_nsec == UTIME_NOW)
1707                         inode->last_access_time = get_wim_timestamp();
1708                 else
1709                         inode->last_access_time = timespec_to_wim_timestamp(&tv[0]);
1710         }
1711         if (tv[1].tv_nsec != UTIME_OMIT) {
1712                 if (tv[1].tv_nsec == UTIME_NOW)
1713                         inode->last_write_time = get_wim_timestamp();
1714                 else
1715                         inode->last_write_time = timespec_to_wim_timestamp(&tv[1]);
1716         }
1717         return 0;
1718 }
1719 #else
1720 static int wimfs_utime(const char *path, struct utimbuf *times)
1721 {
1722         struct dentry *dentry;
1723         struct inode *inode;
1724         WIMStruct *w = wimfs_get_WIMStruct();
1725
1726         dentry = get_dentry(w, path);
1727         if (!dentry)
1728                 return -ENOENT;
1729         inode = dentry->d_inode;
1730
1731         inode->last_write_time = unix_timestamp_to_wim(times->modtime);
1732         inode->last_access_time = unix_timestamp_to_wim(times->actime);
1733         return 0;
1734 }
1735 #endif
1736
1737 /* Writes to a file in the WIM filesystem.
1738  * It may be an alternate data stream, but here we don't even notice because we
1739  * just get a lookup table entry. */
1740 static int wimfs_write(const char *path, const char *buf, size_t size,
1741                        off_t offset, struct fuse_file_info *fi)
1742 {
1743         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1744         int ret;
1745         u64 now;
1746
1747         if (!fd)
1748                 return -EBADF;
1749
1750         wimlib_assert(fd->f_lte);
1751         wimlib_assert(fd->f_lte->staging_file_name);
1752         wimlib_assert(fd->staging_fd != -1);
1753         wimlib_assert(fd->f_inode);
1754
1755         /* Seek to the requested position */
1756         if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1757                 return -errno;
1758
1759         /* Write the data. */
1760         ret = write(fd->staging_fd, buf, size);
1761         if (ret == -1)
1762                 return -errno;
1763
1764         now = get_wim_timestamp();
1765         fd->f_inode->last_write_time = now;
1766         fd->f_inode->last_access_time = now;
1767         return ret;
1768 }
1769
1770 static struct fuse_operations wimfs_operations = {
1771         .access      = wimfs_access,
1772         .chmod       = wimfs_chmod,
1773         .destroy     = wimfs_destroy,
1774 #if 0
1775         .fallocate   = wimfs_fallocate,
1776 #endif
1777         .fgetattr    = wimfs_fgetattr,
1778         .ftruncate   = wimfs_ftruncate,
1779         .getattr     = wimfs_getattr,
1780 #ifdef ENABLE_XATTR
1781         .getxattr    = wimfs_getxattr,
1782 #endif
1783         .link        = wimfs_link,
1784 #ifdef ENABLE_XATTR
1785         .listxattr   = wimfs_listxattr,
1786 #endif
1787         .mkdir       = wimfs_mkdir,
1788         .mknod       = wimfs_mknod,
1789         .open        = wimfs_open,
1790         .opendir     = wimfs_opendir,
1791         .read        = wimfs_read,
1792         .readdir     = wimfs_readdir,
1793         .readlink    = wimfs_readlink,
1794         .release     = wimfs_release,
1795         .releasedir  = wimfs_releasedir,
1796 #ifdef ENABLE_XATTR
1797         .removexattr = wimfs_removexattr,
1798 #endif
1799         .rename      = wimfs_rename,
1800         .rmdir       = wimfs_rmdir,
1801 #ifdef ENABLE_XATTR
1802         .setxattr    = wimfs_setxattr,
1803 #endif
1804         .symlink     = wimfs_symlink,
1805         .truncate    = wimfs_truncate,
1806         .unlink      = wimfs_unlink,
1807 #ifdef HAVE_UTIMENSAT
1808         .utimens     = wimfs_utimens,
1809 #else
1810         .utime       = wimfs_utime,
1811 #endif
1812         .write       = wimfs_write,
1813 };
1814
1815
1816 /* Mounts a WIM file. */
1817 WIMLIBAPI int wimlib_mount(WIMStruct *wim, int image, const char *dir,
1818                            int flags, WIMStruct **additional_swms,
1819                            unsigned num_additional_swms)
1820 {
1821         int argc = 0;
1822         char *argv[16];
1823         int ret;
1824         char *dir_copy;
1825         struct lookup_table *joined_tab, *wim_tab_save;
1826         struct image_metadata *imd;
1827         struct wimfs_context ctx;
1828
1829         DEBUG("Mount: wim = %p, image = %d, dir = %s, flags = %d, ",
1830               wim, image, dir, flags);
1831
1832         if (!wim || !dir)
1833                 return WIMLIB_ERR_INVALID_PARAM;
1834
1835         ret = verify_swm_set(wim, additional_swms, num_additional_swms);
1836         if (ret != 0)
1837                 return ret;
1838
1839         if (num_additional_swms) {
1840                 ret = new_joined_lookup_table(wim, additional_swms,
1841                                               num_additional_swms,
1842                                               &joined_tab);
1843                 if (ret != 0)
1844                         return ret;
1845                 wim_tab_save = wim->lookup_table;
1846                 wim->lookup_table = joined_tab;
1847         }
1848
1849         ret = select_wim_image(wim, image);
1850
1851         if (ret != 0)
1852                 goto out;
1853
1854         imd = &wim->image_metadata[image - 1];
1855
1856         DEBUG("Selected image %d", image);
1857
1858         if (imd->root_dentry->refcnt != 1) {
1859                 ERROR("Cannot mount image that was just exported with "
1860                       "wimlib_export()");
1861                 ret = WIMLIB_ERR_INVALID_PARAM;
1862                 goto out;
1863         }
1864
1865         if (!(flags & (WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
1866                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
1867                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)))
1868                 flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
1869
1870
1871         DEBUG("Initializing struct wimfs_context");
1872         init_wimfs_context(&ctx);
1873
1874         DEBUG("Getting current directory");
1875         ctx.working_directory = getcwd(NULL, 0);
1876         if (!ctx.working_directory) {
1877                 ERROR_WITH_ERRNO("Could not determine current directory");
1878                 ret = WIMLIB_ERR_NOTDIR;
1879                 goto out;
1880         }
1881
1882         DEBUG("Unlinking message queues in case they already exist");
1883         ret = set_message_queue_names(&ctx, dir);
1884         if (ret != 0)
1885                 goto out_free_working_directory;
1886         unlink_message_queues(&ctx);
1887
1888         DEBUG("Preparing arguments to fuse_main()");
1889
1890         dir_copy = STRDUP(dir);
1891         if (!dir_copy)
1892                 goto out_free_message_queue_names;
1893
1894         argv[argc++] = "imagex";
1895         argv[argc++] = dir_copy;
1896         argv[argc++] = "-s"; /* disable multi-threaded operation */
1897
1898         if (flags & WIMLIB_MOUNT_FLAG_DEBUG)
1899                 argv[argc++] = "-d";
1900
1901         /*
1902          * We provide the use_ino option because we are going to assign inode
1903          * numbers oursides.  The inodes will be given unique numbers in the
1904          * assign_inode_numbers() function, and the static variable @next_ino is
1905          * set to the next available inode number.
1906          */
1907         char optstring[256] = "use_ino,subtype=wimfs,attr_timeout=0";
1908         argv[argc++] = "-o";
1909         argv[argc++] = optstring;
1910         if ((flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
1911                 /* Read-write mount.  Make the staging directory */
1912                 ret = make_staging_dir(&ctx);
1913                 if (ret != 0)
1914                         goto out_free_dir_copy;
1915         } else {
1916                 /* Read-only mount */
1917                 strcat(optstring, ",ro");
1918         }
1919         argv[argc] = NULL;
1920
1921 #ifdef ENABLE_DEBUG
1922         {
1923                 int i;
1924                 DEBUG("FUSE command line (argc = %d): ", argc);
1925                 for (i = 0; i < argc; i++) {
1926                         fputs(argv[i], stdout);
1927                         putchar(' ');
1928                 }
1929                 putchar('\n');
1930                 fflush(stdout);
1931         }
1932 #endif
1933
1934         /* Mark dentry tree as modified if read-write mount. */
1935         if (flags & WIMLIB_MOUNT_FLAG_READWRITE)
1936                 imd->modified = true;
1937
1938         /* Resolve all the lookup table entries of the dentry tree */
1939         DEBUG("Resolving lookup table entries");
1940         for_dentry_in_tree(imd->root_dentry, dentry_resolve_ltes,
1941                            wim->lookup_table);
1942
1943         ctx.next_ino = assign_inode_numbers(&imd->inode_list);
1944         DEBUG("(next_ino = %"PRIu64")", ctx.next_ino);
1945
1946         /* Finish initializing the filesystem context. */
1947         ctx.wim = wim;
1948         ctx.mount_flags = flags;
1949
1950         DEBUG("Calling fuse_main()");
1951
1952         ret = fuse_main(argc, argv, &wimfs_operations, &ctx);
1953
1954         DEBUG("Returned from fuse_main() (ret = %d)", ret);
1955         if (ret)
1956                 ret = WIMLIB_ERR_FUSE;
1957 out_free_dir_copy:
1958         FREE(dir_copy);
1959 out_free_message_queue_names:
1960         free_message_queue_names(&ctx);
1961 out_free_working_directory:
1962         FREE(ctx.working_directory);
1963         ctx.working_directory = NULL;
1964 out:
1965         if (num_additional_swms) {
1966                 free_lookup_table(wim->lookup_table);
1967                 wim->lookup_table = wim_tab_save;
1968         }
1969         return ret;
1970 }
1971
1972
1973 /*
1974  * Unmounts the WIM file that was previously mounted on @dir by using
1975  * wimlib_mount().
1976  */
1977 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
1978 {
1979         pid_t pid;
1980         int status;
1981         int ret;
1982         char msg[2];
1983         struct timeval now;
1984         struct timespec timeout;
1985         long msgsize;
1986         struct wimfs_context ctx;
1987         char *mailbox;
1988
1989         init_wimfs_context(&ctx);
1990
1991         /* Open message queues between the unmount process and the
1992          * filesystem daemon. */
1993         ret = set_message_queue_names(&ctx, dir);
1994         if (ret != 0)
1995                 goto out;
1996
1997         ret = open_message_queues(&ctx, false);
1998         if (ret != 0)
1999                 goto out_free_message_queue_names;
2000
2001         /* Send a message to the filesystem daemon saying whether to commit or
2002          * not. */
2003         msg[0] = (flags & WIMLIB_UNMOUNT_FLAG_COMMIT) ? 1 : 0;
2004         msg[1] = (flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY) ? 1 : 0;
2005
2006         DEBUG("Sending message: %scommit, %scheck",
2007                         (msg[0] ? "" : "don't "),
2008                         (msg[1] ? "" : "don't "));
2009         ret = mq_send(ctx.unmount_to_daemon_mq, msg, 2, 1);
2010         if (ret == -1) {
2011                 ERROR_WITH_ERRNO("Failed to notify filesystem daemon whether "
2012                                  "we want to commit changes or not");
2013                 ret = WIMLIB_ERR_MQUEUE;
2014                 goto out_close_message_queues;
2015         }
2016
2017         /* Execute `fusermount -u', which is installed setuid root, to unmount
2018          * the WIM.
2019          *
2020          * FUSE does not yet implement synchronous unmounts.  This means that
2021          * fusermount -u will return before the filesystem daemon returns from
2022          * wimfs_destroy().  This is partly what we want, because we need to
2023          * send a message from this process to the filesystem daemon telling
2024          * whether --commit was specified or not.  However, after that, the
2025          * unmount process must wait for the filesystem daemon to finish writing
2026          * the WIM file.
2027          */
2028
2029         pid = fork();
2030         if (pid == -1) {
2031                 ERROR_WITH_ERRNO("Failed to fork()");
2032                 ret = WIMLIB_ERR_FORK;
2033                 goto out_close_message_queues;
2034         }
2035         if (pid == 0) {
2036                 /* Child */
2037                 execlp("fusermount", "fusermount", "-u", dir, NULL);
2038                 ERROR_WITH_ERRNO("Failed to execute `fusermount'");
2039                 exit(WIMLIB_ERR_FUSERMOUNT);
2040         }
2041
2042         /* Parent */
2043         ret = wait(&status);
2044         if (ret == -1) {
2045                 ERROR_WITH_ERRNO("Failed to wait for fusermount process to "
2046                                  "terminate");
2047                 ret = WIMLIB_ERR_FUSERMOUNT;
2048                 goto out_close_message_queues;
2049         }
2050
2051         if (status != 0) {
2052                 ERROR("fusermount exited with status %d", status);
2053
2054                 /* Try again, but with the `umount' program.  This is required
2055                  * on other FUSE implementations such as FreeBSD's that do not
2056                  * have a `fusermount' program. */
2057
2058                 pid = fork();
2059                 if (pid == -1) {
2060                         ERROR_WITH_ERRNO("Failed to fork()");
2061                         ret = WIMLIB_ERR_FORK;
2062                         goto out_close_message_queues;
2063                 }
2064                 if (pid == 0) {
2065                         /* Child */
2066                         execlp("umount", "umount", dir, NULL);
2067                         ERROR_WITH_ERRNO("Failed to execute `umount'");
2068                         exit(WIMLIB_ERR_FUSERMOUNT);
2069                 }
2070
2071                 /* Parent */
2072                 ret = wait(&status);
2073                 if (ret == -1) {
2074                         ERROR_WITH_ERRNO("Failed to wait for `umount' process to "
2075                                          "terminate");
2076                         ret = WIMLIB_ERR_FUSERMOUNT;
2077                         goto out_close_message_queues;
2078                 }
2079                 if (status != 0) {
2080                         ERROR("`umount' exited with failure status");
2081                         ret = WIMLIB_ERR_FUSERMOUNT;
2082                         goto out_close_message_queues;
2083                 }
2084         }
2085
2086         wimlib_assert(status == 0);
2087
2088         /* Wait for a message from the filesytem daemon indicating whether  the
2089          * filesystem was unmounted successfully (0) or an error occurred (1).
2090          * This may take a long time if a big WIM file needs to be rewritten. */
2091
2092         /* Wait at most 600??? seconds before giving up and returning false.
2093          * Either it's a really big WIM file, or (more likely) the
2094          * filesystem daemon has crashed or failed for some reason.
2095          *
2096          * XXX come up with some method to determine if the filesystem
2097          * daemon has really crashed or not.
2098          *
2099          * XXX Idea: have mount daemon write its PID into the WIM file header?
2100          * No, this wouldn't work because we know the directory but not the WIM
2101          * file...
2102          * */
2103
2104         gettimeofday(&now, NULL);
2105         timeout.tv_sec = now.tv_sec + 600;
2106         timeout.tv_nsec = now.tv_usec * 1000;
2107
2108         ret = get_mailbox(ctx.daemon_to_unmount_mq, 2, &msgsize, &mailbox);
2109         if (ret != 0)
2110                 goto out_close_message_queues;
2111
2112         mailbox[0] = 0;
2113         DEBUG("Waiting for message telling us whether the unmount was "
2114                         "successful or not.");
2115         ret = mq_timedreceive(ctx.daemon_to_unmount_mq, mailbox,
2116                               msgsize, NULL, &timeout);
2117         if (ret == -1) {
2118                 if (errno == ETIMEDOUT) {
2119                         ERROR("Timed out- probably the filesystem daemon "
2120                               "crashed and the WIM was not written "
2121                               "successfully.");
2122                         ret = WIMLIB_ERR_TIMEOUT;
2123                 } else {
2124                         ERROR_WITH_ERRNO("mq_receive()");
2125                         ret = WIMLIB_ERR_MQUEUE;
2126                 }
2127                 goto out_free_mailbox;
2128
2129         }
2130         DEBUG("Received message: Unmount %s", (mailbox[0] ? "Failed" : "Ok"));
2131         ret = mailbox[0];
2132         if (ret)
2133                 ERROR("Unmount failed");
2134 out_free_mailbox:
2135         FREE(mailbox);
2136 out_close_message_queues:
2137         close_message_queues(&ctx);
2138 out_free_message_queue_names:
2139         free_message_queue_names(&ctx);
2140 out:
2141         return ret;
2142 }
2143
2144 #else /* WITH_FUSE */
2145
2146
2147 static inline int mount_unsupported_error()
2148 {
2149         ERROR("wimlib was compiled with --without-fuse, which disables support "
2150               "for mounting WIMs.");
2151         return WIMLIB_ERR_UNSUPPORTED;
2152 }
2153
2154 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
2155 {
2156         return mount_unsupported_error();
2157 }
2158
2159 WIMLIBAPI int wimlib_mount(WIMStruct *wim_p, int image, const char *dir,
2160                            int flags, WIMStruct **additional_swms,
2161                            unsigned num_additional_swms)
2162 {
2163         return mount_unsupported_error();
2164 }
2165
2166 #endif /* WITH_FUSE */