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