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