⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pgpztrees.c

📁 PGP—Pretty Good Privacy
💻 C
📖 第 1 页 / 共 3 页
字号:
scan_tree(ZTreesContext *ctx, ct_data near *tree, int max_code)
{
    int n;                     /* iterates over all tree elements */
    int prevlen = -1;          /* last emitted length */
    int curlen;                /* length of current code */
    int nextlen = tree[0].Len; /* length of next code */
    int count = 0;             /* repeat count of the current code */
    int max_count = 7;         /* max repeat count */
    int min_count = 4;         /* min repeat count */

    if (nextlen == 0)
        max_count = 138, min_count = 3;
    tree[max_code+1].Len = (PGPUInt16)-1; /* guard */

    for (n = 0; n <= max_code; n++) {
        curlen = nextlen; nextlen = tree[n+1].Len;
        if (++count < max_count && curlen == nextlen) {
            continue;
        } else if (count < min_count) {
            ctx->bl_tree[curlen].Freq += count;
        } else if (curlen != 0) {
            if (curlen != prevlen)
                ctx->bl_tree[curlen].Freq++;
            ctx->bl_tree[REP_3_6].Freq++;
        } else if (count <= 10) {
            ctx->bl_tree[REPZ_3_10].Freq++;
        } else {
            ctx->bl_tree[REPZ_11_138].Freq++;
        }
        count = 0; prevlen = curlen;
        if (nextlen == 0) {
            max_count = 138, min_count = 3;
		} else if (curlen == nextlen) {
            max_count = 6, min_count = 3;
		} else {
            max_count = 7, min_count = 4;
        }
    }
}

/* ===========================================================================
 * Send a literal or distance tree in compressed form, using the codes in
 * bl_tree.
 */
static void
send_tree(ZTreesContext *ctx, struct ZBitsContext *zbcontext,
	ct_data near *tree, int max_code)
{
    int n;                     /* iterates over all tree elements */
    int prevlen = -1;          /* last emitted length */
    int curlen;                /* length of current code */
    int nextlen = tree[0].Len; /* length of next code */
    int count = 0;             /* repeat count of the current code */
    int max_count = 7;         /* max repeat count */
    int min_count = 4;         /* min repeat count */

    /* tree[max_code+1].Len = -1; */  /* guard already set */
    if (nextlen == 0)
        max_count = 138, min_count = 3;

    for (n = 0; n <= max_code; n++) {
        curlen = nextlen;
        nextlen = tree[n+1].Len;
        if (++count < max_count && curlen == nextlen) {
            continue;
        } else if (count < min_count) {
            do {
                send_code(zbcontext, curlen, ctx->bl_tree);
            } while (--count != 0);
        } else if (curlen != 0) {
			if (curlen != prevlen) {
                send_code(zbcontext, curlen, ctx->bl_tree);
                count--;
            }
            ZipAssert(count >= 3 && count <= 6, " 3_6?");
            send_code(zbcontext, REP_3_6, ctx->bl_tree);
            send_bits(zbcontext, count-3, 2);
        } else if (count <= 10) {
            send_code(zbcontext, REPZ_3_10, ctx->bl_tree);
            send_bits(zbcontext, count-3, 3);
        } else {
            send_code(zbcontext, REPZ_11_138, ctx->bl_tree);
            send_bits(zbcontext, count-11, 7);
        }
        count = 0; prevlen = curlen;
        if (nextlen == 0) {
            max_count = 138, min_count = 3;
        } else if (curlen == nextlen) {
            max_count = 6, min_count = 3;
        } else {
            max_count = 7, min_count = 4;
        }
    }
}

/* ===========================================================================
 * Construct the Huffman tree for the bit lengths and return the index in
 * bl_order of the last bit length code to send.
 */
