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