1/* bashhist.c -- bash interface to the GNU history library. */
2
3/* Copyright (C) 1993-2009 Free Software Foundation, Inc.
4
5   This file is part of GNU Bash, the Bourne Again SHell.
6
7   Bash is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   Bash is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with Bash.  If not, see <http://www.gnu.org/licenses/>.
19*/
20
21#include "config.h"
22
23#if defined (HISTORY)
24
25#if defined (HAVE_UNISTD_H)
26#  ifdef _MINIX
27#    include <sys/types.h>
28#  endif
29#  include <unistd.h>
30#endif
31
32#include "bashtypes.h"
33#include <stdio.h>
34#include <errno.h>
35#include "bashansi.h"
36#include "posixstat.h"
37#include "filecntl.h"
38
39#include "bashintl.h"
40
41#include "shell.h"
42#include "flags.h"
43#include "input.h"
44#include "parser.h"	/* for the struct dstack stuff. */
45#include "pathexp.h"	/* for the struct ignorevar stuff */
46#include "bashhist.h"	/* matching prototypes and declarations */
47#include "builtins/common.h"
48
49#include <readline/history.h>
50#include <glob/glob.h>
51#include <glob/strmatch.h>
52
53#if defined (READLINE)
54#  include "bashline.h"
55extern int rl_done, rl_dispatching;	/* should really include readline.h */
56#endif
57
58#if !defined (errno)
59extern int errno;
60#endif
61
62static int histignore_item_func __P((struct ign *));
63static int check_history_control __P((char *));
64static void hc_erasedups __P((char *));
65static void really_add_history __P((char *));
66
67static struct ignorevar histignore =
68{
69  "HISTIGNORE",
70  (struct ign *)0,
71  0,
72  (char *)0,
73  (sh_iv_item_func_t *)histignore_item_func,
74};
75
76#define HIGN_EXPAND 0x01
77
78/* Declarations of bash history variables. */
79/* Non-zero means to remember lines typed to the shell on the history
80   list.  This is different than the user-controlled behaviour; this
81   becomes zero when we read lines from a file, for example. */
82int remember_on_history = 1;
83int enable_history_list = 1;	/* value for `set -o history' */
84
85/* The number of lines that Bash has added to this history session.  The
86   difference between the number of the top element in the history list
87   (offset from history_base) and the number of lines in the history file.
88   Appending this session's history to the history file resets this to 0. */
89int history_lines_this_session;
90
91/* The number of lines that Bash has read from the history file. */
92int history_lines_in_file;
93
94#if defined (BANG_HISTORY)
95/* Non-zero means do no history expansion on this line, regardless
96   of what history_expansion says. */
97int history_expansion_inhibited;
98#endif
99
100/* With the old default, every line was saved in the history individually.
101   I.e., if the user enters:
102	bash$ for i in a b c
103	> do
104	> echo $i
105	> done
106   Each line will be individually saved in the history.
107	bash$ history
108	10  for i in a b c
109	11  do
110	12  echo $i
111	13  done
112	14  history
113   If the variable command_oriented_history is set, multiple lines
114   which form one command will be saved as one history entry.
115	bash$ for i in a b c
116	> do
117	> echo $i
118	> done
119	bash$ history
120	10  for i in a b c
121    do
122    echo $i
123    done
124	11  history
125   The user can then recall the whole command all at once instead
126   of just being able to recall one line at a time.
127
128   This is now enabled by default.
129   */
130int command_oriented_history = 1;
131
132/* Set to 1 if the first line of a possibly-multi-line command was saved
133   in the history list.  Managed by maybe_add_history(), but global so
134   the history-manipluating builtins can see it. */
135int current_command_first_line_saved = 0;
136
137/* Non-zero means to store newlines in the history list when using
138   command_oriented_history rather than trying to use semicolons. */
139int literal_history;
140
141/* Non-zero means to append the history to the history file at shell
142   exit, even if the history has been stifled. */
143int force_append_history;
144
145/* A nit for picking at history saving.  Flags have the following values:
146
147   Value == 0 means save all lines parsed by the shell on the history.
148   Value & HC_IGNSPACE means save all lines that do not start with a space.
149   Value & HC_IGNDUPS means save all lines that do not match the last
150   line saved.
151   Value & HC_ERASEDUPS means to remove all other matching lines from the
152   history list before saving the latest line. */
153int history_control;
154
155/* Set to 1 if the last command was added to the history list successfully
156   as a separate history entry; set to 0 if the line was ignored or added
157   to a previous entry as part of command-oriented-history processing. */
158int hist_last_line_added;
159
160/* Set to 1 if builtins/history.def:push_history added the last history
161   entry. */
162int hist_last_line_pushed;
163
164#if defined (READLINE)
165/* If non-zero, and readline is being used, the user is offered the
166   chance to re-edit a failed history expansion. */
167int history_reediting;
168
169/* If non-zero, and readline is being used, don't directly execute a
170   line with history substitution.  Reload it into the editing buffer
171   instead and let the user further edit and confirm with a newline. */
172int hist_verify;
173
174#endif /* READLINE */
175
176/* Non-zero means to not save function definitions in the history list. */
177int dont_save_function_defs;
178
179/* Variables declared in other files used here. */
180extern int current_command_line_count;
181
182extern struct dstack dstack;
183
184static int bash_history_inhibit_expansion __P((char *, int));
185#if defined (READLINE)
186static void re_edit __P((char *));
187#endif
188static int history_expansion_p __P((char *));
189static int shell_comment __P((char *));
190static int should_expand __P((char *));
191static HIST_ENTRY *last_history_entry __P((void));
192static char *expand_histignore_pattern __P((char *));
193static int history_should_ignore __P((char *));
194
195/* Is the history expansion starting at string[i] one that should not
196   be expanded? */
197static int
198bash_history_inhibit_expansion (string, i)
199     char *string;
200     int i;
201{
202  /* The shell uses ! as a pattern negation character in globbing [...]
203     expressions, so let those pass without expansion. */
204  if (i > 0 && (string[i - 1] == '[') && member (']', string + i + 1))
205    return (1);
206  /* The shell uses ! as the indirect expansion character, so let those
207     expansions pass as well. */
208  else if (i > 1 && string[i - 1] == '{' && string[i - 2] == '$' &&
209	     member ('}', string + i + 1))
210    return (1);
211#if defined (EXTENDED_GLOB)
212  else if (extended_glob && i > 1 && string[i+1] == '(' && member (')', string + i + 2))
213    return (1);
214#endif
215  else
216    return (0);
217}
218
219void
220bash_initialize_history ()
221{
222  history_quotes_inhibit_expansion = 1;
223  history_search_delimiter_chars = ";&()|<>";
224  history_inhibit_expansion_function = bash_history_inhibit_expansion;
225#if defined (BANG_HISTORY)
226  sv_histchars ("histchars");
227#endif
228}
229
230void
231bash_history_reinit (interact)
232     int interact;
233{
234#if defined (BANG_HISTORY)
235  history_expansion = interact != 0;
236  history_expansion_inhibited = 1;
237#endif
238  remember_on_history = enable_history_list = interact != 0;
239  history_inhibit_expansion_function = bash_history_inhibit_expansion;
240}
241
242void
243bash_history_disable ()
244{
245  remember_on_history = 0;
246#if defined (BANG_HISTORY)
247  history_expansion_inhibited = 1;
248#endif
249}
250
251void
252bash_history_enable ()
253{
254  remember_on_history = 1;
255#if defined (BANG_HISTORY)
256  history_expansion_inhibited = 0;
257#endif
258  history_inhibit_expansion_function = bash_history_inhibit_expansion;
259  sv_history_control ("HISTCONTROL");
260  sv_histignore ("HISTIGNORE");
261}
262
263/* Load the history list from the history file. */
264void
265load_history ()
266{
267  char *hf;
268
269  /* Truncate history file for interactive shells which desire it.
270     Note that the history file is automatically truncated to the
271     size of HISTSIZE if the user does not explicitly set the size
272     differently. */
273  set_if_not ("HISTSIZE", "500");
274  sv_histsize ("HISTSIZE");
275
276  set_if_not ("HISTFILESIZE", get_string_value ("HISTSIZE"));
277  sv_histsize ("HISTFILESIZE");
278
279  /* Read the history in HISTFILE into the history list. */
280  hf = get_string_value ("HISTFILE");
281
282  if (hf && *hf && file_exists (hf))
283    {
284      read_history (hf);
285      using_history ();
286      history_lines_in_file = where_history ();
287    }
288}
289
290void
291bash_clear_history ()
292{
293  clear_history ();
294  history_lines_this_session = 0;
295}
296
297/* Delete and free the history list entry at offset I. */
298int
299bash_delete_histent (i)
300     int i;
301{
302  HIST_ENTRY *discard;
303
304  discard = remove_history (i);
305  if (discard)
306    free_history_entry (discard);
307  history_lines_this_session--;
308
309  return 1;
310}
311
312int
313bash_delete_last_history ()
314{
315  register int i;
316  HIST_ENTRY **hlist, *histent;
317  int r;
318
319  hlist = history_list ();
320  if (hlist == NULL)
321    return 0;
322
323  for (i = 0; hlist[i]; i++)
324    ;
325  i--;
326
327  /* History_get () takes a parameter that must be offset by history_base. */
328  histent = history_get (history_base + i);	/* Don't free this */
329  if (histent == NULL)
330    return 0;
331
332  r = bash_delete_histent (i);
333
334  if (where_history () > history_length)
335    history_set_pos (history_length);
336
337  return r;
338}
339
340#ifdef INCLUDE_UNUSED
341/* Write the existing history out to the history file. */
342void
343save_history ()
344{
345  char *hf;
346
347  hf = get_string_value ("HISTFILE");
348  if (hf && *hf && file_exists (hf))
349    {
350      /* Append only the lines that occurred this session to
351	 the history file. */
352      using_history ();
353
354      if (history_lines_this_session < where_history () || force_append_history)
355	append_history (history_lines_this_session, hf);
356      else
357	write_history (hf);
358      sv_histsize ("HISTFILESIZE");
359    }
360}
361#endif
362
363int
364maybe_append_history (filename)
365     char *filename;
366{
367  int fd, result;
368  struct stat buf;
369
370  result = EXECUTION_SUCCESS;
371  if (history_lines_this_session && (history_lines_this_session < where_history ()))
372    {
373      /* If the filename was supplied, then create it if necessary. */
374      if (stat (filename, &buf) == -1 && errno == ENOENT)
375	{
376	  fd = open (filename, O_WRONLY|O_CREAT, 0600);
377	  if (fd < 0)
378	    {
379	      builtin_error (_("%s: cannot create: %s"), filename, strerror (errno));
380	      return (EXECUTION_FAILURE);
381	    }
382	  close (fd);
383	}
384      result = append_history (history_lines_this_session, filename);
385      history_lines_in_file += history_lines_this_session;
386      history_lines_this_session = 0;
387    }
388  return (result);
389}
390
391/* If this is an interactive shell, then append the lines executed
392   this session to the history file. */
393int
394maybe_save_shell_history ()
395{
396  int result;
397  char *hf;
398
399  result = 0;
400  if (history_lines_this_session)
401    {
402      hf = get_string_value ("HISTFILE");
403
404      if (hf && *hf)
405	{
406	  /* If the file doesn't exist, then create it. */
407	  if (file_exists (hf) == 0)
408	    {
409	      int file;
410	      file = open (hf, O_CREAT | O_TRUNC | O_WRONLY, 0600);
411	      if (file != -1)
412		close (file);
413	    }
414
415	  /* Now actually append the lines if the history hasn't been
416	     stifled.  If the history has been stifled, rewrite the
417	     history file. */
418	  using_history ();
419	  if (history_lines_this_session <= where_history () || force_append_history)
420	    {
421	      result = append_history (history_lines_this_session, hf);
422	      history_lines_in_file += history_lines_this_session;
423	    }
424	  else
425	    {
426	      result = write_history (hf);
427	      history_lines_in_file = history_lines_this_session;
428	    }
429	  history_lines_this_session = 0;
430
431	  sv_histsize ("HISTFILESIZE");
432	}
433    }
434  return (result);
435}
436
437#if defined (READLINE)
438/* Tell readline () that we have some text for it to edit. */
439static void
440re_edit (text)
441     char *text;
442{
443  if (bash_input.type == st_stdin)
444    bash_re_edit (text);
445}
446#endif /* READLINE */
447
448/* Return 1 if this line needs history expansion. */
449static int
450history_expansion_p (line)
451     char *line;
452{
453  register char *s;
454
455  for (s = line; *s; s++)
456    if (*s == history_expansion_char || *s == history_subst_char)
457      return 1;
458  return 0;
459}
460
461/* Do pre-processing on LINE.  If PRINT_CHANGES is non-zero, then
462   print the results of expanding the line if there were any changes.
463   If there is an error, return NULL, otherwise the expanded line is
464   returned.  If ADDIT is non-zero the line is added to the history
465   list after history expansion.  ADDIT is just a suggestion;
466   REMEMBER_ON_HISTORY can veto, and does.
467   Right now this does history expansion. */
468char *
469pre_process_line (line, print_changes, addit)
470     char *line;
471     int print_changes, addit;
472{
473  char *history_value;
474  char *return_value;
475  int expanded;
476
477  return_value = line;
478  expanded = 0;
479
480#  if defined (BANG_HISTORY)
481  /* History expand the line.  If this results in no errors, then
482     add that line to the history if ADDIT is non-zero. */
483  if (!history_expansion_inhibited && history_expansion && history_expansion_p (line))
484    {
485      expanded = history_expand (line, &history_value);
486
487      if (expanded)
488	{
489	  if (print_changes)
490	    {
491	      if (expanded < 0)
492		internal_error ("%s", history_value);
493#if defined (READLINE)
494	      else if (hist_verify == 0 || expanded == 2)
495#else
496	      else
497#endif
498		fprintf (stderr, "%s\n", history_value);
499	    }
500
501	  /* If there was an error, return NULL. */
502	  if (expanded < 0 || expanded == 2)	/* 2 == print only */
503	    {
504#    if defined (READLINE)
505	      if (expanded == 2 && rl_dispatching == 0 && *history_value)
506#    else
507	      if (expanded == 2 && *history_value)
508#    endif /* !READLINE */
509		maybe_add_history (history_value);
510
511	      free (history_value);
512
513#    if defined (READLINE)
514	      /* New hack.  We can allow the user to edit the
515		 failed history expansion. */
516	      if (history_reediting && expanded < 0 && rl_done)
517		re_edit (line);
518#    endif /* READLINE */
519	      return ((char *)NULL);
520	    }
521
522#    if defined (READLINE)
523	  if (hist_verify && expanded == 1)
524	    {
525	      re_edit (history_value);
526	      return ((char *)NULL);
527	    }
528#    endif
529	}
530
531      /* Let other expansions know that return_value can be free'ed,
532	 and that a line has been added to the history list.  Note
533	 that we only add lines that have something in them. */
534      expanded = 1;
535      return_value = history_value;
536    }
537#  endif /* BANG_HISTORY */
538
539  if (addit && remember_on_history && *return_value)
540    maybe_add_history (return_value);
541
542#if 0
543  if (expanded == 0)
544    return_value = savestring (line);
545#endif
546
547  return (return_value);
548}
549
550/* Return 1 if the first non-whitespace character in LINE is a `#', indicating
551 * that the line is a shell comment. */
552static int
553shell_comment (line)
554     char *line;
555{
556  char *p;
557
558  for (p = line; p && *p && whitespace (*p); p++)
559    ;
560  return (p && *p == '#');
561}
562
563#ifdef INCLUDE_UNUSED
564/* Remove shell comments from LINE.  A `#' and anything after it is a comment.
565   This isn't really useful yet, since it doesn't handle quoting. */
566static char *
567filter_comments (line)
568     char *line;
569{
570  char *p;
571
572  for (p = line; p && *p && *p != '#'; p++)
573    ;
574  if (p && *p == '#')
575    *p = '\0';
576  return (line);
577}
578#endif
579
580/* Check LINE against what HISTCONTROL says to do.  Returns 1 if the line
581   should be saved; 0 if it should be discarded. */
582static int
583check_history_control (line)
584     char *line;
585{
586  HIST_ENTRY *temp;
587  int r;
588
589  if (history_control == 0)
590    return 1;
591
592  /* ignorespace or ignoreboth */
593  if ((history_control & HC_IGNSPACE) && *line == ' ')
594    return 0;
595
596  /* ignoredups or ignoreboth */
597  if (history_control & HC_IGNDUPS)
598    {
599      using_history ();
600      temp = previous_history ();
601
602      r = (temp == 0 || STREQ (temp->line, line) == 0);
603
604      using_history ();
605
606      if (r == 0)
607	return r;
608    }
609
610  return 1;
611}
612
613/* Remove all entries matching LINE from the history list.  Triggered when
614   HISTCONTROL includes `erasedups'. */
615static void
616hc_erasedups (line)
617     char *line;
618{
619  HIST_ENTRY *temp;
620  int r;
621
622  using_history ();
623  while (temp = previous_history ())
624    {
625      if (STREQ (temp->line, line))
626	{
627	  r = where_history ();
628	  remove_history (r);
629	}
630    }
631  using_history ();
632}
633
634/* Add LINE to the history list, handling possibly multi-line compound
635   commands.  We note whether or not we save the first line of each command
636   (which is usually the entire command and history entry), and don't add
637   the second and subsequent lines of a multi-line compound command if we
638   didn't save the first line.  We don't usually save shell comment lines in
639   compound commands in the history, because they could have the effect of
640   commenting out the rest of the command when the entire command is saved as
641   a single history entry (when COMMAND_ORIENTED_HISTORY is enabled).  If
642   LITERAL_HISTORY is set, we're saving lines in the history with embedded
643   newlines, so it's OK to save comment lines.  We also make sure to save
644   multiple-line quoted strings or other constructs. */
645void
646maybe_add_history (line)
647     char *line;
648{
649  hist_last_line_added = 0;
650
651  /* Don't use the value of history_control to affect the second
652     and subsequent lines of a multi-line command (old code did
653     this only when command_oriented_history is enabled). */
654  if (current_command_line_count > 1)
655    {
656      if (current_command_first_line_saved &&
657	  (literal_history || dstack.delimiter_depth != 0 || shell_comment (line) == 0))
658	bash_add_history (line);
659      return;
660    }
661
662  /* This is the first line of a (possible multi-line) command.  Note whether
663     or not we should save the first line and remember it. */
664  current_command_first_line_saved = check_add_history (line, 0);
665}
666
667/* Just check LINE against HISTCONTROL and HISTIGNORE and add it to the
668   history if it's OK.  Used by `history -s' as well as maybe_add_history().
669   Returns 1 if the line was saved in the history, 0 otherwise. */
670int
671check_add_history (line, force)
672     char *line;
673     int force;
674{
675  if (check_history_control (line) && history_should_ignore (line) == 0)
676    {
677      /* We're committed to saving the line.  If the user has requested it,
678	 remove other matching lines from the history. */
679      if (history_control & HC_ERASEDUPS)
680	hc_erasedups (line);
681
682      if (force)
683	{
684	  really_add_history (line);
685	  using_history ();
686	}
687      else
688	bash_add_history (line);
689      return 1;
690    }
691  return 0;
692}
693
694/* Add a line to the history list.
695   The variable COMMAND_ORIENTED_HISTORY controls the style of history
696   remembering;  when non-zero, and LINE is not the first line of a
697   complete parser construct, append LINE to the last history line instead
698   of adding it as a new line. */
699void
700bash_add_history (line)
701     char *line;
702{
703  int add_it, offset, curlen;
704  HIST_ENTRY *current, *old;
705  char *chars_to_add, *new_line;
706
707  add_it = 1;
708  if (command_oriented_history && current_command_line_count > 1)
709    {
710      chars_to_add = literal_history ? "\n" : history_delimiting_chars ();
711
712      using_history ();
713      current = previous_history ();
714
715      if (current)
716	{
717	  /* If the previous line ended with an escaped newline (escaped
718	     with backslash, but otherwise unquoted), then remove the quoted
719	     newline, since that is what happens when the line is parsed. */
720	  curlen = strlen (current->line);
721
722	  if (dstack.delimiter_depth == 0 && current->line[curlen - 1] == '\\' &&
723	      current->line[curlen - 2] != '\\')
724	    {
725	      current->line[curlen - 1] = '\0';
726	      curlen--;
727	      chars_to_add = "";
728	    }
729
730	  new_line = (char *)xmalloc (1
731				      + curlen
732				      + strlen (line)
733				      + strlen (chars_to_add));
734	  sprintf (new_line, "%s%s%s", current->line, chars_to_add, line);
735	  offset = where_history ();
736	  old = replace_history_entry (offset, new_line, current->data);
737	  free (new_line);
738
739	  if (old)
740	    free_history_entry (old);
741
742	  add_it = 0;
743	}
744    }
745
746  if (add_it)
747    really_add_history (line);
748
749  using_history ();
750}
751
752static void
753really_add_history (line)
754     char *line;
755{
756  hist_last_line_added = 1;
757  hist_last_line_pushed = 0;
758  add_history (line);
759  history_lines_this_session++;
760}
761
762int
763history_number ()
764{
765  using_history ();
766  return (remember_on_history ? history_base + where_history () : 1);
767}
768
769static int
770should_expand (s)
771     char *s;
772{
773  char *p;
774
775  for (p = s; p && *p; p++)
776    {
777      if (*p == '\\')
778	p++;
779      else if (*p == '&')
780	return 1;
781    }
782  return 0;
783}
784
785static int
786histignore_item_func (ign)
787     struct ign *ign;
788{
789  if (should_expand (ign->val))
790    ign->flags |= HIGN_EXPAND;
791  return (0);
792}
793
794void
795setup_history_ignore (varname)
796     char *varname;
797{
798  setup_ignore_patterns (&histignore);
799}
800
801static HIST_ENTRY *
802last_history_entry ()
803{
804  HIST_ENTRY *he;
805
806  using_history ();
807  he = previous_history ();
808  using_history ();
809  return he;
810}
811
812char *
813last_history_line ()
814{
815  HIST_ENTRY *he;
816
817  he = last_history_entry ();
818  if (he == 0)
819    return ((char *)NULL);
820  return he->line;
821}
822
823static char *
824expand_histignore_pattern (pat)
825     char *pat;
826{
827  HIST_ENTRY *phe;
828  char *ret;
829
830  phe = last_history_entry ();
831
832  if (phe == (HIST_ENTRY *)0)
833    return (savestring (pat));
834
835  ret = strcreplace (pat, '&', phe->line, 1);
836
837  return ret;
838}
839
840/* Return 1 if we should not put LINE into the history according to the
841   patterns in HISTIGNORE. */
842static int
843history_should_ignore (line)
844     char *line;
845{
846  register int i, match;
847  char *npat;
848
849  if (histignore.num_ignores == 0)
850    return 0;
851
852  for (i = match = 0; i < histignore.num_ignores; i++)
853    {
854      if (histignore.ignores[i].flags & HIGN_EXPAND)
855	npat = expand_histignore_pattern (histignore.ignores[i].val);
856      else
857	npat = histignore.ignores[i].val;
858
859      match = strmatch (npat, line, FNMATCH_EXTFLAG) != FNM_NOMATCH;
860
861      if (histignore.ignores[i].flags & HIGN_EXPAND)
862	free (npat);
863
864      if (match)
865	break;
866    }
867
868  return match;
869}
870#endif /* HISTORY */
871