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