]> wimlib.net Git - wimlib/blob - src/mount_image.c
Implement unmount progress callback
[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                        wimlib_progress_func_t progress_func)
771 {
772         int ret;
773         struct lookup_table_entry *lte, *tmp;
774         WIMStruct *w = ctx->wim;
775
776         DEBUG("Closing all staging file descriptors.");
777         list_for_each_entry_safe(lte, tmp, &ctx->staging_list, staging_list) {
778                 ret = inode_close_fds(lte->lte_inode);
779                 if (ret != 0)
780                         return ret;
781         }
782
783         DEBUG("Calculating SHA1 checksums for all new staging files.");
784         list_for_each_entry(lte, &ctx->staging_list, staging_list) {
785                 ret = update_lte_of_staging_file(lte, w->lookup_table);
786                 if (ret != 0)
787                         return ret;
788         }
789
790         xml_update_image_info(w, w->current_image);
791         ret = wimlib_overwrite(w, write_flags, 0, progress_func);
792         if (ret != 0)
793                 ERROR("Failed to commit changes to mounted WIM image");
794         return ret;
795 }
796
797
798
799 /* Simple function that returns the concatenation of 2 strings. */
800 static char *strcat_dup(const char *s1, const char *s2, size_t max_len)
801 {
802         size_t len = strlen(s1) + strlen(s2);
803         if (len > max_len)
804                 len = max_len;
805         char *p = MALLOC(len + 1);
806         if (!p)
807                 return NULL;
808         snprintf(p, len + 1, "%s%s", s1, s2);
809         return p;
810 }
811
812 static int set_message_queue_names(struct wimfs_context *ctx,
813                                    const char *mount_dir)
814 {
815         static const char *u2d_prefix = "/wimlib-unmount-to-daemon-mq";
816         static const char *d2u_prefix = "/wimlib-daemon-to-unmount-mq";
817         char *dir_path;
818         char *p;
819         int ret;
820
821         dir_path = realpath(mount_dir, NULL);
822         if (!dir_path) {
823                 ERROR_WITH_ERRNO("Failed to resolve path \"%s\"", mount_dir);
824                 if (errno == ENOMEM)
825                         return WIMLIB_ERR_NOMEM;
826                 else
827                         return WIMLIB_ERR_NOTDIR;
828         }
829
830         p = dir_path;
831         while (*p) {
832                 if (*p == '/')
833                         *p = 0xff;
834                 p++;
835         }
836
837         ctx->unmount_to_daemon_mq_name = strcat_dup(u2d_prefix, dir_path,
838                                                     NAME_MAX);
839         if (!ctx->unmount_to_daemon_mq_name) {
840                 ret = WIMLIB_ERR_NOMEM;
841                 goto out_free_dir_path;
842         }
843         ctx->daemon_to_unmount_mq_name = strcat_dup(d2u_prefix, dir_path,
844                                                     NAME_MAX);
845         if (!ctx->daemon_to_unmount_mq_name) {
846                 ret = WIMLIB_ERR_NOMEM;
847                 goto out_free_unmount_to_daemon_mq_name;
848         }
849
850         ret = 0;
851         goto out_free_dir_path;
852 out_free_unmount_to_daemon_mq_name:
853         FREE(ctx->unmount_to_daemon_mq_name);
854         ctx->unmount_to_daemon_mq_name = NULL;
855 out_free_dir_path:
856         FREE(dir_path);
857         return ret;
858 }
859
860 static void free_message_queue_names(struct wimfs_context *ctx)
861 {
862         FREE(ctx->unmount_to_daemon_mq_name);
863         FREE(ctx->daemon_to_unmount_mq_name);
864         ctx->unmount_to_daemon_mq_name = NULL;
865         ctx->daemon_to_unmount_mq_name = NULL;
866 }
867
868 /*
869  * Opens two POSIX message queue: one for sending messages from the unmount
870  * process to the daemon process, and one to go the other way.  The names of the
871  * message queues, which must be system-wide unique, are be based on the mount
872  * point.
873  *
874  * @daemon specifies whether the calling process is the filesystem daemon or the
875  * unmount process.
876  */
877 static int open_message_queues(struct wimfs_context *ctx, bool daemon)
878 {
879         int unmount_to_daemon_mq_flags = O_WRONLY | O_CREAT;
880         int daemon_to_unmount_mq_flags = O_RDONLY | O_CREAT;
881
882         if (daemon)
883                 swap(unmount_to_daemon_mq_flags, daemon_to_unmount_mq_flags);
884
885         DEBUG("Opening message queue \"%s\"", ctx->unmount_to_daemon_mq_name);
886         ctx->unmount_to_daemon_mq = mq_open(ctx->unmount_to_daemon_mq_name,
887                                             unmount_to_daemon_mq_flags, 0700, NULL);
888
889         if (ctx->unmount_to_daemon_mq == (mqd_t)-1) {
890                 ERROR_WITH_ERRNO("mq_open()");
891                 return WIMLIB_ERR_MQUEUE;
892         }
893
894         DEBUG("Opening message queue \"%s\"", ctx->daemon_to_unmount_mq_name);
895         ctx->daemon_to_unmount_mq = mq_open(ctx->daemon_to_unmount_mq_name,
896                                             daemon_to_unmount_mq_flags, 0700, NULL);
897
898         if (ctx->daemon_to_unmount_mq == (mqd_t)-1) {
899                 ERROR_WITH_ERRNO("mq_open()");
900                 mq_close(ctx->unmount_to_daemon_mq);
901                 mq_unlink(ctx->unmount_to_daemon_mq_name);
902                 ctx->unmount_to_daemon_mq = (mqd_t)-1;
903                 return WIMLIB_ERR_MQUEUE;
904         }
905         return 0;
906 }
907
908 /* Try to determine the maximum message size of a message queue.  The return
909  * value is the maximum message size, or a guess of 8192 bytes if it cannot be
910  * determined. */
911 static long mq_get_msgsize(mqd_t mq)
912 {
913         static const char *msgsize_max_file = "/proc/sys/fs/mqueue/msgsize_max";
914         FILE *fp;
915         struct mq_attr attr;
916         long msgsize;
917
918         if (mq_getattr(mq, &attr) == 0) {
919                 msgsize = attr.mq_msgsize;
920         } else {
921                 ERROR_WITH_ERRNO("mq_getattr()");
922                 ERROR("Attempting to read %s", msgsize_max_file);
923                 fp = fopen(msgsize_max_file, "rb");
924                 if (fp) {
925                         if (fscanf(fp, "%ld", &msgsize) != 1) {
926                                 ERROR("Assuming message size of 8192");
927                                 msgsize = 8192;
928                         }
929                         fclose(fp);
930                 } else {
931                         ERROR_WITH_ERRNO("Failed to open the file `%s'",
932                                          msgsize_max_file);
933                         ERROR("Assuming message size of 8192");
934                         msgsize = 8192;
935                 }
936         }
937         return msgsize;
938 }
939
940 static int get_mailbox(mqd_t mq, long needed_msgsize, long *msgsize_ret,
941                        void **mailbox_ret)
942 {
943         long msgsize;
944         char *mailbox;
945
946         msgsize = mq_get_msgsize(mq);
947
948         if (msgsize < needed_msgsize) {
949                 ERROR("Message queue max size must be at least %ld!",
950                       needed_msgsize);
951                 return WIMLIB_ERR_MQUEUE;
952         }
953
954         mailbox = MALLOC(msgsize);
955         if (!mailbox) {
956                 ERROR("Failed to allocate %ld bytes for mailbox", msgsize);
957                 return WIMLIB_ERR_NOMEM;
958         }
959         *msgsize_ret = msgsize;
960         *mailbox_ret = mailbox;
961         return 0;
962 }
963
964 static void unlink_message_queues(struct wimfs_context *ctx)
965 {
966         mq_unlink(ctx->unmount_to_daemon_mq_name);
967         mq_unlink(ctx->daemon_to_unmount_mq_name);
968 }
969
970 /* Closes the message queues, which are allocated in static variables */
971 static void close_message_queues(struct wimfs_context *ctx)
972 {
973         DEBUG("Closing message queues");
974         mq_close(ctx->unmount_to_daemon_mq);
975         ctx->unmount_to_daemon_mq = (mqd_t)(-1);
976         mq_close(ctx->daemon_to_unmount_mq);
977         ctx->daemon_to_unmount_mq = (mqd_t)(-1);
978         unlink_message_queues(ctx);
979 }
980
981
982 struct unmount_msg_hdr {
983         u32 min_version;
984         u32 cur_version;
985         u32 msg_type;
986         u32 msg_size;
987 } PACKED;
988
989 struct msg_unmount_request {
990         struct unmount_msg_hdr hdr;
991         u32 unmount_flags;
992         u8 want_progress_messages;
993 } PACKED;
994
995 struct msg_daemon_info {
996         struct unmount_msg_hdr hdr;
997         pid_t daemon_pid;
998         u32 mount_flags;
999 } PACKED;
1000
1001 struct msg_unmount_finished {
1002         struct unmount_msg_hdr hdr;
1003         int32_t status;
1004 } PACKED;
1005
1006 struct msg_write_streams_progress {
1007         struct unmount_msg_hdr hdr;
1008         union wimlib_progress_info info;
1009 } PACKED;
1010
1011 enum {
1012         MSG_TYPE_UNMOUNT_REQUEST,
1013         MSG_TYPE_DAEMON_INFO,
1014         MSG_TYPE_WRITE_STREAMS_PROGRESS,
1015         MSG_TYPE_UNMOUNT_FINISHED,
1016         MSG_TYPE_MAX,
1017 };
1018
1019 struct msg_handler_context {
1020         bool is_daemon;
1021         int timeout_seconds;
1022         union {
1023                 struct {
1024                         pid_t daemon_pid;
1025                         int mount_flags;
1026                         int status;
1027                         wimlib_progress_func_t progress_func;
1028                 } unmount;
1029                 struct {
1030                         struct wimfs_context *wimfs_ctx;
1031                 } daemon;
1032         };
1033 };
1034
1035 static int send_unmount_request_msg(mqd_t mq, int unmount_flags,
1036                                     u8 want_progress_messages)
1037 {
1038         DEBUG("Sending unmount request msg");
1039         struct msg_unmount_request msg = {
1040                 .hdr = {
1041                         .min_version = WIMLIB_MAKEVERSION(1, 2, 0),
1042                         .cur_version = WIMLIB_VERSION_CODE,
1043                         .msg_type    = MSG_TYPE_UNMOUNT_REQUEST,
1044                         .msg_size    = sizeof(msg),
1045                 },
1046                 .unmount_flags = unmount_flags,
1047                 .want_progress_messages = want_progress_messages,
1048         };
1049
1050         if (mq_send(mq, (void*)&msg, sizeof(msg), 1)) {
1051                 ERROR_WITH_ERRNO("Failed to communicate with filesystem daemon");
1052                 return WIMLIB_ERR_MQUEUE;
1053         }
1054         return 0;
1055 }
1056
1057 static int send_daemon_info_msg(mqd_t mq, pid_t pid, int mount_flags)
1058 {
1059         DEBUG("Sending daemon info msg (pid = %d, mount_flags=%x)",
1060               pid, mount_flags);
1061
1062         struct msg_daemon_info msg = {
1063                 .hdr = {
1064                         .min_version = WIMLIB_MAKEVERSION(1, 2, 0),
1065                         .cur_version = WIMLIB_VERSION_CODE,
1066                         .msg_type = MSG_TYPE_DAEMON_INFO,
1067                         .msg_size = sizeof(msg),
1068                 },
1069                 .daemon_pid = pid,
1070                 .mount_flags = mount_flags,
1071         };
1072         if (mq_send(mq, (void*)&msg, sizeof(msg), 1)) {
1073                 ERROR_WITH_ERRNO("Failed to send daemon info to unmount process");
1074                 return WIMLIB_ERR_MQUEUE;
1075         }
1076         return 0;
1077 }
1078
1079 static void send_unmount_finished_msg(mqd_t mq, int status)
1080 {
1081         DEBUG("Sending unmount finished msg");
1082         struct msg_unmount_finished msg = {
1083                 .hdr = {
1084                         .min_version = WIMLIB_MAKEVERSION(1, 2, 0),
1085                         .cur_version = WIMLIB_VERSION_CODE,
1086                         .msg_type = MSG_TYPE_UNMOUNT_FINISHED,
1087                         .msg_size = sizeof(msg),
1088                 },
1089                 .status = status,
1090         };
1091         if (mq_send(mq, (void*)&msg, sizeof(msg), 1))
1092                 ERROR_WITH_ERRNO("Failed to send status to unmount process");
1093 }
1094
1095 static int unmount_progress_func(enum wimlib_progress_msg msg,
1096                                  const union wimlib_progress_info *info)
1097 {
1098         if (msg == WIMLIB_PROGRESS_MSG_WRITE_STREAMS) {
1099                 struct msg_write_streams_progress msg = {
1100                         .hdr = {
1101                                 .min_version = WIMLIB_MAKEVERSION(1, 2, 0),
1102                                 .cur_version = WIMLIB_VERSION_CODE,
1103                                 .msg_type = MSG_TYPE_WRITE_STREAMS_PROGRESS,
1104                                 .msg_size = sizeof(msg),
1105                         },
1106                         .info = *info,
1107                 };
1108                 if (mq_send(wimfs_get_context()->daemon_to_unmount_mq,
1109                             (void*)&msg, sizeof(msg), 1))
1110                 {
1111                         ERROR_WITH_ERRNO("Failed to send status to unmount process");
1112                 }
1113         }
1114         return 0;
1115 }
1116
1117 static int msg_unmount_request_handler(const void *_msg,
1118                                        struct msg_handler_context *handler_ctx)
1119 {
1120         const struct msg_unmount_request *msg;
1121         struct wimfs_context *wimfs_ctx;
1122         int status = 0;
1123         int ret;
1124         int unmount_flags;
1125
1126         DEBUG("Handling unmount request msg");
1127
1128         msg = _msg;
1129         wimfs_ctx = handler_ctx->daemon.wimfs_ctx;
1130
1131         if (msg->hdr.msg_size < sizeof(*msg)) {
1132                 status = WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE;
1133                 goto out;
1134         }
1135
1136         unmount_flags = msg->unmount_flags;
1137
1138         ret = send_daemon_info_msg(wimfs_ctx->daemon_to_unmount_mq, getpid(),
1139                                    wimfs_ctx->mount_flags);
1140         if (ret != 0) {
1141                 status = ret;
1142                 goto out;
1143         }
1144
1145         if (wimfs_ctx->mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
1146                 if (unmount_flags & WIMLIB_UNMOUNT_FLAG_COMMIT) {
1147                         int write_flags = 0;
1148                         if (unmount_flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY)
1149                                 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1150                         if (unmount_flags & WIMLIB_UNMOUNT_FLAG_REBUILD)
1151                                 write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1152                         if (unmount_flags & WIMLIB_UNMOUNT_FLAG_RECOMPRESS)
1153                                 write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
1154                         status = rebuild_wim(wimfs_ctx, write_flags,
1155                                              unmount_progress_func);
1156                 }
1157         } else {
1158                 DEBUG("Read-only mount");
1159                 status = 0;
1160         }
1161
1162 out:
1163         if (wimfs_ctx->mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
1164                 ret = delete_staging_dir(wimfs_ctx);
1165                 if (ret != 0) {
1166                         ERROR("Failed to delete the staging directory");
1167                         if (status == 0)
1168                                 status = ret;
1169                 }
1170         }
1171         send_unmount_finished_msg(wimfs_ctx->daemon_to_unmount_mq, status);
1172         return MSG_BREAK_LOOP;
1173 }
1174
1175 static int msg_daemon_info_handler(const void *_msg,
1176                                    struct msg_handler_context *handler_ctx)
1177 {
1178         const struct msg_daemon_info *msg = _msg;
1179         DEBUG("Handling daemon info msg");
1180         if (msg->hdr.msg_size < sizeof(*msg))
1181                 return WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE;
1182         handler_ctx->unmount.daemon_pid = msg->daemon_pid;
1183         handler_ctx->unmount.mount_flags = msg->mount_flags;
1184         handler_ctx->timeout_seconds = 1;
1185         DEBUG("pid of daemon is %d; mount flags were %#x",
1186               handler_ctx->unmount.daemon_pid,
1187               handler_ctx->unmount.mount_flags);
1188         return 0;
1189 }
1190
1191 static int msg_write_streams_progress_handler(const void *_msg,
1192                                               struct msg_handler_context *handler_ctx)
1193 {
1194         const struct msg_write_streams_progress *msg = _msg;
1195         if (msg->hdr.msg_size < sizeof(*msg))
1196                 return WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE;
1197         if (handler_ctx->unmount.progress_func) {
1198                 handler_ctx->unmount.progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1199                                                    &msg->info);
1200         }
1201         return 0;
1202 }
1203
1204 static int msg_unmount_finished_handler(const void *_msg,
1205                                         struct msg_handler_context *handler_ctx)
1206 {
1207         const struct msg_unmount_finished *msg = _msg;
1208         DEBUG("Handling unmount finished message");
1209         if (msg->hdr.msg_size < sizeof(*msg))
1210                 return WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE;
1211         handler_ctx->unmount.status = msg->status;
1212         DEBUG("status is %d", handler_ctx->unmount.status);
1213         return MSG_BREAK_LOOP;
1214 }
1215
1216 static int unmount_timed_out_cb(struct msg_handler_context *handler_ctx)
1217 {
1218         if (handler_ctx->unmount.daemon_pid == 0) {
1219                 goto out_crashed;
1220         } else {
1221                 kill(handler_ctx->unmount.daemon_pid, 0);
1222                 if (errno == ESRCH) {
1223                         goto out_crashed;
1224                 } else {
1225                         DEBUG("Filesystem daemon is still alive... "
1226                               "Waiting another %d seconds\n",
1227                               handler_ctx->timeout_seconds);
1228                         return 0;
1229                 }
1230         }
1231 out_crashed:
1232         ERROR("The filesystem daemon has crashed!  Changes to the "
1233               "WIM may not have been commited.");
1234         return WIMLIB_ERR_FILESYSTEM_DAEMON_CRASHED;
1235 }
1236
1237 static int daemon_timed_out_cb(struct msg_handler_context *handler_ctx)
1238 {
1239         DEBUG("Timed out");
1240         return WIMLIB_ERR_TIMEOUT;
1241 }
1242
1243 typedef int (*msg_handler_t)(const void *_msg,
1244                              struct msg_handler_context *handler_ctx);
1245
1246 struct msg_handler_callbacks {
1247         int (*timed_out)(struct msg_handler_context *);
1248         msg_handler_t msg_handlers[MSG_TYPE_MAX];
1249 };
1250
1251 static const struct msg_handler_callbacks unmount_msg_handler_callbacks = {
1252         .timed_out = unmount_timed_out_cb,
1253         .msg_handlers = {
1254                 [MSG_TYPE_DAEMON_INFO] = msg_daemon_info_handler,
1255                 [MSG_TYPE_WRITE_STREAMS_PROGRESS] = msg_write_streams_progress_handler,
1256                 [MSG_TYPE_UNMOUNT_FINISHED] = msg_unmount_finished_handler,
1257         },
1258 };
1259
1260 static const struct msg_handler_callbacks daemon_msg_handler_callbacks = {
1261         .timed_out = daemon_timed_out_cb,
1262         .msg_handlers = {
1263                 [MSG_TYPE_UNMOUNT_REQUEST] = msg_unmount_request_handler,
1264         },
1265 };
1266
1267 static int receive_message(mqd_t mq, struct msg_handler_context *handler_ctx,
1268                            const msg_handler_t msg_handlers[],
1269                            long mailbox_size, void *mailbox)
1270 {
1271         struct timeval now;
1272         struct timespec timeout;
1273         ssize_t bytes_received;
1274         struct unmount_msg_hdr *hdr;
1275         int ret;
1276
1277         gettimeofday(&now, NULL);
1278         timeout.tv_sec = now.tv_sec + handler_ctx->timeout_seconds;
1279         timeout.tv_nsec = now.tv_usec * 1000;
1280
1281         bytes_received = mq_timedreceive(mq, mailbox,
1282                                          mailbox_size, NULL, &timeout);
1283         hdr = mailbox;
1284         if (bytes_received == -1) {
1285                 if (errno == ETIMEDOUT) {
1286                         ret = WIMLIB_ERR_TIMEOUT;
1287                 } else {
1288                         ERROR_WITH_ERRNO("mq_timedreceive()");
1289                         ret = WIMLIB_ERR_MQUEUE;
1290                 }
1291         } else if (bytes_received < sizeof(*hdr) ||
1292                    bytes_received != hdr->msg_size) {
1293                 ret = WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE;
1294         } else if (WIMLIB_VERSION_CODE < hdr->min_version) {
1295                 /*ERROR("Cannot understand the received message. "*/
1296                       /*"Please upgrade wimlib to at least v%d.%d.%d",*/
1297                       /*WIMLIB_GET_MAJOR_VERSION(hdr->min_version),*/
1298                       /*WIMLIB_GET_MINOR_VERSION(hdr->min_version),*/
1299                       /*WIMLIB_GET_PATCH_VERSION(hdr->min_version));*/
1300                 ret = MSG_VERSION_TOO_HIGH;
1301         } else if (hdr->msg_type >= MSG_TYPE_MAX) {
1302                 ret = WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE;
1303         } else if (msg_handlers[hdr->msg_type] == NULL) {
1304                 ret = WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE;
1305         } else {
1306                 ret = msg_handlers[hdr->msg_type](mailbox, handler_ctx);
1307         }
1308         return ret;
1309 }
1310
1311 static int message_loop(mqd_t mq,
1312                         const struct msg_handler_callbacks *callbacks,
1313                         struct msg_handler_context *handler_ctx)
1314 {
1315         static const size_t MAX_MSG_SIZE = 512;
1316         long msgsize;
1317         void *mailbox;
1318         int ret;
1319
1320         DEBUG("Entering message loop");
1321
1322         ret = get_mailbox(mq, MAX_MSG_SIZE, &msgsize, &mailbox);
1323         if (ret != 0)
1324                 return ret;
1325         while (1) {
1326                 ret = receive_message(mq, handler_ctx,
1327                                       callbacks->msg_handlers,
1328                                       msgsize, mailbox);
1329                 if (ret == 0 || ret == MSG_VERSION_TOO_HIGH) {
1330                         continue;
1331                 } else if (ret == MSG_BREAK_LOOP) {
1332                         ret = 0;
1333                         break;
1334                 } else if (ret == WIMLIB_ERR_TIMEOUT) {
1335                         if (callbacks->timed_out)
1336                                 ret = callbacks->timed_out(handler_ctx);
1337                         if (ret == 0)
1338                                 continue;
1339                         else
1340                                 break;
1341                 } else {
1342                         ERROR_WITH_ERRNO("Error communicating with "
1343                                          "filesystem daemon");
1344                         break;
1345                 }
1346         }
1347         FREE(mailbox);
1348         DEBUG("Exiting message loop");
1349         return ret;
1350 }
1351
1352 /* Execute `fusermount -u', which is installed setuid root, to unmount the WIM.
1353  *
1354  * FUSE does not yet implement synchronous unmounts.  This means that fusermount
1355  * -u will return before the filesystem daemon returns from wimfs_destroy().
1356  *  This is partly what we want, because we need to send a message from this
1357  *  process to the filesystem daemon telling whether --commit was specified or
1358  *  not.  However, after that, the unmount process must wait for the filesystem
1359  *  daemon to finish writing the WIM file.
1360  */
1361 static int execute_fusermount(const char *dir)
1362 {
1363         pid_t pid;
1364         int ret;
1365         int status;
1366
1367         pid = fork();
1368         if (pid == -1) {
1369                 ERROR_WITH_ERRNO("Failed to fork()");
1370                 return WIMLIB_ERR_FORK;
1371         }
1372         if (pid == 0) {
1373                 /* Child */
1374                 execlp("fusermount", "fusermount", "-u", dir, NULL);
1375                 ERROR_WITH_ERRNO("Failed to execute `fusermount'");
1376                 exit(WIMLIB_ERR_FUSERMOUNT);
1377         }
1378
1379         /* Parent */
1380         ret = wait(&status);
1381         if (ret == -1) {
1382                 ERROR_WITH_ERRNO("Failed to wait for fusermount process to "
1383                                  "terminate");
1384                 return WIMLIB_ERR_FUSERMOUNT;
1385         }
1386
1387         if (status != 0) {
1388                 if (status == WIMLIB_ERR_FUSERMOUNT)
1389                         ERROR("Could not find the `fusermount' program");
1390                 else
1391                         ERROR("fusermount exited with status %d", status);
1392
1393                 /* Try again, but with the `umount' program.  This is required
1394                  * on other FUSE implementations such as FreeBSD's that do not
1395                  * have a `fusermount' program. */
1396
1397                 pid = fork();
1398                 if (pid == -1) {
1399                         ERROR_WITH_ERRNO("Failed to fork()");
1400                         return WIMLIB_ERR_FORK;
1401                 }
1402                 if (pid == 0) {
1403                         /* Child */
1404                         execlp("umount", "umount", dir, NULL);
1405                         ERROR_WITH_ERRNO("Failed to execute `umount'");
1406                         exit(WIMLIB_ERR_FUSERMOUNT);
1407                 }
1408
1409                 /* Parent */
1410                 ret = wait(&status);
1411                 if (ret == -1) {
1412                         ERROR_WITH_ERRNO("Failed to wait for `umount' process to "
1413                                          "terminate");
1414                         return WIMLIB_ERR_FUSERMOUNT;
1415                 }
1416                 if (status != 0) {
1417                         ERROR("`umount' exited with failure status");
1418                         return WIMLIB_ERR_FUSERMOUNT;
1419                 }
1420         }
1421         return 0;
1422 }
1423
1424 static int wimfs_access(const char *path, int mask)
1425 {
1426         /* Permissions not implemented */
1427         return 0;
1428 }
1429
1430 static int wimfs_chmod(const char *path, mode_t mask)
1431 {
1432         struct dentry *dentry;
1433         struct wimfs_context *ctx = wimfs_get_context();
1434         struct inode *inode;
1435         struct stat stbuf;
1436         int ret;
1437
1438         ret = lookup_resource(ctx->wim, path,
1439                               get_lookup_flags(ctx) | LOOKUP_FLAG_DIRECTORY_OK,
1440                               &dentry, NULL, NULL);
1441         if (ret != 0)
1442                 return ret;
1443         inode = dentry->d_inode;
1444         inode_to_stbuf(inode, NULL, &stbuf);
1445         if (mask == stbuf.st_mode)
1446                 return 0;
1447         else
1448                 return -EPERM;
1449 }
1450
1451 /* Called when the filesystem is unmounted. */
1452 static void wimfs_destroy(void *p)
1453 {
1454         struct wimfs_context *wimfs_ctx;
1455
1456         wimfs_ctx = wimfs_get_context();
1457
1458         if (open_message_queues(wimfs_ctx, true))
1459                 return;
1460
1461         struct msg_handler_context handler_ctx = {
1462                 .is_daemon = true,
1463                 .timeout_seconds = 5,
1464                 .daemon = {
1465                         .wimfs_ctx = wimfs_ctx,
1466                 },
1467         };
1468
1469         message_loop(wimfs_ctx->unmount_to_daemon_mq,
1470                      &daemon_msg_handler_callbacks,
1471                      &handler_ctx);
1472
1473         close_message_queues(wimfs_ctx);
1474 }
1475
1476 #if 0
1477 static int wimfs_fallocate(const char *path, int mode,
1478                            off_t offset, off_t len, struct fuse_file_info *fi)
1479 {
1480         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1481         wimlib_assert(fd->staging_fd != -1);
1482         return fallocate(fd->staging_fd, mode, offset, len);
1483 }
1484
1485 #endif
1486
1487 static int wimfs_fgetattr(const char *path, struct stat *stbuf,
1488                           struct fuse_file_info *fi)
1489 {
1490         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1491         return inode_to_stbuf(fd->f_inode, fd->f_lte, stbuf);
1492 }
1493
1494 static int wimfs_ftruncate(const char *path, off_t size,
1495                            struct fuse_file_info *fi)
1496 {
1497         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1498         int ret = ftruncate(fd->staging_fd, size);
1499         if (ret != 0)
1500                 return -errno;
1501         if (fd->f_lte && size < fd->f_lte->resource_entry.original_size)
1502                 fd->f_lte->resource_entry.original_size = size;
1503         return 0;
1504 }
1505
1506 /*
1507  * Fills in a `struct stat' that corresponds to a file or directory in the WIM.
1508  */
1509 static int wimfs_getattr(const char *path, struct stat *stbuf)
1510 {
1511         struct dentry *dentry;
1512         struct lookup_table_entry *lte;
1513         int ret;
1514         struct wimfs_context *ctx = wimfs_get_context();
1515
1516         ret = lookup_resource(ctx->wim, path,
1517                               get_lookup_flags(ctx) | LOOKUP_FLAG_DIRECTORY_OK,
1518                               &dentry, &lte, NULL);
1519         if (ret != 0)
1520                 return ret;
1521         return inode_to_stbuf(dentry->d_inode, lte, stbuf);
1522 }
1523
1524 #ifdef ENABLE_XATTR
1525 /* Read an alternate data stream through the XATTR interface, or get its size */
1526 static int wimfs_getxattr(const char *path, const char *name, char *value,
1527                           size_t size)
1528 {
1529         int ret;
1530         struct inode *inode;
1531         struct ads_entry *ads_entry;
1532         size_t res_size;
1533         struct lookup_table_entry *lte;
1534         struct wimfs_context *ctx = wimfs_get_context();
1535
1536         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1537                 return -ENOTSUP;
1538
1539         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1540                 return -ENOATTR;
1541         name += 5;
1542
1543         inode = wim_pathname_to_inode(ctx->wim, path);
1544         if (!inode)
1545                 return -ENOENT;
1546
1547         ads_entry = inode_get_ads_entry(inode, name, NULL);
1548         if (!ads_entry)
1549                 return -ENOATTR;
1550
1551         lte = ads_entry->lte;
1552         res_size = wim_resource_size(lte);
1553
1554         if (size == 0)
1555                 return res_size;
1556
1557         if (res_size > size)
1558                 return -ERANGE;
1559
1560         ret = read_full_wim_resource(lte, (u8*)value,
1561                                      WIMLIB_RESOURCE_FLAG_MULTITHREADED);
1562         if (ret != 0)
1563                 return -EIO;
1564
1565         return res_size;
1566 }
1567 #endif
1568
1569 /* Create a hard link */
1570 static int wimfs_link(const char *to, const char *from)
1571 {
1572         struct dentry *from_dentry, *from_dentry_parent;
1573         const char *link_name;
1574         struct inode *inode;
1575         struct lookup_table_entry *lte;
1576         WIMStruct *w = wimfs_get_WIMStruct();
1577         u16 i;
1578
1579         inode = wim_pathname_to_inode(w, to);
1580         if (!inode)
1581                 return -ENOENT;
1582
1583         if (inode->attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1584                 return -EEXIST;
1585
1586         if (inode->attributes & FILE_ATTRIBUTE_DIRECTORY)
1587                 return -EPERM;
1588
1589         from_dentry_parent = get_parent_dentry(w, from);
1590         if (!from_dentry_parent)
1591                 return -ENOENT;
1592         if (!dentry_is_directory(from_dentry_parent))
1593                 return -ENOTDIR;
1594
1595         link_name = path_basename(from);
1596         if (get_dentry_child_with_name(from_dentry_parent, link_name))
1597                 return -EEXIST;
1598         from_dentry = new_dentry(link_name);
1599         if (!from_dentry)
1600                 return -ENOMEM;
1601
1602         inode_add_dentry(from_dentry, inode);
1603         from_dentry->d_inode = inode;
1604         inode->link_count++;
1605
1606         for (i = 0; i <= inode->num_ads; i++) {
1607                 lte = inode_stream_lte_resolved(inode, i);
1608                 if (lte)
1609                         lte->refcnt++;
1610         }
1611         dentry_add_child(from_dentry_parent, from_dentry);
1612         return 0;
1613 }
1614
1615 #ifdef ENABLE_XATTR
1616 static int wimfs_listxattr(const char *path, char *list, size_t size)
1617 {
1618         size_t needed_size;
1619         struct inode *inode;
1620         struct wimfs_context *ctx = wimfs_get_context();
1621         u16 i;
1622         char *p;
1623
1624         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1625                 return -ENOTSUP;
1626
1627         /* List alternate data streams, or get the list size */
1628
1629         inode = wim_pathname_to_inode(ctx->wim, path);
1630         if (!inode)
1631                 return -ENOENT;
1632
1633         if (size == 0) {
1634                 needed_size = 0;
1635                 for (i = 0; i < inode->num_ads; i++)
1636                         needed_size += inode->ads_entries[i].stream_name_utf8_len + 6;
1637                 return needed_size;
1638         } else {
1639                 p = list;
1640                 for (i = 0; i < inode->num_ads; i++) {
1641                         needed_size = inode->ads_entries[i].stream_name_utf8_len + 6;
1642                         if (needed_size > size)
1643                                 return -ERANGE;
1644                         p += sprintf(p, "user.%s",
1645                                      inode->ads_entries[i].stream_name_utf8) + 1;
1646                         size -= needed_size;
1647                 }
1648                 return p - list;
1649         }
1650 }
1651 #endif
1652
1653
1654 /* Create a directory in the WIM.
1655  * @mode is currently ignored.  */
1656 static int wimfs_mkdir(const char *path, mode_t mode)
1657 {
1658         struct dentry *dentry;
1659         int ret;
1660
1661         ret = create_dentry(wimfs_get_context(), path, &dentry);
1662         if (ret == 0)
1663                 dentry->d_inode->attributes = FILE_ATTRIBUTE_DIRECTORY;
1664         return ret;
1665 }
1666
1667 /* Create a regular file in the WIM.
1668  * @mode is currently ignored.  */
1669 static int wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
1670 {
1671         const char *stream_name;
1672         struct wimfs_context *ctx = wimfs_get_context();
1673         if ((ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
1674              && (stream_name = path_stream_name(path))) {
1675                 /* Make an alternate data stream */
1676                 struct ads_entry *new_entry;
1677                 struct inode *inode;
1678
1679                 char *p = (char*)stream_name - 1;
1680                 wimlib_assert(*p == ':');
1681                 *p = '\0';
1682
1683                 inode = wim_pathname_to_inode(ctx->wim, path);
1684                 if (!inode)
1685                         return -ENOENT;
1686                 if (inode->attributes &
1687                     (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1688                         return -ENOENT;
1689                 if (inode_get_ads_entry(inode, stream_name, NULL))
1690                         return -EEXIST;
1691                 new_entry = inode_add_ads(inode, stream_name);
1692                 if (!new_entry)
1693                         return -ENOMEM;
1694                 return 0;
1695         } else {
1696                 struct dentry *dentry;
1697                 int ret;
1698
1699                 /* Make a normal file (not an alternate data stream) */
1700                 ret = create_dentry(ctx, path, &dentry);
1701                 if (ret == 0)
1702                         dentry->d_inode->attributes = FILE_ATTRIBUTE_NORMAL;
1703                 return ret;
1704         }
1705 }
1706
1707
1708 /* Open a file.  */
1709 static int wimfs_open(const char *path, struct fuse_file_info *fi)
1710 {
1711         struct dentry *dentry;
1712         struct lookup_table_entry *lte;
1713         int ret;
1714         struct wimlib_fd *fd;
1715         struct inode *inode;
1716         u16 stream_idx;
1717         u32 stream_id;
1718         struct wimfs_context *ctx = wimfs_get_context();
1719
1720         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1721                               &dentry, &lte, &stream_idx);
1722         if (ret != 0)
1723                 return ret;
1724
1725         inode = dentry->d_inode;
1726
1727         if (stream_idx == 0)
1728                 stream_id = 0;
1729         else
1730                 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
1731
1732         /* The file resource may be in the staging directory (read-write mounts
1733          * only) or in the WIM.  If it's in the staging directory, we need to
1734          * open a native file descriptor for the corresponding file.  Otherwise,
1735          * we can read the file resource directly from the WIM file if we are
1736          * opening it read-only, but we need to extract the resource to the
1737          * staging directory if we are opening it writable. */
1738
1739         if (flags_writable(fi->flags) &&
1740             (!lte || lte->resource_location != RESOURCE_IN_STAGING_FILE)) {
1741                 u64 size = (lte) ? wim_resource_size(lte) : 0;
1742                 ret = extract_resource_to_staging_dir(inode, stream_id,
1743                                                       &lte, size, ctx);
1744                 if (ret != 0)
1745                         return ret;
1746         }
1747
1748         ret = alloc_wimlib_fd(inode, stream_id, lte, &fd,
1749                               wimfs_ctx_readonly(ctx));
1750         if (ret != 0)
1751                 return ret;
1752
1753         if (lte && lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1754                 fd->staging_fd = open(lte->staging_file_name, fi->flags);
1755                 if (fd->staging_fd == -1) {
1756                         int errno_save = errno;
1757                         close_wimlib_fd(fd);
1758                         return -errno_save;
1759                 }
1760         }
1761         fi->fh = (uintptr_t)fd;
1762         return 0;
1763 }
1764
1765 /* Opens a directory. */
1766 static int wimfs_opendir(const char *path, struct fuse_file_info *fi)
1767 {
1768         struct inode *inode;
1769         int ret;
1770         struct wimlib_fd *fd = NULL;
1771         struct wimfs_context *ctx = wimfs_get_context();
1772         WIMStruct *w = ctx->wim;
1773
1774         inode = wim_pathname_to_inode(w, path);
1775         if (!inode)
1776                 return -ENOENT;
1777         if (!inode_is_directory(inode))
1778                 return -ENOTDIR;
1779         ret = alloc_wimlib_fd(inode, 0, NULL, &fd, wimfs_ctx_readonly(ctx));
1780         fi->fh = (uintptr_t)fd;
1781         return ret;
1782 }
1783
1784
1785 /*
1786  * Read data from a file in the WIM or in the staging directory.
1787  */
1788 static int wimfs_read(const char *path, char *buf, size_t size,
1789                       off_t offset, struct fuse_file_info *fi)
1790 {
1791         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1792         ssize_t ret;
1793
1794         if (!fd)
1795                 return -EBADF;
1796
1797         if (!fd->f_lte) /* Empty stream with no lookup table entry */
1798                 return 0;
1799
1800         if (fd->f_lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1801                 /* Read from staging file */
1802
1803                 wimlib_assert(fd->f_lte->staging_file_name);
1804                 wimlib_assert(fd->staging_fd != -1);
1805
1806                 DEBUG("Seek to offset %zu", offset);
1807
1808                 if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1809                         return -errno;
1810                 ret = read(fd->staging_fd, buf, size);
1811                 if (ret == -1)
1812                         return -errno;
1813                 return ret;
1814         } else {
1815                 /* Read from WIM */
1816                 u64 res_size = wim_resource_size(fd->f_lte);
1817                 if (offset > res_size)
1818                         return -EOVERFLOW;
1819                 size = min(size, res_size - offset);
1820                 if (read_wim_resource(fd->f_lte, (u8*)buf,
1821                                       size, offset,
1822                                       WIMLIB_RESOURCE_FLAG_MULTITHREADED) != 0)
1823                         return -EIO;
1824                 return size;
1825         }
1826 }
1827
1828 struct fill_params {
1829         void *buf;
1830         fuse_fill_dir_t filler;
1831 };
1832
1833 static int dentry_fuse_fill(struct dentry *dentry, void *arg)
1834 {
1835         struct fill_params *fill_params = arg;
1836         return fill_params->filler(fill_params->buf, dentry->file_name_utf8,
1837                                    NULL, 0);
1838 }
1839
1840 /* Fills in the entries of the directory specified by @path using the
1841  * FUSE-provided function @filler.  */
1842 static int wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
1843                          off_t offset, struct fuse_file_info *fi)
1844 {
1845         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1846         struct inode *inode;
1847
1848         if (!fd)
1849                 return -EBADF;
1850
1851         inode = fd->f_inode;
1852
1853         struct fill_params fill_params = {
1854                 .buf = buf,
1855                 .filler = filler,
1856         };
1857
1858         filler(buf, ".", NULL, 0);
1859         filler(buf, "..", NULL, 0);
1860
1861         return for_dentry_in_rbtree(inode->children.rb_node,
1862                                     dentry_fuse_fill, &fill_params);
1863 }
1864
1865
1866 static int wimfs_readlink(const char *path, char *buf, size_t buf_len)
1867 {
1868         struct wimfs_context *ctx = wimfs_get_context();
1869         struct inode *inode = wim_pathname_to_inode(ctx->wim, path);
1870         int ret;
1871         if (!inode)
1872                 return -ENOENT;
1873         if (!inode_is_symlink(inode))
1874                 return -EINVAL;
1875
1876         ret = inode_readlink(inode, buf, buf_len, ctx->wim,
1877                              WIMLIB_RESOURCE_FLAG_MULTITHREADED);
1878         if (ret > 0)
1879                 ret = 0;
1880         return ret;
1881 }
1882
1883 /* Close a file. */
1884 static int wimfs_release(const char *path, struct fuse_file_info *fi)
1885 {
1886         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1887         return close_wimlib_fd(fd);
1888 }
1889
1890 /* Close a directory */
1891 static int wimfs_releasedir(const char *path, struct fuse_file_info *fi)
1892 {
1893         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1894         return close_wimlib_fd(fd);
1895 }
1896
1897 #ifdef ENABLE_XATTR
1898 /* Remove an alternate data stream through the XATTR interface */
1899 static int wimfs_removexattr(const char *path, const char *name)
1900 {
1901         struct inode *inode;
1902         struct ads_entry *ads_entry;
1903         u16 ads_idx;
1904         struct wimfs_context *ctx = wimfs_get_context();
1905
1906         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1907                 return -ENOTSUP;
1908
1909         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1910                 return -ENOATTR;
1911         name += 5;
1912
1913         inode = wim_pathname_to_inode(ctx->wim, path);
1914         if (!inode)
1915                 return -ENOENT;
1916
1917         ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
1918         if (!ads_entry)
1919                 return -ENOATTR;
1920         inode_remove_ads(inode, ads_idx, ctx->wim->lookup_table);
1921         return 0;
1922 }
1923 #endif
1924
1925 /* Renames a file or directory.  See rename (3) */
1926 static int wimfs_rename(const char *from, const char *to)
1927 {
1928         struct dentry *src;
1929         struct dentry *dst;
1930         struct dentry *parent_of_dst;
1931         char *file_name_utf16 = NULL, *file_name_utf8 = NULL;
1932         u16 file_name_utf16_len, file_name_utf8_len;
1933         WIMStruct *w = wimfs_get_WIMStruct();
1934         int ret;
1935
1936         /* This rename() implementation currently only supports actual files
1937          * (not alternate data streams) */
1938
1939         src = get_dentry(w, from);
1940         if (!src)
1941                 return -ENOENT;
1942
1943         dst = get_dentry(w, to);
1944
1945         ret = get_names(&file_name_utf16, &file_name_utf8,
1946                         &file_name_utf16_len, &file_name_utf8_len,
1947                         path_basename(to));
1948         if (ret != 0)
1949                 return -ENOMEM;
1950
1951         if (dst) {
1952                 /* Destination file exists */
1953
1954                 if (src == dst) /* Same file */
1955                         return 0;
1956
1957                 if (!dentry_is_directory(src)) {
1958                         /* Cannot rename non-directory to directory. */
1959                         if (dentry_is_directory(dst))
1960                                 return -EISDIR;
1961                 } else {
1962                         /* Cannot rename directory to a non-directory or a non-empty
1963                          * directory */
1964                         if (!dentry_is_directory(dst))
1965                                 return -ENOTDIR;
1966                         if (inode_has_children(dst->d_inode))
1967                                 return -ENOTEMPTY;
1968                 }
1969                 parent_of_dst = dst->parent;
1970                 remove_dentry(dst, w->lookup_table);
1971         } else {
1972                 /* Destination does not exist */
1973                 parent_of_dst = get_parent_dentry(w, to);
1974                 if (!parent_of_dst)
1975                         return -ENOENT;
1976
1977                 if (!dentry_is_directory(parent_of_dst))
1978                         return -ENOTDIR;
1979         }
1980
1981         FREE(src->file_name);
1982         FREE(src->file_name_utf8);
1983         src->file_name          = file_name_utf16;
1984         src->file_name_utf8     = file_name_utf8;
1985         src->file_name_len      = file_name_utf16_len;
1986         src->file_name_utf8_len = file_name_utf8_len;
1987
1988         unlink_dentry(src);
1989         dentry_add_child(parent_of_dst, src);
1990         return 0;
1991 }
1992
1993 /* Remove a directory */
1994 static int wimfs_rmdir(const char *path)
1995 {
1996         struct dentry *dentry;
1997         WIMStruct *w = wimfs_get_WIMStruct();
1998
1999         dentry = get_dentry(w, path);
2000         if (!dentry)
2001                 return -ENOENT;
2002
2003         if (!dentry_is_empty_directory(dentry))
2004                 return -ENOTEMPTY;
2005
2006         remove_dentry(dentry, w->lookup_table);
2007         return 0;
2008 }
2009
2010 #ifdef ENABLE_XATTR
2011 /* Write an alternate data stream through the XATTR interface */
2012 static int wimfs_setxattr(const char *path, const char *name,
2013                           const char *value, size_t size, int flags)
2014 {
2015         struct ads_entry *existing_ads_entry;
2016         struct ads_entry *new_ads_entry;
2017         struct lookup_table_entry *existing_lte;
2018         struct lookup_table_entry *lte;
2019         struct inode *inode;
2020         u8 value_hash[SHA1_HASH_SIZE];
2021         u16 ads_idx;
2022         struct wimfs_context *ctx = wimfs_get_context();
2023
2024         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
2025                 return -ENOTSUP;
2026
2027         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
2028                 return -ENOATTR;
2029         name += 5;
2030
2031         inode = wim_pathname_to_inode(ctx->wim, path);
2032         if (!inode)
2033                 return -ENOENT;
2034
2035         existing_ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
2036         if (existing_ads_entry) {
2037                 if (flags & XATTR_CREATE)
2038                         return -EEXIST;
2039                 inode_remove_ads(inode, ads_idx, ctx->wim->lookup_table);
2040         } else {
2041                 if (flags & XATTR_REPLACE)
2042                         return -ENOATTR;
2043         }
2044         new_ads_entry = inode_add_ads(inode, name);
2045         if (!new_ads_entry)
2046                 return -ENOMEM;
2047
2048         sha1_buffer((const u8*)value, size, value_hash);
2049
2050         existing_lte = __lookup_resource(ctx->wim->lookup_table, value_hash);
2051
2052         if (existing_lte) {
2053                 lte = existing_lte;
2054                 lte->refcnt++;
2055         } else {
2056                 u8 *value_copy;
2057                 lte = new_lookup_table_entry();
2058                 if (!lte)
2059                         return -ENOMEM;
2060                 value_copy = MALLOC(size);
2061                 if (!value_copy) {
2062                         FREE(lte);
2063                         return -ENOMEM;
2064                 }
2065                 memcpy(value_copy, value, size);
2066                 lte->resource_location            = RESOURCE_IN_ATTACHED_BUFFER;
2067                 lte->attached_buffer              = value_copy;
2068                 lte->resource_entry.original_size = size;
2069                 lte->resource_entry.size          = size;
2070                 lte->resource_entry.flags         = 0;
2071                 copy_hash(lte->hash, value_hash);
2072                 lookup_table_insert(ctx->wim->lookup_table, lte);
2073         }
2074         new_ads_entry->lte = lte;
2075         return 0;
2076 }
2077 #endif
2078
2079 static int wimfs_symlink(const char *to, const char *from)
2080 {
2081         struct wimfs_context *ctx = wimfs_get_context();
2082         struct dentry *dentry;
2083         int ret;
2084
2085         ret = create_dentry(ctx, from, &dentry);
2086         if (ret == 0) {
2087                 dentry->d_inode->attributes = FILE_ATTRIBUTE_REPARSE_POINT;
2088                 dentry->d_inode->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
2089                 if (inode_set_symlink(dentry->d_inode, to,
2090                                       ctx->wim->lookup_table, NULL))
2091                 {
2092                         unlink_dentry(dentry);
2093                         free_dentry(dentry);
2094                         ret = -ENOMEM;
2095                 }
2096         }
2097         return ret;
2098 }
2099
2100
2101 /* Reduce the size of a file */
2102 static int wimfs_truncate(const char *path, off_t size)
2103 {
2104         struct dentry *dentry;
2105         struct lookup_table_entry *lte;
2106         int ret;
2107         u16 stream_idx;
2108         u32 stream_id;
2109         struct inode *inode;
2110         struct wimfs_context *ctx = wimfs_get_context();
2111
2112         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
2113                               &dentry, &lte, &stream_idx);
2114
2115         if (ret != 0)
2116                 return ret;
2117
2118         if (lte == NULL && size == 0)
2119                 return 0;
2120
2121         inode = dentry->d_inode;
2122         if (stream_idx == 0)
2123                 stream_id = 0;
2124         else
2125                 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
2126
2127         if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
2128                 ret = truncate(lte->staging_file_name, size);
2129                 if (ret != 0)
2130                         ret = -errno;
2131         } else {
2132                 /* File in WIM.  Extract it to the staging directory, but only
2133                  * the first @size bytes of it. */
2134                 ret = extract_resource_to_staging_dir(inode, stream_id,
2135                                                       &lte, size, ctx);
2136         }
2137         return ret;
2138 }
2139
2140 /* Unlink a non-directory or alternate data stream */
2141 static int wimfs_unlink(const char *path)
2142 {
2143         struct dentry *dentry;
2144         struct lookup_table_entry *lte;
2145         int ret;
2146         u16 stream_idx;
2147         struct wimfs_context *ctx = wimfs_get_context();
2148
2149         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
2150                               &dentry, &lte, &stream_idx);
2151
2152         if (ret != 0)
2153                 return ret;
2154
2155         if (stream_idx == 0)
2156                 remove_dentry(dentry, ctx->wim->lookup_table);
2157         else
2158                 inode_remove_ads(dentry->d_inode, stream_idx - 1,
2159                                  ctx->wim->lookup_table);
2160         return 0;
2161 }
2162
2163 #ifdef HAVE_UTIMENSAT
2164 /*
2165  * Change the timestamp on a file dentry.
2166  *
2167  * Note that alternate data streams do not have their own timestamps.
2168  */
2169 static int wimfs_utimens(const char *path, const struct timespec tv[2])
2170 {
2171         struct dentry *dentry;
2172         struct inode *inode;
2173         WIMStruct *w = wimfs_get_WIMStruct();
2174
2175         dentry = get_dentry(w, path);
2176         if (!dentry)
2177                 return -ENOENT;
2178         inode = dentry->d_inode;
2179
2180         if (tv[0].tv_nsec != UTIME_OMIT) {
2181                 if (tv[0].tv_nsec == UTIME_NOW)
2182                         inode->last_access_time = get_wim_timestamp();
2183                 else
2184                         inode->last_access_time = timespec_to_wim_timestamp(&tv[0]);
2185         }
2186         if (tv[1].tv_nsec != UTIME_OMIT) {
2187                 if (tv[1].tv_nsec == UTIME_NOW)
2188                         inode->last_write_time = get_wim_timestamp();
2189                 else
2190                         inode->last_write_time = timespec_to_wim_timestamp(&tv[1]);
2191         }
2192         return 0;
2193 }
2194 #else
2195 static int wimfs_utime(const char *path, struct utimbuf *times)
2196 {
2197         struct dentry *dentry;
2198         struct inode *inode;
2199         WIMStruct *w = wimfs_get_WIMStruct();
2200
2201         dentry = get_dentry(w, path);
2202         if (!dentry)
2203                 return -ENOENT;
2204         inode = dentry->d_inode;
2205
2206         inode->last_write_time = unix_timestamp_to_wim(times->modtime);
2207         inode->last_access_time = unix_timestamp_to_wim(times->actime);
2208         return 0;
2209 }
2210 #endif
2211
2212 /* Writes to a file in the WIM filesystem.
2213  * It may be an alternate data stream, but here we don't even notice because we
2214  * just get a lookup table entry. */
2215 static int wimfs_write(const char *path, const char *buf, size_t size,
2216                        off_t offset, struct fuse_file_info *fi)
2217 {
2218         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
2219         int ret;
2220         u64 now;
2221
2222         if (!fd)
2223                 return -EBADF;
2224
2225         wimlib_assert(fd->f_lte);
2226         wimlib_assert(fd->f_lte->staging_file_name);
2227         wimlib_assert(fd->staging_fd != -1);
2228         wimlib_assert(fd->f_inode);
2229
2230         /* Seek to the requested position */
2231         if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
2232                 return -errno;
2233
2234         /* Write the data. */
2235         ret = write(fd->staging_fd, buf, size);
2236         if (ret == -1)
2237                 return -errno;
2238
2239         now = get_wim_timestamp();
2240         fd->f_inode->last_write_time = now;
2241         fd->f_inode->last_access_time = now;
2242         return ret;
2243 }
2244
2245 static struct fuse_operations wimfs_operations = {
2246         .access      = wimfs_access,
2247         .chmod       = wimfs_chmod,
2248         .destroy     = wimfs_destroy,
2249 #if 0
2250         .fallocate   = wimfs_fallocate,
2251 #endif
2252         .fgetattr    = wimfs_fgetattr,
2253         .ftruncate   = wimfs_ftruncate,
2254         .getattr     = wimfs_getattr,
2255 #ifdef ENABLE_XATTR
2256         .getxattr    = wimfs_getxattr,
2257 #endif
2258         .link        = wimfs_link,
2259 #ifdef ENABLE_XATTR
2260         .listxattr   = wimfs_listxattr,
2261 #endif
2262         .mkdir       = wimfs_mkdir,
2263         .mknod       = wimfs_mknod,
2264         .open        = wimfs_open,
2265         .opendir     = wimfs_opendir,
2266         .read        = wimfs_read,
2267         .readdir     = wimfs_readdir,
2268         .readlink    = wimfs_readlink,
2269         .release     = wimfs_release,
2270         .releasedir  = wimfs_releasedir,
2271 #ifdef ENABLE_XATTR
2272         .removexattr = wimfs_removexattr,
2273 #endif
2274         .rename      = wimfs_rename,
2275         .rmdir       = wimfs_rmdir,
2276 #ifdef ENABLE_XATTR
2277         .setxattr    = wimfs_setxattr,
2278 #endif
2279         .symlink     = wimfs_symlink,
2280         .truncate    = wimfs_truncate,
2281         .unlink      = wimfs_unlink,
2282 #ifdef HAVE_UTIMENSAT
2283         .utimens     = wimfs_utimens,
2284 #else
2285         .utime       = wimfs_utime,
2286 #endif
2287         .write       = wimfs_write,
2288
2289 #if FUSE_MAJOR_VERSION > 2 || (FUSE_MAJOR_VERSION == 2 && FUSE_MINOR_VERSION >= 8)
2290         .flag_nullpath_ok = 1,
2291 #endif
2292 #if FUSE_MAJOR_VERSION > 2 || (FUSE_MAJOR_VERSION == 2 && FUSE_MINOR_VERSION >= 9)
2293         .flag_nopath = 1,
2294         .flag_utime_omit_ok = 1,
2295 #endif
2296 };
2297
2298
2299 /* Mounts an image from a WIM file. */
2300 WIMLIBAPI int wimlib_mount_image(WIMStruct *wim, int image, const char *dir,
2301                                  int mount_flags, WIMStruct **additional_swms,
2302                                  unsigned num_additional_swms,
2303                                  const char *staging_dir)
2304 {
2305         int argc = 0;
2306         char *argv[16];
2307         int ret;
2308         char *dir_copy;
2309         struct lookup_table *joined_tab, *wim_tab_save;
2310         struct image_metadata *imd;
2311         struct wimfs_context ctx;
2312         struct hlist_node *cur_node;
2313         struct inode *inode;
2314
2315         DEBUG("Mount: wim = %p, image = %d, dir = %s, flags = %d, ",
2316               wim, image, dir, mount_flags);
2317
2318         if (!wim || !dir)
2319                 return WIMLIB_ERR_INVALID_PARAM;
2320
2321         ret = verify_swm_set(wim, additional_swms, num_additional_swms);
2322         if (ret != 0)
2323                 return ret;
2324
2325         if ((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) && (wim->hdr.total_parts != 1)) {
2326                 ERROR("Cannot mount a split WIM read-write");
2327                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2328         }
2329
2330         if (num_additional_swms) {
2331                 ret = new_joined_lookup_table(wim, additional_swms,
2332                                               num_additional_swms,
2333                                               &joined_tab);
2334                 if (ret != 0)
2335                         return ret;
2336                 wim_tab_save = wim->lookup_table;
2337                 wim->lookup_table = joined_tab;
2338         }
2339
2340         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2341                 ret = wim_run_full_verifications(wim);
2342                 if (ret != 0)
2343                         goto out;
2344         }
2345
2346         ret = select_wim_image(wim, image);
2347         if (ret != 0)
2348                 goto out;
2349
2350         DEBUG("Selected image %d", image);
2351
2352         imd = wim_get_current_image_metadata(wim);
2353
2354         if (imd->root_dentry->refcnt != 1) {
2355                 ERROR("Cannot mount image that was just exported with "
2356                       "wimlib_export_image()");
2357                 ret = WIMLIB_ERR_INVALID_PARAM;
2358                 goto out;
2359         }
2360
2361         if (imd->modified) {
2362                 ERROR("Cannot mount image that was added "
2363                       "with wimlib_add_image()");
2364                 ret = WIMLIB_ERR_INVALID_PARAM;
2365                 goto out;
2366         }
2367
2368         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2369                 ret = lock_wim(wim, wim->fp);
2370                 if (ret != 0)
2371                         goto out;
2372         }
2373
2374         if (!(mount_flags & (WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
2375                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
2376                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)))
2377                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
2378
2379
2380         DEBUG("Initializing struct wimfs_context");
2381         init_wimfs_context(&ctx);
2382         ctx.wim = wim;
2383         ctx.mount_flags = mount_flags;
2384         ctx.image_inode_list = &imd->inode_list;
2385
2386         if (mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
2387                 ctx.default_lookup_flags = LOOKUP_FLAG_ADS_OK;
2388
2389         DEBUG("Unlinking message queues in case they already exist");
2390         ret = set_message_queue_names(&ctx, dir);
2391         if (ret != 0)
2392                 goto out_unlock;
2393         unlink_message_queues(&ctx);
2394
2395         DEBUG("Preparing arguments to fuse_main()");
2396
2397         dir_copy = STRDUP(dir);
2398         if (!dir_copy)
2399                 goto out_free_message_queue_names;
2400
2401         argv[argc++] = "imagex";
2402         argv[argc++] = dir_copy;
2403
2404         /* disable multi-threaded operation for read-write mounts */
2405         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2406                 argv[argc++] = "-s";
2407
2408         if (mount_flags & WIMLIB_MOUNT_FLAG_DEBUG)
2409                 argv[argc++] = "-d";
2410
2411         /*
2412          * We provide the use_ino option because we are going to assign inode
2413          * numbers oursides.  The inodes will be given unique numbers in the
2414          * assign_inode_numbers() function, and the static variable @next_ino is
2415          * set to the next available inode number.
2416          */
2417         char optstring[256] =
2418                 "use_ino"
2419                 ",subtype=wimfs"
2420                 ",attr_timeout=0"
2421 #if FUSE_MAJOR_VERSION > 2 || (FUSE_MAJOR_VERSION == 2 && FUSE_MINOR_VERSION >= 8)
2422                 ",hard_remove"
2423 #endif
2424                 ;
2425         argv[argc++] = "-o";
2426         argv[argc++] = optstring;
2427         if ((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
2428                 /* Read-write mount.  Make the staging directory */
2429                 ret = make_staging_dir(&ctx, staging_dir);
2430                 if (ret != 0)
2431                         goto out_free_dir_copy;
2432         } else {
2433                 /* Read-only mount */
2434                 strcat(optstring, ",ro");
2435         }
2436         argv[argc] = NULL;
2437
2438 #ifdef ENABLE_DEBUG
2439         {
2440                 int i;
2441                 DEBUG("FUSE command line (argc = %d): ", argc);
2442                 for (i = 0; i < argc; i++) {
2443                         fputs(argv[i], stdout);
2444                         putchar(' ');
2445                 }
2446                 putchar('\n');
2447                 fflush(stdout);
2448         }
2449 #endif
2450
2451         /* Mark dentry tree as modified if read-write mount. */
2452         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2453                 imd->modified = 1;
2454                 imd->has_been_mounted_rw = 1;
2455         }
2456
2457         /* Resolve the lookup table entries for every inode in the image, and
2458          * assign inode numbers */
2459         DEBUG("Resolving lookup table entries and assigning inode numbers");
2460
2461         ctx.next_ino = 1;
2462         hlist_for_each_entry(inode, cur_node, &imd->inode_list, hlist) {
2463                 inode_resolve_ltes(inode, wim->lookup_table);
2464                 inode->ino = ctx.next_ino++;
2465         }
2466         /*ctx.next_ino = assign_inode_numbers(&imd->inode_list);*/
2467         DEBUG("(next_ino = %"PRIu64")", ctx.next_ino);
2468
2469         DEBUG("Calling fuse_main()");
2470
2471         ret = fuse_main(argc, argv, &wimfs_operations, &ctx);
2472
2473         DEBUG("Returned from fuse_main() (ret = %d)", ret);
2474         if (ret)
2475                 ret = WIMLIB_ERR_FUSE;
2476 out_free_dir_copy:
2477         FREE(dir_copy);
2478 out_unlock:
2479         wim->wim_locked = 0;
2480 out_free_message_queue_names:
2481         free_message_queue_names(&ctx);
2482 out:
2483         if (num_additional_swms) {
2484                 free_lookup_table(wim->lookup_table);
2485                 wim->lookup_table = wim_tab_save;
2486         }
2487         return ret;
2488 }
2489
2490 /*
2491  * Unmounts the WIM file that was previously mounted on @dir by using
2492  * wimlib_mount_image().
2493  */
2494 WIMLIBAPI int wimlib_unmount_image(const char *dir, int unmount_flags,
2495                                    wimlib_progress_func_t progress_func)
2496 {
2497         int ret;
2498         struct wimfs_context wimfs_ctx;
2499
2500         init_wimfs_context(&wimfs_ctx);
2501
2502         ret = set_message_queue_names(&wimfs_ctx, dir);
2503         if (ret != 0)
2504                 goto out;
2505
2506         ret = open_message_queues(&wimfs_ctx, false);
2507         if (ret != 0)
2508                 goto out_free_message_queue_names;
2509
2510         ret = send_unmount_request_msg(wimfs_ctx.unmount_to_daemon_mq,
2511                                        unmount_flags,
2512                                        progress_func != NULL);
2513         if (ret != 0)
2514                 goto out_close_message_queues;
2515
2516         ret = execute_fusermount(dir);
2517         if (ret != 0)
2518                 goto out_close_message_queues;
2519
2520         struct msg_handler_context handler_ctx = {
2521                 .is_daemon = false,
2522                 .timeout_seconds = 5,
2523                 .unmount = {
2524                         .daemon_pid = 0,
2525                         .progress_func = progress_func,
2526                 },
2527         };
2528
2529         ret = message_loop(wimfs_ctx.daemon_to_unmount_mq,
2530                            &unmount_msg_handler_callbacks,
2531                            &handler_ctx);
2532         if (ret == 0)
2533                 ret = handler_ctx.unmount.status;
2534 out_close_message_queues:
2535         close_message_queues(&wimfs_ctx);
2536 out_free_message_queue_names:
2537         free_message_queue_names(&wimfs_ctx);
2538 out:
2539         return ret;
2540 }
2541
2542 #else /* WITH_FUSE */
2543
2544
2545 static inline int mount_unsupported_error()
2546 {
2547         ERROR("wimlib was compiled with --without-fuse, which disables support "
2548               "for mounting WIMs.");
2549         return WIMLIB_ERR_UNSUPPORTED;
2550 }
2551
2552 WIMLIBAPI int wimlib_unmount_image(const char *dir, int unmount_flags,
2553                                    wimlib_progress_func_t progress_func)
2554 {
2555         return mount_unsupported_error();
2556 }
2557
2558 WIMLIBAPI int wimlib_mount_image(WIMStruct *wim_p, int image, const char *dir,
2559                                  int mount_flags, WIMStruct **additional_swms,
2560                                  unsigned num_additional_swms,
2561                                  const char *staging_dir)
2562 {
2563         return mount_unsupported_error();
2564 }
2565
2566 #endif /* WITH_FUSE */