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