6e160a228d46adc7a6753b1f8d312a003cdc893c
[libguestfs.git] / cat / virt-filesystems.c
1 /* virt-filesystems
2  * Copyright (C) 2010-2011 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 <stdint.h>
24 #include <inttypes.h>
25 #include <unistd.h>
26 #include <getopt.h>
27 #include <locale.h>
28 #include <assert.h>
29 #include <string.h>
30 #include <libintl.h>
31
32 #include "c-ctype.h"
33 #include "human.h"
34 #include "progname.h"
35
36 #include "guestfs.h"
37 #include "options.h"
38
39 #define DISABLE_GUESTFS_ERRORS_FOR(stmt) do {                           \
40     guestfs_error_handler_cb old_error_cb;                              \
41     void *old_error_data;                                               \
42     old_error_cb = guestfs_get_error_handler (g, &old_error_data);      \
43     guestfs_set_error_handler (g, NULL, NULL);                          \
44     stmt;                                                               \
45     guestfs_set_error_handler (g, old_error_cb, old_error_data);        \
46   } while (0)
47
48 /* These globals are shared with options.c. */
49 guestfs_h *g;
50
51 int read_only = 1;
52 int live = 0;
53 int verbose = 0;
54 int keys_from_stdin = 0;
55 int echo_keys = 0;
56 const char *libvirt_uri = NULL;
57 int inspector = 0;
58
59 static int csv = 0;             /* --csv */
60 static int human = 0;           /* --human-readable|-h */
61
62 /* What is selected for output. */
63 #define OUTPUT_FILESYSTEMS        1
64 #define OUTPUT_FILESYSTEMS_EXTRA  2
65 #define OUTPUT_PARTITIONS         4
66 #define OUTPUT_BLOCKDEVS          8
67 #define OUTPUT_LVS               16
68 #define OUTPUT_VGS               32
69 #define OUTPUT_PVS               64
70 #define OUTPUT_ALL          INT_MAX
71 static int output = 0;
72
73 /* What columns to output.  This is in display order. */
74 #define COLUMN_NAME               1 /* always shown */
75 #define COLUMN_TYPE               2
76 #define COLUMN_VFS_TYPE           4 /* if --filesystems */
77 #define COLUMN_VFS_LABEL          8 /* if --filesystems */
78 #define COLUMN_MBR               16
79 #define COLUMN_SIZE              32 /* bytes, or human-readable if -h */
80 #define COLUMN_PARENT_NAME       64 /* only for partitions, LVs */
81 #define COLUMN_UUID             128 /* if --uuid */
82 #define NR_COLUMNS                8
83 static int columns;
84
85 static char *canonical_device (const char *dev);
86 static void do_output_title (void);
87 static void do_output (void);
88 static void do_output_end (void);
89
90 static inline char *
91 bad_cast (char const *s)
92 {
93   return (char *) s;
94 }
95
96 static void __attribute__((noreturn))
97 usage (int status)
98 {
99   if (status != EXIT_SUCCESS)
100     fprintf (stderr, _("Try `%s --help' for more information.\n"),
101              program_name);
102   else {
103     fprintf (stdout,
104            _("%s: list filesystems, partitions, block devices, LVM in a VM\n"
105              "Copyright (C) 2010 Red Hat Inc.\n"
106              "Usage:\n"
107              "  %s [--options] -d domname\n"
108              "  %s [--options] -a disk.img [-a disk.img ...]\n"
109              "Options:\n"
110              "  -a|--add image       Add image\n"
111              "  --all                Display everything\n"
112              "  --blkdevs|--block-devices\n"
113              "                       Display block devices\n"
114              "  -c|--connect uri     Specify libvirt URI for -d option\n"
115              "  --csv                Output as Comma-Separated Values\n"
116              "  -d|--domain guest    Add disks from libvirt guest\n"
117              "  --echo-keys          Don't turn off echo for passphrases\n"
118              "  --extra              Display swap and data filesystems\n"
119              "  --filesystems        Display mountable filesystems\n"
120              "  --format[=raw|..]    Force disk format for -a option\n"
121              "  -h|--human-readable  Human-readable sizes in --long output\n"
122              "  --help               Display brief help\n"
123              "  --keys-from-stdin    Read passphrases from stdin\n"
124              "  -l|--long            Long output\n"
125              "  --lvs|--logvols|--logical-volumes\n"
126              "                       Display LVM logical volumes\n"
127              "  --no-title           No title in --long output\n"
128              "  --parts|--partitions Display partitions\n"
129              "  --pvs|--physvols|--physical-volumes\n"
130              "                       Display LVM physical volumes\n"
131              "  --uuid|--uuids       Add UUIDs to --long output\n"
132              "  -v|--verbose         Verbose messages\n"
133              "  -V|--version         Display version and exit\n"
134              "  --vgs|--volgroups|--volume-groups\n"
135              "                       Display LVM volume groups\n"
136              "  -x                   Trace libguestfs API calls\n"
137              "For more information, see the manpage %s(1).\n"),
138              program_name, program_name, program_name,
139              program_name);
140   }
141   exit (status);
142 }
143
144 int
145 main (int argc, char *argv[])
146 {
147   /* Set global program name that is not polluted with libtool artifacts.  */
148   set_program_name (argv[0]);
149
150   setlocale (LC_ALL, "");
151   bindtextdomain (PACKAGE, LOCALEBASEDIR);
152   textdomain (PACKAGE);
153
154   enum { HELP_OPTION = CHAR_MAX + 1 };
155
156   static const char *options = "a:c:d:hlvVx";
157   static const struct option long_options[] = {
158     { "add", 1, 0, 'a' },
159     { "all", 0, 0, 0 },
160     { "blkdevs", 0, 0, 0 },
161     { "block-devices", 0, 0, 0 },
162     { "connect", 1, 0, 'c' },
163     { "csv", 0, 0, 0 },
164     { "domain", 1, 0, 'd' },
165     { "echo-keys", 0, 0, 0 },
166     { "extra", 0, 0, 0 },
167     { "filesystems", 0, 0, 0 },
168     { "format", 2, 0, 0 },
169     { "help", 0, 0, HELP_OPTION },
170     { "human-readable", 0, 0, 'h' },
171     { "keys-from-stdin", 0, 0, 0 },
172     { "long", 0, 0, 'l' },
173     { "logical-volumes", 0, 0, 0 },
174     { "logvols", 0, 0, 0 },
175     { "lvs", 0, 0, 0 },
176     { "no-title", 0, 0, 0 },
177     { "parts", 0, 0, 0 },
178     { "partitions", 0, 0, 0 },
179     { "physical-volumes", 0, 0, 0 },
180     { "physvols", 0, 0, 0 },
181     { "pvs", 0, 0, 0 },
182     { "uuid", 0, 0, 0 },
183     { "uuids", 0, 0, 0 },
184     { "verbose", 0, 0, 'v' },
185     { "version", 0, 0, 'V' },
186     { "vgs", 0, 0, 0 },
187     { "volgroups", 0, 0, 0 },
188     { "volume-groups", 0, 0, 0 },
189     { 0, 0, 0, 0 }
190   };
191   struct drv *drvs = NULL;
192   struct drv *drv;
193   const char *format = NULL;
194   int c;
195   int option_index;
196   int no_title = 0;             /* --no-title */
197   int long_mode = 0;            /* --long|-l */
198   int uuid = 0;                 /* --uuid */
199   int title;
200
201   g = guestfs_create ();
202   if (g == NULL) {
203     fprintf (stderr, _("guestfs_create: failed to create handle\n"));
204     exit (EXIT_FAILURE);
205   }
206
207   argv[0] = bad_cast (program_name);
208
209   for (;;) {
210     c = getopt_long (argc, argv, options, long_options, &option_index);
211     if (c == -1) break;
212
213     switch (c) {
214     case 0:                     /* options which are long only */
215       if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
216         keys_from_stdin = 1;
217       } else if (STREQ (long_options[option_index].name, "echo-keys")) {
218         echo_keys = 1;
219       } else if (STREQ (long_options[option_index].name, "format")) {
220         if (!optarg || STREQ (optarg, ""))
221           format = NULL;
222         else
223           format = optarg;
224       } else if (STREQ (long_options[option_index].name, "all")) {
225         output = OUTPUT_ALL;
226       } else if (STREQ (long_options[option_index].name, "blkdevs") ||
227                  STREQ (long_options[option_index].name, "block-devices")) {
228         output |= OUTPUT_BLOCKDEVS;
229       } else if (STREQ (long_options[option_index].name, "csv")) {
230         csv = 1;
231       } else if (STREQ (long_options[option_index].name, "extra")) {
232         output |= OUTPUT_FILESYSTEMS;
233         output |= OUTPUT_FILESYSTEMS_EXTRA;
234       } else if (STREQ (long_options[option_index].name, "filesystems")) {
235         output |= OUTPUT_FILESYSTEMS;
236       } else if (STREQ (long_options[option_index].name, "logical-volumes") ||
237                  STREQ (long_options[option_index].name, "logvols") ||
238                  STREQ (long_options[option_index].name, "lvs")) {
239         output |= OUTPUT_LVS;
240       } else if (STREQ (long_options[option_index].name, "no-title")) {
241         no_title = 1;
242       } else if (STREQ (long_options[option_index].name, "parts") ||
243                  STREQ (long_options[option_index].name, "partitions")) {
244         output |= OUTPUT_PARTITIONS;
245       } else if (STREQ (long_options[option_index].name, "physical-volumes") ||
246                  STREQ (long_options[option_index].name, "physvols") ||
247                  STREQ (long_options[option_index].name, "pvs")) {
248         output |= OUTPUT_PVS;
249       } else if (STREQ (long_options[option_index].name, "uuid") ||
250                  STREQ (long_options[option_index].name, "uuids")) {
251         uuid = 1;
252       } else if (STREQ (long_options[option_index].name, "vgs") ||
253                  STREQ (long_options[option_index].name, "volgroups") ||
254                  STREQ (long_options[option_index].name, "volume-groups")) {
255         output |= OUTPUT_VGS;
256       } else {
257         fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
258                  program_name, long_options[option_index].name, option_index);
259         exit (EXIT_FAILURE);
260       }
261       break;
262
263     case 'a':
264       OPTION_a;
265       break;
266
267     case 'c':
268       OPTION_c;
269       break;
270
271     case 'd':
272       OPTION_d;
273       break;
274
275     case 'h':
276       human = 1;
277       break;
278
279     case 'l':
280       long_mode = 1;
281       break;
282
283     case 'v':
284       OPTION_v;
285       break;
286
287     case 'V':
288       OPTION_V;
289       break;
290
291     case 'x':
292       OPTION_x;
293       break;
294
295     case HELP_OPTION:
296       usage (EXIT_SUCCESS);
297
298     default:
299       usage (EXIT_FAILURE);
300     }
301   }
302
303   /* These are really constants, but they have to be variables for the
304    * options parsing code.  Assert here that they have known-good
305    * values.
306    */
307   assert (read_only == 1);
308   assert (inspector == 0);
309   assert (live == 0);
310
311   /* Must be no extra arguments on the command line. */
312   if (optind != argc)
313     usage (EXIT_FAILURE);
314
315   /* -h and --csv doesn't make sense.  Spreadsheets will corrupt these
316    * fields.  (RHBZ#600977).
317    */
318   if (human && csv) {
319     fprintf (stderr, _("%s: you cannot use -h and --csv options together.\n"),
320              program_name);
321     exit (EXIT_FAILURE);
322   }
323
324   /* Nothing selected for output, means --filesystems is implied. */
325   if (output == 0)
326     output = OUTPUT_FILESYSTEMS;
327
328   /* What columns will be displayed? */
329   columns = COLUMN_NAME;
330   if (long_mode) {
331     columns |= COLUMN_TYPE;
332     columns |= COLUMN_SIZE;
333     if ((output & OUTPUT_FILESYSTEMS)) {
334       columns |= COLUMN_VFS_TYPE;
335       columns |= COLUMN_VFS_LABEL;
336     }
337     if ((output & (OUTPUT_PARTITIONS|OUTPUT_LVS)))
338       columns |= COLUMN_PARENT_NAME;
339     if ((output & OUTPUT_PARTITIONS))
340       columns |= COLUMN_MBR;
341     if (uuid)
342       columns |= COLUMN_UUID;
343   }
344
345   /* Display title by default only in long mode. */
346   title = long_mode;
347   if (no_title)
348     title = 0;
349
350   /* User must have specified some drives. */
351   if (drvs == NULL)
352     usage (EXIT_FAILURE);
353
354   /* Add drives. */
355   add_drives (drvs, 'a');
356
357   if (guestfs_launch (g) == -1)
358     exit (EXIT_FAILURE);
359
360   /* Free up data structures, no longer needed after this point. */
361   free_drives (drvs);
362
363   if (title)
364     do_output_title ();
365   do_output ();
366   do_output_end ();
367
368   guestfs_close (g);
369
370   exit (EXIT_SUCCESS);
371 }
372
373 static void do_output_filesystems (void);
374 static void do_output_lvs (void);
375 static void do_output_vgs (void);
376 static void do_output_pvs (void);
377 static void do_output_partitions (void);
378 static void do_output_blockdevs (void);
379 static void write_row (const char *name, const char *type, const char *vfs_type, const char *vfs_label, int mbr_id, int64_t size, const char *parent_name, const char *uuid);
380 static void write_row_strings (char **strings, size_t len);
381
382 static void
383 do_output_title (void)
384 {
385   const char *headings[NR_COLUMNS];
386   size_t len = 0;
387
388   /* NB. These strings are not localized and must not contain spaces. */
389   if ((columns & COLUMN_NAME))
390     headings[len++] = "Name";
391   if ((columns & COLUMN_TYPE))
392     headings[len++] = "Type";
393   if ((columns & COLUMN_VFS_TYPE))
394     headings[len++] = "VFS";
395   if ((columns & COLUMN_VFS_LABEL))
396     headings[len++] = "Label";
397   if ((columns & COLUMN_MBR))
398     headings[len++] = "MBR";
399   if ((columns & COLUMN_SIZE))
400     headings[len++] = "Size";
401   if ((columns & COLUMN_PARENT_NAME))
402     headings[len++] = "Parent";
403   if ((columns & COLUMN_UUID))
404     headings[len++] = "UUID";
405   assert (len <= NR_COLUMNS);
406
407   write_row_strings ((char **) headings, len);
408 }
409
410 static void
411 do_output (void)
412 {
413   /* The ordering here is trying to be most specific -> least specific,
414    * although that is not required or guaranteed.
415    */
416   if ((output & OUTPUT_FILESYSTEMS))
417     do_output_filesystems ();
418
419   if ((output & OUTPUT_LVS))
420     do_output_lvs ();
421
422   if ((output & OUTPUT_VGS))
423     do_output_vgs ();
424
425   if ((output & OUTPUT_PVS))
426     do_output_pvs ();
427
428   if ((output & OUTPUT_PARTITIONS))
429     do_output_partitions ();
430
431   if ((output & OUTPUT_BLOCKDEVS))
432     do_output_blockdevs ();
433 }
434
435 static void
436 do_output_filesystems (void)
437 {
438   char **fses;
439   size_t i;
440
441   fses = guestfs_list_filesystems (g);
442   if (fses == NULL)
443     exit (EXIT_FAILURE);
444
445   for (i = 0; fses[i] != NULL; i += 2) {
446     char *dev, *vfs_label = NULL, *vfs_uuid = NULL;
447     int64_t size = -1;
448
449     /* Skip swap and unknown, unless --extra flag was given. */
450     if (!(output & OUTPUT_FILESYSTEMS_EXTRA) &&
451         (STREQ (fses[i+1], "swap") || STREQ (fses[i+1], "unknown")))
452       continue;
453
454     dev = canonical_device (fses[i]);
455
456     /* Only bother to look these up if we will be displaying them,
457      * otherwise pass them as NULL.
458      */
459     if ((columns & COLUMN_VFS_LABEL)) {
460       DISABLE_GUESTFS_ERRORS_FOR (
461         vfs_label = guestfs_vfs_label (g, fses[i]);
462       );
463       if (vfs_label == NULL) {
464         vfs_label = strdup ("");
465         if (!vfs_label) {
466           perror ("strdup");
467           exit (EXIT_FAILURE);
468         }
469       }
470     }
471     if ((columns & COLUMN_UUID)) {
472       DISABLE_GUESTFS_ERRORS_FOR (
473         vfs_uuid = guestfs_vfs_uuid (g, fses[i]);
474       );
475       if (vfs_uuid == NULL) {
476         vfs_uuid = strdup ("");
477         if (!vfs_uuid) {
478           perror ("strdup");
479           exit (EXIT_FAILURE);
480         }
481       }
482     }
483     if ((columns & COLUMN_SIZE)) {
484       size = guestfs_blockdev_getsize64 (g, fses[i]);
485       if (size == -1)
486         exit (EXIT_FAILURE);
487     }
488
489     write_row (dev, "filesystem",
490                fses[i+1], vfs_label, -1, size, NULL, vfs_uuid);
491
492     free (dev);
493     free (vfs_label);
494     free (vfs_uuid);
495     free (fses[i]);
496     free (fses[i+1]);
497   }
498
499   free (fses);
500 }
501
502 static void
503 do_output_lvs (void)
504 {
505   char **lvs;
506   size_t i;
507
508   lvs = guestfs_lvs (g);
509   if (lvs == NULL)
510     exit (EXIT_FAILURE);
511
512   for (i = 0; lvs[i] != NULL; ++i) {
513     char *uuid = NULL, *parent_name = NULL;
514     int64_t size = -1;
515
516     if ((columns & COLUMN_SIZE)) {
517       size = guestfs_blockdev_getsize64 (g, lvs[i]);
518       if (size == -1)
519         exit (EXIT_FAILURE);
520     }
521     if ((columns & COLUMN_UUID)) {
522       uuid = guestfs_lvuuid (g, lvs[i]);
523       if (uuid == NULL)
524         exit (EXIT_FAILURE);
525     }
526     if ((columns & COLUMN_PARENT_NAME)) {
527       parent_name = strdup (lvs[i]);
528       if (parent_name == NULL) {
529         perror ("strdup");
530         exit (EXIT_FAILURE);
531       }
532       char *p = strrchr (parent_name, '/');
533       if (p)
534         *p = '\0';
535     }
536
537     write_row (lvs[i], "lv",
538                NULL, NULL, -1, size, parent_name, uuid);
539
540     free (uuid);
541     free (parent_name);
542     free (lvs[i]);
543   }
544
545   free (lvs);
546 }
547
548 static void
549 do_output_vgs (void)
550 {
551   struct guestfs_lvm_vg_list *vgs;
552   size_t i;
553
554   vgs = guestfs_vgs_full (g);
555   if (vgs == NULL)
556     exit (EXIT_FAILURE);
557
558   for (i = 0; i < vgs->len; ++i) {
559     char name[PATH_MAX];
560     char uuid[33];
561
562     strcpy (name, "/dev/");
563     strcpy (&name[5], vgs->val[i].vg_name);
564     memcpy (uuid, vgs->val[i].vg_uuid, 32);
565     uuid[32] = '\0';
566     write_row (name, "vg",
567                NULL, NULL, -1, (int64_t) vgs->val[i].vg_size, NULL, uuid);
568
569   }
570
571   guestfs_free_lvm_vg_list (vgs);
572 }
573
574 static void
575 do_output_pvs (void)
576 {
577   struct guestfs_lvm_pv_list *pvs;
578   size_t i;
579
580   pvs = guestfs_pvs_full (g);
581   if (pvs == NULL)
582     exit (EXIT_FAILURE);
583
584   for (i = 0; i < pvs->len; ++i) {
585     char *dev;
586     char uuid[33];
587
588     dev = canonical_device (pvs->val[i].pv_name);
589
590     memcpy (uuid, pvs->val[i].pv_uuid, 32);
591     uuid[32] = '\0';
592     write_row (dev, "pv",
593                NULL, NULL, -1, (int64_t) pvs->val[i].pv_size, NULL, uuid);
594
595     free (dev);
596   }
597
598   guestfs_free_lvm_pv_list (pvs);
599 }
600
601 static int
602 get_mbr_id (const char *dev, const char *parent_name)
603 {
604   char *parttype = NULL;
605   int mbr_id = -1, partnum;
606
607   DISABLE_GUESTFS_ERRORS_FOR (
608     parttype = guestfs_part_get_parttype (g, parent_name);
609   );
610
611   if (parttype && STREQ (parttype, "msdos")) {
612     DISABLE_GUESTFS_ERRORS_FOR (
613       partnum = guestfs_part_to_partnum (g, dev);
614     );
615     if (partnum >= 0) {
616       DISABLE_GUESTFS_ERRORS_FOR (
617         mbr_id = guestfs_part_get_mbr_id (g, parent_name, partnum);
618       );
619     }
620   }
621
622   free (parttype);
623
624   return mbr_id;
625 }
626
627 static void
628 do_output_partitions (void)
629 {
630   char **parts;
631   size_t i;
632
633   parts = guestfs_list_partitions (g);
634   if (parts == NULL)
635     exit (EXIT_FAILURE);
636
637   for (i = 0; parts[i] != NULL; ++i) {
638     char *dev, *parent_name = NULL;
639     int64_t size = -1;
640     int mbr_id = -1;
641
642     dev = canonical_device (parts[i]);
643
644     if ((columns & COLUMN_SIZE)) {
645       size = guestfs_blockdev_getsize64 (g, parts[i]);
646       if (size == -1)
647         exit (EXIT_FAILURE);
648     }
649     if ((columns & COLUMN_PARENT_NAME)) {
650       parent_name = guestfs_part_to_dev (g, parts[i]);
651       if (parent_name == NULL)
652         exit (EXIT_FAILURE);
653
654       if ((columns & COLUMN_MBR))
655         mbr_id = get_mbr_id (parts[i], parent_name);
656
657       char *p = canonical_device (parent_name);
658       free (parent_name);
659       parent_name = p;
660     }
661
662     write_row (dev, "partition",
663                NULL, NULL, mbr_id, size, parent_name, NULL);
664
665     free (dev);
666     free (parent_name);
667     free (parts[i]);
668   }
669
670   free (parts);
671 }
672
673 static void
674 do_output_blockdevs (void)
675 {
676   char **devices;
677   size_t i;
678
679   devices = guestfs_list_devices (g);
680   if (devices == NULL)
681     exit (EXIT_FAILURE);
682
683   for (i = 0; devices[i] != NULL; ++i) {
684     int64_t size = -1;
685     char *dev;
686
687     dev = canonical_device (devices[i]);
688
689     if ((columns & COLUMN_SIZE)) {
690       size = guestfs_blockdev_getsize64 (g, devices[i]);
691       if (size == -1)
692         exit (EXIT_FAILURE);
693     }
694
695     write_row (dev, "device",
696                NULL, NULL, -1, size, NULL, NULL);
697
698     free (dev);
699     free (devices[i]);
700   }
701
702   free (devices);
703 }
704
705 /* /dev/vda1 -> /dev/sda.  Returns a string which the caller must free. */
706 static char *
707 canonical_device (const char *dev)
708 {
709   char *ret = strdup (dev);
710   if (ret == NULL) {
711     perror ("strdup");
712     exit (EXIT_FAILURE);
713   }
714
715   if (STRPREFIX (ret, "/dev/") &&
716       (ret[5] == 'h' || ret[5] == 'v') &&
717       ret[6] == 'd' &&
718       c_isalpha (ret[7]) &&
719       (c_isdigit (ret[8]) || ret[8] == '\0'))
720     ret[5] = 's';
721
722   return ret;
723 }
724
725 static void
726 write_row (const char *name, const char *type,
727            const char *vfs_type, const char *vfs_label, int mbr_id,
728            int64_t size, const char *parent_name, const char *uuid)
729 {
730   const char *strings[NR_COLUMNS];
731   size_t len = 0;
732   char hum[LONGEST_HUMAN_READABLE];
733   char num[256];
734   char mbr_id_str[3];
735
736   if ((columns & COLUMN_NAME))
737     strings[len++] = name;
738   if ((columns & COLUMN_TYPE))
739     strings[len++] = type;
740   if ((columns & COLUMN_VFS_TYPE))
741     strings[len++] = vfs_type;
742   if ((columns & COLUMN_VFS_LABEL))
743     strings[len++] = vfs_label;
744   if ((columns & COLUMN_MBR)) {
745     if (mbr_id >= 0) {
746       snprintf (mbr_id_str, sizeof mbr_id_str, "%02x", mbr_id);
747       strings[len++] = mbr_id_str;
748     } else
749       strings[len++] = NULL;
750   }
751   if ((columns & COLUMN_SIZE)) {
752     if (size >= 0) {
753       if (human) {
754         strings[len++] =
755           human_readable ((uintmax_t) size, hum,
756                           human_round_to_nearest|human_autoscale|
757                           human_base_1024|human_SI,
758                           1, 1);
759       }
760       else {
761         snprintf (num, sizeof num, "%" PRIi64, size);
762         strings[len++] = num;
763       }
764     }
765     else
766       strings[len++] = NULL;
767   }
768   if ((columns & COLUMN_PARENT_NAME))
769     strings[len++] = parent_name;
770   if ((columns & COLUMN_UUID))
771     strings[len++] = uuid;
772   assert (len <= NR_COLUMNS);
773
774   write_row_strings ((char **) strings, len);
775 }
776
777 static void add_row (char **strings, size_t len);
778 static void write_csv_field (const char *field);
779
780 static void
781 write_row_strings (char **strings, size_t len)
782 {
783   if (!csv) {
784     /* Text mode.  Because we want the columns to line up, we can't
785      * output directly, but instead need to save up the rows and
786      * output them at the end.
787      */
788     add_row (strings, len);
789   }
790   else {                    /* CSV mode: output it directly, quoted */
791     size_t i;
792
793     for (i = 0; i < len; ++i) {
794       if (i > 0)
795         putchar (',');
796       if (strings[i] != NULL)
797         write_csv_field (strings[i]);
798     }
799     putchar ('\n');
800   }
801 }
802
803 /* Function to quote CSV fields on output without requiring an
804  * external module.
805  */
806 static void
807 write_csv_field (const char *field)
808 {
809   size_t i, len;
810   int needs_quoting = 0;
811
812   len = strlen (field);
813
814   for (i = 0; i < len; ++i) {
815     if (field[i] == ' ' || field[i] == '"' ||
816         field[i] == '\n' || field[i] == ',') {
817       needs_quoting = 1;
818       break;
819     }
820   }
821
822   if (!needs_quoting) {
823     printf ("%s", field);
824     return;
825   }
826
827   /* Quoting for CSV fields. */
828   putchar ('"');
829   for (i = 0; i < len; ++i) {
830     if (field[i] == '"') {
831       putchar ('"');
832       putchar ('"');
833     } else
834       putchar (field[i]);
835   }
836   putchar ('"');
837 }
838
839 /* This code is only used in text mode (non-CSV output). */
840 static char ***rows = NULL;
841 static size_t nr_rows = 0;
842 static size_t max_width[NR_COLUMNS];
843
844 static void
845 add_row (char **strings, size_t len)
846 {
847   size_t i, slen;
848   char **row;
849
850   assert (len <= NR_COLUMNS);
851
852   row = malloc (sizeof (char *) * len);
853   if (row == NULL) {
854     perror ("malloc");
855     exit (EXIT_FAILURE);
856   }
857
858   for (i = 0; i < len; ++i) {
859     if (strings[i]) {
860       row[i] = strdup (strings[i]);
861       if (row[i] == NULL) {
862         perror ("strdup");
863         exit (EXIT_FAILURE);
864       }
865
866       /* Keep a running total of the max width of each column. */
867       slen = strlen (strings[i]);
868       if (slen == 0)
869         slen = 1; /* because "" is printed as "-" */
870       if (slen > max_width[i])
871         max_width[i] = slen;
872     }
873     else
874       row[i] = NULL;
875   }
876
877   rows = realloc (rows, sizeof (char **) * (nr_rows + 1));
878   if (rows == NULL) {
879     perror ("realloc");
880     exit (EXIT_FAILURE);
881   }
882   rows[nr_rows] = row;
883   nr_rows++;
884 }
885
886 /* In text mode we saved up all the output so that we can print the
887  * columns aligned.
888  */
889 static void
890 do_output_end (void)
891 {
892   size_t i, j, k, len, space_btwn;
893
894   if (csv)
895     return;
896
897   /* How much space between columns?  Try 2 spaces between columns, but
898    * if that just pushes us over 72 columns, use 1 space.
899    */
900   space_btwn = 2;
901   i = 0;
902   for (j = 0; j < NR_COLUMNS; ++j)
903     i += max_width[j] + space_btwn;
904   if (i > 72)
905     space_btwn = 1;
906
907   for (i = 0; i < nr_rows; ++i) {
908     char **row = rows[i];
909
910     k = 0;
911
912     for (j = 0; j < NR_COLUMNS; ++j) {
913       /* Ignore columns which are completely empty.  This also deals
914        * with the fact that we didn't remember the length of each row
915        * in add_row above.
916        */
917       if (max_width[j] == 0)
918         continue;
919
920       while (k) {
921         putchar (' ');
922         k--;
923       }
924
925       if (row[j] == NULL || STREQ (row[j], "")) {
926         printf ("-");
927         len = 1;
928       } else {
929         printf ("%s", row[j]);
930         len = strlen (row[j]);
931       }
932       free (row[j]);
933
934       assert (len <= max_width[j]);
935       k = max_width[j] - len + space_btwn;
936     }
937
938     putchar ('\n');
939     free (row);
940   }
941   free (rows);
942 }