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