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