]> wimlib.net Git - wimlib/blob - src/mount_image.c
74b751c95047e28cc1053752c08e3cd79d7dac63
[wimlib] / src / mount_image.c
1 /*
2  * mount_image.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 General Public License as published by the Free
17  * Software Foundation; either version 3 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 General Public License for more
23  * details.
24  *
25  * You should have received a copy of the GNU 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
33 #include "sha1.h"
34 #include "lookup_table.h"
35 #include "xml.h"
36 #include "buffer_io.h"
37 #include "timestamp.h"
38 #include <limits.h>
39 #include <stdlib.h>
40 #include <unistd.h>
41 #include <sys/wait.h>
42 #define FUSE_USE_VERSION 26
43 #include <errno.h>
44 #include <string.h>
45 #include <sys/time.h>
46 #include <fuse.h>
47 #include <ftw.h>
48 #include <mqueue.h>
49 #include <utime.h>
50
51 #ifdef ENABLE_XATTR
52 #include <attr/xattr.h>
53 #endif
54
55 /* File descriptor to a file open on the WIM filesystem. */
56 struct wimlib_fd {
57         struct inode *f_inode;
58         struct lookup_table_entry *f_lte;
59         int staging_fd;
60         u16 idx;
61         u32 stream_id;
62 };
63
64 struct wimfs_context {
65         /* The WIMStruct for the mounted WIM. */
66         WIMStruct *wim;
67
68         /* Name of the staging directory for a read-write mount.  Whenever a new file is
69          * created, it is done so in the staging directory.  Furthermore, whenever a
70          * file in the WIM is modified, it is extracted to the staging directory.  If
71          * changes are commited when the WIM is unmounted, the file resources are merged
72          * in from the staging directory when writing the new WIM. */
73         char *staging_dir_name;
74         size_t staging_dir_name_len;
75
76         /* Flags passed to wimlib_mount(). */
77         int mount_flags;
78
79         int default_lookup_flags;
80
81         /* Next inode number to be assigned. */
82         u64 next_ino;
83
84         /* List of lookup table entries in the staging directory */
85         struct list_head staging_list;
86
87         /* List of inodes in the mounted image */
88         struct hlist_head *image_inode_list;
89
90         /* Name and message queue descriptors for message queues between the filesystem
91          * daemon process and the unmount process.  These are used when the filesystem
92          * is unmounted and the process running wimlib_mount() (i.e. the `imagex
93          * unmount' command) needs to communicate with the filesystem daemon running
94          * fuse_main() (i.e. that spawned by the `imagex mount' or `imagex mountrw'
95          * commands */
96         char *unmount_to_daemon_mq_name;
97         char *daemon_to_unmount_mq_name;
98         mqd_t unmount_to_daemon_mq;
99         mqd_t daemon_to_unmount_mq;
100 };
101
102 static void init_wimfs_context(struct wimfs_context *ctx)
103 {
104         memset(ctx, 0, sizeof(*ctx));
105         ctx->unmount_to_daemon_mq = (mqd_t)-1;
106         ctx->daemon_to_unmount_mq = (mqd_t)-1;
107         INIT_LIST_HEAD(&ctx->staging_list);
108 }
109
110 static inline struct wimfs_context *wimfs_get_context()
111 {
112         return (struct wimfs_context*)fuse_get_context()->private_data;
113 }
114
115 static inline WIMStruct *wimfs_get_WIMStruct()
116 {
117         return wimfs_get_context()->wim;
118 }
119
120 static inline bool wimfs_ctx_readonly(const struct wimfs_context *ctx)
121 {
122         return (ctx->mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) == 0;
123 }
124
125 static inline int get_lookup_flags(const struct wimfs_context *ctx)
126 {
127         return ctx->default_lookup_flags;
128 }
129
130 /* Returns nonzero if write permission is requested on the file open flags */
131 static inline int flags_writable(int open_flags)
132 {
133         return open_flags & (O_RDWR | O_WRONLY);
134 }
135
136 /*
137  * Allocate a file descriptor for a stream.
138  *
139  * @inode:      inode containing the stream we're opening
140  * @stream_id:  ID of the stream we're opening
141  * @lte:        Lookup table entry for the stream (may be NULL)
142  * @fd_ret:     Return the allocated file descriptor if successful.
143  * @readonly:   True if this is a read-only mount.
144  *
145  * Return 0 iff successful or error code if unsuccessful.
146  */
147 static int alloc_wimlib_fd(struct inode *inode,
148                            u32 stream_id,
149                            struct lookup_table_entry *lte,
150                            struct wimlib_fd **fd_ret,
151                            bool readonly)
152 {
153         static const u16 fds_per_alloc = 8;
154         static const u16 max_fds = 0xffff;
155         int ret;
156
157         pthread_mutex_lock(&inode->i_mutex);
158
159         DEBUG("Allocating fd for stream ID %u from inode %lx (open = %u, allocated = %u)",
160               stream_id, inode->ino, inode->num_opened_fds,
161               inode->num_allocated_fds);
162
163         if (inode->num_opened_fds == inode->num_allocated_fds) {
164                 struct wimlib_fd **fds;
165                 u16 num_new_fds;
166
167                 if (inode->num_allocated_fds == max_fds) {
168                         ret = -EMFILE;
169                         goto out;
170                 }
171                 num_new_fds = min(fds_per_alloc,
172                                   max_fds - inode->num_allocated_fds);
173
174                 fds = REALLOC(inode->fds,
175                               (inode->num_allocated_fds + num_new_fds) *
176                                 sizeof(inode->fds[0]));
177                 if (!fds) {
178                         ret = -ENOMEM;
179                         goto out;
180                 }
181                 memset(&fds[inode->num_allocated_fds], 0,
182                        num_new_fds * sizeof(fds[0]));
183                 inode->fds = fds;
184                 inode->num_allocated_fds += num_new_fds;
185         }
186         for (u16 i = 0; ; i++) {
187                 if (!inode->fds[i]) {
188                         struct wimlib_fd *fd = CALLOC(1, sizeof(*fd));
189                         if (!fd) {
190                                 ret = -ENOMEM;
191                                 break;
192                         }
193                         fd->f_inode    = inode;
194                         fd->f_lte      = lte;
195                         fd->staging_fd = -1;
196                         fd->idx        = i;
197                         fd->stream_id  = stream_id;
198                         *fd_ret        = fd;
199                         inode->fds[i]  = fd;
200                         inode->num_opened_fds++;
201                         if (lte && !readonly)
202                                 lte->num_opened_fds++;
203                         DEBUG("Allocated fd (idx = %u)", fd->idx);
204                         ret = 0;
205                         break;
206                 }
207         }
208 out:
209         pthread_mutex_unlock(&inode->i_mutex);
210         return ret;
211 }
212
213 static void inode_put_fd(struct inode *inode, struct wimlib_fd *fd)
214 {
215         wimlib_assert(inode != NULL);
216
217         pthread_mutex_lock(&inode->i_mutex);
218
219         wimlib_assert(fd->f_inode == inode);
220         wimlib_assert(inode->num_opened_fds != 0);
221         wimlib_assert(fd->idx < inode->num_allocated_fds);
222         wimlib_assert(inode->fds[fd->idx] == fd);
223
224         inode->fds[fd->idx] = NULL;
225         FREE(fd);
226         if (--inode->num_opened_fds == 0 && inode->link_count == 0) {
227                 pthread_mutex_unlock(&inode->i_mutex);
228                 free_inode(inode);
229         } else {
230                 pthread_mutex_unlock(&inode->i_mutex);
231         }
232 }
233
234 static int lte_put_fd(struct lookup_table_entry *lte, struct wimlib_fd *fd)
235 {
236         wimlib_assert(fd->f_lte == lte);
237
238         if (!lte) /* Empty stream with no lookup table entry */
239                 return 0;
240
241         /* Close staging file descriptor if needed. */
242
243         if (lte->resource_location == RESOURCE_IN_STAGING_FILE
244              && fd->staging_fd != -1)
245         {
246                 if (close(fd->staging_fd) != 0) {
247                         ERROR_WITH_ERRNO("Failed to close staging file");
248                         return -errno;
249                 }
250         }
251         lte_decrement_num_opened_fds(lte);
252         return 0;
253 }
254
255 /* Close a file descriptor. */
256 static int close_wimlib_fd(struct wimlib_fd *fd)
257 {
258         int ret;
259         DEBUG("Closing fd (inode = %lu, opened = %u, allocated = %u)",
260               fd->f_inode->ino, fd->f_inode->num_opened_fds,
261               fd->f_inode->num_allocated_fds);
262         ret = lte_put_fd(fd->f_lte, fd);
263         if (ret != 0)
264                 return ret;
265
266         inode_put_fd(fd->f_inode, fd);
267         return 0;
268 }
269
270 static int create_dentry(struct wimfs_context *ctx, const char *path,
271                          struct dentry **dentry_ret)
272 {
273         struct dentry *parent;
274         struct dentry *new;
275         const char *basename;
276
277         parent = get_parent_dentry(ctx->wim, path);
278         if (!parent)
279                 return -ENOENT;
280
281         if (!dentry_is_directory(parent))
282                 return -ENOTDIR;
283
284         basename = path_basename(path);
285         if (get_dentry_child_with_name(parent, basename))
286                 return -EEXIST;
287
288         new = new_dentry_with_inode(basename);
289         if (!new)
290                 return -ENOMEM;
291
292         new->d_inode->resolved = 1;
293         new->d_inode->ino = ctx->next_ino++;
294         dentry_add_child(parent, new);
295         hlist_add_head(&new->d_inode->hlist, ctx->image_inode_list);
296         *dentry_ret = new;
297         return 0;
298 }
299
300 /* Remove a dentry; i.e. remove a reference to the corresponding inode.
301  *
302  * If there are no remaining references to the inode either through dentries or
303  * open file descriptors, the inode is freed.  Otherwise, the inode is not
304  * removed, but the dentry is unlinked and freed.
305  *
306  * Either way, all lookup table entries referenced by the inode have their
307  * reference count decremented.  If a lookup table entry has no open file
308  * descriptors and no references remaining, it is freed, and the staging file is
309  * unlinked.
310  */
311 static void remove_dentry(struct dentry *dentry,
312                           struct lookup_table *lookup_table)
313 {
314         struct inode *inode = dentry->d_inode;
315         struct lookup_table_entry *lte;
316         unsigned i;
317
318         for (i = 0; i <= inode->num_ads; i++) {
319                 lte = inode_stream_lte_resolved(inode, i);
320                 if (lte)
321                         lte_decrement_refcnt(lte, lookup_table);
322         }
323         unlink_dentry(dentry);
324         put_dentry(dentry);
325 }
326
327 /* Transfers file attributes from a struct inode to a `stat' buffer.
328  *
329  * The lookup table entry tells us which stream in the inode we are statting.
330  * For a named data stream, everything returned is the same as the unnamed data
331  * stream except possibly the size and block count. */
332 static int inode_to_stbuf(const struct inode *inode,
333                           struct lookup_table_entry *lte, struct stat *stbuf)
334 {
335         if (inode_is_symlink(inode))
336                 stbuf->st_mode = S_IFLNK | 0777;
337         else if (inode_is_directory(inode))
338                 stbuf->st_mode = S_IFDIR | 0755;
339         else
340                 stbuf->st_mode = S_IFREG | 0755;
341
342         stbuf->st_ino   = (ino_t)inode->ino;
343         stbuf->st_nlink = inode->link_count;
344         stbuf->st_uid   = getuid();
345         stbuf->st_gid   = getgid();
346
347         if (lte) {
348                 if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
349                         struct stat native_stat;
350                         if (stat(lte->staging_file_name, &native_stat) != 0) {
351                                 DEBUG("Failed to stat `%s': %m",
352                                       lte->staging_file_name);
353                                 return -errno;
354                         }
355                         stbuf->st_size = native_stat.st_size;
356                 } else {
357                         stbuf->st_size = wim_resource_size(lte);
358                 }
359         } else {
360                 stbuf->st_size = 0;
361         }
362
363         stbuf->st_atime   = wim_timestamp_to_unix(inode->last_access_time);
364         stbuf->st_mtime   = wim_timestamp_to_unix(inode->last_write_time);
365         stbuf->st_ctime   = wim_timestamp_to_unix(inode->creation_time);
366         stbuf->st_blocks  = (stbuf->st_size + 511) / 512;
367         return 0;
368 }
369
370 /* Creates a new staging file and returns its file descriptor opened for
371  * writing.
372  *
373  * @name_ret: A location into which the a pointer to the newly allocated name of
374  *                      the staging file is stored.
375  * @return:  The file descriptor for the new file.  Returns -1 and sets errno on
376  *              error, for any reason possible from the creat() function.
377  */
378 static int create_staging_file(char **name_ret, int open_flags,
379                                struct wimfs_context *ctx)
380 {
381         size_t name_len;
382         char *name;
383         struct stat stbuf;
384         int fd;
385         int errno_save;
386
387         name_len = ctx->staging_dir_name_len + 1 + SHA1_HASH_SIZE;
388         name = MALLOC(name_len + 1);
389         if (!name) {
390                 errno = ENOMEM;
391                 return -1;
392         }
393
394         do {
395
396                 memcpy(name, ctx->staging_dir_name, ctx->staging_dir_name_len);
397                 name[ctx->staging_dir_name_len] = '/';
398                 randomize_char_array_with_alnum(name + ctx->staging_dir_name_len + 1,
399                                                 SHA1_HASH_SIZE);
400                 name[name_len] = '\0';
401
402
403         /* Just in case, verify that the randomly generated name doesn't name an
404          * existing file, and try again if so  */
405         } while (stat(name, &stbuf) == 0);
406
407         if (errno != ENOENT)
408                 /* other error! */
409                 return -1;
410
411         /* doesn't exist--- ok */
412
413         DEBUG("Creating staging file `%s'", name);
414
415         fd = open(name, open_flags | O_CREAT | O_TRUNC, 0600);
416         if (fd == -1) {
417                 errno_save = errno;
418                 FREE(name);
419                 errno = errno_save;
420         } else {
421                 *name_ret = name;
422         }
423         return fd;
424 }
425
426 /*
427  * Extract a WIM resource to the staging directory.
428  *
429  * @inode:  Inode that contains the stream we are extracting
430  *
431  * @stream_id: Identifier for the stream (it stays constant even if the indices
432  * of the stream entries are changed)
433  *
434  * @lte: Pointer to pointer to the lookup table entry for the stream we need to
435  * extract, or NULL if there was no lookup table entry present for the stream
436  *
437  * @size:  Number of bytes of the stream we want to extract (this supports the
438  * wimfs_truncate() function).  It may be more than the actual stream length, in
439  * which case the extra space is filled with zeroes.
440  *
441  * @ctx:  Context for the WIM filesystem.
442  *
443  * Returns 0 on success or a negative error code on failure.
444  */
445 static int extract_resource_to_staging_dir(struct inode *inode,
446                                            u32 stream_id,
447                                            struct lookup_table_entry **lte,
448                                            off_t size,
449                                            struct wimfs_context *ctx)
450 {
451         char *staging_file_name;
452         int ret;
453         int fd;
454         struct lookup_table_entry *old_lte, *new_lte;
455         off_t extract_size;
456
457         DEBUG("Extracting resource to staging dir: inode %"PRIu64", "
458               "stream id %"PRIu32, inode->ino, stream_id);
459
460         old_lte = *lte;
461
462         wimlib_assert(old_lte == NULL ||
463                       old_lte->resource_location != RESOURCE_IN_STAGING_FILE);
464
465         /* Create the staging file */
466         fd = create_staging_file(&staging_file_name, O_WRONLY, ctx);
467         if (fd == -1)
468                 return -errno;
469
470         /* Extract the stream to the staging file (possibly truncated) */
471         if (old_lte) {
472                 extract_size = min(wim_resource_size(old_lte), size);
473                 ret = extract_wim_resource_to_fd(old_lte, fd, extract_size);
474         } else {
475                 ret = 0;
476                 extract_size = 0;
477         }
478
479         /* In the case of truncate() to more than the file length, extend the
480          * file with zeroes by calling ftruncate() on the underlying staging
481          * file */
482         if (ret == 0 && size > extract_size)
483                 ret = ftruncate(fd, size);
484
485         /* Close the staging file descriptor and check for errors.  If there's
486          * an error, unlink the staging file. */
487         if (ret != 0 || close(fd) != 0) {
488                 if (errno != 0)
489                         ret = -errno;
490                 else
491                         ret = -EIO;
492                 close(fd);
493                 goto out_delete_staging_file;
494         }
495
496         /* Now deal with the lookup table entries.  We may be able to re-use the
497          * existing entry, but we may have to create a new one instead. */
498
499         if (old_lte && inode->link_count == old_lte->refcnt) {
500                 /* The reference count of the existing lookup table entry is the
501                  * same as the link count of the inode that contains the stream
502                  * we're opening.  Therefore, ALL the references to the lookup
503                  * table entry correspond to the stream we're trying to extract,
504                  * so the lookup table entry can be re-used.  */
505                 DEBUG("Re-using lookup table entry");
506                 lookup_table_unlink(ctx->wim->lookup_table, old_lte);
507                 new_lte = old_lte;
508         } else {
509                 if (old_lte) {
510                         /* There's an existing lookup table entry, but its
511                          * reference count is greater than the link count for
512                          * the inode containing a stream we're opening.
513                          * Therefore, we need to split the lookup table entry.
514                          */
515                         wimlib_assert(old_lte->refcnt > inode->link_count);
516                         DEBUG("Splitting lookup table entry "
517                               "(inode->link_count = %u, old_lte->refcnt = %u)",
518                               inode->link_count, old_lte->refcnt);
519                 }
520
521                 new_lte = new_lookup_table_entry();
522                 if (!new_lte) {
523                         ret = -ENOMEM;
524                         goto out_delete_staging_file;
525                 }
526
527                 /* There may already be open file descriptors to this stream if
528                  * it's previously been opened read-only, but just now we're
529                  * opening it read-write.  Identify those file descriptors and
530                  * change their lookup table entry pointers to point to the new
531                  * lookup table entry, and open staging file descriptors for
532                  * them.
533                  *
534                  * At the same time, we need to count the number of these opened
535                  * file descriptors to the new lookup table entry.  If there's
536                  * an old lookup table entry, this number needs to be subtracted
537                  * from the fd's opened to the old entry. */
538                 for (u16 i = 0, j = 0; j < inode->num_opened_fds; i++) {
539                         struct wimlib_fd *fd = inode->fds[i];
540                         if (fd) {
541                                 if (fd->stream_id == stream_id) {
542                                         wimlib_assert(fd->f_lte == old_lte);
543                                         wimlib_assert(fd->staging_fd == -1);
544                                         fd->f_lte = new_lte;
545                                         new_lte->num_opened_fds++;
546                                         fd->staging_fd = open(staging_file_name, O_RDONLY);
547                                         if (fd->staging_fd == -1) {
548                                                 ret = -errno;
549                                                 goto out_revert_fd_changes;
550                                         }
551                                 }
552                                 j++;
553                         }
554                 }
555                 DEBUG("%hu fd's were already opened to the file we extracted",
556                       new_lte->num_opened_fds);
557                 if (old_lte) {
558                         old_lte->num_opened_fds -= new_lte->num_opened_fds;
559                         old_lte->refcnt -= inode->link_count;
560                 }
561         }
562
563         new_lte->refcnt                       = inode->link_count;
564         new_lte->resource_location            = RESOURCE_IN_STAGING_FILE;
565         new_lte->staging_file_name            = staging_file_name;
566         new_lte->lte_inode                    = inode;
567         random_hash(new_lte->hash);
568
569         if (stream_id == 0)
570                 inode->lte = new_lte;
571         else
572                 for (u16 i = 0; i < inode->num_ads; i++)
573                         if (inode->ads_entries[i].stream_id == stream_id)
574                                 inode->ads_entries[i].lte = new_lte;
575
576         lookup_table_insert(ctx->wim->lookup_table, new_lte);
577         list_add(&new_lte->staging_list, &ctx->staging_list);
578         *lte = new_lte;
579         return 0;
580 out_revert_fd_changes:
581         for (u16 i = 0, j = 0; j < new_lte->num_opened_fds; i++) {
582                 struct wimlib_fd *fd = inode->fds[i];
583                 if (fd && fd->stream_id == stream_id && fd->f_lte == new_lte) {
584                         fd->f_lte = old_lte;
585                         if (fd->staging_fd != -1) {
586                                 close(fd->staging_fd);
587                                 fd->staging_fd = -1;
588                         }
589                         j++;
590                 }
591         }
592         free_lookup_table_entry(new_lte);
593 out_delete_staging_file:
594         unlink(staging_file_name);
595         FREE(staging_file_name);
596         return ret;
597 }
598
599 /*
600  * Creates a randomly named staging directory and saves its name in the
601  * filesystem context structure.
602  */
603 static int make_staging_dir(struct wimfs_context *ctx, const char *user_prefix)
604 {
605         static const size_t random_suffix_len = 10;
606         static const char *common_suffix = ".staging";
607         static const size_t common_suffix_len = 8;
608
609         char *staging_dir_name = NULL;
610         size_t staging_dir_name_len;
611         size_t prefix_len;
612         const char *wim_basename;
613         char *real_user_prefix = NULL;
614         int ret;
615
616         if (user_prefix) {
617                 real_user_prefix = realpath(user_prefix, NULL);
618                 if (!real_user_prefix) {
619                         ERROR_WITH_ERRNO("Could not resolve `%s'",
620                                          real_user_prefix);
621                         ret = WIMLIB_ERR_NOTDIR;
622                         goto out;
623                 }
624                 wim_basename = path_basename(ctx->wim->filename);
625                 prefix_len = strlen(real_user_prefix) + 1 + strlen(wim_basename);
626         } else {
627                 prefix_len = strlen(ctx->wim->filename);
628         }
629
630         staging_dir_name_len = prefix_len + common_suffix_len + random_suffix_len;
631
632         staging_dir_name = MALLOC(staging_dir_name_len + 1);
633         if (!staging_dir_name) {
634                 ret = WIMLIB_ERR_NOMEM;
635                 goto out;
636         }
637
638         if (real_user_prefix)
639                 sprintf(staging_dir_name, "%s/%s", real_user_prefix, wim_basename);
640         else
641                 strcpy(staging_dir_name, ctx->wim->filename);
642
643         strcat(staging_dir_name, common_suffix);
644
645         randomize_char_array_with_alnum(staging_dir_name + prefix_len + common_suffix_len,
646                                         random_suffix_len);
647
648         staging_dir_name[staging_dir_name_len] = '\0';
649
650         if (mkdir(staging_dir_name, 0700) != 0) {
651                 ERROR_WITH_ERRNO("Failed to create temporary directory `%s'",
652                                  staging_dir_name);
653                 ret = WIMLIB_ERR_MKDIR;
654         } else {
655                 ret = 0;
656         }
657 out:
658         FREE(real_user_prefix);
659         if (ret == 0) {
660                 ctx->staging_dir_name = staging_dir_name;
661                 ctx->staging_dir_name_len = staging_dir_name_len;
662         } else {
663                 FREE(staging_dir_name);
664         }
665         return ret;
666 }
667
668 static int remove_file_or_directory(const char *fpath, const struct stat *sb,
669                                     int typeflag, struct FTW *ftwbuf)
670 {
671         if (remove(fpath) == 0)
672                 return 0;
673         else {
674                 ERROR_WITH_ERRNO("Cannot remove `%s'", fpath);
675                 return WIMLIB_ERR_DELETE_STAGING_DIR;
676         }
677 }
678
679
680 /*
681  * Deletes the staging directory and all the files contained in it.
682  */
683 static int delete_staging_dir(struct wimfs_context *ctx)
684 {
685         int ret;
686         ret = nftw(ctx->staging_dir_name, remove_file_or_directory,
687                    10, FTW_DEPTH);
688         FREE(ctx->staging_dir_name);
689         ctx->staging_dir_name = NULL;
690         return ret;
691 }
692
693
694 /* Simple function that returns the concatenation of 2 strings. */
695 static char *strcat_dup(const char *s1, const char *s2, size_t max_len)
696 {
697         size_t len = strlen(s1) + strlen(s2);
698         if (len > max_len)
699                 len = max_len;
700         char *p = MALLOC(len + 1);
701         if (!p)
702                 return NULL;
703         snprintf(p, len + 1, "%s%s", s1, s2);
704         return p;
705 }
706
707 static int set_message_queue_names(struct wimfs_context *ctx,
708                                    const char *mount_dir)
709 {
710         static const char *u2d_prefix = "/wimlib-unmount-to-daemon-mq";
711         static const char *d2u_prefix = "/wimlib-daemon-to-unmount-mq";
712         char *dir_path;
713         char *p;
714         int ret;
715
716         dir_path = realpath(mount_dir, NULL);
717         if (!dir_path) {
718                 ERROR_WITH_ERRNO("Failed to resolve path \"%s\"", mount_dir);
719                 if (errno == ENOMEM)
720                         return WIMLIB_ERR_NOMEM;
721                 else
722                         return WIMLIB_ERR_NOTDIR;
723         }
724
725         p = dir_path;
726         while (*p) {
727                 if (*p == '/')
728                         *p = 0xff;
729                 p++;
730         }
731
732         ctx->unmount_to_daemon_mq_name = strcat_dup(u2d_prefix, dir_path,
733                                                     NAME_MAX);
734         if (!ctx->unmount_to_daemon_mq_name) {
735                 ret = WIMLIB_ERR_NOMEM;
736                 goto out_free_dir_path;
737         }
738         ctx->daemon_to_unmount_mq_name = strcat_dup(d2u_prefix, dir_path,
739                                                     NAME_MAX);
740         if (!ctx->daemon_to_unmount_mq_name) {
741                 ret = WIMLIB_ERR_NOMEM;
742                 goto out_free_unmount_to_daemon_mq_name;
743         }
744
745         ret = 0;
746         goto out_free_dir_path;
747 out_free_unmount_to_daemon_mq_name:
748         FREE(ctx->unmount_to_daemon_mq_name);
749         ctx->unmount_to_daemon_mq_name = NULL;
750 out_free_dir_path:
751         FREE(dir_path);
752         return ret;
753 }
754
755 static void free_message_queue_names(struct wimfs_context *ctx)
756 {
757         FREE(ctx->unmount_to_daemon_mq_name);
758         FREE(ctx->daemon_to_unmount_mq_name);
759         ctx->unmount_to_daemon_mq_name = NULL;
760         ctx->daemon_to_unmount_mq_name = NULL;
761 }
762
763 /*
764  * Opens two POSIX message queue: one for sending messages from the unmount
765  * process to the daemon process, and one to go the other way.  The names of the
766  * message queues, which must be system-wide unique, are be based on the mount
767  * point.  (There of course is still a possibility of a collision if one were to
768  * unmount two identically named directories simultaneously...)
769  *
770  * @daemon specifies whether the calling process is the filesystem daemon or the
771  * unmount process.
772  */
773 static int open_message_queues(struct wimfs_context *ctx, bool daemon)
774 {
775         int unmount_to_daemon_mq_flags = O_WRONLY | O_CREAT;
776         int daemon_to_unmount_mq_flags = O_RDONLY | O_CREAT;
777
778         if (daemon)
779                 swap(unmount_to_daemon_mq_flags, daemon_to_unmount_mq_flags);
780
781         DEBUG("Opening message queue \"%s\"", ctx->unmount_to_daemon_mq_name);
782         ctx->unmount_to_daemon_mq = mq_open(ctx->unmount_to_daemon_mq_name,
783                                             unmount_to_daemon_mq_flags, 0700, NULL);
784
785         if (ctx->unmount_to_daemon_mq == (mqd_t)-1) {
786                 ERROR_WITH_ERRNO("mq_open()");
787                 return WIMLIB_ERR_MQUEUE;
788         }
789
790         DEBUG("Opening message queue \"%s\"", ctx->daemon_to_unmount_mq_name);
791         ctx->daemon_to_unmount_mq = mq_open(ctx->daemon_to_unmount_mq_name,
792                                             daemon_to_unmount_mq_flags, 0700, NULL);
793
794         if (ctx->daemon_to_unmount_mq == (mqd_t)-1) {
795                 ERROR_WITH_ERRNO("mq_open()");
796                 mq_close(ctx->unmount_to_daemon_mq);
797                 mq_unlink(ctx->unmount_to_daemon_mq_name);
798                 ctx->unmount_to_daemon_mq = (mqd_t)-1;
799                 return WIMLIB_ERR_MQUEUE;
800         }
801         return 0;
802 }
803
804 /* Try to determine the maximum message size of a message queue.  The return
805  * value is the maximum message size, or a guess of 8192 bytes if it cannot be
806  * determined. */
807 static long mq_get_msgsize(mqd_t mq)
808 {
809         static const char *msgsize_max_file = "/proc/sys/fs/mqueue/msgsize_max";
810         FILE *fp;
811         struct mq_attr attr;
812         long msgsize;
813
814         if (mq_getattr(mq, &attr) == 0) {
815                 msgsize = attr.mq_msgsize;
816         } else {
817                 ERROR_WITH_ERRNO("mq_getattr()");
818                 ERROR("Attempting to read %s", msgsize_max_file);
819                 fp = fopen(msgsize_max_file, "rb");
820                 if (fp) {
821                         if (fscanf(fp, "%ld", &msgsize) != 1) {
822                                 ERROR("Assuming message size of 8192");
823                                 msgsize = 8192;
824                         }
825                         fclose(fp);
826                 } else {
827                         ERROR_WITH_ERRNO("Failed to open the file `%s'",
828                                          msgsize_max_file);
829                         ERROR("Assuming message size of 8192");
830                         msgsize = 8192;
831                 }
832         }
833         return msgsize;
834 }
835
836 static int get_mailbox(mqd_t mq, long needed_msgsize, long *msgsize_ret,
837                        void **mailbox_ret)
838 {
839         long msgsize;
840         char *mailbox;
841
842         msgsize = mq_get_msgsize(mq);
843
844         if (msgsize < needed_msgsize) {
845                 ERROR("Message queue max size must be at least %ld!",
846                       needed_msgsize);
847                 return WIMLIB_ERR_MQUEUE;
848         }
849
850         mailbox = MALLOC(msgsize);
851         if (!mailbox) {
852                 ERROR("Failed to allocate %ld bytes for mailbox", msgsize);
853                 return WIMLIB_ERR_NOMEM;
854         }
855         *msgsize_ret = msgsize;
856         *mailbox_ret = mailbox;
857         return 0;
858 }
859
860 static void unlink_message_queues(struct wimfs_context *ctx)
861 {
862         mq_unlink(ctx->unmount_to_daemon_mq_name);
863         mq_unlink(ctx->daemon_to_unmount_mq_name);
864 }
865
866 /* Closes the message queues, which are allocated in static variables */
867 static void close_message_queues(struct wimfs_context *ctx)
868 {
869         mq_close(ctx->unmount_to_daemon_mq);
870         ctx->unmount_to_daemon_mq = (mqd_t)(-1);
871         mq_close(ctx->daemon_to_unmount_mq);
872         ctx->daemon_to_unmount_mq = (mqd_t)(-1);
873         unlink_message_queues(ctx);
874 }
875
876 struct unmount_message_header {
877         u32 min_version;
878         u32 cur_version;
879         u32 data_size;
880 };
881
882 struct unmount_request {
883         struct unmount_message_header hdr;
884         struct {
885                 u32 unmount_flags;
886         } data;
887 };
888
889 struct unmount_response {
890         struct unmount_message_header hdr;
891         struct {
892                 int32_t status;
893                 u32 mount_flags;
894         } data;
895 };
896
897 static void inode_update_lte_ptr(struct inode *inode,
898                                  struct lookup_table_entry *old_lte,
899                                  struct lookup_table_entry *new_lte)
900 {
901         if (inode->lte == old_lte) {
902                 inode->lte = new_lte;
903         } else {
904                 for (unsigned i = 0; i < inode->num_ads; i++) {
905                         if (inode->ads_entries[i].lte == old_lte) {
906                                 inode->ads_entries[i].lte = new_lte;
907                                 break;
908                         }
909                 }
910         }
911 }
912
913 static int update_lte_of_staging_file(struct lookup_table_entry *lte,
914                                       struct lookup_table *table)
915 {
916         struct lookup_table_entry *duplicate_lte;
917         int ret;
918         u8 hash[SHA1_HASH_SIZE];
919         struct stat stbuf;
920
921         ret = sha1sum(lte->staging_file_name, hash);
922         if (ret != 0)
923                 return ret;
924         lookup_table_unlink(table, lte);
925         duplicate_lte = __lookup_resource(table, hash);
926         if (duplicate_lte) {
927                 /* Merge duplicate lookup table entries */
928                 duplicate_lte->refcnt += lte->refcnt;
929                 inode_update_lte_ptr(lte->lte_inode, lte, duplicate_lte);
930                 free_lookup_table_entry(lte);
931         } else {
932                 if (stat(lte->staging_file_name, &stbuf) != 0) {
933                         ERROR_WITH_ERRNO("Failed to stat `%s'", lte->staging_file_name);
934                         return WIMLIB_ERR_STAT;
935                 }
936                 if (stbuf.st_size == 0) {
937                         /* Zero-length stream.  No lookup table entry needed. */
938                         inode_update_lte_ptr(lte->lte_inode, lte, NULL);
939                         free_lookup_table_entry(lte);
940                 } else {
941                         wimlib_assert(&lte->file_on_disk == &lte->staging_file_name);
942                         lte->resource_entry.original_size = stbuf.st_size;
943                         lte->resource_entry.size = stbuf.st_size;
944                         lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
945                         lte->file_on_disk_fp = NULL;
946                         copy_hash(lte->hash, hash);
947                         lookup_table_insert(table, lte);
948                 }
949         }
950         return 0;
951 }
952
953 static int inode_close_fds(struct inode *inode)
954 {
955         u16 num_opened_fds = inode->num_opened_fds;
956         for (u16 i = 0, j = 0; j < num_opened_fds; i++) {
957                 struct wimlib_fd *fd = inode->fds[i];
958                 if (fd) {
959                         wimlib_assert(fd->f_inode == inode);
960                         int ret = close_wimlib_fd(fd);
961                         if (ret != 0)
962                                 return ret;
963                         j++;
964                 }
965         }
966         return 0;
967 }
968
969 /* Overwrites the WIM file, with changes saved. */
970 static int rebuild_wim(struct wimfs_context *ctx, int write_flags)
971 {
972         int ret;
973         struct lookup_table_entry *lte, *tmp;
974         WIMStruct *w = ctx->wim;
975
976         DEBUG("Closing all staging file descriptors.");
977         list_for_each_entry_safe(lte, tmp, &ctx->staging_list, staging_list) {
978                 ret = inode_close_fds(lte->lte_inode);
979                 if (ret != 0)
980                         return ret;
981         }
982
983         DEBUG("Calculating SHA1 checksums for all new staging files.");
984         list_for_each_entry(lte, &ctx->staging_list, staging_list) {
985                 ret = update_lte_of_staging_file(lte, w->lookup_table);
986                 if (ret != 0)
987                         return ret;
988         }
989
990         xml_update_image_info(w, w->current_image);
991         ret = wimlib_overwrite(w, write_flags, 0, NULL);
992         if (ret != 0)
993                 ERROR("Failed to commit changes to mounted WIM image");
994         return ret;
995 }
996
997 /* Send a message to the filesystem daemon saying whether to commit or not. */
998 static int send_unmount_request(struct wimfs_context *ctx, int unmount_flags)
999 {
1000         int ret;
1001         struct unmount_request msg;
1002
1003         msg.hdr.min_version    = WIMLIB_MAKEVERSION(1, 2, 0);
1004         msg.hdr.cur_version    = WIMLIB_VERSION_CODE;
1005         msg.hdr.data_size      = sizeof(msg.data);
1006         msg.data.unmount_flags = unmount_flags;
1007
1008         ret = mq_send(ctx->unmount_to_daemon_mq, (void*)&msg,
1009                       sizeof(msg), 1);
1010         if (ret == -1) {
1011                 ERROR_WITH_ERRNO("Failed to notify filesystem daemon whether "
1012                                  "we want to commit changes or not");
1013                 return WIMLIB_ERR_MQUEUE;
1014         }
1015         return 0;
1016 }
1017
1018 static int receive_unmount_request(struct wimfs_context *ctx,
1019                                    int *unmount_flags)
1020 {
1021         void *mailbox;
1022         long msgsize;
1023         struct timeval now;
1024         struct timespec timeout;
1025         ssize_t bytes_received;
1026         struct unmount_request *msg;
1027         int ret;
1028
1029         ret = get_mailbox(ctx->unmount_to_daemon_mq,
1030                           sizeof(struct unmount_request),
1031                           &msgsize, &mailbox);
1032         if (ret != 0)
1033                 return ret;
1034
1035         /* Wait at most 3 seconds before giving up and discarding changes. */
1036         gettimeofday(&now, NULL);
1037         timeout.tv_sec = now.tv_sec + 3;
1038         timeout.tv_nsec = now.tv_usec * 1000;
1039
1040         bytes_received = mq_timedreceive(ctx->unmount_to_daemon_mq, mailbox,
1041                                          msgsize, NULL, &timeout);
1042         msg = mailbox;
1043         if (bytes_received == -1) {
1044                 ERROR_WITH_ERRNO("mq_timedreceive()");
1045                 ERROR("Not committing.");
1046                 ret = WIMLIB_ERR_MQUEUE;
1047         } else if (bytes_received < sizeof(struct unmount_message_header) ||
1048                    bytes_received != sizeof(struct unmount_message_header) + msg->hdr.data_size) {
1049                 ERROR("Received invalid unmount request");
1050                 ret = WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE;
1051         } else if (WIMLIB_VERSION_CODE < msg->hdr.min_version) {
1052                 ERROR("Cannot understand the unmount request. "
1053                       "Please upgrade wimlib to at least v%d.%d.%d",
1054                       WIMLIB_GET_MAJOR_VERSION(msg->hdr.min_version),
1055                       WIMLIB_GET_MINOR_VERSION(msg->hdr.min_version),
1056                       WIMLIB_GET_PATCH_VERSION(msg->hdr.min_version));
1057                 ret = WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE;
1058         } else {
1059                 *unmount_flags = msg->data.unmount_flags;
1060                 ret = 0;
1061         }
1062         FREE(mailbox);
1063         return ret;
1064 }
1065
1066 static void send_unmount_response(struct wimfs_context *ctx, int status)
1067 {
1068         struct unmount_response response;
1069         response.hdr.min_version  = WIMLIB_MAKEVERSION(1, 2, 0);
1070         response.hdr.cur_version  = WIMLIB_VERSION_CODE;
1071         response.hdr.data_size    = sizeof(response.data);
1072         response.data.status      = status;
1073         response.data.mount_flags = ctx->mount_flags;
1074         if (mq_send(ctx->daemon_to_unmount_mq, (void*)&response,
1075                     sizeof(response), 1))
1076                 ERROR_WITH_ERRNO("Failed to send status to unmount process");
1077 }
1078
1079 /* Wait for a message from the filesytem daemon indicating whether  the
1080  * filesystem was unmounted successfully.  This may
1081  * take a long time if a big WIM file needs to be rewritten.
1082  *
1083  * Wait at most 600??? seconds before giving up and returning an error.  Either
1084  * it's a really big WIM file, or (more likely) the filesystem daemon has
1085  * crashed or failed for some reason.
1086  *
1087  * XXX come up with some method to determine if the filesystem daemon has really
1088  * crashed or not.
1089  *
1090  * XXX Idea: have mount daemon write its PID into the WIM file header?  No, this
1091  * wouldn't work because we know the directory but not the WIM file...
1092  */
1093 static int receive_unmount_response(struct wimfs_context *ctx)
1094 {
1095         long msgsize;
1096         void *mailbox;
1097         struct timeval now;
1098         struct timespec timeout;
1099         ssize_t bytes_received;
1100         int ret;
1101         struct unmount_response *msg;
1102
1103         ret = get_mailbox(ctx->daemon_to_unmount_mq,
1104                           sizeof(struct unmount_response), &msgsize, &mailbox);
1105         if (ret != 0)
1106                 return ret;
1107
1108         DEBUG("Waiting for message telling us whether the unmount was "
1109               "successful or not.");
1110
1111         gettimeofday(&now, NULL);
1112         timeout.tv_sec = now.tv_sec + 600;
1113         timeout.tv_nsec = now.tv_usec * 1000;
1114         bytes_received = mq_timedreceive(ctx->daemon_to_unmount_mq,
1115                                          mailbox, msgsize, NULL, &timeout);
1116         msg = mailbox;
1117         if (bytes_received == -1) {
1118                 if (errno == ETIMEDOUT) {
1119                         ERROR("Timed out- probably the filesystem daemon "
1120                               "crashed and the WIM was not written "
1121                               "successfully.");
1122                         ret = WIMLIB_ERR_TIMEOUT;
1123                 } else {
1124                         ERROR_WITH_ERRNO("mq_receive()");
1125                         ret = WIMLIB_ERR_MQUEUE;
1126                 }
1127         } else if (bytes_received < sizeof(struct unmount_message_header) ||
1128                    bytes_received != sizeof(struct unmount_message_header) + msg->hdr.data_size ||
1129                    WIMLIB_VERSION_CODE < msg->hdr.min_version) {
1130                 ERROR("Received invalid unmount response");
1131                 ret = WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE;
1132         } else if (WIMLIB_VERSION_CODE < msg->hdr.min_version) {
1133                 ERROR("Cannot understand the unmount response. "
1134                       "Please upgrade wimlib to at least v%d.%d.%d",
1135                       WIMLIB_GET_MAJOR_VERSION(msg->hdr.min_version),
1136                       WIMLIB_GET_MINOR_VERSION(msg->hdr.min_version),
1137                       WIMLIB_GET_PATCH_VERSION(msg->hdr.min_version));
1138                 ret = WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE;
1139         } else {
1140                 ret = msg->data.status;
1141                 if (ret) {
1142                         ERROR("A failure status (%d) was returned "
1143                               "by the filesystem daemon", ret);
1144                 }
1145         }
1146         FREE(mailbox);
1147         return ret;
1148 }
1149
1150 /* Execute `fusermount -u', which is installed setuid root, to unmount the WIM.
1151  *
1152  * FUSE does not yet implement synchronous unmounts.  This means that fusermount
1153  * -u will return before the filesystem daemon returns from wimfs_destroy().
1154  *  This is partly what we want, because we need to send a message from this
1155  *  process to the filesystem daemon telling whether --commit was specified or
1156  *  not.  However, after that, the unmount process must wait for the filesystem
1157  *  daemon to finish writing the WIM file.
1158  */
1159 static int execute_fusermount(const char *dir)
1160 {
1161         pid_t pid;
1162         int ret;
1163         int status;
1164
1165         pid = fork();
1166         if (pid == -1) {
1167                 ERROR_WITH_ERRNO("Failed to fork()");
1168                 return WIMLIB_ERR_FORK;
1169         }
1170         if (pid == 0) {
1171                 /* Child */
1172                 execlp("fusermount", "fusermount", "-u", dir, NULL);
1173                 ERROR_WITH_ERRNO("Failed to execute `fusermount'");
1174                 exit(WIMLIB_ERR_FUSERMOUNT);
1175         }
1176
1177         /* Parent */
1178         ret = wait(&status);
1179         if (ret == -1) {
1180                 ERROR_WITH_ERRNO("Failed to wait for fusermount process to "
1181                                  "terminate");
1182                 return WIMLIB_ERR_FUSERMOUNT;
1183         }
1184
1185         if (status != 0) {
1186                 if (status == WIMLIB_ERR_FUSERMOUNT)
1187                         ERROR("Could not find the `fusermount' program");
1188                 else
1189                         ERROR("fusermount exited with status %d", status);
1190
1191                 /* Try again, but with the `umount' program.  This is required
1192                  * on other FUSE implementations such as FreeBSD's that do not
1193                  * have a `fusermount' program. */
1194
1195                 pid = fork();
1196                 if (pid == -1) {
1197                         ERROR_WITH_ERRNO("Failed to fork()");
1198                         return WIMLIB_ERR_FORK;
1199                 }
1200                 if (pid == 0) {
1201                         /* Child */
1202                         execlp("umount", "umount", dir, NULL);
1203                         ERROR_WITH_ERRNO("Failed to execute `umount'");
1204                         exit(WIMLIB_ERR_FUSERMOUNT);
1205                 }
1206
1207                 /* Parent */
1208                 ret = wait(&status);
1209                 if (ret == -1) {
1210                         ERROR_WITH_ERRNO("Failed to wait for `umount' process to "
1211                                          "terminate");
1212                         return WIMLIB_ERR_FUSERMOUNT;
1213                 }
1214                 if (status != 0) {
1215                         ERROR("`umount' exited with failure status");
1216                         return WIMLIB_ERR_FUSERMOUNT;
1217                 }
1218         }
1219         return 0;
1220 }
1221
1222 static int wimfs_access(const char *path, int mask)
1223 {
1224         /* Permissions not implemented */
1225         return 0;
1226 }
1227
1228 static int wimfs_chmod(const char *path, mode_t mask)
1229 {
1230         struct dentry *dentry;
1231         struct wimfs_context *ctx = wimfs_get_context();
1232         struct inode *inode;
1233         struct stat stbuf;
1234         int ret;
1235
1236         ret = lookup_resource(ctx->wim, path,
1237                               get_lookup_flags(ctx) | LOOKUP_FLAG_DIRECTORY_OK,
1238                               &dentry, NULL, NULL);
1239         if (ret != 0)
1240                 return ret;
1241         inode = dentry->d_inode;
1242         inode_to_stbuf(inode, NULL, &stbuf);
1243         if (mask == stbuf.st_mode)
1244                 return 0;
1245         else
1246                 return -EPERM;
1247 }
1248
1249 /* Called when the filesystem is unmounted. */
1250 static void wimfs_destroy(void *p)
1251 {
1252         /* The `imagex unmount' command, which is running in a separate process
1253          * and is executing the wimlib_unmount() function, will send this
1254          * process a `struct unmount_request' through a message queue that
1255          * specifies some unmount options, such as other to commit changes or
1256          * not. */
1257
1258         int ret;
1259         int unmount_flags;
1260         struct wimfs_context *ctx;
1261         int status;
1262
1263         ctx = wimfs_get_context();
1264         if (open_message_queues(ctx, true))
1265                 return;
1266
1267         ret = receive_unmount_request(ctx, &unmount_flags);
1268         status = ret;
1269         if (ret == 0) {
1270                 if (ctx->mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
1271                         if (unmount_flags & WIMLIB_UNMOUNT_FLAG_COMMIT) {
1272                                 int write_flags = 0;
1273                                 if (unmount_flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY)
1274                                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1275                                 if (unmount_flags & WIMLIB_UNMOUNT_FLAG_REBUILD)
1276                                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1277                                 if (unmount_flags & WIMLIB_UNMOUNT_FLAG_RECOMPRESS)
1278                                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
1279                                 status = rebuild_wim(ctx, write_flags);
1280                         }
1281                         ret = delete_staging_dir(ctx);
1282                         if (ret != 0) {
1283                                 ERROR("Failed to delete the staging directory");
1284                                 if (status == 0)
1285                                         status = ret;
1286                         }
1287                 } else {
1288                         DEBUG("Read-only mount");
1289                 }
1290         }
1291         send_unmount_response(ctx, status);
1292         close_message_queues(ctx);
1293 }
1294
1295 #if 0
1296 static int wimfs_fallocate(const char *path, int mode,
1297                            off_t offset, off_t len, struct fuse_file_info *fi)
1298 {
1299         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1300         wimlib_assert(fd->staging_fd != -1);
1301         return fallocate(fd->staging_fd, mode, offset, len);
1302 }
1303
1304 #endif
1305
1306 static int wimfs_fgetattr(const char *path, struct stat *stbuf,
1307                           struct fuse_file_info *fi)
1308 {
1309         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1310         return inode_to_stbuf(fd->f_inode, fd->f_lte, stbuf);
1311 }
1312
1313 static int wimfs_ftruncate(const char *path, off_t size,
1314                            struct fuse_file_info *fi)
1315 {
1316         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1317         int ret = ftruncate(fd->staging_fd, size);
1318         if (ret != 0)
1319                 return -errno;
1320         if (fd->f_lte && size < fd->f_lte->resource_entry.original_size)
1321                 fd->f_lte->resource_entry.original_size = size;
1322         return 0;
1323 }
1324
1325 /*
1326  * Fills in a `struct stat' that corresponds to a file or directory in the WIM.
1327  */
1328 static int wimfs_getattr(const char *path, struct stat *stbuf)
1329 {
1330         struct dentry *dentry;
1331         struct lookup_table_entry *lte;
1332         int ret;
1333         struct wimfs_context *ctx = wimfs_get_context();
1334
1335         ret = lookup_resource(ctx->wim, path,
1336                               get_lookup_flags(ctx) | LOOKUP_FLAG_DIRECTORY_OK,
1337                               &dentry, &lte, NULL);
1338         if (ret != 0)
1339                 return ret;
1340         return inode_to_stbuf(dentry->d_inode, lte, stbuf);
1341 }
1342
1343 #ifdef ENABLE_XATTR
1344 /* Read an alternate data stream through the XATTR interface, or get its size */
1345 static int wimfs_getxattr(const char *path, const char *name, char *value,
1346                           size_t size)
1347 {
1348         int ret;
1349         struct inode *inode;
1350         struct ads_entry *ads_entry;
1351         size_t res_size;
1352         struct lookup_table_entry *lte;
1353         struct wimfs_context *ctx = wimfs_get_context();
1354
1355         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1356                 return -ENOTSUP;
1357
1358         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1359                 return -ENOATTR;
1360         name += 5;
1361
1362         inode = wim_pathname_to_inode(ctx->wim, path);
1363         if (!inode)
1364                 return -ENOENT;
1365
1366         ads_entry = inode_get_ads_entry(inode, name, NULL);
1367         if (!ads_entry)
1368                 return -ENOATTR;
1369
1370         lte = ads_entry->lte;
1371         res_size = wim_resource_size(lte);
1372
1373         if (size == 0)
1374                 return res_size;
1375
1376         if (res_size > size)
1377                 return -ERANGE;
1378
1379         ret = read_full_wim_resource(lte, (u8*)value,
1380                                      WIMLIB_RESOURCE_FLAG_MULTITHREADED);
1381         if (ret != 0)
1382                 return -EIO;
1383
1384         return res_size;
1385 }
1386 #endif
1387
1388 /* Create a hard link */
1389 static int wimfs_link(const char *to, const char *from)
1390 {
1391         struct dentry *from_dentry, *from_dentry_parent;
1392         const char *link_name;
1393         struct inode *inode;
1394         struct lookup_table_entry *lte;
1395         WIMStruct *w = wimfs_get_WIMStruct();
1396         u16 i;
1397
1398         inode = wim_pathname_to_inode(w, to);
1399         if (!inode)
1400                 return -ENOENT;
1401
1402         if (inode->attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1403                 return -EEXIST;
1404
1405         if (inode->attributes & FILE_ATTRIBUTE_DIRECTORY)
1406                 return -EPERM;
1407
1408         from_dentry_parent = get_parent_dentry(w, from);
1409         if (!from_dentry_parent)
1410                 return -ENOENT;
1411         if (!dentry_is_directory(from_dentry_parent))
1412                 return -ENOTDIR;
1413
1414         link_name = path_basename(from);
1415         if (get_dentry_child_with_name(from_dentry_parent, link_name))
1416                 return -EEXIST;
1417         from_dentry = new_dentry(link_name);
1418         if (!from_dentry)
1419                 return -ENOMEM;
1420
1421         inode_add_dentry(from_dentry, inode);
1422         from_dentry->d_inode = inode;
1423         inode->link_count++;
1424
1425         for (i = 0; i <= inode->num_ads; i++) {
1426                 lte = inode_stream_lte_resolved(inode, i);
1427                 if (lte)
1428                         lte->refcnt++;
1429         }
1430         dentry_add_child(from_dentry_parent, from_dentry);
1431         return 0;
1432 }
1433
1434 #ifdef ENABLE_XATTR
1435 static int wimfs_listxattr(const char *path, char *list, size_t size)
1436 {
1437         size_t needed_size;
1438         struct inode *inode;
1439         struct wimfs_context *ctx = wimfs_get_context();
1440         u16 i;
1441         char *p;
1442
1443         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1444                 return -ENOTSUP;
1445
1446         /* List alternate data streams, or get the list size */
1447
1448         inode = wim_pathname_to_inode(ctx->wim, path);
1449         if (!inode)
1450                 return -ENOENT;
1451
1452         if (size == 0) {
1453                 needed_size = 0;
1454                 for (i = 0; i < inode->num_ads; i++)
1455                         needed_size += inode->ads_entries[i].stream_name_utf8_len + 6;
1456                 return needed_size;
1457         } else {
1458                 p = list;
1459                 for (i = 0; i < inode->num_ads; i++) {
1460                         needed_size = inode->ads_entries[i].stream_name_utf8_len + 6;
1461                         if (needed_size > size)
1462                                 return -ERANGE;
1463                         p += sprintf(p, "user.%s",
1464                                      inode->ads_entries[i].stream_name_utf8) + 1;
1465                         size -= needed_size;
1466                 }
1467                 return p - list;
1468         }
1469 }
1470 #endif
1471
1472
1473 /* Create a directory in the WIM.
1474  * @mode is currently ignored.  */
1475 static int wimfs_mkdir(const char *path, mode_t mode)
1476 {
1477         struct dentry *dentry;
1478         int ret;
1479
1480         ret = create_dentry(wimfs_get_context(), path, &dentry);
1481         if (ret == 0)
1482                 dentry->d_inode->attributes = FILE_ATTRIBUTE_DIRECTORY;
1483         return ret;
1484 }
1485
1486 /* Create a regular file in the WIM.
1487  * @mode is currently ignored.  */
1488 static int wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
1489 {
1490         const char *stream_name;
1491         struct wimfs_context *ctx = wimfs_get_context();
1492         if ((ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
1493              && (stream_name = path_stream_name(path))) {
1494                 /* Make an alternate data stream */
1495                 struct ads_entry *new_entry;
1496                 struct inode *inode;
1497
1498                 char *p = (char*)stream_name - 1;
1499                 wimlib_assert(*p == ':');
1500                 *p = '\0';
1501
1502                 inode = wim_pathname_to_inode(ctx->wim, path);
1503                 if (!inode)
1504                         return -ENOENT;
1505                 if (inode->attributes &
1506                     (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1507                         return -ENOENT;
1508                 if (inode_get_ads_entry(inode, stream_name, NULL))
1509                         return -EEXIST;
1510                 new_entry = inode_add_ads(inode, stream_name);
1511                 if (!new_entry)
1512                         return -ENOMEM;
1513                 return 0;
1514         } else {
1515                 struct dentry *dentry;
1516                 int ret;
1517
1518                 /* Make a normal file (not an alternate data stream) */
1519                 ret = create_dentry(ctx, path, &dentry);
1520                 if (ret == 0)
1521                         dentry->d_inode->attributes = FILE_ATTRIBUTE_NORMAL;
1522                 return ret;
1523         }
1524 }
1525
1526
1527 /* Open a file.  */
1528 static int wimfs_open(const char *path, struct fuse_file_info *fi)
1529 {
1530         struct dentry *dentry;
1531         struct lookup_table_entry *lte;
1532         int ret;
1533         struct wimlib_fd *fd;
1534         struct inode *inode;
1535         u16 stream_idx;
1536         u32 stream_id;
1537         struct wimfs_context *ctx = wimfs_get_context();
1538
1539         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1540                               &dentry, &lte, &stream_idx);
1541         if (ret != 0)
1542                 return ret;
1543
1544         inode = dentry->d_inode;
1545
1546         if (stream_idx == 0)
1547                 stream_id = 0;
1548         else
1549                 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
1550
1551         /* The file resource may be in the staging directory (read-write mounts
1552          * only) or in the WIM.  If it's in the staging directory, we need to
1553          * open a native file descriptor for the corresponding file.  Otherwise,
1554          * we can read the file resource directly from the WIM file if we are
1555          * opening it read-only, but we need to extract the resource to the
1556          * staging directory if we are opening it writable. */
1557
1558         if (flags_writable(fi->flags) &&
1559             (!lte || lte->resource_location != RESOURCE_IN_STAGING_FILE)) {
1560                 u64 size = (lte) ? wim_resource_size(lte) : 0;
1561                 ret = extract_resource_to_staging_dir(inode, stream_id,
1562                                                       &lte, size, ctx);
1563                 if (ret != 0)
1564                         return ret;
1565         }
1566
1567         ret = alloc_wimlib_fd(inode, stream_id, lte, &fd,
1568                               wimfs_ctx_readonly(ctx));
1569         if (ret != 0)
1570                 return ret;
1571
1572         if (lte && lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1573                 fd->staging_fd = open(lte->staging_file_name, fi->flags);
1574                 if (fd->staging_fd == -1) {
1575                         int errno_save = errno;
1576                         close_wimlib_fd(fd);
1577                         return -errno_save;
1578                 }
1579         }
1580         fi->fh = (uintptr_t)fd;
1581         return 0;
1582 }
1583
1584 /* Opens a directory. */
1585 static int wimfs_opendir(const char *path, struct fuse_file_info *fi)
1586 {
1587         struct inode *inode;
1588         int ret;
1589         struct wimlib_fd *fd = NULL;
1590         struct wimfs_context *ctx = wimfs_get_context();
1591         WIMStruct *w = ctx->wim;
1592
1593         inode = wim_pathname_to_inode(w, path);
1594         if (!inode)
1595                 return -ENOENT;
1596         if (!inode_is_directory(inode))
1597                 return -ENOTDIR;
1598         ret = alloc_wimlib_fd(inode, 0, NULL, &fd, wimfs_ctx_readonly(ctx));
1599         fi->fh = (uintptr_t)fd;
1600         return ret;
1601 }
1602
1603
1604 /*
1605  * Read data from a file in the WIM or in the staging directory.
1606  */
1607 static int wimfs_read(const char *path, char *buf, size_t size,
1608                       off_t offset, struct fuse_file_info *fi)
1609 {
1610         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1611         ssize_t ret;
1612
1613         if (!fd)
1614                 return -EBADF;
1615
1616         if (!fd->f_lte) /* Empty stream with no lookup table entry */
1617                 return 0;
1618
1619         if (fd->f_lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1620                 /* Read from staging file */
1621
1622                 wimlib_assert(fd->f_lte->staging_file_name);
1623                 wimlib_assert(fd->staging_fd != -1);
1624
1625                 DEBUG("Seek to offset %zu", offset);
1626
1627                 if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1628                         return -errno;
1629                 ret = read(fd->staging_fd, buf, size);
1630                 if (ret == -1)
1631                         return -errno;
1632                 return ret;
1633         } else {
1634                 /* Read from WIM */
1635                 u64 res_size = wim_resource_size(fd->f_lte);
1636                 if (offset > res_size)
1637                         return -EOVERFLOW;
1638                 size = min(size, res_size - offset);
1639                 if (read_wim_resource(fd->f_lte, (u8*)buf,
1640                                       size, offset,
1641                                       WIMLIB_RESOURCE_FLAG_MULTITHREADED) != 0)
1642                         return -EIO;
1643                 return size;
1644         }
1645 }
1646
1647 struct fill_params {
1648         void *buf;
1649         fuse_fill_dir_t filler;
1650 };
1651
1652 static int dentry_fuse_fill(struct dentry *dentry, void *arg)
1653 {
1654         struct fill_params *fill_params = arg;
1655         return fill_params->filler(fill_params->buf, dentry->file_name_utf8,
1656                                    NULL, 0);
1657 }
1658
1659 /* Fills in the entries of the directory specified by @path using the
1660  * FUSE-provided function @filler.  */
1661 static int wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
1662                          off_t offset, struct fuse_file_info *fi)
1663 {
1664         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1665         struct inode *inode;
1666
1667         if (!fd)
1668                 return -EBADF;
1669
1670         inode = fd->f_inode;
1671
1672         struct fill_params fill_params = {
1673                 .buf = buf,
1674                 .filler = filler,
1675         };
1676
1677         filler(buf, ".", NULL, 0);
1678         filler(buf, "..", NULL, 0);
1679
1680         return for_dentry_in_rbtree(inode->children.rb_node,
1681                                     dentry_fuse_fill, &fill_params);
1682 }
1683
1684
1685 static int wimfs_readlink(const char *path, char *buf, size_t buf_len)
1686 {
1687         struct wimfs_context *ctx = wimfs_get_context();
1688         struct inode *inode = wim_pathname_to_inode(ctx->wim, path);
1689         int ret;
1690         if (!inode)
1691                 return -ENOENT;
1692         if (!inode_is_symlink(inode))
1693                 return -EINVAL;
1694
1695         ret = inode_readlink(inode, buf, buf_len, ctx->wim,
1696                              WIMLIB_RESOURCE_FLAG_MULTITHREADED);
1697         if (ret > 0)
1698                 ret = 0;
1699         return ret;
1700 }
1701
1702 /* Close a file. */
1703 static int wimfs_release(const char *path, struct fuse_file_info *fi)
1704 {
1705         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1706         return close_wimlib_fd(fd);
1707 }
1708
1709 /* Close a directory */
1710 static int wimfs_releasedir(const char *path, struct fuse_file_info *fi)
1711 {
1712         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1713         return close_wimlib_fd(fd);
1714 }
1715
1716 #ifdef ENABLE_XATTR
1717 /* Remove an alternate data stream through the XATTR interface */
1718 static int wimfs_removexattr(const char *path, const char *name)
1719 {
1720         struct inode *inode;
1721         struct ads_entry *ads_entry;
1722         u16 ads_idx;
1723         struct wimfs_context *ctx = wimfs_get_context();
1724
1725         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1726                 return -ENOTSUP;
1727
1728         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1729                 return -ENOATTR;
1730         name += 5;
1731
1732         inode = wim_pathname_to_inode(ctx->wim, path);
1733         if (!inode)
1734                 return -ENOENT;
1735
1736         ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
1737         if (!ads_entry)
1738                 return -ENOATTR;
1739         inode_remove_ads(inode, ads_idx, ctx->wim->lookup_table);
1740         return 0;
1741 }
1742 #endif
1743
1744 /* Renames a file or directory.  See rename (3) */
1745 static int wimfs_rename(const char *from, const char *to)
1746 {
1747         struct dentry *src;
1748         struct dentry *dst;
1749         struct dentry *parent_of_dst;
1750         char *file_name_utf16 = NULL, *file_name_utf8 = NULL;
1751         u16 file_name_utf16_len, file_name_utf8_len;
1752         WIMStruct *w = wimfs_get_WIMStruct();
1753         int ret;
1754
1755         /* This rename() implementation currently only supports actual files
1756          * (not alternate data streams) */
1757
1758         src = get_dentry(w, from);
1759         if (!src)
1760                 return -ENOENT;
1761
1762         dst = get_dentry(w, to);
1763
1764         ret = get_names(&file_name_utf16, &file_name_utf8,
1765                         &file_name_utf16_len, &file_name_utf8_len,
1766                         path_basename(to));
1767         if (ret != 0)
1768                 return -ENOMEM;
1769
1770         if (dst) {
1771                 /* Destination file exists */
1772
1773                 if (src == dst) /* Same file */
1774                         return 0;
1775
1776                 if (!dentry_is_directory(src)) {
1777                         /* Cannot rename non-directory to directory. */
1778                         if (dentry_is_directory(dst))
1779                                 return -EISDIR;
1780                 } else {
1781                         /* Cannot rename directory to a non-directory or a non-empty
1782                          * directory */
1783                         if (!dentry_is_directory(dst))
1784                                 return -ENOTDIR;
1785                         if (inode_has_children(dst->d_inode))
1786                                 return -ENOTEMPTY;
1787                 }
1788                 parent_of_dst = dst->parent;
1789                 remove_dentry(dst, w->lookup_table);
1790         } else {
1791                 /* Destination does not exist */
1792                 parent_of_dst = get_parent_dentry(w, to);
1793                 if (!parent_of_dst)
1794                         return -ENOENT;
1795
1796                 if (!dentry_is_directory(parent_of_dst))
1797                         return -ENOTDIR;
1798         }
1799
1800         FREE(src->file_name);
1801         FREE(src->file_name_utf8);
1802         src->file_name          = file_name_utf16;
1803         src->file_name_utf8     = file_name_utf8;
1804         src->file_name_len      = file_name_utf16_len;
1805         src->file_name_utf8_len = file_name_utf8_len;
1806
1807         unlink_dentry(src);
1808         dentry_add_child(parent_of_dst, src);
1809         return 0;
1810 }
1811
1812 /* Remove a directory */
1813 static int wimfs_rmdir(const char *path)
1814 {
1815         struct dentry *dentry;
1816         WIMStruct *w = wimfs_get_WIMStruct();
1817
1818         dentry = get_dentry(w, path);
1819         if (!dentry)
1820                 return -ENOENT;
1821
1822         if (!dentry_is_empty_directory(dentry))
1823                 return -ENOTEMPTY;
1824
1825         remove_dentry(dentry, w->lookup_table);
1826         return 0;
1827 }
1828
1829 #ifdef ENABLE_XATTR
1830 /* Write an alternate data stream through the XATTR interface */
1831 static int wimfs_setxattr(const char *path, const char *name,
1832                           const char *value, size_t size, int flags)
1833 {
1834         struct ads_entry *existing_ads_entry;
1835         struct ads_entry *new_ads_entry;
1836         struct lookup_table_entry *existing_lte;
1837         struct lookup_table_entry *lte;
1838         struct inode *inode;
1839         u8 value_hash[SHA1_HASH_SIZE];
1840         u16 ads_idx;
1841         struct wimfs_context *ctx = wimfs_get_context();
1842
1843         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1844                 return -ENOTSUP;
1845
1846         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1847                 return -ENOATTR;
1848         name += 5;
1849
1850         inode = wim_pathname_to_inode(ctx->wim, path);
1851         if (!inode)
1852                 return -ENOENT;
1853
1854         existing_ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
1855         if (existing_ads_entry) {
1856                 if (flags & XATTR_CREATE)
1857                         return -EEXIST;
1858                 inode_remove_ads(inode, ads_idx, ctx->wim->lookup_table);
1859         } else {
1860                 if (flags & XATTR_REPLACE)
1861                         return -ENOATTR;
1862         }
1863         new_ads_entry = inode_add_ads(inode, name);
1864         if (!new_ads_entry)
1865                 return -ENOMEM;
1866
1867         sha1_buffer((const u8*)value, size, value_hash);
1868
1869         existing_lte = __lookup_resource(ctx->wim->lookup_table, value_hash);
1870
1871         if (existing_lte) {
1872                 lte = existing_lte;
1873                 lte->refcnt++;
1874         } else {
1875                 u8 *value_copy;
1876                 lte = new_lookup_table_entry();
1877                 if (!lte)
1878                         return -ENOMEM;
1879                 value_copy = MALLOC(size);
1880                 if (!value_copy) {
1881                         FREE(lte);
1882                         return -ENOMEM;
1883                 }
1884                 memcpy(value_copy, value, size);
1885                 lte->resource_location            = RESOURCE_IN_ATTACHED_BUFFER;
1886                 lte->attached_buffer              = value_copy;
1887                 lte->resource_entry.original_size = size;
1888                 lte->resource_entry.size          = size;
1889                 lte->resource_entry.flags         = 0;
1890                 copy_hash(lte->hash, value_hash);
1891                 lookup_table_insert(ctx->wim->lookup_table, lte);
1892         }
1893         new_ads_entry->lte = lte;
1894         return 0;
1895 }
1896 #endif
1897
1898 static int wimfs_symlink(const char *to, const char *from)
1899 {
1900         struct wimfs_context *ctx = wimfs_get_context();
1901         struct dentry *dentry;
1902         int ret;
1903
1904         ret = create_dentry(ctx, from, &dentry);
1905         if (ret == 0) {
1906                 dentry->d_inode->attributes = FILE_ATTRIBUTE_REPARSE_POINT;
1907                 dentry->d_inode->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
1908                 if (inode_set_symlink(dentry->d_inode, to,
1909                                       ctx->wim->lookup_table, NULL))
1910                 {
1911                         unlink_dentry(dentry);
1912                         free_dentry(dentry);
1913                         ret = -ENOMEM;
1914                 }
1915         }
1916         return ret;
1917 }
1918
1919
1920 /* Reduce the size of a file */
1921 static int wimfs_truncate(const char *path, off_t size)
1922 {
1923         struct dentry *dentry;
1924         struct lookup_table_entry *lte;
1925         int ret;
1926         u16 stream_idx;
1927         u32 stream_id;
1928         struct inode *inode;
1929         struct wimfs_context *ctx = wimfs_get_context();
1930
1931         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1932                               &dentry, &lte, &stream_idx);
1933
1934         if (ret != 0)
1935                 return ret;
1936
1937         if (lte == NULL && size == 0)
1938                 return 0;
1939
1940         inode = dentry->d_inode;
1941         if (stream_idx == 0)
1942                 stream_id = 0;
1943         else
1944                 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
1945
1946         if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1947                 ret = truncate(lte->staging_file_name, size);
1948                 if (ret != 0)
1949                         ret = -errno;
1950         } else {
1951                 /* File in WIM.  Extract it to the staging directory, but only
1952                  * the first @size bytes of it. */
1953                 ret = extract_resource_to_staging_dir(inode, stream_id,
1954                                                       &lte, size, ctx);
1955         }
1956         return ret;
1957 }
1958
1959 /* Unlink a non-directory or alternate data stream */
1960 static int wimfs_unlink(const char *path)
1961 {
1962         struct dentry *dentry;
1963         struct lookup_table_entry *lte;
1964         int ret;
1965         u16 stream_idx;
1966         struct wimfs_context *ctx = wimfs_get_context();
1967
1968         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1969                               &dentry, &lte, &stream_idx);
1970
1971         if (ret != 0)
1972                 return ret;
1973
1974         if (stream_idx == 0)
1975                 remove_dentry(dentry, ctx->wim->lookup_table);
1976         else
1977                 inode_remove_ads(dentry->d_inode, stream_idx - 1,
1978                                  ctx->wim->lookup_table);
1979         return 0;
1980 }
1981
1982 #ifdef HAVE_UTIMENSAT
1983 /*
1984  * Change the timestamp on a file dentry.
1985  *
1986  * Note that alternate data streams do not have their own timestamps.
1987  */
1988 static int wimfs_utimens(const char *path, const struct timespec tv[2])
1989 {
1990         struct dentry *dentry;
1991         struct inode *inode;
1992         WIMStruct *w = wimfs_get_WIMStruct();
1993
1994         dentry = get_dentry(w, path);
1995         if (!dentry)
1996                 return -ENOENT;
1997         inode = dentry->d_inode;
1998
1999         if (tv[0].tv_nsec != UTIME_OMIT) {
2000                 if (tv[0].tv_nsec == UTIME_NOW)
2001                         inode->last_access_time = get_wim_timestamp();
2002                 else
2003                         inode->last_access_time = timespec_to_wim_timestamp(&tv[0]);
2004         }
2005         if (tv[1].tv_nsec != UTIME_OMIT) {
2006                 if (tv[1].tv_nsec == UTIME_NOW)
2007                         inode->last_write_time = get_wim_timestamp();
2008                 else
2009                         inode->last_write_time = timespec_to_wim_timestamp(&tv[1]);
2010         }
2011         return 0;
2012 }
2013 #else
2014 static int wimfs_utime(const char *path, struct utimbuf *times)
2015 {
2016         struct dentry *dentry;
2017         struct inode *inode;
2018         WIMStruct *w = wimfs_get_WIMStruct();
2019
2020         dentry = get_dentry(w, path);
2021         if (!dentry)
2022                 return -ENOENT;
2023         inode = dentry->d_inode;
2024
2025         inode->last_write_time = unix_timestamp_to_wim(times->modtime);
2026         inode->last_access_time = unix_timestamp_to_wim(times->actime);
2027         return 0;
2028 }
2029 #endif
2030
2031 /* Writes to a file in the WIM filesystem.
2032  * It may be an alternate data stream, but here we don't even notice because we
2033  * just get a lookup table entry. */
2034 static int wimfs_write(const char *path, const char *buf, size_t size,
2035                        off_t offset, struct fuse_file_info *fi)
2036 {
2037         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
2038         int ret;
2039         u64 now;
2040
2041         if (!fd)
2042                 return -EBADF;
2043
2044         wimlib_assert(fd->f_lte);
2045         wimlib_assert(fd->f_lte->staging_file_name);
2046         wimlib_assert(fd->staging_fd != -1);
2047         wimlib_assert(fd->f_inode);
2048
2049         /* Seek to the requested position */
2050         if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
2051                 return -errno;
2052
2053         /* Write the data. */
2054         ret = write(fd->staging_fd, buf, size);
2055         if (ret == -1)
2056                 return -errno;
2057
2058         now = get_wim_timestamp();
2059         fd->f_inode->last_write_time = now;
2060         fd->f_inode->last_access_time = now;
2061         return ret;
2062 }
2063
2064 static struct fuse_operations wimfs_operations = {
2065         .access      = wimfs_access,
2066         .chmod       = wimfs_chmod,
2067         .destroy     = wimfs_destroy,
2068 #if 0
2069         .fallocate   = wimfs_fallocate,
2070 #endif
2071         .fgetattr    = wimfs_fgetattr,
2072         .ftruncate   = wimfs_ftruncate,
2073         .getattr     = wimfs_getattr,
2074 #ifdef ENABLE_XATTR
2075         .getxattr    = wimfs_getxattr,
2076 #endif
2077         .link        = wimfs_link,
2078 #ifdef ENABLE_XATTR
2079         .listxattr   = wimfs_listxattr,
2080 #endif
2081         .mkdir       = wimfs_mkdir,
2082         .mknod       = wimfs_mknod,
2083         .open        = wimfs_open,
2084         .opendir     = wimfs_opendir,
2085         .read        = wimfs_read,
2086         .readdir     = wimfs_readdir,
2087         .readlink    = wimfs_readlink,
2088         .release     = wimfs_release,
2089         .releasedir  = wimfs_releasedir,
2090 #ifdef ENABLE_XATTR
2091         .removexattr = wimfs_removexattr,
2092 #endif
2093         .rename      = wimfs_rename,
2094         .rmdir       = wimfs_rmdir,
2095 #ifdef ENABLE_XATTR
2096         .setxattr    = wimfs_setxattr,
2097 #endif
2098         .symlink     = wimfs_symlink,
2099         .truncate    = wimfs_truncate,
2100         .unlink      = wimfs_unlink,
2101 #ifdef HAVE_UTIMENSAT
2102         .utimens     = wimfs_utimens,
2103 #else
2104         .utime       = wimfs_utime,
2105 #endif
2106         .write       = wimfs_write,
2107
2108 #if FUSE_MAJOR_VERSION > 2 || (FUSE_MAJOR_VERSION == 2 && FUSE_MINOR_VERSION >= 8)
2109         .flag_nullpath_ok = 1,
2110 #endif
2111 #if FUSE_MAJOR_VERSION > 2 || (FUSE_MAJOR_VERSION == 2 && FUSE_MINOR_VERSION >= 9)
2112         .flag_nopath = 1,
2113         .flag_utime_omit_ok = 1,
2114 #endif
2115 };
2116
2117
2118 /* Mounts an image from a WIM file. */
2119 WIMLIBAPI int wimlib_mount_image(WIMStruct *wim, int image, const char *dir,
2120                                  int mount_flags, WIMStruct **additional_swms,
2121                                  unsigned num_additional_swms,
2122                                  const char *staging_dir)
2123 {
2124         int argc = 0;
2125         char *argv[16];
2126         int ret;
2127         char *dir_copy;
2128         struct lookup_table *joined_tab, *wim_tab_save;
2129         struct image_metadata *imd;
2130         struct wimfs_context ctx;
2131         struct hlist_node *cur_node;
2132         struct inode *inode;
2133
2134         DEBUG("Mount: wim = %p, image = %d, dir = %s, flags = %d, ",
2135               wim, image, dir, mount_flags);
2136
2137         if (!wim || !dir)
2138                 return WIMLIB_ERR_INVALID_PARAM;
2139
2140         ret = verify_swm_set(wim, additional_swms, num_additional_swms);
2141         if (ret != 0)
2142                 return ret;
2143
2144         if ((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) && (wim->hdr.total_parts != 1)) {
2145                 ERROR("Cannot mount a split WIM read-write");
2146                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2147         }
2148
2149         if (num_additional_swms) {
2150                 ret = new_joined_lookup_table(wim, additional_swms,
2151                                               num_additional_swms,
2152                                               &joined_tab);
2153                 if (ret != 0)
2154                         return ret;
2155                 wim_tab_save = wim->lookup_table;
2156                 wim->lookup_table = joined_tab;
2157         }
2158
2159         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2160                 ret = wim_run_full_verifications(wim);
2161                 if (ret != 0)
2162                         goto out;
2163         }
2164
2165         ret = select_wim_image(wim, image);
2166         if (ret != 0)
2167                 goto out;
2168
2169         DEBUG("Selected image %d", image);
2170
2171         imd = wim_get_current_image_metadata(wim);
2172
2173         if (imd->root_dentry->refcnt != 1) {
2174                 ERROR("Cannot mount image that was just exported with "
2175                       "wimlib_export_image()");
2176                 ret = WIMLIB_ERR_INVALID_PARAM;
2177                 goto out;
2178         }
2179
2180         if (imd->modified) {
2181                 ERROR("Cannot mount image that was added "
2182                       "with wimlib_add_image()");
2183                 ret = WIMLIB_ERR_INVALID_PARAM;
2184                 goto out;
2185         }
2186
2187         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2188                 ret = lock_wim(wim, wim->fp);
2189                 if (ret != 0)
2190                         goto out;
2191         }
2192
2193         if (!(mount_flags & (WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
2194                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
2195                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)))
2196                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
2197
2198
2199         DEBUG("Initializing struct wimfs_context");
2200         init_wimfs_context(&ctx);
2201         ctx.wim = wim;
2202         ctx.mount_flags = mount_flags;
2203         ctx.image_inode_list = &imd->inode_list;
2204
2205         if (mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
2206                 ctx.default_lookup_flags = LOOKUP_FLAG_ADS_OK;
2207
2208         DEBUG("Unlinking message queues in case they already exist");
2209         ret = set_message_queue_names(&ctx, dir);
2210         if (ret != 0)
2211                 goto out_unlock;
2212         unlink_message_queues(&ctx);
2213
2214         DEBUG("Preparing arguments to fuse_main()");
2215
2216         dir_copy = STRDUP(dir);
2217         if (!dir_copy)
2218                 goto out_free_message_queue_names;
2219
2220         argv[argc++] = "imagex";
2221         argv[argc++] = dir_copy;
2222
2223         /* disable multi-threaded operation for read-write mounts */
2224         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2225                 argv[argc++] = "-s";
2226
2227         if (mount_flags & WIMLIB_MOUNT_FLAG_DEBUG)
2228                 argv[argc++] = "-d";
2229
2230         /*
2231          * We provide the use_ino option because we are going to assign inode
2232          * numbers oursides.  The inodes will be given unique numbers in the
2233          * assign_inode_numbers() function, and the static variable @next_ino is
2234          * set to the next available inode number.
2235          */
2236         char optstring[256] =
2237                 "use_ino"
2238                 ",subtype=wimfs"
2239                 ",attr_timeout=0"
2240 #if FUSE_MAJOR_VERSION > 2 || (FUSE_MAJOR_VERSION == 2 && FUSE_MINOR_VERSION >= 8)
2241                 ",hard_remove"
2242 #endif
2243                 ;
2244         argv[argc++] = "-o";
2245         argv[argc++] = optstring;
2246         if ((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
2247                 /* Read-write mount.  Make the staging directory */
2248                 ret = make_staging_dir(&ctx, staging_dir);
2249                 if (ret != 0)
2250                         goto out_free_dir_copy;
2251         } else {
2252                 /* Read-only mount */
2253                 strcat(optstring, ",ro");
2254         }
2255         argv[argc] = NULL;
2256
2257 #ifdef ENABLE_DEBUG
2258         {
2259                 int i;
2260                 DEBUG("FUSE command line (argc = %d): ", argc);
2261                 for (i = 0; i < argc; i++) {
2262                         fputs(argv[i], stdout);
2263                         putchar(' ');
2264                 }
2265                 putchar('\n');
2266                 fflush(stdout);
2267         }
2268 #endif
2269
2270         /* Mark dentry tree as modified if read-write mount. */
2271         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2272                 imd->modified = 1;
2273                 imd->has_been_mounted_rw = 1;
2274         }
2275
2276         /* Resolve the lookup table entries for every inode in the image, and
2277          * assign inode numbers */
2278         DEBUG("Resolving lookup table entries and assigning inode numbers");
2279
2280         ctx.next_ino = 1;
2281         hlist_for_each_entry(inode, cur_node, &imd->inode_list, hlist) {
2282                 inode_resolve_ltes(inode, wim->lookup_table);
2283                 inode->ino = ctx.next_ino++;
2284         }
2285         /*ctx.next_ino = assign_inode_numbers(&imd->inode_list);*/
2286         DEBUG("(next_ino = %"PRIu64")", ctx.next_ino);
2287
2288         DEBUG("Calling fuse_main()");
2289
2290         ret = fuse_main(argc, argv, &wimfs_operations, &ctx);
2291
2292         DEBUG("Returned from fuse_main() (ret = %d)", ret);
2293         if (ret)
2294                 ret = WIMLIB_ERR_FUSE;
2295 out_free_dir_copy:
2296         FREE(dir_copy);
2297 out_unlock:
2298         wim->wim_locked = 0;
2299 out_free_message_queue_names:
2300         free_message_queue_names(&ctx);
2301 out:
2302         if (num_additional_swms) {
2303                 free_lookup_table(wim->lookup_table);
2304                 wim->lookup_table = wim_tab_save;
2305         }
2306         return ret;
2307 }
2308
2309 /*
2310  * Unmounts the WIM file that was previously mounted on @dir by using
2311  * wimlib_mount_image().
2312  */
2313 WIMLIBAPI int wimlib_unmount_image(const char *dir, int unmount_flags,
2314                                    wimlib_progress_func_t progress_func)
2315 {
2316         int ret;
2317         struct wimfs_context ctx;
2318
2319         init_wimfs_context(&ctx);
2320
2321         ret = set_message_queue_names(&ctx, dir);
2322         if (ret != 0)
2323                 goto out;
2324
2325         ret = open_message_queues(&ctx, false);
2326         if (ret != 0)
2327                 goto out_free_message_queue_names;
2328
2329         ret = send_unmount_request(&ctx, unmount_flags);
2330         if (ret != 0)
2331                 goto out_close_message_queues;
2332
2333         ret = execute_fusermount(dir);
2334         if (ret != 0)
2335                 goto out_close_message_queues;
2336         ret = receive_unmount_response(&ctx);
2337 out_close_message_queues:
2338         close_message_queues(&ctx);
2339 out_free_message_queue_names:
2340         free_message_queue_names(&ctx);
2341 out:
2342         return ret;
2343 }
2344
2345 #else /* WITH_FUSE */
2346
2347
2348 static inline int mount_unsupported_error()
2349 {
2350         ERROR("wimlib was compiled with --without-fuse, which disables support "
2351               "for mounting WIMs.");
2352         return WIMLIB_ERR_UNSUPPORTED;
2353 }
2354
2355 WIMLIBAPI int wimlib_unmount_image(const char *dir, int unmount_flags,
2356                                    wimlib_progress_func_t progress_func)
2357 {
2358         return mount_unsupported_error();
2359 }
2360
2361 WIMLIBAPI int wimlib_mount_image(WIMStruct *wim_p, int image, const char *dir,
2362                                  int mount_flags, WIMStruct **additional_swms,
2363                                  unsigned num_additional_swms,
2364                                  const char *staging_dir)
2365 {
2366         return mount_unsupported_error();
2367 }
2368
2369 #endif /* WITH_FUSE */