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