]> wimlib.net Git - wimlib/blob - src/mount.c
fd->lte => fd->f_lte, fix inode_add_ads()
[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         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->f_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->f_lte == old_lte);
389                                         fd->f_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->f_lte == new_lte) {
430                         fd->f_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->f_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->f_lte && size < fd->f_lte->resource_entry.original_size)
875                 fd->f_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 /* Creates a regular file. */
1046 static int wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
1047 {
1048         const char *stream_name;
1049         if ((mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
1050              && (stream_name = path_stream_name(path))) {
1051                 /* Make an alternate data stream */
1052                 struct ads_entry *new_entry;
1053                 struct dentry *dentry;
1054
1055                 char *p = (char*)stream_name - 1;
1056                 wimlib_assert(*p == ':');
1057                 *p = '\0';
1058
1059                 dentry = get_dentry(w, path);
1060                 if (!dentry || !dentry_is_regular_file(dentry))
1061                         return -ENOENT;
1062                 if (inode_get_ads_entry(dentry->d_inode, stream_name, NULL))
1063                         return -EEXIST;
1064                 new_entry = inode_add_ads(dentry->d_inode, stream_name);
1065                 if (!new_entry)
1066                         return -ENOENT;
1067         } else {
1068                 struct dentry *dentry, *parent;
1069                 const char *basename;
1070
1071                 /* Make a normal file (not an alternate data stream) */
1072
1073                 /* Make sure that the parent of @path exists and is a directory, and
1074                  * that the dentry named by @path does not already exist.  */
1075                 parent = get_parent_dentry(w, path);
1076                 if (!parent)
1077                         return -ENOENT;
1078                 if (!dentry_is_directory(parent))
1079                         return -ENOTDIR;
1080
1081                 basename = path_basename(path);
1082                 if (get_dentry_child_with_name(parent, path))
1083                         return -EEXIST;
1084
1085                 dentry = new_dentry_with_inode(basename);
1086                 if (!dentry)
1087                         return -ENOMEM;
1088                 dentry->d_inode->resolved = true;
1089                 dentry->d_inode->ino = next_ino++;
1090                 link_dentry(dentry, parent);
1091         }
1092         return 0;
1093 }
1094
1095
1096 /* Open a file.  */
1097 static int wimfs_open(const char *path, struct fuse_file_info *fi)
1098 {
1099         struct dentry *dentry;
1100         struct lookup_table_entry *lte;
1101         int ret;
1102         struct wimlib_fd *fd;
1103         struct inode *inode;
1104         u16 stream_idx;
1105         u32 stream_id;
1106
1107         ret = lookup_resource(w, path, get_lookup_flags(), &dentry, &lte,
1108                               &stream_idx);
1109         if (ret != 0)
1110                 return ret;
1111
1112         inode = dentry->d_inode;
1113
1114         if (stream_idx == 0)
1115                 stream_id = 0;
1116         else
1117                 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
1118
1119         /* The file resource may be in the staging directory (read-write mounts
1120          * only) or in the WIM.  If it's in the staging directory, we need to
1121          * open a native file descriptor for the corresponding file.  Otherwise,
1122          * we can read the file resource directly from the WIM file if we are
1123          * opening it read-only, but we need to extract the resource to the
1124          * staging directory if we are opening it writable. */
1125
1126         if (flags_writable(fi->flags) &&
1127             (!lte || lte->resource_location != RESOURCE_IN_STAGING_FILE)) {
1128                 u64 size = (lte) ? wim_resource_size(lte) : 0;
1129                 ret = extract_resource_to_staging_dir(inode, stream_id,
1130                                                       &lte, size);
1131                 if (ret != 0)
1132                         return ret;
1133         }
1134
1135         ret = alloc_wimlib_fd(inode, stream_id, lte, &fd);
1136         if (ret != 0)
1137                 return ret;
1138
1139         if (lte && lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1140                 fd->staging_fd = open(lte->staging_file_name, fi->flags);
1141                 if (fd->staging_fd == -1) {
1142                         close_wimlib_fd(fd);
1143                         return -errno;
1144                 }
1145         }
1146         fi->fh = (uintptr_t)fd;
1147         return 0;
1148 }
1149
1150 /* Opens a directory. */
1151 static int wimfs_opendir(const char *path, struct fuse_file_info *fi)
1152 {
1153         struct inode *inode;
1154         int ret;
1155         struct wimlib_fd *fd = NULL;
1156         
1157         inode = wim_pathname_to_inode(w, path);
1158         if (!inode)
1159                 return -ENOENT;
1160         if (!inode_is_directory(inode))
1161                 return -ENOTDIR;
1162         ret = alloc_wimlib_fd(inode, 0, NULL, &fd);
1163         fi->fh = (uintptr_t)fd;
1164         return ret;
1165 }
1166
1167
1168 /*
1169  * Read data from a file in the WIM or in the staging directory. 
1170  */
1171 static int wimfs_read(const char *path, char *buf, size_t size, 
1172                       off_t offset, struct fuse_file_info *fi)
1173 {
1174         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1175
1176         if (!fd)
1177                 return -EBADF;
1178
1179         if (!fd->f_lte) /* Empty stream with no lookup table entry */
1180                 return 0;
1181
1182         if (fd->f_lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1183                 /* Read from staging file */
1184
1185                 wimlib_assert(fd->f_lte->staging_file_name);
1186                 wimlib_assert(fd->staging_fd != -1);
1187
1188                 ssize_t ret;
1189                 DEBUG("Seek to offset %zu", offset);
1190
1191                 if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1192                         return -errno;
1193                 ret = read(fd->staging_fd, buf, size);
1194                 if (ret == -1)
1195                         return -errno;
1196                 return ret;
1197         } else {
1198                 /* Read from WIM */
1199
1200                 u64 res_size = wim_resource_size(fd->f_lte);
1201                 
1202                 if (offset > res_size)
1203                         return -EOVERFLOW;
1204
1205                 size = min(size, res_size - offset);
1206
1207                 if (read_wim_resource(fd->f_lte, (u8*)buf,
1208                                       size, offset, false) != 0)
1209                         return -EIO;
1210                 return size;
1211         }
1212 }
1213
1214 /* Fills in the entries of the directory specified by @path using the
1215  * FUSE-provided function @filler.  */
1216 static int wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, 
1217                          off_t offset, struct fuse_file_info *fi)
1218 {
1219         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1220         struct inode *inode;
1221         struct dentry *child;
1222
1223         if (!fd)
1224                 return -EBADF;
1225
1226         inode = fd->f_inode;
1227
1228         filler(buf, ".", NULL, 0);
1229         filler(buf, "..", NULL, 0);
1230
1231         child = inode->children;
1232
1233         if (!child)
1234                 return 0;
1235
1236         do {
1237                 if (filler(buf, child->file_name_utf8, NULL, 0))
1238                         return 0;
1239                 child = child->next;
1240         } while (child != inode->children);
1241         return 0;
1242 }
1243
1244
1245 static int wimfs_readlink(const char *path, char *buf, size_t buf_len)
1246 {
1247         struct dentry *dentry = get_dentry(w, path);
1248         int ret;
1249         if (!dentry)
1250                 return -ENOENT;
1251         if (!dentry_is_symlink(dentry))
1252                 return -EINVAL;
1253
1254         ret = inode_readlink(dentry->d_inode, buf, buf_len, w);
1255         if (ret > 0)
1256                 ret = 0;
1257         return ret;
1258 }
1259
1260 /* Close a file. */
1261 static int wimfs_release(const char *path, struct fuse_file_info *fi)
1262 {
1263         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1264         return close_wimlib_fd(fd);
1265 }
1266
1267 /* Close a directory */
1268 static int wimfs_releasedir(const char *path, struct fuse_file_info *fi)
1269 {
1270         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1271         return close_wimlib_fd(fd);
1272 }
1273
1274 #ifdef ENABLE_XATTR
1275 /* Remove an alternate data stream through the XATTR interface */
1276 static int wimfs_removexattr(const char *path, const char *name)
1277 {
1278         struct dentry *dentry;
1279         struct ads_entry *ads_entry;
1280         u16 ads_idx;
1281         if (!(mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1282                 return -ENOTSUP;
1283
1284         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1285                 return -ENOATTR;
1286         name += 5;
1287
1288         dentry = get_dentry(w, path);
1289         if (!dentry)
1290                 return -ENOENT;
1291
1292         ads_entry = inode_get_ads_entry(dentry->d_inode, name, &ads_idx);
1293         if (!ads_entry)
1294                 return -ENOATTR;
1295         inode_remove_ads(dentry->d_inode, ads_idx, w->lookup_table);
1296         return 0;
1297 }
1298 #endif
1299
1300 /* Renames a file or directory.  See rename (3) */
1301 static int wimfs_rename(const char *from, const char *to)
1302 {
1303         struct dentry *src;
1304         struct dentry *dst;
1305         struct dentry *parent_of_dst;
1306         char *file_name_utf16 = NULL, *file_name_utf8 = NULL;
1307         u16 file_name_utf16_len, file_name_utf8_len;
1308         int ret;
1309
1310         /* This rename() implementation currently only supports actual files
1311          * (not alternate data streams) */
1312         
1313         src = get_dentry(w, from);
1314         if (!src)
1315                 return -ENOENT;
1316
1317         dst = get_dentry(w, to);
1318
1319
1320         ret = get_names(&file_name_utf16, &file_name_utf8,
1321                         &file_name_utf16_len, &file_name_utf8_len,
1322                         path_basename(to));
1323         if (ret != 0)
1324                 return -ENOMEM;
1325
1326         if (dst) {
1327                 /* Destination file exists */
1328
1329                 if (src == dst) /* Same file */
1330                         return 0;
1331
1332                 if (!dentry_is_directory(src)) {
1333                         /* Cannot rename non-directory to directory. */
1334                         if (dentry_is_directory(dst))
1335                                 return -EISDIR;
1336                 } else {
1337                         /* Cannot rename directory to a non-directory or a non-empty
1338                          * directory */
1339                         if (!dentry_is_directory(dst))
1340                                 return -ENOTDIR;
1341                         if (dst->d_inode->children != NULL)
1342                                 return -ENOTEMPTY;
1343                 }
1344                 parent_of_dst = dst->parent;
1345                 remove_dentry(dst, w->lookup_table);
1346         } else {
1347                 /* Destination does not exist */
1348                 parent_of_dst = get_parent_dentry(w, to);
1349                 if (!parent_of_dst)
1350                         return -ENOENT;
1351
1352                 if (!dentry_is_directory(parent_of_dst))
1353                         return -ENOTDIR;
1354         }
1355
1356         FREE(src->file_name);
1357         FREE(src->file_name_utf8);
1358         src->file_name          = file_name_utf16;
1359         src->file_name_utf8     = file_name_utf8;
1360         src->file_name_len      = file_name_utf16_len;
1361         src->file_name_utf8_len = file_name_utf8_len;
1362
1363         unlink_dentry(src);
1364         link_dentry(src, parent_of_dst);
1365         return 0;
1366 }
1367
1368 /* Remove a directory */
1369 static int wimfs_rmdir(const char *path)
1370 {
1371         struct dentry *dentry;
1372         
1373         dentry = get_dentry(w, path);
1374         if (!dentry)
1375                 return -ENOENT;
1376
1377         if (!dentry_is_empty_directory(dentry))
1378                 return -ENOTEMPTY;
1379
1380         remove_dentry(dentry, w->lookup_table);
1381         return 0;
1382 }
1383
1384 #ifdef ENABLE_XATTR
1385 /* Write an alternate data stream through the XATTR interface */
1386 static int wimfs_setxattr(const char *path, const char *name,
1387                           const char *value, size_t size, int flags)
1388 {
1389         struct ads_entry *existing_ads_entry;
1390         struct ads_entry *new_ads_entry;
1391         struct lookup_table_entry *existing_lte;
1392         struct lookup_table_entry *lte;
1393         struct inode *inode;
1394         u8 value_hash[SHA1_HASH_SIZE];
1395         u16 ads_idx;
1396
1397         if (!(mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1398                 return -ENOTSUP;
1399
1400         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1401                 return -ENOATTR;
1402         name += 5;
1403
1404         inode = wim_pathname_to_inode(w, path);
1405         if (!inode)
1406                 return -ENOENT;
1407
1408         existing_ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
1409         if (existing_ads_entry) {
1410                 if (flags & XATTR_CREATE)
1411                         return -EEXIST;
1412                 inode_remove_ads(inode, ads_idx, w->lookup_table);
1413         } else {
1414                 if (flags & XATTR_REPLACE)
1415                         return -ENOATTR;
1416         }
1417         new_ads_entry = inode_add_ads(inode, name);
1418         if (!new_ads_entry)
1419                 return -ENOMEM;
1420
1421         sha1_buffer((const u8*)value, size, value_hash);
1422
1423         existing_lte = __lookup_resource(w->lookup_table, value_hash);
1424
1425         if (existing_lte) {
1426                 lte = existing_lte;
1427                 lte->refcnt++;
1428         } else {
1429                 u8 *value_copy;
1430                 lte = new_lookup_table_entry();
1431                 if (!lte)
1432                         return -ENOMEM;
1433                 value_copy = MALLOC(size);
1434                 if (!value_copy) {
1435                         FREE(lte);
1436                         return -ENOMEM;
1437                 }
1438                 memcpy(value_copy, value, size);
1439                 lte->resource_location            = RESOURCE_IN_ATTACHED_BUFFER;
1440                 lte->attached_buffer              = value_copy;
1441                 lte->resource_entry.original_size = size;
1442                 lte->resource_entry.size          = size;
1443                 lte->resource_entry.flags         = 0;
1444                 copy_hash(lte->hash, value_hash);
1445                 lookup_table_insert(w->lookup_table, lte);
1446         }
1447         new_ads_entry->lte = lte;
1448         return 0;
1449 }
1450 #endif
1451
1452 static int wimfs_symlink(const char *to, const char *from)
1453 {
1454         struct dentry *dentry_parent, *dentry;
1455         const char *link_name;
1456         struct inode *inode;
1457         
1458         dentry_parent = get_parent_dentry(w, from);
1459         if (!dentry_parent)
1460                 return -ENOENT;
1461         if (!dentry_is_directory(dentry_parent))
1462                 return -ENOTDIR;
1463
1464         link_name = path_basename(from);
1465
1466         if (get_dentry_child_with_name(dentry_parent, link_name))
1467                 return -EEXIST;
1468         dentry = new_dentry_with_inode(link_name);
1469         if (!dentry)
1470                 return -ENOMEM;
1471         inode = dentry->d_inode;
1472
1473         inode->attributes  = FILE_ATTRIBUTE_REPARSE_POINT;
1474         inode->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
1475         inode->ino         = next_ino++;
1476         inode->resolved    = true;
1477
1478         if (inode_set_symlink(inode, to, w->lookup_table, NULL) != 0)
1479                 goto out_free_dentry;
1480
1481         link_dentry(dentry, dentry_parent);
1482         return 0;
1483 out_free_dentry:
1484         free_dentry(dentry);
1485         return -ENOMEM;
1486 }
1487
1488
1489 /* Reduce the size of a file */
1490 static int wimfs_truncate(const char *path, off_t size)
1491 {
1492         struct dentry *dentry;
1493         struct lookup_table_entry *lte;
1494         int ret;
1495         u16 stream_idx;
1496         u32 stream_id;
1497         struct inode *inode;
1498         
1499         ret = lookup_resource(w, path, get_lookup_flags(), &dentry,
1500                               &lte, &stream_idx);
1501
1502         if (ret != 0)
1503                 return ret;
1504
1505         if (!lte) /* Already a zero-length file */
1506                 return 0;
1507
1508         inode = dentry->d_inode;
1509
1510         if (stream_idx == 0)
1511                 stream_id = 0;
1512         else
1513                 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
1514
1515         if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1516                 wimlib_assert(lte->staging_file_name);
1517                 ret = truncate(lte->staging_file_name, size);
1518                 if (ret != 0)
1519                         return -errno;
1520                 lte->resource_entry.original_size = size;
1521         } else {
1522                 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
1523                 /* File in WIM.  Extract it to the staging directory, but only
1524                  * the first @size bytes of it. */
1525                 ret = extract_resource_to_staging_dir(inode, stream_id,
1526                                                       &lte, size);
1527         }
1528         return ret;
1529 }
1530
1531 /* Remove a regular file */
1532 static int wimfs_unlink(const char *path)
1533 {
1534         struct dentry *dentry;
1535         struct lookup_table_entry *lte;
1536         struct inode *inode;
1537         int ret;
1538         u16 stream_idx;
1539         unsigned i;
1540         
1541         ret = lookup_resource(w, path, get_lookup_flags(), &dentry,
1542                               &lte, &stream_idx);
1543
1544         if (ret != 0)
1545                 return ret;
1546
1547         if (stream_idx == 0)
1548                 remove_dentry(dentry, w->lookup_table);
1549         else
1550                 inode_remove_ads(dentry->d_inode, stream_idx - 1, w->lookup_table);
1551         return 0;
1552 }
1553
1554 #ifdef HAVE_UTIMENSAT
1555 /* 
1556  * Change the timestamp on a file dentry. 
1557  *
1558  * Note that alternate data streams do not have their own timestamps.
1559  */
1560 static int wimfs_utimens(const char *path, const struct timespec tv[2])
1561 {
1562         struct dentry *dentry;
1563         struct inode *inode;
1564         dentry = get_dentry(w, path);
1565         if (!dentry)
1566                 return -ENOENT;
1567         inode = dentry->d_inode;
1568
1569         if (tv[0].tv_nsec != UTIME_OMIT) {
1570                 if (tv[0].tv_nsec == UTIME_NOW)
1571                         inode->last_access_time = get_wim_timestamp();
1572                 else
1573                         inode->last_access_time = timespec_to_wim_timestamp(&tv[0]);
1574         }
1575         if (tv[1].tv_nsec != UTIME_OMIT) {
1576                 if (tv[1].tv_nsec == UTIME_NOW)
1577                         inode->last_write_time = get_wim_timestamp();
1578                 else
1579                         inode->last_write_time = timespec_to_wim_timestamp(&tv[1]);
1580         }
1581         return 0;
1582 }
1583 #else
1584 static int wimfs_utime(const char *path, struct utimbuf *times)
1585 {
1586         struct dentry *dentry;
1587         struct inode *inode;
1588         dentry = get_dentry(w, path);
1589         if (!dentry)
1590                 return -ENOENT;
1591         inode = dentry->d_inode;
1592
1593         inode->last_write_time = unix_timestamp_to_wim(times->modtime);
1594         inode->last_access_time = unix_timestamp_to_wim(times->actime);
1595         return 0;
1596 }
1597 #endif
1598
1599 /* Writes to a file in the WIM filesystem. 
1600  * It may be an alternate data stream, but here we don't even notice because we
1601  * just get a lookup table entry. */
1602 static int wimfs_write(const char *path, const char *buf, size_t size, 
1603                        off_t offset, struct fuse_file_info *fi)
1604 {
1605         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1606         int ret;
1607         u64 now;
1608
1609         if (!fd)
1610                 return -EBADF;
1611
1612         wimlib_assert(fd->f_lte);
1613         wimlib_assert(fd->f_lte->staging_file_name);
1614         wimlib_assert(fd->staging_fd != -1);
1615         wimlib_assert(fd->f_inode);
1616
1617         /* Seek to the requested position */
1618         if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1619                 return -errno;
1620
1621         /* Write the data. */
1622         ret = write(fd->staging_fd, buf, size);
1623         if (ret == -1)
1624                 return -errno;
1625
1626         now = get_wim_timestamp();
1627         fd->f_inode->last_write_time = now;
1628         fd->f_inode->last_access_time = now;
1629         return ret;
1630 }
1631
1632 static struct fuse_operations wimfs_operations = {
1633         .access      = wimfs_access,
1634         .destroy     = wimfs_destroy,
1635 #if 0
1636         .fallocate   = wimfs_fallocate,
1637 #endif
1638         .fgetattr    = wimfs_fgetattr,
1639         .ftruncate   = wimfs_ftruncate,
1640         .getattr     = wimfs_getattr,
1641 #ifdef ENABLE_XATTR
1642         .getxattr    = wimfs_getxattr,
1643 #endif
1644         .link        = wimfs_link,
1645 #ifdef ENABLE_XATTR
1646         .listxattr   = wimfs_listxattr,
1647 #endif
1648         .mkdir       = wimfs_mkdir,
1649         .mknod       = wimfs_mknod,
1650         .open        = wimfs_open,
1651         .opendir     = wimfs_opendir,
1652         .read        = wimfs_read,
1653         .readdir     = wimfs_readdir,
1654         .readlink    = wimfs_readlink,
1655         .release     = wimfs_release,
1656         .releasedir  = wimfs_releasedir,
1657 #ifdef ENABLE_XATTR
1658         .removexattr = wimfs_removexattr,
1659 #endif
1660         .rename      = wimfs_rename,
1661         .rmdir       = wimfs_rmdir,
1662 #ifdef ENABLE_XATTR
1663         .setxattr    = wimfs_setxattr,
1664 #endif
1665         .symlink     = wimfs_symlink,
1666         .truncate    = wimfs_truncate,
1667         .unlink      = wimfs_unlink,
1668 #ifdef HAVE_UTIMENSAT
1669         .utimens     = wimfs_utimens,
1670 #else
1671         .utime       = wimfs_utime,
1672 #endif
1673         .write       = wimfs_write,
1674 };
1675
1676
1677 /* Mounts a WIM file. */
1678 WIMLIBAPI int wimlib_mount(WIMStruct *wim, int image, const char *dir, 
1679                            int flags, WIMStruct **additional_swms,
1680                            unsigned num_additional_swms)
1681 {
1682         int argc = 0;
1683         char *argv[16];
1684         int ret;
1685         char *p;
1686         struct lookup_table *joined_tab, *wim_tab_save;
1687         struct image_metadata *imd;
1688
1689         DEBUG("Mount: wim = %p, image = %d, dir = %s, flags = %d, ",
1690                         wim, image, dir, flags);
1691
1692         if (!wim || !dir)
1693                 return WIMLIB_ERR_INVALID_PARAM;
1694
1695         ret = verify_swm_set(wim, additional_swms, num_additional_swms);
1696         if (ret != 0)
1697                 return ret;
1698
1699         if (num_additional_swms) {
1700                 ret = new_joined_lookup_table(wim, additional_swms,
1701                                               num_additional_swms,
1702                                               &joined_tab);
1703                 if (ret != 0)
1704                         return ret;
1705                 wim_tab_save = wim->lookup_table;
1706                 wim->lookup_table = joined_tab;
1707         }
1708
1709         ret = wimlib_select_image(wim, image);
1710
1711         if (ret != 0)
1712                 goto out;
1713
1714         imd = &wim->image_metadata[image - 1];
1715
1716         DEBUG("Selected image %d", image);
1717
1718         next_ino = assign_inode_numbers(&imd->inode_list);
1719
1720         DEBUG("(next_ino = %"PRIu64")", next_ino);
1721
1722         /* Resolve all the lookup table entries of the dentry tree */
1723         DEBUG("Resolving lookup table entries");
1724         for_dentry_in_tree(imd->root_dentry, dentry_resolve_ltes,
1725                            wim->lookup_table);
1726
1727         if (flags & WIMLIB_MOUNT_FLAG_READWRITE)
1728                 imd->modified = true;
1729
1730         if (!(flags & (WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
1731                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
1732                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)))
1733                 flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
1734
1735         DEBUG("Getting current directory");
1736
1737         mount_dir = dir;
1738         working_directory = getcwd(NULL, 0);
1739         if (!working_directory) {
1740                 ERROR_WITH_ERRNO("Could not determine current directory");
1741                 ret = WIMLIB_ERR_NOTDIR;
1742                 goto out;
1743         }
1744
1745         DEBUG("Closing POSIX message queues");
1746         /* XXX hack to get rid of the message queues if they already exist for
1747          * some reason (maybe left over from a previous mount that wasn't
1748          * unmounted correctly) */
1749         ret = open_message_queues(true);
1750         if (ret != 0)
1751                 goto out;
1752         close_message_queues();
1753
1754         DEBUG("Preparing arguments to fuse_main()");
1755
1756
1757         p = STRDUP(dir);
1758         if (!p) {
1759                 ret = WIMLIB_ERR_NOMEM;
1760                 goto out;
1761         }
1762
1763         argv[argc++] = "imagex";
1764         argv[argc++] = p;
1765         argv[argc++] = "-s"; /* disable multi-threaded operation */
1766
1767         if (flags & WIMLIB_MOUNT_FLAG_DEBUG)
1768                 argv[argc++] = "-d";
1769
1770         /* 
1771          * We provide the use_ino option because we are going to assign inode
1772          * numbers oursides.  We've already numbered the inodes with unique
1773          * numbers in the assign_inode_numbers() function, and the static
1774          * variable next_ino is set to the next available inode number.
1775          */
1776         char optstring[256] = "use_ino,subtype=wimfs,attr_timeout=0";
1777         argv[argc++] = "-o";
1778         argv[argc++] = optstring;
1779         if ((flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
1780                 /* Read-write mount.  Make the staging directory */
1781                 make_staging_dir();
1782                 if (!staging_dir_name) {
1783                         FREE(p);
1784                         ret = WIMLIB_ERR_MKDIR;
1785                         goto out;
1786                 }
1787         } else {
1788                 /* Read-only mount */
1789                 strcat(optstring, ",ro");
1790         }
1791         argv[argc] = NULL;
1792
1793 #ifdef ENABLE_DEBUG
1794         {
1795                 int i;
1796                 DEBUG("FUSE command line (argc = %d): ", argc);
1797                 for (i = 0; i < argc; i++) {
1798                         fputs(argv[i], stdout);
1799                         putchar(' ');
1800                 }
1801                 putchar('\n');
1802                 fflush(stdout);
1803         }
1804 #endif
1805
1806         /* Set static variables. */
1807         w = wim;
1808         mount_flags = flags;
1809
1810         ret = fuse_main(argc, argv, &wimfs_operations, NULL);
1811         if (ret)
1812                 ret = WIMLIB_ERR_FUSE;
1813 out:
1814         if (num_additional_swms) {
1815                 free_lookup_table(wim->lookup_table);
1816                 wim->lookup_table = wim_tab_save;
1817         }
1818         return ret;
1819 }
1820
1821
1822 /* 
1823  * Unmounts the WIM file that was previously mounted on @dir by using
1824  * wimlib_mount().
1825  */
1826 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
1827 {
1828         pid_t pid;
1829         int status;
1830         int ret;
1831         char msg[2];
1832         struct timeval now;
1833         struct timespec timeout;
1834         int msgsize;
1835         int errno_save;
1836
1837         mount_dir = dir;
1838
1839         /* Open message queues between the unmount process and the
1840          * filesystem daemon. */
1841         ret = open_message_queues(false);
1842         if (ret != 0)
1843                 return ret;
1844
1845         /* Send a message to the filesystem saying whether to commit or
1846          * not. */
1847         msg[0] = (flags & WIMLIB_UNMOUNT_FLAG_COMMIT) ? 1 : 0;
1848         msg[1] = (flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY) ? 1 : 0;
1849
1850         DEBUG("Sending message: %s, %s", 
1851                         (msg[0] == 0) ? "don't commit" : "commit",
1852                         (msg[1] == 0) ? "don't check"  : "check");
1853         ret = mq_send(unmount_to_daemon_mq, msg, 2, 1);
1854         if (ret == -1) {
1855                 ERROR("Failed to notify filesystem daemon whether we want to "
1856                       "commit changes or not");
1857                 close_message_queues();
1858                 return WIMLIB_ERR_MQUEUE;
1859         }
1860
1861         /* Execute `fusermount -u', which is installed setuid root, to unmount
1862          * the WIM.
1863          *
1864          * FUSE does not yet implement synchronous unmounts.  This means that
1865          * fusermount -u will return before the filesystem daemon returns from
1866          * wimfs_destroy().  This is partly what we want, because we need to
1867          * send a message from this process to the filesystem daemon telling
1868          * whether --commit was specified or not.  However, after that, the
1869          * unmount process must wait for the filesystem daemon to finish writing
1870          * the WIM file. 
1871          */
1872
1873
1874         pid = fork();
1875         if (pid == -1) {
1876                 ERROR_WITH_ERRNO("Failed to fork()");
1877                 return WIMLIB_ERR_FORK;
1878         }
1879         if (pid == 0) {
1880                 execlp("fusermount", "fusermount", "-u", dir, NULL);
1881                 ERROR_WITH_ERRNO("Failed to execute `fusermount'");
1882                 exit(WIMLIB_ERR_FUSERMOUNT);
1883         }
1884
1885         ret = wait(&status);
1886         if (ret == -1) {
1887                 ERROR_WITH_ERRNO("Failed to wait for fusermount process to "
1888                                  "terminate");
1889                 return WIMLIB_ERR_FUSERMOUNT;
1890         }
1891
1892         if (status != 0) {
1893                 ERROR("fusermount exited with status %d", status);
1894
1895                 /* Try again, but with the `umount' program.  This is required
1896                  * on other FUSE implementations such as FreeBSD's that do not
1897                  * have a `fusermount' program. */
1898
1899                 pid = fork();
1900                 if (pid == -1) {
1901                         ERROR_WITH_ERRNO("Failed to fork()");
1902                         return WIMLIB_ERR_FORK;
1903                 }
1904                 if (pid == 0) {
1905                         execlp("umount", "umount", dir, NULL);
1906                         ERROR_WITH_ERRNO("Failed to execute `umount'");
1907                         exit(WIMLIB_ERR_FUSERMOUNT);
1908                 }
1909
1910                 ret = wait(&status);
1911                 if (ret == -1) {
1912                         ERROR_WITH_ERRNO("Failed to wait for `umount' process to "
1913                                          "terminate");
1914                         return WIMLIB_ERR_FUSERMOUNT;
1915                 }
1916                 if (status != 0) {
1917                         ERROR("`umount' exited with failure status");
1918                         return WIMLIB_ERR_FUSERMOUNT;
1919                 }
1920         }
1921
1922
1923         /* Wait for a message from the filesytem daemon indicating whether  the
1924          * filesystem was unmounted successfully (0) or an error occurred (1).
1925          * This may take a long time if a big WIM file needs to be rewritten. */
1926
1927         /* Wait at most 600??? seconds before giving up and returning false.
1928          * Either it's a really big WIM file, or (more likely) the
1929          * filesystem daemon has crashed or failed for some reason.
1930          *
1931          * XXX come up with some method to determine if the filesystem
1932          * daemon has really crashed or not. 
1933          *
1934          * XXX Idea: have mount daemon write its PID into the WIM file header?
1935          * */
1936
1937         gettimeofday(&now, NULL);
1938         timeout.tv_sec = now.tv_sec + 600;
1939         timeout.tv_nsec = now.tv_usec * 1000;
1940
1941         msgsize = mq_get_msgsize(daemon_to_unmount_mq);
1942         char mailbox[msgsize];
1943
1944         mailbox[0] = 0;
1945         DEBUG("Waiting for message telling us whether the unmount was "
1946                         "successful or not.");
1947         ret = mq_timedreceive(daemon_to_unmount_mq, mailbox, msgsize,
1948                               NULL, &timeout);
1949         errno_save = errno;
1950         close_message_queues();
1951         if (ret == -1) {
1952                 if (errno_save == ETIMEDOUT) {
1953                         ERROR("Timed out- probably the filesystem daemon "
1954                               "crashed and the WIM was not written "
1955                               "successfully.");
1956                         return WIMLIB_ERR_TIMEOUT;
1957                 } else {
1958                         ERROR("mq_receive(): %s", strerror(errno_save));
1959                         return WIMLIB_ERR_MQUEUE;
1960                 }
1961
1962         }
1963         DEBUG("Received message: %s",
1964               (mailbox[0] == 0) ?  "Unmount OK" : "Unmount Failed");
1965         if (mailbox[0] != 0)
1966                 ERROR("Unmount failed");
1967         return mailbox[0];
1968 }
1969
1970 #else /* WITH_FUSE */
1971
1972
1973 static inline int mount_unsupported_error()
1974 {
1975         ERROR("WIMLIB was compiled with --without-fuse, which disables support "
1976               "for mounting WIMs.");
1977         return WIMLIB_ERR_UNSUPPORTED;
1978 }
1979
1980 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
1981 {
1982         return mount_unsupported_error();
1983 }
1984
1985 WIMLIBAPI int wimlib_mount(WIMStruct *wim_p, int image, const char *dir, 
1986                            int flags, WIMStruct **additional_swms,
1987                            unsigned num_additional_swms)
1988 {
1989         return mount_unsupported_error();
1990 }
1991
1992 #endif /* WITH_FUSE */