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