]> wimlib.net Git - wimlib/blob - src/mount.c
Symbolic links (IN PROGRESS)
[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 /* The WIMStruct for the mounted WIM. */
49 static WIMStruct *w;
50
51 /* Working directory when `imagex mount' is run. */
52 static const char *working_directory;
53
54 /* Name of the staging directory for a read-write mount.  Whenever a new file is
55  * created, it is done so in the staging directory.  Furthermore, whenever a
56  * file in the WIM is modified, it is extracted to the staging directory.  If
57  * changes are commited when the WIM is unmounted, the file resources are merged
58  * in from the staging directory when writing the new WIM. */
59 static char *staging_dir_name;
60 static size_t staging_dir_name_len;
61
62 /* Flags passed to wimlib_mount(). */
63 static int mount_flags;
64
65 /* Name of the directory on which the WIM file is mounted. */
66 static const char *mount_dir;
67
68
69 /* 
70  * Creates a randomly named staging directory and returns its name into the
71  * static variable staging_dir_name.
72  *
73  * If the staging directory cannot be created, staging_dir_name is set to NULL.
74  * */
75 static void make_staging_dir()
76 {
77         /* XXX Give the user an option of where to stage files */
78
79         static char prefix[] = "wimlib-staging-";
80         static const size_t prefix_len = 15;
81         static const size_t suffix_len = 10;
82
83         size_t pwd_len = strlen(working_directory);
84
85         staging_dir_name_len = pwd_len + 1 + prefix_len + suffix_len;
86
87         staging_dir_name = MALLOC(staging_dir_name_len + 1);
88         if (!staging_dir_name) {
89                 ERROR("Out of memory");
90                 return;
91         }
92
93         memcpy(staging_dir_name, working_directory, pwd_len);
94         staging_dir_name[pwd_len] = '/';
95         memcpy(staging_dir_name + pwd_len + 1, prefix, prefix_len);
96         randomize_char_array_with_alnum(staging_dir_name + pwd_len + 1 + prefix_len,
97                                 suffix_len);
98         staging_dir_name[staging_dir_name_len] = '\0';
99
100         if (mkdir(staging_dir_name, 0700) != 0) {
101                 ERROR_WITH_ERRNO("Failed to create temporary directory `%s'",
102                                  staging_dir_name);
103                 FREE(staging_dir_name);
104                 staging_dir_name = NULL;
105         }
106 }
107
108 static int remove_file_or_directory(const char *fpath, const struct stat *sb,
109                 int typeflag, struct FTW *ftwbuf)
110 {
111         if (remove(fpath) == 0)
112                 return 0;
113         else
114                 return WIMLIB_ERR_DELETE_STAGING_DIR;
115 }
116
117
118 /* 
119  * Deletes the staging directory and all the files contained in it. 
120  */
121 static inline int delete_staging_dir()
122 {
123         int ret;
124         
125         ret = nftw(staging_dir_name, remove_file_or_directory,10, FTW_DEPTH);
126         staging_dir_name = NULL;
127         return ret;
128 }
129
130 /* Name and message queue descriptors for message queues between the filesystem
131  * daemon process and the unmount process.  These are used when the filesystem
132  * is unmounted and the process running wimlib_mount() (i.e. the `imagex
133  * unmount' command) needs to communicate with the filesystem daemon running
134  * fuse_main() (i.e. that spawned by the `imagex mount' or `imagex mountrw'
135  * commands */
136 static char *unmount_to_daemon_mq_name;
137 static char *daemon_to_unmount_mq_name;
138 static int unmount_to_daemon_mq;
139 static int daemon_to_unmount_mq;
140
141 /* Simple function that returns the concatenation of 4 strings. */
142 static char *strcat_dup(const char *s1, const char *s2, const char *s3, 
143                                                         const char *s4)
144 {
145         size_t len = strlen(s1) + strlen(s2) + strlen(s3) + strlen(s4) + 1;
146         char *p = MALLOC(len);
147         if (!p)
148                 return NULL;
149         *p = '\0';
150         strcat(p, s1);
151         strcat(p, s2);
152         strcat(p, s3);
153         strcat(p, s4);
154         return p;
155 }
156
157 /* Removes trailing forward slashes in a string. */
158 static void remove_trailing_slashes(char *s)
159 {
160         long len = strlen(s);
161         for (long i = len - 1; i >= 1; i--) {
162                 if (s[i] == '/')
163                         s[i] = '\0';
164                 else
165                         break;
166         }
167 }
168
169 /* Changes forward slashes to underscores in a string. */
170 static void s_slashes_underscores_g(char *s)
171 {
172         while (*s) {
173                 if (*s == '/')
174                         *s = '_';
175                 s++;
176         }
177 }
178
179 /* 
180  * Opens two POSIX message queue: one for sending messages from the unmount
181  * process to the daemon process, and one to go the other way.  The names of the
182  * message queues, which must be system-wide unique, are be based on the mount
183  * point.  (There of course is still a possibility of a collision if one were to
184  * unmount two identically named directories simultaneously...)
185  *
186  * @daemon specifies whether the calling process is the filesystem daemon or the
187  * unmount process.
188  */
189 static int open_message_queues(bool daemon)
190 {
191         static const char *slash = "/";
192         static const char *prefix = "wimlib-";
193         static const char *u2d_suffix = "unmount-to-daemon-mq";
194         static const char *d2u_suffix = "daemon-to-unmount-mq";
195
196         const char *mount_dir_basename = path_basename(mount_dir);
197         int flags;
198         int ret;
199
200         unmount_to_daemon_mq_name = strcat_dup(slash, mount_dir_basename,
201                                                 prefix, u2d_suffix);
202         if (!unmount_to_daemon_mq_name) {
203                 ERROR("Out of memory");
204                 return WIMLIB_ERR_NOMEM;
205         }
206         daemon_to_unmount_mq_name = strcat_dup(slash, mount_dir_basename,
207                                                 prefix, d2u_suffix);
208         if (!daemon_to_unmount_mq_name) {
209                 ERROR("Out of memory");
210                 ret = WIMLIB_ERR_NOMEM;
211                 goto err1;
212         }
213
214         remove_trailing_slashes(unmount_to_daemon_mq_name);
215         remove_trailing_slashes(daemon_to_unmount_mq_name);
216         s_slashes_underscores_g(unmount_to_daemon_mq_name + 1);
217         s_slashes_underscores_g(daemon_to_unmount_mq_name + 1);
218
219         if (daemon)
220                 flags = O_RDONLY | O_CREAT;
221         else
222                 flags = O_WRONLY | O_CREAT;
223
224         unmount_to_daemon_mq = mq_open(unmount_to_daemon_mq_name, flags, 
225                                        0700, NULL);
226
227         if (unmount_to_daemon_mq == -1) {
228                 ERROR_WITH_ERRNO("mq_open()");
229                 ret = WIMLIB_ERR_MQUEUE;
230                 goto err2;
231         }
232
233         if (daemon)
234                 flags = O_WRONLY | O_CREAT;
235         else
236                 flags = O_RDONLY | O_CREAT;
237
238         daemon_to_unmount_mq = mq_open(daemon_to_unmount_mq_name, flags, 
239                                        0700, NULL);
240
241         if (daemon_to_unmount_mq == -1) {
242                 ERROR_WITH_ERRNO("mq_open()");
243                 ret = WIMLIB_ERR_MQUEUE;
244                 goto err3;
245         }
246         return 0;
247 err3:
248         mq_close(unmount_to_daemon_mq);
249         mq_unlink(unmount_to_daemon_mq_name);
250 err2:
251         FREE(daemon_to_unmount_mq_name);
252 err1:
253         FREE(unmount_to_daemon_mq_name);
254         return ret;
255 }
256
257 static int mq_get_msgsize(mqd_t mq)
258 {
259         static const char *msgsize_max_file = "/proc/sys/fs/mqueue/msgsize_max";
260         FILE *fp;
261         struct mq_attr attr;
262         int msgsize;
263
264         if (mq_getattr(unmount_to_daemon_mq, &attr) == 0) {
265                 msgsize = attr.mq_msgsize;
266         } else {
267                 ERROR_WITH_ERRNO("mq_getattr()");
268                 ERROR("Attempting to read %s", msgsize_max_file);
269                 fp = fopen(msgsize_max_file, "rb");
270                 if (fp) {
271                         if (fscanf(fp, "%d", &msgsize) != 1) {
272                                 ERROR("Assuming message size of 8192");
273                                 msgsize = 8192;
274                         }
275                         fclose(fp);
276                 } else {
277                         ERROR_WITH_ERRNO("Failed to open the file `%s'",
278                                          msgsize_max_file);
279                         ERROR("Assuming message size of 8192");
280                         msgsize = 8192;
281                 }
282         }
283         return msgsize;
284 }
285
286 /* Closes the message queues, which are allocated in static variables */
287 static void close_message_queues()
288 {
289         mq_close(unmount_to_daemon_mq);
290         mq_close(daemon_to_unmount_mq);
291         mq_unlink(unmount_to_daemon_mq_name);
292         mq_unlink(daemon_to_unmount_mq_name);
293 }
294
295 static int wimfs_access(const char *path, int mask)
296 {
297         /* XXX Permissions not implemented */
298         return 0;
299 }
300
301 /* Closes the staging file descriptor associated with the lookup table entry, if
302  * it is opened. */
303 static int close_staging_file(struct lookup_table_entry *lte, void *ignore)
304 {
305         if (lte->staging_file_name && lte->staging_num_times_opened) {
306                 if (close(lte->staging_fd) != 0) {
307                         ERROR_WITH_ERRNO("Failed close file `%s'",
308                                          lte->staging_file_name);
309                         return WIMLIB_ERR_WRITE;
310                 }
311         }
312         return 0;
313 }
314
315
316 /* Calculates the SHA1 sum for @dentry if its file resource is in a staging
317  * file.  Updates the SHA1 sum in the dentry and the lookup table entry.  If
318  * there is already a lookup table entry with the same checksum, increment its
319  * reference count and destroy the lookup entry with the updated checksum. */
320 static int calculate_sha1sum_for_staging_file(struct dentry *dentry, void *lookup_table)
321 {
322         struct lookup_table *table;
323         struct lookup_table_entry *lte; 
324         struct lookup_table_entry *existing;
325         int ret;
326
327         table = lookup_table;
328         lte = lookup_resource(table, dentry->hash);
329         
330         if (lte && lte->staging_file_name) {
331
332                 DEBUG("Calculating SHA1 hash for file `%s'",
333                       dentry->file_name_utf8);
334                 ret = sha1sum(lte->staging_file_name, dentry->hash);
335                 if (ret != 0)
336                         return ret;
337
338                 lookup_table_unlink(table, lte);
339                 memcpy(lte->hash, dentry->hash, WIM_HASH_SIZE);
340                 existing = lookup_resource(table, dentry->hash);
341                 if (existing) {
342                         DEBUG("Merging duplicate lookup table entries for file "
343                               "`%s'", dentry->file_name_utf8);
344                         free_lookup_table_entry(lte);
345                         existing->refcnt++;
346                 } else {
347                         lookup_table_insert(table, lte);
348                 }
349         }
350         return 0;
351 }
352
353 /* Overwrites the WIM file, with changes saved. */
354 static int rebuild_wim(WIMStruct *w, bool check_integrity)
355 {
356         int ret;
357         struct dentry *root;
358
359         root = wim_root_dentry(w);
360
361         DEBUG("Closing all staging file descriptors.");
362         /* Close all the staging file descriptors. */
363         ret = for_lookup_table_entry(w->lookup_table, close_staging_file, NULL);
364         if (ret != 0) {
365                 ERROR("Failed to close all staging files");
366                 return ret;
367         }
368
369         DEBUG("Calculating SHA1 checksums for all new staging files.");
370         /* Calculate SHA1 checksums for all staging files, and merge unnecessary
371          * lookup table entries. */
372         ret = for_dentry_in_tree(root, calculate_sha1sum_for_staging_file,
373                                  w->lookup_table);
374         if (ret != 0) {
375                 ERROR("Failed to calculate new SHA1 checksums");
376                 return ret;
377         }
378
379         xml_update_image_info(w, w->current_image);
380
381         ret = wimlib_overwrite(w, check_integrity);
382         if (ret != 0) {
383                 ERROR("Failed to commit changes");
384                 return ret;
385         }
386         return ret;
387 }
388
389 /* Called when the filesystem is unmounted. */
390 static void wimfs_destroy(void *p)
391 {
392
393         /* For read-write mounts, the `imagex unmount' command, which is
394          * running in a separate process and is executing the
395          * wimlib_unmount() function, will send this process a byte
396          * through a message queue that indicates whether the --commit
397          * option was specified or not. */
398
399         int msgsize;
400         struct timespec timeout;
401         struct timeval now;
402         ssize_t bytes_received;
403         int ret;
404         char commit;
405         char check_integrity;
406         char status;
407
408         ret = open_message_queues(true);
409         if (ret != 0)
410                 exit(1);
411
412         msgsize = mq_get_msgsize(unmount_to_daemon_mq);
413         char msg[msgsize];
414         msg[0] = 0;
415         msg[1] = 0;
416
417         /* Wait at most 3 seconds before giving up and discarding changes. */
418         gettimeofday(&now, NULL);
419         timeout.tv_sec = now.tv_sec + 3;
420         timeout.tv_nsec = now.tv_usec * 1000;
421         DEBUG("Waiting for message telling us whether to commit or not, and "
422               "whether to include integrity checks.");
423
424         bytes_received = mq_timedreceive(unmount_to_daemon_mq, msg, 
425                                          msgsize, NULL, &timeout);
426         commit = msg[0];
427         check_integrity = msg[1];
428         if (bytes_received == -1) {
429                 if (errno == ETIMEDOUT) {
430                         ERROR("Timed out.");
431                 } else {
432                         ERROR_WITH_ERRNO("mq_timedreceive()");
433                 }
434                 ERROR("Not committing.");
435         } else {
436                 DEBUG("Received message: [%d %d]", msg[0], msg[1]);
437         }
438
439         status = 0;
440         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
441                 if (commit) {
442                         status = chdir(working_directory);
443                         if (status != 0) {
444                                 ERROR_WITH_ERRNO("chdir()");
445                                 status = WIMLIB_ERR_NOTDIR;
446                                 goto done;
447                         }
448                         status = rebuild_wim(w, (check_integrity != 0));
449                 }
450                 ret = delete_staging_dir();
451                 if (ret != 0) {
452                         ERROR_WITH_ERRNO("Failed to delete the staging "
453                                          "directory");
454                         if (status == 0)
455                                 status = ret;
456                 }
457         }
458 done:
459         ret = mq_send(daemon_to_unmount_mq, &status, 1, 1);
460         if (ret == -1)
461                 ERROR_WITH_ERRNO("Failed to send status to unmount process");
462         close_message_queues();
463 }
464
465 /*
466  * Fills in a `struct stat' that corresponds to a file or directory in the WIM.
467  */
468 static int wimfs_getattr(const char *path, struct stat *stbuf)
469 {
470         struct dentry *dentry = get_dentry(w, path);
471         if (!dentry)
472                 return -ENOENT;
473         dentry_to_stbuf(dentry, stbuf, w->lookup_table);
474         return 0;
475 }
476
477 /* 
478  * Create a directory in the WIM.  
479  * @mode is currently ignored.
480  */
481 static int wimfs_mkdir(const char *path, mode_t mode)
482 {
483         struct dentry *parent;
484         struct dentry *newdir;
485         const char *basename;
486         
487         parent = get_parent_dentry(w, path);
488         if (!parent)
489                 return -ENOENT;
490
491         if (!dentry_is_directory(parent))
492                 return -ENOTDIR;
493
494         basename = path_basename(path);
495         if (get_dentry_child_with_name(parent, basename))
496                 return -EEXIST;
497
498         newdir = new_dentry(basename);
499         newdir->attributes |= FILE_ATTRIBUTE_DIRECTORY;
500         link_dentry(newdir, parent);
501         return 0;
502 }
503
504 /* Creates a new staging file and returns its file descriptor opened for
505  * writing.
506  *
507  * @name_ret: A location into which the a pointer to the newly allocated name of
508  *                      the staging file is stored.
509  * @return:  The file descriptor for the new file.  Returns -1 and sets errno on
510  *              error, for any reason possible from the creat() function.
511  */
512 static int create_staging_file(char **name_ret)
513 {
514         size_t name_len;
515         char *name;
516         struct stat stbuf;
517         int fd;
518         int errno_save;
519
520         name_len = staging_dir_name_len + 1 + WIM_HASH_SIZE;
521         name = MALLOC(name_len + 1);
522         if (!name) {
523                 errno = ENOMEM;
524                 return -1;
525         }
526
527         memcpy(name, staging_dir_name, staging_dir_name_len);
528         name[staging_dir_name_len] = '/';
529         randomize_char_array_with_alnum(name + staging_dir_name_len + 1,
530                                         WIM_HASH_SIZE);
531         name[name_len] = '\0';
532
533
534         /* Just in case, verify that the randomly generated name doesn't name an
535          * existing file, and try again if so  */
536         if (stat(name, &stbuf) == 0) {
537                 /* stat succeeded-- the file must exist. Try another name. */
538                 FREE(name);
539                 return create_staging_file(name_ret);
540         } else {
541                 if (errno != ENOENT)
542                         /* other error! */
543                         return -1;
544                 /* doesn't exist--- ok */
545         }
546
547         DEBUG("Creating staging file '%s'", name);
548
549         fd = creat(name, 0600); 
550         if (fd == -1) {
551                 errno_save = errno;
552                 FREE(name);
553                 errno = errno_save;
554         } else {
555                 *name_ret = name;
556         }
557         return fd;
558 }
559
560 /* Creates a regular file.  This is done in the staging directory.  */
561 static int wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
562 {
563         struct dentry *parent, *dentry;
564         const char *basename;
565         struct lookup_table_entry *lte;
566         char *tmpfile_name;
567         int fd;
568         int err;
569
570         /* Make sure that the parent of @path exists and is a directory, and
571          * that the dentry named by @path does not already exist.  */
572         parent = get_parent_dentry(w, path);
573         if (!parent)
574                 return -ENOENT;
575         if (!dentry_is_directory(parent))
576                 return -ENOTDIR;
577         basename = path_basename(path);
578         if (get_dentry_child_with_name(parent, path))
579                 return -EEXIST;
580
581         dentry = new_dentry(basename);
582
583         /* XXX fill in a temporary random hash value- really should check for
584          * duplicates */
585         randomize_byte_array(dentry->hash, WIM_HASH_SIZE);
586
587         /* Create a lookup table entry having the same hash value */
588         lte = new_lookup_table_entry();
589         memcpy(lte->hash, dentry->hash, WIM_HASH_SIZE);
590
591         fd = create_staging_file(&tmpfile_name);
592
593         if (fd == -1)
594                 goto mknod_error;
595
596         if (close(fd) != 0)
597                 goto mknod_error;
598
599         lte->staging_file_name = tmpfile_name;
600
601         /* Insert the lookup table entry, and link the new dentry with its
602          * parent. */
603         lookup_table_insert(w->lookup_table, lte);
604         link_dentry(dentry, parent);
605         return 0;
606 mknod_error:
607         err = errno;
608         free_lookup_table_entry(lte);
609         return -err;
610 }
611
612 /* Open a file.  */
613 static int wimfs_open(const char *path, struct fuse_file_info *fi)
614 {
615         struct dentry *dentry;
616         struct lookup_table_entry *lte;
617         
618         dentry = get_dentry(w, path);
619
620         if (!dentry)
621                 return -ENOENT;
622         if (dentry_is_directory(dentry))
623                 return -EISDIR;
624         lte = wim_lookup_resource(w, dentry);
625
626         if (lte) {
627                 /* If this file is in the staging directory and the file is not
628                  * currently open, open it. */
629                 if (lte->staging_file_name && lte->staging_num_times_opened == 0) {
630                         lte->staging_fd = open(lte->staging_file_name, O_RDWR);
631                         if (lte->staging_fd == -1)
632                                 return -errno;
633                         lte->staging_offset = 0;
634                 }
635         } else {
636                 /* no lookup table entry, so the file must be empty.  Create a
637                  * lookup table entry for the file, unless it's a read-only
638                  * filesystem.  */
639                 char *tmpfile_name;
640                 int fd;
641
642                 if (!staging_dir_name) /* Read-only filesystem */
643                         return 0;
644
645                 lte = new_lookup_table_entry();
646                 if (!lte)
647                         return -ENOMEM;
648
649                 fd = create_staging_file(&tmpfile_name);
650
651                 if (fd == -1) {
652                         int err = errno;
653                         free(lte);
654                         return -err;
655                 }
656                 lte->resource_entry.original_size = 0;
657                 randomize_byte_array(lte->hash, WIM_HASH_SIZE);
658                 memcpy(dentry->hash, lte->hash, WIM_HASH_SIZE);
659                 lte->staging_file_name = tmpfile_name;
660                 lte->staging_fd = fd;
661                 lte->staging_offset = 0;
662                 lookup_table_insert(w->lookup_table, lte);
663         }
664         lte->staging_num_times_opened++;
665         return 0;
666 }
667
668 /* Opens a directory. */
669 static int wimfs_opendir(const char *path, struct fuse_file_info *fi)
670 {
671         struct dentry *dentry;
672         
673         dentry = get_dentry(w, path);
674         if (!dentry || !dentry_is_directory(dentry))
675                 return -ENOTDIR;
676         return 0;
677 }
678
679
680 /*
681  * Read data from a file in the WIM or in the staging directory. 
682  */
683 static int wimfs_read(const char *path, char *buf, size_t size, 
684                 off_t offset, struct fuse_file_info *fi)
685 {
686         struct dentry *dentry;
687         struct lookup_table_entry *lte;
688         
689         dentry = get_dentry(w, path);
690
691         if (!dentry)
692                 return -EEXIST;
693
694         if (!dentry_is_regular_file(dentry))
695                 return -EISDIR;
696
697         lte = wim_lookup_resource(w, dentry);
698
699         if (!lte)
700                 return 0;
701
702         if (lte->staging_file_name) {
703
704                 /* Read from staging */
705                 int fd;
706                 off_t cur_offset;
707                 ssize_t ret;
708
709                 if (lte->staging_num_times_opened == 0)
710                         return -EBADF;
711
712                 fd = lte->staging_fd;
713                 cur_offset = lte->staging_offset;
714                 if (cur_offset != offset)
715                         if (lseek(fd, offset, SEEK_SET) == -1)
716                                 return -errno;
717                 lte->staging_offset = offset;
718
719                 ret = read(fd, buf, size);
720                 if (ret == -1)
721                         return -errno;
722                 lte->staging_offset = offset + ret;
723
724                 return ret;
725         } else {
726
727                 /* Read from WIM */
728
729                 struct resource_entry *res_entry;
730                 int ctype;
731                 
732                 res_entry = &lte->resource_entry;
733
734                 ctype = wim_resource_compression_type(w, res_entry);
735
736                 if (offset > res_entry->original_size)
737                         return -EOVERFLOW;
738
739                 size = min(size, res_entry->original_size - offset);
740
741                 if (read_resource(w->fp, res_entry->size, 
742                                   res_entry->original_size,
743                                   res_entry->offset, ctype, size, 
744                                   offset, buf) != 0)
745                         return -EIO;
746                 return size;
747         }
748 }
749
750 /* Fills in the entries of the directory specified by @path using the
751  * FUSE-provided function @filler.  */
752 static int wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, 
753                                 off_t offset, struct fuse_file_info *fi)
754 {
755         struct dentry *parent;
756         struct dentry *child;
757         struct stat st;
758
759         parent = get_dentry(w, path);
760
761         if (!parent)
762                 return -EEXIST;
763
764         if (!dentry_is_directory(parent))
765                 return -ENOTDIR;
766
767         filler(buf, ".", NULL, 0);
768         filler(buf, "..", NULL, 0);
769
770         child = parent->children;
771
772         if (!child)
773                 return 0;
774
775         do {
776                 if (filler(buf, child->file_name_utf8, NULL, 0))
777                         return 0;
778                 child = child->next;
779         } while (child != parent->children);
780         return 0;
781 }
782
783
784 static int wimfs_readlink(const char *path, char *buf, size_t buf_len)
785 {
786         struct dentry *dentry = get_dentry(w, path);
787         int ret;
788         if (!dentry)
789                 return -ENOENT;
790         if (!dentry_is_symlink(dentry))
791                 return -EINVAL;
792
793         ret = dentry_readlink(dentry, buf, buf_len, w);
794         if (ret > 0)
795                 ret = 0;
796         return ret;
797 }
798
799 /* Close a file. */
800 static int wimfs_release(const char *path, struct fuse_file_info *fi)
801 {
802         struct dentry *dentry;
803         struct lookup_table_entry *lte;
804         int ret;
805         
806         dentry = get_dentry(w, path);
807         if (!dentry)
808                 return -EEXIST;
809         lte = wim_lookup_resource(w, dentry);
810
811         if (!lte)
812                 return 0;
813         
814         if (lte->staging_num_times_opened == 0)
815                 return -EBADF;
816
817         if (--lte->staging_num_times_opened == 0 && lte->staging_file_name) {
818                 ret = close(lte->staging_fd);
819                 if (ret != 0)
820                         return -errno;
821         }
822         return 0;
823 }
824
825 /* Renames a file or directory.  See rename (3) */
826 static int wimfs_rename(const char *from, const char *to)
827 {
828         struct dentry *src;
829         struct dentry *dst;
830         struct dentry *parent_of_dst;
831         
832         src = get_dentry(w, from);
833         if (!src)
834                 return -ENOENT;
835
836         dst = get_dentry(w, to);
837
838         if (dst) {
839                 if (!dentry_is_directory(src)) {
840                         /* Cannot rename non-directory to directory. */
841                         if (dentry_is_directory(dst))
842                                 return -EISDIR;
843                 } else {
844                         /* Cannot rename directory to a non-directory or a non-empty
845                          * directory */
846                         if (!dentry_is_directory(dst))
847                                 return -ENOTDIR;
848                         if (dst->children != NULL)
849                                 return -ENOTEMPTY;
850                 }
851                 parent_of_dst = dst->parent;
852                 unlink_dentry(dst);
853                 lookup_table_decrement_refcnt(w->lookup_table, dst->hash);
854                 free_dentry(dst);
855         } else {
856                 parent_of_dst = get_parent_dentry(w, to);
857                 if (!parent_of_dst)
858                         return -ENOENT;
859         }
860
861         unlink_dentry(src);
862         change_dentry_name(src, path_basename(to));
863         link_dentry(src, parent_of_dst);
864         /*calculate_dentry_full_path(src);*/
865         return 0;
866 }
867
868 /* Remove a directory */
869 static int wimfs_rmdir(const char *path)
870 {
871         struct dentry *dentry;
872         
873         dentry = get_dentry(w, path);
874         if (!dentry)
875                 return -EEXIST;
876
877         if (!dentry_is_empty_directory(dentry))
878                 return -EEXIST;
879
880         unlink_dentry(dentry);
881         free_dentry(dentry);
882         return 0;
883 }
884
885 /* Extracts the resource corresponding to @dentry and its lookup table entry
886  * @lte to a file in the staging directory.  The lookup table entry for @dentry
887  * is updated to point to the new file.  If @lte has multiple dentries
888  * referencing it, a new lookup table entry is created and the hash of @dentry
889  * is changed to point to the new lookup table entry.
890  *
891  * Only @size bytes are extracted, to support truncating the file. 
892  *
893  * Returns the negative error code on failure.
894  */
895 static int extract_resource_to_staging_dir(struct dentry *dentry, 
896                                            struct lookup_table_entry *lte, 
897                                            u64 size)
898 {
899         int fd;
900         bool ret;
901         char *staging_file_name;
902         struct lookup_table_entry *new_lte;
903
904         /* File in WIM.  Copy it to the staging directory. */
905         fd = create_staging_file(&staging_file_name);
906         if (fd == -1)
907                 return -errno;
908
909         ret = extract_resource_to_fd(w, &lte->resource_entry, fd, size);
910         if (ret != 0) {
911                 if (errno != 0)
912                         ret = -errno;
913                 else
914                         ret = -EIO;
915                 unlink(staging_file_name);
916                 FREE(staging_file_name);
917                 return ret;
918         }
919
920         if (lte->refcnt != 1) {
921                 /* Need to make a new lookup table entry if we are
922                  * changing only one copy of a hardlinked entry */
923                 lte->refcnt--;
924
925                 new_lte = new_lookup_table_entry();
926                 if (!new_lte)
927                         return -ENOMEM;
928                 randomize_byte_array(dentry->hash, WIM_HASH_SIZE);
929                 memcpy(new_lte->hash, dentry->hash, WIM_HASH_SIZE);
930
931                 new_lte->resource_entry.flags = 0;
932                 new_lte->staging_num_times_opened = lte->staging_num_times_opened;
933
934                 lookup_table_insert(w->lookup_table, new_lte);
935
936                 lte = new_lte;
937         } 
938
939         lte->resource_entry.original_size = size;
940         lte->staging_file_name = staging_file_name;
941         
942         if (lte->staging_num_times_opened == 0)
943                 close(fd);
944         else
945                 lte->staging_fd = fd;
946         return 0;
947 }
948
949 /* Reduce the size of a file */
950 static int wimfs_truncate(const char *path, off_t size)
951 {
952         struct dentry *dentry;
953         struct lookup_table_entry *lte;
954         int ret;
955
956         dentry = get_dentry(w, path);
957         if (!dentry)
958                 return -EEXIST;
959         lte = wim_lookup_resource(w, dentry);
960
961         if (!lte) /* Already a zero-length file */
962                 return 0;
963         if (lte->staging_file_name) {
964                 /* File on disk.  Call POSIX API */
965                 if (lte->staging_num_times_opened != 0)
966                         ret = ftruncate(lte->staging_fd, size);
967                 else
968                         ret = truncate(lte->staging_file_name, size);
969                 if (ret != 0)
970                         return -errno;
971                 dentry_update_all_timestamps(dentry);
972                 lte->resource_entry.original_size = size;
973                 return 0;
974         } else {
975                 /* File in WIM.  Extract it to the staging directory, but only
976                  * the first @size bytes of it. */
977                 return extract_resource_to_staging_dir(dentry, lte, size);
978         }
979 }
980
981 /* Remove a regular file */
982 static int wimfs_unlink(const char *path)
983 {
984         struct dentry *dentry;
985         struct lookup_table_entry *lte;
986         
987         dentry = get_dentry(w, path);
988         if (!dentry)
989                 return -EEXIST;
990
991         if (!dentry_is_regular_file(dentry))
992                 return -EEXIST;
993
994         lte = wim_lookup_resource(w, dentry);
995         if (lte) {
996                 if (lte->staging_file_name)
997                         if (unlink(lte->staging_file_name) != 0)
998                                 return -errno;
999                 lookup_table_decrement_refcnt(w->lookup_table, dentry->hash);
1000         }
1001
1002         unlink_dentry(dentry);
1003         free_dentry(dentry);
1004         return 0;
1005 }
1006
1007 static int wimfs_utimens(const char *path, const struct timespec tv[2])
1008 {
1009         struct dentry *dentry = get_dentry(w, path);
1010         if (!dentry)
1011                 return -ENOENT;
1012         time_t last_access_t = (tv[0].tv_nsec == UTIME_NOW) ? 
1013                                 time(NULL) : tv[0].tv_sec;
1014         dentry->last_access_time = unix_timestamp_to_ms(last_access_t);
1015         time_t last_mod_t = (tv[1].tv_nsec == UTIME_NOW) ?  
1016                                 time(NULL) : tv[1].tv_sec;
1017         dentry->last_write_time = unix_timestamp_to_ms(last_mod_t);
1018         return 0;
1019 }
1020
1021 /* Writes to a file in the WIM filesystem. */
1022 static int wimfs_write(const char *path, const char *buf, size_t size, 
1023                                 off_t offset, struct fuse_file_info *fi)
1024 {
1025         struct dentry *dentry;
1026         struct lookup_table_entry *lte;
1027         ssize_t ret;
1028
1029         dentry = get_dentry(w, path);
1030         if (!dentry)
1031                 return -EEXIST;
1032         lte = wim_lookup_resource(w, dentry);
1033
1034         if (!lte) /* this should not happen */
1035                 return -EEXIST;
1036
1037         if (lte->staging_num_times_opened == 0)
1038                 return -EBADF;
1039         if (lte->staging_file_name) {
1040
1041                 /* File in staging directory. We can write to it directly. */
1042
1043                 /* Seek to correct position in file if needed. */
1044                 if (lte->staging_offset != offset) {
1045                         if (lseek(lte->staging_fd, offset, SEEK_SET) == -1)
1046                                 return -errno;
1047                         lte->staging_offset = offset;
1048                 }
1049
1050                 /* Write the data. */
1051                 ret = write(lte->staging_fd, buf, size);
1052                 if (ret == -1)
1053                         return -errno;
1054
1055                 /* Adjust the stored offset of staging_fd. */
1056                 lte->staging_offset = offset + ret;
1057
1058                 /* Increase file size if needed. */
1059                 if (lte->resource_entry.original_size < lte->staging_offset)
1060                         lte->resource_entry.original_size = lte->staging_offset;
1061
1062                 /* The file has been modified, so all its timestamps must be
1063                  * updated. */
1064                 dentry_update_all_timestamps(dentry);
1065                 return ret;
1066         } else {
1067                 /* File in the WIM.  We must extract it to the staging directory
1068                  * before it can be written to. */
1069                 ret = extract_resource_to_staging_dir(dentry, lte, 
1070                                         lte->resource_entry.original_size);
1071                 if (ret != 0)
1072                         return ret;
1073                 else
1074                         return wimfs_write(path, buf, size, offset, fi);
1075         }
1076 }
1077
1078
1079 static struct fuse_operations wimfs_oper = {
1080         .access   = wimfs_access,
1081         .destroy  = wimfs_destroy,
1082         .getattr  = wimfs_getattr,
1083         .mkdir    = wimfs_mkdir,
1084         .mknod    = wimfs_mknod,
1085         .open     = wimfs_open,
1086         .opendir  = wimfs_opendir,
1087         .read     = wimfs_read,
1088         .readdir  = wimfs_readdir,
1089         .readlink = wimfs_readlink,
1090         .release  = wimfs_release,
1091         .rename   = wimfs_rename,
1092         .rmdir    = wimfs_rmdir,
1093         .truncate = wimfs_truncate,
1094         .unlink   = wimfs_unlink,
1095         .utimens  = wimfs_utimens,
1096         .write    = wimfs_write,
1097 };
1098
1099
1100 /* Mounts a WIM file. */
1101 WIMLIBAPI int wimlib_mount(WIMStruct *wim, int image, const char *dir, 
1102                            int flags)
1103 {
1104         int argc = 0;
1105         char *argv[6];
1106         int ret;
1107         char *p;
1108
1109         DEBUG("Mount: wim = %p, image = %d, dir = %s, flags = %d, ",
1110                         wim, image, dir, flags);
1111
1112         if (!dir)
1113                 return WIMLIB_ERR_INVALID_PARAM;
1114
1115         ret = wimlib_select_image(wim, image);
1116
1117         if (ret != 0)
1118                 return ret;
1119
1120         if (flags & WIMLIB_MOUNT_FLAG_READWRITE)
1121                 wim_get_current_image_metadata(wim)->modified = true;
1122
1123         if (!(flags & (WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
1124                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
1125                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)))
1126                 flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
1127
1128         mount_dir = dir;
1129         working_directory = getcwd(NULL, 0);
1130         if (!working_directory) {
1131                 ERROR_WITH_ERRNO("Could not determine current directory");
1132                 return WIMLIB_ERR_NOTDIR;
1133         }
1134
1135         p = STRDUP(dir);
1136         if (!p)
1137                 return WIMLIB_ERR_NOMEM;
1138
1139         argv[argc++] = "mount";
1140         argv[argc++] = p;
1141         argv[argc++] = "-s"; /* disable multi-threaded operation */
1142
1143         if (flags & WIMLIB_MOUNT_FLAG_DEBUG) {
1144                 argv[argc++] = "-d";
1145         }
1146         if (!(flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
1147                 argv[argc++] = "-o";
1148                 argv[argc++] = "ro";
1149         } else {
1150                 make_staging_dir();
1151                 if (!staging_dir_name) {
1152                         FREE(p);
1153                         return WIMLIB_ERR_MKDIR;
1154                 }
1155         }
1156
1157 #ifdef ENABLE_DEBUG
1158         {
1159                 int i;
1160                 DEBUG("FUSE command line (argc = %d): ", argc);
1161                 for (i = 0; i < argc; i++) {
1162                         fputs(argv[i], stdout);
1163                         putchar(' ');
1164                 }
1165                 putchar('\n');
1166                 fflush(stdout);
1167         }
1168 #endif
1169
1170         /* Set static variables. */
1171         w = wim;
1172         mount_flags = flags;
1173
1174         ret = fuse_main(argc, argv, &wimfs_oper, NULL);
1175
1176         return (ret == 0) ? 0 : WIMLIB_ERR_FUSE;
1177 }
1178
1179
1180 /* 
1181  * Unmounts the WIM file that was previously mounted on @dir by using
1182  * wimlib_mount().
1183  */
1184 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
1185 {
1186         pid_t pid;
1187         int status;
1188         int ret;
1189         char msg[2];
1190         struct timeval now;
1191         struct timespec timeout;
1192         int msgsize;
1193         int errno_save;
1194
1195         /* Execute `fusermount -u', which is installed setuid root, to unmount
1196          * the WIM.
1197          *
1198          * FUSE does not yet implement synchronous unmounts.  This means that
1199          * fusermount -u will return before the filesystem daemon returns from
1200          * wimfs_destroy().  This is partly what we want, because we need to
1201          * send a message from this process to the filesystem daemon telling
1202          * whether --commit was specified or not.  However, after that, the
1203          * unmount process must wait for the filesystem daemon to finish writing
1204          * the WIM file. 
1205          */
1206
1207         mount_dir = dir;
1208         pid = fork();
1209         if (pid == -1) {
1210                 ERROR_WITH_ERRNO("Failed to fork()");
1211                 return WIMLIB_ERR_FORK;
1212         }
1213         if (pid == 0) {
1214                 execlp("fusermount", "fusermount", "-u", dir, NULL);
1215                 ERROR_WITH_ERRNO("Failed to execute `fusermount'");
1216                 return WIMLIB_ERR_FUSERMOUNT;
1217         }
1218
1219         ret = waitpid(pid, &status, 0);
1220         if (ret == -1) {
1221                 ERROR_WITH_ERRNO("Failed to wait for fusermount process to "
1222                                  "terminate");
1223                 return WIMLIB_ERR_FUSERMOUNT;
1224         }
1225
1226         if (status != 0) {
1227                 ERROR("fusermount exited with status %d", status);
1228                 return WIMLIB_ERR_FUSERMOUNT;
1229         }
1230
1231         /* Open message queues between the unmount process and the
1232          * filesystem daemon. */
1233         ret = open_message_queues(false);
1234         if (ret != 0)
1235                 return ret;
1236
1237         /* Send a message to the filesystem saying whether to commit or
1238          * not. */
1239         msg[0] = (flags & WIMLIB_UNMOUNT_FLAG_COMMIT) ? 1 : 0;
1240         msg[1] = (flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY) ? 1 : 0;
1241
1242         DEBUG("Sending message: %s, %s", 
1243                         (msg[0] == 0) ? "don't commit" : "commit",
1244                         (msg[1] == 0) ? "don't check"  : "check");
1245         ret = mq_send(unmount_to_daemon_mq, msg, 2, 1);
1246         if (ret == -1) {
1247                 ERROR("Failed to notify filesystem daemon whether we want to "
1248                       "commit changes or not");
1249                 close_message_queues();
1250                 return WIMLIB_ERR_MQUEUE;
1251         }
1252
1253         /* Wait for a message from the filesytem daemon indicating whether  the
1254          * filesystem was unmounted successfully (0) or an error occurred (1).
1255          * This may take a long time if a big WIM file needs to be rewritten. */
1256
1257         /* Wait at most 600??? seconds before giving up and returning false.
1258          * Either it's a really big WIM file, or (more likely) the
1259          * filesystem daemon has crashed or failed for some reason.
1260          *
1261          * XXX come up with some method to determine if the filesystem
1262          * daemon has really crashed or not. */
1263
1264         gettimeofday(&now, NULL);
1265         timeout.tv_sec = now.tv_sec + 600;
1266         timeout.tv_nsec = now.tv_usec * 1000;
1267
1268         msgsize = mq_get_msgsize(daemon_to_unmount_mq);
1269         char mailbox[msgsize];
1270
1271         mailbox[0] = 0;
1272         DEBUG("Waiting for message telling us whether the unmount was "
1273                         "successful or not.");
1274         ret = mq_timedreceive(daemon_to_unmount_mq, mailbox, msgsize,
1275                               NULL, &timeout);
1276         errno_save = errno;
1277         close_message_queues();
1278         if (ret == -1) {
1279                 if (errno_save == ETIMEDOUT) {
1280                         ERROR("Timed out- probably the filesystem daemon "
1281                               "crashed and the WIM was not written "
1282                               "successfully.");
1283                         return WIMLIB_ERR_TIMEOUT;
1284                 } else {
1285                         ERROR("mq_receive(): %s", strerror(errno_save));
1286                         return WIMLIB_ERR_MQUEUE;
1287                 }
1288
1289         }
1290         DEBUG("Received message: %s",
1291               (mailbox[0] == 0) ?  "Unmount OK" : "Unmount Failed");
1292         if (mailbox[0] != 0)
1293                 ERROR("Unmount failed");
1294         return mailbox[0];
1295 }
1296
1297 #else /* WITH_FUSE */
1298
1299
1300 static inline int mount_unsupported_error()
1301 {
1302         ERROR("WIMLIB was compiled with --without-fuse, which disables support "
1303               "for mounting WIMs.");
1304         return WIMLIB_ERR_UNSUPPORTED;
1305 }
1306
1307 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
1308 {
1309         return mount_unsupported_error();
1310 }
1311
1312 WIMLIBAPI int wimlib_mount(WIMStruct *wim_p, int image, const char *dir, 
1313                            int flags)
1314 {
1315         return mount_unsupported_error();
1316 }
1317
1318 #endif /* WITH_FUSE */