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