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