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