]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libarchive/archive_write_set_compression_gzip.c
Merge r340 from libarchive.googlecode.com: If zlib/bzlib aren't available,
[FreeBSD/FreeBSD.git] / lib / libarchive / archive_write_set_compression_gzip.c
1 /*-
2  * Copyright (c) 2003-2007 Tim Kientzle
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "archive_platform.h"
27
28 __FBSDID("$FreeBSD$");
29
30 #ifdef HAVE_ERRNO_H
31 #include <errno.h>
32 #endif
33 #ifdef HAVE_STDLIB_H
34 #include <stdlib.h>
35 #endif
36 #ifdef HAVE_STRING_H
37 #include <string.h>
38 #endif
39 #include <time.h>
40 #ifdef HAVE_ZLIB_H
41 #include <zlib.h>
42 #endif
43
44 #include "archive.h"
45 #include "archive_private.h"
46 #include "archive_write_private.h"
47
48 #ifndef HAVE_ZLIB_H
49 int
50 archive_write_set_compression_gzip(struct archive *_a)
51 {
52         /* Unsupported gzip compression, we don't have zlib */
53         return (ARCHIVE_FATAL);
54 }
55 #else
56 /* Don't compile this if we don't have zlib. */
57
58 struct private_data {
59         z_stream         stream;
60         int64_t          total_in;
61         unsigned char   *compressed;
62         size_t           compressed_buffer_size;
63         unsigned long    crc;
64 };
65
66
67 /*
68  * Yuck.  zlib.h is not const-correct, so I need this one bit
69  * of ugly hackery to convert a const * pointer to a non-const pointer.
70  */
71 #define SET_NEXT_IN(st,src)                                     \
72         (st)->stream.next_in = (Bytef *)(uintptr_t)(const void *)(src)
73
74 static int      archive_compressor_gzip_finish(struct archive_write *);
75 static int      archive_compressor_gzip_init(struct archive_write *);
76 static int      archive_compressor_gzip_write(struct archive_write *,
77                     const void *, size_t);
78 static int      drive_compressor(struct archive_write *, struct private_data *,
79                     int finishing);
80
81
82 /*
83  * Allocate, initialize and return a archive object.
84  */
85 int
86 archive_write_set_compression_gzip(struct archive *_a)
87 {
88         struct archive_write *a = (struct archive_write *)_a;
89         __archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC,
90             ARCHIVE_STATE_NEW, "archive_write_set_compression_gzip");
91         a->compressor.init = &archive_compressor_gzip_init;
92         a->archive.compression_code = ARCHIVE_COMPRESSION_GZIP;
93         a->archive.compression_name = "gzip";
94         return (ARCHIVE_OK);
95 }
96
97 /*
98  * Setup callback.
99  */
100 static int
101 archive_compressor_gzip_init(struct archive_write *a)
102 {
103         int ret;
104         struct private_data *state;
105         time_t t;
106
107         a->archive.compression_code = ARCHIVE_COMPRESSION_GZIP;
108         a->archive.compression_name = "gzip";
109
110         if (a->client_opener != NULL) {
111                 ret = (a->client_opener)(&a->archive, a->client_data);
112                 if (ret != ARCHIVE_OK)
113                         return (ret);
114         }
115
116         /*
117          * The next check is a temporary workaround until the gzip
118          * code can be overhauled some.  The code should not require
119          * that compressed_buffer_size == bytes_per_block.  Removing
120          * this assumption will allow us to compress larger chunks at
121          * a time, which should improve overall performance
122          * marginally.  As a minor side-effect, such a cleanup would
123          * allow us to support truly arbitrary block sizes.
124          */
125         if (a->bytes_per_block < 10) {
126                 archive_set_error(&a->archive, EINVAL,
127                     "GZip compressor requires a minimum 10 byte block size");
128                 return (ARCHIVE_FATAL);
129         }
130
131         state = (struct private_data *)malloc(sizeof(*state));
132         if (state == NULL) {
133                 archive_set_error(&a->archive, ENOMEM,
134                     "Can't allocate data for compression");
135                 return (ARCHIVE_FATAL);
136         }
137         memset(state, 0, sizeof(*state));
138
139         /*
140          * See comment above.  We should set compressed_buffer_size to
141          * max(bytes_per_block, 65536), but the code can't handle that yet.
142          */
143         state->compressed_buffer_size = a->bytes_per_block;
144         state->compressed = (unsigned char *)malloc(state->compressed_buffer_size);
145         state->crc = crc32(0L, NULL, 0);
146
147         if (state->compressed == NULL) {
148                 archive_set_error(&a->archive, ENOMEM,
149                     "Can't allocate data for compression buffer");
150                 free(state);
151                 return (ARCHIVE_FATAL);
152         }
153
154         state->stream.next_out = state->compressed;
155         state->stream.avail_out = state->compressed_buffer_size;
156
157         /* Prime output buffer with a gzip header. */
158         t = time(NULL);
159         state->compressed[0] = 0x1f; /* GZip signature bytes */
160         state->compressed[1] = 0x8b;
161         state->compressed[2] = 0x08; /* "Deflate" compression */
162         state->compressed[3] = 0; /* No options */
163         state->compressed[4] = (t)&0xff;  /* Timestamp */
164         state->compressed[5] = (t>>8)&0xff;
165         state->compressed[6] = (t>>16)&0xff;
166         state->compressed[7] = (t>>24)&0xff;
167         state->compressed[8] = 0; /* No deflate options */
168         state->compressed[9] = 3; /* OS=Unix */
169         state->stream.next_out += 10;
170         state->stream.avail_out -= 10;
171
172         a->compressor.write = archive_compressor_gzip_write;
173         a->compressor.finish = archive_compressor_gzip_finish;
174
175         /* Initialize compression library. */
176         ret = deflateInit2(&(state->stream),
177             Z_DEFAULT_COMPRESSION,
178             Z_DEFLATED,
179             -15 /* < 0 to suppress zlib header */,
180             8,
181             Z_DEFAULT_STRATEGY);
182
183         if (ret == Z_OK) {
184                 a->compressor.data = state;
185                 return (0);
186         }
187
188         /* Library setup failed: clean up. */
189         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Internal error "
190             "initializing compression library");
191         free(state->compressed);
192         free(state);
193
194         /* Override the error message if we know what really went wrong. */
195         switch (ret) {
196         case Z_STREAM_ERROR:
197                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
198                     "Internal error initializing "
199                     "compression library: invalid setup parameter");
200                 break;
201         case Z_MEM_ERROR:
202                 archive_set_error(&a->archive, ENOMEM, "Internal error initializing "
203                     "compression library");
204                 break;
205         case Z_VERSION_ERROR:
206                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
207                     "Internal error initializing "
208                     "compression library: invalid library version");
209                 break;
210         }
211
212         return (ARCHIVE_FATAL);
213 }
214
215 /*
216  * Write data to the compressed stream.
217  */
218 static int
219 archive_compressor_gzip_write(struct archive_write *a, const void *buff,
220     size_t length)
221 {
222         struct private_data *state;
223         int ret;
224
225         state = (struct private_data *)a->compressor.data;
226         if (a->client_writer == NULL) {
227                 archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
228                     "No write callback is registered?  "
229                     "This is probably an internal programming error.");
230                 return (ARCHIVE_FATAL);
231         }
232
233         /* Update statistics */
234         state->crc = crc32(state->crc, (const Bytef *)buff, length);
235         state->total_in += length;
236
237         /* Compress input data to output buffer */
238         SET_NEXT_IN(state, buff);
239         state->stream.avail_in = length;
240         if ((ret = drive_compressor(a, state, 0)) != ARCHIVE_OK)
241                 return (ret);
242
243         a->archive.file_position += length;
244         return (ARCHIVE_OK);
245 }
246
247
248 /*
249  * Finish the compression...
250  */
251 static int
252 archive_compressor_gzip_finish(struct archive_write *a)
253 {
254         ssize_t block_length, target_block_length, bytes_written;
255         int ret;
256         struct private_data *state;
257         unsigned tocopy;
258         unsigned char trailer[8];
259
260         state = (struct private_data *)a->compressor.data;
261         ret = 0;
262         if (a->client_writer == NULL) {
263                 archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
264                     "No write callback is registered?  "
265                     "This is probably an internal programming error.");
266                 ret = ARCHIVE_FATAL;
267                 goto cleanup;
268         }
269
270         /* By default, always pad the uncompressed data. */
271         if (a->pad_uncompressed) {
272                 tocopy = a->bytes_per_block -
273                     (state->total_in % a->bytes_per_block);
274                 while (tocopy > 0 && tocopy < (unsigned)a->bytes_per_block) {
275                         SET_NEXT_IN(state, a->nulls);
276                         state->stream.avail_in = tocopy < a->null_length ?
277                             tocopy : a->null_length;
278                         state->crc = crc32(state->crc, a->nulls,
279                             state->stream.avail_in);
280                         state->total_in += state->stream.avail_in;
281                         tocopy -= state->stream.avail_in;
282                         ret = drive_compressor(a, state, 0);
283                         if (ret != ARCHIVE_OK)
284                                 goto cleanup;
285                 }
286         }
287
288         /* Finish compression cycle */
289         if (((ret = drive_compressor(a, state, 1))) != ARCHIVE_OK)
290                 goto cleanup;
291
292         /* Build trailer: 4-byte CRC and 4-byte length. */
293         trailer[0] = (state->crc)&0xff;
294         trailer[1] = (state->crc >> 8)&0xff;
295         trailer[2] = (state->crc >> 16)&0xff;
296         trailer[3] = (state->crc >> 24)&0xff;
297         trailer[4] = (state->total_in)&0xff;
298         trailer[5] = (state->total_in >> 8)&0xff;
299         trailer[6] = (state->total_in >> 16)&0xff;
300         trailer[7] = (state->total_in >> 24)&0xff;
301
302         /* Add trailer to current block. */
303         tocopy = 8;
304         if (tocopy > state->stream.avail_out)
305                 tocopy = state->stream.avail_out;
306         memcpy(state->stream.next_out, trailer, tocopy);
307         state->stream.next_out += tocopy;
308         state->stream.avail_out -= tocopy;
309
310         /* If it overflowed, flush and start a new block. */
311         if (tocopy < 8) {
312                 bytes_written = (a->client_writer)(&a->archive, a->client_data,
313                     state->compressed, state->compressed_buffer_size);
314                 if (bytes_written <= 0) {
315                         ret = ARCHIVE_FATAL;
316                         goto cleanup;
317                 }
318                 a->archive.raw_position += bytes_written;
319                 state->stream.next_out = state->compressed;
320                 state->stream.avail_out = state->compressed_buffer_size;
321                 memcpy(state->stream.next_out, trailer + tocopy, 8-tocopy);
322                 state->stream.next_out += 8-tocopy;
323                 state->stream.avail_out -= 8-tocopy;
324         }
325
326         /* Optionally, pad the final compressed block. */
327         block_length = state->stream.next_out - state->compressed;
328
329
330         /* Tricky calculation to determine size of last block. */
331         target_block_length = block_length;
332         if (a->bytes_in_last_block <= 0)
333                 /* Default or Zero: pad to full block */
334                 target_block_length = a->bytes_per_block;
335         else
336                 /* Round length to next multiple of bytes_in_last_block. */
337                 target_block_length = a->bytes_in_last_block *
338                     ( (block_length + a->bytes_in_last_block - 1) /
339                         a->bytes_in_last_block);
340         if (target_block_length > a->bytes_per_block)
341                 target_block_length = a->bytes_per_block;
342         if (block_length < target_block_length) {
343                 memset(state->stream.next_out, 0,
344                     target_block_length - block_length);
345                 block_length = target_block_length;
346         }
347
348         /* Write the last block */
349         bytes_written = (a->client_writer)(&a->archive, a->client_data,
350             state->compressed, block_length);
351         if (bytes_written <= 0) {
352                 ret = ARCHIVE_FATAL;
353                 goto cleanup;
354         }
355         a->archive.raw_position += bytes_written;
356
357         /* Cleanup: shut down compressor, release memory, etc. */
358 cleanup:
359         switch (deflateEnd(&(state->stream))) {
360         case Z_OK:
361                 break;
362         default:
363                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
364                     "Failed to clean up compressor");
365                 ret = ARCHIVE_FATAL;
366         }
367         free(state->compressed);
368         free(state);
369         return (ret);
370 }
371
372 /*
373  * Utility function to push input data through compressor,
374  * writing full output blocks as necessary.
375  *
376  * Note that this handles both the regular write case (finishing ==
377  * false) and the end-of-archive case (finishing == true).
378  */
379 static int
380 drive_compressor(struct archive_write *a, struct private_data *state, int finishing)
381 {
382         ssize_t bytes_written;
383         int ret;
384
385         for (;;) {
386                 if (state->stream.avail_out == 0) {
387                         bytes_written = (a->client_writer)(&a->archive,
388                             a->client_data, state->compressed,
389                             state->compressed_buffer_size);
390                         if (bytes_written <= 0) {
391                                 /* TODO: Handle this write failure */
392                                 return (ARCHIVE_FATAL);
393                         } else if ((size_t)bytes_written < state->compressed_buffer_size) {
394                                 /* Short write: Move remaining to
395                                  * front of block and keep filling */
396                                 memmove(state->compressed,
397                                     state->compressed + bytes_written,
398                                     state->compressed_buffer_size - bytes_written);
399                         }
400                         a->archive.raw_position += bytes_written;
401                         state->stream.next_out
402                             = state->compressed +
403                             state->compressed_buffer_size - bytes_written;
404                         state->stream.avail_out = bytes_written;
405                 }
406
407                 /* If there's nothing to do, we're done. */
408                 if (!finishing && state->stream.avail_in == 0)
409                         return (ARCHIVE_OK);
410
411                 ret = deflate(&(state->stream),
412                     finishing ? Z_FINISH : Z_NO_FLUSH );
413
414                 switch (ret) {
415                 case Z_OK:
416                         /* In non-finishing case, check if compressor
417                          * consumed everything */
418                         if (!finishing && state->stream.avail_in == 0)
419                                 return (ARCHIVE_OK);
420                         /* In finishing case, this return always means
421                          * there's more work */
422                         break;
423                 case Z_STREAM_END:
424                         /* This return can only occur in finishing case. */
425                         return (ARCHIVE_OK);
426                 default:
427                         /* Any other return value indicates an error. */
428                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
429                             "GZip compression failed:"
430                             " deflate() call returned status %d",
431                             ret);
432                         return (ARCHIVE_FATAL);
433                 }
434         }
435 }
436
437 #endif /* HAVE_ZLIB_H */