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