HelenOS sources
This source file includes following definitions.
- gzip_check
- gzip_size
- gzip_expand
#include <stdint.h>
#include <stddef.h>
#include <errno.h>
#include <mem.h>
#include <byteorder.h>
#include <gzip.h>
#include <inflate.h>
#define GZIP_ID1 UINT8_C(0x1f)
#define GZIP_ID2 UINT8_C(0x8b)
#define GZIP_METHOD_DEFLATE UINT8_C(0x08)
#define GZIP_FLAGS_MASK UINT8_C(0x1f)
#define GZIP_FLAG_FHCRC UINT8_C(1 << 1)
#define GZIP_FLAG_FEXTRA UINT8_C(1 << 2)
#define GZIP_FLAG_FNAME UINT8_C(1 << 3)
#define GZIP_FLAG_FCOMMENT UINT8_C(1 << 4)
typedef struct {
uint8_t id1;
uint8_t id2;
uint8_t method;
uint8_t flags;
uint32_t mtime;
uint8_t extra_flags;
uint8_t os;
} __attribute__((packed)) gzip_header_t;
typedef struct {
uint32_t crc32;
uint32_t size;
} __attribute__((packed)) gzip_footer_t;
bool gzip_check(const void *src, size_t srclen)
{
if ((srclen < (sizeof(gzip_header_t) + sizeof(gzip_footer_t))))
return false;
gzip_header_t header;
memcpy(&header, src, sizeof(header));
if ((header.id1 != GZIP_ID1) ||
(header.id2 != GZIP_ID2) ||
(header.method != GZIP_METHOD_DEFLATE) ||
((header.flags & (~GZIP_FLAGS_MASK)) != 0))
return false;
return true;
}
size_t gzip_size(const void *src, size_t srclen)
{
if (!gzip_check(src, srclen))
return 0;
gzip_footer_t footer;
memcpy(&footer, src + srclen - sizeof(footer), sizeof(footer));
return uint32_t_le2host(footer.size);
}
int gzip_expand(const void *src, size_t srclen, void *dest, size_t destlen)
{
if (!gzip_check(src, srclen))
return EINVAL;
gzip_header_t header;
memcpy(&header, src, sizeof(header));
gzip_footer_t footer;
memcpy(&footer, src + srclen - sizeof(footer), sizeof(footer));
if (destlen != uint32_t_le2host(footer.size))
return EINVAL;
const void *stream = src + sizeof(header);
size_t stream_length = srclen - sizeof(header) - sizeof(footer);
if ((header.flags & GZIP_FLAG_FEXTRA) != 0) {
uint16_t extra_length;
if (stream_length < sizeof(extra_length))
return EINVAL;
memcpy(&extra_length, stream, sizeof(extra_length));
stream += sizeof(extra_length);
stream_length -= sizeof(extra_length);
if (stream_length < extra_length)
return EINVAL;
stream += extra_length;
stream_length -= extra_length;
}
if ((header.flags & GZIP_FLAG_FNAME) != 0) {
while (*((uint8_t *) stream) != 0) {
if (stream_length == 0)
return EINVAL;
stream++;
stream_length--;
}
if (stream_length == 0)
return EINVAL;
stream++;
stream_length--;
}
if ((header.flags & GZIP_FLAG_FCOMMENT) != 0) {
while (*((uint8_t *) stream) != 0) {
if (stream_length == 0)
return EINVAL;
stream++;
stream_length--;
}
if (stream_length == 0)
return EINVAL;
stream++;
stream_length--;
}
if ((header.flags & GZIP_FLAG_FHCRC) != 0) {
if (stream_length < 2)
return EINVAL;
stream += 2;
stream_length -= 2;
}
return inflate(stream, stream_length, dest, destlen);
}
HelenOS homepage, sources at GitHub