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