xref: /freebsd/contrib/less/ch.c (revision 4523eebc6c1828d4fd41d7f1ab943cf079043bc8)
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 *help_data;
128 extern constant int size_help_data;
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(LM(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) help_data[ch_fpos];
279 			n = 1;
280 		} else
281 		{
282 			if (ch_file < 0)
283 				return (EOI);
284 			n = iread(ch_file, &bp->data[bp->datasize], LBUFSIZE - bp->datasize);
285 		}
286 
287 		read_again = FALSE;
288 		if (n == READ_INTR)
289 			return (EOI);
290 		if (n == READ_AGAIN)
291 		{
292 			read_again = TRUE;
293 			n = 0;
294 		}
295 		if (n < 0)
296 		{
297 #if MSDOS_COMPILER==WIN32C
298 			if (errno == EPIPE)
299 				n = 0;
300 			else
301 #endif
302 			{
303 				read_error = TRUE;
304 				return (EOI);
305 			}
306 		}
307 
308 #if LOGFILE
309 		/*
310 		 * If we have a log file, write the new data to it.
311 		 */
312 		if (secure_allow(SF_LOGFILE))
313 		{
314 			if (logfile >= 0 && n > 0)
315 				write(logfile, &bp->data[bp->datasize], (size_t) n);
316 		}
317 #endif
318 
319 		ch_fpos += n;
320 		bp->datasize += (size_t) n;
321 		if (read_pipe_at_eof)
322 			ch_set_eof(); /* update length of pipe */
323 
324 		if (n == 0)
325 		{
326 			/* Either end of file or no data available.
327 			 * read_again indicates the latter. */
328 			if (!read_again)
329 			{
330 				ch_fsize = pos;
331 				if (ch_flags & CH_POPENED)
332 				{
333 					/*
334 					 * ch_file is a pipe from a LESSOPEN child program.
335 					 * Since we've read to EOF, the child should have exited.
336 					 * Close the pipe now so the child does not remain a
337 					 * zombie. This also reports any error status from the
338 					 * child if -show-preproc-errors is enabled.
339 					 */
340 					close_pipe(get_altpipe(curr_ifile));
341 					set_altpipe(curr_ifile, NULL);
342 					ch_file = -1;
343 				}
344 			}
345 			if (ignore_eoi || read_again)
346 			{
347 				/* Wait a while, then try again. */
348 				if (!waiting_for_data)
349 				{
350 					PARG parg;
351 					parg.p_string = wait_message();
352 					ixerror("%s", &parg);
353 					waiting_for_data = TRUE;
354 				}
355 				sleep_ms(50); /* Reduce system load */
356 			}
357 			if (ignore_eoi && follow_mode == FOLLOW_NAME && curr_ifile_changed())
358 			{
359 				/* screen_trashed=2 causes make_display to reopen the file. */
360 				screen_trashed_num(2);
361 				return (EOI);
362 			}
363 			if (sigs)
364 				return (EOI);
365 			if (read_pipe_at_eof)
366 				/* No new data; we are still at EOF on the pipe. */
367 				return (EOI);
368 		}
369 
370 		found:
371 		if (ch_bufhead != bn)
372 		{
373 			/*
374 			 * Move the buffer to the head of the buffer chain.
375 			 * This orders the buffer chain, most- to least-recently used.
376 			 */
377 			BUF_RM(bn);
378 			BUF_INS_HEAD(bn);
379 
380 			/*
381 			 * Move to head of hash chain too.
382 			 */
383 			BUF_HASH_RM(bn);
384 			BUF_HASH_INS(bn, h);
385 		}
386 
387 		if (ch_offset < bp->datasize)
388 			break;
389 		/*
390 		 * After all that, we still don't have enough data.
391 		 * Go back and try again.
392 		 */
393 	}
394 	return (bp->data[ch_offset]);
395 }
396 
397 /*
398  * ch_ungetchar is a rather kludgy and limited way to push
399  * a single char onto an input file descriptor.
400  */
ch_ungetchar(int c)401 public void ch_ungetchar(int c)
402 {
403 	if (c < 0)
404 		ch_have_ungotchar = FALSE;
405 	else
406 	{
407 		if (ch_have_ungotchar)
408 			error(LM(ch_ungetchar_overrun), NULL_PARG);
409 		ch_ungotchar = (unsigned char) c;
410 		ch_have_ungotchar = TRUE;
411 	}
412 }
413 
414 #if LOGFILE
415 /*
416  * Close the logfile.
417  * If we haven't read all of standard input into it, do that now.
418  */
end_logfile(void)419 public void end_logfile(void)
420 {
421 	static lbool tried = FALSE;
422 
423 	if (logfile < 0)
424 		return;
425 	if (!tried && ch_fsize == NULL_POSITION)
426 	{
427 		tried = TRUE;
428 		ierror(LM(Finishing_logfile), NULL_PARG);
429 		while (ch_forw_get() != EOI)
430 			if (ABORT_SIGS())
431 				break;
432 	}
433 	close(logfile);
434 	logfile = -1;
435 	free(namelogfile);
436 	namelogfile = NULL;
437 	putstr("\n");
438 	flush();
439 }
440 
441 /*
442  * Start a log file AFTER less has already been running.
443  * Invoked from the - command; see toggle_option().
444  * Write all the existing buffered data to the log file.
445  */
sync_logfile(void)446 public void sync_logfile(void)
447 {
448 	struct buf *bp;
449 	struct bufnode *bn;
450 	lbool warned = FALSE;
451 	int h;
452 	BLOCKNUM block;
453 	BLOCKNUM nblocks;
454 
455 	if (logfile < 0)
456 		return;
457 	nblocks = (ch_fpos + LBUFSIZE - 1) / LBUFSIZE;
458 	for (block = 0;  block < nblocks;  block++)
459 	{
460 		lbool wrote = FALSE;
461 		h = BUFHASH(block);
462 		FOR_BUFS_IN_CHAIN(h, bn)
463 		{
464 			bp = bufnode_buf(bn);
465 			if (bp->block == block)
466 			{
467 				write(logfile, bp->data, bp->datasize);
468 				wrote = TRUE;
469 				break;
470 			}
471 		}
472 		if (!wrote && !warned)
473 		{
474 			error(LM(log_file_is_incomplete), NULL_PARG);
475 			warned = TRUE;
476 		}
477 	}
478 }
479 
480 #endif
481 
482 /*
483  * Determine if a specific block is currently in one of the buffers.
484  */
buffered(BLOCKNUM block)485 static lbool buffered(BLOCKNUM block)
486 {
487 	struct buf *bp;
488 	struct bufnode *bn;
489 	int h;
490 
491 	h = BUFHASH(block);
492 	FOR_BUFS_IN_CHAIN(h, bn)
493 	{
494 		bp = bufnode_buf(bn);
495 		if (bp->block == block)
496 			return (TRUE);
497 	}
498 	return (FALSE);
499 }
500 
501 /*
502  * Seek to a specified position in the file.
503  * Return 0 if successful, non-zero if can't seek there.
504  */
ch_seek(POSITION pos)505 public int ch_seek(POSITION pos)
506 {
507 	BLOCKNUM new_block;
508 	POSITION len;
509 
510 	if (thisfile == NULL)
511 		return (0);
512 
513 	len = ch_length();
514 	if (pos < ch_zero() || (len != NULL_POSITION && pos > len))
515 		return (1);
516 
517 	new_block = pos / LBUFSIZE;
518 	if (!(ch_flags & CH_CANSEEK) && pos != ch_fpos && !buffered(new_block))
519 	{
520 		if (ch_fpos > pos)
521 			return (1);
522 		while (ch_fpos < pos)
523 		{
524 			if (ch_forw_get() == EOI)
525 				return (1);
526 			if (ABORT_SIGS())
527 				return (1);
528 		}
529 		return (0);
530 	}
531 	/*
532 	 * Set read pointer.
533 	 */
534 	ch_block = new_block;
535 	ch_offset = (size_t) (pos % LBUFSIZE);
536 	return (0);
537 }
538 
539 /*
540  * Seek to the end of the file.
541  */
ch_end_seek(void)542 public int ch_end_seek(void)
543 {
544 	POSITION len;
545 
546 	if (thisfile == NULL)
547 		return (0);
548 
549 	if (ch_flags & CH_CANSEEK)
550 		ch_fsize = filesize(ch_file);
551 
552 	len = ch_length();
553 	if (len != NULL_POSITION)
554 		return (ch_seek(len));
555 
556 	/*
557 	 * Do it the slow way: read till end of data.
558 	 */
559 	while (ch_forw_get() != EOI)
560 		if (ABORT_SIGS())
561 			return (1);
562 	return (0);
563 }
564 
565 /*
566  * Seek to the last position in the file that is currently buffered.
567  */
ch_end_buffer_seek(void)568 public int ch_end_buffer_seek(void)
569 {
570 	struct buf *bp;
571 	struct bufnode *bn;
572 	POSITION buf_pos;
573 	POSITION end_pos;
574 
575 	if (thisfile == NULL || (ch_flags & CH_CANSEEK))
576 		return (ch_end_seek());
577 
578 	end_pos = 0;
579 	FOR_BUFS(bn)
580 	{
581 		bp = bufnode_buf(bn);
582 		buf_pos = ch_position(bp->block, bp->datasize);
583 		if (buf_pos > end_pos)
584 			end_pos = buf_pos;
585 	}
586 
587 	return (ch_seek(end_pos));
588 }
589 
590 /*
591  * Seek to the beginning of the file, or as close to it as we can get.
592  * We may not be able to seek there if input is a pipe and the
593  * beginning of the pipe is no longer buffered.
594  */
ch_beg_seek(void)595 public int ch_beg_seek(void)
596 {
597 	struct bufnode *bn;
598 	struct bufnode *firstbn;
599 
600 	/*
601 	 * Try a plain ch_seek first.
602 	 */
603 	if (ch_seek(ch_zero()) == 0)
604 		return (0);
605 
606 	/*
607 	 * Can't get to position 0.
608 	 * Look thru the buffers for the one closest to position 0.
609 	 */
610 	firstbn = ch_bufhead;
611 	if (firstbn == END_OF_CHAIN)
612 		return (1);
613 	FOR_BUFS(bn)
614 	{
615 		if (bufnode_buf(bn)->block < bufnode_buf(firstbn)->block)
616 			firstbn = bn;
617 	}
618 	ch_block = bufnode_buf(firstbn)->block;
619 	ch_offset = 0;
620 	return (0);
621 }
622 
623 /*
624  * Return the length of the file, if known.
625  */
ch_length(void)626 public POSITION ch_length(void)
627 {
628 	if (thisfile == NULL)
629 		return (NULL_POSITION);
630 	if (ignore_eoi)
631 		return (NULL_POSITION);
632 	if (ch_flags & CH_HELPFILE)
633 		return (size_help_data);
634 	if (ch_flags & CH_NODATA)
635 		return (0);
636 	return (ch_fsize);
637 }
638 
639 /*
640  * Update the file size, in case it has changed.
641  */
ch_resize(void)642 public void ch_resize(void)
643 {
644 	POSITION fsize;
645 
646 	if (!(ch_flags & CH_CANSEEK))
647 		return;
648 	fsize = filesize(ch_file);
649 	if (fsize != NULL_POSITION)
650 		ch_fsize = fsize;
651 }
652 
653 /*
654  * Return the current position in the file.
655  */
ch_tell(void)656 public POSITION ch_tell(void)
657 {
658 	if (thisfile == NULL)
659 		return (NULL_POSITION);
660 	return ch_position(ch_block, ch_offset);
661 }
662 
663 /*
664  * Get the current char and post-increment the read pointer.
665  */
ch_forw_get(void)666 public int ch_forw_get(void)
667 {
668 	int c;
669 
670 	if (thisfile == NULL)
671 		return (EOI);
672 	c = ch_get();
673 	if (c == EOI)
674 		return (EOI);
675 	if (ch_offset < LBUFSIZE-1)
676 		ch_offset++;
677 	else
678 	{
679 		ch_block ++;
680 		ch_offset = 0;
681 	}
682 	return (c);
683 }
684 
685 /*
686  * Pre-decrement the read pointer and get the new current char.
687  */
ch_back_get(void)688 public int ch_back_get(void)
689 {
690 	if (thisfile == NULL)
691 		return (EOI);
692 	if (ch_offset > 0)
693 		ch_offset --;
694 	else
695 	{
696 		if (ch_block <= 0)
697 			return (EOI);
698 		if (!(ch_flags & CH_CANSEEK) && !buffered(ch_block-1))
699 			return (EOI);
700 		ch_block--;
701 		ch_offset = LBUFSIZE-1;
702 	}
703 	return (ch_get());
704 }
705 
706 /*
707  * Set max amount of buffer space.
708  * bufspace is in units of 1024 bytes.  -1 mean no limit.
709  */
ch_setbufspace(ssize_t bufspace)710 public void ch_setbufspace(ssize_t bufspace)
711 {
712 	if (bufspace < 0)
713 		maxbufs = -1;
714 	else
715 	{
716 		size_t lbufk = LBUFSIZE / 1024;
717 		maxbufs = (int) (bufspace / lbufk + (bufspace % lbufk != 0));
718 		if (maxbufs < 1)
719 			maxbufs = 1;
720 	}
721 }
722 
723 /*
724  * Flush (discard) any saved file state, including buffer contents.
725  */
ch_flush(void)726 public void ch_flush(void)
727 {
728 	struct bufnode *bn;
729 
730 	if (thisfile == NULL)
731 		return;
732 
733 	if (!(ch_flags & CH_CANSEEK))
734 	{
735 		/*
736 		 * If input is a pipe, we don't flush buffer contents,
737 		 * since the contents can't be recovered.
738 		 */
739 		ch_fsize = NULL_POSITION;
740 		return;
741 	}
742 
743 	/*
744 	 * Initialize all the buffers.
745 	 */
746 	FOR_BUFS(bn)
747 	{
748 		bufnode_buf(bn)->block = -1;
749 	}
750 
751 	/*
752 	 * Seek to a known position: the beginning of the file.
753 	 */
754 	ch_fpos = 0;
755 	ch_block = 0; /* ch_fpos / LBUFSIZE; */
756 	ch_offset = 0; /* ch_fpos % LBUFSIZE; */
757 
758 	if (ch_flags & CH_NOTRUSTSIZE)
759 	{
760 		ch_fsize = NULL_POSITION;
761 		ch_flags &= ~CH_CANSEEK;
762 	} else
763 	{
764 		ch_fsize = (ch_flags & CH_HELPFILE) ? size_help_data : filesize(ch_file);
765 	}
766 
767 	if (less_lseek(ch_file, (less_off_t)0, SEEK_SET) == BAD_LSEEK)
768 	{
769 		/*
770 		 * Warning only; even if the seek fails for some reason,
771 		 * there's a good chance we're at the beginning anyway.
772 		 * {{ I think this is bogus reasoning. }}
773 		 */
774 		error(LM(seek_error_to_0), NULL_PARG);
775 	}
776 }
777 
778 /*
779  * Allocate a new buffer.
780  * The buffer is added to the tail of the buffer chain.
781  */
ch_addbuf(void)782 static int ch_addbuf(void)
783 {
784 	struct buf *bp;
785 	struct bufnode *bn;
786 
787 	/*
788 	 * Allocate and initialize a new buffer and link it
789 	 * onto the tail of the buffer list.
790 	 */
791 	bp = (struct buf *) calloc(1, sizeof(struct buf));
792 	if (bp == NULL)
793 		return (1);
794 	ch_nbufs++;
795 	bp->block = -1;
796 	bn = &bp->node;
797 
798 	BUF_INS_TAIL(bn);
799 	BUF_HASH_INS(bn, 0);
800 	return (0);
801 }
802 
803 /*
804  *
805  */
init_hashtbl(void)806 static void init_hashtbl(void)
807 {
808 	int h;
809 
810 	for (h = 0;  h < BUFHASH_SIZE;  h++)
811 	{
812 		thisfile->hashtbl[h].hnext = END_OF_HCHAIN(h);
813 		thisfile->hashtbl[h].hprev = END_OF_HCHAIN(h);
814 	}
815 }
816 
817 /*
818  * Delete all buffers for this file.
819  */
ch_delbufs(void)820 static void ch_delbufs(void)
821 {
822 	struct bufnode *bn;
823 
824 	while (ch_bufhead != END_OF_CHAIN)
825 	{
826 		bn = ch_bufhead;
827 		BUF_RM(bn);
828 		free(bufnode_buf(bn));
829 	}
830 	ch_nbufs = 0;
831 	init_hashtbl();
832 }
833 
834 /*
835  * Is it possible to seek on a file descriptor?
836  */
seekable(int f)837 public lbool seekable(int f)
838 {
839 #if MSDOS_COMPILER
840 	extern int fd0;
841 	if (f == fd0 && !isatty(fd0))
842 	{
843 		/*
844 		 * In MS-DOS, pipes are seekable.  Check for
845 		 * standard input, and pretend it is not seekable.
846 		 */
847 		return (FALSE);
848 	}
849 #endif
850 	return (less_lseek(f, (less_off_t)1, SEEK_SET) != BAD_LSEEK);
851 }
852 
853 /*
854  * Force EOF to be at the current read position.
855  * This is used after an ignore_eof read, during which the EOF may change.
856  */
ch_set_eof(void)857 public void ch_set_eof(void)
858 {
859 	if (ch_fsize != NULL_POSITION && ch_fsize < ch_fpos)
860 		ch_fsize = ch_fpos;
861 }
862 
863 
864 /*
865  * Initialize file state for a new file.
866  */
ch_init(int f,int flags,ssize_t nread)867 public void ch_init(int f, int flags, ssize_t nread)
868 {
869 	/*
870 	 * See if we already have a filestate for this file.
871 	 */
872 	thisfile = (struct filestate *) get_filestate(curr_ifile);
873 	if (thisfile == NULL)
874 	{
875 		/*
876 		 * Allocate and initialize a new filestate.
877 		 */
878 		thisfile = (struct filestate *)
879 				ecalloc(1, sizeof(struct filestate));
880 		thisfile->buflist.next = thisfile->buflist.prev = END_OF_CHAIN;
881 		thisfile->nbufs = 0;
882 		thisfile->flags = flags;
883 		thisfile->fpos = 0;
884 		thisfile->block = 0;
885 		thisfile->offset = 0;
886 		thisfile->file = -1;
887 		thisfile->fsize = NULL_POSITION;
888 		init_hashtbl();
889 		/*
890 		 * Try to seek; set CH_CANSEEK if it works.
891 		 */
892 		if ((flags & CH_CANSEEK) && !seekable(f))
893 			ch_flags &= ~CH_CANSEEK;
894 		set_filestate(curr_ifile, (void *) thisfile);
895 	}
896 	if (thisfile->file == -1)
897 		thisfile->file = f;
898 
899 	/*
900 	 * Figure out the size of the file, if we can.
901 	 */
902 	ch_fsize = (flags & CH_HELPFILE) ? size_help_data : filesize(ch_file);
903 
904 	if (ch_fsize == 0 && nread > 0)
905 	{
906 		/*
907 		 * This is a kludge to workaround a Linux kernel bug: files in some
908 		 * pseudo filesystems like /proc and tracefs have a size of 0 according
909 		 * to fstat() but have readable data.
910 		 */
911 		ch_flags |= CH_NOTRUSTSIZE;
912 	}
913 
914 	ch_flush();
915 }
916 
917 /*
918  * Close a filestate.
919  */
ch_close(void)920 public void ch_close(void)
921 {
922 	lbool keepstate = FALSE;
923 
924 	if (thisfile == NULL)
925 		return;
926 
927 	if ((ch_flags & (CH_CANSEEK|CH_POPENED|CH_HELPFILE)) && !(ch_flags & CH_KEEPOPEN))
928 	{
929 		/*
930 		 * We can seek or re-open, so we don't need to keep buffers.
931 		 */
932 		ch_delbufs();
933 	} else
934 		keepstate = TRUE;
935 	if (!(ch_flags & CH_KEEPOPEN))
936 	{
937 		/*
938 		 * We don't need to keep the file descriptor open
939 		 * (because we can re-open it.)
940 		 * But don't really close it if it was opened via popen(),
941 		 * because pclose() wants to close it.
942 		 */
943 		if (ch_file >= 0 && !(ch_flags & (CH_POPENED|CH_HELPFILE)))
944 			close(ch_file);
945 		ch_file = -1;
946 	} else
947 		keepstate = TRUE;
948 	if (!keepstate)
949 	{
950 		/*
951 		 * We don't even need to keep the filestate structure.
952 		 */
953 		free(thisfile);
954 		thisfile = NULL;
955 		set_filestate(curr_ifile, (void *) NULL);
956 	}
957 }
958 
959 /*
960  * Return ch_flags for the current file.
961  */
ch_getflags(void)962 public int ch_getflags(void)
963 {
964 	if (thisfile == NULL)
965 		return (0);
966 	return (ch_flags);
967 }
968 
969 #if 0
970 static void ch_dump(struct filestate *fs)
971 {
972 	struct buf *bp;
973 	struct bufnode *bn;
974 	unsigned char *s;
975 
976 	if (fs == NULL)
977 	{
978 		printf(" --no filestate\n");
979 		return;
980 	}
981 	printf(" file %d, flags %x, fpos %x, fsize %x, blk/off %x/%x\n",
982 		fs->file, fs->flags, fs->fpos,
983 		fs->fsize, fs->block, fs->offset);
984 	printf(" %d bufs:\n", fs->nbufs);
985 	for (bn = fs->next; bn != &fs->buflist;  bn = bn->next)
986 	{
987 		bp = bufnode_buf(bn);
988 		printf("%x: blk %x, size %x \"",
989 			bp, bp->block, bp->datasize);
990 		for (s = bp->data;  s < bp->data + 30;  s++)
991 			if (*s >= ' ' && *s < 0x7F)
992 				printf("%c", *s);
993 			else
994 				printf(".");
995 		printf("\"\n");
996 	}
997 }
998 #endif
999