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