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