-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathhistory.c
1891 lines (1684 loc) · 54.6 KB
/
history.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Yash: yet another shell */
/* history.c: command history management */
/* (C) 2007-2021 magicant */
/* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include "common.h"
#include "history.h"
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#if HAVE_GETTEXT
# include <libintl.h>
#endif
#include <limits.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <wchar.h>
#include <wctype.h>
#include "builtin.h"
#include "exec.h"
#include "job.h"
#include "option.h"
#include "path.h"
#include "redir.h"
#include "sig.h"
#include "strbuf.h"
#include "util.h"
#include "variable.h"
#include "yash.h"
/* The maximum size of history list (<= INT_MAX / 10) */
#ifndef MAX_HISTSIZE
#define MAX_HISTSIZE 1000000
#endif
#if MAX_HISTSIZE > INT_MAX / 10
#error MAX_HISTSIZE is too large
#endif
/* The minimum value of `max_number',
* which must be at least 32768 according to POSIX. */
/* Must be a power of 10. */
#ifndef HISTORY_MIN_MAX_NUMBER
#define HISTORY_MIN_MAX_NUMBER 100000
#endif
#if HISTORY_MIN_MAX_NUMBER < 32768
#error HISTORY_MIN_MAX_NUMBER is too small
#endif
/* The default size of the history list,
* which must be at least 128 according to POSIX. */
#ifndef DEFAULT_HISTSIZE
#define DEFAULT_HISTSIZE 500
#endif
#if DEFAULT_HISTSIZE < 128
#error DEFAULT_HISTSIZE is too small
#endif
#if DEFAULT_HISTSIZE > HISTORY_MIN_MAX_NUMBER
#error DEFAULT_HISTSIZE cannot be larger than HISTORY_MIN_MAX_NUMBER
#endif
#ifndef HISTORY_DEFAULT_LINE_LENGTH
#define HISTORY_DEFAULT_LINE_LENGTH 127
#endif
/* The main history list. */
histlist_T histlist = {
.link = { Histlist, Histlist, },
.count = 0,
};
/* History entries are stored in this doubly-linked list.
* The `Newest' (`link.prev') member points to the newest entry and the `Oldest'
* (`link.next') member points to the oldest entry. When there's no entries,
* `Newest' and `Oldest' point to `histlist' itself. */
/* The maximum limit of the number of an entry.
* Must always be no less than `histsize' or `HISTORY_MIN_MAX_NUMBER'.
* The number of any entry is not greater than this value. */
static unsigned max_number = HISTORY_MIN_MAX_NUMBER;
/* The size limit of the history list. */
static unsigned histsize = DEFAULT_HISTSIZE;
/* When a new entry is added, if there are entries that has the same value as
* the new entry in the `histrmdup' newest entries, those entries are removed.*/
static unsigned histrmdup = 0;
/* File stream for the history file. */
static FILE *histfile = NULL;
/* The revision number of the history file. A valid revision number is
* non-negative. */
static long histfilerev = -1;
/* The number of lines in the history file, not including the signature.
* When this number reaches the threshold, the history file is refreshed. */
static size_t histfilelines = 0;
/* Indicates if the history file should be flushed before it is unlocked. */
static bool histneedflush = false;
/* The current time returned by `time' */
static time_t now = (time_t) -1;
/* If true, the history is locked, that is, readonly. */
static bool hist_lock = false;
struct search_result_T {
histlink_T *prev, *next;
};
static void update_time(void);
static void set_histsize(unsigned newsize);
static histentry_T *new_entry(unsigned number, time_t time, const char *line)
__attribute__((nonnull));
static bool need_remove_entry(unsigned number)
__attribute__((pure));
static void remove_entry(histentry_T *e)
__attribute__((nonnull));
static void remove_last_entry(void);
static void clear_all_entries(void);
static struct search_result_T search_entry_by_number(unsigned number)
__attribute__((pure));
static histlink_T *get_nth_newest_entry(unsigned n)
__attribute__((pure));
static histlink_T *search_entry_by_prefix(const char *prefix)
__attribute__((nonnull,pure));
static bool search_result_is_newer(
struct search_result_T sr1, struct search_result_T sr2)
__attribute__((pure));
static bool entry_is_newer(const histentry_T *e1, const histentry_T *e2)
__attribute__((nonnull,pure));
static void add_histfile_pid(pid_t pid);
static void remove_histfile_pid(pid_t pid);
static void clear_histfile_pids(void);
static void write_histfile_pids(void);
static FILE *open_histfile(void);
static bool lock_histfile(short type);
static bool read_line(FILE *restrict f, xwcsbuf_T *restrict buf)
__attribute__((nonnull));
static bool try_read_line(FILE *restrict f, xwcsbuf_T *restrict buf)
__attribute__((nonnull));
static long read_signature(void);
static void read_history_raw(void);
static void read_history(void);
static void parse_history_entry(const wchar_t *line)
__attribute__((nonnull));
static void parse_removed_entry(const wchar_t *numstr)
__attribute__((nonnull));
static void parse_process_id(const wchar_t *numstr)
__attribute__((nonnull));
static void update_history(bool refresh);
static void maybe_refresh_file(void);
static int wprintf_histfile(const wchar_t *format, ...)
__attribute__((nonnull));
static void write_signature(void);
static void write_history_entry(const histentry_T *entry)
__attribute__((nonnull));
static void refresh_file(void);
static void add_history_line(const wchar_t *line, size_t maxlen)
__attribute__((nonnull));
static void remove_duplicates(const char *line)
__attribute__((nonnull));
/* Updates the value of `now'. */
void update_time(void)
{
now = time(NULL);
}
/* Changes `histsize' to `newsize' and accordingly sets `max_number'. */
/* `histsize' is set only once in initialization. */
void set_histsize(unsigned newsize)
{
if (newsize > MAX_HISTSIZE)
newsize = MAX_HISTSIZE;
if (newsize == 0)
newsize = 1;
histsize = newsize;
max_number = HISTORY_MIN_MAX_NUMBER;
while (max_number < 2 * histsize)
max_number *= 10;
/* `max_number' is the smallest power of 10 that is not less than
* 2 * histsize. */
}
/* Adds a new history entry to the end of `histlist'.
* Some oldest entries may be removed in this function if they conflict with the
* new one or the list is full. */
histentry_T *new_entry(unsigned number, time_t time, const char *line)
{
assert(!hist_lock);
assert(number > 0);
assert(number <= max_number);
while (need_remove_entry(number))
remove_entry(ashistentry(histlist.Oldest));
histentry_T *new = xmallocs(sizeof *new,
add(strlen(line), 1), sizeof *new->value);
new->Prev = histlist.Newest;
new->Next = Histlist;
histlist.Newest = new->Prev->next = &new->link;
new->number = number;
new->time = time;
strcpy(new->value, line);
histlist.count++;
assert(histlist.count <= histsize);
return new;
}
bool need_remove_entry(unsigned number)
{
if (histlist.count == 0)
return false;
if (histlist.count >= histsize)
return true;
unsigned oldest = ashistentry(histlist.Oldest)->number;
unsigned newest = ashistentry(histlist.Newest)->number;
if (oldest <= newest)
return oldest <= number && number <= newest;
else
return oldest <= number || number <= newest;
}
/* Removes the specified entry from `histlist'. */
void remove_entry(histentry_T *entry)
{
assert(!hist_lock);
assert(&entry->link != Histlist);
entry->Prev->next = entry->Next;
entry->Next->prev = entry->Prev;
histlist.count--;
free(entry);
}
/* Removes the newest entry. */
void remove_last_entry(void)
{
if (histlist.count > 0)
remove_entry(ashistentry(histlist.Newest));
}
/* Renumbers all the entries in `histlist', starting from 1. */
void renumber_all_entries(void)
{
assert(!hist_lock);
if (histlist.count > 0) {
unsigned num = 0;
for (histlink_T *l = histlist.Oldest; l != Histlist; l = l->next)
ashistentry(l)->number = ++num;
assert(num == histlist.count);
}
}
/* Removes all entries in the history list. */
void clear_all_entries(void)
{
assert(!hist_lock);
histlink_T *l = histlist.Oldest;
while (l != Histlist) {
histlink_T *next = l->next;
free(ashistentry(l));
l = next;
}
histlist.Oldest = histlist.Newest = Histlist;
histlist.count = 0;
}
/* Searches for the entry that has the specified `number'.
* If there is such an entry in the history, the both members of the returned
* `search_result_T' structure will be pointers to the entry. Otherwise, the
* returned structure will contain pointers to the nearest neighbor entries.
* (If there is not the neighbor in either direction, the pointer will be
* `Histlist'.) */
struct search_result_T search_entry_by_number(unsigned number)
{
struct search_result_T result;
if (histlist.count == 0) {
result.prev = result.next = Histlist;
return result;
}
unsigned oldestnum = ashistentry(histlist.Oldest)->number;
unsigned nnewestnum = ashistentry(histlist.Newest)->number;
unsigned nnumber = number;
if (nnewestnum < oldestnum) {
if (nnumber <= nnewestnum)
nnumber += max_number;
nnewestnum += max_number;
}
if (nnumber < oldestnum) {
result.prev = Histlist;
result.next = histlist.Oldest;
return result;
} else if (nnumber > nnewestnum) {
result.prev = histlist.Newest;
result.next = Histlist;
return result;
}
histlink_T *l;
if (2 * (nnumber - oldestnum) < nnewestnum - oldestnum) {
/* search from the oldest */
l = histlist.Oldest;
while (number < ashistentry(l)->number)
l = l->next;
while (number > ashistentry(l)->number)
l = l->next;
result.next = l;
if (number != ashistentry(l)->number)
l = l->prev;
result.prev = l;
} else {
/* search from the newest */
l = histlist.Newest;
while (number > ashistentry(l)->number)
l = l->prev;
while (number < ashistentry(l)->number)
l = l->prev;
result.prev = l;
if (number != ashistentry(l)->number)
l = l->next;
result.next = l;
}
return result;
}
/* Returns the nth newest entry (or the oldest entry if `n' is too big).
* Returns `Histlist' if `n' is zero or the history is empty. */
histlink_T *get_nth_newest_entry(unsigned n)
{
if (histlist.count <= n)
return histlist.Oldest;
histlink_T *l = Histlist;
while (n-- > 0)
l = l->prev;
return l;
}
/* Searches for the newest entry whose value begins with the specified `prefix'.
* Returns `Histlist' if not found. */
histlink_T *search_entry_by_prefix(const char *prefix)
{
histlink_T *l;
for (l = histlist.Newest; l != Histlist; l = l->prev)
if (matchstrprefix(ashistentry(l)->value, prefix) != NULL)
break;
return l;
}
/* Returns true iff `sr1' is newer than `sr2'.
* For each search_result_T structure, the `prev' and `next' members must not be
* both `Histlist'. */
bool search_result_is_newer(
struct search_result_T sr1, struct search_result_T sr2)
{
if (sr1.prev == Histlist || sr2.next == Histlist)
return false;
if (sr1.next == Histlist || sr2.prev == Histlist)
return true;
return entry_is_newer(ashistentry(sr1.prev), ashistentry(sr2.prev))
|| entry_is_newer(ashistentry(sr1.next), ashistentry(sr2.next));
}
/* Returns true iff `e1' is newer than `e2'. */
bool entry_is_newer(const histentry_T *e1, const histentry_T *e2)
{
assert(histlist.count > 0);
unsigned n1 = e1->number;
unsigned n2 = e2->number;
unsigned newest = ashistentry(histlist.Newest)->number;
unsigned oldest = ashistentry(histlist.Oldest)->number;
return (n1 <= newest && newest < oldest && oldest <= n2)
|| (n2 <= n1 && (oldest <= n2 || n1 <= newest));
}
/********** Process ID list **********/
struct pidlist_T {
size_t count;
pid_t *pids;
};
/* The process IDs of processes that share the history file.
* The `pids' member may be null when the `count' member is zero. */
static struct pidlist_T histfilepids = { 0, NULL, };
/* Adds `pid' to `histfilepids'. `pid' must be positive. */
void add_histfile_pid(pid_t pid)
{
assert(pid > 0);
for (size_t i = 0; i < histfilepids.count; i++)
if (histfilepids.pids[i] == pid)
return; /* don't add if already added */
histfilepids.pids = xrealloce(histfilepids.pids,
histfilepids.count, 1, sizeof *histfilepids.pids);
histfilepids.pids[histfilepids.count++] = pid;
}
/* If `pid' is non-zero, removes `pid' from `histfilepids'.
* If `pid' is zero, removes process IDs of non-existent processes from
* `histfilepids'. */
void remove_histfile_pid(pid_t pid)
{
for (size_t i = 0; i < histfilepids.count; ) {
if (pid != 0 ? histfilepids.pids[i] == pid
: !process_exists(histfilepids.pids[i])) {
memmove(&histfilepids.pids[i], &histfilepids.pids[i + 1],
(histfilepids.count - i - 1) * sizeof *histfilepids.pids);
histfilepids.count--;
histfilepids.pids = xreallocn(histfilepids.pids,
histfilepids.count, sizeof *histfilepids.pids);
} else {
i++;
}
}
}
/* Clears `histfilepids'. */
void clear_histfile_pids(void)
{
free(histfilepids.pids);
histfilepids = (struct pidlist_T) { 0, NULL, };
}
/* Writes process IDs in `histfilepids' to the history file. */
/* This function does not return any error status. The caller should check
* `ferror' for the file. */
void write_histfile_pids(void)
{
assert(histfile != NULL);
for (size_t i = 0; i < histfilepids.count; i++)
wprintf_histfile(L"p%jd\n", (intmax_t) histfilepids.pids[i]);
histfilelines += histfilepids.count;
}
/********** History file functions **********/
/***** FORMAT OF THE HISTORY FILE *****
*
* The first line of the history file has the following form:
* #$# yash history v0 rXXX
* where `XXX' is the revision number of the file. The revision number is
* incremented each time the file is refreshed.
*
* The rest of the file consists of lines containing history data, each entry
* per line. The type of entry is determined by the first character of the line:
* 0-9 or A-F history entry
* c history entry cancellation
* d history entry deletion
* p shell process addition/elimination info
* others ignored line
*
* A history entry has the following form:
* NNN:TTT COMMAND
* where `NNN' is the entry number, `TTT' is the time of the command, and
* `COMMAND' is the command. Both `NNN' and `TTT' are uppercase hexadecimal
* non-negative numbers. `COMMAND' may contain any characters except newline and
* null.
*
* A history entry cancellation consists of a single character `c'. It cancels
* the previous history entry.
*
* A history entry deletion has the form:
* dNNN
* where `NNN' is the number of the entry to be removed (hexadecimal).
*
* A shell process addition/elimination is in the form:
* pXXX
* where `XXX' is the process id (decimal integer). For addition `XXX' is
* positive and for elimination `XXX' is negative.
*/
/* Opens the history file.
* Returns NULL on failure. */
FILE *open_histfile(void)
{
const wchar_t *vhistfile = getvar(L VAR_HISTFILE);
if (vhistfile == NULL)
return NULL;
char *mbshistfile = malloc_wcstombs(vhistfile);
if (mbshistfile == NULL)
return NULL;
int fd = open(mbshistfile, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
free(mbshistfile);
if (fd < 0)
return NULL;
struct stat st;
if (fstat(fd, &st) < 0 || !S_ISREG(st.st_mode)
|| (st.st_mode & (S_IRWXG | S_IRWXO))) {
xclose(fd);
return NULL;
}
fd = move_to_shellfd(fd);
if (fd < 0)
return NULL;
FILE *f = fdopen(fd, "r+");
if (f == NULL) {
remove_shellfd(fd);
xclose(fd);
}
return f;
}
/* Locks the history file, which must have been open.
* `type' must be one of `F_RDLCK', `F_WRLCK' and `F_UNLCK'.
* If `type' is `F_UNLCK', the buffer for the history file is flushed before
* unlocking the file.
* When another process is holding a lock for the file, this process will be
* blocked until the lock is freed.
* Returns true iff successful. */
bool lock_histfile(short type)
{
if (type == F_UNLCK && histneedflush) {
histneedflush = false;
fflush(histfile);
/* We only flush the history file after writing. POSIX doesn't define
* the behavior of flush without writing. We don't use fseek instead of
* fflush because fseek is less reliable than fflush. In some
* implementations (including glibc), fseek doesn't flush the file. */
}
struct flock flock = {
.l_type = type,
.l_whence = SEEK_SET,
.l_start = 0,
.l_len = 0, /* to the end of file */
};
int fd = fileno(histfile);
int result;
while ((result = fcntl(fd, F_SETLKW, &flock)) == -1 && errno == EINTR);
return result != -1;
}
/* Reads one line from file `f'.
* The line is appended to buffer `buf', which must have been initialized.
* The terminating newline is not left in `buf'.
* On failure, false is returned, in which case the contents of `buf' is
* unspecified.
* If there is no more line in the file, false is returned.
* This function may ignore lines longer than LINE_MAX. */
bool read_line(FILE *restrict f, xwcsbuf_T *restrict buf)
{
bool accept_current_line = true;
size_t initial_length = buf->length;
for (;;) {
if (try_read_line(f, buf)) {
if (accept_current_line)
return true;
/* Read one more line and accept it. */
accept_current_line = true;
} else {
if (feof(f) || ferror(f))
return false;
/* Now, the position of `f' is in the middle of a very long line
* that should be ignored. */
accept_current_line = false;
}
wb_truncate(buf, initial_length);
}
}
/* Reads one line from file `f'.
* The line is appended to buffer `buf', which must have been initialized.
* If a line was read successfully, true is returned. The terminating newline is
* not left in `buf'.
* The return value is false if:
* * an error occurred (ferror()),
* * the end of the input was reached (feof()), or
* * the current line is too long (at least LINE_MAX characters), in which case
* the position of `f' is left in the middle of the current line.
* The contents of `buf' is unspecified if the return value is false. */
bool try_read_line(FILE *restrict f, xwcsbuf_T *restrict buf)
{
#if FGETWS_BROKEN
wb_ensuremax(buf, LINE_MAX);
#endif
while (fgetws(&buf->contents[buf->length],
buf->maxlength - buf->length + 1, f)) {
size_t len = wcslen(&buf->contents[buf->length]);
if (len == 0)
return false;
buf->length += len;
if (buf->contents[buf->length - 1] == L'\n') {
wb_truncate(buf, buf->length - 1);
return true;
}
if (buf->length > LINE_MAX)
return false; /* Too long line. Give up. */
wb_ensuremax(buf, add(buf->length, 80));
}
return false;
}
/* Reads the signature of the history file (`histfile') and checks if it is a
* valid signature.
* If valid:
* - the file is positioned just after the signature,
* - the return value is the revision of the file (non-negative).
* Otherwise:
* - the file position is undefined,
* - the return value is negative. */
/* The history file should be locked. */
long read_signature(void)
{
xwcsbuf_T buf;
long rev = -1;
const wchar_t *s;
assert(histfile != NULL);
rewind(histfile);
if (!read_line(histfile, wb_initwithmax(&buf, HISTORY_DEFAULT_LINE_LENGTH)))
goto end;
s = matchwcsprefix(buf.contents, L"#$# yash history v0 r");
if (s == NULL || !iswdigit(s[0]))
goto end;
if (!xwcstol(s, 10, &rev))
rev = -1;
end:
wb_destroy(&buf);
return rev;
}
/* Reads history entries from the history file, which must have been open.
* The file format is assumed a simple text, one entry per line.
* The file is read from the current position.
* The entries that were read from the file are appended to `histlist'. */
/* The file should be locked. */
/* This function does not return any error status. The caller should check
* `ferror' and/or `feof' for the file. */
void read_history_raw(void)
{
xwcsbuf_T buf;
assert(histfile != NULL);
wb_initwithmax(&buf, HISTORY_DEFAULT_LINE_LENGTH);
while (read_line(histfile, &buf)) {
char *line = malloc_wcstombs(buf.contents);
if (line != NULL) {
new_entry(next_history_number(), -1, line);
free(line);
}
wb_clear(&buf);
}
wb_destroy(&buf);
}
/* Reads history entries from the history file.
* The file is read from the current position.
* The entries that were read from the file are appended to `histlist'.
* `update_time' must be called before calling this function. */
/* The file should be locked. */
/* This function does not return any error status. The caller should check
* `ferror' and/or `feof' for the file. */
void read_history(void)
{
xwcsbuf_T buf;
assert(histfile != NULL);
wb_initwithmax(&buf, HISTORY_DEFAULT_LINE_LENGTH);
while (read_line(histfile, &buf)) {
histfilelines++;
switch (buf.contents[0]) {
case L'0': case L'1': case L'2': case L'3': case L'4':
case L'5': case L'6': case L'7': case L'8': case L'9':
case L'A': case L'B': case L'C': case L'D': case L'E': case L'F':
parse_history_entry(buf.contents);
break;
case L'c':
remove_last_entry();
break;
case L'd':
parse_removed_entry(buf.contents + 1);
break;
case L'p':
parse_process_id(buf.contents + 1);
break;
}
wb_clear(&buf);
}
wb_destroy(&buf);
}
void parse_history_entry(const wchar_t *line)
{
unsigned long num;
time_t time;
wchar_t *end;
char *value;
assert(iswxdigit(line[0]));
errno = 0;
num = wcstoul(line, &end, 0x10);
if (errno || end[0] == L'\0' || num > max_number)
return;
if (end[0] == L':' && iswxdigit(end[1])) {
unsigned long long t;
errno = 0;
t = wcstoull(&end[1], &end, 0x10);
if (errno || end[0] == L'\0')
time = -1;
else if (t > (unsigned long long) now)
time = now;
else
time = (time_t) t;
} else {
time = -1;
}
if (!iswspace(end[0]))
return;
value = malloc_wcstombs(&end[1]);
if (value != NULL) {
new_entry((unsigned) num, time, value);
free(value);
}
}
void parse_removed_entry(const wchar_t *numstr)
{
unsigned long num;
wchar_t *end;
if (histlist.count == 0)
return;
if (numstr[0] == L'\0')
return;
errno = 0;
num = wcstoul(numstr, &end, 0x10);
if (errno || (*end != L'\0' && !iswspace(*end)))
return;
if (num > max_number)
return;
struct search_result_T sr = search_entry_by_number((unsigned) num);
if (sr.prev == sr.next)
remove_entry(ashistentry(sr.prev));
}
void parse_process_id(const wchar_t *numstr)
{
intmax_t num;
wchar_t *end;
if (numstr[0] == L'\0')
return;
errno = 0;
num = wcstoimax(numstr, &end, 10);
if (errno || (*end != L'\0' && !iswspace(*end)))
return;
if (num > 0)
add_histfile_pid((pid_t) num);
else if (num < 0)
remove_histfile_pid((pid_t) -num);
/* XXX: this cast and negation may be unsafe */
}
/* Re-reads history from the history file.
* Changes that have been made to the file by other shell processes are brought
* into this shell's history. The current data in this shell's history may be
* changed.
* If `refresh' is true, this function may call `refresh_file'.
* On failure, `histfile' is closed and set to NULL.
* `update_time' must be called before calling this function.
* After calling this function, `histfile' must not be read without
* repositioning. */
/* The history file should be locked (F_WRLCK if `refresh' is true or F_RDLCK if
* `refresh' is false).
* This function must be called just before writing to the history file. */
void update_history(bool refresh)
{
bool posfail;
fpos_t pos;
long rev;
if (histfile == NULL)
return;
assert(!hist_lock);
#if WIO_BROKEN
posfail = true;
#else
posfail = fgetpos(histfile, &pos);
#endif
rev = read_signature();
if (rev < 0)
goto error;
if (!posfail && rev == histfilerev) {
/* The revision has not been changed. Just read new entries. */
fsetpos(histfile, &pos);
read_history();
} else {
/* The revision has been changed. Re-read everything. */
clear_all_entries();
clear_histfile_pids();
add_histfile_pid(shell_pid);
histfilerev = rev;
histfilelines = 0;
read_history();
}
if (ferror(histfile) || !feof(histfile))
goto error;
if (refresh)
maybe_refresh_file();
return;
error:
close_history_file();
}
/* Refreshes the history file if it is time to do that.
* `histfile' must not be NULL. */
void maybe_refresh_file(void)
{
assert(histfile != NULL);
if (histfilelines > 20
&& histfilelines / 2 >= histlist.count + histfilepids.count) {
remove_histfile_pid(0);
refresh_file();
}
}
/* Like `fwprintf(histfile, format, ...)', but the `histneedflush' flag is set.
*/
int wprintf_histfile(const wchar_t *format, ...)
{
va_list ap;
int result;
histneedflush = true;
va_start(ap, format);
result = vfwprintf(histfile, format, ap);
va_end(ap);
return result;
}
/* Writes the signature with an incremented revision number, after emptying the
* file. */
/* This function does not return any error status. The caller should check
* `ferror' for the file. */
void write_signature(void)
{
assert(histfile != NULL);
rewind(histfile);
while (ftruncate(fileno(histfile), 0) < 0 && errno == EINTR);
if (histfilerev < 0 || histfilerev == LONG_MAX)
histfilerev = 0;
else
histfilerev++;
wprintf_histfile(L"#$# yash history v0 r%ld\n", histfilerev);
histfilelines = 0;
}
/* Writes the specified entry to the history file. */
/* The file should be locked. */
/* This function does not return any error status. The caller should check
* `ferror' for the file. */
void write_history_entry(const histentry_T *entry)
{
assert(histfile != NULL);
/* don't print very long line */
if (xstrnlen(entry->value, LINE_MAX) >= LINE_MAX)
return;
if (entry->time >= 0)
wprintf_histfile(L"%X:%lX %s\n",
entry->number, (unsigned long) entry->time, entry->value);
else
wprintf_histfile(L"%X %s\n",
entry->number, entry->value);
histfilelines++;
}
/* Clears and rewrites the contents of the history file.
* The file will have a new revision number. */
/* The file should be locked. */
/* This function does not return any error status. The caller should check
* `ferror' for the file. */
void refresh_file(void)
{
write_signature();
write_histfile_pids();
for (const histlink_T *l = histlist.Oldest; l != Histlist; l = l->next)
write_history_entry(ashistentry(l));
}
/********** External functions **********/
/* Initializes history function if not yet initialized.
* If the shell is not interactive, history is never initialized. */
void maybe_init_history(void)
{
static bool initialized = false;
if (!is_interactive_now || initialized)
return;
initialized = true;
/* set `histsize' */
const wchar_t *vhistsize = getvar(L VAR_HISTSIZE);
if (vhistsize != NULL && vhistsize[0] != L'\0') {
unsigned long size;
if (xwcstoul(vhistsize, 10, &size))
set_histsize(size);
}
/* set `histrmdup' */
const wchar_t *vhistrmdup = getvar(L VAR_HISTRMDUP);
if (vhistrmdup != NULL && vhistrmdup[0] != L'\0') {
unsigned long rmdup;
if (xwcstoul(vhistrmdup, 10, &rmdup))
histrmdup = (rmdup <= histsize) ? rmdup : histsize;
}
update_time();
/* open the history file and read it */
histfile = open_histfile();
if (histfile != NULL) {
lock_histfile(F_WRLCK);
histfilerev = read_signature();
if (histfilerev < 0) {
rewind(histfile);
read_history_raw();
goto refresh;
}
read_history();
if (ferror(histfile) || !feof(histfile)) {
close_history_file();
return;
}
remove_histfile_pid(0);
if (histfilepids.count == 0) {
renumber_all_entries();
refresh:
refresh_file();
} else {
maybe_refresh_file();
}
add_histfile_pid(shell_pid);
wprintf_histfile(L"p%jd\n", (intmax_t) shell_pid);
histfilelines++;