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