]> wimlib.net Git - wimlib/blob - src/mount.c
rebuild_wim(): Fix possible problem with fd closing
[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 returns its name into the
501  * static variable staging_dir_name.
502  *
503  * If the staging directory cannot be created, staging_dir_name is set to NULL.
504  * */
505 static int make_staging_dir(struct wimfs_context *ctx)
506 {
507         /* XXX Give the user an option of where to stage files */
508
509         static const char prefix[] = "wimlib-staging-";
510         static const size_t prefix_len = sizeof(prefix) - 1;
511         static const size_t random_suffix_len = 10;
512
513         size_t pwd_len = strlen(ctx->working_directory);
514
515         ctx->staging_dir_name_len = pwd_len + 1 + prefix_len + random_suffix_len;
516
517         ctx->staging_dir_name = MALLOC(ctx->staging_dir_name_len + 1);
518         if (!ctx->staging_dir_name)
519                 return WIMLIB_ERR_NOMEM;
520
521         memcpy(ctx->staging_dir_name, ctx->working_directory, pwd_len);
522         ctx->staging_dir_name[pwd_len] = '/';
523         memcpy(ctx->staging_dir_name + pwd_len + 1, prefix, prefix_len);
524         randomize_char_array_with_alnum(ctx->staging_dir_name + pwd_len +
525                                         1 + prefix_len, random_suffix_len);
526         ctx->staging_dir_name[ctx->staging_dir_name_len] = '\0';
527
528         if (mkdir(ctx->staging_dir_name, 0700) != 0) {
529                 ERROR_WITH_ERRNO("Failed to create temporary directory `%s'",
530                                  ctx->staging_dir_name);
531                 FREE(ctx->staging_dir_name);
532                 ctx->staging_dir_name = NULL;
533                 return WIMLIB_ERR_MKDIR;
534         }
535         return 0;
536 }
537
538 static int remove_file_or_directory(const char *fpath, const struct stat *sb,
539                                     int typeflag, struct FTW *ftwbuf)
540 {
541         if (remove(fpath) == 0)
542                 return 0;
543         else {
544                 ERROR_WITH_ERRNO("Cannot remove `%s'", fpath);
545                 return WIMLIB_ERR_DELETE_STAGING_DIR;
546         }
547 }
548
549
550 /*
551  * Deletes the staging directory and all the files contained in it.
552  */
553 static int delete_staging_dir(struct wimfs_context *ctx)
554 {
555         int ret;
556         wimlib_assert(ctx->staging_dir_name != NULL);
557         ret = nftw(ctx->staging_dir_name, remove_file_or_directory,
558                    10, FTW_DEPTH);
559         FREE(ctx->staging_dir_name);
560         ctx->staging_dir_name = NULL;
561         return ret;
562 }
563
564
565 /* Simple function that returns the concatenation of 2 strings. */
566 static char *strcat_dup(const char *s1, const char *s2, size_t max_len)
567 {
568         size_t len = strlen(s1) + strlen(s2);
569         if (len > max_len)
570                 len = max_len;
571         char *p = MALLOC(len + 1);
572         if (!p)
573                 return NULL;
574         snprintf(p, len + 1, "%s%s", s1, s2);
575         return p;
576 }
577
578 static int set_message_queue_names(struct wimfs_context *ctx,
579                                    const char *mount_dir)
580 {
581         static const char *u2d_prefix = "/wimlib-unmount-to-daemon-mq";
582         static const char *d2u_prefix = "/wimlib-daemon-to-unmount-mq";
583         char *dir_path;
584         char *p;
585         int ret;
586
587         dir_path = realpath(mount_dir, NULL);
588         if (!dir_path) {
589                 ERROR_WITH_ERRNO("Failed to resolve path \"%s\"", mount_dir);
590                 return WIMLIB_ERR_NOTDIR;
591         }
592
593         DEBUG("Using absolute dir_path = `%s'", dir_path);
594
595
596         p = dir_path;
597         while (*p) {
598                 if (*p == '/')
599                         *p = 0xff;
600                 p++;
601         }
602
603         ctx->unmount_to_daemon_mq_name = strcat_dup(u2d_prefix, dir_path,
604                                                     NAME_MAX);
605         if (!ctx->unmount_to_daemon_mq_name) {
606                 ret = WIMLIB_ERR_NOMEM;
607                 goto out_free_dir_path;
608         }
609         ctx->daemon_to_unmount_mq_name = strcat_dup(d2u_prefix, dir_path,
610                                                     NAME_MAX);
611         if (!ctx->daemon_to_unmount_mq_name) {
612                 ret = WIMLIB_ERR_NOMEM;
613                 goto out_free_unmount_to_daemon_mq_name;
614         }
615
616         ret = 0;
617         goto out_free_dir_path;
618 out_free_unmount_to_daemon_mq_name:
619         FREE(ctx->unmount_to_daemon_mq_name);
620         ctx->unmount_to_daemon_mq_name = NULL;
621 out_free_dir_path:
622         FREE(dir_path);
623         return ret;
624 }
625
626 static void free_message_queue_names(struct wimfs_context *ctx)
627 {
628         FREE(ctx->unmount_to_daemon_mq_name);
629         FREE(ctx->daemon_to_unmount_mq_name);
630         ctx->unmount_to_daemon_mq_name = NULL;
631         ctx->daemon_to_unmount_mq_name = NULL;
632 }
633
634 /*
635  * Opens two POSIX message queue: one for sending messages from the unmount
636  * process to the daemon process, and one to go the other way.  The names of the
637  * message queues, which must be system-wide unique, are be based on the mount
638  * point.  (There of course is still a possibility of a collision if one were to
639  * unmount two identically named directories simultaneously...)
640  *
641  * @daemon specifies whether the calling process is the filesystem daemon or the
642  * unmount process.
643  */
644 static int open_message_queues(struct wimfs_context *ctx, bool daemon)
645 {
646         int flags;
647         int ret;
648
649         wimlib_assert(ctx->unmount_to_daemon_mq_name != NULL &&
650                       ctx->daemon_to_unmount_mq_name != NULL);
651
652         if (daemon)
653                 flags = O_RDONLY | O_CREAT;
654         else
655                 flags = O_WRONLY | O_CREAT;
656
657         DEBUG("Opening message queue \"%s\"", ctx->unmount_to_daemon_mq_name);
658         ctx->unmount_to_daemon_mq = mq_open(ctx->unmount_to_daemon_mq_name,
659                                             flags, 0700, NULL);
660
661         if (ctx->unmount_to_daemon_mq == (mqd_t)-1) {
662                 ERROR_WITH_ERRNO("mq_open()");
663                 ret = WIMLIB_ERR_MQUEUE;
664                 goto out;
665         }
666
667         if (daemon)
668                 flags = O_WRONLY | O_CREAT;
669         else
670                 flags = O_RDONLY | O_CREAT;
671
672         DEBUG("Opening message queue \"%s\"", ctx->daemon_to_unmount_mq_name);
673         ctx->daemon_to_unmount_mq = mq_open(ctx->daemon_to_unmount_mq_name,
674                                             flags, 0700, NULL);
675
676         if (ctx->daemon_to_unmount_mq == (mqd_t)-1) {
677                 ERROR_WITH_ERRNO("mq_open()");
678                 ret = WIMLIB_ERR_MQUEUE;
679                 goto out_close_unmount_to_daemon_mq;
680         }
681         ret = 0;
682         goto out;
683 out_close_unmount_to_daemon_mq:
684         mq_close(ctx->unmount_to_daemon_mq);
685         mq_unlink(ctx->unmount_to_daemon_mq_name);
686         ctx->unmount_to_daemon_mq = (mqd_t)-1;
687 out:
688         return ret;
689 }
690
691 /* Try to determine the maximum message size of a message queue.  The return
692  * value is the maximum message size, or a guess of 8192 bytes if it cannot be
693  * determined. */
694 static long mq_get_msgsize(mqd_t mq)
695 {
696         static const char *msgsize_max_file = "/proc/sys/fs/mqueue/msgsize_max";
697         FILE *fp;
698         struct mq_attr attr;
699         long msgsize;
700
701         if (mq_getattr(mq, &attr) == 0) {
702                 msgsize = attr.mq_msgsize;
703         } else {
704                 ERROR_WITH_ERRNO("mq_getattr()");
705                 ERROR("Attempting to read %s", msgsize_max_file);
706                 fp = fopen(msgsize_max_file, "rb");
707                 if (fp) {
708                         if (fscanf(fp, "%ld", &msgsize) != 1) {
709                                 ERROR("Assuming message size of 8192");
710                                 msgsize = 8192;
711                         }
712                         fclose(fp);
713                 } else {
714                         ERROR_WITH_ERRNO("Failed to open the file `%s'",
715                                          msgsize_max_file);
716                         ERROR("Assuming message size of 8192");
717                         msgsize = 8192;
718                 }
719         }
720         return msgsize;
721 }
722
723 static int get_mailbox(mqd_t mq, long needed_msgsize, long *msgsize_ret,
724                        char **mailbox_ret)
725 {
726         long msgsize;
727         char *mailbox;
728
729         msgsize = mq_get_msgsize(mq);
730
731         if (msgsize < needed_msgsize) {
732                 ERROR("Message queue max size must be at least %ld!",
733                       needed_msgsize);
734                 return WIMLIB_ERR_MQUEUE;
735         }
736
737         mailbox = MALLOC(msgsize);
738         if (!mailbox) {
739                 ERROR("Failed to allocate %ld bytes for mailbox", msgsize);
740                 return WIMLIB_ERR_NOMEM;
741         }
742         *msgsize_ret = msgsize;
743         *mailbox_ret = mailbox;
744         return 0;
745 }
746
747 static void unlink_message_queues(struct wimfs_context *ctx)
748 {
749         mq_unlink(ctx->unmount_to_daemon_mq_name);
750         mq_unlink(ctx->daemon_to_unmount_mq_name);
751 }
752
753 /* Closes the message queues, which are allocated in static variables */
754 static void close_message_queues(struct wimfs_context *ctx)
755 {
756         mq_close(ctx->unmount_to_daemon_mq);
757         ctx->unmount_to_daemon_mq = (mqd_t)(-1);
758         mq_close(ctx->daemon_to_unmount_mq);
759         ctx->daemon_to_unmount_mq = (mqd_t)(-1);
760         unlink_message_queues(ctx);
761 }
762
763 static int wimfs_access(const char *path, int mask)
764 {
765         /* Permissions not implemented */
766         return 0;
767 }
768
769 static int wimfs_chmod(const char *path, mode_t mask)
770 {
771         struct dentry *dentry;
772         struct wimfs_context *ctx = wimfs_get_context();
773         struct inode *inode;
774         struct stat stbuf;
775         int ret;
776
777         ret = lookup_resource(ctx->wim, path,
778                               get_lookup_flags(ctx) | LOOKUP_FLAG_DIRECTORY_OK,
779                               &dentry, NULL, NULL);
780         if (ret != 0)
781                 return ret;
782         inode = dentry->d_inode;
783         inode_to_stbuf(inode, NULL, &stbuf);
784         if (mask == stbuf.st_mode)
785                 return 0;
786         else
787                 return -EPERM;
788
789 }
790
791 static void inode_update_lte_ptr(struct inode *inode,
792                                  struct lookup_table_entry *old_lte,
793                                  struct lookup_table_entry *new_lte)
794 {
795         if (inode->lte == old_lte) {
796                 inode->lte = new_lte;
797         } else {
798                 for (unsigned i = 0; i < inode->num_ads; i++) {
799                         if (inode->ads_entries[i].lte == old_lte) {
800                                 inode->ads_entries[i].lte = new_lte;
801                                 break;
802                         }
803                 }
804         }
805 }
806
807 static int update_lte_of_staging_file(struct lookup_table_entry *lte,
808                                       struct lookup_table *table)
809 {
810         struct lookup_table_entry *duplicate_lte;
811         int ret;
812         u8 hash[SHA1_HASH_SIZE];
813         struct stat stbuf;
814
815         wimlib_assert(lte->resource_location == RESOURCE_IN_STAGING_FILE);
816         wimlib_assert(lte->staging_file_name);
817
818         ret = sha1sum(lte->staging_file_name, hash);
819         if (ret != 0)
820                 return ret;
821
822         lookup_table_unlink(table, lte);
823
824         duplicate_lte = __lookup_resource(table, hash);
825
826         if (duplicate_lte) {
827                 /* Merge duplicate lookup table entries */
828                 duplicate_lte->refcnt += lte->refcnt;
829                 list_del(&lte->staging_list);
830                 inode_update_lte_ptr(lte->lte_inode, lte, duplicate_lte);
831                 free_lookup_table_entry(lte);
832         } else {
833                 if (stat(lte->staging_file_name, &stbuf) != 0) {
834                         ERROR_WITH_ERRNO("Failed to stat `%s'", lte->staging_file_name);
835                         return WIMLIB_ERR_STAT;
836                 }
837                 if (stbuf.st_size == 0) {
838                         /* Zero-length stream.  No lookup table entry needed. */
839                         inode_update_lte_ptr(lte->lte_inode, lte, NULL);
840                         free_lookup_table_entry(lte);
841                 } else {
842                         wimlib_assert(&lte->file_on_disk == &lte->staging_file_name);
843                         lte->resource_entry.original_size = stbuf.st_size;
844                         lte->resource_entry.size = stbuf.st_size;
845                         lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
846                         lte->lte_inode = NULL;
847                         copy_hash(lte->hash, hash);
848                         lookup_table_insert(table, lte);
849                 }
850         }
851         return 0;
852 }
853
854 static int inode_close_fds(struct inode *inode)
855 {
856         u16 num_opened_fds = inode->num_opened_fds;
857         for (u16 i = 0, j = 0; j < num_opened_fds; i++) {
858                 struct wimlib_fd *fd = inode->fds[i];
859                 if (fd) {
860                         wimlib_assert(fd->f_inode == inode);
861                         int ret = close_wimlib_fd(fd);
862                         if (ret != 0)
863                                 return ret;
864                         j++;
865                 }
866         }
867         return 0;
868 }
869
870 /* Overwrites the WIM file, with changes saved. */
871 static int rebuild_wim(struct wimfs_context *ctx, bool check_integrity)
872 {
873         int ret;
874         struct lookup_table_entry *lte, *tmp;
875         WIMStruct *w = ctx->wim;
876
877
878         DEBUG("Closing all staging file descriptors.");
879         list_for_each_entry_safe(lte, tmp, &ctx->staging_list, staging_list) {
880                 ret = inode_close_fds(lte->lte_inode);
881                 if (ret != 0)
882                         return ret;
883         }
884
885         DEBUG("Calculating SHA1 checksums for all new staging files.");
886         list_for_each_entry_safe(lte, tmp, &ctx->staging_list, staging_list) {
887                 ret = update_lte_of_staging_file(lte, ctx->wim->lookup_table);
888                 if (ret != 0)
889                         return ret;
890         }
891
892         xml_update_image_info(w, w->current_image);
893
894         ret = wimlib_overwrite(w, check_integrity);
895         if (ret != 0) {
896                 ERROR("Failed to commit changes");
897                 return ret;
898         }
899         return ret;
900 }
901
902 /* Called when the filesystem is unmounted. */
903 static void wimfs_destroy(void *p)
904 {
905         /* For read-write mounts, the `imagex unmount' command, which is
906          * running in a separate process and is executing the
907          * wimlib_unmount() function, will send this process a byte
908          * through a message queue that indicates whether the --commit
909          * option was specified or not. */
910
911         long msgsize;
912         struct timespec timeout;
913         struct timeval now;
914         ssize_t bytes_received;
915         int ret;
916         char commit;
917         char check_integrity;
918         char status;
919         char *mailbox;
920         struct wimfs_context *ctx = wimfs_get_context();
921
922         if (open_message_queues(ctx, true))
923                 return;
924
925         if (get_mailbox(ctx->unmount_to_daemon_mq, 2, &msgsize, &mailbox))
926                 goto out_close_message_queues;
927
928         /* Wait at most 3 seconds before giving up and discarding changes. */
929         gettimeofday(&now, NULL);
930         timeout.tv_sec = now.tv_sec + 3;
931         timeout.tv_nsec = now.tv_usec * 1000;
932         DEBUG("Waiting for message telling us whether to commit or not, and "
933               "whether to include integrity checks.");
934
935         bytes_received = mq_timedreceive(ctx->unmount_to_daemon_mq, mailbox,
936                                          msgsize, NULL, &timeout);
937         if (bytes_received == -1) {
938                 ERROR_WITH_ERRNO("mq_timedreceive()");
939                 ERROR("Not committing.");
940                 commit = 0;
941                 check_integrity = 0;
942         } else {
943                 DEBUG("Received message: [%d %d]", mailbox[0], mailbox[1]);
944                 commit = mailbox[0];
945                 check_integrity = mailbox[1];
946         }
947
948         status = 0;
949         if (ctx->mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
950                 if (commit) {
951                         ret = chdir(ctx->working_directory);
952                         if (ret == 0) {
953                                 status = rebuild_wim(ctx, (check_integrity != 0));
954                         } else {
955                                 ERROR_WITH_ERRNO("chdir()");
956                                 status = WIMLIB_ERR_NOTDIR;
957                         }
958                 }
959                 ret = delete_staging_dir(ctx);
960                 if (ret != 0) {
961                         ERROR("Failed to delete the staging directory");
962                         if (status == 0)
963                                 status = ret;
964                 }
965         } else {
966                 DEBUG("Read-only mount");
967         }
968         DEBUG("Sending status %hhd", status);
969         ret = mq_send(ctx->daemon_to_unmount_mq, &status, 1, 1);
970         if (ret == -1)
971                 ERROR_WITH_ERRNO("Failed to send status to unmount process");
972         FREE(mailbox);
973 out_close_message_queues:
974         close_message_queues(ctx);
975 }
976
977 #if 0
978 static int wimfs_fallocate(const char *path, int mode,
979                            off_t offset, off_t len, struct fuse_file_info *fi)
980 {
981         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
982         wimlib_assert(fd->staging_fd != -1);
983         return fallocate(fd->staging_fd, mode, offset, len);
984 }
985
986 #endif
987
988 static int wimfs_fgetattr(const char *path, struct stat *stbuf,
989                           struct fuse_file_info *fi)
990 {
991         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
992         return inode_to_stbuf(fd->f_inode, fd->f_lte, stbuf);
993 }
994
995 static int wimfs_ftruncate(const char *path, off_t size,
996                            struct fuse_file_info *fi)
997 {
998         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
999         int ret = ftruncate(fd->staging_fd, size);
1000         if (ret != 0)
1001                 return -errno;
1002         if (fd->f_lte && size < fd->f_lte->resource_entry.original_size)
1003                 fd->f_lte->resource_entry.original_size = size;
1004         return 0;
1005 }
1006
1007 /*
1008  * Fills in a `struct stat' that corresponds to a file or directory in the WIM.
1009  */
1010 static int wimfs_getattr(const char *path, struct stat *stbuf)
1011 {
1012         struct dentry *dentry;
1013         struct lookup_table_entry *lte;
1014         int ret;
1015         struct wimfs_context *ctx = wimfs_get_context();
1016
1017         ret = lookup_resource(ctx->wim, path,
1018                               get_lookup_flags(ctx) | LOOKUP_FLAG_DIRECTORY_OK,
1019                               &dentry, &lte, NULL);
1020         if (ret != 0)
1021                 return ret;
1022         return inode_to_stbuf(dentry->d_inode, lte, stbuf);
1023 }
1024
1025 #ifdef ENABLE_XATTR
1026 /* Read an alternate data stream through the XATTR interface, or get its size */
1027 static int wimfs_getxattr(const char *path, const char *name, char *value,
1028                           size_t size)
1029 {
1030         int ret;
1031         struct inode *inode;
1032         struct ads_entry *ads_entry;
1033         size_t res_size;
1034         struct lookup_table_entry *lte;
1035         struct wimfs_context *ctx = wimfs_get_context();
1036
1037         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1038                 return -ENOTSUP;
1039
1040         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1041                 return -ENOATTR;
1042         name += 5;
1043
1044         inode = wim_pathname_to_inode(ctx->wim, path);
1045         if (!inode)
1046                 return -ENOENT;
1047
1048         ads_entry = inode_get_ads_entry(inode, name, NULL);
1049         if (!ads_entry)
1050                 return -ENOATTR;
1051
1052         lte = ads_entry->lte;
1053         res_size = wim_resource_size(lte);
1054
1055         if (size == 0)
1056                 return res_size;
1057
1058         if (res_size > size)
1059                 return -ERANGE;
1060
1061         ret = read_full_wim_resource(lte, (u8*)value);
1062         if (ret != 0)
1063                 return -EIO;
1064
1065         return res_size;
1066 }
1067 #endif
1068
1069 /* Create a hard link */
1070 static int wimfs_link(const char *to, const char *from)
1071 {
1072         struct dentry *from_dentry, *from_dentry_parent;
1073         const char *link_name;
1074         struct inode *inode;
1075         struct lookup_table_entry *lte;
1076         WIMStruct *w = wimfs_get_WIMStruct();
1077
1078         inode = wim_pathname_to_inode(w, to);
1079         if (!inode)
1080                 return -ENOENT;
1081
1082         if (!inode_is_regular_file(inode))
1083                 return -EPERM;
1084
1085         from_dentry_parent = get_parent_dentry(w, from);
1086         if (!from_dentry_parent)
1087                 return -ENOENT;
1088         if (!dentry_is_directory(from_dentry_parent))
1089                 return -ENOTDIR;
1090
1091         link_name = path_basename(from);
1092         if (get_dentry_child_with_name(from_dentry_parent, link_name))
1093                 return -EEXIST;
1094         from_dentry = new_dentry(link_name);
1095         if (!from_dentry)
1096                 return -ENOMEM;
1097
1098
1099         inode_add_dentry(from_dentry, inode);
1100         from_dentry->d_inode = inode;
1101         inode->link_count++;
1102
1103         for (unsigned i = 0; i <= inode->num_ads; i++) {
1104                 lte = inode_stream_lte_resolved(inode, i);
1105                 if (lte)
1106                         lte->refcnt++;
1107         }
1108
1109         dentry_add_child(from_dentry_parent, from_dentry);
1110         return 0;
1111 }
1112
1113 #ifdef ENABLE_XATTR
1114 static int wimfs_listxattr(const char *path, char *list, size_t size)
1115 {
1116         size_t needed_size;
1117         struct inode *inode;
1118         struct wimfs_context *ctx = wimfs_get_context();
1119
1120         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1121                 return -ENOTSUP;
1122
1123         /* List alternate data streams, or get the list size */
1124
1125         inode = wim_pathname_to_inode(ctx->wim, path);
1126         if (!inode)
1127                 return -ENOENT;
1128
1129         if (size == 0) {
1130                 needed_size = 0;
1131                 for (u16 i = 0; i < inode->num_ads; i++)
1132                         needed_size += inode->ads_entries[i].stream_name_utf8_len + 6;
1133                 return needed_size;
1134         } else {
1135                 char *p = list;
1136                 for (u16 i = 0; i < inode->num_ads; i++) {
1137                         needed_size = inode->ads_entries[i].stream_name_utf8_len + 6;
1138                         if (needed_size > size)
1139                                 return -ERANGE;
1140                         p += sprintf(p, "user.%s",
1141                                      inode->ads_entries[i].stream_name_utf8) + 1;
1142                         size -= needed_size;
1143                 }
1144                 return p - list;
1145         }
1146 }
1147 #endif
1148
1149 /*
1150  * Create a directory in the WIM.
1151  * @mode is currently ignored.
1152  */
1153 static int wimfs_mkdir(const char *path, mode_t mode)
1154 {
1155         struct dentry *parent;
1156         struct dentry *newdir;
1157         const char *basename;
1158         struct wimfs_context *ctx = wimfs_get_context();
1159
1160         parent = get_parent_dentry(ctx->wim, path);
1161         if (!parent)
1162                 return -ENOENT;
1163
1164         if (!dentry_is_directory(parent))
1165                 return -ENOTDIR;
1166
1167         basename = path_basename(path);
1168         if (get_dentry_child_with_name(parent, basename))
1169                 return -EEXIST;
1170
1171         newdir = new_dentry_with_inode(basename);
1172         newdir->d_inode->attributes |= FILE_ATTRIBUTE_DIRECTORY;
1173         newdir->d_inode->resolved = true;
1174         newdir->d_inode->ino = ctx->next_ino++;
1175         dentry_add_child(parent, newdir);
1176         return 0;
1177 }
1178
1179 /* Creates a regular file. */
1180 static int wimfs_mknod(const char *path, mode_t mode, dev_t rdev)
1181 {
1182         const char *stream_name;
1183         struct wimfs_context *ctx = wimfs_get_context();
1184         if ((ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)
1185              && (stream_name = path_stream_name(path))) {
1186                 /* Make an alternate data stream */
1187                 struct ads_entry *new_entry;
1188                 struct inode *inode;
1189
1190                 char *p = (char*)stream_name - 1;
1191                 wimlib_assert(*p == ':');
1192                 *p = '\0';
1193
1194                 inode = wim_pathname_to_inode(ctx->wim, path);
1195                 if (!inode)
1196                         return -ENOENT;
1197                 if (!inode_is_regular_file(inode))
1198                         return -ENOENT;
1199                 if (inode_get_ads_entry(inode, stream_name, NULL))
1200                         return -EEXIST;
1201                 new_entry = inode_add_ads(inode, stream_name);
1202                 if (!new_entry)
1203                         return -ENOMEM;
1204         } else {
1205                 struct dentry *dentry, *parent;
1206                 const char *basename;
1207
1208                 /* Make a normal file (not an alternate data stream) */
1209
1210                 /* Make sure that the parent of @path exists and is a directory, and
1211                  * that the dentry named by @path does not already exist.  */
1212                 parent = get_parent_dentry(ctx->wim, path);
1213                 if (!parent)
1214                         return -ENOENT;
1215                 if (!dentry_is_directory(parent))
1216                         return -ENOTDIR;
1217
1218                 basename = path_basename(path);
1219                 if (get_dentry_child_with_name(parent, path))
1220                         return -EEXIST;
1221
1222                 dentry = new_dentry_with_inode(basename);
1223                 if (!dentry)
1224                         return -ENOMEM;
1225                 dentry->d_inode->resolved = true;
1226                 dentry->d_inode->ino = ctx->next_ino++;
1227                 dentry_add_child(parent, dentry);
1228         }
1229         return 0;
1230 }
1231
1232
1233 /* Open a file.  */
1234 static int wimfs_open(const char *path, struct fuse_file_info *fi)
1235 {
1236         struct dentry *dentry;
1237         struct lookup_table_entry *lte;
1238         int ret;
1239         struct wimlib_fd *fd;
1240         struct inode *inode;
1241         u16 stream_idx;
1242         u32 stream_id;
1243         struct wimfs_context *ctx = wimfs_get_context();
1244
1245         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1246                               &dentry, &lte, &stream_idx);
1247         if (ret != 0)
1248                 return ret;
1249
1250         inode = dentry->d_inode;
1251
1252         if (stream_idx == 0)
1253                 stream_id = 0;
1254         else
1255                 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
1256
1257         /* The file resource may be in the staging directory (read-write mounts
1258          * only) or in the WIM.  If it's in the staging directory, we need to
1259          * open a native file descriptor for the corresponding file.  Otherwise,
1260          * we can read the file resource directly from the WIM file if we are
1261          * opening it read-only, but we need to extract the resource to the
1262          * staging directory if we are opening it writable. */
1263
1264         if (flags_writable(fi->flags) &&
1265             (!lte || lte->resource_location != RESOURCE_IN_STAGING_FILE)) {
1266                 u64 size = (lte) ? wim_resource_size(lte) : 0;
1267                 ret = extract_resource_to_staging_dir(inode, stream_id,
1268                                                       &lte, size, ctx);
1269                 if (ret != 0)
1270                         return ret;
1271         }
1272
1273         ret = alloc_wimlib_fd(inode, stream_id, lte, &fd);
1274         if (ret != 0)
1275                 return ret;
1276
1277         if (lte && lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1278                 fd->staging_fd = open(lte->staging_file_name, fi->flags);
1279                 if (fd->staging_fd == -1) {
1280                         close_wimlib_fd(fd);
1281                         return -errno;
1282                 }
1283         }
1284         fi->fh = (uintptr_t)fd;
1285         return 0;
1286 }
1287
1288 /* Opens a directory. */
1289 static int wimfs_opendir(const char *path, struct fuse_file_info *fi)
1290 {
1291         struct inode *inode;
1292         int ret;
1293         struct wimlib_fd *fd = NULL;
1294         WIMStruct *w = wimfs_get_WIMStruct();
1295
1296         inode = wim_pathname_to_inode(w, path);
1297         if (!inode)
1298                 return -ENOENT;
1299         if (!inode_is_directory(inode))
1300                 return -ENOTDIR;
1301         ret = alloc_wimlib_fd(inode, 0, NULL, &fd);
1302         fi->fh = (uintptr_t)fd;
1303         return ret;
1304 }
1305
1306
1307 /*
1308  * Read data from a file in the WIM or in the staging directory.
1309  */
1310 static int wimfs_read(const char *path, char *buf, size_t size,
1311                       off_t offset, struct fuse_file_info *fi)
1312 {
1313         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1314
1315         if (!fd)
1316                 return -EBADF;
1317
1318         if (!fd->f_lte) /* Empty stream with no lookup table entry */
1319                 return 0;
1320
1321         if (fd->f_lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1322                 /* Read from staging file */
1323
1324                 wimlib_assert(fd->f_lte->staging_file_name);
1325                 wimlib_assert(fd->staging_fd != -1);
1326
1327                 ssize_t ret;
1328                 DEBUG("Seek to offset %zu", offset);
1329
1330                 if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1331                         return -errno;
1332                 ret = read(fd->staging_fd, buf, size);
1333                 if (ret == -1)
1334                         return -errno;
1335                 return ret;
1336         } else {
1337                 /* Read from WIM */
1338
1339                 u64 res_size = wim_resource_size(fd->f_lte);
1340
1341                 if (offset > res_size)
1342                         return -EOVERFLOW;
1343
1344                 size = min(size, res_size - offset);
1345
1346                 if (read_wim_resource(fd->f_lte, (u8*)buf,
1347                                       size, offset, false) != 0)
1348                         return -EIO;
1349                 return size;
1350         }
1351 }
1352
1353 struct fill_params {
1354         void *buf;
1355         fuse_fill_dir_t filler;
1356 };
1357
1358 static int dentry_fuse_fill(struct dentry *dentry, void *arg)
1359 {
1360         struct fill_params *fill_params = arg;
1361         return fill_params->filler(fill_params->buf, dentry->file_name_utf8,
1362                                    NULL, 0);
1363 }
1364
1365 /* Fills in the entries of the directory specified by @path using the
1366  * FUSE-provided function @filler.  */
1367 static int wimfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
1368                          off_t offset, struct fuse_file_info *fi)
1369 {
1370         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1371         struct inode *inode;
1372
1373         if (!fd)
1374                 return -EBADF;
1375
1376         inode = fd->f_inode;
1377
1378         struct fill_params fill_params = {
1379                 .buf = buf,
1380                 .filler = filler,
1381         };
1382
1383         filler(buf, ".", NULL, 0);
1384         filler(buf, "..", NULL, 0);
1385
1386         return for_dentry_in_rbtree(inode->children.rb_node,
1387                                     dentry_fuse_fill, &fill_params);
1388 }
1389
1390
1391 static int wimfs_readlink(const char *path, char *buf, size_t buf_len)
1392 {
1393         struct wimfs_context *ctx = wimfs_get_context();
1394         struct inode *inode = wim_pathname_to_inode(ctx->wim, path);
1395         int ret;
1396         if (!inode)
1397                 return -ENOENT;
1398         if (!inode_is_symlink(inode))
1399                 return -EINVAL;
1400
1401         ret = inode_readlink(inode, buf, buf_len, ctx->wim);
1402         if (ret > 0)
1403                 ret = 0;
1404         return ret;
1405 }
1406
1407 /* Close a file. */
1408 static int wimfs_release(const char *path, struct fuse_file_info *fi)
1409 {
1410         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1411         return close_wimlib_fd(fd);
1412 }
1413
1414 /* Close a directory */
1415 static int wimfs_releasedir(const char *path, struct fuse_file_info *fi)
1416 {
1417         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1418         return close_wimlib_fd(fd);
1419 }
1420
1421 #ifdef ENABLE_XATTR
1422 /* Remove an alternate data stream through the XATTR interface */
1423 static int wimfs_removexattr(const char *path, const char *name)
1424 {
1425         struct inode *inode;
1426         struct ads_entry *ads_entry;
1427         u16 ads_idx;
1428         struct wimfs_context *ctx = wimfs_get_context();
1429
1430         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1431                 return -ENOTSUP;
1432
1433         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1434                 return -ENOATTR;
1435         name += 5;
1436
1437         inode = wim_pathname_to_inode(ctx->wim, path);
1438         if (!inode)
1439                 return -ENOENT;
1440
1441         ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
1442         if (!ads_entry)
1443                 return -ENOATTR;
1444         inode_remove_ads(inode, ads_idx, ctx->wim->lookup_table);
1445         return 0;
1446 }
1447 #endif
1448
1449 /* Renames a file or directory.  See rename (3) */
1450 static int wimfs_rename(const char *from, const char *to)
1451 {
1452         struct dentry *src;
1453         struct dentry *dst;
1454         struct dentry *parent_of_dst;
1455         char *file_name_utf16 = NULL, *file_name_utf8 = NULL;
1456         u16 file_name_utf16_len, file_name_utf8_len;
1457         WIMStruct *w = wimfs_get_WIMStruct();
1458         int ret;
1459
1460         /* This rename() implementation currently only supports actual files
1461          * (not alternate data streams) */
1462
1463         src = get_dentry(w, from);
1464         if (!src)
1465                 return -ENOENT;
1466
1467         dst = get_dentry(w, to);
1468
1469
1470         ret = get_names(&file_name_utf16, &file_name_utf8,
1471                         &file_name_utf16_len, &file_name_utf8_len,
1472                         path_basename(to));
1473         if (ret != 0)
1474                 return -ENOMEM;
1475
1476         if (dst) {
1477                 /* Destination file exists */
1478
1479                 if (src == dst) /* Same file */
1480                         return 0;
1481
1482                 if (!dentry_is_directory(src)) {
1483                         /* Cannot rename non-directory to directory. */
1484                         if (dentry_is_directory(dst))
1485                                 return -EISDIR;
1486                 } else {
1487                         /* Cannot rename directory to a non-directory or a non-empty
1488                          * directory */
1489                         if (!dentry_is_directory(dst))
1490                                 return -ENOTDIR;
1491                         if (inode_has_children(dst->d_inode))
1492                                 return -ENOTEMPTY;
1493                 }
1494                 parent_of_dst = dst->parent;
1495                 remove_dentry(dst, w->lookup_table);
1496         } else {
1497                 /* Destination does not exist */
1498                 parent_of_dst = get_parent_dentry(w, to);
1499                 if (!parent_of_dst)
1500                         return -ENOENT;
1501
1502                 if (!dentry_is_directory(parent_of_dst))
1503                         return -ENOTDIR;
1504         }
1505
1506         FREE(src->file_name);
1507         FREE(src->file_name_utf8);
1508         src->file_name          = file_name_utf16;
1509         src->file_name_utf8     = file_name_utf8;
1510         src->file_name_len      = file_name_utf16_len;
1511         src->file_name_utf8_len = file_name_utf8_len;
1512
1513         unlink_dentry(src);
1514         dentry_add_child(parent_of_dst, src);
1515         return 0;
1516 }
1517
1518 /* Remove a directory */
1519 static int wimfs_rmdir(const char *path)
1520 {
1521         struct dentry *dentry;
1522         WIMStruct *w = wimfs_get_WIMStruct();
1523
1524         dentry = get_dentry(w, path);
1525         if (!dentry)
1526                 return -ENOENT;
1527
1528         if (!dentry_is_empty_directory(dentry))
1529                 return -ENOTEMPTY;
1530
1531         remove_dentry(dentry, w->lookup_table);
1532         return 0;
1533 }
1534
1535 #ifdef ENABLE_XATTR
1536 /* Write an alternate data stream through the XATTR interface */
1537 static int wimfs_setxattr(const char *path, const char *name,
1538                           const char *value, size_t size, int flags)
1539 {
1540         struct ads_entry *existing_ads_entry;
1541         struct ads_entry *new_ads_entry;
1542         struct lookup_table_entry *existing_lte;
1543         struct lookup_table_entry *lte;
1544         struct inode *inode;
1545         u8 value_hash[SHA1_HASH_SIZE];
1546         u16 ads_idx;
1547         struct wimfs_context *ctx = wimfs_get_context();
1548
1549         if (!(ctx->mount_flags & WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR))
1550                 return -ENOTSUP;
1551
1552         if (strlen(name) < 5 || memcmp(name, "user.", 5) != 0)
1553                 return -ENOATTR;
1554         name += 5;
1555
1556         inode = wim_pathname_to_inode(ctx->wim, path);
1557         if (!inode)
1558                 return -ENOENT;
1559
1560         existing_ads_entry = inode_get_ads_entry(inode, name, &ads_idx);
1561         if (existing_ads_entry) {
1562                 if (flags & XATTR_CREATE)
1563                         return -EEXIST;
1564                 inode_remove_ads(inode, ads_idx, ctx->wim->lookup_table);
1565         } else {
1566                 if (flags & XATTR_REPLACE)
1567                         return -ENOATTR;
1568         }
1569         new_ads_entry = inode_add_ads(inode, name);
1570         if (!new_ads_entry)
1571                 return -ENOMEM;
1572
1573         sha1_buffer((const u8*)value, size, value_hash);
1574
1575         existing_lte = __lookup_resource(ctx->wim->lookup_table, value_hash);
1576
1577         if (existing_lte) {
1578                 lte = existing_lte;
1579                 lte->refcnt++;
1580         } else {
1581                 u8 *value_copy;
1582                 lte = new_lookup_table_entry();
1583                 if (!lte)
1584                         return -ENOMEM;
1585                 value_copy = MALLOC(size);
1586                 if (!value_copy) {
1587                         FREE(lte);
1588                         return -ENOMEM;
1589                 }
1590                 memcpy(value_copy, value, size);
1591                 lte->resource_location            = RESOURCE_IN_ATTACHED_BUFFER;
1592                 lte->attached_buffer              = value_copy;
1593                 lte->resource_entry.original_size = size;
1594                 lte->resource_entry.size          = size;
1595                 lte->resource_entry.flags         = 0;
1596                 copy_hash(lte->hash, value_hash);
1597                 lookup_table_insert(ctx->wim->lookup_table, lte);
1598         }
1599         new_ads_entry->lte = lte;
1600         return 0;
1601 }
1602 #endif
1603
1604 static int wimfs_symlink(const char *to, const char *from)
1605 {
1606         struct dentry *dentry_parent, *dentry;
1607         const char *link_name;
1608         struct inode *inode;
1609         struct wimfs_context *ctx = wimfs_get_context();
1610
1611         dentry_parent = get_parent_dentry(ctx->wim, from);
1612         if (!dentry_parent)
1613                 return -ENOENT;
1614         if (!dentry_is_directory(dentry_parent))
1615                 return -ENOTDIR;
1616
1617         link_name = path_basename(from);
1618
1619         if (get_dentry_child_with_name(dentry_parent, link_name))
1620                 return -EEXIST;
1621         dentry = new_dentry_with_inode(link_name);
1622         if (!dentry)
1623                 return -ENOMEM;
1624         inode = dentry->d_inode;
1625
1626         inode->attributes  = FILE_ATTRIBUTE_REPARSE_POINT;
1627         inode->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
1628         inode->ino         = ctx->next_ino++;
1629         inode->resolved    = true;
1630
1631         if (inode_set_symlink(inode, to, ctx->wim->lookup_table, NULL) != 0)
1632                 goto out_free_dentry;
1633
1634         dentry_add_child(dentry_parent, dentry);
1635         return 0;
1636 out_free_dentry:
1637         free_dentry(dentry);
1638         return -ENOMEM;
1639 }
1640
1641
1642 /* Reduce the size of a file */
1643 static int wimfs_truncate(const char *path, off_t size)
1644 {
1645         struct dentry *dentry;
1646         struct lookup_table_entry *lte;
1647         int ret;
1648         u16 stream_idx;
1649         u32 stream_id;
1650         struct inode *inode;
1651         struct wimfs_context *ctx = wimfs_get_context();
1652
1653         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1654                               &dentry, &lte, &stream_idx);
1655
1656         if (ret != 0)
1657                 return ret;
1658
1659         if (!lte) /* Already a zero-length file */
1660                 return 0;
1661
1662         inode = dentry->d_inode;
1663
1664         if (stream_idx == 0)
1665                 stream_id = 0;
1666         else
1667                 stream_id = inode->ads_entries[stream_idx - 1].stream_id;
1668
1669         if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
1670                 wimlib_assert(lte->staging_file_name);
1671                 ret = truncate(lte->staging_file_name, size);
1672                 if (ret != 0)
1673                         return -errno;
1674                 lte->resource_entry.original_size = size;
1675         } else {
1676                 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
1677                 /* File in WIM.  Extract it to the staging directory, but only
1678                  * the first @size bytes of it. */
1679                 ret = extract_resource_to_staging_dir(inode, stream_id,
1680                                                       &lte, size, ctx);
1681         }
1682         return ret;
1683 }
1684
1685 /* Remove a regular file */
1686 static int wimfs_unlink(const char *path)
1687 {
1688         struct dentry *dentry;
1689         struct lookup_table_entry *lte;
1690         int ret;
1691         u16 stream_idx;
1692         struct wimfs_context *ctx = wimfs_get_context();
1693
1694         ret = lookup_resource(ctx->wim, path, get_lookup_flags(ctx),
1695                               &dentry, &lte, &stream_idx);
1696
1697         if (ret != 0)
1698                 return ret;
1699
1700         if (stream_idx == 0)
1701                 remove_dentry(dentry, ctx->wim->lookup_table);
1702         else
1703                 inode_remove_ads(dentry->d_inode, stream_idx - 1,
1704                                  ctx->wim->lookup_table);
1705         return 0;
1706 }
1707
1708 #ifdef HAVE_UTIMENSAT
1709 /*
1710  * Change the timestamp on a file dentry.
1711  *
1712  * Note that alternate data streams do not have their own timestamps.
1713  */
1714 static int wimfs_utimens(const char *path, const struct timespec tv[2])
1715 {
1716         struct dentry *dentry;
1717         struct inode *inode;
1718         WIMStruct *w = wimfs_get_WIMStruct();
1719
1720         dentry = get_dentry(w, path);
1721         if (!dentry)
1722                 return -ENOENT;
1723         inode = dentry->d_inode;
1724
1725         if (tv[0].tv_nsec != UTIME_OMIT) {
1726                 if (tv[0].tv_nsec == UTIME_NOW)
1727                         inode->last_access_time = get_wim_timestamp();
1728                 else
1729                         inode->last_access_time = timespec_to_wim_timestamp(&tv[0]);
1730         }
1731         if (tv[1].tv_nsec != UTIME_OMIT) {
1732                 if (tv[1].tv_nsec == UTIME_NOW)
1733                         inode->last_write_time = get_wim_timestamp();
1734                 else
1735                         inode->last_write_time = timespec_to_wim_timestamp(&tv[1]);
1736         }
1737         return 0;
1738 }
1739 #else
1740 static int wimfs_utime(const char *path, struct utimbuf *times)
1741 {
1742         struct dentry *dentry;
1743         struct inode *inode;
1744         WIMStruct *w = wimfs_get_WIMStruct();
1745
1746         dentry = get_dentry(w, path);
1747         if (!dentry)
1748                 return -ENOENT;
1749         inode = dentry->d_inode;
1750
1751         inode->last_write_time = unix_timestamp_to_wim(times->modtime);
1752         inode->last_access_time = unix_timestamp_to_wim(times->actime);
1753         return 0;
1754 }
1755 #endif
1756
1757 /* Writes to a file in the WIM filesystem.
1758  * It may be an alternate data stream, but here we don't even notice because we
1759  * just get a lookup table entry. */
1760 static int wimfs_write(const char *path, const char *buf, size_t size,
1761                        off_t offset, struct fuse_file_info *fi)
1762 {
1763         struct wimlib_fd *fd = (struct wimlib_fd*)(uintptr_t)fi->fh;
1764         int ret;
1765         u64 now;
1766
1767         if (!fd)
1768                 return -EBADF;
1769
1770         wimlib_assert(fd->f_lte);
1771         wimlib_assert(fd->f_lte->staging_file_name);
1772         wimlib_assert(fd->staging_fd != -1);
1773         wimlib_assert(fd->f_inode);
1774
1775         /* Seek to the requested position */
1776         if (lseek(fd->staging_fd, offset, SEEK_SET) == -1)
1777                 return -errno;
1778
1779         /* Write the data. */
1780         ret = write(fd->staging_fd, buf, size);
1781         if (ret == -1)
1782                 return -errno;
1783
1784         now = get_wim_timestamp();
1785         fd->f_inode->last_write_time = now;
1786         fd->f_inode->last_access_time = now;
1787         return ret;
1788 }
1789
1790 static struct fuse_operations wimfs_operations = {
1791         .access      = wimfs_access,
1792         .chmod       = wimfs_chmod,
1793         .destroy     = wimfs_destroy,
1794 #if 0
1795         .fallocate   = wimfs_fallocate,
1796 #endif
1797         .fgetattr    = wimfs_fgetattr,
1798         .ftruncate   = wimfs_ftruncate,
1799         .getattr     = wimfs_getattr,
1800 #ifdef ENABLE_XATTR
1801         .getxattr    = wimfs_getxattr,
1802 #endif
1803         .link        = wimfs_link,
1804 #ifdef ENABLE_XATTR
1805         .listxattr   = wimfs_listxattr,
1806 #endif
1807         .mkdir       = wimfs_mkdir,
1808         .mknod       = wimfs_mknod,
1809         .open        = wimfs_open,
1810         .opendir     = wimfs_opendir,
1811         .read        = wimfs_read,
1812         .readdir     = wimfs_readdir,
1813         .readlink    = wimfs_readlink,
1814         .release     = wimfs_release,
1815         .releasedir  = wimfs_releasedir,
1816 #ifdef ENABLE_XATTR
1817         .removexattr = wimfs_removexattr,
1818 #endif
1819         .rename      = wimfs_rename,
1820         .rmdir       = wimfs_rmdir,
1821 #ifdef ENABLE_XATTR
1822         .setxattr    = wimfs_setxattr,
1823 #endif
1824         .symlink     = wimfs_symlink,
1825         .truncate    = wimfs_truncate,
1826         .unlink      = wimfs_unlink,
1827 #ifdef HAVE_UTIMENSAT
1828         .utimens     = wimfs_utimens,
1829 #else
1830         .utime       = wimfs_utime,
1831 #endif
1832         .write       = wimfs_write,
1833 };
1834
1835
1836 /* Mounts a WIM file. */
1837 WIMLIBAPI int wimlib_mount(WIMStruct *wim, int image, const char *dir,
1838                            int flags, WIMStruct **additional_swms,
1839                            unsigned num_additional_swms)
1840 {
1841         int argc = 0;
1842         char *argv[16];
1843         int ret;
1844         char *dir_copy;
1845         struct lookup_table *joined_tab, *wim_tab_save;
1846         struct image_metadata *imd;
1847         struct wimfs_context ctx;
1848
1849         DEBUG("Mount: wim = %p, image = %d, dir = %s, flags = %d, ",
1850               wim, image, dir, flags);
1851
1852         if (!wim || !dir)
1853                 return WIMLIB_ERR_INVALID_PARAM;
1854
1855         ret = verify_swm_set(wim, additional_swms, num_additional_swms);
1856         if (ret != 0)
1857                 return ret;
1858
1859         if (num_additional_swms) {
1860                 ret = new_joined_lookup_table(wim, additional_swms,
1861                                               num_additional_swms,
1862                                               &joined_tab);
1863                 if (ret != 0)
1864                         return ret;
1865                 wim_tab_save = wim->lookup_table;
1866                 wim->lookup_table = joined_tab;
1867         }
1868
1869         ret = select_wim_image(wim, image);
1870
1871         if (ret != 0)
1872                 goto out;
1873
1874         imd = &wim->image_metadata[image - 1];
1875
1876         DEBUG("Selected image %d", image);
1877
1878         if (imd->root_dentry->refcnt != 1) {
1879                 ERROR("Cannot mount image that was just exported with "
1880                       "wimlib_export()");
1881                 ret = WIMLIB_ERR_INVALID_PARAM;
1882                 goto out;
1883         }
1884
1885         if (!(flags & (WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE |
1886                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR |
1887                        WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS)))
1888                 flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
1889
1890
1891         DEBUG("Initializing struct wimfs_context");
1892         init_wimfs_context(&ctx);
1893
1894         DEBUG("Getting current directory");
1895         ctx.working_directory = getcwd(NULL, 0);
1896         if (!ctx.working_directory) {
1897                 ERROR_WITH_ERRNO("Could not determine current directory");
1898                 ret = WIMLIB_ERR_NOTDIR;
1899                 goto out;
1900         }
1901
1902         DEBUG("Unlinking message queues in case they already exist");
1903         ret = set_message_queue_names(&ctx, dir);
1904         if (ret != 0)
1905                 goto out_free_working_directory;
1906         unlink_message_queues(&ctx);
1907
1908         DEBUG("Preparing arguments to fuse_main()");
1909
1910         dir_copy = STRDUP(dir);
1911         if (!dir_copy)
1912                 goto out_free_message_queue_names;
1913
1914         argv[argc++] = "imagex";
1915         argv[argc++] = dir_copy;
1916
1917         /* disable multi-threaded operation for read-write mounts */
1918         if (flags & WIMLIB_MOUNT_FLAG_READWRITE)
1919                 argv[argc++] = "-s";
1920
1921         if (flags & WIMLIB_MOUNT_FLAG_DEBUG)
1922                 argv[argc++] = "-d";
1923
1924         /*
1925          * We provide the use_ino option because we are going to assign inode
1926          * numbers oursides.  The inodes will be given unique numbers in the
1927          * assign_inode_numbers() function, and the static variable @next_ino is
1928          * set to the next available inode number.
1929          */
1930         char optstring[256] = "use_ino,subtype=wimfs,attr_timeout=0";
1931         argv[argc++] = "-o";
1932         argv[argc++] = optstring;
1933         if ((flags & WIMLIB_MOUNT_FLAG_READWRITE)) {
1934                 /* Read-write mount.  Make the staging directory */
1935                 ret = make_staging_dir(&ctx);
1936                 if (ret != 0)
1937                         goto out_free_dir_copy;
1938         } else {
1939                 /* Read-only mount */
1940                 strcat(optstring, ",ro");
1941         }
1942         argv[argc] = NULL;
1943
1944 #ifdef ENABLE_DEBUG
1945         {
1946                 int i;
1947                 DEBUG("FUSE command line (argc = %d): ", argc);
1948                 for (i = 0; i < argc; i++) {
1949                         fputs(argv[i], stdout);
1950                         putchar(' ');
1951                 }
1952                 putchar('\n');
1953                 fflush(stdout);
1954         }
1955 #endif
1956
1957         /* Mark dentry tree as modified if read-write mount. */
1958         if (flags & WIMLIB_MOUNT_FLAG_READWRITE)
1959                 imd->modified = true;
1960
1961         /* Resolve all the lookup table entries of the dentry tree */
1962         DEBUG("Resolving lookup table entries");
1963         for_dentry_in_tree(imd->root_dentry, dentry_resolve_ltes,
1964                            wim->lookup_table);
1965
1966         ctx.next_ino = assign_inode_numbers(&imd->inode_list);
1967         DEBUG("(next_ino = %"PRIu64")", ctx.next_ino);
1968
1969         /* Finish initializing the filesystem context. */
1970         ctx.wim = wim;
1971         ctx.mount_flags = flags;
1972
1973         DEBUG("Calling fuse_main()");
1974
1975         ret = fuse_main(argc, argv, &wimfs_operations, &ctx);
1976
1977         DEBUG("Returned from fuse_main() (ret = %d)", ret);
1978         if (ret)
1979                 ret = WIMLIB_ERR_FUSE;
1980 out_free_dir_copy:
1981         FREE(dir_copy);
1982 out_free_message_queue_names:
1983         free_message_queue_names(&ctx);
1984 out_free_working_directory:
1985         FREE(ctx.working_directory);
1986         ctx.working_directory = NULL;
1987 out:
1988         if (num_additional_swms) {
1989                 free_lookup_table(wim->lookup_table);
1990                 wim->lookup_table = wim_tab_save;
1991         }
1992         return ret;
1993 }
1994
1995
1996 /*
1997  * Unmounts the WIM file that was previously mounted on @dir by using
1998  * wimlib_mount().
1999  */
2000 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
2001 {
2002         pid_t pid;
2003         int status;
2004         int ret;
2005         char msg[2];
2006         struct timeval now;
2007         struct timespec timeout;
2008         long msgsize;
2009         struct wimfs_context ctx;
2010         char *mailbox;
2011
2012         init_wimfs_context(&ctx);
2013
2014         /* Open message queues between the unmount process and the
2015          * filesystem daemon. */
2016         ret = set_message_queue_names(&ctx, dir);
2017         if (ret != 0)
2018                 goto out;
2019
2020         ret = open_message_queues(&ctx, false);
2021         if (ret != 0)
2022                 goto out_free_message_queue_names;
2023
2024         /* Send a message to the filesystem daemon saying whether to commit or
2025          * not. */
2026         msg[0] = (flags & WIMLIB_UNMOUNT_FLAG_COMMIT) ? 1 : 0;
2027         msg[1] = (flags & WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY) ? 1 : 0;
2028
2029         DEBUG("Sending message: %scommit, %scheck",
2030                         (msg[0] ? "" : "don't "),
2031                         (msg[1] ? "" : "don't "));
2032         ret = mq_send(ctx.unmount_to_daemon_mq, msg, 2, 1);
2033         if (ret == -1) {
2034                 ERROR_WITH_ERRNO("Failed to notify filesystem daemon whether "
2035                                  "we want to commit changes or not");
2036                 ret = WIMLIB_ERR_MQUEUE;
2037                 goto out_close_message_queues;
2038         }
2039
2040         /* Execute `fusermount -u', which is installed setuid root, to unmount
2041          * the WIM.
2042          *
2043          * FUSE does not yet implement synchronous unmounts.  This means that
2044          * fusermount -u will return before the filesystem daemon returns from
2045          * wimfs_destroy().  This is partly what we want, because we need to
2046          * send a message from this process to the filesystem daemon telling
2047          * whether --commit was specified or not.  However, after that, the
2048          * unmount process must wait for the filesystem daemon to finish writing
2049          * the WIM file.
2050          */
2051
2052         pid = fork();
2053         if (pid == -1) {
2054                 ERROR_WITH_ERRNO("Failed to fork()");
2055                 ret = WIMLIB_ERR_FORK;
2056                 goto out_close_message_queues;
2057         }
2058         if (pid == 0) {
2059                 /* Child */
2060                 execlp("fusermount", "fusermount", "-u", dir, NULL);
2061                 ERROR_WITH_ERRNO("Failed to execute `fusermount'");
2062                 exit(WIMLIB_ERR_FUSERMOUNT);
2063         }
2064
2065         /* Parent */
2066         ret = wait(&status);
2067         if (ret == -1) {
2068                 ERROR_WITH_ERRNO("Failed to wait for fusermount process to "
2069                                  "terminate");
2070                 ret = WIMLIB_ERR_FUSERMOUNT;
2071                 goto out_close_message_queues;
2072         }
2073
2074         if (status != 0) {
2075                 ERROR("fusermount exited with status %d", status);
2076
2077                 /* Try again, but with the `umount' program.  This is required
2078                  * on other FUSE implementations such as FreeBSD's that do not
2079                  * have a `fusermount' program. */
2080
2081                 pid = fork();
2082                 if (pid == -1) {
2083                         ERROR_WITH_ERRNO("Failed to fork()");
2084                         ret = WIMLIB_ERR_FORK;
2085                         goto out_close_message_queues;
2086                 }
2087                 if (pid == 0) {
2088                         /* Child */
2089                         execlp("umount", "umount", dir, NULL);
2090                         ERROR_WITH_ERRNO("Failed to execute `umount'");
2091                         exit(WIMLIB_ERR_FUSERMOUNT);
2092                 }
2093
2094                 /* Parent */
2095                 ret = wait(&status);
2096                 if (ret == -1) {
2097                         ERROR_WITH_ERRNO("Failed to wait for `umount' process to "
2098                                          "terminate");
2099                         ret = WIMLIB_ERR_FUSERMOUNT;
2100                         goto out_close_message_queues;
2101                 }
2102                 if (status != 0) {
2103                         ERROR("`umount' exited with failure status");
2104                         ret = WIMLIB_ERR_FUSERMOUNT;
2105                         goto out_close_message_queues;
2106                 }
2107         }
2108
2109         wimlib_assert(status == 0);
2110
2111         /* Wait for a message from the filesytem daemon indicating whether  the
2112          * filesystem was unmounted successfully (0) or an error occurred (1).
2113          * This may take a long time if a big WIM file needs to be rewritten. */
2114
2115         /* Wait at most 600??? seconds before giving up and returning false.
2116          * Either it's a really big WIM file, or (more likely) the
2117          * filesystem daemon has crashed or failed for some reason.
2118          *
2119          * XXX come up with some method to determine if the filesystem
2120          * daemon has really crashed or not.
2121          *
2122          * XXX Idea: have mount daemon write its PID into the WIM file header?
2123          * No, this wouldn't work because we know the directory but not the WIM
2124          * file...
2125          * */
2126
2127         gettimeofday(&now, NULL);
2128         timeout.tv_sec = now.tv_sec + 600;
2129         timeout.tv_nsec = now.tv_usec * 1000;
2130
2131         ret = get_mailbox(ctx.daemon_to_unmount_mq, 2, &msgsize, &mailbox);
2132         if (ret != 0)
2133                 goto out_close_message_queues;
2134
2135         mailbox[0] = 0;
2136         DEBUG("Waiting for message telling us whether the unmount was "
2137                         "successful or not.");
2138         ret = mq_timedreceive(ctx.daemon_to_unmount_mq, mailbox,
2139                               msgsize, NULL, &timeout);
2140         if (ret == -1) {
2141                 if (errno == ETIMEDOUT) {
2142                         ERROR("Timed out- probably the filesystem daemon "
2143                               "crashed and the WIM was not written "
2144                               "successfully.");
2145                         ret = WIMLIB_ERR_TIMEOUT;
2146                 } else {
2147                         ERROR_WITH_ERRNO("mq_receive()");
2148                         ret = WIMLIB_ERR_MQUEUE;
2149                 }
2150                 goto out_free_mailbox;
2151
2152         }
2153         DEBUG("Received message: Unmount %s", (mailbox[0] ? "Failed" : "Ok"));
2154         ret = mailbox[0];
2155         if (ret)
2156                 ERROR("Unmount failed");
2157 out_free_mailbox:
2158         FREE(mailbox);
2159 out_close_message_queues:
2160         close_message_queues(&ctx);
2161 out_free_message_queue_names:
2162         free_message_queue_names(&ctx);
2163 out:
2164         return ret;
2165 }
2166
2167 #else /* WITH_FUSE */
2168
2169
2170 static inline int mount_unsupported_error()
2171 {
2172         ERROR("wimlib was compiled with --without-fuse, which disables support "
2173               "for mounting WIMs.");
2174         return WIMLIB_ERR_UNSUPPORTED;
2175 }
2176
2177 WIMLIBAPI int wimlib_unmount(const char *dir, int flags)
2178 {
2179         return mount_unsupported_error();
2180 }
2181
2182 WIMLIBAPI int wimlib_mount(WIMStruct *wim_p, int image, const char *dir,
2183                            int flags, WIMStruct **additional_swms,
2184                            unsigned num_additional_swms)
2185 {
2186         return mount_unsupported_error();
2187 }
2188
2189 #endif /* WITH_FUSE */