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