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