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