]> wimlib.net Git - wimlib/blob - src/mount.c
b8fe52784c0d85b4603e0f9eb85432337f4f0078
[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 Lesser General Public License as published by the Free
17  * Software Foundation; either version 2.1 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 Lesser General Public License for more
23  * details.
24  *
25  * You should have received a copy of the GNU Lesser General Public License
26  * along with wimlib; if not, see http://www.gnu.org/licenses/.
27  */
28
29 #include "wimlib_internal.h"
30
31 #ifdef WITH_FUSE
32 #include "sha1.h"
33 #include "lookup_table.h"
34 #include "xml.h"
35 #include "io.h"
36 #include "timestamp.h"
37 #include <stdlib.h>
38 #include <unistd.h>
39 #include <sys/wait.h>
40 #define FUSE_USE_VERSION 26
41 #include <errno.h>
42 #include <string.h>
43 #include <sys/time.h>
44 #include <fuse.h>
45 #include <ftw.h>
46 #include <mqueue.h>
47
48 struct wimlib_fd {
49         u16 idx;
50         int staging_fd;
51         u64 hard_link_group;
52         struct lookup_table_entry *lte;
53         struct dentry *dentry;
54 };
55
56 /* The WIMStruct for the mounted WIM. */
57 static WIMStruct *w;
58
59 /* Working directory when `imagex mount' is run. */
60 static const char *working_directory;
61
62 /* Name of the staging directory for a read-write mount.  Whenever a new file is
63  * created, it is done so in the staging directory.  Furthermore, whenever a
64  * file in the WIM is modified, it is extracted to the staging directory.  If
65  * changes are commited when the WIM is unmounted, the file resources are merged
66  * in from the staging directory when writing the new WIM. */
67 static char *staging_dir_name;
68 static size_t staging_dir_name_len;
69
70 /* Flags passed to wimlib_mount(). */
71 static int mount_flags;
72
73 /* Name of the directory on which the WIM file is mounted. */
74 static const char *mount_dir;
75
76
77 static inline int get_lookup_flags()
78 {
79         if (mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
80                 return LOOKUP_FLAG_ADS_OK;
81         else
82                 return 0;
83 }
84
85 static inline int flags_writable(int open_flags)
86 {
87         return open_flags & (O_RDWR | O_WRONLY);
88 }
89
90 static int alloc_wimlib_fd(struct lookup_table_entry *lte,
91                            struct wimlib_fd **fd_ret)
92 {
93         static const u16 fds_per_alloc = 8;
94         static const u16 max_fds = 0xffff;
95
96         if (lte->num_opened_fds == lte->num_allocated_fds) {
97                 struct wimlib_fd **fds;
98                 u16 num_new_fds;
99
100                 if (lte->num_allocated_fds == max_fds)
101                         return -EMFILE;
102                 num_new_fds = min(fds_per_alloc, max_fds - lte->num_allocated_fds);
103                 
104                 fds = CALLOC(lte->num_allocated_fds + num_new_fds,
105                              sizeof(lte->fds[0]));
106                 if (!fds)
107                         return -ENOMEM;
108                 memcpy(fds, lte->fds,
109                        lte->num_allocated_fds * sizeof(lte->fds[0]));
110                 FREE(lte->fds);
111                 lte->fds = fds;
112                 lte->num_allocated_fds += num_new_fds;
113         }
114         for (u16 i = 0; ; i++) {
115                 if (!lte->fds[i]) {
116                         struct wimlib_fd *fd = CALLOC(1, sizeof(*fd));
117                         if (!fd)
118                                 return -ENOMEM;
119                         fd->staging_fd = -1;
120                         fd->idx        = i;
121                         fd->lte        = lte;
122                         lte->fds[i]    = fd;
123                         lte->num_opened_fds++;
124                         *fd_ret        = fd;
125                         return 0;
126                 }
127         }
128 }
129
130 static int close_wimlib_fd(struct wimlib_fd *fd)
131 {
132         struct lookup_table_entry *lte = fd->lte;
133
134         wimlib_assert(lte);
135         wimlib_assert(lte->num_opened_fds);
136
137         if (lte->staging_file_name) {
138                 wimlib_assert(fd->staging_fd != -1);
139                 if (close(fd->staging_fd) != 0)
140                         return -errno;
141         }
142         if (--lte->num_opened_fds == 0 && lte->refcnt == 0)
143                 free_lookup_table_entry(lte);
144         lte->fds[fd->idx] = NULL;
145         FREE(fd);
146         return 0;
147 }
148
149 static void remove_dentry(struct dentry *dentry,
150                           struct lookup_table *lookup_table)
151 {
152         const u8 *hash = dentry->hash;
153         u16 i = 0;
154         struct lookup_table_entry *lte;
155         while (1) {
156                 lte = lookup_table_decrement_refcnt(lookup_table, hash);
157                 if (lte && lte->num_opened_fds)
158                         for (u16 i = 0; i < lte->num_allocated_fds; i++)
159                                 if (lte->fds[i] && lte->fds[i]->dentry == dentry)
160                                         lte->fds[i]->dentry = NULL;
161                 if (i == dentry->num_ads)
162                         break;
163                 hash = dentry->ads_entries[i].hash;
164                 i++;
165         }
166
167         unlink_dentry(dentry);
168         put_dentry(dentry);
169 }
170
171 static void dentry_increment_lookup_table_refcnts(struct dentry *dentry,
172                                                   struct lookup_table *lookup_table)
173 {
174         u16 i = 0;
175         const u8 *hash = dentry->hash;
176         struct lookup_table_entry *lte;
177         while (1) {
178                 lte = __lookup_resource(lookup_table, hash);
179                 if (lte)
180                         lte->refcnt++;
181                 if (i == dentry->num_ads)
182                         break;
183                 hash = dentry->ads_entries[i].hash;
184                 i++;
185         }
186 }
187
188 /* Creates a new staging file and returns its file descriptor opened for
189  * writing.
190  *
191  * @name_ret: A location into which the a pointer to the newly allocated name of
192  *                      the staging file is stored.
193  * @return:  The file descriptor for the new file.  Returns -1 and sets errno on
194  *              error, for any reason possible from the creat() function.
195  */
196 static int create_staging_file(char **name_ret, int open_flags)
197 {
198         size_t name_len;
199         char *name;
200         struct stat stbuf;
201         int fd;
202         int errno_save;
203
204         name_len = staging_dir_name_len + 1 + WIM_HASH_SIZE;
205         name = MALLOC(name_len + 1);
206         if (!name) {
207                 errno = ENOMEM;
208                 return -1;
209         }
210
211         do {
212
213                 memcpy(name, staging_dir_name, staging_dir_name_len);
214                 name[staging_dir_name_len] = '/';
215                 randomize_char_array_with_alnum(name + staging_dir_name_len + 1,
216                                                 WIM_HASH_SIZE);
217                 name[name_len] = '\0';
218
219
220         /* Just in case, verify that the randomly generated name doesn't name an
221          * existing file, and try again if so  */
222         } while (stat(name, &stbuf) == 0);
223
224         if (errno != ENOENT)
225                 /* other error! */
226                 return -1;
227
228         /* doesn't exist--- ok */
229
230         DEBUG("Creating staging file `%s'", name);
231
232         fd = open(name, open_flags | O_CREAT | O_TRUNC, 0600); 
233         if (fd == -1) {
234                 errno_save = errno;
235                 FREE(name);
236                 errno = errno_save;
237         } else {
238                 *name_ret = name;
239         }
240         return fd;
241 }
242
243 /* 
244  * Extract a WIM resource to the staging directory.
245  *
246  * We need to:
247  * - Create a staging file for the WIM resource
248  * - Extract the resource to it
249  * - Create a new lte for the file resource
250  * - Transfer fds from the old lte to the new lte, but
251  *   only if they share the same hard link group as this
252  *   dentry
253  */
254 static int extract_resource_to_staging_dir(struct dentry *dentry,
255                                            struct lookup_table_entry **lte,
256                                            off_t size)
257 {
258         char *staging_file_name;
259         int ret;
260         int fd;
261         struct lookup_table_entry *old_lte, *new_lte;
262         size_t link_group_size;
263
264         old_lte = *lte;
265         fd = create_staging_file(&staging_file_name, O_WRONLY);
266         if (fd == -1)
267                 return -errno;
268
269         if (old_lte)
270                 ret = extract_resource_to_fd(w, &old_lte->resource_entry, fd,
271                                              size);
272         else
273                 ret = 0;
274         if (ret != 0 || close(fd) != 0) {
275                 if (errno != 0)
276                         ret = -errno;
277                 else
278                         ret = -EIO;
279                 close(fd);
280                 goto out_delete_staging_file;
281         }
282
283         link_group_size = dentry_link_group_size(dentry);
284
285         if (old_lte) {
286                 if (link_group_size == old_lte->refcnt) {
287                         /* This hard link group is the only user of the lookup
288                          * table entry, so we can re-use it. */
289                         lookup_table_remove(w->lookup_table, old_lte);
290                         new_lte = old_lte;
291                 } else {
292                         /* Split a hard link group away from the "lookup table
293                          * entry" hard link group (i.e. we had two hard link
294                          * groups that were identical, but now we are changing
295                          * one of them) */
296
297                         /* XXX The ADS really complicate things here and not
298                          * everything is going to work correctly yet.  For
299                          * example it could be the same that a file contains two
300                          * file streams that are identical and therefore share
301                          * the same lookup table entry despite the fact that the
302                          * streams themselves are not hardlinked. */
303                         wimlib_assert(old_lte->refcnt > link_group_size);
304
305                         new_lte = new_lookup_table_entry();
306                         if (!new_lte) {
307                                 ret = -ENOMEM;
308                                 goto out_delete_staging_file;
309                         }
310
311                         u16 num_transferred_fds = 0;
312                         for (u16 i = 0; i < old_lte->num_allocated_fds; i++) {
313                                 if (old_lte->fds[i] &&
314                                     old_lte->fds[i]->dentry->hard_link ==
315                                       dentry->hard_link)
316                                 {
317                                         num_transferred_fds++;
318                                 }
319                         }
320                         new_lte->fds = MALLOC(num_transferred_fds *
321                                               sizeof(new_lte->fds[0]));
322                         if (!new_lte->fds) {
323                                 free_lookup_table_entry(new_lte);
324                                 ret = -ENOMEM;
325                                 goto out_delete_staging_file;
326                         }
327                         u16 j = 0;
328                         for (u16 i = 0; i < old_lte->num_allocated_fds; i++) {
329                                 if (old_lte->fds[i] &&
330                                     old_lte->fds[i]->dentry->hard_link ==
331                                       dentry->hard_link)
332                                 {
333                                         struct wimlib_fd *fd = old_lte->fds[i];
334                                         old_lte->fds[i] = NULL;
335                                         fd->lte = new_lte;
336                                         fd->idx = j;
337                                         new_lte->fds[j] = fd;
338                                 }
339                         }
340                         old_lte->refcnt -= link_group_size;
341                         old_lte->num_opened_fds -= j;
342                         new_lte->num_opened_fds = j;
343
344                 } 
345         } else {
346                 new_lte = new_lookup_table_entry();
347                 if (!new_lte) {
348                         ret = -ENOMEM;
349                         goto out_delete_staging_file;
350                 }
351         }
352         new_lte->resource_entry.original_size = size;
353         new_lte->refcnt = link_group_size;
354         randomize_byte_array(new_lte->hash, WIM_HASH_SIZE);
355         new_lte->staging_file_name = staging_file_name;
356
357         lookup_table_insert(w->lookup_table, new_lte);
358         *lte = new_lte;
359         return 0;
360 out_delete_staging_file:
361         unlink(staging_file_name);
362         FREE(staging_file_name);
363         return ret;
364 }
365
366 /* 
367  * Creates a randomly named staging directory and returns its name into the
368  * static variable staging_dir_name.
369  *
370  * If the staging directory cannot be created, staging_dir_name is set to NULL.
371  * */
372 static void make_staging_dir()
373 {
374         /* XXX Give the user an option of where to stage files */
375
376         static char prefix[] = "wimlib-staging-";
377         static const size_t prefix_len = 15;
378         static const size_t suffix_len = 10;
379
380         size_t pwd_len = strlen(working_directory);
381
382         staging_dir_name_len = pwd_len + 1 + prefix_len + suffix_len;
383
384         staging_dir_name = MALLOC(staging_dir_name_len + 1);
385         if (!staging_dir_name) {
386                 ERROR("Out of memory");
387                 return;
388         }
389
390         memcpy(staging_dir_name, working_directory, pwd_len);
391         staging_dir_name[pwd_len] = '/';
392         memcpy(staging_dir_name + pwd_len + 1, prefix, prefix_len);
393         randomize_char_array_with_alnum(staging_dir_name + pwd_len + 1 + prefix_len,
394                                 suffix_len);
395         staging_dir_name[staging_dir_name_len] = '\0';
396
397         if (mkdir(staging_dir_name, 0700) != 0) {
398                 ERROR_WITH_ERRNO("Failed to create temporary directory `%s'",
399                                  staging_dir_name);
400                 FREE(staging_dir_name);
401                 staging_dir_name = NULL;
402         }
403 }
404
405 static int remove_file_or_directory(const char *fpath, const struct stat *sb,
406                 int typeflag, struct FTW *ftwbuf)
407 {
408         if (remove(fpath) == 0)
409                 return 0;
410         else
411                 return WIMLIB_ERR_DELETE_STAGING_DIR;
412 }
413
414
415 /* 
416  * Deletes the staging directory and all the files contained in it. 
417  */
418 static inline int delete_staging_dir()
419 {
420         int ret;
421         
422         ret = nftw(staging_dir_name, remove_file_or_directory,10, FTW_DEPTH);
423         staging_dir_name = NULL;
424         return ret;
425 }
426
427 /* Name and message queue descriptors for message queues between the filesystem
428  * daemon process and the unmount process.  These are used when the filesystem
429  * is unmounted and the process running wimlib_mount() (i.e. the `imagex
430  * unmount' command) needs to communicate with the filesystem daemon running
431  * fuse_main() (i.e. that spawned by the `imagex mount' or `imagex mountrw'
432  * commands */
433 static char *unmount_to_daemon_mq_name;
434 static char *daemon_to_unmount_mq_name;
435 static int unmount_to_daemon_mq;
436 static int daemon_to_unmount_mq;
437
438 /* Simple function that returns the concatenation of 4 strings. */
439 static char *strcat_dup(const char *s1, const char *s2, const char *s3, 
440                                                         const char *s4)
441 {
442         size_t len = strlen(s1) + strlen(s2) + strlen(s3) + strlen(s4) + 1;
443         char *p = MALLOC(len);
444         if (!p)
445                 return NULL;
446         *p = '\0';
447         strcat(p, s1);
448         strcat(p, s2);
449         strcat(p, s3);
450         strcat(p, s4);
451         return p;
452 }
453
454 /* Removes trailing forward slashes in a string. */
455 static void remove_trailing_slashes(char *s)
456 {
457         long len = strlen(s);
458         for (long i = len - 1; i >= 1; i--) {
459                 if (s[i] == '/')
460                         s[i] = '\0';
461                 else
462                         break;
463         }
464 }
465
466 /* Changes forward slashes to underscores in a string. */
467 static void s_slashes_underscores_g(char *s)
468 {
469         while (*s) {
470                 if (*s == '/')
471                         *s = '_';
472                 s++;
473         }
474 }
475
476 /* 
477  * Opens two POSIX message queue: one for sending messages from the unmount
478  * process to the daemon process, and one to go the other way.  The names of the
479  * message queues, which must be system-wide unique, are be based on the mount
480  * point.  (There of course is still a possibility of a collision if one were to
481  * unmount two identically named directories simultaneously...)
482  *
483  * @daemon specifies whether the calling process is the filesystem daemon or the
484  * unmount process.
485  */
486 static int open_message_queues(bool daemon)
487 {
488         static const char *slash = "/";
489         static const char *prefix = "wimlib-";
490         static const char *u2d_suffix = "unmount-to-daemon-mq";
491         static const char *d2u_suffix = "daemon-to-unmount-mq";
492
493         const char *mount_dir_basename = path_basename(mount_dir);
494         int flags;
495         int ret;
496
497         unmount_to_daemon_mq_name = strcat_dup(slash, mount_dir_basename,
498                                                 prefix, u2d_suffix);
499         if (!unmount_to_daemon_mq_name) {
500                 ERROR("Out of memory");
501                 return WIMLIB_ERR_NOMEM;
502         }
503         daemon_to_unmount_mq_name = strcat_dup(slash, mount_dir_basename,
504                                                 prefix, d2u_suffix);
505         if (!daemon_to_unmount_mq_name) {
506                 ERROR("Out of memory");
507                 ret = WIMLIB_ERR_NOMEM;
508                 goto err1;
509         }
510
511         remove_trailing_slashes(unmount_to_daemon_mq_name);
512         remove_trailing_slashes(daemon_to_unmount_mq_name);
513         s_slashes_underscores_g(unmount_to_daemon_mq_name + 1);
514         s_slashes_underscores_g(daemon_to_unmount_mq_name + 1);
515
516         if (daemon)
517                 flags = O_RDONLY | O_CREAT;
518         else
519                 flags = O_WRONLY | O_CREAT;
520
521         unmount_to_daemon_mq = mq_open(unmount_to_daemon_mq_name, flags, 
522                                        0700, NULL);
523
524         if (unmount_to_daemon_mq == -1) {
525                 ERROR_WITH_ERRNO("mq_open()");
526                 ret = WIMLIB_ERR_MQUEUE;
527                 goto err2;
528         }
529
530         if (daemon)
531                 flags = O_WRONLY | O_CREAT;
532         else
533                 flags = O_RDONLY | O_CREAT;
534
535         daemon_to_unmount_mq = mq_open(daemon_to_unmount_mq_name, flags, 
536                                        0700, NULL);
537
538         if (daemon_to_unmount_mq == -1) {
539                 ERROR_WITH_ERRNO("mq_open()");
540                 ret = WIMLIB_ERR_MQUEUE;
541                 goto err3;
542         }
543         return 0;
544 err3:
545         mq_close(unmount_to_daemon_mq);
546         mq_unlink(unmount_to_daemon_mq_name);
547 err2:
548         FREE(daemon_to_unmount_mq_name);
549 err1:
550         FREE(unmount_to_daemon_mq_name);
551         return ret;
552 }
553
554 static int mq_get_msgsize(mqd_t mq)
555 {
556         static const char *msgsize_max_file = "/proc/sys/fs/mqueue/msgsize_max";
557         FILE *fp;
558         struct mq_attr attr;
559         int msgsize;
560
561         if (mq_getattr(unmount_to_daemon_mq, &attr) == 0) {
562                 msgsize = attr.mq_msgsize;
563         } else {
564                 ERROR_WITH_ERRNO("mq_getattr()");
565                 ERROR("Attempting to read %s", msgsize_max_file);
566                 fp = fopen(msgsize_max_file, "rb");
567                 if (fp) {
568                         if (fscanf(fp, "%d", &msgsize) != 1) {
569                                 ERROR("Assuming message size of 8192");
570                                 msgsize = 8192;
571                         }
572                         fclose(fp);
573                 } else {
574                         ERROR_WITH_ERRNO("Failed to open the file `%s'",
575                                          msgsize_max_file);
576                         ERROR("Assuming message size of 8192");
577                         msgsize = 8192;
578                 }
579         }
580         return msgsize;
581 }
582
583 /* Closes the message queues, which are allocated in static variables */
584 static void close_message_queues()
585 {
586         mq_close(unmount_to_daemon_mq);
587         mq_close(daemon_to_unmount_mq);
588         mq_unlink(unmount_to_daemon_mq_name);
589         mq_unlink(daemon_to_unmount_mq_name);
590 }
591
592 static int wimfs_access(const char *path, int mask)
593 {
594         /* XXX Permissions not implemented */
595         return 0;
596 }
597
598 /* Closes the staging file descriptor associated with the lookup table entry, if
599  * it is opened. */
600 static int close_lte_fds(struct lookup_table_entry *lte, void *ignore)
601 {
602         for (u16 i = 0; i < lte->num_opened_fds; i++) {
603                 if (lte->fds[i] && lte->fds[i]->staging_fd != -1) {
604                         if (close(lte->fds[i]->staging_fd) != 0) {
605                                 ERROR_WITH_ERRNO("Failed close file `%s'",
606                                                  lte->staging_file_name);
607                                 return WIMLIB_ERR_WRITE;
608                         }
609                 }
610         }
611         return 0;
612 }
613
614
615 /* Calculates the SHA1 sum for @dentry if its file resource is in a staging
616  * file.  Updates the SHA1 sum in the dentry and the lookup table entry.  If
617  * there is already a lookup table entry with the same checksum, increment its
618  * reference count and destroy the lookup entry with the updated checksum. */
619 static int calculate_sha1sum_for_staging_file(struct dentry *dentry,
620                                               void *_lookup_table)
621 {
622         struct lookup_table *lookup_table =  _lookup_table;
623         u8 *hash = dentry->hash;
624         u16 i = 0;
625         while (1) {
626                 struct lookup_table_entry *lte = __lookup_resource(lookup_table, hash);
627                 if (lte && lte->staging_file_name) {
628                         struct lookup_table_entry *existing;
629                         int ret;
630
631                         DEBUG("Calculating SHA1 hash for file `%s'",
632                               dentry->file_name_utf8);
633                         ret = sha1sum(lte->staging_file_name, lte->hash);
634                         if (ret != 0)
635                                 return ret;
636
637                         lookup_table_unlink(lookup_table, lte);
638                         memcpy(hash, lte->hash, WIM_HASH_SIZE);
639                         existing = __lookup_resource(lookup_table, hash);
640                         if (existing) {
641                                 DEBUG("Merging duplicate lookup table entries for file "
642                                       "`%s'", dentry->file_name_utf8);
643                                 free_lookup_table_entry(lte);
644                                 existing->refcnt++;
645                         } else {
646                                 lookup_table_insert(lookup_table, lte);
647                         }
648                 }
649                 if (i == dentry->num_ads)
650                         break;
651                 hash = dentry->ads_entries[i].hash;
652                 i++;
653         }
654         return 0;
655 }
656
657 /* Overwrites the WIM file, with changes saved. */
658 static int rebuild_wim(WIMStruct *w, bool check_integrity)
659 {
660         int ret;
661         struct dentry *root;
662
663         root = wim_root_dentry(w);
664
665         DEBUG("Closing all staging file descriptors.");
666         /* Close all the staging file descriptors. */
667         ret = for_lookup_table_entry(w->lookup_table, close_lte_fds, NULL);
668         if (ret != 0) {
669                 ERROR("Failed to close all staging files");
670                 return ret;
671         }
672
673         DEBUG("Calculating SHA1 checksums for all new staging files.");
674         /* Calculate SHA1 checksums for all staging files, and merge unnecessary
675          * lookup table entries. */
676         ret = for_dentry_in_tree(root, calculate_sha1sum_for_staging_file,
677                                  w->lookup_table);
678         if (ret != 0) {
679                 ERROR("Failed to calculate new SHA1 checksums");
680                 return ret;
681         }
682
683         xml_update_image_info(w, w->current_image);
684
685         ret = wimlib_overwrite(w, check_integrity);
686         if (ret != 0) {
687                 ERROR("Failed to commit changes");
688                 return ret;
689         }
690         return ret;
691 }
692
693 /* Called when the filesystem is unmounted. */
694 static void wimfs_destroy(void *p)
695 {
696
697         /* For read-write mounts, the `imagex unmount' command, which is
698          * running in a separate process and is executing the
699          * wimlib_unmount() function, will send this process a byte
700          * through a message queue that indicates whether the --commit
701          * option was specified or not. */
702
703         int msgsize;
704         struct timespec timeout;
705         struct timeval now;
706         ssize_t bytes_received;
707         int ret;
708         char commit;
709         char check_integrity;
710         char status;
711
712         ret = open_message_queues(true);
713         if (ret != 0)
714                 exit(1);
715
716         msgsize = mq_get_msgsize(unmount_to_daemon_mq);
717         char msg[msgsize];
718         msg[0] = 0;
719         msg[1] = 0;
720
721         /* Wait at most 3 seconds before giving up and discarding changes. */
722         gettimeofday(&now, NULL);
723         timeout.tv_sec = now.tv_sec + 3;
724         timeout.tv_nsec = now.tv_usec * 1000;
725         DEBUG("Waiting for message telling us whether to commit or not, and "
726               "whether to include integrity checks.");
727
728         bytes_received = mq_timedreceive(unmount_to_daemon_mq, msg, 
729                                          msgsize, NULL, &timeout);
730         commit = msg[0];
731         check_integrity = msg[1];
732         if (bytes_received == -1) {
733                 if (errno == ETIMEDOUT) {
734                         ERROR("Timed out.");
735                 } else {
736                         ERROR_WITH_ERRNO("mq_timedreceive()");
737                 }
738                 ERROR("Not committing.");
739         } else {
740                 DEBUG("Received message: [%d %d]", msg[0], msg[1]);
741         }
742
743         status = 0;
744         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
745                 if (commit) {
746                         status = chdir(working_directory);
747                         if (status != 0) {
748                                 ERROR_WITH_ERRNO("chdir()");
749                                 status = WIMLIB_ERR_NOTDIR;
750                                 goto done;
751                         }
752                         status = rebuild_wim(w, (check_integrity != 0));
753                 }
754                 ret = delete_staging_dir();
755                 if (ret != 0) {
756                         ERROR_WITH_ERRNO("Failed to delete the staging "
757                                          "directory");
758                         if (status == 0)
759                                 status = ret;
760                 }
761         }
762 done:
763         ret = mq_send(daemon_to_unmount_mq, &status, 1, 1);
764         if (ret == -1)
765                 ERROR_WITH_ERRNO("Failed to send status to unmount process");
766         close_message_queues();
767 }
768
769 static int wimfs_fgetattr(const char *path, struct stat *stbuf,
770                           struct fuse_file_info *fi)
771 {
772         struct wimlib_fd *fd = (struct wimlib_fd*)fi->fh;
773         dentry_to_stbuf(fd->dentry, stbuf, w->lookup_table);
774         return 0;
775 }
776
777 static int wimfs_ftruncate(const char *path, off_t size,
778                            struct fuse_file_info *fi)
779 {
780         struct wimlib_fd *fd = (struct wimlib_fd*)fi->fh;
781         int ret = ftruncate(fd->staging_fd, size);
782         if (ret != 0)
783                 return ret;
784         fd->lte->resource_entry.original_size = size;
785         return 0;
786 }
787
788 /*
789  * Fills in a `struct stat' that corresponds to a file or directory in the WIM.
790  */
791 static int wimfs_getattr(const char *path, struct stat *stbuf)
792 {
793         struct dentry *dentry = get_dentry(w, path);
794         if (!dentry)
795                 return -ENOENT;
796         dentry_to_stbuf(dentry, stbuf, w->lookup_table);
797         return 0;
798 }
799
800 /* Create a hard link */
801 static int wimfs_link(const char *to, const char *from)
802 {
803         struct dentry *to_dentry, *from_dentry, *from_dentry_parent;
804         const char *link_name;
805
806         to_dentry = get_dentry(w, to);
807         if (!to_dentry)
808                 return -ENOENT;
809         if (!dentry_is_regular_file(to_dentry))
810                 return -EPERM;
811
812         from_dentry_parent = get_parent_dentry(w, from);
813         if (!from_dentry_parent)
814                 return -ENOENT;
815         if (!dentry_is_directory(from_dentry_parent))
816                 return -ENOTDIR;
817
818         link_name = path_basename(from);
819         if (get_dentry_child_with_name(from_dentry_parent, link_name))
820                 return -EEXIST;
821         from_dentry = clone_dentry(to_dentry);
822         if (!from_dentry)
823                 return -ENOMEM;
824         if (change_dentry_name(from_dentry, link_name) != 0) {
825                 FREE(from_dentry);
826                 return -ENOMEM;
827         }
828         list_add(&from_dentry->link_group_list, &to_dentry->link_group_list);
829         link_dentry(from_dentry, from_dentry_parent);
830         dentry_increment_lookup_table_refcnts(from_dentry, w->lookup_table);
831         return 0;
832 }
833
834 /* 
835  * Create a directory in the WIM.  
836  * @mode is currently ignored.
837  */
838 static int wimfs_mkdir(const char *path, mode_t mode)
839 {
840         struct dentry *parent;
841         struct dentry *newdir;
842         const char *basename;
843         
844         parent = get_parent_dentry(w, path);
845         if (!parent)
846                 return -ENOENT;
847
848         if (!dentry_is_directory(parent))
849                 return -ENOTDIR;
850
851         basename = path_basename(path);
852         if (get_dentry_child_with_name(parent, basename))
853                 return -EEXIST;
854
855         newdir = new_dentry(basename);
856         newdir->attributes |= FILE_ATTRIBUTE_DIRECTORY;
857         link_dentry(newdir, parent);
858         return 0;
859 }
860
861
862 /* Creates a regular file. */
863 static int wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
864 {
865         const char *stream_name;
866         if ((mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
867              && (stream_name = path_stream_name(path))) {
868                 struct ads_entry *new_entry;
869                 struct dentry *dentry;
870
871                 dentry = get_dentry(w, path);
872                 if (!dentry || !dentry_is_regular_file(dentry))
873                         return -ENOENT;
874                 if (dentry_get_ads_entry(dentry, stream_name))
875                         return -EEXIST;
876                 new_entry = dentry_add_ads(dentry, stream_name);
877                 if (!new_entry)
878                         return -ENOENT;
879         } else {
880                 struct dentry *dentry, *parent;
881                 const char *basename;
882
883                 /* Make sure that the parent of @path exists and is a directory, and
884                  * that the dentry named by @path does not already exist.  */
885                 parent = get_parent_dentry(w, path);
886                 if (!parent)
887                         return -ENOENT;
888                 if (!dentry_is_directory(parent))
889                         return -ENOTDIR;
890
891                 basename = path_basename(path);
892                 if (get_dentry_child_with_name(parent, path))
893                         return -EEXIST;
894
895                 dentry = new_dentry(basename);
896                 if (!dentry)
897                         return -ENOMEM;
898                 link_dentry(dentry, parent);
899         }
900         return 0;
901 }
902
903
904 /* Open a file.  */
905 static int wimfs_open(const char *path, struct fuse_file_info *fi)
906 {
907         struct dentry *dentry;
908         struct lookup_table_entry *lte;
909         u8 *dentry_hash;
910         int ret;
911         struct wimlib_fd *fd;
912
913         ret = lookup_resource(w, path, get_lookup_flags(), &dentry, &lte,
914                               &dentry_hash);
915         if (ret != 0)
916                 return ret;
917
918         if (!lte) {
919                 /* Empty file with no lookup-table entry.  This is fine if it's
920                  * a read-only filesystem.  Otherwise we need to create a lookup
921                  * table entry so that we can keep track of the file descriptors
922                  * (this is important in case someone opens the file for
923                  * writing) */
924                 if (!(mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
925                         fi->fh = 0;
926                         return 0;
927                 }
928
929                 ret = extract_resource_to_staging_dir(dentry, &lte, 0);
930                 if (ret != 0)
931                         return ret;
932                 memcpy(dentry_hash, lte->hash, WIM_HASH_SIZE);
933         }
934
935         ret = alloc_wimlib_fd(lte, &fd);
936         if (ret != 0)
937                 return ret;
938
939         fd->dentry = dentry;
940
941         /* The file resource may be in the staging directory (read-write
942          * mounts only) or in the WIM.  If it's in the staging
943          * directory, we need to open a native file descriptor for the
944          * corresponding file.  Otherwise, we can read the file resource
945          * directly from the WIM file if we are opening it read-only,
946          * but we need to extract the resource to the staging directory
947          * if we are opening it writable. */
948         if (flags_writable(fi->flags) && !lte->staging_file_name) {
949                 ret = extract_resource_to_staging_dir(dentry, &lte,
950                                                       lte->resource_entry.original_size);
951                 if (ret != 0)
952                         return ret;
953                 memcpy(dentry_hash, lte->hash, WIM_HASH_SIZE);
954         }
955         if (lte->staging_file_name) {
956                 fd->staging_fd = open(lte->staging_file_name, fi->flags);
957                 if (fd->staging_fd == -1) {
958                         close_wimlib_fd(fd);
959                         return -errno;
960                 }
961         }
962         fi->fh = (uint64_t)fd;
963         return 0;
964 }
965
966 /* Opens a directory. */
967 static int wimfs_opendir(const char *path, struct fuse_file_info *fi)
968 {
969         struct dentry *dentry;
970         
971         dentry = get_dentry(w, path);
972         if (!dentry)
973                 return -ENOENT;
974         if (!dentry_is_directory(dentry))
975                 return -ENOTDIR;
976         dentry->num_times_opened++;
977         fi->fh = (uint64_t)dentry;
978         return 0;
979 }
980
981
982 /*
983  * Read data from a file in the WIM or in the staging directory. 
984  */
985 static int wimfs_read(const char *path, char *buf, size_t size, 
986                       off_t offset, struct fuse_file_info *fi)
987 {
988         struct wimlib_fd *fd = (struct wimlib_fd*)fi->fh;
989
990         if (!fd) {
991                 /* Empty file with no lookup table entry on read-only mounted
992                  * WIM */
993                 wimlib_assert(!(mount_flags & WIMLIB_MOUNT_FLAG_READWRITE));
994                 return 0;
995         }
996
997         if (fd->lte->staging_file_name) {
998                 /* Read from staging file */
999
1000                 wimlib_assert(fd->staging_fd != -1);
1001
1002                 ssize_t ret;
1003                 DEBUG("Seek to offset %zu", offset);
1004
1005                 if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1006                         return -errno;
1007                 ret = read(fd->staging_fd, buf, size);
1008                 if (ret == -1)
1009                         return -errno;
1010                 return ret;
1011         } else {
1012
1013                 /* Read from WIM */
1014
1015                 struct resource_entry *res_entry;
1016                 int ctype;
1017                 
1018                 res_entry = &fd->lte->resource_entry;
1019
1020                 ctype = wim_resource_compression_type(w, res_entry);
1021
1022                 if (offset > res_entry->original_size)
1023                         return -EOVERFLOW;
1024
1025                 size = min(size, res_entry->original_size - offset);
1026
1027                 if (read_resource(w->fp, res_entry->size, 
1028                                   res_entry->original_size,
1029                                   res_entry->offset, ctype, size, 
1030                                   offset, buf) != 0)
1031                         return -EIO;
1032                 return size;
1033         }
1034 }
1035
1036 /* Fills in the entries of the directory specified by @path using the
1037  * FUSE-provided function @filler.  */
1038 static int wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, 
1039                                 off_t offset, struct fuse_file_info *fi)
1040 {
1041         struct dentry *parent, *child;
1042         
1043         parent = (struct dentry*)fi->fh;
1044         child = parent->children;
1045
1046         filler(buf, ".", NULL, 0);
1047         filler(buf, "..", NULL, 0);
1048
1049         if (!child)
1050                 return 0;
1051
1052         do {
1053                 if (filler(buf, child->file_name_utf8, NULL, 0))
1054                         return 0;
1055                 child = child->next;
1056         } while (child != parent->children);
1057         return 0;
1058 }
1059
1060
1061 static int wimfs_readlink(const char *path, char *buf, size_t buf_len)
1062 {
1063         struct dentry *dentry = get_dentry(w, path);
1064         int ret;
1065         if (!dentry)
1066                 return -ENOENT;
1067         if (!dentry_is_symlink(dentry))
1068                 return -EINVAL;
1069
1070         ret = dentry_readlink(dentry, buf, buf_len, w);
1071         if (ret > 0)
1072                 ret = 0;
1073         return ret;
1074 }
1075
1076 /* Close a file. */
1077 static int wimfs_release(const char *path, struct fuse_file_info *fi)
1078 {
1079         int ret;
1080         struct wimlib_fd *fd = (struct wimlib_fd*)fi->fh;
1081
1082         if (!fd) {
1083                 /* Empty file with no lookup table entry on read-only mounted
1084                  * WIM */
1085                 wimlib_assert(!(mount_flags & WIMLIB_MOUNT_FLAG_READWRITE));
1086                 return 0;
1087         }
1088
1089         if (flags_writable(fi->flags) && fd->dentry) {
1090                 u64 now = get_timestamp();
1091                 fd->dentry->last_access_time = now;
1092                 fd->dentry->last_write_time = now;
1093         }
1094
1095         return close_wimlib_fd(fd);
1096 }
1097
1098 static int wimfs_releasedir(const char *path, struct fuse_file_info *fi)
1099 {
1100         struct dentry *dentry = (struct dentry *)fi->fh;
1101
1102         wimlib_assert(dentry->num_times_opened);
1103         if (--dentry->num_times_opened == 0)
1104                 free_dentry(dentry);
1105         return 0;
1106 }
1107
1108 /* Renames a file or directory.  See rename (3) */
1109 static int wimfs_rename(const char *from, const char *to)
1110 {
1111         struct dentry *src;
1112         struct dentry *dst;
1113         struct dentry *parent_of_dst;
1114         char *file_name_utf16 = NULL, *file_name_utf8 = NULL;
1115         u16 file_name_utf16_len, file_name_utf8_len;
1116         int ret;
1117
1118         /* This rename() implementation currently only supports actual files
1119          * (not alternate data streams) */
1120         
1121         src = get_dentry(w, from);
1122         if (!src)
1123                 return -ENOENT;
1124
1125         dst = get_dentry(w, to);
1126
1127
1128         ret = get_names(&file_name_utf16, &file_name_utf8,
1129                         &file_name_utf16_len, &file_name_utf8_len,
1130                         path_basename(to));
1131         if (ret != 0)
1132                 return -ENOMEM;
1133
1134         if (dst) {
1135                 if (src == dst) /* Same file */
1136                         return 0;
1137
1138                 if (!dentry_is_directory(src)) {
1139                         /* Cannot rename non-directory to directory. */
1140                         if (dentry_is_directory(dst))
1141                                 return -EISDIR;
1142                 } else {
1143                         /* Cannot rename directory to a non-directory or a non-empty
1144                          * directory */
1145                         if (!dentry_is_directory(dst))
1146                                 return -ENOTDIR;
1147                         if (dst->children != NULL)
1148                                 return -ENOTEMPTY;
1149                 }
1150                 parent_of_dst = dst->parent;
1151                 remove_dentry(dst, w->lookup_table);
1152         } else {
1153                 parent_of_dst = get_parent_dentry(w, to);
1154                 if (!parent_of_dst)
1155                         return -ENOENT;
1156         }
1157
1158         FREE(src->file_name);
1159         FREE(src->file_name_utf8);
1160         src->file_name          = file_name_utf16;
1161         src->file_name_utf8     = file_name_utf8;
1162         src->file_name_len      = file_name_utf16_len;
1163         src->file_name_utf8_len = file_name_utf8_len;
1164
1165         unlink_dentry(src);
1166         link_dentry(src, parent_of_dst);
1167         return 0;
1168 }
1169
1170 /* Remove a directory */
1171 static int wimfs_rmdir(const char *path)
1172 {
1173         struct dentry *dentry;
1174         
1175         dentry = get_dentry(w, path);
1176         if (!dentry)
1177                 return -ENOENT;
1178
1179         if (!dentry_is_empty_directory(dentry))
1180                 return -ENOTEMPTY;
1181
1182         unlink_dentry(dentry);
1183         if (dentry->num_times_opened == 0)
1184                 free_dentry(dentry);
1185         return 0;
1186 }
1187
1188 static int wimfs_symlink(const char *to, const char *from)
1189 {
1190         struct dentry *dentry_parent, *dentry;
1191         const char *link_name;
1192         
1193         dentry_parent = get_parent_dentry(w, from);
1194         if (!dentry_parent)
1195                 return -ENOENT;
1196         if (!dentry_is_directory(dentry_parent))
1197                 return -ENOTDIR;
1198
1199         link_name = path_basename(from);
1200
1201         if (get_dentry_child_with_name(dentry_parent, link_name))
1202                 return -EEXIST;
1203         dentry = new_dentry(link_name);
1204         if (!dentry)
1205                 return -ENOMEM;
1206
1207         dentry->attributes = FILE_ATTRIBUTE_REPARSE_POINT;
1208         dentry->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
1209
1210         if (dentry_set_symlink(dentry, to, w->lookup_table) != 0)
1211                 goto out_free_dentry;
1212
1213         link_dentry(dentry, dentry_parent);
1214         return 0;
1215 out_free_dentry:
1216         free_dentry(dentry);
1217         return -ENOMEM;
1218 }
1219
1220
1221 /* Reduce the size of a file */
1222 static int wimfs_truncate(const char *path, off_t size)
1223 {
1224         struct dentry *dentry;
1225         struct lookup_table_entry *lte;
1226         int ret;
1227         u8 *dentry_hash;
1228         
1229         ret = lookup_resource(w, path, get_lookup_flags(), &dentry,
1230                               &lte, &dentry_hash);
1231
1232         if (ret != 0)
1233                 return ret;
1234
1235         if (!lte) /* Already a zero-length file */
1236                 return 0;
1237
1238         if (lte->staging_file_name) {
1239                 ret = truncate(lte->staging_file_name, size);
1240                 if (ret != 0)
1241                         return -errno;
1242                 lte->resource_entry.original_size = size;
1243         } else {
1244                 /* File in WIM.  Extract it to the staging directory, but only
1245                  * the first @size bytes of it. */
1246                 ret = extract_resource_to_staging_dir(dentry, &lte, size);
1247         }
1248         dentry_update_all_timestamps(dentry);
1249         return ret;
1250 }
1251
1252 /* Remove a regular file */
1253 static int wimfs_unlink(const char *path)
1254 {
1255         struct dentry *dentry;
1256         struct lookup_table_entry *lte;
1257         int ret;
1258         u8 *dentry_hash;
1259         
1260         ret = lookup_resource(w, path, get_lookup_flags(), &dentry,
1261                               &lte, &dentry_hash);
1262
1263         if (ret != 0)
1264                 return ret;
1265
1266         if (lte && lte->staging_file_name)
1267                 if (unlink(lte->staging_file_name) != 0)
1268                         return -errno;
1269
1270         if (dentry_hash == dentry->hash) {
1271                 /* We are removing the full dentry including all alternate data
1272                  * streams. */
1273                 remove_dentry(dentry, w->lookup_table);
1274         } else {
1275                 /* We are removing an alternate data stream. */
1276                 struct ads_entry *cur_entry = dentry->ads_entries;
1277                 while (cur_entry->hash != dentry_hash)
1278                         cur_entry++;
1279                 lookup_table_decrement_refcnt(w->lookup_table, cur_entry->hash);
1280                 
1281                 dentry_remove_ads(dentry, cur_entry);
1282         }
1283         /* Beware: The lookup table entry(s) may still be referenced by users
1284          * that have opened the corresponding streams.  They are freed later in
1285          * wimfs_release() when the last file user has closed the stream. */
1286         return 0;
1287 }
1288
1289 /* Change the timestamp on a file dentry. 
1290  *
1291  * There is no distinction between a file and its alternate data streams here.  */
1292 static int wimfs_utimens(const char *path, const struct timespec tv[2])
1293 {
1294         struct dentry *dentry = get_dentry(w, path);
1295         if (!dentry)
1296                 return -ENOENT;
1297         time_t last_access_t = (tv[0].tv_nsec == UTIME_NOW) ? 
1298                                 time(NULL) : tv[0].tv_sec;
1299         dentry->last_access_time = unix_timestamp_to_ms(last_access_t);
1300         time_t last_mod_t = (tv[1].tv_nsec == UTIME_NOW) ?  
1301                                 time(NULL) : tv[1].tv_sec;
1302         dentry->last_write_time = unix_timestamp_to_ms(last_mod_t);
1303         return 0;
1304 }
1305
1306 /* Writes to a file in the WIM filesystem. 
1307  * It may be an alternate data stream, but here we don't even notice because we
1308  * just get a lookup table entry. */
1309 static int wimfs_write(const char *path, const char *buf, size_t size, 
1310                        off_t offset, struct fuse_file_info *fi)
1311 {
1312         struct wimlib_fd *fd = (struct wimlib_fd*)fi->fh;
1313         int ret;
1314
1315         wimlib_assert(fd->lte);
1316         wimlib_assert(fd->lte->staging_file_name);
1317         wimlib_assert(fd->staging_fd != -1);
1318
1319         /* Write the data. */
1320         ret = write(fd->staging_fd, buf, size);
1321         if (ret == -1)
1322                 return -errno;
1323
1324         return ret;
1325 }
1326
1327
1328 static struct fuse_operations wimfs_operations = {
1329         .access     = wimfs_access,
1330         .destroy    = wimfs_destroy,
1331         .fgetattr   = wimfs_fgetattr,
1332         .ftruncate  = wimfs_ftruncate,
1333         .getattr    = wimfs_getattr,
1334         .link       = wimfs_link,
1335         .mkdir      = wimfs_mkdir,
1336         .mknod      = wimfs_mknod,
1337         .open       = wimfs_open,
1338         .opendir    = wimfs_opendir,
1339         .read       = wimfs_read,
1340         .readdir    = wimfs_readdir,
1341         .readlink   = wimfs_readlink,
1342         .release    = wimfs_release,
1343         .releasedir = wimfs_releasedir,
1344         .rename     = wimfs_rename,
1345         .rmdir      = wimfs_rmdir,
1346         .symlink    = wimfs_symlink,
1347         .truncate   = wimfs_truncate,
1348         .unlink     = wimfs_unlink,
1349         .utimens    = wimfs_utimens,
1350         .write      = wimfs_write,
1351 };
1352
1353
1354 /* Mounts a WIM file. */
1355 WIMLIBAPI int wimlib_mount(WIMStruct *wim, int image, const char *dir, 
1356                            int flags)
1357 {
1358         int argc = 0;
1359         char *argv[6];
1360         int ret;
1361         char *p;
1362
1363         DEBUG("Mount: wim = %p, image = %d, dir = %s, flags = %d, ",
1364                         wim, image, dir, flags);
1365
1366         if (!dir)
1367                 return WIMLIB_ERR_INVALID_PARAM;
1368
1369         ret = wimlib_select_image(wim, image);
1370
1371         if (ret != 0)
1372                 return ret;
1373
1374         if (flags & WIMLIB_MOUNT_FLAG_READWRITE)
1375                 wim_get_current_image_metadata(wim)->modified = true;
1376
1377         if (!(flags & (WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
1378                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
1379                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)))
1380                 flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
1381
1382         mount_dir = dir;
1383         working_directory = getcwd(NULL, 0);
1384         if (!working_directory) {
1385                 ERROR_WITH_ERRNO("Could not determine current directory");
1386                 return WIMLIB_ERR_NOTDIR;
1387         }
1388
1389         p = STRDUP(dir);
1390         if (!p)
1391                 return WIMLIB_ERR_NOMEM;
1392
1393         argv[argc++] = "mount";
1394         argv[argc++] = p;
1395         argv[argc++] = "-s"; /* disable multi-threaded operation */
1396
1397         if (flags & WIMLIB_MOUNT_FLAG_DEBUG) {
1398                 argv[argc++] = "-d";
1399         }
1400         if (!(flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
1401                 argv[argc++] = "-o";
1402                 argv[argc++] = "ro";
1403         } else {
1404                 make_staging_dir();
1405                 if (!staging_dir_name) {
1406                         FREE(p);
1407                         return WIMLIB_ERR_MKDIR;
1408                 }
1409         }
1410
1411 #ifdef ENABLE_DEBUG
1412         {
1413                 int i;
1414                 DEBUG("FUSE command line (argc = %d): ", argc);
1415                 for (i = 0; i < argc; i++) {
1416                         fputs(argv[i], stdout);
1417                         putchar(' ');
1418                 }
1419                 putchar('\n');
1420                 fflush(stdout);
1421         }
1422 #endif
1423
1424         /* Set static variables. */
1425         w = wim;
1426         mount_flags = flags;
1427
1428         ret = fuse_main(argc, argv, &wimfs_operations, NULL);
1429
1430         return (ret == 0) ? 0 : WIMLIB_ERR_FUSE;
1431 }
1432
1433
1434 /* 
1435  * Unmounts the WIM file that was previously mounted on @dir by using
1436  * wimlib_mount().
1437  */
1438 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
1439 {
1440         pid_t pid;
1441         int status;
1442         int ret;
1443         char msg[2];
1444         struct timeval now;
1445         struct timespec timeout;
1446         int msgsize;
1447         int errno_save;
1448
1449         /* Execute `fusermount -u', which is installed setuid root, to unmount
1450          * the WIM.
1451          *
1452          * FUSE does not yet implement synchronous unmounts.  This means that
1453          * fusermount -u will return before the filesystem daemon returns from
1454          * wimfs_destroy().  This is partly what we want, because we need to
1455          * send a message from this process to the filesystem daemon telling
1456          * whether --commit was specified or not.  However, after that, the
1457          * unmount process must wait for the filesystem daemon to finish writing
1458          * the WIM file. 
1459          */
1460
1461         mount_dir = dir;
1462         pid = fork();
1463         if (pid == -1) {
1464                 ERROR_WITH_ERRNO("Failed to fork()");
1465                 return WIMLIB_ERR_FORK;
1466         }
1467         if (pid == 0) {
1468                 execlp("fusermount", "fusermount", "-u", dir, NULL);
1469                 ERROR_WITH_ERRNO("Failed to execute `fusermount'");
1470                 return WIMLIB_ERR_FUSERMOUNT;
1471         }
1472
1473         ret = waitpid(pid, &status, 0);
1474         if (ret == -1) {
1475                 ERROR_WITH_ERRNO("Failed to wait for fusermount process to "
1476                                  "terminate");
1477                 return WIMLIB_ERR_FUSERMOUNT;
1478         }
1479
1480         if (status != 0) {
1481                 ERROR("fusermount exited with status %d", status);
1482                 return WIMLIB_ERR_FUSERMOUNT;
1483         }
1484
1485         /* Open message queues between the unmount process and the
1486          * filesystem daemon. */
1487         ret = open_message_queues(false);
1488         if (ret != 0)
1489                 return ret;
1490
1491         /* Send a message to the filesystem saying whether to commit or
1492          * not. */
1493         msg[0] = (flags & WIMLIB_UNMOUNT_FLAG_COMMIT) ? 1 : 0;
1494         msg[1] = (flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY) ? 1 : 0;
1495
1496         DEBUG("Sending message: %s, %s", 
1497                         (msg[0] == 0) ? "don't commit" : "commit",
1498                         (msg[1] == 0) ? "don't check"  : "check");
1499         ret = mq_send(unmount_to_daemon_mq, msg, 2, 1);
1500         if (ret == -1) {
1501                 ERROR("Failed to notify filesystem daemon whether we want to "
1502                       "commit changes or not");
1503                 close_message_queues();
1504                 return WIMLIB_ERR_MQUEUE;
1505         }
1506
1507         /* Wait for a message from the filesytem daemon indicating whether  the
1508          * filesystem was unmounted successfully (0) or an error occurred (1).
1509          * This may take a long time if a big WIM file needs to be rewritten. */
1510
1511         /* Wait at most 600??? seconds before giving up and returning false.
1512          * Either it's a really big WIM file, or (more likely) the
1513          * filesystem daemon has crashed or failed for some reason.
1514          *
1515          * XXX come up with some method to determine if the filesystem
1516          * daemon has really crashed or not. */
1517
1518         gettimeofday(&now, NULL);
1519         timeout.tv_sec = now.tv_sec + 600;
1520         timeout.tv_nsec = now.tv_usec * 1000;
1521
1522         msgsize = mq_get_msgsize(daemon_to_unmount_mq);
1523         char mailbox[msgsize];
1524
1525         mailbox[0] = 0;
1526         DEBUG("Waiting for message telling us whether the unmount was "
1527                         "successful or not.");
1528         ret = mq_timedreceive(daemon_to_unmount_mq, mailbox, msgsize,
1529                               NULL, &timeout);
1530         errno_save = errno;
1531         close_message_queues();
1532         if (ret == -1) {
1533                 if (errno_save == ETIMEDOUT) {
1534                         ERROR("Timed out- probably the filesystem daemon "
1535                               "crashed and the WIM was not written "
1536                               "successfully.");
1537                         return WIMLIB_ERR_TIMEOUT;
1538                 } else {
1539                         ERROR("mq_receive(): %s", strerror(errno_save));
1540                         return WIMLIB_ERR_MQUEUE;
1541                 }
1542
1543         }
1544         DEBUG("Received message: %s",
1545               (mailbox[0] == 0) ?  "Unmount OK" : "Unmount Failed");
1546         if (mailbox[0] != 0)
1547                 ERROR("Unmount failed");
1548         return mailbox[0];
1549 }
1550
1551 #else /* WITH_FUSE */
1552
1553
1554 static inline int mount_unsupported_error()
1555 {
1556         ERROR("WIMLIB was compiled with --without-fuse, which disables support "
1557               "for mounting WIMs.");
1558         return WIMLIB_ERR_UNSUPPORTED;
1559 }
1560
1561 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
1562 {
1563         return mount_unsupported_error();
1564 }
1565
1566 WIMLIBAPI int wimlib_mount(WIMStruct *wim_p, int image, const char *dir, 
1567                            int flags)
1568 {
1569         return mount_unsupported_error();
1570 }
1571
1572 #endif /* WITH_FUSE */