1 /*- 2 * Copyright (c) 1985, 1986, 1992 The Regents of the University of California. 3 * All rights reserved. 4 * 5 * This code is derived from software contributed to Berkeley by 6 * Diomidis Spinellis and James A. Woods, derived from original 7 * work by Spencer Thomas and Joseph Orost. 8 * 9 * %sccs.include.redist.c% 10 */ 11 12 #if defined(LIBC_SCCS) && !defined(lint) 13 static char sccsid[] = "@(#)zopen.c 5.2 (Berkeley) 12/17/92"; 14 #endif /* LIBC_SCCS and not lint */ 15 16 /*- 17 * fcompress.c - File compression ala IEEE Computer, June 1984. 18 * 19 * Compress authors: 20 * Spencer W. Thomas (decvax!utah-cs!thomas) 21 * Jim McKie (decvax!mcvax!jim) 22 * Steve Davies (decvax!vax135!petsd!peora!srd) 23 * Ken Turkowski (decvax!decwrl!turtlevax!ken) 24 * James A. Woods (decvax!ihnp4!ames!jaw) 25 * Joe Orost (decvax!vax135!petsd!joe) 26 * 27 * Cleaned up and converted to library returning I/O streams by 28 * Diomidis Spinellis <dds@doc.ic.ac.uk>. 29 * 30 * zopen(filename, mode, bits) 31 * Returns a FILE * that can be used for read or write. The modes 32 * supported are only "r" and "w". Seeking is not allowed. On 33 * reading the file is decompressed, on writing it is compressed. 34 * The output is compatible with compress(1) with 16 bit tables. 35 * Any file produced by compress(1) can be read. 36 */ 37 38 #include <sys/param.h> 39 #include <sys/stat.h> 40 41 #include <ctype.h> 42 #include <errno.h> 43 #include <signal.h> 44 #include <stdio.h> 45 #include <stdlib.h> 46 #include <string.h> 47 #include <unistd.h> 48 49 #define BITS 16 /* Default bits. */ 50 #define HSIZE 69001 /* 95% occupancy */ 51 52 /* A code_int must be able to hold 2**BITS values of type int, and also -1. */ 53 typedef long code_int; 54 typedef long count_int; 55 56 typedef u_char char_type; 57 static char_type magic_header[] = 58 {'\037', '\235'}; /* 1F 9D */ 59 60 #define BIT_MASK 0x1f /* Defines for third byte of header. */ 61 #define BLOCK_MASK 0x80 62 63 /* 64 * Masks 0x40 and 0x20 are free. I think 0x20 should mean that there is 65 * a fourth header byte (for expansion). 66 */ 67 #define INIT_BITS 9 /* Initial number of bits/code. */ 68 69 #define MAXCODE(n_bits) ((1 << (n_bits)) - 1) 70 71 struct s_zstate { 72 FILE *zs_fp; /* File stream for I/O */ 73 char zs_mode; /* r or w */ 74 enum { 75 S_START, S_MIDDLE, S_EOF 76 } zs_state; /* State of computation */ 77 int zs_n_bits; /* Number of bits/code. */ 78 int zs_maxbits; /* User settable max # bits/code. */ 79 code_int zs_maxcode; /* Maximum code, given n_bits. */ 80 code_int zs_maxmaxcode; /* Should NEVER generate this code. */ 81 count_int zs_htab [HSIZE]; 82 u_short zs_codetab [HSIZE]; 83 code_int zs_hsize; /* For dynamic table sizing. */ 84 code_int zs_free_ent; /* First unused entry. */ 85 /* 86 * Block compression parameters -- after all codes are used up, 87 * and compression rate changes, start over. 88 */ 89 int zs_block_compress; 90 int zs_clear_flg; 91 long zs_ratio; 92 count_int zs_checkpoint; 93 int zs_offset; 94 long zs_in_count; /* Length of input. */ 95 long zs_bytes_out; /* Length of compressed output. */ 96 long zs_out_count; /* # of codes output (for debugging). */ 97 char_type zs_buf[BITS]; 98 union { 99 struct { 100 long zs_fcode; 101 code_int zs_ent; 102 code_int zs_hsize_reg; 103 int zs_hshift; 104 } w; /* Write paramenters */ 105 struct { 106 char_type *zs_stackp; 107 int zs_finchar; 108 code_int zs_code, zs_oldcode, zs_incode; 109 int zs_roffset, zs_size; 110 char_type zs_gbuf[BITS]; 111 } r; /* Read parameters */ 112 } u; 113 }; 114 115 /* Definitions to retain old variable names */ 116 #define fp zs->zs_fp 117 #define zmode zs->zs_mode 118 #define state zs->zs_state 119 #define n_bits zs->zs_n_bits 120 #define maxbits zs->zs_maxbits 121 #define maxcode zs->zs_maxcode 122 #define maxmaxcode zs->zs_maxmaxcode 123 #define htab zs->zs_htab 124 #define codetab zs->zs_codetab 125 #define hsize zs->zs_hsize 126 #define free_ent zs->zs_free_ent 127 #define block_compress zs->zs_block_compress 128 #define clear_flg zs->zs_clear_flg 129 #define ratio zs->zs_ratio 130 #define checkpoint zs->zs_checkpoint 131 #define offset zs->zs_offset 132 #define in_count zs->zs_in_count 133 #define bytes_out zs->zs_bytes_out 134 #define out_count zs->zs_out_count 135 #define buf zs->zs_buf 136 #define fcode zs->u.w.zs_fcode 137 #define hsize_reg zs->u.w.zs_hsize_reg 138 #define ent zs->u.w.zs_ent 139 #define hshift zs->u.w.zs_hshift 140 #define stackp zs->u.r.zs_stackp 141 #define finchar zs->u.r.zs_finchar 142 #define code zs->u.r.zs_code 143 #define oldcode zs->u.r.zs_oldcode 144 #define incode zs->u.r.zs_incode 145 #define roffset zs->u.r.zs_roffset 146 #define size zs->u.r.zs_size 147 #define gbuf zs->u.r.zs_gbuf 148 149 /* 150 * To save much memory, we overlay the table used by compress() with those 151 * used by decompress(). The tab_prefix table is the same size and type as 152 * the codetab. The tab_suffix table needs 2**BITS characters. We get this 153 * from the beginning of htab. The output stack uses the rest of htab, and 154 * contains characters. There is plenty of room for any possible stack 155 * (stack used to be 8000 characters). 156 */ 157 158 #define htabof(i) htab[i] 159 #define codetabof(i) codetab[i] 160 161 #define tab_prefixof(i) codetabof(i) 162 #define tab_suffixof(i) ((char_type *)(htab))[i] 163 #define de_stack ((char_type *)&tab_suffixof(1 << BITS)) 164 165 #define CHECK_GAP 10000 /* Ratio check interval. */ 166 167 /* 168 * the next two codes should not be changed lightly, as they must not 169 * lie within the contiguous general code space. 170 */ 171 #define FIRST 257 /* First free entry. */ 172 #define CLEAR 256 /* Table clear output code. */ 173 174 static int cl_block __P((struct s_zstate *)); 175 static void cl_hash __P((struct s_zstate *, count_int)); 176 static code_int getcode __P((struct s_zstate *)); 177 static int output __P((struct s_zstate *, code_int)); 178 static int zclose __P((void *)); 179 static int zread __P((void *, char *, int)); 180 static int zwrite __P((void *, const char *, int)); 181 182 /*- 183 * Algorithm from "A Technique for High Performance Data Compression", 184 * Terry A. Welch, IEEE Computer Vol 17, No 6 (June 1984), pp 8-19. 185 * 186 * Algorithm: 187 * Modified Lempel-Ziv method (LZW). Basically finds common 188 * substrings and replaces them with a variable size code. This is 189 * deterministic, and can be done on the fly. Thus, the decompression 190 * procedure needs no input table, but tracks the way the table was built. 191 */ 192 193 /*- 194 * compress write 195 * 196 * Algorithm: use open addressing double hashing (no chaining) on the 197 * prefix code / next character combination. We do a variant of Knuth's 198 * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime 199 * secondary probe. Here, the modular division first probe is gives way 200 * to a faster exclusive-or manipulation. Also do block compression with 201 * an adaptive reset, whereby the code table is cleared when the compression 202 * ratio decreases, but after the table fills. The variable-length output 203 * codes are re-sized at this point, and a special CLEAR code is generated 204 * for the decompressor. Late addition: construct the table according to 205 * file size for noticeable speed improvement on small files. Please direct 206 * questions about this implementation to ames!jaw. 207 */ 208 static int 209 zwrite(cookie, wbp, num) 210 void *cookie; 211 const char *wbp; 212 int num; 213 { 214 register code_int i; 215 register int c, disp; 216 struct s_zstate *zs; 217 const u_char *bp; 218 u_char tmp; 219 int count; 220 221 if (num == 0) 222 return (0); 223 224 zs = cookie; 225 count = num; 226 bp = (u_char *)wbp; 227 if (state == S_MIDDLE) 228 goto middle; 229 state = S_MIDDLE; 230 231 maxmaxcode = 1L << BITS; 232 if (fwrite(magic_header, 233 sizeof(char), sizeof(magic_header), fp) != sizeof(magic_header)) 234 return (-1); 235 tmp = (u_char)(BITS | block_compress); 236 if (fwrite(&tmp, sizeof(char), sizeof(tmp), fp) != sizeof(tmp)) 237 return (-1); 238 239 offset = 0; 240 bytes_out = 3; /* Includes 3-byte header mojo. */ 241 out_count = 0; 242 clear_flg = 0; 243 ratio = 0; 244 in_count = 1; 245 checkpoint = CHECK_GAP; 246 maxcode = MAXCODE(n_bits = INIT_BITS); 247 free_ent = ((block_compress) ? FIRST : 256); 248 249 ent = *bp++; 250 --count; 251 252 hshift = 0; 253 for (fcode = (long)hsize; fcode < 65536L; fcode *= 2L) 254 hshift++; 255 hshift = 8 - hshift; /* Set hash code range bound. */ 256 257 hsize_reg = hsize; 258 cl_hash(zs, (count_int)hsize_reg); /* Clear hash table. */ 259 260 middle: for (i = 0; count--;) { 261 c = *bp++; 262 in_count++; 263 fcode = (long)(((long)c << maxbits) + ent); 264 i = ((c << hshift) ^ ent); /* Xor hashing. */ 265 266 if (htabof(i) == fcode) { 267 ent = codetabof(i); 268 continue; 269 } else if ((long)htabof(i) < 0) /* Empty slot. */ 270 goto nomatch; 271 disp = hsize_reg - i; /* Secondary hash (after G. Knott). */ 272 if (i == 0) 273 disp = 1; 274 probe: if ((i -= disp) < 0) 275 i += hsize_reg; 276 277 if (htabof(i) == fcode) { 278 ent = codetabof(i); 279 continue; 280 } 281 if ((long)htabof(i) >= 0) 282 goto probe; 283 nomatch: if (output(zs, (code_int) ent) == -1) 284 return (-1); 285 out_count++; 286 ent = c; 287 if (free_ent < maxmaxcode) { 288 codetabof(i) = free_ent++; /* code -> hashtable */ 289 htabof(i) = fcode; 290 } else if ((count_int)in_count >= 291 checkpoint && block_compress) { 292 if (cl_block(zs) == -1) 293 return (-1); 294 } 295 } 296 return (num); 297 } 298 299 static int 300 zclose(cookie) 301 void *cookie; 302 { 303 struct s_zstate *zs; 304 305 zs = cookie; 306 if (zmode == 'w') { /* Put out the final code. */ 307 if (output(zs, (code_int) ent) == -1) { 308 free(zs); 309 (void)fclose(fp); 310 return (-1); 311 } 312 out_count++; 313 if (output(zs, (code_int) - 1) == -1) { 314 free(zs); 315 (void)fclose(fp); 316 return (-1); 317 } 318 } 319 free(zs); 320 return (fclose(fp) == EOF ? -1 : 0); 321 } 322 323 /*- 324 * Output the given code. 325 * Inputs: 326 * code: A n_bits-bit integer. If == -1, then EOF. This assumes 327 * that n_bits =< (long)wordsize - 1. 328 * Outputs: 329 * Outputs code to the file. 330 * Assumptions: 331 * Chars are 8 bits long. 332 * Algorithm: 333 * Maintain a BITS character long buffer (so that 8 codes will 334 * fit in it exactly). Use the VAX insv instruction to insert each 335 * code in turn. When the buffer fills up empty it and start over. 336 */ 337 338 static char_type lmask[9] = 339 {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00}; 340 static char_type rmask[9] = 341 {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff}; 342 343 static int 344 output(zs, ocode) 345 struct s_zstate *zs; 346 code_int ocode; 347 { 348 register int bits, r_off; 349 register char_type *bp; 350 351 r_off = offset; 352 bits = n_bits; 353 bp = buf; 354 if (ocode >= 0) { 355 /* Get to the first byte. */ 356 bp += (r_off >> 3); 357 r_off &= 7; 358 /* 359 * Since ocode is always >= 8 bits, only need to mask the first 360 * hunk on the left. 361 */ 362 *bp = (*bp & rmask[r_off]) | (ocode << r_off) & lmask[r_off]; 363 bp++; 364 bits -= (8 - r_off); 365 ocode >>= 8 - r_off; 366 /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */ 367 if (bits >= 8) { 368 *bp++ = ocode; 369 ocode >>= 8; 370 bits -= 8; 371 } 372 /* Last bits. */ 373 if (bits) 374 *bp = ocode; 375 offset += n_bits; 376 if (offset == (n_bits << 3)) { 377 bp = buf; 378 bits = n_bits; 379 bytes_out += bits; 380 if (fwrite(bp, sizeof(char), bits, fp) != bits) 381 return (-1); 382 bp += bits; 383 bits = 0; 384 offset = 0; 385 } 386 /* 387 * If the next entry is going to be too big for the ocode size, 388 * then increase it, if possible. 389 */ 390 if (free_ent > maxcode || (clear_flg > 0)) { 391 /* 392 * Write the whole buffer, because the input side won't 393 * discover the size increase until after it has read it. 394 */ 395 if (offset > 0) { 396 if (fwrite(buf, 1, n_bits, fp) != n_bits) 397 return (-1); 398 bytes_out += n_bits; 399 } 400 offset = 0; 401 402 if (clear_flg) { 403 maxcode = MAXCODE(n_bits = INIT_BITS); 404 clear_flg = 0; 405 } else { 406 n_bits++; 407 if (n_bits == maxbits) 408 maxcode = maxmaxcode; 409 else 410 maxcode = MAXCODE(n_bits); 411 } 412 } 413 } else { 414 /* At EOF, write the rest of the buffer. */ 415 if (offset > 0) { 416 offset = (offset + 7) / 8; 417 if (fwrite(buf, 1, offset, fp) != offset) 418 return (-1); 419 bytes_out += offset; 420 } 421 offset = 0; 422 } 423 return (0); 424 } 425 426 /* 427 * Decompress read. This routine adapts to the codes in the file building 428 * the "string" table on-the-fly; requiring no table to be stored in the 429 * compressed file. The tables used herein are shared with those of the 430 * compress() routine. See the definitions above. 431 */ 432 static int 433 zread(cookie, rbp, num) 434 void *cookie; 435 char *rbp; 436 int num; 437 { 438 register u_int count; 439 struct s_zstate *zs; 440 u_char *bp, header[3]; 441 442 if (num == 0) 443 return (0); 444 445 zs = cookie; 446 count = num; 447 bp = (u_char *)rbp; 448 switch (state) { 449 case S_START: 450 state = S_MIDDLE; 451 break; 452 case S_MIDDLE: 453 goto middle; 454 case S_EOF: 455 goto eof; 456 } 457 458 /* Check the magic number */ 459 if (fread(header, 460 sizeof(char), sizeof(header), fp) != sizeof(header) || 461 memcmp(header, magic_header, sizeof(magic_header)) != 0) { 462 errno = EFTYPE; 463 return (-1); 464 } 465 maxbits = header[2]; /* Set -b from file. */ 466 block_compress = maxbits & BLOCK_MASK; 467 maxbits &= BIT_MASK; 468 maxmaxcode = 1L << maxbits; 469 if (maxbits > BITS) { 470 errno = EFTYPE; 471 return (-1); 472 } 473 /* As above, initialize the first 256 entries in the table. */ 474 maxcode = MAXCODE(n_bits = INIT_BITS); 475 for (code = 255; code >= 0; code--) { 476 tab_prefixof(code) = 0; 477 tab_suffixof(code) = (char_type) code; 478 } 479 free_ent = block_compress ? FIRST : 256; 480 481 finchar = oldcode = getcode(zs); 482 if (oldcode == -1) /* EOF already? */ 483 return (0); /* Get out of here */ 484 485 /* First code must be 8 bits = char. */ 486 *bp++ = (u_char)finchar; 487 count--; 488 stackp = de_stack; 489 490 while ((code = getcode(zs)) > -1) { 491 492 if ((code == CLEAR) && block_compress) { 493 for (code = 255; code >= 0; code--) 494 tab_prefixof(code) = 0; 495 clear_flg = 1; 496 free_ent = FIRST - 1; 497 if ((code = getcode(zs)) == -1) /* O, untimely death! */ 498 break; 499 } 500 incode = code; 501 502 /* Special case for KwKwK string. */ 503 if (code >= free_ent) { 504 *stackp++ = finchar; 505 code = oldcode; 506 } 507 508 /* Generate output characters in reverse order. */ 509 while (code >= 256) { 510 *stackp++ = tab_suffixof(code); 511 code = tab_prefixof(code); 512 } 513 *stackp++ = finchar = tab_suffixof(code); 514 515 /* And put them out in forward order. */ 516 middle: do { 517 if (count-- == 0) 518 return (num); 519 *bp++ = *--stackp; 520 } while (stackp > de_stack); 521 522 /* Generate the new entry. */ 523 if ((code = free_ent) < maxmaxcode) { 524 tab_prefixof(code) = (u_short) oldcode; 525 tab_suffixof(code) = finchar; 526 free_ent = code + 1; 527 } 528 529 /* Remember previous code. */ 530 oldcode = incode; 531 } 532 state = S_EOF; 533 eof: return (num - count); 534 } 535 536 /*- 537 * Read one code from the standard input. If EOF, return -1. 538 * Inputs: 539 * stdin 540 * Outputs: 541 * code or -1 is returned. 542 */ 543 static code_int 544 getcode(zs) 545 struct s_zstate *zs; 546 { 547 register code_int gcode; 548 register int r_off, bits; 549 register char_type *bp; 550 551 bp = gbuf; 552 if (clear_flg > 0 || roffset >= size || free_ent > maxcode) { 553 /* 554 * If the next entry will be too big for the current gcode 555 * size, then we must increase the size. This implies reading 556 * a new buffer full, too. 557 */ 558 if (free_ent > maxcode) { 559 n_bits++; 560 if (n_bits == maxbits) /* Won't get any bigger now. */ 561 maxcode = maxmaxcode; 562 else 563 maxcode = MAXCODE(n_bits); 564 } 565 if (clear_flg > 0) { 566 maxcode = MAXCODE(n_bits = INIT_BITS); 567 clear_flg = 0; 568 } 569 size = fread(gbuf, 1, n_bits, fp); 570 if (size <= 0) /* End of file. */ 571 return (-1); 572 roffset = 0; 573 /* Round size down to integral number of codes. */ 574 size = (size << 3) - (n_bits - 1); 575 } 576 r_off = roffset; 577 bits = n_bits; 578 579 /* Get to the first byte. */ 580 bp += (r_off >> 3); 581 r_off &= 7; 582 583 /* Get first part (low order bits). */ 584 gcode = (*bp++ >> r_off); 585 bits -= (8 - r_off); 586 r_off = 8 - r_off; /* Now, roffset into gcode word. */ 587 588 /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */ 589 if (bits >= 8) { 590 gcode |= *bp++ << r_off; 591 r_off += 8; 592 bits -= 8; 593 } 594 595 /* High order bits. */ 596 gcode |= (*bp & rmask[bits]) << r_off; 597 roffset += n_bits; 598 599 return (gcode); 600 } 601 602 static int 603 cl_block(zs) /* Table clear for block compress. */ 604 struct s_zstate *zs; 605 { 606 register long rat; 607 608 checkpoint = in_count + CHECK_GAP; 609 610 if (in_count > 0x007fffff) { /* Shift will overflow. */ 611 rat = bytes_out >> 8; 612 if (rat == 0) /* Don't divide by zero. */ 613 rat = 0x7fffffff; 614 else 615 rat = in_count / rat; 616 } else 617 rat = (in_count << 8) / bytes_out; /* 8 fractional bits. */ 618 if (rat > ratio) 619 ratio = rat; 620 else { 621 ratio = 0; 622 cl_hash(zs, (count_int) hsize); 623 free_ent = FIRST; 624 clear_flg = 1; 625 if (output(zs, (code_int) CLEAR) == -1) 626 return (-1); 627 } 628 return (0); 629 } 630 631 static void 632 cl_hash(zs, cl_hsize) /* Reset code table. */ 633 struct s_zstate *zs; 634 register count_int cl_hsize; 635 { 636 register count_int *htab_p; 637 register long i, m1; 638 639 m1 = -1; 640 htab_p = htab + cl_hsize; 641 i = cl_hsize - 16; 642 do { /* Might use Sys V memset(3) here. */ 643 *(htab_p - 16) = m1; 644 *(htab_p - 15) = m1; 645 *(htab_p - 14) = m1; 646 *(htab_p - 13) = m1; 647 *(htab_p - 12) = m1; 648 *(htab_p - 11) = m1; 649 *(htab_p - 10) = m1; 650 *(htab_p - 9) = m1; 651 *(htab_p - 8) = m1; 652 *(htab_p - 7) = m1; 653 *(htab_p - 6) = m1; 654 *(htab_p - 5) = m1; 655 *(htab_p - 4) = m1; 656 *(htab_p - 3) = m1; 657 *(htab_p - 2) = m1; 658 *(htab_p - 1) = m1; 659 htab_p -= 16; 660 } while ((i -= 16) >= 0); 661 for (i += 16; i > 0; i--) 662 *--htab_p = m1; 663 } 664 665 FILE * 666 zopen(fname, mode, bits) 667 const char *fname, *mode; 668 int bits; 669 { 670 struct s_zstate *zs; 671 672 if (mode[0] != 'r' && mode[0] != 'w' || mode[1] != '\0' || 673 bits < 0 || bits > BITS) { 674 errno = EINVAL; 675 return (NULL); 676 } 677 678 if ((zs = calloc(1, sizeof(struct s_zstate))) == NULL) 679 return (NULL); 680 681 maxbits = bits ? bits : BITS; /* User settable max # bits/code. */ 682 maxmaxcode = 1 << BITS; /* Should NEVER generate this code. */ 683 hsize = HSIZE; /* For dynamic table sizing. */ 684 free_ent = 0; /* First unused entry. */ 685 block_compress = BLOCK_MASK; 686 clear_flg = 0; 687 ratio = 0; 688 checkpoint = CHECK_GAP; 689 in_count = 1; /* Length of input. */ 690 out_count = 0; /* # of codes output (for debugging). */ 691 state = S_START; 692 roffset = 0; 693 size = 0; 694 695 /* 696 * Layering compress on top of stdio in order to provide buffering, 697 * and ensure that reads and write work with the data specified. 698 */ 699 if ((fp = fopen(fname, mode)) == NULL) { 700 free(zs); 701 return (NULL); 702 } 703 switch (*mode) { 704 case 'r': 705 zmode = 'r'; 706 return (funopen(zs, zread, NULL, NULL, zclose)); 707 case 'w': 708 zmode = 'w'; 709 return (funopen(zs, NULL, zwrite, NULL, zclose)); 710 } 711 /* NOTREACHED */ 712 } 713