]> wimlib.net Git - wimlib/blob - src/mount_image.c
7fe8bb537fb1621a5e5742fba40aa98ed8347dde
[wimlib] / src / mount_image.c
1 /*
2  * mount_image.c
3  *
4  * This file implements mounting of WIM images using FUSE
5  * (Filesystem in Userspace).  See http://fuse.sourceforge.net/.
6  *
7  * Currently it is only expected to work on Linux.
8  */
9
10 /*
11  * Copyright (C) 2012, 2013, 2014, 2015 Eric Biggers
12  *
13  * This file is free software; you can redistribute it and/or modify it under
14  * the terms of the GNU Lesser General Public License as published by the Free
15  * Software Foundation; either version 3 of the License, or (at your option) any
16  * later version.
17  *
18  * This file is distributed in the hope that it will be useful, but WITHOUT
19  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
20  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
21  * details.
22  *
23  * You should have received a copy of the GNU Lesser General Public License
24  * along with this file; if not, see http://www.gnu.org/licenses/.
25  */
26
27 #ifdef HAVE_CONFIG_H
28 #  include "config.h"
29 #endif
30
31 #include "wimlib.h"
32 #include "wimlib/error.h"
33
34 #ifdef WITH_FUSE
35
36 #ifdef __WIN32__
37 #  error "FUSE mount not supported on Windows!  Please configure --without-fuse"
38 #endif
39
40 #define FUSE_USE_VERSION 26
41
42 #include <attr/xattr.h>
43 #include <dirent.h>
44 #include <errno.h>
45 #include <fuse.h>
46 #include <limits.h>
47 #include <mqueue.h>
48 #include <pthread.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <sys/stat.h>
52 #include <sys/time.h>
53 #include <sys/types.h>
54 #include <unistd.h>
55 #include <utime.h>
56
57 #include "wimlib/blob_table.h"
58 #include "wimlib/dentry.h"
59 #include "wimlib/encoding.h"
60 #include "wimlib/metadata.h"
61 #include "wimlib/paths.h"
62 #include "wimlib/progress.h"
63 #include "wimlib/reparse.h"
64 #include "wimlib/timestamp.h"
65 #include "wimlib/unix_data.h"
66 #include "wimlib/write.h"
67 #include "wimlib/xml.h"
68
69 #ifndef O_NOFOLLOW
70 #  define O_NOFOLLOW 0  /* Security only...  */
71 #endif
72
73 #define WIMFS_MQUEUE_NAME_LEN 32
74
75 #define WIMLIB_UNMOUNT_FLAG_SEND_PROGRESS 0x80000000
76
77 struct wimfs_unmount_info {
78         unsigned unmount_flags;
79         char mq_name[WIMFS_MQUEUE_NAME_LEN + 1];
80 };
81
82 struct commit_progress_report {
83         enum wimlib_progress_msg msg;
84         union wimlib_progress_info info;
85 };
86
87 /* Description of an open file on a mounted WIM image.  Actually, this
88  * represents the open state of a particular data stream of an inode, rather
89  * than the inode itself.  (An inode might have multiple named data streams in
90  * addition to the default, unnamed data stream.)  At a given time, an inode in
91  * the WIM image might have multiple file descriptors open to it, each to any
92  * one of its data streams.  */
93 struct wimfs_fd {
94
95         /* Pointer to the inode of this open file.
96          * 'i_num_opened_fds' of the inode tracks the number of file descriptors
97          * that reference it.  */
98         struct wim_inode *f_inode;
99
100         /* Pointer to the blob descriptor for the data stream that has been
101          * opened.  'num_opened_fds' of the blob descriptor tracks the number of
102          * file descriptors that reference it.  Or, this value may be NULL,
103          * which indicates that the opened stream is empty and consequently does
104          * not have a blob descriptor.  */
105         struct blob_descriptor *f_blob;
106
107         /* If valid (filedes_valid(&f_staging_fd)), this contains the
108          * corresponding native file descriptor for the staging file that has
109          * been created for reading from and/or writing to this open stream.  A
110          * single staging file might have multiple file descriptors open to it
111          * simultaneously, each used by a different 'struct wimfs_fd'.
112          *
113          * Or, if invalid (!filedes_valid(&f_staging_fd)), this 'struct
114          * wimfs_fd' is not associated with a staging file.  This is permissible
115          * only if this 'struct wimfs_fd' was opened read-only and the stream
116          * has not yet been extracted to a staging file.  */
117         struct filedes f_staging_fd;
118
119         /* 0-based index of this file descriptor in the file descriptor table of
120          * its inode.  */
121         u16 f_idx;
122
123         /* Unique ID of the opened stream in the inode.  This will stay the same
124          * even if the indices of the inode's streams are changed by a deletion.
125          */
126         u32 f_stream_id;
127 };
128
129 #define WIMFS_FD(fi) ((struct wimfs_fd *)(uintptr_t)((fi)->fh))
130
131 /* Context structure for a mounted WIM image.  */
132 struct wimfs_context {
133         /* The WIMStruct containing the mounted image.  The mounted image is the
134          * currently selected image (wim->current_image).  */
135         WIMStruct *wim;
136
137         /* Flags passed to wimlib_mount_image() (WIMLIB_MOUNT_FLAG_*).  */
138         int mount_flags;
139
140         /* Default flags for path lookup in the WIM image.  */
141         int default_lookup_flags;
142
143         /* Information about the user who has mounted the WIM image  */
144         uid_t owner_uid;
145         gid_t owner_gid;
146
147         /* Information about the staging directory for a read-write mount.  */
148         int parent_dir_fd;
149         int staging_dir_fd;
150         char *staging_dir_name;
151
152         /* For read-write mounts, the inode number to be assigned to the next
153          * created file.  Note: since this isn't a persistent filesystem and we
154          * can re-assign the inode numbers just before mounting the image, it's
155          * good enough to just generate inode numbers sequentially.  */
156         u64 next_ino;
157
158         /* Number of file descriptors open to the mounted WIM image.  */
159         unsigned long num_open_fds;
160
161         /* Original list of blobs in the mounted image, linked by
162          * 'struct blob_descriptor'.orig_blob_list.  */
163         struct list_head orig_blob_list;
164
165         /* Parameters for unmounting the image (can be set via extended
166          * attribute "wimfs.unmount_info").  */
167         struct wimfs_unmount_info unmount_info;
168 };
169
170 #define WIMFS_CTX(fuse_ctx) ((struct wimfs_context*)(fuse_ctx)->private_data)
171
172 /* Retrieve the context structure for the currently mounted WIM image.
173  *
174  * Note: this is a per-thread variable.  It is possible for different threads to
175  * mount different images at the same time in the same process, although they
176  * must use different WIMStructs!  */
177 static inline struct wimfs_context *
178 wimfs_get_context(void)
179 {
180         return WIMFS_CTX(fuse_get_context());
181 }
182
183 static void
184 wimfs_inc_num_open_fds(void)
185 {
186         wimfs_get_context()->num_open_fds++;
187 }
188
189 static void
190 wimfs_dec_num_open_fds(void)
191 {
192         wimfs_get_context()->num_open_fds--;
193 }
194
195 /* Retrieve the WIMStruct for the currently mounted WIM image.  */
196 static inline WIMStruct *
197 wimfs_get_WIMStruct(void)
198 {
199         return wimfs_get_context()->wim;
200 }
201
202 /* Is write permission requested on the file?  */
203 static inline bool
204 flags_writable(int open_flags)
205 {
206         int accmode = (open_flags & O_ACCMODE);
207         return (accmode == O_RDWR || accmode == O_WRONLY);
208 }
209
210 static mode_t
211 fuse_mask_mode(mode_t mode, const struct fuse_context *fuse_ctx)
212 {
213 #if FUSE_MAJOR_VERSION > 2 || (FUSE_MAJOR_VERSION == 2 && FUSE_MINOR_VERSION >= 8)
214         mode &= ~fuse_ctx->umask;
215 #endif
216         return mode;
217 }
218
219 /*
220  * Allocate a file descriptor to a data stream in the mounted WIM image.
221  *
222  * @inode
223  *      The inode containing the stream being opened
224  * @strm
225  *      The stream of the inode being opened
226  * @fd_ret
227  *      On success, a pointer to the new file descriptor will be stored here.
228  *
229  * Returns 0 or a -errno code.
230  */
231 static int
232 alloc_wimfs_fd(struct wim_inode *inode,
233                struct wim_inode_stream *strm,
234                struct wimfs_fd **fd_ret)
235 {
236         static const u16 min_fds_per_alloc = 8;
237         static const u16 max_fds = 0xffff;
238         u16 i;
239         struct wimfs_fd *fd;
240
241         if (inode->i_num_opened_fds == inode->i_num_allocated_fds) {
242                 u16 num_new_fds;
243                 struct wimfs_fd **fds;
244
245                 /* Expand this inode's file descriptor table.  */
246
247                 num_new_fds = max(min_fds_per_alloc,
248                                   inode->i_num_allocated_fds / 4);
249
250                 num_new_fds = min(num_new_fds,
251                                   max_fds - inode->i_num_allocated_fds);
252
253                 if (num_new_fds == 0)
254                         return -EMFILE;
255
256                 fds = REALLOC(inode->i_fds,
257                               (inode->i_num_allocated_fds + num_new_fds) *
258                                 sizeof(fds[0]));
259                 if (!fds)
260                         return -ENOMEM;
261
262                 memset(&fds[inode->i_num_allocated_fds], 0,
263                        num_new_fds * sizeof(fds[0]));
264                 inode->i_fds = fds;
265                 inode->i_num_allocated_fds += num_new_fds;
266                 inode->i_next_fd = inode->i_num_opened_fds;
267         }
268
269         /* Allocate the file descriptor in the first available space in the
270          * inode's file descriptor table.
271          *
272          * i_next_fd is the lower bound on the next open slot.  */
273         for (i = inode->i_next_fd; inode->i_fds[i]; i++)
274                 ;
275
276         fd = MALLOC(sizeof(*fd));
277         if (!fd)
278                 return -ENOMEM;
279
280         fd->f_inode     = inode;
281         fd->f_blob      = stream_blob_resolved(strm);
282         filedes_invalidate(&fd->f_staging_fd);
283         fd->f_idx       = i;
284         fd->f_stream_id = strm->stream_id;
285         *fd_ret         = fd;
286         inode->i_fds[i] = fd;
287         inode->i_num_opened_fds++;
288         if (fd->f_blob)
289                 fd->f_blob->num_opened_fds++;
290         wimfs_inc_num_open_fds();
291         inode->i_next_fd = i + 1;
292         return 0;
293 }
294
295 /*
296  * Close a file descriptor to a data stream in the mounted WIM image.
297  *
298  * Returns 0 or a -errno code.  The file descriptor is always closed.
299  */
300 static int
301 close_wimfs_fd(struct wimfs_fd *fd)
302 {
303         int ret = 0;
304         struct wim_inode *inode;
305
306         /* Close the staging file if open.  */
307         if (filedes_valid(&fd->f_staging_fd))
308                  if (filedes_close(&fd->f_staging_fd))
309                          ret = -errno;
310
311         /* Release this file descriptor from its blob descriptor.  */
312         if (fd->f_blob)
313                 blob_decrement_num_opened_fds(fd->f_blob);
314
315         wimfs_dec_num_open_fds();
316
317         /* Release this file descriptor from its inode.  */
318         inode = fd->f_inode;
319         inode->i_fds[fd->f_idx] = NULL;
320         if (fd->f_idx < inode->i_next_fd)
321                 inode->i_next_fd = fd->f_idx;
322         FREE(fd);
323         inode_dec_num_opened_fds(inode);
324         return ret;
325 }
326
327 /*
328  * Translate a path into the corresponding inode in the mounted WIM image.
329  *
330  * See get_dentry() for more information.
331  *
332  * Returns a pointer to the resulting inode, or NULL with errno set.
333  */
334 static struct wim_inode *
335 wim_pathname_to_inode(WIMStruct *wim, const char *path)
336 {
337         struct wim_dentry *dentry;
338
339         dentry = get_dentry(wim, path, WIMLIB_CASE_SENSITIVE);
340         if (!dentry)
341                 return NULL;
342         return dentry->d_inode;
343 }
344
345 /* Can look up named data stream with colon syntax  */
346 #define LOOKUP_FLAG_ADS_OK              0x01
347
348 /* Can look up directory (otherwise get -ENOTDIR)  */
349 #define LOOKUP_FLAG_DIRECTORY_OK        0x02
350
351 /* Get the data stream of the specified name from the specified inode.  Returns
352  * NULL with errno set if not found.  */
353 static struct wim_inode_stream *
354 inode_get_data_stream_tstr(const struct wim_inode *inode,
355                            const char *stream_name)
356 {
357         struct wim_inode_stream *strm;
358
359         if (!stream_name || !*stream_name) {
360                 strm = inode_get_unnamed_stream(inode, STREAM_TYPE_DATA);
361         } else {
362                 const utf16lechar *uname;
363
364                 if (tstr_get_utf16le(stream_name, &uname))
365                         return NULL;
366                 strm = inode_get_stream(inode, STREAM_TYPE_DATA, uname);
367                 tstr_put_utf16le(uname);
368         }
369         if (!strm)
370                 errno = ENOENT;
371         return strm;
372 }
373
374 /*
375  * Translate a path into the corresponding dentry and stream in the mounted WIM
376  * image.
377  *
378  * Returns 0 or a -errno code.  @dentry_ret and @strm_ret are both optional.
379  */
380 static int
381 wim_pathname_to_stream(const struct wimfs_context *ctx,
382                        const char *path,
383                        int lookup_flags,
384                        struct wim_dentry **dentry_ret,
385                        struct wim_inode_stream **strm_ret)
386 {
387         WIMStruct *wim = ctx->wim;
388         struct wim_dentry *dentry;
389         struct wim_inode *inode;
390         struct wim_inode_stream *strm;
391         const char *stream_name = NULL;
392         char *p = NULL;
393
394         lookup_flags |= ctx->default_lookup_flags;
395
396         if (lookup_flags & LOOKUP_FLAG_ADS_OK) {
397                 stream_name = path_stream_name(path);
398                 if (stream_name) {
399                         p = (char *)stream_name - 1;
400                         *p = '\0';
401                 }
402         }
403
404         dentry = get_dentry(wim, path, WIMLIB_CASE_SENSITIVE);
405         if (p)
406                 *p = ':';
407         if (!dentry)
408                 return -errno;
409
410         inode = dentry->d_inode;
411
412         if (inode_resolve_streams(inode, wim->blob_table, false))
413                 return -EIO;
414
415         if (!(lookup_flags & LOOKUP_FLAG_DIRECTORY_OK)
416               && inode_is_directory(inode))
417                 return -EISDIR;
418
419         strm = inode_get_data_stream_tstr(inode, stream_name);
420         if (!strm) {
421                 /* Force creation of an unnamed data stream  */
422                 if (!stream_name)
423                         strm = inode_add_stream(inode, STREAM_TYPE_DATA,
424                                                 NO_STREAM_NAME, NULL);
425                 if (!strm)
426                         return -errno;
427         }
428
429         if (dentry_ret)
430                 *dentry_ret = dentry;
431         if (strm_ret)
432                 *strm_ret = strm;
433         return 0;
434 }
435
436 /*
437  * Create a new file in the mounted WIM image.
438  *
439  * @fuse_ctx
440  *      The FUSE context for the mounted image.
441  * @path
442  *      The path at which to create the first link to the new file.  If a file
443  *      already exists at this path, -EEXIST is returned.
444  * @mode
445  *      The UNIX mode for the new file.  This is only honored if
446  *      WIMLIB_MOUNT_FLAG_UNIX_DATA was passed to wimlib_mount_image().
447  * @rdev
448  *      The device ID for the new file, encoding the major and minor device
449  *      numbers.  This is only honored if WIMLIB_MOUNT_FLAG_UNIX_DATA was passed
450  *      to wimlib_mount_image().
451  * @attributes
452  *      Windows file attributes to use for the new file.
453  * @dentry_ret
454  *      On success, a pointer to the new dentry is returned here.  Its d_inode
455  *      member will point to the new inode that was created for it and added to
456  *      the mounted WIM image.
457  *
458  * Returns 0 or a -errno code.
459  */
460 static int
461 create_file(struct fuse_context *fuse_ctx, const char *path,
462             mode_t mode, dev_t rdev, u32 attributes,
463             struct wim_dentry **dentry_ret)
464 {
465         struct wimfs_context *wimfs_ctx = WIMFS_CTX(fuse_ctx);
466         struct wim_dentry *parent;
467         const char *basename;
468         struct wim_dentry *new_dentry;
469         struct wim_inode *new_inode;
470
471         parent = get_parent_dentry(wimfs_ctx->wim, path, WIMLIB_CASE_SENSITIVE);
472         if (!parent)
473                 return -errno;
474
475         if (!dentry_is_directory(parent))
476                 return -ENOTDIR;
477
478         basename = path_basename(path);
479
480         if (get_dentry_child_with_name(parent, basename, WIMLIB_CASE_SENSITIVE))
481                 return -EEXIST;
482
483         if (new_dentry_with_new_inode(basename, true, &new_dentry))
484                 return -ENOMEM;
485
486         new_inode = new_dentry->d_inode;
487
488         new_inode->i_ino = wimfs_ctx->next_ino++;
489         new_inode->i_attributes = attributes;
490
491         if (wimfs_ctx->mount_flags & WIMLIB_MOUNT_FLAG_UNIX_DATA) {
492                 struct wimlib_unix_data unix_data;
493
494                 unix_data.uid = fuse_ctx->uid;
495                 unix_data.gid = fuse_ctx->gid;
496                 unix_data.mode = fuse_mask_mode(mode, fuse_ctx);
497                 unix_data.rdev = rdev;
498                 if (!inode_set_unix_data(new_inode, &unix_data, UNIX_DATA_ALL))
499                 {
500                         free_dentry(new_dentry);
501                         return -ENOMEM;
502                 }
503         }
504
505         list_add_tail(&new_inode->i_list,
506                       &wim_get_current_image_metadata(wimfs_ctx->wim)->inode_list);
507
508         dentry_add_child(parent, new_dentry);
509
510         *dentry_ret = new_dentry;
511         return 0;
512 }
513
514 /*
515  * Remove a dentry from the mounted WIM image; i.e. remove an alias for an
516  * inode.
517  */
518 static void
519 remove_dentry(struct wim_dentry *dentry, struct blob_table *blob_table)
520 {
521         /* Drop blob references.  */
522         inode_unref_blobs(dentry->d_inode, blob_table);
523
524         /* Unlink the dentry from the image's dentry tree.  */
525         unlink_dentry(dentry);
526
527         /* Delete the dentry.  This will also decrement the link count of the
528          * corresponding inode, and possibly cause it to be deleted as well.  */
529         free_dentry(dentry);
530 }
531
532 /* Generate UNIX filetype mode bits for the specified WIM inode, based on its
533  * Windows file attributes.  */
534 static mode_t
535 inode_unix_file_type(const struct wim_inode *inode)
536 {
537         if (inode_is_symlink(inode))
538                 return S_IFLNK;
539         else if (inode_is_directory(inode))
540                 return S_IFDIR;
541         else
542                 return S_IFREG;
543 }
544
545 /* Generate a default UNIX mode for the specified WIM inode.  */
546 static mode_t
547 inode_default_unix_mode(const struct wim_inode *inode)
548 {
549         return inode_unix_file_type(inode) | 0777;
550 }
551
552 /*
553  * Retrieve standard UNIX metadata ('struct stat') for a WIM inode.
554  *
555  * @blob is the blob descriptor for the stream of the inode that is being
556  * queried, or NULL.  We mostly return the same information for all streams, but
557  * st_size and st_blocks may be different for different streams.
558  *
559  * This always returns 0.
560  */
561 static int
562 inode_to_stbuf(const struct wim_inode *inode,
563                const struct blob_descriptor *blob, struct stat *stbuf)
564 {
565         const struct wimfs_context *ctx = wimfs_get_context();
566         struct wimlib_unix_data unix_data;
567
568         memset(stbuf, 0, sizeof(struct stat));
569         if ((ctx->mount_flags & WIMLIB_MOUNT_FLAG_UNIX_DATA) &&
570             inode_get_unix_data(inode, &unix_data))
571         {
572                 /* Use the user ID, group ID, mode, and device ID from the
573                  * inode's extra UNIX metadata information.  */
574                 stbuf->st_uid = unix_data.uid;
575                 stbuf->st_gid = unix_data.gid;
576                 stbuf->st_mode = unix_data.mode;
577                 stbuf->st_rdev = unix_data.rdev;
578         } else {
579                 /* Generate default values for the user ID, group ID, and mode.
580                  *
581                  * Note: in the case of an allow_other mount, fuse_context.uid
582                  * may not be the same as wimfs_context.owner_uid!  */
583                 stbuf->st_uid = ctx->owner_uid;
584                 stbuf->st_gid = ctx->owner_gid;
585                 stbuf->st_mode = inode_default_unix_mode(inode);
586         }
587         stbuf->st_ino = inode->i_ino;
588         stbuf->st_nlink = inode->i_nlink;
589         if (blob)
590                 stbuf->st_size = blob->size;
591 #ifdef HAVE_STAT_NANOSECOND_PRECISION
592         stbuf->st_atim = wim_timestamp_to_timespec(inode->i_last_access_time);
593         stbuf->st_mtim = wim_timestamp_to_timespec(inode->i_last_write_time);
594         stbuf->st_ctim = stbuf->st_mtim;
595 #else
596         stbuf->st_atime = wim_timestamp_to_time_t(inode->i_last_access_time);
597         stbuf->st_mtime = wim_timestamp_to_time_t(inode->i_last_write_time);
598         stbuf->st_ctime = stbuf->st_mtime;
599 #endif
600         stbuf->st_blocks = DIV_ROUND_UP(stbuf->st_size, 512);
601         return 0;
602 }
603
604 /* Update the last access and last write timestamps of a WIM inode.  */
605 static void
606 touch_inode(struct wim_inode *inode)
607 {
608         u64 now = now_as_wim_timestamp();
609         inode->i_last_access_time = now;
610         inode->i_last_write_time = now;
611 }
612
613 static void
614 touch_parent(struct wim_dentry *dentry)
615 {
616         touch_inode(dentry->d_parent->d_inode);
617 }
618
619 /*
620  * Create a new file in the staging directory for a read-write mounted image.
621  *
622  * On success, returns the file descriptor for the new staging file, opened for
623  * writing.  In addition, stores the allocated name of the staging file in
624  * @name_ret.
625  *
626  * On failure, returns -1 and sets errno.
627  */
628 static int
629 create_staging_file(const struct wimfs_context *ctx, char **name_ret)
630 {
631
632         static const size_t STAGING_FILE_NAME_LEN = 20;
633         char *name;
634         int fd;
635
636         name = MALLOC(STAGING_FILE_NAME_LEN + 1);
637         if (!name)
638                 return -1;
639         name[STAGING_FILE_NAME_LEN] = '\0';
640
641 retry:
642         randomize_char_array_with_alnum(name, STAGING_FILE_NAME_LEN);
643         fd = openat(ctx->staging_dir_fd, name,
644                     O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0600);
645         if (unlikely(fd < 0)) {
646                 if (unlikely(errno == EEXIST))
647                         /* Try again with another name.  */
648                         goto retry;
649                 FREE(name);
650         } else {
651                 *name_ret = name;
652         }
653         return fd;
654 }
655
656 /*
657  * Extract a blob to the staging directory.  This is necessary when a stream
658  * using the blob is being opened for writing and the blob has not already been
659  * extracted to the staging directory.
660  *
661  * @inode
662  *      The inode containing the stream being opened for writing.
663  * @strm
664  *      The stream being opened for writing.  The blob descriptor to which the
665  *      stream refers will be changed by this function.
666  * @size
667  *      Number of bytes of the blob to extract and include in the staging file.
668  *      It may be less than the actual blob length, in which case only a prefix
669  *      of the blob will be extracted.  It may also be more than the actual blob
670  *      length, in which case the extra space will be zero-filled.
671  *
672  * Returns 0 or a -errno code.
673  */
674 static int
675 extract_blob_to_staging_dir(struct wim_inode *inode,
676                             struct wim_inode_stream *strm,
677                             off_t size, const struct wimfs_context *ctx)
678 {
679         struct blob_descriptor *old_blob;
680         struct blob_descriptor *new_blob;
681         char *staging_file_name;
682         int staging_fd;
683         off_t extract_size;
684         int result;
685         int ret;
686
687         old_blob = stream_blob_resolved(strm);
688
689         /* Create the staging file.  */
690         staging_fd = create_staging_file(ctx, &staging_file_name);
691         if (unlikely(staging_fd < 0))
692                 return -errno;
693
694         /* Extract the stream to the staging file (possibly truncated).  */
695         if (old_blob) {
696                 struct filedes fd;
697
698                 filedes_init(&fd, staging_fd);
699                 errno = 0;
700                 extract_size = min(old_blob->size, size);
701                 result = extract_blob_to_fd(old_blob, &fd, extract_size);
702         } else {
703                 extract_size = 0;
704                 result = 0;
705         }
706
707         /* In the case of truncate() to more than the file length, extend the
708          * staging file with zeroes by calling ftruncate().  */
709         if (!result && size > extract_size)
710                 result = ftruncate(staging_fd, size);
711
712         /* Close the staging file.  */
713         if (close(staging_fd))
714                 result = -1;
715
716         /* If an error occurred, unlink the staging file.  */
717         if (unlikely(result)) {
718                 /* extract_blob_to_fd() should set errno, but if it didn't,
719                  * set a default value.  */
720                 ret = errno ? -errno : -EIO;
721                 goto out_delete_staging_file;
722         }
723
724         /* Create a blob descriptor for the staging file.  */
725         new_blob = new_blob_descriptor();
726         if (unlikely(!new_blob)) {
727                 ret = -ENOMEM;
728                 goto out_delete_staging_file;
729         }
730
731         /* There may already be open file descriptors to this stream if it's
732          * previously been opened read-only, but just now we're opening it
733          * read-write.  Identify those file descriptors, update them to use the
734          * new blob descriptor, and open staging file descriptors for them.  */
735         for (u16 i = 0, j = 0; j < inode->i_num_opened_fds; i++) {
736                 struct wimfs_fd *fd;
737                 int raw_fd;
738
739                 fd = inode->i_fds[i];
740                 if (!fd)
741                         continue;
742
743                 j++;
744
745                 if (fd->f_stream_id != strm->stream_id)
746                         continue;
747
748                 /* This is a readonly fd for the same stream.  */
749                 fd->f_blob = new_blob;
750                 new_blob->num_opened_fds++;
751                 raw_fd = openat(ctx->staging_dir_fd, staging_file_name,
752                                 O_RDONLY | O_NOFOLLOW);
753                 if (unlikely(raw_fd < 0)) {
754                         ret = -errno;
755                         goto out_revert_fd_changes;
756                 }
757                 filedes_init(&fd->f_staging_fd, raw_fd);
758         }
759
760         if (old_blob)
761                 old_blob->num_opened_fds -= new_blob->num_opened_fds;
762
763         new_blob->blob_location     = BLOB_IN_STAGING_FILE;
764         new_blob->staging_file_name = staging_file_name;
765         new_blob->staging_dir_fd    = ctx->staging_dir_fd;
766         new_blob->size              = size;
767
768         prepare_unhashed_blob(new_blob, inode, strm->stream_id,
769                               &wim_get_current_image_metadata(ctx->wim)->unhashed_blobs);
770         inode_replace_stream_blob(inode, strm, new_blob, ctx->wim->blob_table);
771         return 0;
772
773 out_revert_fd_changes:
774         for (u16 i = 0; new_blob->num_opened_fds; i++) {
775                 struct wimfs_fd *fd = inode->i_fds[i];
776                 if (fd && fd->f_stream_id == strm->stream_id) {
777                         fd->f_blob = old_blob;
778                         if (filedes_valid(&fd->f_staging_fd)) {
779                                 filedes_close(&fd->f_staging_fd);
780                                 filedes_invalidate(&fd->f_staging_fd);
781                         }
782                         new_blob->num_opened_fds--;
783                 }
784         }
785         free_blob_descriptor(new_blob);
786 out_delete_staging_file:
787         unlinkat(ctx->staging_dir_fd, staging_file_name, 0);
788         FREE(staging_file_name);
789         return ret;
790 }
791
792 /*
793  * Create the staging directory for the WIM file.
794  *
795  * The staging directory will be created in the directory specified by the open
796  * file descriptor @parent_dir_fd.  It will be given a randomly generated name
797  * based on @wim_basename, the name of the WIM file.
798  *
799  * On success, returns a file descriptor to the open staging directory with
800  * O_RDONLY access.  In addition, stores the allocated name of the staging
801  * directory (relative to @parent_dir_fd) in @staging_dir_name_ret.
802  * On failure, returns -1 and sets errno.
803  */
804 static int
805 make_staging_dir_at(int parent_dir_fd, const char *wim_basename,
806                     char **staging_dir_name_ret)
807 {
808         static const char common_suffix[8] = ".staging";
809         static const size_t random_suffix_len = 10;
810         size_t wim_basename_len;
811         size_t staging_dir_name_len;
812         char *staging_dir_name;
813         char *p;
814         int fd;
815
816         wim_basename_len = strlen(wim_basename);
817         staging_dir_name_len = wim_basename_len + sizeof(common_suffix) +
818                                random_suffix_len;
819         staging_dir_name = MALLOC(staging_dir_name_len + 1);
820         if (!staging_dir_name)
821                 return -1;
822
823         p = staging_dir_name;
824         p = mempcpy(p, wim_basename, wim_basename_len);
825         p = mempcpy(p, common_suffix, sizeof(common_suffix));
826         randomize_char_array_with_alnum(p, random_suffix_len);
827         p += random_suffix_len;
828         *p = '\0';
829
830         if (mkdirat(parent_dir_fd, staging_dir_name, 0700))
831                 goto err1;
832
833         fd = openat(parent_dir_fd, staging_dir_name,
834                     O_RDONLY | O_DIRECTORY | O_NOFOLLOW);
835         if (fd < 0)
836                 goto err2;
837
838         *staging_dir_name_ret = staging_dir_name;
839         return fd;
840
841 err2:
842         unlinkat(parent_dir_fd, staging_dir_name, AT_REMOVEDIR);
843 err1:
844         FREE(staging_dir_name);
845         return -1;
846 }
847
848 /*
849  * Create the staging directory and set ctx->staging_dir_fd,
850  * ctx->staging_dir_name, and ctx->parent_dir_fd.
851  */
852 static int
853 make_staging_dir(struct wimfs_context *ctx, const char *parent_dir_path)
854 {
855         const char *wim_basename;
856         char *end = NULL;
857         int ret;
858
859         wim_basename = path_basename(ctx->wim->filename);
860
861         if (!parent_dir_path) {
862                 /* The user did not specify a directory.  Default to creating
863                  * the staging directory alongside the WIM file.  */
864                 if (wim_basename > ctx->wim->filename) {
865                         parent_dir_path = ctx->wim->filename;
866                         end = (char *)(wim_basename - 1);
867                         /* *end must be a slash.  Temporarily overwrite it so we
868                          * can open the parent directory.  */
869                         *end = '\0';
870                 } else {
871                         parent_dir_path = ".";
872                 }
873         }
874
875         /* Open the parent directory (in which we'll create our staging
876          * directory).  */
877         ctx->parent_dir_fd = open(parent_dir_path, O_RDONLY | O_DIRECTORY);
878         if (ctx->parent_dir_fd < 0) {
879                 ERROR_WITH_ERRNO("Can't open directory \"%s\"",
880                                  parent_dir_path);
881                 ret = WIMLIB_ERR_OPENDIR;
882                 goto out_restore_wim_filename;
883         }
884
885         ctx->staging_dir_fd = make_staging_dir_at(ctx->parent_dir_fd,
886                                                   wim_basename,
887                                                   &ctx->staging_dir_name);
888         if (ctx->staging_dir_fd < 0) {
889                 ERROR_WITH_ERRNO("Can't create staging directory in \"%s\"",
890                                  parent_dir_path);
891                 close(ctx->parent_dir_fd);
892                 ret = WIMLIB_ERR_MKDIR;
893                 goto out_restore_wim_filename;
894         }
895         ret = 0;
896 out_restore_wim_filename:
897         if (end)
898                 *end = '/';
899         return ret;
900 }
901
902 /* Deletes the staging directory, undoing the effects of a successful call to
903  * make_staging_dir().  */
904 static void
905 delete_staging_dir(struct wimfs_context *ctx)
906 {
907         DIR *dir;
908         struct dirent *ent;
909
910         dir = fdopendir(ctx->staging_dir_fd);
911         if (dir) {
912                 while ((ent = readdir(dir)))
913                         unlinkat(ctx->staging_dir_fd, ent->d_name, 0);
914                 closedir(dir);
915         } else {
916                 close(ctx->staging_dir_fd);
917         }
918         if (unlinkat(ctx->parent_dir_fd, ctx->staging_dir_name, AT_REMOVEDIR))
919                 WARNING_WITH_ERRNO("Could not delete staging directory");
920         FREE(ctx->staging_dir_name);
921         close(ctx->parent_dir_fd);
922 }
923
924 /* Number the inodes in the mounted image sequentially.  */
925 static void
926 reassign_inode_numbers(struct wimfs_context *ctx)
927 {
928         struct wim_image_metadata *imd;
929         struct wim_inode *inode;
930
931         ctx->next_ino = 1;
932         imd = wim_get_current_image_metadata(ctx->wim);
933         image_for_each_inode(inode, imd)
934                 inode->i_ino = ctx->next_ino++;
935 }
936
937 static void
938 release_extra_refcnts(struct wimfs_context *ctx)
939 {
940         struct list_head *list = &ctx->orig_blob_list;
941         struct blob_table *blob_table = ctx->wim->blob_table;
942         struct blob_descriptor *blob, *tmp;
943
944         list_for_each_entry_safe(blob, tmp, list, orig_blob_list)
945                 blob_subtract_refcnt(blob, blob_table, blob->out_refcnt);
946 }
947
948 /* Delete the 'struct blob_descriptor' for any stream that was modified
949  * or created in the read-write mounted image and had a final size of 0.  */
950 static void
951 delete_empty_blobs(struct wimfs_context *ctx)
952 {
953         struct blob_descriptor *blob, *tmp;
954         struct wim_image_metadata *imd;
955
956         imd = wim_get_current_image_metadata(ctx->wim);
957
958         image_for_each_unhashed_blob_safe(blob, tmp, imd) {
959                 if (!blob->size) {
960                         *retrieve_pointer_to_unhashed_blob(blob) = NULL;
961                         list_del(&blob->unhashed_list);
962                         free_blob_descriptor(blob);
963                 }
964         }
965 }
966
967 /* Close all file descriptors open to the specified inode.
968  *
969  * Note: closing the last file descriptor might free the inode.  */
970 static void
971 inode_close_fds(struct wim_inode *inode)
972 {
973         u16 num_open_fds = inode->i_num_opened_fds;
974         for (u16 i = 0; num_open_fds; i++) {
975                 if (inode->i_fds[i]) {
976                         close_wimfs_fd(inode->i_fds[i]);
977                         num_open_fds--;
978                 }
979         }
980 }
981
982 /* Close all file descriptors open to the mounted image.  */
983 static void
984 close_all_fds(struct wimfs_context *ctx)
985 {
986         struct wim_inode *inode, *tmp;
987         struct wim_image_metadata *imd;
988
989         imd = wim_get_current_image_metadata(ctx->wim);
990
991         list_for_each_entry_safe(inode, tmp, &imd->inode_list, i_list)
992                 inode_close_fds(inode);
993 }
994
995 /* Moves the currently selected image, which may have been modified, to a new
996  * index, and sets the original index to refer to a reset (unmodified) copy of
997  * the image.  */
998 static int
999 renew_current_image(struct wimfs_context *ctx)
1000 {
1001         WIMStruct *wim = ctx->wim;
1002         int idx = wim->current_image - 1;
1003         struct wim_image_metadata *imd = wim->image_metadata[idx];
1004         struct wim_image_metadata *replace_imd;
1005         struct blob_descriptor *new_blob;
1006         int ret;
1007
1008         /* Create 'replace_imd' structure to use for the reset original,
1009          * unmodified image.  */
1010         ret = WIMLIB_ERR_NOMEM;
1011         replace_imd = new_image_metadata();
1012         if (!replace_imd)
1013                 goto err;
1014
1015         /* Create new blob descriptor for the modified image's metadata
1016          * resource, which doesn't exist yet.  */
1017         ret = WIMLIB_ERR_NOMEM;
1018         new_blob = new_blob_descriptor();
1019         if (!new_blob)
1020                 goto err_put_replace_imd;
1021         new_blob->refcnt = 1;
1022         new_blob->flags = WIM_RESHDR_FLAG_METADATA;
1023         new_blob->unhashed = 1;
1024
1025         /* Make the image being moved available at a new index.  Increments the
1026          * WIM's image count, but does not increment the reference count of the
1027          * 'struct image_metadata'.  */
1028         ret = append_image_metadata(wim, imd);
1029         if (ret)
1030                 goto err_free_new_blob;
1031
1032         ret = xml_add_image(wim, "");
1033         if (ret)
1034                 goto err_undo_append;
1035
1036         replace_imd->metadata_blob = imd->metadata_blob;
1037         imd->metadata_blob = new_blob;
1038         wim->image_metadata[idx] = replace_imd;
1039         wim->current_image = wim->hdr.image_count;
1040         return 0;
1041
1042 err_undo_append:
1043         wim->hdr.image_count--;
1044 err_free_new_blob:
1045         free_blob_descriptor(new_blob);
1046 err_put_replace_imd:
1047         put_image_metadata(replace_imd, NULL);
1048 err:
1049         return ret;
1050 }
1051
1052 static enum wimlib_progress_status
1053 commit_progress_func(enum wimlib_progress_msg msg,
1054                      union wimlib_progress_info *info, void *progctx)
1055 {
1056         mqd_t mq = *(mqd_t *)progctx;
1057         struct commit_progress_report report;
1058
1059         memset(&report, 0, sizeof(report));
1060         report.msg = msg;
1061         if (info)
1062                 report.info = *info;
1063         mq_send(mq, (const char *)&report, sizeof(report), 1);
1064         return WIMLIB_PROGRESS_STATUS_CONTINUE;
1065 }
1066
1067 /* Commit the mounted image to the underlying WIM file.  */
1068 static int
1069 commit_image(struct wimfs_context *ctx, int unmount_flags, mqd_t mq)
1070 {
1071         int write_flags;
1072
1073         if (unmount_flags & WIMLIB_UNMOUNT_FLAG_SEND_PROGRESS)
1074                 wimlib_register_progress_function(ctx->wim,
1075                                                   commit_progress_func, &mq);
1076         else
1077                 wimlib_register_progress_function(ctx->wim, NULL, NULL);
1078
1079         if (unmount_flags & WIMLIB_UNMOUNT_FLAG_NEW_IMAGE) {
1080                 int ret = renew_current_image(ctx);
1081                 if (ret)
1082                         return ret;
1083         } else {
1084                 release_extra_refcnts(ctx);
1085         }
1086         INIT_LIST_HEAD(&ctx->orig_blob_list);
1087         delete_empty_blobs(ctx);
1088         xml_update_image_info(ctx->wim, ctx->wim->current_image);
1089
1090         write_flags = 0;
1091
1092         if (unmount_flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY)
1093                 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1094
1095         if (unmount_flags & WIMLIB_UNMOUNT_FLAG_REBUILD)
1096                 write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1097
1098         if (unmount_flags & WIMLIB_UNMOUNT_FLAG_RECOMPRESS)
1099                 write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
1100
1101         return wimlib_overwrite(ctx->wim, write_flags, 0);
1102 }
1103
1104 /* In the case of an allow_other mount, only the mount owner and root are
1105  * allowed to unmount the filesystem.  */
1106 static bool
1107 may_unmount_wimfs(void)
1108 {
1109         const struct fuse_context *fuse_ctx = fuse_get_context();
1110         const struct wimfs_context *wimfs_ctx = WIMFS_CTX(fuse_ctx);
1111
1112         return (fuse_ctx->uid == wimfs_ctx->owner_uid ||
1113                 fuse_ctx->uid == 0);
1114 }
1115
1116 /* Unmount the mounted image, called from the daemon process.  */
1117 static int
1118 unmount_wimfs(void)
1119 {
1120         struct fuse_context *fuse_ctx = fuse_get_context();
1121         struct wimfs_context *wimfs_ctx = WIMFS_CTX(fuse_ctx);
1122         const struct wimfs_unmount_info *info = &wimfs_ctx->unmount_info;
1123         int unmount_flags = info->unmount_flags;
1124         mqd_t mq = (mqd_t)-1;
1125         int ret;
1126
1127         /* Ignore COMMIT if the image is mounted read-only.  */
1128         if (!(wimfs_ctx->mount_flags & WIMLIB_MOUNT_FLAG_READWRITE))
1129                 unmount_flags &= ~WIMLIB_UNMOUNT_FLAG_COMMIT;
1130
1131         if (unmount_flags & WIMLIB_UNMOUNT_FLAG_SEND_PROGRESS) {
1132                 mq = mq_open(info->mq_name, O_WRONLY | O_NONBLOCK);
1133                 if (mq == (mqd_t)-1) {
1134                         ret = WIMLIB_ERR_MQUEUE;
1135                         goto out;
1136                 }
1137         }
1138
1139         if (wimfs_ctx->num_open_fds) {
1140
1141                 /* There are still open file descriptors to the image.  */
1142
1143                 /* With COMMIT, refuse to unmount unless FORCE is also
1144                  * specified.  */
1145                 if ((unmount_flags & (WIMLIB_UNMOUNT_FLAG_COMMIT |
1146                                       WIMLIB_UNMOUNT_FLAG_FORCE))
1147                                  == WIMLIB_UNMOUNT_FLAG_COMMIT)
1148                 {
1149                         ret = WIMLIB_ERR_MOUNTED_IMAGE_IS_BUSY;
1150                         goto out;
1151                 }
1152
1153                 /* Force-close all file descriptors.  */
1154                 close_all_fds(wimfs_ctx);
1155         }
1156
1157         if (unmount_flags & WIMLIB_UNMOUNT_FLAG_COMMIT)
1158                 ret = commit_image(wimfs_ctx, unmount_flags, mq);
1159         else
1160                 ret = 0;  /* Read-only mount, or discarding changes to
1161                              a read-write mount  */
1162
1163 out:
1164         /* Leave the image mounted if commit failed, unless this is a
1165          * forced unmount.  The user can retry without COMMIT if they
1166          * want.  */
1167         if (!ret || (unmount_flags & WIMLIB_UNMOUNT_FLAG_FORCE)) {
1168                 unlock_wim_for_append(wimfs_ctx->wim);
1169                 fuse_exit(fuse_ctx->fuse);
1170         }
1171         if (mq != (mqd_t)-1)
1172                 mq_close(mq);
1173         return ret;
1174 }
1175
1176 static int
1177 wimfs_chmod(const char *path, mode_t mask)
1178 {
1179         const struct wimfs_context *ctx = wimfs_get_context();
1180         struct wim_inode *inode;
1181         struct wimlib_unix_data unix_data;
1182
1183         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_UNIX_DATA))
1184                 return -EOPNOTSUPP;
1185
1186         inode = wim_pathname_to_inode(ctx->wim, path);
1187         if (!inode)
1188                 return -errno;
1189
1190         unix_data.uid = ctx->owner_uid;
1191         unix_data.gid = ctx->owner_gid;
1192         unix_data.mode = mask;
1193         unix_data.rdev = 0;
1194
1195         if (!inode_set_unix_data(inode, &unix_data, UNIX_DATA_MODE))
1196                 return -ENOMEM;
1197
1198         return 0;
1199 }
1200
1201 static int
1202 wimfs_chown(const char *path, uid_t uid, gid_t gid)
1203 {
1204         const struct wimfs_context *ctx = wimfs_get_context();
1205         struct wim_inode *inode;
1206         struct wimlib_unix_data unix_data;
1207         int which;
1208
1209         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_UNIX_DATA))
1210                 return -EOPNOTSUPP;
1211
1212         inode = wim_pathname_to_inode(ctx->wim, path);
1213         if (!inode)
1214                 return -errno;
1215
1216         which = 0;
1217
1218         if (uid != (uid_t)-1)
1219                 which |= UNIX_DATA_UID;
1220         else
1221                 uid = ctx->owner_uid;
1222
1223         if (gid != (gid_t)-1)
1224                 which |= UNIX_DATA_GID;
1225         else
1226                 gid = ctx->owner_gid;
1227
1228         unix_data.uid = uid;
1229         unix_data.gid = gid;
1230         unix_data.mode = inode_default_unix_mode(inode);
1231         unix_data.rdev = 0;
1232
1233         if (!inode_set_unix_data(inode, &unix_data, which))
1234                 return -ENOMEM;
1235
1236         return 0;
1237 }
1238
1239 static int
1240 wimfs_fgetattr(const char *path, struct stat *stbuf, struct fuse_file_info *fi)
1241 {
1242         struct wimfs_fd *fd = WIMFS_FD(fi);
1243         return inode_to_stbuf(fd->f_inode, fd->f_blob, stbuf);
1244 }
1245
1246 static int
1247 wimfs_ftruncate(const char *path, off_t size, struct fuse_file_info *fi)
1248 {
1249         struct wimfs_fd *fd = WIMFS_FD(fi);
1250         if (ftruncate(fd->f_staging_fd.fd, size))
1251                 return -errno;
1252         touch_inode(fd->f_inode);
1253         fd->f_blob->size = size;
1254         return 0;
1255 }
1256
1257 static int
1258 wimfs_getattr(const char *path, struct stat *stbuf)
1259 {
1260         const struct wimfs_context *ctx = wimfs_get_context();
1261         struct wim_dentry *dentry;
1262         struct wim_inode_stream *strm;
1263         int ret;
1264
1265         ret = wim_pathname_to_stream(ctx, path, LOOKUP_FLAG_DIRECTORY_OK,
1266                                      &dentry, &strm);
1267         if (ret)
1268                 return ret;
1269
1270         return inode_to_stbuf(dentry->d_inode,
1271                               stream_blob_resolved(strm), stbuf);
1272 }
1273
1274 static int
1275 copy_xattr(char *dest, size_t destsize, const void *src, size_t srcsize)
1276 {
1277         if (destsize) {
1278                 if (destsize < srcsize)
1279                         return -ERANGE;
1280                 memcpy(dest, src, srcsize);
1281         }
1282         return srcsize;
1283 }
1284
1285 static int
1286 wimfs_getxattr(const char *path, const char *name, char *value,
1287                size_t size)
1288 {
1289         const struct wimfs_context *ctx = wimfs_get_context();
1290         struct wim_inode *inode;
1291         struct wim_inode_stream *strm;
1292         struct blob_descriptor *blob;
1293
1294         if (!strncmp(name, "wimfs.", 6)) {
1295                 /* Handle some magical extended attributes.  These really should
1296                  * be ioctls, but directory ioctls aren't supported until
1297                  * libfuse 2.9, and even then they are broken.  */
1298                 name += 6;
1299                 if (!strcmp(name, "wim_filename")) {
1300                         return copy_xattr(value, size, ctx->wim->filename,
1301                                           strlen(ctx->wim->filename));
1302                 }
1303                 if (!strcmp(name, "wim_info")) {
1304                         struct wimlib_wim_info info;
1305
1306                         wimlib_get_wim_info(ctx->wim, &info);
1307
1308                         return copy_xattr(value, size, &info, sizeof(info));
1309                 }
1310                 if (!strcmp(name, "mounted_image")) {
1311                         return copy_xattr(value, size,
1312                                           &ctx->wim->current_image, sizeof(int));
1313                 }
1314                 if (!strcmp(name, "mount_flags")) {
1315                         return copy_xattr(value, size,
1316                                           &ctx->mount_flags, sizeof(int));
1317                 }
1318                 if (!strcmp(name, "unmount")) {
1319                         if (!may_unmount_wimfs())
1320                                 return -EPERM;
1321                         if (size) {
1322                                 int status;
1323
1324                                 if (size < sizeof(int))
1325                                         return -ERANGE;
1326                                 status = unmount_wimfs();
1327                                 memcpy(value, &status, sizeof(int));
1328                         }
1329                         return sizeof(int);
1330                 }
1331                 return -ENOATTR;
1332         }
1333
1334         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1335                 return -ENOTSUP;
1336
1337         if (strncmp(name, "user.", 5))
1338                 return -ENOATTR;
1339         name += 5;
1340
1341         if (!*name)
1342                 return -ENOATTR;
1343
1344         /* Querying a named data stream  */
1345
1346         inode = wim_pathname_to_inode(ctx->wim, path);
1347         if (!inode)
1348                 return -errno;
1349
1350         strm = inode_get_data_stream_tstr(inode, name);
1351         if (!strm)
1352                 return (errno == ENOENT) ? -ENOATTR : -errno;
1353
1354         blob = stream_blob_resolved(strm);
1355         if (!blob)
1356                 return 0;
1357
1358         if (unlikely(blob->size > INT_MAX))
1359                 return -EFBIG;
1360
1361         if (size) {
1362                 if (size < blob->size)
1363                         return -ERANGE;
1364
1365                 if (read_full_blob_into_buf(blob, value))
1366                         return errno ? -errno : -EIO;
1367         }
1368         return blob->size;
1369 }
1370
1371 static int
1372 wimfs_link(const char *existing_path, const char *new_path)
1373 {
1374         WIMStruct *wim = wimfs_get_WIMStruct();
1375         const char *new_name;
1376         struct wim_inode *inode;
1377         struct wim_dentry *dir;
1378         struct wim_dentry *new_alias;
1379
1380         inode = wim_pathname_to_inode(wim, existing_path);
1381         if (!inode)
1382                 return -errno;
1383
1384         if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1385                                    FILE_ATTRIBUTE_REPARSE_POINT))
1386                 return -EPERM;
1387
1388         new_name = path_basename(new_path);
1389
1390         dir = get_parent_dentry(wim, new_path, WIMLIB_CASE_SENSITIVE);
1391         if (!dir)
1392                 return -errno;
1393
1394         if (!dentry_is_directory(dir))
1395                 return -ENOTDIR;
1396
1397         if (get_dentry_child_with_name(dir, new_name, WIMLIB_CASE_SENSITIVE))
1398                 return -EEXIST;
1399
1400         if (new_dentry_with_existing_inode(new_name, inode, &new_alias))
1401                 return -ENOMEM;
1402
1403         dentry_add_child(dir, new_alias);
1404         touch_inode(dir->d_inode);
1405         return 0;
1406 }
1407
1408 static int
1409 wimfs_listxattr(const char *path, char *list, size_t size)
1410 {
1411         const struct wimfs_context *ctx = wimfs_get_context();
1412         const struct wim_inode *inode;
1413         char *p = list;
1414         char *end = list + size;
1415         int total_size = 0;
1416
1417         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1418                 return -ENOTSUP;
1419
1420         /* List named data streams, or get the list size.  We report each named
1421          * data stream "X" as an extended attribute "user.X".  */
1422
1423         inode = wim_pathname_to_inode(ctx->wim, path);
1424         if (!inode)
1425                 return -errno;
1426
1427         for (unsigned i = 0; i < inode->i_num_streams; i++) {
1428                 const struct wim_inode_stream *strm;
1429                 char *stream_name_mbs;
1430                 size_t stream_name_mbs_nbytes;
1431
1432                 strm = &inode->i_streams[i];
1433
1434                 if (!stream_is_named_data_stream(strm))
1435                         continue;
1436
1437                 if (utf16le_to_tstr(strm->stream_name,
1438                                     utf16le_len_bytes(strm->stream_name),
1439                                     &stream_name_mbs,
1440                                     &stream_name_mbs_nbytes))
1441                         return -errno;
1442
1443                 if (unlikely(INT_MAX - total_size < stream_name_mbs_nbytes + 6)) {
1444                         FREE(stream_name_mbs);
1445                         return -EFBIG;
1446                 }
1447
1448                 total_size += stream_name_mbs_nbytes + 6;
1449                 if (size) {
1450                         if (end - p < stream_name_mbs_nbytes + 6) {
1451                                 FREE(stream_name_mbs);
1452                                 return -ERANGE;
1453                         }
1454                         p = mempcpy(p, "user.", 5);
1455                         p = mempcpy(p, stream_name_mbs, stream_name_mbs_nbytes);
1456                         *p++ = '\0';
1457                 }
1458                 FREE(stream_name_mbs);
1459         }
1460         return total_size;
1461 }
1462
1463 static int
1464 wimfs_mkdir(const char *path, mode_t mode)
1465 {
1466         struct wim_dentry *dentry;
1467         int ret;
1468
1469         /* Note: according to fuse.h, mode may not include S_IFDIR  */
1470         ret = create_file(fuse_get_context(), path, mode | S_IFDIR, 0,
1471                           FILE_ATTRIBUTE_DIRECTORY, &dentry);
1472         if (ret)
1473                 return ret;
1474         touch_parent(dentry);
1475         return 0;
1476 }
1477
1478 static int
1479 wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
1480 {
1481         struct fuse_context *fuse_ctx = fuse_get_context();
1482         struct wimfs_context *wimfs_ctx = WIMFS_CTX(fuse_ctx);
1483         const char *stream_name;
1484
1485         if ((wimfs_ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
1486              && (stream_name = path_stream_name(path)))
1487         {
1488                 struct wim_inode *inode;
1489                 struct wim_inode_stream *existing_strm;
1490                 struct wim_inode_stream *new_strm;
1491                 char *p;
1492                 const utf16lechar *uname;
1493
1494                 /* Create a named data stream.  */
1495
1496                 if (!S_ISREG(mode))
1497                         return -EOPNOTSUPP;
1498
1499                 p = (char *)stream_name - 1;
1500
1501                 *p = '\0';
1502                 inode = wim_pathname_to_inode(wimfs_ctx->wim, path);
1503                 *p = ':';
1504                 if (!inode)
1505                         return -errno;
1506
1507                 if (tstr_get_utf16le(stream_name, &uname))
1508                         return -errno;
1509
1510                 existing_strm = inode_get_stream(inode, STREAM_TYPE_DATA, uname);
1511                 if (existing_strm) {
1512                         tstr_put_utf16le(uname);
1513                         return -EEXIST;
1514                 }
1515
1516                 new_strm = inode_add_stream(inode, STREAM_TYPE_DATA, uname, NULL);
1517
1518                 tstr_put_utf16le(uname);
1519
1520                 if (!new_strm)
1521                         return -errno;
1522                 return 0;
1523         } else {
1524                 /* Create a regular file, device node, named pipe, or socket.
1525                  */
1526                 struct wim_dentry *dentry;
1527                 int ret;
1528
1529                 if (!S_ISREG(mode) &&
1530                     !(wimfs_ctx->mount_flags & WIMLIB_MOUNT_FLAG_UNIX_DATA))
1531                         return -EPERM;
1532
1533                 /* Note: we still use FILE_ATTRIBUTE_NORMAL for device nodes,
1534                  * named pipes, and sockets.  The real mode is in the UNIX
1535                  * metadata.  */
1536                 ret = create_file(fuse_ctx, path, mode, rdev,
1537                                   FILE_ATTRIBUTE_NORMAL, &dentry);
1538                 if (ret)
1539                         return ret;
1540                 touch_parent(dentry);
1541                 return 0;
1542         }
1543 }
1544
1545 static int
1546 wimfs_open(const char *path, struct fuse_file_info *fi)
1547 {
1548         struct wimfs_context *ctx = wimfs_get_context();
1549         struct wim_dentry *dentry;
1550         struct wim_inode *inode;
1551         struct wim_inode_stream *strm;
1552         struct blob_descriptor *blob;
1553         struct wimfs_fd *fd;
1554         int ret;
1555
1556         ret = wim_pathname_to_stream(ctx, path, 0, &dentry, &strm);
1557         if (ret)
1558                 return ret;
1559
1560         inode = dentry->d_inode;
1561         blob = stream_blob_resolved(strm);
1562
1563         /* The data of the file being opened may be in the staging directory
1564          * (read-write mounts only) or in the WIM.  If it's in the staging
1565          * directory, we need to open a native file descriptor for the
1566          * corresponding file.  Otherwise, we can read the file data directly
1567          * from the WIM file if we are opening it read-only, but we need to
1568          * extract the data to the staging directory if we are opening it
1569          * writable.  */
1570
1571         if (flags_writable(fi->flags) &&
1572             (!blob || blob->blob_location != BLOB_IN_STAGING_FILE)) {
1573                 ret = extract_blob_to_staging_dir(inode,
1574                                                   strm,
1575                                                   blob ? blob->size : 0,
1576                                                   ctx);
1577                 if (ret)
1578                         return ret;
1579                 blob = stream_blob_resolved(strm);
1580         }
1581
1582         ret = alloc_wimfs_fd(inode, strm, &fd);
1583         if (ret)
1584                 return ret;
1585
1586         if (blob && blob->blob_location == BLOB_IN_STAGING_FILE) {
1587                 int raw_fd;
1588
1589                 raw_fd = openat(blob->staging_dir_fd, blob->staging_file_name,
1590                                 (fi->flags & O_ACCMODE) | O_NOFOLLOW);
1591                 if (raw_fd < 0) {
1592                         close_wimfs_fd(fd);
1593                         return -errno;
1594                 }
1595                 filedes_init(&fd->f_staging_fd, raw_fd);
1596         }
1597         fi->fh = (uintptr_t)fd;
1598         return 0;
1599 }
1600
1601 static int
1602 wimfs_opendir(const char *path, struct fuse_file_info *fi)
1603 {
1604         WIMStruct *wim = wimfs_get_WIMStruct();
1605         struct wim_inode *inode;
1606         struct wim_inode_stream *strm;
1607         struct wimfs_fd *fd;
1608         int ret;
1609
1610         inode = wim_pathname_to_inode(wim, path);
1611         if (!inode)
1612                 return -errno;
1613         if (!inode_is_directory(inode))
1614                 return -ENOTDIR;
1615         strm = inode_get_unnamed_stream(inode, STREAM_TYPE_DATA);
1616         if (!strm)
1617                 return -ENOTDIR;
1618         ret = alloc_wimfs_fd(inode, strm, &fd);
1619         if (ret)
1620                 return ret;
1621         fi->fh = (uintptr_t)fd;
1622         return 0;
1623 }
1624
1625 static int
1626 wimfs_read(const char *path, char *buf, size_t size,
1627            off_t offset, struct fuse_file_info *fi)
1628 {
1629         struct wimfs_fd *fd = WIMFS_FD(fi);
1630         const struct blob_descriptor *blob;
1631         ssize_t ret;
1632
1633         blob = fd->f_blob;
1634         if (!blob)
1635                 return 0;
1636
1637         if (offset >= blob->size)
1638                 return 0;
1639
1640         if (size > blob->size - offset)
1641                 size = blob->size - offset;
1642
1643         if (!size)
1644                 return 0;
1645
1646         switch (blob->blob_location) {
1647         case BLOB_IN_WIM:
1648                 if (read_partial_wim_blob_into_buf(blob, size, offset, buf))
1649                         ret = errno ? -errno : -EIO;
1650                 else
1651                         ret = size;
1652                 break;
1653         case BLOB_IN_STAGING_FILE:
1654                 ret = raw_pread(&fd->f_staging_fd, buf, size, offset);
1655                 if (ret < 0)
1656                         ret = -errno;
1657                 break;
1658         case BLOB_IN_ATTACHED_BUFFER:
1659                 memcpy(buf, blob->attached_buffer + offset, size);
1660                 ret = size;
1661                 break;
1662         default:
1663                 ret = -EINVAL;
1664                 break;
1665         }
1666         return ret;
1667 }
1668
1669 static int
1670 wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
1671               off_t offset, struct fuse_file_info *fi)
1672 {
1673         struct wimfs_fd *fd = WIMFS_FD(fi);
1674         const struct wim_inode *inode;
1675         const struct wim_dentry *child;
1676         int ret;
1677
1678         inode = fd->f_inode;
1679
1680         ret = filler(buf, ".", NULL, 0);
1681         if (ret)
1682                 return ret;
1683         ret = filler(buf, "..", NULL, 0);
1684         if (ret)
1685                 return ret;
1686
1687         for_inode_child(child, inode) {
1688                 char *file_name_mbs;
1689                 size_t file_name_mbs_nbytes;
1690
1691                 ret = utf16le_to_tstr(child->file_name,
1692                                       child->file_name_nbytes,
1693                                       &file_name_mbs,
1694                                       &file_name_mbs_nbytes);
1695                 if (ret)
1696                         return -errno;
1697
1698                 ret = filler(buf, file_name_mbs, NULL, 0);
1699                 FREE(file_name_mbs);
1700                 if (ret)
1701                         return ret;
1702         }
1703         return 0;
1704 }
1705
1706 static int
1707 wimfs_readlink(const char *path, char *buf, size_t buf_len)
1708 {
1709         WIMStruct *wim = wimfs_get_WIMStruct();
1710         const struct wim_inode *inode;
1711         ssize_t ret;
1712
1713         inode = wim_pathname_to_inode(wim, path);
1714         if (!inode)
1715                 return -errno;
1716         if (!inode_is_symlink(inode))
1717                 return -EINVAL;
1718         if (buf_len == 0)
1719                 return -EINVAL;
1720         ret = wim_inode_readlink(inode, buf, buf_len - 1, NULL);
1721         if (ret >= 0) {
1722                 buf[ret] = '\0';
1723                 ret = 0;
1724         } else if (ret == -ENAMETOOLONG) {
1725                 buf[buf_len - 1] = '\0';
1726         }
1727         return ret;
1728 }
1729
1730 /* We use this for both release() and releasedir(), since in both cases we
1731  * simply need to close the file descriptor.  */
1732 static int
1733 wimfs_release(const char *path, struct fuse_file_info *fi)
1734 {
1735         return close_wimfs_fd(WIMFS_FD(fi));
1736 }
1737
1738 static int
1739 wimfs_removexattr(const char *path, const char *name)
1740 {
1741         struct wimfs_context *ctx = wimfs_get_context();
1742         struct wim_inode *inode;
1743         struct wim_inode_stream *strm;
1744
1745         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1746                 return -ENOTSUP;
1747
1748         if (strncmp(name, "user.", 5))
1749                 return -ENOATTR;
1750         name += 5;
1751
1752         if (!*name)
1753                 return -ENOATTR;
1754
1755         /* Removing a named data stream.  */
1756
1757         inode = wim_pathname_to_inode(ctx->wim, path);
1758         if (!inode)
1759                 return -errno;
1760
1761         strm = inode_get_data_stream_tstr(inode, name);
1762         if (!strm)
1763                 return (errno == ENOENT) ? -ENOATTR : -errno;
1764
1765         inode_remove_stream(inode, strm, ctx->wim->blob_table);
1766         return 0;
1767 }
1768
1769 static int
1770 wimfs_rename(const char *from, const char *to)
1771 {
1772         return rename_wim_path(wimfs_get_WIMStruct(), from, to,
1773                                WIMLIB_CASE_SENSITIVE, NULL);
1774 }
1775
1776 static int
1777 wimfs_rmdir(const char *path)
1778 {
1779         WIMStruct *wim = wimfs_get_WIMStruct();
1780         struct wim_dentry *dentry;
1781
1782         dentry = get_dentry(wim, path, WIMLIB_CASE_SENSITIVE);
1783         if (!dentry)
1784                 return -errno;
1785
1786         if (!dentry_is_directory(dentry))
1787                 return -ENOTDIR;
1788
1789         if (dentry_has_children(dentry))
1790                 return -ENOTEMPTY;
1791
1792         touch_parent(dentry);
1793         remove_dentry(dentry, wim->blob_table);
1794         return 0;
1795 }
1796
1797 static int
1798 wimfs_setxattr(const char *path, const char *name,
1799                const char *value, size_t size, int flags)
1800 {
1801         struct wimfs_context *ctx = wimfs_get_context();
1802         struct wim_inode *inode;
1803         struct wim_inode_stream *strm;
1804         const utf16lechar *uname;
1805         int ret;
1806
1807         if (!strncmp(name, "wimfs.", 6)) {
1808                 /* Handle some magical extended attributes.  These really should
1809                  * be ioctls, but directory ioctls aren't supported until
1810                  * libfuse 2.9, and even then they are broken.  [Fixed by
1811                  * libfuse commit e3b7d4c278a26520be63d99d6ea84b26906fe73d]  */
1812                 name += 6;
1813                 if (!strcmp(name, "unmount_info")) {
1814                         if (!may_unmount_wimfs())
1815                                 return -EPERM;
1816                         if (size < sizeof(struct wimfs_unmount_info))
1817                                 return -EINVAL;
1818                         memcpy(&ctx->unmount_info, value,
1819                                sizeof(struct wimfs_unmount_info));
1820                         return 0;
1821                 }
1822                 return -ENOATTR;
1823         }
1824
1825         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1826                 return -ENOTSUP;
1827
1828         if (strncmp(name, "user.", 5))
1829                 return -ENOATTR;
1830         name += 5;
1831
1832         if (!*name)
1833                 return -ENOATTR;
1834
1835         /* Setting the contents of a named data stream.  */
1836
1837         inode = wim_pathname_to_inode(ctx->wim, path);
1838         if (!inode)
1839                 return -errno;
1840
1841         ret = tstr_get_utf16le(name, &uname);
1842         if (ret)
1843                 return -errno;
1844
1845         strm = inode_get_stream(inode, STREAM_TYPE_DATA, uname);
1846         if (strm) {
1847                 ret = -EEXIST;
1848                 if (flags & XATTR_CREATE)
1849                         goto out_put_uname;
1850         } else {
1851                 ret = -ENOATTR;
1852                 if (flags & XATTR_REPLACE)
1853                         goto out_put_uname;
1854         }
1855
1856         if (strm) {
1857                 if (!inode_replace_stream_data(inode, strm, value, size,
1858                                                ctx->wim->blob_table))
1859                 {
1860                         ret = -errno;
1861                         goto out_put_uname;
1862                 }
1863         } else {
1864                 if (!inode_add_stream_with_data(inode, STREAM_TYPE_DATA, uname,
1865                                                 value, size, ctx->wim->blob_table))
1866                 {
1867                         ret = -errno;
1868                         goto out_put_uname;
1869                 }
1870         }
1871
1872         ret = 0;
1873 out_put_uname:
1874         tstr_put_utf16le(uname);
1875         return ret;
1876 }
1877
1878 static int
1879 wimfs_symlink(const char *to, const char *from)
1880 {
1881         struct fuse_context *fuse_ctx = fuse_get_context();
1882         struct wimfs_context *wimfs_ctx = WIMFS_CTX(fuse_ctx);
1883         struct wim_dentry *dentry;
1884         int ret;
1885
1886         ret = create_file(fuse_ctx, from, S_IFLNK | 0777, 0,
1887                           FILE_ATTRIBUTE_REPARSE_POINT, &dentry);
1888         if (ret)
1889                 return ret;
1890         dentry->d_inode->i_reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
1891         ret = wim_inode_set_symlink(dentry->d_inode, to,
1892                                     wimfs_ctx->wim->blob_table);
1893         if (ret) {
1894                 remove_dentry(dentry, wimfs_ctx->wim->blob_table);
1895                 if (ret == WIMLIB_ERR_NOMEM)
1896                         ret = -ENOMEM;
1897                 else
1898                         ret = -EINVAL;
1899         } else {
1900                 touch_parent(dentry);
1901         }
1902         return ret;
1903 }
1904
1905 static int
1906 wimfs_truncate(const char *path, off_t size)
1907 {
1908         const struct wimfs_context *ctx = wimfs_get_context();
1909         struct wim_dentry *dentry;
1910         struct wim_inode_stream *strm;
1911         struct blob_descriptor *blob;
1912         int ret;
1913         int fd;
1914
1915         ret = wim_pathname_to_stream(ctx, path, 0, &dentry, &strm);
1916         if (ret)
1917                 return ret;
1918
1919         blob = stream_blob_resolved(strm);
1920
1921         if (!blob && !size)
1922                 return 0;
1923
1924         if (!blob || blob->blob_location != BLOB_IN_STAGING_FILE) {
1925                 return extract_blob_to_staging_dir(dentry->d_inode,
1926                                                    strm, size, ctx);
1927         }
1928
1929         /* Truncate the staging file.  */
1930         fd = openat(blob->staging_dir_fd, blob->staging_file_name,
1931                     O_WRONLY | O_NOFOLLOW);
1932         if (fd < 0)
1933                 return -errno;
1934         ret = ftruncate(fd, size);
1935         if (close(fd) || ret)
1936                 return -errno;
1937         blob->size = size;
1938         touch_inode(dentry->d_inode);
1939         return 0;
1940 }
1941
1942 static int
1943 wimfs_unlink(const char *path)
1944 {
1945         const struct wimfs_context *ctx = wimfs_get_context();
1946         struct wim_dentry *dentry;
1947         struct wim_inode_stream *strm;
1948         int ret;
1949
1950         ret = wim_pathname_to_stream(ctx, path, 0, &dentry, &strm);
1951         if (ret)
1952                 return ret;
1953
1954         if (stream_is_named(strm)) {
1955                 inode_remove_stream(dentry->d_inode, strm,
1956                                     ctx->wim->blob_table);
1957         } else {
1958                 touch_parent(dentry);
1959                 remove_dentry(dentry, ctx->wim->blob_table);
1960         }
1961         return 0;
1962 }
1963
1964 #ifdef HAVE_UTIMENSAT
1965 /*
1966  * Change the timestamp on a file dentry.
1967  *
1968  * Note that alternate data streams do not have their own timestamps.
1969  */
1970 static int
1971 wimfs_utimens(const char *path, const struct timespec tv[2])
1972 {
1973         WIMStruct *wim = wimfs_get_WIMStruct();
1974         struct wim_inode *inode;
1975
1976         inode = wim_pathname_to_inode(wim, path);
1977         if (!inode)
1978                 return -errno;
1979
1980         if (tv[0].tv_nsec != UTIME_OMIT) {
1981                 if (tv[0].tv_nsec == UTIME_NOW)
1982                         inode->i_last_access_time = now_as_wim_timestamp();
1983                 else
1984                         inode->i_last_access_time = timespec_to_wim_timestamp(&tv[0]);
1985         }
1986         if (tv[1].tv_nsec != UTIME_OMIT) {
1987                 if (tv[1].tv_nsec == UTIME_NOW)
1988                         inode->i_last_write_time = now_as_wim_timestamp();
1989                 else
1990                         inode->i_last_write_time = timespec_to_wim_timestamp(&tv[1]);
1991         }
1992         return 0;
1993 }
1994 #else /* HAVE_UTIMENSAT */
1995 static int
1996 wimfs_utime(const char *path, struct utimbuf *times)
1997 {
1998         WIMStruct *wim = wimfs_get_WIMStruct();
1999         struct wim_inode *inode;
2000
2001         inode = wim_pathname_to_inode(wim, path);
2002         if (!inode)
2003                 return -errno;
2004
2005         inode->i_last_access_time = time_t_to_wim_timestamp(times->actime);
2006         inode->i_last_write_time = time_t_to_wim_timestamp(times->modtime);
2007         return 0;
2008 }
2009 #endif /* !HAVE_UTIMENSAT */
2010
2011 static int
2012 wimfs_write(const char *path, const char *buf, size_t size,
2013             off_t offset, struct fuse_file_info *fi)
2014 {
2015         struct wimfs_fd *fd = WIMFS_FD(fi);
2016         ssize_t ret;
2017
2018         ret = raw_pwrite(&fd->f_staging_fd, buf, size, offset);
2019         if (ret < 0)
2020                 return -errno;
2021
2022         if (offset + size > fd->f_blob->size)
2023                 fd->f_blob->size = offset + size;
2024
2025         touch_inode(fd->f_inode);
2026         return ret;
2027 }
2028
2029 static struct fuse_operations wimfs_operations = {
2030         .chmod       = wimfs_chmod,
2031         .chown       = wimfs_chown,
2032         .fgetattr    = wimfs_fgetattr,
2033         .ftruncate   = wimfs_ftruncate,
2034         .getattr     = wimfs_getattr,
2035         .getxattr    = wimfs_getxattr,
2036         .link        = wimfs_link,
2037         .listxattr   = wimfs_listxattr,
2038         .mkdir       = wimfs_mkdir,
2039         .mknod       = wimfs_mknod,
2040         .open        = wimfs_open,
2041         .opendir     = wimfs_opendir,
2042         .read        = wimfs_read,
2043         .readdir     = wimfs_readdir,
2044         .readlink    = wimfs_readlink,
2045         .release     = wimfs_release,
2046         .releasedir  = wimfs_release,
2047         .removexattr = wimfs_removexattr,
2048         .rename      = wimfs_rename,
2049         .rmdir       = wimfs_rmdir,
2050         .setxattr    = wimfs_setxattr,
2051         .symlink     = wimfs_symlink,
2052         .truncate    = wimfs_truncate,
2053         .unlink      = wimfs_unlink,
2054 #ifdef HAVE_UTIMENSAT
2055         .utimens     = wimfs_utimens,
2056 #else
2057         .utime       = wimfs_utime,
2058 #endif
2059         .write       = wimfs_write,
2060
2061         /* We keep track of file descriptor structures (struct wimfs_fd), so
2062          * there is no need to have the file path provided on operations such as
2063          * read().  */
2064 #if FUSE_MAJOR_VERSION > 2 || (FUSE_MAJOR_VERSION == 2 && FUSE_MINOR_VERSION >= 8)
2065         .flag_nullpath_ok = 1,
2066 #endif
2067 #if FUSE_MAJOR_VERSION > 2 || (FUSE_MAJOR_VERSION == 2 && FUSE_MINOR_VERSION >= 9)
2068         .flag_nopath = 1,
2069         .flag_utime_omit_ok = 1,
2070 #endif
2071 };
2072
2073 /* API function documented in wimlib.h  */
2074 WIMLIBAPI int
2075 wimlib_mount_image(WIMStruct *wim, int image, const char *dir,
2076                    int mount_flags, const char *staging_dir)
2077 {
2078         int ret;
2079         struct wim_image_metadata *imd;
2080         struct wimfs_context ctx;
2081         char *fuse_argv[16];
2082         int fuse_argc;
2083
2084         if (!wim || !dir || !*dir)
2085                 return WIMLIB_ERR_INVALID_PARAM;
2086
2087         if (mount_flags & ~(WIMLIB_MOUNT_FLAG_READWRITE |
2088                             WIMLIB_MOUNT_FLAG_DEBUG |
2089                             WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
2090                             WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
2091                             WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS |
2092                             WIMLIB_MOUNT_FLAG_UNIX_DATA |
2093                             WIMLIB_MOUNT_FLAG_ALLOW_OTHER))
2094                 return WIMLIB_ERR_INVALID_PARAM;
2095
2096         /* For read-write mount, check for write access to the WIM.  */
2097         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2098                 if (!wim->filename)
2099                         return WIMLIB_ERR_NO_FILENAME;
2100                 ret = can_modify_wim(wim);
2101                 if (ret)
2102                         return ret;
2103         }
2104
2105         /* Select the image to mount.  */
2106         ret = select_wim_image(wim, image);
2107         if (ret)
2108                 return ret;
2109
2110         /* Get the metadata for the image to mount.  */
2111         imd = wim_get_current_image_metadata(wim);
2112
2113         if (imd->modified) {
2114                 /* To avoid complicating things, we don't support mounting
2115                  * images to which in-memory modifications have already been
2116                  * made.  */
2117                 ERROR("Cannot mount a modified WIM image!");
2118                 return WIMLIB_ERR_INVALID_PARAM;
2119         }
2120
2121         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2122                 ret = lock_wim_for_append(wim);
2123                 if (ret)
2124                         return ret;
2125         }
2126
2127         /* If the user did not specify an interface for accessing named
2128          * data streams, use the default (extended attributes).  */
2129         if (!(mount_flags & (WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
2130                              WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
2131                              WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)))
2132                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
2133
2134         /* Start initializing the wimfs_context.  */
2135         memset(&ctx, 0, sizeof(struct wimfs_context));
2136         ctx.wim = wim;
2137         ctx.mount_flags = mount_flags;
2138         if (mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
2139                 ctx.default_lookup_flags = LOOKUP_FLAG_ADS_OK;
2140         /* For read-write mount, create the staging directory.  */
2141         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2142                 ret = make_staging_dir(&ctx, staging_dir);
2143                 if (ret)
2144                         goto out_unlock;
2145         }
2146         ctx.owner_uid = getuid();
2147         ctx.owner_gid = getgid();
2148
2149         /* Add each blob referenced by files in the image to a list and
2150          * preemptively double the number of references to each.  This is done
2151          * to allow implementing the WIMLIB_UNMOUNT_FLAG_NEW_IMAGE semantics.
2152          */
2153         INIT_LIST_HEAD(&ctx.orig_blob_list);
2154         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2155                 unsigned i;
2156                 struct wim_inode *inode;
2157                 struct blob_descriptor *blob;
2158
2159                 image_for_each_inode(inode, imd) {
2160                         for (i = 0; i < inode->i_num_streams; i++) {
2161                                 blob = stream_blob(&inode->i_streams[i],
2162                                                    wim->blob_table);
2163                                 if (blob)
2164                                         blob->out_refcnt = 0;
2165                         }
2166                 }
2167
2168                 image_for_each_inode(inode, imd) {
2169                         for (i = 0; i < inode->i_num_streams; i++) {
2170                                 blob = stream_blob(&inode->i_streams[i],
2171                                                    wim->blob_table);
2172                                 if (blob) {
2173                                         if (blob->out_refcnt == 0)
2174                                                 list_add(&blob->orig_blob_list,
2175                                                          &ctx.orig_blob_list);
2176                                         blob->out_refcnt += inode->i_nlink;
2177                                         blob->refcnt += inode->i_nlink;
2178                                 }
2179                         }
2180                 }
2181         }
2182
2183         /* Assign new inode numbers.  */
2184         reassign_inode_numbers(&ctx);
2185
2186         /* If a read-write mount, mark the image as modified.  */
2187         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2188                 imd->modified = 1;
2189
2190         /* Build the FUSE command line.  */
2191
2192         fuse_argc = 0;
2193         fuse_argv[fuse_argc++] = "wimlib";
2194         fuse_argv[fuse_argc++] = (char *)dir;
2195
2196         /* Disable multi-threaded operation.  */
2197         fuse_argv[fuse_argc++] = "-s";
2198
2199         /* Enable FUSE debug mode (don't fork) if requested by the user.  */
2200         if (mount_flags & WIMLIB_MOUNT_FLAG_DEBUG)
2201                 fuse_argv[fuse_argc++] = "-d";
2202
2203         /*
2204          * Build the FUSE mount options:
2205          *
2206          * use_ino
2207          *      FUSE will use the inode numbers we provide.  We want this,
2208          *      because we have inodes and will number them ourselves.
2209          *
2210          * subtype=wimfs
2211          *      Name for our filesystem (main type is "fuse").
2212          *
2213          * hard_remove
2214          *      If an open file is unlinked, unlink it for real rather than
2215          *      renaming it to a hidden file.  Our code supports this; an
2216          *      unlinked inode is retained until all its file descriptors have
2217          *      been closed.
2218          *
2219          * default_permissions
2220          *      FUSE will perform permission checking.  Useful when
2221          *      WIMLIB_MOUNT_FLAG_UNIX_DATA is provided and the WIM image
2222          *      contains the UNIX permissions for each file.
2223          *
2224          * kernel_cache
2225          *      Cache the contents of files.  This will speed up repeated access
2226          *      to files on a mounted WIM image, since they won't need to be
2227          *      decompressed repeatedly.  This option is valid because data in
2228          *      the WIM image should never be changed externally.  (Although, if
2229          *      someone really wanted to they could modify the WIM file or mess
2230          *      with the staging directory; but then they're asking for
2231          *      trouble.)
2232          *
2233          * entry_timeout=1000000000
2234          *      Cache positive name lookups indefinitely, since names can only
2235          *      be added, removed, or modified through the mounted filesystem
2236          *      itself.
2237          *
2238          * negative_timeout=1000000000
2239          *      Cache negative name lookups indefinitely, since names can only
2240          *      be added, removed, or modified through the mounted filesystem
2241          *      itself.
2242          *
2243          * attr_timeout=0
2244          *      Don't cache file/directory attributes.  This is needed as a
2245          *      workaround for the fact that when caching attributes, the high
2246          *      level interface to libfuse considers a file which has several
2247          *      hard-linked names as several different files.  (Otherwise, we
2248          *      could cache our file/directory attributes indefinitely, since
2249          *      they can only be changed through the mounted filesystem itself.)
2250          */
2251         char optstring[256] =
2252                 "use_ino"
2253                 ",subtype=wimfs"
2254                 ",hard_remove"
2255                 ",default_permissions"
2256                 ",kernel_cache"
2257                 ",entry_timeout=1000000000"
2258                 ",negative_timeout=1000000000"
2259                 ",attr_timeout=0"
2260                 ;
2261         fuse_argv[fuse_argc++] = "-o";
2262         fuse_argv[fuse_argc++] = optstring;
2263         if (!(mount_flags & WIMLIB_MOUNT_FLAG_READWRITE))
2264                 strcat(optstring, ",ro");
2265         if (mount_flags & WIMLIB_MOUNT_FLAG_ALLOW_OTHER)
2266                 strcat(optstring, ",allow_other");
2267         fuse_argv[fuse_argc] = NULL;
2268
2269         /* Mount our filesystem.  */
2270         ret = fuse_main(fuse_argc, fuse_argv, &wimfs_operations, &ctx);
2271
2272         /* Cleanup and return.  */
2273         if (ret)
2274                 ret = WIMLIB_ERR_FUSE;
2275         release_extra_refcnts(&ctx);
2276         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2277                 delete_staging_dir(&ctx);
2278 out_unlock:
2279         unlock_wim_for_append(wim);
2280         return ret;
2281 }
2282
2283 struct commit_progress_thread_args {
2284         mqd_t mq;
2285         wimlib_progress_func_t progfunc;
2286         void *progctx;
2287 };
2288
2289 static void *
2290 commit_progress_thread_proc(void *_args)
2291 {
2292         struct commit_progress_thread_args *args = _args;
2293         struct commit_progress_report report;
2294         ssize_t ret;
2295
2296         for (;;) {
2297                 ret = mq_receive(args->mq,
2298                                  (char *)&report, sizeof(report), NULL);
2299                 if (ret == sizeof(report)) {
2300                         call_progress(args->progfunc, report.msg,
2301                                       &report.info, args->progctx);
2302                 } else {
2303                         if (ret == 0 || (ret < 0 && errno != EINTR))
2304                                 break;
2305                 }
2306         }
2307         return NULL;
2308 }
2309
2310 static void
2311 generate_message_queue_name(char name[WIMFS_MQUEUE_NAME_LEN + 1])
2312 {
2313         name[0] = '/';
2314         memcpy(name + 1, "wimfs-", 6);
2315         randomize_char_array_with_alnum(name + 7, WIMFS_MQUEUE_NAME_LEN - 7);
2316         name[WIMFS_MQUEUE_NAME_LEN] = '\0';
2317 }
2318
2319 static mqd_t
2320 create_message_queue(const char *name)
2321 {
2322         bool am_root;
2323         mode_t umask_save;
2324         mode_t mode;
2325         struct mq_attr attr;
2326         mqd_t mq;
2327
2328         memset(&attr, 0, sizeof(attr));
2329         attr.mq_maxmsg = 8;
2330         attr.mq_msgsize = sizeof(struct commit_progress_report);
2331
2332         am_root = (geteuid() == 0);
2333         if (am_root) {
2334                 /* Filesystem mounted as normal user with --allow-other should
2335                  * be able to send messages to root user, if they're doing the
2336                  * unmount.  */
2337                 umask_save = umask(0);
2338                 mode = 0666;
2339         } else {
2340                 mode = 0600;
2341         }
2342         mq = mq_open(name, O_RDWR | O_CREAT | O_EXCL, mode, &attr);
2343         if (am_root)
2344                 umask(umask_save);
2345         return mq;
2346 }
2347
2348 /* Unmount a read-only or read-write mounted WIM image.  */
2349 static int
2350 do_unmount(const char *dir)
2351 {
2352         int status;
2353         ssize_t len;
2354
2355         len = getxattr(dir, "wimfs.unmount", &status, sizeof(int));
2356         if (len == sizeof(int))
2357                 return status;
2358         else if (len < 0 && (errno == EACCES || errno == EPERM))
2359                 return WIMLIB_ERR_NOT_PERMITTED_TO_UNMOUNT;
2360         else
2361                 return WIMLIB_ERR_NOT_A_MOUNTPOINT;
2362 }
2363
2364 static int
2365 set_unmount_info(const char *dir, const struct wimfs_unmount_info *unmount_info)
2366 {
2367         if (!setxattr(dir, "wimfs.unmount_info",
2368                       unmount_info, sizeof(struct wimfs_unmount_info), 0))
2369                 return 0;
2370         else if (errno == EROFS)
2371                 return 0;
2372         else if (errno == EACCES || errno == EPERM)
2373                 return WIMLIB_ERR_NOT_PERMITTED_TO_UNMOUNT;
2374         else
2375                 return WIMLIB_ERR_NOT_A_MOUNTPOINT;
2376 }
2377
2378 static int
2379 do_unmount_discard(const char *dir)
2380 {
2381         int ret;
2382         struct wimfs_unmount_info unmount_info;
2383
2384         memset(&unmount_info, 0, sizeof(unmount_info));
2385
2386         ret = set_unmount_info(dir, &unmount_info);
2387         if (ret)
2388                 return ret;
2389         return do_unmount(dir);
2390 }
2391
2392 /* Unmount a read-write mounted WIM image, committing the changes.  */
2393 static int
2394 do_unmount_commit(const char *dir, int unmount_flags,
2395                   wimlib_progress_func_t progfunc, void *progctx)
2396 {
2397         struct wimfs_unmount_info unmount_info;
2398         mqd_t mq;
2399         struct commit_progress_thread_args args;
2400         pthread_t commit_progress_tid;
2401         int ret;
2402
2403         memset(&unmount_info, 0, sizeof(unmount_info));
2404         unmount_info.unmount_flags = unmount_flags;
2405
2406         /* The current thread will be stuck in getxattr() until the image is
2407          * committed.  Create a thread to handle the progress messages.  */
2408         if (progfunc) {
2409                 generate_message_queue_name(unmount_info.mq_name);
2410
2411                 mq = create_message_queue(unmount_info.mq_name);
2412                 if (mq == (mqd_t)-1) {
2413                         ERROR_WITH_ERRNO("Can't create POSIX message queue");
2414                         return WIMLIB_ERR_MQUEUE;
2415                 }
2416                 args.mq = mq;
2417                 args.progfunc = progfunc;
2418                 args.progctx = progctx;
2419                 ret = pthread_create(&commit_progress_tid, NULL,
2420                                      commit_progress_thread_proc, &args);
2421                 if (ret) {
2422                         errno = ret;
2423                         ERROR_WITH_ERRNO("Can't create thread");
2424                         ret = WIMLIB_ERR_NOMEM;
2425                         goto out_delete_mq;
2426                 }
2427                 unmount_info.unmount_flags |= WIMLIB_UNMOUNT_FLAG_SEND_PROGRESS;
2428         }
2429
2430         ret = set_unmount_info(dir, &unmount_info);
2431         if (!ret)
2432                 ret = do_unmount(dir);
2433         if (progfunc) {
2434                 /* Terminate the progress thread.  */
2435                 char empty[1];
2436                 mq_send(mq, empty, 0, 1);
2437                 pthread_join(commit_progress_tid, NULL);
2438         }
2439 out_delete_mq:
2440         if (progfunc) {
2441                 mq_close(mq);
2442                 mq_unlink(unmount_info.mq_name);
2443         }
2444         return ret;
2445 }
2446
2447 static int
2448 begin_unmount(const char *dir, int unmount_flags, int *mount_flags_ret,
2449               wimlib_progress_func_t progfunc, void *progctx)
2450 {
2451         int mount_flags;
2452         int mounted_image;
2453         int wim_filename_len;
2454         union wimlib_progress_info progress;
2455
2456         if (getxattr(dir, "wimfs.mount_flags",
2457                      &mount_flags, sizeof(int)) != sizeof(int))
2458                 return WIMLIB_ERR_NOT_A_MOUNTPOINT;
2459
2460         *mount_flags_ret = mount_flags;
2461
2462         if (!progfunc)
2463                 return 0;
2464
2465         if (getxattr(dir, "wimfs.mounted_image",
2466                      &mounted_image, sizeof(int)) != sizeof(int))
2467                 return WIMLIB_ERR_NOT_A_MOUNTPOINT;
2468
2469         wim_filename_len = getxattr(dir, "wimfs.wim_filename", NULL, 0);
2470         if (wim_filename_len < 0)
2471                 return WIMLIB_ERR_NOT_A_MOUNTPOINT;
2472
2473         char wim_filename[wim_filename_len + 1];
2474         if (getxattr(dir, "wimfs.wim_filename",
2475                      wim_filename, wim_filename_len) != wim_filename_len)
2476                 return WIMLIB_ERR_NOT_A_MOUNTPOINT;
2477         wim_filename[wim_filename_len] = '\0';
2478
2479         progress.unmount.mountpoint = dir;
2480         progress.unmount.mounted_wim = wim_filename;
2481         progress.unmount.mounted_image = mounted_image;
2482         progress.unmount.mount_flags = mount_flags;
2483         progress.unmount.unmount_flags = unmount_flags;
2484
2485         return call_progress(progfunc, WIMLIB_PROGRESS_MSG_UNMOUNT_BEGIN,
2486                              &progress, progctx);
2487 }
2488
2489 /* API function documented in wimlib.h  */
2490 WIMLIBAPI int
2491 wimlib_unmount_image_with_progress(const char *dir, int unmount_flags,
2492                                    wimlib_progress_func_t progfunc, void *progctx)
2493 {
2494         int mount_flags;
2495         int ret;
2496
2497         ret = wimlib_global_init(WIMLIB_INIT_FLAG_ASSUME_UTF8);
2498         if (ret)
2499                 return ret;
2500
2501         if (unmount_flags & ~(WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY |
2502                               WIMLIB_UNMOUNT_FLAG_COMMIT |
2503                               WIMLIB_UNMOUNT_FLAG_REBUILD |
2504                               WIMLIB_UNMOUNT_FLAG_RECOMPRESS |
2505                               WIMLIB_UNMOUNT_FLAG_FORCE |
2506                               WIMLIB_UNMOUNT_FLAG_NEW_IMAGE))
2507                 return WIMLIB_ERR_INVALID_PARAM;
2508
2509         ret = begin_unmount(dir, unmount_flags, &mount_flags,
2510                             progfunc, progctx);
2511         if (ret)
2512                 return ret;
2513
2514         if ((unmount_flags & WIMLIB_UNMOUNT_FLAG_COMMIT) &&
2515             (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE))
2516                 return do_unmount_commit(dir, unmount_flags,
2517                                          progfunc, progctx);
2518         else
2519                 return do_unmount_discard(dir);
2520 }
2521
2522 #else /* WITH_FUSE */
2523
2524
2525 static int
2526 mount_unsupported_error(void)
2527 {
2528 #if defined(__WIN32__)
2529         ERROR("Sorry-- Mounting WIM images is not supported on Windows!");
2530 #else
2531         ERROR("wimlib was compiled with --without-fuse, which disables support "
2532               "for mounting WIMs.");
2533 #endif
2534         return WIMLIB_ERR_UNSUPPORTED;
2535 }
2536
2537 WIMLIBAPI int
2538 wimlib_unmount_image_with_progress(const tchar *dir, int unmount_flags,
2539                                    wimlib_progress_func_t progfunc, void *progctx)
2540 {
2541         return mount_unsupported_error();
2542 }
2543
2544 WIMLIBAPI int
2545 wimlib_mount_image(WIMStruct *wim, int image, const tchar *dir,
2546                    int mount_flags, const tchar *staging_dir)
2547 {
2548         return mount_unsupported_error();
2549 }
2550
2551 #endif /* !WITH_FUSE */
2552
2553 WIMLIBAPI int
2554 wimlib_unmount_image(const tchar *dir, int unmount_flags)
2555 {
2556         return wimlib_unmount_image_with_progress(dir, unmount_flags, NULL, NULL);
2557 }