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