static int
build_bl_tree(ZTreesContext *ctx)
{
    int max_blindex;  /* index of last bit length code of non zero freq */

    /* Determine the bit length frequencies for literal and distance trees */
    scan_tree(ctx, ctx->dyn_ltree, ctx->l_desc.max_code);
    scan_tree(ctx, ctx->dyn_dtree, ctx->d_desc.max_code);

    /* Build the bit length tree: */
    build_tree(ctx, &ctx->bl_desc);
    /* opt_len now includes the length of the tree representations, except
     * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
     */

    /* Determine the number of bit length codes to send. The pkzip format
     * requires that at least 4 bit length codes be sent. (appnote.txt says
     * 3 but the actual value used is 4.)
     */
    for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
        if (ctx->bl_tree[bl_order[max_blindex]].Len != 0)
            break;
    }
    /* Update opt_len to include the bit length tree and counts */
    ctx->opt_len += 3*(max_blindex+1) + 5+5+4;
    Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", ctx->opt_len,
			ctx->static_len));

    return max_blindex;
}

/* ===========================================================================
 * Send the header for a block using dynamic Huffman trees: the counts, the
 * lengths of the bit length codes, the literal tree and the distance tree.
 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
 */
static void
send_all_trees(ZTreesContext *ctx, struct ZBitsContext *zbcontext,
	int lcodes, int dcodes, int blcodes)
{
    int rank;                    /* index in bl_order */

    ZipAssert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4,
            "not enough codes");
    ZipAssert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
            "too many codes");
    Tracev((stderr, "\nbl counts: "));
    send_bits(zbcontext, lcodes-257, 5);
    /* not +255 as stated in appnote.txt 1.93a or -256 in 2.04c */
    send_bits(zbcontext, dcodes-1,   5);
    send_bits(zbcontext, blcodes-4,  4); /* not -3 as stated in appnote.txt */
    for (rank = 0; rank < blcodes; rank++) {
        Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
        send_bits(zbcontext, ctx->bl_tree[bl_order[rank]].Len, 3);
    }
    Tracev((stderr, "\nbl tree: sent %ld", bits_sent));

    /* send the literal tree */
    send_tree(ctx, zbcontext, (ct_data near *)ctx->dyn_ltree, lcodes-1);
    Tracev((stderr, "\nlit tree: sent %ld", bits_sent));

    /* send the distance tree */
    send_tree(ctx, zbcontext, (ct_data near *)ctx->dyn_dtree, dcodes-1);
    Tracev((stderr, "\ndist tree: sent %ld", bits_sent));
}

/* ===========================================================================
 * Determine the best encoding for the current block: dynamic trees, static
 * trees or store, and output the encoded block to the zip file. This function
 * returns the total compressed length for the file so far.
 *
 * buf: the input block, or NULL if too old
 * stored_len: the length of the input block
 * eof: true if this is the last block for the file
 */
