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