Bring in an errno.9 manual page (based on NetBSD's).
[dragonfly.git] / contrib / less / ch.c
blobda729c5dec06d2eaee07dd823a602327b52b3312
1 /*
2 * Copyright (C) 1984-2015 Mark Nudelman
4 * You may distribute under the terms of either the GNU General Public
5 * License or the Less License, as specified in the README file.
7 * For more information, see the README file.
8 */
12 * Low level character input from the input file.
13 * We use these special purpose routines which optimize moving
14 * both forward and backward from the current read pointer.
17 #include "less.h"
18 #if MSDOS_COMPILER==WIN32C
19 #include <errno.h>
20 #include <windows.h>
21 #endif
23 #if HAVE_STAT_INO
24 #include <sys/stat.h>
25 extern dev_t curr_dev;
26 extern ino_t curr_ino;
27 #endif
29 typedef POSITION BLOCKNUM;
31 public int ignore_eoi;
34 * Pool of buffers holding the most recently used blocks of the input file.
35 * The buffer pool is kept as a doubly-linked circular list,
36 * in order from most- to least-recently used.
37 * The circular list is anchored by the file state "thisfile".
39 struct bufnode {
40 struct bufnode *next, *prev;
41 struct bufnode *hnext, *hprev;
44 #define LBUFSIZE 8192
45 struct buf {
46 struct bufnode node;
47 BLOCKNUM block;
48 unsigned int datasize;
49 unsigned char data[LBUFSIZE];
51 #define bufnode_buf(bn) ((struct buf *) bn)
54 * The file state is maintained in a filestate structure.
55 * A pointer to the filestate is kept in the ifile structure.
57 #define BUFHASH_SIZE 1024
58 struct filestate {
59 struct bufnode buflist;
60 struct bufnode hashtbl[BUFHASH_SIZE];
61 int file;
62 int flags;
63 POSITION fpos;
64 int nbufs;
65 BLOCKNUM block;
66 unsigned int offset;
67 POSITION fsize;
70 #define ch_bufhead thisfile->buflist.next
71 #define ch_buftail thisfile->buflist.prev
72 #define ch_nbufs thisfile->nbufs
73 #define ch_block thisfile->block
74 #define ch_offset thisfile->offset
75 #define ch_fpos thisfile->fpos
76 #define ch_fsize thisfile->fsize
77 #define ch_flags thisfile->flags
78 #define ch_file thisfile->file
80 #define END_OF_CHAIN (&thisfile->buflist)
81 #define END_OF_HCHAIN(h) (&thisfile->hashtbl[h])
82 #define BUFHASH(blk) ((blk) & (BUFHASH_SIZE-1))
85 * Macros to manipulate the list of buffers in thisfile->buflist.
87 #define FOR_BUFS(bn) \
88 for (bn = ch_bufhead; bn != END_OF_CHAIN; bn = bn->next)
90 #define BUF_RM(bn) \
91 (bn)->next->prev = (bn)->prev; \
92 (bn)->prev->next = (bn)->next;
94 #define BUF_INS_HEAD(bn) \
95 (bn)->next = ch_bufhead; \
96 (bn)->prev = END_OF_CHAIN; \
97 ch_bufhead->prev = (bn); \
98 ch_bufhead = (bn);
100 #define BUF_INS_TAIL(bn) \
101 (bn)->next = END_OF_CHAIN; \
102 (bn)->prev = ch_buftail; \
103 ch_buftail->next = (bn); \
104 ch_buftail = (bn);
107 * Macros to manipulate the list of buffers in thisfile->hashtbl[n].
109 #define FOR_BUFS_IN_CHAIN(h,bn) \
110 for (bn = thisfile->hashtbl[h].hnext; \
111 bn != END_OF_HCHAIN(h); bn = bn->hnext)
113 #define BUF_HASH_RM(bn) \
114 (bn)->hnext->hprev = (bn)->hprev; \
115 (bn)->hprev->hnext = (bn)->hnext;
117 #define BUF_HASH_INS(bn,h) \
118 (bn)->hnext = thisfile->hashtbl[h].hnext; \
119 (bn)->hprev = END_OF_HCHAIN(h); \
120 thisfile->hashtbl[h].hnext->hprev = (bn); \
121 thisfile->hashtbl[h].hnext = (bn);
123 static struct filestate *thisfile;
124 static int ch_ungotchar = -1;
125 static int maxbufs = -1;
127 extern int autobuf;
128 extern int sigs;
129 extern int secure;
130 extern int screen_trashed;
131 extern int follow_mode;
132 extern constant char helpdata[];
133 extern constant int size_helpdata;
134 extern IFILE curr_ifile;
135 #if LOGFILE
136 extern int logfile;
137 extern char *namelogfile;
138 #endif
140 static int ch_addbuf();
144 * Get the character pointed to by the read pointer.
147 ch_get()
149 register struct buf *bp;
150 register struct bufnode *bn;
151 register int n;
152 register int slept;
153 register int h;
154 POSITION pos;
155 POSITION len;
157 if (thisfile == NULL)
158 return (EOI);
161 * Quick check for the common case where
162 * the desired char is in the head buffer.
164 if (ch_bufhead != END_OF_CHAIN)
166 bp = bufnode_buf(ch_bufhead);
167 if (ch_block == bp->block && ch_offset < bp->datasize)
168 return bp->data[ch_offset];
171 slept = FALSE;
174 * Look for a buffer holding the desired block.
176 h = BUFHASH(ch_block);
177 FOR_BUFS_IN_CHAIN(h, bn)
179 bp = bufnode_buf(bn);
180 if (bp->block == ch_block)
182 if (ch_offset >= bp->datasize)
184 * Need more data in this buffer.
186 break;
187 goto found;
190 if (bn == END_OF_HCHAIN(h))
193 * Block is not in a buffer.
194 * Take the least recently used buffer
195 * and read the desired block into it.
196 * If the LRU buffer has data in it,
197 * then maybe allocate a new buffer.
199 if (ch_buftail == END_OF_CHAIN ||
200 bufnode_buf(ch_buftail)->block != -1)
203 * There is no empty buffer to use.
204 * Allocate a new buffer if:
205 * 1. We can't seek on this file and -b is not in effect; or
206 * 2. We haven't allocated the max buffers for this file yet.
208 if ((autobuf && !(ch_flags & CH_CANSEEK)) ||
209 (maxbufs < 0 || ch_nbufs < maxbufs))
210 if (ch_addbuf())
212 * Allocation failed: turn off autobuf.
214 autobuf = OPT_OFF;
216 bn = ch_buftail;
217 bp = bufnode_buf(bn);
218 BUF_HASH_RM(bn); /* Remove from old hash chain. */
219 bp->block = ch_block;
220 bp->datasize = 0;
221 BUF_HASH_INS(bn, h); /* Insert into new hash chain. */
224 read_more:
225 pos = (ch_block * LBUFSIZE) + bp->datasize;
226 if ((len = ch_length()) != NULL_POSITION && pos >= len)
228 * At end of file.
230 return (EOI);
232 if (pos != ch_fpos)
235 * Not at the correct position: must seek.
236 * If input is a pipe, we're in trouble (can't seek on a pipe).
237 * Some data has been lost: just return "?".
239 if (!(ch_flags & CH_CANSEEK))
240 return ('?');
241 if (lseek(ch_file, (off_t)pos, SEEK_SET) == BAD_LSEEK)
243 error("seek error", NULL_PARG);
244 clear_eol();
245 return (EOI);
247 ch_fpos = pos;
251 * Read the block.
252 * If we read less than a full block, that's ok.
253 * We use partial block and pick up the rest next time.
255 if (ch_ungotchar != -1)
257 bp->data[bp->datasize] = ch_ungotchar;
258 n = 1;
259 ch_ungotchar = -1;
260 } else if (ch_flags & CH_HELPFILE)
262 bp->data[bp->datasize] = helpdata[ch_fpos];
263 n = 1;
264 } else
266 n = iread(ch_file, &bp->data[bp->datasize],
267 (unsigned int)(LBUFSIZE - bp->datasize));
270 if (n == READ_INTR)
271 return (EOI);
272 if (n < 0)
274 #if MSDOS_COMPILER==WIN32C
275 if (errno != EPIPE)
276 #endif
278 error("read error", NULL_PARG);
279 clear_eol();
281 n = 0;
284 #if LOGFILE
286 * If we have a log file, write the new data to it.
288 if (!secure && logfile >= 0 && n > 0)
289 write(logfile, (char *) &bp->data[bp->datasize], n);
290 #endif
292 ch_fpos += n;
293 bp->datasize += n;
296 * If we have read to end of file, set ch_fsize to indicate
297 * the position of the end of file.
299 if (n == 0)
301 ch_fsize = pos;
302 if (ignore_eoi)
305 * We are ignoring EOF.
306 * Wait a while, then try again.
308 if (!slept)
310 PARG parg;
311 parg.p_string = wait_message();
312 ierror("%s", &parg);
314 #if !MSDOS_COMPILER
315 sleep(1);
316 #else
317 #if MSDOS_COMPILER==WIN32C
318 Sleep(1000);
319 #endif
320 #endif
321 slept = TRUE;
323 #if HAVE_STAT_INO
324 if (follow_mode == FOLLOW_NAME)
326 /* See whether the file's i-number has changed,
327 * or the file has shrunk.
328 * If so, force the file to be closed and
329 * reopened. */
330 struct stat st;
331 POSITION curr_pos = ch_tell();
332 int r = stat(get_filename(curr_ifile), &st);
333 if (r == 0 && (st.st_ino != curr_ino ||
334 st.st_dev != curr_dev ||
335 (curr_pos != NULL_POSITION && st.st_size < curr_pos)))
337 /* screen_trashed=2 causes
338 * make_display to reopen the file. */
339 screen_trashed = 2;
340 return (EOI);
343 #endif
345 if (sigs)
346 return (EOI);
349 found:
350 if (ch_bufhead != bn)
353 * Move the buffer to the head of the buffer chain.
354 * This orders the buffer chain, most- to least-recently used.
356 BUF_RM(bn);
357 BUF_INS_HEAD(bn);
360 * Move to head of hash chain too.
362 BUF_HASH_RM(bn);
363 BUF_HASH_INS(bn, h);
366 if (ch_offset >= bp->datasize)
368 * After all that, we still don't have enough data.
369 * Go back and try again.
371 goto read_more;
373 return (bp->data[ch_offset]);
377 * ch_ungetchar is a rather kludgy and limited way to push
378 * a single char onto an input file descriptor.
380 public void
381 ch_ungetchar(c)
382 int c;
384 if (c != -1 && ch_ungotchar != -1)
385 error("ch_ungetchar overrun", NULL_PARG);
386 ch_ungotchar = c;
389 #if LOGFILE
391 * Close the logfile.
392 * If we haven't read all of standard input into it, do that now.
394 public void
395 end_logfile()
397 static int tried = FALSE;
399 if (logfile < 0)
400 return;
401 if (!tried && ch_fsize == NULL_POSITION)
403 tried = TRUE;
404 ierror("Finishing logfile", NULL_PARG);
405 while (ch_forw_get() != EOI)
406 if (ABORT_SIGS())
407 break;
409 close(logfile);
410 logfile = -1;
411 namelogfile = NULL;
415 * Start a log file AFTER less has already been running.
416 * Invoked from the - command; see toggle_option().
417 * Write all the existing buffered data to the log file.
419 public void
420 sync_logfile()
422 register struct buf *bp;
423 register struct bufnode *bn;
424 int warned = FALSE;
425 BLOCKNUM block;
426 BLOCKNUM nblocks;
428 nblocks = (ch_fpos + LBUFSIZE - 1) / LBUFSIZE;
429 for (block = 0; block < nblocks; block++)
431 int wrote = FALSE;
432 FOR_BUFS(bn)
434 bp = bufnode_buf(bn);
435 if (bp->block == block)
437 write(logfile, (char *) bp->data, bp->datasize);
438 wrote = TRUE;
439 break;
442 if (!wrote && !warned)
444 error("Warning: log file is incomplete",
445 NULL_PARG);
446 warned = TRUE;
451 #endif
454 * Determine if a specific block is currently in one of the buffers.
456 static int
457 buffered(block)
458 BLOCKNUM block;
460 register struct buf *bp;
461 register struct bufnode *bn;
462 register int h;
464 h = BUFHASH(block);
465 FOR_BUFS_IN_CHAIN(h, bn)
467 bp = bufnode_buf(bn);
468 if (bp->block == block)
469 return (TRUE);
471 return (FALSE);
475 * Seek to a specified position in the file.
476 * Return 0 if successful, non-zero if can't seek there.
478 public int
479 ch_seek(pos)
480 register POSITION pos;
482 BLOCKNUM new_block;
483 POSITION len;
485 if (thisfile == NULL)
486 return (0);
488 len = ch_length();
489 if (pos < ch_zero() || (len != NULL_POSITION && pos > len))
490 return (1);
492 new_block = pos / LBUFSIZE;
493 if (!(ch_flags & CH_CANSEEK) && pos != ch_fpos && !buffered(new_block))
495 if (ch_fpos > pos)
496 return (1);
497 while (ch_fpos < pos)
499 if (ch_forw_get() == EOI)
500 return (1);
501 if (ABORT_SIGS())
502 return (1);
504 return (0);
507 * Set read pointer.
509 ch_block = new_block;
510 ch_offset = pos % LBUFSIZE;
511 return (0);
515 * Seek to the end of the file.
517 public int
518 ch_end_seek()
520 POSITION len;
522 if (thisfile == NULL)
523 return (0);
525 if (ch_flags & CH_CANSEEK)
526 ch_fsize = filesize(ch_file);
528 len = ch_length();
529 if (len != NULL_POSITION)
530 return (ch_seek(len));
533 * Do it the slow way: read till end of data.
535 while (ch_forw_get() != EOI)
536 if (ABORT_SIGS())
537 return (1);
538 return (0);
542 * Seek to the last position in the file that is currently buffered.
544 public int
545 ch_end_buffer_seek()
547 register struct buf *bp;
548 register struct bufnode *bn;
549 POSITION buf_pos;
550 POSITION end_pos;
552 if (thisfile == NULL || (ch_flags & CH_CANSEEK))
553 return (ch_end_seek());
555 end_pos = 0;
556 FOR_BUFS(bn)
558 bp = bufnode_buf(bn);
559 buf_pos = (bp->block * LBUFSIZE) + bp->datasize;
560 if (buf_pos > end_pos)
561 end_pos = buf_pos;
564 return (ch_seek(end_pos));
568 * Seek to the beginning of the file, or as close to it as we can get.
569 * We may not be able to seek there if input is a pipe and the
570 * beginning of the pipe is no longer buffered.
572 public int
573 ch_beg_seek()
575 register struct bufnode *bn;
576 register struct bufnode *firstbn;
579 * Try a plain ch_seek first.
581 if (ch_seek(ch_zero()) == 0)
582 return (0);
585 * Can't get to position 0.
586 * Look thru the buffers for the one closest to position 0.
588 firstbn = ch_bufhead;
589 if (firstbn == END_OF_CHAIN)
590 return (1);
591 FOR_BUFS(bn)
593 if (bufnode_buf(bn)->block < bufnode_buf(firstbn)->block)
594 firstbn = bn;
596 ch_block = bufnode_buf(firstbn)->block;
597 ch_offset = 0;
598 return (0);
602 * Return the length of the file, if known.
604 public POSITION
605 ch_length()
607 if (thisfile == NULL)
608 return (NULL_POSITION);
609 if (ignore_eoi)
610 return (NULL_POSITION);
611 if (ch_flags & CH_HELPFILE)
612 return (size_helpdata);
613 if (ch_flags & CH_NODATA)
614 return (0);
615 return (ch_fsize);
619 * Return the current position in the file.
621 public POSITION
622 ch_tell()
624 if (thisfile == NULL)
625 return (NULL_POSITION);
626 return (ch_block * LBUFSIZE) + ch_offset;
630 * Get the current char and post-increment the read pointer.
632 public int
633 ch_forw_get()
635 register int c;
637 if (thisfile == NULL)
638 return (EOI);
639 c = ch_get();
640 if (c == EOI)
641 return (EOI);
642 if (ch_offset < LBUFSIZE-1)
643 ch_offset++;
644 else
646 ch_block ++;
647 ch_offset = 0;
649 return (c);
653 * Pre-decrement the read pointer and get the new current char.
655 public int
656 ch_back_get()
658 if (thisfile == NULL)
659 return (EOI);
660 if (ch_offset > 0)
661 ch_offset --;
662 else
664 if (ch_block <= 0)
665 return (EOI);
666 if (!(ch_flags & CH_CANSEEK) && !buffered(ch_block-1))
667 return (EOI);
668 ch_block--;
669 ch_offset = LBUFSIZE-1;
671 return (ch_get());
675 * Set max amount of buffer space.
676 * bufspace is in units of 1024 bytes. -1 mean no limit.
678 public void
679 ch_setbufspace(bufspace)
680 int bufspace;
682 if (bufspace < 0)
683 maxbufs = -1;
684 else
686 maxbufs = ((bufspace * 1024) + LBUFSIZE-1) / LBUFSIZE;
687 if (maxbufs < 1)
688 maxbufs = 1;
693 * Flush (discard) any saved file state, including buffer contents.
695 public void
696 ch_flush()
698 register struct bufnode *bn;
700 if (thisfile == NULL)
701 return;
703 if (!(ch_flags & CH_CANSEEK))
706 * If input is a pipe, we don't flush buffer contents,
707 * since the contents can't be recovered.
709 ch_fsize = NULL_POSITION;
710 return;
714 * Initialize all the buffers.
716 FOR_BUFS(bn)
718 bufnode_buf(bn)->block = -1;
722 * Figure out the size of the file, if we can.
724 ch_fsize = filesize(ch_file);
727 * Seek to a known position: the beginning of the file.
729 ch_fpos = 0;
730 ch_block = 0; /* ch_fpos / LBUFSIZE; */
731 ch_offset = 0; /* ch_fpos % LBUFSIZE; */
733 #if 1
735 * This is a kludge to workaround a Linux kernel bug: files in
736 * /proc have a size of 0 according to fstat() but have readable
737 * data. They are sometimes, but not always, seekable.
738 * Force them to be non-seekable here.
740 if (ch_fsize == 0)
742 ch_fsize = NULL_POSITION;
743 ch_flags &= ~CH_CANSEEK;
745 #endif
747 if (lseek(ch_file, (off_t)0, SEEK_SET) == BAD_LSEEK)
750 * Warning only; even if the seek fails for some reason,
751 * there's a good chance we're at the beginning anyway.
752 * {{ I think this is bogus reasoning. }}
754 error("seek error to 0", NULL_PARG);
759 * Allocate a new buffer.
760 * The buffer is added to the tail of the buffer chain.
762 static int
763 ch_addbuf()
765 register struct buf *bp;
766 register struct bufnode *bn;
769 * Allocate and initialize a new buffer and link it
770 * onto the tail of the buffer list.
772 bp = (struct buf *) calloc(1, sizeof(struct buf));
773 if (bp == NULL)
774 return (1);
775 ch_nbufs++;
776 bp->block = -1;
777 bn = &bp->node;
779 BUF_INS_TAIL(bn);
780 BUF_HASH_INS(bn, 0);
781 return (0);
787 static void
788 init_hashtbl()
790 register int h;
792 for (h = 0; h < BUFHASH_SIZE; h++)
794 thisfile->hashtbl[h].hnext = END_OF_HCHAIN(h);
795 thisfile->hashtbl[h].hprev = END_OF_HCHAIN(h);
800 * Delete all buffers for this file.
802 static void
803 ch_delbufs()
805 register struct bufnode *bn;
807 while (ch_bufhead != END_OF_CHAIN)
809 bn = ch_bufhead;
810 BUF_RM(bn);
811 free(bufnode_buf(bn));
813 ch_nbufs = 0;
814 init_hashtbl();
818 * Is it possible to seek on a file descriptor?
820 public int
821 seekable(f)
822 int f;
824 #if MSDOS_COMPILER
825 extern int fd0;
826 if (f == fd0 && !isatty(fd0))
829 * In MS-DOS, pipes are seekable. Check for
830 * standard input, and pretend it is not seekable.
832 return (0);
834 #endif
835 return (lseek(f, (off_t)1, SEEK_SET) != BAD_LSEEK);
839 * Force EOF to be at the current read position.
840 * This is used after an ignore_eof read, during which the EOF may change.
842 public void
843 ch_set_eof()
845 ch_fsize = ch_fpos;
850 * Initialize file state for a new file.
852 public void
853 ch_init(f, flags)
854 int f;
855 int flags;
858 * See if we already have a filestate for this file.
860 thisfile = (struct filestate *) get_filestate(curr_ifile);
861 if (thisfile == NULL)
864 * Allocate and initialize a new filestate.
866 thisfile = (struct filestate *)
867 calloc(1, sizeof(struct filestate));
868 thisfile->buflist.next = thisfile->buflist.prev = END_OF_CHAIN;
869 thisfile->nbufs = 0;
870 thisfile->flags = 0;
871 thisfile->fpos = 0;
872 thisfile->block = 0;
873 thisfile->offset = 0;
874 thisfile->file = -1;
875 thisfile->fsize = NULL_POSITION;
876 ch_flags = flags;
877 init_hashtbl();
879 * Try to seek; set CH_CANSEEK if it works.
881 if ((flags & CH_CANSEEK) && !seekable(f))
882 ch_flags &= ~CH_CANSEEK;
883 set_filestate(curr_ifile, (void *) thisfile);
885 if (thisfile->file == -1)
886 thisfile->file = f;
887 ch_flush();
891 * Close a filestate.
893 public void
894 ch_close()
896 int keepstate = FALSE;
898 if (thisfile == NULL)
899 return;
901 if (ch_flags & (CH_CANSEEK|CH_POPENED|CH_HELPFILE))
904 * We can seek or re-open, so we don't need to keep buffers.
906 ch_delbufs();
907 } else
908 keepstate = TRUE;
909 if (!(ch_flags & CH_KEEPOPEN))
912 * We don't need to keep the file descriptor open
913 * (because we can re-open it.)
914 * But don't really close it if it was opened via popen(),
915 * because pclose() wants to close it.
917 if (!(ch_flags & (CH_POPENED|CH_HELPFILE)))
918 close(ch_file);
919 ch_file = -1;
920 } else
921 keepstate = TRUE;
922 if (!keepstate)
925 * We don't even need to keep the filestate structure.
927 free(thisfile);
928 thisfile = NULL;
929 set_filestate(curr_ifile, (void *) NULL);
934 * Return ch_flags for the current file.
936 public int
937 ch_getflags()
939 if (thisfile == NULL)
940 return (0);
941 return (ch_flags);
944 #if 0
945 public void
946 ch_dump(struct filestate *fs)
948 struct buf *bp;
949 struct bufnode *bn;
950 unsigned char *s;
952 if (fs == NULL)
954 printf(" --no filestate\n");
955 return;
957 printf(" file %d, flags %x, fpos %x, fsize %x, blk/off %x/%x\n",
958 fs->file, fs->flags, fs->fpos,
959 fs->fsize, fs->block, fs->offset);
960 printf(" %d bufs:\n", fs->nbufs);
961 for (bn = fs->next; bn != &fs->buflist; bn = bn->next)
963 bp = bufnode_buf(bn);
964 printf("%x: blk %x, size %x \"",
965 bp, bp->block, bp->datasize);
966 for (s = bp->data; s < bp->data + 30; s++)
967 if (*s >= ' ' && *s < 0x7F)
968 printf("%c", *s);
969 else
970 printf(".");
971 printf("\"\n");
974 #endif