fish: Add guestfish --live, guestmount --live options.
[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 live = 0;
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   assert (live == 0);
306
307   /* Must be no extra arguments on the command line. */
308   if (optind != argc)
309     usage (EXIT_FAILURE);
310
311   /* -h and --csv doesn't make sense.  Spreadsheets will corrupt these
312    * fields.  (RHBZ#600977).
313    */
314   if (human && csv) {
315     fprintf (stderr, _("%s: you cannot use -h and --csv options together.\n"),
316              program_name);
317     exit (EXIT_FAILURE);
318   }
319
320   /* Nothing selected for output, means --filesystems is implied. */
321   if (output == 0)
322     output = OUTPUT_FILESYSTEMS;
323
324   /* What columns will be displayed? */
325   columns = COLUMN_NAME;
326   if (long_mode) {
327     columns |= COLUMN_TYPE;
328     columns |= COLUMN_SIZE;
329     if ((output & OUTPUT_FILESYSTEMS)) {
330       columns |= COLUMN_VFS_TYPE;
331       columns |= COLUMN_VFS_LABEL;
332     }
333     if ((output & (OUTPUT_PARTITIONS|OUTPUT_LVS)))
334       columns |= COLUMN_PARENT_NAME;
335     if (uuid)
336       columns |= COLUMN_UUID;
337   }
338
339   /* Display title by default only in long mode. */
340   title = long_mode;
341   if (no_title)
342     title = 0;
343
344   /* User must have specified some drives. */
345   if (drvs == NULL)
346     usage (EXIT_FAILURE);
347
348   /* Add drives. */
349   add_drives (drvs, 'a');
350
351   if (guestfs_launch (g) == -1)
352     exit (EXIT_FAILURE);
353
354   /* Free up data structures, no longer needed after this point. */
355   free_drives (drvs);
356
357   if (title)
358     do_output_title ();
359   do_output ();
360   do_output_end ();
361
362   guestfs_close (g);
363
364   exit (EXIT_SUCCESS);
365 }
366
367 static void do_output_filesystems (void);
368 static void do_output_lvs (void);
369 static void do_output_vgs (void);
370 static void do_output_pvs (void);
371 static void do_output_partitions (void);
372 static void do_output_blockdevs (void);
373 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);
374 static void write_row_strings (char **strings, size_t len);
375
376 static void
377 do_output_title (void)
378 {
379   const char *headings[NR_COLUMNS];
380   size_t len = 0;
381
382   /* NB. These strings are not localized and must not contain spaces. */
383   if ((columns & COLUMN_NAME))
384     headings[len++] = "Name";
385   if ((columns & COLUMN_TYPE))
386     headings[len++] = "Type";
387   if ((columns & COLUMN_VFS_TYPE))
388     headings[len++] = "VFS";
389   if ((columns & COLUMN_VFS_LABEL))
390     headings[len++] = "Label";
391   if ((columns & COLUMN_SIZE))
392     headings[len++] = "Size";
393   if ((columns & COLUMN_PARENT_NAME))
394     headings[len++] = "Parent";
395   if ((columns & COLUMN_UUID))
396     headings[len++] = "UUID";
397   assert (len <= NR_COLUMNS);
398
399   write_row_strings ((char **) headings, len);
400 }
401
402 static void
403 do_output (void)
404 {
405   /* The ordering here is trying to be most specific -> least specific,
406    * although that is not required or guaranteed.
407    */
408   if ((output & OUTPUT_FILESYSTEMS))
409     do_output_filesystems ();
410
411   if ((output & OUTPUT_LVS))
412     do_output_lvs ();
413
414   if ((output & OUTPUT_VGS))
415     do_output_vgs ();
416
417   if ((output & OUTPUT_PVS))
418     do_output_pvs ();
419
420   if ((output & OUTPUT_PARTITIONS))
421     do_output_partitions ();
422
423   if ((output & OUTPUT_BLOCKDEVS))
424     do_output_blockdevs ();
425 }
426
427 static void
428 do_output_filesystems (void)
429 {
430   char **fses;
431   size_t i;
432
433   fses = guestfs_list_filesystems (g);
434   if (fses == NULL)
435     exit (EXIT_FAILURE);
436
437   for (i = 0; fses[i] != NULL; i += 2) {
438     char *dev, *vfs_label = NULL, *vfs_uuid = NULL;
439     int64_t size = -1;
440
441     /* Skip swap and unknown, unless --extra flag was given. */
442     if (!(output & OUTPUT_FILESYSTEMS_EXTRA) &&
443         (STREQ (fses[i+1], "swap") || STREQ (fses[i+1], "unknown")))
444       continue;
445
446     dev = canonical_device (fses[i]);
447
448     /* Only bother to look these up if we will be displaying them,
449      * otherwise pass them as NULL.
450      */
451     if ((columns & COLUMN_VFS_LABEL)) {
452       DISABLE_GUESTFS_ERRORS_FOR (
453         vfs_label = guestfs_vfs_label (g, fses[i]);
454       );
455       if (vfs_label == NULL) {
456         vfs_label = strdup ("");
457         if (!vfs_label) {
458           perror ("strdup");
459           exit (EXIT_FAILURE);
460         }
461       }
462     }
463     if ((columns & COLUMN_UUID)) {
464       DISABLE_GUESTFS_ERRORS_FOR (
465         vfs_uuid = guestfs_vfs_uuid (g, fses[i]);
466       );
467       if (vfs_uuid == NULL) {
468         vfs_uuid = strdup ("");
469         if (!vfs_uuid) {
470           perror ("strdup");
471           exit (EXIT_FAILURE);
472         }
473       }
474     }
475     if ((columns & COLUMN_SIZE)) {
476       size = guestfs_blockdev_getsize64 (g, fses[i]);
477       if (size == -1)
478         exit (EXIT_FAILURE);
479     }
480
481     write_row (dev, "filesystem",
482                fses[i+1], vfs_label, size, NULL, vfs_uuid);
483
484     free (dev);
485     free (vfs_label);
486     free (vfs_uuid);
487     free (fses[i]);
488     free (fses[i+1]);
489   }
490
491   free (fses);
492 }
493
494 static void
495 do_output_lvs (void)
496 {
497   char **lvs;
498   size_t i;
499
500   lvs = guestfs_lvs (g);
501   if (lvs == NULL)
502     exit (EXIT_FAILURE);
503
504   for (i = 0; lvs[i] != NULL; ++i) {
505     char *uuid = NULL, *parent_name = NULL;
506     int64_t size = -1;
507
508     if ((columns & COLUMN_SIZE)) {
509       size = guestfs_blockdev_getsize64 (g, lvs[i]);
510       if (size == -1)
511         exit (EXIT_FAILURE);
512     }
513     if ((columns & COLUMN_UUID)) {
514       uuid = guestfs_lvuuid (g, lvs[i]);
515       if (uuid == NULL)
516         exit (EXIT_FAILURE);
517     }
518     if ((columns & COLUMN_PARENT_NAME)) {
519       parent_name = strdup (lvs[i]);
520       if (parent_name == NULL) {
521         perror ("strdup");
522         exit (EXIT_FAILURE);
523       }
524       char *p = strrchr (parent_name, '/');
525       if (p)
526         *p = '\0';
527     }
528
529     write_row (lvs[i], "lv",
530                NULL, NULL, size, parent_name, uuid);
531
532     free (uuid);
533     free (parent_name);
534     free (lvs[i]);
535   }
536
537   free (lvs);
538 }
539
540 static void
541 do_output_vgs (void)
542 {
543   struct guestfs_lvm_vg_list *vgs;
544   size_t i;
545
546   vgs = guestfs_vgs_full (g);
547   if (vgs == NULL)
548     exit (EXIT_FAILURE);
549
550   for (i = 0; i < vgs->len; ++i) {
551     char name[PATH_MAX];
552     char uuid[33];
553
554     strcpy (name, "/dev/");
555     strcpy (&name[5], vgs->val[i].vg_name);
556     memcpy (uuid, vgs->val[i].vg_uuid, 32);
557     uuid[32] = '\0';
558     write_row (name, "vg",
559                NULL, NULL, (int64_t) vgs->val[i].vg_size, NULL, uuid);
560
561   }
562
563   guestfs_free_lvm_vg_list (vgs);
564 }
565
566 static void
567 do_output_pvs (void)
568 {
569   struct guestfs_lvm_pv_list *pvs;
570   size_t i;
571
572   pvs = guestfs_pvs_full (g);
573   if (pvs == NULL)
574     exit (EXIT_FAILURE);
575
576   for (i = 0; i < pvs->len; ++i) {
577     char *dev;
578     char uuid[33];
579
580     dev = canonical_device (pvs->val[i].pv_name);
581
582     memcpy (uuid, pvs->val[i].pv_uuid, 32);
583     uuid[32] = '\0';
584     write_row (dev, "pv",
585                NULL, NULL, (int64_t) pvs->val[i].pv_size, NULL, uuid);
586
587     free (dev);
588   }
589
590   guestfs_free_lvm_pv_list (pvs);
591 }
592
593 static void
594 do_output_partitions (void)
595 {
596   char **parts;
597   size_t i;
598
599   parts = guestfs_list_partitions (g);
600   if (parts == NULL)
601     exit (EXIT_FAILURE);
602
603   for (i = 0; parts[i] != NULL; ++i) {
604     char *dev, *parent_name = NULL;
605     int64_t size = -1;
606
607     dev = canonical_device (parts[i]);
608
609     if ((columns & COLUMN_SIZE)) {
610       size = guestfs_blockdev_getsize64 (g, parts[i]);
611       if (size == -1)
612         exit (EXIT_FAILURE);
613     }
614     if ((columns & COLUMN_PARENT_NAME)) {
615       parent_name = guestfs_part_to_dev (g, parts[i]);
616       if (parent_name == NULL)
617         exit (EXIT_FAILURE);
618       char *p = canonical_device (parent_name);
619       free (parent_name);
620       parent_name = p;
621     }
622
623     write_row (dev, "partition",
624                NULL, NULL, size, parent_name, NULL);
625
626     free (dev);
627     free (parent_name);
628     free (parts[i]);
629   }
630
631   free (parts);
632 }
633
634 static void
635 do_output_blockdevs (void)
636 {
637   char **devices;
638   size_t i;
639
640   devices = guestfs_list_devices (g);
641   if (devices == NULL)
642     exit (EXIT_FAILURE);
643
644   for (i = 0; devices[i] != NULL; ++i) {
645     int64_t size = -1;
646     char *dev;
647
648     dev = canonical_device (devices[i]);
649
650     if ((columns & COLUMN_SIZE)) {
651       size = guestfs_blockdev_getsize64 (g, devices[i]);
652       if (size == -1)
653         exit (EXIT_FAILURE);
654     }
655
656     write_row (dev, "device",
657                NULL, NULL, size, NULL, NULL);
658
659     free (dev);
660     free (devices[i]);
661   }
662
663   free (devices);
664 }
665
666 /* /dev/vda1 -> /dev/sda.  Returns a string which the caller must free. */
667 static char *
668 canonical_device (const char *dev)
669 {
670   char *ret = strdup (dev);
671   if (ret == NULL) {
672     perror ("strdup");
673     exit (EXIT_FAILURE);
674   }
675
676   if (STRPREFIX (ret, "/dev/") &&
677       (ret[5] == 'h' || ret[5] == 'v') &&
678       ret[6] == 'd' &&
679       c_isalpha (ret[7]) &&
680       (c_isdigit (ret[8]) || ret[8] == '\0'))
681     ret[5] = 's';
682
683   return ret;
684 }
685
686 static void
687 write_row (const char *name, const char *type,
688            const char *vfs_type, const char *vfs_label,
689            int64_t size, const char *parent_name, const char *uuid)
690 {
691   const char *strings[NR_COLUMNS];
692   size_t len = 0;
693   char hum[LONGEST_HUMAN_READABLE];
694   char num[256];
695
696   if ((columns & COLUMN_NAME))
697     strings[len++] = name;
698   if ((columns & COLUMN_TYPE))
699     strings[len++] = type;
700   if ((columns & COLUMN_VFS_TYPE))
701     strings[len++] = vfs_type;
702   if ((columns & COLUMN_VFS_LABEL))
703     strings[len++] = vfs_label;
704   if ((columns & COLUMN_SIZE)) {
705     if (size >= 0) {
706       if (human) {
707         strings[len++] =
708           human_readable ((uintmax_t) size, hum,
709                           human_round_to_nearest|human_autoscale|
710                           human_base_1024|human_SI,
711                           1, 1);
712       }
713       else {
714         snprintf (num, sizeof num, "%" PRIi64, size);
715         strings[len++] = num;
716       }
717     }
718     else
719       strings[len++] = NULL;
720   }
721   if ((columns & COLUMN_PARENT_NAME))
722     strings[len++] = parent_name;
723   if ((columns & COLUMN_UUID))
724     strings[len++] = uuid;
725   assert (len <= NR_COLUMNS);
726
727   write_row_strings ((char **) strings, len);
728 }
729
730 static void add_row (char **strings, size_t len);
731 static void write_csv_field (const char *field);
732
733 static void
734 write_row_strings (char **strings, size_t len)
735 {
736   if (!csv) {
737     /* Text mode.  Because we want the columns to line up, we can't
738      * output directly, but instead need to save up the rows and
739      * output them at the end.
740      */
741     add_row (strings, len);
742   }
743   else {                    /* CSV mode: output it directly, quoted */
744     size_t i;
745
746     for (i = 0; i < len; ++i) {
747       if (i > 0)
748         putchar (',');
749       if (strings[i] != NULL)
750         write_csv_field (strings[i]);
751     }
752     putchar ('\n');
753   }
754 }
755
756 /* Function to quote CSV fields on output without requiring an
757  * external module.
758  */
759 static void
760 write_csv_field (const char *field)
761 {
762   size_t i, len;
763   int needs_quoting = 0;
764
765   len = strlen (field);
766
767   for (i = 0; i < len; ++i) {
768     if (field[i] == ' ' || field[i] == '"' ||
769         field[i] == '\n' || field[i] == ',') {
770       needs_quoting = 1;
771       break;
772     }
773   }
774
775   if (!needs_quoting) {
776     printf ("%s", field);
777     return;
778   }
779
780   /* Quoting for CSV fields. */
781   putchar ('"');
782   for (i = 0; i < len; ++i) {
783     if (field[i] == '"') {
784       putchar ('"');
785       putchar ('"');
786     } else
787       putchar (field[i]);
788   }
789   putchar ('"');
790 }
791
792 /* This code is only used in text mode (non-CSV output). */
793 static char ***rows = NULL;
794 static size_t nr_rows = 0;
795 static size_t max_width[NR_COLUMNS];
796
797 static void
798 add_row (char **strings, size_t len)
799 {
800   size_t i, slen;
801   char **row;
802
803   assert (len <= NR_COLUMNS);
804
805   row = malloc (sizeof (char *) * len);
806   if (row == NULL) {
807     perror ("malloc");
808     exit (EXIT_FAILURE);
809   }
810
811   for (i = 0; i < len; ++i) {
812     if (strings[i]) {
813       row[i] = strdup (strings[i]);
814       if (row[i] == NULL) {
815         perror ("strdup");
816         exit (EXIT_FAILURE);
817       }
818
819       /* Keep a running total of the max width of each column. */
820       slen = strlen (strings[i]);
821       if (slen == 0)
822         slen = 1; /* because "" is printed as "-" */
823       if (slen > max_width[i])
824         max_width[i] = slen;
825     }
826     else
827       row[i] = NULL;
828   }
829
830   rows = realloc (rows, sizeof (char **) * (nr_rows + 1));
831   if (rows == NULL) {
832     perror ("realloc");
833     exit (EXIT_FAILURE);
834   }
835   rows[nr_rows] = row;
836   nr_rows++;
837 }
838
839 /* In text mode we saved up all the output so that we can print the
840  * columns aligned.
841  */
842 static void
843 do_output_end (void)
844 {
845   size_t i, j, k, len, space_btwn;
846
847   if (csv)
848     return;
849
850   /* How much space between columns?  Try 2 spaces between columns, but
851    * if that just pushes us over 72 columns, use 1 space.
852    */
853   space_btwn = 2;
854   i = 0;
855   for (j = 0; j < NR_COLUMNS; ++j)
856     i += max_width[j] + space_btwn;
857   if (i > 72)
858     space_btwn = 1;
859
860   for (i = 0; i < nr_rows; ++i) {
861     char **row = rows[i];
862
863     k = 0;
864
865     for (j = 0; j < NR_COLUMNS; ++j) {
866       /* Ignore columns which are completely empty.  This also deals
867        * with the fact that we didn't remember the length of each row
868        * in add_row above.
869        */
870       if (max_width[j] == 0)
871         continue;
872
873       while (k) {
874         putchar (' ');
875         k--;
876       }
877
878       if (row[j] == NULL || STREQ (row[j], "")) {
879         printf ("-");
880         len = 1;
881       } else {
882         printf ("%s", row[j]);
883         len = strlen (row[j]);
884       }
885       free (row[j]);
886
887       assert (len <= max_width[j]);
888       k = max_width[j] - len + space_btwn;
889     }
890
891     putchar ('\n');
892     free (row);
893   }
894   free (rows);
895 }