PGPUInt32
flush_block(ZTreesContext *ctx, struct ZBitsContext *zbcontext,
	char const *buf, PGPUInt32 stored_len, int eof, PGPByte *window)
{
    PGPUInt32 opt_lenb, static_lenb; /* opt_len and static_len in bytes */
    int max_blindex;  /* index of last bit length code of non zero freq */

	/* Save the flags for the last 8 items */
    ctx->flag_buf[ctx->last_flags] = ctx->flags;

    /* Construct the literal and distance trees */
    build_tree(ctx, (tree_desc near *)(&ctx->l_desc));
    Tracev((stderr, "\nlit data: dyn %ld, stat %ld", ctx->opt_len,
			ctx->static_len));

    build_tree(ctx, (tree_desc near *)(&ctx->d_desc));
    Tracev((stderr, "\ndist data: dyn %ld, stat %ld", ctx->opt_len,
			ctx->static_len));
    /* At this point, opt_len and static_len are the total bit lengths of
     * the compressed block data, excluding the tree representations.
     */

    /* Build the bit length tree for the above two trees, and get the index
     * in bl_order of the last bit length code to send.
     */
    max_blindex = build_bl_tree(ctx);

    /* Determine the best encoding. Compute first the block length in bytes */
    opt_lenb = (ctx->opt_len+3+7)>>3;
    static_lenb = (ctx->static_len+3+7)>>3;
    ctx->input_len += stored_len; /* for debugging only */

    Trace((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ",
		   opt_lenb, ctx->opt_len, static_lenb, ctx->static_len, stored_len,
		   ctx->last_lit, ctx->last_dist));

    if (static_lenb <= opt_lenb) opt_lenb = static_lenb;

#ifndef PGP /* PGP can't handle stored files - disable this test */
    /*
     * If compression failed and this is the first and last block,
     * and if the zip file can be seeked (to rewrite the local header),
     * the whole file is transformed into a stored file:
     */
#ifdef FORCE_METHOD
    if (ctx->level == 1 && eof && ctx->compressed_len == 0L) {
		/* force stored file */
#else
    if (stored_len <= opt_lenb && eof && ctx->compressed_len == 0L &&
		seekable()) {
#endif
        /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
        if (buf == NULL) error ("block vanished");

		/* without header */
        copy_block(zbcontext, buf, (unsigned)stored_len, 0);
        ctx->compressed_len = stored_len << 3;
    } else
#endif /* PGP */

#ifdef FORCE_METHOD
	if (ctx->level == 2 && buf != (char*)NULL) { /* force stored block */
#else
	if (stored_len+4 <= opt_lenb && buf != (char*)NULL) {
		/* 4: two words for the lengths */
#endif
        /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
         * Otherwise we can't have processed more than WSIZE input bytes since
         * the last block flush, because compression would have been
         * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
         * transform a block into a stored block.
         */
        send_bits(zbcontext, (STORED_BLOCK<<1)+eof, 3);  /* send block type */
        ctx->compressed_len = (ctx->compressed_len + 3 + 7) & ~7L;
		ctx->compressed_len += (stored_len + 4) << 3;

		copy_block(zbcontext, buf, (unsigned)stored_len, 1); /* with header */

#ifdef FORCE_METHOD
    } else if (ctx->level == 3) { /* force static trees */
#else
    } else if (static_lenb == opt_lenb) {
#endif
        send_bits(zbcontext, (STATIC_TREES<<1)+eof, 3);
        compress_block(ctx, zbcontext,
					   (ct_data near *)ctx->static_ltree,
					   (ct_data near *)ctx->static_dtree);
        ctx->compressed_len += 3 + ctx->static_len;
    } else {
        send_bits(zbcontext, (DYN_TREES<<1)+eof, 3);
        send_all_trees(ctx, zbcontext, ctx->l_desc.max_code+1,
					   ctx->d_desc.max_code+1, max_blindex+1);
        compress_block(ctx, zbcontext,
					   (ct_data near *)ctx->dyn_ltree,
					   (ct_data near *)ctx->dyn_dtree);
        ctx->compressed_len += 3 + ctx->opt_len;
    }
    ZipAssert (ctx->compressed_len == bits_sent, "bad compressed size");
    init_block(ctx);

    if (eof) {
#if defined(PGP) && !defined(MMAP)
        /* Wipe out sensitive data for pgp */
        pgpClearMemory( window,
        	(unsigned)(2*WSIZE-1)); /* -1 needed if WSIZE=32K */
#else /* !PGP */
        ZipAssert (ctx->input_len == ctx->isize, "bad input size");
#endif
		bi_windup(zbcontext);
        ctx->compressed_len += 7;  /* align on byte boundary */
    }
    Tracev((stderr,"\ncomprlen %lu(%lu) ", ctx->compressed_len>>3,
			ctx->compressed_len-7*eof));

    return ctx->compressed_len >> 3;
}

/* ===========================================================================
 * Save the match info and tally the frequency counts. Return true if
 * the current block must be flushed.
 *
 * dist is the distance to the matched string, or 0 if none.
 * lc is the length of the match, or the character if dist == 0.
 */
int
ct_tally(ZTreesContext *ctx, unsigned dist, unsigned lc, long block_start,
	unsigned strstart)
{
    ctx->l_buf[ctx->last_lit++] = (PGPByte)lc;
    if (dist == 0) {
        /* lc is the unmatched char */
        ctx->dyn_ltree[lc].Freq++;
    } else {
        /* Here, lc is the match length - MIN_MATCH */
        dist--;             /* dist = match distance - 1 */
        ZipAssert((PGPUInt16)dist < (PGPUInt16)MAX_DIST &&
               (PGPUInt16)lc <= (PGPUInt16)(MAX_MATCH-MIN_MATCH) &&
               (PGPUInt16)d_code(ctx, dist) < (PGPUInt16)D_CODES, 
               "ct_tally: bad match");

        ctx->dyn_ltree[ctx->length_code[lc]+LITERALS+1].Freq++;
        ctx->dyn_dtree[d_code(ctx, dist)].Freq++;

        ctx->d_buf[ctx->last_dist++] = (PGPUInt16)dist;
        ctx->flags |= ctx->flag_bit;
    }
    ctx->flag_bit <<= 1;

    /* Output the flags if they fill a byte: */
    if ((ctx->last_lit & 7) == 0) {
        ctx->flag_buf[ctx->last_flags++] = ctx->flags;
        ctx->flags = 0, ctx->flag_bit = 1;
    }
    /* Try to guess if it is profitable to stop the current block here */
    if (/* ctx->level > 2 && */ (ctx->last_lit & 0xfff) == 0) {
        /* Compute an upper bound for the compressed length */
        PGPUInt32 out_length = (PGPUInt32)ctx->last_lit*8L;
        PGPUInt32 in_length = (PGPUInt32)strstart-block_start;
        int dcode;

        for (dcode = 0; dcode < D_CODES; dcode++)
            out_length += (PGPUInt32)
				ctx->dyn_dtree[dcode].Freq*(5L+extra_dbits[dcode]);
        out_length >>= 3;
        Trace((stderr,"\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ",
               ctx->last_lit, ctx->last_dist, in_length, out_length,
               100L - out_length*100L/in_length));
        if (ctx->last_dist < ctx->last_lit/2 && out_length < in_length/2)
			return 1;
    }
    return (ctx->last_lit == LIT_BUFSIZE-1 || ctx->last_dist == DIST_BUFSIZE);
    /* We avoid equality with LIT_BUFSIZE because of wraparound at 64K
     * on 16 bit machines and because stored blocks are restricted to
     * 64K-1 bytes.
     */
}

/* ===========================================================================
 * Send the block data compressed using the given Huffman trees
 */
static void
compress_block(ZTreesContext *ctx, struct ZBitsContext *zbcontext,
	ct_data near *ltree, ct_data near *dtree)
{
    unsigned dist;      /* distance of matched string */
    int lc;             /* match length or unmatched char (if dist == 0) */
    unsigned lx = 0;    /* running index in l_buf */
    unsigned dx = 0;    /* running index in d_buf */
    unsigned fx = 0;    /* running index in flag_buf */
    PGPByte flag = 0;       /* current flags */
    unsigned code;      /* the code to send */
    int extra;          /* number of extra bits to send */

    if (ctx->last_lit != 0) do {
        if ((lx & 7) == 0)
			flag = ctx->flag_buf[fx++];
        lc = ctx->l_buf[lx++];
        if ((flag & 1) == 0) {
            send_code(zbcontext, lc, ltree); /* send a literal byte */
            Tracecv(isgraph(lc), (stderr," '%c' ", lc));
        } else {
            /* Here, lc is the match length - MIN_MATCH */
            code = ctx->length_code[lc];
			/* send the length code */
            send_code(zbcontext, code+LITERALS+1, ltree);
            extra = extra_lbits[code];
            if (extra != 0) {
                lc -= ctx->base_length[code];
				/* send the extra length bits */
                send_bits(zbcontext, lc, extra);
            }
            dist = ctx->d_buf[dx++];
            /* Here, dist is the match distance - 1 */
            code = d_code(ctx, dist);
            ZipAssert (code < D_CODES, "bad d_code");

			send_code(zbcontext, code, dtree);    /* send the distance code */
			extra = extra_dbits[code];
			if (extra != 0) {
				dist -= ctx->base_dist[code];
				/* send the extra distance bits */
				send_bits(zbcontext, dist, extra);
			}
		} /* literal or match pair ? */
		flag >>= 1;
    } while (lx < ctx->last_lit);

    send_code(zbcontext, END_BLOCK, ltree);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -