739d8cbf87f11afd80b00b3eac8e09be6f7ee3ce
[libguestfs.git] / fuse / guestmount.c
1 /* guestmount - mount guests using libguestfs and FUSE
2  * Copyright (C) 2009 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  *
18  * Derived from the example program 'fusexmp.c':
19  * Copyright (C) 2001-2007  Miklos Szeredi <miklos@szeredi.hu>
20  *
21  * This program can be distributed under the terms of the GNU GPL.
22  * See the file COPYING.
23  */
24
25 #define FUSE_USE_VERSION 26
26
27 #include <config.h>
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <stdint.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include <getopt.h>
35 #include <fcntl.h>
36 #include <dirent.h>
37 #include <errno.h>
38 #include <signal.h>
39 #include <time.h>
40 #include <assert.h>
41 #include <sys/time.h>
42 #include <sys/types.h>
43
44 #include <fuse.h>
45 #include <guestfs.h>
46
47 #include "progname.h"
48
49 #include "guestmount.h"
50 #include "dircache.h"
51
52 /* See <attr/xattr.h> */
53 #ifndef ENOATTR
54 #define ENOATTR ENODATA
55 #endif
56
57 static guestfs_h *g = NULL;
58 static int read_only = 0;
59 int verbose = 0;
60 int dir_cache_timeout = 60;
61
62 /* This is ugly: guestfs errors are strings, FUSE wants -errno.  We
63  * have to do the conversion as best we can.
64  */
65 #define MAX_ERRNO 256
66
67 static int
68 error (void)
69 {
70   int i;
71   const char *err = guestfs_last_error (g);
72
73   if (!err)
74     return -EINVAL;
75
76   if (verbose)
77     fprintf (stderr, "%s\n", err);
78
79   /* Add a few of our own ... */
80
81   /* This indicates guestfsd died.  Translate into a hard EIO error.
82    * Arguably we could relaunch the guest if we hit this error.
83    */
84   if (strstr (err, "call launch before using this function"))
85     return -EIO;
86
87   /* See if it matches an errno string in the host. */
88   for (i = 0; i < MAX_ERRNO; ++i) {
89     const char *e = strerror (i);
90     if (e && strstr (err, e) != NULL)
91       return -i;
92   }
93
94   /* Too bad, return a generic error. */
95   return -EINVAL;
96 }
97
98 static struct guestfs_xattr_list *
99 copy_xattr_list (const struct guestfs_xattr *first, size_t num)
100 {
101   struct guestfs_xattr_list *xattrs;
102
103   xattrs = malloc (sizeof *xattrs);
104   if (xattrs == NULL) {
105     perror ("malloc");
106     return NULL;
107   }
108
109   xattrs->len = num;
110   xattrs->val = malloc (num * sizeof (struct guestfs_xattr));
111   if (xattrs->val == NULL) {
112     perror ("malloc");
113     free (xattrs);
114     return NULL;
115   }
116
117   size_t i;
118   for (i = 0; i < num; ++i) {
119     xattrs->val[i].attrname = strdup (first[i].attrname);
120     xattrs->val[i].attrval_len = first[i].attrval_len;
121     xattrs->val[i].attrval = malloc (first[i].attrval_len);
122     memcpy (xattrs->val[i].attrval, first[i].attrval, first[i].attrval_len);
123   }
124
125   return xattrs;
126 }
127
128 static int
129 fg_readdir (const char *path, void *buf, fuse_fill_dir_t filler,
130             off_t offset, struct fuse_file_info *fi)
131 {
132   time_t now;
133   time (&now);
134
135   dir_cache_remove_all_expired (now);
136
137   struct guestfs_dirent_list *ents;
138
139   ents = guestfs_readdir (g, path);
140   if (ents == NULL)
141     return error ();
142
143   size_t i;
144   for (i = 0; i < ents->len; ++i) {
145     struct stat stat;
146     memset (&stat, 0, sizeof stat);
147
148     stat.st_ino = ents->val[i].ino;
149     switch (ents->val[i].ftyp) {
150     case 'b': stat.st_mode = S_IFBLK; break;
151     case 'c': stat.st_mode = S_IFCHR; break;
152     case 'd': stat.st_mode = S_IFDIR; break;
153     case 'f': stat.st_mode = S_IFIFO; break;
154     case 'l': stat.st_mode = S_IFLNK; break;
155     case 'r': stat.st_mode = S_IFREG; break;
156     case 's': stat.st_mode = S_IFSOCK; break;
157     case 'u':
158     case '?':
159     default:  stat.st_mode = 0;
160     }
161
162     /* Copied from the example, which also ignores 'offset'.  I'm
163      * not quite sure how this is ever supposed to work on large
164      * directories. XXX
165      */
166     if (filler (buf, ents->val[i].name, &stat, 0))
167       break;
168   }
169
170   /* Now prepopulate the directory caches.  This step is just an
171    * optimization, don't worry if it fails.
172    */
173   char **names = malloc ((ents->len + 1) * sizeof (char *));
174   if (names) {
175     for (i = 0; i < ents->len; ++i)
176       names[i] = ents->val[i].name;
177     names[i] = NULL;
178
179     struct guestfs_stat_list *ss = guestfs_lstatlist (g, path, names);
180     if (ss) {
181       for (i = 0; i < ss->len; ++i) {
182         if (ss->val[i].ino >= 0) {
183           struct stat statbuf;
184
185           statbuf.st_dev = ss->val[i].dev;
186           statbuf.st_ino = ss->val[i].ino;
187           statbuf.st_mode = ss->val[i].mode;
188           statbuf.st_nlink = ss->val[i].nlink;
189           statbuf.st_uid = ss->val[i].uid;
190           statbuf.st_gid = ss->val[i].gid;
191           statbuf.st_rdev = ss->val[i].rdev;
192           statbuf.st_size = ss->val[i].size;
193           statbuf.st_blksize = ss->val[i].blksize;
194           statbuf.st_blocks = ss->val[i].blocks;
195           statbuf.st_atime = ss->val[i].atime;
196           statbuf.st_mtime = ss->val[i].mtime;
197           statbuf.st_ctime = ss->val[i].ctime;
198
199           lsc_insert (path, names[i], now, &statbuf);
200         }
201       }
202       guestfs_free_stat_list (ss);
203     }
204
205     struct guestfs_xattr_list *xattrs = guestfs_lxattrlist (g, path, names);
206     if (xattrs) {
207       size_t ni, num;
208       struct guestfs_xattr *first;
209       struct guestfs_xattr_list *copy;
210       for (i = 0, ni = 0; i < xattrs->len; ++i, ++ni) {
211         assert (strlen (xattrs->val[i].attrname) == 0);
212         if (xattrs->val[i].attrval_len > 0) {
213           ++i;
214           first = &xattrs->val[i];
215           num = 0;
216           for (; i < xattrs->len && strlen (xattrs->val[i].attrname) > 0; ++i)
217             num++;
218
219           copy = copy_xattr_list (first, num);
220           if (copy)
221             xac_insert (path, names[ni], now, copy);
222
223           i--;
224         }
225       }
226       guestfs_free_xattr_list (xattrs);
227     }
228
229     char **links = guestfs_readlinklist (g, path, names);
230     if (links) {
231       for (i = 0; names[i] != NULL; ++i) {
232         if (links[i][0])
233           /* Note that rlc_insert owns the string links[i] after this, */
234           rlc_insert (path, names[i], now, links[i]);
235         else
236           /* which is why we have to free links[i] here. */
237           free (links[i]);
238       }
239       free (links);             /* free the array, not the strings */
240     }
241
242     free (names);
243   }
244
245   guestfs_free_dirent_list (ents);
246
247   return 0;
248 }
249
250 static int
251 fg_getattr (const char *path, struct stat *statbuf)
252 {
253   const struct stat *buf;
254
255   buf = lsc_lookup (path);
256   if (buf) {
257     memcpy (statbuf, buf, sizeof *statbuf);
258     return 0;
259   }
260
261   struct guestfs_stat *r;
262
263   r = guestfs_lstat (g, path);
264   if (r == NULL)
265     return error ();
266
267   statbuf->st_dev = r->dev;
268   statbuf->st_ino = r->ino;
269   statbuf->st_mode = r->mode;
270   statbuf->st_nlink = r->nlink;
271   statbuf->st_uid = r->uid;
272   statbuf->st_gid = r->gid;
273   statbuf->st_rdev = r->rdev;
274   statbuf->st_size = r->size;
275   statbuf->st_blksize = r->blksize;
276   statbuf->st_blocks = r->blocks;
277   statbuf->st_atime = r->atime;
278   statbuf->st_mtime = r->mtime;
279   statbuf->st_ctime = r->ctime;
280
281   guestfs_free_stat (r);
282
283   return 0;
284 }
285
286 /* Nautilus loves to use access(2) to test everything about a file,
287  * such as whether it's executable.  Therefore treat this a lot like
288  * fg_getattr.
289  */
290 static int
291 fg_access (const char *path, int mask)
292 {
293   struct stat statbuf;
294   int r;
295
296   if (read_only && (mask & W_OK))
297     return -EROFS;
298
299   r = fg_getattr (path, &statbuf);
300   if (r < 0 || mask == F_OK)
301     return r;
302
303   struct fuse_context *fuse = fuse_get_context ();
304   int ok = 1;
305
306   if (mask & R_OK)
307     ok = ok &&
308       (  fuse->uid == statbuf.st_uid ? statbuf.st_mode & S_IRUSR
309        : fuse->gid == statbuf.st_gid ? statbuf.st_mode & S_IRGRP
310        : statbuf.st_mode & S_IROTH);
311   if (mask & W_OK)
312     ok = ok &&
313       (  fuse->uid == statbuf.st_uid ? statbuf.st_mode & S_IWUSR
314        : fuse->gid == statbuf.st_gid ? statbuf.st_mode & S_IWGRP
315        : statbuf.st_mode & S_IWOTH);
316   if (mask & X_OK)
317     ok = ok &&
318       (  fuse->uid == statbuf.st_uid ? statbuf.st_mode & S_IXUSR
319        : fuse->gid == statbuf.st_gid ? statbuf.st_mode & S_IXGRP
320        : statbuf.st_mode & S_IXOTH);
321
322   return ok ? 0 : -EACCES;
323 }
324
325 static int
326 fg_readlink (const char *path, char *buf, size_t size)
327 {
328   const char *r;
329   int free_it = 0;
330
331   r = rlc_lookup (path);
332   if (!r) {
333     r = guestfs_readlink (g, path);
334     if (r == NULL)
335       return error ();
336     free_it = 1;
337   }
338
339   /* Note this is different from the real readlink(2) syscall.  FUSE wants
340    * the string to be always nul-terminated, even if truncated.
341    */
342   size_t len = strlen (r);
343   if (len > size - 1)
344     len = size - 1;
345
346   memcpy (buf, r, len);
347   buf[len] = '\0';
348
349   if (free_it) {
350     char *tmp = (char *) r;
351     free (tmp);
352   }
353
354   return 0;
355 }
356
357 static int
358 fg_mknod (const char *path, mode_t mode, dev_t rdev)
359 {
360   int r;
361
362   if (read_only) return -EROFS;
363
364   dir_cache_invalidate (path);
365
366   r = guestfs_mknod (g, mode, major (rdev), minor (rdev), path);
367   if (r == -1)
368     return error ();
369
370   return 0;
371 }
372
373 static int
374 fg_mkdir (const char *path, mode_t mode)
375 {
376   int r;
377
378   if (read_only) return -EROFS;
379
380   dir_cache_invalidate (path);
381
382   r = guestfs_mkdir_mode (g, path, mode);
383   if (r == -1)
384     return error ();
385
386   return 0;
387 }
388
389 static int
390 fg_unlink (const char *path)
391 {
392   int r;
393
394   if (read_only) return -EROFS;
395
396   dir_cache_invalidate (path);
397
398   r = guestfs_rm (g, path);
399   if (r == -1)
400     return error ();
401
402   return 0;
403 }
404
405 static int
406 fg_rmdir (const char *path)
407 {
408   int r;
409
410   if (read_only) return -EROFS;
411
412   dir_cache_invalidate (path);
413
414   r = guestfs_rmdir (g, path);
415   if (r == -1)
416     return error ();
417
418   return 0;
419 }
420
421 static int
422 fg_symlink (const char *from, const char *to)
423 {
424   int r;
425
426   if (read_only) return -EROFS;
427
428   dir_cache_invalidate (to);
429
430   r = guestfs_ln_s (g, to, from);
431   if (r == -1)
432     return error ();
433
434   return 0;
435 }
436
437 static int
438 fg_rename (const char *from, const char *to)
439 {
440   int r;
441
442   if (read_only) return -EROFS;
443
444   dir_cache_invalidate (to);
445
446   /* XXX It's not clear how close the 'mv' command is to the
447    * rename syscall.  We might need to add the rename syscall
448    * to the guestfs(3) API.
449    */
450   r = guestfs_mv (g, from, to);
451   if (r == -1)
452     return error ();
453
454   return 0;
455 }
456
457 static int
458 fg_link (const char *from, const char *to)
459 {
460   int r;
461
462   if (read_only) return -EROFS;
463
464   dir_cache_invalidate (to);
465
466   r = guestfs_ln (g, to, from);
467   if (r == -1)
468     return error ();
469
470   return 0;
471 }
472
473 static int
474 fg_chmod (const char *path, mode_t mode)
475 {
476   int r;
477
478   if (read_only) return -EROFS;
479
480   dir_cache_invalidate (path);
481
482   r = guestfs_chmod (g, mode, path);
483   if (r == -1)
484     return error ();
485
486   return 0;
487 }
488
489 static int
490 fg_chown (const char *path, uid_t uid, gid_t gid)
491 {
492   int r;
493
494   if (read_only) return -EROFS;
495
496   dir_cache_invalidate (path);
497
498   r = guestfs_lchown (g, uid, gid, path);
499   if (r == -1)
500     return error ();
501
502   return 0;
503 }
504
505 static int
506 fg_truncate (const char *path, off_t size)
507 {
508   int r;
509
510   if (read_only) return -EROFS;
511
512   dir_cache_invalidate (path);
513
514   r = guestfs_truncate_size (g, path, size);
515   if (r == -1)
516     return error ();
517
518   return 0;
519 }
520
521 static int
522 fg_utimens (const char *path, const struct timespec ts[2])
523 {
524   int r;
525
526   if (read_only) return -EROFS;
527
528   dir_cache_invalidate (path);
529
530   time_t atsecs = ts[0].tv_sec;
531   long atnsecs = ts[0].tv_nsec;
532   time_t mtsecs = ts[1].tv_sec;
533   long mtnsecs = ts[1].tv_nsec;
534
535   if (atnsecs == UTIME_NOW)
536     atnsecs = -1;
537   if (atnsecs == UTIME_OMIT)
538     atnsecs = -2;
539   if (mtnsecs == UTIME_NOW)
540     mtnsecs = -1;
541   if (mtnsecs == UTIME_OMIT)
542     mtnsecs = -2;
543
544   r = guestfs_utimens (g, path, atsecs, atnsecs, mtsecs, mtnsecs);
545   if (r == -1)
546     return error ();
547
548   return 0;
549 }
550
551 /* This call is quite hard to emulate through the guestfs(3) API.  In
552  * one sense it's a little like access (see above) because it tests
553  * whether opening a file would succeed given the flags.  But it also
554  * has side effects such as truncating the file if O_TRUNC is given.
555  * Therefore we need to emulate it ... painfully.
556  */
557 static int
558 fg_open (const char *path, struct fuse_file_info *fi)
559 {
560   int r, exists;
561
562   if (fi->flags & O_WRONLY) {
563     if (read_only)
564       return -EROFS;
565   }
566
567   exists = guestfs_exists (g, path);
568   if (exists == -1)
569     return error ();
570
571   if (fi->flags & O_CREAT) {
572     if (read_only)
573       return -EROFS;
574
575     dir_cache_invalidate (path);
576
577     /* Exclusive?  File must not exist already. */
578     if (fi->flags & O_EXCL) {
579       if (exists)
580         return -EEXIST;
581     }
582
583     /* Create?  Touch it and optionally truncate it. */
584     r = guestfs_touch (g, path);
585     if (r == -1)
586       return error ();
587
588     if (fi->flags & O_TRUNC) {
589       r = guestfs_truncate (g, path);
590       if (r == -1)
591         return error ();
592     }
593   } else {
594     /* Not create, just check it exists. */
595     if (!exists)
596       return -ENOENT;
597   }
598
599   return 0;
600 }
601
602 static int
603 fg_read (const char *path, char *buf, size_t size, off_t offset,
604          struct fuse_file_info *fi)
605 {
606   char *r;
607   size_t rsize;
608
609   if (verbose)
610     fprintf (stderr, "fg_read: %s: size %zu offset %ju\n",
611              path, size, offset);
612
613   /* The guestfs protocol limits size to somewhere over 2MB.  We just
614    * reduce the requested size here accordingly and push the problem
615    * up to every user.  http://www.jwz.org/doc/worse-is-better.html
616    */
617   const size_t limit = 2 * 1024 * 1024;
618   if (size > limit)
619     size = limit;
620
621   r = guestfs_pread (g, path, size, offset, &rsize);
622   if (r == NULL)
623     return error ();
624
625   /* This should never happen, but at least it stops us overflowing
626    * the output buffer if it does happen.
627    */
628   if (rsize > size)
629     rsize = size;
630
631   memcpy (buf, r, rsize);
632   free (r);
633
634   return rsize;
635 }
636
637 static int
638 fg_write (const char *path, const char *buf, size_t size,
639           off_t offset, struct fuse_file_info *fi)
640 {
641   if (read_only) return -EROFS;
642
643   dir_cache_invalidate (path);
644
645   return -ENOSYS;               /* XXX */
646 }
647
648 static int
649 fg_statfs (const char *path, struct statvfs *stbuf)
650 {
651   struct guestfs_statvfs *r;
652
653   r = guestfs_statvfs (g, path);
654   if (r == NULL)
655     return error ();
656
657   stbuf->f_bsize = r->bsize;
658   stbuf->f_frsize = r->frsize;
659   stbuf->f_blocks = r->blocks;
660   stbuf->f_bfree = r->bfree;
661   stbuf->f_bavail = r->bavail;
662   stbuf->f_files = r->files;
663   stbuf->f_ffree = r->ffree;
664   stbuf->f_favail = r->favail;
665   stbuf->f_fsid = r->fsid;
666   stbuf->f_flag = r->flag;
667   stbuf->f_namemax = r->namemax;
668
669   guestfs_free_statvfs (r);
670
671   return 0;
672 }
673
674 static int
675 fg_release (const char *path, struct fuse_file_info *fi)
676 {
677   /* Just a stub. This method is optional and can safely be left
678    * unimplemented.
679    */
680   return 0;
681 }
682
683 /* Emulate this by calling sync. */
684 static int fg_fsync(const char *path, int isdatasync,
685                      struct fuse_file_info *fi)
686 {
687   int r;
688
689   r = guestfs_sync (g);
690   if (r == -1)
691     return error ();
692
693   return 0;
694 }
695
696 static int
697 fg_setxattr (const char *path, const char *name, const char *value,
698              size_t size, int flags)
699 {
700   int r;
701
702   if (read_only) return -EROFS;
703
704   dir_cache_invalidate (path);
705
706   /* XXX Underlying guestfs(3) API doesn't understand the flags. */
707   r = guestfs_lsetxattr (g, name, value, size, path);
708   if (r == -1)
709     return error ();
710
711   return 0;
712 }
713
714 /* The guestfs(3) API for getting xattrs is much easier to use
715  * than the real syscall.  Unfortunately we now have to emulate
716  * the real syscall using that API :-(
717  */
718 static int
719 fg_getxattr (const char *path, const char *name, char *value,
720              size_t size)
721 {
722   const struct guestfs_xattr_list *xattrs;
723   int free_attrs = 0;
724
725   xattrs = xac_lookup (path);
726   if (xattrs == NULL) {
727     xattrs = guestfs_lgetxattrs (g, path);
728     if (xattrs == NULL)
729       return error ();
730     free_attrs = 1;
731   }
732
733   size_t i;
734   int r = -ENOATTR;
735   for (i = 0; i < xattrs->len; ++i) {
736     if (STREQ (xattrs->val[i].attrname, name)) {
737       size_t sz = xattrs->val[i].attrval_len;
738       if (sz > size)
739         sz = size;
740       memcpy (value, xattrs->val[i].attrval, sz);
741       r = 0;
742       break;
743     }
744   }
745
746   if (free_attrs)
747     guestfs_free_xattr_list ((struct guestfs_xattr_list *) xattrs);
748
749   return r;
750 }
751
752 /* Ditto as above. */
753 static int
754 fg_listxattr (const char *path, char *list, size_t size)
755 {
756   const struct guestfs_xattr_list *xattrs;
757   int free_attrs = 0;
758
759   xattrs = xac_lookup (path);
760   if (xattrs == NULL) {
761     xattrs = guestfs_lgetxattrs (g, path);
762     if (xattrs == NULL)
763       return error ();
764     free_attrs = 1;
765   }
766
767   size_t i;
768   ssize_t copied = 0;
769   for (i = 0; i < xattrs->len; ++i) {
770     size_t len = strlen (xattrs->val[i].attrname) + 1;
771     if (size >= len) {
772       memcpy (list, xattrs->val[i].attrname, len);
773       size -= len;
774       list += len;
775       copied += len;
776     } else {
777       copied = -ERANGE;
778       break;
779     }
780   }
781
782   if (free_attrs)
783     guestfs_free_xattr_list ((struct guestfs_xattr_list *) xattrs);
784
785   return copied;
786 }
787
788 static int
789 fg_removexattr(const char *path, const char *name)
790 {
791   int r;
792
793   if (read_only) return -EROFS;
794
795   dir_cache_invalidate (path);
796
797   r = guestfs_lremovexattr (g, name, path);
798   if (r == -1)
799     return error ();
800
801   return 0;
802 }
803
804 static struct fuse_operations fg_operations = {
805   .getattr      = fg_getattr,
806   .access       = fg_access,
807   .readlink     = fg_readlink,
808   .readdir      = fg_readdir,
809   .mknod        = fg_mknod,
810   .mkdir        = fg_mkdir,
811   .symlink      = fg_symlink,
812   .unlink       = fg_unlink,
813   .rmdir        = fg_rmdir,
814   .rename       = fg_rename,
815   .link         = fg_link,
816   .chmod        = fg_chmod,
817   .chown        = fg_chown,
818   .truncate     = fg_truncate,
819   .utimens      = fg_utimens,
820   .open         = fg_open,
821   .read         = fg_read,
822   .write        = fg_write,
823   .statfs       = fg_statfs,
824   .release      = fg_release,
825   .fsync        = fg_fsync,
826   .setxattr     = fg_setxattr,
827   .getxattr     = fg_getxattr,
828   .listxattr    = fg_listxattr,
829   .removexattr  = fg_removexattr,
830 };
831
832 struct drv {
833   struct drv *next;
834   char *filename;
835 };
836
837 struct mp {
838   struct mp *next;
839   char *device;
840   char *mountpoint;
841 };
842
843 static void add_drives (struct drv *);
844 static void mount_mps (struct mp *);
845
846 static void __attribute__((noreturn))
847 fuse_help (void)
848 {
849   const char *tmp_argv[] = { program_name, "--help", NULL };
850   fuse_main (2, (char **) tmp_argv, &fg_operations, NULL);
851   exit (0);
852 }
853
854 static void __attribute__((noreturn))
855 usage (int status)
856 {
857   if (status != EXIT_SUCCESS)
858     fprintf (stderr, _("Try `%s --help' for more information.\n"),
859              program_name);
860   else {
861     fprintf (stdout,
862            _("%s: FUSE module for libguestfs\n"
863              "%s lets you mount a virtual machine filesystem\n"
864              "Copyright (C) 2009 Red Hat Inc.\n"
865              "Usage:\n"
866              "  %s [--options] [-- [--FUSE-options]] mountpoint\n"
867              "Options:\n"
868              "  -a|--add image       Add image\n"
869              "  --dir-cache-timeout  Set readdir cache timeout (default 5 sec)\n"
870              "  --fuse-help          Display extra FUSE options\n"
871              "  --help               Display help message and exit\n"
872              "  -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
873              "  -n|--no-sync         Don't autosync\n"
874              "  -o|--option opt      Pass extra option to FUSE\n"
875              "  -r|--ro              Mount read-only\n"
876              "  --selinux            Enable SELinux support\n"
877              "  --trace              Trace guestfs API calls (to stderr)\n"
878              "  -v|--verbose         Verbose messages\n"
879              "  -V|--version         Display version and exit\n"
880              ),
881              program_name, program_name, program_name);
882   }
883   exit (status);
884 }
885
886 int
887 main (int argc, char *argv[])
888 {
889   enum { HELP_OPTION = CHAR_MAX + 1 };
890
891   /* The command line arguments are broadly compatible with (a subset
892    * of) guestfish.  Thus we have to deal mainly with -a, -m and --ro.
893    */
894   static const char *options = "a:m:no:rv?V";
895   static const struct option long_options[] = {
896     { "add", 1, 0, 'a' },
897     { "dir-cache-timeout", 1, 0, 0 },
898     { "fuse-help", 0, 0, 0 },
899     { "help", 0, 0, HELP_OPTION },
900     { "mount", 1, 0, 'm' },
901     { "no-sync", 0, 0, 'n' },
902     { "option", 1, 0, 'o' },
903     { "ro", 0, 0, 'r' },
904     { "selinux", 0, 0, 0 },
905     { "trace", 0, 0, 0 },
906     { "verbose", 0, 0, 'v' },
907     { "version", 0, 0, 'V' },
908     { 0, 0, 0, 0 }
909   };
910
911   struct drv *drvs = NULL;
912   struct drv *drv;
913   struct mp *mps = NULL;
914   struct mp *mp;
915   char *p;
916   int c, i, r;
917   int option_index;
918   struct sigaction sa;
919
920   int fuse_argc = 0;
921   const char **fuse_argv = NULL;
922
923 #define ADD_FUSE_ARG(str)                                               \
924   do {                                                                  \
925     fuse_argc ++;                                                       \
926     fuse_argv = realloc (fuse_argv, (1+fuse_argc) * sizeof (char *));   \
927     if (!fuse_argv) {                                                   \
928       perror ("realloc");                                               \
929       exit (1);                                                         \
930     }                                                                   \
931     fuse_argv[fuse_argc-1] = (str);                                     \
932     fuse_argv[fuse_argc] = NULL;                                        \
933   } while (0)
934
935   /* LC_ALL=C is required so we can parse error messages. */
936   setenv ("LC_ALL", "C", 1);
937
938   /* Set global program name that is not polluted with libtool artifacts.  */
939   set_program_name (argv[0]);
940
941   memset (&sa, 0, sizeof sa);
942   sa.sa_handler = SIG_IGN;
943   sa.sa_flags = SA_RESTART;
944   sigaction (SIGPIPE, &sa, NULL);
945
946   /* Various initialization. */
947   init_dir_caches ();
948
949   g = guestfs_create ();
950   if (g == NULL) {
951     fprintf (stderr, _("guestfs_create: failed to create handle\n"));
952     exit (1);
953   }
954
955   guestfs_set_autosync (g, 1);
956   guestfs_set_recovery_proc (g, 0);
957
958   ADD_FUSE_ARG (program_name);
959   /* MUST be single-threaded.  You cannot have two threads accessing the
960    * same libguestfs handle, and opening more than one handle is likely
961    * to be very expensive.
962    */
963   ADD_FUSE_ARG ("-s");
964
965   /* If developing, add ./appliance to the path.  Note that libtools
966    * interferes with this because uninstalled guestfish is a shell
967    * script that runs the real program with an absolute path.  Detect
968    * that too.
969    *
970    * BUT if LIBGUESTFS_PATH environment variable is already set by
971    * the user, then don't override it.
972    */
973   if (getenv ("LIBGUESTFS_PATH") == NULL &&
974       argv[0] &&
975       (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
976     guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
977
978   for (;;) {
979     c = getopt_long (argc, argv, options, long_options, &option_index);
980     if (c == -1) break;
981
982     switch (c) {
983     case 0:                     /* options which are long only */
984       if (STREQ (long_options[option_index].name, "dir-cache-timeout"))
985         dir_cache_timeout = atoi (optarg);
986       else if (STREQ (long_options[option_index].name, "fuse-help"))
987         fuse_help ();
988       else if (STREQ (long_options[option_index].name, "selinux"))
989         guestfs_set_selinux (g, 1);
990       else if (STREQ (long_options[option_index].name, "trace")) {
991         ADD_FUSE_ARG ("-f");
992         guestfs_set_trace (g, 1);
993         guestfs_set_recovery_proc (g, 1);
994       }
995       else {
996         fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
997                  program_name, long_options[option_index].name, option_index);
998         exit (1);
999       }
1000       break;
1001
1002     case 'a':
1003       if (access (optarg, R_OK) != 0) {
1004         perror (optarg);
1005         exit (1);
1006       }
1007       drv = malloc (sizeof (struct drv));
1008       if (!drv) {
1009         perror ("malloc");
1010         exit (1);
1011       }
1012       drv->filename = optarg;
1013       drv->next = drvs;
1014       drvs = drv;
1015       break;
1016
1017     case 'm':
1018       mp = malloc (sizeof (struct mp));
1019       if (!mp) {
1020         perror ("malloc");
1021         exit (1);
1022       }
1023       p = strchr (optarg, ':');
1024       if (p) {
1025         *p = '\0';
1026         mp->mountpoint = p+1;
1027       } else
1028         mp->mountpoint = bad_cast ("/");
1029       mp->device = optarg;
1030       mp->next = mps;
1031       mps = mp;
1032       break;
1033
1034     case 'n':
1035       guestfs_set_autosync (g, 0);
1036       break;
1037
1038     case 'o':
1039       ADD_FUSE_ARG ("-o");
1040       ADD_FUSE_ARG (optarg);
1041       break;
1042
1043     case 'r':
1044       read_only = 1;
1045       break;
1046
1047     case 'v':
1048       verbose++;
1049       guestfs_set_verbose (g, verbose);
1050       break;
1051
1052     case 'V':
1053       printf ("%s %s\n", program_name, PACKAGE_VERSION);
1054       exit (0);
1055
1056     case HELP_OPTION:
1057       usage (0);
1058
1059     default:
1060       usage (1);
1061     }
1062   }
1063
1064   /* We must have at least one -a and at least one -m. */
1065   if (!drvs || !mps) {
1066     fprintf (stderr,
1067              _("%s: must have at least one -a and at least one -m option\n"),
1068              program_name);
1069     exit (1);
1070   }
1071
1072   /* We'd better have a mountpoint. */
1073   if (optind+1 != argc) {
1074     fprintf (stderr,
1075              _("%s: you must specify a mountpoint in the host filesystem\n"),
1076              program_name);
1077     exit (1);
1078   }
1079
1080   /* Do the guest drives and mountpoints. */
1081   add_drives (drvs);
1082   if (guestfs_launch (g) == -1)
1083     exit (1);
1084   mount_mps (mps);
1085
1086   /* FUSE example does this, not clear if it's necessary, but ... */
1087   if (guestfs_umask (g, 0) == -1)
1088     exit (1);
1089
1090   /* At the last minute, remove the libguestfs error handler.  In code
1091    * above this point, the default error handler has been used which
1092    * sends all errors to stderr.  Now before entering FUSE itself we
1093    * want to silence errors so we can convert them (see error()
1094    * function above).
1095    */
1096   guestfs_set_error_handler (g, NULL, NULL);
1097
1098   /* Finish off FUSE args. */
1099   ADD_FUSE_ARG (argv[optind]);
1100
1101   /*
1102     It says about the line containing the for-statement:
1103     error: assuming signed overflow does not occur when simplifying conditional to constant [-Wstrict-overflow]
1104
1105   if (verbose) {
1106     fprintf (stderr, "guestmount: invoking FUSE with args [");
1107     for (i = 0; i < fuse_argc; ++i) {
1108       if (i > 0) fprintf (stderr, ", ");
1109       fprintf (stderr, "%s", fuse_argv[i]);
1110     }
1111     fprintf (stderr, "]\n");
1112   }
1113   */
1114
1115   r = fuse_main (fuse_argc, (char **) fuse_argv, &fg_operations, NULL);
1116
1117   /* Cleanup. */
1118   guestfs_close (g);
1119   free_dir_caches ();
1120
1121   exit (r == -1 ? 1 : 0);
1122 }
1123
1124 /* List is built in reverse order, so add them in reverse order. */
1125 static void
1126 add_drives (struct drv *drv)
1127 {
1128   int r;
1129
1130   if (drv) {
1131     add_drives (drv->next);
1132     if (!read_only)
1133       r = guestfs_add_drive (g, drv->filename);
1134     else
1135       r = guestfs_add_drive_ro (g, drv->filename);
1136     if (r == -1)
1137       exit (1);
1138   }
1139 }
1140
1141 /* List is built in reverse order, so mount them in reverse order. */
1142 static void
1143 mount_mps (struct mp *mp)
1144 {
1145   int r;
1146
1147   if (mp) {
1148     mount_mps (mp->next);
1149     if (!read_only)
1150       r = guestfs_mount (g, mp->device, mp->mountpoint);
1151     else
1152       r = guestfs_mount_ro (g, mp->device, mp->mountpoint);
1153     if (r == -1)
1154       exit (1);
1155   }
1156 }