b4a917fcf9f5a65a4c136c891647b44a9a47cc35
[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, from, to);
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 (from);
445   dir_cache_invalidate (to);
446
447   /* XXX It's not clear how close the 'mv' command is to the
448    * rename syscall.  We might need to add the rename syscall
449    * to the guestfs(3) API.
450    */
451   r = guestfs_mv (g, from, to);
452   if (r == -1)
453     return error ();
454
455   return 0;
456 }
457
458 static int
459 fg_link (const char *from, const char *to)
460 {
461   int r;
462
463   if (read_only) return -EROFS;
464
465   dir_cache_invalidate (from);
466   dir_cache_invalidate (to);
467
468   r = guestfs_ln (g, from, to);
469   if (r == -1)
470     return error ();
471
472   return 0;
473 }
474
475 static int
476 fg_chmod (const char *path, mode_t mode)
477 {
478   int r;
479
480   if (read_only) return -EROFS;
481
482   dir_cache_invalidate (path);
483
484   r = guestfs_chmod (g, mode, path);
485   if (r == -1)
486     return error ();
487
488   return 0;
489 }
490
491 static int
492 fg_chown (const char *path, uid_t uid, gid_t gid)
493 {
494   int r;
495
496   if (read_only) return -EROFS;
497
498   dir_cache_invalidate (path);
499
500   r = guestfs_lchown (g, uid, gid, path);
501   if (r == -1)
502     return error ();
503
504   return 0;
505 }
506
507 static int
508 fg_truncate (const char *path, off_t size)
509 {
510   int r;
511
512   if (read_only) return -EROFS;
513
514   dir_cache_invalidate (path);
515
516   r = guestfs_truncate_size (g, path, size);
517   if (r == -1)
518     return error ();
519
520   return 0;
521 }
522
523 static int
524 fg_utimens (const char *path, const struct timespec ts[2])
525 {
526   int r;
527
528   if (read_only) return -EROFS;
529
530   dir_cache_invalidate (path);
531
532   time_t atsecs = ts[0].tv_sec;
533   long atnsecs = ts[0].tv_nsec;
534   time_t mtsecs = ts[1].tv_sec;
535   long mtnsecs = ts[1].tv_nsec;
536
537 #ifdef UTIME_NOW
538   if (atnsecs == UTIME_NOW)
539     atnsecs = -1;
540 #endif
541 #ifdef UTIME_OMIT
542   if (atnsecs == UTIME_OMIT)
543     atnsecs = -2;
544 #endif
545 #ifdef UTIME_NOW
546   if (mtnsecs == UTIME_NOW)
547     mtnsecs = -1;
548 #endif
549 #ifdef UTIME_OMIT
550   if (mtnsecs == UTIME_OMIT)
551     mtnsecs = -2;
552 #endif
553
554   r = guestfs_utimens (g, path, atsecs, atnsecs, mtsecs, mtnsecs);
555   if (r == -1)
556     return error ();
557
558   return 0;
559 }
560
561 /* This call is quite hard to emulate through the guestfs(3) API.  In
562  * one sense it's a little like access (see above) because it tests
563  * whether opening a file would succeed given the flags.  But it also
564  * has side effects such as truncating the file if O_TRUNC is given.
565  * Therefore we need to emulate it ... painfully.
566  */
567 static int
568 fg_open (const char *path, struct fuse_file_info *fi)
569 {
570   int r, exists;
571
572   if (fi->flags & O_WRONLY) {
573     if (read_only)
574       return -EROFS;
575   }
576
577   exists = guestfs_exists (g, path);
578   if (exists == -1)
579     return error ();
580
581   if (fi->flags & O_CREAT) {
582     if (read_only)
583       return -EROFS;
584
585     dir_cache_invalidate (path);
586
587     /* Exclusive?  File must not exist already. */
588     if (fi->flags & O_EXCL) {
589       if (exists)
590         return -EEXIST;
591     }
592
593     /* Create?  Touch it and optionally truncate it. */
594     r = guestfs_touch (g, path);
595     if (r == -1)
596       return error ();
597
598     if (fi->flags & O_TRUNC) {
599       r = guestfs_truncate (g, path);
600       if (r == -1)
601         return error ();
602     }
603   } else {
604     /* Not create, just check it exists. */
605     if (!exists)
606       return -ENOENT;
607   }
608
609   return 0;
610 }
611
612 static int
613 fg_read (const char *path, char *buf, size_t size, off_t offset,
614          struct fuse_file_info *fi)
615 {
616   char *r;
617   size_t rsize;
618
619   if (verbose)
620     fprintf (stderr, "fg_read: %s: size %zu offset %ju\n",
621              path, size, offset);
622
623   /* The guestfs protocol limits size to somewhere over 2MB.  We just
624    * reduce the requested size here accordingly and push the problem
625    * up to every user.  http://www.jwz.org/doc/worse-is-better.html
626    */
627   const size_t limit = 2 * 1024 * 1024;
628   if (size > limit)
629     size = limit;
630
631   r = guestfs_pread (g, path, size, offset, &rsize);
632   if (r == NULL)
633     return error ();
634
635   /* This should never happen, but at least it stops us overflowing
636    * the output buffer if it does happen.
637    */
638   if (rsize > size)
639     rsize = size;
640
641   memcpy (buf, r, rsize);
642   free (r);
643
644   return rsize;
645 }
646
647 static int
648 fg_write (const char *path, const char *buf, size_t size,
649           off_t offset, struct fuse_file_info *fi)
650 {
651   if (read_only) return -EROFS;
652
653   dir_cache_invalidate (path);
654
655   return -ENOSYS;               /* XXX */
656 }
657
658 static int
659 fg_statfs (const char *path, struct statvfs *stbuf)
660 {
661   struct guestfs_statvfs *r;
662
663   r = guestfs_statvfs (g, path);
664   if (r == NULL)
665     return error ();
666
667   stbuf->f_bsize = r->bsize;
668   stbuf->f_frsize = r->frsize;
669   stbuf->f_blocks = r->blocks;
670   stbuf->f_bfree = r->bfree;
671   stbuf->f_bavail = r->bavail;
672   stbuf->f_files = r->files;
673   stbuf->f_ffree = r->ffree;
674   stbuf->f_favail = r->favail;
675   stbuf->f_fsid = r->fsid;
676   stbuf->f_flag = r->flag;
677   stbuf->f_namemax = r->namemax;
678
679   guestfs_free_statvfs (r);
680
681   return 0;
682 }
683
684 static int
685 fg_release (const char *path, struct fuse_file_info *fi)
686 {
687   /* Just a stub. This method is optional and can safely be left
688    * unimplemented.
689    */
690   return 0;
691 }
692
693 /* Emulate this by calling sync. */
694 static int fg_fsync(const char *path, int isdatasync,
695                      struct fuse_file_info *fi)
696 {
697   int r;
698
699   r = guestfs_sync (g);
700   if (r == -1)
701     return error ();
702
703   return 0;
704 }
705
706 static int
707 fg_setxattr (const char *path, const char *name, const char *value,
708              size_t size, int flags)
709 {
710   int r;
711
712   if (read_only) return -EROFS;
713
714   dir_cache_invalidate (path);
715
716   /* XXX Underlying guestfs(3) API doesn't understand the flags. */
717   r = guestfs_lsetxattr (g, name, value, size, path);
718   if (r == -1)
719     return error ();
720
721   return 0;
722 }
723
724 /* The guestfs(3) API for getting xattrs is much easier to use
725  * than the real syscall.  Unfortunately we now have to emulate
726  * the real syscall using that API :-(
727  */
728 static int
729 fg_getxattr (const char *path, const char *name, char *value,
730              size_t size)
731 {
732   const struct guestfs_xattr_list *xattrs;
733   int free_attrs = 0;
734
735   xattrs = xac_lookup (path);
736   if (xattrs == NULL) {
737     xattrs = guestfs_lgetxattrs (g, path);
738     if (xattrs == NULL)
739       return error ();
740     free_attrs = 1;
741   }
742
743   size_t i;
744   int r = -ENOATTR;
745   for (i = 0; i < xattrs->len; ++i) {
746     if (STREQ (xattrs->val[i].attrname, name)) {
747       size_t sz = xattrs->val[i].attrval_len;
748       if (sz > size)
749         sz = size;
750       memcpy (value, xattrs->val[i].attrval, sz);
751       r = 0;
752       break;
753     }
754   }
755
756   if (free_attrs)
757     guestfs_free_xattr_list ((struct guestfs_xattr_list *) xattrs);
758
759   return r;
760 }
761
762 /* Ditto as above. */
763 static int
764 fg_listxattr (const char *path, char *list, size_t size)
765 {
766   const struct guestfs_xattr_list *xattrs;
767   int free_attrs = 0;
768
769   xattrs = xac_lookup (path);
770   if (xattrs == NULL) {
771     xattrs = guestfs_lgetxattrs (g, path);
772     if (xattrs == NULL)
773       return error ();
774     free_attrs = 1;
775   }
776
777   size_t i;
778   ssize_t copied = 0;
779   for (i = 0; i < xattrs->len; ++i) {
780     size_t len = strlen (xattrs->val[i].attrname) + 1;
781     if (size >= len) {
782       memcpy (list, xattrs->val[i].attrname, len);
783       size -= len;
784       list += len;
785       copied += len;
786     } else {
787       copied = -ERANGE;
788       break;
789     }
790   }
791
792   if (free_attrs)
793     guestfs_free_xattr_list ((struct guestfs_xattr_list *) xattrs);
794
795   return copied;
796 }
797
798 static int
799 fg_removexattr(const char *path, const char *name)
800 {
801   int r;
802
803   if (read_only) return -EROFS;
804
805   dir_cache_invalidate (path);
806
807   r = guestfs_lremovexattr (g, name, path);
808   if (r == -1)
809     return error ();
810
811   return 0;
812 }
813
814 static struct fuse_operations fg_operations = {
815   .getattr      = fg_getattr,
816   .access       = fg_access,
817   .readlink     = fg_readlink,
818   .readdir      = fg_readdir,
819   .mknod        = fg_mknod,
820   .mkdir        = fg_mkdir,
821   .symlink      = fg_symlink,
822   .unlink       = fg_unlink,
823   .rmdir        = fg_rmdir,
824   .rename       = fg_rename,
825   .link         = fg_link,
826   .chmod        = fg_chmod,
827   .chown        = fg_chown,
828   .truncate     = fg_truncate,
829   .utimens      = fg_utimens,
830   .open         = fg_open,
831   .read         = fg_read,
832   .write        = fg_write,
833   .statfs       = fg_statfs,
834   .release      = fg_release,
835   .fsync        = fg_fsync,
836   .setxattr     = fg_setxattr,
837   .getxattr     = fg_getxattr,
838   .listxattr    = fg_listxattr,
839   .removexattr  = fg_removexattr,
840 };
841
842 struct drv {
843   struct drv *next;
844   char *filename;
845 };
846
847 struct mp {
848   struct mp *next;
849   char *device;
850   char *mountpoint;
851 };
852
853 static void add_drives (struct drv *);
854 static void mount_mps (struct mp *);
855
856 static void __attribute__((noreturn))
857 fuse_help (void)
858 {
859   const char *tmp_argv[] = { program_name, "--help", NULL };
860   fuse_main (2, (char **) tmp_argv, &fg_operations, NULL);
861   exit (EXIT_SUCCESS);
862 }
863
864 static void __attribute__((noreturn))
865 usage (int status)
866 {
867   if (status != EXIT_SUCCESS)
868     fprintf (stderr, _("Try `%s --help' for more information.\n"),
869              program_name);
870   else {
871     fprintf (stdout,
872            _("%s: FUSE module for libguestfs\n"
873              "%s lets you mount a virtual machine filesystem\n"
874              "Copyright (C) 2009 Red Hat Inc.\n"
875              "Usage:\n"
876              "  %s [--options] [-- [--FUSE-options]] mountpoint\n"
877              "Options:\n"
878              "  -a|--add image       Add image\n"
879              "  --dir-cache-timeout  Set readdir cache timeout (default 5 sec)\n"
880              "  --fuse-help          Display extra FUSE options\n"
881              "  --help               Display help message and exit\n"
882              "  -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
883              "  -n|--no-sync         Don't autosync\n"
884              "  -o|--option opt      Pass extra option to FUSE\n"
885              "  -r|--ro              Mount read-only\n"
886              "  --selinux            Enable SELinux support\n"
887              "  --trace              Trace guestfs API calls (to stderr)\n"
888              "  -v|--verbose         Verbose messages\n"
889              "  -V|--version         Display version and exit\n"
890              ),
891              program_name, program_name, program_name);
892   }
893   exit (status);
894 }
895
896 int
897 main (int argc, char *argv[])
898 {
899   setlocale (LC_ALL, "");
900   bindtextdomain (PACKAGE, LOCALEBASEDIR);
901   textdomain (PACKAGE);
902
903   enum { HELP_OPTION = CHAR_MAX + 1 };
904
905   /* The command line arguments are broadly compatible with (a subset
906    * of) guestfish.  Thus we have to deal mainly with -a, -m and --ro.
907    */
908   static const char *options = "a:m:no:rv?V";
909   static const struct option long_options[] = {
910     { "add", 1, 0, 'a' },
911     { "dir-cache-timeout", 1, 0, 0 },
912     { "fuse-help", 0, 0, 0 },
913     { "help", 0, 0, HELP_OPTION },
914     { "mount", 1, 0, 'm' },
915     { "no-sync", 0, 0, 'n' },
916     { "option", 1, 0, 'o' },
917     { "ro", 0, 0, 'r' },
918     { "selinux", 0, 0, 0 },
919     { "trace", 0, 0, 0 },
920     { "verbose", 0, 0, 'v' },
921     { "version", 0, 0, 'V' },
922     { 0, 0, 0, 0 }
923   };
924
925   struct drv *drvs = NULL;
926   struct drv *drv;
927   struct mp *mps = NULL;
928   struct mp *mp;
929   char *p;
930   int c, r;
931   int option_index;
932   struct sigaction sa;
933
934   int fuse_argc = 0;
935   const char **fuse_argv = NULL;
936
937 #define ADD_FUSE_ARG(str)                                               \
938   do {                                                                  \
939     fuse_argc ++;                                                       \
940     fuse_argv = realloc (fuse_argv, (1+fuse_argc) * sizeof (char *));   \
941     if (!fuse_argv) {                                                   \
942       perror ("realloc");                                               \
943       exit (EXIT_FAILURE);                                                         \
944     }                                                                   \
945     fuse_argv[fuse_argc-1] = (str);                                     \
946     fuse_argv[fuse_argc] = NULL;                                        \
947   } while (0)
948
949   /* LC_ALL=C is required so we can parse error messages. */
950   setenv ("LC_ALL", "C", 1);
951
952   /* Set global program name that is not polluted with libtool artifacts.  */
953   set_program_name (argv[0]);
954
955   memset (&sa, 0, sizeof sa);
956   sa.sa_handler = SIG_IGN;
957   sa.sa_flags = SA_RESTART;
958   sigaction (SIGPIPE, &sa, NULL);
959
960   /* Various initialization. */
961   init_dir_caches ();
962
963   g = guestfs_create ();
964   if (g == NULL) {
965     fprintf (stderr, _("guestfs_create: failed to create handle\n"));
966     exit (EXIT_FAILURE);
967   }
968
969   guestfs_set_autosync (g, 1);
970   guestfs_set_recovery_proc (g, 0);
971
972   ADD_FUSE_ARG (program_name);
973   /* MUST be single-threaded.  You cannot have two threads accessing the
974    * same libguestfs handle, and opening more than one handle is likely
975    * to be very expensive.
976    */
977   ADD_FUSE_ARG ("-s");
978
979   /* If developing, add ./appliance to the path.  Note that libtools
980    * interferes with this because uninstalled guestfish is a shell
981    * script that runs the real program with an absolute path.  Detect
982    * that too.
983    *
984    * BUT if LIBGUESTFS_PATH environment variable is already set by
985    * the user, then don't override it.
986    */
987   if (getenv ("LIBGUESTFS_PATH") == NULL &&
988       argv[0] &&
989       (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
990     guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
991
992   for (;;) {
993     c = getopt_long (argc, argv, options, long_options, &option_index);
994     if (c == -1) break;
995
996     switch (c) {
997     case 0:                     /* options which are long only */
998       if (STREQ (long_options[option_index].name, "dir-cache-timeout"))
999         dir_cache_timeout = atoi (optarg);
1000       else if (STREQ (long_options[option_index].name, "fuse-help"))
1001         fuse_help ();
1002       else if (STREQ (long_options[option_index].name, "selinux"))
1003         guestfs_set_selinux (g, 1);
1004       else if (STREQ (long_options[option_index].name, "trace")) {
1005         ADD_FUSE_ARG ("-f");
1006         guestfs_set_trace (g, 1);
1007         guestfs_set_recovery_proc (g, 1);
1008       }
1009       else {
1010         fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
1011                  program_name, long_options[option_index].name, option_index);
1012         exit (EXIT_FAILURE);
1013       }
1014       break;
1015
1016     case 'a':
1017       if (access (optarg, R_OK) != 0) {
1018         perror (optarg);
1019         exit (EXIT_FAILURE);
1020       }
1021       drv = malloc (sizeof (struct drv));
1022       if (!drv) {
1023         perror ("malloc");
1024         exit (EXIT_FAILURE);
1025       }
1026       drv->filename = optarg;
1027       drv->next = drvs;
1028       drvs = drv;
1029       break;
1030
1031     case 'm':
1032       mp = malloc (sizeof (struct mp));
1033       if (!mp) {
1034         perror ("malloc");
1035         exit (EXIT_FAILURE);
1036       }
1037       p = strchr (optarg, ':');
1038       if (p) {
1039         *p = '\0';
1040         mp->mountpoint = p+1;
1041       } else
1042         mp->mountpoint = bad_cast ("/");
1043       mp->device = optarg;
1044       mp->next = mps;
1045       mps = mp;
1046       break;
1047
1048     case 'n':
1049       guestfs_set_autosync (g, 0);
1050       break;
1051
1052     case 'o':
1053       ADD_FUSE_ARG ("-o");
1054       ADD_FUSE_ARG (optarg);
1055       break;
1056
1057     case 'r':
1058       read_only = 1;
1059       break;
1060
1061     case 'v':
1062       verbose++;
1063       guestfs_set_verbose (g, verbose);
1064       break;
1065
1066     case 'V':
1067       printf ("%s %s\n", program_name, PACKAGE_VERSION);
1068       exit (EXIT_SUCCESS);
1069
1070     case HELP_OPTION:
1071       usage (EXIT_SUCCESS);
1072
1073     default:
1074       usage (EXIT_FAILURE);
1075     }
1076   }
1077
1078   /* We must have at least one -a and at least one -m. */
1079   if (!drvs || !mps) {
1080     fprintf (stderr,
1081              _("%s: must have at least one -a and at least one -m option\n"),
1082              program_name);
1083     exit (EXIT_FAILURE);
1084   }
1085
1086   /* We'd better have a mountpoint. */
1087   if (optind+1 != argc) {
1088     fprintf (stderr,
1089              _("%s: you must specify a mountpoint in the host filesystem\n"),
1090              program_name);
1091     exit (EXIT_FAILURE);
1092   }
1093
1094   /* Do the guest drives and mountpoints. */
1095   add_drives (drvs);
1096   if (guestfs_launch (g) == -1)
1097     exit (EXIT_FAILURE);
1098   mount_mps (mps);
1099
1100   /* FUSE example does this, not clear if it's necessary, but ... */
1101   if (guestfs_umask (g, 0) == -1)
1102     exit (EXIT_FAILURE);
1103
1104   /* At the last minute, remove the libguestfs error handler.  In code
1105    * above this point, the default error handler has been used which
1106    * sends all errors to stderr.  Now before entering FUSE itself we
1107    * want to silence errors so we can convert them (see error()
1108    * function above).
1109    */
1110   guestfs_set_error_handler (g, NULL, NULL);
1111
1112   /* Finish off FUSE args. */
1113   ADD_FUSE_ARG (argv[optind]);
1114
1115   /*
1116     It says about the line containing the for-statement:
1117     error: assuming signed overflow does not occur when simplifying conditional to constant [-Wstrict-overflow]
1118
1119   if (verbose) {
1120     fprintf (stderr, "guestmount: invoking FUSE with args [");
1121     for (i = 0; i < fuse_argc; ++i) {
1122       if (i > 0) fprintf (stderr, ", ");
1123       fprintf (stderr, "%s", fuse_argv[i]);
1124     }
1125     fprintf (stderr, "]\n");
1126   }
1127   */
1128
1129   r = fuse_main (fuse_argc, (char **) fuse_argv, &fg_operations, NULL);
1130
1131   /* Cleanup. */
1132   guestfs_close (g);
1133   free_dir_caches ();
1134
1135   exit (r == -1 ? 1 : 0);
1136 }
1137
1138 /* List is built in reverse order, so add them in reverse order. */
1139 static void
1140 add_drives (struct drv *drv)
1141 {
1142   int r;
1143
1144   if (drv) {
1145     add_drives (drv->next);
1146     if (!read_only)
1147       r = guestfs_add_drive (g, drv->filename);
1148     else
1149       r = guestfs_add_drive_ro (g, drv->filename);
1150     if (r == -1)
1151       exit (EXIT_FAILURE);
1152   }
1153 }
1154
1155 /* List is built in reverse order, so mount them in reverse order. */
1156 static void
1157 mount_mps (struct mp *mp)
1158 {
1159   int r;
1160
1161   if (mp) {
1162     mount_mps (mp->next);
1163
1164     /* Don't use guestfs_mount here because that will default to mount
1165      * options -o sync,noatime.  For more information, see guestfs(3)
1166      * section "LIBGUESTFS GOTCHAS".
1167      */
1168     const char *options = read_only ? "ro" : "";
1169     r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
1170     if (r == -1)
1171       exit (EXIT_FAILURE);
1172   }
1173 }