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