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