]> wimlib.net Git - wimlib/blob - src/mount.c
Remove more trailing whitespace
[wimlib] / src / mount.c
1 /*
2  * mount.c
3  *
4  * This file implements mounting of WIM files using FUSE, which stands for
5  * Filesystem in Userspace.  FUSE allows a filesystem to be implemented in a
6  * userspace process by implementing the filesystem primitives--- read(),
7  * write(), readdir(), etc.
8  */
9
10 /*
11  * Copyright (C) 2012 Eric Biggers
12  *
13  * This file is part of wimlib, a library for working with WIM files.
14  *
15  * wimlib is free software; you can redistribute it and/or modify it under the
16  * terms of the GNU General Public License as published by the Free
17  * Software Foundation; either version 3 of the License, or (at your option)
18  * any later version.
19  *
20  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
21  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
22  * A PARTICULAR PURPOSE. See the GNU General Public License for more
23  * details.
24  *
25  * You should have received a copy of the GNU General Public License
26  * along with wimlib; if not, see http://www.gnu.org/licenses/.
27  */
28
29 #include "wimlib_internal.h"
30
31 #ifdef WITH_FUSE
32
33 #include "sha1.h"
34 #include "lookup_table.h"
35 #include "xml.h"
36 #include "io.h"
37 #include "timestamp.h"
38 #include <stdlib.h>
39 #include <unistd.h>
40 #include <sys/wait.h>
41 #define FUSE_USE_VERSION 26
42 #include <errno.h>
43 #include <string.h>
44 #include <sys/time.h>
45 #include <fuse.h>
46 #include <ftw.h>
47 #include <mqueue.h>
48 #include <utime.h>
49
50 #ifdef ENABLE_XATTR
51 #include <attr/xattr.h>
52 #endif
53
54 /* File descriptor to a file open on the WIM filesystem. */
55 struct wimlib_fd {
56         struct inode *f_inode;
57         struct lookup_table_entry *f_lte;
58         int staging_fd;
59         u16 idx;
60         u32 stream_id;
61 };
62
63 /* The WIMStruct for the mounted WIM. */
64 static WIMStruct *w;
65
66 /* Working directory when `imagex mount' is run. */
67 static const char *working_directory;
68
69 /* Name of the staging directory for a read-write mount.  Whenever a new file is
70  * created, it is done so in the staging directory.  Furthermore, whenever a
71  * file in the WIM is modified, it is extracted to the staging directory.  If
72  * changes are commited when the WIM is unmounted, the file resources are merged
73  * in from the staging directory when writing the new WIM. */
74 static char *staging_dir_name;
75 static size_t staging_dir_name_len;
76
77 /* Flags passed to wimlib_mount(). */
78 static int mount_flags;
79
80 /* Name of the directory on which the WIM file is mounted. */
81 static const char *mount_dir;
82
83 /* Next inode number to be assigned. */
84 static u64 next_ino;
85
86 /* List of lookup table entries in the staging directory */
87 static LIST_HEAD(staging_list);
88
89 static inline int get_lookup_flags()
90 {
91         if (mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
92                 return LOOKUP_FLAG_ADS_OK;
93         else
94                 return 0;
95 }
96
97 /* Returns nonzero if write permission is requested on the file open flags */
98 static inline int flags_writable(int open_flags)
99 {
100         return open_flags & (O_RDWR | O_WRONLY);
101 }
102
103 /*
104  * Allocate a file descriptor for a stream.
105  *
106  * @inode:      inode containing the stream we're opening
107  * @stream_id:  ID of the stream we're opening
108  * @lte:        Lookup table entry for the stream (may be NULL)
109  * @fd_ret:     Return the allocated file descriptor if successful.
110  *
111  * Return 0 iff successful or error code if unsuccessful.
112  */
113 static int alloc_wimlib_fd(struct inode *inode,
114                            u32 stream_id,
115                            struct lookup_table_entry *lte,
116                            struct wimlib_fd **fd_ret)
117 {
118         static const u16 fds_per_alloc = 8;
119         static const u16 max_fds = 0xffff;
120
121         DEBUG("Allocating fd for stream ID %u from inode %lx (open = %u, allocated = %u)",
122               stream_id, inode->ino, inode->num_opened_fds,
123               inode->num_allocated_fds);
124
125         if (inode->num_opened_fds == inode->num_allocated_fds) {
126                 struct wimlib_fd **fds;
127                 u16 num_new_fds;
128
129                 if (inode->num_allocated_fds == max_fds)
130                         return -EMFILE;
131                 num_new_fds = min(fds_per_alloc,
132                                   max_fds - inode->num_allocated_fds);
133
134                 fds = REALLOC(inode->fds,
135                               (inode->num_allocated_fds + num_new_fds) *
136                                 sizeof(inode->fds[0]));
137                 if (!fds)
138                         return -ENOMEM;
139                 memset(&fds[inode->num_allocated_fds], 0,
140                        num_new_fds * sizeof(fds[0]));
141                 inode->fds = fds;
142                 inode->num_allocated_fds += num_new_fds;
143         }
144         for (u16 i = 0; ; i++) {
145                 if (!inode->fds[i]) {
146                         struct wimlib_fd *fd = CALLOC(1, sizeof(*fd));
147                         if (!fd)
148                                 return -ENOMEM;
149                         fd->f_inode    = inode;
150                         fd->f_lte      = lte;
151                         fd->staging_fd = -1;
152                         fd->idx        = i;
153                         fd->stream_id  = stream_id;
154                         *fd_ret        = fd;
155                         inode->fds[i]  = fd;
156                         inode->num_opened_fds++;
157                         if (lte)
158                                 lte->num_opened_fds++;
159                         DEBUG("Allocated fd");
160                         return 0;
161                 }
162         }
163 }
164
165 static void inode_put_fd(struct inode *inode, struct wimlib_fd *fd)
166 {
167         wimlib_assert(fd);
168         wimlib_assert(inode);
169         wimlib_assert(fd->f_inode == inode);
170         wimlib_assert(inode->num_opened_fds);
171         wimlib_assert(fd->idx < inode->num_opened_fds);
172         wimlib_assert(inode->fds[fd->idx] == fd);
173
174         inode->fds[fd->idx] = NULL;
175         FREE(fd);
176         if (--inode->num_opened_fds == 0 && inode->link_count == 0)
177                 free_inode(inode);
178 }
179
180 static int lte_put_fd(struct lookup_table_entry *lte, struct wimlib_fd *fd)
181 {
182         wimlib_assert(fd);
183         wimlib_assert(fd->f_lte == lte);
184
185         if (!lte) /* Empty stream with no lookup table entry */
186                 return 0;
187
188         /* Close staging file descriptor if needed. */
189
190         if (lte->resource_location == RESOURCE_IN_STAGING_FILE
191              && fd->staging_fd != -1)
192         {
193                 if (close(fd->staging_fd) != 0) {
194                         ERROR_WITH_ERRNO("Failed to close staging file");
195                         return -errno;
196                 }
197         }
198         lte_decrement_num_opened_fds(lte, w->lookup_table);
199         return 0;
200 }
201
202 /* Close a file descriptor. */
203 static int close_wimlib_fd(struct wimlib_fd *fd)
204 {
205         int ret;
206         wimlib_assert(fd);
207         DEBUG("Closing fd (inode = %lu, opened = %u, allocated = %u)",
208               fd->f_inode->ino, fd->f_inode->num_opened_fds,
209               fd->f_inode->num_allocated_fds);
210         ret = lte_put_fd(fd->f_lte, fd);
211         if (ret != 0)
212                 return ret;
213
214         inode_put_fd(fd->f_inode, fd);
215         return 0;
216 }
217
218 /* Remove a dentry; i.e. remove a reference to the corresponding inode.
219  *
220  * If there are no remaining references to the inode either through dentries or
221  * open file descriptors, the inode is freed.  Otherwise, the inode is not
222  * removed, but the dentry is unlinked and freed.
223  *
224  * Either way, all lookup table entries referenced by the inode have their
225  * reference count decremented.  If a lookup table entry has no open file
226  * descriptors and no references remaining, it is freed, and the staging file is
227  * unlinked.
228  */
229 static void remove_dentry(struct dentry *dentry,
230                           struct lookup_table *lookup_table)
231 {
232         struct inode *inode = dentry->d_inode;
233         struct lookup_table_entry *lte;
234         unsigned i;
235
236         for (i = 0; i <= inode->num_ads; i++) {
237                 lte = inode_stream_lte_resolved(inode, i);
238                 if (lte)
239                         lte_decrement_refcnt(lte, lookup_table);
240         }
241         unlink_dentry(dentry);
242         put_dentry(dentry);
243 }
244
245 /* Creates a new staging file and returns its file descriptor opened for
246  * writing.
247  *
248  * @name_ret: A location into which the a pointer to the newly allocated name of
249  *                      the staging file is stored.
250  * @return:  The file descriptor for the new file.  Returns -1 and sets errno on
251  *              error, for any reason possible from the creat() function.
252  */
253 static int create_staging_file(char **name_ret, int open_flags)
254 {
255         size_t name_len;
256         char *name;
257         struct stat stbuf;
258         int fd;
259         int errno_save;
260
261         name_len = staging_dir_name_len + 1 + SHA1_HASH_SIZE;
262         name = MALLOC(name_len + 1);
263         if (!name) {
264                 errno = ENOMEM;
265                 return -1;
266         }
267
268         do {
269
270                 memcpy(name, staging_dir_name, staging_dir_name_len);
271                 name[staging_dir_name_len] = '/';
272                 randomize_char_array_with_alnum(name + staging_dir_name_len + 1,
273                                                 SHA1_HASH_SIZE);
274                 name[name_len] = '\0';
275
276
277         /* Just in case, verify that the randomly generated name doesn't name an
278          * existing file, and try again if so  */
279         } while (stat(name, &stbuf) == 0);
280
281         if (errno != ENOENT)
282                 /* other error! */
283                 return -1;
284
285         /* doesn't exist--- ok */
286
287         DEBUG("Creating staging file `%s'", name);
288
289         fd = open(name, open_flags | O_CREAT | O_TRUNC, 0600);
290         if (fd == -1) {
291                 errno_save = errno;
292                 FREE(name);
293                 errno = errno_save;
294         } else {
295                 *name_ret = name;
296         }
297         return fd;
298 }
299
300 /*
301  * Extract a WIM resource to the staging directory.
302  *
303  * @inode:  Inode that contains the stream we are extracting
304  *
305  * @stream_id: Identifier for the stream (it stays constant even if the indices
306  * of the stream entries are changed)
307  *
308  * @lte: Pointer to pointer to the lookup table entry for the stream we need to
309  * extract, or NULL if there was no lookup table entry present for the stream
310  *
311  * @size:  Number of bytes of the stream we want to extract (this supports the
312  * wimfs_truncate() function).
313  */
314 static int extract_resource_to_staging_dir(struct inode *inode,
315                                            u32 stream_id,
316                                            struct lookup_table_entry **lte,
317                                            off_t size)
318 {
319         char *staging_file_name;
320         int ret;
321         int fd;
322         struct lookup_table_entry *old_lte, *new_lte;
323
324         DEBUG("Extracting resource to staging dir: inode %"PRIu64", "
325               "stream id %"PRIu32, inode->ino, stream_id);
326
327         old_lte = *lte;
328         fd = create_staging_file(&staging_file_name, O_WRONLY);
329         if (fd == -1)
330                 return -errno;
331
332         if (old_lte)
333                 ret = extract_wim_resource_to_fd(old_lte, fd, size);
334         else
335                 ret = 0;
336         if (ret != 0 || close(fd) != 0) {
337                 if (errno != 0)
338                         ret = -errno;
339                 else
340                         ret = -EIO;
341                 close(fd);
342                 goto out_delete_staging_file;
343         }
344
345         if (old_lte && inode->link_count == old_lte->refcnt) {
346                 /* The reference count of the existing lookup table
347                  * entry is the same as the link count of the inode that
348                  * contains the stream we're opening.  Therefore, ALL
349                  * the references to the lookup table entry correspond
350                  * to the stream we're trying to extract, so the lookup
351                  * table entry can be re-used.  */
352                 DEBUG("Re-using lookup table entry");
353                 lookup_table_unlink(w->lookup_table, old_lte);
354                 new_lte = old_lte;
355         } else {
356                 if (old_lte) {
357                         /* There's an existing lookup table entry, but its
358                          * reference count is creater than the link count for
359                          * the inode containing a stream we're opening.
360                          * Therefore, we need to split the lookup table entry.
361                          * */
362                         wimlib_assert(old_lte->refcnt > inode->link_count);
363                         DEBUG("Splitting lookup table entry "
364                               "(inode->link_count = %zu, old_lte->refcnt = %u)",
365                               inode->link_count, old_lte->refcnt);
366
367                 }
368
369                 new_lte = new_lookup_table_entry();
370                 if (!new_lte) {
371                         ret = -ENOMEM;
372                         goto out_delete_staging_file;
373                 }
374
375                 /* There may already be open file descriptors to this stream if
376                  * it's previously been opened read-only, but just now we're
377                  * opening it read-write.  Identify those file descriptors and
378                  * change their lookup table entry pointers to point to the new
379                  * lookup table entry, and open staging file descriptors for
380                  * them.
381                  *
382                  * At the same time, we need to count the number of these opened
383                  * file descriptors to the new lookup table entry.  If there's
384                  * an old lookup table entry, this number needs to be subtracted
385                  * from the fd's opened to the old entry. */
386                 for (u16 i = 0, j = 0; j < inode->num_opened_fds; i++) {
387                         struct wimlib_fd *fd = inode->fds[i];
388                         if (fd) {
389                                 if (fd->stream_id == stream_id) {
390                                         wimlib_assert(fd->f_lte == old_lte);
391                                         wimlib_assert(fd->staging_fd == -1);
392                                         fd->f_lte = new_lte;
393                                         new_lte->num_opened_fds++;
394                                         fd->staging_fd = open(staging_file_name, O_RDONLY);
395                                         if (fd->staging_fd == -1) {
396                                                 ret = -errno;
397                                                 goto out_revert_fd_changes;
398                                         }
399                                 }
400                                 j++;
401                         }
402                 }
403                 DEBUG("%zu fd's were already opened to the file we extracted",
404                       new_lte->num_opened_fds);
405                 if (old_lte) {
406                         old_lte->num_opened_fds -= new_lte->num_opened_fds;
407                         old_lte->refcnt -= inode->link_count;
408                 }
409         }
410
411         new_lte->resource_entry.original_size = size;
412         new_lte->refcnt                       = inode->link_count;
413         new_lte->resource_location            = RESOURCE_IN_STAGING_FILE;
414         new_lte->staging_file_name            = staging_file_name;
415         new_lte->lte_inode                    = inode;
416         random_hash(new_lte->hash);
417
418         if (stream_id == 0)
419                 inode->lte = new_lte;
420         else
421                 for (u16 i = 0; i < inode->num_ads; i++)
422                         if (inode->ads_entries[i].stream_id == stream_id)
423                                 inode->ads_entries[i].lte = new_lte;
424
425         lookup_table_insert(w->lookup_table, new_lte);
426         list_add(&new_lte->staging_list, &staging_list);
427         *lte = new_lte;
428         return 0;
429 out_revert_fd_changes:
430         for (u16 i = 0, j = 0; j < new_lte->num_opened_fds; i++) {
431                 struct wimlib_fd *fd = inode->fds[i];
432                 if (fd && fd->stream_id == stream_id && fd->f_lte == new_lte) {
433                         fd->f_lte = old_lte;
434                         if (fd->staging_fd != -1) {
435                                 close(fd->staging_fd);
436                                 fd->staging_fd = -1;
437                         }
438                         j++;
439                 }
440         }
441 out_free_new_lte:
442         free_lookup_table_entry(new_lte);
443 out_delete_staging_file:
444         unlink(staging_file_name);
445         FREE(staging_file_name);
446         return ret;
447 }
448
449 /*
450  * Creates a randomly named staging directory and returns its name into the
451  * static variable staging_dir_name.
452  *
453  * If the staging directory cannot be created, staging_dir_name is set to NULL.
454  * */
455 static void make_staging_dir()
456 {
457         /* XXX Give the user an option of where to stage files */
458
459         static char prefix[] = "wimlib-staging-";
460         static const size_t prefix_len = 15;
461         static const size_t suffix_len = 10;
462
463         size_t pwd_len = strlen(working_directory);
464
465         staging_dir_name_len = pwd_len + 1 + prefix_len + suffix_len;
466
467         staging_dir_name = MALLOC(staging_dir_name_len + 1);
468         if (!staging_dir_name) {
469                 ERROR("Out of memory");
470                 return;
471         }
472
473         memcpy(staging_dir_name, working_directory, pwd_len);
474         staging_dir_name[pwd_len] = '/';
475         memcpy(staging_dir_name + pwd_len + 1, prefix, prefix_len);
476         randomize_char_array_with_alnum(staging_dir_name + pwd_len + 1 + prefix_len,
477                                 suffix_len);
478         staging_dir_name[staging_dir_name_len] = '\0';
479
480         if (mkdir(staging_dir_name, 0700) != 0) {
481                 ERROR_WITH_ERRNO("Failed to create temporary directory `%s'",
482                                  staging_dir_name);
483                 FREE(staging_dir_name);
484                 staging_dir_name = NULL;
485         }
486 }
487
488 static int remove_file_or_directory(const char *fpath, const struct stat *sb,
489                                     int typeflag, struct FTW *ftwbuf)
490 {
491         if (remove(fpath) == 0)
492                 return 0;
493         else
494                 return WIMLIB_ERR_DELETE_STAGING_DIR;
495 }
496
497
498 /*
499  * Deletes the staging directory and all the files contained in it.
500  */
501 static int delete_staging_dir()
502 {
503         int ret;
504
505         ret = nftw(staging_dir_name, remove_file_or_directory,10, FTW_DEPTH);
506         staging_dir_name = NULL;
507         return ret;
508 }
509
510 /* Name and message queue descriptors for message queues between the filesystem
511  * daemon process and the unmount process.  These are used when the filesystem
512  * is unmounted and the process running wimlib_mount() (i.e. the `imagex
513  * unmount' command) needs to communicate with the filesystem daemon running
514  * fuse_main() (i.e. that spawned by the `imagex mount' or `imagex mountrw'
515  * commands */
516 static char *unmount_to_daemon_mq_name;
517 static char *daemon_to_unmount_mq_name;
518 static mqd_t unmount_to_daemon_mq;
519 static mqd_t daemon_to_unmount_mq;
520
521 /* Simple function that returns the concatenation of 4 strings. */
522 static char *strcat_dup(const char *s1, const char *s2, const char *s3,
523                         const char *s4)
524 {
525         size_t len = strlen(s1) + strlen(s2) + strlen(s3) + strlen(s4) + 1;
526         char *p = MALLOC(len);
527         if (!p)
528                 return NULL;
529         p = strcpy(p, s1);
530         p = strcat(p, s2);
531         p = strcat(p, s3);
532         return strcat(p, s4);
533 }
534
535 /* Removes trailing forward slashes in a string. */
536 static void remove_trailing_slashes(char *s)
537 {
538         long len = strlen(s);
539         for (long i = len - 1; i >= 1; i--) {
540                 if (s[i] == '/')
541                         s[i] = '\0';
542                 else
543                         break;
544         }
545 }
546
547 /* Changes forward slashes to underscores in a string. */
548 static void s_slashes_underscores_g(char *s)
549 {
550         while (*s) {
551                 if (*s == '/')
552                         *s = '_';
553                 s++;
554         }
555 }
556
557 /*
558  * Opens two POSIX message queue: one for sending messages from the unmount
559  * process to the daemon process, and one to go the other way.  The names of the
560  * message queues, which must be system-wide unique, are be based on the mount
561  * point.  (There of course is still a possibility of a collision if one were to
562  * unmount two identically named directories simultaneously...)
563  *
564  * @daemon specifies whether the calling process is the filesystem daemon or the
565  * unmount process.
566  */
567 static int open_message_queues(bool daemon)
568 {
569         static const char *slash = "/";
570         static const char *prefix = "wimlib-";
571         static const char *u2d_suffix = "unmount-to-daemon-mq";
572         static const char *d2u_suffix = "daemon-to-unmount-mq";
573
574         const char *mount_dir_basename = path_basename(mount_dir);
575         int flags;
576         int ret;
577
578         unmount_to_daemon_mq_name = strcat_dup(slash, mount_dir_basename,
579                                                 prefix, u2d_suffix);
580         if (!unmount_to_daemon_mq_name) {
581                 ERROR("Out of memory");
582                 return WIMLIB_ERR_NOMEM;
583         }
584         daemon_to_unmount_mq_name = strcat_dup(slash, mount_dir_basename,
585                                                 prefix, d2u_suffix);
586         if (!daemon_to_unmount_mq_name) {
587                 ERROR("Out of memory");
588                 ret = WIMLIB_ERR_NOMEM;
589                 goto err1;
590         }
591
592         remove_trailing_slashes(unmount_to_daemon_mq_name);
593         remove_trailing_slashes(daemon_to_unmount_mq_name);
594         s_slashes_underscores_g(unmount_to_daemon_mq_name + 1);
595         s_slashes_underscores_g(daemon_to_unmount_mq_name + 1);
596
597         if (daemon)
598                 flags = O_RDONLY | O_CREAT;
599         else
600                 flags = O_WRONLY | O_CREAT;
601
602         unmount_to_daemon_mq = mq_open(unmount_to_daemon_mq_name, flags,
603                                        0700, NULL);
604
605         if (unmount_to_daemon_mq == (mqd_t)-1) {
606                 ERROR_WITH_ERRNO("mq_open()");
607                 ret = WIMLIB_ERR_MQUEUE;
608                 goto err2;
609         }
610
611         if (daemon)
612                 flags = O_WRONLY | O_CREAT;
613         else
614                 flags = O_RDONLY | O_CREAT;
615
616         daemon_to_unmount_mq = mq_open(daemon_to_unmount_mq_name, flags,
617                                        0700, NULL);
618
619         if (daemon_to_unmount_mq == (mqd_t)-1) {
620                 ERROR_WITH_ERRNO("mq_open()");
621                 ret = WIMLIB_ERR_MQUEUE;
622                 goto err3;
623         }
624         return 0;
625 err3:
626         mq_close(unmount_to_daemon_mq);
627         mq_unlink(unmount_to_daemon_mq_name);
628 err2:
629         FREE(daemon_to_unmount_mq_name);
630 err1:
631         FREE(unmount_to_daemon_mq_name);
632         return ret;
633 }
634
635 static int mq_get_msgsize(mqd_t mq)
636 {
637         static const char *msgsize_max_file = "/proc/sys/fs/mqueue/msgsize_max";
638         FILE *fp;
639         struct mq_attr attr;
640         int msgsize;
641
642         if (mq_getattr(unmount_to_daemon_mq, &attr) == 0) {
643                 msgsize = attr.mq_msgsize;
644         } else {
645                 ERROR_WITH_ERRNO("mq_getattr()");
646                 ERROR("Attempting to read %s", msgsize_max_file);
647                 fp = fopen(msgsize_max_file, "rb");
648                 if (fp) {
649                         if (fscanf(fp, "%d", &msgsize) != 1) {
650                                 ERROR("Assuming message size of 8192");
651                                 msgsize = 8192;
652                         }
653                         fclose(fp);
654                 } else {
655                         ERROR_WITH_ERRNO("Failed to open the file `%s'",
656                                          msgsize_max_file);
657                         ERROR("Assuming message size of 8192");
658                         msgsize = 8192;
659                 }
660         }
661         return msgsize;
662 }
663
664 /* Closes the message queues, which are allocated in static variables */
665 static void close_message_queues()
666 {
667         mq_close(unmount_to_daemon_mq);
668         mq_close(daemon_to_unmount_mq);
669         mq_unlink(unmount_to_daemon_mq_name);
670         mq_unlink(daemon_to_unmount_mq_name);
671 }
672
673 static int wimfs_access(const char *path, int mask)
674 {
675         /* Permissions not implemented */
676         return 0;
677 }
678
679 static void inode_update_lte_ptr(struct inode *inode,
680                                  struct lookup_table_entry *old_lte,
681                                  struct lookup_table_entry *new_lte)
682 {
683         if (inode->lte == old_lte) {
684                 inode->lte = new_lte;
685         } else {
686                 for (unsigned i = 0; i < inode->num_ads; i++) {
687                         if (inode->ads_entries[i].lte == old_lte) {
688                                 inode->ads_entries[i].lte = new_lte;
689                                 break;
690                         }
691                 }
692         }
693 }
694
695 static int update_lte_of_staging_file(struct lookup_table_entry *lte,
696                                       struct lookup_table *table)
697 {
698         struct lookup_table_entry *duplicate_lte;
699         int ret;
700         u8 hash[SHA1_HASH_SIZE];
701         struct stat stbuf;
702
703         wimlib_assert(lte->resource_location == RESOURCE_IN_STAGING_FILE);
704         wimlib_assert(lte->staging_file_name);
705
706         ret = sha1sum(lte->staging_file_name, hash);
707         if (ret != 0)
708                 return ret;
709
710         lookup_table_unlink(table, lte);
711
712         duplicate_lte = __lookup_resource(table, hash);
713
714         if (duplicate_lte) {
715                 /* Merge duplicate lookup table entries */
716                 duplicate_lte->refcnt += lte->refcnt;
717                 list_del(&lte->staging_list);
718                 inode_update_lte_ptr(lte->lte_inode, lte, duplicate_lte);
719                 free_lookup_table_entry(lte);
720         } else {
721                 if (stat(lte->staging_file_name, &stbuf) != 0) {
722                         ERROR_WITH_ERRNO("Failed to stat `%s'", lte->staging_file_name);
723                         return WIMLIB_ERR_STAT;
724                 }
725                 if (stbuf.st_size == 0) {
726                         /* Zero-length stream.  No lookup table entry needed. */
727                         inode_update_lte_ptr(lte->lte_inode, lte, NULL);
728                         free_lookup_table_entry(lte);
729                 } else {
730                         wimlib_assert(&lte->file_on_disk == &lte->staging_file_name);
731                         lte->resource_entry.original_size = stbuf.st_size;
732                         lte->resource_entry.size = stbuf.st_size;
733                         lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
734                         lte->lte_inode = NULL;
735                         copy_hash(lte->hash, hash);
736                         lookup_table_insert(table, lte);
737                 }
738         }
739         return 0;
740 }
741
742 static int inode_close_fds(struct inode *inode)
743 {
744         u16 num_opened_fds = inode->num_opened_fds;
745         for (u16 i = 0, j = 0; j < num_opened_fds; i++) {
746                 struct wimlib_fd *fd = inode->fds[i];
747                 if (fd) {
748                         wimlib_assert(fd->f_inode == inode);
749                         int ret = close_wimlib_fd(fd);
750                         if (ret != 0)
751                                 return ret;
752                         j++;
753                 }
754         }
755         return 0;
756 }
757
758 /* Overwrites the WIM file, with changes saved. */
759 static int rebuild_wim(WIMStruct *w, bool check_integrity)
760 {
761         int ret;
762         struct lookup_table_entry *lte, *tmp;
763
764
765         DEBUG("Closing all staging file descriptors.");
766         list_for_each_entry(lte, &staging_list, staging_list) {
767                 ret = inode_close_fds(lte->lte_inode);
768                 if (ret != 0)
769                         return ret;
770         }
771
772         DEBUG("Calculating SHA1 checksums for all new staging files.");
773         list_for_each_entry_safe(lte, tmp, &staging_list, staging_list) {
774                 ret = update_lte_of_staging_file(lte, w->lookup_table);
775                 if (ret != 0)
776                         return ret;
777         }
778
779         xml_update_image_info(w, w->current_image);
780
781         ret = wimlib_overwrite(w, check_integrity);
782         if (ret != 0) {
783                 ERROR("Failed to commit changes");
784                 return ret;
785         }
786         return ret;
787 }
788
789 /* Called when the filesystem is unmounted. */
790 static void wimfs_destroy(void *p)
791 {
792         /* For read-write mounts, the `imagex unmount' command, which is
793          * running in a separate process and is executing the
794          * wimlib_unmount() function, will send this process a byte
795          * through a message queue that indicates whether the --commit
796          * option was specified or not. */
797
798         int msgsize;
799         struct timespec timeout;
800         struct timeval now;
801         ssize_t bytes_received;
802         int ret;
803         char commit;
804         char check_integrity;
805         char status;
806
807         ret = open_message_queues(true);
808         if (ret != 0)
809                 exit(1);
810
811         msgsize = mq_get_msgsize(unmount_to_daemon_mq);
812         char msg[msgsize];
813         msg[0] = 0;
814         msg[1] = 0;
815
816         /* Wait at most 3 seconds before giving up and discarding changes. */
817         gettimeofday(&now, NULL);
818         timeout.tv_sec = now.tv_sec + 3;
819         timeout.tv_nsec = now.tv_usec * 1000;
820         DEBUG("Waiting for message telling us whether to commit or not, and "
821               "whether to include integrity checks.");
822
823         bytes_received = mq_timedreceive(unmount_to_daemon_mq, msg,
824                                          msgsize, NULL, &timeout);
825         commit = msg[0];
826         check_integrity = msg[1];
827         if (bytes_received == -1) {
828                 if (errno == ETIMEDOUT) {
829                         ERROR("Timed out.");
830                 } else {
831                         ERROR_WITH_ERRNO("mq_timedreceive()");
832                 }
833                 ERROR("Not committing.");
834         } else {
835                 DEBUG("Received message: [%d %d]", msg[0], msg[1]);
836         }
837
838         status = 0;
839         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
840                 if (commit) {
841                         status = chdir(working_directory);
842                         if (status != 0) {
843                                 ERROR_WITH_ERRNO("chdir()");
844                                 status = WIMLIB_ERR_NOTDIR;
845                                 goto done;
846                         }
847                         status = rebuild_wim(w, (check_integrity != 0));
848                 }
849                 ret = delete_staging_dir();
850                 if (ret != 0) {
851                         ERROR_WITH_ERRNO("Failed to delete the staging "
852                                          "directory");
853                         if (status == 0)
854                                 status = ret;
855                 }
856         } else {
857                 DEBUG("Read-only mount");
858         }
859 done:
860         DEBUG("Sending status %u", status);
861         ret = mq_send(daemon_to_unmount_mq, &status, 1, 1);
862         if (ret == -1)
863                 ERROR_WITH_ERRNO("Failed to send status to unmount process");
864         close_message_queues();
865 }
866
867 #if 0
868 static int wimfs_fallocate(const char *path, int mode,
869                            off_t offset, off_t len, struct fuse_file_info *fi)
870 {
871         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
872         wimlib_assert(fd->staging_fd != -1);
873         return fallocate(fd->staging_fd, mode, offset, len);
874 }
875
876 #endif
877
878 static int wimfs_fgetattr(const char *path, struct stat *stbuf,
879                           struct fuse_file_info *fi)
880 {
881         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
882         return inode_to_stbuf(fd->f_inode, fd->f_lte, stbuf);
883 }
884
885 static int wimfs_ftruncate(const char *path, off_t size,
886                            struct fuse_file_info *fi)
887 {
888         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
889         int ret = ftruncate(fd->staging_fd, size);
890         if (ret != 0)
891                 return ret;
892         if (fd->f_lte && size < fd->f_lte->resource_entry.original_size)
893                 fd->f_lte->resource_entry.original_size = size;
894         return 0;
895 }
896
897 /*
898  * Fills in a `struct stat' that corresponds to a file or directory in the WIM.
899  */
900 static int wimfs_getattr(const char *path, struct stat *stbuf)
901 {
902         struct dentry *dentry;
903         struct lookup_table_entry *lte;
904         int ret;
905
906         ret = lookup_resource(w, path,
907                               get_lookup_flags() | LOOKUP_FLAG_DIRECTORY_OK,
908                               &dentry, &lte, NULL);
909         if (ret != 0)
910                 return ret;
911         return inode_to_stbuf(dentry->d_inode, lte, stbuf);
912 }
913
914 #ifdef ENABLE_XATTR
915 /* Read an alternate data stream through the XATTR interface, or get its size */
916 static int wimfs_getxattr(const char *path, const char *name, char *value,
917                           size_t size)
918 {
919         int ret;
920         struct inode *inode;
921         struct ads_entry *ads_entry;
922         size_t res_size;
923         struct lookup_table_entry *lte;
924
925         if (!(mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
926                 return -ENOTSUP;
927
928         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
929                 return -ENOATTR;
930         name += 5;
931
932         inode = wim_pathname_to_inode(w, path);
933         if (!inode)
934                 return -ENOENT;
935
936         ads_entry = inode_get_ads_entry(inode, name, NULL);
937         if (!ads_entry)
938                 return -ENOATTR;
939
940         lte = ads_entry->lte;
941         res_size = wim_resource_size(lte);
942
943         if (size == 0)
944                 return res_size;
945
946         if (res_size > size)
947                 return -ERANGE;
948
949         ret = read_full_wim_resource(lte, (u8*)value);
950         if (ret != 0)
951                 return -EIO;
952
953         return res_size;
954 }
955 #endif
956
957 /* Create a hard link */
958 static int wimfs_link(const char *to, const char *from)
959 {
960         struct dentry *from_dentry, *from_dentry_parent;
961         const char *link_name;
962         struct inode *inode;
963         struct lookup_table_entry *lte;
964
965         inode = wim_pathname_to_inode(w, to);
966         if (!inode)
967                 return -ENOENT;
968
969         if (!inode_is_regular_file(inode))
970                 return -EPERM;
971
972         from_dentry_parent = get_parent_dentry(w, from);
973         if (!from_dentry_parent)
974                 return -ENOENT;
975         if (!dentry_is_directory(from_dentry_parent))
976                 return -ENOTDIR;
977
978         link_name = path_basename(from);
979         if (get_dentry_child_with_name(from_dentry_parent, link_name))
980                 return -EEXIST;
981         from_dentry = new_dentry(link_name);
982         if (!from_dentry)
983                 return -ENOMEM;
984
985
986         inode_add_dentry(from_dentry, inode);
987         from_dentry->d_inode = inode;
988         inode->link_count++;
989
990         for (unsigned i = 0; i <= inode->num_ads; i++) {
991                 lte = inode_stream_lte_resolved(inode, i);
992                 if (lte)
993                         lte->refcnt++;
994         }
995
996         link_dentry(from_dentry, from_dentry_parent);
997         return 0;
998 }
999
1000 #ifdef ENABLE_XATTR
1001 static int wimfs_listxattr(const char *path, char *list, size_t size)
1002 {
1003         int ret;
1004         size_t needed_size;
1005         unsigned i;
1006         struct inode *inode;
1007
1008         if (!(mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1009                 return -ENOTSUP;
1010
1011         /* List alternate data streams, or get the list size */
1012
1013         inode = wim_pathname_to_inode(w, path);
1014         if (!inode)
1015                 return -ENOENT;
1016
1017         if (size == 0) {
1018                 needed_size = 0;
1019                 for (i = 0; i < inode->num_ads; i++)
1020                         needed_size += inode->ads_entries[i].stream_name_utf8_len + 6;
1021                 return needed_size;
1022         } else {
1023                 char *p = list;
1024                 for (i = 0; i < inode->num_ads; i++) {
1025                         needed_size = inode->ads_entries[i].stream_name_utf8_len + 6;
1026                         if (needed_size > size)
1027                                 return -ERANGE;
1028                         p += sprintf(p, "user.%s",
1029                                      inode->ads_entries[i].stream_name_utf8) + 1;
1030                         size -= needed_size;
1031                 }
1032                 return p - list;
1033         }
1034 }
1035 #endif
1036
1037 /*
1038  * Create a directory in the WIM.
1039  * @mode is currently ignored.
1040  */
1041 static int wimfs_mkdir(const char *path, mode_t mode)
1042 {
1043         struct dentry *parent;
1044         struct dentry *newdir;
1045         const char *basename;
1046
1047         parent = get_parent_dentry(w, path);
1048         if (!parent)
1049                 return -ENOENT;
1050
1051         if (!dentry_is_directory(parent))
1052                 return -ENOTDIR;
1053
1054         basename = path_basename(path);
1055         if (get_dentry_child_with_name(parent, basename))
1056                 return -EEXIST;
1057
1058         newdir = new_dentry_with_inode(basename);
1059         newdir->d_inode->attributes |= FILE_ATTRIBUTE_DIRECTORY;
1060         newdir->d_inode->resolved = true;
1061         newdir->d_inode->ino = next_ino++;
1062         link_dentry(newdir, parent);
1063         return 0;
1064 }
1065
1066 /* Creates a regular file. */
1067 static int wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
1068 {
1069         const char *stream_name;
1070         if ((mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
1071              && (stream_name = path_stream_name(path))) {
1072                 /* Make an alternate data stream */
1073                 struct ads_entry *new_entry;
1074                 struct inode *inode;
1075
1076                 char *p = (char*)stream_name - 1;
1077                 wimlib_assert(*p == ':');
1078                 *p = '\0';
1079
1080                 inode = wim_pathname_to_inode(w, path);
1081                 if (!inode)
1082                         return -ENOENT;
1083                 if (!inode_is_regular_file(inode))
1084                         return -ENOENT;
1085                 if (inode_get_ads_entry(inode, stream_name, NULL))
1086                         return -EEXIST;
1087                 new_entry = inode_add_ads(inode, stream_name);
1088                 if (!new_entry)
1089                         return -ENOMEM;
1090         } else {
1091                 struct dentry *dentry, *parent;
1092                 const char *basename;
1093
1094                 /* Make a normal file (not an alternate data stream) */
1095
1096                 /* Make sure that the parent of @path exists and is a directory, and
1097                  * that the dentry named by @path does not already exist.  */
1098                 parent = get_parent_dentry(w, path);
1099                 if (!parent)
1100                         return -ENOENT;
1101                 if (!dentry_is_directory(parent))
1102                         return -ENOTDIR;
1103
1104                 basename = path_basename(path);
1105                 if (get_dentry_child_with_name(parent, path))
1106                         return -EEXIST;
1107
1108                 dentry = new_dentry_with_inode(basename);
1109                 if (!dentry)
1110                         return -ENOMEM;
1111                 dentry->d_inode->resolved = true;
1112                 dentry->d_inode->ino = next_ino++;
1113                 link_dentry(dentry, parent);
1114         }
1115         return 0;
1116 }
1117
1118
1119 /* Open a file.  */
1120 static int wimfs_open(const char *path, struct fuse_file_info *fi)
1121 {
1122         struct dentry *dentry;
1123         struct lookup_table_entry *lte;
1124         int ret;
1125         struct wimlib_fd *fd;
1126         struct inode *inode;
1127         u16 stream_idx;
1128         u32 stream_id;
1129
1130         ret = lookup_resource(w, path, get_lookup_flags(), &dentry, &lte,
1131                               &stream_idx);
1132         if (ret != 0)
1133                 return ret;
1134
1135         inode = dentry->d_inode;
1136
1137         if (stream_idx == 0)
1138                 stream_id = 0;
1139         else
1140                 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
1141
1142         /* The file resource may be in the staging directory (read-write mounts
1143          * only) or in the WIM.  If it's in the staging directory, we need to
1144          * open a native file descriptor for the corresponding file.  Otherwise,
1145          * we can read the file resource directly from the WIM file if we are
1146          * opening it read-only, but we need to extract the resource to the
1147          * staging directory if we are opening it writable. */
1148
1149         if (flags_writable(fi->flags) &&
1150             (!lte || lte->resource_location != RESOURCE_IN_STAGING_FILE)) {
1151                 u64 size = (lte) ? wim_resource_size(lte) : 0;
1152                 ret = extract_resource_to_staging_dir(inode, stream_id,
1153                                                       &lte, size);
1154                 if (ret != 0)
1155                         return ret;
1156         }
1157
1158         ret = alloc_wimlib_fd(inode, stream_id, lte, &fd);
1159         if (ret != 0)
1160                 return ret;
1161
1162         if (lte && lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1163                 fd->staging_fd = open(lte->staging_file_name, fi->flags);
1164                 if (fd->staging_fd == -1) {
1165                         close_wimlib_fd(fd);
1166                         return -errno;
1167                 }
1168         }
1169         fi->fh = (uintptr_t)fd;
1170         return 0;
1171 }
1172
1173 /* Opens a directory. */
1174 static int wimfs_opendir(const char *path, struct fuse_file_info *fi)
1175 {
1176         struct inode *inode;
1177         int ret;
1178         struct wimlib_fd *fd = NULL;
1179
1180         inode = wim_pathname_to_inode(w, path);
1181         if (!inode)
1182                 return -ENOENT;
1183         if (!inode_is_directory(inode))
1184                 return -ENOTDIR;
1185         ret = alloc_wimlib_fd(inode, 0, NULL, &fd);
1186         fi->fh = (uintptr_t)fd;
1187         return ret;
1188 }
1189
1190
1191 /*
1192  * Read data from a file in the WIM or in the staging directory.
1193  */
1194 static int wimfs_read(const char *path, char *buf, size_t size,
1195                       off_t offset, struct fuse_file_info *fi)
1196 {
1197         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1198
1199         if (!fd)
1200                 return -EBADF;
1201
1202         if (!fd->f_lte) /* Empty stream with no lookup table entry */
1203                 return 0;
1204
1205         if (fd->f_lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1206                 /* Read from staging file */
1207
1208                 wimlib_assert(fd->f_lte->staging_file_name);
1209                 wimlib_assert(fd->staging_fd != -1);
1210
1211                 ssize_t ret;
1212                 DEBUG("Seek to offset %zu", offset);
1213
1214                 if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1215                         return -errno;
1216                 ret = read(fd->staging_fd, buf, size);
1217                 if (ret == -1)
1218                         return -errno;
1219                 return ret;
1220         } else {
1221                 /* Read from WIM */
1222
1223                 u64 res_size = wim_resource_size(fd->f_lte);
1224
1225                 if (offset > res_size)
1226                         return -EOVERFLOW;
1227
1228                 size = min(size, res_size - offset);
1229
1230                 if (read_wim_resource(fd->f_lte, (u8*)buf,
1231                                       size, offset, false) != 0)
1232                         return -EIO;
1233                 return size;
1234         }
1235 }
1236
1237 /* Fills in the entries of the directory specified by @path using the
1238  * FUSE-provided function @filler.  */
1239 static int wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
1240                          off_t offset, struct fuse_file_info *fi)
1241 {
1242         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1243         struct inode *inode;
1244         struct dentry *child;
1245
1246         if (!fd)
1247                 return -EBADF;
1248
1249         inode = fd->f_inode;
1250
1251         filler(buf, ".", NULL, 0);
1252         filler(buf, "..", NULL, 0);
1253
1254         child = inode->children;
1255
1256         if (!child)
1257                 return 0;
1258
1259         do {
1260                 if (filler(buf, child->file_name_utf8, NULL, 0))
1261                         return 0;
1262                 child = child->next;
1263         } while (child != inode->children);
1264         return 0;
1265 }
1266
1267
1268 static int wimfs_readlink(const char *path, char *buf, size_t buf_len)
1269 {
1270         struct inode *inode = wim_pathname_to_inode(w, path);
1271         int ret;
1272         if (!inode)
1273                 return -ENOENT;
1274         if (!inode_is_symlink(inode))
1275                 return -EINVAL;
1276
1277         ret = inode_readlink(inode, buf, buf_len, w);
1278         if (ret > 0)
1279                 ret = 0;
1280         return ret;
1281 }
1282
1283 /* Close a file. */
1284 static int wimfs_release(const char *path, struct fuse_file_info *fi)
1285 {
1286         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1287         return close_wimlib_fd(fd);
1288 }
1289
1290 /* Close a directory */
1291 static int wimfs_releasedir(const char *path, struct fuse_file_info *fi)
1292 {
1293         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1294         return close_wimlib_fd(fd);
1295 }
1296
1297 #ifdef ENABLE_XATTR
1298 /* Remove an alternate data stream through the XATTR interface */
1299 static int wimfs_removexattr(const char *path, const char *name)
1300 {
1301         struct inode *inode;
1302         struct ads_entry *ads_entry;
1303         u16 ads_idx;
1304         if (!(mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1305                 return -ENOTSUP;
1306
1307         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1308                 return -ENOATTR;
1309         name += 5;
1310
1311         inode = wim_pathname_to_inode(w, path);
1312         if (!inode)
1313                 return -ENOENT;
1314
1315         ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
1316         if (!ads_entry)
1317                 return -ENOATTR;
1318         inode_remove_ads(inode, ads_idx, w->lookup_table);
1319         return 0;
1320 }
1321 #endif
1322
1323 /* Renames a file or directory.  See rename (3) */
1324 static int wimfs_rename(const char *from, const char *to)
1325 {
1326         struct dentry *src;
1327         struct dentry *dst;
1328         struct dentry *parent_of_dst;
1329         char *file_name_utf16 = NULL, *file_name_utf8 = NULL;
1330         u16 file_name_utf16_len, file_name_utf8_len;
1331         int ret;
1332
1333         /* This rename() implementation currently only supports actual files
1334          * (not alternate data streams) */
1335
1336         src = get_dentry(w, from);
1337         if (!src)
1338                 return -ENOENT;
1339
1340         dst = get_dentry(w, to);
1341
1342
1343         ret = get_names(&file_name_utf16, &file_name_utf8,
1344                         &file_name_utf16_len, &file_name_utf8_len,
1345                         path_basename(to));
1346         if (ret != 0)
1347                 return -ENOMEM;
1348
1349         if (dst) {
1350                 /* Destination file exists */
1351
1352                 if (src == dst) /* Same file */
1353                         return 0;
1354
1355                 if (!dentry_is_directory(src)) {
1356                         /* Cannot rename non-directory to directory. */
1357                         if (dentry_is_directory(dst))
1358                                 return -EISDIR;
1359                 } else {
1360                         /* Cannot rename directory to a non-directory or a non-empty
1361                          * directory */
1362                         if (!dentry_is_directory(dst))
1363                                 return -ENOTDIR;
1364                         if (dst->d_inode->children != NULL)
1365                                 return -ENOTEMPTY;
1366                 }
1367                 parent_of_dst = dst->parent;
1368                 remove_dentry(dst, w->lookup_table);
1369         } else {
1370                 /* Destination does not exist */
1371                 parent_of_dst = get_parent_dentry(w, to);
1372                 if (!parent_of_dst)
1373                         return -ENOENT;
1374
1375                 if (!dentry_is_directory(parent_of_dst))
1376                         return -ENOTDIR;
1377         }
1378
1379         FREE(src->file_name);
1380         FREE(src->file_name_utf8);
1381         src->file_name          = file_name_utf16;
1382         src->file_name_utf8     = file_name_utf8;
1383         src->file_name_len      = file_name_utf16_len;
1384         src->file_name_utf8_len = file_name_utf8_len;
1385
1386         unlink_dentry(src);
1387         link_dentry(src, parent_of_dst);
1388         return 0;
1389 }
1390
1391 /* Remove a directory */
1392 static int wimfs_rmdir(const char *path)
1393 {
1394         struct dentry *dentry;
1395
1396         dentry = get_dentry(w, path);
1397         if (!dentry)
1398                 return -ENOENT;
1399
1400         if (!dentry_is_empty_directory(dentry))
1401                 return -ENOTEMPTY;
1402
1403         remove_dentry(dentry, w->lookup_table);
1404         return 0;
1405 }
1406
1407 #ifdef ENABLE_XATTR
1408 /* Write an alternate data stream through the XATTR interface */
1409 static int wimfs_setxattr(const char *path, const char *name,
1410                           const char *value, size_t size, int flags)
1411 {
1412         struct ads_entry *existing_ads_entry;
1413         struct ads_entry *new_ads_entry;
1414         struct lookup_table_entry *existing_lte;
1415         struct lookup_table_entry *lte;
1416         struct inode *inode;
1417         u8 value_hash[SHA1_HASH_SIZE];
1418         u16 ads_idx;
1419
1420         if (!(mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1421                 return -ENOTSUP;
1422
1423         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1424                 return -ENOATTR;
1425         name += 5;
1426
1427         inode = wim_pathname_to_inode(w, path);
1428         if (!inode)
1429                 return -ENOENT;
1430
1431         existing_ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
1432         if (existing_ads_entry) {
1433                 if (flags & XATTR_CREATE)
1434                         return -EEXIST;
1435                 inode_remove_ads(inode, ads_idx, w->lookup_table);
1436         } else {
1437                 if (flags & XATTR_REPLACE)
1438                         return -ENOATTR;
1439         }
1440         new_ads_entry = inode_add_ads(inode, name);
1441         if (!new_ads_entry)
1442                 return -ENOMEM;
1443
1444         sha1_buffer((const u8*)value, size, value_hash);
1445
1446         existing_lte = __lookup_resource(w->lookup_table, value_hash);
1447
1448         if (existing_lte) {
1449                 lte = existing_lte;
1450                 lte->refcnt++;
1451         } else {
1452                 u8 *value_copy;
1453                 lte = new_lookup_table_entry();
1454                 if (!lte)
1455                         return -ENOMEM;
1456                 value_copy = MALLOC(size);
1457                 if (!value_copy) {
1458                         FREE(lte);
1459                         return -ENOMEM;
1460                 }
1461                 memcpy(value_copy, value, size);
1462                 lte->resource_location            = RESOURCE_IN_ATTACHED_BUFFER;
1463                 lte->attached_buffer              = value_copy;
1464                 lte->resource_entry.original_size = size;
1465                 lte->resource_entry.size          = size;
1466                 lte->resource_entry.flags         = 0;
1467                 copy_hash(lte->hash, value_hash);
1468                 lookup_table_insert(w->lookup_table, lte);
1469         }
1470         new_ads_entry->lte = lte;
1471         return 0;
1472 }
1473 #endif
1474
1475 static int wimfs_symlink(const char *to, const char *from)
1476 {
1477         struct dentry *dentry_parent, *dentry;
1478         const char *link_name;
1479         struct inode *inode;
1480
1481         dentry_parent = get_parent_dentry(w, from);
1482         if (!dentry_parent)
1483                 return -ENOENT;
1484         if (!dentry_is_directory(dentry_parent))
1485                 return -ENOTDIR;
1486
1487         link_name = path_basename(from);
1488
1489         if (get_dentry_child_with_name(dentry_parent, link_name))
1490                 return -EEXIST;
1491         dentry = new_dentry_with_inode(link_name);
1492         if (!dentry)
1493                 return -ENOMEM;
1494         inode = dentry->d_inode;
1495
1496         inode->attributes  = FILE_ATTRIBUTE_REPARSE_POINT;
1497         inode->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
1498         inode->ino         = next_ino++;
1499         inode->resolved    = true;
1500
1501         if (inode_set_symlink(inode, to, w->lookup_table, NULL) != 0)
1502                 goto out_free_dentry;
1503
1504         link_dentry(dentry, dentry_parent);
1505         return 0;
1506 out_free_dentry:
1507         free_dentry(dentry);
1508         return -ENOMEM;
1509 }
1510
1511
1512 /* Reduce the size of a file */
1513 static int wimfs_truncate(const char *path, off_t size)
1514 {
1515         struct dentry *dentry;
1516         struct lookup_table_entry *lte;
1517         int ret;
1518         u16 stream_idx;
1519         u32 stream_id;
1520         struct inode *inode;
1521
1522         ret = lookup_resource(w, path, get_lookup_flags(), &dentry,
1523                               &lte, &stream_idx);
1524
1525         if (ret != 0)
1526                 return ret;
1527
1528         if (!lte) /* Already a zero-length file */
1529                 return 0;
1530
1531         inode = dentry->d_inode;
1532
1533         if (stream_idx == 0)
1534                 stream_id = 0;
1535         else
1536                 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
1537
1538         if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1539                 wimlib_assert(lte->staging_file_name);
1540                 ret = truncate(lte->staging_file_name, size);
1541                 if (ret != 0)
1542                         return -errno;
1543                 lte->resource_entry.original_size = size;
1544         } else {
1545                 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
1546                 /* File in WIM.  Extract it to the staging directory, but only
1547                  * the first @size bytes of it. */
1548                 ret = extract_resource_to_staging_dir(inode, stream_id,
1549                                                       &lte, size);
1550         }
1551         return ret;
1552 }
1553
1554 /* Remove a regular file */
1555 static int wimfs_unlink(const char *path)
1556 {
1557         struct dentry *dentry;
1558         struct lookup_table_entry *lte;
1559         struct inode *inode;
1560         int ret;
1561         u16 stream_idx;
1562         unsigned i;
1563
1564         ret = lookup_resource(w, path, get_lookup_flags(), &dentry,
1565                               &lte, &stream_idx);
1566
1567         if (ret != 0)
1568                 return ret;
1569
1570         if (stream_idx == 0)
1571                 remove_dentry(dentry, w->lookup_table);
1572         else
1573                 inode_remove_ads(dentry->d_inode, stream_idx - 1, w->lookup_table);
1574         return 0;
1575 }
1576
1577 #ifdef HAVE_UTIMENSAT
1578 /*
1579  * Change the timestamp on a file dentry.
1580  *
1581  * Note that alternate data streams do not have their own timestamps.
1582  */
1583 static int wimfs_utimens(const char *path, const struct timespec tv[2])
1584 {
1585         struct dentry *dentry;
1586         struct inode *inode;
1587         dentry = get_dentry(w, path);
1588         if (!dentry)
1589                 return -ENOENT;
1590         inode = dentry->d_inode;
1591
1592         if (tv[0].tv_nsec != UTIME_OMIT) {
1593                 if (tv[0].tv_nsec == UTIME_NOW)
1594                         inode->last_access_time = get_wim_timestamp();
1595                 else
1596                         inode->last_access_time = timespec_to_wim_timestamp(&tv[0]);
1597         }
1598         if (tv[1].tv_nsec != UTIME_OMIT) {
1599                 if (tv[1].tv_nsec == UTIME_NOW)
1600                         inode->last_write_time = get_wim_timestamp();
1601                 else
1602                         inode->last_write_time = timespec_to_wim_timestamp(&tv[1]);
1603         }
1604         return 0;
1605 }
1606 #else
1607 static int wimfs_utime(const char *path, struct utimbuf *times)
1608 {
1609         struct dentry *dentry;
1610         struct inode *inode;
1611         dentry = get_dentry(w, path);
1612         if (!dentry)
1613                 return -ENOENT;
1614         inode = dentry->d_inode;
1615
1616         inode->last_write_time = unix_timestamp_to_wim(times->modtime);
1617         inode->last_access_time = unix_timestamp_to_wim(times->actime);
1618         return 0;
1619 }
1620 #endif
1621
1622 /* Writes to a file in the WIM filesystem.
1623  * It may be an alternate data stream, but here we don't even notice because we
1624  * just get a lookup table entry. */
1625 static int wimfs_write(const char *path, const char *buf, size_t size,
1626                        off_t offset, struct fuse_file_info *fi)
1627 {
1628         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1629         int ret;
1630         u64 now;
1631
1632         if (!fd)
1633                 return -EBADF;
1634
1635         wimlib_assert(fd->f_lte);
1636         wimlib_assert(fd->f_lte->staging_file_name);
1637         wimlib_assert(fd->staging_fd != -1);
1638         wimlib_assert(fd->f_inode);
1639
1640         /* Seek to the requested position */
1641         if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1642                 return -errno;
1643
1644         /* Write the data. */
1645         ret = write(fd->staging_fd, buf, size);
1646         if (ret == -1)
1647                 return -errno;
1648
1649         now = get_wim_timestamp();
1650         fd->f_inode->last_write_time = now;
1651         fd->f_inode->last_access_time = now;
1652         return ret;
1653 }
1654
1655 static struct fuse_operations wimfs_operations = {
1656         .access      = wimfs_access,
1657         .destroy     = wimfs_destroy,
1658 #if 0
1659         .fallocate   = wimfs_fallocate,
1660 #endif
1661         .fgetattr    = wimfs_fgetattr,
1662         .ftruncate   = wimfs_ftruncate,
1663         .getattr     = wimfs_getattr,
1664 #ifdef ENABLE_XATTR
1665         .getxattr    = wimfs_getxattr,
1666 #endif
1667         .link        = wimfs_link,
1668 #ifdef ENABLE_XATTR
1669         .listxattr   = wimfs_listxattr,
1670 #endif
1671         .mkdir       = wimfs_mkdir,
1672         .mknod       = wimfs_mknod,
1673         .open        = wimfs_open,
1674         .opendir     = wimfs_opendir,
1675         .read        = wimfs_read,
1676         .readdir     = wimfs_readdir,
1677         .readlink    = wimfs_readlink,
1678         .release     = wimfs_release,
1679         .releasedir  = wimfs_releasedir,
1680 #ifdef ENABLE_XATTR
1681         .removexattr = wimfs_removexattr,
1682 #endif
1683         .rename      = wimfs_rename,
1684         .rmdir       = wimfs_rmdir,
1685 #ifdef ENABLE_XATTR
1686         .setxattr    = wimfs_setxattr,
1687 #endif
1688         .symlink     = wimfs_symlink,
1689         .truncate    = wimfs_truncate,
1690         .unlink      = wimfs_unlink,
1691 #ifdef HAVE_UTIMENSAT
1692         .utimens     = wimfs_utimens,
1693 #else
1694         .utime       = wimfs_utime,
1695 #endif
1696         .write       = wimfs_write,
1697 };
1698
1699
1700 /* Mounts a WIM file. */
1701 WIMLIBAPI int wimlib_mount(WIMStruct *wim, int image, const char *dir,
1702                            int flags, WIMStruct **additional_swms,
1703                            unsigned num_additional_swms)
1704 {
1705         int argc = 0;
1706         char *argv[16];
1707         int ret;
1708         char *p;
1709         struct lookup_table *joined_tab, *wim_tab_save;
1710         struct image_metadata *imd;
1711
1712         DEBUG("Mount: wim = %p, image = %d, dir = %s, flags = %d, ",
1713                         wim, image, dir, flags);
1714
1715         if (!wim || !dir)
1716                 return WIMLIB_ERR_INVALID_PARAM;
1717
1718         ret = verify_swm_set(wim, additional_swms, num_additional_swms);
1719         if (ret != 0)
1720                 return ret;
1721
1722         if (num_additional_swms) {
1723                 ret = new_joined_lookup_table(wim, additional_swms,
1724                                               num_additional_swms,
1725                                               &joined_tab);
1726                 if (ret != 0)
1727                         return ret;
1728                 wim_tab_save = wim->lookup_table;
1729                 wim->lookup_table = joined_tab;
1730         }
1731
1732         ret = select_wim_image(wim, image);
1733
1734         if (ret != 0)
1735                 goto out;
1736
1737         imd = &wim->image_metadata[image - 1];
1738
1739         DEBUG("Selected image %d", image);
1740
1741         if (imd->root_dentry->refcnt != 1) {
1742                 ERROR("Cannot mount image that was just exported with "
1743                       "wimlib_export()");
1744                 return WIMLIB_ERR_INVALID_PARAM;
1745         }
1746
1747         next_ino = assign_inode_numbers(&imd->inode_list);
1748
1749         DEBUG("(next_ino = %"PRIu64")", next_ino);
1750
1751         /* Resolve all the lookup table entries of the dentry tree */
1752         DEBUG("Resolving lookup table entries");
1753         for_dentry_in_tree(imd->root_dentry, dentry_resolve_ltes,
1754                            wim->lookup_table);
1755
1756         if (flags & WIMLIB_MOUNT_FLAG_READWRITE)
1757                 imd->modified = true;
1758
1759         if (!(flags & (WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
1760                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
1761                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)))
1762                 flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
1763
1764         DEBUG("Getting current directory");
1765
1766         mount_dir = dir;
1767         working_directory = getcwd(NULL, 0);
1768         if (!working_directory) {
1769                 ERROR_WITH_ERRNO("Could not determine current directory");
1770                 ret = WIMLIB_ERR_NOTDIR;
1771                 goto out;
1772         }
1773
1774         DEBUG("Closing POSIX message queues");
1775         /* XXX hack to get rid of the message queues if they already exist for
1776          * some reason (maybe left over from a previous mount that wasn't
1777          * unmounted correctly) */
1778         ret = open_message_queues(true);
1779         if (ret != 0)
1780                 goto out;
1781         close_message_queues();
1782
1783         DEBUG("Preparing arguments to fuse_main()");
1784
1785
1786         p = STRDUP(dir);
1787         if (!p) {
1788                 ret = WIMLIB_ERR_NOMEM;
1789                 goto out;
1790         }
1791
1792         argv[argc++] = "imagex";
1793         argv[argc++] = p;
1794         argv[argc++] = "-s"; /* disable multi-threaded operation */
1795
1796         if (flags & WIMLIB_MOUNT_FLAG_DEBUG)
1797                 argv[argc++] = "-d";
1798
1799         /*
1800          * We provide the use_ino option because we are going to assign inode
1801          * numbers oursides.  We've already numbered the inodes with unique
1802          * numbers in the assign_inode_numbers() function, and the static
1803          * variable next_ino is set to the next available inode number.
1804          */
1805         char optstring[256] = "use_ino,subtype=wimfs,attr_timeout=0";
1806         argv[argc++] = "-o";
1807         argv[argc++] = optstring;
1808         if ((flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
1809                 /* Read-write mount.  Make the staging directory */
1810                 make_staging_dir();
1811                 if (!staging_dir_name) {
1812                         FREE(p);
1813                         ret = WIMLIB_ERR_MKDIR;
1814                         goto out;
1815                 }
1816         } else {
1817                 /* Read-only mount */
1818                 strcat(optstring, ",ro");
1819         }
1820         argv[argc] = NULL;
1821
1822 #ifdef ENABLE_DEBUG
1823         {
1824                 int i;
1825                 DEBUG("FUSE command line (argc = %d): ", argc);
1826                 for (i = 0; i < argc; i++) {
1827                         fputs(argv[i], stdout);
1828                         putchar(' ');
1829                 }
1830                 putchar('\n');
1831                 fflush(stdout);
1832         }
1833 #endif
1834
1835         /* Set static variables. */
1836         w = wim;
1837         mount_flags = flags;
1838
1839         ret = fuse_main(argc, argv, &wimfs_operations, NULL);
1840         if (ret)
1841                 ret = WIMLIB_ERR_FUSE;
1842 out:
1843         if (num_additional_swms) {
1844                 free_lookup_table(wim->lookup_table);
1845                 wim->lookup_table = wim_tab_save;
1846         }
1847         return ret;
1848 }
1849
1850
1851 /*
1852  * Unmounts the WIM file that was previously mounted on @dir by using
1853  * wimlib_mount().
1854  */
1855 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
1856 {
1857         pid_t pid;
1858         int status;
1859         int ret;
1860         char msg[2];
1861         struct timeval now;
1862         struct timespec timeout;
1863         int msgsize;
1864         int errno_save;
1865
1866         mount_dir = dir;
1867
1868         /* Open message queues between the unmount process and the
1869          * filesystem daemon. */
1870         ret = open_message_queues(false);
1871         if (ret != 0)
1872                 return ret;
1873
1874         /* Send a message to the filesystem saying whether to commit or
1875          * not. */
1876         msg[0] = (flags & WIMLIB_UNMOUNT_FLAG_COMMIT) ? 1 : 0;
1877         msg[1] = (flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY) ? 1 : 0;
1878
1879         DEBUG("Sending message: %s, %s",
1880                         (msg[0] == 0) ? "don't commit" : "commit",
1881                         (msg[1] == 0) ? "don't check"  : "check");
1882         ret = mq_send(unmount_to_daemon_mq, msg, 2, 1);
1883         if (ret == -1) {
1884                 ERROR("Failed to notify filesystem daemon whether we want to "
1885                       "commit changes or not");
1886                 close_message_queues();
1887                 return WIMLIB_ERR_MQUEUE;
1888         }
1889
1890         /* Execute `fusermount -u', which is installed setuid root, to unmount
1891          * the WIM.
1892          *
1893          * FUSE does not yet implement synchronous unmounts.  This means that
1894          * fusermount -u will return before the filesystem daemon returns from
1895          * wimfs_destroy().  This is partly what we want, because we need to
1896          * send a message from this process to the filesystem daemon telling
1897          * whether --commit was specified or not.  However, after that, the
1898          * unmount process must wait for the filesystem daemon to finish writing
1899          * the WIM file.
1900          */
1901
1902
1903         pid = fork();
1904         if (pid == -1) {
1905                 ERROR_WITH_ERRNO("Failed to fork()");
1906                 return WIMLIB_ERR_FORK;
1907         }
1908         if (pid == 0) {
1909                 execlp("fusermount", "fusermount", "-u", dir, NULL);
1910                 ERROR_WITH_ERRNO("Failed to execute `fusermount'");
1911                 exit(WIMLIB_ERR_FUSERMOUNT);
1912         }
1913
1914         ret = wait(&status);
1915         if (ret == -1) {
1916                 ERROR_WITH_ERRNO("Failed to wait for fusermount process to "
1917                                  "terminate");
1918                 return WIMLIB_ERR_FUSERMOUNT;
1919         }
1920
1921         if (status != 0) {
1922                 ERROR("fusermount exited with status %d", status);
1923
1924                 /* Try again, but with the `umount' program.  This is required
1925                  * on other FUSE implementations such as FreeBSD's that do not
1926                  * have a `fusermount' program. */
1927
1928                 pid = fork();
1929                 if (pid == -1) {
1930                         ERROR_WITH_ERRNO("Failed to fork()");
1931                         return WIMLIB_ERR_FORK;
1932                 }
1933                 if (pid == 0) {
1934                         execlp("umount", "umount", dir, NULL);
1935                         ERROR_WITH_ERRNO("Failed to execute `umount'");
1936                         exit(WIMLIB_ERR_FUSERMOUNT);
1937                 }
1938
1939                 ret = wait(&status);
1940                 if (ret == -1) {
1941                         ERROR_WITH_ERRNO("Failed to wait for `umount' process to "
1942                                          "terminate");
1943                         return WIMLIB_ERR_FUSERMOUNT;
1944                 }
1945                 if (status != 0) {
1946                         ERROR("`umount' exited with failure status");
1947                         return WIMLIB_ERR_FUSERMOUNT;
1948                 }
1949         }
1950
1951
1952         /* Wait for a message from the filesytem daemon indicating whether  the
1953          * filesystem was unmounted successfully (0) or an error occurred (1).
1954          * This may take a long time if a big WIM file needs to be rewritten. */
1955
1956         /* Wait at most 600??? seconds before giving up and returning false.
1957          * Either it's a really big WIM file, or (more likely) the
1958          * filesystem daemon has crashed or failed for some reason.
1959          *
1960          * XXX come up with some method to determine if the filesystem
1961          * daemon has really crashed or not.
1962          *
1963          * XXX Idea: have mount daemon write its PID into the WIM file header?
1964          * */
1965
1966         gettimeofday(&now, NULL);
1967         timeout.tv_sec = now.tv_sec + 600;
1968         timeout.tv_nsec = now.tv_usec * 1000;
1969
1970         msgsize = mq_get_msgsize(daemon_to_unmount_mq);
1971         char mailbox[msgsize];
1972
1973         mailbox[0] = 0;
1974         DEBUG("Waiting for message telling us whether the unmount was "
1975                         "successful or not.");
1976         ret = mq_timedreceive(daemon_to_unmount_mq, mailbox, msgsize,
1977                               NULL, &timeout);
1978         errno_save = errno;
1979         close_message_queues();
1980         if (ret == -1) {
1981                 if (errno_save == ETIMEDOUT) {
1982                         ERROR("Timed out- probably the filesystem daemon "
1983                               "crashed and the WIM was not written "
1984                               "successfully.");
1985                         return WIMLIB_ERR_TIMEOUT;
1986                 } else {
1987                         ERROR("mq_receive(): %s", strerror(errno_save));
1988                         return WIMLIB_ERR_MQUEUE;
1989                 }
1990
1991         }
1992         DEBUG("Received message: %s",
1993               (mailbox[0] == 0) ?  "Unmount OK" : "Unmount Failed");
1994         if (mailbox[0] != 0)
1995                 ERROR("Unmount failed");
1996         return mailbox[0];
1997 }
1998
1999 #else /* WITH_FUSE */
2000
2001
2002 static inline int mount_unsupported_error()
2003 {
2004         ERROR("WIMLIB was compiled with --without-fuse, which disables support "
2005               "for mounting WIMs.");
2006         return WIMLIB_ERR_UNSUPPORTED;
2007 }
2008
2009 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
2010 {
2011         return mount_unsupported_error();
2012 }
2013
2014 WIMLIBAPI int wimlib_mount(WIMStruct *wim_p, int image, const char *dir,
2015                            int flags, WIMStruct **additional_swms,
2016                            unsigned num_additional_swms)
2017 {
2018         return mount_unsupported_error();
2019 }
2020
2021 #endif /* WITH_FUSE */