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