1 /* vi: set sw=4 ts=4: */
2 /*
3  * Utility routines.
4  *
5  * Copyright (C) many different people.
6  * If you wrote this, please acknowledge your work.
7  *
8  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
9  */
10 
11 #include "libbb.h"
12 
xmalloc_fgets_internal(FILE * file,const char * terminating_string,int chop_off,size_t * maxsz_p)13 static char *xmalloc_fgets_internal(FILE *file, const char *terminating_string, int chop_off, size_t *maxsz_p)
14 {
15 	char *linebuf = NULL;
16 	const int term_length = strlen(terminating_string);
17 	int end_string_offset;
18 	int linebufsz = 0;
19 	int idx = 0;
20 	int ch;
21 	size_t maxsz = *maxsz_p;
22 
23 	while (1) {
24 		ch = fgetc(file);
25 		if (ch == EOF) {
26 			if (idx == 0)
27 				return linebuf; /* NULL */
28 			break;
29 		}
30 
31 		if (idx >= linebufsz) {
32 			linebufsz += 200;
33 			linebuf = xrealloc(linebuf, linebufsz);
34 			if (idx >= maxsz) {
35 				linebuf[idx] = ch;
36 				idx++;
37 				break;
38 			}
39 		}
40 
41 		linebuf[idx] = ch;
42 		idx++;
43 
44 		/* Check for terminating string */
45 		end_string_offset = idx - term_length;
46 		if (end_string_offset >= 0
47 		 && memcmp(&linebuf[end_string_offset], terminating_string, term_length) == 0
48 		) {
49 			if (chop_off)
50 				idx -= term_length;
51 			break;
52 		}
53 	}
54 	/* Grow/shrink *first*, then store NUL */
55 	linebuf = xrealloc(linebuf, idx + 1);
56 	linebuf[idx] = '\0';
57 	*maxsz_p = idx;
58 	return linebuf;
59 }
60 
61 /* Read up to TERMINATING_STRING from FILE and return it,
62  * including terminating string.
63  * Non-terminated string can be returned if EOF is reached.
64  * Return NULL if EOF is reached immediately.  */
xmalloc_fgets_str(FILE * file,const char * terminating_string)65 char* FAST_FUNC xmalloc_fgets_str(FILE *file, const char *terminating_string)
66 {
67 	size_t maxsz = INT_MAX - 4095;
68 	return xmalloc_fgets_internal(file, terminating_string, 0, &maxsz);
69 }
70 
xmalloc_fgets_str_len(FILE * file,const char * terminating_string,size_t * maxsz_p)71 char* FAST_FUNC xmalloc_fgets_str_len(FILE *file, const char *terminating_string, size_t *maxsz_p)
72 {
73 	size_t maxsz;
74 
75 	if (!maxsz_p) {
76 		maxsz = INT_MAX - 4095;
77 		maxsz_p = &maxsz;
78 	}
79 	return xmalloc_fgets_internal(file, terminating_string, 0, maxsz_p);
80 }
81 
xmalloc_fgetline_str(FILE * file,const char * terminating_string)82 char* FAST_FUNC xmalloc_fgetline_str(FILE *file, const char *terminating_string)
83 {
84 	size_t maxsz = INT_MAX - 4095;
85 	return xmalloc_fgets_internal(file, terminating_string, 1, &maxsz);
86 }
87