]> wimlib.net Git - wimlib/blob - src/mount.c
ac4aeb376c750d9ed94387711aca35e0a54e9aeb
[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 #include <attr/xattr.h>
48
49 struct wimlib_fd {
50         u16 idx;
51         int staging_fd;
52         u64 hard_link_group;
53         struct lookup_table_entry *lte;
54         struct dentry *dentry;
55 };
56
57 /* The WIMStruct for the mounted WIM. */
58 static WIMStruct *w;
59
60 /* Working directory when `imagex mount' is run. */
61 static const char *working_directory;
62
63 /* Name of the staging directory for a read-write mount.  Whenever a new file is
64  * created, it is done so in the staging directory.  Furthermore, whenever a
65  * file in the WIM is modified, it is extracted to the staging directory.  If
66  * changes are commited when the WIM is unmounted, the file resources are merged
67  * in from the staging directory when writing the new WIM. */
68 static char *staging_dir_name;
69 static size_t staging_dir_name_len;
70
71 /* Flags passed to wimlib_mount(). */
72 static int mount_flags;
73
74 /* Name of the directory on which the WIM file is mounted. */
75 static const char *mount_dir;
76
77 /* Next hard link group ID to be assigned.  These are also used as the inode
78  * numbers. */
79 static u64 next_link_group_id;
80
81 /* List of lookup table entries in the staging directory */
82 static LIST_HEAD(staging_list);
83
84 static inline int get_lookup_flags()
85 {
86         if (mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
87                 return LOOKUP_FLAG_ADS_OK;
88         else
89                 return 0;
90 }
91
92 /* Returns nonzero if write permission is requested on the file open flags */
93 static inline int flags_writable(int open_flags)
94 {
95         return open_flags & (O_RDWR | O_WRONLY);
96 }
97
98 /* 
99  * Allocate a file descriptor for a lookup table entry
100  */
101 static int alloc_wimlib_fd(struct lookup_table_entry *lte,
102                            struct wimlib_fd **fd_ret)
103 {
104         static const u16 fds_per_alloc = 8;
105         static const u16 max_fds = 0xffff;
106
107         if (lte->num_opened_fds == lte->num_allocated_fds) {
108                 struct wimlib_fd **fds;
109                 u16 num_new_fds;
110
111                 if (lte->num_allocated_fds == max_fds)
112                         return -EMFILE;
113                 num_new_fds = min(fds_per_alloc, max_fds - lte->num_allocated_fds);
114                 
115                 fds = REALLOC(lte->fds, (lte->num_allocated_fds + num_new_fds) *
116                                sizeof(lte->fds[0]));
117                 if (!fds)
118                         return -ENOMEM;
119                 memset(&fds[lte->num_allocated_fds], 0,
120                        num_new_fds * sizeof(fds[0]));
121                 lte->fds = fds;
122                 lte->num_allocated_fds += num_new_fds;
123         }
124         for (u16 i = 0; ; i++) {
125                 if (!lte->fds[i]) {
126                         struct wimlib_fd *fd = CALLOC(1, sizeof(*fd));
127                         if (!fd)
128                                 return -ENOMEM;
129                         fd->staging_fd = -1;
130                         fd->idx        = i;
131                         fd->lte        = lte;
132                         lte->fds[i]    = fd;
133                         lte->num_opened_fds++;
134                         *fd_ret        = fd;
135                         return 0;
136                 }
137         }
138 }
139
140 static int close_wimlib_fd(struct wimlib_fd *fd)
141 {
142         struct lookup_table_entry *lte = fd->lte;
143
144         wimlib_assert(lte);
145         wimlib_assert(lte->num_opened_fds);
146
147         if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
148                 wimlib_assert(lte->staging_file_name);
149                 wimlib_assert(fd->staging_fd != -1);
150                 if (close(fd->staging_fd) != 0)
151                         return -errno;
152         }
153         if (--lte->num_opened_fds == 0 && lte->refcnt == 0) {
154                 if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
155                         wimlib_assert(lte->staging_file_name);
156                         unlink(lte->staging_file_name);
157                 }
158                 free_lookup_table_entry(lte);
159         }
160         wimlib_assert(lte->fds[fd->idx] == fd);
161         lte->fds[fd->idx] = NULL;
162         FREE(fd);
163         return 0;
164 }
165
166 /* Remove a dentry and all its alternate file streams */
167 static void remove_dentry(struct dentry *dentry,
168                           struct lookup_table *lookup_table)
169 {
170         wimlib_assert(dentry);
171         wimlib_assert(dentry->resolved);
172
173         struct lookup_table_entry *lte = dentry->lte;
174         u16 i = 0;
175         while (1) {
176                 lte = lte_decrement_refcnt(lte, lookup_table);
177                 if (lte && lte->num_opened_fds)
178                         for (u16 i = 0; i < lte->num_allocated_fds; i++)
179                                 if (lte->fds[i] && lte->fds[i]->dentry == dentry)
180                                         lte->fds[i]->dentry = NULL;
181                 if (i == dentry->num_ads)
182                         break;
183                 lte = dentry->ads_entries[i].lte;
184                 i++;
185         }
186
187         unlink_dentry(dentry);
188         put_dentry(dentry);
189 }
190
191 static void remove_ads(struct dentry *dentry,
192                        struct ads_entry *ads_entry,
193                        struct lookup_table *lookup_table)
194 {
195         struct lookup_table_entry *lte;
196
197         wimlib_assert(dentry->resolved);
198
199         lte = lte_decrement_refcnt(lte, lookup_table);
200         if (lte)
201                 list_del(&ads_entry->lte_group_list.list);
202         dentry_remove_ads(dentry, ads_entry);
203 }
204
205 /* Transfers file attributes from a struct dentry to a `stat' buffer. */
206 int dentry_to_stbuf(const struct dentry *dentry, struct stat *stbuf)
207 {
208         struct lookup_table_entry *lte;
209
210         if (dentry_is_symlink(dentry))
211                 stbuf->st_mode = S_IFLNK | 0777;
212         else if (dentry_is_directory(dentry))
213                 stbuf->st_mode = S_IFDIR | 0755;
214         else
215                 stbuf->st_mode = S_IFREG | 0644;
216
217         stbuf->st_ino = (ino_t)dentry->hard_link;
218
219         stbuf->st_nlink = dentry_link_group_size(dentry);
220         stbuf->st_uid   = getuid();
221         stbuf->st_gid   = getgid();
222
223         /* Use the size of the unnamed (default) file stream. */
224         lte = dentry_first_lte_resolved(dentry);
225         if (lte) {
226                 if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
227                         wimlib_assert(lte->staging_file_name);
228                         struct stat native_stat;
229                         if (stat(lte->staging_file_name, &native_stat) != 0) {
230                                 DEBUG("Failed to stat `%s': %m",
231                                       lte->staging_file_name);
232                                 return -errno;
233                         }
234                         stbuf->st_size = native_stat.st_size;
235                 } else {
236                         stbuf->st_size = lte->resource_entry.original_size;
237                 }
238         } else {
239                 stbuf->st_size = 0;
240         }
241
242         stbuf->st_atime   = wim_timestamp_to_unix(dentry->last_access_time);
243         stbuf->st_mtime   = wim_timestamp_to_unix(dentry->last_write_time);
244         stbuf->st_ctime   = wim_timestamp_to_unix(dentry->creation_time);
245         stbuf->st_blocks  = (stbuf->st_size + 511) / 512;
246         return 0;
247 }
248
249 /* Creates a new staging file and returns its file descriptor opened for
250  * writing.
251  *
252  * @name_ret: A location into which the a pointer to the newly allocated name of
253  *                      the staging file is stored.
254  * @return:  The file descriptor for the new file.  Returns -1 and sets errno on
255  *              error, for any reason possible from the creat() function.
256  */
257 static int create_staging_file(char **name_ret, int open_flags)
258 {
259         size_t name_len;
260         char *name;
261         struct stat stbuf;
262         int fd;
263         int errno_save;
264
265         name_len = staging_dir_name_len + 1 + SHA1_HASH_SIZE;
266         name = MALLOC(name_len + 1);
267         if (!name) {
268                 errno = ENOMEM;
269                 return -1;
270         }
271
272         do {
273
274                 memcpy(name, staging_dir_name, staging_dir_name_len);
275                 name[staging_dir_name_len] = '/';
276                 randomize_char_array_with_alnum(name + staging_dir_name_len + 1,
277                                                 SHA1_HASH_SIZE);
278                 name[name_len] = '\0';
279
280
281         /* Just in case, verify that the randomly generated name doesn't name an
282          * existing file, and try again if so  */
283         } while (stat(name, &stbuf) == 0);
284
285         if (errno != ENOENT)
286                 /* other error! */
287                 return -1;
288
289         /* doesn't exist--- ok */
290
291         DEBUG("Creating staging file `%s'", name);
292
293         fd = open(name, open_flags | O_CREAT | O_TRUNC, 0600); 
294         if (fd == -1) {
295                 errno_save = errno;
296                 FREE(name);
297                 errno = errno_save;
298         } else {
299                 *name_ret = name;
300         }
301         return fd;
302 }
303
304 /* 
305  * Removes open file descriptors from a lookup table entry @old_lte where the
306  * file descriptors have opened the corresponding file resource in the context
307  * of the hard link group @link_group; these file descriptors are extracted and
308  * placed in a new lookup table entry, which is returned.
309  */
310 static struct lookup_table_entry *
311 lte_extract_fds(struct lookup_table_entry *old_lte, u64 link_group)
312 {
313         int ret;
314         u16 num_transferred_fds;
315         struct lookup_table_entry *new_lte;
316
317         new_lte = new_lookup_table_entry();
318         if (!new_lte)
319                 return NULL;
320
321         num_transferred_fds = 0;
322         for (u16 i = 0; i < old_lte->num_allocated_fds; i++)
323                 if (old_lte->fds[i] && old_lte->fds[i]->dentry &&
324                     old_lte->fds[i]->dentry->hard_link == link_group)
325                         num_transferred_fds++;
326         DEBUG("Transferring %u file descriptors",
327               num_transferred_fds);
328         new_lte->fds = MALLOC(num_transferred_fds * sizeof(new_lte->fds[0]));
329         if (!new_lte->fds) {
330                 FREE(new_lte);
331                 return NULL;
332         }
333         for (u16 i = 0, j = 0; ; i++) {
334                 if (old_lte->fds[i] && old_lte->fds[i]->dentry &&
335                     old_lte->fds[i]->dentry->hard_link == link_group) {
336                         struct wimlib_fd *fd = old_lte->fds[i];
337                         old_lte->fds[i] = NULL;
338                         fd->lte = new_lte;
339                         fd->idx = j;
340                         new_lte->fds[j] = fd;
341                         if (++j == num_transferred_fds)
342                                 break;
343                 }
344         }
345         DEBUG("old_lte: %u fds open; new_lte: %u fds open",
346               old_lte->num_opened_fds, new_lte->num_opened_fds);
347         old_lte->num_opened_fds -= num_transferred_fds;
348         new_lte->num_opened_fds = num_transferred_fds;
349         new_lte->num_allocated_fds = num_transferred_fds;
350         return new_lte;
351 }
352
353 /* 
354  * Transfers an alternate data stream entry to a new lookup table entry
355  */
356 static void lte_transfer_ads_entry(struct lookup_table_entry *new_lte,
357                                    struct ads_entry *ads_entry)
358 {
359         list_del(&ads_entry->lte_group_list.list);
360         list_add(&ads_entry->lte_group_list.list, &new_lte->lte_group_list);
361         ads_entry->lte = new_lte;
362 }
363
364 /* 
365  * Transfers a dentry to a new lookup table entry
366  */
367 static void lte_transfer_dentry(struct lookup_table_entry *new_lte,
368                                 struct dentry *dentry)
369 {
370         wimlib_assert(dentry->lte_group_list.list.next);
371         wimlib_assert(new_lte->lte_group_list.next);
372         list_del(&dentry->lte_group_list.list);
373         list_add(&dentry->lte_group_list.list, &new_lte->lte_group_list);
374         dentry->lte = new_lte;
375 }
376
377 static void lte_transfer_stream_entries(struct lookup_table_entry *new_lte,
378                                         struct dentry *dentry,
379                                         unsigned stream_idx)
380 {
381         INIT_LIST_HEAD(&new_lte->lte_group_list);
382         if (stream_idx == 0) {
383                 struct list_head *pos = &dentry->link_group_list;
384                 do {
385                         struct dentry *d;
386                         d = container_of(pos, struct dentry, link_group_list);
387                         wimlib_assert(d->hard_link == dentry->hard_link);
388                         lte_transfer_dentry(new_lte, d);
389                         pos = pos->next;
390                 } while (pos != &dentry->link_group_list);
391         } else {
392                 struct ads_entry *ads_entry;
393                 wimlib_assert(stream_idx <= dentry->num_ads);
394                 ads_entry = &dentry->ads_entries[stream_idx - 1];
395                 lte_transfer_ads_entry(new_lte, ads_entry);
396         }
397 }
398
399 /* 
400  * Extract a WIM resource to the staging directory.
401  *
402  * @dentry, @stream_idx:  The stream on whose behalf we are modifying the lookup
403  * table entry (these may be more streams than this that reference the lookup
404  * table entry)
405  *
406  * @lte: Pointer to pointer to the lookup table entry for the stream we need to
407  * extract, or NULL if there was no lookup table entry present for the stream
408  *
409  * @size:  Number of bytes of the stream we want to extract (this supports the
410  * wimfs_truncate() function).
411  */
412 static int extract_resource_to_staging_dir(struct dentry *dentry,
413                                            unsigned stream_idx,
414                                            struct lookup_table_entry **lte,
415                                            off_t size)
416 {
417         char *staging_file_name;
418         int ret;
419         int fd;
420         struct lookup_table_entry *old_lte, *new_lte;
421         size_t link_group_size;
422
423         /*
424          * We need to:
425          * - Create a staging file for the WIM resource
426          * - Extract the resource to it
427          * - Create a new lte for the file resource
428          * - Transfer fds from the old lte to the new lte, but only if they share the
429          *   same hard link group as this dentry.  If there is no old lte, then this
430          *   step does not need to be done
431          * - Transfer stream entries from the old lte's list to the new lte's list.  If
432          *   there is no old lte, we instead transfer entries for the hard link group.
433          *
434          *   Note: *lte is permitted to be NULL, in which case there is no old
435          *   lookup table entry.
436          */
437
438         DEBUG("Extracting resource `%s' to staging directory", dentry->full_path_utf8);
439
440         old_lte = *lte;
441         fd = create_staging_file(&staging_file_name, O_WRONLY);
442         if (fd == -1)
443                 return -errno;
444
445         if (old_lte)
446                 ret = extract_wim_resource_to_fd(old_lte, fd, size);
447         else
448                 ret = 0;
449         if (ret != 0 || close(fd) != 0) {
450                 if (errno != 0)
451                         ret = -errno;
452                 else
453                         ret = -EIO;
454                 close(fd);
455                 goto out_delete_staging_file;
456         }
457
458         link_group_size = dentry_link_group_size(dentry);
459
460         if (old_lte) {
461                 if (link_group_size == old_lte->refcnt) {
462                         /* This hard link group is the only user of the lookup
463                          * table entry, so we can re-use it. */
464                         DEBUG("Re-using lookup table entry");
465                         lookup_table_unlink(w->lookup_table, old_lte);
466                         new_lte = old_lte;
467                 } else {
468                         DEBUG("Splitting lookup table entry "
469                               "(link_group_size = %u, lte refcnt = %u)",
470                               link_group_size, old_lte->refcnt);
471                         /* Split a hard link group away from the "lookup table
472                          * entry" hard link group (i.e. we had two hard link
473                          * groups that were identical, but now we are changing
474                          * one of them) */
475
476                         /* XXX 
477                          * The ADS really complicate things here and not
478                          * everything is going to work correctly yet.  For
479                          * example it could be the same that a file contains two
480                          * file streams that are identical and therefore share
481                          * the same lookup table entry despite the fact that the
482                          * streams themselves are not hardlinked. 
483                          * XXX*/
484                         wimlib_assert(old_lte->refcnt > link_group_size);
485
486                         new_lte = lte_extract_fds(old_lte, dentry->hard_link);
487                         if (!new_lte) {
488                                 ret = -ENOMEM;
489                                 goto out_delete_staging_file;
490                         }
491
492                         lte_transfer_stream_entries(new_lte, dentry, stream_idx);
493                         old_lte->refcnt -= link_group_size;
494                 } 
495         } else {
496                 /* No old_lte was supplied, so the resource had no lookup table
497                  * entry before (it must be an empty resource) */
498                 new_lte = new_lookup_table_entry();
499                 if (!new_lte) {
500                         ret = -ENOMEM;
501                         goto out_delete_staging_file;
502                 }
503                 lte_transfer_stream_entries(new_lte, dentry, stream_idx);
504         }
505         new_lte->resource_entry.original_size = size;
506         new_lte->refcnt = link_group_size;
507         random_hash(new_lte->hash);
508         if (new_lte->staging_file_name)
509                 FREE(new_lte->staging_file_name);
510         new_lte->staging_file_name = staging_file_name;
511         new_lte->resource_location = RESOURCE_IN_STAGING_FILE;
512
513         lookup_table_insert(w->lookup_table, new_lte);
514         list_add(&new_lte->staging_list, &staging_list);
515         *lte = new_lte;
516         return 0;
517 out_delete_staging_file:
518         unlink(staging_file_name);
519         FREE(staging_file_name);
520         return ret;
521 }
522
523 /* 
524  * Creates a randomly named staging directory and returns its name into the
525  * static variable staging_dir_name.
526  *
527  * If the staging directory cannot be created, staging_dir_name is set to NULL.
528  * */
529 static void make_staging_dir()
530 {
531         /* XXX Give the user an option of where to stage files */
532
533         static char prefix[] = "wimlib-staging-";
534         static const size_t prefix_len = 15;
535         static const size_t suffix_len = 10;
536
537         size_t pwd_len = strlen(working_directory);
538
539         staging_dir_name_len = pwd_len + 1 + prefix_len + suffix_len;
540
541         staging_dir_name = MALLOC(staging_dir_name_len + 1);
542         if (!staging_dir_name) {
543                 ERROR("Out of memory");
544                 return;
545         }
546
547         memcpy(staging_dir_name, working_directory, pwd_len);
548         staging_dir_name[pwd_len] = '/';
549         memcpy(staging_dir_name + pwd_len + 1, prefix, prefix_len);
550         randomize_char_array_with_alnum(staging_dir_name + pwd_len + 1 + prefix_len,
551                                 suffix_len);
552         staging_dir_name[staging_dir_name_len] = '\0';
553
554         if (mkdir(staging_dir_name, 0700) != 0) {
555                 ERROR_WITH_ERRNO("Failed to create temporary directory `%s'",
556                                  staging_dir_name);
557                 FREE(staging_dir_name);
558                 staging_dir_name = NULL;
559         }
560 }
561
562 static int remove_file_or_directory(const char *fpath, const struct stat *sb,
563                 int typeflag, struct FTW *ftwbuf)
564 {
565         if (remove(fpath) == 0)
566                 return 0;
567         else
568                 return WIMLIB_ERR_DELETE_STAGING_DIR;
569 }
570
571
572 /* 
573  * Deletes the staging directory and all the files contained in it. 
574  */
575 static inline int delete_staging_dir()
576 {
577         int ret;
578         
579         ret = nftw(staging_dir_name, remove_file_or_directory,10, FTW_DEPTH);
580         staging_dir_name = NULL;
581         return ret;
582 }
583
584 /* Name and message queue descriptors for message queues between the filesystem
585  * daemon process and the unmount process.  These are used when the filesystem
586  * is unmounted and the process running wimlib_mount() (i.e. the `imagex
587  * unmount' command) needs to communicate with the filesystem daemon running
588  * fuse_main() (i.e. that spawned by the `imagex mount' or `imagex mountrw'
589  * commands */
590 static char *unmount_to_daemon_mq_name;
591 static char *daemon_to_unmount_mq_name;
592 static int unmount_to_daemon_mq;
593 static int daemon_to_unmount_mq;
594
595 /* Simple function that returns the concatenation of 4 strings. */
596 static char *strcat_dup(const char *s1, const char *s2, const char *s3, 
597                                                         const char *s4)
598 {
599         size_t len = strlen(s1) + strlen(s2) + strlen(s3) + strlen(s4) + 1;
600         char *p = MALLOC(len);
601         if (!p)
602                 return NULL;
603         *p = '\0';
604         strcat(p, s1);
605         strcat(p, s2);
606         strcat(p, s3);
607         strcat(p, s4);
608         return p;
609 }
610
611 /* Removes trailing forward slashes in a string. */
612 static void remove_trailing_slashes(char *s)
613 {
614         long len = strlen(s);
615         for (long i = len - 1; i >= 1; i--) {
616                 if (s[i] == '/')
617                         s[i] = '\0';
618                 else
619                         break;
620         }
621 }
622
623 /* Changes forward slashes to underscores in a string. */
624 static void s_slashes_underscores_g(char *s)
625 {
626         while (*s) {
627                 if (*s == '/')
628                         *s = '_';
629                 s++;
630         }
631 }
632
633 /* 
634  * Opens two POSIX message queue: one for sending messages from the unmount
635  * process to the daemon process, and one to go the other way.  The names of the
636  * message queues, which must be system-wide unique, are be based on the mount
637  * point.  (There of course is still a possibility of a collision if one were to
638  * unmount two identically named directories simultaneously...)
639  *
640  * @daemon specifies whether the calling process is the filesystem daemon or the
641  * unmount process.
642  */
643 static int open_message_queues(bool daemon)
644 {
645         static const char *slash = "/";
646         static const char *prefix = "wimlib-";
647         static const char *u2d_suffix = "unmount-to-daemon-mq";
648         static const char *d2u_suffix = "daemon-to-unmount-mq";
649
650         const char *mount_dir_basename = path_basename(mount_dir);
651         int flags;
652         int ret;
653
654         unmount_to_daemon_mq_name = strcat_dup(slash, mount_dir_basename,
655                                                 prefix, u2d_suffix);
656         if (!unmount_to_daemon_mq_name) {
657                 ERROR("Out of memory");
658                 return WIMLIB_ERR_NOMEM;
659         }
660         daemon_to_unmount_mq_name = strcat_dup(slash, mount_dir_basename,
661                                                 prefix, d2u_suffix);
662         if (!daemon_to_unmount_mq_name) {
663                 ERROR("Out of memory");
664                 ret = WIMLIB_ERR_NOMEM;
665                 goto err1;
666         }
667
668         remove_trailing_slashes(unmount_to_daemon_mq_name);
669         remove_trailing_slashes(daemon_to_unmount_mq_name);
670         s_slashes_underscores_g(unmount_to_daemon_mq_name + 1);
671         s_slashes_underscores_g(daemon_to_unmount_mq_name + 1);
672
673         if (daemon)
674                 flags = O_RDONLY | O_CREAT;
675         else
676                 flags = O_WRONLY | O_CREAT;
677
678         unmount_to_daemon_mq = mq_open(unmount_to_daemon_mq_name, flags, 
679                                        0700, NULL);
680
681         if (unmount_to_daemon_mq == -1) {
682                 ERROR_WITH_ERRNO("mq_open()");
683                 ret = WIMLIB_ERR_MQUEUE;
684                 goto err2;
685         }
686
687         if (daemon)
688                 flags = O_WRONLY | O_CREAT;
689         else
690                 flags = O_RDONLY | O_CREAT;
691
692         daemon_to_unmount_mq = mq_open(daemon_to_unmount_mq_name, flags, 
693                                        0700, NULL);
694
695         if (daemon_to_unmount_mq == -1) {
696                 ERROR_WITH_ERRNO("mq_open()");
697                 ret = WIMLIB_ERR_MQUEUE;
698                 goto err3;
699         }
700         return 0;
701 err3:
702         mq_close(unmount_to_daemon_mq);
703         mq_unlink(unmount_to_daemon_mq_name);
704 err2:
705         FREE(daemon_to_unmount_mq_name);
706 err1:
707         FREE(unmount_to_daemon_mq_name);
708         return ret;
709 }
710
711 static int mq_get_msgsize(mqd_t mq)
712 {
713         static const char *msgsize_max_file = "/proc/sys/fs/mqueue/msgsize_max";
714         FILE *fp;
715         struct mq_attr attr;
716         int msgsize;
717
718         if (mq_getattr(unmount_to_daemon_mq, &attr) == 0) {
719                 msgsize = attr.mq_msgsize;
720         } else {
721                 ERROR_WITH_ERRNO("mq_getattr()");
722                 ERROR("Attempting to read %s", msgsize_max_file);
723                 fp = fopen(msgsize_max_file, "rb");
724                 if (fp) {
725                         if (fscanf(fp, "%d", &msgsize) != 1) {
726                                 ERROR("Assuming message size of 8192");
727                                 msgsize = 8192;
728                         }
729                         fclose(fp);
730                 } else {
731                         ERROR_WITH_ERRNO("Failed to open the file `%s'",
732                                          msgsize_max_file);
733                         ERROR("Assuming message size of 8192");
734                         msgsize = 8192;
735                 }
736         }
737         return msgsize;
738 }
739
740 /* Closes the message queues, which are allocated in static variables */
741 static void close_message_queues()
742 {
743         mq_close(unmount_to_daemon_mq);
744         mq_close(daemon_to_unmount_mq);
745         mq_unlink(unmount_to_daemon_mq_name);
746         mq_unlink(daemon_to_unmount_mq_name);
747 }
748
749 static int wimfs_access(const char *path, int mask)
750 {
751         /* XXX Permissions not implemented */
752         return 0;
753 }
754
755 /* Closes the staging file descriptor associated with the lookup table entry, if
756  * it is opened. */
757 static int close_lte_fds(struct lookup_table_entry *lte)
758 {
759         for (u16 i = 0, j = 0; j < lte->num_opened_fds; i++) {
760                 if (lte->fds[i] && lte->fds[i]->staging_fd != -1) {
761                         wimlib_assert(lte->resource_location == RESOURCE_IN_STAGING_FILE);
762                         wimlib_assert(lte->staging_file_name);
763                         if (close(lte->fds[i]->staging_fd) != 0) {
764                                 ERROR_WITH_ERRNO("Failed close file `%s'",
765                                                  lte->staging_file_name);
766                                 return WIMLIB_ERR_WRITE;
767                         }
768                         j++;
769                 }
770         }
771         return 0;
772 }
773
774 static void lte_list_change_lte_ptr(struct lookup_table_entry *lte,
775                                     struct lookup_table_entry *newptr)
776 {
777         struct list_head *pos;
778         struct stream_list_head *head;
779         list_for_each(pos, &lte->lte_group_list) {
780                 head = container_of(pos, struct stream_list_head, list);
781                 if (head->type == STREAM_TYPE_ADS) {
782                         struct ads_entry *ads_entry;
783                         ads_entry = container_of(head, struct ads_entry, lte_group_list);
784
785                         ads_entry->lte = newptr;
786                 } else {
787                         wimlib_assert(head->type == STREAM_TYPE_NORMAL);
788
789                         struct dentry *dentry;
790                         dentry = container_of(head, struct dentry, lte_group_list);
791
792                         dentry->lte = newptr;
793                 }
794         }
795 }
796
797
798 static int update_lte_of_staging_file(struct lookup_table_entry *lte,
799                                       struct lookup_table *table)
800 {
801         struct lookup_table_entry *duplicate_lte;
802         int ret;
803         u8 hash[SHA1_HASH_SIZE];
804         struct stat stbuf;
805
806         wimlib_assert(lte->resource_location == RESOURCE_IN_STAGING_FILE);
807         wimlib_assert(lte->staging_file_name);
808
809         ret = sha1sum(lte->staging_file_name, hash);
810         if (ret != 0)
811                 return ret;
812
813         lookup_table_unlink(table, lte);
814
815         duplicate_lte = __lookup_resource(table, hash);
816
817         if (duplicate_lte) {
818                 /* Merge duplicate lookup table entries */
819
820                 lte_list_change_lte_ptr(lte, duplicate_lte);
821                 duplicate_lte->refcnt += lte->refcnt;
822                 list_splice(&lte->lte_group_list,
823                             &duplicate_lte->lte_group_list);
824
825                 free_lookup_table_entry(lte);
826         } else {
827                 if (stat(lte->staging_file_name, &stbuf) != 0) {
828                         ERROR_WITH_ERRNO("Failed to stat `%s'", lte->staging_file_name);
829                         return WIMLIB_ERR_STAT;
830                 }
831                 wimlib_assert(&lte->file_on_disk == &lte->staging_file_name);
832                 lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
833                 copy_hash(lte->hash, hash);
834                 lte->resource_entry.original_size = stbuf.st_size;
835                 lte->resource_entry.size = stbuf.st_size;
836                 lookup_table_insert(table, lte);
837         }
838
839         return 0;
840 }
841
842 /* Overwrites the WIM file, with changes saved. */
843 static int rebuild_wim(WIMStruct *w, bool check_integrity)
844 {
845         int ret;
846         struct lookup_table_entry *lte, *tmp;
847
848         /* Close all the staging file descriptors. */
849         DEBUG("Closing all staging file descriptors.");
850         list_for_each_entry(lte, &staging_list, staging_list) {
851                 ret = close_lte_fds(lte);
852                 if (ret != 0)
853                         return ret;
854         }
855
856         /* Calculate SHA1 checksums for all staging files, and merge unnecessary
857          * lookup table entries. */
858         DEBUG("Calculating SHA1 checksums for all new staging files.");
859         list_for_each_entry_safe(lte, tmp, &staging_list, staging_list) {
860                 ret = update_lte_of_staging_file(lte, w->lookup_table);
861                 if (ret != 0)
862                         return ret;
863         }
864         if (ret != 0)
865                 return ret;
866
867         xml_update_image_info(w, w->current_image);
868
869         ret = wimlib_overwrite(w, check_integrity);
870         if (ret != 0) {
871                 ERROR("Failed to commit changes");
872                 return ret;
873         }
874         return ret;
875 }
876
877 /* Called when the filesystem is unmounted. */
878 static void wimfs_destroy(void *p)
879 {
880         /* For read-write mounts, the `imagex unmount' command, which is
881          * running in a separate process and is executing the
882          * wimlib_unmount() function, will send this process a byte
883          * through a message queue that indicates whether the --commit
884          * option was specified or not. */
885
886         int msgsize;
887         struct timespec timeout;
888         struct timeval now;
889         ssize_t bytes_received;
890         int ret;
891         char commit;
892         char check_integrity;
893         char status;
894
895         ret = open_message_queues(true);
896         if (ret != 0)
897                 exit(1);
898
899         msgsize = mq_get_msgsize(unmount_to_daemon_mq);
900         char msg[msgsize];
901         msg[0] = 0;
902         msg[1] = 0;
903
904         /* Wait at most 3 seconds before giving up and discarding changes. */
905         gettimeofday(&now, NULL);
906         timeout.tv_sec = now.tv_sec + 3;
907         timeout.tv_nsec = now.tv_usec * 1000;
908         DEBUG("Waiting for message telling us whether to commit or not, and "
909               "whether to include integrity checks.");
910
911         bytes_received = mq_timedreceive(unmount_to_daemon_mq, msg, 
912                                          msgsize, NULL, &timeout);
913         commit = msg[0];
914         check_integrity = msg[1];
915         if (bytes_received == -1) {
916                 if (errno == ETIMEDOUT) {
917                         ERROR("Timed out.");
918                 } else {
919                         ERROR_WITH_ERRNO("mq_timedreceive()");
920                 }
921                 ERROR("Not committing.");
922         } else {
923                 DEBUG("Received message: [%d %d]", msg[0], msg[1]);
924         }
925
926         status = 0;
927         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
928                 if (commit) {
929                         status = chdir(working_directory);
930                         if (status != 0) {
931                                 ERROR_WITH_ERRNO("chdir()");
932                                 status = WIMLIB_ERR_NOTDIR;
933                                 goto done;
934                         }
935                         status = rebuild_wim(w, (check_integrity != 0));
936                 }
937                 ret = delete_staging_dir();
938                 if (ret != 0) {
939                         ERROR_WITH_ERRNO("Failed to delete the staging "
940                                          "directory");
941                         if (status == 0)
942                                 status = ret;
943                 }
944         } else {
945                 DEBUG("Read-only mount");
946         }
947 done:
948         DEBUG("Sending status %u", status);
949         ret = mq_send(daemon_to_unmount_mq, &status, 1, 1);
950         if (ret == -1)
951                 ERROR_WITH_ERRNO("Failed to send status to unmount process");
952         close_message_queues();
953 }
954
955 static int wimfs_fallocate(const char *path, int mode,
956                            off_t offset, off_t len, struct fuse_file_info *fi)
957 {
958         struct wimlib_fd *fd = (struct wimlib_fd*)fi->fh;
959         wimlib_assert(fd->staging_fd != -1);
960         return fallocate(fd->staging_fd, mode, offset, len);
961 }
962
963 static int wimfs_fgetattr(const char *path, struct stat *stbuf,
964                           struct fuse_file_info *fi)
965 {
966         struct wimlib_fd *fd = (struct wimlib_fd*)fi->fh;
967         return dentry_to_stbuf(fd->dentry, stbuf);
968 }
969
970 static int wimfs_ftruncate(const char *path, off_t size,
971                            struct fuse_file_info *fi)
972 {
973         struct wimlib_fd *fd = (struct wimlib_fd*)fi->fh;
974         int ret = ftruncate(fd->staging_fd, size);
975         if (ret != 0)
976                 return ret;
977         fd->lte->resource_entry.original_size = size;
978         return 0;
979 }
980
981 /*
982  * Fills in a `struct stat' that corresponds to a file or directory in the WIM.
983  */
984 static int wimfs_getattr(const char *path, struct stat *stbuf)
985 {
986         const char *stream_name;
987         char *p = NULL;
988         struct dentry *dentry;
989         int ret;
990
991         ret = lookup_resource(w, path, get_lookup_flags(), &dentry, NULL, NULL);
992         if (ret != 0)
993                 return ret;
994         return dentry_to_stbuf(dentry, stbuf);
995 }
996
997 /* Read an alternate data stream through the XATTR interface, or get its size */
998 static int wimfs_getxattr(const char *path, const char *name, char *value,
999                           size_t size)
1000 {
1001         int ret;
1002         struct dentry *dentry;
1003         struct ads_entry *ads_entry;
1004         size_t res_size;
1005         struct lookup_table_entry *lte;
1006
1007         if (!(mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1008                 return -ENOTSUP;
1009
1010         if (memcmp(name, "user.", 5) != 0)
1011                 return -ENOATTR;
1012         name += 5;
1013
1014         dentry = get_dentry(w, path);
1015         if (!dentry)
1016                 return -ENOENT;
1017         ads_entry = dentry_get_ads_entry(dentry, name);
1018         if (!ads_entry)
1019                 return -ENOATTR;
1020
1021         lte = ads_entry->lte;
1022         res_size = wim_resource_size(lte);
1023
1024         if (size == 0)
1025                 return res_size;
1026         if (res_size > size)
1027                 return -ERANGE;
1028         ret = read_full_wim_resource(lte, value);
1029         if (ret != 0)
1030                 return -EIO;
1031         return res_size;
1032 }
1033
1034 /* Create a hard link */
1035 static int wimfs_link(const char *to, const char *from)
1036 {
1037         struct dentry *to_dentry, *from_dentry, *from_dentry_parent;
1038         const char *link_name;
1039
1040         to_dentry = get_dentry(w, to);
1041         if (!to_dentry)
1042                 return -ENOENT;
1043         if (!dentry_is_regular_file(to_dentry))
1044                 return -EPERM;
1045
1046         from_dentry_parent = get_parent_dentry(w, from);
1047         if (!from_dentry_parent)
1048                 return -ENOENT;
1049         if (!dentry_is_directory(from_dentry_parent))
1050                 return -ENOTDIR;
1051
1052         link_name = path_basename(from);
1053         if (get_dentry_child_with_name(from_dentry_parent, link_name))
1054                 return -EEXIST;
1055         from_dentry = clone_dentry(to_dentry);
1056         if (!from_dentry)
1057                 return -ENOMEM;
1058         if (change_dentry_name(from_dentry, link_name) != 0) {
1059                 FREE(from_dentry);
1060                 return -ENOMEM;
1061         }
1062
1063         /* Add the new dentry to the dentry list for the link group */
1064         list_add(&from_dentry->link_group_list, &to_dentry->link_group_list);
1065
1066         /* Increment reference counts for the unnamed file stream and all
1067          * alternate data streams. */
1068         if (from_dentry->lte) {
1069                 list_add(&from_dentry->lte_group_list.list,
1070                          &to_dentry->lte_group_list.list);
1071                 from_dentry->lte->refcnt++;
1072         }
1073         for (u16 i = 0; i < from_dentry->num_ads; i++) {
1074                 struct ads_entry *ads_entry = &from_dentry->ads_entries[i];
1075                 if (ads_entry->lte)
1076                         ads_entry->lte->refcnt++;
1077         }
1078
1079         /* The ADS entries are owned by another dentry. */
1080         from_dentry->ads_entries_status = ADS_ENTRIES_USER;
1081
1082         link_dentry(from_dentry, from_dentry_parent);
1083         return 0;
1084 }
1085
1086 static int wimfs_listxattr(const char *path, char *list, size_t size)
1087 {
1088         struct dentry *dentry;
1089         int ret;
1090         char *p = list;
1091         size_t needed_size;
1092         unsigned i;
1093         if (!(mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1094                 return -ENOTSUP;
1095
1096         /* List alternate data streams, or get the list size */
1097
1098         ret = lookup_resource(w, path, get_lookup_flags(), &dentry, NULL, NULL);
1099         if (ret != 0)
1100                 return ret;
1101         if (size == 0) {
1102                 needed_size = 0;
1103                 for (i = 0; i < dentry->num_ads; i++)
1104                         needed_size += dentry->ads_entries[i].stream_name_utf8_len + 6;
1105                 return needed_size;
1106         } else {
1107                 for (i = 0; i < dentry->num_ads; i++) {
1108                         needed_size = dentry->ads_entries[i].stream_name_utf8_len + 6;
1109                         if (needed_size > size)
1110                                 return -ERANGE;
1111                         p += sprintf(p, "user.%s",
1112                                      dentry->ads_entries[i].stream_name_utf8) + 1;
1113                         size -= needed_size;
1114                 }
1115                 return p - list;
1116         }
1117 }
1118
1119 /* 
1120  * Create a directory in the WIM.  
1121  * @mode is currently ignored.
1122  */
1123 static int wimfs_mkdir(const char *path, mode_t mode)
1124 {
1125         struct dentry *parent;
1126         struct dentry *newdir;
1127         const char *basename;
1128         
1129         parent = get_parent_dentry(w, path);
1130         if (!parent)
1131                 return -ENOENT;
1132
1133         if (!dentry_is_directory(parent))
1134                 return -ENOTDIR;
1135
1136         basename = path_basename(path);
1137         if (get_dentry_child_with_name(parent, basename))
1138                 return -EEXIST;
1139
1140         newdir = new_dentry(basename);
1141         newdir->attributes |= FILE_ATTRIBUTE_DIRECTORY;
1142         newdir->resolved = true;
1143         newdir->hard_link = next_link_group_id++;
1144         link_dentry(newdir, parent);
1145         return 0;
1146 }
1147
1148
1149 /* Creates a regular file. */
1150 static int wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
1151 {
1152         const char *stream_name;
1153         const char *file_name;
1154         if ((mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
1155              && (stream_name = path_stream_name(path))) {
1156                 /* Make an alternate data stream */
1157                 struct ads_entry *new_entry;
1158                 struct dentry *dentry;
1159
1160                 char *p = (char*)stream_name - 1;
1161                 wimlib_assert(*p == ':');
1162                 *p = '\0';
1163
1164                 dentry = get_dentry(w, path);
1165                 if (!dentry || !dentry_is_regular_file(dentry))
1166                         return -ENOENT;
1167                 if (dentry_get_ads_entry(dentry, stream_name))
1168                         return -EEXIST;
1169                 new_entry = dentry_add_ads(dentry, stream_name);
1170                 if (!new_entry)
1171                         return -ENOENT;
1172         } else {
1173                 struct dentry *dentry, *parent;
1174                 const char *basename;
1175
1176                 /* Make a normal file (not an alternate data stream) */
1177
1178                 /* Make sure that the parent of @path exists and is a directory, and
1179                  * that the dentry named by @path does not already exist.  */
1180                 parent = get_parent_dentry(w, path);
1181                 if (!parent)
1182                         return -ENOENT;
1183                 if (!dentry_is_directory(parent))
1184                         return -ENOTDIR;
1185
1186                 basename = path_basename(path);
1187                 if (get_dentry_child_with_name(parent, path))
1188                         return -EEXIST;
1189
1190                 dentry = new_dentry(basename);
1191                 if (!dentry)
1192                         return -ENOMEM;
1193                 dentry->resolved = true;
1194                 dentry->hard_link = next_link_group_id++;
1195                 dentry->lte_group_list.type = STREAM_TYPE_NORMAL;
1196                 INIT_LIST_HEAD(&dentry->lte_group_list.list);
1197                 link_dentry(dentry, parent);
1198         }
1199         return 0;
1200 }
1201
1202
1203 /* Open a file.  */
1204 static int wimfs_open(const char *path, struct fuse_file_info *fi)
1205 {
1206         struct dentry *dentry;
1207         struct lookup_table_entry *lte;
1208         u8 *dentry_hash;
1209         int ret;
1210         struct wimlib_fd *fd;
1211         unsigned stream_idx;
1212
1213         ret = lookup_resource(w, path, get_lookup_flags(), &dentry, &lte,
1214                               &stream_idx);
1215         if (ret != 0)
1216                 return ret;
1217
1218         if (!lte) {
1219                 /* Empty file with no lookup-table entry.  This is fine if it's
1220                  * a read-only filesystem.  Otherwise we need to create a lookup
1221                  * table entry so that we can keep track of the file descriptors
1222                  * (this is important in case someone opens the file for
1223                  * writing) */
1224                 if (!(mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
1225                         fi->fh = 0;
1226                         return 0;
1227                 }
1228
1229                 ret = extract_resource_to_staging_dir(dentry, stream_idx,
1230                                                       &lte, 0);
1231                 if (ret != 0)
1232                         return ret;
1233         }
1234
1235         ret = alloc_wimlib_fd(lte, &fd);
1236         if (ret != 0)
1237                 return ret;
1238
1239         fd->dentry = dentry;
1240
1241         /* The file resource may be in the staging directory (read-write
1242          * mounts only) or in the WIM.  If it's in the staging
1243          * directory, we need to open a native file descriptor for the
1244          * corresponding file.  Otherwise, we can read the file resource
1245          * directly from the WIM file if we are opening it read-only,
1246          * but we need to extract the resource to the staging directory
1247          * if we are opening it writable. */
1248         if (flags_writable(fi->flags) &&
1249               lte->resource_location != RESOURCE_IN_STAGING_FILE) {
1250                 ret = extract_resource_to_staging_dir(dentry, stream_idx, &lte,
1251                                                       lte->resource_entry.original_size);
1252                 if (ret != 0)
1253                         return ret;
1254         }
1255         if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1256                 fd->staging_fd = open(lte->staging_file_name, fi->flags);
1257                 if (fd->staging_fd == -1) {
1258                         close_wimlib_fd(fd);
1259                         return -errno;
1260                 }
1261         }
1262         fi->fh = (uint64_t)fd;
1263         return 0;
1264 }
1265
1266 /* Opens a directory. */
1267 static int wimfs_opendir(const char *path, struct fuse_file_info *fi)
1268 {
1269         struct dentry *dentry;
1270         
1271         dentry = get_dentry(w, path);
1272         if (!dentry)
1273                 return -ENOENT;
1274         if (!dentry_is_directory(dentry))
1275                 return -ENOTDIR;
1276         dentry->num_times_opened++;
1277         fi->fh = (uint64_t)dentry;
1278         return 0;
1279 }
1280
1281
1282 /*
1283  * Read data from a file in the WIM or in the staging directory. 
1284  */
1285 static int wimfs_read(const char *path, char *buf, size_t size, 
1286                       off_t offset, struct fuse_file_info *fi)
1287 {
1288         struct wimlib_fd *fd = (struct wimlib_fd*)fi->fh;
1289
1290         if (!fd) {
1291                 /* Empty file with no lookup table entry on read-only mounted
1292                  * WIM */
1293                 wimlib_assert(!(mount_flags & WIMLIB_MOUNT_FLAG_READWRITE));
1294                 return 0;
1295         }
1296
1297         wimlib_assert(fd->lte);
1298
1299         if (fd->lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1300                 /* Read from staging file */
1301
1302                 wimlib_assert(fd->lte->staging_file_name);
1303                 wimlib_assert(fd->staging_fd != -1);
1304
1305                 ssize_t ret;
1306                 DEBUG("Seek to offset %zu", offset);
1307
1308                 if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1309                         return -errno;
1310                 ret = read(fd->staging_fd, buf, size);
1311                 if (ret == -1)
1312                         return -errno;
1313                 return ret;
1314         } else {
1315                 /* Read from WIM */
1316
1317                 const struct resource_entry *res_entry;
1318                 
1319                 res_entry = &fd->lte->resource_entry;
1320
1321                 if (offset > res_entry->original_size)
1322                         return -EOVERFLOW;
1323
1324                 size = min(size, res_entry->original_size - offset);
1325
1326                 if (read_wim_resource(fd->lte, buf, size, offset, false) != 0)
1327                         return -EIO;
1328                 return size;
1329         }
1330 }
1331
1332 /* Fills in the entries of the directory specified by @path using the
1333  * FUSE-provided function @filler.  */
1334 static int wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, 
1335                          off_t offset, struct fuse_file_info *fi)
1336 {
1337         struct dentry *parent, *child;
1338         
1339         parent = (struct dentry*)fi->fh;
1340         wimlib_assert(parent);
1341         child = parent->children;
1342
1343         filler(buf, ".", NULL, 0);
1344         filler(buf, "..", NULL, 0);
1345
1346         if (!child)
1347                 return 0;
1348
1349         do {
1350                 if (filler(buf, child->file_name_utf8, NULL, 0))
1351                         return 0;
1352                 child = child->next;
1353         } while (child != parent->children);
1354         return 0;
1355 }
1356
1357
1358 static int wimfs_readlink(const char *path, char *buf, size_t buf_len)
1359 {
1360         struct dentry *dentry = get_dentry(w, path);
1361         int ret;
1362         if (!dentry)
1363                 return -ENOENT;
1364         if (!dentry_is_symlink(dentry))
1365                 return -EINVAL;
1366
1367         ret = dentry_readlink(dentry, buf, buf_len, w);
1368         if (ret > 0)
1369                 ret = 0;
1370         return ret;
1371 }
1372
1373 /* Close a file. */
1374 static int wimfs_release(const char *path, struct fuse_file_info *fi)
1375 {
1376         int ret;
1377         struct wimlib_fd *fd = (struct wimlib_fd*)fi->fh;
1378
1379         if (!fd) {
1380                 /* Empty file with no lookup table entry on read-only mounted
1381                  * WIM */
1382                 wimlib_assert(!(mount_flags & WIMLIB_MOUNT_FLAG_READWRITE));
1383                 return 0;
1384         }
1385
1386         if (flags_writable(fi->flags) && fd->dentry) {
1387                 u64 now = get_wim_timestamp();
1388                 fd->dentry->last_access_time = now;
1389                 fd->dentry->last_write_time = now;
1390         }
1391
1392         return close_wimlib_fd(fd);
1393 }
1394
1395 static int wimfs_releasedir(const char *path, struct fuse_file_info *fi)
1396 {
1397         struct dentry *dentry = (struct dentry *)fi->fh;
1398
1399         wimlib_assert(dentry);
1400         wimlib_assert(dentry->num_times_opened);
1401         if (--dentry->num_times_opened == 0)
1402                 free_dentry(dentry);
1403         return 0;
1404 }
1405
1406 /* Remove an alternate data stream through the XATTR interface */
1407 static int wimfs_removexattr(const char *path, const char *name)
1408 {
1409         struct dentry *dentry;
1410         struct ads_entry *ads_entry;
1411         int ret;
1412         if (!(mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1413                 return -ENOTSUP;
1414
1415         if (memcmp(name, "user.", 5) != 0)
1416                 return -ENOATTR;
1417         name += 5;
1418
1419         dentry = get_dentry(w, path);
1420         if (!dentry)
1421                 return -ENOENT;
1422
1423         ads_entry = dentry_get_ads_entry(dentry, name);
1424         if (!ads_entry)
1425                 return -ENOATTR;
1426         remove_ads(dentry, ads_entry, w->lookup_table);
1427         return 0;
1428 }
1429
1430 /* Renames a file or directory.  See rename (3) */
1431 static int wimfs_rename(const char *from, const char *to)
1432 {
1433         struct dentry *src;
1434         struct dentry *dst;
1435         struct dentry *parent_of_dst;
1436         char *file_name_utf16 = NULL, *file_name_utf8 = NULL;
1437         u16 file_name_utf16_len, file_name_utf8_len;
1438         int ret;
1439
1440         /* This rename() implementation currently only supports actual files
1441          * (not alternate data streams) */
1442         
1443         src = get_dentry(w, from);
1444         if (!src)
1445                 return -ENOENT;
1446
1447         dst = get_dentry(w, to);
1448
1449
1450         ret = get_names(&file_name_utf16, &file_name_utf8,
1451                         &file_name_utf16_len, &file_name_utf8_len,
1452                         path_basename(to));
1453         if (ret != 0)
1454                 return -ENOMEM;
1455
1456         if (dst) {
1457                 /* Destination file exists */
1458
1459                 if (src == dst) /* Same file */
1460                         return 0;
1461
1462                 if (!dentry_is_directory(src)) {
1463                         /* Cannot rename non-directory to directory. */
1464                         if (dentry_is_directory(dst))
1465                                 return -EISDIR;
1466                 } else {
1467                         /* Cannot rename directory to a non-directory or a non-empty
1468                          * directory */
1469                         if (!dentry_is_directory(dst))
1470                                 return -ENOTDIR;
1471                         if (dst->children != NULL)
1472                                 return -ENOTEMPTY;
1473                 }
1474                 parent_of_dst = dst->parent;
1475                 remove_dentry(dst, w->lookup_table);
1476         } else {
1477                 /* Destination does not exist */
1478                 parent_of_dst = get_parent_dentry(w, to);
1479                 if (!parent_of_dst)
1480                         return -ENOENT;
1481
1482                 if (!dentry_is_directory(parent_of_dst))
1483                         return -ENOTDIR;
1484         }
1485
1486         FREE(src->file_name);
1487         FREE(src->file_name_utf8);
1488         src->file_name          = file_name_utf16;
1489         src->file_name_utf8     = file_name_utf8;
1490         src->file_name_len      = file_name_utf16_len;
1491         src->file_name_utf8_len = file_name_utf8_len;
1492
1493         unlink_dentry(src);
1494         link_dentry(src, parent_of_dst);
1495         return 0;
1496 }
1497
1498 /* Remove a directory */
1499 static int wimfs_rmdir(const char *path)
1500 {
1501         struct dentry *dentry;
1502         
1503         dentry = get_dentry(w, path);
1504         if (!dentry)
1505                 return -ENOENT;
1506
1507         if (!dentry_is_empty_directory(dentry))
1508                 return -ENOTEMPTY;
1509
1510         unlink_dentry(dentry);
1511         if (dentry->num_times_opened == 0)
1512                 free_dentry(dentry);
1513         return 0;
1514 }
1515
1516 /* Write an alternate data stream through the XATTR interface */
1517 static int wimfs_setxattr(const char *path, const char *name,
1518                           const char *value, size_t size, int flags)
1519 {
1520         struct dentry *dentry;
1521         struct ads_entry *existing_ads_entry;
1522         struct ads_entry *new_ads_entry;
1523         struct lookup_table_entry *existing_lte;
1524         struct lookup_table_entry *lte;
1525         u8 value_hash[SHA1_HASH_SIZE];
1526         int ret;
1527         int fd;
1528
1529         if (!(mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1530                 return -ENOTSUP;
1531
1532         dentry = get_dentry(w, path);
1533         if (!dentry)
1534                 return -ENOENT;
1535         existing_ads_entry = dentry_get_ads_entry(dentry, name);
1536         if (existing_ads_entry) {
1537                 if (flags & XATTR_CREATE)
1538                         return -EEXIST;
1539                 remove_ads(dentry, existing_ads_entry, w->lookup_table);
1540         } else {
1541                 if (flags & XATTR_REPLACE)
1542                         return -ENOATTR;
1543         }
1544         new_ads_entry = dentry_add_ads(dentry, name);
1545         if (!new_ads_entry)
1546                 return -ENOMEM;
1547
1548         sha1_buffer(value, size, value_hash);
1549
1550         existing_lte = __lookup_resource(w->lookup_table, value_hash);
1551
1552         if (existing_lte) {
1553                 lte = existing_lte;
1554                 lte->refcnt++;
1555         } else {
1556                 char *value_copy;
1557                 lte = new_lookup_table_entry();
1558                 if (!lte)
1559                         return -ENOMEM;
1560                 value_copy = MALLOC(size);
1561                 if (!value_copy) {
1562                         FREE(lte);
1563                         return -ENOMEM;
1564                 }
1565                 lte->resource_location            = RESOURCE_IN_ATTACHED_BUFFER;
1566                 lte->attached_buffer              = value_copy;
1567                 lte->resource_entry.original_size = size;
1568                 lte->resource_entry.size          = size;
1569                 lte->resource_entry.flags         = 0;
1570                 copy_hash(lte->hash, value_hash);
1571                 lookup_table_insert(w->lookup_table, lte);
1572         }
1573         new_ads_entry->lte = lte;
1574         return 0;
1575 }
1576
1577 static int wimfs_symlink(const char *to, const char *from)
1578 {
1579         struct dentry *dentry_parent, *dentry;
1580         const char *link_name;
1581         struct lookup_table_entry *lte;
1582         
1583         dentry_parent = get_parent_dentry(w, from);
1584         if (!dentry_parent)
1585                 return -ENOENT;
1586         if (!dentry_is_directory(dentry_parent))
1587                 return -ENOTDIR;
1588
1589         link_name = path_basename(from);
1590
1591         if (get_dentry_child_with_name(dentry_parent, link_name))
1592                 return -EEXIST;
1593         dentry = new_dentry(link_name);
1594         if (!dentry)
1595                 return -ENOMEM;
1596
1597         dentry->attributes = FILE_ATTRIBUTE_REPARSE_POINT;
1598         dentry->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
1599         dentry->hard_link = next_link_group_id++;
1600
1601         if (dentry_set_symlink(dentry, to, w->lookup_table, &lte) != 0)
1602                 goto out_free_dentry;
1603
1604         wimlib_assert(lte);
1605
1606         dentry->ads_entries[1].lte_group_list.type = STREAM_TYPE_ADS;
1607         list_add(&dentry->ads_entries[1].lte_group_list.list,
1608                  &lte->lte_group_list);
1609         wimlib_assert(dentry->resolved);
1610
1611         link_dentry(dentry, dentry_parent);
1612         return 0;
1613 out_free_dentry:
1614         free_dentry(dentry);
1615         return -ENOMEM;
1616 }
1617
1618
1619 /* Reduce the size of a file */
1620 static int wimfs_truncate(const char *path, off_t size)
1621 {
1622         struct dentry *dentry;
1623         struct lookup_table_entry *lte;
1624         int ret;
1625         unsigned stream_idx;
1626         
1627         ret = lookup_resource(w, path, get_lookup_flags(), &dentry,
1628                               &lte, &stream_idx);
1629
1630         if (ret != 0)
1631                 return ret;
1632
1633         if (!lte) /* Already a zero-length file */
1634                 return 0;
1635
1636         if (lte->staging_file_name) {
1637                 ret = truncate(lte->staging_file_name, size);
1638                 if (ret != 0)
1639                         return -errno;
1640                 lte->resource_entry.original_size = size;
1641         } else {
1642                 /* File in WIM.  Extract it to the staging directory, but only
1643                  * the first @size bytes of it. */
1644                 ret = extract_resource_to_staging_dir(dentry, stream_idx,
1645                                                       &lte, size);
1646         }
1647         dentry_update_all_timestamps(dentry);
1648         return ret;
1649 }
1650
1651 /* Remove a regular file */
1652 static int wimfs_unlink(const char *path)
1653 {
1654         struct dentry *dentry;
1655         struct lookup_table_entry *lte;
1656         int ret;
1657         u8 *dentry_hash;
1658         unsigned stream_idx;
1659         
1660         ret = lookup_resource(w, path, get_lookup_flags(), &dentry,
1661                               &lte, &stream_idx);
1662
1663         if (ret != 0)
1664                 return ret;
1665
1666         if (stream_idx == 0) {
1667                 /* We are removing the full dentry including all alternate data
1668                  * streams. */
1669                 remove_dentry(dentry, w->lookup_table);
1670         } else {
1671                 /* We are removing an alternate data stream. */
1672                 remove_ads(dentry, &dentry->ads_entries[stream_idx - 1],
1673                            w->lookup_table);
1674         }
1675         /* Beware: The lookup table entry(s) may still be referenced by users
1676          * that have opened the corresponding streams.  They are freed later in
1677          * wimfs_release() when the last file user has closed the stream. */
1678         return 0;
1679 }
1680
1681 /* 
1682  * Change the timestamp on a file dentry. 
1683  *
1684  * Note that alternate data streams do not have their own timestamps.
1685  */
1686 static int wimfs_utimens(const char *path, const struct timespec tv[2])
1687 {
1688         struct dentry *dentry = get_dentry(w, path);
1689         if (!dentry)
1690                 return -ENOENT;
1691         if (tv[0].tv_nsec != UTIME_OMIT) {
1692                 if (tv[0].tv_nsec == UTIME_NOW)
1693                         dentry->last_access_time = get_wim_timestamp();
1694                 else
1695                         dentry->last_access_time = timespec_to_wim_timestamp(&tv[0]);
1696         }
1697         if (tv[1].tv_nsec != UTIME_OMIT) {
1698                 if (tv[1].tv_nsec == UTIME_NOW)
1699                         dentry->last_write_time = get_wim_timestamp();
1700                 else
1701                         dentry->last_write_time = timespec_to_wim_timestamp(&tv[1]);
1702         }
1703         return 0;
1704 }
1705
1706 /* Writes to a file in the WIM filesystem. 
1707  * It may be an alternate data stream, but here we don't even notice because we
1708  * just get a lookup table entry. */
1709 static int wimfs_write(const char *path, const char *buf, size_t size, 
1710                        off_t offset, struct fuse_file_info *fi)
1711 {
1712         struct wimlib_fd *fd = (struct wimlib_fd*)fi->fh;
1713         int ret;
1714
1715         wimlib_assert(fd);
1716         wimlib_assert(fd->lte);
1717         wimlib_assert(fd->lte->staging_file_name);
1718         wimlib_assert(fd->staging_fd != -1);
1719
1720         /* Seek to the requested position */
1721         if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1722                 return -errno;
1723
1724         /* Write the data. */
1725         ret = write(fd->staging_fd, buf, size);
1726         if (ret == -1)
1727                 return -errno;
1728
1729         return ret;
1730 }
1731
1732 static struct fuse_operations wimfs_operations = {
1733         .access      = wimfs_access,
1734         .destroy     = wimfs_destroy,
1735         .fallocate   = wimfs_fallocate,
1736         .fgetattr    = wimfs_fgetattr,
1737         .ftruncate   = wimfs_ftruncate,
1738         .getattr     = wimfs_getattr,
1739         .getxattr    = wimfs_getxattr,
1740         .link        = wimfs_link,
1741         .listxattr   = wimfs_listxattr,
1742         .mkdir       = wimfs_mkdir,
1743         .mknod       = wimfs_mknod,
1744         .open        = wimfs_open,
1745         .opendir     = wimfs_opendir,
1746         .read        = wimfs_read,
1747         .readdir     = wimfs_readdir,
1748         .readlink    = wimfs_readlink,
1749         .release     = wimfs_release,
1750         .releasedir  = wimfs_releasedir,
1751         .removexattr = wimfs_removexattr,
1752         .rename      = wimfs_rename,
1753         .rmdir       = wimfs_rmdir,
1754         .setxattr    = wimfs_setxattr,
1755         .symlink     = wimfs_symlink,
1756         .truncate    = wimfs_truncate,
1757         .unlink      = wimfs_unlink,
1758         .utimens     = wimfs_utimens,
1759         .write       = wimfs_write,
1760 };
1761
1762
1763 static int check_lte_refcnt(struct lookup_table_entry *lte, void *ignore)
1764 {
1765         size_t lte_group_size = 0;
1766         struct list_head *cur;
1767         list_for_each(cur, &lte->lte_group_list)
1768                 lte_group_size++;
1769         if (lte_group_size > lte->refcnt) {
1770 #ifdef ENABLE_ERROR_MESSAGES
1771                 ERROR("The following lookup table entry has a reference count "
1772                       "of %u, but", lte->refcnt);
1773                 ERROR("We found %u references to it", lte_group_size);
1774                 print_lookup_table_entry(lte);
1775 #endif
1776                 return WIMLIB_ERR_INVALID_DENTRY;
1777         }
1778         return 0;
1779 }
1780
1781 /* Mounts a WIM file. */
1782 WIMLIBAPI int wimlib_mount(WIMStruct *wim, int image, const char *dir, 
1783                            int flags)
1784 {
1785         int argc = 0;
1786         char *argv[16];
1787         int ret;
1788         char *p;
1789
1790         DEBUG("Mount: wim = %p, image = %d, dir = %s, flags = %d, ",
1791                         wim, image, dir, flags);
1792
1793         if (!dir)
1794                 return WIMLIB_ERR_INVALID_PARAM;
1795
1796         ret = wimlib_select_image(wim, image);
1797
1798         if (ret != 0)
1799                 return ret;
1800
1801         DEBUG("Selected image %d", image);
1802
1803         next_link_group_id = assign_link_groups(wim->image_metadata[image - 1].lgt);
1804
1805         /* Resolve all the lookup table entries of the dentry tree */
1806         for_dentry_in_tree(wim_root_dentry(wim), dentry_resolve_ltes,
1807                            wim->lookup_table);
1808
1809         ret = for_lookup_table_entry(wim->lookup_table, check_lte_refcnt, NULL);
1810         if (ret != 0)
1811                 return ret;
1812
1813         if (flags & WIMLIB_MOUNT_FLAG_READWRITE)
1814                 wim_get_current_image_metadata(wim)->modified = true;
1815
1816         if (!(flags & (WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
1817                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
1818                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)))
1819                 flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
1820
1821         mount_dir = dir;
1822         working_directory = getcwd(NULL, 0);
1823         if (!working_directory) {
1824                 ERROR_WITH_ERRNO("Could not determine current directory");
1825                 return WIMLIB_ERR_NOTDIR;
1826         }
1827
1828         p = STRDUP(dir);
1829         if (!p)
1830                 return WIMLIB_ERR_NOMEM;
1831
1832         argv[argc++] = "imagex";
1833         argv[argc++] = p;
1834         argv[argc++] = "-s"; /* disable multi-threaded operation */
1835
1836         if (flags & WIMLIB_MOUNT_FLAG_DEBUG)
1837                 argv[argc++] = "-d";
1838
1839         /* 
1840          * We provide the use_ino option because we are going to assign inode
1841          * numbers oursides.  We've already numbered the hard link groups with
1842          * unique numbers with the assign_link_groups() function, and the static
1843          * variable next_link_group_id is set to the next available link group
1844          * ID that we will assign to new dentries.
1845          */
1846         char optstring[256] = "use_ino";
1847         argv[argc++] = "-o";
1848         argv[argc++] = optstring;
1849         if ((flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
1850                 /* Read-write mount.  Make the staging directory */
1851                 make_staging_dir();
1852                 if (!staging_dir_name) {
1853                         FREE(p);
1854                         return WIMLIB_ERR_MKDIR;
1855                 }
1856         } else {
1857                 /* Read-only mount */
1858                 strcat(optstring, ",ro");
1859         }
1860         argv[argc] = NULL;
1861
1862 #ifdef ENABLE_DEBUG
1863         {
1864                 int i;
1865                 DEBUG("FUSE command line (argc = %d): ", argc);
1866                 for (i = 0; i < argc; i++) {
1867                         fputs(argv[i], stdout);
1868                         putchar(' ');
1869                 }
1870                 putchar('\n');
1871                 fflush(stdout);
1872         }
1873 #endif
1874
1875         /* Set static variables. */
1876         w = wim;
1877         mount_flags = flags;
1878
1879         ret = fuse_main(argc, argv, &wimfs_operations, NULL);
1880
1881         return (ret == 0) ? 0 : WIMLIB_ERR_FUSE;
1882 }
1883
1884
1885 /* 
1886  * Unmounts the WIM file that was previously mounted on @dir by using
1887  * wimlib_mount().
1888  */
1889 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
1890 {
1891         pid_t pid;
1892         int status;
1893         int ret;
1894         char msg[2];
1895         struct timeval now;
1896         struct timespec timeout;
1897         int msgsize;
1898         int errno_save;
1899
1900         /* Execute `fusermount -u', which is installed setuid root, to unmount
1901          * the WIM.
1902          *
1903          * FUSE does not yet implement synchronous unmounts.  This means that
1904          * fusermount -u will return before the filesystem daemon returns from
1905          * wimfs_destroy().  This is partly what we want, because we need to
1906          * send a message from this process to the filesystem daemon telling
1907          * whether --commit was specified or not.  However, after that, the
1908          * unmount process must wait for the filesystem daemon to finish writing
1909          * the WIM file. 
1910          */
1911
1912         mount_dir = dir;
1913         pid = fork();
1914         if (pid == -1) {
1915                 ERROR_WITH_ERRNO("Failed to fork()");
1916                 return WIMLIB_ERR_FORK;
1917         }
1918         if (pid == 0) {
1919                 execlp("fusermount", "fusermount", "-u", dir, NULL);
1920                 ERROR_WITH_ERRNO("Failed to execute `fusermount'");
1921                 return WIMLIB_ERR_FUSERMOUNT;
1922         }
1923
1924         ret = waitpid(pid, &status, 0);
1925         if (ret == -1) {
1926                 ERROR_WITH_ERRNO("Failed to wait for fusermount process to "
1927                                  "terminate");
1928                 return WIMLIB_ERR_FUSERMOUNT;
1929         }
1930
1931         if (status != 0) {
1932                 ERROR("fusermount exited with status %d", status);
1933                 return WIMLIB_ERR_FUSERMOUNT;
1934         }
1935
1936         /* Open message queues between the unmount process and the
1937          * filesystem daemon. */
1938         ret = open_message_queues(false);
1939         if (ret != 0)
1940                 return ret;
1941
1942         /* Send a message to the filesystem saying whether to commit or
1943          * not. */
1944         msg[0] = (flags & WIMLIB_UNMOUNT_FLAG_COMMIT) ? 1 : 0;
1945         msg[1] = (flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY) ? 1 : 0;
1946
1947         DEBUG("Sending message: %s, %s", 
1948                         (msg[0] == 0) ? "don't commit" : "commit",
1949                         (msg[1] == 0) ? "don't check"  : "check");
1950         ret = mq_send(unmount_to_daemon_mq, msg, 2, 1);
1951         if (ret == -1) {
1952                 ERROR("Failed to notify filesystem daemon whether we want to "
1953                       "commit changes or not");
1954                 close_message_queues();
1955                 return WIMLIB_ERR_MQUEUE;
1956         }
1957
1958         /* Wait for a message from the filesytem daemon indicating whether  the
1959          * filesystem was unmounted successfully (0) or an error occurred (1).
1960          * This may take a long time if a big WIM file needs to be rewritten. */
1961
1962         /* Wait at most 600??? seconds before giving up and returning false.
1963          * Either it's a really big WIM file, or (more likely) the
1964          * filesystem daemon has crashed or failed for some reason.
1965          *
1966          * XXX come up with some method to determine if the filesystem
1967          * daemon has really crashed or not. 
1968          *
1969          * XXX Idea: have mount daemon write its PID into the WIM file header?
1970          * */
1971
1972         gettimeofday(&now, NULL);
1973         timeout.tv_sec = now.tv_sec + 600;
1974         timeout.tv_nsec = now.tv_usec * 1000;
1975
1976         msgsize = mq_get_msgsize(daemon_to_unmount_mq);
1977         char mailbox[msgsize];
1978
1979         mailbox[0] = 0;
1980         DEBUG("Waiting for message telling us whether the unmount was "
1981                         "successful or not.");
1982         ret = mq_timedreceive(daemon_to_unmount_mq, mailbox, msgsize,
1983                               NULL, &timeout);
1984         errno_save = errno;
1985         close_message_queues();
1986         if (ret == -1) {
1987                 if (errno_save == ETIMEDOUT) {
1988                         ERROR("Timed out- probably the filesystem daemon "
1989                               "crashed and the WIM was not written "
1990                               "successfully.");
1991                         return WIMLIB_ERR_TIMEOUT;
1992                 } else {
1993                         ERROR("mq_receive(): %s", strerror(errno_save));
1994                         return WIMLIB_ERR_MQUEUE;
1995                 }
1996
1997         }
1998         DEBUG("Received message: %s",
1999               (mailbox[0] == 0) ?  "Unmount OK" : "Unmount Failed");
2000         if (mailbox[0] != 0)
2001                 ERROR("Unmount failed");
2002         return mailbox[0];
2003 }
2004
2005 #else /* WITH_FUSE */
2006
2007
2008 static inline int mount_unsupported_error()
2009 {
2010         ERROR("WIMLIB was compiled with --without-fuse, which disables support "
2011               "for mounting WIMs.");
2012         return WIMLIB_ERR_UNSUPPORTED;
2013 }
2014
2015 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
2016 {
2017         return mount_unsupported_error();
2018 }
2019
2020 WIMLIBAPI int wimlib_mount(WIMStruct *wim_p, int image, const char *dir, 
2021                            int flags)
2022 {
2023         return mount_unsupported_error();
2024 }
2025
2026 #endif /* WITH_FUSE */