File: gzip.cc

package info (click to toggle)
monotone 0.48-3
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 20,096 kB
  • ctags: 8,077
  • sloc: cpp: 81,000; sh: 6,402; perl: 1,241; lisp: 1,045; makefile: 655; python: 566; sql: 112; ansic: 52
file content (428 lines) | stat: -rw-r--r-- 13,526 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/*************************************************
* Gzip Compressor Source File                    *
* (C) 2001 Peter J Jones (pjones@pmade.org)      *
*     2001-2004 Jack Lloyd                       *
*                                                *
* Based on the comp_zlib module, modified        *
* by Matt Johnston. This is not a complete       *
* gzip implementation (it only handles basic     *
* headers).                                      *
*************************************************/

/* This could be implemented a lot more cleanly if we rely on zlib >= 1.2
 * being available. the Gzip Compressor would just be a subclass of
 * Zlib Compressor, with window_bits+=16 for deflateInit2(), etc */

#include <base.hh>
#include <gzip.hh>

#include <botan/botan.h>

#if BOTAN_VERSION_CODE >= BOTAN_VERSION_CODE_FOR(1,7,7)
#include <botan/loadstor.h>
#include <botan/filters.h>
#endif

#include <cstring>
#include <map>
#include <zlib.h>

namespace Botan {

namespace {

/*************************************************
* Allocation Information for Zlib                *
*************************************************/
class Zlib_Alloc_Info
   {
   public:
      std::map<void*, u32bit> current_allocs;
      Allocator* alloc;

      Zlib_Alloc_Info() { alloc = Allocator::get(false); }
   };

/*************************************************
* Allocation Function for Zlib                   *
*************************************************/
void* zlib_malloc(void* info_ptr, unsigned int n, unsigned int size)
   {
   Zlib_Alloc_Info* info = static_cast<Zlib_Alloc_Info*>(info_ptr);
   void* ptr = info->alloc->allocate(n * size);
   info->current_allocs[ptr] = n * size;
   return ptr;
   }

/*************************************************
* Allocation Function for Zlib                   *
*************************************************/
void zlib_free(void* info_ptr, void* ptr)
   {
   Zlib_Alloc_Info* info = static_cast<Zlib_Alloc_Info*>(info_ptr);
   std::map<void*, u32bit>::const_iterator i = info->current_allocs.find(ptr);
   if(i == info->current_allocs.end())
      throw Invalid_Argument("zlib_free: Got pointer not allocated by us");
   info->alloc->deallocate(ptr, i->second);
   }
}

/*************************************************
* Wrapper Type for Zlib z_stream                 *
*************************************************/
class Zlib_Stream
   {
   public:
      z_stream stream;

