]> wimlib.net Git - wimlib/blob - src/mount.c
f3043c2b5a7e26f910d9c4f51840290fd9e416d1
[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         lte->staging_num_times_opened = 0;
589         lte->resource_entry.original_size = 0;
590         memcpy(lte->hash, dentry->hash, WIM_HASH_SIZE);
591
592         fd = create_staging_file(&tmpfile_name);
593
594         if (fd == -1)
595                 goto mknod_error;
596
597         if (close(fd) != 0)
598                 goto mknod_error;
599
600         lte->staging_file_name = tmpfile_name;
601
602         /* Insert the lookup table entry, and link the new dentry with its
603          * parent. */
604         lookup_table_insert(w->lookup_table, lte);
605         link_dentry(dentry, parent);
606         return 0;
607 mknod_error:
608         err = errno;
609         free_lookup_table_entry(lte);
610         return -err;
611 }
612
613 /* Open a file.  */
614 static int wimfs_open(const char *path, struct fuse_file_info *fi)
615 {
616         struct dentry *dentry;
617         struct lookup_table_entry *lte;
618         
619         dentry = get_dentry(w, path);
620
621         if (!dentry)
622                 return -EEXIST;
623         if (dentry_is_directory(dentry))
624                 return -EISDIR;
625         lte = wim_lookup_resource(w, dentry);
626
627         if (lte) {
628                 /* If this file is in the staging directory and the file is not
629                  * currently open, open it. */
630                 if (lte->staging_file_name && lte->staging_num_times_opened == 0) {
631                         lte->staging_fd = open(lte->staging_file_name, O_RDWR);
632                         if (lte->staging_fd == -1)
633                                 return -errno;
634                         lte->staging_offset = 0;
635                 }
636         } else {
637                 /* no lookup table entry, so the file must be empty.  Create a
638                  * lookup table entry for the file, unless it's a read-only
639                  * filesystem.  */
640                 char *tmpfile_name;
641                 int fd;
642
643                 if (!staging_dir_name) /* Read-only filesystem */
644                         return 0;
645
646                 lte = new_lookup_table_entry();
647                 if (!lte)
648                         return -ENOMEM;
649
650                 fd = create_staging_file(&tmpfile_name);
651
652                 if (fd == -1) {
653                         int err = errno;
654                         free(lte);
655                         return -err;
656                 }
657                 lte->resource_entry.original_size = 0;
658                 randomize_byte_array(lte->hash, WIM_HASH_SIZE);
659                 memcpy(dentry->hash, lte->hash, WIM_HASH_SIZE);
660                 lte->staging_file_name = tmpfile_name;
661                 lte->staging_fd = fd;
662                 lte->staging_offset = 0;
663                 lookup_table_insert(w->lookup_table, lte);
664         }
665         lte->staging_num_times_opened++;
666         return 0;
667 }
668
669 /* Opens a directory. */
670 static int wimfs_opendir(const char *path, struct fuse_file_info *fi)
671 {
672         struct dentry *dentry;
673         
674         dentry = get_dentry(w, path);
675         if (!dentry || !dentry_is_directory(dentry))
676                 return -ENOTDIR;
677         return 0;
678 }
679
680
681 /*
682  * Read data from a file in the WIM or in the staging directory. 
683  */
684 static int wimfs_read(const char *path, char *buf, size_t size, 
685                 off_t offset, struct fuse_file_info *fi)
686 {
687         struct dentry *dentry;
688         struct lookup_table_entry *lte;
689         
690         dentry = get_dentry(w, path);
691
692         if (!dentry)
693                 return -EEXIST;
694
695         if (!dentry_is_regular_file(dentry))
696                 return -EISDIR;
697
698         lte = wim_lookup_resource(w, dentry);
699
700         if (!lte)
701                 return 0;
702
703         if (lte->staging_file_name) {
704
705                 /* Read from staging */
706                 int fd;
707                 off_t cur_offset;
708                 ssize_t ret;
709
710                 if (lte->staging_num_times_opened == 0)
711                         return -EBADF;
712
713                 fd = lte->staging_fd;
714                 cur_offset = lte->staging_offset;
715                 if (cur_offset != offset)
716                         if (lseek(fd, offset, SEEK_SET) == -1)
717                                 return -errno;
718                 lte->staging_offset = offset;
719
720                 ret = read(fd, buf, size);
721                 if (ret == -1)
722                         return -errno;
723                 lte->staging_offset = offset + ret;
724
725                 return ret;
726         } else {
727
728                 /* Read from WIM */
729
730                 struct resource_entry *res_entry;
731                 int ctype;
732                 
733                 res_entry = &lte->resource_entry;
734
735                 ctype = wim_resource_compression_type(w, res_entry);
736
737                 if (offset > res_entry->original_size)
738                         return -EOVERFLOW;
739
740                 size = min(size, res_entry->original_size - offset);
741
742                 if (read_resource(w->fp, res_entry->size, 
743                                   res_entry->original_size,
744                                   res_entry->offset, ctype, size, 
745                                   offset, buf) != 0)
746                         return -EIO;
747                 return size;
748         }
749 }
750
751 /* Fills in the entries of the directory specified by @path using the
752  * FUSE-provided function @filler.  */
753 static int wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, 
754                                 off_t offset, struct fuse_file_info *fi)
755 {
756         struct dentry *parent;
757         struct dentry *child;
758         struct stat st;
759
760         parent = get_dentry(w, path);
761
762         if (!parent)
763                 return -EEXIST;
764
765         if (!dentry_is_directory(parent))
766                 return -ENOTDIR;
767
768         filler(buf, ".", NULL, 0);
769         filler(buf, "..", NULL, 0);
770
771         child = parent->children;
772
773         if (!child)
774                 return 0;
775
776         do {
777                 memset(&st, 0, sizeof(st));
778                 if (filler(buf, child->file_name_utf8, &st, 0))
779                         return 0;
780                 child = child->next;
781         } while (child != parent->children);
782         return 0;
783 }
784
785 /* Close a file. */
786 static int wimfs_release(const char *path, struct fuse_file_info *fi)
787 {
788         struct dentry *dentry;
789         struct lookup_table_entry *lte;
790         int ret;
791         
792         dentry = get_dentry(w, path);
793         if (!dentry)
794                 return -EEXIST;
795         lte = wim_lookup_resource(w, dentry);
796
797         if (!lte)
798                 return 0;
799         
800         if (lte->staging_num_times_opened == 0)
801                 return -EBADF;
802
803         if (--lte->staging_num_times_opened == 0 && lte->staging_file_name) {
804                 ret = close(lte->staging_fd);
805                 if (ret != 0)
806                         return -errno;
807         }
808         return 0;
809 }
810
811 /* Renames a file or directory.  See rename (3) */
812 static int wimfs_rename(const char *from, const char *to)
813 {
814         struct dentry *src;
815         struct dentry *dst;
816         struct dentry *parent_of_dst;
817         
818         src = get_dentry(w, from);
819         if (!src)
820                 return -ENOENT;
821
822         dst = get_dentry(w, to);
823
824         if (dst) {
825                 if (!dentry_is_directory(src)) {
826                         /* Cannot rename non-directory to directory. */
827                         if (dentry_is_directory(dst))
828                                 return -EISDIR;
829                 } else {
830                         /* Cannot rename directory to a non-directory or a non-empty
831                          * directory */
832                         if (!dentry_is_directory(dst))
833                                 return -ENOTDIR;
834                         if (dst->children != NULL)
835                                 return -ENOTEMPTY;
836                 }
837                 parent_of_dst = dst->parent;
838                 unlink_dentry(dst);
839                 lookup_table_decrement_refcnt(w->lookup_table, dst->hash);
840                 free_dentry(dst);
841         } else {
842                 parent_of_dst = get_parent_dentry(w, to);
843                 if (!parent_of_dst)
844                         return -ENOENT;
845         }
846
847         unlink_dentry(src);
848         change_dentry_name(src, path_basename(to));
849         link_dentry(src, parent_of_dst);
850         /*calculate_dentry_full_path(src);*/
851         return 0;
852 }
853
854 /* Remove a directory */
855 static int wimfs_rmdir(const char *path)
856 {
857         struct dentry *dentry;
858         
859         dentry = get_dentry(w, path);
860         if (!dentry)
861                 return -EEXIST;
862
863         if (!dentry_is_empty_directory(dentry))
864                 return -EEXIST;
865
866         unlink_dentry(dentry);
867         free_dentry(dentry);
868         return 0;
869 }
870
871 /* Extracts the resource corresponding to @dentry and its lookup table entry
872  * @lte to a file in the staging directory.  The lookup table entry for @dentry
873  * is updated to point to the new file.  If @lte has multiple dentries
874  * referencing it, a new lookup table entry is created and the hash of @dentry
875  * is changed to point to the new lookup table entry.
876  *
877  * Only @size bytes are extracted, to support truncating the file. 
878  *
879  * Returns the negative error code on failure.
880  */
881 static int extract_resource_to_staging_dir(struct dentry *dentry, 
882                                            struct lookup_table_entry *lte, 
883                                            u64 size)
884 {
885         int fd;
886         bool ret;
887         char *staging_file_name;
888         struct lookup_table_entry *new_lte;
889
890         /* File in WIM.  Copy it to the staging directory. */
891         fd = create_staging_file(&staging_file_name);
892         if (fd == -1)
893                 return -errno;
894
895         ret = extract_resource_to_fd(w, &lte->resource_entry, fd, size);
896         if (ret != 0) {
897                 if (errno != 0)
898                         ret = -errno;
899                 else
900                         ret = -EIO;
901                 unlink(staging_file_name);
902                 FREE(staging_file_name);
903                 return ret;
904         }
905
906         if (lte->refcnt != 1) {
907                 /* Need to make a new lookup table entry if we are
908                  * changing only one copy of a hardlinked entry */
909                 lte->refcnt--;
910
911                 new_lte = new_lookup_table_entry();
912                 if (!new_lte)
913                         return -ENOMEM;
914                 randomize_byte_array(dentry->hash, WIM_HASH_SIZE);
915                 memcpy(new_lte->hash, dentry->hash, WIM_HASH_SIZE);
916
917                 new_lte->resource_entry.flags = 0;
918                 new_lte->staging_num_times_opened = lte->staging_num_times_opened;
919
920                 lookup_table_insert(w->lookup_table, new_lte);
921
922                 lte = new_lte;
923         } 
924
925         lte->resource_entry.original_size = size;
926         lte->staging_file_name = staging_file_name;
927         
928         if (lte->staging_num_times_opened == 0)
929                 close(fd);
930         else
931                 lte->staging_fd = fd;
932         return 0;
933 }
934
935 /* Reduce the size of a file */
936 static int wimfs_truncate(const char *path, off_t size)
937 {
938         struct dentry *dentry;
939         struct lookup_table_entry *lte;
940         int ret;
941
942         dentry = get_dentry(w, path);
943         if (!dentry)
944                 return -EEXIST;
945         lte = wim_lookup_resource(w, dentry);
946
947         if (!lte) /* Already a zero-length file */
948                 return 0;
949         if (lte->staging_file_name) {
950                 /* File on disk.  Call POSIX API */
951                 if (lte->staging_num_times_opened != 0)
952                         ret = ftruncate(lte->staging_fd, size);
953                 else
954                         ret = truncate(lte->staging_file_name, size);
955                 if (ret != 0)
956                         return -errno;
957                 dentry_update_all_timestamps(dentry);
958                 lte->resource_entry.original_size = size;
959                 return 0;
960         } else {
961                 /* File in WIM.  Extract it to the staging directory, but only
962                  * the first @size bytes of it. */
963                 return extract_resource_to_staging_dir(dentry, lte, size);
964         }
965 }
966
967 /* Remove a regular file */
968 static int wimfs_unlink(const char *path)
969 {
970         struct dentry *dentry;
971         struct lookup_table_entry *lte;
972         
973         dentry = get_dentry(w, path);
974         if (!dentry)
975                 return -EEXIST;
976
977         if (!dentry_is_regular_file(dentry))
978                 return -EEXIST;
979
980         lte = wim_lookup_resource(w, dentry);
981         if (lte) {
982                 if (lte->staging_file_name)
983                         if (unlink(lte->staging_file_name) != 0)
984                                 return -errno;
985                 lookup_table_decrement_refcnt(w->lookup_table, dentry->hash);
986         }
987
988         unlink_dentry(dentry);
989         free_dentry(dentry);
990         return 0;
991 }
992
993 static int wimfs_utimens(const char *path, const struct timespec tv[2])
994 {
995         struct dentry *dentry = get_dentry(w, path);
996         if (!dentry)
997                 return -ENOENT;
998         time_t last_access_t = (tv[0].tv_nsec == UTIME_NOW) ? 
999                                 time(NULL) : tv[0].tv_sec;
1000         dentry->last_access_time = unix_timestamp_to_ms(last_access_t);
1001         time_t last_mod_t = (tv[1].tv_nsec == UTIME_NOW) ?  
1002                                 time(NULL) : tv[1].tv_sec;
1003         dentry->last_write_time = unix_timestamp_to_ms(last_mod_t);
1004         return 0;
1005 }
1006
1007 /* Writes to a file in the WIM filesystem. */
1008 static int wimfs_write(const char *path, const char *buf, size_t size, 
1009                                 off_t offset, struct fuse_file_info *fi)
1010 {
1011         struct dentry *dentry;
1012         struct lookup_table_entry *lte;
1013         ssize_t ret;
1014
1015         dentry = get_dentry(w, path);
1016         if (!dentry)
1017                 return -EEXIST;
1018         lte = wim_lookup_resource(w, dentry);
1019
1020         if (!lte) /* this should not happen */
1021                 return -EEXIST;
1022
1023         if (lte->staging_num_times_opened == 0)
1024                 return -EBADF;
1025         if (lte->staging_file_name) {
1026
1027                 /* File in staging directory. We can write to it directly. */
1028
1029                 /* Seek to correct position in file if needed. */
1030                 if (lte->staging_offset != offset) {
1031                         if (lseek(lte->staging_fd, offset, SEEK_SET) == -1)
1032                                 return -errno;
1033                         lte->staging_offset = offset;
1034                 }
1035
1036                 /* Write the data. */
1037                 ret = write(lte->staging_fd, buf, size);
1038                 if (ret == -1)
1039                         return -errno;
1040
1041                 /* Adjust the stored offset of staging_fd. */
1042                 lte->staging_offset = offset + ret;
1043
1044                 /* Increase file size if needed. */
1045                 if (lte->resource_entry.original_size < lte->staging_offset)
1046                         lte->resource_entry.original_size = lte->staging_offset;
1047
1048                 /* The file has been modified, so all its timestamps must be
1049                  * updated. */
1050                 dentry_update_all_timestamps(dentry);
1051                 return ret;
1052         } else {
1053                 /* File in the WIM.  We must extract it to the staging directory
1054                  * before it can be written to. */
1055                 ret = extract_resource_to_staging_dir(dentry, lte, 
1056                                         lte->resource_entry.original_size);
1057                 if (ret != 0)
1058                         return ret;
1059                 else
1060                         return wimfs_write(path, buf, size, offset, fi);
1061         }
1062 }
1063
1064
1065 static struct fuse_operations wimfs_oper = {
1066         .access   = wimfs_access,
1067         .destroy  = wimfs_destroy,
1068         .getattr  = wimfs_getattr,
1069         .mkdir    = wimfs_mkdir,
1070         .mknod    = wimfs_mknod,
1071         .open     = wimfs_open,
1072         .opendir  = wimfs_opendir,
1073         .read     = wimfs_read,
1074         .readdir  = wimfs_readdir,
1075         .release  = wimfs_release,
1076         .rename   = wimfs_rename,
1077         .rmdir    = wimfs_rmdir,
1078         .truncate = wimfs_truncate,
1079         .unlink   = wimfs_unlink,
1080         .utimens  = wimfs_utimens,
1081         .write    = wimfs_write,
1082 };
1083
1084
1085 /* Mounts a WIM file. */
1086 WIMLIBAPI int wimlib_mount(WIMStruct *wim, int image, const char *dir, 
1087                            int flags)
1088 {
1089         int argc = 0;
1090         char *argv[6];
1091         int ret;
1092         char *p;
1093
1094         DEBUG("Mount: wim = %p, image = %d, dir = %s, flags = %d, ",
1095                         wim, image, dir, flags);
1096
1097         if (!dir)
1098                 return WIMLIB_ERR_INVALID_PARAM;
1099
1100         ret = wimlib_select_image(wim, image);
1101
1102         if (ret != 0)
1103                 return ret;
1104
1105         if (flags & WIMLIB_MOUNT_FLAG_READWRITE)
1106                 wim_get_current_image_metadata(wim)->modified = true;
1107
1108         mount_dir = dir;
1109         working_directory = getcwd(NULL, 0);
1110         if (!working_directory) {
1111                 ERROR_WITH_ERRNO("Could not determine current directory");
1112                 return WIMLIB_ERR_NOTDIR;
1113         }
1114
1115         p = STRDUP(dir);
1116         if (!p)
1117                 return WIMLIB_ERR_NOMEM;
1118
1119         argv[argc++] = "mount";
1120         argv[argc++] = p;
1121         argv[argc++] = "-s"; /* disable multi-threaded operation */
1122
1123         if (flags & WIMLIB_MOUNT_FLAG_DEBUG) {
1124                 argv[argc++] = "-d";
1125         }
1126         if (!(flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
1127                 argv[argc++] = "-o";
1128                 argv[argc++] = "ro";
1129         } else {
1130                 make_staging_dir();
1131                 if (!staging_dir_name) {
1132                         FREE(p);
1133                         return WIMLIB_ERR_MKDIR;
1134                 }
1135         }
1136
1137 #ifdef ENABLE_DEBUG
1138         {
1139                 int i;
1140                 DEBUG("FUSE command line (argc = %d): ", argc);
1141                 for (i = 0; i < argc; i++) {
1142                         fputs(argv[i], stdout);
1143                         putchar(' ');
1144                 }
1145                 putchar('\n');
1146                 fflush(stdout);
1147         }
1148 #endif
1149
1150         /* Set static variables. */
1151         w = wim;
1152         mount_flags = flags;
1153
1154         ret = fuse_main(argc, argv, &wimfs_oper, NULL);
1155
1156         return (ret == 0) ? 0 : WIMLIB_ERR_FUSE;
1157 }
1158
1159
1160 /* 
1161  * Unmounts the WIM file that was previously mounted on @dir by using
1162  * wimlib_mount().
1163  */
1164 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
1165 {
1166         pid_t pid;
1167         int status;
1168         int ret;
1169         char msg[2];
1170         struct timeval now;
1171         struct timespec timeout;
1172         int msgsize;
1173         int errno_save;
1174
1175         /* Execute `fusermount -u', which is installed setuid root, to unmount
1176          * the WIM.
1177          *
1178          * FUSE does not yet implement synchronous unmounts.  This means that
1179          * fusermount -u will return before the filesystem daemon returns from
1180          * wimfs_destroy().  This is partly what we want, because we need to
1181          * send a message from this process to the filesystem daemon telling
1182          * whether --commit was specified or not.  However, after that, the
1183          * unmount process must wait for the filesystem daemon to finish writing
1184          * the WIM file. 
1185          */
1186
1187         mount_dir = dir;
1188         pid = fork();
1189         if (pid == -1) {
1190                 ERROR_WITH_ERRNO("Failed to fork()");
1191                 return WIMLIB_ERR_FORK;
1192         }
1193         if (pid == 0) {
1194                 execlp("fusermount", "fusermount", "-u", dir, NULL);
1195                 ERROR_WITH_ERRNO("Failed to execute `fusermount'");
1196                 return WIMLIB_ERR_FUSERMOUNT;
1197         }
1198
1199         ret = waitpid(pid, &status, 0);
1200         if (ret == -1) {
1201                 ERROR_WITH_ERRNO("Failed to wait for fusermount process to "
1202                                  "terminate");
1203                 return WIMLIB_ERR_FUSERMOUNT;
1204         }
1205
1206         if (status != 0) {
1207                 ERROR("fusermount exited with status %d", status);
1208                 return WIMLIB_ERR_FUSERMOUNT;
1209         }
1210
1211         /* Open message queues between the unmount process and the
1212          * filesystem daemon. */
1213         ret = open_message_queues(false);
1214         if (ret != 0)
1215                 return ret;
1216
1217         /* Send a message to the filesystem saying whether to commit or
1218          * not. */
1219         msg[0] = (flags & WIMLIB_UNMOUNT_FLAG_COMMIT) ? 1 : 0;
1220         msg[1] = (flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY) ? 1 : 0;
1221
1222         DEBUG("Sending message: %s, %s", 
1223                         (msg[0] == 0) ? "don't commit" : "commit",
1224                         (msg[1] == 0) ? "don't check"  : "check");
1225         ret = mq_send(unmount_to_daemon_mq, msg, 2, 1);
1226         if (ret == -1) {
1227                 ERROR("Failed to notify filesystem daemon whether we want to "
1228                       "commit changes or not");
1229                 close_message_queues();
1230                 return WIMLIB_ERR_MQUEUE;
1231         }
1232
1233         /* Wait for a message from the filesytem daemon indicating whether  the
1234          * filesystem was unmounted successfully (0) or an error occurred (1).
1235          * This may take a long time if a big WIM file needs to be rewritten. */
1236
1237         /* Wait at most 600??? seconds before giving up and returning false.
1238          * Either it's a really big WIM file, or (more likely) the
1239          * filesystem daemon has crashed or failed for some reason.
1240          *
1241          * XXX come up with some method to determine if the filesystem
1242          * daemon has really crashed or not. */
1243
1244         gettimeofday(&now, NULL);
1245         timeout.tv_sec = now.tv_sec + 600;
1246         timeout.tv_nsec = now.tv_usec * 1000;
1247
1248         msgsize = mq_get_msgsize(daemon_to_unmount_mq);
1249         char mailbox[msgsize];
1250
1251         mailbox[0] = 0;
1252         DEBUG("Waiting for message telling us whether the unmount was "
1253                         "successful or not.");
1254         ret = mq_timedreceive(daemon_to_unmount_mq, mailbox, msgsize,
1255                               NULL, &timeout);
1256         errno_save = errno;
1257         close_message_queues();
1258         if (ret == -1) {
1259                 if (errno_save == ETIMEDOUT) {
1260                         ERROR("Timed out- probably the filesystem daemon "
1261                               "crashed and the WIM was not written "
1262                               "successfully.");
1263                         return WIMLIB_ERR_TIMEOUT;
1264                 } else {
1265                         ERROR("mq_receive(): %s", strerror(errno_save));
1266                         return WIMLIB_ERR_MQUEUE;
1267                 }
1268
1269         }
1270         DEBUG("Received message: %s",
1271               (mailbox[0] == 0) ?  "Unmount OK" : "Unmount Failed");
1272         if (mailbox[0] != 0)
1273                 ERROR("Unmount failed");
1274         return mailbox[0];
1275 }
1276
1277 #else /* WITH_FUSE */
1278
1279
1280 static inline int mount_unsupported_error()
1281 {
1282         ERROR("WIMLIB was compiled with --without-fuse, which disables support "
1283               "for mounting WIMs.");
1284         return WIMLIB_ERR_UNSUPPORTED;
1285 }
1286
1287 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
1288 {
1289         return mount_unsupported_error();
1290 }
1291
1292 WIMLIBAPI int wimlib_mount(WIMStruct *wim_p, int image, const char *dir, 
1293                            int flags)
1294 {
1295         return mount_unsupported_error();
1296 }
1297
1298 #endif /* WITH_FUSE */