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