      Zlib_Stream()
         {
         std::memset(&stream, 0, sizeof(z_stream));
         stream.zalloc = zlib_malloc;
         stream.zfree = zlib_free;
         stream.opaque = new Zlib_Alloc_Info;
         }
      ~Zlib_Stream()
         {
         Zlib_Alloc_Info* info = static_cast<Zlib_Alloc_Info*>(stream.opaque);
         delete info;
         std::memset(&stream, 0, sizeof(z_stream));
         }
   };

/*************************************************
* Gzip_Compression Constructor                   *
*************************************************/
Gzip_Compression::Gzip_Compression(u32bit l) :
   level((l >= 9) ? 9 : l), buffer(DEFAULT_BUFFERSIZE),
   pipe(new Hash_Filter("CRC32")), count( 0 )
   {

   zlib = new Zlib_Stream;
   // window_bits == -15 relies on an undocumented feature of zlib, which
   // supresses the zlib header on the message. We need that since gzip doesn't
   // use this header.  The feature been confirmed to exist in 1.1.4, which
   // everyone should be using due to security fixes. In later versions this
   // feature is documented, along with the ability to do proper gzip output
   // (that would be a nicer way to do things, but will have to wait until 1.2
   // becomes more widespread).
   // The other settings are the defaults that deflateInit() gives
   if(deflateInit2(&(zlib->stream), level, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) != Z_OK)
      {
      delete zlib; zlib = 0;
      throw Exception("Gzip_Compression: Memory allocation error");
      }
   }

/*************************************************
* Gzip_Compression Destructor                    *
*************************************************/
Gzip_Compression::~Gzip_Compression()
   {
   deflateEnd(&(zlib->stream));
   delete zlib; zlib = 0;
   }

/*************************************************
* Start Compressing with Gzip                    *
*************************************************/
void Gzip_Compression::start_msg()
   {
   clear();
   put_header();
   pipe.start_msg();
   count = 0;
   }

/*************************************************
* Compress Input with Gzip                       *
*************************************************/
void Gzip_Compression::write(const byte input[], u32bit length)
   {

   count += length;
   pipe.write(input, length);

   zlib->stream.next_in = (Bytef*)input;
   zlib->stream.avail_in = length;

   while(zlib->stream.avail_in != 0)
      {
      zlib->stream.next_out = (Bytef*)buffer.begin();
      zlib->stream.avail_out = buffer.size();
      int rc = deflate(&(zlib->stream), Z_NO_FLUSH);
      if (rc != Z_OK && rc != Z_STREAM_END)
         throw Exception("Internal error in Gzip_Compression deflate.");
      send(buffer.begin(), buffer.size() - zlib->stream.avail_out);
      }
   }

/*************************************************
* Finish Compressing with Gzip                   *
*************************************************/
void Gzip_Compression::end_msg()
   {
   zlib->stream.next_in = 0;
   zlib->stream.avail_in = 0;

   int rc = Z_OK;
   while(rc != Z_STREAM_END)
      {
      zlib->stream.next_out = (Bytef*)buffer.begin();
      zlib->stream.avail_out = buffer.size();
      rc = deflate(&(zlib->stream), Z_FINISH);
      if (rc != Z_OK && rc != Z_STREAM_END)
         throw Exception("Internal error in Gzip_Compression finishing deflate.");
      send(buffer.begin(), buffer.size() - zlib->stream.avail_out);
      }

   pipe.end_msg();
   put_footer();
   clear();
   }

/*************************************************
* Clean up Compression Context                   *
*************************************************/
void Gzip_Compression::clear()
   {
   deflateReset(&(zlib->stream));
   }

/*************************************************
* Put a basic gzip header at the beginning       *
*************************************************/
void Gzip_Compression::put_header()
   {
   send(GZIP::GZIP_HEADER, sizeof(GZIP::GZIP_HEADER));
   }

/*************************************************
* Put a gzip footer at the end                   *
*************************************************/
void Gzip_Compression::put_footer()
   {
   // 4 byte CRC32, and 4 byte length field
   SecureVector<byte> buf(4);
   SecureVector<byte> tmpbuf(4);

   pipe.read(tmpbuf.begin(), tmpbuf.size(), Pipe::LAST_MESSAGE);

   // CRC32 is the reverse order to what gzip expects.
   for (int i = 0; i < 4; i++)
      buf[3-i] = tmpbuf[i];

   send(buf.begin(), buf.size());

   // Length - LSB first
   for (int i = 0; i < 4; i++)
      buf[3-i] = get_byte(i, count);

   send(buf.begin(), buf.size());
   }

/*************************************************
* Gzip_Decompression Constructor                 *
*************************************************/
Gzip_Decompression::Gzip_Decompression() : buffer(DEFAULT_BUFFERSIZE),
   no_writes(true), pipe(new Hash_Filter("CRC32")), footer(0)
   {
   if (DEFAULT_BUFFERSIZE < sizeof(GZIP::GZIP_HEADER))
      throw Exception("DEFAULT_BUFFERSIZE is too small");

   zlib = new Zlib_Stream;

   // window_bits == -15 is raw zlib (no header) - see comment
   // above about deflateInit2
   if(inflateInit2(&(zlib->stream), -15) != Z_OK)
      {
      delete zlib; zlib = 0;
      throw Exception("Gzip_Decompression: Memory allocation error");
      }
   }

/*************************************************
* Gzip_Decompression Destructor                  *
*************************************************/
Gzip_Decompression::~Gzip_Decompression()
   {
      inflateEnd(&(zlib->stream));
      delete zlib; zlib = 0;
   }

/*************************************************
* Start Decompressing with Gzip                  *
*************************************************/
void Gzip_Decompression::start_msg()
   {
   if (!no_writes)
      throw Exception("Gzip_Decompression: start_msg after already writing");

   pipe.start_msg();
   datacount = 0;
   pos = 0;
   in_footer = false;
   }

/*************************************************
* Decompress Input with Gzip                     *
*************************************************/
void Gzip_Decompression::write(const byte input[], u32bit length)
   {
   if(length) no_writes = false;

   // If we're in the footer, take what we need, then go to the next block
   if (in_footer)
      {
         u32bit eat_len = eat_footer(input, length);
         input += eat_len;
         length -= eat_len;
         if (length == 0)
            return;
      }

   // Check the gzip header
   if (pos < sizeof(GZIP::GZIP_HEADER))
      {
      u32bit len = std::min((u32bit)sizeof(GZIP::GZIP_HEADER)-pos, length);
      u32bit cmplen = len;
      // The last byte is the OS flag - we don't care about that
      if (pos + len - 1 >= GZIP::HEADER_POS_OS)
         cmplen--;

      if (std::memcmp(input, &GZIP::GZIP_HEADER[pos], cmplen) != 0)
         {
         throw Decoding_Error("Gzip_Decompression: Data integrity error in header");
         }
      input += len;
      length -= len;
      pos += len;
      }

   pos += length;

   zlib->stream.next_in = (Bytef*)input;
   zlib->stream.avail_in = length;

   while(zlib->stream.avail_in != 0)
      {
      zlib->stream.next_out = (Bytef*)buffer.begin();
      zlib->stream.avail_out = buffer.size();

      int rc = inflate(&(zlib->stream), Z_SYNC_FLUSH);
      if(rc != Z_OK && rc != Z_STREAM_END)
         {
         if(rc == Z_DATA_ERROR)
            throw Decoding_Error("Gzip_Decompression: Data integrity error");
         if(rc == Z_NEED_DICT)
            throw Decoding_Error("Gzip_Decompression: Need preset dictionary");
         if(rc == Z_MEM_ERROR)
            throw Exception("Gzip_Decompression: Memory allocation error");
         throw Exception("Gzip_Decompression: Unknown decompress error");
         }
      send(buffer.begin(), buffer.size() - zlib->stream.avail_out);
      pipe.write(buffer.begin(), buffer.size() - zlib->stream.avail_out);
      datacount += buffer.size() - zlib->stream.avail_out;

      // Reached the end - we now need to check the footer
      if(rc == Z_STREAM_END)
         {
         u32bit read_from_block = length - zlib->stream.avail_in;
         u32bit eat_len = eat_footer((Bytef*)input + read_from_block, zlib->stream.avail_in);
         read_from_block += eat_len;
         input += read_from_block;
         length -= read_from_block;
         zlib->stream.next_in = (Bytef*)input;
         zlib->stream.avail_in = length;
         }
      }
   }

/*************************************************
* Store the footer bytes                         *
*************************************************/
u32bit Gzip_Decompression::eat_footer(const byte input[], u32bit length)
   {
      if (footer.size() >= GZIP::FOOTER_LENGTH)
         throw Decoding_Error("Gzip_Decompression: Data integrity error in footer");

      u32bit eat_len = std::min(GZIP::FOOTER_LENGTH-footer.size(), length);
      footer.append(input, eat_len);

      if (footer.size() == GZIP::FOOTER_LENGTH)
         {
         check_footer();
         clear();
         }

         return eat_len;
   }

/*************************************************
* Check the gzip footer                          *
*************************************************/
void Gzip_Decompression::check_footer()
   {
   if (footer.size() != GZIP::FOOTER_LENGTH)
      throw Exception("Gzip_Decompression: Error finalizing decompression");

   pipe.end_msg();

   // 4 byte CRC32, and 4 byte length field
   SecureVector<byte> buf(4);
   SecureVector<byte> tmpbuf(4);
   pipe.read(tmpbuf.begin(), tmpbuf.size(), Pipe::LAST_MESSAGE);

  // CRC32 is the reverse order to what gzip expects.
  for (int i = 0; i < 4; i++)
     buf[3-i] = tmpbuf[i];

  tmpbuf.set(footer.begin(), 4);
  if (buf != tmpbuf)
      throw Decoding_Error("Gzip_Decompression: Data integrity error - CRC32 error");

   // Check the length matches - it is encoded LSB-first
   for (int i = 0; i < 4; i++)
      {
      if (footer.begin()[GZIP::FOOTER_LENGTH-1-i] != get_byte(i, datacount))
         throw Decoding_Error("Gzip_Decompression: Data integrity error - incorrect length");
      }

   }

/*************************************************
* Finish Decompressing with Gzip                 *
*************************************************/
void Gzip_Decompression::end_msg()
   {

   // All messages should end with a footer, and when a footer is successfully
   // read, clear() will reset no_writes
   if(no_writes) return;

   throw Exception("Gzip_Decompression: didn't find footer");

   }

/*************************************************
* Clean up Decompression Context                 *
*************************************************/
void Gzip_Decompression::clear()
   {
   no_writes = true;
   inflateReset(&(zlib->stream));

   footer.destroy();
   pos = 0;
   datacount = 0;
   }

}

// Local Variables:
// mode: C++
// fill-column: 76
// c-file-style: "gnu"
// indent-tabs-mode: nil
// End:
// vim: et:sw=2:sts=2:ts=2:cino=>2s,{s,\:s,+s,t0,g0,^-2,e-2,n-2,p2s,(0,=s: