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