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