]> wimlib.net Git - wimlib/blob - src/mount.c
Apply timestamps correctly when extracting WIM image
[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_resource_to_fd(w, &old_lte->resource_entry, fd,
428                                              size);
429         else
430                 ret = 0;
431         if (ret != 0 || close(fd) != 0) {
432                 if (errno != 0)
433                         ret = -errno;
434                 else
435                         ret = -EIO;
436                 close(fd);
437                 goto out_delete_staging_file;
438         }
439
440         link_group_size = dentry_link_group_size(dentry);
441
442         if (old_lte) {
443                 if (link_group_size == old_lte->refcnt) {
444                         /* This hard link group is the only user of the lookup
445                          * table entry, so we can re-use it. */
446                         DEBUG("Re-using lookup table entry");
447                         lookup_table_unlink(w->lookup_table, old_lte);
448                         new_lte = old_lte;
449                 } else {
450                         DEBUG("Splitting lookup table entry "
451                               "(link_group_size = %u, lte refcnt = %u)",
452                               link_group_size, old_lte->refcnt);
453                         /* Split a hard link group away from the "lookup table
454                          * entry" hard link group (i.e. we had two hard link
455                          * groups that were identical, but now we are changing
456                          * one of them) */
457
458                         /* XXX 
459                          * The ADS really complicate things here and not
460                          * everything is going to work correctly yet.  For
461                          * example it could be the same that a file contains two
462                          * file streams that are identical and therefore share
463                          * the same lookup table entry despite the fact that the
464                          * streams themselves are not hardlinked. 
465                          * XXX*/
466                         wimlib_assert(old_lte->refcnt > link_group_size);
467
468                         new_lte = lte_extract_fds(old_lte, dentry->hard_link);
469                         if (!new_lte) {
470                                 ret = -ENOMEM;
471                                 goto out_delete_staging_file;
472                         }
473
474                         lte_transfer_stream_entries(new_lte, dentry, stream_idx);
475                         old_lte->refcnt -= link_group_size;
476                 } 
477         } else {
478                 /* No old_lte was supplied, so the resource had no lookup table
479                  * entry before (it must be an empty resource) */
480                 new_lte = new_lookup_table_entry();
481                 if (!new_lte) {
482                         ret = -ENOMEM;
483                         goto out_delete_staging_file;
484                 }
485                 lte_transfer_stream_entries(new_lte, dentry, stream_idx);
486         }
487         new_lte->resource_entry.original_size = size;
488         new_lte->refcnt = link_group_size;
489         random_hash(new_lte->hash);
490         new_lte->staging_file_name = staging_file_name;
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 calculate_sha1sum_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
782         ret = sha1sum(lte->staging_file_name, hash);
783         if (ret != 0)
784                 return ret;
785
786         lookup_table_unlink(table, lte);
787         copy_hash(lte->hash, hash);
788
789         duplicate_lte = __lookup_resource(table, hash);
790
791         if (duplicate_lte) {
792                 /* Merge duplicate lookup table entries */
793
794                 lte_list_change_lte_ptr(lte, duplicate_lte);
795                 duplicate_lte->refcnt += lte->refcnt;
796                 list_splice(&duplicate_lte->lte_group_list,
797                             &lte->lte_group_list);
798
799                 free_lookup_table_entry(lte);
800         } else {
801                 lookup_table_insert(table, lte);
802         }
803
804         return 0;
805 }
806
807 /* Overwrites the WIM file, with changes saved. */
808 static int rebuild_wim(WIMStruct *w, bool check_integrity)
809 {
810         int ret;
811         struct lookup_table_entry *lte, *tmp;
812
813         /* Close all the staging file descriptors. */
814         DEBUG("Closing all staging file descriptors.");
815         list_for_each_entry(lte, &staging_list, staging_list) {
816                 ret = close_lte_fds(lte);
817                 if (ret != 0)
818                         return ret;
819         }
820
821         /* Calculate SHA1 checksums for all staging files, and merge unnecessary
822          * lookup table entries. */
823         DEBUG("Calculating SHA1 checksums for all new staging files.");
824         list_for_each_entry_safe(lte, tmp, &staging_list, staging_list) {
825                 ret = calculate_sha1sum_of_staging_file(lte, w->lookup_table);
826                 if (ret != 0)
827                         return ret;
828         }
829         if (ret != 0)
830                 return ret;
831
832         xml_update_image_info(w, w->current_image);
833
834         ret = wimlib_overwrite(w, check_integrity);
835         if (ret != 0) {
836                 ERROR("Failed to commit changes");
837                 return ret;
838         }
839         return ret;
840 }
841
842 /* Called when the filesystem is unmounted. */
843 static void wimfs_destroy(void *p)
844 {
845         /* For read-write mounts, the `imagex unmount' command, which is
846          * running in a separate process and is executing the
847          * wimlib_unmount() function, will send this process a byte
848          * through a message queue that indicates whether the --commit
849          * option was specified or not. */
850
851         int msgsize;
852         struct timespec timeout;
853         struct timeval now;
854         ssize_t bytes_received;
855         int ret;
856         char commit;
857         char check_integrity;
858         char status;
859
860         ret = open_message_queues(true);
861         if (ret != 0)
862                 exit(1);
863
864         msgsize = mq_get_msgsize(unmount_to_daemon_mq);
865         char msg[msgsize];
866         msg[0] = 0;
867         msg[1] = 0;
868
869         /* Wait at most 3 seconds before giving up and discarding changes. */
870         gettimeofday(&now, NULL);
871         timeout.tv_sec = now.tv_sec + 3;
872         timeout.tv_nsec = now.tv_usec * 1000;
873         DEBUG("Waiting for message telling us whether to commit or not, and "
874               "whether to include integrity checks.");
875
876         bytes_received = mq_timedreceive(unmount_to_daemon_mq, msg, 
877                                          msgsize, NULL, &timeout);
878         commit = msg[0];
879         check_integrity = msg[1];
880         if (bytes_received == -1) {
881                 if (errno == ETIMEDOUT) {
882                         ERROR("Timed out.");
883                 } else {
884                         ERROR_WITH_ERRNO("mq_timedreceive()");
885                 }
886                 ERROR("Not committing.");
887         } else {
888                 DEBUG("Received message: [%d %d]", msg[0], msg[1]);
889         }
890
891         status = 0;
892         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
893                 if (commit) {
894                         status = chdir(working_directory);
895                         if (status != 0) {
896                                 ERROR_WITH_ERRNO("chdir()");
897                                 status = WIMLIB_ERR_NOTDIR;
898                                 goto done;
899                         }
900                         status = rebuild_wim(w, (check_integrity != 0));
901                 }
902                 ret = delete_staging_dir();
903                 if (ret != 0) {
904                         ERROR_WITH_ERRNO("Failed to delete the staging "
905                                          "directory");
906                         if (status == 0)
907                                 status = ret;
908                 }
909         } else {
910                 DEBUG("Read-only mount");
911         }
912 done:
913         DEBUG("Sending status %u", status);
914         ret = mq_send(daemon_to_unmount_mq, &status, 1, 1);
915         if (ret == -1)
916                 ERROR_WITH_ERRNO("Failed to send status to unmount process");
917         close_message_queues();
918 }
919
920 static int wimfs_fallocate(const char *path, int mode,
921                            off_t offset, off_t len, struct fuse_file_info *fi)
922 {
923         struct wimlib_fd *fd = (struct wimlib_fd*)fi->fh;
924         wimlib_assert(fd->staging_fd != -1);
925         return fallocate(fd->staging_fd, mode, offset, len);
926 }
927
928 static int wimfs_fgetattr(const char *path, struct stat *stbuf,
929                           struct fuse_file_info *fi)
930 {
931         struct wimlib_fd *fd = (struct wimlib_fd*)fi->fh;
932         return dentry_to_stbuf(fd->dentry, stbuf);
933 }
934
935 static int wimfs_ftruncate(const char *path, off_t size,
936                            struct fuse_file_info *fi)
937 {
938         struct wimlib_fd *fd = (struct wimlib_fd*)fi->fh;
939         int ret = ftruncate(fd->staging_fd, size);
940         if (ret != 0)
941                 return ret;
942         fd->lte->resource_entry.original_size = size;
943         return 0;
944 }
945
946 /*
947  * Fills in a `struct stat' that corresponds to a file or directory in the WIM.
948  */
949 static int wimfs_getattr(const char *path, struct stat *stbuf)
950 {
951         struct dentry *dentry = get_dentry(w, path);
952         if (!dentry)
953                 return -ENOENT;
954         return dentry_to_stbuf(dentry, stbuf);
955 }
956
957 static int wimfs_getxattr(const char *path, const char *name, char *value,
958                           size_t size)
959 {
960         /* XXX */
961         return -ENOTSUP;
962 }
963
964 /* Create a hard link */
965 static int wimfs_link(const char *to, const char *from)
966 {
967         struct dentry *to_dentry, *from_dentry, *from_dentry_parent;
968         const char *link_name;
969
970         to_dentry = get_dentry(w, to);
971         if (!to_dentry)
972                 return -ENOENT;
973         if (!dentry_is_regular_file(to_dentry))
974                 return -EPERM;
975
976         from_dentry_parent = get_parent_dentry(w, from);
977         if (!from_dentry_parent)
978                 return -ENOENT;
979         if (!dentry_is_directory(from_dentry_parent))
980                 return -ENOTDIR;
981
982         link_name = path_basename(from);
983         if (get_dentry_child_with_name(from_dentry_parent, link_name))
984                 return -EEXIST;
985         from_dentry = clone_dentry(to_dentry);
986         if (!from_dentry)
987                 return -ENOMEM;
988         if (change_dentry_name(from_dentry, link_name) != 0) {
989                 FREE(from_dentry);
990                 return -ENOMEM;
991         }
992
993         /* Add the new dentry to the dentry list for the link group */
994         list_add(&from_dentry->link_group_list, &to_dentry->link_group_list);
995
996         /* Increment reference counts for the unnamed file stream and all
997          * alternate data streams. */
998         if (from_dentry->lte) {
999                 list_add(&from_dentry->lte_group_list.list,
1000                          &to_dentry->lte_group_list.list);
1001                 from_dentry->lte->refcnt++;
1002         }
1003         for (u16 i = 0; i < from_dentry->num_ads; i++) {
1004                 struct ads_entry *ads_entry = &from_dentry->ads_entries[i];
1005                 if (ads_entry->lte)
1006                         ads_entry->lte->refcnt++;
1007         }
1008
1009         /* The ADS entries are owned by another dentry. */
1010         from_dentry->ads_entries_status = ADS_ENTRIES_USER;
1011
1012         link_dentry(from_dentry, from_dentry_parent);
1013         return 0;
1014 }
1015
1016 static int wimfs_listxattr(const char *path, char *list, size_t size)
1017 {
1018         /* XXX */
1019         return -ENOTSUP;
1020 }
1021
1022 /* 
1023  * Create a directory in the WIM.  
1024  * @mode is currently ignored.
1025  */
1026 static int wimfs_mkdir(const char *path, mode_t mode)
1027 {
1028         struct dentry *parent;
1029         struct dentry *newdir;
1030         const char *basename;
1031         
1032         parent = get_parent_dentry(w, path);
1033         if (!parent)
1034                 return -ENOENT;
1035
1036         if (!dentry_is_directory(parent))
1037                 return -ENOTDIR;
1038
1039         basename = path_basename(path);
1040         if (get_dentry_child_with_name(parent, basename))
1041                 return -EEXIST;
1042
1043         newdir = new_dentry(basename);
1044         newdir->attributes |= FILE_ATTRIBUTE_DIRECTORY;
1045         newdir->resolved = true;
1046         newdir->hard_link = next_link_group_id++;
1047         link_dentry(newdir, parent);
1048         return 0;
1049 }
1050
1051
1052 /* Creates a regular file. */
1053 static int wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
1054 {
1055         const char *stream_name;
1056         if ((mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
1057              && (stream_name = path_stream_name(path))) {
1058                 /* Make an alternate data stream */
1059                 struct ads_entry *new_entry;
1060                 struct dentry *dentry;
1061
1062                 dentry = get_dentry(w, path);
1063                 if (!dentry || !dentry_is_regular_file(dentry))
1064                         return -ENOENT;
1065                 if (dentry_get_ads_entry(dentry, stream_name))
1066                         return -EEXIST;
1067                 new_entry = dentry_add_ads(dentry, stream_name);
1068                 if (!new_entry)
1069                         return -ENOENT;
1070         } else {
1071                 struct dentry *dentry, *parent;
1072                 const char *basename;
1073
1074                 /* Make a normal file (not an alternate data stream) */
1075
1076                 /* Make sure that the parent of @path exists and is a directory, and
1077                  * that the dentry named by @path does not already exist.  */
1078                 parent = get_parent_dentry(w, path);
1079                 if (!parent)
1080                         return -ENOENT;
1081                 if (!dentry_is_directory(parent))
1082                         return -ENOTDIR;
1083
1084                 basename = path_basename(path);
1085                 if (get_dentry_child_with_name(parent, path))
1086                         return -EEXIST;
1087
1088                 dentry = new_dentry(basename);
1089                 if (!dentry)
1090                         return -ENOMEM;
1091                 dentry->resolved = true;
1092                 dentry->hard_link = next_link_group_id++;
1093                 dentry->lte_group_list.type = STREAM_TYPE_NORMAL;
1094                 INIT_LIST_HEAD(&dentry->lte_group_list.list);
1095                 link_dentry(dentry, parent);
1096         }
1097         return 0;
1098 }
1099
1100
1101 /* Open a file.  */
1102 static int wimfs_open(const char *path, struct fuse_file_info *fi)
1103 {
1104         struct dentry *dentry;
1105         struct lookup_table_entry *lte;
1106         u8 *dentry_hash;
1107         int ret;
1108         struct wimlib_fd *fd;
1109         unsigned stream_idx;
1110
1111         ret = lookup_resource(w, path, get_lookup_flags(), &dentry, &lte,
1112                               &stream_idx);
1113         if (ret != 0)
1114                 return ret;
1115
1116         if (!lte) {
1117                 /* Empty file with no lookup-table entry.  This is fine if it's
1118                  * a read-only filesystem.  Otherwise we need to create a lookup
1119                  * table entry so that we can keep track of the file descriptors
1120                  * (this is important in case someone opens the file for
1121                  * writing) */
1122                 if (!(mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
1123                         fi->fh = 0;
1124                         return 0;
1125                 }
1126
1127                 ret = extract_resource_to_staging_dir(dentry, stream_idx,
1128                                                       &lte, 0);
1129                 if (ret != 0)
1130                         return ret;
1131         }
1132
1133         ret = alloc_wimlib_fd(lte, &fd);
1134         if (ret != 0)
1135                 return ret;
1136
1137         fd->dentry = dentry;
1138
1139         /* The file resource may be in the staging directory (read-write
1140          * mounts only) or in the WIM.  If it's in the staging
1141          * directory, we need to open a native file descriptor for the
1142          * corresponding file.  Otherwise, we can read the file resource
1143          * directly from the WIM file if we are opening it read-only,
1144          * but we need to extract the resource to the staging directory
1145          * if we are opening it writable. */
1146         if (flags_writable(fi->flags) && !lte->staging_file_name) {
1147                 ret = extract_resource_to_staging_dir(dentry, stream_idx, &lte,
1148                                                       lte->resource_entry.original_size);
1149                 if (ret != 0)
1150                         return ret;
1151         }
1152         if (lte->staging_file_name) {
1153                 fd->staging_fd = open(lte->staging_file_name, fi->flags);
1154                 if (fd->staging_fd == -1) {
1155                         close_wimlib_fd(fd);
1156                         return -errno;
1157                 }
1158         }
1159         fi->fh = (uint64_t)fd;
1160         return 0;
1161 }
1162
1163 /* Opens a directory. */
1164 static int wimfs_opendir(const char *path, struct fuse_file_info *fi)
1165 {
1166         struct dentry *dentry;
1167         
1168         dentry = get_dentry(w, path);
1169         if (!dentry)
1170                 return -ENOENT;
1171         if (!dentry_is_directory(dentry))
1172                 return -ENOTDIR;
1173         dentry->num_times_opened++;
1174         fi->fh = (uint64_t)dentry;
1175         return 0;
1176 }
1177
1178
1179 /*
1180  * Read data from a file in the WIM or in the staging directory. 
1181  */
1182 static int wimfs_read(const char *path, char *buf, size_t size, 
1183                       off_t offset, struct fuse_file_info *fi)
1184 {
1185         struct wimlib_fd *fd = (struct wimlib_fd*)fi->fh;
1186
1187         if (!fd) {
1188                 /* Empty file with no lookup table entry on read-only mounted
1189                  * WIM */
1190                 wimlib_assert(!(mount_flags & WIMLIB_MOUNT_FLAG_READWRITE));
1191                 return 0;
1192         }
1193
1194         wimlib_assert(fd->lte);
1195
1196         if (fd->lte->staging_file_name) {
1197                 /* Read from staging file */
1198
1199                 wimlib_assert(fd->staging_fd != -1);
1200
1201                 ssize_t ret;
1202                 DEBUG("Seek to offset %zu", offset);
1203
1204                 if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1205                         return -errno;
1206                 ret = read(fd->staging_fd, buf, size);
1207                 if (ret == -1)
1208                         return -errno;
1209                 return ret;
1210         } else {
1211                 /* Read from WIM */
1212
1213                 struct resource_entry *res_entry;
1214                 int ctype;
1215                 
1216                 res_entry = &fd->lte->resource_entry;
1217
1218                 ctype = wim_resource_compression_type(w, res_entry);
1219
1220                 if (offset > res_entry->original_size)
1221                         return -EOVERFLOW;
1222
1223                 size = min(size, res_entry->original_size - offset);
1224
1225                 if (read_resource(w->fp, res_entry->size, 
1226                                   res_entry->original_size,
1227                                   res_entry->offset, ctype, size, 
1228                                   offset, buf) != 0)
1229                         return -EIO;
1230                 return size;
1231         }
1232 }
1233
1234 /* Fills in the entries of the directory specified by @path using the
1235  * FUSE-provided function @filler.  */
1236 static int wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, 
1237                          off_t offset, struct fuse_file_info *fi)
1238 {
1239         struct dentry *parent, *child;
1240         
1241         parent = (struct dentry*)fi->fh;
1242         wimlib_assert(parent);
1243         child = parent->children;
1244
1245         filler(buf, ".", NULL, 0);
1246         filler(buf, "..", NULL, 0);
1247
1248         if (!child)
1249                 return 0;
1250
1251         do {
1252                 if (filler(buf, child->file_name_utf8, NULL, 0))
1253                         return 0;
1254                 child = child->next;
1255         } while (child != parent->children);
1256         return 0;
1257 }
1258
1259
1260 static int wimfs_readlink(const char *path, char *buf, size_t buf_len)
1261 {
1262         struct dentry *dentry = get_dentry(w, path);
1263         int ret;
1264         if (!dentry)
1265                 return -ENOENT;
1266         if (!dentry_is_symlink(dentry))
1267                 return -EINVAL;
1268
1269         ret = dentry_readlink(dentry, buf, buf_len, w);
1270         if (ret > 0)
1271                 ret = 0;
1272         return ret;
1273 }
1274
1275 /* Close a file. */
1276 static int wimfs_release(const char *path, struct fuse_file_info *fi)
1277 {
1278         int ret;
1279         struct wimlib_fd *fd = (struct wimlib_fd*)fi->fh;
1280
1281         if (!fd) {
1282                 /* Empty file with no lookup table entry on read-only mounted
1283                  * WIM */
1284                 wimlib_assert(!(mount_flags & WIMLIB_MOUNT_FLAG_READWRITE));
1285                 return 0;
1286         }
1287
1288         if (flags_writable(fi->flags) && fd->dentry) {
1289                 u64 now = get_wim_timestamp();
1290                 fd->dentry->last_access_time = now;
1291                 fd->dentry->last_write_time = now;
1292         }
1293
1294         return close_wimlib_fd(fd);
1295 }
1296
1297 static int wimfs_releasedir(const char *path, struct fuse_file_info *fi)
1298 {
1299         struct dentry *dentry = (struct dentry *)fi->fh;
1300
1301         wimlib_assert(dentry);
1302         wimlib_assert(dentry->num_times_opened);
1303         if (--dentry->num_times_opened == 0)
1304                 free_dentry(dentry);
1305         return 0;
1306 }
1307
1308 static int wimfs_removexattr(const char *path, const char *name)
1309 {
1310         /* XXX */
1311         return -ENOTSUP;
1312 }
1313
1314 /* Renames a file or directory.  See rename (3) */
1315 static int wimfs_rename(const char *from, const char *to)
1316 {
1317         struct dentry *src;
1318         struct dentry *dst;
1319         struct dentry *parent_of_dst;
1320         char *file_name_utf16 = NULL, *file_name_utf8 = NULL;
1321         u16 file_name_utf16_len, file_name_utf8_len;
1322         int ret;
1323
1324         /* This rename() implementation currently only supports actual files
1325          * (not alternate data streams) */
1326         
1327         src = get_dentry(w, from);
1328         if (!src)
1329                 return -ENOENT;
1330
1331         dst = get_dentry(w, to);
1332
1333
1334         ret = get_names(&file_name_utf16, &file_name_utf8,
1335                         &file_name_utf16_len, &file_name_utf8_len,
1336                         path_basename(to));
1337         if (ret != 0)
1338                 return -ENOMEM;
1339
1340         if (dst) {
1341                 /* Destination file exists */
1342
1343                 if (src == dst) /* Same file */
1344                         return 0;
1345
1346                 if (!dentry_is_directory(src)) {
1347                         /* Cannot rename non-directory to directory. */
1348                         if (dentry_is_directory(dst))
1349                                 return -EISDIR;
1350                 } else {
1351                         /* Cannot rename directory to a non-directory or a non-empty
1352                          * directory */
1353                         if (!dentry_is_directory(dst))
1354                                 return -ENOTDIR;
1355                         if (dst->children != NULL)
1356                                 return -ENOTEMPTY;
1357                 }
1358                 parent_of_dst = dst->parent;
1359                 remove_dentry(dst, w->lookup_table);
1360         } else {
1361                 /* Destination does not exist */
1362                 parent_of_dst = get_parent_dentry(w, to);
1363                 if (!parent_of_dst)
1364                         return -ENOENT;
1365
1366                 if (!dentry_is_directory(parent_of_dst))
1367                         return -ENOTDIR;
1368         }
1369
1370         FREE(src->file_name);
1371         FREE(src->file_name_utf8);
1372         src->file_name          = file_name_utf16;
1373         src->file_name_utf8     = file_name_utf8;
1374         src->file_name_len      = file_name_utf16_len;
1375         src->file_name_utf8_len = file_name_utf8_len;
1376
1377         unlink_dentry(src);
1378         link_dentry(src, parent_of_dst);
1379         return 0;
1380 }
1381
1382 /* Remove a directory */
1383 static int wimfs_rmdir(const char *path)
1384 {
1385         struct dentry *dentry;
1386         
1387         dentry = get_dentry(w, path);
1388         if (!dentry)
1389                 return -ENOENT;
1390
1391         if (!dentry_is_empty_directory(dentry))
1392                 return -ENOTEMPTY;
1393
1394         unlink_dentry(dentry);
1395         if (dentry->num_times_opened == 0)
1396                 free_dentry(dentry);
1397         return 0;
1398 }
1399
1400 static int wimfs_setxattr(const char *path, const char *name,
1401                           const char *value, size_t size, int flags)
1402 {
1403         /* XXX */
1404         return -ENOTSUP;
1405 }
1406
1407 static int wimfs_symlink(const char *to, const char *from)
1408 {
1409         struct dentry *dentry_parent, *dentry;
1410         const char *link_name;
1411         struct lookup_table_entry *lte;
1412         
1413         dentry_parent = get_parent_dentry(w, from);
1414         if (!dentry_parent)
1415                 return -ENOENT;
1416         if (!dentry_is_directory(dentry_parent))
1417                 return -ENOTDIR;
1418
1419         link_name = path_basename(from);
1420
1421         if (get_dentry_child_with_name(dentry_parent, link_name))
1422                 return -EEXIST;
1423         dentry = new_dentry(link_name);
1424         if (!dentry)
1425                 return -ENOMEM;
1426
1427         dentry->attributes = FILE_ATTRIBUTE_REPARSE_POINT;
1428         dentry->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
1429         dentry->hard_link = next_link_group_id++;
1430
1431         if (dentry_set_symlink(dentry, to, w->lookup_table, &lte) != 0)
1432                 goto out_free_dentry;
1433
1434         wimlib_assert(lte);
1435
1436         dentry->ads_entries[1].lte_group_list.type = STREAM_TYPE_ADS;
1437         list_add(&dentry->ads_entries[1].lte_group_list.list,
1438                  &lte->lte_group_list);
1439         wimlib_assert(dentry->resolved);
1440
1441         link_dentry(dentry, dentry_parent);
1442         return 0;
1443 out_free_dentry:
1444         free_dentry(dentry);
1445         return -ENOMEM;
1446 }
1447
1448
1449 /* Reduce the size of a file */
1450 static int wimfs_truncate(const char *path, off_t size)
1451 {
1452         struct dentry *dentry;
1453         struct lookup_table_entry *lte;
1454         int ret;
1455         unsigned stream_idx;
1456         
1457         ret = lookup_resource(w, path, get_lookup_flags(), &dentry,
1458                               &lte, &stream_idx);
1459
1460         if (ret != 0)
1461                 return ret;
1462
1463         if (!lte) /* Already a zero-length file */
1464                 return 0;
1465
1466         if (lte->staging_file_name) {
1467                 ret = truncate(lte->staging_file_name, size);
1468                 if (ret != 0)
1469                         return -errno;
1470                 lte->resource_entry.original_size = size;
1471         } else {
1472                 /* File in WIM.  Extract it to the staging directory, but only
1473                  * the first @size bytes of it. */
1474                 ret = extract_resource_to_staging_dir(dentry, stream_idx,
1475                                                       &lte, size);
1476         }
1477         dentry_update_all_timestamps(dentry);
1478         return ret;
1479 }
1480
1481 /* Remove a regular file */
1482 static int wimfs_unlink(const char *path)
1483 {
1484         struct dentry *dentry;
1485         struct lookup_table_entry *lte;
1486         int ret;
1487         u8 *dentry_hash;
1488         unsigned stream_idx;
1489         
1490         ret = lookup_resource(w, path, get_lookup_flags(), &dentry,
1491                               &lte, &stream_idx);
1492
1493         if (ret != 0)
1494                 return ret;
1495
1496         if (stream_idx == 0) {
1497                 /* We are removing the full dentry including all alternate data
1498                  * streams. */
1499                 remove_dentry(dentry, w->lookup_table);
1500         } else {
1501                 /* We are removing an alternate data stream. */
1502                 struct ads_entry *ads_entry;
1503                 
1504                 ads_entry = &dentry->ads_entries[stream_idx - 1];
1505                 lte = lte_decrement_refcnt(lte, w->lookup_table);
1506                 if (lte)
1507                         list_del(&ads_entry->lte_group_list.list);
1508                 dentry_remove_ads(dentry, ads_entry);
1509         }
1510         /* Beware: The lookup table entry(s) may still be referenced by users
1511          * that have opened the corresponding streams.  They are freed later in
1512          * wimfs_release() when the last file user has closed the stream. */
1513         return 0;
1514 }
1515
1516 /* 
1517  * Change the timestamp on a file dentry. 
1518  *
1519  * Note that alternate data streams do not have their own timestamps.
1520  */
1521 static int wimfs_utimens(const char *path, const struct timespec tv[2])
1522 {
1523         struct dentry *dentry = get_dentry(w, path);
1524         if (!dentry)
1525                 return -ENOENT;
1526         if (tv[0].tv_nsec != UTIME_OMIT) {
1527                 if (tv[0].tv_nsec == UTIME_NOW)
1528                         dentry->last_access_time = get_wim_timestamp();
1529                 else
1530                         dentry->last_access_time = timespec_to_wim_timestamp(&tv[0]);
1531         }
1532         if (tv[1].tv_nsec != UTIME_OMIT) {
1533                 if (tv[1].tv_nsec == UTIME_NOW)
1534                         dentry->last_write_time = get_wim_timestamp();
1535                 else
1536                         dentry->last_write_time = timespec_to_wim_timestamp(&tv[1]);
1537         }
1538         return 0;
1539 }
1540
1541 /* Writes to a file in the WIM filesystem. 
1542  * It may be an alternate data stream, but here we don't even notice because we
1543  * just get a lookup table entry. */
1544 static int wimfs_write(const char *path, const char *buf, size_t size, 
1545                        off_t offset, struct fuse_file_info *fi)
1546 {
1547         struct wimlib_fd *fd = (struct wimlib_fd*)fi->fh;
1548         int ret;
1549
1550         wimlib_assert(fd);
1551         wimlib_assert(fd->lte);
1552         wimlib_assert(fd->lte->staging_file_name);
1553         wimlib_assert(fd->staging_fd != -1);
1554
1555         /* Seek to the requested position */
1556         if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1557                 return -errno;
1558
1559         /* Write the data. */
1560         ret = write(fd->staging_fd, buf, size);
1561         if (ret == -1)
1562                 return -errno;
1563
1564         return ret;
1565 }
1566
1567 static struct fuse_operations wimfs_operations = {
1568         .access      = wimfs_access,
1569         .destroy     = wimfs_destroy,
1570         .fallocate   = wimfs_fallocate,
1571         .fgetattr    = wimfs_fgetattr,
1572         .ftruncate   = wimfs_ftruncate,
1573         .getattr     = wimfs_getattr,
1574         .getxattr    = wimfs_getxattr,
1575         .link        = wimfs_link,
1576         .listxattr   = wimfs_listxattr,
1577         .mkdir       = wimfs_mkdir,
1578         .mknod       = wimfs_mknod,
1579         .open        = wimfs_open,
1580         .opendir     = wimfs_opendir,
1581         .read        = wimfs_read,
1582         .readdir     = wimfs_readdir,
1583         .readlink    = wimfs_readlink,
1584         .release     = wimfs_release,
1585         .releasedir  = wimfs_releasedir,
1586         .removexattr = wimfs_removexattr,
1587         .rename      = wimfs_rename,
1588         .rmdir       = wimfs_rmdir,
1589         .setxattr    = wimfs_setxattr,
1590         .symlink     = wimfs_symlink,
1591         .truncate    = wimfs_truncate,
1592         .unlink      = wimfs_unlink,
1593         .utimens     = wimfs_utimens,
1594         .write       = wimfs_write,
1595 };
1596
1597
1598 static int check_lte_refcnt(struct lookup_table_entry *lte, void *ignore)
1599 {
1600         size_t lte_group_size = 0;
1601         struct list_head *cur;
1602         list_for_each(cur, &lte->lte_group_list)
1603                 lte_group_size++;
1604         if (lte_group_size > lte->refcnt) {
1605 #ifdef ENABLE_ERROR_MESSAGES
1606                 ERROR("The following lookup table entry has a reference count "
1607                       "of %u, but", lte->refcnt);
1608                 ERROR("We found %u references to it", lte_group_size);
1609                 print_lookup_table_entry(lte);
1610 #endif
1611                 return WIMLIB_ERR_INVALID_DENTRY;
1612         }
1613         return 0;
1614 }
1615
1616 /* Mounts a WIM file. */
1617 WIMLIBAPI int wimlib_mount(WIMStruct *wim, int image, const char *dir, 
1618                            int flags)
1619 {
1620         int argc = 0;
1621         char *argv[16];
1622         int ret;
1623         char *p;
1624
1625         DEBUG("Mount: wim = %p, image = %d, dir = %s, flags = %d, ",
1626                         wim, image, dir, flags);
1627
1628         if (!dir)
1629                 return WIMLIB_ERR_INVALID_PARAM;
1630
1631         ret = wimlib_select_image(wim, image);
1632
1633         if (ret != 0)
1634                 return ret;
1635
1636         DEBUG("Selected image %d", image);
1637
1638         next_link_group_id = assign_link_groups(wim->image_metadata[image - 1].lgt);
1639
1640         /* Resolve all the lookup table entries of the dentry tree */
1641         for_dentry_in_tree(wim_root_dentry(wim), dentry_resolve_ltes,
1642                            wim->lookup_table);
1643
1644         ret = for_lookup_table_entry(wim->lookup_table, check_lte_refcnt, NULL);
1645         if (ret != 0)
1646                 return ret;
1647
1648         if (flags & WIMLIB_MOUNT_FLAG_READWRITE)
1649                 wim_get_current_image_metadata(wim)->modified = true;
1650
1651         if (!(flags & (WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
1652                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
1653                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)))
1654                 flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
1655
1656         mount_dir = dir;
1657         working_directory = getcwd(NULL, 0);
1658         if (!working_directory) {
1659                 ERROR_WITH_ERRNO("Could not determine current directory");
1660                 return WIMLIB_ERR_NOTDIR;
1661         }
1662
1663         p = STRDUP(dir);
1664         if (!p)
1665                 return WIMLIB_ERR_NOMEM;
1666
1667         argv[argc++] = "mount";
1668         argv[argc++] = p;
1669         argv[argc++] = "-s"; /* disable multi-threaded operation */
1670
1671         if (flags & WIMLIB_MOUNT_FLAG_DEBUG)
1672                 argv[argc++] = "-d";
1673
1674         /* 
1675          * We provide the use_ino option because we are going to assign inode
1676          * numbers oursides.  We've already numbered the hard link groups with
1677          * unique numbers with the assign_link_groups() function, and the static
1678          * variable next_link_group_id is set to the next available link group
1679          * ID that we will assign to new dentries.
1680          */
1681         char optstring[256] = "use_ino";
1682         argv[argc++] = "-o";
1683         argv[argc++] = optstring;
1684         if ((flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
1685                 /* Read-write mount.  Make the staging directory */
1686                 make_staging_dir();
1687                 if (!staging_dir_name) {
1688                         FREE(p);
1689                         return WIMLIB_ERR_MKDIR;
1690                 }
1691         } else {
1692                 /* Read-only mount */
1693                 strcat(optstring, ",ro");
1694         }
1695         argv[argc] = NULL;
1696
1697 #ifdef ENABLE_DEBUG
1698         {
1699                 int i;
1700                 DEBUG("FUSE command line (argc = %d): ", argc);
1701                 for (i = 0; i < argc; i++) {
1702                         fputs(argv[i], stdout);
1703                         putchar(' ');
1704                 }
1705                 putchar('\n');
1706                 fflush(stdout);
1707         }
1708 #endif
1709
1710         /* Set static variables. */
1711         w = wim;
1712         mount_flags = flags;
1713
1714         ret = fuse_main(argc, argv, &wimfs_operations, NULL);
1715
1716         return (ret == 0) ? 0 : WIMLIB_ERR_FUSE;
1717 }
1718
1719
1720 /* 
1721  * Unmounts the WIM file that was previously mounted on @dir by using
1722  * wimlib_mount().
1723  */
1724 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
1725 {
1726         pid_t pid;
1727         int status;
1728         int ret;
1729         char msg[2];
1730         struct timeval now;
1731         struct timespec timeout;
1732         int msgsize;
1733         int errno_save;
1734
1735         /* Execute `fusermount -u', which is installed setuid root, to unmount
1736          * the WIM.
1737          *
1738          * FUSE does not yet implement synchronous unmounts.  This means that
1739          * fusermount -u will return before the filesystem daemon returns from
1740          * wimfs_destroy().  This is partly what we want, because we need to
1741          * send a message from this process to the filesystem daemon telling
1742          * whether --commit was specified or not.  However, after that, the
1743          * unmount process must wait for the filesystem daemon to finish writing
1744          * the WIM file. 
1745          */
1746
1747         mount_dir = dir;
1748         pid = fork();
1749         if (pid == -1) {
1750                 ERROR_WITH_ERRNO("Failed to fork()");
1751                 return WIMLIB_ERR_FORK;
1752         }
1753         if (pid == 0) {
1754                 execlp("fusermount", "fusermount", "-u", dir, NULL);
1755                 ERROR_WITH_ERRNO("Failed to execute `fusermount'");
1756                 return WIMLIB_ERR_FUSERMOUNT;
1757         }
1758
1759         ret = waitpid(pid, &status, 0);
1760         if (ret == -1) {
1761                 ERROR_WITH_ERRNO("Failed to wait for fusermount process to "
1762                                  "terminate");
1763                 return WIMLIB_ERR_FUSERMOUNT;
1764         }
1765
1766         if (status != 0) {
1767                 ERROR("fusermount exited with status %d", status);
1768                 return WIMLIB_ERR_FUSERMOUNT;
1769         }
1770
1771         /* Open message queues between the unmount process and the
1772          * filesystem daemon. */
1773         ret = open_message_queues(false);
1774         if (ret != 0)
1775                 return ret;
1776
1777         /* Send a message to the filesystem saying whether to commit or
1778          * not. */
1779         msg[0] = (flags & WIMLIB_UNMOUNT_FLAG_COMMIT) ? 1 : 0;
1780         msg[1] = (flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY) ? 1 : 0;
1781
1782         DEBUG("Sending message: %s, %s", 
1783                         (msg[0] == 0) ? "don't commit" : "commit",
1784                         (msg[1] == 0) ? "don't check"  : "check");
1785         ret = mq_send(unmount_to_daemon_mq, msg, 2, 1);
1786         if (ret == -1) {
1787                 ERROR("Failed to notify filesystem daemon whether we want to "
1788                       "commit changes or not");
1789                 close_message_queues();
1790                 return WIMLIB_ERR_MQUEUE;
1791         }
1792
1793         /* Wait for a message from the filesytem daemon indicating whether  the
1794          * filesystem was unmounted successfully (0) or an error occurred (1).
1795          * This may take a long time if a big WIM file needs to be rewritten. */
1796
1797         /* Wait at most 600??? seconds before giving up and returning false.
1798          * Either it's a really big WIM file, or (more likely) the
1799          * filesystem daemon has crashed or failed for some reason.
1800          *
1801          * XXX come up with some method to determine if the filesystem
1802          * daemon has really crashed or not. 
1803          *
1804          * XXX Idea: have mount daemon write its PID into the WIM file header?
1805          * */
1806
1807         gettimeofday(&now, NULL);
1808         timeout.tv_sec = now.tv_sec + 600;
1809         timeout.tv_nsec = now.tv_usec * 1000;
1810
1811         msgsize = mq_get_msgsize(daemon_to_unmount_mq);
1812         char mailbox[msgsize];
1813
1814         mailbox[0] = 0;
1815         DEBUG("Waiting for message telling us whether the unmount was "
1816                         "successful or not.");
1817         ret = mq_timedreceive(daemon_to_unmount_mq, mailbox, msgsize,
1818                               NULL, &timeout);
1819         errno_save = errno;
1820         close_message_queues();
1821         if (ret == -1) {
1822                 if (errno_save == ETIMEDOUT) {
1823                         ERROR("Timed out- probably the filesystem daemon "
1824                               "crashed and the WIM was not written "
1825                               "successfully.");
1826                         return WIMLIB_ERR_TIMEOUT;
1827                 } else {
1828                         ERROR("mq_receive(): %s", strerror(errno_save));
1829                         return WIMLIB_ERR_MQUEUE;
1830                 }
1831
1832         }
1833         DEBUG("Received message: %s",
1834               (mailbox[0] == 0) ?  "Unmount OK" : "Unmount Failed");
1835         if (mailbox[0] != 0)
1836                 ERROR("Unmount failed");
1837         return mailbox[0];
1838 }
1839
1840 #else /* WITH_FUSE */
1841
1842
1843 static inline int mount_unsupported_error()
1844 {
1845         ERROR("WIMLIB was compiled with --without-fuse, which disables support "
1846               "for mounting WIMs.");
1847         return WIMLIB_ERR_UNSUPPORTED;
1848 }
1849
1850 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
1851 {
1852         return mount_unsupported_error();
1853 }
1854
1855 WIMLIBAPI int wimlib_mount(WIMStruct *wim_p, int image, const char *dir, 
1856                            int flags)
1857 {
1858         return mount_unsupported_error();
1859 }
1860
1861 #endif /* WITH_FUSE */