xref: /freebsd/contrib/less/ch.c (revision fa0dc4f0f96a1b77d4be7bcdbf965897cda14521)
1 /*
2  * Copyright (C) 1984-2026  Mark Nudelman
3  *
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.
6  *
7  * For more information, see the README file.
8  */
9 
10 
11 /*
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.
15  */
16 
17 #include "less.h"
18 #if MSDOS_COMPILER==WIN32C
19 #include <errno.h>
20 #include <windows.h>
21 #endif
22 
23 typedef POSITION BLOCKNUM;
24 
25 public lbool ignore_eoi = FALSE;
26 public lbool read_error = FALSE;
27 
28 /*
29  * Pool of buffers holding the most recently used blocks of the input file.
30  * The buffer pool is kept as a doubly-linked circular list,
31  * in order from most- to least-recently used.
32  * The circular list is anchored by the file state "thisfile".
33  */
34 struct bufnode {
35 	struct bufnode *next, *prev;
36 	struct bufnode *hnext, *hprev;
37 };
38 
39 #define LBUFSIZE        8192
40 struct buf {
41 	struct bufnode node;
42 	BLOCKNUM block;
43 	size_t datasize;
44 	unsigned char data[LBUFSIZE];
45 };
46 #define bufnode_buf(bn)  ((struct buf *) bn)
47 
48 /*
49  * The file state is maintained in a filestate structure.
50  * A pointer to the filestate is kept in the ifile structure.
51  */
52 #define BUFHASH_SIZE    1024
53 struct filestate {
54 	struct bufnode buflist;
55 	struct bufnode hashtbl[BUFHASH_SIZE];
56 	int file;
57 	int flags;
58 	POSITION fpos;
59 	int nbufs;
60 	BLOCKNUM block;
61 	size_t offset;
62 	POSITION fsize;
63 };
64 
65 #define ch_bufhead      thisfile->buflist.next
66 #define ch_buftail      thisfile->buflist.prev
67 #define ch_nbufs        thisfile->nbufs
68 #define ch_block        thisfile->block
69 #define ch_offset       thisfile->offset
70 #define ch_fpos         thisfile->fpos
71 #define ch_fsize        thisfile->fsize
72 #define ch_flags        thisfile->flags
73 #define ch_file         thisfile->file
74 
75 #define END_OF_CHAIN    (&thisfile->buflist)
76 #define END_OF_HCHAIN(h) (&thisfile->hashtbl[h])
77 #define BUFHASH(blk)    ((blk) & (BUFHASH_SIZE-1))
78 
79 /*
80  * Macros to manipulate the list of buffers in thisfile->buflist.
81  */
82 #define FOR_BUFS(bn) \
83 	for (bn = ch_bufhead;  bn != END_OF_CHAIN;  bn = bn->next)
84 
85 #define BUF_RM(bn) \
86 	(bn)->next->prev = (bn)->prev; \
87 	(bn)->prev->next = (bn)->next;
88 
89 #define BUF_INS_HEAD(bn) \
90 	(bn)->next = ch_bufhead; \
91 	(bn)->prev = END_OF_CHAIN; \
92 	ch_bufhead->prev = (bn); \
93 	ch_bufhead = (bn);
94 
95 #define BUF_INS_TAIL(bn) \
96 	(bn)->next = END_OF_CHAIN; \
97 	(bn)->prev = ch_buftail; \
98 	ch_buftail->next = (bn); \
99 	ch_buftail = (bn);
100 
101 /*
102  * Macros to manipulate the list of buffers in thisfile->hashtbl[n].
103  */
104 #define FOR_BUFS_IN_CHAIN(h,bn) \
105 	for (bn = thisfile->hashtbl[h].hnext;  \
106 	     bn != END_OF_HCHAIN(h);  bn = bn->hnext)
107 
108 #define BUF_HASH_RM(bn) \
109 	(bn)->hnext->hprev = (bn)->hprev; \
110 	(bn)->hprev->hnext = (bn)->hnext;
111 
112 #define BUF_HASH_INS(bn,h) \
113 	(bn)->hnext = thisfile->hashtbl[h].hnext; \
114 	(bn)->hprev = END_OF_HCHAIN(h); \
115 	thisfile->hashtbl[h].hnext->hprev = (bn); \
116 	thisfile->hashtbl[h].hnext = (bn);
117 
118 static struct filestate *thisfile;
119 static unsigned char ch_ungotchar;
120 static lbool ch_have_ungotchar = FALSE;
121 static int maxbufs = -1;
122 
123 extern int autobuf;
124 extern int sigs;
125 extern int follow_mode;
126 extern lbool waiting_for_data;
127 extern constant char helpdata[];
128 extern constant int size_helpdata;
129 extern IFILE curr_ifile;
130 #if LOGFILE
131 extern int logfile;
132 extern char *namelogfile;
133 #endif
134 
135 static int ch_addbuf();
136 
137 /*
138  * Return the file position corresponding to an offset within a block.
139  */
ch_position(BLOCKNUM block,size_t offset)140 static POSITION ch_position(BLOCKNUM block, size_t offset)
141 {
142 	return (block * LBUFSIZE) + (POSITION) offset;
143 }
144 
145 /*
146  * Get the character pointed to by the read pointer.
147  */
ch_get(void)148 static int ch_get(void)
149 {
150 	struct buf *bp;
151 	struct bufnode *bn;
152 	ssize_t n;
153 	int h;
154 
155 	if (thisfile == NULL)
156 		return (EOI);
157 
158 	/*
159 	 * Quick check for the common case where
160 	 * the desired char is in the head buffer.
161 	 */
162 	if (ch_bufhead != END_OF_CHAIN)
163 	{
164 		bp = bufnode_buf(ch_bufhead);
165 		if (ch_block == bp->block && ch_offset < bp->datasize)
166 			return bp->data[ch_offset];
167 	}
168 
169 	/*
170 	 * Look for a buffer holding the desired block.
171 	 */
172 	waiting_for_data = FALSE;
173 	h = BUFHASH(ch_block);
174 	FOR_BUFS_IN_CHAIN(h, bn)
175 	{
176 		bp = bufnode_buf(bn);
177 		if (bp->block == ch_block)
178 		{
179 			if (ch_offset >= bp->datasize)
180 				/*
181 				 * Need more data in this buffer.
182 				 */
183 				break;
184 			goto found;
185 		}
186 	}
187 	if (ABORT_SIGS())
188 		return (EOI);
189 	if (bn == END_OF_HCHAIN(h))
190 	{
191 		/*
192 		 * Block is not in a buffer.
193 		 * Take the least recently used buffer
194 		 * and read the desired block into it.
195 		 * If the LRU buffer has data in it,
196 		 * then maybe allocate a new buffer.
197 		 */
198 		if (ch_buftail == END_OF_CHAIN ||
199 			bufnode_buf(ch_buftail)->block != -1)
200 		{
201 			/*
202 			 * There is no empty buffer to use.
203 			 * Allocate a new buffer if:
204 			 * 1. We can't seek on this file and -b is not in effect; or
205 			 * 2. We haven't allocated the max buffers for this file yet.
206 			 */
207 			if ((autobuf && !(ch_flags & CH_CANSEEK)) ||
208 				(maxbufs < 0 || ch_nbufs < maxbufs))
209 				if (ch_addbuf())
210 					/*
211 					 * Allocation failed: turn off autobuf.
212 					 */
213 					autobuf = OPT_OFF;
214 		}
215 		bn = ch_buftail;
216 		bp = bufnode_buf(bn);
217 		BUF_HASH_RM(bn); /* Remove from old hash chain. */
218 		bp->block = ch_block;
219 		bp->datasize = 0;
220 		BUF_HASH_INS(bn, h); /* Insert into new hash chain. */
221 	}
222 
223 	for (;;)
224 	{
225 		lbool read_again;
226 		POSITION len;
227 		POSITION pos = ch_position(ch_block, bp->datasize);
228 		lbool read_pipe_at_eof = FALSE;
229 		if ((len = ch_length()) != NULL_POSITION && pos >= len)
230 		{
231 			/*
232 			 * Apparently at end of file.
233 			 * Double-check the file size in case it has changed.
234 			 */
235 			ch_resize();
236 			if ((len = ch_length()) != NULL_POSITION && pos >= len)
237 			{
238 				if (ch_flags & (CH_CANSEEK|CH_HELPFILE))
239 					return (EOI);
240 				/* ch_length doesn't work for pipes, so just try to
241 				 * read from the pipe to see if more data has appeared.
242 				 * This can happen only in limited situations, such as
243 				 * a fifo that the writer has closed and reopened. */
244 				read_pipe_at_eof = TRUE;
245 			}
246 		}
247 
248 		if (pos != ch_fpos)
249 		{
250 			/*
251 			 * Not at the correct position: must seek.
252 			 * If input is a pipe, we're in trouble (can't seek on a pipe).
253 			 * Some data has been lost: just return "?".
254 			 */
255 			if (!(ch_flags & CH_CANSEEK))
256 				return ('?');
257 			if (less_lseek(ch_file, (less_off_t)pos, SEEK_SET) == BAD_LSEEK)
258 			{
259 				error("seek error", NULL_PARG);
260 				clear_eol();
261 				return (EOI);
262 			}
263 			ch_fpos = pos;
264 		}
265 
266 		/*
267 		 * Read the block.
268 		 * If we read less than a full block, that's ok.
269 		 * We use partial block and pick up the rest next time.
270 		 */
271 		if (ch_have_ungotchar)
272 		{
273 			bp->data[bp->datasize] = ch_ungotchar;
274 			n = 1;
275 			ch_have_ungotchar = FALSE;
276 		} else if (ch_flags & CH_HELPFILE)
277 		{
278 			bp->data[bp->datasize] = (unsigned char) helpdata[ch_fpos];
279 			n = 1;
280 		} else
281 		{
282 			n = iread(ch_file, &bp->data[bp->datasize], LBUFSIZE - bp->datasize);
283 		}
284 
285 		read_again = FALSE;
286 		if (n == READ_INTR)
287 			return (EOI);
288 		if (n == READ_AGAIN)
289 		{
290 			read_again = TRUE;
291 			n = 0;
292 		}
293 		if (n < 0)
294 		{
295 #if MSDOS_COMPILER==WIN32C
296 			if (errno == EPIPE)
297 				n = 0;
298 			else
299 #endif
300 			{
301 				read_error = TRUE;
302 				return (EOI);
303 			}
304 		}
305 
306 #if LOGFILE
307 		/*
308 		 * If we have a log file, write the new data to it.
309 		 */
310 		if (secure_allow(SF_LOGFILE))
311 		{
312 			if (logfile >= 0 && n > 0)
313 				write(logfile, &bp->data[bp->datasize], (size_t) n);
314 		}
315 #endif
316 
317 		ch_fpos += n;
318 		bp->datasize += (size_t) n;
319 		if (read_pipe_at_eof)
320 			ch_set_eof(); /* update length of pipe */
321 
322 		if (n == 0)
323 		{
324 			/* Either end of file or no data available.
325 			 * read_again indicates the latter. */
326 			if (!read_again)
327 				ch_fsize = pos;
328 			if (ignore_eoi || read_again)
329 			{
330 				/* Wait a while, then try again. */
331 				if (!waiting_for_data)
332 				{
333 					PARG parg;
334 					parg.p_string = wait_message();
335 					ixerror("%s", &parg);
336 					waiting_for_data = TRUE;
337 				}
338 				sleep_ms(50); /* Reduce system load */
339 			}
340 			if (ignore_eoi && follow_mode == FOLLOW_NAME && curr_ifile_changed())
341 			{
342 				/* screen_trashed=2 causes make_display to reopen the file. */
343 				screen_trashed_num(2);
344 				return (EOI);
345 			}
346 			if (sigs)
347 				return (EOI);
348 			if (read_pipe_at_eof)
349 				/* No new data; we are still at EOF on the pipe. */
350 				return (EOI);
351 		}
352 
353 		found:
354 		if (ch_bufhead != bn)
355 		{
356 			/*
357 			 * Move the buffer to the head of the buffer chain.
358 			 * This orders the buffer chain, most- to least-recently used.
359 			 */
360 			BUF_RM(bn);
361 			BUF_INS_HEAD(bn);
362 
363 			/*
364 			 * Move to head of hash chain too.
365 			 */
366 			BUF_HASH_RM(bn);
367 			BUF_HASH_INS(bn, h);
368 		}
369 
370 		if (ch_offset < bp->datasize)
371 			break;
372 		/*
373 		 * After all that, we still don't have enough data.
374 		 * Go back and try again.
375 		 */
376 	}
377 	return (bp->data[ch_offset]);
378 }
379 
380 /*
381  * ch_ungetchar is a rather kludgy and limited way to push
382  * a single char onto an input file descriptor.
383  */
ch_ungetchar(int c)384 public void ch_ungetchar(int c)
385 {
386 	if (c < 0)
387 		ch_have_ungotchar = FALSE;
388 	else
389 	{
390 		if (ch_have_ungotchar)
391 			error("ch_ungetchar overrun", NULL_PARG);
392 		ch_ungotchar = (unsigned char) c;
393 		ch_have_ungotchar = TRUE;
394 	}
395 }
396 
397 #if LOGFILE
398 /*
399  * Close the logfile.
400  * If we haven't read all of standard input into it, do that now.
401  */
end_logfile(void)402 public void end_logfile(void)
403 {
404 	static lbool tried = FALSE;
405 
406 	if (logfile < 0)
407 		return;
408 	if (!tried && ch_fsize == NULL_POSITION)
409 	{
410 		tried = TRUE;
411 		ierror("Finishing logfile", NULL_PARG);
412 		while (ch_forw_get() != EOI)
413 			if (ABORT_SIGS())
414 				break;
415 	}
416 	close(logfile);
417 	logfile = -1;
418 	free(namelogfile);
419 	namelogfile = NULL;
420 	putstr("\n");
421 	flush();
422 }
423 
424 /*
425  * Start a log file AFTER less has already been running.
426  * Invoked from the - command; see toggle_option().
427  * Write all the existing buffered data to the log file.
428  */
sync_logfile(void)429 public void sync_logfile(void)
430 {
431 	struct buf *bp;
432 	struct bufnode *bn;
433 	lbool warned = FALSE;
434 	int h;
435 	BLOCKNUM block;
436 	BLOCKNUM nblocks;
437 
438 	if (logfile < 0)
439 		return;
440 	nblocks = (ch_fpos + LBUFSIZE - 1) / LBUFSIZE;
441 	for (block = 0;  block < nblocks;  block++)
442 	{
443 		lbool wrote = FALSE;
444 		h = BUFHASH(block);
445 		FOR_BUFS_IN_CHAIN(h, bn)
446 		{
447 			bp = bufnode_buf(bn);
448 			if (bp->block == block)
449 			{
450 				write(logfile, bp->data, bp->datasize);
451 				wrote = TRUE;
452 				break;
453 			}
454 		}
455 		if (!wrote && !warned)
456 		{
457 			error("Warning: log file is incomplete",
458 				NULL_PARG);
459 			warned = TRUE;
460 		}
461 	}
462 }
463 
464 #endif
465 
466 /*
467  * Determine if a specific block is currently in one of the buffers.
468  */
buffered(BLOCKNUM block)469 static lbool buffered(BLOCKNUM block)
470 {
471 	struct buf *bp;
472 	struct bufnode *bn;
473 	int h;
474 
475 	h = BUFHASH(block);
476 	FOR_BUFS_IN_CHAIN(h, bn)
477 	{
478 		bp = bufnode_buf(bn);
479 		if (bp->block == block)
480 			return (TRUE);
481 	}
482 	return (FALSE);
483 }
484 
485 /*
486  * Seek to a specified position in the file.
487  * Return 0 if successful, non-zero if can't seek there.
488  */
ch_seek(POSITION pos)489 public int ch_seek(POSITION pos)
490 {
491 	BLOCKNUM new_block;
492 	POSITION len;
493 
494 	if (thisfile == NULL)
495 		return (0);
496 
497 	len = ch_length();
498 	if (pos < ch_zero() || (len != NULL_POSITION && pos > len))
499 		return (1);
500 
501 	new_block = pos / LBUFSIZE;
502 	if (!(ch_flags & CH_CANSEEK) && pos != ch_fpos && !buffered(new_block))
503 	{
504 		if (ch_fpos > pos)
505 			return (1);
506 		while (ch_fpos < pos)
507 		{
508 			if (ch_forw_get() == EOI)
509 				return (1);
510 			if (ABORT_SIGS())
511 				return (1);
512 		}
513 		return (0);
514 	}
515 	/*
516 	 * Set read pointer.
517 	 */
518 	ch_block = new_block;
519 	ch_offset = (size_t) (pos % LBUFSIZE);
520 	return (0);
521 }
522 
523 /*
524  * Seek to the end of the file.
525  */
ch_end_seek(void)526 public int ch_end_seek(void)
527 {
528 	POSITION len;
529 
530 	if (thisfile == NULL)
531 		return (0);
532 
533 	if (ch_flags & CH_CANSEEK)
534 		ch_fsize = filesize(ch_file);
535 
536 	len = ch_length();
537 	if (len != NULL_POSITION)
538 		return (ch_seek(len));
539 
540 	/*
541 	 * Do it the slow way: read till end of data.
542 	 */
543 	while (ch_forw_get() != EOI)
544 		if (ABORT_SIGS())
545 			return (1);
546 	return (0);
547 }
548 
549 /*
550  * Seek to the last position in the file that is currently buffered.
551  */
ch_end_buffer_seek(void)552 public int ch_end_buffer_seek(void)
553 {
554 	struct buf *bp;
555 	struct bufnode *bn;
556 	POSITION buf_pos;
557 	POSITION end_pos;
558 
559 	if (thisfile == NULL || (ch_flags & CH_CANSEEK))
560 		return (ch_end_seek());
561 
562 	end_pos = 0;
563 	FOR_BUFS(bn)
564 	{
565 		bp = bufnode_buf(bn);
566 		buf_pos = ch_position(bp->block, bp->datasize);
567 		if (buf_pos > end_pos)
568 			end_pos = buf_pos;
569 	}
570 
571 	return (ch_seek(end_pos));
572 }
573 
574 /*
575  * Seek to the beginning of the file, or as close to it as we can get.
576  * We may not be able to seek there if input is a pipe and the
577  * beginning of the pipe is no longer buffered.
578  */
ch_beg_seek(void)579 public int ch_beg_seek(void)
580 {
581 	struct bufnode *bn;
582 	struct bufnode *firstbn;
583 
584 	/*
585 	 * Try a plain ch_seek first.
586 	 */
587 	if (ch_seek(ch_zero()) == 0)
588 		return (0);
589 
590 	/*
591 	 * Can't get to position 0.
592 	 * Look thru the buffers for the one closest to position 0.
593 	 */
594 	firstbn = ch_bufhead;
595 	if (firstbn == END_OF_CHAIN)
596 		return (1);
597 	FOR_BUFS(bn)
598 	{
599 		if (bufnode_buf(bn)->block < bufnode_buf(firstbn)->block)
600 			firstbn = bn;
601 	}
602 	ch_block = bufnode_buf(firstbn)->block;
603 	ch_offset = 0;
604 	return (0);
605 }
606 
607 /*
608  * Return the length of the file, if known.
609  */
ch_length(void)610 public POSITION ch_length(void)
611 {
612 	if (thisfile == NULL)
613 		return (NULL_POSITION);
614 	if (ignore_eoi)
615 		return (NULL_POSITION);
616 	if (ch_flags & CH_HELPFILE)
617 		return (size_helpdata);
618 	if (ch_flags & CH_NODATA)
619 		return (0);
620 	return (ch_fsize);
621 }
622 
623 /*
624  * Update the file size, in case it has changed.
625  */
ch_resize(void)626 public void ch_resize(void)
627 {
628 	POSITION fsize;
629 
630 	if (!(ch_flags & CH_CANSEEK))
631 		return;
632 	fsize = filesize(ch_file);
633 	if (fsize != NULL_POSITION)
634 		ch_fsize = fsize;
635 }
636 
637 /*
638  * Return the current position in the file.
639  */
ch_tell(void)640 public POSITION ch_tell(void)
641 {
642 	if (thisfile == NULL)
643 		return (NULL_POSITION);
644 	return ch_position(ch_block, ch_offset);
645 }
646 
647 /*
648  * Get the current char and post-increment the read pointer.
649  */
ch_forw_get(void)650 public int ch_forw_get(void)
651 {
652 	int c;
653 
654 	if (thisfile == NULL)
655 		return (EOI);
656 	c = ch_get();
657 	if (c == EOI)
658 		return (EOI);
659 	if (ch_offset < LBUFSIZE-1)
660 		ch_offset++;
661 	else
662 	{
663 		ch_block ++;
664 		ch_offset = 0;
665 	}
666 	return (c);
667 }
668 
669 /*
670  * Pre-decrement the read pointer and get the new current char.
671  */
ch_back_get(void)672 public int ch_back_get(void)
673 {
674 	if (thisfile == NULL)
675 		return (EOI);
676 	if (ch_offset > 0)
677 		ch_offset --;
678 	else
679 	{
680 		if (ch_block <= 0)
681 			return (EOI);
682 		if (!(ch_flags & CH_CANSEEK) && !buffered(ch_block-1))
683 			return (EOI);
684 		ch_block--;
685 		ch_offset = LBUFSIZE-1;
686 	}
687 	return (ch_get());
688 }
689 
690 /*
691  * Set max amount of buffer space.
692  * bufspace is in units of 1024 bytes.  -1 mean no limit.
693  */
ch_setbufspace(ssize_t bufspace)694 public void ch_setbufspace(ssize_t bufspace)
695 {
696 	if (bufspace < 0)
697 		maxbufs = -1;
698 	else
699 	{
700 		size_t lbufk = LBUFSIZE / 1024;
701 		maxbufs = (int) (bufspace / lbufk + (bufspace % lbufk != 0));
702 		if (maxbufs < 1)
703 			maxbufs = 1;
704 	}
705 }
706 
707 /*
708  * Flush (discard) any saved file state, including buffer contents.
709  */
ch_flush(void)710 public void ch_flush(void)
711 {
712 	struct bufnode *bn;
713 
714 	if (thisfile == NULL)
715 		return;
716 
717 	if (!(ch_flags & CH_CANSEEK))
718 	{
719 		/*
720 		 * If input is a pipe, we don't flush buffer contents,
721 		 * since the contents can't be recovered.
722 		 */
723 		ch_fsize = NULL_POSITION;
724 		return;
725 	}
726 
727 	/*
728 	 * Initialize all the buffers.
729 	 */
730 	FOR_BUFS(bn)
731 	{
732 		bufnode_buf(bn)->block = -1;
733 	}
734 
735 	/*
736 	 * Seek to a known position: the beginning of the file.
737 	 */
738 	ch_fpos = 0;
739 	ch_block = 0; /* ch_fpos / LBUFSIZE; */
740 	ch_offset = 0; /* ch_fpos % LBUFSIZE; */
741 
742 	if (ch_flags & CH_NOTRUSTSIZE)
743 	{
744 		ch_fsize = NULL_POSITION;
745 		ch_flags &= ~CH_CANSEEK;
746 	} else
747 	{
748 		ch_fsize = (ch_flags & CH_HELPFILE) ? size_helpdata : filesize(ch_file);
749 	}
750 
751 	if (less_lseek(ch_file, (less_off_t)0, SEEK_SET) == BAD_LSEEK)
752 	{
753 		/*
754 		 * Warning only; even if the seek fails for some reason,
755 		 * there's a good chance we're at the beginning anyway.
756 		 * {{ I think this is bogus reasoning. }}
757 		 */
758 		error("seek error to 0", NULL_PARG);
759 	}
760 }
761 
762 /*
763  * Allocate a new buffer.
764  * The buffer is added to the tail of the buffer chain.
765  */
ch_addbuf(void)766 static int ch_addbuf(void)
767 {
768 	struct buf *bp;
769 	struct bufnode *bn;
770 
771 	/*
772 	 * Allocate and initialize a new buffer and link it
773 	 * onto the tail of the buffer list.
774 	 */
775 	bp = (struct buf *) calloc(1, sizeof(struct buf));
776 	if (bp == NULL)
777 		return (1);
778 	ch_nbufs++;
779 	bp->block = -1;
780 	bn = &bp->node;
781 
782 	BUF_INS_TAIL(bn);
783 	BUF_HASH_INS(bn, 0);
784 	return (0);
785 }
786 
787 /*
788  *
789  */
init_hashtbl(void)790 static void init_hashtbl(void)
791 {
792 	int h;
793 
794 	for (h = 0;  h < BUFHASH_SIZE;  h++)
795 	{
796 		thisfile->hashtbl[h].hnext = END_OF_HCHAIN(h);
797 		thisfile->hashtbl[h].hprev = END_OF_HCHAIN(h);
798 	}
799 }
800 
801 /*
802  * Delete all buffers for this file.
803  */
ch_delbufs(void)804 static void ch_delbufs(void)
805 {
806 	struct bufnode *bn;
807 
808 	while (ch_bufhead != END_OF_CHAIN)
809 	{
810 		bn = ch_bufhead;
811 		BUF_RM(bn);
812 		free(bufnode_buf(bn));
813 	}
814 	ch_nbufs = 0;
815 	init_hashtbl();
816 }
817 
818 /*
819  * Is it possible to seek on a file descriptor?
820  */
seekable(int f)821 public int seekable(int f)
822 {
823 #if MSDOS_COMPILER
824 	extern int fd0;
825 	if (f == fd0 && !isatty(fd0))
826 	{
827 		/*
828 		 * In MS-DOS, pipes are seekable.  Check for
829 		 * standard input, and pretend it is not seekable.
830 		 */
831 		return (0);
832 	}
833 #endif
834 	return (less_lseek(f, (less_off_t)1, SEEK_SET) != BAD_LSEEK);
835 }
836 
837 /*
838  * Force EOF to be at the current read position.
839  * This is used after an ignore_eof read, during which the EOF may change.
840  */
ch_set_eof(void)841 public void ch_set_eof(void)
842 {
843 	if (ch_fsize != NULL_POSITION && ch_fsize < ch_fpos)
844 		ch_fsize = ch_fpos;
845 }
846 
847 
848 /*
849  * Initialize file state for a new file.
850  */
ch_init(int f,int flags,ssize_t nread)851 public void ch_init(int f, int flags, ssize_t nread)
852 {
853 	/*
854 	 * See if we already have a filestate for this file.
855 	 */
856 	thisfile = (struct filestate *) get_filestate(curr_ifile);
857 	if (thisfile == NULL)
858 	{
859 		/*
860 		 * Allocate and initialize a new filestate.
861 		 */
862 		thisfile = (struct filestate *)
863 				ecalloc(1, sizeof(struct filestate));
864 		thisfile->buflist.next = thisfile->buflist.prev = END_OF_CHAIN;
865 		thisfile->nbufs = 0;
866 		thisfile->flags = flags;
867 		thisfile->fpos = 0;
868 		thisfile->block = 0;
869 		thisfile->offset = 0;
870 		thisfile->file = -1;
871 		thisfile->fsize = NULL_POSITION;
872 		init_hashtbl();
873 		/*
874 		 * Try to seek; set CH_CANSEEK if it works.
875 		 */
876 		if ((flags & CH_CANSEEK) && !seekable(f))
877 			ch_flags &= ~CH_CANSEEK;
878 		set_filestate(curr_ifile, (void *) thisfile);
879 	}
880 	if (thisfile->file == -1)
881 		thisfile->file = f;
882 
883 	/*
884 	 * Figure out the size of the file, if we can.
885 	 */
886 	ch_fsize = (flags & CH_HELPFILE) ? size_helpdata : filesize(ch_file);
887 
888 	if (ch_fsize == 0 && nread > 0)
889 	{
890 		/*
891 		 * This is a kludge to workaround a Linux kernel bug: files in some
892 		 * pseudo filesystems like /proc and tracefs have a size of 0 according
893 		 * to fstat() but have readable data.
894 		 */
895 		ch_flags |= CH_NOTRUSTSIZE;
896 	}
897 
898 	ch_flush();
899 }
900 
901 /*
902  * Close a filestate.
903  */
ch_close(void)904 public void ch_close(void)
905 {
906 	lbool keepstate = FALSE;
907 
908 	if (thisfile == NULL)
909 		return;
910 
911 	if ((ch_flags & (CH_CANSEEK|CH_POPENED|CH_HELPFILE)) && !(ch_flags & CH_KEEPOPEN))
912 	{
913 		/*
914 		 * We can seek or re-open, so we don't need to keep buffers.
915 		 */
916 		ch_delbufs();
917 	} else
918 		keepstate = TRUE;
919 	if (!(ch_flags & CH_KEEPOPEN))
920 	{
921 		/*
922 		 * We don't need to keep the file descriptor open
923 		 * (because we can re-open it.)
924 		 * But don't really close it if it was opened via popen(),
925 		 * because pclose() wants to close it.
926 		 */
927 		if (!(ch_flags & (CH_POPENED|CH_HELPFILE)))
928 			close(ch_file);
929 		ch_file = -1;
930 	} else
931 		keepstate = TRUE;
932 	if (!keepstate)
933 	{
934 		/*
935 		 * We don't even need to keep the filestate structure.
936 		 */
937 		free(thisfile);
938 		thisfile = NULL;
939 		set_filestate(curr_ifile, (void *) NULL);
940 	}
941 }
942 
943 /*
944  * Return ch_flags for the current file.
945  */
ch_getflags(void)946 public int ch_getflags(void)
947 {
948 	if (thisfile == NULL)
949 		return (0);
950 	return (ch_flags);
951 }
952 
953 #if 0
954 static void ch_dump(struct filestate *fs)
955 {
956 	struct buf *bp;
957 	struct bufnode *bn;
958 	unsigned char *s;
959 
960 	if (fs == NULL)
961 	{
962 		printf(" --no filestate\n");
963 		return;
964 	}
965 	printf(" file %d, flags %x, fpos %x, fsize %x, blk/off %x/%x\n",
966 		fs->file, fs->flags, fs->fpos,
967 		fs->fsize, fs->block, fs->offset);
968 	printf(" %d bufs:\n", fs->nbufs);
969 	for (bn = fs->next; bn != &fs->buflist;  bn = bn->next)
970 	{
971 		bp = bufnode_buf(bn);
972 		printf("%x: blk %x, size %x \"",
973 			bp, bp->block, bp->datasize);
974 		for (s = bp->data;  s < bp->data + 30;  s++)
975 			if (*s >= ' ' && *s < 0x7F)
976 				printf("%c", *s);
977 			else
978 				printf(".");
979 		printf("\"\n");
980 	}
981 }
982 #endif
983