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