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