xref: /freebsd/usr.bin/fortune/strfile/strfile.c (revision 069ac18495ad8fde2748bc94b0f80a50250bb01d)
1 /*-
2  * Copyright (c) 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Ken Arnold.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #include <sys/param.h>
34 #include <sys/endian.h>
35 #include <ctype.h>
36 #include <locale.h>
37 #include <stdbool.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <time.h>
42 #include <unistd.h>
43 
44 #include "strfile.h"
45 
46 /*
47  *	This program takes a file composed of strings separated by
48  * lines starting with two consecutive delimiting character (default
49  * character is '%') and creates another file which consists of a table
50  * describing the file (structure from "strfile.h"), a table of seek
51  * pointers to the start of the strings, and the strings, each terminated
52  * by a null byte.  Usage:
53  *
54  *	% strfile [-iorsx] [ -cC ] sourcefile [ datafile ]
55  *
56  *	C - Allow comments marked by a double delimiter at line's beginning
57  *	c - Change delimiting character from '%' to 'C'
58  *	s - Silent.  Give no summary of data processed at the end of
59  *	    the run.
60  *	o - order the strings in alphabetic order
61  *	i - if ordering, ignore case
62  *	r - randomize the order of the strings
63  *	x - set rotated bit
64  *
65  *		Ken Arnold	Sept. 7, 1978 --
66  *
67  *	Added ordering options.
68  */
69 
70 #define	STORING_PTRS	(Oflag || Rflag)
71 #define	CHUNKSIZE	512
72 
73 #define		ALLOC(ptr, sz)	do { \
74 			if (ptr == NULL) \
75 				ptr = malloc(CHUNKSIZE * sizeof(*ptr)); \
76 			else if (((sz) + 1) % CHUNKSIZE == 0) \
77 				ptr = realloc(ptr, ((sz) + CHUNKSIZE) * sizeof(*ptr)); \
78 			if (ptr == NULL) { \
79 				fprintf(stderr, "out of space\n"); \
80 				exit(1); \
81 			} \
82 		} while (0)
83 
84 typedef struct {
85 	int	first;
86 	off_t	pos;
87 } STR;
88 
89 static char	*Infile		= NULL,		/* input file name */
90 		Outfile[MAXPATHLEN] = "",	/* output file name */
91 		Delimch		= '%';		/* delimiting character */
92 
93 static int	Cflag		= false;	/* embedded comments */
94 static int	Sflag		= false;	/* silent run flag */
95 static int	Oflag		= false;	/* ordering flag */
96 static int	Iflag		= false;	/* ignore case flag */
97 static int	Rflag		= false;	/* randomize order flag */
98 static int	Xflag		= false;	/* set rotated bit */
99 static uint32_t	Num_pts		= 0;		/* number of pointers/strings */
100 
101 static off_t	*Seekpts;
102 
103 static FILE	*Sort_1, *Sort_2;		/* pointers for sorting */
104 
105 static STRFILE	Tbl;				/* statistics table */
106 
107 static STR	*Firstch;			/* first chars of each string */
108 
109 static void add_offset(FILE *, off_t);
110 static int cmp_str(const void *, const void *);
111 static int stable_collate_range_cmp(int, int);
112 static void do_order(void);
113 static void getargs(int, char **);
114 static void randomize(void);
115 static void usage(void) __dead2;
116 
117 /*
118  * main:
119  *	Drive the sucker.  There are two main modes -- either we store
120  *	the seek pointers, if the table is to be sorted or randomized,
121  *	or we write the pointer directly to the file, if we are to stay
122  *	in file order.  If the former, we allocate and re-allocate in
123  *	CHUNKSIZE blocks; if the latter, we just write each pointer,
124  *	and then seek back to the beginning to write in the table.
125  */
126 int
127 main(int ac, char *av[])
128 {
129 	char *sp, *nsp, dc;
130 	FILE *inf, *outf;
131 	off_t last_off, pos, *p;
132 	size_t length;
133 	int first;
134 	uint32_t cnt;
135 	STR *fp;
136 	static char string[257];
137 
138 	setlocale(LC_ALL, "");
139 
140 	getargs(ac, av);		/* evalute arguments */
141 	dc = Delimch;
142 	if ((inf = fopen(Infile, "r")) == NULL) {
143 		perror(Infile);
144 		exit(1);
145 	}
146 
147 	if ((outf = fopen(Outfile, "w")) == NULL) {
148 		perror(Outfile);
149 		exit(1);
150 	}
151 	if (!STORING_PTRS)
152 		fseek(outf, (long)sizeof(Tbl), SEEK_SET);
153 
154 	/*
155 	 * Write the strings onto the file
156 	 */
157 
158 	Tbl.str_longlen = 0;
159 	Tbl.str_shortlen = 0xffffffff;
160 	Tbl.str_delim = dc;
161 	Tbl.str_version = VERSION;
162 	first = Oflag;
163 	add_offset(outf, ftello(inf));
164 	last_off = 0;
165 	do {
166 		sp = fgets(string, 256, inf);
167 		if (sp == NULL || (sp[0] == dc && sp[1] == '\n')) {
168 			pos = ftello(inf);
169 			length = (size_t)(pos - last_off) -
170 			    (sp != NULL ? strlen(sp) : 0);
171 			last_off = pos;
172 			if (length == 0)
173 				continue;
174 			add_offset(outf, pos);
175 			if ((size_t)Tbl.str_longlen < length)
176 				Tbl.str_longlen = length;
177 			if ((size_t)Tbl.str_shortlen > length)
178 				Tbl.str_shortlen = length;
179 			first = Oflag;
180 		}
181 		else if (first) {
182 			for (nsp = sp; !isalnum((unsigned char)*nsp); nsp++)
183 				continue;
184 			ALLOC(Firstch, Num_pts);
185 			fp = &Firstch[Num_pts - 1];
186 			if (Iflag && isupper((unsigned char)*nsp))
187 				fp->first = tolower((unsigned char)*nsp);
188 			else
189 				fp->first = *nsp;
190 			fp->pos = Seekpts[Num_pts - 1];
191 			first = false;
192 		}
193 	} while (sp != NULL);
194 
195 	/*
196 	 * write the tables in
197 	 */
198 
199 	fclose(inf);
200 	Tbl.str_numstr = Num_pts - 1;
201 
202 	if (Cflag)
203 		Tbl.str_flags |= STR_COMMENTS;
204 
205 	if (Oflag)
206 		do_order();
207 	else if (Rflag)
208 		randomize();
209 
210 	if (Xflag)
211 		Tbl.str_flags |= STR_ROTATED;
212 
213 	if (!Sflag) {
214 		printf("\"%s\" created\n", Outfile);
215 		if (Num_pts == 2)
216 			puts("There was 1 string");
217 		else
218 			printf("There were %u strings\n", Num_pts - 1);
219 		printf("Longest string: %u byte%s\n", Tbl.str_longlen,
220 		       Tbl.str_longlen == 1 ? "" : "s");
221 		printf("Shortest string: %u byte%s\n", Tbl.str_shortlen,
222 		       Tbl.str_shortlen == 1 ? "" : "s");
223 	}
224 
225 	rewind(outf);
226 	Tbl.str_version = htobe32(Tbl.str_version);
227 	Tbl.str_numstr = htobe32(Tbl.str_numstr);
228 	Tbl.str_longlen = htobe32(Tbl.str_longlen);
229 	Tbl.str_shortlen = htobe32(Tbl.str_shortlen);
230 	Tbl.str_flags = htobe32(Tbl.str_flags);
231 	fwrite((char *)&Tbl, sizeof(Tbl), 1, outf);
232 	if (STORING_PTRS) {
233 		for (p = Seekpts, cnt = Num_pts; cnt--; ++p)
234 			*p = htobe64(*p);
235 		fwrite(Seekpts, sizeof(*Seekpts), (size_t)Num_pts, outf);
236 	}
237 	fclose(outf);
238 	exit(0);
239 }
240 
241 /*
242  *	This routine evaluates arguments from the command line
243  */
244 void
245 getargs(int argc, char **argv)
246 {
247 	int ch;
248 
249 	while ((ch = getopt(argc, argv, "Cc:iorsx")) != -1)
250 		switch(ch) {
251 		case 'C':			/* embedded comments */
252 			Cflag++;
253 			break;
254 		case 'c':			/* new delimiting char */
255 			Delimch = *optarg;
256 			if (!isascii(Delimch)) {
257 				printf("bad delimiting character: '\\%o\n'",
258 				       (unsigned char)Delimch);
259 			}
260 			break;
261 		case 'i':			/* ignore case in ordering */
262 			Iflag++;
263 			break;
264 		case 'o':			/* order strings */
265 			Oflag++;
266 			break;
267 		case 'r':			/* randomize pointers */
268 			Rflag++;
269 			break;
270 		case 's':			/* silent */
271 			Sflag++;
272 			break;
273 		case 'x':			/* set the rotated bit */
274 			Xflag++;
275 			break;
276 		case '?':
277 		default:
278 			usage();
279 		}
280 	argv += optind;
281 
282 	if (*argv) {
283 		Infile = *argv;
284 		if (*++argv) {
285 			if (strlcpy(Outfile, *argv, sizeof(Outfile)) >=
286 			    sizeof(Outfile)) {
287 				fprintf(stderr,
288 				    "output_file path is too long\n");
289 				exit(1);
290 			}
291 		}
292 	}
293 	if (!Infile) {
294 		puts("No input file name");
295 		usage();
296 	}
297 	if (*Outfile == '\0') {
298 		if ((size_t)snprintf(Outfile, sizeof(Outfile), "%s.dat",
299 		    Infile) >= sizeof(Outfile)) {
300 			fprintf(stderr,
301 			    "generated output_file path is too long\n");
302 			exit(1);
303 		}
304 	}
305 }
306 
307 void
308 usage(void)
309 {
310 	fprintf(stderr,
311 	    "strfile [-Ciorsx] [-c char] source_file [output_file]\n");
312 	exit(1);
313 }
314 
315 /*
316  * add_offset:
317  *	Add an offset to the list, or write it out, as appropriate.
318  */
319 void
320 add_offset(FILE *fp, off_t off)
321 {
322 	off_t beoff;
323 
324 	if (!STORING_PTRS) {
325 		beoff = htobe64(off);
326 		fwrite(&beoff, 1, sizeof(beoff), fp);
327 	} else {
328 		ALLOC(Seekpts, Num_pts + 1);
329 		Seekpts[Num_pts] = off;
330 	}
331 	Num_pts++;
332 }
333 
334 /*
335  * do_order:
336  *	Order the strings alphabetically (possibly ignoring case).
337  */
338 void
339 do_order(void)
340 {
341 	uint32_t i;
342 	off_t *lp;
343 	STR *fp;
344 
345 	Sort_1 = fopen(Infile, "r");
346 	Sort_2 = fopen(Infile, "r");
347 	qsort(Firstch, (size_t)Tbl.str_numstr, sizeof(*Firstch), cmp_str);
348 	i = Tbl.str_numstr;
349 	lp = Seekpts;
350 	fp = Firstch;
351 	while (i--)
352 		*lp++ = fp++->pos;
353 	fclose(Sort_1);
354 	fclose(Sort_2);
355 	Tbl.str_flags |= STR_ORDERED;
356 }
357 
358 static int
359 stable_collate_range_cmp(int c1, int c2)
360 {
361 	static char s1[2], s2[2];
362 	int ret;
363 
364 	s1[0] = c1;
365 	s2[0] = c2;
366 	if ((ret = strcoll(s1, s2)) != 0)
367 		return (ret);
368 	return (c1 - c2);
369 }
370 
371 /*
372  * cmp_str:
373  *	Compare two strings in the file
374  */
375 int
376 cmp_str(const void *s1, const void *s2)
377 {
378 	const STR *p1, *p2;
379 	int c1, c2, n1, n2, r;
380 
381 #define	SET_N(nf,ch)	(nf = (ch == '\n'))
382 #define	IS_END(ch,nf)	(ch == EOF || (ch == (unsigned char)Delimch && nf))
383 
384 	p1 = (const STR *)s1;
385 	p2 = (const STR *)s2;
386 
387 	c1 = (unsigned char)p1->first;
388 	c2 = (unsigned char)p2->first;
389 	if ((r = stable_collate_range_cmp(c1, c2)) != 0)
390 		return (r);
391 
392 	fseeko(Sort_1, p1->pos, SEEK_SET);
393 	fseeko(Sort_2, p2->pos, SEEK_SET);
394 
395 	n1 = false;
396 	n2 = false;
397 	while (!isalnum(c1 = getc(Sort_1)) && c1 != '\0' && c1 != EOF)
398 		SET_N(n1, c1);
399 	while (!isalnum(c2 = getc(Sort_2)) && c2 != '\0' && c2 != EOF)
400 		SET_N(n2, c2);
401 
402 	while (!IS_END(c1, n1) && !IS_END(c2, n2)) {
403 		if (Iflag) {
404 			if (isupper(c1))
405 				c1 = tolower(c1);
406 			if (isupper(c2))
407 				c2 = tolower(c2);
408 		}
409 		if ((r = stable_collate_range_cmp(c1, c2)) != 0)
410 			return (r);
411 		SET_N(n1, c1);
412 		SET_N(n2, c2);
413 		c1 = getc(Sort_1);
414 		c2 = getc(Sort_2);
415 	}
416 	if (IS_END(c1, n1))
417 		c1 = 0;
418 	if (IS_END(c2, n2))
419 		c2 = 0;
420 
421 	return (stable_collate_range_cmp(c1, c2));
422 }
423 
424 /*
425  * randomize:
426  *	Randomize the order of the string table.  We must be careful
427  *	not to randomize across delimiter boundaries.  All
428  *	randomization is done within each block.
429  */
430 void
431 randomize(void)
432 {
433 	uint32_t cnt, i;
434 	off_t tmp;
435 	off_t *sp;
436 
437 	Tbl.str_flags |= STR_RANDOM;
438 	cnt = Tbl.str_numstr;
439 
440 	/*
441 	 * move things around randomly
442 	 */
443 
444 	for (sp = Seekpts; cnt > 0; cnt--, sp++) {
445 		i = arc4random_uniform(cnt);
446 		tmp = sp[0];
447 		sp[0] = sp[i];
448 		sp[i] = tmp;
449 	}
450 }
451