]> wimlib.net Git - wimlib/blob - src/mount_image.c
87620defc68daf0daf2356fc2577afb4cee995bd
[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_data_stream(inode);
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 static u64
553 blob_size(const struct blob_descriptor *blob)
554 {
555         if (!blob)
556                 return 0;
557         return blob->size;
558 }
559
560 static u64
561 blob_stored_size(const struct blob_descriptor *blob)
562 {
563         if (!blob)
564                 return 0;
565         if (blob->blob_location == BLOB_IN_WIM &&
566             blob->size == blob->rdesc->uncompressed_size)
567                 return blob->rdesc->size_in_wim;
568         return blob->size;
569 }
570
571 /*
572  * Retrieve standard UNIX metadata ('struct stat') for a WIM inode.
573  *
574  * @blob is the blob descriptor for the stream of the inode that is being
575  * queried, or NULL.  We mostly return the same information for all streams, but
576  * st_size and st_blocks may be different for different streams.
577  *
578  * This always returns 0.
579  */
580 static int
581 inode_to_stbuf(const struct wim_inode *inode,
582                const struct blob_descriptor *blob, struct stat *stbuf)
583 {
584         const struct wimfs_context *ctx = wimfs_get_context();
585         struct wimlib_unix_data unix_data;
586
587         memset(stbuf, 0, sizeof(struct stat));
588         if ((ctx->mount_flags & WIMLIB_MOUNT_FLAG_UNIX_DATA) &&
589             inode_get_unix_data(inode, &unix_data))
590         {
591                 /* Use the user ID, group ID, mode, and device ID from the
592                  * inode's extra UNIX metadata information.  */
593                 stbuf->st_uid = unix_data.uid;
594                 stbuf->st_gid = unix_data.gid;
595                 stbuf->st_mode = unix_data.mode;
596                 stbuf->st_rdev = unix_data.rdev;
597         } else {
598                 /* Generate default values for the user ID, group ID, and mode.
599                  *
600                  * Note: in the case of an allow_other mount, fuse_context.uid
601                  * may not be the same as wimfs_context.owner_uid!  */
602                 stbuf->st_uid = ctx->owner_uid;
603                 stbuf->st_gid = ctx->owner_gid;
604                 stbuf->st_mode = inode_default_unix_mode(inode);
605         }
606         stbuf->st_ino = inode->i_ino;
607         stbuf->st_nlink = inode->i_nlink;
608         stbuf->st_size = blob_size(blob);
609 #ifdef HAVE_STAT_NANOSECOND_PRECISION
610         stbuf->st_atim = wim_timestamp_to_timespec(inode->i_last_access_time);
611         stbuf->st_mtim = wim_timestamp_to_timespec(inode->i_last_write_time);
612         stbuf->st_ctim = stbuf->st_mtim;
613 #else
614         stbuf->st_atime = wim_timestamp_to_time_t(inode->i_last_access_time);
615         stbuf->st_mtime = wim_timestamp_to_time_t(inode->i_last_write_time);
616         stbuf->st_ctime = stbuf->st_mtime;
617 #endif
618         stbuf->st_blocks = DIV_ROUND_UP(blob_stored_size(blob), 512);
619         return 0;
620 }
621
622 /* Update the last access and last write timestamps of a WIM inode.  */
623 static void
624 touch_inode(struct wim_inode *inode)
625 {
626         u64 now = now_as_wim_timestamp();
627         inode->i_last_access_time = now;
628         inode->i_last_write_time = now;
629 }
630
631 static void
632 touch_parent(struct wim_dentry *dentry)
633 {
634         touch_inode(dentry->d_parent->d_inode);
635 }
636
637 /*
638  * Create a new file in the staging directory for a read-write mounted image.
639  *
640  * On success, returns the file descriptor for the new staging file, opened for
641  * writing.  In addition, stores the allocated name of the staging file in
642  * @name_ret.
643  *
644  * On failure, returns -1 and sets errno.
645  */
646 static int
647 create_staging_file(const struct wimfs_context *ctx, char **name_ret)
648 {
649
650         static const size_t STAGING_FILE_NAME_LEN = 20;
651         char *name;
652         int fd;
653
654         name = MALLOC(STAGING_FILE_NAME_LEN + 1);
655         if (!name)
656                 return -1;
657         name[STAGING_FILE_NAME_LEN] = '\0';
658
659 retry:
660         randomize_char_array_with_alnum(name, STAGING_FILE_NAME_LEN);
661         fd = openat(ctx->staging_dir_fd, name,
662                     O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0600);
663         if (unlikely(fd < 0)) {
664                 if (unlikely(errno == EEXIST))
665                         /* Try again with another name.  */
666                         goto retry;
667                 FREE(name);
668         } else {
669                 *name_ret = name;
670         }
671         return fd;
672 }
673
674 /*
675  * Extract a blob to the staging directory.  This is necessary when a stream
676  * using the blob is being opened for writing and the blob has not already been
677  * extracted to the staging directory.
678  *
679  * @inode
680  *      The inode containing the stream being opened for writing.
681  * @strm
682  *      The stream being opened for writing.  The blob descriptor to which the
683  *      stream refers will be changed by this function.
684  * @size
685  *      Number of bytes of the blob to extract and include in the staging file.
686  *      It may be less than the actual blob length, in which case only a prefix
687  *      of the blob will be extracted.  It may also be more than the actual blob
688  *      length, in which case the extra space will be zero-filled.
689  *
690  * Returns 0 or a -errno code.
691  */
692 static int
693 extract_blob_to_staging_dir(struct wim_inode *inode,
694                             struct wim_inode_stream *strm,
695                             off_t size, const struct wimfs_context *ctx)
696 {
697         struct blob_descriptor *old_blob;
698         struct blob_descriptor *new_blob;
699         char *staging_file_name;
700         int staging_fd;
701         off_t extract_size;
702         int result;
703         int ret;
704
705         old_blob = stream_blob_resolved(strm);
706
707         /* Create the staging file.  */
708         staging_fd = create_staging_file(ctx, &staging_file_name);
709         if (unlikely(staging_fd < 0))
710                 return -errno;
711
712         /* Extract the stream to the staging file (possibly truncated).  */
713         if (old_blob) {
714                 struct filedes fd;
715
716                 filedes_init(&fd, staging_fd);
717                 errno = 0;
718                 extract_size = min(old_blob->size, size);
719                 result = extract_blob_to_fd(old_blob, &fd, extract_size);
720         } else {
721                 extract_size = 0;
722                 result = 0;
723         }
724
725         /* In the case of truncate() to more than the file length, extend the
726          * staging file with zeroes by calling ftruncate().  */
727         if (!result && size > extract_size)
728                 result = ftruncate(staging_fd, size);
729
730         /* Close the staging file.  */
731         if (close(staging_fd))
732                 result = -1;
733
734         /* If an error occurred, unlink the staging file.  */
735         if (unlikely(result)) {
736                 /* extract_blob_to_fd() should set errno, but if it didn't,
737                  * set a default value.  */
738                 ret = errno ? -errno : -EIO;
739                 goto out_delete_staging_file;
740         }
741
742         /* Create a blob descriptor for the staging file.  */
743         new_blob = new_blob_descriptor();
744         if (unlikely(!new_blob)) {
745                 ret = -ENOMEM;
746                 goto out_delete_staging_file;
747         }
748
749         /* There may already be open file descriptors to this stream if it's
750          * previously been opened read-only, but just now we're opening it
751          * read-write.  Identify those file descriptors, update them to use the
752          * new blob descriptor, and open staging file descriptors for them.  */
753         for (u16 i = 0, j = 0; j < inode->i_num_opened_fds; i++) {
754                 struct wimfs_fd *fd;
755                 int raw_fd;
756
757                 fd = inode->i_fds[i];
758                 if (!fd)
759                         continue;
760
761                 j++;
762
763                 if (fd->f_stream_id != strm->stream_id)
764                         continue;
765
766                 /* This is a readonly fd for the same stream.  */
767                 fd->f_blob = new_blob;
768                 new_blob->num_opened_fds++;
769                 raw_fd = openat(ctx->staging_dir_fd, staging_file_name,
770                                 O_RDONLY | O_NOFOLLOW);
771                 if (unlikely(raw_fd < 0)) {
772                         ret = -errno;
773                         goto out_revert_fd_changes;
774                 }
775                 filedes_init(&fd->f_staging_fd, raw_fd);
776         }
777
778         if (old_blob)
779                 old_blob->num_opened_fds -= new_blob->num_opened_fds;
780
781         new_blob->blob_location     = BLOB_IN_STAGING_FILE;
782         new_blob->staging_file_name = staging_file_name;
783         new_blob->staging_dir_fd    = ctx->staging_dir_fd;
784         new_blob->size              = size;
785
786         prepare_unhashed_blob(new_blob, inode, strm->stream_id,
787                               &wim_get_current_image_metadata(ctx->wim)->unhashed_blobs);
788         inode_replace_stream_blob(inode, strm, new_blob, ctx->wim->blob_table);
789         return 0;
790
791 out_revert_fd_changes:
792         for (u16 i = 0; new_blob->num_opened_fds; i++) {
793                 struct wimfs_fd *fd = inode->i_fds[i];
794                 if (fd && fd->f_stream_id == strm->stream_id) {
795                         fd->f_blob = old_blob;
796                         if (filedes_valid(&fd->f_staging_fd)) {
797                                 filedes_close(&fd->f_staging_fd);
798                                 filedes_invalidate(&fd->f_staging_fd);
799                         }
800                         new_blob->num_opened_fds--;
801                 }
802         }
803         free_blob_descriptor(new_blob);
804 out_delete_staging_file:
805         unlinkat(ctx->staging_dir_fd, staging_file_name, 0);
806         FREE(staging_file_name);
807         return ret;
808 }
809
810 /*
811  * Create the staging directory for the WIM file.
812  *
813  * The staging directory will be created in the directory specified by the open
814  * file descriptor @parent_dir_fd.  It will be given a randomly generated name
815  * based on @wim_basename, the name of the WIM file.
816  *
817  * On success, returns a file descriptor to the open staging directory with
818  * O_RDONLY access.  In addition, stores the allocated name of the staging
819  * directory (relative to @parent_dir_fd) in @staging_dir_name_ret.
820  * On failure, returns -1 and sets errno.
821  */
822 static int
823 make_staging_dir_at(int parent_dir_fd, const char *wim_basename,
824                     char **staging_dir_name_ret)
825 {
826         static const char common_suffix[8] = ".staging";
827         static const size_t random_suffix_len = 10;
828         size_t wim_basename_len;
829         size_t staging_dir_name_len;
830         char *staging_dir_name;
831         char *p;
832         int fd;
833
834         wim_basename_len = strlen(wim_basename);
835         staging_dir_name_len = wim_basename_len + sizeof(common_suffix) +
836                                random_suffix_len;
837         staging_dir_name = MALLOC(staging_dir_name_len + 1);
838         if (!staging_dir_name)
839                 return -1;
840
841         p = staging_dir_name;
842         p = mempcpy(p, wim_basename, wim_basename_len);
843         p = mempcpy(p, common_suffix, sizeof(common_suffix));
844         randomize_char_array_with_alnum(p, random_suffix_len);
845         p += random_suffix_len;
846         *p = '\0';
847
848         if (mkdirat(parent_dir_fd, staging_dir_name, 0700))
849                 goto err1;
850
851         fd = openat(parent_dir_fd, staging_dir_name,
852                     O_RDONLY | O_DIRECTORY | O_NOFOLLOW);
853         if (fd < 0)
854                 goto err2;
855
856         *staging_dir_name_ret = staging_dir_name;
857         return fd;
858
859 err2:
860         unlinkat(parent_dir_fd, staging_dir_name, AT_REMOVEDIR);
861 err1:
862         FREE(staging_dir_name);
863         return -1;
864 }
865
866 /*
867  * Create the staging directory and set ctx->staging_dir_fd,
868  * ctx->staging_dir_name, and ctx->parent_dir_fd.
869  */
870 static int
871 make_staging_dir(struct wimfs_context *ctx, const char *parent_dir_path)
872 {
873         const char *wim_basename;
874         char *end = NULL;
875         int ret;
876
877         wim_basename = path_basename(ctx->wim->filename);
878
879         if (!parent_dir_path) {
880                 /* The user did not specify a directory.  Default to creating
881                  * the staging directory alongside the WIM file.  */
882                 if (wim_basename > ctx->wim->filename) {
883                         parent_dir_path = ctx->wim->filename;
884                         end = (char *)(wim_basename - 1);
885                         /* *end must be a slash.  Temporarily overwrite it so we
886                          * can open the parent directory.  */
887                         *end = '\0';
888                 } else {
889                         parent_dir_path = ".";
890                 }
891         }
892
893         /* Open the parent directory (in which we'll create our staging
894          * directory).  */
895         ctx->parent_dir_fd = open(parent_dir_path, O_RDONLY | O_DIRECTORY);
896         if (ctx->parent_dir_fd < 0) {
897                 ERROR_WITH_ERRNO("Can't open directory \"%s\"",
898                                  parent_dir_path);
899                 ret = WIMLIB_ERR_OPENDIR;
900                 goto out_restore_wim_filename;
901         }
902
903         ctx->staging_dir_fd = make_staging_dir_at(ctx->parent_dir_fd,
904                                                   wim_basename,
905                                                   &ctx->staging_dir_name);
906         if (ctx->staging_dir_fd < 0) {
907                 ERROR_WITH_ERRNO("Can't create staging directory in \"%s\"",
908                                  parent_dir_path);
909                 close(ctx->parent_dir_fd);
910                 ret = WIMLIB_ERR_MKDIR;
911                 goto out_restore_wim_filename;
912         }
913         ret = 0;
914 out_restore_wim_filename:
915         if (end)
916                 *end = '/';
917         return ret;
918 }
919
920 /* Deletes the staging directory, undoing the effects of a successful call to
921  * make_staging_dir().  */
922 static void
923 delete_staging_dir(struct wimfs_context *ctx)
924 {
925         DIR *dir;
926         struct dirent *ent;
927
928         dir = fdopendir(ctx->staging_dir_fd);
929         if (dir) {
930                 while ((ent = readdir(dir)))
931                         unlinkat(ctx->staging_dir_fd, ent->d_name, 0);
932                 closedir(dir);
933         } else {
934                 close(ctx->staging_dir_fd);
935         }
936         if (unlinkat(ctx->parent_dir_fd, ctx->staging_dir_name, AT_REMOVEDIR))
937                 WARNING_WITH_ERRNO("Could not delete staging directory");
938         FREE(ctx->staging_dir_name);
939         close(ctx->parent_dir_fd);
940 }
941
942 /* Number the inodes in the mounted image sequentially.  */
943 static void
944 reassign_inode_numbers(struct wimfs_context *ctx)
945 {
946         struct wim_image_metadata *imd;
947         struct wim_inode *inode;
948
949         ctx->next_ino = 1;
950         imd = wim_get_current_image_metadata(ctx->wim);
951         image_for_each_inode(inode, imd)
952                 inode->i_ino = ctx->next_ino++;
953 }
954
955 static void
956 release_extra_refcnts(struct wimfs_context *ctx)
957 {
958         struct list_head *list = &ctx->orig_blob_list;
959         struct blob_table *blob_table = ctx->wim->blob_table;
960         struct blob_descriptor *blob, *tmp;
961
962         list_for_each_entry_safe(blob, tmp, list, orig_blob_list)
963                 blob_subtract_refcnt(blob, blob_table, blob->out_refcnt);
964 }
965
966 /* Delete the 'struct blob_descriptor' for any stream that was modified
967  * or created in the read-write mounted image and had a final size of 0.  */
968 static void
969 delete_empty_blobs(struct wimfs_context *ctx)
970 {
971         struct blob_descriptor *blob, *tmp;
972         struct wim_image_metadata *imd;
973
974         imd = wim_get_current_image_metadata(ctx->wim);
975
976         image_for_each_unhashed_blob_safe(blob, tmp, imd) {
977                 if (!blob->size) {
978                         *retrieve_pointer_to_unhashed_blob(blob) = NULL;
979                         list_del(&blob->unhashed_list);
980                         free_blob_descriptor(blob);
981                 }
982         }
983 }
984
985 /* Close all file descriptors open to the specified inode.
986  *
987  * Note: closing the last file descriptor might free the inode.  */
988 static void
989 inode_close_fds(struct wim_inode *inode)
990 {
991         u16 num_open_fds = inode->i_num_opened_fds;
992         for (u16 i = 0; num_open_fds; i++) {
993                 if (inode->i_fds[i]) {
994                         close_wimfs_fd(inode->i_fds[i]);
995                         num_open_fds--;
996                 }
997         }
998 }
999
1000 /* Close all file descriptors open to the mounted image.  */
1001 static void
1002 close_all_fds(struct wimfs_context *ctx)
1003 {
1004         struct wim_inode *inode, *tmp;
1005         struct wim_image_metadata *imd;
1006
1007         imd = wim_get_current_image_metadata(ctx->wim);
1008
1009         list_for_each_entry_safe(inode, tmp, &imd->inode_list, i_list)
1010                 inode_close_fds(inode);
1011 }
1012
1013 /* Moves the currently selected image, which may have been modified, to a new
1014  * index, and sets the original index to refer to a reset (unmodified) copy of
1015  * the image.  */
1016 static int
1017 renew_current_image(struct wimfs_context *ctx)
1018 {
1019         WIMStruct *wim = ctx->wim;
1020         int idx = wim->current_image - 1;
1021         struct wim_image_metadata *imd = wim->image_metadata[idx];
1022         struct wim_image_metadata *replace_imd;
1023         struct blob_descriptor *new_blob;
1024         int ret;
1025
1026         /* Create 'replace_imd' structure to use for the reset original,
1027          * unmodified image.  */
1028         ret = WIMLIB_ERR_NOMEM;
1029         replace_imd = new_image_metadata();
1030         if (!replace_imd)
1031                 goto err;
1032
1033         /* Create new blob descriptor for the modified image's metadata
1034          * resource, which doesn't exist yet.  */
1035         ret = WIMLIB_ERR_NOMEM;
1036         new_blob = new_blob_descriptor();
1037         if (!new_blob)
1038                 goto err_put_replace_imd;
1039
1040         new_blob->refcnt = 1;
1041         new_blob->unhashed = 1;
1042         new_blob->is_metadata = 1;
1043
1044         /* Make the image being moved available at a new index.  Increments the
1045          * WIM's image count, but does not increment the reference count of the
1046          * 'struct image_metadata'.  */
1047         ret = append_image_metadata(wim, imd);
1048         if (ret)
1049                 goto err_free_new_blob;
1050
1051         ret = xml_add_image(wim, "");
1052         if (ret)
1053                 goto err_undo_append;
1054
1055         replace_imd->metadata_blob = imd->metadata_blob;
1056         imd->metadata_blob = new_blob;
1057         wim->image_metadata[idx] = replace_imd;
1058         wim->current_image = wim->hdr.image_count;
1059         return 0;
1060
1061 err_undo_append:
1062         wim->hdr.image_count--;
1063 err_free_new_blob:
1064         free_blob_descriptor(new_blob);
1065 err_put_replace_imd:
1066         put_image_metadata(replace_imd, NULL);
1067 err:
1068         return ret;
1069 }
1070
1071 static enum wimlib_progress_status
1072 commit_progress_func(enum wimlib_progress_msg msg,
1073                      union wimlib_progress_info *info, void *progctx)
1074 {
1075         mqd_t mq = *(mqd_t *)progctx;
1076         struct commit_progress_report report;
1077
1078         memset(&report, 0, sizeof(report));
1079         report.msg = msg;
1080         if (info)
1081                 report.info = *info;
1082         mq_send(mq, (const char *)&report, sizeof(report), 1);
1083         return WIMLIB_PROGRESS_STATUS_CONTINUE;
1084 }
1085
1086 /* Commit the mounted image to the underlying WIM file.  */
1087 static int
1088 commit_image(struct wimfs_context *ctx, int unmount_flags, mqd_t mq)
1089 {
1090         int write_flags;
1091
1092         if (unmount_flags & WIMLIB_UNMOUNT_FLAG_SEND_PROGRESS)
1093                 wimlib_register_progress_function(ctx->wim,
1094                                                   commit_progress_func, &mq);
1095         else
1096                 wimlib_register_progress_function(ctx->wim, NULL, NULL);
1097
1098         if (unmount_flags & WIMLIB_UNMOUNT_FLAG_NEW_IMAGE) {
1099                 int ret = renew_current_image(ctx);
1100                 if (ret)
1101                         return ret;
1102         } else {
1103                 release_extra_refcnts(ctx);
1104         }
1105         INIT_LIST_HEAD(&ctx->orig_blob_list);
1106         delete_empty_blobs(ctx);
1107         xml_update_image_info(ctx->wim, ctx->wim->current_image);
1108
1109         write_flags = 0;
1110
1111         if (unmount_flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY)
1112                 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1113
1114         if (unmount_flags & WIMLIB_UNMOUNT_FLAG_REBUILD)
1115                 write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1116
1117         if (unmount_flags & WIMLIB_UNMOUNT_FLAG_RECOMPRESS)
1118                 write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
1119
1120         return wimlib_overwrite(ctx->wim, write_flags, 0);
1121 }
1122
1123 /* In the case of an allow_other mount, only the mount owner and root are
1124  * allowed to unmount the filesystem.  */
1125 static bool
1126 may_unmount_wimfs(void)
1127 {
1128         const struct fuse_context *fuse_ctx = fuse_get_context();
1129         const struct wimfs_context *wimfs_ctx = WIMFS_CTX(fuse_ctx);
1130
1131         return (fuse_ctx->uid == wimfs_ctx->owner_uid ||
1132                 fuse_ctx->uid == 0);
1133 }
1134
1135 /* Unmount the mounted image, called from the daemon process.  */
1136 static int
1137 unmount_wimfs(void)
1138 {
1139         struct fuse_context *fuse_ctx = fuse_get_context();
1140         struct wimfs_context *wimfs_ctx = WIMFS_CTX(fuse_ctx);
1141         const struct wimfs_unmount_info *info = &wimfs_ctx->unmount_info;
1142         int unmount_flags = info->unmount_flags;
1143         mqd_t mq = (mqd_t)-1;
1144         int ret;
1145
1146         /* Ignore COMMIT if the image is mounted read-only.  */
1147         if (!(wimfs_ctx->mount_flags & WIMLIB_MOUNT_FLAG_READWRITE))
1148                 unmount_flags &= ~WIMLIB_UNMOUNT_FLAG_COMMIT;
1149
1150         if (unmount_flags & WIMLIB_UNMOUNT_FLAG_SEND_PROGRESS) {
1151                 mq = mq_open(info->mq_name, O_WRONLY | O_NONBLOCK);
1152                 if (mq == (mqd_t)-1) {
1153                         ret = WIMLIB_ERR_MQUEUE;
1154                         goto out;
1155                 }
1156         }
1157
1158         if (wimfs_ctx->num_open_fds) {
1159
1160                 /* There are still open file descriptors to the image.  */
1161
1162                 /* With COMMIT, refuse to unmount unless FORCE is also
1163                  * specified.  */
1164                 if ((unmount_flags & (WIMLIB_UNMOUNT_FLAG_COMMIT |
1165                                       WIMLIB_UNMOUNT_FLAG_FORCE))
1166                                  == WIMLIB_UNMOUNT_FLAG_COMMIT)
1167                 {
1168                         ret = WIMLIB_ERR_MOUNTED_IMAGE_IS_BUSY;
1169                         goto out;
1170                 }
1171
1172                 /* Force-close all file descriptors.  */
1173                 close_all_fds(wimfs_ctx);
1174         }
1175
1176         if (unmount_flags & WIMLIB_UNMOUNT_FLAG_COMMIT)
1177                 ret = commit_image(wimfs_ctx, unmount_flags, mq);
1178         else
1179                 ret = 0;  /* Read-only mount, or discarding changes to
1180                              a read-write mount  */
1181
1182 out:
1183         /* Leave the image mounted if commit failed, unless this is a
1184          * forced unmount.  The user can retry without COMMIT if they
1185          * want.  */
1186         if (!ret || (unmount_flags & WIMLIB_UNMOUNT_FLAG_FORCE)) {
1187                 unlock_wim_for_append(wimfs_ctx->wim);
1188                 fuse_exit(fuse_ctx->fuse);
1189         }
1190         if (mq != (mqd_t)-1)
1191                 mq_close(mq);
1192         return ret;
1193 }
1194
1195 static int
1196 wimfs_chmod(const char *path, mode_t mask)
1197 {
1198         const struct wimfs_context *ctx = wimfs_get_context();
1199         struct wim_inode *inode;
1200         struct wimlib_unix_data unix_data;
1201
1202         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_UNIX_DATA))
1203                 return -EOPNOTSUPP;
1204
1205         inode = wim_pathname_to_inode(ctx->wim, path);
1206         if (!inode)
1207                 return -errno;
1208
1209         unix_data.uid = ctx->owner_uid;
1210         unix_data.gid = ctx->owner_gid;
1211         unix_data.mode = mask;
1212         unix_data.rdev = 0;
1213
1214         if (!inode_set_unix_data(inode, &unix_data, UNIX_DATA_MODE))
1215                 return -ENOMEM;
1216
1217         return 0;
1218 }
1219
1220 static int
1221 wimfs_chown(const char *path, uid_t uid, gid_t gid)
1222 {
1223         const struct wimfs_context *ctx = wimfs_get_context();
1224         struct wim_inode *inode;
1225         struct wimlib_unix_data unix_data;
1226         int which;
1227
1228         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_UNIX_DATA))
1229                 return -EOPNOTSUPP;
1230
1231         inode = wim_pathname_to_inode(ctx->wim, path);
1232         if (!inode)
1233                 return -errno;
1234
1235         which = 0;
1236
1237         if (uid != (uid_t)-1)
1238                 which |= UNIX_DATA_UID;
1239         else
1240                 uid = ctx->owner_uid;
1241
1242         if (gid != (gid_t)-1)
1243                 which |= UNIX_DATA_GID;
1244         else
1245                 gid = ctx->owner_gid;
1246
1247         unix_data.uid = uid;
1248         unix_data.gid = gid;
1249         unix_data.mode = inode_default_unix_mode(inode);
1250         unix_data.rdev = 0;
1251
1252         if (!inode_set_unix_data(inode, &unix_data, which))
1253                 return -ENOMEM;
1254
1255         return 0;
1256 }
1257
1258 static int
1259 wimfs_fgetattr(const char *path, struct stat *stbuf, struct fuse_file_info *fi)
1260 {
1261         struct wimfs_fd *fd = WIMFS_FD(fi);
1262         return inode_to_stbuf(fd->f_inode, fd->f_blob, stbuf);
1263 }
1264
1265 static int
1266 wimfs_ftruncate(const char *path, off_t size, struct fuse_file_info *fi)
1267 {
1268         struct wimfs_fd *fd = WIMFS_FD(fi);
1269         if (ftruncate(fd->f_staging_fd.fd, size))
1270                 return -errno;
1271         touch_inode(fd->f_inode);
1272         fd->f_blob->size = size;
1273         return 0;
1274 }
1275
1276 static int
1277 wimfs_getattr(const char *path, struct stat *stbuf)
1278 {
1279         const struct wimfs_context *ctx = wimfs_get_context();
1280         struct wim_dentry *dentry;
1281         struct wim_inode_stream *strm;
1282         int ret;
1283
1284         ret = wim_pathname_to_stream(ctx, path, LOOKUP_FLAG_DIRECTORY_OK,
1285                                      &dentry, &strm);
1286         if (ret)
1287                 return ret;
1288
1289         return inode_to_stbuf(dentry->d_inode,
1290                               stream_blob_resolved(strm), stbuf);
1291 }
1292
1293 static int
1294 copy_xattr(char *dest, size_t destsize, const void *src, size_t srcsize)
1295 {
1296         if (destsize) {
1297                 if (destsize < srcsize)
1298                         return -ERANGE;
1299                 memcpy(dest, src, srcsize);
1300         }
1301         return srcsize;
1302 }
1303
1304 static int
1305 wimfs_getxattr(const char *path, const char *name, char *value,
1306                size_t size)
1307 {
1308         const struct wimfs_context *ctx = wimfs_get_context();
1309         struct wim_inode *inode;
1310         struct wim_inode_stream *strm;
1311         struct blob_descriptor *blob;
1312
1313         if (!strncmp(name, "wimfs.", 6)) {
1314                 /* Handle some magical extended attributes.  These really should
1315                  * be ioctls, but directory ioctls aren't supported until
1316                  * libfuse 2.9, and even then they are broken.  */
1317                 name += 6;
1318                 if (!strcmp(name, "wim_filename")) {
1319                         return copy_xattr(value, size, ctx->wim->filename,
1320                                           strlen(ctx->wim->filename));
1321                 }
1322                 if (!strcmp(name, "wim_info")) {
1323                         struct wimlib_wim_info info;
1324
1325                         wimlib_get_wim_info(ctx->wim, &info);
1326
1327                         return copy_xattr(value, size, &info, sizeof(info));
1328                 }
1329                 if (!strcmp(name, "mounted_image")) {
1330                         return copy_xattr(value, size,
1331                                           &ctx->wim->current_image, sizeof(int));
1332                 }
1333                 if (!strcmp(name, "mount_flags")) {
1334                         return copy_xattr(value, size,
1335                                           &ctx->mount_flags, sizeof(int));
1336                 }
1337                 if (!strcmp(name, "unmount")) {
1338                         if (!may_unmount_wimfs())
1339                                 return -EPERM;
1340                         if (size) {
1341                                 int status;
1342
1343                                 if (size < sizeof(int))
1344                                         return -ERANGE;
1345                                 status = unmount_wimfs();
1346                                 memcpy(value, &status, sizeof(int));
1347                         }
1348                         return sizeof(int);
1349                 }
1350                 return -ENOATTR;
1351         }
1352
1353         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1354                 return -ENOTSUP;
1355
1356         if (strncmp(name, "user.", 5))
1357                 return -ENOATTR;
1358         name += 5;
1359
1360         if (!*name)
1361                 return -ENOATTR;
1362
1363         /* Querying a named data stream  */
1364
1365         inode = wim_pathname_to_inode(ctx->wim, path);
1366         if (!inode)
1367                 return -errno;
1368
1369         strm = inode_get_data_stream_tstr(inode, name);
1370         if (!strm)
1371                 return (errno == ENOENT) ? -ENOATTR : -errno;
1372
1373         blob = stream_blob_resolved(strm);
1374         if (!blob)
1375                 return 0;
1376
1377         if (unlikely(blob->size > INT_MAX))
1378                 return -EFBIG;
1379
1380         if (size) {
1381                 if (size < blob->size)
1382                         return -ERANGE;
1383
1384                 if (read_full_blob_into_buf(blob, value))
1385                         return errno ? -errno : -EIO;
1386         }
1387         return blob->size;
1388 }
1389
1390 static int
1391 wimfs_link(const char *existing_path, const char *new_path)
1392 {
1393         WIMStruct *wim = wimfs_get_WIMStruct();
1394         const char *new_name;
1395         struct wim_inode *inode;
1396         struct wim_dentry *dir;
1397         struct wim_dentry *new_alias;
1398
1399         inode = wim_pathname_to_inode(wim, existing_path);
1400         if (!inode)
1401                 return -errno;
1402
1403         if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1404                                    FILE_ATTRIBUTE_REPARSE_POINT))
1405                 return -EPERM;
1406
1407         new_name = path_basename(new_path);
1408
1409         dir = get_parent_dentry(wim, new_path, WIMLIB_CASE_SENSITIVE);
1410         if (!dir)
1411                 return -errno;
1412
1413         if (!dentry_is_directory(dir))
1414                 return -ENOTDIR;
1415
1416         if (get_dentry_child_with_name(dir, new_name, WIMLIB_CASE_SENSITIVE))
1417                 return -EEXIST;
1418
1419         if (new_dentry_with_existing_inode(new_name, inode, &new_alias))
1420                 return -ENOMEM;
1421
1422         dentry_add_child(dir, new_alias);
1423         touch_inode(dir->d_inode);
1424         return 0;
1425 }
1426
1427 static int
1428 wimfs_listxattr(const char *path, char *list, size_t size)
1429 {
1430         const struct wimfs_context *ctx = wimfs_get_context();
1431         const struct wim_inode *inode;
1432         char *p = list;
1433         char *end = list + size;
1434         int total_size = 0;
1435
1436         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1437                 return -ENOTSUP;
1438
1439         /* List named data streams, or get the list size.  We report each named
1440          * data stream "X" as an extended attribute "user.X".  */
1441
1442         inode = wim_pathname_to_inode(ctx->wim, path);
1443         if (!inode)
1444                 return -errno;
1445
1446         for (unsigned i = 0; i < inode->i_num_streams; i++) {
1447                 const struct wim_inode_stream *strm;
1448                 char *stream_name_mbs;
1449                 size_t stream_name_mbs_nbytes;
1450
1451                 strm = &inode->i_streams[i];
1452
1453                 if (!stream_is_named_data_stream(strm))
1454                         continue;
1455
1456                 if (utf16le_to_tstr(strm->stream_name,
1457                                     utf16le_len_bytes(strm->stream_name),
1458                                     &stream_name_mbs,
1459                                     &stream_name_mbs_nbytes))
1460                         return -errno;
1461
1462                 if (unlikely(INT_MAX - total_size < stream_name_mbs_nbytes + 6)) {
1463                         FREE(stream_name_mbs);
1464                         return -EFBIG;
1465                 }
1466
1467                 total_size += stream_name_mbs_nbytes + 6;
1468                 if (size) {
1469                         if (end - p < stream_name_mbs_nbytes + 6) {
1470                                 FREE(stream_name_mbs);
1471                                 return -ERANGE;
1472                         }
1473                         p = mempcpy(p, "user.", 5);
1474                         p = mempcpy(p, stream_name_mbs, stream_name_mbs_nbytes);
1475                         *p++ = '\0';
1476                 }
1477                 FREE(stream_name_mbs);
1478         }
1479         return total_size;
1480 }
1481
1482 static int
1483 wimfs_mkdir(const char *path, mode_t mode)
1484 {
1485         struct wim_dentry *dentry;
1486         int ret;
1487
1488         /* Note: according to fuse.h, mode may not include S_IFDIR  */
1489         ret = create_file(fuse_get_context(), path, mode | S_IFDIR, 0,
1490                           FILE_ATTRIBUTE_DIRECTORY, &dentry);
1491         if (ret)
1492                 return ret;
1493         touch_parent(dentry);
1494         return 0;
1495 }
1496
1497 static int
1498 wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
1499 {
1500         struct fuse_context *fuse_ctx = fuse_get_context();
1501         struct wimfs_context *wimfs_ctx = WIMFS_CTX(fuse_ctx);
1502         const char *stream_name;
1503
1504         if ((wimfs_ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
1505              && (stream_name = path_stream_name(path)))
1506         {
1507                 struct wim_inode *inode;
1508                 struct wim_inode_stream *existing_strm;
1509                 struct wim_inode_stream *new_strm;
1510                 char *p;
1511                 const utf16lechar *uname;
1512
1513                 /* Create a named data stream.  */
1514
1515                 if (!S_ISREG(mode))
1516                         return -EOPNOTSUPP;
1517
1518                 p = (char *)stream_name - 1;
1519
1520                 *p = '\0';
1521                 inode = wim_pathname_to_inode(wimfs_ctx->wim, path);
1522                 *p = ':';
1523                 if (!inode)
1524                         return -errno;
1525
1526                 if (tstr_get_utf16le(stream_name, &uname))
1527                         return -errno;
1528
1529                 existing_strm = inode_get_stream(inode, STREAM_TYPE_DATA, uname);
1530                 if (existing_strm) {
1531                         tstr_put_utf16le(uname);
1532                         return -EEXIST;
1533                 }
1534
1535                 new_strm = inode_add_stream(inode, STREAM_TYPE_DATA, uname, NULL);
1536
1537                 tstr_put_utf16le(uname);
1538
1539                 if (!new_strm)
1540                         return -errno;
1541                 return 0;
1542         } else {
1543                 /* Create a regular file, device node, named pipe, or socket.
1544                  */
1545                 struct wim_dentry *dentry;
1546                 int ret;
1547
1548                 if (!S_ISREG(mode) &&
1549                     !(wimfs_ctx->mount_flags & WIMLIB_MOUNT_FLAG_UNIX_DATA))
1550                         return -EPERM;
1551
1552                 /* Note: we still use FILE_ATTRIBUTE_NORMAL for device nodes,
1553                  * named pipes, and sockets.  The real mode is in the UNIX
1554                  * metadata.  */
1555                 ret = create_file(fuse_ctx, path, mode, rdev,
1556                                   FILE_ATTRIBUTE_NORMAL, &dentry);
1557                 if (ret)
1558                         return ret;
1559                 touch_parent(dentry);
1560                 return 0;
1561         }
1562 }
1563
1564 static int
1565 wimfs_open(const char *path, struct fuse_file_info *fi)
1566 {
1567         struct wimfs_context *ctx = wimfs_get_context();
1568         struct wim_dentry *dentry;
1569         struct wim_inode *inode;
1570         struct wim_inode_stream *strm;
1571         struct blob_descriptor *blob;
1572         struct wimfs_fd *fd;
1573         int ret;
1574
1575         ret = wim_pathname_to_stream(ctx, path, 0, &dentry, &strm);
1576         if (ret)
1577                 return ret;
1578
1579         inode = dentry->d_inode;
1580         blob = stream_blob_resolved(strm);
1581
1582         /* The data of the file being opened may be in the staging directory
1583          * (read-write mounts only) or in the WIM.  If it's in the staging
1584          * directory, we need to open a native file descriptor for the
1585          * corresponding file.  Otherwise, we can read the file data directly
1586          * from the WIM file if we are opening it read-only, but we need to
1587          * extract the data to the staging directory if we are opening it
1588          * writable.  */
1589
1590         if (flags_writable(fi->flags) &&
1591             (!blob || blob->blob_location != BLOB_IN_STAGING_FILE)) {
1592                 ret = extract_blob_to_staging_dir(inode,
1593                                                   strm,
1594                                                   blob_size(blob),
1595                                                   ctx);
1596                 if (ret)
1597                         return ret;
1598                 blob = stream_blob_resolved(strm);
1599         }
1600
1601         ret = alloc_wimfs_fd(inode, strm, &fd);
1602         if (ret)
1603                 return ret;
1604
1605         if (blob && blob->blob_location == BLOB_IN_STAGING_FILE) {
1606                 int raw_fd;
1607
1608                 raw_fd = openat(blob->staging_dir_fd, blob->staging_file_name,
1609                                 (fi->flags & O_ACCMODE) | O_NOFOLLOW);
1610                 if (raw_fd < 0) {
1611                         close_wimfs_fd(fd);
1612                         return -errno;
1613                 }
1614                 filedes_init(&fd->f_staging_fd, raw_fd);
1615         }
1616         fi->fh = (uintptr_t)fd;
1617         return 0;
1618 }
1619
1620 static int
1621 wimfs_opendir(const char *path, struct fuse_file_info *fi)
1622 {
1623         WIMStruct *wim = wimfs_get_WIMStruct();
1624         struct wim_inode *inode;
1625         struct wim_inode_stream *strm;
1626         struct wimfs_fd *fd;
1627         int ret;
1628
1629         inode = wim_pathname_to_inode(wim, path);
1630         if (!inode)
1631                 return -errno;
1632         if (!inode_is_directory(inode))
1633                 return -ENOTDIR;
1634         strm = inode_get_unnamed_data_stream(inode);
1635         if (!strm)
1636                 return -ENOTDIR;
1637         ret = alloc_wimfs_fd(inode, strm, &fd);
1638         if (ret)
1639                 return ret;
1640         fi->fh = (uintptr_t)fd;
1641         return 0;
1642 }
1643
1644 static int
1645 wimfs_read(const char *path, char *buf, size_t size,
1646            off_t offset, struct fuse_file_info *fi)
1647 {
1648         struct wimfs_fd *fd = WIMFS_FD(fi);
1649         const struct blob_descriptor *blob;
1650         ssize_t ret;
1651
1652         blob = fd->f_blob;
1653         if (!blob)
1654                 return 0;
1655
1656         if (offset >= blob->size)
1657                 return 0;
1658
1659         if (size > blob->size - offset)
1660                 size = blob->size - offset;
1661
1662         if (!size)
1663                 return 0;
1664
1665         switch (blob->blob_location) {
1666         case BLOB_IN_WIM:
1667                 if (read_partial_wim_blob_into_buf(blob, size, offset, buf))
1668                         ret = errno ? -errno : -EIO;
1669                 else
1670                         ret = size;
1671                 break;
1672         case BLOB_IN_STAGING_FILE:
1673                 ret = raw_pread(&fd->f_staging_fd, buf, size, offset);
1674                 if (ret < 0)
1675                         ret = -errno;
1676                 break;
1677         case BLOB_IN_ATTACHED_BUFFER:
1678                 memcpy(buf, blob->attached_buffer + offset, size);
1679                 ret = size;
1680                 break;
1681         default:
1682                 ret = -EINVAL;
1683                 break;
1684         }
1685         return ret;
1686 }
1687
1688 static int
1689 wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
1690               off_t offset, struct fuse_file_info *fi)
1691 {
1692         struct wimfs_fd *fd = WIMFS_FD(fi);
1693         const struct wim_inode *inode;
1694         const struct wim_dentry *child;
1695         int ret;
1696
1697         inode = fd->f_inode;
1698
1699         ret = filler(buf, ".", NULL, 0);
1700         if (ret)
1701                 return ret;
1702         ret = filler(buf, "..", NULL, 0);
1703         if (ret)
1704                 return ret;
1705
1706         for_inode_child(child, inode) {
1707                 char *file_name_mbs;
1708                 size_t file_name_mbs_nbytes;
1709
1710                 ret = utf16le_to_tstr(child->file_name,
1711                                       child->file_name_nbytes,
1712                                       &file_name_mbs,
1713                                       &file_name_mbs_nbytes);
1714                 if (ret)
1715                         return -errno;
1716
1717                 ret = filler(buf, file_name_mbs, NULL, 0);
1718                 FREE(file_name_mbs);
1719                 if (ret)
1720                         return ret;
1721         }
1722         return 0;
1723 }
1724
1725 static int
1726 wimfs_readlink(const char *path, char *buf, size_t buf_len)
1727 {
1728         WIMStruct *wim = wimfs_get_WIMStruct();
1729         const struct wim_inode *inode;
1730         ssize_t ret;
1731
1732         inode = wim_pathname_to_inode(wim, path);
1733         if (!inode)
1734                 return -errno;
1735         if (!inode_is_symlink(inode))
1736                 return -EINVAL;
1737         if (buf_len == 0)
1738                 return -EINVAL;
1739         ret = wim_inode_readlink(inode, buf, buf_len - 1, NULL);
1740         if (ret >= 0) {
1741                 buf[ret] = '\0';
1742                 ret = 0;
1743         } else if (ret == -ENAMETOOLONG) {
1744                 buf[buf_len - 1] = '\0';
1745         }
1746         return ret;
1747 }
1748
1749 /* We use this for both release() and releasedir(), since in both cases we
1750  * simply need to close the file descriptor.  */
1751 static int
1752 wimfs_release(const char *path, struct fuse_file_info *fi)
1753 {
1754         return close_wimfs_fd(WIMFS_FD(fi));
1755 }
1756
1757 static int
1758 wimfs_removexattr(const char *path, const char *name)
1759 {
1760         struct wimfs_context *ctx = wimfs_get_context();
1761         struct wim_inode *inode;
1762         struct wim_inode_stream *strm;
1763
1764         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1765                 return -ENOTSUP;
1766
1767         if (strncmp(name, "user.", 5))
1768                 return -ENOATTR;
1769         name += 5;
1770
1771         if (!*name)
1772                 return -ENOATTR;
1773
1774         /* Removing a named data stream.  */
1775
1776         inode = wim_pathname_to_inode(ctx->wim, path);
1777         if (!inode)
1778                 return -errno;
1779
1780         strm = inode_get_data_stream_tstr(inode, name);
1781         if (!strm)
1782                 return (errno == ENOENT) ? -ENOATTR : -errno;
1783
1784         inode_remove_stream(inode, strm, ctx->wim->blob_table);
1785         return 0;
1786 }
1787
1788 static int
1789 wimfs_rename(const char *from, const char *to)
1790 {
1791         return rename_wim_path(wimfs_get_WIMStruct(), from, to,
1792                                WIMLIB_CASE_SENSITIVE, NULL);
1793 }
1794
1795 static int
1796 wimfs_rmdir(const char *path)
1797 {
1798         WIMStruct *wim = wimfs_get_WIMStruct();
1799         struct wim_dentry *dentry;
1800
1801         dentry = get_dentry(wim, path, WIMLIB_CASE_SENSITIVE);
1802         if (!dentry)
1803                 return -errno;
1804
1805         if (!dentry_is_directory(dentry))
1806                 return -ENOTDIR;
1807
1808         if (dentry_has_children(dentry))
1809                 return -ENOTEMPTY;
1810
1811         touch_parent(dentry);
1812         remove_dentry(dentry, wim->blob_table);
1813         return 0;
1814 }
1815
1816 static int
1817 wimfs_setxattr(const char *path, const char *name,
1818                const char *value, size_t size, int flags)
1819 {
1820         struct wimfs_context *ctx = wimfs_get_context();
1821         struct wim_inode *inode;
1822         struct wim_inode_stream *strm;
1823         const utf16lechar *uname;
1824         int ret;
1825
1826         if (!strncmp(name, "wimfs.", 6)) {
1827                 /* Handle some magical extended attributes.  These really should
1828                  * be ioctls, but directory ioctls aren't supported until
1829                  * libfuse 2.9, and even then they are broken.  [Fixed by
1830                  * libfuse commit e3b7d4c278a26520be63d99d6ea84b26906fe73d]  */
1831                 name += 6;
1832                 if (!strcmp(name, "unmount_info")) {
1833                         if (!may_unmount_wimfs())
1834                                 return -EPERM;
1835                         if (size < sizeof(struct wimfs_unmount_info))
1836                                 return -EINVAL;
1837                         memcpy(&ctx->unmount_info, value,
1838                                sizeof(struct wimfs_unmount_info));
1839                         return 0;
1840                 }
1841                 return -ENOATTR;
1842         }
1843
1844         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1845                 return -ENOTSUP;
1846
1847         if (strncmp(name, "user.", 5))
1848                 return -ENOATTR;
1849         name += 5;
1850
1851         if (!*name)
1852                 return -ENOATTR;
1853
1854         /* Setting the contents of a named data stream.  */
1855
1856         inode = wim_pathname_to_inode(ctx->wim, path);
1857         if (!inode)
1858                 return -errno;
1859
1860         ret = tstr_get_utf16le(name, &uname);
1861         if (ret)
1862                 return -errno;
1863
1864         strm = inode_get_stream(inode, STREAM_TYPE_DATA, uname);
1865         if (strm) {
1866                 ret = -EEXIST;
1867                 if (flags & XATTR_CREATE)
1868                         goto out_put_uname;
1869         } else {
1870                 ret = -ENOATTR;
1871                 if (flags & XATTR_REPLACE)
1872                         goto out_put_uname;
1873         }
1874
1875         if (strm) {
1876                 if (!inode_replace_stream_data(inode, strm, value, size,
1877                                                ctx->wim->blob_table))
1878                 {
1879                         ret = -errno;
1880                         goto out_put_uname;
1881                 }
1882         } else {
1883                 if (!inode_add_stream_with_data(inode, STREAM_TYPE_DATA, uname,
1884                                                 value, size, ctx->wim->blob_table))
1885                 {
1886                         ret = -errno;
1887                         goto out_put_uname;
1888                 }
1889         }
1890
1891         ret = 0;
1892 out_put_uname:
1893         tstr_put_utf16le(uname);
1894         return ret;
1895 }
1896
1897 static int
1898 wimfs_symlink(const char *to, const char *from)
1899 {
1900         struct fuse_context *fuse_ctx = fuse_get_context();
1901         struct wimfs_context *wimfs_ctx = WIMFS_CTX(fuse_ctx);
1902         struct wim_dentry *dentry;
1903         int ret;
1904
1905         ret = create_file(fuse_ctx, from, S_IFLNK | 0777, 0,
1906                           FILE_ATTRIBUTE_REPARSE_POINT, &dentry);
1907         if (ret)
1908                 return ret;
1909         dentry->d_inode->i_reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
1910         ret = wim_inode_set_symlink(dentry->d_inode, to,
1911                                     wimfs_ctx->wim->blob_table);
1912         if (ret) {
1913                 remove_dentry(dentry, wimfs_ctx->wim->blob_table);
1914                 if (ret == WIMLIB_ERR_NOMEM)
1915                         ret = -ENOMEM;
1916                 else
1917                         ret = -EINVAL;
1918         } else {
1919                 touch_parent(dentry);
1920         }
1921         return ret;
1922 }
1923
1924 static int
1925 wimfs_truncate(const char *path, off_t size)
1926 {
1927         const struct wimfs_context *ctx = wimfs_get_context();
1928         struct wim_dentry *dentry;
1929         struct wim_inode_stream *strm;
1930         struct blob_descriptor *blob;
1931         int ret;
1932         int fd;
1933
1934         ret = wim_pathname_to_stream(ctx, path, 0, &dentry, &strm);
1935         if (ret)
1936                 return ret;
1937
1938         blob = stream_blob_resolved(strm);
1939
1940         if (!blob && !size)
1941                 return 0;
1942
1943         if (!blob || blob->blob_location != BLOB_IN_STAGING_FILE) {
1944                 return extract_blob_to_staging_dir(dentry->d_inode,
1945                                                    strm, size, ctx);
1946         }
1947
1948         /* Truncate the staging file.  */
1949         fd = openat(blob->staging_dir_fd, blob->staging_file_name,
1950                     O_WRONLY | O_NOFOLLOW);
1951         if (fd < 0)
1952                 return -errno;
1953         ret = ftruncate(fd, size);
1954         if (close(fd) || ret)
1955                 return -errno;
1956         blob->size = size;
1957         touch_inode(dentry->d_inode);
1958         return 0;
1959 }
1960
1961 static int
1962 wimfs_unlink(const char *path)
1963 {
1964         const struct wimfs_context *ctx = wimfs_get_context();
1965         struct wim_dentry *dentry;
1966         struct wim_inode_stream *strm;
1967         int ret;
1968
1969         ret = wim_pathname_to_stream(ctx, path, 0, &dentry, &strm);
1970         if (ret)
1971                 return ret;
1972
1973         if (stream_is_named(strm)) {
1974                 inode_remove_stream(dentry->d_inode, strm,
1975                                     ctx->wim->blob_table);
1976         } else {
1977                 touch_parent(dentry);
1978                 remove_dentry(dentry, ctx->wim->blob_table);
1979         }
1980         return 0;
1981 }
1982
1983 #ifdef HAVE_UTIMENSAT
1984 /*
1985  * Change the timestamp on a file dentry.
1986  *
1987  * Note that alternate data streams do not have their own timestamps.
1988  */
1989 static int
1990 wimfs_utimens(const char *path, const struct timespec tv[2])
1991 {
1992         WIMStruct *wim = wimfs_get_WIMStruct();
1993         struct wim_inode *inode;
1994
1995         inode = wim_pathname_to_inode(wim, path);
1996         if (!inode)
1997                 return -errno;
1998
1999         if (tv[0].tv_nsec != UTIME_OMIT) {
2000                 if (tv[0].tv_nsec == UTIME_NOW)
2001                         inode->i_last_access_time = now_as_wim_timestamp();
2002                 else
2003                         inode->i_last_access_time = timespec_to_wim_timestamp(&tv[0]);
2004         }
2005         if (tv[1].tv_nsec != UTIME_OMIT) {
2006                 if (tv[1].tv_nsec == UTIME_NOW)
2007                         inode->i_last_write_time = now_as_wim_timestamp();
2008                 else
2009                         inode->i_last_write_time = timespec_to_wim_timestamp(&tv[1]);
2010         }
2011         return 0;
2012 }
2013 #else /* HAVE_UTIMENSAT */
2014 static int
2015 wimfs_utime(const char *path, struct utimbuf *times)
2016 {
2017         WIMStruct *wim = wimfs_get_WIMStruct();
2018         struct wim_inode *inode;
2019
2020         inode = wim_pathname_to_inode(wim, path);
2021         if (!inode)
2022                 return -errno;
2023
2024         inode->i_last_access_time = time_t_to_wim_timestamp(times->actime);
2025         inode->i_last_write_time = time_t_to_wim_timestamp(times->modtime);
2026         return 0;
2027 }
2028 #endif /* !HAVE_UTIMENSAT */
2029
2030 static int
2031 wimfs_write(const char *path, const char *buf, size_t size,
2032             off_t offset, struct fuse_file_info *fi)
2033 {
2034         struct wimfs_fd *fd = WIMFS_FD(fi);
2035         ssize_t ret;
2036
2037         ret = raw_pwrite(&fd->f_staging_fd, buf, size, offset);
2038         if (ret < 0)
2039                 return -errno;
2040
2041         if (offset + size > fd->f_blob->size)
2042                 fd->f_blob->size = offset + size;
2043
2044         touch_inode(fd->f_inode);
2045         return ret;
2046 }
2047
2048 static struct fuse_operations wimfs_operations = {
2049         .chmod       = wimfs_chmod,
2050         .chown       = wimfs_chown,
2051         .fgetattr    = wimfs_fgetattr,
2052         .ftruncate   = wimfs_ftruncate,
2053         .getattr     = wimfs_getattr,
2054         .getxattr    = wimfs_getxattr,
2055         .link        = wimfs_link,
2056         .listxattr   = wimfs_listxattr,
2057         .mkdir       = wimfs_mkdir,
2058         .mknod       = wimfs_mknod,
2059         .open        = wimfs_open,
2060         .opendir     = wimfs_opendir,
2061         .read        = wimfs_read,
2062         .readdir     = wimfs_readdir,
2063         .readlink    = wimfs_readlink,
2064         .release     = wimfs_release,
2065         .releasedir  = wimfs_release,
2066         .removexattr = wimfs_removexattr,
2067         .rename      = wimfs_rename,
2068         .rmdir       = wimfs_rmdir,
2069         .setxattr    = wimfs_setxattr,
2070         .symlink     = wimfs_symlink,
2071         .truncate    = wimfs_truncate,
2072         .unlink      = wimfs_unlink,
2073 #ifdef HAVE_UTIMENSAT
2074         .utimens     = wimfs_utimens,
2075 #else
2076         .utime       = wimfs_utime,
2077 #endif
2078         .write       = wimfs_write,
2079
2080         /* We keep track of file descriptor structures (struct wimfs_fd), so
2081          * there is no need to have the file path provided on operations such as
2082          * read().  */
2083 #if FUSE_MAJOR_VERSION > 2 || (FUSE_MAJOR_VERSION == 2 && FUSE_MINOR_VERSION >= 8)
2084         .flag_nullpath_ok = 1,
2085 #endif
2086 #if FUSE_MAJOR_VERSION > 2 || (FUSE_MAJOR_VERSION == 2 && FUSE_MINOR_VERSION >= 9)
2087         .flag_nopath = 1,
2088         .flag_utime_omit_ok = 1,
2089 #endif
2090 };
2091
2092 /* API function documented in wimlib.h  */
2093 WIMLIBAPI int
2094 wimlib_mount_image(WIMStruct *wim, int image, const char *dir,
2095                    int mount_flags, const char *staging_dir)
2096 {
2097         int ret;
2098         struct wim_image_metadata *imd;
2099         struct wimfs_context ctx;
2100         char *fuse_argv[16];
2101         int fuse_argc;
2102
2103         if (!wim || !dir || !*dir)
2104                 return WIMLIB_ERR_INVALID_PARAM;
2105
2106         if (mount_flags & ~(WIMLIB_MOUNT_FLAG_READWRITE |
2107                             WIMLIB_MOUNT_FLAG_DEBUG |
2108                             WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
2109                             WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
2110                             WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS |
2111                             WIMLIB_MOUNT_FLAG_UNIX_DATA |
2112                             WIMLIB_MOUNT_FLAG_ALLOW_OTHER))
2113                 return WIMLIB_ERR_INVALID_PARAM;
2114
2115         /* For read-write mount, check for write access to the WIM.  */
2116         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2117                 if (!wim->filename)
2118                         return WIMLIB_ERR_NO_FILENAME;
2119                 ret = can_modify_wim(wim);
2120                 if (ret)
2121                         return ret;
2122         }
2123
2124         /* Select the image to mount.  */
2125         ret = select_wim_image(wim, image);
2126         if (ret)
2127                 return ret;
2128
2129         /* Get the metadata for the image to mount.  */
2130         imd = wim_get_current_image_metadata(wim);
2131
2132         if (imd->modified) {
2133                 /* To avoid complicating things, we don't support mounting
2134                  * images to which in-memory modifications have already been
2135                  * made.  */
2136                 ERROR("Cannot mount a modified WIM image!");
2137                 return WIMLIB_ERR_INVALID_PARAM;
2138         }
2139
2140         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2141                 ret = lock_wim_for_append(wim);
2142                 if (ret)
2143                         return ret;
2144         }
2145
2146         /* If the user did not specify an interface for accessing named
2147          * data streams, use the default (extended attributes).  */
2148         if (!(mount_flags & (WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
2149                              WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
2150                              WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)))
2151                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
2152
2153         /* Start initializing the wimfs_context.  */
2154         memset(&ctx, 0, sizeof(struct wimfs_context));
2155         ctx.wim = wim;
2156         ctx.mount_flags = mount_flags;
2157         if (mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
2158                 ctx.default_lookup_flags = LOOKUP_FLAG_ADS_OK;
2159         /* For read-write mount, create the staging directory.  */
2160         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2161                 ret = make_staging_dir(&ctx, staging_dir);
2162                 if (ret)
2163                         goto out_unlock;
2164         }
2165         ctx.owner_uid = getuid();
2166         ctx.owner_gid = getgid();
2167
2168         /* Add each blob referenced by files in the image to a list and
2169          * preemptively double the number of references to each.  This is done
2170          * to allow implementing the WIMLIB_UNMOUNT_FLAG_NEW_IMAGE semantics.
2171          */
2172         INIT_LIST_HEAD(&ctx.orig_blob_list);
2173         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2174                 unsigned i;
2175                 struct wim_inode *inode;
2176                 struct blob_descriptor *blob;
2177
2178                 image_for_each_inode(inode, imd) {
2179                         for (i = 0; i < inode->i_num_streams; i++) {
2180                                 blob = stream_blob(&inode->i_streams[i],
2181                                                    wim->blob_table);
2182                                 if (blob)
2183                                         blob->out_refcnt = 0;
2184                         }
2185                 }
2186
2187                 image_for_each_inode(inode, imd) {
2188                         for (i = 0; i < inode->i_num_streams; i++) {
2189                                 blob = stream_blob(&inode->i_streams[i],
2190                                                    wim->blob_table);
2191                                 if (blob) {
2192                                         if (blob->out_refcnt == 0)
2193                                                 list_add(&blob->orig_blob_list,
2194                                                          &ctx.orig_blob_list);
2195                                         blob->out_refcnt += inode->i_nlink;
2196                                         blob->refcnt += inode->i_nlink;
2197                                 }
2198                         }
2199                 }
2200         }
2201
2202         /* Assign new inode numbers.  */
2203         reassign_inode_numbers(&ctx);
2204
2205         /* If a read-write mount, mark the image as modified.  */
2206         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2207                 imd->modified = 1;
2208
2209         /* Build the FUSE command line.  */
2210
2211         fuse_argc = 0;
2212         fuse_argv[fuse_argc++] = "wimlib";
2213         fuse_argv[fuse_argc++] = (char *)dir;
2214
2215         /* Disable multi-threaded operation.  */
2216         fuse_argv[fuse_argc++] = "-s";
2217
2218         /* Enable FUSE debug mode (don't fork) if requested by the user.  */
2219         if (mount_flags & WIMLIB_MOUNT_FLAG_DEBUG)
2220                 fuse_argv[fuse_argc++] = "-d";
2221
2222         /*
2223          * Build the FUSE mount options:
2224          *
2225          * use_ino
2226          *      FUSE will use the inode numbers we provide.  We want this,
2227          *      because we have inodes and will number them ourselves.
2228          *
2229          * subtype=wimfs
2230          *      Name for our filesystem (main type is "fuse").
2231          *
2232          * hard_remove
2233          *      If an open file is unlinked, unlink it for real rather than
2234          *      renaming it to a hidden file.  Our code supports this; an
2235          *      unlinked inode is retained until all its file descriptors have
2236          *      been closed.
2237          *
2238          * default_permissions
2239          *      FUSE will perform permission checking.  Useful when
2240          *      WIMLIB_MOUNT_FLAG_UNIX_DATA is provided and the WIM image
2241          *      contains the UNIX permissions for each file.
2242          *
2243          * kernel_cache
2244          *      Cache the contents of files.  This will speed up repeated access
2245          *      to files on a mounted WIM image, since they won't need to be
2246          *      decompressed repeatedly.  This option is valid because data in
2247          *      the WIM image should never be changed externally.  (Although, if
2248          *      someone really wanted to they could modify the WIM file or mess
2249          *      with the staging directory; but then they're asking for
2250          *      trouble.)
2251          *
2252          * entry_timeout=1000000000
2253          *      Cache positive name lookups indefinitely, since names can only
2254          *      be added, removed, or modified through the mounted filesystem
2255          *      itself.
2256          *
2257          * negative_timeout=1000000000
2258          *      Cache negative name lookups indefinitely, since names can only
2259          *      be added, removed, or modified through the mounted filesystem
2260          *      itself.
2261          *
2262          * attr_timeout=0
2263          *      Don't cache file/directory attributes.  This is needed as a
2264          *      workaround for the fact that when caching attributes, the high
2265          *      level interface to libfuse considers a file which has several
2266          *      hard-linked names as several different files.  (Otherwise, we
2267          *      could cache our file/directory attributes indefinitely, since
2268          *      they can only be changed through the mounted filesystem itself.)
2269          */
2270         char optstring[256] =
2271                 "use_ino"
2272                 ",subtype=wimfs"
2273                 ",hard_remove"
2274                 ",default_permissions"
2275                 ",kernel_cache"
2276                 ",entry_timeout=1000000000"
2277                 ",negative_timeout=1000000000"
2278                 ",attr_timeout=0"
2279                 ;
2280         fuse_argv[fuse_argc++] = "-o";
2281         fuse_argv[fuse_argc++] = optstring;
2282         if (!(mount_flags & WIMLIB_MOUNT_FLAG_READWRITE))
2283                 strcat(optstring, ",ro");
2284         if (mount_flags & WIMLIB_MOUNT_FLAG_ALLOW_OTHER)
2285                 strcat(optstring, ",allow_other");
2286         fuse_argv[fuse_argc] = NULL;
2287
2288         /* Mount our filesystem.  */
2289         ret = fuse_main(fuse_argc, fuse_argv, &wimfs_operations, &ctx);
2290
2291         /* Cleanup and return.  */
2292         if (ret)
2293                 ret = WIMLIB_ERR_FUSE;
2294         release_extra_refcnts(&ctx);
2295         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2296                 delete_staging_dir(&ctx);
2297 out_unlock:
2298         unlock_wim_for_append(wim);
2299         return ret;
2300 }
2301
2302 struct commit_progress_thread_args {
2303         mqd_t mq;
2304         wimlib_progress_func_t progfunc;
2305         void *progctx;
2306 };
2307
2308 static void *
2309 commit_progress_thread_proc(void *_args)
2310 {
2311         struct commit_progress_thread_args *args = _args;
2312         struct commit_progress_report report;
2313         ssize_t ret;
2314
2315         for (;;) {
2316                 ret = mq_receive(args->mq,
2317                                  (char *)&report, sizeof(report), NULL);
2318                 if (ret == sizeof(report)) {
2319                         call_progress(args->progfunc, report.msg,
2320                                       &report.info, args->progctx);
2321                 } else {
2322                         if (ret == 0 || (ret < 0 && errno != EINTR))
2323                                 break;
2324                 }
2325         }
2326         return NULL;
2327 }
2328
2329 static void
2330 generate_message_queue_name(char name[WIMFS_MQUEUE_NAME_LEN + 1])
2331 {
2332         name[0] = '/';
2333         memcpy(name + 1, "wimfs-", 6);
2334         randomize_char_array_with_alnum(name + 7, WIMFS_MQUEUE_NAME_LEN - 7);
2335         name[WIMFS_MQUEUE_NAME_LEN] = '\0';
2336 }
2337
2338 static mqd_t
2339 create_message_queue(const char *name)
2340 {
2341         bool am_root;
2342         mode_t umask_save;
2343         mode_t mode;
2344         struct mq_attr attr;
2345         mqd_t mq;
2346
2347         memset(&attr, 0, sizeof(attr));
2348         attr.mq_maxmsg = 8;
2349         attr.mq_msgsize = sizeof(struct commit_progress_report);
2350
2351         am_root = (geteuid() == 0);
2352         if (am_root) {
2353                 /* Filesystem mounted as normal user with --allow-other should
2354                  * be able to send messages to root user, if they're doing the
2355                  * unmount.  */
2356                 umask_save = umask(0);
2357                 mode = 0666;
2358         } else {
2359                 mode = 0600;
2360         }
2361         mq = mq_open(name, O_RDWR | O_CREAT | O_EXCL, mode, &attr);
2362         if (am_root)
2363                 umask(umask_save);
2364         return mq;
2365 }
2366
2367 /* Unmount a read-only or read-write mounted WIM image.  */
2368 static int
2369 do_unmount(const char *dir)
2370 {
2371         int status;
2372         ssize_t len;
2373
2374         len = getxattr(dir, "wimfs.unmount", &status, sizeof(int));
2375         if (len == sizeof(int))
2376                 return status;
2377         else if (len < 0 && (errno == EACCES || errno == EPERM))
2378                 return WIMLIB_ERR_NOT_PERMITTED_TO_UNMOUNT;
2379         else
2380                 return WIMLIB_ERR_NOT_A_MOUNTPOINT;
2381 }
2382
2383 static int
2384 set_unmount_info(const char *dir, const struct wimfs_unmount_info *unmount_info)
2385 {
2386         if (!setxattr(dir, "wimfs.unmount_info",
2387                       unmount_info, sizeof(struct wimfs_unmount_info), 0))
2388                 return 0;
2389         else if (errno == EROFS)
2390                 return 0;
2391         else if (errno == EACCES || errno == EPERM)
2392                 return WIMLIB_ERR_NOT_PERMITTED_TO_UNMOUNT;
2393         else
2394                 return WIMLIB_ERR_NOT_A_MOUNTPOINT;
2395 }
2396
2397 static int
2398 do_unmount_discard(const char *dir)
2399 {
2400         int ret;
2401         struct wimfs_unmount_info unmount_info;
2402
2403         memset(&unmount_info, 0, sizeof(unmount_info));
2404
2405         ret = set_unmount_info(dir, &unmount_info);
2406         if (ret)
2407                 return ret;
2408         return do_unmount(dir);
2409 }
2410
2411 /* Unmount a read-write mounted WIM image, committing the changes.  */
2412 static int
2413 do_unmount_commit(const char *dir, int unmount_flags,
2414                   wimlib_progress_func_t progfunc, void *progctx)
2415 {
2416         struct wimfs_unmount_info unmount_info;
2417         mqd_t mq;
2418         struct commit_progress_thread_args args;
2419         pthread_t commit_progress_tid;
2420         int ret;
2421
2422         memset(&unmount_info, 0, sizeof(unmount_info));
2423         unmount_info.unmount_flags = unmount_flags;
2424
2425         /* The current thread will be stuck in getxattr() until the image is
2426          * committed.  Create a thread to handle the progress messages.  */
2427         if (progfunc) {
2428                 generate_message_queue_name(unmount_info.mq_name);
2429
2430                 mq = create_message_queue(unmount_info.mq_name);
2431                 if (mq == (mqd_t)-1) {
2432                         ERROR_WITH_ERRNO("Can't create POSIX message queue");
2433                         return WIMLIB_ERR_MQUEUE;
2434                 }
2435                 args.mq = mq;
2436                 args.progfunc = progfunc;
2437                 args.progctx = progctx;
2438                 ret = pthread_create(&commit_progress_tid, NULL,
2439                                      commit_progress_thread_proc, &args);
2440                 if (ret) {
2441                         errno = ret;
2442                         ERROR_WITH_ERRNO("Can't create thread");
2443                         ret = WIMLIB_ERR_NOMEM;
2444                         goto out_delete_mq;
2445                 }
2446                 unmount_info.unmount_flags |= WIMLIB_UNMOUNT_FLAG_SEND_PROGRESS;
2447         }
2448
2449         ret = set_unmount_info(dir, &unmount_info);
2450         if (!ret)
2451                 ret = do_unmount(dir);
2452         if (progfunc) {
2453                 /* Terminate the progress thread.  */
2454                 char empty[1];
2455                 mq_send(mq, empty, 0, 1);
2456                 pthread_join(commit_progress_tid, NULL);
2457         }
2458 out_delete_mq:
2459         if (progfunc) {
2460                 mq_close(mq);
2461                 mq_unlink(unmount_info.mq_name);
2462         }
2463         return ret;
2464 }
2465
2466 static int
2467 begin_unmount(const char *dir, int unmount_flags, int *mount_flags_ret,
2468               wimlib_progress_func_t progfunc, void *progctx)
2469 {
2470         int mount_flags;
2471         int mounted_image;
2472         int wim_filename_len;
2473         union wimlib_progress_info progress;
2474
2475         if (getxattr(dir, "wimfs.mount_flags",
2476                      &mount_flags, sizeof(int)) != sizeof(int))
2477                 return WIMLIB_ERR_NOT_A_MOUNTPOINT;
2478
2479         *mount_flags_ret = mount_flags;
2480
2481         if (!progfunc)
2482                 return 0;
2483
2484         if (getxattr(dir, "wimfs.mounted_image",
2485                      &mounted_image, sizeof(int)) != sizeof(int))
2486                 return WIMLIB_ERR_NOT_A_MOUNTPOINT;
2487
2488         wim_filename_len = getxattr(dir, "wimfs.wim_filename", NULL, 0);
2489         if (wim_filename_len < 0)
2490                 return WIMLIB_ERR_NOT_A_MOUNTPOINT;
2491
2492         char wim_filename[wim_filename_len + 1];
2493         if (getxattr(dir, "wimfs.wim_filename",
2494                      wim_filename, wim_filename_len) != wim_filename_len)
2495                 return WIMLIB_ERR_NOT_A_MOUNTPOINT;
2496         wim_filename[wim_filename_len] = '\0';
2497
2498         progress.unmount.mountpoint = dir;
2499         progress.unmount.mounted_wim = wim_filename;
2500         progress.unmount.mounted_image = mounted_image;
2501         progress.unmount.mount_flags = mount_flags;
2502         progress.unmount.unmount_flags = unmount_flags;
2503
2504         return call_progress(progfunc, WIMLIB_PROGRESS_MSG_UNMOUNT_BEGIN,
2505                              &progress, progctx);
2506 }
2507
2508 /* API function documented in wimlib.h  */
2509 WIMLIBAPI int
2510 wimlib_unmount_image_with_progress(const char *dir, int unmount_flags,
2511                                    wimlib_progress_func_t progfunc, void *progctx)
2512 {
2513         int mount_flags;
2514         int ret;
2515
2516         ret = wimlib_global_init(WIMLIB_INIT_FLAG_ASSUME_UTF8);
2517         if (ret)
2518                 return ret;
2519
2520         if (unmount_flags & ~(WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY |
2521                               WIMLIB_UNMOUNT_FLAG_COMMIT |
2522                               WIMLIB_UNMOUNT_FLAG_REBUILD |
2523                               WIMLIB_UNMOUNT_FLAG_RECOMPRESS |
2524                               WIMLIB_UNMOUNT_FLAG_FORCE |
2525                               WIMLIB_UNMOUNT_FLAG_NEW_IMAGE))
2526                 return WIMLIB_ERR_INVALID_PARAM;
2527
2528         ret = begin_unmount(dir, unmount_flags, &mount_flags,
2529                             progfunc, progctx);
2530         if (ret)
2531                 return ret;
2532
2533         if ((unmount_flags & WIMLIB_UNMOUNT_FLAG_COMMIT) &&
2534             (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE))
2535                 return do_unmount_commit(dir, unmount_flags,
2536                                          progfunc, progctx);
2537         else
2538                 return do_unmount_discard(dir);
2539 }
2540
2541 #else /* WITH_FUSE */
2542
2543
2544 static int
2545 mount_unsupported_error(void)
2546 {
2547 #if defined(__WIN32__)
2548         ERROR("Sorry-- Mounting WIM images is not supported on Windows!");
2549 #else
2550         ERROR("wimlib was compiled with --without-fuse, which disables support "
2551               "for mounting WIMs.");
2552 #endif
2553         return WIMLIB_ERR_UNSUPPORTED;
2554 }
2555
2556 WIMLIBAPI int
2557 wimlib_unmount_image_with_progress(const tchar *dir, int unmount_flags,
2558                                    wimlib_progress_func_t progfunc, void *progctx)
2559 {
2560         return mount_unsupported_error();
2561 }
2562
2563 WIMLIBAPI int
2564 wimlib_mount_image(WIMStruct *wim, int image, const tchar *dir,
2565                    int mount_flags, const tchar *staging_dir)
2566 {
2567         return mount_unsupported_error();
2568 }
2569
2570 #endif /* !WITH_FUSE */
2571
2572 WIMLIBAPI int
2573 wimlib_unmount_image(const tchar *dir, int unmount_flags)
2574 {
2575         return wimlib_unmount_image_with_progress(dir, unmount_flags, NULL, NULL);
2576 }