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