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