xref: /openbsd/usr.bin/join/join.c (revision db3296cf)
1 /* $OpenBSD: join.c,v 1.16 2003/06/10 22:20:47 deraadt Exp $	*/
2 
3 /*-
4  * Copyright (c) 1991, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Steve Hayman of the Computer Science Department, Indiana University,
9  * Michiro Hikida and David Goodenough.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #ifndef lint
37 static char copyright[] =
38 "@(#) Copyright (c) 1991, 1993, 1994\n\
39 	The Regents of the University of California.  All rights reserved.\n";
40 #endif /* not lint */
41 
42 #ifndef lint
43 /*static char sccsid[] = "@(#)join.c	8.6 (Berkeley) 5/4/95"; */
44 static char rcsid[] = "$OpenBSD: join.c,v 1.16 2003/06/10 22:20:47 deraadt Exp $";
45 #endif /* not lint */
46 
47 #include <sys/param.h>
48 
49 #include <ctype.h>
50 #include <err.h>
51 #include <errno.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <unistd.h>
56 
57 /*
58  * There's a structure per input file which encapsulates the state of the
59  * file.  We repeatedly read lines from each file until we've read in all
60  * the consecutive lines from the file with a common join field.  Then we
61  * compare the set of lines with an equivalent set from the other file.
62  */
63 typedef struct {
64 	char *line;			/* line */
65 	u_long linealloc;		/* line allocated count */
66 	char **fields;			/* line field(s) */
67 	u_long fieldcnt;		/* line field(s) count */
68 	u_long fieldalloc;		/* line field(s) allocated count */
69 	u_long cfieldc;			/* current field count */
70 	long	 fpos;			/* fpos of start of field */
71 } LINE;
72 
73 typedef struct {
74 	FILE *fp;			/* file descriptor */
75 	u_long joinf;			/* join field (-1, -2, -j) */
76 	int unpair;			/* output unpairable lines (-a) */
77 	int number;			/* 1 for file 1, 2 for file 2 */
78 	LINE *set;			/* set of lines with same field */
79 	int pushbool;			/* if pushback is set */
80 	u_long pushback;		/* line on the stack */
81 	u_long setcnt;			/* set count */
82 	u_long setalloc;		/* set allocated count */
83 	u_long setusedc;		/* sets used  */
84 } INPUT;
85 INPUT input1 = { NULL, 0, 0, 1, NULL, 0, 0, 0, },
86       input2 = { NULL, 0, 0, 2, NULL, 0, 0, 0, };
87 
88 typedef struct {
89 	u_long	filenum;	/* file number */
90 	u_long	fieldno;	/* field number */
91 } OLIST;
92 OLIST *olist;			/* output field list */
93 u_long olistcnt;		/* output field list count */
94 u_long olistalloc;		/* output field allocated count */
95 
96 int joinout = 1;		/* show lines with matched join fields (-v) */
97 int needsep;			/* need separator character */
98 int spans = 1;			/* span multiple delimiters (-t) */
99 char *empty;			/* empty field replacement string (-e) */
100 char *tabchar = " \t";		/* delimiter characters (-t) */
101 
102 int  cmp(LINE *, u_long, LINE *, u_long);
103 void fieldarg(char *);
104 void joinlines(INPUT *, INPUT *);
105 void obsolete(char **);
106 void outfield(LINE *, u_long, int);
107 void outoneline(INPUT *, LINE *);
108 void outtwoline(INPUT *, LINE *, INPUT *, LINE *);
109 void slurp(INPUT *);
110 void slurpit(INPUT *);
111 void usage(void);
112 
113 int
114 main(int argc, char *argv[])
115 {
116 	INPUT *F1, *F2;
117 	int aflag, ch, cval, vflag;
118 	char *end;
119 
120 	F1 = &input1;
121 	F2 = &input2;
122 
123 	aflag = vflag = 0;
124 	obsolete(argv);
125 	while ((ch = getopt(argc, argv, "\01a:e:j:1:2:o:t:v:")) != -1) {
126 		switch (ch) {
127 		case '\01':		/* See comment in obsolete(). */
128 			aflag = 1;
129 			F1->unpair = F2->unpair = 1;
130 			break;
131 		case '1':
132 			if ((F1->joinf = strtol(optarg, &end, 10)) < 1)
133 				errx(1, "-1 option field number less than 1");
134 			if (*end)
135 				errx(1, "illegal field number -- %s", optarg);
136 			--F1->joinf;
137 			break;
138 		case '2':
139 			if ((F2->joinf = strtol(optarg, &end, 10)) < 1)
140 				errx(1, "-2 option field number less than 1");
141 			if (*end)
142 				errx(1, "illegal field number -- %s", optarg);
143 			--F2->joinf;
144 			break;
145 		case 'a':
146 			aflag = 1;
147 			switch(strtol(optarg, &end, 10)) {
148 			case 1:
149 				F1->unpair = 1;
150 				break;
151 			case 2:
152 				F2->unpair = 1;
153 				break;
154 			default:
155 				errx(1, "-a option file number not 1 or 2");
156 				break;
157 			}
158 			if (*end)
159 				errx(1, "illegal file number -- %s", optarg);
160 			break;
161 		case 'e':
162 			empty = optarg;
163 			break;
164 		case 'j':
165 			if ((F1->joinf = F2->joinf = strtol(optarg, &end, 10)) < 1)
166 				errx(1, "-j option field number less than 1");
167 			if (*end)
168 				errx(1, "illegal field number -- %s", optarg);
169 			--F1->joinf;
170 			--F2->joinf;
171 			break;
172 		case 'o':
173 			fieldarg(optarg);
174 			break;
175 		case 't':
176 			spans = 0;
177 			if (strlen(tabchar = optarg) != 1)
178 				errx(1, "illegal tab character specification");
179 			break;
180 		case 'v':
181 			vflag = 1;
182 			joinout = 0;
183 			switch (strtol(optarg, &end, 10)) {
184 			case 1:
185 				F1->unpair = 1;
186 				break;
187 			case 2:
188 				F2->unpair = 1;
189 				break;
190 			default:
191 				errx(1, "-v option file number not 1 or 2");
192 				break;
193 			}
194 			if (*end)
195 				errx(1, "illegal file number -- %s", optarg);
196 			break;
197 		case '?':
198 		default:
199 			usage();
200 		}
201 	}
202 	argc -= optind;
203 	argv += optind;
204 
205 	if (aflag && vflag)
206 		errx(1, "the -a and -v options are mutually exclusive");
207 
208 	if (argc != 2)
209 		usage();
210 
211 	/* Open the files; "-" means stdin. */
212 	if (!strcmp(*argv, "-"))
213 		F1->fp = stdin;
214 	else if ((F1->fp = fopen(*argv, "r")) == NULL)
215 		err(1, "%s", *argv);
216 	++argv;
217 	if (!strcmp(*argv, "-"))
218 		F2->fp = stdin;
219 	else if ((F2->fp = fopen(*argv, "r")) == NULL)
220 		err(1, "%s", *argv);
221 	if (F1->fp == stdin && F2->fp == stdin)
222 		errx(1, "only one input file may be stdin");
223 
224 	F1->setusedc = 0;
225 	F2->setusedc = 0;
226 	slurp(F1);
227 	slurp(F2);
228 	F1->set->cfieldc = 0;
229 	F2->set->cfieldc = 0;
230 
231 	/*
232 	 * We try to let the files have the same field value, advancing
233 	 * whoever falls behind and always advancing the file(s) we output
234 	 * from.
235 	*/
236 	while (F1->setcnt && F2->setcnt) {
237 		cval = cmp(F1->set, F1->joinf, F2->set, F2->joinf);
238 		if (cval == 0) {
239 			/* Oh joy, oh rapture, oh beauty divine! */
240 			if (joinout)
241 				joinlines(F1, F2);
242 			slurp(F1);
243 			slurp(F2);
244 		}
245 		else {
246 			if (F1->unpair
247 			&& (cval < 0 || F2->set->cfieldc == F2->setusedc -1)) {
248 				joinlines(F1, NULL);
249 				slurp(F1);
250 			}
251 			else if (cval < 0)
252 				/* File 1 takes the lead... */
253 				slurp(F1);
254 			if (F2->unpair
255 			&& (cval > 0 || F1->set->cfieldc == F1->setusedc -1)) {
256 				joinlines(F2, NULL);
257 				slurp(F2);
258 			}
259 			else if (cval > 0)
260 				/* File 2 takes the lead... */
261 				slurp(F2);
262 		}
263 	}
264 
265 	/*
266 	 * Now that one of the files is used up, optionally output any
267 	 * remaining lines from the other file.
268 	 */
269 	if (F1->unpair)
270 		while (F1->setcnt) {
271 			joinlines(F1, NULL);
272 			slurp(F1);
273 		}
274 	if (F2->unpair)
275 		while (F2->setcnt) {
276 			joinlines(F2, NULL);
277 			slurp(F2);
278 		}
279 
280 	return 0;
281 }
282 
283 /* wrapper around slurpit() to keep track of what field we are on */
284 void slurp(INPUT *F)
285 {
286 	long fpos;
287 	u_long cfieldc;
288 
289 	if (F->set == NULL) {
290 		fpos = 0;
291 		cfieldc = 0;
292 	}
293 	else {
294 		fpos = F->set->fpos;
295 		cfieldc = F->set->cfieldc;
296 	}
297 	slurpit(F);
298 	if (F->set == NULL)
299 		return;
300 	else if (fpos != F->set->fpos)
301 		F->set->cfieldc = cfieldc+1;
302 }
303 
304 void
305 slurpit(INPUT *F)
306 {
307 	LINE *lp, *lastlp, tmp;
308 	size_t len;
309 	int cnt;
310 	char *bp, *fieldp;
311 	long fpos;
312 	/*
313 	 * Read all of the lines from an input file that have the same
314 	 * join field.
315 	 */
316 
317 	F->setcnt = 0;
318 	for (lastlp = NULL; ; ++F->setcnt, lastlp = lp) {
319 		/*
320 		 * If we're out of space to hold line structures, allocate
321 		 * more.  Initialize the structure so that we know that this
322 		 * is new space.
323 		 */
324 		if (F->setcnt == F->setalloc) {
325 			cnt = F->setalloc;
326 			F->setalloc += 50;
327 			if ((F->set = realloc(F->set,
328 			    F->setalloc * sizeof(LINE))) == NULL)
329 				err(1, NULL);
330 			memset(F->set + cnt, 0, 50 * sizeof(LINE));
331 			/* re-set lastlp in case it moved */
332 			if (lastlp != NULL)
333 				lastlp = &F->set[F->setcnt - 1];
334 		}
335 		/*
336 		 * Get any pushed back line, else get the next line.  Allocate
337 		 * space as necessary.  If taking the line from the stack swap
338 		 * the two structures so that we don't lose space allocated to
339 		 * either structure.  This could be avoided by doing another
340 		 * level of indirection, but it's probably okay as is.
341 		 * but it's probably okay as is.
342 		 */
343 		lp = &F->set[F->setcnt];
344 		if (F->pushbool) {
345 			tmp = F->set[F->setcnt];
346 			F->set[F->setcnt] = F->set[F->pushback];
347 			F->set[F->pushback] = tmp;
348 			F->pushbool = 0;
349 			continue;
350 		}
351 		if ((bp = fgetln(F->fp, &len)) == NULL)
352 			return;
353 		/*
354 		 * we depend on knowing on what field we are, one safe way is
355 		 * the file position.
356 		*/
357 		fpos = ftell(F->fp) - len;
358 		if (lp->linealloc <= len + 1) {
359 			lp->linealloc += MAX(100, len + 1 - lp->linealloc);
360 			if ((lp->line = realloc(lp->line, lp->linealloc))
361 			== NULL)
362 				err(1, NULL);
363 		}
364 		F->setusedc++;
365 		memmove(lp->line, bp, len);
366 		lp->fpos = fpos;
367 		/* Replace trailing newline, if it exists. */
368 		if (bp[len - 1] == '\n')
369 			lp->line[len - 1] = '\0';
370 		else
371 			lp->line[len] = '\0';
372 		bp = lp->line;
373 
374 		/* Split the line into fields, allocate space as necessary. */
375 		lp->fieldcnt = 0;
376 		while ((fieldp = strsep(&bp, tabchar)) != NULL) {
377 			if (spans && *fieldp == '\0')
378 				continue;
379 			if (lp->fieldcnt == lp->fieldalloc) {
380 				lp->fieldalloc += 50;
381 				if ((lp->fields = realloc(lp->fields,
382 				    lp->fieldalloc * sizeof(char *))) == NULL)
383 					err(1, NULL);
384 			}
385 			lp->fields[lp->fieldcnt++] = fieldp;
386 		}
387 
388 		/* See if the join field value has changed. */
389 		if (lastlp != NULL && cmp(lp, F->joinf, lastlp, F->joinf)) {
390 			F->pushbool = 1;
391 			F->pushback = F->setcnt;
392 			break;
393 		}
394 	}
395 }
396 
397 int
398 cmp(LINE *lp1, u_long fieldno1, LINE *lp2, u_long fieldno2)
399 {
400 	if (lp1->fieldcnt <= fieldno1)
401 		return (-1);
402 	else if (lp2->fieldcnt <= fieldno2)
403 		return (1);
404 	return (strcmp(lp1->fields[fieldno1], lp2->fields[fieldno2]));
405 }
406 
407 void
408 joinlines(INPUT *F1, INPUT *F2)
409 {
410 	int cnt1, cnt2;
411 
412 	/*
413 	 * Output the results of a join comparison.  The output may be from
414 	 * either file 1 or file 2 (in which case the first argument is the
415 	 * file from which to output) or from both.
416 	 */
417 	if (F2 == NULL) {
418 		for (cnt1 = 0; cnt1 < F1->setcnt; ++cnt1)
419 			outoneline(F1, &F1->set[cnt1]);
420 		return;
421 	}
422 	for (cnt1 = 0; cnt1 < F1->setcnt; ++cnt1)
423 		for (cnt2 = 0; cnt2 < F2->setcnt; ++cnt2)
424 			outtwoline(F1, &F1->set[cnt1], F2, &F2->set[cnt2]);
425 }
426 
427 void
428 outoneline(INPUT *F, LINE *lp)
429 {
430 	int cnt;
431 
432 	/*
433 	 * Output a single line from one of the files, according to the
434 	 * join rules.  This happens when we are writing unmatched single
435 	 * lines.  Output empty fields in the right places.
436 	 */
437 	if (olist)
438 		for (cnt = 0; cnt < olistcnt; ++cnt) {
439 			if (olist[cnt].filenum == F->number)
440 				outfield(lp, olist[cnt].fieldno, 0);
441 			else
442 				outfield(lp, 0, 1);
443 		}
444 	else
445 		for (cnt = 0; cnt < lp->fieldcnt; ++cnt)
446 			outfield(lp, cnt, 0);
447 	putchar('\n');
448 	if (ferror(stdout))
449 		err(1, "stdout");
450 	needsep = 0;
451 }
452 
453 void
454 outtwoline(INPUT *F1, LINE *lp1, INPUT *F2, LINE *lp2)
455 {
456 	int cnt;
457 
458 	/* Output a pair of lines according to the join list (if any). */
459 	if (olist) {
460 		for (cnt = 0; cnt < olistcnt; ++cnt)
461 			if (olist[cnt].filenum == 1)
462 				outfield(lp1, olist[cnt].fieldno, 0);
463 			else /* if (olist[cnt].filenum == 2) */
464 				outfield(lp2, olist[cnt].fieldno, 0);
465 	} else {
466 		/*
467 		 * Output the join field, then the remaining fields from F1
468 		 * and F2.
469 		 */
470 		outfield(lp1, F1->joinf, 0);
471 		for (cnt = 0; cnt < lp1->fieldcnt; ++cnt)
472 			if (F1->joinf != cnt)
473 				outfield(lp1, cnt, 0);
474 		for (cnt = 0; cnt < lp2->fieldcnt; ++cnt)
475 			if (F2->joinf != cnt)
476 				outfield(lp2, cnt, 0);
477 	}
478 	putchar('\n');
479 	if (ferror(stdout))
480 		err(1, "stdout");
481 	needsep = 0;
482 }
483 
484 void
485 outfield(LINE *lp, u_long fieldno, int out_empty)
486 {
487 	if (needsep++)
488 		putchar((int)*tabchar);
489 	if (!ferror(stdout)) {
490 		if (lp->fieldcnt <= fieldno || out_empty) {
491 			if (empty != NULL)
492 				fputs(empty, stdout);
493 		} else {
494 			if (*lp->fields[fieldno] == '\0')
495 				return;
496 			fputs(lp->fields[fieldno], stdout);
497 		}
498 	}
499 	if (ferror(stdout))
500 		err(1, "stdout");
501 }
502 
503 /*
504  * Convert an output list argument "2.1, 1.3, 2.4" into an array of output
505  * fields.
506  */
507 void
508 fieldarg(char *option)
509 {
510 	u_long fieldno;
511 	char *end, *token;
512 
513 	while ((token = strsep(&option, ", \t")) != NULL) {
514 		if (*token == '\0')
515 			continue;
516 		if ((token[0] != '1' && token[0] != '2') || token[1] != '.')
517 			errx(1, "malformed -o option field");
518 		fieldno = strtol(token + 2, &end, 10);
519 		if (*end)
520 			errx(1, "malformed -o option field");
521 		if (fieldno == 0)
522 			errx(1, "field numbers are 1 based");
523 		if (olistcnt == olistalloc) {
524 			olistalloc += 50;
525 			if ((olist = realloc(olist,
526 			    olistalloc * sizeof(OLIST))) == NULL)
527 				err(1, NULL);
528 		}
529 		olist[olistcnt].filenum = token[0] - '0';
530 		olist[olistcnt].fieldno = fieldno - 1;
531 		++olistcnt;
532 	}
533 }
534 
535 void
536 obsolete(char **argv)
537 {
538 	int len;
539 	char **p, *ap, *t;
540 
541 	while ((ap = *++argv) != NULL) {
542 		/* Return if "--". */
543 		if (ap[0] == '-' && ap[1] == '-')
544 			return;
545 		/* skip if not an option */
546 		if (ap[0] != '-')
547 			continue;
548 		switch (ap[1]) {
549 		case 'a':
550 			/*
551 			 * The original join allowed "-a", which meant the
552 			 * same as -a1 plus -a2.  POSIX 1003.2, Draft 11.2
553 			 * only specifies this as "-a 1" and "a -2", so we
554 			 * have to use another option flag, one that is
555 			 * unlikely to ever be used or accidentally entered
556 			 * on the command line.  (Well, we could reallocate
557 			 * the argv array, but that hardly seems worthwhile.)
558 			 */
559 			if (ap[2] == '\0')
560 				ap[1] = '\01';
561 			break;
562 		case 'j':
563 			/*
564 			 * The original join allowed "-j[12] arg" and "-j arg".
565 			 * Convert the former to "-[12] arg".  Don't convert
566 			 * the latter since getopt(3) can handle it.
567 			 */
568 			switch(ap[2]) {
569 			case '1':
570 				if (ap[3] != '\0')
571 					goto jbad;
572 				ap[1] = '1';
573 				ap[2] = '\0';
574 				break;
575 			case '2':
576 				if (ap[3] != '\0')
577 					goto jbad;
578 				ap[1] = '2';
579 				ap[2] = '\0';
580 				break;
581 			case '\0':
582 				break;
583 			default:
584 jbad:				errx(1, "illegal option -- %s", ap);
585 				usage();
586 			}
587 			break;
588 		case 'o':
589 			/*
590 			 * The original join allowed "-o arg arg".
591 			 * Convert to "-o arg -o arg".
592 			 */
593 			if (ap[2] != '\0')
594 				break;
595 			for (p = argv + 2; *p != NULL; ++p) {
596 				if ((p[0][0] != '1' && p[0][0] != '2') || p[0][1] != '.')
597 					break;
598 				len = strlen(*p);
599 				if (len - 2 != strspn(*p + 2, "0123456789"))
600 					break;
601 				if ((t = malloc(len + 3)) == NULL)
602 					err(1, NULL);
603 				t[0] = '-';
604 				t[1] = 'o';
605 				memmove(t + 2, *p, len + 1);
606 				*p = t;
607 			}
608 			argv = p - 1;
609 			break;
610 		}
611 	}
612 }
613 
614 void
615 usage(void)
616 {
617 	(void)fprintf(stderr, "%s%s\n",
618 	    "usage: join [-a fileno | -v fileno ] [-e string] [-1 field] ",
619 	    "[-2 field]\n            [-o list] [-t char] file1 file2");
620 	exit(1);
621 }
622