]> wimlib.net Git - wimlib/blob - src/mount_image.c
d3021a535907971756d48fcf9366b04fd00b5cc6
[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                 return WIMLIB_ERR_NOTDIR;
670         }
671
672         DEBUG("Using absolute dir_path = `%s'", dir_path);
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                        char **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 static int wimfs_access(const char *path, int mask)
843 {
844         /* Permissions not implemented */
845         return 0;
846 }
847
848 static int wimfs_chmod(const char *path, mode_t mask)
849 {
850         struct dentry *dentry;
851         struct wimfs_context *ctx = wimfs_get_context();
852         struct inode *inode;
853         struct stat stbuf;
854         int ret;
855
856         ret = lookup_resource(ctx->wim, path,
857                               get_lookup_flags(ctx) | LOOKUP_FLAG_DIRECTORY_OK,
858                               &dentry, NULL, NULL);
859         if (ret != 0)
860                 return ret;
861         inode = dentry->d_inode;
862         inode_to_stbuf(inode, NULL, &stbuf);
863         if (mask == stbuf.st_mode)
864                 return 0;
865         else
866                 return -EPERM;
867
868 }
869
870 static void inode_update_lte_ptr(struct inode *inode,
871                                  struct lookup_table_entry *old_lte,
872                                  struct lookup_table_entry *new_lte)
873 {
874         if (inode->lte == old_lte) {
875                 inode->lte = new_lte;
876         } else {
877                 for (unsigned i = 0; i < inode->num_ads; i++) {
878                         if (inode->ads_entries[i].lte == old_lte) {
879                                 inode->ads_entries[i].lte = new_lte;
880                                 break;
881                         }
882                 }
883         }
884 }
885
886 static int update_lte_of_staging_file(struct lookup_table_entry *lte,
887                                       struct lookup_table *table)
888 {
889         struct lookup_table_entry *duplicate_lte;
890         int ret;
891         u8 hash[SHA1_HASH_SIZE];
892         struct stat stbuf;
893
894         wimlib_assert(lte->resource_location == RESOURCE_IN_STAGING_FILE);
895         wimlib_assert(lte->staging_file_name);
896
897         ret = sha1sum(lte->staging_file_name, hash);
898         if (ret != 0)
899                 return ret;
900
901         lookup_table_unlink(table, lte);
902
903         duplicate_lte = __lookup_resource(table, hash);
904
905         if (duplicate_lte) {
906                 /* Merge duplicate lookup table entries */
907                 duplicate_lte->refcnt += lte->refcnt;
908                 list_del(&lte->staging_list);
909                 inode_update_lte_ptr(lte->lte_inode, lte, duplicate_lte);
910                 free_lookup_table_entry(lte);
911         } else {
912                 if (stat(lte->staging_file_name, &stbuf) != 0) {
913                         ERROR_WITH_ERRNO("Failed to stat `%s'", lte->staging_file_name);
914                         return WIMLIB_ERR_STAT;
915                 }
916                 if (stbuf.st_size == 0) {
917                         /* Zero-length stream.  No lookup table entry needed. */
918                         inode_update_lte_ptr(lte->lte_inode, lte, NULL);
919                         free_lookup_table_entry(lte);
920                 } else {
921                         wimlib_assert(&lte->file_on_disk == &lte->staging_file_name);
922                         lte->resource_entry.original_size = stbuf.st_size;
923                         lte->resource_entry.size = stbuf.st_size;
924                         lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
925                         lte->lte_inode = NULL;
926                         copy_hash(lte->hash, hash);
927                         lookup_table_insert(table, lte);
928                 }
929         }
930         return 0;
931 }
932
933 static int inode_close_fds(struct inode *inode)
934 {
935         u16 num_opened_fds = inode->num_opened_fds;
936         for (u16 i = 0, j = 0; j < num_opened_fds; i++) {
937                 struct wimlib_fd *fd = inode->fds[i];
938                 if (fd) {
939                         wimlib_assert(fd->f_inode == inode);
940                         int ret = close_wimlib_fd(fd);
941                         if (ret != 0)
942                                 return ret;
943                         j++;
944                 }
945         }
946         return 0;
947 }
948
949 /* Overwrites the WIM file, with changes saved. */
950 static int rebuild_wim(struct wimfs_context *ctx, int write_flags)
951 {
952         int ret;
953         struct lookup_table_entry *lte, *tmp;
954         WIMStruct *w = ctx->wim;
955
956
957         DEBUG("Closing all staging file descriptors.");
958         list_for_each_entry_safe(lte, tmp, &ctx->staging_list, staging_list) {
959                 ret = inode_close_fds(lte->lte_inode);
960                 if (ret != 0)
961                         return ret;
962         }
963
964         DEBUG("Calculating SHA1 checksums for all new staging files.");
965         list_for_each_entry_safe(lte, tmp, &ctx->staging_list, staging_list) {
966                 ret = update_lte_of_staging_file(lte, ctx->wim->lookup_table);
967                 if (ret != 0)
968                         return ret;
969         }
970
971         xml_update_image_info(w, w->current_image);
972
973         ret = wimlib_overwrite(w, write_flags, 0, NULL);
974         if (ret != 0) {
975                 ERROR("Failed to commit changes");
976                 return ret;
977         }
978         return ret;
979 }
980
981 /* Called when the filesystem is unmounted. */
982 static void wimfs_destroy(void *p)
983 {
984         /* For read-write mounts, the `imagex unmount' command, which is
985          * running in a separate process and is executing the
986          * wimlib_unmount() function, will send this process a byte
987          * through a message queue that indicates whether the --commit
988          * option was specified or not. */
989
990         long msgsize;
991         struct timespec timeout;
992         struct timeval now;
993         ssize_t bytes_received;
994         int ret;
995         char commit;
996         char check_integrity;
997         char status;
998         char *mailbox;
999         struct wimfs_context *ctx = wimfs_get_context();
1000         int write_flags;
1001
1002         if (open_message_queues(ctx, true))
1003                 return;
1004
1005         if (get_mailbox(ctx->unmount_to_daemon_mq, 2, &msgsize, &mailbox))
1006                 goto out_close_message_queues;
1007
1008         /* Wait at most 3 seconds before giving up and discarding changes. */
1009         gettimeofday(&now, NULL);
1010         timeout.tv_sec = now.tv_sec + 3;
1011         timeout.tv_nsec = now.tv_usec * 1000;
1012         DEBUG("Waiting for message telling us whether to commit or not, and "
1013               "whether to include integrity checks.");
1014
1015         bytes_received = mq_timedreceive(ctx->unmount_to_daemon_mq, mailbox,
1016                                          msgsize, NULL, &timeout);
1017         if (bytes_received == -1) {
1018                 ERROR_WITH_ERRNO("mq_timedreceive()");
1019                 ERROR("Not committing.");
1020                 commit = 0;
1021                 check_integrity = 0;
1022         } else {
1023                 DEBUG("Received message: [%d %d]", mailbox[0], mailbox[1]);
1024                 commit = mailbox[0];
1025                 check_integrity = mailbox[1];
1026         }
1027
1028         status = 0;
1029         if (ctx->mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
1030                 if (commit) {
1031                         if (check_integrity)
1032                                 write_flags = WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1033                         else
1034                                 write_flags = 0;
1035                         status = rebuild_wim(ctx, write_flags);
1036                 }
1037                 ret = delete_staging_dir(ctx);
1038                 if (ret != 0) {
1039                         ERROR("Failed to delete the staging directory");
1040                         if (status == 0)
1041                                 status = ret;
1042                 }
1043         } else {
1044                 DEBUG("Read-only mount");
1045         }
1046         DEBUG("Sending status %hhd", status);
1047         ret = mq_send(ctx->daemon_to_unmount_mq, &status, 1, 1);
1048         if (ret == -1)
1049                 ERROR_WITH_ERRNO("Failed to send status to unmount process");
1050         FREE(mailbox);
1051 out_close_message_queues:
1052         close_message_queues(ctx);
1053 }
1054
1055 #if 0
1056 static int wimfs_fallocate(const char *path, int mode,
1057                            off_t offset, off_t len, struct fuse_file_info *fi)
1058 {
1059         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1060         wimlib_assert(fd->staging_fd != -1);
1061         return fallocate(fd->staging_fd, mode, offset, len);
1062 }
1063
1064 #endif
1065
1066 static int wimfs_fgetattr(const char *path, struct stat *stbuf,
1067                           struct fuse_file_info *fi)
1068 {
1069         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1070         return inode_to_stbuf(fd->f_inode, fd->f_lte, stbuf);
1071 }
1072
1073 static int wimfs_ftruncate(const char *path, off_t size,
1074                            struct fuse_file_info *fi)
1075 {
1076         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1077         int ret = ftruncate(fd->staging_fd, size);
1078         if (ret != 0)
1079                 return -errno;
1080         if (fd->f_lte && size < fd->f_lte->resource_entry.original_size)
1081                 fd->f_lte->resource_entry.original_size = size;
1082         return 0;
1083 }
1084
1085 /*
1086  * Fills in a `struct stat' that corresponds to a file or directory in the WIM.
1087  */
1088 static int wimfs_getattr(const char *path, struct stat *stbuf)
1089 {
1090         struct dentry *dentry;
1091         struct lookup_table_entry *lte;
1092         int ret;
1093         struct wimfs_context *ctx = wimfs_get_context();
1094
1095         ret = lookup_resource(ctx->wim, path,
1096                               get_lookup_flags(ctx) | LOOKUP_FLAG_DIRECTORY_OK,
1097                               &dentry, &lte, NULL);
1098         if (ret != 0)
1099                 return ret;
1100         return inode_to_stbuf(dentry->d_inode, lte, stbuf);
1101 }
1102
1103 #ifdef ENABLE_XATTR
1104 /* Read an alternate data stream through the XATTR interface, or get its size */
1105 static int wimfs_getxattr(const char *path, const char *name, char *value,
1106                           size_t size)
1107 {
1108         int ret;
1109         struct inode *inode;
1110         struct ads_entry *ads_entry;
1111         size_t res_size;
1112         struct lookup_table_entry *lte;
1113         struct wimfs_context *ctx = wimfs_get_context();
1114
1115         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1116                 return -ENOTSUP;
1117
1118         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1119                 return -ENOATTR;
1120         name += 5;
1121
1122         inode = wim_pathname_to_inode(ctx->wim, path);
1123         if (!inode)
1124                 return -ENOENT;
1125
1126         ads_entry = inode_get_ads_entry(inode, name, NULL);
1127         if (!ads_entry)
1128                 return -ENOATTR;
1129
1130         lte = ads_entry->lte;
1131         res_size = wim_resource_size(lte);
1132
1133         if (size == 0)
1134                 return res_size;
1135
1136         if (res_size > size)
1137                 return -ERANGE;
1138
1139         ret = read_full_wim_resource(lte, (u8*)value,
1140                                      WIMLIB_RESOURCE_FLAG_MULTITHREADED);
1141         if (ret != 0)
1142                 return -EIO;
1143
1144         return res_size;
1145 }
1146 #endif
1147
1148 /* Create a hard link */
1149 static int wimfs_link(const char *to, const char *from)
1150 {
1151         struct dentry *from_dentry, *from_dentry_parent;
1152         const char *link_name;
1153         struct inode *inode;
1154         struct lookup_table_entry *lte;
1155         WIMStruct *w = wimfs_get_WIMStruct();
1156
1157         inode = wim_pathname_to_inode(w, to);
1158         if (!inode)
1159                 return -ENOENT;
1160
1161         if (!inode_is_regular_file(inode))
1162                 return -EPERM;
1163
1164         from_dentry_parent = get_parent_dentry(w, from);
1165         if (!from_dentry_parent)
1166                 return -ENOENT;
1167         if (!dentry_is_directory(from_dentry_parent))
1168                 return -ENOTDIR;
1169
1170         link_name = path_basename(from);
1171         if (get_dentry_child_with_name(from_dentry_parent, link_name))
1172                 return -EEXIST;
1173         from_dentry = new_dentry(link_name);
1174         if (!from_dentry)
1175                 return -ENOMEM;
1176
1177
1178         inode_add_dentry(from_dentry, inode);
1179         from_dentry->d_inode = inode;
1180         inode->link_count++;
1181
1182         for (unsigned i = 0; i <= inode->num_ads; i++) {
1183                 lte = inode_stream_lte_resolved(inode, i);
1184                 if (lte)
1185                         lte->refcnt++;
1186         }
1187
1188         dentry_add_child(from_dentry_parent, from_dentry);
1189         return 0;
1190 }
1191
1192 #ifdef ENABLE_XATTR
1193 static int wimfs_listxattr(const char *path, char *list, size_t size)
1194 {
1195         size_t needed_size;
1196         struct inode *inode;
1197         struct wimfs_context *ctx = wimfs_get_context();
1198
1199         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1200                 return -ENOTSUP;
1201
1202         /* List alternate data streams, or get the list size */
1203
1204         inode = wim_pathname_to_inode(ctx->wim, path);
1205         if (!inode)
1206                 return -ENOENT;
1207
1208         if (size == 0) {
1209                 needed_size = 0;
1210                 for (u16 i = 0; i < inode->num_ads; i++)
1211                         needed_size += inode->ads_entries[i].stream_name_utf8_len + 6;
1212                 return needed_size;
1213         } else {
1214                 char *p = list;
1215                 for (u16 i = 0; i < inode->num_ads; i++) {
1216                         needed_size = inode->ads_entries[i].stream_name_utf8_len + 6;
1217                         if (needed_size > size)
1218                                 return -ERANGE;
1219                         p += sprintf(p, "user.%s",
1220                                      inode->ads_entries[i].stream_name_utf8) + 1;
1221                         size -= needed_size;
1222                 }
1223                 return p - list;
1224         }
1225 }
1226 #endif
1227
1228 /*
1229  * Create a directory in the WIM.
1230  * @mode is currently ignored.
1231  */
1232 static int wimfs_mkdir(const char *path, mode_t mode)
1233 {
1234         struct dentry *parent;
1235         struct dentry *newdir;
1236         const char *basename;
1237         struct wimfs_context *ctx = wimfs_get_context();
1238
1239         parent = get_parent_dentry(ctx->wim, path);
1240         if (!parent)
1241                 return -ENOENT;
1242
1243         if (!dentry_is_directory(parent))
1244                 return -ENOTDIR;
1245
1246         basename = path_basename(path);
1247         if (get_dentry_child_with_name(parent, basename))
1248                 return -EEXIST;
1249
1250         newdir = new_dentry_with_inode(basename);
1251         newdir->d_inode->attributes |= FILE_ATTRIBUTE_DIRECTORY;
1252         newdir->d_inode->resolved = true;
1253         newdir->d_inode->ino = ctx->next_ino++;
1254         dentry_add_child(parent, newdir);
1255         return 0;
1256 }
1257
1258 /* Creates a regular file. */
1259 static int wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
1260 {
1261         const char *stream_name;
1262         struct wimfs_context *ctx = wimfs_get_context();
1263         if ((ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
1264              && (stream_name = path_stream_name(path))) {
1265                 /* Make an alternate data stream */
1266                 struct ads_entry *new_entry;
1267                 struct inode *inode;
1268
1269                 char *p = (char*)stream_name - 1;
1270                 wimlib_assert(*p == ':');
1271                 *p = '\0';
1272
1273                 inode = wim_pathname_to_inode(ctx->wim, path);
1274                 if (!inode)
1275                         return -ENOENT;
1276                 if (!inode_is_regular_file(inode))
1277                         return -ENOENT;
1278                 if (inode_get_ads_entry(inode, stream_name, NULL))
1279                         return -EEXIST;
1280                 new_entry = inode_add_ads(inode, stream_name);
1281                 if (!new_entry)
1282                         return -ENOMEM;
1283         } else {
1284                 struct dentry *dentry, *parent;
1285                 const char *basename;
1286
1287                 /* Make a normal file (not an alternate data stream) */
1288
1289                 /* Make sure that the parent of @path exists and is a directory, and
1290                  * that the dentry named by @path does not already exist.  */
1291                 parent = get_parent_dentry(ctx->wim, path);
1292                 if (!parent)
1293                         return -ENOENT;
1294                 if (!dentry_is_directory(parent))
1295                         return -ENOTDIR;
1296
1297                 basename = path_basename(path);
1298                 if (get_dentry_child_with_name(parent, path))
1299                         return -EEXIST;
1300
1301                 dentry = new_dentry_with_inode(basename);
1302                 if (!dentry)
1303                         return -ENOMEM;
1304                 dentry->d_inode->resolved = true;
1305                 dentry->d_inode->ino = ctx->next_ino++;
1306                 dentry_add_child(parent, dentry);
1307         }
1308         return 0;
1309 }
1310
1311
1312 /* Open a file.  */
1313 static int wimfs_open(const char *path, struct fuse_file_info *fi)
1314 {
1315         struct dentry *dentry;
1316         struct lookup_table_entry *lte;
1317         int ret;
1318         struct wimlib_fd *fd;
1319         struct inode *inode;
1320         u16 stream_idx;
1321         u32 stream_id;
1322         struct wimfs_context *ctx = wimfs_get_context();
1323
1324         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1325                               &dentry, &lte, &stream_idx);
1326         if (ret != 0)
1327                 return ret;
1328
1329         inode = dentry->d_inode;
1330
1331         if (stream_idx == 0)
1332                 stream_id = 0;
1333         else
1334                 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
1335
1336         /* The file resource may be in the staging directory (read-write mounts
1337          * only) or in the WIM.  If it's in the staging directory, we need to
1338          * open a native file descriptor for the corresponding file.  Otherwise,
1339          * we can read the file resource directly from the WIM file if we are
1340          * opening it read-only, but we need to extract the resource to the
1341          * staging directory if we are opening it writable. */
1342
1343         if (flags_writable(fi->flags) &&
1344             (!lte || lte->resource_location != RESOURCE_IN_STAGING_FILE)) {
1345                 u64 size = (lte) ? wim_resource_size(lte) : 0;
1346                 ret = extract_resource_to_staging_dir(inode, stream_id,
1347                                                       &lte, size, ctx);
1348                 if (ret != 0)
1349                         return ret;
1350         }
1351
1352         ret = alloc_wimlib_fd(inode, stream_id, lte, &fd,
1353                               wimfs_ctx_readonly(ctx));
1354         if (ret != 0)
1355                 return ret;
1356
1357         if (lte && lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1358                 fd->staging_fd = open(lte->staging_file_name, fi->flags);
1359                 if (fd->staging_fd == -1) {
1360                         close_wimlib_fd(fd);
1361                         return -errno;
1362                 }
1363         }
1364         fi->fh = (uintptr_t)fd;
1365         return 0;
1366 }
1367
1368 /* Opens a directory. */
1369 static int wimfs_opendir(const char *path, struct fuse_file_info *fi)
1370 {
1371         struct inode *inode;
1372         int ret;
1373         struct wimlib_fd *fd = NULL;
1374         struct wimfs_context *ctx = wimfs_get_context();
1375         WIMStruct *w = ctx->wim;
1376
1377         inode = wim_pathname_to_inode(w, path);
1378         if (!inode)
1379                 return -ENOENT;
1380         if (!inode_is_directory(inode))
1381                 return -ENOTDIR;
1382         ret = alloc_wimlib_fd(inode, 0, NULL, &fd, wimfs_ctx_readonly(ctx));
1383         fi->fh = (uintptr_t)fd;
1384         return ret;
1385 }
1386
1387
1388 /*
1389  * Read data from a file in the WIM or in the staging directory.
1390  */
1391 static int wimfs_read(const char *path, char *buf, size_t size,
1392                       off_t offset, struct fuse_file_info *fi)
1393 {
1394         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1395
1396         if (!fd)
1397                 return -EBADF;
1398
1399         if (!fd->f_lte) /* Empty stream with no lookup table entry */
1400                 return 0;
1401
1402         if (fd->f_lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1403                 /* Read from staging file */
1404
1405                 wimlib_assert(fd->f_lte->staging_file_name);
1406                 wimlib_assert(fd->staging_fd != -1);
1407
1408                 ssize_t ret;
1409                 DEBUG("Seek to offset %zu", offset);
1410
1411                 if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1412                         return -errno;
1413                 ret = read(fd->staging_fd, buf, size);
1414                 if (ret == -1)
1415                         return -errno;
1416                 return ret;
1417         } else {
1418                 /* Read from WIM */
1419
1420                 wimlib_assert(fd->f_lte->resource_location == RESOURCE_IN_WIM);
1421
1422                 u64 res_size = wim_resource_size(fd->f_lte);
1423
1424                 if (offset > res_size)
1425                         return -EOVERFLOW;
1426
1427                 size = min(size, res_size - offset);
1428
1429                 if (read_wim_resource(fd->f_lte, (u8*)buf,
1430                                       size, offset,
1431                                       WIMLIB_RESOURCE_FLAG_MULTITHREADED) != 0)
1432                         return -EIO;
1433                 return size;
1434         }
1435 }
1436
1437 struct fill_params {
1438         void *buf;
1439         fuse_fill_dir_t filler;
1440 };
1441
1442 static int dentry_fuse_fill(struct dentry *dentry, void *arg)
1443 {
1444         struct fill_params *fill_params = arg;
1445         return fill_params->filler(fill_params->buf, dentry->file_name_utf8,
1446                                    NULL, 0);
1447 }
1448
1449 /* Fills in the entries of the directory specified by @path using the
1450  * FUSE-provided function @filler.  */
1451 static int wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
1452                          off_t offset, struct fuse_file_info *fi)
1453 {
1454         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1455         struct inode *inode;
1456
1457         if (!fd)
1458                 return -EBADF;
1459
1460         inode = fd->f_inode;
1461
1462         struct fill_params fill_params = {
1463                 .buf = buf,
1464                 .filler = filler,
1465         };
1466
1467         filler(buf, ".", NULL, 0);
1468         filler(buf, "..", NULL, 0);
1469
1470         return for_dentry_in_rbtree(inode->children.rb_node,
1471                                     dentry_fuse_fill, &fill_params);
1472 }
1473
1474
1475 static int wimfs_readlink(const char *path, char *buf, size_t buf_len)
1476 {
1477         struct wimfs_context *ctx = wimfs_get_context();
1478         struct inode *inode = wim_pathname_to_inode(ctx->wim, path);
1479         int ret;
1480         if (!inode)
1481                 return -ENOENT;
1482         if (!inode_is_symlink(inode))
1483                 return -EINVAL;
1484
1485         ret = inode_readlink(inode, buf, buf_len, ctx->wim,
1486                              WIMLIB_RESOURCE_FLAG_MULTITHREADED);
1487         if (ret > 0)
1488                 ret = 0;
1489         return ret;
1490 }
1491
1492 /* Close a file. */
1493 static int wimfs_release(const char *path, struct fuse_file_info *fi)
1494 {
1495         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1496         return close_wimlib_fd(fd);
1497 }
1498
1499 /* Close a directory */
1500 static int wimfs_releasedir(const char *path, struct fuse_file_info *fi)
1501 {
1502         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1503         return close_wimlib_fd(fd);
1504 }
1505
1506 #ifdef ENABLE_XATTR
1507 /* Remove an alternate data stream through the XATTR interface */
1508 static int wimfs_removexattr(const char *path, const char *name)
1509 {
1510         struct inode *inode;
1511         struct ads_entry *ads_entry;
1512         u16 ads_idx;
1513         struct wimfs_context *ctx = wimfs_get_context();
1514
1515         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1516                 return -ENOTSUP;
1517
1518         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1519                 return -ENOATTR;
1520         name += 5;
1521
1522         inode = wim_pathname_to_inode(ctx->wim, path);
1523         if (!inode)
1524                 return -ENOENT;
1525
1526         ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
1527         if (!ads_entry)
1528                 return -ENOATTR;
1529         inode_remove_ads(inode, ads_idx, ctx->wim->lookup_table);
1530         return 0;
1531 }
1532 #endif
1533
1534 /* Renames a file or directory.  See rename (3) */
1535 static int wimfs_rename(const char *from, const char *to)
1536 {
1537         struct dentry *src;
1538         struct dentry *dst;
1539         struct dentry *parent_of_dst;
1540         char *file_name_utf16 = NULL, *file_name_utf8 = NULL;
1541         u16 file_name_utf16_len, file_name_utf8_len;
1542         WIMStruct *w = wimfs_get_WIMStruct();
1543         int ret;
1544
1545         /* This rename() implementation currently only supports actual files
1546          * (not alternate data streams) */
1547
1548         src = get_dentry(w, from);
1549         if (!src)
1550                 return -ENOENT;
1551
1552         dst = get_dentry(w, to);
1553
1554
1555         ret = get_names(&file_name_utf16, &file_name_utf8,
1556                         &file_name_utf16_len, &file_name_utf8_len,
1557                         path_basename(to));
1558         if (ret != 0)
1559                 return -ENOMEM;
1560
1561         if (dst) {
1562                 /* Destination file exists */
1563
1564                 if (src == dst) /* Same file */
1565                         return 0;
1566
1567                 if (!dentry_is_directory(src)) {
1568                         /* Cannot rename non-directory to directory. */
1569                         if (dentry_is_directory(dst))
1570                                 return -EISDIR;
1571                 } else {
1572                         /* Cannot rename directory to a non-directory or a non-empty
1573                          * directory */
1574                         if (!dentry_is_directory(dst))
1575                                 return -ENOTDIR;
1576                         if (inode_has_children(dst->d_inode))
1577                                 return -ENOTEMPTY;
1578                 }
1579                 parent_of_dst = dst->parent;
1580                 remove_dentry(dst, w->lookup_table);
1581         } else {
1582                 /* Destination does not exist */
1583                 parent_of_dst = get_parent_dentry(w, to);
1584                 if (!parent_of_dst)
1585                         return -ENOENT;
1586
1587                 if (!dentry_is_directory(parent_of_dst))
1588                         return -ENOTDIR;
1589         }
1590
1591         FREE(src->file_name);
1592         FREE(src->file_name_utf8);
1593         src->file_name          = file_name_utf16;
1594         src->file_name_utf8     = file_name_utf8;
1595         src->file_name_len      = file_name_utf16_len;
1596         src->file_name_utf8_len = file_name_utf8_len;
1597
1598         unlink_dentry(src);
1599         dentry_add_child(parent_of_dst, src);
1600         return 0;
1601 }
1602
1603 /* Remove a directory */
1604 static int wimfs_rmdir(const char *path)
1605 {
1606         struct dentry *dentry;
1607         WIMStruct *w = wimfs_get_WIMStruct();
1608
1609         dentry = get_dentry(w, path);
1610         if (!dentry)
1611                 return -ENOENT;
1612
1613         if (!dentry_is_empty_directory(dentry))
1614                 return -ENOTEMPTY;
1615
1616         remove_dentry(dentry, w->lookup_table);
1617         return 0;
1618 }
1619
1620 #ifdef ENABLE_XATTR
1621 /* Write an alternate data stream through the XATTR interface */
1622 static int wimfs_setxattr(const char *path, const char *name,
1623                           const char *value, size_t size, int flags)
1624 {
1625         struct ads_entry *existing_ads_entry;
1626         struct ads_entry *new_ads_entry;
1627         struct lookup_table_entry *existing_lte;
1628         struct lookup_table_entry *lte;
1629         struct inode *inode;
1630         u8 value_hash[SHA1_HASH_SIZE];
1631         u16 ads_idx;
1632         struct wimfs_context *ctx = wimfs_get_context();
1633
1634         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1635                 return -ENOTSUP;
1636
1637         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1638                 return -ENOATTR;
1639         name += 5;
1640
1641         inode = wim_pathname_to_inode(ctx->wim, path);
1642         if (!inode)
1643                 return -ENOENT;
1644
1645         existing_ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
1646         if (existing_ads_entry) {
1647                 if (flags & XATTR_CREATE)
1648                         return -EEXIST;
1649                 inode_remove_ads(inode, ads_idx, ctx->wim->lookup_table);
1650         } else {
1651                 if (flags & XATTR_REPLACE)
1652                         return -ENOATTR;
1653         }
1654         new_ads_entry = inode_add_ads(inode, name);
1655         if (!new_ads_entry)
1656                 return -ENOMEM;
1657
1658         sha1_buffer((const u8*)value, size, value_hash);
1659
1660         existing_lte = __lookup_resource(ctx->wim->lookup_table, value_hash);
1661
1662         if (existing_lte) {
1663                 lte = existing_lte;
1664                 lte->refcnt++;
1665         } else {
1666                 u8 *value_copy;
1667                 lte = new_lookup_table_entry();
1668                 if (!lte)
1669                         return -ENOMEM;
1670                 value_copy = MALLOC(size);
1671                 if (!value_copy) {
1672                         FREE(lte);
1673                         return -ENOMEM;
1674                 }
1675                 memcpy(value_copy, value, size);
1676                 lte->resource_location            = RESOURCE_IN_ATTACHED_BUFFER;
1677                 lte->attached_buffer              = value_copy;
1678                 lte->resource_entry.original_size = size;
1679                 lte->resource_entry.size          = size;
1680                 lte->resource_entry.flags         = 0;
1681                 copy_hash(lte->hash, value_hash);
1682                 lookup_table_insert(ctx->wim->lookup_table, lte);
1683         }
1684         new_ads_entry->lte = lte;
1685         return 0;
1686 }
1687 #endif
1688
1689 static int wimfs_symlink(const char *to, const char *from)
1690 {
1691         struct dentry *dentry_parent, *dentry;
1692         const char *link_name;
1693         struct inode *inode;
1694         struct wimfs_context *ctx = wimfs_get_context();
1695
1696         dentry_parent = get_parent_dentry(ctx->wim, from);
1697         if (!dentry_parent)
1698                 return -ENOENT;
1699         if (!dentry_is_directory(dentry_parent))
1700                 return -ENOTDIR;
1701
1702         link_name = path_basename(from);
1703
1704         if (get_dentry_child_with_name(dentry_parent, link_name))
1705                 return -EEXIST;
1706         dentry = new_dentry_with_inode(link_name);
1707         if (!dentry)
1708                 return -ENOMEM;
1709         inode = dentry->d_inode;
1710
1711         inode->attributes  = FILE_ATTRIBUTE_REPARSE_POINT;
1712         inode->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
1713         inode->ino         = ctx->next_ino++;
1714         inode->resolved    = true;
1715
1716         if (inode_set_symlink(inode, to, ctx->wim->lookup_table, NULL) != 0)
1717                 goto out_free_dentry;
1718
1719         dentry_add_child(dentry_parent, dentry);
1720         return 0;
1721 out_free_dentry:
1722         free_dentry(dentry);
1723         return -ENOMEM;
1724 }
1725
1726
1727 /* Reduce the size of a file */
1728 static int wimfs_truncate(const char *path, off_t size)
1729 {
1730         struct dentry *dentry;
1731         struct lookup_table_entry *lte;
1732         int ret;
1733         u16 stream_idx;
1734         u32 stream_id;
1735         struct inode *inode;
1736         struct wimfs_context *ctx = wimfs_get_context();
1737
1738         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1739                               &dentry, &lte, &stream_idx);
1740
1741         if (ret != 0)
1742                 return ret;
1743
1744         if (!lte) /* Already a zero-length file */
1745                 return 0;
1746
1747         inode = dentry->d_inode;
1748
1749         if (stream_idx == 0)
1750                 stream_id = 0;
1751         else
1752                 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
1753
1754         if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1755                 wimlib_assert(lte->staging_file_name);
1756                 ret = truncate(lte->staging_file_name, size);
1757                 if (ret != 0)
1758                         return -errno;
1759                 lte->resource_entry.original_size = size;
1760         } else {
1761                 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
1762                 /* File in WIM.  Extract it to the staging directory, but only
1763                  * the first @size bytes of it. */
1764                 ret = extract_resource_to_staging_dir(inode, stream_id,
1765                                                       &lte, size, ctx);
1766         }
1767         return ret;
1768 }
1769
1770 /* Remove a regular file */
1771 static int wimfs_unlink(const char *path)
1772 {
1773         struct dentry *dentry;
1774         struct lookup_table_entry *lte;
1775         int ret;
1776         u16 stream_idx;
1777         struct wimfs_context *ctx = wimfs_get_context();
1778
1779         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1780                               &dentry, &lte, &stream_idx);
1781
1782         if (ret != 0)
1783                 return ret;
1784
1785         if (stream_idx == 0)
1786                 remove_dentry(dentry, ctx->wim->lookup_table);
1787         else
1788                 inode_remove_ads(dentry->d_inode, stream_idx - 1,
1789                                  ctx->wim->lookup_table);
1790         return 0;
1791 }
1792
1793 #ifdef HAVE_UTIMENSAT
1794 /*
1795  * Change the timestamp on a file dentry.
1796  *
1797  * Note that alternate data streams do not have their own timestamps.
1798  */
1799 static int wimfs_utimens(const char *path, const struct timespec tv[2])
1800 {
1801         struct dentry *dentry;
1802         struct inode *inode;
1803         WIMStruct *w = wimfs_get_WIMStruct();
1804
1805         dentry = get_dentry(w, path);
1806         if (!dentry)
1807                 return -ENOENT;
1808         inode = dentry->d_inode;
1809
1810         if (tv[0].tv_nsec != UTIME_OMIT) {
1811                 if (tv[0].tv_nsec == UTIME_NOW)
1812                         inode->last_access_time = get_wim_timestamp();
1813                 else
1814                         inode->last_access_time = timespec_to_wim_timestamp(&tv[0]);
1815         }
1816         if (tv[1].tv_nsec != UTIME_OMIT) {
1817                 if (tv[1].tv_nsec == UTIME_NOW)
1818                         inode->last_write_time = get_wim_timestamp();
1819                 else
1820                         inode->last_write_time = timespec_to_wim_timestamp(&tv[1]);
1821         }
1822         return 0;
1823 }
1824 #else
1825 static int wimfs_utime(const char *path, struct utimbuf *times)
1826 {
1827         struct dentry *dentry;
1828         struct inode *inode;
1829         WIMStruct *w = wimfs_get_WIMStruct();
1830
1831         dentry = get_dentry(w, path);
1832         if (!dentry)
1833                 return -ENOENT;
1834         inode = dentry->d_inode;
1835
1836         inode->last_write_time = unix_timestamp_to_wim(times->modtime);
1837         inode->last_access_time = unix_timestamp_to_wim(times->actime);
1838         return 0;
1839 }
1840 #endif
1841
1842 /* Writes to a file in the WIM filesystem.
1843  * It may be an alternate data stream, but here we don't even notice because we
1844  * just get a lookup table entry. */
1845 static int wimfs_write(const char *path, const char *buf, size_t size,
1846                        off_t offset, struct fuse_file_info *fi)
1847 {
1848         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1849         int ret;
1850         u64 now;
1851
1852         if (!fd)
1853                 return -EBADF;
1854
1855         wimlib_assert(fd->f_lte);
1856         wimlib_assert(fd->f_lte->staging_file_name);
1857         wimlib_assert(fd->staging_fd != -1);
1858         wimlib_assert(fd->f_inode);
1859
1860         /* Seek to the requested position */
1861         if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1862                 return -errno;
1863
1864         /* Write the data. */
1865         ret = write(fd->staging_fd, buf, size);
1866         if (ret == -1)
1867                 return -errno;
1868
1869         now = get_wim_timestamp();
1870         fd->f_inode->last_write_time = now;
1871         fd->f_inode->last_access_time = now;
1872         return ret;
1873 }
1874
1875 static struct fuse_operations wimfs_operations = {
1876         .access      = wimfs_access,
1877         .chmod       = wimfs_chmod,
1878         .destroy     = wimfs_destroy,
1879 #if 0
1880         .fallocate   = wimfs_fallocate,
1881 #endif
1882         .fgetattr    = wimfs_fgetattr,
1883         .ftruncate   = wimfs_ftruncate,
1884         .getattr     = wimfs_getattr,
1885 #ifdef ENABLE_XATTR
1886         .getxattr    = wimfs_getxattr,
1887 #endif
1888         .link        = wimfs_link,
1889 #ifdef ENABLE_XATTR
1890         .listxattr   = wimfs_listxattr,
1891 #endif
1892         .mkdir       = wimfs_mkdir,
1893         .mknod       = wimfs_mknod,
1894         .open        = wimfs_open,
1895         .opendir     = wimfs_opendir,
1896         .read        = wimfs_read,
1897         .readdir     = wimfs_readdir,
1898         .readlink    = wimfs_readlink,
1899         .release     = wimfs_release,
1900         .releasedir  = wimfs_releasedir,
1901 #ifdef ENABLE_XATTR
1902         .removexattr = wimfs_removexattr,
1903 #endif
1904         .rename      = wimfs_rename,
1905         .rmdir       = wimfs_rmdir,
1906 #ifdef ENABLE_XATTR
1907         .setxattr    = wimfs_setxattr,
1908 #endif
1909         .symlink     = wimfs_symlink,
1910         .truncate    = wimfs_truncate,
1911         .unlink      = wimfs_unlink,
1912 #ifdef HAVE_UTIMENSAT
1913         .utimens     = wimfs_utimens,
1914 #else
1915         .utime       = wimfs_utime,
1916 #endif
1917         .write       = wimfs_write,
1918
1919 #if FUSE_MAJOR_VERSION > 2 || (FUSE_MAJOR_VERSION == 2 && FUSE_MINOR_VERSION >= 8)
1920         .flag_nullpath_ok = 1,
1921 #endif
1922 #if FUSE_MAJOR_VERSION > 2 || (FUSE_MAJOR_VERSION == 2 && FUSE_MINOR_VERSION >= 9)
1923         .flag_nopath = 1,
1924         .flag_utime_omit_ok = 1,
1925 #endif
1926 };
1927
1928
1929 /* Mounts an image from a WIM file. */
1930 WIMLIBAPI int wimlib_mount_image(WIMStruct *wim, int image, const char *dir,
1931                                  int mount_flags, WIMStruct **additional_swms,
1932                                  unsigned num_additional_swms,
1933                                  const char *staging_dir)
1934 {
1935         int argc = 0;
1936         char *argv[16];
1937         int ret;
1938         char *dir_copy;
1939         struct lookup_table *joined_tab, *wim_tab_save;
1940         struct image_metadata *imd;
1941         struct wimfs_context ctx;
1942
1943         DEBUG("Mount: wim = %p, image = %d, dir = %s, flags = %d, ",
1944               wim, image, dir, mount_flags);
1945
1946         if (!wim || !dir)
1947                 return WIMLIB_ERR_INVALID_PARAM;
1948
1949         ret = verify_swm_set(wim, additional_swms, num_additional_swms);
1950         if (ret != 0)
1951                 return ret;
1952
1953         if ((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) && (wim->hdr.total_parts != 1)) {
1954                 ERROR("Cannot mount a split WIM read-write");
1955                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1956         }
1957
1958         if (num_additional_swms) {
1959                 ret = new_joined_lookup_table(wim, additional_swms,
1960                                               num_additional_swms,
1961                                               &joined_tab);
1962                 if (ret != 0)
1963                         return ret;
1964                 wim_tab_save = wim->lookup_table;
1965                 wim->lookup_table = joined_tab;
1966         }
1967
1968         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
1969                 ret = wim_run_full_verifications(wim);
1970                 if (ret != 0)
1971                         goto out;
1972         }
1973
1974         ret = select_wim_image(wim, image);
1975
1976         if (ret != 0)
1977                 goto out;
1978
1979         imd = &wim->image_metadata[image - 1];
1980
1981         DEBUG("Selected image %d", image);
1982
1983         if (imd->root_dentry->refcnt != 1) {
1984                 ERROR("Cannot mount image that was just exported with "
1985                       "wimlib_export_image()");
1986                 ret = WIMLIB_ERR_INVALID_PARAM;
1987                 goto out;
1988         }
1989
1990         if (imd->modified) {
1991                 ERROR("Cannot mount image that was added "
1992                       "with wimlib_add_image()");
1993                 ret = WIMLIB_ERR_INVALID_PARAM;
1994                 goto out;
1995         }
1996
1997         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
1998                 ret = lock_wim(wim->fp, wim->filename);
1999                 if (ret != 0)
2000                         goto out;
2001         }
2002
2003         if (!(mount_flags & (WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
2004                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
2005                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)))
2006                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
2007
2008
2009         DEBUG("Initializing struct wimfs_context");
2010         init_wimfs_context(&ctx);
2011         ctx.wim = wim;
2012         ctx.mount_flags = mount_flags;
2013
2014         DEBUG("Unlinking message queues in case they already exist");
2015         ret = set_message_queue_names(&ctx, dir);
2016         if (ret != 0)
2017                 goto out;
2018         unlink_message_queues(&ctx);
2019
2020         DEBUG("Preparing arguments to fuse_main()");
2021
2022         dir_copy = STRDUP(dir);
2023         if (!dir_copy)
2024                 goto out_free_message_queue_names;
2025
2026         argv[argc++] = "imagex";
2027         argv[argc++] = dir_copy;
2028
2029         /* disable multi-threaded operation for read-write mounts */
2030         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2031                 argv[argc++] = "-s";
2032
2033         if (mount_flags & WIMLIB_MOUNT_FLAG_DEBUG)
2034                 argv[argc++] = "-d";
2035
2036         /*
2037          * We provide the use_ino option because we are going to assign inode
2038          * numbers oursides.  The inodes will be given unique numbers in the
2039          * assign_inode_numbers() function, and the static variable @next_ino is
2040          * set to the next available inode number.
2041          */
2042         char optstring[256] = "use_ino,subtype=wimfs,attr_timeout=0";
2043         argv[argc++] = "-o";
2044         argv[argc++] = optstring;
2045         if ((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
2046                 /* Read-write mount.  Make the staging directory */
2047                 ret = make_staging_dir(&ctx, staging_dir);
2048                 if (ret != 0)
2049                         goto out_free_dir_copy;
2050         } else {
2051                 /* Read-only mount */
2052                 strcat(optstring, ",ro");
2053         }
2054         argv[argc] = NULL;
2055
2056 #ifdef ENABLE_DEBUG
2057         {
2058                 int i;
2059                 DEBUG("FUSE command line (argc = %d): ", argc);
2060                 for (i = 0; i < argc; i++) {
2061                         fputs(argv[i], stdout);
2062                         putchar(' ');
2063                 }
2064                 putchar('\n');
2065                 fflush(stdout);
2066         }
2067 #endif
2068
2069         /* Mark dentry tree as modified if read-write mount. */
2070         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2071                 imd->modified = 1;
2072                 imd->has_been_mounted_rw = 1;
2073         }
2074
2075         /* Resolve all the lookup table entries of the dentry tree */
2076         DEBUG("Resolving lookup table entries");
2077         for_dentry_in_tree(imd->root_dentry, dentry_resolve_ltes,
2078                            wim->lookup_table);
2079
2080         ctx.next_ino = assign_inode_numbers(&imd->inode_list);
2081         DEBUG("(next_ino = %"PRIu64")", ctx.next_ino);
2082
2083
2084         DEBUG("Calling fuse_main()");
2085
2086         ret = fuse_main(argc, argv, &wimfs_operations, &ctx);
2087
2088         DEBUG("Returned from fuse_main() (ret = %d)", ret);
2089         if (ret)
2090                 ret = WIMLIB_ERR_FUSE;
2091 out_free_dir_copy:
2092         FREE(dir_copy);
2093 out_free_message_queue_names:
2094         free_message_queue_names(&ctx);
2095 out:
2096         if (num_additional_swms) {
2097                 free_lookup_table(wim->lookup_table);
2098                 wim->lookup_table = wim_tab_save;
2099         }
2100         return ret;
2101 }
2102
2103
2104 /*
2105  * Unmounts the WIM file that was previously mounted on @dir by using
2106  * wimlib_mount_image().
2107  */
2108 WIMLIBAPI int wimlib_unmount_image(const char *dir, int unmount_flags,
2109                                    wimlib_progress_func_t progress_func)
2110 {
2111         pid_t pid;
2112         int status;
2113         int ret;
2114         char msg[2];
2115         struct timeval now;
2116         struct timespec timeout;
2117         long msgsize;
2118         struct wimfs_context ctx;
2119         char *mailbox;
2120
2121         init_wimfs_context(&ctx);
2122
2123         /* Open message queues between the unmount process and the
2124          * filesystem daemon. */
2125         ret = set_message_queue_names(&ctx, dir);
2126         if (ret != 0)
2127                 goto out;
2128
2129         ret = open_message_queues(&ctx, false);
2130         if (ret != 0)
2131                 goto out_free_message_queue_names;
2132
2133         /* Send a message to the filesystem daemon saying whether to commit or
2134          * not. */
2135         msg[0] = (unmount_flags & WIMLIB_UNMOUNT_FLAG_COMMIT) ? 1 : 0;
2136         msg[1] = (unmount_flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY) ? 1 : 0;
2137
2138         DEBUG("Sending message: %scommit, %scheck",
2139                         (msg[0] ? "" : "don't "),
2140                         (msg[1] ? "" : "don't "));
2141         ret = mq_send(ctx.unmount_to_daemon_mq, msg, 2, 1);
2142         if (ret == -1) {
2143                 ERROR_WITH_ERRNO("Failed to notify filesystem daemon whether "
2144                                  "we want to commit changes or not");
2145                 ret = WIMLIB_ERR_MQUEUE;
2146                 goto out_close_message_queues;
2147         }
2148
2149         /* Execute `fusermount -u', which is installed setuid root, to unmount
2150          * the WIM.
2151          *
2152          * FUSE does not yet implement synchronous unmounts.  This means that
2153          * fusermount -u will return before the filesystem daemon returns from
2154          * wimfs_destroy().  This is partly what we want, because we need to
2155          * send a message from this process to the filesystem daemon telling
2156          * whether --commit was specified or not.  However, after that, the
2157          * unmount process must wait for the filesystem daemon to finish writing
2158          * the WIM file.
2159          */
2160
2161         pid = fork();
2162         if (pid == -1) {
2163                 ERROR_WITH_ERRNO("Failed to fork()");
2164                 ret = WIMLIB_ERR_FORK;
2165                 goto out_close_message_queues;
2166         }
2167         if (pid == 0) {
2168                 /* Child */
2169                 execlp("fusermount", "fusermount", "-u", dir, NULL);
2170                 ERROR_WITH_ERRNO("Failed to execute `fusermount'");
2171                 exit(WIMLIB_ERR_FUSERMOUNT);
2172         }
2173
2174         /* Parent */
2175         ret = wait(&status);
2176         if (ret == -1) {
2177                 ERROR_WITH_ERRNO("Failed to wait for fusermount process to "
2178                                  "terminate");
2179                 ret = WIMLIB_ERR_FUSERMOUNT;
2180                 goto out_close_message_queues;
2181         }
2182
2183         if (status != 0) {
2184                 ERROR("fusermount exited with status %d", status);
2185
2186                 /* Try again, but with the `umount' program.  This is required
2187                  * on other FUSE implementations such as FreeBSD's that do not
2188                  * have a `fusermount' program. */
2189
2190                 pid = fork();
2191                 if (pid == -1) {
2192                         ERROR_WITH_ERRNO("Failed to fork()");
2193                         ret = WIMLIB_ERR_FORK;
2194                         goto out_close_message_queues;
2195                 }
2196                 if (pid == 0) {
2197                         /* Child */
2198                         execlp("umount", "umount", dir, NULL);
2199                         ERROR_WITH_ERRNO("Failed to execute `umount'");
2200                         exit(WIMLIB_ERR_FUSERMOUNT);
2201                 }
2202
2203                 /* Parent */
2204                 ret = wait(&status);
2205                 if (ret == -1) {
2206                         ERROR_WITH_ERRNO("Failed to wait for `umount' process to "
2207                                          "terminate");
2208                         ret = WIMLIB_ERR_FUSERMOUNT;
2209                         goto out_close_message_queues;
2210                 }
2211                 if (status != 0) {
2212                         ERROR("`umount' exited with failure status");
2213                         ret = WIMLIB_ERR_FUSERMOUNT;
2214                         goto out_close_message_queues;
2215                 }
2216         }
2217
2218         wimlib_assert(status == 0);
2219
2220         /* Wait for a message from the filesytem daemon indicating whether  the
2221          * filesystem was unmounted successfully (0) or an error occurred (1).
2222          * This may take a long time if a big WIM file needs to be rewritten. */
2223
2224         /* Wait at most 600??? seconds before giving up and returning false.
2225          * Either it's a really big WIM file, or (more likely) the
2226          * filesystem daemon has crashed or failed for some reason.
2227          *
2228          * XXX come up with some method to determine if the filesystem
2229          * daemon has really crashed or not.
2230          *
2231          * XXX Idea: have mount daemon write its PID into the WIM file header?
2232          * No, this wouldn't work because we know the directory but not the WIM
2233          * file...
2234          * */
2235
2236         gettimeofday(&now, NULL);
2237         timeout.tv_sec = now.tv_sec + 600;
2238         timeout.tv_nsec = now.tv_usec * 1000;
2239
2240         ret = get_mailbox(ctx.daemon_to_unmount_mq, 2, &msgsize, &mailbox);
2241         if (ret != 0)
2242                 goto out_close_message_queues;
2243
2244         mailbox[0] = 0;
2245         DEBUG("Waiting for message telling us whether the unmount was "
2246                         "successful or not.");
2247         ret = mq_timedreceive(ctx.daemon_to_unmount_mq, mailbox,
2248                               msgsize, NULL, &timeout);
2249         if (ret == -1) {
2250                 if (errno == ETIMEDOUT) {
2251                         ERROR("Timed out- probably the filesystem daemon "
2252                               "crashed and the WIM was not written "
2253                               "successfully.");
2254                         ret = WIMLIB_ERR_TIMEOUT;
2255                 } else {
2256                         ERROR_WITH_ERRNO("mq_receive()");
2257                         ret = WIMLIB_ERR_MQUEUE;
2258                 }
2259                 goto out_free_mailbox;
2260
2261         }
2262         DEBUG("Received message: Unmount %s", (mailbox[0] ? "Failed" : "Ok"));
2263         ret = mailbox[0];
2264         if (ret)
2265                 ERROR("Unmount failed");
2266 out_free_mailbox:
2267         FREE(mailbox);
2268 out_close_message_queues:
2269         close_message_queues(&ctx);
2270 out_free_message_queue_names:
2271         free_message_queue_names(&ctx);
2272 out:
2273         return ret;
2274 }
2275
2276 #else /* WITH_FUSE */
2277
2278
2279 static inline int mount_unsupported_error()
2280 {
2281         ERROR("wimlib was compiled with --without-fuse, which disables support "
2282               "for mounting WIMs.");
2283         return WIMLIB_ERR_UNSUPPORTED;
2284 }
2285
2286 WIMLIBAPI int wimlib_unmount_image(const char *dir, int unmount_flags,
2287                                    wimlib_progress_func_t progress_func)
2288 {
2289         return mount_unsupported_error();
2290 }
2291
2292 WIMLIBAPI int wimlib_mount_image(WIMStruct *wim_p, int image, const char *dir,
2293                                  int mount_flags, WIMStruct **additional_swms,
2294                                  unsigned num_additional_swms,
2295                                  const char *staging_dir)
2296 {
2297         return mount_unsupported_error();
2298 }
2299
2300 #endif /* WITH_FUSE */