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