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