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