Sync readline/ to version 7.0 alpha
[deliverable/binutils-gdb.git] / readline / histfile.c
1 /* histfile.c - functions to manipulate the history file. */
2
3 /* Copyright (C) 1989-2015 Free Software Foundation, Inc.
4
5 This file contains the GNU History Library (History), a set of
6 routines for managing the text of previously typed lines.
7
8 History is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 History is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with History. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 /* The goal is to make the implementation transparent, so that you
23 don't have to know what data types are used, just what functions
24 you can call. I think I have done that. */
25
26 #define READLINE_LIBRARY
27
28 #if defined (__TANDEM)
29 # include <floss.h>
30 #endif
31
32 #if defined (HAVE_CONFIG_H)
33 # include <config.h>
34 #endif
35
36 #include <stdio.h>
37
38 #if defined (HAVE_LIMITS_H)
39 # include <limits.h>
40 #endif
41
42 #include <sys/types.h>
43 #if ! defined (_MINIX) && defined (HAVE_SYS_FILE_H)
44 # include <sys/file.h>
45 #endif
46 #include "posixstat.h"
47 #include <fcntl.h>
48
49 #if defined (HAVE_STDLIB_H)
50 # include <stdlib.h>
51 #else
52 # include "ansi_stdlib.h"
53 #endif /* HAVE_STDLIB_H */
54
55 #if defined (HAVE_UNISTD_H)
56 # include <unistd.h>
57 #endif
58
59 #include <ctype.h>
60
61 #if defined (__EMX__)
62 # undef HAVE_MMAP
63 #endif
64
65 #ifdef HISTORY_USE_MMAP
66 # include <sys/mman.h>
67
68 # ifdef MAP_FILE
69 # define MAP_RFLAGS (MAP_FILE|MAP_PRIVATE)
70 # define MAP_WFLAGS (MAP_FILE|MAP_SHARED)
71 # else
72 # define MAP_RFLAGS MAP_PRIVATE
73 # define MAP_WFLAGS MAP_SHARED
74 # endif
75
76 # ifndef MAP_FAILED
77 # define MAP_FAILED ((void *)-1)
78 # endif
79
80 #endif /* HISTORY_USE_MMAP */
81
82 /* If we're compiling for __EMX__ (OS/2) or __CYGWIN__ (cygwin32 environment
83 on win 95/98/nt), we want to open files with O_BINARY mode so that there
84 is no \n -> \r\n conversion performed. On other systems, we don't want to
85 mess around with O_BINARY at all, so we ensure that it's defined to 0. */
86 #if defined (__EMX__) || defined (__CYGWIN__)
87 # ifndef O_BINARY
88 # define O_BINARY 0
89 # endif
90 #else /* !__EMX__ && !__CYGWIN__ */
91 # undef O_BINARY
92 # define O_BINARY 0
93 #endif /* !__EMX__ && !__CYGWIN__ */
94
95 #include <errno.h>
96 #if !defined (errno)
97 extern int errno;
98 #endif /* !errno */
99
100 #include "history.h"
101 #include "histlib.h"
102
103 #include "rlshell.h"
104 #include "xmalloc.h"
105
106 #if !defined (PATH_MAX)
107 # define PATH_MAX 1024 /* default */
108 #endif
109
110 /* If non-zero, we write timestamps to the history file in history_do_write() */
111 int history_write_timestamps = 0;
112
113 /* Immediately after a call to read_history() or read_history_range(), this
114 will return the number of lines just read from the history file in that
115 call. */
116 int history_lines_read_from_file = 0;
117
118 /* Immediately after a call to write_history() or history_do_write(), this
119 will return the number of lines just written to the history file in that
120 call. This also works with history_truncate_file. */
121 int history_lines_written_to_file = 0;
122
123 /* Does S look like the beginning of a history timestamp entry? Placeholder
124 for more extensive tests. */
125 #define HIST_TIMESTAMP_START(s) (*(s) == history_comment_char && isdigit ((unsigned char)(s)[1]) )
126
127 static char *history_backupfile PARAMS((const char *));
128 static char *history_tempfile PARAMS((const char *));
129 static int histfile_backup PARAMS((const char *, const char *));
130 static int histfile_restore PARAMS((const char *, const char *));
131
132 /* Return the string that should be used in the place of this
133 filename. This only matters when you don't specify the
134 filename to read_history (), or write_history (). */
135 static char *
136 history_filename (filename)
137 const char *filename;
138 {
139 char *return_val;
140 const char *home;
141 int home_len;
142
143 return_val = filename ? savestring (filename) : (char *)NULL;
144
145 if (return_val)
146 return (return_val);
147
148 home = sh_get_env_value ("HOME");
149 #if defined (_WIN32)
150 if (home == 0)
151 home = sh_get_env_value ("APPDATA");
152 #endif
153
154 if (home == 0)
155 return (NULL);
156 else
157 home_len = strlen (home);
158
159 return_val = (char *)xmalloc (2 + home_len + 8); /* strlen(".history") == 8 */
160 strcpy (return_val, home);
161 return_val[home_len] = '/';
162 #if defined (__MSDOS__)
163 strcpy (return_val + home_len + 1, "_history");
164 #else
165 strcpy (return_val + home_len + 1, ".history");
166 #endif
167
168 return (return_val);
169 }
170
171 static char *
172 history_backupfile (filename)
173 const char *filename;
174 {
175 const char *fn;
176 char *ret, linkbuf[PATH_MAX+1];
177 size_t len;
178 ssize_t n;
179 struct stat fs;
180
181 fn = filename;
182 #if defined (HAVE_READLINK)
183 /* Follow symlink to avoid backing up symlink itself; call will fail if
184 not a symlink */
185 if ((n = readlink (filename, linkbuf, sizeof (linkbuf) - 1)) > 0)
186 {
187 linkbuf[n] = '\0';
188 fn = linkbuf;
189 }
190 #endif
191
192 len = strlen (fn);
193 ret = xmalloc (len + 2);
194 strcpy (ret, fn);
195 ret[len] = '-';
196 ret[len+1] = '\0';
197 return ret;
198 }
199
200 static char *
201 history_tempfile (filename)
202 const char *filename;
203 {
204 const char *fn;
205 char *ret, linkbuf[PATH_MAX+1];
206 size_t len;
207 ssize_t n;
208 struct stat fs;
209 int pid;
210
211 fn = filename;
212 #if defined (HAVE_READLINK)
213 /* Follow symlink so tempfile created in the same directory as any symlinked
214 history file; call will fail if not a symlink */
215 if ((n = readlink (filename, linkbuf, sizeof (linkbuf) - 1)) > 0)
216 {
217 linkbuf[n] = '\0';
218 fn = linkbuf;
219 }
220 #endif
221
222 len = strlen (fn);
223 ret = xmalloc (len + 11);
224 strcpy (ret, fn);
225
226 pid = (int)getpid ();
227
228 /* filename-PID.tmp */
229 ret[len] = '-';
230 ret[len+1] = (pid / 10000 % 10) + '0';
231 ret[len+2] = (pid / 1000 % 10) + '0';
232 ret[len+3] = (pid / 100 % 10) + '0';
233 ret[len+4] = (pid / 10 % 10) + '0';
234 ret[len+5] = (pid % 10) + '0';
235 strcpy (ret + len + 6, ".tmp");
236
237 return ret;
238 }
239
240 /* Add the contents of FILENAME to the history list, a line at a time.
241 If FILENAME is NULL, then read from ~/.history. Returns 0 if
242 successful, or errno if not. */
243 int
244 read_history (filename)
245 const char *filename;
246 {
247 return (read_history_range (filename, 0, -1));
248 }
249
250 /* Read a range of lines from FILENAME, adding them to the history list.
251 Start reading at the FROM'th line and end at the TO'th. If FROM
252 is zero, start at the beginning. If TO is less than FROM, read
253 until the end of the file. If FILENAME is NULL, then read from
254 ~/.history. Returns 0 if successful, or errno if not. */
255 int
256 read_history_range (filename, from, to)
257 const char *filename;
258 int from, to;
259 {
260 register char *line_start, *line_end, *p;
261 char *input, *buffer, *bufend, *last_ts;
262 int file, current_line, chars_read;
263 struct stat finfo;
264 size_t file_size;
265 #if defined (EFBIG)
266 int overflow_errno = EFBIG;
267 #elif defined (EOVERFLOW)
268 int overflow_errno = EOVERFLOW;
269 #else
270 int overflow_errno = EIO;
271 #endif
272
273 history_lines_read_from_file = 0;
274
275 buffer = last_ts = (char *)NULL;
276 input = history_filename (filename);
277 file = input ? open (input, O_RDONLY|O_BINARY, 0666) : -1;
278
279 if ((file < 0) || (fstat (file, &finfo) == -1))
280 goto error_and_exit;
281
282 file_size = (size_t)finfo.st_size;
283
284 /* check for overflow on very large files */
285 if (file_size != finfo.st_size || file_size + 1 < file_size)
286 {
287 errno = overflow_errno;
288 goto error_and_exit;
289 }
290
291 #ifdef HISTORY_USE_MMAP
292 /* We map read/write and private so we can change newlines to NULs without
293 affecting the underlying object. */
294 buffer = (char *)mmap (0, file_size, PROT_READ|PROT_WRITE, MAP_RFLAGS, file, 0);
295 if ((void *)buffer == MAP_FAILED)
296 {
297 errno = overflow_errno;
298 goto error_and_exit;
299 }
300 chars_read = file_size;
301 #else
302 buffer = (char *)malloc (file_size + 1);
303 if (buffer == 0)
304 {
305 errno = overflow_errno;
306 goto error_and_exit;
307 }
308
309 chars_read = read (file, buffer, file_size);
310 #endif
311 if (chars_read < 0)
312 {
313 error_and_exit:
314 if (errno != 0)
315 chars_read = errno;
316 else
317 chars_read = EIO;
318 if (file >= 0)
319 close (file);
320
321 FREE (input);
322 #ifndef HISTORY_USE_MMAP
323 FREE (buffer);
324 #endif
325
326 return (chars_read);
327 }
328
329 close (file);
330
331 /* Set TO to larger than end of file if negative. */
332 if (to < 0)
333 to = chars_read;
334
335 /* Start at beginning of file, work to end. */
336 bufend = buffer + chars_read;
337 current_line = 0;
338
339 /* Skip lines until we are at FROM. */
340 for (line_start = line_end = buffer; line_end < bufend && current_line < from; line_end++)
341 if (*line_end == '\n')
342 {
343 p = line_end + 1;
344 /* If we see something we think is a timestamp, continue with this
345 line. We should check more extensively here... */
346 if (HIST_TIMESTAMP_START(p) == 0)
347 current_line++;
348 line_start = p;
349 }
350
351 /* If there are lines left to gobble, then gobble them now. */
352 for (line_end = line_start; line_end < bufend; line_end++)
353 if (*line_end == '\n')
354 {
355 /* Change to allow Windows-like \r\n end of line delimiter. */
356 if (line_end > line_start && line_end[-1] == '\r')
357 line_end[-1] = '\0';
358 else
359 *line_end = '\0';
360
361 if (*line_start)
362 {
363 if (HIST_TIMESTAMP_START(line_start) == 0)
364 {
365 add_history (line_start);
366 if (last_ts)
367 {
368 add_history_time (last_ts);
369 last_ts = NULL;
370 }
371 }
372 else
373 {
374 last_ts = line_start;
375 current_line--;
376 }
377 }
378
379 current_line++;
380
381 if (current_line >= to)
382 break;
383
384 line_start = line_end + 1;
385 }
386
387 history_lines_read_from_file = current_line;
388
389 FREE (input);
390 #ifndef HISTORY_USE_MMAP
391 FREE (buffer);
392 #else
393 munmap (buffer, file_size);
394 #endif
395
396 return (0);
397 }
398
399 /* Save FILENAME to BACK, handling case where FILENAME is a symlink
400 (e.g., ~/.bash_history -> .histfiles/.bash_history.$HOSTNAME) */
401 static int
402 histfile_backup (filename, back)
403 const char *filename;
404 const char *back;
405 {
406 #if defined (HAVE_READLINK)
407 char linkbuf[PATH_MAX+1];
408 ssize_t n;
409
410 /* Follow to target of symlink to avoid renaming symlink itself */
411 if ((n = readlink (filename, linkbuf, sizeof (linkbuf) - 1)) > 0)
412 {
413 linkbuf[n] = '\0';
414 return (rename (linkbuf, back));
415 }
416 #endif
417 return (rename (filename, back));
418 }
419
420 /* Restore ORIG from BACKUP handling case where ORIG is a symlink
421 (e.g., ~/.bash_history -> .histfiles/.bash_history.$HOSTNAME) */
422 static int
423 histfile_restore (backup, orig)
424 const char *backup;
425 const char *orig;
426 {
427 #if defined (HAVE_READLINK)
428 char linkbuf[PATH_MAX+1];
429 ssize_t n;
430
431 /* Follow to target of symlink to avoid renaming symlink itself */
432 if ((n = readlink (orig, linkbuf, sizeof (linkbuf) - 1)) > 0)
433 {
434 linkbuf[n] = '\0';
435 return (rename (backup, linkbuf));
436 }
437 #endif
438 return (rename (backup, orig));
439 }
440
441 /* Truncate the history file FNAME, leaving only LINES trailing lines.
442 If FNAME is NULL, then use ~/.history. Writes a new file and renames
443 it to the original name. Returns 0 on success, errno on failure. */
444 int
445 history_truncate_file (fname, lines)
446 const char *fname;
447 int lines;
448 {
449 char *buffer, *filename, *tempname, *bp, *bp1; /* bp1 == bp+1 */
450 int file, chars_read, rv, orig_lines, exists;
451 struct stat finfo;
452 size_t file_size;
453
454 history_lines_written_to_file = 0;
455
456 buffer = (char *)NULL;
457 filename = history_filename (fname);
458 tempname = 0;
459 file = filename ? open (filename, O_RDONLY|O_BINARY, 0666) : -1;
460 rv = exists = 0;
461
462 /* Don't try to truncate non-regular files. */
463 if (file == -1 || fstat (file, &finfo) == -1)
464 {
465 rv = errno;
466 if (file != -1)
467 close (file);
468 goto truncate_exit;
469 }
470 exists = 1;
471
472 if (S_ISREG (finfo.st_mode) == 0)
473 {
474 close (file);
475 #ifdef EFTYPE
476 rv = EFTYPE;
477 #else
478 rv = EINVAL;
479 #endif
480 goto truncate_exit;
481 }
482
483 file_size = (size_t)finfo.st_size;
484
485 /* check for overflow on very large files */
486 if (file_size != finfo.st_size || file_size + 1 < file_size)
487 {
488 close (file);
489 #if defined (EFBIG)
490 rv = errno = EFBIG;
491 #elif defined (EOVERFLOW)
492 rv = errno = EOVERFLOW;
493 #else
494 rv = errno = EINVAL;
495 #endif
496 goto truncate_exit;
497 }
498
499 buffer = (char *)malloc (file_size + 1);
500 if (buffer == 0)
501 {
502 rv = errno;
503 close (file);
504 goto truncate_exit;
505 }
506
507 chars_read = read (file, buffer, file_size);
508 close (file);
509
510 if (chars_read <= 0)
511 {
512 rv = (chars_read < 0) ? errno : 0;
513 goto truncate_exit;
514 }
515
516 orig_lines = lines;
517 /* Count backwards from the end of buffer until we have passed
518 LINES lines. bp1 is set funny initially. But since bp[1] can't
519 be a comment character (since it's off the end) and *bp can't be
520 both a newline and the history comment character, it should be OK. */
521 for (bp1 = bp = buffer + chars_read - 1; lines && bp > buffer; bp--)
522 {
523 if (*bp == '\n' && HIST_TIMESTAMP_START(bp1) == 0)
524 lines--;
525 bp1 = bp;
526 }
527
528 /* If this is the first line, then the file contains exactly the
529 number of lines we want to truncate to, so we don't need to do
530 anything. It's the first line if we don't find a newline between
531 the current value of i and 0. Otherwise, write from the start of
532 this line until the end of the buffer. */
533 for ( ; bp > buffer; bp--)
534 {
535 if (*bp == '\n' && HIST_TIMESTAMP_START(bp1) == 0)
536 {
537 bp++;
538 break;
539 }
540 bp1 = bp;
541 }
542
543 /* Write only if there are more lines in the file than we want to
544 truncate to. */
545 if (bp <= buffer)
546 {
547 rv = 0;
548 /* No-op if LINES == 0 at this point */
549 history_lines_written_to_file = orig_lines - lines;
550 goto truncate_exit;
551 }
552
553 tempname = history_tempfile (filename);
554
555 if ((file = open (tempname, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0600)) != -1)
556 {
557 if (write (file, bp, chars_read - (bp - buffer)) < 0)
558 rv = errno;
559
560 if (close (file) < 0 && rv == 0)
561 rv = errno;
562 }
563 else
564 rv = errno;
565
566 truncate_exit:
567 FREE (buffer);
568
569 history_lines_written_to_file = orig_lines - lines;
570
571 if (rv == 0 && filename && tempname)
572 rv = histfile_restore (tempname, filename);
573
574 if (rv != 0)
575 {
576 if (tempname)
577 unlink (tempname);
578 history_lines_written_to_file = 0;
579 }
580
581 /* Make sure the new filename is owned by the same user as the old. If one
582 user is running this, it's a no-op. If the shell is running after sudo
583 with a shared history file, we don't want to leave the history file
584 owned by root. */
585 if (rv == 0 && exists)
586 chown (filename, finfo.st_uid, finfo.st_gid);
587
588 xfree (filename);
589 FREE (tempname);
590
591 return rv;
592 }
593
594 /* Workhorse function for writing history. Writes the last NELEMENT entries
595 from the history list to FILENAME. OVERWRITE is non-zero if you
596 wish to replace FILENAME with the entries. */
597 static int
598 history_do_write (filename, nelements, overwrite)
599 const char *filename;
600 int nelements, overwrite;
601 {
602 register int i;
603 char *output, *tempname, *histname;
604 int file, mode, rv, exists;
605 struct stat finfo;
606 #ifdef HISTORY_USE_MMAP
607 size_t cursize;
608
609 history_lines_written_to_file = 0;
610
611 mode = overwrite ? O_RDWR|O_CREAT|O_TRUNC|O_BINARY : O_RDWR|O_APPEND|O_BINARY;
612 #else
613 mode = overwrite ? O_WRONLY|O_CREAT|O_TRUNC|O_BINARY : O_WRONLY|O_APPEND|O_BINARY;
614 #endif
615 histname = history_filename (filename);
616 tempname = (overwrite && histname) ? history_tempfile (histname) : 0;
617 output = tempname ? tempname : histname;
618 exists = histname ? (stat (histname, &finfo) == 0) : 0;
619
620 file = output ? open (output, mode, 0600) : -1;
621 rv = 0;
622
623 if (file == -1)
624 {
625 rv = errno;
626 FREE (histname);
627 FREE (tempname);
628 return (rv);
629 }
630
631 #ifdef HISTORY_USE_MMAP
632 cursize = overwrite ? 0 : lseek (file, 0, SEEK_END);
633 #endif
634
635 if (nelements > history_length)
636 nelements = history_length;
637
638 /* Build a buffer of all the lines to write, and write them in one syscall.
639 Suggested by Peter Ho (peter@robosts.oxford.ac.uk). */
640 {
641 HIST_ENTRY **the_history; /* local */
642 register int j;
643 int buffer_size;
644 char *buffer;
645
646 the_history = history_list ();
647 /* Calculate the total number of bytes to write. */
648 for (buffer_size = 0, i = history_length - nelements; i < history_length; i++)
649 #if 0
650 buffer_size += 2 + HISTENT_BYTES (the_history[i]);
651 #else
652 {
653 if (history_write_timestamps && the_history[i]->timestamp && the_history[i]->timestamp[0])
654 buffer_size += strlen (the_history[i]->timestamp) + 1;
655 buffer_size += strlen (the_history[i]->line) + 1;
656 }
657 #endif
658
659 /* Allocate the buffer, and fill it. */
660 #ifdef HISTORY_USE_MMAP
661 if (ftruncate (file, buffer_size+cursize) == -1)
662 goto mmap_error;
663 buffer = (char *)mmap (0, buffer_size, PROT_READ|PROT_WRITE, MAP_WFLAGS, file, cursize);
664 if ((void *)buffer == MAP_FAILED)
665 {
666 mmap_error:
667 rv = errno;
668 close (file);
669 if (tempname)
670 unlink (tempname);
671 FREE (histname);
672 FREE (tempname);
673 return rv;
674 }
675 #else
676 buffer = (char *)malloc (buffer_size);
677 if (buffer == 0)
678 {
679 rv = errno;
680 close (file);
681 if (tempname)
682 unlink (tempname);
683 FREE (histname);
684 FREE (tempname);
685 return rv;
686 }
687 #endif
688
689 for (j = 0, i = history_length - nelements; i < history_length; i++)
690 {
691 if (history_write_timestamps && the_history[i]->timestamp && the_history[i]->timestamp[0])
692 {
693 strcpy (buffer + j, the_history[i]->timestamp);
694 j += strlen (the_history[i]->timestamp);
695 buffer[j++] = '\n';
696 }
697 strcpy (buffer + j, the_history[i]->line);
698 j += strlen (the_history[i]->line);
699 buffer[j++] = '\n';
700 }
701
702 #ifdef HISTORY_USE_MMAP
703 if (msync (buffer, buffer_size, MS_ASYNC) != 0 || munmap (buffer, buffer_size) != 0)
704 rv = errno;
705 #else
706 if (write (file, buffer, buffer_size) < 0)
707 rv = errno;
708 xfree (buffer);
709 #endif
710 }
711
712 history_lines_written_to_file = nelements;
713
714 if (close (file) < 0 && rv == 0)
715 rv = errno;
716
717 if (rv == 0 && histname && tempname)
718 rv = histfile_restore (tempname, histname);
719
720 if (rv != 0)
721 {
722 if (tempname)
723 unlink (tempname);
724 history_lines_written_to_file = 0;
725 }
726
727 /* Make sure the new filename is owned by the same user as the old. If one
728 user is running this, it's a no-op. If the shell is running after sudo
729 with a shared history file, we don't want to leave the history file
730 owned by root. */
731 if (rv == 0 && exists)
732 chown (histname, finfo.st_uid, finfo.st_gid);
733
734 FREE (histname);
735 FREE (tempname);
736
737 return (rv);
738 }
739
740 /* Append NELEMENT entries to FILENAME. The entries appended are from
741 the end of the list minus NELEMENTs up to the end of the list. */
742 int
743 append_history (nelements, filename)
744 int nelements;
745 const char *filename;
746 {
747 return (history_do_write (filename, nelements, HISTORY_APPEND));
748 }
749
750 /* Overwrite FILENAME with the current history. If FILENAME is NULL,
751 then write the history list to ~/.history. Values returned
752 are as in read_history ().*/
753 int
754 write_history (filename)
755 const char *filename;
756 {
757 return (history_do_write (filename, history_length, HISTORY_OVERWRITE));
758 }
This page took 0.054827 seconds and 4 git commands to generate.