]> wimlib.net Git - wimlib/blob - src/mount.c
Implement readlink() on WIM filesystem
[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 -EEXIST;
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  * Find the symlink target of a symbolic link dentry in the WIM.
785  *
786  * See http://msdn.microsoft.com/en-us/library/cc232006(v=prot.10).aspx
787  * Except the first 8 bytes aren't included in the resource (presumably because
788  * we already know the reparse tag from the dentry, and we already know the
789  * reparse tag len from the lookup table entry resource length).
790  */
791 static int get_symlink_name(const u8 *resource, size_t resource_len,
792                             char *buf, size_t buf_len)
793 {
794         const u8 *p = resource;
795         u16 substitute_name_offset;
796         u16 substitute_name_len;
797         u16 print_name_offset;
798         u16 print_name_len;
799         u32 flags;
800         char *link_target;
801         size_t link_target_len;
802         int ret;
803         if (resource_len < 12)
804                 return -EIO;
805         p = get_u16(p, &substitute_name_offset);
806         p = get_u16(p, &substitute_name_len);
807         p = get_u16(p, &print_name_offset);
808         p = get_u16(p, &print_name_len);
809         p = get_u32(p, &flags);
810         if (12 + substitute_name_offset + substitute_name_len > resource_len)
811                 return -EIO;
812         link_target = utf16_to_utf8(p + substitute_name_offset,
813                                     substitute_name_len,
814                                     &link_target_len);
815         if (!link_target)
816                 return -EIO;
817         if (link_target_len + 1 > buf_len) {
818                 ret = -ENAMETOOLONG;
819                 goto out;
820         }
821         memcpy(buf, link_target, link_target_len + 1);
822         ret = 0;
823 out:
824         free(link_target);
825         return ret;
826 }
827
828 static int wimfs_readlink(const char *path, char *buf, size_t buf_len)
829 {
830         struct dentry *dentry = get_dentry(w, path);
831         struct ads_entry *ads;
832         struct lookup_table_entry *entry;
833         struct resource_entry *res_entry;
834         if (!dentry)
835                 return -ENOENT;
836         if (!dentry_is_symlink(dentry))
837                 return -EINVAL;
838
839         /* 
840          * This is of course not actually documented, but what I think is going
841          * on here is that the symlink dentries have 2 alternate data streams;
842          * one is the default data stream, which is not used and is empty, and
843          * one is the symlink buffer data stream, which is confusingly also
844          * unnamed, but isn't empty as it contains the symlink target within the
845          * resource.
846          */
847         if (dentry->num_ads != 2)
848                 return -EIO;
849         if ((entry = lookup_resource(w->lookup_table, dentry->ads_entries[0].hash)))
850                 goto do_readlink;
851         if ((entry = lookup_resource(w->lookup_table, dentry->ads_entries[1].hash)))
852                 goto do_readlink;
853         return -EIO;
854 do_readlink:
855         res_entry = &entry->resource_entry;
856         char res_buf[res_entry->original_size];
857         if (read_full_resource(w->fp, res_entry->size, 
858                                res_entry->original_size,
859                                res_entry->offset,
860                                wim_resource_compression_type(w, res_entry),
861                                res_buf) != 0)
862                 return -EIO;
863         return get_symlink_name(res_buf, res_entry->original_size, buf, buf_len);
864 }
865
866 /* Close a file. */
867 static int wimfs_release(const char *path, struct fuse_file_info *fi)
868 {
869         struct dentry *dentry;
870         struct lookup_table_entry *lte;
871         int ret;
872         
873         dentry = get_dentry(w, path);
874         if (!dentry)
875                 return -EEXIST;
876         lte = wim_lookup_resource(w, dentry);
877
878         if (!lte)
879                 return 0;
880         
881         if (lte->staging_num_times_opened == 0)
882                 return -EBADF;
883
884         if (--lte->staging_num_times_opened == 0 && lte->staging_file_name) {
885                 ret = close(lte->staging_fd);
886                 if (ret != 0)
887                         return -errno;
888         }
889         return 0;
890 }
891
892 /* Renames a file or directory.  See rename (3) */
893 static int wimfs_rename(const char *from, const char *to)
894 {
895         struct dentry *src;
896         struct dentry *dst;
897         struct dentry *parent_of_dst;
898         
899         src = get_dentry(w, from);
900         if (!src)
901                 return -ENOENT;
902
903         dst = get_dentry(w, to);
904
905         if (dst) {
906                 if (!dentry_is_directory(src)) {
907                         /* Cannot rename non-directory to directory. */
908                         if (dentry_is_directory(dst))
909                                 return -EISDIR;
910                 } else {
911                         /* Cannot rename directory to a non-directory or a non-empty
912                          * directory */
913                         if (!dentry_is_directory(dst))
914                                 return -ENOTDIR;
915                         if (dst->children != NULL)
916                                 return -ENOTEMPTY;
917                 }
918                 parent_of_dst = dst->parent;
919                 unlink_dentry(dst);
920                 lookup_table_decrement_refcnt(w->lookup_table, dst->hash);
921                 free_dentry(dst);
922         } else {
923                 parent_of_dst = get_parent_dentry(w, to);
924                 if (!parent_of_dst)
925                         return -ENOENT;
926         }
927
928         unlink_dentry(src);
929         change_dentry_name(src, path_basename(to));
930         link_dentry(src, parent_of_dst);
931         /*calculate_dentry_full_path(src);*/
932         return 0;
933 }
934
935 /* Remove a directory */
936 static int wimfs_rmdir(const char *path)
937 {
938         struct dentry *dentry;
939         
940         dentry = get_dentry(w, path);
941         if (!dentry)
942                 return -EEXIST;
943
944         if (!dentry_is_empty_directory(dentry))
945                 return -EEXIST;
946
947         unlink_dentry(dentry);
948         free_dentry(dentry);
949         return 0;
950 }
951
952 /* Extracts the resource corresponding to @dentry and its lookup table entry
953  * @lte to a file in the staging directory.  The lookup table entry for @dentry
954  * is updated to point to the new file.  If @lte has multiple dentries
955  * referencing it, a new lookup table entry is created and the hash of @dentry
956  * is changed to point to the new lookup table entry.
957  *
958  * Only @size bytes are extracted, to support truncating the file. 
959  *
960  * Returns the negative error code on failure.
961  */
962 static int extract_resource_to_staging_dir(struct dentry *dentry, 
963                                            struct lookup_table_entry *lte, 
964                                            u64 size)
965 {
966         int fd;
967         bool ret;
968         char *staging_file_name;
969         struct lookup_table_entry *new_lte;
970
971         /* File in WIM.  Copy it to the staging directory. */
972         fd = create_staging_file(&staging_file_name);
973         if (fd == -1)
974                 return -errno;
975
976         ret = extract_resource_to_fd(w, &lte->resource_entry, fd, size);
977         if (ret != 0) {
978                 if (errno != 0)
979                         ret = -errno;
980                 else
981                         ret = -EIO;
982                 unlink(staging_file_name);
983                 FREE(staging_file_name);
984                 return ret;
985         }
986
987         if (lte->refcnt != 1) {
988                 /* Need to make a new lookup table entry if we are
989                  * changing only one copy of a hardlinked entry */
990                 lte->refcnt--;
991
992                 new_lte = new_lookup_table_entry();
993                 if (!new_lte)
994                         return -ENOMEM;
995                 randomize_byte_array(dentry->hash, WIM_HASH_SIZE);
996                 memcpy(new_lte->hash, dentry->hash, WIM_HASH_SIZE);
997
998                 new_lte->resource_entry.flags = 0;
999                 new_lte->staging_num_times_opened = lte->staging_num_times_opened;
1000
1001                 lookup_table_insert(w->lookup_table, new_lte);
1002
1003                 lte = new_lte;
1004         } 
1005
1006         lte->resource_entry.original_size = size;
1007         lte->staging_file_name = staging_file_name;
1008         
1009         if (lte->staging_num_times_opened == 0)
1010                 close(fd);
1011         else
1012                 lte->staging_fd = fd;
1013         return 0;
1014 }
1015
1016 /* Reduce the size of a file */
1017 static int wimfs_truncate(const char *path, off_t size)
1018 {
1019         struct dentry *dentry;
1020         struct lookup_table_entry *lte;
1021         int ret;
1022
1023         dentry = get_dentry(w, path);
1024         if (!dentry)
1025                 return -EEXIST;
1026         lte = wim_lookup_resource(w, dentry);
1027
1028         if (!lte) /* Already a zero-length file */
1029                 return 0;
1030         if (lte->staging_file_name) {
1031                 /* File on disk.  Call POSIX API */
1032                 if (lte->staging_num_times_opened != 0)
1033                         ret = ftruncate(lte->staging_fd, size);
1034                 else
1035                         ret = truncate(lte->staging_file_name, size);
1036                 if (ret != 0)
1037                         return -errno;
1038                 dentry_update_all_timestamps(dentry);
1039                 lte->resource_entry.original_size = size;
1040                 return 0;
1041         } else {
1042                 /* File in WIM.  Extract it to the staging directory, but only
1043                  * the first @size bytes of it. */
1044                 return extract_resource_to_staging_dir(dentry, lte, size);
1045         }
1046 }
1047
1048 /* Remove a regular file */
1049 static int wimfs_unlink(const char *path)
1050 {
1051         struct dentry *dentry;
1052         struct lookup_table_entry *lte;
1053         
1054         dentry = get_dentry(w, path);
1055         if (!dentry)
1056                 return -EEXIST;
1057
1058         if (!dentry_is_regular_file(dentry))
1059                 return -EEXIST;
1060
1061         lte = wim_lookup_resource(w, dentry);
1062         if (lte) {
1063                 if (lte->staging_file_name)
1064                         if (unlink(lte->staging_file_name) != 0)
1065                                 return -errno;
1066                 lookup_table_decrement_refcnt(w->lookup_table, dentry->hash);
1067         }
1068
1069         unlink_dentry(dentry);
1070         free_dentry(dentry);
1071         return 0;
1072 }
1073
1074 static int wimfs_utimens(const char *path, const struct timespec tv[2])
1075 {
1076         struct dentry *dentry = get_dentry(w, path);
1077         if (!dentry)
1078                 return -ENOENT;
1079         time_t last_access_t = (tv[0].tv_nsec == UTIME_NOW) ? 
1080                                 time(NULL) : tv[0].tv_sec;
1081         dentry->last_access_time = unix_timestamp_to_ms(last_access_t);
1082         time_t last_mod_t = (tv[1].tv_nsec == UTIME_NOW) ?  
1083                                 time(NULL) : tv[1].tv_sec;
1084         dentry->last_write_time = unix_timestamp_to_ms(last_mod_t);
1085         return 0;
1086 }
1087
1088 /* Writes to a file in the WIM filesystem. */
1089 static int wimfs_write(const char *path, const char *buf, size_t size, 
1090                                 off_t offset, struct fuse_file_info *fi)
1091 {
1092         struct dentry *dentry;
1093         struct lookup_table_entry *lte;
1094         ssize_t ret;
1095
1096         dentry = get_dentry(w, path);
1097         if (!dentry)
1098                 return -EEXIST;
1099         lte = wim_lookup_resource(w, dentry);
1100
1101         if (!lte) /* this should not happen */
1102                 return -EEXIST;
1103
1104         if (lte->staging_num_times_opened == 0)
1105                 return -EBADF;
1106         if (lte->staging_file_name) {
1107
1108                 /* File in staging directory. We can write to it directly. */
1109
1110                 /* Seek to correct position in file if needed. */
1111                 if (lte->staging_offset != offset) {
1112                         if (lseek(lte->staging_fd, offset, SEEK_SET) == -1)
1113                                 return -errno;
1114                         lte->staging_offset = offset;
1115                 }
1116
1117                 /* Write the data. */
1118                 ret = write(lte->staging_fd, buf, size);
1119                 if (ret == -1)
1120                         return -errno;
1121
1122                 /* Adjust the stored offset of staging_fd. */
1123                 lte->staging_offset = offset + ret;
1124
1125                 /* Increase file size if needed. */
1126                 if (lte->resource_entry.original_size < lte->staging_offset)
1127                         lte->resource_entry.original_size = lte->staging_offset;
1128
1129                 /* The file has been modified, so all its timestamps must be
1130                  * updated. */
1131                 dentry_update_all_timestamps(dentry);
1132                 return ret;
1133         } else {
1134                 /* File in the WIM.  We must extract it to the staging directory
1135                  * before it can be written to. */
1136                 ret = extract_resource_to_staging_dir(dentry, lte, 
1137                                         lte->resource_entry.original_size);
1138                 if (ret != 0)
1139                         return ret;
1140                 else
1141                         return wimfs_write(path, buf, size, offset, fi);
1142         }
1143 }
1144
1145
1146 static struct fuse_operations wimfs_oper = {
1147         .access   = wimfs_access,
1148         .destroy  = wimfs_destroy,
1149         .getattr  = wimfs_getattr,
1150         .mkdir    = wimfs_mkdir,
1151         .mknod    = wimfs_mknod,
1152         .open     = wimfs_open,
1153         .opendir  = wimfs_opendir,
1154         .read     = wimfs_read,
1155         .readdir  = wimfs_readdir,
1156         .readlink = wimfs_readlink,
1157         .release  = wimfs_release,
1158         .rename   = wimfs_rename,
1159         .rmdir    = wimfs_rmdir,
1160         .truncate = wimfs_truncate,
1161         .unlink   = wimfs_unlink,
1162         .utimens  = wimfs_utimens,
1163         .write    = wimfs_write,
1164 };
1165
1166
1167 /* Mounts a WIM file. */
1168 WIMLIBAPI int wimlib_mount(WIMStruct *wim, int image, const char *dir, 
1169                            int flags)
1170 {
1171         int argc = 0;
1172         char *argv[6];
1173         int ret;
1174         char *p;
1175
1176         DEBUG("Mount: wim = %p, image = %d, dir = %s, flags = %d, ",
1177                         wim, image, dir, flags);
1178
1179         if (!dir)
1180                 return WIMLIB_ERR_INVALID_PARAM;
1181
1182         ret = wimlib_select_image(wim, image);
1183
1184         if (ret != 0)
1185                 return ret;
1186
1187         if (flags & WIMLIB_MOUNT_FLAG_READWRITE)
1188                 wim_get_current_image_metadata(wim)->modified = true;
1189
1190         if (!(flags & (WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
1191                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
1192                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)))
1193                 flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
1194
1195         mount_dir = dir;
1196         working_directory = getcwd(NULL, 0);
1197         if (!working_directory) {
1198                 ERROR_WITH_ERRNO("Could not determine current directory");
1199                 return WIMLIB_ERR_NOTDIR;
1200         }
1201
1202         p = STRDUP(dir);
1203         if (!p)
1204                 return WIMLIB_ERR_NOMEM;
1205
1206         argv[argc++] = "mount";
1207         argv[argc++] = p;
1208         argv[argc++] = "-s"; /* disable multi-threaded operation */
1209
1210         if (flags & WIMLIB_MOUNT_FLAG_DEBUG) {
1211                 argv[argc++] = "-d";
1212         }
1213         if (!(flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
1214                 argv[argc++] = "-o";
1215                 argv[argc++] = "ro";
1216         } else {
1217                 make_staging_dir();
1218                 if (!staging_dir_name) {
1219                         FREE(p);
1220                         return WIMLIB_ERR_MKDIR;
1221                 }
1222         }
1223
1224 #ifdef ENABLE_DEBUG
1225         {
1226                 int i;
1227                 DEBUG("FUSE command line (argc = %d): ", argc);
1228                 for (i = 0; i < argc; i++) {
1229                         fputs(argv[i], stdout);
1230                         putchar(' ');
1231                 }
1232                 putchar('\n');
1233                 fflush(stdout);
1234         }
1235 #endif
1236
1237         /* Set static variables. */
1238         w = wim;
1239         mount_flags = flags;
1240
1241         ret = fuse_main(argc, argv, &wimfs_oper, NULL);
1242
1243         return (ret == 0) ? 0 : WIMLIB_ERR_FUSE;
1244 }
1245
1246
1247 /* 
1248  * Unmounts the WIM file that was previously mounted on @dir by using
1249  * wimlib_mount().
1250  */
1251 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
1252 {
1253         pid_t pid;
1254         int status;
1255         int ret;
1256         char msg[2];
1257         struct timeval now;
1258         struct timespec timeout;
1259         int msgsize;
1260         int errno_save;
1261
1262         /* Execute `fusermount -u', which is installed setuid root, to unmount
1263          * the WIM.
1264          *
1265          * FUSE does not yet implement synchronous unmounts.  This means that
1266          * fusermount -u will return before the filesystem daemon returns from
1267          * wimfs_destroy().  This is partly what we want, because we need to
1268          * send a message from this process to the filesystem daemon telling
1269          * whether --commit was specified or not.  However, after that, the
1270          * unmount process must wait for the filesystem daemon to finish writing
1271          * the WIM file. 
1272          */
1273
1274         mount_dir = dir;
1275         pid = fork();
1276         if (pid == -1) {
1277                 ERROR_WITH_ERRNO("Failed to fork()");
1278                 return WIMLIB_ERR_FORK;
1279         }
1280         if (pid == 0) {
1281                 execlp("fusermount", "fusermount", "-u", dir, NULL);
1282                 ERROR_WITH_ERRNO("Failed to execute `fusermount'");
1283                 return WIMLIB_ERR_FUSERMOUNT;
1284         }
1285
1286         ret = waitpid(pid, &status, 0);
1287         if (ret == -1) {
1288                 ERROR_WITH_ERRNO("Failed to wait for fusermount process to "
1289                                  "terminate");
1290                 return WIMLIB_ERR_FUSERMOUNT;
1291         }
1292
1293         if (status != 0) {
1294                 ERROR("fusermount exited with status %d", status);
1295                 return WIMLIB_ERR_FUSERMOUNT;
1296         }
1297
1298         /* Open message queues between the unmount process and the
1299          * filesystem daemon. */
1300         ret = open_message_queues(false);
1301         if (ret != 0)
1302                 return ret;
1303
1304         /* Send a message to the filesystem saying whether to commit or
1305          * not. */
1306         msg[0] = (flags & WIMLIB_UNMOUNT_FLAG_COMMIT) ? 1 : 0;
1307         msg[1] = (flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY) ? 1 : 0;
1308
1309         DEBUG("Sending message: %s, %s", 
1310                         (msg[0] == 0) ? "don't commit" : "commit",
1311                         (msg[1] == 0) ? "don't check"  : "check");
1312         ret = mq_send(unmount_to_daemon_mq, msg, 2, 1);
1313         if (ret == -1) {
1314                 ERROR("Failed to notify filesystem daemon whether we want to "
1315                       "commit changes or not");
1316                 close_message_queues();
1317                 return WIMLIB_ERR_MQUEUE;
1318         }
1319
1320         /* Wait for a message from the filesytem daemon indicating whether  the
1321          * filesystem was unmounted successfully (0) or an error occurred (1).
1322          * This may take a long time if a big WIM file needs to be rewritten. */
1323
1324         /* Wait at most 600??? seconds before giving up and returning false.
1325          * Either it's a really big WIM file, or (more likely) the
1326          * filesystem daemon has crashed or failed for some reason.
1327          *
1328          * XXX come up with some method to determine if the filesystem
1329          * daemon has really crashed or not. */
1330
1331         gettimeofday(&now, NULL);
1332         timeout.tv_sec = now.tv_sec + 600;
1333         timeout.tv_nsec = now.tv_usec * 1000;
1334
1335         msgsize = mq_get_msgsize(daemon_to_unmount_mq);
1336         char mailbox[msgsize];
1337
1338         mailbox[0] = 0;
1339         DEBUG("Waiting for message telling us whether the unmount was "
1340                         "successful or not.");
1341         ret = mq_timedreceive(daemon_to_unmount_mq, mailbox, msgsize,
1342                               NULL, &timeout);
1343         errno_save = errno;
1344         close_message_queues();
1345         if (ret == -1) {
1346                 if (errno_save == ETIMEDOUT) {
1347                         ERROR("Timed out- probably the filesystem daemon "
1348                               "crashed and the WIM was not written "
1349                               "successfully.");
1350                         return WIMLIB_ERR_TIMEOUT;
1351                 } else {
1352                         ERROR("mq_receive(): %s", strerror(errno_save));
1353                         return WIMLIB_ERR_MQUEUE;
1354                 }
1355
1356         }
1357         DEBUG("Received message: %s",
1358               (mailbox[0] == 0) ?  "Unmount OK" : "Unmount Failed");
1359         if (mailbox[0] != 0)
1360                 ERROR("Unmount failed");
1361         return mailbox[0];
1362 }
1363
1364 #else /* WITH_FUSE */
1365
1366
1367 static inline int mount_unsupported_error()
1368 {
1369         ERROR("WIMLIB was compiled with --without-fuse, which disables support "
1370               "for mounting WIMs.");
1371         return WIMLIB_ERR_UNSUPPORTED;
1372 }
1373
1374 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
1375 {
1376         return mount_unsupported_error();
1377 }
1378
1379 WIMLIBAPI int wimlib_mount(WIMStruct *wim_p, int image, const char *dir, 
1380                            int flags)
1381 {
1382         return mount_unsupported_error();
1383 }
1384
1385 #endif /* WITH_FUSE */