Added guestfish -i option to run virt-inspector.
[libguestfs.git] / fish / fish.c
1 /* guestfish - the filesystem interactive shell
2  * Copyright (C) 2009 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 #define _GNU_SOURCE // for strchrnul
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <getopt.h>
29 #include <signal.h>
30 #include <assert.h>
31 #include <ctype.h>
32
33 #ifdef HAVE_LIBREADLINE
34 #include <readline/readline.h>
35 #include <readline/history.h>
36 #endif
37
38 #include <guestfs.h>
39
40 #include "fish.h"
41
42 struct mp {
43   struct mp *next;
44   char *device;
45   char *mountpoint;
46 };
47
48 struct drv {
49   struct drv *next;
50   char *filename;
51 };
52
53 static void add_drives (struct drv *drv);
54 static void mount_mps (struct mp *mp);
55 static void interactive (void);
56 static void shell_script (void);
57 static void script (int prompt);
58 static void cmdline (char *argv[], int optind, int argc);
59 static void initialize_readline (void);
60 static void cleanup_readline (void);
61 static void add_history_line (const char *);
62
63 /* Currently open libguestfs handle. */
64 guestfs_h *g;
65
66 int read_only = 0;
67 int quit = 0;
68 int verbose = 0;
69
70 int
71 launch (guestfs_h *_g)
72 {
73   assert (_g == g);
74
75   if (guestfs_is_config (g)) {
76     if (guestfs_launch (g) == -1)
77       return -1;
78     if (guestfs_wait_ready (g) == -1)
79       return -1;
80   }
81   return 0;
82 }
83
84 static void
85 usage (void)
86 {
87   fprintf (stderr,
88            _("guestfish: guest filesystem shell\n"
89              "guestfish lets you edit virtual machine filesystems\n"
90              "Copyright (C) 2009 Red Hat Inc.\n"
91              "Usage:\n"
92              "  guestfish [--options] cmd [: cmd : cmd ...]\n"
93              "  guestfish -i libvirt-domain\n"
94              "  guestfish -i disk-image(s)\n"
95              "or for interactive use:\n"
96              "  guestfish\n"
97              "or from a shell script:\n"
98              "  guestfish <<EOF\n"
99              "  cmd\n"
100              "  ...\n"
101              "  EOF\n"
102              "Options:\n"
103              "  -h|--cmd-help        List available commands\n"
104              "  -h|--cmd-help cmd    Display detailed help on 'cmd'\n"
105              "  -a|--add image       Add image\n"
106              "  -D|--no-dest-paths   Don't tab-complete paths from guest fs\n"
107              "  -f|--file file       Read commands from file\n"
108              "  -i|--inspector       Run virt-inspector to get disk mountpoints\n"
109              "  -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
110              "  -n|--no-sync         Don't autosync\n"
111              "  -r|--ro              Mount read-only\n"
112              "  -v|--verbose         Verbose messages\n"
113              "  -V|--version         Display version and exit\n"
114              "For more information,  see the manpage guestfish(1).\n"));
115 }
116
117 int
118 main (int argc, char *argv[])
119 {
120   static const char *options = "a:f:h::im:nrv?V";
121   static struct option long_options[] = {
122     { "add", 1, 0, 'a' },
123     { "cmd-help", 2, 0, 'h' },
124     { "file", 1, 0, 'f' },
125     { "help", 0, 0, '?' },
126     { "inspector", 0, 0, 'i' },
127     { "mount", 1, 0, 'm' },
128     { "no-dest-paths", 0, 0, 'D' },
129     { "no-sync", 0, 0, 'n' },
130     { "ro", 0, 0, 'r' },
131     { "verbose", 0, 0, 'v' },
132     { "version", 0, 0, 'V' },
133     { 0, 0, 0, 0 }
134   };
135   struct drv *drvs = NULL;
136   struct drv *drv;
137   struct mp *mps = NULL;
138   struct mp *mp;
139   char *p, *file = NULL;
140   int c, inspector = 0;
141
142   initialize_readline ();
143
144   /* guestfs_create is meant to be a lightweight operation, so
145    * it's OK to do it early here.
146    */
147   g = guestfs_create ();
148   if (g == NULL) {
149     fprintf (stderr, _("guestfs_create: failed to create handle\n"));
150     exit (1);
151   }
152
153   guestfs_set_autosync (g, 1);
154
155   /* If developing, add ./appliance to the path.  Note that libtools
156    * interferes with this because uninstalled guestfish is a shell
157    * script that runs the real program with an absolute path.  Detect
158    * that too.
159    *
160    * BUT if LIBGUESTFS_PATH environment variable is already set by
161    * the user, then don't override it.
162    */
163   if (getenv ("LIBGUESTFS_PATH") == NULL &&
164       argv[0] &&
165       (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
166     guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
167
168   for (;;) {
169     c = getopt_long (argc, argv, options, long_options, NULL);
170     if (c == -1) break;
171
172     switch (c) {
173     case 'a':
174       if (access (optarg, R_OK) != 0) {
175         perror (optarg);
176         exit (1);
177       }
178       drv = malloc (sizeof (struct drv));
179       if (!drv) {
180         perror ("malloc");
181         exit (1);
182       }
183       drv->filename = optarg;
184       drv->next = drvs;
185       drvs = drv;
186       break;
187
188     case 'D':
189       complete_dest_paths = 0;
190       break;
191
192     case 'f':
193       if (file) {
194         fprintf (stderr, _("guestfish: only one -f parameter can be given\n"));
195         exit (1);
196       }
197       file = optarg;
198       break;
199
200     case 'h':
201       if (optarg)
202         display_command (optarg);
203       else if (argv[optind] && argv[optind][0] != '-')
204         display_command (argv[optind++]);
205       else
206         list_commands ();
207       exit (0);
208
209     case 'i':
210       inspector = 1;
211       break;
212
213     case 'm':
214       mp = malloc (sizeof (struct mp));
215       if (!mp) {
216         perror ("malloc");
217         exit (1);
218       }
219       p = strchr (optarg, ':');
220       if (p) {
221         *p = '\0';
222         mp->mountpoint = p+1;
223       } else
224         mp->mountpoint = "/";
225       mp->device = optarg;
226       mp->next = mps;
227       mps = mp;
228       break;
229
230     case 'n':
231       guestfs_set_autosync (g, 0);
232       break;
233
234     case 'r':
235       read_only = 1;
236       break;
237
238     case 'v':
239       verbose++;
240       guestfs_set_verbose (g, verbose);
241       break;
242
243     case 'V':
244       printf ("guestfish %s\n", PACKAGE_VERSION);
245       exit (0);
246
247     case '?':
248       usage ();
249       exit (0);
250
251     default:
252       fprintf (stderr, _("guestfish: unexpected command line option 0x%x\n"),
253                c);
254       exit (1);
255     }
256   }
257
258   /* Inspector mode invalidates most of the other arguments. */
259   if (inspector) {
260     char cmd[1024];
261     int r;
262
263     if (drvs || mps) {
264       fprintf (stderr, _("guestfish: cannot use -i option with -a or -m\n"));
265       exit (1);
266     }
267     if (optind >= argc) {
268       fprintf (stderr, _("guestfish -i requires a libvirt domain or path(s) to disk image(s)\n"));
269       exit (1);
270     }
271
272     strcpy (cmd, "a=`virt-inspector");
273     while (optind < argc) {
274       if (strlen (cmd) + strlen (argv[optind]) + strlen (argv[0]) + 60
275           >= sizeof cmd) {
276         fprintf (stderr, _("guestfish: virt-inspector command too long for fixed-size buffer\n"));
277         exit (1);
278       }
279       strcat (cmd, " ");
280       strcat (cmd, argv[optind]);
281       optind++;
282     }
283
284     if (read_only)
285       strcat (cmd, " --ro-fish");
286     else
287       strcat (cmd, " --fish");
288
289     sprintf (&cmd[strlen(cmd)], "` && %s $a", argv[0]);
290
291     if (guestfs_get_verbose (g))
292       strcat (cmd, " -v");
293     if (!guestfs_get_autosync (g))
294       strcat (cmd, " -n");
295
296     /*printf ("%s\n", cmd);*/
297
298     r = system (cmd);
299     if (r == -1) {
300       perror ("system");
301       exit (1);
302     }
303     exit (WEXITSTATUS (r));
304   }
305
306   /* If we've got drives to add, add them now. */
307   add_drives (drvs);
308
309   /* If we've got mountpoints, we must launch the guest and mount them. */
310   if (mps != NULL) {
311     if (launch (g) == -1) exit (1);
312     mount_mps (mps);
313   }
314
315   /* -f (file) parameter? */
316   if (file) {
317     close (0);
318     if (open (file, O_RDONLY) == -1) {
319       perror (file);
320       exit (1);
321     }
322   }
323
324   /* Interactive, shell script, or command(s) on the command line? */
325   if (optind >= argc) {
326     if (isatty (0))
327       interactive ();
328     else
329       shell_script ();
330   }
331   else
332     cmdline (argv, optind, argc);
333
334   cleanup_readline ();
335
336   exit (0);
337 }
338
339 void
340 pod2text (const char *heading, const char *str)
341 {
342   FILE *fp;
343
344   fp = popen ("pod2text", "w");
345   if (fp == NULL) {
346     /* pod2text failed, maybe not found, so let's just print the
347      * source instead, since that's better than doing nothing.
348      */
349     printf ("%s\n\n%s\n", heading, str);
350     return;
351   }
352   fputs ("=head1 ", fp);
353   fputs (heading, fp);
354   fputs ("\n\n", fp);
355   fputs (str, fp);
356   pclose (fp);
357 }
358
359 /* List is built in reverse order, so mount them in reverse order. */
360 static void
361 mount_mps (struct mp *mp)
362 {
363   int r;
364
365   if (mp) {
366     mount_mps (mp->next);
367     if (!read_only)
368       r = guestfs_mount (g, mp->device, mp->mountpoint);
369     else
370       r = guestfs_mount_ro (g, mp->device, mp->mountpoint);
371     if (r == -1)
372       exit (1);
373   }
374 }
375
376 static void
377 add_drives (struct drv *drv)
378 {
379   int r;
380
381   if (drv) {
382     add_drives (drv->next);
383     if (!read_only)
384       r = guestfs_add_drive (g, drv->filename);
385     else
386       r = guestfs_add_drive_ro (g, drv->filename);
387     if (r == -1)
388       exit (1);
389   }
390 }
391
392 static void
393 interactive (void)
394 {
395   script (1);
396 }
397
398 static void
399 shell_script (void)
400 {
401   script (0);
402 }
403
404 #define FISH "><fs> "
405
406 static char *line_read = NULL;
407
408 static char *
409 rl_gets (int prompt)
410 {
411 #ifdef HAVE_LIBREADLINE
412
413   if (prompt) {
414     if (line_read) {
415       free (line_read);
416       line_read = NULL;
417     }
418
419     line_read = readline (prompt ? FISH : "");
420
421     if (line_read && *line_read)
422       add_history_line (line_read);
423
424     return line_read;
425   }
426
427 #endif /* HAVE_LIBREADLINE */
428
429   static char buf[8192];
430   int len;
431
432   if (prompt) printf (FISH);
433   line_read = fgets (buf, sizeof buf, stdin);
434
435   if (line_read) {
436     len = strlen (line_read);
437     if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
438   }
439
440   return line_read;
441 }
442
443 static void
444 script (int prompt)
445 {
446   char *buf;
447   char *cmd;
448   char *p, *pend;
449   char *argv[64];
450   int i, len;
451   int global_exit_on_error = !prompt;
452   int exit_on_error;
453
454   if (prompt)
455     printf (_("\n"
456               "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
457               "editing virtual machine filesystems.\n"
458               "\n"
459               "Type: 'help' for help with commands\n"
460               "      'quit' to quit the shell\n"
461               "\n"));
462
463   while (!quit) {
464     exit_on_error = global_exit_on_error;
465
466     buf = rl_gets (prompt);
467     if (!buf) {
468       quit = 1;
469       break;
470     }
471
472     /* Skip any initial whitespace before the command. */
473   again:
474     while (*buf && isspace (*buf))
475       buf++;
476
477     if (!*buf) continue;
478
479     /* If the next character is '#' then this is a comment. */
480     if (*buf == '#') continue;
481
482     /* If the next character is '!' then pass the whole lot to system(3). */
483     if (*buf == '!') {
484       int r;
485
486       r = system (buf+1);
487       if (exit_on_error) {
488         if (r == -1 ||
489             (WIFSIGNALED (r) &&
490              (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
491             WEXITSTATUS (r) != 0)
492           exit (1);
493       }
494       continue;
495     }
496
497     /* If the next character is '-' allow the command to fail without
498      * exiting on error (just for this one command though).
499      */
500     if (*buf == '-') {
501       exit_on_error = 0;
502       buf++;
503       goto again;
504     }
505
506     /* Get the command (cannot be quoted). */
507     len = strcspn (buf, " \t");
508
509     if (len == 0) continue;
510
511     cmd = buf;
512     i = 0;
513     if (buf[len] == '\0') {
514       argv[0] = NULL;
515       goto got_command;
516     }
517
518     buf[len] = '\0';
519     p = &buf[len+1];
520     p += strspn (p, " \t");
521
522     /* Get the parameters. */
523     while (*p && i < sizeof argv / sizeof argv[0]) {
524       /* Parameters which start with quotes or square brackets
525        * are treated specially.  Bare parameters are delimited
526        * by whitespace.
527        */
528       if (*p == '"') {
529         p++;
530         len = strcspn (p, "\"");
531         if (p[len] == '\0') {
532           fprintf (stderr, _("guestfish: unterminated double quote\n"));
533           if (exit_on_error) exit (1);
534           goto next_command;
535         }
536         if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
537           fprintf (stderr, _("guestfish: command arguments not separated by whitespace\n"));
538           if (exit_on_error) exit (1);
539           goto next_command;
540         }
541         p[len] = '\0';
542         pend = p[len+1] ? &p[len+2] : &p[len+1];
543       } else if (*p == '\'') {
544         p++;
545         len = strcspn (p, "'");
546         if (p[len] == '\0') {
547           fprintf (stderr, _("guestfish: unterminated single quote\n"));
548           if (exit_on_error) exit (1);
549           goto next_command;
550         }
551         if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
552           fprintf (stderr, _("guestfish: command arguments not separated by whitespace\n"));
553           if (exit_on_error) exit (1);
554           goto next_command;
555         }
556         p[len] = '\0';
557         pend = p[len+1] ? &p[len+2] : &p[len+1];
558         /*
559       } else if (*p == '[') {
560         int c = 1;
561         p++;
562         pend = p;
563         while (*pend && c != 0) {
564           if (*pend == '[') c++;
565           else if (*pend == ']') c--;
566           pend++;
567         }
568         if (c != 0) {
569           fprintf (stderr, _("guestfish: unterminated \"[...]\" sequence\n"));
570           if (exit_on_error) exit (1);
571           goto next_command;
572         }
573         if (*pend && (*pend != ' ' && *pend != '\t')) {
574           fprintf (stderr, _("guestfish: command arguments not separated by whitespace\n"));
575           if (exit_on_error) exit (1);
576           goto next_command;
577         }
578         *(pend-1) = '\0';
579         */
580       } else if (*p != ' ' && *p != '\t') {
581         len = strcspn (p, " \t");
582         if (p[len]) {
583           p[len] = '\0';
584           pend = &p[len+1];
585         } else
586           pend = &p[len];
587       } else {
588         fprintf (stderr, _("guestfish: internal error parsing string at '%s'\n"),
589                  p);
590         abort ();
591       }
592
593       argv[i++] = p;
594       p = pend;
595
596       if (*p)
597         p += strspn (p, " \t");
598     }
599
600     if (i == sizeof argv / sizeof argv[0]) {
601       fprintf (stderr, _("guestfish: too many arguments\n"));
602       if (exit_on_error) exit (1);
603       goto next_command;
604     }
605
606     argv[i] = NULL;
607
608   got_command:
609     if (issue_command (cmd, argv) == -1) {
610       if (exit_on_error) exit (1);
611     }
612
613   next_command:;
614   }
615   if (prompt) printf ("\n");
616 }
617
618 static void
619 cmdline (char *argv[], int optind, int argc)
620 {
621   const char *cmd;
622   char **params;
623
624   if (optind >= argc) return;
625
626   cmd = argv[optind++];
627   if (strcmp (cmd, ":") == 0) {
628     fprintf (stderr, _("guestfish: empty command on command line\n"));
629     exit (1);
630   }
631   params = &argv[optind];
632
633   /* Search for end of command list or ":" ... */
634   while (optind < argc && strcmp (argv[optind], ":") != 0)
635     optind++;
636
637   if (optind == argc) {
638     if (issue_command (cmd, params) == -1) exit (1);
639   } else {
640     argv[optind] = NULL;
641     if (issue_command (cmd, params) == -1) exit (1);
642     cmdline (argv, optind+1, argc);
643   }
644 }
645
646 int
647 issue_command (const char *cmd, char *argv[])
648 {
649   int argc;
650
651   for (argc = 0; argv[argc] != NULL; ++argc)
652     ;
653
654   if (strcasecmp (cmd, "help") == 0) {
655     if (argc == 0)
656       list_commands ();
657     else
658       display_command (argv[0]);
659     return 0;
660   }
661   else if (strcasecmp (cmd, "quit") == 0 ||
662            strcasecmp (cmd, "exit") == 0 ||
663            strcasecmp (cmd, "q") == 0) {
664     quit = 1;
665     return 0;
666   }
667   else if (strcasecmp (cmd, "alloc") == 0 ||
668            strcasecmp (cmd, "allocate") == 0)
669     return do_alloc (cmd, argc, argv);
670   else if (strcasecmp (cmd, "echo") == 0)
671     return do_echo (cmd, argc, argv);
672   else if (strcasecmp (cmd, "edit") == 0 ||
673            strcasecmp (cmd, "vi") == 0 ||
674            strcasecmp (cmd, "emacs") == 0)
675     return do_edit (cmd, argc, argv);
676   else if (strcasecmp (cmd, "lcd") == 0)
677     return do_lcd (cmd, argc, argv);
678   else if (strcasecmp (cmd, "glob") == 0)
679     return do_glob (cmd, argc, argv);
680   else
681     return run_action (cmd, argc, argv);
682 }
683
684 void
685 list_builtin_commands (void)
686 {
687   /* help and quit should appear at the top */
688   printf ("%-20s %s\n",
689           "help", _("display a list of commands or help on a command"));
690   printf ("%-20s %s\n",
691           "quit", _("quit guestfish"));
692
693   printf ("%-20s %s\n",
694           "alloc", _("allocate an image"));
695   printf ("%-20s %s\n",
696           "echo", _("display a line of text"));
697   printf ("%-20s %s\n",
698           "edit", _("edit a file in the image"));
699   printf ("%-20s %s\n",
700           "lcd", _("local change directory"));
701   printf ("%-20s %s\n",
702           "glob", _("expand wildcards in command"));
703
704   /* actions are printed after this (see list_commands) */
705 }
706
707 void
708 display_builtin_command (const char *cmd)
709 {
710   /* help for actions is auto-generated, see display_command */
711
712   if (strcasecmp (cmd, "alloc") == 0 ||
713       strcasecmp (cmd, "allocate") == 0)
714     printf (_("alloc - allocate an image\n"
715               "     alloc <filename> <size>\n"
716               "\n"
717               "    This creates an empty (zeroed) file of the given size,\n"
718               "    and then adds so it can be further examined.\n"
719               "\n"
720               "    For more advanced image creation, see qemu-img utility.\n"
721               "\n"
722               "    Size can be specified (where <nn> means a number):\n"
723               "    <nn>             number of kilobytes\n"
724               "      eg: 1440       standard 3.5\" floppy\n"
725               "    <nn>K or <nn>KB  number of kilobytes\n"
726               "    <nn>M or <nn>MB  number of megabytes\n"
727               "    <nn>G or <nn>GB  number of gigabytes\n"
728               "    <nn>sects        number of 512 byte sectors\n"));
729   else if (strcasecmp (cmd, "echo") == 0)
730     printf (_("echo - display a line of text\n"
731               "     echo [<params> ...]\n"
732               "\n"
733               "    This echos the parameters to the terminal.\n"));
734   else if (strcasecmp (cmd, "edit") == 0 ||
735            strcasecmp (cmd, "vi") == 0 ||
736            strcasecmp (cmd, "emacs") == 0)
737     printf (_("edit - edit a file in the image\n"
738               "     edit <filename>\n"
739               "\n"
740               "    This is used to edit a file.\n"
741               "\n"
742               "    It is the equivalent of (and is implemented by)\n"
743               "    running \"cat\", editing locally, and then \"write-file\".\n"
744               "\n"
745               "    Normally it uses $EDITOR, but if you use the aliases\n"
746               "    \"vi\" or \"emacs\" you will get those editors.\n"
747               "\n"
748               "    NOTE: This will not work reliably for large files\n"
749               "    (> 2 MB) or binary files containing \\0 bytes.\n"));
750   else if (strcasecmp (cmd, "lcd") == 0)
751     printf (_("lcd - local change directory\n"
752               "    lcd <directory>\n"
753               "\n"
754               "    Change guestfish's current directory. This command is\n"
755               "    useful if you want to download files to a particular\n"
756               "    place.\n"));
757   else if (strcasecmp (cmd, "glob") == 0)
758     printf (_("glob - expand wildcards in command\n"
759               "    glob <command> [<args> ...]\n"
760               "\n"
761               "    Glob runs <command> with wildcards expanded in any\n"
762               "    command args.  Note that the command is run repeatedly\n"
763               "    once for each expanded argument.\n"));
764   else if (strcasecmp (cmd, "help") == 0)
765     printf (_("help - display a list of commands or help on a command\n"
766               "     help cmd\n"
767               "     help\n"));
768   else if (strcasecmp (cmd, "quit") == 0 ||
769            strcasecmp (cmd, "exit") == 0 ||
770            strcasecmp (cmd, "q") == 0)
771     printf (_("quit - quit guestfish\n"
772               "     quit\n"));
773   else
774     fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
775              cmd);
776 }
777
778 void
779 free_strings (char **argv)
780 {
781   int argc;
782
783   for (argc = 0; argv[argc] != NULL; ++argc)
784     free (argv[argc]);
785   free (argv);
786 }
787
788 int
789 count_strings (char * const * const argv)
790 {
791   int c;
792
793   for (c = 0; argv[c]; ++c)
794     ;
795   return c;
796 }
797
798 void
799 print_strings (char * const * const argv)
800 {
801   int argc;
802
803   for (argc = 0; argv[argc] != NULL; ++argc)
804     printf ("%s\n", argv[argc]);
805 }
806
807 void
808 print_table (char * const * const argv)
809 {
810   int i;
811
812   for (i = 0; argv[i] != NULL; i += 2)
813     printf ("%s: %s\n", argv[i], argv[i+1]);
814 }
815
816 int
817 is_true (const char *str)
818 {
819   return
820     strcasecmp (str, "0") != 0 &&
821     strcasecmp (str, "f") != 0 &&
822     strcasecmp (str, "false") != 0 &&
823     strcasecmp (str, "n") != 0 &&
824     strcasecmp (str, "no") != 0;
825 }
826
827 /* XXX We could improve list parsing. */
828 char **
829 parse_string_list (const char *str)
830 {
831   char **argv;
832   const char *p, *pend;
833   int argc, i;
834
835   argc = 1;
836   for (i = 0; str[i]; ++i)
837     if (str[i] == ' ') argc++;
838
839   argv = malloc (sizeof (char *) * (argc+1));
840   if (argv == NULL) { perror ("malloc"); exit (1); }
841
842   p = str;
843   i = 0;
844   while (*p) {
845     pend = strchrnul (p, ' ');
846     argv[i] = strndup (p, pend-p);
847     i++;
848     p = *pend == ' ' ? pend+1 : pend;
849   }
850   argv[i] = NULL;
851
852   return argv;
853 }
854
855 #ifdef HAVE_LIBREADLINE
856 static char histfile[1024];
857 static int nr_history_lines = 0;
858 #endif
859
860 static void
861 initialize_readline (void)
862 {
863 #ifdef HAVE_LIBREADLINE
864   const char *home;
865
866   home = getenv ("HOME");
867   if (home) {
868     snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
869     using_history ();
870     (void) read_history (histfile);
871   }
872
873   rl_readline_name = "guestfish";
874   rl_attempted_completion_function = do_completion;
875 #endif
876 }
877
878 static void
879 cleanup_readline (void)
880 {
881 #ifdef HAVE_LIBREADLINE
882   int fd;
883
884   if (histfile[0] != '\0') {
885     fd = open (histfile, O_WRONLY|O_CREAT, 0644);
886     if (fd == -1) {
887       perror (histfile);
888       return;
889     }
890     close (fd);
891
892     (void) append_history (nr_history_lines, histfile);
893   }
894 #endif
895 }
896
897 static void
898 add_history_line (const char *line)
899 {
900 #ifdef HAVE_LIBREADLINE
901   add_history (line);
902   nr_history_lines++;
903 #endif
904 }