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