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