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