aboutsummaryrefslogtreecommitdiff
path: root/src/libflate/inflatezlib.c
blob: 3f31f10a54efd8f36c3b1a07de07d0d5ce2d27a0 (plain)
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
#include <u.h>
#include <libc.h>
#include <flate.h>
#include "zlib.h"

typedef struct ZWrite	ZWrite;

struct ZWrite
{
	ulong	adler;
	void	*wr;
	int	(*w)(void*, void*, int);
};

static int
zlwrite(void *vzw, void *buf, int n)
{
	ZWrite *zw;

	zw = vzw;
	zw->adler = adler32(zw->adler, buf, n);
	n = (*zw->w)(zw->wr, buf, n);
	if(n <= 0)
		return n;
	return n;
}

int
inflatezlib(void *wr, int (*w)(void*, void*, int), void *getr, int (*get)(void*))
{
	ZWrite zw;
	ulong v;
	int c, i;

	c = (*get)(getr);
	if(c < 0)
		return FlateInputFail;
	i = (*get)(getr);
	if(i < 0)
		return FlateInputFail;

	if(((c << 8) | i) % 31)
		return FlateCorrupted;
	if((c & ZlibMeth) != ZlibDeflate
	|| (c & ZlibCInfo) > ZlibWin32k)
		return FlateCorrupted;

	zw.wr = wr;
	zw.w = w;
	zw.adler = 1;
	i = inflate(&zw, zlwrite, getr, get);
	if(i != FlateOk)
		return i;

	v = 0;
	for(i = 0; i < 4; i++){
		c = (*get)(getr);
		if(c < 0)
			return FlateInputFail;
		v = (v << 8) | c;
	}
	if(zw.adler != v)
		return FlateCorrupted;

	return FlateOk;
}