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