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