1228753Smm/*-
2228753Smm * Copyright (c) 2008 Joerg Sonnenberger
3228753Smm * All rights reserved.
4228753Smm *
5228753Smm * Redistribution and use in source and binary forms, with or without
6228753Smm * modification, are permitted provided that the following conditions
7228753Smm * are met:
8228753Smm * 1. Redistributions of source code must retain the above copyright
9228753Smm *    notice, this list of conditions and the following disclaimer.
10228753Smm * 2. Redistributions in binary form must reproduce the above copyright
11228753Smm *    notice, this list of conditions and the following disclaimer in the
12228753Smm *    documentation and/or other materials provided with the distribution.
13228753Smm *
14228753Smm * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15228753Smm * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16228753Smm * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17228753Smm * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18228753Smm * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19228753Smm * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20228753Smm * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21228753Smm * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22228753Smm * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23228753Smm * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24228753Smm */
25228753Smm
26228753Smm/*-
27228753Smm * Copyright (c) 1985, 1986, 1992, 1993
28228753Smm *	The Regents of the University of California.  All rights reserved.
29228753Smm *
30228753Smm * This code is derived from software contributed to Berkeley by
31228753Smm * Diomidis Spinellis and James A. Woods, derived from original
32228753Smm * work by Spencer Thomas and Joseph Orost.
33228753Smm *
34228753Smm * Redistribution and use in source and binary forms, with or without
35228753Smm * modification, are permitted provided that the following conditions
36228753Smm * are met:
37228753Smm * 1. Redistributions of source code must retain the above copyright
38228753Smm *    notice, this list of conditions and the following disclaimer.
39228753Smm * 2. Redistributions in binary form must reproduce the above copyright
40228753Smm *    notice, this list of conditions and the following disclaimer in the
41228753Smm *    documentation and/or other materials provided with the distribution.
42228753Smm * 3. Neither the name of the University nor the names of its contributors
43228753Smm *    may be used to endorse or promote products derived from this software
44228753Smm *    without specific prior written permission.
45228753Smm *
46228753Smm * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
47228753Smm * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48228753Smm * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49228753Smm * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
50228753Smm * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
51228753Smm * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
52228753Smm * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
53228753Smm * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
54228753Smm * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
55228753Smm * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
56228753Smm * SUCH DAMAGE.
57228753Smm */
58228753Smm
59228753Smm#include "archive_platform.h"
60228753Smm
61228753Smm__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_compression_compress.c 201111 2009-12-28 03:33:05Z kientzle $");
62228753Smm
63228753Smm#ifdef HAVE_ERRNO_H
64228753Smm#include <errno.h>
65228753Smm#endif
66228753Smm#ifdef HAVE_STDLIB_H
67228753Smm#include <stdlib.h>
68228753Smm#endif
69228753Smm#ifdef HAVE_STRING_H
70228753Smm#include <string.h>
71228753Smm#endif
72228753Smm
73228753Smm#include "archive.h"
74228753Smm#include "archive_private.h"
75228753Smm#include "archive_write_private.h"
76228753Smm
77228753Smm#define	HSIZE		69001	/* 95% occupancy */
78228753Smm#define	HSHIFT		8	/* 8 - trunc(log2(HSIZE / 65536)) */
79228753Smm#define	CHECK_GAP 10000		/* Ratio check interval. */
80228753Smm
81228753Smm#define	MAXCODE(bits)	((1 << (bits)) - 1)
82228753Smm
83228753Smm/*
84228753Smm * the next two codes should not be changed lightly, as they must not
85228753Smm * lie within the contiguous general code space.
86228753Smm */
87228753Smm#define	FIRST	257		/* First free entry. */
88228753Smm#define	CLEAR	256		/* Table clear output code. */
89228753Smm
90228753Smmstruct private_data {
91231200Smm	int64_t in_count, out_count, checkpoint;
92228753Smm
93228753Smm	int code_len;			/* Number of bits/code. */
94228753Smm	int cur_maxcode;		/* Maximum code, given n_bits. */
95228753Smm	int max_maxcode;		/* Should NEVER generate this code. */
96228753Smm	int hashtab [HSIZE];
97228753Smm	unsigned short codetab [HSIZE];
98228753Smm	int first_free;		/* First unused entry. */
99228753Smm	int compress_ratio;
100228753Smm
101228753Smm	int cur_code, cur_fcode;
102228753Smm
103228753Smm	int bit_offset;
104228753Smm	unsigned char bit_buf;
105228753Smm
106228753Smm	unsigned char	*compressed;
107228753Smm	size_t		 compressed_buffer_size;
108228753Smm	size_t		 compressed_offset;
109228753Smm};
110228753Smm
111231200Smmstatic int archive_compressor_compress_open(struct archive_write_filter *);
112231200Smmstatic int archive_compressor_compress_write(struct archive_write_filter *,
113228753Smm		    const void *, size_t);
114231200Smmstatic int archive_compressor_compress_close(struct archive_write_filter *);
115231200Smmstatic int archive_compressor_compress_free(struct archive_write_filter *);
116228753Smm
117231200Smm#if ARCHIVE_VERSION_NUMBER < 4000000
118231200Smmint
119231200Smmarchive_write_set_compression_compress(struct archive *a)
120231200Smm{
121231200Smm	__archive_write_filters_free(a);
122231200Smm	return (archive_write_add_filter_compress(a));
123231200Smm}
124231200Smm#endif
125231200Smm
126228753Smm/*
127231200Smm * Add a compress filter to this write handle.
128228753Smm */
129228753Smmint
130231200Smmarchive_write_add_filter_compress(struct archive *_a)
131228753Smm{
132228753Smm	struct archive_write *a = (struct archive_write *)_a;
133231200Smm	struct archive_write_filter *f = __archive_write_allocate_filter(_a);
134231200Smm
135231200Smm	archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC,
136231200Smm	    ARCHIVE_STATE_NEW, "archive_write_add_filter_compress");
137231200Smm	f->open = &archive_compressor_compress_open;
138248616Smm	f->code = ARCHIVE_FILTER_COMPRESS;
139231200Smm	f->name = "compress";
140228753Smm	return (ARCHIVE_OK);
141228753Smm}
142228753Smm
143228753Smm/*
144228753Smm * Setup callback.
145228753Smm */
146228753Smmstatic int
147231200Smmarchive_compressor_compress_open(struct archive_write_filter *f)
148228753Smm{
149228753Smm	int ret;
150228753Smm	struct private_data *state;
151238856Smm	size_t bs = 65536, bpb;
152228753Smm
153248616Smm	f->code = ARCHIVE_FILTER_COMPRESS;
154231200Smm	f->name = "compress";
155228753Smm
156231200Smm	ret = __archive_write_open_filter(f->next_filter);
157231200Smm	if (ret != ARCHIVE_OK)
158231200Smm		return (ret);
159228753Smm
160231200Smm	state = (struct private_data *)calloc(1, sizeof(*state));
161228753Smm	if (state == NULL) {
162231200Smm		archive_set_error(f->archive, ENOMEM,
163228753Smm		    "Can't allocate data for compression");
164228753Smm		return (ARCHIVE_FATAL);
165228753Smm	}
166228753Smm
167238856Smm	if (f->archive->magic == ARCHIVE_WRITE_MAGIC) {
168238856Smm		/* Buffer size should be a multiple number of the of bytes
169238856Smm		 * per block for performance. */
170238856Smm		bpb = archive_write_get_bytes_per_block(f->archive);
171238856Smm		if (bpb > bs)
172238856Smm			bs = bpb;
173238856Smm		else if (bpb != 0)
174238856Smm			bs -= bs % bpb;
175238856Smm	}
176238856Smm	state->compressed_buffer_size = bs;
177228753Smm	state->compressed = malloc(state->compressed_buffer_size);
178228753Smm
179228753Smm	if (state->compressed == NULL) {
180231200Smm		archive_set_error(f->archive, ENOMEM,
181228753Smm		    "Can't allocate data for compression buffer");
182228753Smm		free(state);
183228753Smm		return (ARCHIVE_FATAL);
184228753Smm	}
185228753Smm
186231200Smm	f->write = archive_compressor_compress_write;
187231200Smm	f->close = archive_compressor_compress_close;
188231200Smm	f->free = archive_compressor_compress_free;
189228753Smm
190228753Smm	state->max_maxcode = 0x10000;	/* Should NEVER generate this code. */
191228753Smm	state->in_count = 0;		/* Length of input. */
192228753Smm	state->bit_buf = 0;
193228753Smm	state->bit_offset = 0;
194228753Smm	state->out_count = 3;		/* Includes 3-byte header mojo. */
195228753Smm	state->compress_ratio = 0;
196228753Smm	state->checkpoint = CHECK_GAP;
197228753Smm	state->code_len = 9;
198228753Smm	state->cur_maxcode = MAXCODE(state->code_len);
199228753Smm	state->first_free = FIRST;
200228753Smm
201228753Smm	memset(state->hashtab, 0xff, sizeof(state->hashtab));
202228753Smm
203228753Smm	/* Prime output buffer with a gzip header. */
204228753Smm	state->compressed[0] = 0x1f; /* Compress */
205228753Smm	state->compressed[1] = 0x9d;
206228753Smm	state->compressed[2] = 0x90; /* Block mode, 16bit max */
207228753Smm	state->compressed_offset = 3;
208228753Smm
209231200Smm	f->data = state;
210228753Smm	return (0);
211228753Smm}
212228753Smm
213228753Smm/*-
214228753Smm * Output the given code.
215228753Smm * Inputs:
216228753Smm * 	code:	A n_bits-bit integer.  If == -1, then EOF.  This assumes
217231200Smm *		that n_bits <= (long)wordsize - 1.
218228753Smm * Outputs:
219228753Smm * 	Outputs code to the file.
220228753Smm * Assumptions:
221228753Smm *	Chars are 8 bits long.
222228753Smm * Algorithm:
223228753Smm * 	Maintain a BITS character long buffer (so that 8 codes will
224228753Smm * fit in it exactly).  Use the VAX insv instruction to insert each
225228753Smm * code in turn.  When the buffer fills up empty it and start over.
226228753Smm */
227228753Smm
228231200Smmstatic const unsigned char rmask[9] =
229228753Smm	{0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
230228753Smm
231228753Smmstatic int
232231200Smmoutput_byte(struct archive_write_filter *f, unsigned char c)
233228753Smm{
234231200Smm	struct private_data *state = f->data;
235228753Smm
236228753Smm	state->compressed[state->compressed_offset++] = c;
237228753Smm	++state->out_count;
238228753Smm
239228753Smm	if (state->compressed_buffer_size == state->compressed_offset) {
240231200Smm		int ret = __archive_write_filter(f->next_filter,
241228753Smm		    state->compressed, state->compressed_buffer_size);
242231200Smm		if (ret != ARCHIVE_OK)
243228753Smm			return ARCHIVE_FATAL;
244228753Smm		state->compressed_offset = 0;
245228753Smm	}
246228753Smm
247228753Smm	return ARCHIVE_OK;
248228753Smm}
249228753Smm
250228753Smmstatic int
251231200Smmoutput_code(struct archive_write_filter *f, int ocode)
252228753Smm{
253231200Smm	struct private_data *state = f->data;
254228753Smm	int bits, ret, clear_flg, bit_offset;
255228753Smm
256228753Smm	clear_flg = ocode == CLEAR;
257228753Smm
258228753Smm	/*
259228753Smm	 * Since ocode is always >= 8 bits, only need to mask the first
260228753Smm	 * hunk on the left.
261228753Smm	 */
262228753Smm	bit_offset = state->bit_offset % 8;
263228753Smm	state->bit_buf |= (ocode << bit_offset) & 0xff;
264231200Smm	output_byte(f, state->bit_buf);
265228753Smm
266228753Smm	bits = state->code_len - (8 - bit_offset);
267228753Smm	ocode >>= 8 - bit_offset;
268228753Smm	/* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
269228753Smm	if (bits >= 8) {
270231200Smm		output_byte(f, ocode & 0xff);
271228753Smm		ocode >>= 8;
272228753Smm		bits -= 8;
273228753Smm	}
274228753Smm	/* Last bits. */
275228753Smm	state->bit_offset += state->code_len;
276228753Smm	state->bit_buf = ocode & rmask[bits];
277228753Smm	if (state->bit_offset == state->code_len * 8)
278228753Smm		state->bit_offset = 0;
279228753Smm
280228753Smm	/*
281228753Smm	 * If the next entry is going to be too big for the ocode size,
282228753Smm	 * then increase it, if possible.
283228753Smm	 */
284228753Smm	if (clear_flg || state->first_free > state->cur_maxcode) {
285228753Smm	       /*
286228753Smm		* Write the whole buffer, because the input side won't
287228753Smm		* discover the size increase until after it has read it.
288228753Smm		*/
289228753Smm		if (state->bit_offset > 0) {
290228753Smm			while (state->bit_offset < state->code_len * 8) {
291231200Smm				ret = output_byte(f, state->bit_buf);
292228753Smm				if (ret != ARCHIVE_OK)
293228753Smm					return ret;
294228753Smm				state->bit_offset += 8;
295228753Smm				state->bit_buf = 0;
296228753Smm			}
297228753Smm		}
298228753Smm		state->bit_buf = 0;
299228753Smm		state->bit_offset = 0;
300228753Smm
301228753Smm		if (clear_flg) {
302228753Smm			state->code_len = 9;
303228753Smm			state->cur_maxcode = MAXCODE(state->code_len);
304228753Smm		} else {
305228753Smm			state->code_len++;
306228753Smm			if (state->code_len == 16)
307228753Smm				state->cur_maxcode = state->max_maxcode;
308228753Smm			else
309228753Smm				state->cur_maxcode = MAXCODE(state->code_len);
310228753Smm		}
311228753Smm	}
312228753Smm
313228753Smm	return (ARCHIVE_OK);
314228753Smm}
315228753Smm
316228753Smmstatic int
317231200Smmoutput_flush(struct archive_write_filter *f)
318228753Smm{
319231200Smm	struct private_data *state = f->data;
320228753Smm	int ret;
321228753Smm
322228753Smm	/* At EOF, write the rest of the buffer. */
323228753Smm	if (state->bit_offset % 8) {
324228753Smm		state->code_len = (state->bit_offset % 8 + 7) / 8;
325231200Smm		ret = output_byte(f, state->bit_buf);
326228753Smm		if (ret != ARCHIVE_OK)
327228753Smm			return ret;
328228753Smm	}
329228753Smm
330228753Smm	return (ARCHIVE_OK);
331228753Smm}
332228753Smm
333228753Smm/*
334228753Smm * Write data to the compressed stream.
335228753Smm */
336228753Smmstatic int
337231200Smmarchive_compressor_compress_write(struct archive_write_filter *f,
338231200Smm    const void *buff, size_t length)
339228753Smm{
340231200Smm	struct private_data *state = (struct private_data *)f->data;
341228753Smm	int i;
342228753Smm	int ratio;
343228753Smm	int c, disp, ret;
344228753Smm	const unsigned char *bp;
345228753Smm
346228753Smm	if (length == 0)
347228753Smm		return ARCHIVE_OK;
348228753Smm
349228753Smm	bp = buff;
350228753Smm
351228753Smm	if (state->in_count == 0) {
352228753Smm		state->cur_code = *bp++;
353228753Smm		++state->in_count;
354228753Smm		--length;
355228753Smm	}
356228753Smm
357228753Smm	while (length--) {
358228753Smm		c = *bp++;
359228753Smm		state->in_count++;
360228753Smm		state->cur_fcode = (c << 16) + state->cur_code;
361228753Smm		i = ((c << HSHIFT) ^ state->cur_code);	/* Xor hashing. */
362228753Smm
363228753Smm		if (state->hashtab[i] == state->cur_fcode) {
364228753Smm			state->cur_code = state->codetab[i];
365228753Smm			continue;
366228753Smm		}
367228753Smm		if (state->hashtab[i] < 0)	/* Empty slot. */
368228753Smm			goto nomatch;
369228753Smm		/* Secondary hash (after G. Knott). */
370228753Smm		if (i == 0)
371228753Smm			disp = 1;
372228753Smm		else
373228753Smm			disp = HSIZE - i;
374231200Smm probe:
375228753Smm		if ((i -= disp) < 0)
376228753Smm			i += HSIZE;
377228753Smm
378228753Smm		if (state->hashtab[i] == state->cur_fcode) {
379228753Smm			state->cur_code = state->codetab[i];
380228753Smm			continue;
381228753Smm		}
382228753Smm		if (state->hashtab[i] >= 0)
383228753Smm			goto probe;
384231200Smm nomatch:
385231200Smm		ret = output_code(f, state->cur_code);
386228753Smm		if (ret != ARCHIVE_OK)
387228753Smm			return ret;
388228753Smm		state->cur_code = c;
389228753Smm		if (state->first_free < state->max_maxcode) {
390228753Smm			state->codetab[i] = state->first_free++;	/* code -> hashtable */
391228753Smm			state->hashtab[i] = state->cur_fcode;
392228753Smm			continue;
393228753Smm		}
394228753Smm		if (state->in_count < state->checkpoint)
395228753Smm			continue;
396228753Smm
397228753Smm		state->checkpoint = state->in_count + CHECK_GAP;
398228753Smm
399238856Smm		if (state->in_count <= 0x007fffff && state->out_count != 0)
400238856Smm			ratio = (int)(state->in_count * 256 / state->out_count);
401238856Smm		else if ((ratio = (int)(state->out_count / 256)) == 0)
402228753Smm			ratio = 0x7fffffff;
403228753Smm		else
404238856Smm			ratio = (int)(state->in_count / ratio);
405228753Smm
406228753Smm		if (ratio > state->compress_ratio)
407228753Smm			state->compress_ratio = ratio;
408228753Smm		else {
409228753Smm			state->compress_ratio = 0;
410228753Smm			memset(state->hashtab, 0xff, sizeof(state->hashtab));
411228753Smm			state->first_free = FIRST;
412231200Smm			ret = output_code(f, CLEAR);
413228753Smm			if (ret != ARCHIVE_OK)
414228753Smm				return ret;
415228753Smm		}
416228753Smm	}
417228753Smm
418228753Smm	return (ARCHIVE_OK);
419228753Smm}
420228753Smm
421228753Smm
422228753Smm/*
423228753Smm * Finish the compression...
424228753Smm */
425228753Smmstatic int
426231200Smmarchive_compressor_compress_close(struct archive_write_filter *f)
427228753Smm{
428231200Smm	struct private_data *state = (struct private_data *)f->data;
429231200Smm	int ret, ret2;
430228753Smm
431231200Smm	ret = output_code(f, state->cur_code);
432228753Smm	if (ret != ARCHIVE_OK)
433228753Smm		goto cleanup;
434231200Smm	ret = output_flush(f);
435228753Smm	if (ret != ARCHIVE_OK)
436228753Smm		goto cleanup;
437228753Smm
438228753Smm	/* Write the last block */
439231200Smm	ret = __archive_write_filter(f->next_filter,
440231200Smm	    state->compressed, state->compressed_offset);
441228753Smmcleanup:
442231200Smm	ret2 = __archive_write_close_filter(f->next_filter);
443231200Smm	if (ret > ret2)
444231200Smm		ret = ret2;
445228753Smm	free(state->compressed);
446228753Smm	free(state);
447228753Smm	return (ret);
448228753Smm}
449231200Smm
450231200Smmstatic int
451231200Smmarchive_compressor_compress_free(struct archive_write_filter *f)
452231200Smm{
453231200Smm	(void)f; /* UNUSED */
454231200Smm	return (ARCHIVE_OK);
455231200Smm}
456