ls: Rewrite virt-ls in C.
[libguestfs.git] / cat / virt-ls.c
1 /* virt-ls
2  * Copyright (C) 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
19 #include <config.h>
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <inttypes.h>
24 #include <unistd.h>
25 #include <getopt.h>
26 #include <fcntl.h>
27 #include <assert.h>
28
29 #include "progname.h"
30
31 #include "guestfs.h"
32 #include "options.h"
33
34 /* Currently open libguestfs handle. */
35 guestfs_h *g;
36
37 int read_only = 1;
38 int verbose = 0;
39 int keys_from_stdin = 0;
40 int echo_keys = 0;
41 const char *libvirt_uri = NULL;
42 int inspector = 1;
43
44 static inline char *
45 bad_cast (char const *s)
46 {
47   return (char *) s;
48 }
49
50 static void __attribute__((noreturn))
51 usage (int status)
52 {
53   if (status != EXIT_SUCCESS)
54     fprintf (stderr, _("Try `%s --help' for more information.\n"),
55              program_name);
56   else {
57     fprintf (stdout,
58            _("%s: list files in a virtual machine\n"
59              "Copyright (C) 2010 Red Hat Inc.\n"
60              "Usage:\n"
61              "  %s [--options] -d domname file [dir ...]\n"
62              "  %s [--options] -a disk.img [-a disk.img ...] dir [dir ...]\n"
63              "Options:\n"
64              "  -a|--add image       Add image\n"
65              "  -c|--connect uri     Specify libvirt URI for -d option\n"
66              "  -d|--domain guest    Add disks from libvirt guest\n"
67              "  --echo-keys          Don't turn off echo for passphrases\n"
68              "  --format[=raw|..]    Force disk format for -a option\n"
69              "  --help               Display brief help\n"
70              "  --keys-from-stdin    Read passphrases from stdin\n"
71              "  -l|--long            Long listing\n"
72              "  -R|--recursive       Recursive listing\n"
73              "  -v|--verbose         Verbose messages\n"
74              "  -V|--version         Display version and exit\n"
75              "  -x                   Trace libguestfs API calls\n"
76              "For more information, see the manpage %s(1).\n"),
77              program_name, program_name, program_name,
78              program_name);
79   }
80   exit (status);
81 }
82
83 int
84 main (int argc, char *argv[])
85 {
86   /* Set global program name that is not polluted with libtool artifacts.  */
87   set_program_name (argv[0]);
88
89   setlocale (LC_ALL, "");
90   bindtextdomain (PACKAGE, LOCALEBASEDIR);
91   textdomain (PACKAGE);
92
93   enum { HELP_OPTION = CHAR_MAX + 1 };
94
95   static const char *options = "a:c:d:lRvVx";
96   static const struct option long_options[] = {
97     { "add", 1, 0, 'a' },
98     { "connect", 1, 0, 'c' },
99     { "domain", 1, 0, 'd' },
100     { "echo-keys", 0, 0, 0 },
101     { "format", 2, 0, 0 },
102     { "help", 0, 0, HELP_OPTION },
103     { "keys-from-stdin", 0, 0, 0 },
104     { "long", 0, 0, 'l' },
105     { "recursive", 0, 0, 'R' },
106     { "verbose", 0, 0, 'v' },
107     { "version", 0, 0, 'V' },
108     { 0, 0, 0, 0 }
109   };
110   struct drv *drvs = NULL;
111   struct drv *drv;
112   char *p, *file = NULL;
113   const char *format = NULL;
114   int c;
115   int option_index;
116   int next_prepared_drive = 1;
117   char mode = 0;
118
119   g = guestfs_create ();
120   if (g == NULL) {
121     fprintf (stderr, _("guestfs_create: failed to create handle\n"));
122     exit (EXIT_FAILURE);
123   }
124
125   argv[0] = bad_cast (program_name);
126
127   for (;;) {
128     c = getopt_long (argc, argv, options, long_options, &option_index);
129     if (c == -1) break;
130
131     switch (c) {
132     case 0:                     /* options which are long only */
133       if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
134         keys_from_stdin = 1;
135       } else if (STREQ (long_options[option_index].name, "echo-keys")) {
136         echo_keys = 1;
137       } else if (STREQ (long_options[option_index].name, "format")) {
138         if (!optarg || STREQ (optarg, ""))
139           format = NULL;
140         else
141           format = optarg;
142       } else {
143         fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
144                  program_name, long_options[option_index].name, option_index);
145         exit (EXIT_FAILURE);
146       }
147       break;
148
149     case 'a':
150       OPTION_a;
151       break;
152
153     case 'c':
154       OPTION_c;
155       break;
156
157     case 'd':
158       OPTION_d;
159       break;
160
161     case 'h':
162       usage (EXIT_SUCCESS);
163
164     case 'l':
165       mode = 'l';
166       break;
167
168     case 'R':
169       mode = 'R';
170       break;
171
172     case 'v':
173       OPTION_v;
174       break;
175
176     case 'V':
177       OPTION_V;
178       break;
179
180     case 'x':
181       OPTION_x;
182       break;
183
184     case HELP_OPTION:
185       usage (EXIT_SUCCESS);
186
187     default:
188       usage (EXIT_FAILURE);
189     }
190   }
191
192   /* Old-style syntax?  There were no -a or -d options in the old
193    * virt-ls which is how we detect this.
194    */
195   if (drvs == NULL) {
196     /* argc - 1 because last parameter is the single directory name. */
197     while (optind < argc - 1) {
198       if (strchr (argv[optind], '/') ||
199           access (argv[optind], F_OK) == 0) { /* simulate -a option */
200         drv = malloc (sizeof (struct drv));
201         if (!drv) {
202           perror ("malloc");
203           exit (EXIT_FAILURE);
204         }
205         drv->type = drv_a;
206         drv->a.filename = argv[optind];
207         drv->a.format = NULL;
208         drv->next = drvs;
209         drvs = drv;
210       } else {                  /* simulate -d option */
211         drv = malloc (sizeof (struct drv));
212         if (!drv) {
213           perror ("malloc");
214           exit (EXIT_FAILURE);
215         }
216         drv->type = drv_d;
217         drv->d.guest = argv[optind];
218         drv->next = drvs;
219         drvs = drv;
220       }
221
222       optind++;
223     }
224   }
225
226   /* These are really constants, but they have to be variables for the
227    * options parsing code.  Assert here that they have known-good
228    * values.
229    */
230   assert (read_only == 1);
231   assert (inspector == 1);
232
233   /* User must specify at least one directory name on the command line. */
234   if (optind >= argc || argc - optind < 1)
235     usage (EXIT_FAILURE);
236
237   /* User must have specified some drives. */
238   if (drvs == NULL)
239     usage (EXIT_FAILURE);
240
241   /* Add drives, inspect and mount.  Note that inspector is always true,
242    * and there is no -m option.
243    */
244   add_drives (drvs, 'a');
245
246   if (guestfs_launch (g) == -1)
247     exit (EXIT_FAILURE);
248
249   inspect_mount ();
250
251   /* Free up data structures, no longer needed after this point. */
252   free_drives (drvs);
253
254   unsigned errors = 0;
255
256   while (optind < argc) {
257     const char *dir = argv[optind];
258
259     if (mode == 0) {
260       char **lines;
261       size_t i;
262
263       if ((lines = guestfs_ls (g, dir)) == NULL)
264         errors++;
265       else {
266         for (i = 0; lines[i] != NULL; ++i) {
267           printf ("%s\n", lines[i]);
268           free (lines[i]);
269         }
270         free (lines);
271       }
272     }
273     else if (mode == 'l') {
274       char *out;
275       size_t i;
276
277       if ((out = guestfs_ll (g, dir)) == NULL)
278         errors++;
279       else {
280         printf ("%s", out);
281         free (out);
282       }
283     }
284     else if (mode == 'R') {
285       /* This is TMP_TEMPLATE_ON_STACK expanded from fish.h. */
286       const char *tmpdir = guestfs_tmpdir ();
287       char tmpfile[strlen (tmpdir) + 32];
288       sprintf (tmpfile, "%s/virtlsXXXXXX", tmpdir);
289
290       int fd = mkstemp (tmpfile);
291       if (fd == -1) {
292         perror ("mkstemp");
293         exit (EXIT_FAILURE);
294       }
295
296       char buf[BUFSIZ]; /* also used below */
297       snprintf (buf, sizeof buf, "/dev/fd/%d", fd);
298
299       if (guestfs_find0 (g, dir, buf) == -1)
300         errors++;
301       else {
302         if (close (fd) == -1) {
303           perror (tmpfile);
304           exit (EXIT_FAILURE);
305         }
306
307         /* The output of find0 is a \0-separated file.  Turn each \0 into
308          * a \n character.
309          */
310         fd = open (tmpfile, O_RDONLY);
311         if (fd == -1) {
312           perror (tmpfile);
313           exit (EXIT_FAILURE);
314         }
315
316         ssize_t r;
317         while ((r = read (fd, buf, sizeof buf)) > 0) {
318           size_t i;
319           for (i = 0; i < (size_t) r; ++i)
320             if (buf[i] == '\0')
321               buf[i] = '\n';
322
323           size_t n = r;
324           while (n > 0) {
325             r = write (1, buf, n);
326             if (r == -1) {
327               perror ("write");
328               exit (EXIT_FAILURE);
329             }
330             n -= r;
331           }
332         }
333
334         if (r == -1 || close (fd) == -1) {
335           perror (tmpfile);
336           exit (EXIT_FAILURE);
337         }
338       }
339
340       unlink (tmpfile);
341     }
342     optind++;
343   }
344
345   guestfs_close (g);
346
347   exit (errors == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
348 }