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