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.
11 * Copyright (C) 2012 Eric Biggers
13 * This file is part of wimlib, a library for working with WIM files.
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)
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
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/.
29 #include "wimlib_internal.h"
34 #include "lookup_table.h"
36 #include "buffer_io.h"
37 #include "timestamp.h"
42 #define FUSE_USE_VERSION 26
52 #include <attr/xattr.h>
55 /* File descriptor to a file open on the WIM filesystem. */
57 struct inode *f_inode;
58 struct lookup_table_entry *f_lte;
64 struct wimfs_context {
65 /* The WIMStruct for the mounted WIM. */
68 /* Name of the staging directory for a read-write mount. Whenever a new file is
69 * created, it is done so in the staging directory. Furthermore, whenever a
70 * file in the WIM is modified, it is extracted to the staging directory. If
71 * changes are commited when the WIM is unmounted, the file resources are merged
72 * in from the staging directory when writing the new WIM. */
73 char *staging_dir_name;
74 size_t staging_dir_name_len;
76 /* Flags passed to wimlib_mount(). */
79 int default_lookup_flags;
81 /* Next inode number to be assigned. */
84 /* List of lookup table entries in the staging directory */
85 struct list_head staging_list;
87 /* List of inodes in the mounted image */
88 struct hlist_head *image_inode_list;
90 /* Name and message queue descriptors for message queues between the filesystem
91 * daemon process and the unmount process. These are used when the filesystem
92 * is unmounted and the process running wimlib_mount() (i.e. the `imagex
93 * unmount' command) needs to communicate with the filesystem daemon running
94 * fuse_main() (i.e. that spawned by the `imagex mount' or `imagex mountrw'
96 char *unmount_to_daemon_mq_name;
97 char *daemon_to_unmount_mq_name;
98 mqd_t unmount_to_daemon_mq;
99 mqd_t daemon_to_unmount_mq;
102 static void init_wimfs_context(struct wimfs_context *ctx)
104 memset(ctx, 0, sizeof(*ctx));
105 ctx->unmount_to_daemon_mq = (mqd_t)-1;
106 ctx->daemon_to_unmount_mq = (mqd_t)-1;
107 INIT_LIST_HEAD(&ctx->staging_list);
110 static inline struct wimfs_context *wimfs_get_context()
112 return (struct wimfs_context*)fuse_get_context()->private_data;
115 static inline WIMStruct *wimfs_get_WIMStruct()
117 return wimfs_get_context()->wim;
120 static inline bool wimfs_ctx_readonly(const struct wimfs_context *ctx)
122 return (ctx->mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) == 0;
125 static inline int get_lookup_flags(const struct wimfs_context *ctx)
127 return ctx->default_lookup_flags;
130 /* Returns nonzero if write permission is requested on the file open flags */
131 static inline int flags_writable(int open_flags)
133 return open_flags & (O_RDWR | O_WRONLY);
137 * Allocate a file descriptor for a stream.
139 * @inode: inode containing the stream we're opening
140 * @stream_id: ID of the stream we're opening
141 * @lte: Lookup table entry for the stream (may be NULL)
142 * @fd_ret: Return the allocated file descriptor if successful.
143 * @readonly: True if this is a read-only mount.
145 * Return 0 iff successful or error code if unsuccessful.
147 static int alloc_wimlib_fd(struct inode *inode,
149 struct lookup_table_entry *lte,
150 struct wimlib_fd **fd_ret,
153 static const u16 fds_per_alloc = 8;
154 static const u16 max_fds = 0xffff;
157 pthread_mutex_lock(&inode->i_mutex);
159 DEBUG("Allocating fd for stream ID %u from inode %lx (open = %u, allocated = %u)",
160 stream_id, inode->ino, inode->num_opened_fds,
161 inode->num_allocated_fds);
163 if (inode->num_opened_fds == inode->num_allocated_fds) {
164 struct wimlib_fd **fds;
167 if (inode->num_allocated_fds == max_fds) {
171 num_new_fds = min(fds_per_alloc,
172 max_fds - inode->num_allocated_fds);
174 fds = REALLOC(inode->fds,
175 (inode->num_allocated_fds + num_new_fds) *
176 sizeof(inode->fds[0]));
181 memset(&fds[inode->num_allocated_fds], 0,
182 num_new_fds * sizeof(fds[0]));
184 inode->num_allocated_fds += num_new_fds;
186 for (u16 i = 0; ; i++) {
187 if (!inode->fds[i]) {
188 struct wimlib_fd *fd = CALLOC(1, sizeof(*fd));
197 fd->stream_id = stream_id;
200 inode->num_opened_fds++;
201 if (lte && !readonly)
202 lte->num_opened_fds++;
203 DEBUG("Allocated fd (idx = %u)", fd->idx);
209 pthread_mutex_unlock(&inode->i_mutex);
213 static void inode_put_fd(struct inode *inode, struct wimlib_fd *fd)
215 wimlib_assert(inode != NULL);
217 pthread_mutex_lock(&inode->i_mutex);
219 wimlib_assert(fd->f_inode == inode);
220 wimlib_assert(inode->num_opened_fds != 0);
221 wimlib_assert(fd->idx < inode->num_allocated_fds);
222 wimlib_assert(inode->fds[fd->idx] == fd);
224 inode->fds[fd->idx] = NULL;
226 if (--inode->num_opened_fds == 0 && inode->link_count == 0) {
227 pthread_mutex_unlock(&inode->i_mutex);
230 pthread_mutex_unlock(&inode->i_mutex);
234 static int lte_put_fd(struct lookup_table_entry *lte, struct wimlib_fd *fd)
236 wimlib_assert(fd->f_lte == lte);
238 if (!lte) /* Empty stream with no lookup table entry */
241 /* Close staging file descriptor if needed. */
243 if (lte->resource_location == RESOURCE_IN_STAGING_FILE
244 && fd->staging_fd != -1)
246 if (close(fd->staging_fd) != 0) {
247 ERROR_WITH_ERRNO("Failed to close staging file");
251 lte_decrement_num_opened_fds(lte);
255 /* Close a file descriptor. */
256 static int close_wimlib_fd(struct wimlib_fd *fd)
259 DEBUG("Closing fd (inode = %lu, opened = %u, allocated = %u)",
260 fd->f_inode->ino, fd->f_inode->num_opened_fds,
261 fd->f_inode->num_allocated_fds);
262 ret = lte_put_fd(fd->f_lte, fd);
266 inode_put_fd(fd->f_inode, fd);
270 static int create_dentry(struct wimfs_context *ctx, const char *path,
271 struct dentry **dentry_ret)
273 struct dentry *parent;
275 const char *basename;
277 parent = get_parent_dentry(ctx->wim, path);
281 if (!dentry_is_directory(parent))
284 basename = path_basename(path);
285 if (get_dentry_child_with_name(parent, basename))
288 new = new_dentry_with_inode(basename);
292 new->d_inode->resolved = 1;
293 new->d_inode->ino = ctx->next_ino++;
294 dentry_add_child(parent, new);
295 hlist_add_head(&new->d_inode->hlist, ctx->image_inode_list);
300 /* Remove a dentry; i.e. remove a reference to the corresponding inode.
302 * If there are no remaining references to the inode either through dentries or
303 * open file descriptors, the inode is freed. Otherwise, the inode is not
304 * removed, but the dentry is unlinked and freed.
306 * Either way, all lookup table entries referenced by the inode have their
307 * reference count decremented. If a lookup table entry has no open file
308 * descriptors and no references remaining, it is freed, and the staging file is
311 static void remove_dentry(struct dentry *dentry,
312 struct lookup_table *lookup_table)
314 struct inode *inode = dentry->d_inode;
315 struct lookup_table_entry *lte;
318 for (i = 0; i <= inode->num_ads; i++) {
319 lte = inode_stream_lte_resolved(inode, i);
321 lte_decrement_refcnt(lte, lookup_table);
323 unlink_dentry(dentry);
327 /* Transfers file attributes from a struct inode to a `stat' buffer.
329 * The lookup table entry tells us which stream in the inode we are statting.
330 * For a named data stream, everything returned is the same as the unnamed data
331 * stream except possibly the size and block count. */
332 static int inode_to_stbuf(const struct inode *inode,
333 struct lookup_table_entry *lte, struct stat *stbuf)
335 if (inode_is_symlink(inode))
336 stbuf->st_mode = S_IFLNK | 0777;
337 else if (inode_is_directory(inode))
338 stbuf->st_mode = S_IFDIR | 0755;
340 stbuf->st_mode = S_IFREG | 0755;
342 stbuf->st_ino = (ino_t)inode->ino;
343 stbuf->st_nlink = inode->link_count;
344 stbuf->st_uid = getuid();
345 stbuf->st_gid = getgid();
348 if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
349 struct stat native_stat;
350 if (stat(lte->staging_file_name, &native_stat) != 0) {
351 DEBUG("Failed to stat `%s': %m",
352 lte->staging_file_name);
355 stbuf->st_size = native_stat.st_size;
357 stbuf->st_size = wim_resource_size(lte);
363 stbuf->st_atime = wim_timestamp_to_unix(inode->last_access_time);
364 stbuf->st_mtime = wim_timestamp_to_unix(inode->last_write_time);
365 stbuf->st_ctime = wim_timestamp_to_unix(inode->creation_time);
366 stbuf->st_blocks = (stbuf->st_size + 511) / 512;
370 /* Creates a new staging file and returns its file descriptor opened for
373 * @name_ret: A location into which the a pointer to the newly allocated name of
374 * the staging file is stored.
375 * @return: The file descriptor for the new file. Returns -1 and sets errno on
376 * error, for any reason possible from the creat() function.
378 static int create_staging_file(char **name_ret, int open_flags,
379 struct wimfs_context *ctx)
387 name_len = ctx->staging_dir_name_len + 1 + SHA1_HASH_SIZE;
388 name = MALLOC(name_len + 1);
396 memcpy(name, ctx->staging_dir_name, ctx->staging_dir_name_len);
397 name[ctx->staging_dir_name_len] = '/';
398 randomize_char_array_with_alnum(name + ctx->staging_dir_name_len + 1,
400 name[name_len] = '\0';
403 /* Just in case, verify that the randomly generated name doesn't name an
404 * existing file, and try again if so */
405 } while (stat(name, &stbuf) == 0);
411 /* doesn't exist--- ok */
413 DEBUG("Creating staging file `%s'", name);
415 fd = open(name, open_flags | O_CREAT | O_TRUNC, 0600);
427 * Extract a WIM resource to the staging directory.
429 * @inode: Inode that contains the stream we are extracting
431 * @stream_id: Identifier for the stream (it stays constant even if the indices
432 * of the stream entries are changed)
434 * @lte: Pointer to pointer to the lookup table entry for the stream we need to
435 * extract, or NULL if there was no lookup table entry present for the stream
437 * @size: Number of bytes of the stream we want to extract (this supports the
438 * wimfs_truncate() function). It may be more than the actual stream length, in
439 * which case the extra space is filled with zeroes.
441 * @ctx: Context for the WIM filesystem.
443 * Returns 0 on success or a negative error code on failure.
445 static int extract_resource_to_staging_dir(struct inode *inode,
447 struct lookup_table_entry **lte,
449 struct wimfs_context *ctx)
451 char *staging_file_name;
454 struct lookup_table_entry *old_lte, *new_lte;
457 DEBUG("Extracting resource to staging dir: inode %"PRIu64", "
458 "stream id %"PRIu32, inode->ino, stream_id);
462 wimlib_assert(old_lte == NULL ||
463 old_lte->resource_location != RESOURCE_IN_STAGING_FILE);
465 /* Create the staging file */
466 fd = create_staging_file(&staging_file_name, O_WRONLY, ctx);
470 /* Extract the stream to the staging file (possibly truncated) */
472 extract_size = min(wim_resource_size(old_lte), size);
473 ret = extract_wim_resource_to_fd(old_lte, fd, extract_size);
479 /* In the case of truncate() to more than the file length, extend the
480 * file with zeroes by calling ftruncate() on the underlying staging
482 if (ret == 0 && size > extract_size)
483 ret = ftruncate(fd, size);
485 /* Close the staging file descriptor and check for errors. If there's
486 * an error, unlink the staging file. */
487 if (ret != 0 || close(fd) != 0) {
493 goto out_delete_staging_file;
496 /* Now deal with the lookup table entries. We may be able to re-use the
497 * existing entry, but we may have to create a new one instead. */
499 if (old_lte && inode->link_count == old_lte->refcnt) {
500 /* The reference count of the existing lookup table entry is the
501 * same as the link count of the inode that contains the stream
502 * we're opening. Therefore, ALL the references to the lookup
503 * table entry correspond to the stream we're trying to extract,
504 * so the lookup table entry can be re-used. */
505 DEBUG("Re-using lookup table entry");
506 lookup_table_unlink(ctx->wim->lookup_table, old_lte);
510 /* There's an existing lookup table entry, but its
511 * reference count is greater than the link count for
512 * the inode containing a stream we're opening.
513 * Therefore, we need to split the lookup table entry.
515 wimlib_assert(old_lte->refcnt > inode->link_count);
516 DEBUG("Splitting lookup table entry "
517 "(inode->link_count = %u, old_lte->refcnt = %u)",
518 inode->link_count, old_lte->refcnt);
521 new_lte = new_lookup_table_entry();
524 goto out_delete_staging_file;
527 /* There may already be open file descriptors to this stream if
528 * it's previously been opened read-only, but just now we're
529 * opening it read-write. Identify those file descriptors and
530 * change their lookup table entry pointers to point to the new
531 * lookup table entry, and open staging file descriptors for
534 * At the same time, we need to count the number of these opened
535 * file descriptors to the new lookup table entry. If there's
536 * an old lookup table entry, this number needs to be subtracted
537 * from the fd's opened to the old entry. */
538 for (u16 i = 0, j = 0; j < inode->num_opened_fds; i++) {
539 struct wimlib_fd *fd = inode->fds[i];
541 if (fd->stream_id == stream_id) {
542 wimlib_assert(fd->f_lte == old_lte);
543 wimlib_assert(fd->staging_fd == -1);
545 new_lte->num_opened_fds++;
546 fd->staging_fd = open(staging_file_name, O_RDONLY);
547 if (fd->staging_fd == -1) {
549 goto out_revert_fd_changes;
555 DEBUG("%hu fd's were already opened to the file we extracted",
556 new_lte->num_opened_fds);
558 old_lte->num_opened_fds -= new_lte->num_opened_fds;
559 old_lte->refcnt -= inode->link_count;
563 new_lte->refcnt = inode->link_count;
564 new_lte->resource_location = RESOURCE_IN_STAGING_FILE;
565 new_lte->staging_file_name = staging_file_name;
566 new_lte->lte_inode = inode;
567 random_hash(new_lte->hash);
570 inode->lte = new_lte;
572 for (u16 i = 0; i < inode->num_ads; i++)
573 if (inode->ads_entries[i].stream_id == stream_id)
574 inode->ads_entries[i].lte = new_lte;
576 lookup_table_insert(ctx->wim->lookup_table, new_lte);
577 list_add(&new_lte->staging_list, &ctx->staging_list);
580 out_revert_fd_changes:
581 for (u16 i = 0, j = 0; j < new_lte->num_opened_fds; i++) {
582 struct wimlib_fd *fd = inode->fds[i];
583 if (fd && fd->stream_id == stream_id && fd->f_lte == new_lte) {
585 if (fd->staging_fd != -1) {
586 close(fd->staging_fd);
592 free_lookup_table_entry(new_lte);
593 out_delete_staging_file:
594 unlink(staging_file_name);
595 FREE(staging_file_name);
600 * Creates a randomly named staging directory and saves its name in the
601 * filesystem context structure.
603 static int make_staging_dir(struct wimfs_context *ctx, const char *user_prefix)
605 static const size_t random_suffix_len = 10;
606 static const char *common_suffix = ".staging";
607 static const size_t common_suffix_len = 8;
609 char *staging_dir_name = NULL;
610 size_t staging_dir_name_len;
612 const char *wim_basename;
613 char *real_user_prefix = NULL;
617 real_user_prefix = realpath(user_prefix, NULL);
618 if (!real_user_prefix) {
619 ERROR_WITH_ERRNO("Could not resolve `%s'",
621 ret = WIMLIB_ERR_NOTDIR;
624 wim_basename = path_basename(ctx->wim->filename);
625 prefix_len = strlen(real_user_prefix) + 1 + strlen(wim_basename);
627 prefix_len = strlen(ctx->wim->filename);
630 staging_dir_name_len = prefix_len + common_suffix_len + random_suffix_len;
632 staging_dir_name = MALLOC(staging_dir_name_len + 1);
633 if (!staging_dir_name) {
634 ret = WIMLIB_ERR_NOMEM;
638 if (real_user_prefix)
639 sprintf(staging_dir_name, "%s/%s", real_user_prefix, wim_basename);
641 strcpy(staging_dir_name, ctx->wim->filename);
643 strcat(staging_dir_name, common_suffix);
645 randomize_char_array_with_alnum(staging_dir_name + prefix_len + common_suffix_len,
648 staging_dir_name[staging_dir_name_len] = '\0';
650 if (mkdir(staging_dir_name, 0700) != 0) {
651 ERROR_WITH_ERRNO("Failed to create temporary directory `%s'",
653 ret = WIMLIB_ERR_MKDIR;
658 FREE(real_user_prefix);
660 ctx->staging_dir_name = staging_dir_name;
661 ctx->staging_dir_name_len = staging_dir_name_len;
663 FREE(staging_dir_name);
668 static int remove_file_or_directory(const char *fpath, const struct stat *sb,
669 int typeflag, struct FTW *ftwbuf)
671 if (remove(fpath) == 0)
674 ERROR_WITH_ERRNO("Cannot remove `%s'", fpath);
675 return WIMLIB_ERR_DELETE_STAGING_DIR;
681 * Deletes the staging directory and all the files contained in it.
683 static int delete_staging_dir(struct wimfs_context *ctx)
686 ret = nftw(ctx->staging_dir_name, remove_file_or_directory,
688 FREE(ctx->staging_dir_name);
689 ctx->staging_dir_name = NULL;
694 /* Simple function that returns the concatenation of 2 strings. */
695 static char *strcat_dup(const char *s1, const char *s2, size_t max_len)
697 size_t len = strlen(s1) + strlen(s2);
700 char *p = MALLOC(len + 1);
703 snprintf(p, len + 1, "%s%s", s1, s2);
707 static int set_message_queue_names(struct wimfs_context *ctx,
708 const char *mount_dir)
710 static const char *u2d_prefix = "/wimlib-unmount-to-daemon-mq";
711 static const char *d2u_prefix = "/wimlib-daemon-to-unmount-mq";
716 dir_path = realpath(mount_dir, NULL);
718 ERROR_WITH_ERRNO("Failed to resolve path \"%s\"", mount_dir);
720 return WIMLIB_ERR_NOMEM;
722 return WIMLIB_ERR_NOTDIR;
732 ctx->unmount_to_daemon_mq_name = strcat_dup(u2d_prefix, dir_path,
734 if (!ctx->unmount_to_daemon_mq_name) {
735 ret = WIMLIB_ERR_NOMEM;
736 goto out_free_dir_path;
738 ctx->daemon_to_unmount_mq_name = strcat_dup(d2u_prefix, dir_path,
740 if (!ctx->daemon_to_unmount_mq_name) {
741 ret = WIMLIB_ERR_NOMEM;
742 goto out_free_unmount_to_daemon_mq_name;
746 goto out_free_dir_path;
747 out_free_unmount_to_daemon_mq_name:
748 FREE(ctx->unmount_to_daemon_mq_name);
749 ctx->unmount_to_daemon_mq_name = NULL;
755 static void free_message_queue_names(struct wimfs_context *ctx)
757 FREE(ctx->unmount_to_daemon_mq_name);
758 FREE(ctx->daemon_to_unmount_mq_name);
759 ctx->unmount_to_daemon_mq_name = NULL;
760 ctx->daemon_to_unmount_mq_name = NULL;
764 * Opens two POSIX message queue: one for sending messages from the unmount
765 * process to the daemon process, and one to go the other way. The names of the
766 * message queues, which must be system-wide unique, are be based on the mount
767 * point. (There of course is still a possibility of a collision if one were to
768 * unmount two identically named directories simultaneously...)
770 * @daemon specifies whether the calling process is the filesystem daemon or the
773 static int open_message_queues(struct wimfs_context *ctx, bool daemon)
775 int unmount_to_daemon_mq_flags = O_WRONLY | O_CREAT;
776 int daemon_to_unmount_mq_flags = O_RDONLY | O_CREAT;
779 swap(unmount_to_daemon_mq_flags, daemon_to_unmount_mq_flags);
781 DEBUG("Opening message queue \"%s\"", ctx->unmount_to_daemon_mq_name);
782 ctx->unmount_to_daemon_mq = mq_open(ctx->unmount_to_daemon_mq_name,
783 unmount_to_daemon_mq_flags, 0700, NULL);
785 if (ctx->unmount_to_daemon_mq == (mqd_t)-1) {
786 ERROR_WITH_ERRNO("mq_open()");
787 return WIMLIB_ERR_MQUEUE;
790 DEBUG("Opening message queue \"%s\"", ctx->daemon_to_unmount_mq_name);
791 ctx->daemon_to_unmount_mq = mq_open(ctx->daemon_to_unmount_mq_name,
792 daemon_to_unmount_mq_flags, 0700, NULL);
794 if (ctx->daemon_to_unmount_mq == (mqd_t)-1) {
795 ERROR_WITH_ERRNO("mq_open()");
796 mq_close(ctx->unmount_to_daemon_mq);
797 mq_unlink(ctx->unmount_to_daemon_mq_name);
798 ctx->unmount_to_daemon_mq = (mqd_t)-1;
799 return WIMLIB_ERR_MQUEUE;
804 /* Try to determine the maximum message size of a message queue. The return
805 * value is the maximum message size, or a guess of 8192 bytes if it cannot be
807 static long mq_get_msgsize(mqd_t mq)
809 static const char *msgsize_max_file = "/proc/sys/fs/mqueue/msgsize_max";
814 if (mq_getattr(mq, &attr) == 0) {
815 msgsize = attr.mq_msgsize;
817 ERROR_WITH_ERRNO("mq_getattr()");
818 ERROR("Attempting to read %s", msgsize_max_file);
819 fp = fopen(msgsize_max_file, "rb");
821 if (fscanf(fp, "%ld", &msgsize) != 1) {
822 ERROR("Assuming message size of 8192");
827 ERROR_WITH_ERRNO("Failed to open the file `%s'",
829 ERROR("Assuming message size of 8192");
836 static int get_mailbox(mqd_t mq, long needed_msgsize, long *msgsize_ret,
842 msgsize = mq_get_msgsize(mq);
844 if (msgsize < needed_msgsize) {
845 ERROR("Message queue max size must be at least %ld!",
847 return WIMLIB_ERR_MQUEUE;
850 mailbox = MALLOC(msgsize);
852 ERROR("Failed to allocate %ld bytes for mailbox", msgsize);
853 return WIMLIB_ERR_NOMEM;
855 *msgsize_ret = msgsize;
856 *mailbox_ret = mailbox;
860 static void unlink_message_queues(struct wimfs_context *ctx)
862 mq_unlink(ctx->unmount_to_daemon_mq_name);
863 mq_unlink(ctx->daemon_to_unmount_mq_name);
866 /* Closes the message queues, which are allocated in static variables */
867 static void close_message_queues(struct wimfs_context *ctx)
869 mq_close(ctx->unmount_to_daemon_mq);
870 ctx->unmount_to_daemon_mq = (mqd_t)(-1);
871 mq_close(ctx->daemon_to_unmount_mq);
872 ctx->daemon_to_unmount_mq = (mqd_t)(-1);
873 unlink_message_queues(ctx);
876 struct unmount_message_header {
882 struct unmount_request {
883 struct unmount_message_header hdr;
889 struct unmount_response {
890 struct unmount_message_header hdr;
897 static void inode_update_lte_ptr(struct inode *inode,
898 struct lookup_table_entry *old_lte,
899 struct lookup_table_entry *new_lte)
901 if (inode->lte == old_lte) {
902 inode->lte = new_lte;
904 for (unsigned i = 0; i < inode->num_ads; i++) {
905 if (inode->ads_entries[i].lte == old_lte) {
906 inode->ads_entries[i].lte = new_lte;
913 static int update_lte_of_staging_file(struct lookup_table_entry *lte,
914 struct lookup_table *table)
916 struct lookup_table_entry *duplicate_lte;
918 u8 hash[SHA1_HASH_SIZE];
921 ret = sha1sum(lte->staging_file_name, hash);
924 lookup_table_unlink(table, lte);
925 duplicate_lte = __lookup_resource(table, hash);
927 /* Merge duplicate lookup table entries */
928 duplicate_lte->refcnt += lte->refcnt;
929 inode_update_lte_ptr(lte->lte_inode, lte, duplicate_lte);
930 free_lookup_table_entry(lte);
932 if (stat(lte->staging_file_name, &stbuf) != 0) {
933 ERROR_WITH_ERRNO("Failed to stat `%s'", lte->staging_file_name);
934 return WIMLIB_ERR_STAT;
936 if (stbuf.st_size == 0) {
937 /* Zero-length stream. No lookup table entry needed. */
938 inode_update_lte_ptr(lte->lte_inode, lte, NULL);
939 free_lookup_table_entry(lte);
941 wimlib_assert(<e->file_on_disk == <e->staging_file_name);
942 lte->resource_entry.original_size = stbuf.st_size;
943 lte->resource_entry.size = stbuf.st_size;
944 lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
945 lte->file_on_disk_fp = NULL;
946 copy_hash(lte->hash, hash);
947 lookup_table_insert(table, lte);
953 static int inode_close_fds(struct inode *inode)
955 u16 num_opened_fds = inode->num_opened_fds;
956 for (u16 i = 0, j = 0; j < num_opened_fds; i++) {
957 struct wimlib_fd *fd = inode->fds[i];
959 wimlib_assert(fd->f_inode == inode);
960 int ret = close_wimlib_fd(fd);
969 /* Overwrites the WIM file, with changes saved. */
970 static int rebuild_wim(struct wimfs_context *ctx, int write_flags)
973 struct lookup_table_entry *lte, *tmp;
974 WIMStruct *w = ctx->wim;
976 DEBUG("Closing all staging file descriptors.");
977 list_for_each_entry_safe(lte, tmp, &ctx->staging_list, staging_list) {
978 ret = inode_close_fds(lte->lte_inode);
983 DEBUG("Calculating SHA1 checksums for all new staging files.");
984 list_for_each_entry(lte, &ctx->staging_list, staging_list) {
985 ret = update_lte_of_staging_file(lte, w->lookup_table);
990 xml_update_image_info(w, w->current_image);
991 ret = wimlib_overwrite(w, write_flags, 0, NULL);
993 ERROR("Failed to commit changes to mounted WIM image");
997 /* Send a message to the filesystem daemon saying whether to commit or not. */
998 static int send_unmount_request(struct wimfs_context *ctx, int unmount_flags)
1001 struct unmount_request msg;
1003 msg.hdr.min_version = WIMLIB_MAKEVERSION(1, 2, 0);
1004 msg.hdr.cur_version = WIMLIB_VERSION_CODE;
1005 msg.hdr.data_size = sizeof(msg.data);
1006 msg.data.unmount_flags = unmount_flags;
1008 ret = mq_send(ctx->unmount_to_daemon_mq, (void*)&msg,
1011 ERROR_WITH_ERRNO("Failed to notify filesystem daemon whether "
1012 "we want to commit changes or not");
1013 return WIMLIB_ERR_MQUEUE;
1018 static int receive_unmount_request(struct wimfs_context *ctx,
1024 struct timespec timeout;
1025 ssize_t bytes_received;
1026 struct unmount_request *msg;
1029 ret = get_mailbox(ctx->unmount_to_daemon_mq,
1030 sizeof(struct unmount_request),
1031 &msgsize, &mailbox);
1035 /* Wait at most 3 seconds before giving up and discarding changes. */
1036 gettimeofday(&now, NULL);
1037 timeout.tv_sec = now.tv_sec + 3;
1038 timeout.tv_nsec = now.tv_usec * 1000;
1040 bytes_received = mq_timedreceive(ctx->unmount_to_daemon_mq, mailbox,
1041 msgsize, NULL, &timeout);
1043 if (bytes_received == -1) {
1044 ERROR_WITH_ERRNO("mq_timedreceive()");
1045 ERROR("Not committing.");
1046 ret = WIMLIB_ERR_MQUEUE;
1047 } else if (bytes_received < sizeof(struct unmount_message_header) ||
1048 bytes_received != sizeof(struct unmount_message_header) + msg->hdr.data_size) {
1049 ERROR("Received invalid unmount request");
1050 ret = WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE;
1051 } else if (WIMLIB_VERSION_CODE < msg->hdr.min_version) {
1052 ERROR("Cannot understand the unmount request. "
1053 "Please upgrade wimlib to at least v%d.%d.%d",
1054 WIMLIB_GET_MAJOR_VERSION(msg->hdr.min_version),
1055 WIMLIB_GET_MINOR_VERSION(msg->hdr.min_version),
1056 WIMLIB_GET_PATCH_VERSION(msg->hdr.min_version));
1057 ret = WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE;
1059 *unmount_flags = msg->data.unmount_flags;
1066 static void send_unmount_response(struct wimfs_context *ctx, int status)
1068 struct unmount_response response;
1069 response.hdr.min_version = WIMLIB_MAKEVERSION(1, 2, 0);
1070 response.hdr.cur_version = WIMLIB_VERSION_CODE;
1071 response.hdr.data_size = sizeof(response.data);
1072 response.data.status = status;
1073 response.data.mount_flags = ctx->mount_flags;
1074 if (mq_send(ctx->daemon_to_unmount_mq, (void*)&response,
1075 sizeof(response), 1))
1076 ERROR_WITH_ERRNO("Failed to send status to unmount process");
1079 /* Wait for a message from the filesytem daemon indicating whether the
1080 * filesystem was unmounted successfully. This may
1081 * take a long time if a big WIM file needs to be rewritten.
1083 * Wait at most 600??? seconds before giving up and returning an error. Either
1084 * it's a really big WIM file, or (more likely) the filesystem daemon has
1085 * crashed or failed for some reason.
1087 * XXX come up with some method to determine if the filesystem daemon has really
1090 * XXX Idea: have mount daemon write its PID into the WIM file header? No, this
1091 * wouldn't work because we know the directory but not the WIM file...
1093 static int receive_unmount_response(struct wimfs_context *ctx)
1098 struct timespec timeout;
1099 ssize_t bytes_received;
1101 struct unmount_response *msg;
1103 ret = get_mailbox(ctx->daemon_to_unmount_mq,
1104 sizeof(struct unmount_response), &msgsize, &mailbox);
1108 DEBUG("Waiting for message telling us whether the unmount was "
1109 "successful or not.");
1111 gettimeofday(&now, NULL);
1112 timeout.tv_sec = now.tv_sec + 600;
1113 timeout.tv_nsec = now.tv_usec * 1000;
1114 bytes_received = mq_timedreceive(ctx->daemon_to_unmount_mq,
1115 mailbox, msgsize, NULL, &timeout);
1117 if (bytes_received == -1) {
1118 if (errno == ETIMEDOUT) {
1119 ERROR("Timed out- probably the filesystem daemon "
1120 "crashed and the WIM was not written "
1122 ret = WIMLIB_ERR_TIMEOUT;
1124 ERROR_WITH_ERRNO("mq_receive()");
1125 ret = WIMLIB_ERR_MQUEUE;
1127 } else if (bytes_received < sizeof(struct unmount_message_header) ||
1128 bytes_received != sizeof(struct unmount_message_header) + msg->hdr.data_size ||
1129 WIMLIB_VERSION_CODE < msg->hdr.min_version) {
1130 ERROR("Received invalid unmount response");
1131 ret = WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE;
1132 } else if (WIMLIB_VERSION_CODE < msg->hdr.min_version) {
1133 ERROR("Cannot understand the unmount response. "
1134 "Please upgrade wimlib to at least v%d.%d.%d",
1135 WIMLIB_GET_MAJOR_VERSION(msg->hdr.min_version),
1136 WIMLIB_GET_MINOR_VERSION(msg->hdr.min_version),
1137 WIMLIB_GET_PATCH_VERSION(msg->hdr.min_version));
1138 ret = WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE;
1140 ret = msg->data.status;
1142 ERROR("A failure status (%d) was returned "
1143 "by the filesystem daemon", ret);
1150 /* Execute `fusermount -u', which is installed setuid root, to unmount the WIM.
1152 * FUSE does not yet implement synchronous unmounts. This means that fusermount
1153 * -u will return before the filesystem daemon returns from wimfs_destroy().
1154 * This is partly what we want, because we need to send a message from this
1155 * process to the filesystem daemon telling whether --commit was specified or
1156 * not. However, after that, the unmount process must wait for the filesystem
1157 * daemon to finish writing the WIM file.
1159 static int execute_fusermount(const char *dir)
1167 ERROR_WITH_ERRNO("Failed to fork()");
1168 return WIMLIB_ERR_FORK;
1172 execlp("fusermount", "fusermount", "-u", dir, NULL);
1173 ERROR_WITH_ERRNO("Failed to execute `fusermount'");
1174 exit(WIMLIB_ERR_FUSERMOUNT);
1178 ret = wait(&status);
1180 ERROR_WITH_ERRNO("Failed to wait for fusermount process to "
1182 return WIMLIB_ERR_FUSERMOUNT;
1186 if (status == WIMLIB_ERR_FUSERMOUNT)
1187 ERROR("Could not find the `fusermount' program");
1189 ERROR("fusermount exited with status %d", status);
1191 /* Try again, but with the `umount' program. This is required
1192 * on other FUSE implementations such as FreeBSD's that do not
1193 * have a `fusermount' program. */
1197 ERROR_WITH_ERRNO("Failed to fork()");
1198 return WIMLIB_ERR_FORK;
1202 execlp("umount", "umount", dir, NULL);
1203 ERROR_WITH_ERRNO("Failed to execute `umount'");
1204 exit(WIMLIB_ERR_FUSERMOUNT);
1208 ret = wait(&status);
1210 ERROR_WITH_ERRNO("Failed to wait for `umount' process to "
1212 return WIMLIB_ERR_FUSERMOUNT;
1215 ERROR("`umount' exited with failure status");
1216 return WIMLIB_ERR_FUSERMOUNT;
1222 static int wimfs_access(const char *path, int mask)
1224 /* Permissions not implemented */
1228 static int wimfs_chmod(const char *path, mode_t mask)
1230 struct dentry *dentry;
1231 struct wimfs_context *ctx = wimfs_get_context();
1232 struct inode *inode;
1236 ret = lookup_resource(ctx->wim, path,
1237 get_lookup_flags(ctx) | LOOKUP_FLAG_DIRECTORY_OK,
1238 &dentry, NULL, NULL);
1241 inode = dentry->d_inode;
1242 inode_to_stbuf(inode, NULL, &stbuf);
1243 if (mask == stbuf.st_mode)
1249 /* Called when the filesystem is unmounted. */
1250 static void wimfs_destroy(void *p)
1252 /* The `imagex unmount' command, which is running in a separate process
1253 * and is executing the wimlib_unmount() function, will send this
1254 * process a `struct unmount_request' through a message queue that
1255 * specifies some unmount options, such as other to commit changes or
1260 struct wimfs_context *ctx;
1263 ctx = wimfs_get_context();
1264 if (open_message_queues(ctx, true))
1267 ret = receive_unmount_request(ctx, &unmount_flags);
1270 if (ctx->mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
1271 if (unmount_flags & WIMLIB_UNMOUNT_FLAG_COMMIT) {
1272 int write_flags = 0;
1273 if (unmount_flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY)
1274 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1275 if (unmount_flags & WIMLIB_UNMOUNT_FLAG_REBUILD)
1276 write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1277 if (unmount_flags & WIMLIB_UNMOUNT_FLAG_RECOMPRESS)
1278 write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
1279 status = rebuild_wim(ctx, write_flags);
1281 ret = delete_staging_dir(ctx);
1283 ERROR("Failed to delete the staging directory");
1288 DEBUG("Read-only mount");
1291 send_unmount_response(ctx, status);
1292 close_message_queues(ctx);
1296 static int wimfs_fallocate(const char *path, int mode,
1297 off_t offset, off_t len, struct fuse_file_info *fi)
1299 struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1300 wimlib_assert(fd->staging_fd != -1);
1301 return fallocate(fd->staging_fd, mode, offset, len);
1306 static int wimfs_fgetattr(const char *path, struct stat *stbuf,
1307 struct fuse_file_info *fi)
1309 struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1310 return inode_to_stbuf(fd->f_inode, fd->f_lte, stbuf);
1313 static int wimfs_ftruncate(const char *path, off_t size,
1314 struct fuse_file_info *fi)
1316 struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1317 int ret = ftruncate(fd->staging_fd, size);
1320 if (fd->f_lte && size < fd->f_lte->resource_entry.original_size)
1321 fd->f_lte->resource_entry.original_size = size;
1326 * Fills in a `struct stat' that corresponds to a file or directory in the WIM.
1328 static int wimfs_getattr(const char *path, struct stat *stbuf)
1330 struct dentry *dentry;
1331 struct lookup_table_entry *lte;
1333 struct wimfs_context *ctx = wimfs_get_context();
1335 ret = lookup_resource(ctx->wim, path,
1336 get_lookup_flags(ctx) | LOOKUP_FLAG_DIRECTORY_OK,
1337 &dentry, <e, NULL);
1340 return inode_to_stbuf(dentry->d_inode, lte, stbuf);
1344 /* Read an alternate data stream through the XATTR interface, or get its size */
1345 static int wimfs_getxattr(const char *path, const char *name, char *value,
1349 struct inode *inode;
1350 struct ads_entry *ads_entry;
1352 struct lookup_table_entry *lte;
1353 struct wimfs_context *ctx = wimfs_get_context();
1355 if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1358 if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1362 inode = wim_pathname_to_inode(ctx->wim, path);
1366 ads_entry = inode_get_ads_entry(inode, name, NULL);
1370 lte = ads_entry->lte;
1371 res_size = wim_resource_size(lte);
1376 if (res_size > size)
1379 ret = read_full_wim_resource(lte, (u8*)value,
1380 WIMLIB_RESOURCE_FLAG_MULTITHREADED);
1388 /* Create a hard link */
1389 static int wimfs_link(const char *to, const char *from)
1391 struct dentry *from_dentry, *from_dentry_parent;
1392 const char *link_name;
1393 struct inode *inode;
1394 struct lookup_table_entry *lte;
1395 WIMStruct *w = wimfs_get_WIMStruct();
1398 inode = wim_pathname_to_inode(w, to);
1402 if (inode->attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1405 if (inode->attributes & FILE_ATTRIBUTE_DIRECTORY)
1408 from_dentry_parent = get_parent_dentry(w, from);
1409 if (!from_dentry_parent)
1411 if (!dentry_is_directory(from_dentry_parent))
1414 link_name = path_basename(from);
1415 if (get_dentry_child_with_name(from_dentry_parent, link_name))
1417 from_dentry = new_dentry(link_name);
1421 inode_add_dentry(from_dentry, inode);
1422 from_dentry->d_inode = inode;
1423 inode->link_count++;
1425 for (i = 0; i <= inode->num_ads; i++) {
1426 lte = inode_stream_lte_resolved(inode, i);
1430 dentry_add_child(from_dentry_parent, from_dentry);
1435 static int wimfs_listxattr(const char *path, char *list, size_t size)
1438 struct inode *inode;
1439 struct wimfs_context *ctx = wimfs_get_context();
1443 if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1446 /* List alternate data streams, or get the list size */
1448 inode = wim_pathname_to_inode(ctx->wim, path);
1454 for (i = 0; i < inode->num_ads; i++)
1455 needed_size += inode->ads_entries[i].stream_name_utf8_len + 6;
1459 for (i = 0; i < inode->num_ads; i++) {
1460 needed_size = inode->ads_entries[i].stream_name_utf8_len + 6;
1461 if (needed_size > size)
1463 p += sprintf(p, "user.%s",
1464 inode->ads_entries[i].stream_name_utf8) + 1;
1465 size -= needed_size;
1473 /* Create a directory in the WIM.
1474 * @mode is currently ignored. */
1475 static int wimfs_mkdir(const char *path, mode_t mode)
1477 struct dentry *dentry;
1480 ret = create_dentry(wimfs_get_context(), path, &dentry);
1482 dentry->d_inode->attributes = FILE_ATTRIBUTE_DIRECTORY;
1486 /* Create a regular file in the WIM.
1487 * @mode is currently ignored. */
1488 static int wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
1490 const char *stream_name;
1491 struct wimfs_context *ctx = wimfs_get_context();
1492 if ((ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
1493 && (stream_name = path_stream_name(path))) {
1494 /* Make an alternate data stream */
1495 struct ads_entry *new_entry;
1496 struct inode *inode;
1498 char *p = (char*)stream_name - 1;
1499 wimlib_assert(*p == ':');
1502 inode = wim_pathname_to_inode(ctx->wim, path);
1505 if (inode->attributes &
1506 (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
1508 if (inode_get_ads_entry(inode, stream_name, NULL))
1510 new_entry = inode_add_ads(inode, stream_name);
1515 struct dentry *dentry;
1518 /* Make a normal file (not an alternate data stream) */
1519 ret = create_dentry(ctx, path, &dentry);
1521 dentry->d_inode->attributes = FILE_ATTRIBUTE_NORMAL;
1528 static int wimfs_open(const char *path, struct fuse_file_info *fi)
1530 struct dentry *dentry;
1531 struct lookup_table_entry *lte;
1533 struct wimlib_fd *fd;
1534 struct inode *inode;
1537 struct wimfs_context *ctx = wimfs_get_context();
1539 ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1540 &dentry, <e, &stream_idx);
1544 inode = dentry->d_inode;
1546 if (stream_idx == 0)
1549 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
1551 /* The file resource may be in the staging directory (read-write mounts
1552 * only) or in the WIM. If it's in the staging directory, we need to
1553 * open a native file descriptor for the corresponding file. Otherwise,
1554 * we can read the file resource directly from the WIM file if we are
1555 * opening it read-only, but we need to extract the resource to the
1556 * staging directory if we are opening it writable. */
1558 if (flags_writable(fi->flags) &&
1559 (!lte || lte->resource_location != RESOURCE_IN_STAGING_FILE)) {
1560 u64 size = (lte) ? wim_resource_size(lte) : 0;
1561 ret = extract_resource_to_staging_dir(inode, stream_id,
1567 ret = alloc_wimlib_fd(inode, stream_id, lte, &fd,
1568 wimfs_ctx_readonly(ctx));
1572 if (lte && lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1573 fd->staging_fd = open(lte->staging_file_name, fi->flags);
1574 if (fd->staging_fd == -1) {
1575 int errno_save = errno;
1576 close_wimlib_fd(fd);
1580 fi->fh = (uintptr_t)fd;
1584 /* Opens a directory. */
1585 static int wimfs_opendir(const char *path, struct fuse_file_info *fi)
1587 struct inode *inode;
1589 struct wimlib_fd *fd = NULL;
1590 struct wimfs_context *ctx = wimfs_get_context();
1591 WIMStruct *w = ctx->wim;
1593 inode = wim_pathname_to_inode(w, path);
1596 if (!inode_is_directory(inode))
1598 ret = alloc_wimlib_fd(inode, 0, NULL, &fd, wimfs_ctx_readonly(ctx));
1599 fi->fh = (uintptr_t)fd;
1605 * Read data from a file in the WIM or in the staging directory.
1607 static int wimfs_read(const char *path, char *buf, size_t size,
1608 off_t offset, struct fuse_file_info *fi)
1610 struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1616 if (!fd->f_lte) /* Empty stream with no lookup table entry */
1619 if (fd->f_lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1620 /* Read from staging file */
1622 wimlib_assert(fd->f_lte->staging_file_name);
1623 wimlib_assert(fd->staging_fd != -1);
1625 DEBUG("Seek to offset %zu", offset);
1627 if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1629 ret = read(fd->staging_fd, buf, size);
1635 u64 res_size = wim_resource_size(fd->f_lte);
1636 if (offset > res_size)
1638 size = min(size, res_size - offset);
1639 if (read_wim_resource(fd->f_lte, (u8*)buf,
1641 WIMLIB_RESOURCE_FLAG_MULTITHREADED) != 0)
1647 struct fill_params {
1649 fuse_fill_dir_t filler;
1652 static int dentry_fuse_fill(struct dentry *dentry, void *arg)
1654 struct fill_params *fill_params = arg;
1655 return fill_params->filler(fill_params->buf, dentry->file_name_utf8,
1659 /* Fills in the entries of the directory specified by @path using the
1660 * FUSE-provided function @filler. */
1661 static int wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
1662 off_t offset, struct fuse_file_info *fi)
1664 struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1665 struct inode *inode;
1670 inode = fd->f_inode;
1672 struct fill_params fill_params = {
1677 filler(buf, ".", NULL, 0);
1678 filler(buf, "..", NULL, 0);
1680 return for_dentry_in_rbtree(inode->children.rb_node,
1681 dentry_fuse_fill, &fill_params);
1685 static int wimfs_readlink(const char *path, char *buf, size_t buf_len)
1687 struct wimfs_context *ctx = wimfs_get_context();
1688 struct inode *inode = wim_pathname_to_inode(ctx->wim, path);
1692 if (!inode_is_symlink(inode))
1695 ret = inode_readlink(inode, buf, buf_len, ctx->wim,
1696 WIMLIB_RESOURCE_FLAG_MULTITHREADED);
1703 static int wimfs_release(const char *path, struct fuse_file_info *fi)
1705 struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1706 return close_wimlib_fd(fd);
1709 /* Close a directory */
1710 static int wimfs_releasedir(const char *path, struct fuse_file_info *fi)
1712 struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1713 return close_wimlib_fd(fd);
1717 /* Remove an alternate data stream through the XATTR interface */
1718 static int wimfs_removexattr(const char *path, const char *name)
1720 struct inode *inode;
1721 struct ads_entry *ads_entry;
1723 struct wimfs_context *ctx = wimfs_get_context();
1725 if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1728 if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1732 inode = wim_pathname_to_inode(ctx->wim, path);
1736 ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
1739 inode_remove_ads(inode, ads_idx, ctx->wim->lookup_table);
1744 /* Renames a file or directory. See rename (3) */
1745 static int wimfs_rename(const char *from, const char *to)
1749 struct dentry *parent_of_dst;
1750 char *file_name_utf16 = NULL, *file_name_utf8 = NULL;
1751 u16 file_name_utf16_len, file_name_utf8_len;
1752 WIMStruct *w = wimfs_get_WIMStruct();
1755 /* This rename() implementation currently only supports actual files
1756 * (not alternate data streams) */
1758 src = get_dentry(w, from);
1762 dst = get_dentry(w, to);
1764 ret = get_names(&file_name_utf16, &file_name_utf8,
1765 &file_name_utf16_len, &file_name_utf8_len,
1771 /* Destination file exists */
1773 if (src == dst) /* Same file */
1776 if (!dentry_is_directory(src)) {
1777 /* Cannot rename non-directory to directory. */
1778 if (dentry_is_directory(dst))
1781 /* Cannot rename directory to a non-directory or a non-empty
1783 if (!dentry_is_directory(dst))
1785 if (inode_has_children(dst->d_inode))
1788 parent_of_dst = dst->parent;
1789 remove_dentry(dst, w->lookup_table);
1791 /* Destination does not exist */
1792 parent_of_dst = get_parent_dentry(w, to);
1796 if (!dentry_is_directory(parent_of_dst))
1800 FREE(src->file_name);
1801 FREE(src->file_name_utf8);
1802 src->file_name = file_name_utf16;
1803 src->file_name_utf8 = file_name_utf8;
1804 src->file_name_len = file_name_utf16_len;
1805 src->file_name_utf8_len = file_name_utf8_len;
1808 dentry_add_child(parent_of_dst, src);
1812 /* Remove a directory */
1813 static int wimfs_rmdir(const char *path)
1815 struct dentry *dentry;
1816 WIMStruct *w = wimfs_get_WIMStruct();
1818 dentry = get_dentry(w, path);
1822 if (!dentry_is_empty_directory(dentry))
1825 remove_dentry(dentry, w->lookup_table);
1830 /* Write an alternate data stream through the XATTR interface */
1831 static int wimfs_setxattr(const char *path, const char *name,
1832 const char *value, size_t size, int flags)
1834 struct ads_entry *existing_ads_entry;
1835 struct ads_entry *new_ads_entry;
1836 struct lookup_table_entry *existing_lte;
1837 struct lookup_table_entry *lte;
1838 struct inode *inode;
1839 u8 value_hash[SHA1_HASH_SIZE];
1841 struct wimfs_context *ctx = wimfs_get_context();
1843 if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1846 if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1850 inode = wim_pathname_to_inode(ctx->wim, path);
1854 existing_ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
1855 if (existing_ads_entry) {
1856 if (flags & XATTR_CREATE)
1858 inode_remove_ads(inode, ads_idx, ctx->wim->lookup_table);
1860 if (flags & XATTR_REPLACE)
1863 new_ads_entry = inode_add_ads(inode, name);
1867 sha1_buffer((const u8*)value, size, value_hash);
1869 existing_lte = __lookup_resource(ctx->wim->lookup_table, value_hash);
1876 lte = new_lookup_table_entry();
1879 value_copy = MALLOC(size);
1884 memcpy(value_copy, value, size);
1885 lte->resource_location = RESOURCE_IN_ATTACHED_BUFFER;
1886 lte->attached_buffer = value_copy;
1887 lte->resource_entry.original_size = size;
1888 lte->resource_entry.size = size;
1889 lte->resource_entry.flags = 0;
1890 copy_hash(lte->hash, value_hash);
1891 lookup_table_insert(ctx->wim->lookup_table, lte);
1893 new_ads_entry->lte = lte;
1898 static int wimfs_symlink(const char *to, const char *from)
1900 struct wimfs_context *ctx = wimfs_get_context();
1901 struct dentry *dentry;
1904 ret = create_dentry(ctx, from, &dentry);
1906 dentry->d_inode->attributes = FILE_ATTRIBUTE_REPARSE_POINT;
1907 dentry->d_inode->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
1908 if (inode_set_symlink(dentry->d_inode, to,
1909 ctx->wim->lookup_table, NULL))
1911 unlink_dentry(dentry);
1912 free_dentry(dentry);
1920 /* Reduce the size of a file */
1921 static int wimfs_truncate(const char *path, off_t size)
1923 struct dentry *dentry;
1924 struct lookup_table_entry *lte;
1928 struct inode *inode;
1929 struct wimfs_context *ctx = wimfs_get_context();
1931 ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1932 &dentry, <e, &stream_idx);
1937 if (lte == NULL && size == 0)
1940 inode = dentry->d_inode;
1941 if (stream_idx == 0)
1944 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
1946 if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1947 ret = truncate(lte->staging_file_name, size);
1951 /* File in WIM. Extract it to the staging directory, but only
1952 * the first @size bytes of it. */
1953 ret = extract_resource_to_staging_dir(inode, stream_id,
1959 /* Unlink a non-directory or alternate data stream */
1960 static int wimfs_unlink(const char *path)
1962 struct dentry *dentry;
1963 struct lookup_table_entry *lte;
1966 struct wimfs_context *ctx = wimfs_get_context();
1968 ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1969 &dentry, <e, &stream_idx);
1974 if (stream_idx == 0)
1975 remove_dentry(dentry, ctx->wim->lookup_table);
1977 inode_remove_ads(dentry->d_inode, stream_idx - 1,
1978 ctx->wim->lookup_table);
1982 #ifdef HAVE_UTIMENSAT
1984 * Change the timestamp on a file dentry.
1986 * Note that alternate data streams do not have their own timestamps.
1988 static int wimfs_utimens(const char *path, const struct timespec tv[2])
1990 struct dentry *dentry;
1991 struct inode *inode;
1992 WIMStruct *w = wimfs_get_WIMStruct();
1994 dentry = get_dentry(w, path);
1997 inode = dentry->d_inode;
1999 if (tv[0].tv_nsec != UTIME_OMIT) {
2000 if (tv[0].tv_nsec == UTIME_NOW)
2001 inode->last_access_time = get_wim_timestamp();
2003 inode->last_access_time = timespec_to_wim_timestamp(&tv[0]);
2005 if (tv[1].tv_nsec != UTIME_OMIT) {
2006 if (tv[1].tv_nsec == UTIME_NOW)
2007 inode->last_write_time = get_wim_timestamp();
2009 inode->last_write_time = timespec_to_wim_timestamp(&tv[1]);
2014 static int wimfs_utime(const char *path, struct utimbuf *times)
2016 struct dentry *dentry;
2017 struct inode *inode;
2018 WIMStruct *w = wimfs_get_WIMStruct();
2020 dentry = get_dentry(w, path);
2023 inode = dentry->d_inode;
2025 inode->last_write_time = unix_timestamp_to_wim(times->modtime);
2026 inode->last_access_time = unix_timestamp_to_wim(times->actime);
2031 /* Writes to a file in the WIM filesystem.
2032 * It may be an alternate data stream, but here we don't even notice because we
2033 * just get a lookup table entry. */
2034 static int wimfs_write(const char *path, const char *buf, size_t size,
2035 off_t offset, struct fuse_file_info *fi)
2037 struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
2044 wimlib_assert(fd->f_lte);
2045 wimlib_assert(fd->f_lte->staging_file_name);
2046 wimlib_assert(fd->staging_fd != -1);
2047 wimlib_assert(fd->f_inode);
2049 /* Seek to the requested position */
2050 if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
2053 /* Write the data. */
2054 ret = write(fd->staging_fd, buf, size);
2058 now = get_wim_timestamp();
2059 fd->f_inode->last_write_time = now;
2060 fd->f_inode->last_access_time = now;
2064 static struct fuse_operations wimfs_operations = {
2065 .access = wimfs_access,
2066 .chmod = wimfs_chmod,
2067 .destroy = wimfs_destroy,
2069 .fallocate = wimfs_fallocate,
2071 .fgetattr = wimfs_fgetattr,
2072 .ftruncate = wimfs_ftruncate,
2073 .getattr = wimfs_getattr,
2075 .getxattr = wimfs_getxattr,
2079 .listxattr = wimfs_listxattr,
2081 .mkdir = wimfs_mkdir,
2082 .mknod = wimfs_mknod,
2084 .opendir = wimfs_opendir,
2086 .readdir = wimfs_readdir,
2087 .readlink = wimfs_readlink,
2088 .release = wimfs_release,
2089 .releasedir = wimfs_releasedir,
2091 .removexattr = wimfs_removexattr,
2093 .rename = wimfs_rename,
2094 .rmdir = wimfs_rmdir,
2096 .setxattr = wimfs_setxattr,
2098 .symlink = wimfs_symlink,
2099 .truncate = wimfs_truncate,
2100 .unlink = wimfs_unlink,
2101 #ifdef HAVE_UTIMENSAT
2102 .utimens = wimfs_utimens,
2104 .utime = wimfs_utime,
2106 .write = wimfs_write,
2108 #if FUSE_MAJOR_VERSION > 2 || (FUSE_MAJOR_VERSION == 2 && FUSE_MINOR_VERSION >= 8)
2109 .flag_nullpath_ok = 1,
2111 #if FUSE_MAJOR_VERSION > 2 || (FUSE_MAJOR_VERSION == 2 && FUSE_MINOR_VERSION >= 9)
2113 .flag_utime_omit_ok = 1,
2118 /* Mounts an image from a WIM file. */
2119 WIMLIBAPI int wimlib_mount_image(WIMStruct *wim, int image, const char *dir,
2120 int mount_flags, WIMStruct **additional_swms,
2121 unsigned num_additional_swms,
2122 const char *staging_dir)
2128 struct lookup_table *joined_tab, *wim_tab_save;
2129 struct image_metadata *imd;
2130 struct wimfs_context ctx;
2131 struct hlist_node *cur_node;
2132 struct inode *inode;
2134 DEBUG("Mount: wim = %p, image = %d, dir = %s, flags = %d, ",
2135 wim, image, dir, mount_flags);
2138 return WIMLIB_ERR_INVALID_PARAM;
2140 ret = verify_swm_set(wim, additional_swms, num_additional_swms);
2144 if ((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) && (wim->hdr.total_parts != 1)) {
2145 ERROR("Cannot mount a split WIM read-write");
2146 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
2149 if (num_additional_swms) {
2150 ret = new_joined_lookup_table(wim, additional_swms,
2151 num_additional_swms,
2155 wim_tab_save = wim->lookup_table;
2156 wim->lookup_table = joined_tab;
2159 if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2160 ret = wim_run_full_verifications(wim);
2165 ret = select_wim_image(wim, image);
2169 DEBUG("Selected image %d", image);
2171 imd = wim_get_current_image_metadata(wim);
2173 if (imd->root_dentry->refcnt != 1) {
2174 ERROR("Cannot mount image that was just exported with "
2175 "wimlib_export_image()");
2176 ret = WIMLIB_ERR_INVALID_PARAM;
2180 if (imd->modified) {
2181 ERROR("Cannot mount image that was added "
2182 "with wimlib_add_image()");
2183 ret = WIMLIB_ERR_INVALID_PARAM;
2187 if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2188 ret = lock_wim(wim, wim->fp);
2193 if (!(mount_flags & (WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
2194 WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
2195 WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)))
2196 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
2199 DEBUG("Initializing struct wimfs_context");
2200 init_wimfs_context(&ctx);
2202 ctx.mount_flags = mount_flags;
2203 ctx.image_inode_list = &imd->inode_list;
2205 if (mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
2206 ctx.default_lookup_flags = LOOKUP_FLAG_ADS_OK;
2208 DEBUG("Unlinking message queues in case they already exist");
2209 ret = set_message_queue_names(&ctx, dir);
2212 unlink_message_queues(&ctx);
2214 DEBUG("Preparing arguments to fuse_main()");
2216 dir_copy = STRDUP(dir);
2218 goto out_free_message_queue_names;
2220 argv[argc++] = "imagex";
2221 argv[argc++] = dir_copy;
2223 /* disable multi-threaded operation for read-write mounts */
2224 if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2225 argv[argc++] = "-s";
2227 if (mount_flags & WIMLIB_MOUNT_FLAG_DEBUG)
2228 argv[argc++] = "-d";
2231 * We provide the use_ino option because we are going to assign inode
2232 * numbers oursides. The inodes will be given unique numbers in the
2233 * assign_inode_numbers() function, and the static variable @next_ino is
2234 * set to the next available inode number.
2236 char optstring[256] =
2240 #if FUSE_MAJOR_VERSION > 2 || (FUSE_MAJOR_VERSION == 2 && FUSE_MINOR_VERSION >= 8)
2244 argv[argc++] = "-o";
2245 argv[argc++] = optstring;
2246 if ((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
2247 /* Read-write mount. Make the staging directory */
2248 ret = make_staging_dir(&ctx, staging_dir);
2250 goto out_free_dir_copy;
2252 /* Read-only mount */
2253 strcat(optstring, ",ro");
2260 DEBUG("FUSE command line (argc = %d): ", argc);
2261 for (i = 0; i < argc; i++) {
2262 fputs(argv[i], stdout);
2270 /* Mark dentry tree as modified if read-write mount. */
2271 if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2273 imd->has_been_mounted_rw = 1;
2276 /* Resolve the lookup table entries for every inode in the image, and
2277 * assign inode numbers */
2278 DEBUG("Resolving lookup table entries and assigning inode numbers");
2281 hlist_for_each_entry(inode, cur_node, &imd->inode_list, hlist) {
2282 inode_resolve_ltes(inode, wim->lookup_table);
2283 inode->ino = ctx.next_ino++;
2285 /*ctx.next_ino = assign_inode_numbers(&imd->inode_list);*/
2286 DEBUG("(next_ino = %"PRIu64")", ctx.next_ino);
2288 DEBUG("Calling fuse_main()");
2290 ret = fuse_main(argc, argv, &wimfs_operations, &ctx);
2292 DEBUG("Returned from fuse_main() (ret = %d)", ret);
2294 ret = WIMLIB_ERR_FUSE;
2298 wim->wim_locked = 0;
2299 out_free_message_queue_names:
2300 free_message_queue_names(&ctx);
2302 if (num_additional_swms) {
2303 free_lookup_table(wim->lookup_table);
2304 wim->lookup_table = wim_tab_save;
2310 * Unmounts the WIM file that was previously mounted on @dir by using
2311 * wimlib_mount_image().
2313 WIMLIBAPI int wimlib_unmount_image(const char *dir, int unmount_flags,
2314 wimlib_progress_func_t progress_func)
2317 struct wimfs_context ctx;
2319 init_wimfs_context(&ctx);
2321 ret = set_message_queue_names(&ctx, dir);
2325 ret = open_message_queues(&ctx, false);
2327 goto out_free_message_queue_names;
2329 ret = send_unmount_request(&ctx, unmount_flags);
2331 goto out_close_message_queues;
2333 ret = execute_fusermount(dir);
2335 goto out_close_message_queues;
2336 ret = receive_unmount_response(&ctx);
2337 out_close_message_queues:
2338 close_message_queues(&ctx);
2339 out_free_message_queue_names:
2340 free_message_queue_names(&ctx);
2345 #else /* WITH_FUSE */
2348 static inline int mount_unsupported_error()
2350 ERROR("wimlib was compiled with --without-fuse, which disables support "
2351 "for mounting WIMs.");
2352 return WIMLIB_ERR_UNSUPPORTED;
2355 WIMLIBAPI int wimlib_unmount_image(const char *dir, int unmount_flags,
2356 wimlib_progress_func_t progress_func)
2358 return mount_unsupported_error();
2361 WIMLIBAPI int wimlib_mount_image(WIMStruct *wim_p, int image, const char *dir,
2362 int mount_flags, WIMStruct **additional_swms,
2363 unsigned num_additional_swms,
2364 const char *staging_dir)
2366 return mount_unsupported_error();
2369 #endif /* WITH_FUSE */