build: Don't add version extra string to the version number.
[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 <inttypes.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <getopt.h>
36 #include <fcntl.h>
37 #include <dirent.h>
38 #include <errno.h>
39 #include <signal.h>
40 #include <time.h>
41 #include <assert.h>
42 #include <sys/time.h>
43 #include <sys/types.h>
44 #include <locale.h>
45
46 #include <fuse.h>
47 #include <guestfs.h>
48
49 #include "progname.h"
50
51 #include "guestmount.h"
52 #include "dircache.h"
53
54 /* See <attr/xattr.h> */
55 #ifndef ENOATTR
56 #define ENOATTR ENODATA
57 #endif
58
59 static guestfs_h *g = NULL;
60 static int read_only = 0;
61 int verbose = 0;
62 int dir_cache_timeout = 60;
63
64 /* This is ugly: guestfs errors are strings, FUSE wants -errno.  We
65  * have to do the conversion as best we can.
66  */
67 #define MAX_ERRNO 256
68
69 static int
70 error (void)
71 {
72   int i;
73   const char *err = guestfs_last_error (g);
74
75   if (!err)
76     return -EINVAL;
77
78   if (verbose)
79     fprintf (stderr, "%s\n", err);
80
81   /* Add a few of our own ... */
82
83   /* This indicates guestfsd died.  Translate into a hard EIO error.
84    * Arguably we could relaunch the guest if we hit this error.
85    */
86   if (strstr (err, "call launch before using this function"))
87     return -EIO;
88
89   /* See if it matches an errno string in the host. */
90   for (i = 0; i < MAX_ERRNO; ++i) {
91     const char *e = strerror (i);
92     if (e && strstr (err, e) != NULL)
93       return -i;
94   }
95
96   /* Too bad, return a generic error. */
97   return -EINVAL;
98 }
99
100 static struct guestfs_xattr_list *
101 copy_xattr_list (const struct guestfs_xattr *first, size_t num)
102 {
103   struct guestfs_xattr_list *xattrs;
104
105   xattrs = malloc (sizeof *xattrs);
106   if (xattrs == NULL) {
107     perror ("malloc");
108     return NULL;
109   }
110
111   xattrs->len = num;
112   xattrs->val = malloc (num * sizeof (struct guestfs_xattr));
113   if (xattrs->val == NULL) {
114     perror ("malloc");
115     free (xattrs);
116     return NULL;
117   }
118
119   size_t i;
120   for (i = 0; i < num; ++i) {
121     xattrs->val[i].attrname = strdup (first[i].attrname);
122     xattrs->val[i].attrval_len = first[i].attrval_len;
123     xattrs->val[i].attrval = malloc (first[i].attrval_len);
124     memcpy (xattrs->val[i].attrval, first[i].attrval, first[i].attrval_len);
125   }
126
127   return xattrs;
128 }
129
130 static int
131 fg_readdir (const char *path, void *buf, fuse_fill_dir_t filler,
132             off_t offset, struct fuse_file_info *fi)
133 {
134   time_t now;
135   time (&now);
136
137   dir_cache_remove_all_expired (now);
138
139   struct guestfs_dirent_list *ents;
140
141   ents = guestfs_readdir (g, path);
142   if (ents == NULL)
143     return error ();
144
145   size_t i;
146   for (i = 0; i < ents->len; ++i) {
147     struct stat stat;
148     memset (&stat, 0, sizeof stat);
149
150     stat.st_ino = ents->val[i].ino;
151     switch (ents->val[i].ftyp) {
152     case 'b': stat.st_mode = S_IFBLK; break;
153     case 'c': stat.st_mode = S_IFCHR; break;
154     case 'd': stat.st_mode = S_IFDIR; break;
155     case 'f': stat.st_mode = S_IFIFO; break;
156     case 'l': stat.st_mode = S_IFLNK; break;
157     case 'r': stat.st_mode = S_IFREG; break;
158     case 's': stat.st_mode = S_IFSOCK; break;
159     case 'u':
160     case '?':
161     default:  stat.st_mode = 0;
162     }
163
164     /* Copied from the example, which also ignores 'offset'.  I'm
165      * not quite sure how this is ever supposed to work on large
166      * directories. XXX
167      */
168     if (filler (buf, ents->val[i].name, &stat, 0))
169       break;
170   }
171
172   /* Now prepopulate the directory caches.  This step is just an
173    * optimization, don't worry if it fails.
174    */
175   char **names = malloc ((ents->len + 1) * sizeof (char *));
176   if (names) {
177     for (i = 0; i < ents->len; ++i)
178       names[i] = ents->val[i].name;
179     names[i] = NULL;
180
181     struct guestfs_stat_list *ss = guestfs_lstatlist (g, path, names);
182     if (ss) {
183       for (i = 0; i < ss->len; ++i) {
184         if (ss->val[i].ino >= 0) {
185           struct stat statbuf;
186
187           statbuf.st_dev = ss->val[i].dev;
188           statbuf.st_ino = ss->val[i].ino;
189           statbuf.st_mode = ss->val[i].mode;
190           statbuf.st_nlink = ss->val[i].nlink;
191           statbuf.st_uid = ss->val[i].uid;
192           statbuf.st_gid = ss->val[i].gid;
193           statbuf.st_rdev = ss->val[i].rdev;
194           statbuf.st_size = ss->val[i].size;
195           statbuf.st_blksize = ss->val[i].blksize;
196           statbuf.st_blocks = ss->val[i].blocks;
197           statbuf.st_atime = ss->val[i].atime;
198           statbuf.st_mtime = ss->val[i].mtime;
199           statbuf.st_ctime = ss->val[i].ctime;
200
201           lsc_insert (path, names[i], now, &statbuf);
202         }
203       }
204       guestfs_free_stat_list (ss);
205     }
206
207     struct guestfs_xattr_list *xattrs = guestfs_lxattrlist (g, path, names);
208     if (xattrs) {
209       size_t ni, num;
210       struct guestfs_xattr *first;
211       struct guestfs_xattr_list *copy;
212       for (i = 0, ni = 0; i < xattrs->len; ++i, ++ni) {
213         assert (strlen (xattrs->val[i].attrname) == 0);
214         if (xattrs->val[i].attrval_len > 0) {
215           ++i;
216           first = &xattrs->val[i];
217           num = 0;
218           for (; i < xattrs->len && strlen (xattrs->val[i].attrname) > 0; ++i)
219             num++;
220
221           copy = copy_xattr_list (first, num);
222           if (copy)
223             xac_insert (path, names[ni], now, copy);
224
225           i--;
226         }
227       }
228       guestfs_free_xattr_list (xattrs);
229     }
230
231     char **links = guestfs_readlinklist (g, path, names);
232     if (links) {
233       for (i = 0; names[i] != NULL; ++i) {
234         if (links[i][0])
235           /* Note that rlc_insert owns the string links[i] after this, */
236           rlc_insert (path, names[i], now, links[i]);
237         else
238           /* which is why we have to free links[i] here. */
239           free (links[i]);
240       }
241       free (links);             /* free the array, not the strings */
242     }
243
244     free (names);
245   }
246
247   guestfs_free_dirent_list (ents);
248
249   return 0;
250 }
251
252 static int
253 fg_getattr (const char *path, struct stat *statbuf)
254 {
255   const struct stat *buf;
256
257   buf = lsc_lookup (path);
258   if (buf) {
259     memcpy (statbuf, buf, sizeof *statbuf);
260     return 0;
261   }
262
263   struct guestfs_stat *r;
264
265   r = guestfs_lstat (g, path);
266   if (r == NULL)
267     return error ();
268
269   statbuf->st_dev = r->dev;
270   statbuf->st_ino = r->ino;
271   statbuf->st_mode = r->mode;
272   statbuf->st_nlink = r->nlink;
273   statbuf->st_uid = r->uid;
274   statbuf->st_gid = r->gid;
275   statbuf->st_rdev = r->rdev;
276   statbuf->st_size = r->size;
277   statbuf->st_blksize = r->blksize;
278   statbuf->st_blocks = r->blocks;
279   statbuf->st_atime = r->atime;
280   statbuf->st_mtime = r->mtime;
281   statbuf->st_ctime = r->ctime;
282
283   guestfs_free_stat (r);
284
285   return 0;
286 }
287
288 /* Nautilus loves to use access(2) to test everything about a file,
289  * such as whether it's executable.  Therefore treat this a lot like
290  * fg_getattr.
291  */
292 static int
293 fg_access (const char *path, int mask)
294 {
295   struct stat statbuf;
296   int r;
297
298   if (read_only && (mask & W_OK))
299     return -EROFS;
300
301   r = fg_getattr (path, &statbuf);
302   if (r < 0 || mask == F_OK)
303     return r;
304
305   struct fuse_context *fuse = fuse_get_context ();
306   int ok = 1;
307
308   if (mask & R_OK)
309     ok = ok &&
310       (  fuse->uid == statbuf.st_uid ? statbuf.st_mode & S_IRUSR
311        : fuse->gid == statbuf.st_gid ? statbuf.st_mode & S_IRGRP
312        : statbuf.st_mode & S_IROTH);
313   if (mask & W_OK)
314     ok = ok &&
315       (  fuse->uid == statbuf.st_uid ? statbuf.st_mode & S_IWUSR
316        : fuse->gid == statbuf.st_gid ? statbuf.st_mode & S_IWGRP
317        : statbuf.st_mode & S_IWOTH);
318   if (mask & X_OK)
319     ok = ok &&
320       (  fuse->uid == statbuf.st_uid ? statbuf.st_mode & S_IXUSR
321        : fuse->gid == statbuf.st_gid ? statbuf.st_mode & S_IXGRP
322        : statbuf.st_mode & S_IXOTH);
323
324   return ok ? 0 : -EACCES;
325 }
326
327 static int
328 fg_readlink (const char *path, char *buf, size_t size)
329 {
330   const char *r;
331   int free_it = 0;
332
333   r = rlc_lookup (path);
334   if (!r) {
335     r = guestfs_readlink (g, path);
336     if (r == NULL)
337       return error ();
338     free_it = 1;
339   }
340
341   /* Note this is different from the real readlink(2) syscall.  FUSE wants
342    * the string to be always nul-terminated, even if truncated.
343    */
344   size_t len = strlen (r);
345   if (len > size - 1)
346     len = size - 1;
347
348   memcpy (buf, r, len);
349   buf[len] = '\0';
350
351   if (free_it) {
352     char *tmp = (char *) r;
353     free (tmp);
354   }
355
356   return 0;
357 }
358
359 static int
360 fg_mknod (const char *path, mode_t mode, dev_t rdev)
361 {
362   int r;
363
364   if (read_only) return -EROFS;
365
366   dir_cache_invalidate (path);
367
368   r = guestfs_mknod (g, mode, major (rdev), minor (rdev), path);
369   if (r == -1)
370     return error ();
371
372   return 0;
373 }
374
375 static int
376 fg_mkdir (const char *path, mode_t mode)
377 {
378   int r;
379
380   if (read_only) return -EROFS;
381
382   dir_cache_invalidate (path);
383
384   r = guestfs_mkdir_mode (g, path, mode);
385   if (r == -1)
386     return error ();
387
388   return 0;
389 }
390
391 static int
392 fg_unlink (const char *path)
393 {
394   int r;
395
396   if (read_only) return -EROFS;
397
398   dir_cache_invalidate (path);
399
400   r = guestfs_rm (g, path);
401   if (r == -1)
402     return error ();
403
404   return 0;
405 }
406
407 static int
408 fg_rmdir (const char *path)
409 {
410   int r;
411
412   if (read_only) return -EROFS;
413
414   dir_cache_invalidate (path);
415
416   r = guestfs_rmdir (g, path);
417   if (r == -1)
418     return error ();
419
420   return 0;
421 }
422
423 static int
424 fg_symlink (const char *from, const char *to)
425 {
426   int r;
427
428   if (read_only) return -EROFS;
429
430   dir_cache_invalidate (to);
431
432   r = guestfs_ln_s (g, from, to);
433   if (r == -1)
434     return error ();
435
436   return 0;
437 }
438
439 static int
440 fg_rename (const char *from, const char *to)
441 {
442   int r;
443
444   if (read_only) return -EROFS;
445
446   dir_cache_invalidate (from);
447   dir_cache_invalidate (to);
448
449   /* XXX It's not clear how close the 'mv' command is to the
450    * rename syscall.  We might need to add the rename syscall
451    * to the guestfs(3) API.
452    */
453   r = guestfs_mv (g, from, to);
454   if (r == -1)
455     return error ();
456
457   return 0;
458 }
459
460 static int
461 fg_link (const char *from, const char *to)
462 {
463   int r;
464
465   if (read_only) return -EROFS;
466
467   dir_cache_invalidate (from);
468   dir_cache_invalidate (to);
469
470   r = guestfs_ln (g, from, to);
471   if (r == -1)
472     return error ();
473
474   return 0;
475 }
476
477 static int
478 fg_chmod (const char *path, mode_t mode)
479 {
480   int r;
481
482   if (read_only) return -EROFS;
483
484   dir_cache_invalidate (path);
485
486   r = guestfs_chmod (g, mode, path);
487   if (r == -1)
488     return error ();
489
490   return 0;
491 }
492
493 static int
494 fg_chown (const char *path, uid_t uid, gid_t gid)
495 {
496   int r;
497
498   if (read_only) return -EROFS;
499
500   dir_cache_invalidate (path);
501
502   r = guestfs_lchown (g, uid, gid, path);
503   if (r == -1)
504     return error ();
505
506   return 0;
507 }
508
509 static int
510 fg_truncate (const char *path, off_t size)
511 {
512   int r;
513
514   if (read_only) return -EROFS;
515
516   dir_cache_invalidate (path);
517
518   r = guestfs_truncate_size (g, path, size);
519   if (r == -1)
520     return error ();
521
522   return 0;
523 }
524
525 static int
526 fg_utimens (const char *path, const struct timespec ts[2])
527 {
528   int r;
529
530   if (read_only) return -EROFS;
531
532   dir_cache_invalidate (path);
533
534   time_t atsecs = ts[0].tv_sec;
535   long atnsecs = ts[0].tv_nsec;
536   time_t mtsecs = ts[1].tv_sec;
537   long mtnsecs = ts[1].tv_nsec;
538
539 #ifdef UTIME_NOW
540   if (atnsecs == UTIME_NOW)
541     atnsecs = -1;
542 #endif
543 #ifdef UTIME_OMIT
544   if (atnsecs == UTIME_OMIT)
545     atnsecs = -2;
546 #endif
547 #ifdef UTIME_NOW
548   if (mtnsecs == UTIME_NOW)
549     mtnsecs = -1;
550 #endif
551 #ifdef UTIME_OMIT
552   if (mtnsecs == UTIME_OMIT)
553     mtnsecs = -2;
554 #endif
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 (STREQ (xattrs->val[i].attrname, name)) {
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 (EXIT_SUCCESS);
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   setlocale (LC_ALL, "");
902   bindtextdomain (PACKAGE, LOCALEBASEDIR);
903   textdomain (PACKAGE);
904
905   enum { HELP_OPTION = CHAR_MAX + 1 };
906
907   /* The command line arguments are broadly compatible with (a subset
908    * of) guestfish.  Thus we have to deal mainly with -a, -m and --ro.
909    */
910   static const char *options = "a:m:no:rv?V";
911   static const struct option long_options[] = {
912     { "add", 1, 0, 'a' },
913     { "dir-cache-timeout", 1, 0, 0 },
914     { "fuse-help", 0, 0, 0 },
915     { "help", 0, 0, HELP_OPTION },
916     { "mount", 1, 0, 'm' },
917     { "no-sync", 0, 0, 'n' },
918     { "option", 1, 0, 'o' },
919     { "ro", 0, 0, 'r' },
920     { "selinux", 0, 0, 0 },
921     { "trace", 0, 0, 0 },
922     { "verbose", 0, 0, 'v' },
923     { "version", 0, 0, 'V' },
924     { 0, 0, 0, 0 }
925   };
926
927   struct drv *drvs = NULL;
928   struct drv *drv;
929   struct mp *mps = NULL;
930   struct mp *mp;
931   char *p;
932   int c, r;
933   int option_index;
934   struct sigaction sa;
935
936   int fuse_argc = 0;
937   const char **fuse_argv = NULL;
938
939 #define ADD_FUSE_ARG(str)                                               \
940   do {                                                                  \
941     fuse_argc ++;                                                       \
942     fuse_argv = realloc (fuse_argv, (1+fuse_argc) * sizeof (char *));   \
943     if (!fuse_argv) {                                                   \
944       perror ("realloc");                                               \
945       exit (EXIT_FAILURE);                                                         \
946     }                                                                   \
947     fuse_argv[fuse_argc-1] = (str);                                     \
948     fuse_argv[fuse_argc] = NULL;                                        \
949   } while (0)
950
951   /* LC_ALL=C is required so we can parse error messages. */
952   setenv ("LC_ALL", "C", 1);
953
954   /* Set global program name that is not polluted with libtool artifacts.  */
955   set_program_name (argv[0]);
956
957   memset (&sa, 0, sizeof sa);
958   sa.sa_handler = SIG_IGN;
959   sa.sa_flags = SA_RESTART;
960   sigaction (SIGPIPE, &sa, NULL);
961
962   /* Various initialization. */
963   init_dir_caches ();
964
965   g = guestfs_create ();
966   if (g == NULL) {
967     fprintf (stderr, _("guestfs_create: failed to create handle\n"));
968     exit (EXIT_FAILURE);
969   }
970
971   guestfs_set_autosync (g, 1);
972   guestfs_set_recovery_proc (g, 0);
973
974   ADD_FUSE_ARG (program_name);
975   /* MUST be single-threaded.  You cannot have two threads accessing the
976    * same libguestfs handle, and opening more than one handle is likely
977    * to be very expensive.
978    */
979   ADD_FUSE_ARG ("-s");
980
981   /* If developing, add ./appliance to the path.  Note that libtools
982    * interferes with this because uninstalled guestfish is a shell
983    * script that runs the real program with an absolute path.  Detect
984    * that too.
985    *
986    * BUT if LIBGUESTFS_PATH environment variable is already set by
987    * the user, then don't override it.
988    */
989   if (getenv ("LIBGUESTFS_PATH") == NULL &&
990       argv[0] &&
991       (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
992     guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
993
994   for (;;) {
995     c = getopt_long (argc, argv, options, long_options, &option_index);
996     if (c == -1) break;
997
998     switch (c) {
999     case 0:                     /* options which are long only */
1000       if (STREQ (long_options[option_index].name, "dir-cache-timeout"))
1001         dir_cache_timeout = atoi (optarg);
1002       else if (STREQ (long_options[option_index].name, "fuse-help"))
1003         fuse_help ();
1004       else if (STREQ (long_options[option_index].name, "selinux"))
1005         guestfs_set_selinux (g, 1);
1006       else if (STREQ (long_options[option_index].name, "trace")) {
1007         ADD_FUSE_ARG ("-f");
1008         guestfs_set_trace (g, 1);
1009         guestfs_set_recovery_proc (g, 1);
1010       }
1011       else {
1012         fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
1013                  program_name, long_options[option_index].name, option_index);
1014         exit (EXIT_FAILURE);
1015       }
1016       break;
1017
1018     case 'a':
1019       if (access (optarg, R_OK) != 0) {
1020         perror (optarg);
1021         exit (EXIT_FAILURE);
1022       }
1023       drv = malloc (sizeof (struct drv));
1024       if (!drv) {
1025         perror ("malloc");
1026         exit (EXIT_FAILURE);
1027       }
1028       drv->filename = optarg;
1029       drv->next = drvs;
1030       drvs = drv;
1031       break;
1032
1033     case 'm':
1034       mp = malloc (sizeof (struct mp));
1035       if (!mp) {
1036         perror ("malloc");
1037         exit (EXIT_FAILURE);
1038       }
1039       p = strchr (optarg, ':');
1040       if (p) {
1041         *p = '\0';
1042         mp->mountpoint = p+1;
1043       } else
1044         mp->mountpoint = bad_cast ("/");
1045       mp->device = optarg;
1046       mp->next = mps;
1047       mps = mp;
1048       break;
1049
1050     case 'n':
1051       guestfs_set_autosync (g, 0);
1052       break;
1053
1054     case 'o':
1055       ADD_FUSE_ARG ("-o");
1056       ADD_FUSE_ARG (optarg);
1057       break;
1058
1059     case 'r':
1060       read_only = 1;
1061       break;
1062
1063     case 'v':
1064       verbose++;
1065       guestfs_set_verbose (g, verbose);
1066       break;
1067
1068     case 'V': {
1069       struct guestfs_version *v = guestfs_version (g);
1070       printf ("%s %"PRIi64".%"PRIi64".%"PRIi64"%s\n", program_name,
1071               v->major, v->minor, v->release, v->extra);
1072       exit (EXIT_SUCCESS);
1073     }
1074
1075     case HELP_OPTION:
1076       usage (EXIT_SUCCESS);
1077
1078     default:
1079       usage (EXIT_FAILURE);
1080     }
1081   }
1082
1083   /* We must have at least one -a and at least one -m. */
1084   if (!drvs || !mps) {
1085     fprintf (stderr,
1086              _("%s: must have at least one -a and at least one -m option\n"),
1087              program_name);
1088     exit (EXIT_FAILURE);
1089   }
1090
1091   /* We'd better have a mountpoint. */
1092   if (optind+1 != argc) {
1093     fprintf (stderr,
1094              _("%s: you must specify a mountpoint in the host filesystem\n"),
1095              program_name);
1096     exit (EXIT_FAILURE);
1097   }
1098
1099   /* Do the guest drives and mountpoints. */
1100   add_drives (drvs);
1101   if (guestfs_launch (g) == -1)
1102     exit (EXIT_FAILURE);
1103   mount_mps (mps);
1104
1105   /* FUSE example does this, not clear if it's necessary, but ... */
1106   if (guestfs_umask (g, 0) == -1)
1107     exit (EXIT_FAILURE);
1108
1109   /* At the last minute, remove the libguestfs error handler.  In code
1110    * above this point, the default error handler has been used which
1111    * sends all errors to stderr.  Now before entering FUSE itself we
1112    * want to silence errors so we can convert them (see error()
1113    * function above).
1114    */
1115   guestfs_set_error_handler (g, NULL, NULL);
1116
1117   /* Finish off FUSE args. */
1118   ADD_FUSE_ARG (argv[optind]);
1119
1120   /*
1121     It says about the line containing the for-statement:
1122     error: assuming signed overflow does not occur when simplifying conditional to constant [-Wstrict-overflow]
1123
1124   if (verbose) {
1125     fprintf (stderr, "guestmount: invoking FUSE with args [");
1126     for (i = 0; i < fuse_argc; ++i) {
1127       if (i > 0) fprintf (stderr, ", ");
1128       fprintf (stderr, "%s", fuse_argv[i]);
1129     }
1130     fprintf (stderr, "]\n");
1131   }
1132   */
1133
1134   r = fuse_main (fuse_argc, (char **) fuse_argv, &fg_operations, NULL);
1135
1136   /* Cleanup. */
1137   guestfs_close (g);
1138   free_dir_caches ();
1139
1140   exit (r == -1 ? 1 : 0);
1141 }
1142
1143 /* List is built in reverse order, so add them in reverse order. */
1144 static void
1145 add_drives (struct drv *drv)
1146 {
1147   int r;
1148
1149   if (drv) {
1150     add_drives (drv->next);
1151     if (!read_only)
1152       r = guestfs_add_drive (g, drv->filename);
1153     else
1154       r = guestfs_add_drive_ro (g, drv->filename);
1155     if (r == -1)
1156       exit (EXIT_FAILURE);
1157   }
1158 }
1159
1160 /* List is built in reverse order, so mount them in reverse order. */
1161 static void
1162 mount_mps (struct mp *mp)
1163 {
1164   int r;
1165
1166   if (mp) {
1167     mount_mps (mp->next);
1168
1169     /* Don't use guestfs_mount here because that will default to mount
1170      * options -o sync,noatime.  For more information, see guestfs(3)
1171      * section "LIBGUESTFS GOTCHAS".
1172      */
1173     const char *options = read_only ? "ro" : "";
1174     r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
1175     if (r == -1)
1176       exit (EXIT_FAILURE);
1177   }
1178 }