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