daemon: debug segv correct use of dereferencing NULL.
[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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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       goto next;
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
496   next:
497     free (fses[i]);
498     free (fses[i+1]);
499   }
500
501   free (fses);
502 }
503
504 static void
505 do_output_lvs (void)
506 {
507   char **lvs;
508   size_t i;
509
510   lvs = guestfs_lvs (g);
511   if (lvs == NULL)
512     exit (EXIT_FAILURE);
513
514   for (i = 0; lvs[i] != NULL; ++i) {
515     char *uuid = NULL, *parent_name = NULL;
516     int64_t size = -1;
517
518     if ((columns & COLUMN_SIZE)) {
519       size = guestfs_blockdev_getsize64 (g, lvs[i]);
520       if (size == -1)
521         exit (EXIT_FAILURE);
522     }
523     if ((columns & COLUMN_UUID)) {
524       uuid = guestfs_lvuuid (g, lvs[i]);
525       if (uuid == NULL)
526         exit (EXIT_FAILURE);
527     }
528     if ((columns & COLUMN_PARENT_NAME)) {
529       parent_name = strdup (lvs[i]);
530       if (parent_name == NULL) {
531         perror ("strdup");
532         exit (EXIT_FAILURE);
533       }
534       char *p = strrchr (parent_name, '/');
535       if (p)
536         *p = '\0';
537     }
538
539     write_row (lvs[i], "lv",
540                NULL, NULL, -1, size, parent_name, uuid);
541
542     free (uuid);
543     free (parent_name);
544     free (lvs[i]);
545   }
546
547   free (lvs);
548 }
549
550 static void
551 do_output_vgs (void)
552 {
553   struct guestfs_lvm_vg_list *vgs;
554   size_t i;
555
556   vgs = guestfs_vgs_full (g);
557   if (vgs == NULL)
558     exit (EXIT_FAILURE);
559
560   for (i = 0; i < vgs->len; ++i) {
561     char name[PATH_MAX];
562     char uuid[33];
563
564     strcpy (name, "/dev/");
565     strcpy (&name[5], vgs->val[i].vg_name);
566     memcpy (uuid, vgs->val[i].vg_uuid, 32);
567     uuid[32] = '\0';
568     write_row (name, "vg",
569                NULL, NULL, -1, (int64_t) vgs->val[i].vg_size, NULL, uuid);
570
571   }
572
573   guestfs_free_lvm_vg_list (vgs);
574 }
575
576 static void
577 do_output_pvs (void)
578 {
579   struct guestfs_lvm_pv_list *pvs;
580   size_t i;
581
582   pvs = guestfs_pvs_full (g);
583   if (pvs == NULL)
584     exit (EXIT_FAILURE);
585
586   for (i = 0; i < pvs->len; ++i) {
587     char *dev;
588     char uuid[33];
589
590     dev = canonical_device (pvs->val[i].pv_name);
591
592     memcpy (uuid, pvs->val[i].pv_uuid, 32);
593     uuid[32] = '\0';
594     write_row (dev, "pv",
595                NULL, NULL, -1, (int64_t) pvs->val[i].pv_size, NULL, uuid);
596
597     free (dev);
598   }
599
600   guestfs_free_lvm_pv_list (pvs);
601 }
602
603 static int
604 get_mbr_id (const char *dev, const char *parent_name)
605 {
606   char *parttype = NULL;
607   int mbr_id = -1, partnum;
608
609   DISABLE_GUESTFS_ERRORS_FOR (
610     parttype = guestfs_part_get_parttype (g, parent_name);
611   );
612
613   if (parttype && STREQ (parttype, "msdos")) {
614     DISABLE_GUESTFS_ERRORS_FOR (
615       partnum = guestfs_part_to_partnum (g, dev);
616     );
617     if (partnum >= 0) {
618       DISABLE_GUESTFS_ERRORS_FOR (
619         mbr_id = guestfs_part_get_mbr_id (g, parent_name, partnum);
620       );
621     }
622   }
623
624   free (parttype);
625
626   return mbr_id;
627 }
628
629 static void
630 do_output_partitions (void)
631 {
632   char **parts;
633   size_t i;
634
635   parts = guestfs_list_partitions (g);
636   if (parts == NULL)
637     exit (EXIT_FAILURE);
638
639   for (i = 0; parts[i] != NULL; ++i) {
640     char *dev, *parent_name = NULL;
641     int64_t size = -1;
642     int mbr_id = -1;
643
644     dev = canonical_device (parts[i]);
645
646     if ((columns & COLUMN_SIZE)) {
647       size = guestfs_blockdev_getsize64 (g, parts[i]);
648       if (size == -1)
649         exit (EXIT_FAILURE);
650     }
651     if ((columns & COLUMN_PARENT_NAME)) {
652       parent_name = guestfs_part_to_dev (g, parts[i]);
653       if (parent_name == NULL)
654         exit (EXIT_FAILURE);
655
656       if ((columns & COLUMN_MBR))
657         mbr_id = get_mbr_id (parts[i], parent_name);
658
659       char *p = canonical_device (parent_name);
660       free (parent_name);
661       parent_name = p;
662     }
663
664     write_row (dev, "partition",
665                NULL, NULL, mbr_id, size, parent_name, NULL);
666
667     free (dev);
668     free (parent_name);
669     free (parts[i]);
670   }
671
672   free (parts);
673 }
674
675 static void
676 do_output_blockdevs (void)
677 {
678   char **devices;
679   size_t i;
680
681   devices = guestfs_list_devices (g);
682   if (devices == NULL)
683     exit (EXIT_FAILURE);
684
685   for (i = 0; devices[i] != NULL; ++i) {
686     int64_t size = -1;
687     char *dev;
688
689     dev = canonical_device (devices[i]);
690
691     if ((columns & COLUMN_SIZE)) {
692       size = guestfs_blockdev_getsize64 (g, devices[i]);
693       if (size == -1)
694         exit (EXIT_FAILURE);
695     }
696
697     write_row (dev, "device",
698                NULL, NULL, -1, size, NULL, NULL);
699
700     free (dev);
701     free (devices[i]);
702   }
703
704   free (devices);
705 }
706
707 /* /dev/vda1 -> /dev/sda.  Returns a string which the caller must free. */
708 static char *
709 canonical_device (const char *dev)
710 {
711   char *ret = strdup (dev);
712   if (ret == NULL) {
713     perror ("strdup");
714     exit (EXIT_FAILURE);
715   }
716
717   if (STRPREFIX (ret, "/dev/") &&
718       (ret[5] == 'h' || ret[5] == 'v') &&
719       ret[6] == 'd' &&
720       c_isalpha (ret[7]) &&
721       (c_isdigit (ret[8]) || ret[8] == '\0'))
722     ret[5] = 's';
723
724   return ret;
725 }
726
727 static void
728 write_row (const char *name, const char *type,
729            const char *vfs_type, const char *vfs_label, int mbr_id,
730            int64_t size, const char *parent_name, const char *uuid)
731 {
732   const char *strings[NR_COLUMNS];
733   size_t len = 0;
734   char hum[LONGEST_HUMAN_READABLE];
735   char num[256];
736   char mbr_id_str[3];
737
738   if ((columns & COLUMN_NAME))
739     strings[len++] = name;
740   if ((columns & COLUMN_TYPE))
741     strings[len++] = type;
742   if ((columns & COLUMN_VFS_TYPE))
743     strings[len++] = vfs_type;
744   if ((columns & COLUMN_VFS_LABEL))
745     strings[len++] = vfs_label;
746   if ((columns & COLUMN_MBR)) {
747     if (mbr_id >= 0) {
748       snprintf (mbr_id_str, sizeof mbr_id_str, "%02x", mbr_id);
749       strings[len++] = mbr_id_str;
750     } else
751       strings[len++] = NULL;
752   }
753   if ((columns & COLUMN_SIZE)) {
754     if (size >= 0) {
755       if (human) {
756         strings[len++] =
757           human_readable ((uintmax_t) size, hum,
758                           human_round_to_nearest|human_autoscale|
759                           human_base_1024|human_SI,
760                           1, 1);
761       }
762       else {
763         snprintf (num, sizeof num, "%" PRIi64, size);
764         strings[len++] = num;
765       }
766     }
767     else
768       strings[len++] = NULL;
769   }
770   if ((columns & COLUMN_PARENT_NAME))
771     strings[len++] = parent_name;
772   if ((columns & COLUMN_UUID))
773     strings[len++] = uuid;
774   assert (len <= NR_COLUMNS);
775
776   write_row_strings ((char **) strings, len);
777 }
778
779 static void add_row (char **strings, size_t len);
780 static void write_csv_field (const char *field);
781
782 static void
783 write_row_strings (char **strings, size_t len)
784 {
785   if (!csv) {
786     /* Text mode.  Because we want the columns to line up, we can't
787      * output directly, but instead need to save up the rows and
788      * output them at the end.
789      */
790     add_row (strings, len);
791   }
792   else {                    /* CSV mode: output it directly, quoted */
793     size_t i;
794
795     for (i = 0; i < len; ++i) {
796       if (i > 0)
797         putchar (',');
798       if (strings[i] != NULL)
799         write_csv_field (strings[i]);
800     }
801     putchar ('\n');
802   }
803 }
804
805 /* Function to quote CSV fields on output without requiring an
806  * external module.
807  */
808 static void
809 write_csv_field (const char *field)
810 {
811   size_t i, len;
812   int needs_quoting = 0;
813
814   len = strlen (field);
815
816   for (i = 0; i < len; ++i) {
817     if (field[i] == ' ' || field[i] == '"' ||
818         field[i] == '\n' || field[i] == ',') {
819       needs_quoting = 1;
820       break;
821     }
822   }
823
824   if (!needs_quoting) {
825     printf ("%s", field);
826     return;
827   }
828
829   /* Quoting for CSV fields. */
830   putchar ('"');
831   for (i = 0; i < len; ++i) {
832     if (field[i] == '"') {
833       putchar ('"');
834       putchar ('"');
835     } else
836       putchar (field[i]);
837   }
838   putchar ('"');
839 }
840
841 /* This code is only used in text mode (non-CSV output). */
842 static char ***rows = NULL;
843 static size_t nr_rows = 0;
844 static size_t max_width[NR_COLUMNS];
845
846 static void
847 add_row (char **strings, size_t len)
848 {
849   size_t i, slen;
850   char **row;
851
852   assert (len <= NR_COLUMNS);
853
854   row = malloc (sizeof (char *) * len);
855   if (row == NULL) {
856     perror ("malloc");
857     exit (EXIT_FAILURE);
858   }
859
860   for (i = 0; i < len; ++i) {
861     if (strings[i]) {
862       row[i] = strdup (strings[i]);
863       if (row[i] == NULL) {
864         perror ("strdup");
865         exit (EXIT_FAILURE);
866       }
867
868       /* Keep a running total of the max width of each column. */
869       slen = strlen (strings[i]);
870       if (slen == 0)
871         slen = 1; /* because "" is printed as "-" */
872       if (slen > max_width[i])
873         max_width[i] = slen;
874     }
875     else
876       row[i] = NULL;
877   }
878
879   rows = realloc (rows, sizeof (char **) * (nr_rows + 1));
880   if (rows == NULL) {
881     perror ("realloc");
882     exit (EXIT_FAILURE);
883   }
884   rows[nr_rows] = row;
885   nr_rows++;
886 }
887
888 /* In text mode we saved up all the output so that we can print the
889  * columns aligned.
890  */
891 static void
892 do_output_end (void)
893 {
894   size_t i, j, k, len, space_btwn;
895
896   if (csv)
897     return;
898
899   /* How much space between columns?  Try 2 spaces between columns, but
900    * if that just pushes us over 72 columns, use 1 space.
901    */
902   space_btwn = 2;
903   i = 0;
904   for (j = 0; j < NR_COLUMNS; ++j)
905     i += max_width[j] + space_btwn;
906   if (i > 72)
907     space_btwn = 1;
908
909   for (i = 0; i < nr_rows; ++i) {
910     char **row = rows[i];
911
912     k = 0;
913
914     for (j = 0; j < NR_COLUMNS; ++j) {
915       /* Ignore columns which are completely empty.  This also deals
916        * with the fact that we didn't remember the length of each row
917        * in add_row above.
918        */
919       if (max_width[j] == 0)
920         continue;
921
922       while (k) {
923         putchar (' ');
924         k--;
925       }
926
927       if (row[j] == NULL || STREQ (row[j], "")) {
928         printf ("-");
929         len = 1;
930       } else {
931         printf ("%s", row[j]);
932         len = strlen (row[j]);
933       }
934       free (row[j]);
935
936       assert (len <= max_width[j]);
937       k = max_width[j] - len + space_btwn;
938     }
939
940     putchar ('\n');
941     free (row);
942   }
943   free (rows);
944 }