]> wimlib.net Git - wimlib/blob - src/mount.c
Allow writing to empty files in mounted WIM
[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         ret = delete_staging_dir();
378         if (ret != 0)
379                 ERROR("Failed to delete the staging directory: %m\n");
380         return ret;
381 }
382
383 /* Called when the filesystem is unmounted. */
384 static void wimfs_destroy(void *p)
385 {
386
387         /* For read-write mounts, the `imagex unmount' command, which is
388          * running in a separate process and is executing the
389          * wimlib_unmount() function, will send this process a byte
390          * through a message queue that indicates whether the --commit
391          * option was specified or not. */
392
393         int msgsize;
394         struct timespec timeout;
395         struct timeval now;
396         ssize_t bytes_received;
397         int ret;
398         char commit;
399         char check_integrity;
400         char status;
401
402         ret = open_message_queues(true);
403         if (ret != 0)
404                 exit(1);
405
406         msgsize = mq_get_msgsize(unmount_to_daemon_mq);
407         char msg[msgsize];
408         msg[0] = 0;
409         msg[1] = 0;
410
411         /* Wait at most 3 seconds before giving up and discarding changes. */
412         gettimeofday(&now, NULL);
413         timeout.tv_sec = now.tv_sec + 3;
414         timeout.tv_nsec = now.tv_usec * 1000;
415         DEBUG("Waiting for message telling us whether to commit or not, "
416                         "and whether to include integrity checks.\n");
417
418         bytes_received = mq_timedreceive(unmount_to_daemon_mq, msg, 
419                                          msgsize, NULL, &timeout);
420         commit = msg[0];
421         check_integrity = msg[1];
422         if (bytes_received == -1) {
423                 if (errno == ETIMEDOUT) {
424                         ERROR("Timed out.\n");
425                 } else {
426                         ERROR("mq_timedreceive(): %m\n");
427                 }
428                 ERROR("Not committing.\n");
429         } else {
430                 DEBUG("Received message: [%d %d]\n", msg[0], msg[1]);
431         }
432
433         if (commit && (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
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         } else {
442                 status = 0;
443         }
444 done:
445         ret = mq_send(daemon_to_unmount_mq, &status, 1, 1);
446         if (ret == -1) {
447                 ERROR("Failed to send status to unmount process: %m\n");
448         }
449         close_message_queues();
450 }
451
452 /*
453  * Fills in a `struct stat' that corresponds to a file or directory in the WIM.
454  */
455 static int wimfs_getattr(const char *path, struct stat *stbuf)
456 {
457         struct dentry *dentry = get_dentry(w, path);
458         if (!dentry)
459                 return -ENOENT;
460         dentry_to_stbuf(dentry, stbuf, w->lookup_table);
461         return 0;
462 }
463
464 /* 
465  * Create a directory in the WIM.  
466  * @mode is currently ignored.
467  */
468 static int wimfs_mkdir(const char *path, mode_t mode)
469 {
470         struct dentry *parent;
471         struct dentry *newdir;
472         const char *basename;
473         
474         parent = get_parent_dentry(w, path);
475         if (!parent)
476                 return -ENOENT;
477
478         if (!dentry_is_directory(parent))
479                 return -ENOTDIR;
480
481         basename = path_basename(path);
482         if (get_dentry_child_with_name(parent, basename))
483                 return -EEXIST;
484
485         newdir = new_dentry(basename);
486         newdir->attributes |= WIM_FILE_ATTRIBUTE_DIRECTORY;
487         link_dentry(newdir, parent);
488         return 0;
489 }
490
491 /* Creates a new staging file and returns its file descriptor opened for
492  * writing.
493  *
494  * @name_ret: A location into which the a pointer to the newly allocated name of
495  *                      the staging file is stored.
496  * @return:  The file descriptor for the new file.  Returns -1 and sets errno on
497  *              error, for any reason possible from the creat() function.
498  */
499 static int create_staging_file(char **name_ret)
500 {
501         size_t name_len;
502         char *name;
503         struct stat stbuf;
504         int fd;
505         int errno_save;
506
507         name_len = staging_dir_name_len + 1 + WIM_HASH_SIZE;
508         name = MALLOC(name_len + 1);
509         if (!name) {
510                 errno = ENOMEM;
511                 return -1;
512         }
513
514         memcpy(name, staging_dir_name, staging_dir_name_len);
515         name[staging_dir_name_len] = '/';
516         randomize_char_array_with_alnum(name + staging_dir_name_len + 1,
517                                         WIM_HASH_SIZE);
518         name[name_len] = '\0';
519
520
521         /* Just in case, verify that the randomly generated name doesn't name an
522          * existing file, and try again if so  */
523         if (stat(name, &stbuf) == 0) {
524                 /* stat succeeded-- the file must exist. Try another name. */
525                 FREE(name);
526                 return create_staging_file(name_ret);
527         } else {
528                 if (errno != ENOENT)
529                         /* other error! */
530                         return -1;
531                 /* doesn't exist--- ok */
532         }
533
534         DEBUG("Creating staging file '%s'\n", name);
535
536         fd = creat(name, 0600); 
537         if (fd == -1) {
538                 errno_save = errno;
539                 FREE(name);
540                 errno = errno_save;
541         } else {
542                 *name_ret = name;
543         }
544         return fd;
545 }
546
547 /* Creates a regular file.  This is done in the staging directory.  */
548 static int wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
549 {
550         struct dentry *parent, *dentry;
551         const char *basename;
552         struct lookup_table_entry *lte;
553         char *tmpfile_name;
554         int fd;
555         int err;
556
557         /* Make sure that the parent of @path exists and is a directory, and
558          * that the dentry named by @path does not already exist.  */
559         parent = get_parent_dentry(w, path);
560         if (!parent)
561                 return -ENOENT;
562         if (!dentry_is_directory(parent))
563                 return -ENOTDIR;
564         basename = path_basename(path);
565         if (get_dentry_child_with_name(parent, path))
566                 return -EEXIST;
567
568         dentry = new_dentry(basename);
569
570         /* XXX fill in a temporary random hash value- really should check for
571          * duplicates */
572         randomize_byte_array(dentry->hash, WIM_HASH_SIZE);
573
574         /* Create a lookup table entry having the same hash value */
575         lte = new_lookup_table_entry();
576         lte->staging_num_times_opened = 0;
577         lte->resource_entry.original_size = 0;
578         memcpy(lte->hash, dentry->hash, WIM_HASH_SIZE);
579
580         fd = create_staging_file(&tmpfile_name);
581
582         if (fd == -1)
583                 goto mknod_error;
584
585         if (close(fd) != 0)
586                 goto mknod_error;
587
588         lte->staging_file_name = tmpfile_name;
589
590         /* Insert the lookup table entry, and link the new dentry with its
591          * parent. */
592         lookup_table_insert(w->lookup_table, lte);
593         link_dentry(dentry, parent);
594         return 0;
595 mknod_error:
596         err = errno;
597         free_lookup_table_entry(lte);
598         return -err;
599 }
600
601 /* Open a file.  */
602 static int wimfs_open(const char *path, struct fuse_file_info *fi)
603 {
604         struct dentry *dentry;
605         struct lookup_table_entry *lte;
606         
607         dentry = get_dentry(w, path);
608
609         if (!dentry)
610                 return -EEXIST;
611         if (dentry_is_directory(dentry))
612                 return -EISDIR;
613         lte = wim_lookup_resource(w, dentry);
614
615         if (lte) {
616                 /* If this file is in the staging directory and the file is not
617                  * currently open, open it. */
618                 if (lte->staging_file_name && lte->staging_num_times_opened == 0) {
619                         lte->staging_fd = open(lte->staging_file_name, O_RDWR);
620                         if (lte->staging_fd == -1)
621                                 return -errno;
622                         lte->staging_offset = 0;
623                 }
624         } else {
625                 /* no lookup table entry, so the file must be empty.  Create a
626                  * lookup table entry for the file. */
627                 char *tmpfile_name;
628                 int err;
629                 int fd;
630
631                 lte = new_lookup_table_entry();
632                 if (!lte)
633                         return -ENOMEM;
634
635                 fd = create_staging_file(&tmpfile_name);
636
637                 if (fd == -1) {
638                         err = errno;
639                         free(lte);
640                         return -errno;
641                 }
642                 lte->resource_entry.original_size = 0;
643                 randomize_byte_array(lte->hash, WIM_HASH_SIZE);
644                 memcpy(dentry->hash, lte->hash, WIM_HASH_SIZE);
645                 lte->staging_file_name = tmpfile_name;
646                 lte->staging_fd = fd;
647                 lte->staging_offset = 0;
648                 lookup_table_insert(w->lookup_table, lte);
649         }
650         lte->staging_num_times_opened++;
651         return 0;
652 }
653
654 /* Opens a directory. */
655 static int wimfs_opendir(const char *path, struct fuse_file_info *fi)
656 {
657         struct dentry *dentry;
658         
659         dentry = get_dentry(w, path);
660         if (!dentry || !dentry_is_directory(dentry))
661                 return -ENOTDIR;
662         return 0;
663 }
664
665
666 /*
667  * Read data from a file in the WIM or in the staging directory. 
668  */
669 static int wimfs_read(const char *path, char *buf, size_t size, 
670                 off_t offset, struct fuse_file_info *fi)
671 {
672         struct dentry *dentry;
673         struct lookup_table_entry *lte;
674         
675         dentry = get_dentry(w, path);
676
677         if (!dentry)
678                 return -EEXIST;
679
680         if (!dentry_is_regular_file(dentry))
681                 return -EISDIR;
682
683         lte = wim_lookup_resource(w, dentry);
684
685         if (!lte)
686                 return 0;
687
688         if (lte->staging_file_name) {
689
690                 /* Read from staging */
691                 int fd;
692                 off_t cur_offset;
693                 ssize_t ret;
694
695                 if (lte->staging_num_times_opened == 0)
696                         return -EBADF;
697
698                 fd = lte->staging_fd;
699                 cur_offset = lte->staging_offset;
700                 if (cur_offset != offset)
701                         if (lseek(fd, offset, SEEK_SET) == -1)
702                                 return -errno;
703                 lte->staging_offset = offset;
704
705                 ret = read(fd, buf, size);
706                 if (ret == -1)
707                         return -errno;
708                 lte->staging_offset = offset + ret;
709
710                 return ret;
711         } else {
712
713                 /* Read from WIM */
714
715                 struct resource_entry *res_entry;
716                 int ctype;
717                 
718                 res_entry = &lte->resource_entry;
719
720                 ctype = wim_resource_compression_type(w, res_entry);
721
722                 if (offset > res_entry->original_size)
723                         return -EOVERFLOW;
724
725                 size = min(size, res_entry->original_size - offset);
726
727                 if (read_resource(w->fp, res_entry->size, 
728                                   res_entry->original_size,
729                                   res_entry->offset, ctype, size, 
730                                   offset, buf) != 0)
731                         return -EIO;
732                 return size;
733         }
734 }
735
736 /* Fills in the entries of the directory specified by @path using the
737  * FUSE-provided function @filler.  */
738 static int wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, 
739                                 off_t offset, struct fuse_file_info *fi)
740 {
741         struct dentry *parent;
742         struct dentry *child;
743         struct stat st;
744
745         parent = get_dentry(w, path);
746
747         if (!parent)
748                 return -EEXIST;
749
750         if (!dentry_is_directory(parent))
751                 return -ENOTDIR;
752
753         filler(buf, ".", NULL, 0);
754         filler(buf, "..", NULL, 0);
755
756         child = parent->children;
757
758         if (!child)
759                 return 0;
760
761         do {
762                 memset(&st, 0, sizeof(st));
763                 if (filler(buf, child->file_name_utf8, &st, 0))
764                         return 0;
765                 child = child->next;
766         } while (child != parent->children);
767         return 0;
768 }
769
770 /* Close a file. */
771 static int wimfs_release(const char *path, struct fuse_file_info *fi)
772 {
773         struct dentry *dentry;
774         struct lookup_table_entry *lte;
775         int ret;
776         
777         dentry = get_dentry(w, path);
778         if (!dentry)
779                 return -EEXIST;
780         lte = wim_lookup_resource(w, dentry);
781
782         if (!lte)
783                 return 0;
784         
785         if (lte->staging_num_times_opened == 0)
786                 return -EBADF;
787
788         if (--lte->staging_num_times_opened == 0 && lte->staging_file_name) {
789                 ret = close(lte->staging_fd);
790                 if (ret != 0)
791                         return -errno;
792         }
793         return 0;
794 }
795
796 /* Renames a file or directory.  See rename (3) */
797 static int wimfs_rename(const char *from, const char *to)
798 {
799         struct dentry *src;
800         struct dentry *dst;
801         struct dentry *parent_of_dst;
802         
803         src = get_dentry(w, from);
804         if (!src)
805                 return -ENOENT;
806
807         dst = get_dentry(w, to);
808
809         if (dst) {
810                 if (!dentry_is_directory(src)) {
811                         /* Cannot rename non-directory to directory. */
812                         if (dentry_is_directory(dst))
813                                 return -EISDIR;
814                 } else {
815                         /* Cannot rename directory to a non-directory or a non-empty
816                          * directory */
817                         if (!dentry_is_directory(dst))
818                                 return -ENOTDIR;
819                         if (dst->children != NULL)
820                                 return -ENOTEMPTY;
821                 }
822                 parent_of_dst = dst->parent;
823                 unlink_dentry(dst);
824                 lookup_table_decrement_refcnt(w->lookup_table, dst->hash);
825                 free_dentry(dst);
826         } else {
827                 parent_of_dst = get_parent_dentry(w, to);
828                 if (!parent_of_dst)
829                         return -ENOENT;
830         }
831
832         unlink_dentry(src);
833         change_dentry_name(src, path_basename(to));
834         link_dentry(src, parent_of_dst);
835         /*calculate_dentry_full_path(src);*/
836         return 0;
837 }
838
839 /* Remove a directory */
840 static int wimfs_rmdir(const char *path)
841 {
842         struct dentry *dentry;
843         
844         dentry = get_dentry(w, path);
845         if (!dentry)
846                 return -EEXIST;
847
848         if (!dentry_is_empty_directory(dentry))
849                 return -EEXIST;
850
851         unlink_dentry(dentry);
852         free_dentry(dentry);
853         return 0;
854 }
855
856 /* Extracts the resource corresponding to @dentry and its lookup table entry
857  * @lte to a file in the staging directory.  The lookup table entry for @dentry
858  * is updated to point to the new file.  If @lte has multiple dentries
859  * referencing it, a new lookup table entry is created and the hash of @dentry
860  * is changed to point to the new lookup table entry.
861  *
862  * Only @size bytes are extracted, to support truncating the file. 
863  *
864  * Returns the negative error code on failure.
865  */
866 static int extract_resource_to_staging_dir(struct dentry *dentry, 
867                                            struct lookup_table_entry *lte, 
868                                            u64 size)
869 {
870         int err, fd;
871         bool ret;
872         char *staging_file_name;
873         struct lookup_table_entry *new_lte;
874
875         /* File in WIM.  Copy it to the staging directory. */
876         fd = create_staging_file(&staging_file_name);
877         if (fd == -1)
878                 return -errno;
879
880         ret = extract_resource_to_fd(w, &lte->resource_entry, fd, size);
881         if (ret != 0) {
882                 if (errno != 0)
883                         ret = -errno;
884                 else
885                         ret = -EIO;
886                 unlink(staging_file_name);
887                 FREE(staging_file_name);
888                 return ret;
889         }
890
891         if (lte->refcnt != 1) {
892                 /* Need to make a new lookup table entry if we are
893                  * changing only one copy of a hardlinked entry */
894                 lte->refcnt--;
895
896                 new_lte = new_lookup_table_entry();
897                 if (!new_lte)
898                         return -ENOMEM;
899                 randomize_byte_array(dentry->hash, WIM_HASH_SIZE);
900                 memcpy(new_lte->hash, dentry->hash, WIM_HASH_SIZE);
901
902                 new_lte->resource_entry.flags = 0;
903                 new_lte->staging_num_times_opened = lte->staging_num_times_opened;
904
905                 lookup_table_insert(w->lookup_table, new_lte);
906
907                 lte = new_lte;
908         } 
909
910         lte->resource_entry.original_size = size;
911         lte->staging_file_name = staging_file_name;
912         
913         if (lte->staging_num_times_opened == 0)
914                 close(fd);
915         else
916                 lte->staging_fd = fd;
917         return 0;
918 }
919
920 /* Reduce the size of a file */
921 static int wimfs_truncate(const char *path, off_t size)
922 {
923         struct dentry *dentry;
924         struct lookup_table_entry *lte;
925         int ret;
926
927         dentry = get_dentry(w, path);
928         if (!dentry)
929                 return -EEXIST;
930         lte = wim_lookup_resource(w, dentry);
931
932         if (!lte) /* Already a zero-length file */
933                 return 0;
934         if (lte->staging_file_name) {
935                 /* File on disk.  Call POSIX API */
936                 if (lte->staging_num_times_opened != 0)
937                         ret = ftruncate(lte->staging_fd, size);
938                 else
939                         ret = truncate(lte->staging_file_name, size);
940                 if (ret != 0)
941                         return -errno;
942                 dentry_update_all_timestamps(dentry);
943                 lte->resource_entry.original_size = size;
944                 return 0;
945         } else {
946                 /* File in WIM.  Extract it to the staging directory, but only
947                  * the first @size bytes of it. */
948                 return extract_resource_to_staging_dir(dentry, lte, size);
949         }
950 }
951
952 /* Remove a regular file */
953 static int wimfs_unlink(const char *path)
954 {
955         struct dentry *dentry;
956         struct lookup_table_entry *lte;
957         
958         dentry = get_dentry(w, path);
959         if (!dentry)
960                 return -EEXIST;
961
962         if (!dentry_is_regular_file(dentry))
963                 return -EEXIST;
964
965         lte = wim_lookup_resource(w, dentry);
966         if (lte) {
967                 if (lte->staging_file_name)
968                         if (unlink(lte->staging_file_name) != 0)
969                                 return -errno;
970                 lookup_table_decrement_refcnt(w->lookup_table, dentry->hash);
971         }
972
973         unlink_dentry(dentry);
974         free_dentry(dentry);
975         return 0;
976 }
977
978 /* Writes to a file in the WIM filesystem. */
979 static int wimfs_write(const char *path, const char *buf, size_t size, 
980                                 off_t offset, struct fuse_file_info *fi)
981 {
982         struct dentry *dentry;
983         struct lookup_table_entry *lte;
984         ssize_t ret;
985
986         dentry = get_dentry(w, path);
987         if (!dentry)
988                 return -EEXIST;
989         lte = wim_lookup_resource(w, dentry);
990
991         if (!lte) /* this should not happen */
992                 return -EEXIST;
993
994         if (lte->staging_num_times_opened == 0)
995                 return -EBADF;
996         if (lte->staging_file_name) {
997
998                 /* File in staging directory. We can write to it directly. */
999
1000                 /* Seek to correct position in file if needed. */
1001                 if (lte->staging_offset != offset) {
1002                         if (lseek(lte->staging_fd, offset, SEEK_SET) == -1)
1003                                 return -errno;
1004                         lte->staging_offset = offset;
1005                 }
1006
1007                 /* Write the data. */
1008                 ret = write(lte->staging_fd, buf, size);
1009                 if (ret == -1)
1010                         return -errno;
1011
1012                 /* Adjust the stored offset of staging_fd. */
1013                 lte->staging_offset = offset + ret;
1014
1015                 /* Increase file size if needed. */
1016                 if (lte->resource_entry.original_size < lte->staging_offset)
1017                         lte->resource_entry.original_size = lte->staging_offset;
1018
1019                 /* The file has been modified, so all its timestamps must be
1020                  * updated. */
1021                 dentry_update_all_timestamps(dentry);
1022                 return ret;
1023         } else {
1024                 /* File in the WIM.  We must extract it to the staging directory
1025                  * before it can be written to. */
1026                 ret = extract_resource_to_staging_dir(dentry, lte, 
1027                                         lte->resource_entry.original_size);
1028                 if (ret != 0)
1029                         return ret;
1030                 else
1031                         return wimfs_write(path, buf, size, offset, fi);
1032         }
1033 }
1034
1035
1036 static struct fuse_operations wimfs_oper = {
1037         .access   = wimfs_access,
1038         .destroy  = wimfs_destroy,
1039         .getattr  = wimfs_getattr,
1040         .mkdir    = wimfs_mkdir,
1041         .mknod    = wimfs_mknod,
1042         .open     = wimfs_open,
1043         .opendir  = wimfs_opendir,
1044         .read     = wimfs_read,
1045         .readdir  = wimfs_readdir,
1046         .release  = wimfs_release,
1047         .rename   = wimfs_rename,
1048         .rmdir    = wimfs_rmdir,
1049         .truncate = wimfs_truncate,
1050         .unlink   = wimfs_unlink,
1051         .write    = wimfs_write,
1052 };
1053
1054
1055 /* Mounts a WIM file. */
1056 WIMLIBAPI int wimlib_mount(WIMStruct *wim, int image, const char *dir, 
1057                            int flags)
1058 {
1059         int argc = 0;
1060         char *argv[6];
1061         int ret;
1062         char *p;
1063
1064         DEBUG("Mount: wim = %p, image = %d, dir = %s, flags = %d, ",
1065                         wim, image, dir, flags);
1066
1067         if (!dir)
1068                 return WIMLIB_ERR_INVALID_PARAM;
1069
1070         ret = wimlib_select_image(wim, image);
1071
1072         if (ret != 0)
1073                 return ret;
1074
1075         if (flags & WIMLIB_MOUNT_FLAG_READWRITE)
1076                 wim_get_current_image_metadata(wim)->modified = true;
1077
1078         mount_dir = dir;
1079         working_directory = getcwd(NULL, 0);
1080         if (!working_directory) {
1081                 ERROR("Could not determine current directory: %m\n");
1082                 return WIMLIB_ERR_NOTDIR;
1083         }
1084
1085         p = STRDUP(dir);
1086         if (!p)
1087                 return WIMLIB_ERR_NOMEM;
1088
1089         argv[argc++] = "mount";
1090         argv[argc++] = p;
1091         argv[argc++] = "-s"; /* disable multi-threaded operation */
1092
1093         if (flags & WIMLIB_MOUNT_FLAG_DEBUG) {
1094                 argv[argc++] = "-d";
1095         }
1096         if (!(flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
1097                 argv[argc++] = "-o";
1098                 argv[argc++] = "ro";
1099         } else {
1100                 make_staging_dir();
1101                 if (!staging_dir_name) {
1102                         FREE(p);
1103                         return WIMLIB_ERR_MKDIR;
1104                 }
1105         }
1106
1107 #ifdef ENABLE_DEBUG
1108         {
1109                 int i;
1110                 DEBUG("FUSE command line (argc = %d): ", argc);
1111                 for (i = 0; i < argc; i++) {
1112                         fputs(argv[i], stdout);
1113                         putchar(' ');
1114                 }
1115                 putchar('\n');
1116                 fflush(stdout);
1117         }
1118 #endif
1119
1120         /* Set static variables. */
1121         w = wim;
1122         mount_flags = flags;
1123
1124         ret = fuse_main(argc, argv, &wimfs_oper, NULL);
1125
1126         return (ret == 0) ? 0 : WIMLIB_ERR_FUSE;
1127 }
1128
1129
1130 /* 
1131  * Unmounts the WIM file that was previously mounted on @dir by using
1132  * wimlib_mount().
1133  */
1134 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
1135 {
1136         pid_t pid;
1137         int status;
1138         int ret;
1139         char msg[2];
1140         struct timeval now;
1141         struct timespec timeout;
1142         int msgsize;
1143         int errno_save;
1144
1145         /* Execute `fusermount -u', which is installed setuid root, to unmount
1146          * the WIM.
1147          *
1148          * FUSE does not yet implement synchronous unmounts.  This means that
1149          * fusermount -u will return before the filesystem daemon returns from
1150          * wimfs_destroy().  This is partly what we want, because we need to
1151          * send a message from this process to the filesystem daemon telling
1152          * whether --commit was specified or not.  However, after that, the
1153          * unmount process must wait for the filesystem daemon to finish writing
1154          * the WIM file. 
1155          */
1156
1157         mount_dir = dir;
1158         pid = fork();
1159         if (pid == -1) {
1160                 ERROR("Failed to fork(): %m\n");
1161                 return WIMLIB_ERR_FORK;
1162         }
1163         if (pid == 0) {
1164                 execlp("fusermount", "fusermount", "-u", dir, NULL);
1165                 ERROR("Failed to execute `fusermount': %m\n");
1166                 return WIMLIB_ERR_FUSERMOUNT;
1167         }
1168
1169         ret = waitpid(pid, &status, 0);
1170         if (ret == -1) {
1171                 ERROR("Failed to wait for fusermount process to "
1172                                 "terminate: %m\n");
1173                 return WIMLIB_ERR_FUSERMOUNT;
1174         }
1175
1176         if (status != 0) {
1177                 ERROR("fusermount exited with status %d!\n", status);
1178                 return WIMLIB_ERR_FUSERMOUNT;
1179         }
1180
1181         /* Open message queues between the unmount process and the
1182          * filesystem daemon. */
1183         ret = open_message_queues(false);
1184         if (ret != 0)
1185                 return ret;
1186
1187         /* Send a message to the filesystem saying whether to commit or
1188          * not. */
1189         msg[0] = (flags & WIMLIB_UNMOUNT_FLAG_COMMIT) ? 1 : 0;
1190         msg[1] = (flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY) ? 1 : 0;
1191
1192         DEBUG("Sending message: %s, %s\n", 
1193                         (msg[0] == 0) ? "don't commit" : "commit",
1194                         (msg[1] == 0) ? "don't check"  : "check");
1195         ret = mq_send(unmount_to_daemon_mq, msg, 2, 1);
1196         if (ret == -1) {
1197                 ERROR("Failed to notify filesystem daemon whether "
1198                                 "we want to commit changes or not!\n");
1199                 close_message_queues();
1200                 return WIMLIB_ERR_MQUEUE;
1201         }
1202
1203         /* Wait for a message from the filesytem daemon indicating whether  the
1204          * filesystem was unmounted successfully (0) or an error occurred (1).
1205          * This may take a long time if a big WIM file needs to be rewritten. */
1206
1207         /* Wait at most 600??? seconds before giving up and returning false.
1208          * Either it's a really big WIM file, or (more likely) the
1209          * filesystem daemon has crashed or failed for some reason.
1210          *
1211          * XXX come up with some method to determine if the filesystem
1212          * daemon has really crashed or not. */
1213
1214         gettimeofday(&now, NULL);
1215         timeout.tv_sec = now.tv_sec + 600;
1216         timeout.tv_nsec = now.tv_usec * 1000;
1217
1218         msgsize = mq_get_msgsize(daemon_to_unmount_mq);
1219         char mailbox[msgsize];
1220
1221         mailbox[0] = 0;
1222         DEBUG("Waiting for message telling us whether the unmount was "
1223                         "successful or not.\n");
1224         ret = mq_timedreceive(daemon_to_unmount_mq, mailbox, msgsize,
1225                               NULL, &timeout);
1226         errno_save = errno;
1227         close_message_queues();
1228         if (ret == -1) {
1229                 if (errno_save == ETIMEDOUT) {
1230                         ERROR("Timed out- probably the filesystem "
1231                                         "daemon crashed and the WIM was not "
1232                                         "written successfully.\n");
1233                         return WIMLIB_ERR_TIMEOUT;
1234                 } else {
1235                         ERROR("mq_receive(): %s\n",
1236                                         strerror(errno_save));
1237                         return WIMLIB_ERR_MQUEUE;
1238                 }
1239
1240         }
1241         DEBUG("Received message: %s\n", (mailbox[0] == 0) ? 
1242                                         "Unmount OK" : "Unmount Failed");
1243         if (mailbox[0] != 0)
1244                 ERROR("Unmount failed\n");
1245         return mailbox[0];
1246 }
1247
1248 #else /* WITH_FUSE */
1249
1250
1251 static inline int mount_unsupported_error()
1252 {
1253         ERROR("WIMLIB was compiled with --without-fuse, which "
1254                         "disables support for mounting WIMs.\n");
1255         return WIMLIB_ERR_UNSUPPORTED;
1256 }
1257
1258 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
1259 {
1260         return mount_unsupported_error();
1261 }
1262
1263 WIMLIBAPI int wimlib_mount(WIMStruct *wim_p, int image, const char *dir, 
1264                            int flags)
1265 {
1266         return mount_unsupported_error();
1267 }
1268
1269 #endif /* WITH_FUSE */