SummerGift 8 жил өмнө
parent
commit
54b60425d8

+ 157 - 0
extmod/crypto-algorithms/sha256.c

@@ -0,0 +1,157 @@
+/*********************************************************************
+* Filename:   sha256.c
+* Author:     Brad Conte (brad AT bradconte.com)
+* Copyright:
+* Disclaimer: This code is presented "as is" without any guarantees.
+* Details:    Implementation of the SHA-256 hashing algorithm.
+              SHA-256 is one of the three algorithms in the SHA2
+              specification. The others, SHA-384 and SHA-512, are not
+              offered in this implementation.
+              Algorithm specification can be found here:
+               * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf
+              This implementation uses little endian byte order.
+*********************************************************************/
+
+/*************************** HEADER FILES ***************************/
+#include <stdlib.h>
+#include "sha256.h"
+
+/****************************** MACROS ******************************/
+#define ROTLEFT(a,b) (((a) << (b)) | ((a) >> (32-(b))))
+#define ROTRIGHT(a,b) (((a) >> (b)) | ((a) << (32-(b))))
+
+#define CH(x,y,z) (((x) & (y)) ^ (~(x) & (z)))
+#define MAJ(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
+#define EP0(x) (ROTRIGHT(x,2) ^ ROTRIGHT(x,13) ^ ROTRIGHT(x,22))
+#define EP1(x) (ROTRIGHT(x,6) ^ ROTRIGHT(x,11) ^ ROTRIGHT(x,25))
+#define SIG0(x) (ROTRIGHT(x,7) ^ ROTRIGHT(x,18) ^ ((x) >> 3))
+#define SIG1(x) (ROTRIGHT(x,17) ^ ROTRIGHT(x,19) ^ ((x) >> 10))
+
+/**************************** VARIABLES *****************************/
+static const WORD k[64] = {
+	0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
+	0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
+	0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
+	0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
+	0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
+	0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
+	0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
+	0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
+};
+
+/*********************** FUNCTION DEFINITIONS ***********************/
+static void sha256_transform(CRYAL_SHA256_CTX *ctx, const BYTE data[])
+{
+	WORD a, b, c, d, e, f, g, h, i, j, t1, t2, m[64];
+
+	for (i = 0, j = 0; i < 16; ++i, j += 4)
+		m[i] = (data[j] << 24) | (data[j + 1] << 16) | (data[j + 2] << 8) | (data[j + 3]);
+	for ( ; i < 64; ++i)
+		m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16];
+
+	a = ctx->state[0];
+	b = ctx->state[1];
+	c = ctx->state[2];
+	d = ctx->state[3];
+	e = ctx->state[4];
+	f = ctx->state[5];
+	g = ctx->state[6];
+	h = ctx->state[7];
+
+	for (i = 0; i < 64; ++i) {
+		t1 = h + EP1(e) + CH(e,f,g) + k[i] + m[i];
+		t2 = EP0(a) + MAJ(a,b,c);
+		h = g;
+		g = f;
+		f = e;
+		e = d + t1;
+		d = c;
+		c = b;
+		b = a;
+		a = t1 + t2;
+	}
+
+	ctx->state[0] += a;
+	ctx->state[1] += b;
+	ctx->state[2] += c;
+	ctx->state[3] += d;
+	ctx->state[4] += e;
+	ctx->state[5] += f;
+	ctx->state[6] += g;
+	ctx->state[7] += h;
+}
+
+void sha256_init(CRYAL_SHA256_CTX *ctx)
+{
+	ctx->datalen = 0;
+	ctx->bitlen = 0;
+	ctx->state[0] = 0x6a09e667;
+	ctx->state[1] = 0xbb67ae85;
+	ctx->state[2] = 0x3c6ef372;
+	ctx->state[3] = 0xa54ff53a;
+	ctx->state[4] = 0x510e527f;
+	ctx->state[5] = 0x9b05688c;
+	ctx->state[6] = 0x1f83d9ab;
+	ctx->state[7] = 0x5be0cd19;
+}
+
+void sha256_update(CRYAL_SHA256_CTX *ctx, const BYTE data[], size_t len)
+{
+	WORD i;
+
+	for (i = 0; i < len; ++i) {
+		ctx->data[ctx->datalen] = data[i];
+		ctx->datalen++;
+		if (ctx->datalen == 64) {
+			sha256_transform(ctx, ctx->data);
+			ctx->bitlen += 512;
+			ctx->datalen = 0;
+		}
+	}
+}
+
+void sha256_final(CRYAL_SHA256_CTX *ctx, BYTE hash[])
+{
+	WORD i;
+
+	i = ctx->datalen;
+
+	// Pad whatever data is left in the buffer.
+	if (ctx->datalen < 56) {
+		ctx->data[i++] = 0x80;
+		while (i < 56)
+			ctx->data[i++] = 0x00;
+	}
+	else {
+		ctx->data[i++] = 0x80;
+		while (i < 64)
+			ctx->data[i++] = 0x00;
+		sha256_transform(ctx, ctx->data);
+		memset(ctx->data, 0, 56);
+	}
+
+	// Append to the padding the total message's length in bits and transform.
+	ctx->bitlen += ctx->datalen * 8;
+	ctx->data[63] = ctx->bitlen;
+	ctx->data[62] = ctx->bitlen >> 8;
+	ctx->data[61] = ctx->bitlen >> 16;
+	ctx->data[60] = ctx->bitlen >> 24;
+	ctx->data[59] = ctx->bitlen >> 32;
+	ctx->data[58] = ctx->bitlen >> 40;
+	ctx->data[57] = ctx->bitlen >> 48;
+	ctx->data[56] = ctx->bitlen >> 56;
+	sha256_transform(ctx, ctx->data);
+
+	// Since this implementation uses little endian byte ordering and SHA uses big endian,
+	// reverse all the bytes when copying the final state to the output hash.
+	for (i = 0; i < 4; ++i) {
+		hash[i]      = (ctx->state[0] >> (24 - i * 8)) & 0x000000ff;
+		hash[i + 4]  = (ctx->state[1] >> (24 - i * 8)) & 0x000000ff;
+		hash[i + 8]  = (ctx->state[2] >> (24 - i * 8)) & 0x000000ff;
+		hash[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0x000000ff;
+		hash[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0x000000ff;
+		hash[i + 20] = (ctx->state[5] >> (24 - i * 8)) & 0x000000ff;
+		hash[i + 24] = (ctx->state[6] >> (24 - i * 8)) & 0x000000ff;
+		hash[i + 28] = (ctx->state[7] >> (24 - i * 8)) & 0x000000ff;
+	}
+}

+ 34 - 0
extmod/crypto-algorithms/sha256.h

@@ -0,0 +1,34 @@
+/*********************************************************************
+* Filename:   sha256.h
+* Author:     Brad Conte (brad AT bradconte.com)
+* Copyright:
+* Disclaimer: This code is presented "as is" without any guarantees.
+* Details:    Defines the API for the corresponding SHA1 implementation.
+*********************************************************************/
+
+#ifndef SHA256_H
+#define SHA256_H
+
+/*************************** HEADER FILES ***************************/
+#include <stddef.h>
+
+/****************************** MACROS ******************************/
+#define SHA256_BLOCK_SIZE 32            // SHA256 outputs a 32 byte digest
+
+/**************************** DATA TYPES ****************************/
+typedef unsigned char BYTE;             // 8-bit byte
+typedef unsigned int  WORD;             // 32-bit word, change to "long" for 16-bit machines
+
+typedef struct {
+	BYTE data[64];
+	WORD datalen;
+	unsigned long long bitlen;
+	WORD state[8];
+} CRYAL_SHA256_CTX;
+
+/*********************** FUNCTION DECLARATIONS **********************/
+void sha256_init(CRYAL_SHA256_CTX *ctx);
+void sha256_update(CRYAL_SHA256_CTX *ctx, const BYTE data[], size_t len);
+void sha256_final(CRYAL_SHA256_CTX *ctx, BYTE hash[]);
+
+#endif   // SHA256_H

+ 33 - 0
extmod/re1.5/charclass.c

@@ -0,0 +1,33 @@
+#include "re1.5.h"
+
+int _re1_5_classmatch(const char *pc, const char *sp)
+{
+    // pc points to "cnt" byte after opcode
+    int is_positive = (pc[-1] == Class);
+    int cnt = *pc++;
+    while (cnt--) {
+        if (*sp >= *pc && *sp <= pc[1]) return is_positive;
+        pc += 2;
+    }
+    return !is_positive;
+}
+
+int _re1_5_namedclassmatch(const char *pc, const char *sp)
+{
+    // pc points to name of class
+    int off = (*pc >> 5) & 1;
+    if ((*pc | 0x20) == 'd') {
+        if (!(*sp >= '0' && *sp <= '9')) {
+            off ^= 1;
+        }
+    } else if ((*pc | 0x20) == 's') {
+        if (!(*sp == ' ' || (*sp >= '\t' && *sp <= '\r'))) {
+            off ^= 1;
+        }
+    } else { // w
+        if (!((*sp >= 'A' && *sp <= 'Z') || (*sp >= 'a' && *sp <= 'z') || (*sp >= '0' && *sp <= '9') || *sp == '_')) {
+            off ^= 1;
+        }
+    }
+    return off;
+}

+ 216 - 0
extmod/re1.5/compilecode.c

@@ -0,0 +1,216 @@
+// Copyright 2014 Paul Sokolovsky.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+#include "re1.5.h"
+
+#define INSERT_CODE(at, num, pc) \
+    ((code ? memmove(code + at + num, code + at, pc - at) : (void)0), pc += num)
+#define REL(at, to) (to - at - 2)
+#define EMIT(at, byte) (code ? (code[at] = byte) : (void)(at))
+#define PC (prog->bytelen)
+
+static const char *_compilecode(const char *re, ByteProg *prog, int sizecode)
+{
+    char *code = sizecode ? NULL : prog->insts;
+    int start = PC;
+    int term = PC;
+    int alt_label = 0;
+
+    for (; *re && *re != ')'; re++) {
+        switch (*re) {
+        case '\\':
+            re++;
+            if (!*re) return NULL; // Trailing backslash
+            if ((*re | 0x20) == 'd' || (*re | 0x20) == 's' || (*re | 0x20) == 'w') {
+                term = PC;
+                EMIT(PC++, NamedClass);
+                EMIT(PC++, *re);
+                prog->len++;
+                break;
+            }
+        default:
+            term = PC;
+            EMIT(PC++, Char);
+            EMIT(PC++, *re);
+            prog->len++;
+            break;
+        case '.':
+            term = PC;
+            EMIT(PC++, Any);
+            prog->len++;
+            break;
+        case '[': {
+            int cnt;
+            term = PC;
+            re++;
+            if (*re == '^') {
+                EMIT(PC++, ClassNot);
+                re++;
+            } else {
+                EMIT(PC++, Class);
+            }
+            PC++; // Skip # of pair byte
+            prog->len++;
+            for (cnt = 0; *re != ']'; re++, cnt++) {
+                if (!*re) return NULL;
+                EMIT(PC++, *re);
+                if (re[1] == '-' && re[2] != ']') {
+                    re += 2;
+                }
+                EMIT(PC++, *re);
+            }
+            EMIT(term + 1, cnt);
+            break;
+        }
+        case '(': {
+            term = PC;
+            int sub = 0;
+            int capture = re[1] != '?' || re[2] != ':';
+
+            if (capture) {
+                sub = ++prog->sub;
+                EMIT(PC++, Save);
+                EMIT(PC++, 2 * sub);
+                prog->len++;
+            } else {
+                    re += 2;
+            }
+
+            re = _compilecode(re + 1, prog, sizecode);
+            if (re == NULL || *re != ')') return NULL; // error, or no matching paren
+
+            if (capture) {
+                EMIT(PC++, Save);
+                EMIT(PC++, 2 * sub + 1);
+                prog->len++;
+            }
+
+            break;
+        }
+        case '?':
+            if (PC == term) return NULL; // nothing to repeat
+            INSERT_CODE(term, 2, PC);
+            if (re[1] == '?') {
+                EMIT(term, RSplit);
+                re++;
+            } else {
+                EMIT(term, Split);
+            }
+            EMIT(term + 1, REL(term, PC));
+            prog->len++;
+            term = PC;
+            break;
+        case '*':
+            if (PC == term) return NULL; // nothing to repeat
+            INSERT_CODE(term, 2, PC);
+            EMIT(PC, Jmp);
+            EMIT(PC + 1, REL(PC, term));
+            PC += 2;
+            if (re[1] == '?') {
+                EMIT(term, RSplit);
+                re++;
+            } else {
+                EMIT(term, Split);
+            }
+            EMIT(term + 1, REL(term, PC));
+            prog->len += 2;
+            term = PC;
+            break;
+        case '+':
+            if (PC == term) return NULL; // nothing to repeat
+            if (re[1] == '?') {
+                EMIT(PC, Split);
+                re++;
+            } else {
+                EMIT(PC, RSplit);
+            }
+            EMIT(PC + 1, REL(PC, term));
+            PC += 2;
+            prog->len++;
+            term = PC;
+            break;
+        case '|':
+            if (alt_label) {
+                EMIT(alt_label, REL(alt_label, PC) + 1);
+            }
+            INSERT_CODE(start, 2, PC);
+            EMIT(PC++, Jmp);
+            alt_label = PC++;
+            EMIT(start, Split);
+            EMIT(start + 1, REL(start, PC));
+            prog->len += 2;
+            term = PC;
+            break;
+        case '^':
+            EMIT(PC++, Bol);
+            prog->len++;
+            term = PC;
+            break;
+        case '$':
+            EMIT(PC++, Eol);
+            prog->len++;
+            term = PC;
+            break;
+        }
+    }
+
+    if (alt_label) {
+        EMIT(alt_label, REL(alt_label, PC) + 1);
+    }
+    return re;
+}
+
+int re1_5_sizecode(const char *re)
+{
+    ByteProg dummyprog = {
+         // Save 0, Save 1, Match; more bytes for "search" (vs "match") prefix code
+        .bytelen = 5 + NON_ANCHORED_PREFIX
+    };
+
+    if (_compilecode(re, &dummyprog, /*sizecode*/1) == NULL) return -1;
+
+    return dummyprog.bytelen;
+}
+
+int re1_5_compilecode(ByteProg *prog, const char *re)
+{
+    prog->len = 0;
+    prog->bytelen = 0;
+    prog->sub = 0;
+
+    // Add code to implement non-anchored operation ("search"),
+    // for anchored operation ("match"), this code will be just skipped.
+    // TODO: Implement search in much more efficient manner
+    prog->insts[prog->bytelen++] = RSplit;
+    prog->insts[prog->bytelen++] = 3;
+    prog->insts[prog->bytelen++] = Any;
+    prog->insts[prog->bytelen++] = Jmp;
+    prog->insts[prog->bytelen++] = -5;
+    prog->len += 3;
+
+    prog->insts[prog->bytelen++] = Save;
+    prog->insts[prog->bytelen++] = 0;
+    prog->len++;
+
+    re = _compilecode(re, prog, /*sizecode*/0);
+    if (re == NULL || *re) return 1;
+
+    prog->insts[prog->bytelen++] = Save;
+    prog->insts[prog->bytelen++] = 1;
+    prog->len++;
+
+    prog->insts[prog->bytelen++] = Match;
+    prog->len++;
+
+    return 0;
+}
+
+#if 0
+int main(int argc, char *argv[])
+{
+    int pc = 0;
+    ByteProg *code = re1_5_compilecode(argv[1]);
+    re1_5_dumpcode(code);
+}
+#endif

+ 65 - 0
extmod/re1.5/dumpcode.c

@@ -0,0 +1,65 @@
+// Copyright 2014 Paul Sokolovsky.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+#include "re1.5.h"
+
+void re1_5_dumpcode(ByteProg *prog)
+{
+    int pc = 0;
+    char *code = prog->insts;
+    while (pc < prog->bytelen) {
+                printf("%2d: ", pc);
+                switch(code[pc++]) {
+                default:
+                        assert(0);
+//                        re1_5_fatal("printprog");
+                case Split:
+                        printf("split %d (%d)\n", pc + (signed char)code[pc] + 1, (signed char)code[pc]);
+                        pc++;
+                        break;
+                case RSplit:
+                        printf("rsplit %d (%d)\n", pc + (signed char)code[pc] + 1, (signed char)code[pc]);
+                        pc++;
+                        break;
+                case Jmp:
+                        printf("jmp %d (%d)\n", pc + (signed char)code[pc] + 1, (signed char)code[pc]);
+                        pc++;
+                        break;
+                case Char:
+                        printf("char %c\n", code[pc++]);
+                        break;
+                case Any:
+                        printf("any\n");
+                        break;
+                case Class:
+                case ClassNot: {
+                        int num = code[pc];
+                        printf("class%s %d", (code[pc - 1] == ClassNot ? "not" : ""), num);
+                        pc++;
+                        while (num--) {
+                            printf(" 0x%02x-0x%02x", code[pc], code[pc + 1]);
+                            pc += 2;
+                        }
+                        printf("\n");
+                        break;
+                }
+                case NamedClass:
+                        printf("namedclass %c\n", code[pc++]);
+                        break;
+                case Match:
+                        printf("match\n");
+                        break;
+                case Save:
+                        printf("save %d\n", (unsigned char)code[pc++]);
+                        break;
+                case Bol:
+                        printf("assert bol\n");
+                        break;
+                case Eol:
+                        printf("assert eol\n");
+                        break;
+                }
+    }
+    printf("Bytes: %d, insts: %d\n", prog->bytelen, prog->len);
+}

+ 154 - 0
extmod/re1.5/re1.5.h

@@ -0,0 +1,154 @@
+// Copyright 2007-2009 Russ Cox.  All Rights Reserved.
+// Copyright 2014 Paul Sokolovsky.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+#ifndef _RE1_5_REGEXP__H
+#define _RE1_5_REGEXP__H
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <assert.h>
+
+#define nil ((void*)0)
+#define nelem(x) (sizeof(x)/sizeof((x)[0]))
+
+typedef struct Regexp Regexp;
+typedef struct Prog Prog;
+typedef struct ByteProg ByteProg;
+typedef struct Inst Inst;
+typedef struct Subject Subject;
+
+struct Regexp
+{
+	int type;
+	int n;
+	int ch;
+	Regexp *left;
+	Regexp *right;
+};
+
+enum	/* Regexp.type */
+{
+	Alt = 1,
+	Cat,
+	Lit,
+	Dot,
+	Paren,
+	Quest,
+	Star,
+	Plus,
+};
+
+Regexp *parse(char*);
+Regexp *reg(int type, Regexp *left, Regexp *right);
+void printre(Regexp*);
+#ifndef re1_5_fatal
+void re1_5_fatal(char*);
+#endif
+#ifndef re1_5_stack_chk
+#define re1_5_stack_chk()
+#endif
+void *mal(int);
+
+struct Prog
+{
+	Inst *start;
+	int len;
+};
+
+struct ByteProg
+{
+	int bytelen;
+	int len;
+	int sub;
+	char insts[0];
+};
+
+struct Inst
+{
+	int opcode;
+	int c;
+	int n;
+	Inst *x;
+	Inst *y;
+	int gen;	// global state, oooh!
+};
+
+enum	/* Inst.opcode */
+{
+	// Instructions which consume input bytes (and thus fail if none left)
+	CONSUMERS = 1,
+	Char = CONSUMERS,
+	Any,
+	Class,
+	ClassNot,
+	NamedClass,
+
+	ASSERTS = 0x50,
+	Bol = ASSERTS,
+	Eol,
+
+	// Instructions which take relative offset as arg
+	JUMPS = 0x60,
+	Jmp = JUMPS,
+	Split,
+	RSplit,
+
+	// Other (special) instructions
+	Save = 0x7e,
+	Match = 0x7f,
+};
+
+#define inst_is_consumer(inst) ((inst) < ASSERTS)
+#define inst_is_jump(inst) ((inst) & 0x70 == JUMPS)
+
+Prog *compile(Regexp*);
+void printprog(Prog*);
+
+extern int gen;
+
+enum {
+	MAXSUB = 20
+};
+
+typedef struct Sub Sub;
+
+struct Sub
+{
+	int ref;
+	int nsub;
+	const char *sub[MAXSUB];
+};
+
+Sub *newsub(int n);
+Sub *incref(Sub*);
+Sub *copy(Sub*);
+Sub *update(Sub*, int, const char*);
+void decref(Sub*);
+
+struct Subject {
+	const char *begin;
+	const char *end;
+};
+
+
+#define NON_ANCHORED_PREFIX 5
+#define HANDLE_ANCHORED(bytecode, is_anchored) ((is_anchored) ? (bytecode) + NON_ANCHORED_PREFIX : (bytecode))
+
+int re1_5_backtrack(ByteProg*, Subject*, const char**, int, int);
+int re1_5_pikevm(ByteProg*, Subject*, const char**, int, int);
+int re1_5_recursiveloopprog(ByteProg*, Subject*, const char**, int, int);
+int re1_5_recursiveprog(ByteProg*, Subject*, const char**, int, int);
+int re1_5_thompsonvm(ByteProg*, Subject*, const char**, int, int);
+
+int re1_5_sizecode(const char *re);
+int re1_5_compilecode(ByteProg *prog, const char *re);
+void re1_5_dumpcode(ByteProg *prog);
+void cleanmarks(ByteProg *prog);
+int _re1_5_classmatch(const char *pc, const char *sp);
+int _re1_5_namedclassmatch(const char *pc, const char *sp);
+
+#endif /*_RE1_5_REGEXP__H*/

+ 86 - 0
extmod/re1.5/recursiveloop.c

@@ -0,0 +1,86 @@
+// Copyright 2007-2009 Russ Cox.  All Rights Reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+#include "re1.5.h"
+
+static int
+recursiveloop(char *pc, const char *sp, Subject *input, const char **subp, int nsubp)
+{
+	const char *old;
+	int off;
+
+	re1_5_stack_chk();
+
+	for(;;) {
+		if(inst_is_consumer(*pc)) {
+			// If we need to match a character, but there's none left, it's fail
+			if(sp >= input->end)
+				return 0;
+		}
+		switch(*pc++) {
+		case Char:
+			if(*sp != *pc++)
+				return 0;
+		case Any:
+			sp++;
+			continue;
+		case Class:
+		case ClassNot:
+			if (!_re1_5_classmatch(pc, sp))
+				return 0;
+			pc += *(unsigned char*)pc * 2 + 1;
+			sp++;
+			continue;
+                case NamedClass:
+			if (!_re1_5_namedclassmatch(pc, sp))
+				return 0;
+			pc++;
+			sp++;
+			continue;
+		case Match:
+			return 1;
+		case Jmp:
+			off = (signed char)*pc++;
+			pc = pc + off;
+			continue;
+		case Split:
+			off = (signed char)*pc++;
+			if(recursiveloop(pc, sp, input, subp, nsubp))
+				return 1;
+			pc = pc + off;
+			continue;
+		case RSplit:
+			off = (signed char)*pc++;
+			if(recursiveloop(pc + off, sp, input, subp, nsubp))
+				return 1;
+			continue;
+		case Save:
+			off = (unsigned char)*pc++;
+			if(off >= nsubp) {
+				continue;
+			}
+			old = subp[off];
+			subp[off] = sp;
+			if(recursiveloop(pc, sp, input, subp, nsubp))
+				return 1;
+			subp[off] = old;
+			return 0;
+		case Bol:
+			if(sp != input->begin)
+				return 0;
+			continue;
+		case Eol:
+			if(sp != input->end)
+				return 0;
+			continue;
+		}
+		re1_5_fatal("recursiveloop");
+	}
+}
+
+int
+re1_5_recursiveloopprog(ByteProg *prog, Subject *input, const char **subp, int nsubp, int is_anchored)
+{
+	return recursiveloop(HANDLE_ANCHORED(prog->insts, is_anchored), input->begin, input, subp, nsubp);
+}

+ 78 - 0
extmod/uzlib/adler32.c

@@ -0,0 +1,78 @@
+/*
+ * Adler-32 checksum
+ *
+ * Copyright (c) 2003 by Joergen Ibsen / Jibz
+ * All Rights Reserved
+ *
+ * http://www.ibsensoftware.com/
+ *
+ * This software is provided 'as-is', without any express
+ * or implied warranty.  In no event will the authors be
+ * held liable for any damages arising from the use of
+ * this software.
+ *
+ * Permission is granted to anyone to use this software
+ * for any purpose, including commercial applications,
+ * and to alter it and redistribute it freely, subject to
+ * the following restrictions:
+ *
+ * 1. The origin of this software must not be
+ *    misrepresented; you must not claim that you
+ *    wrote the original software. If you use this
+ *    software in a product, an acknowledgment in
+ *    the product documentation would be appreciated
+ *    but is not required.
+ *
+ * 2. Altered source versions must be plainly marked
+ *    as such, and must not be misrepresented as
+ *    being the original software.
+ *
+ * 3. This notice may not be removed or altered from
+ *    any source distribution.
+ */
+
+/*
+ * Adler-32 algorithm taken from the zlib source, which is
+ * Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler
+ */
+
+#include "tinf.h"
+
+#define A32_BASE 65521
+#define A32_NMAX 5552
+
+uint32_t uzlib_adler32(const void *data, unsigned int length, uint32_t prev_sum /* 1 */)
+{
+   const unsigned char *buf = (const unsigned char *)data;
+
+   unsigned int s1 = prev_sum & 0xffff;
+   unsigned int s2 = prev_sum >> 16;
+
+   while (length > 0)
+   {
+      int k = length < A32_NMAX ? length : A32_NMAX;
+      int i;
+
+      for (i = k / 16; i; --i, buf += 16)
+      {
+         s1 += buf[0];  s2 += s1; s1 += buf[1];  s2 += s1;
+         s1 += buf[2];  s2 += s1; s1 += buf[3];  s2 += s1;
+         s1 += buf[4];  s2 += s1; s1 += buf[5];  s2 += s1;
+         s1 += buf[6];  s2 += s1; s1 += buf[7];  s2 += s1;
+
+         s1 += buf[8];  s2 += s1; s1 += buf[9];  s2 += s1;
+         s1 += buf[10]; s2 += s1; s1 += buf[11]; s2 += s1;
+         s1 += buf[12]; s2 += s1; s1 += buf[13]; s2 += s1;
+         s1 += buf[14]; s2 += s1; s1 += buf[15]; s2 += s1;
+      }
+
+      for (i = k % 16; i; --i) { s1 += *buf++; s2 += s1; }
+
+      s1 %= A32_BASE;
+      s2 %= A32_BASE;
+
+      length -= k;
+   }
+
+   return (s2 << 16) | s1;
+}

+ 63 - 0
extmod/uzlib/crc32.c

@@ -0,0 +1,63 @@
+/*
+ * CRC32 checksum
+ *
+ * Copyright (c) 1998-2003 by Joergen Ibsen / Jibz
+ * All Rights Reserved
+ *
+ * http://www.ibsensoftware.com/
+ *
+ * This software is provided 'as-is', without any express
+ * or implied warranty.  In no event will the authors be
+ * held liable for any damages arising from the use of
+ * this software.
+ *
+ * Permission is granted to anyone to use this software
+ * for any purpose, including commercial applications,
+ * and to alter it and redistribute it freely, subject to
+ * the following restrictions:
+ *
+ * 1. The origin of this software must not be
+ *    misrepresented; you must not claim that you
+ *    wrote the original software. If you use this
+ *    software in a product, an acknowledgment in
+ *    the product documentation would be appreciated
+ *    but is not required.
+ *
+ * 2. Altered source versions must be plainly marked
+ *    as such, and must not be misrepresented as
+ *    being the original software.
+ *
+ * 3. This notice may not be removed or altered from
+ *    any source distribution.
+ */
+
+/*
+ * CRC32 algorithm taken from the zlib source, which is
+ * Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler
+ */
+
+#include "tinf.h"
+
+static const unsigned int tinf_crc32tab[16] = {
+   0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190,
+   0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344,
+   0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278,
+   0xbdbdf21c
+};
+
+/* crc is previous value for incremental computation, 0xffffffff initially */
+uint32_t uzlib_crc32(const void *data, unsigned int length, uint32_t crc)
+{
+   const unsigned char *buf = (const unsigned char *)data;
+   unsigned int i;
+
+   for (i = 0; i < length; ++i)
+   {
+      crc ^= buf[i];
+      crc = tinf_crc32tab[crc & 0x0f] ^ (crc >> 4);
+      crc = tinf_crc32tab[crc & 0x0f] ^ (crc >> 4);
+   }
+
+   // return value suitable for passing in next time, for final value invert it
+   return crc/* ^ 0xffffffff*/;
+}

+ 117 - 0
extmod/uzlib/tinf.h

@@ -0,0 +1,117 @@
+/*
+ * uzlib  -  tiny deflate/inflate library (deflate, gzip, zlib)
+ *
+ * Copyright (c) 2003 by Joergen Ibsen / Jibz
+ * All Rights Reserved
+ * http://www.ibsensoftware.com/
+ *
+ * Copyright (c) 2014-2016 by Paul Sokolovsky
+ */
+
+#ifndef TINF_H_INCLUDED
+#define TINF_H_INCLUDED
+
+#include <stdint.h>
+
+/* calling convention */
+#ifndef TINFCC
+ #ifdef __WATCOMC__
+  #define TINFCC __cdecl
+ #else
+  #define TINFCC
+ #endif
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* ok status, more data produced */
+#define TINF_OK             0
+/* end of compressed stream reached */
+#define TINF_DONE           1
+#define TINF_DATA_ERROR    (-3)
+#define TINF_CHKSUM_ERROR  (-4)
+#define TINF_DICT_ERROR    (-5)
+
+/* checksum types */
+#define TINF_CHKSUM_NONE  0
+#define TINF_CHKSUM_ADLER 1
+#define TINF_CHKSUM_CRC   2
+
+/* data structures */
+
+typedef struct {
+   unsigned short table[16];  /* table of code length counts */
+   unsigned short trans[288]; /* code -> symbol translation table */
+} TINF_TREE;
+
+struct TINF_DATA;
+typedef struct TINF_DATA {
+   const unsigned char *source;
+   /* If source above is NULL, this function will be used to read
+      next byte from source stream */
+   unsigned char (*readSource)(struct TINF_DATA *data);
+
+   unsigned int tag;
+   unsigned int bitcount;
+
+    /* Buffer start */
+    unsigned char *destStart;
+    /* Buffer total size */
+    unsigned int destSize;
+    /* Current pointer in buffer */
+    unsigned char *dest;
+    /* Remaining bytes in buffer */
+    unsigned int destRemaining;
+
+    /* Accumulating checksum */
+    unsigned int checksum;
+    char checksum_type;
+
+    int btype;
+    int bfinal;
+    unsigned int curlen;
+    int lzOff;
+    unsigned char *dict_ring;
+    unsigned int dict_size;
+    unsigned int dict_idx;
+
+   TINF_TREE ltree; /* dynamic length/symbol tree */
+   TINF_TREE dtree; /* dynamic distance tree */
+} TINF_DATA;
+
+#define TINF_PUT(d, c) \
+    { \
+        *d->dest++ = c; \
+        if (d->dict_ring) { d->dict_ring[d->dict_idx++] = c; if (d->dict_idx == d->dict_size) d->dict_idx = 0; } \
+    }
+
+unsigned char TINFCC uzlib_get_byte(TINF_DATA *d);
+
+/* Decompression API */
+
+void TINFCC uzlib_init(void);
+void TINFCC uzlib_uncompress_init(TINF_DATA *d, void *dict, unsigned int dictLen);
+int  TINFCC uzlib_uncompress(TINF_DATA *d);
+int  TINFCC uzlib_uncompress_chksum(TINF_DATA *d);
+
+int TINFCC uzlib_zlib_parse_header(TINF_DATA *d);
+int TINFCC uzlib_gzip_parse_header(TINF_DATA *d);
+
+/* Compression API */
+
+void TINFCC uzlib_compress(void *data, const uint8_t *src, unsigned slen);
+
+/* Checksum API */
+
+/* prev_sum is previous value for incremental computation, 1 initially */
+uint32_t TINFCC uzlib_adler32(const void *data, unsigned int length, uint32_t prev_sum);
+/* crc is previous value for incremental computation, 0xffffffff initially */
+uint32_t TINFCC uzlib_crc32(const void *data, unsigned int length, uint32_t crc);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* TINF_H_INCLUDED */

+ 110 - 0
extmod/uzlib/tinfgzip.c

@@ -0,0 +1,110 @@
+/*
+ * tinfgzip  -  tiny gzip decompressor
+ *
+ * Copyright (c) 2003 by Joergen Ibsen / Jibz
+ * All Rights Reserved
+ *
+ * http://www.ibsensoftware.com/
+ *
+ * Copyright (c) 2014-2016 by Paul Sokolovsky
+ *
+ * This software is provided 'as-is', without any express
+ * or implied warranty.  In no event will the authors be
+ * held liable for any damages arising from the use of
+ * this software.
+ *
+ * Permission is granted to anyone to use this software
+ * for any purpose, including commercial applications,
+ * and to alter it and redistribute it freely, subject to
+ * the following restrictions:
+ *
+ * 1. The origin of this software must not be
+ *    misrepresented; you must not claim that you
+ *    wrote the original software. If you use this
+ *    software in a product, an acknowledgment in
+ *    the product documentation would be appreciated
+ *    but is not required.
+ *
+ * 2. Altered source versions must be plainly marked
+ *    as such, and must not be misrepresented as
+ *    being the original software.
+ *
+ * 3. This notice may not be removed or altered from
+ *    any source distribution.
+ */
+
+#include "tinf.h"
+
+#define FTEXT    1
+#define FHCRC    2
+#define FEXTRA   4
+#define FNAME    8
+#define FCOMMENT 16
+
+void tinf_skip_bytes(TINF_DATA *d, int num);
+uint16_t tinf_get_uint16(TINF_DATA *d);
+
+void tinf_skip_bytes(TINF_DATA *d, int num)
+{
+    while (num--) uzlib_get_byte(d);
+}
+
+uint16_t tinf_get_uint16(TINF_DATA *d)
+{
+    unsigned int v = uzlib_get_byte(d);
+    v = (uzlib_get_byte(d) << 8) | v;
+    return v;
+}
+
+int uzlib_gzip_parse_header(TINF_DATA *d)
+{
+    unsigned char flg;
+
+    /* -- check format -- */
+
+    /* check id bytes */
+    if (uzlib_get_byte(d) != 0x1f || uzlib_get_byte(d) != 0x8b) return TINF_DATA_ERROR;
+
+    /* check method is deflate */
+    if (uzlib_get_byte(d) != 8) return TINF_DATA_ERROR;
+
+    /* get flag byte */
+    flg = uzlib_get_byte(d);
+
+    /* check that reserved bits are zero */
+    if (flg & 0xe0) return TINF_DATA_ERROR;
+
+    /* -- find start of compressed data -- */
+
+    /* skip rest of base header of 10 bytes */
+    tinf_skip_bytes(d, 6);
+
+    /* skip extra data if present */
+    if (flg & FEXTRA)
+    {
+       unsigned int xlen = tinf_get_uint16(d);
+       tinf_skip_bytes(d, xlen);
+    }
+
+    /* skip file name if present */
+    if (flg & FNAME) { while (uzlib_get_byte(d)); }
+
+    /* skip file comment if present */
+    if (flg & FCOMMENT) { while (uzlib_get_byte(d)); }
+
+    /* check header crc if present */
+    if (flg & FHCRC)
+    {
+       /*unsigned int hcrc =*/ tinf_get_uint16(d);
+
+        // TODO: Check!
+//       if (hcrc != (tinf_crc32(src, start - src) & 0x0000ffff))
+//          return TINF_DATA_ERROR;
+    }
+
+    /* initialize for crc32 checksum */
+    d->checksum_type = TINF_CHKSUM_CRC;
+    d->checksum = ~0;
+
+    return TINF_OK;
+}

+ 551 - 0
extmod/uzlib/tinflate.c

@@ -0,0 +1,551 @@
+/*
+ * tinflate  -  tiny inflate
+ *
+ * Copyright (c) 2003 by Joergen Ibsen / Jibz
+ * All Rights Reserved
+ * http://www.ibsensoftware.com/
+ *
+ * Copyright (c) 2014-2016 by Paul Sokolovsky
+ *
+ * This software is provided 'as-is', without any express
+ * or implied warranty.  In no event will the authors be
+ * held liable for any damages arising from the use of
+ * this software.
+ *
+ * Permission is granted to anyone to use this software
+ * for any purpose, including commercial applications,
+ * and to alter it and redistribute it freely, subject to
+ * the following restrictions:
+ *
+ * 1. The origin of this software must not be
+ *    misrepresented; you must not claim that you
+ *    wrote the original software. If you use this
+ *    software in a product, an acknowledgment in
+ *    the product documentation would be appreciated
+ *    but is not required.
+ *
+ * 2. Altered source versions must be plainly marked
+ *    as such, and must not be misrepresented as
+ *    being the original software.
+ *
+ * 3. This notice may not be removed or altered from
+ *    any source distribution.
+ */
+
+#include <assert.h>
+#include "tinf.h"
+
+uint32_t tinf_get_le_uint32(TINF_DATA *d);
+uint32_t tinf_get_be_uint32(TINF_DATA *d);
+
+/* --------------------------------------------------- *
+ * -- uninitialized global data (static structures) -- *
+ * --------------------------------------------------- */
+
+#ifdef RUNTIME_BITS_TABLES
+
+/* extra bits and base tables for length codes */
+unsigned char length_bits[30];
+unsigned short length_base[30];
+
+/* extra bits and base tables for distance codes */
+unsigned char dist_bits[30];
+unsigned short dist_base[30];
+
+#else
+
+const unsigned char length_bits[30] = {
+   0, 0, 0, 0, 0, 0, 0, 0,
+   1, 1, 1, 1, 2, 2, 2, 2,
+   3, 3, 3, 3, 4, 4, 4, 4,
+   5, 5, 5, 5
+};
+const unsigned short length_base[30] = {
+   3, 4, 5, 6, 7, 8, 9, 10,
+   11, 13, 15, 17, 19, 23, 27, 31,
+   35, 43, 51, 59, 67, 83, 99, 115,
+   131, 163, 195, 227, 258
+};
+
+const unsigned char dist_bits[30] = {
+   0, 0, 0, 0, 1, 1, 2, 2,
+   3, 3, 4, 4, 5, 5, 6, 6,
+   7, 7, 8, 8, 9, 9, 10, 10,
+   11, 11, 12, 12, 13, 13
+};
+const unsigned short dist_base[30] = {
+   1, 2, 3, 4, 5, 7, 9, 13,
+   17, 25, 33, 49, 65, 97, 129, 193,
+   257, 385, 513, 769, 1025, 1537, 2049, 3073,
+   4097, 6145, 8193, 12289, 16385, 24577
+};
+
+#endif
+
+/* special ordering of code length codes */
+const unsigned char clcidx[] = {
+   16, 17, 18, 0, 8, 7, 9, 6,
+   10, 5, 11, 4, 12, 3, 13, 2,
+   14, 1, 15
+};
+
+/* ----------------------- *
+ * -- utility functions -- *
+ * ----------------------- */
+
+#ifdef RUNTIME_BITS_TABLES
+/* build extra bits and base tables */
+static void tinf_build_bits_base(unsigned char *bits, unsigned short *base, int delta, int first)
+{
+   int i, sum;
+
+   /* build bits table */
+   for (i = 0; i < delta; ++i) bits[i] = 0;
+   for (i = 0; i < 30 - delta; ++i) bits[i + delta] = i / delta;
+
+   /* build base table */
+   for (sum = first, i = 0; i < 30; ++i)
+   {
+      base[i] = sum;
+      sum += 1 << bits[i];
+   }
+}
+#endif
+
+/* build the fixed huffman trees */
+static void tinf_build_fixed_trees(TINF_TREE *lt, TINF_TREE *dt)
+{
+   int i;
+
+   /* build fixed length tree */
+   for (i = 0; i < 7; ++i) lt->table[i] = 0;
+
+   lt->table[7] = 24;
+   lt->table[8] = 152;
+   lt->table[9] = 112;
+
+   for (i = 0; i < 24; ++i) lt->trans[i] = 256 + i;
+   for (i = 0; i < 144; ++i) lt->trans[24 + i] = i;
+   for (i = 0; i < 8; ++i) lt->trans[24 + 144 + i] = 280 + i;
+   for (i = 0; i < 112; ++i) lt->trans[24 + 144 + 8 + i] = 144 + i;
+
+   /* build fixed distance tree */
+   for (i = 0; i < 5; ++i) dt->table[i] = 0;
+
+   dt->table[5] = 32;
+
+   for (i = 0; i < 32; ++i) dt->trans[i] = i;
+}
+
+/* given an array of code lengths, build a tree */
+static void tinf_build_tree(TINF_TREE *t, const unsigned char *lengths, unsigned int num)
+{
+   unsigned short offs[16];
+   unsigned int i, sum;
+
+   /* clear code length count table */
+   for (i = 0; i < 16; ++i) t->table[i] = 0;
+
+   /* scan symbol lengths, and sum code length counts */
+   for (i = 0; i < num; ++i) t->table[lengths[i]]++;
+
+   t->table[0] = 0;
+
+   /* compute offset table for distribution sort */
+   for (sum = 0, i = 0; i < 16; ++i)
+   {
+      offs[i] = sum;
+      sum += t->table[i];
+   }
+
+   /* create code->symbol translation table (symbols sorted by code) */
+   for (i = 0; i < num; ++i)
+   {
+      if (lengths[i]) t->trans[offs[lengths[i]]++] = i;
+   }
+}
+
+/* ---------------------- *
+ * -- decode functions -- *
+ * ---------------------- */
+
+unsigned char uzlib_get_byte(TINF_DATA *d)
+{
+    if (d->source) {
+        return *d->source++;
+    }
+    return d->readSource(d);
+}
+
+uint32_t tinf_get_le_uint32(TINF_DATA *d)
+{
+    uint32_t val = 0;
+    int i;
+    for (i = 4; i--;) {
+        val = val >> 8 | uzlib_get_byte(d) << 24;
+    }
+    return val;
+}
+
+uint32_t tinf_get_be_uint32(TINF_DATA *d)
+{
+    uint32_t val = 0;
+    int i;
+    for (i = 4; i--;) {
+        val = val << 8 | uzlib_get_byte(d);
+    }
+    return val;
+}
+
+/* get one bit from source stream */
+static int tinf_getbit(TINF_DATA *d)
+{
+   unsigned int bit;
+
+   /* check if tag is empty */
+   if (!d->bitcount--)
+   {
+      /* load next tag */
+      d->tag = uzlib_get_byte(d);
+      d->bitcount = 7;
+   }
+
+   /* shift bit out of tag */
+   bit = d->tag & 0x01;
+   d->tag >>= 1;
+
+   return bit;
+}
+
+/* read a num bit value from a stream and add base */
+static unsigned int tinf_read_bits(TINF_DATA *d, int num, int base)
+{
+   unsigned int val = 0;
+
+   /* read num bits */
+   if (num)
+   {
+      unsigned int limit = 1 << (num);
+      unsigned int mask;
+
+      for (mask = 1; mask < limit; mask *= 2)
+         if (tinf_getbit(d)) val += mask;
+   }
+
+   return val + base;
+}
+
+/* given a data stream and a tree, decode a symbol */
+static int tinf_decode_symbol(TINF_DATA *d, TINF_TREE *t)
+{
+   int sum = 0, cur = 0, len = 0;
+
+   /* get more bits while code value is above sum */
+   do {
+
+      cur = 2*cur + tinf_getbit(d);
+
+      ++len;
+
+      sum += t->table[len];
+      cur -= t->table[len];
+
+   } while (cur >= 0);
+
+   return t->trans[sum + cur];
+}
+
+/* given a data stream, decode dynamic trees from it */
+static void tinf_decode_trees(TINF_DATA *d, TINF_TREE *lt, TINF_TREE *dt)
+{
+   unsigned char lengths[288+32];
+   unsigned int hlit, hdist, hclen;
+   unsigned int i, num, length;
+
+   /* get 5 bits HLIT (257-286) */
+   hlit = tinf_read_bits(d, 5, 257);
+
+   /* get 5 bits HDIST (1-32) */
+   hdist = tinf_read_bits(d, 5, 1);
+
+   /* get 4 bits HCLEN (4-19) */
+   hclen = tinf_read_bits(d, 4, 4);
+
+   for (i = 0; i < 19; ++i) lengths[i] = 0;
+
+   /* read code lengths for code length alphabet */
+   for (i = 0; i < hclen; ++i)
+   {
+      /* get 3 bits code length (0-7) */
+      unsigned int clen = tinf_read_bits(d, 3, 0);
+
+      lengths[clcidx[i]] = clen;
+   }
+
+   /* build code length tree, temporarily use length tree */
+   tinf_build_tree(lt, lengths, 19);
+
+   /* decode code lengths for the dynamic trees */
+   for (num = 0; num < hlit + hdist; )
+   {
+      int sym = tinf_decode_symbol(d, lt);
+
+      switch (sym)
+      {
+      case 16:
+         /* copy previous code length 3-6 times (read 2 bits) */
+         {
+            unsigned char prev = lengths[num - 1];
+            for (length = tinf_read_bits(d, 2, 3); length; --length)
+            {
+               lengths[num++] = prev;
+            }
+         }
+         break;
+      case 17:
+         /* repeat code length 0 for 3-10 times (read 3 bits) */
+         for (length = tinf_read_bits(d, 3, 3); length; --length)
+         {
+            lengths[num++] = 0;
+         }
+         break;
+      case 18:
+         /* repeat code length 0 for 11-138 times (read 7 bits) */
+         for (length = tinf_read_bits(d, 7, 11); length; --length)
+         {
+            lengths[num++] = 0;
+         }
+         break;
+      default:
+         /* values 0-15 represent the actual code lengths */
+         lengths[num++] = sym;
+         break;
+      }
+   }
+
+   /* build dynamic trees */
+   tinf_build_tree(lt, lengths, hlit);
+   tinf_build_tree(dt, lengths + hlit, hdist);
+}
+
+/* ----------------------------- *
+ * -- block inflate functions -- *
+ * ----------------------------- */
+
+/* given a stream and two trees, inflate a block of data */
+static int tinf_inflate_block_data(TINF_DATA *d, TINF_TREE *lt, TINF_TREE *dt)
+{
+    if (d->curlen == 0) {
+        unsigned int offs;
+        int dist;
+        int sym = tinf_decode_symbol(d, lt);
+        //printf("huff sym: %02x\n", sym);
+
+        /* literal byte */
+        if (sym < 256) {
+            TINF_PUT(d, sym);
+            return TINF_OK;
+        }
+
+        /* end of block */
+        if (sym == 256) {
+            return TINF_DONE;
+        }
+
+        /* substring from sliding dictionary */
+        sym -= 257;
+        /* possibly get more bits from length code */
+        d->curlen = tinf_read_bits(d, length_bits[sym], length_base[sym]);
+
+        dist = tinf_decode_symbol(d, dt);
+        /* possibly get more bits from distance code */
+        offs = tinf_read_bits(d, dist_bits[dist], dist_base[dist]);
+        if (d->dict_ring) {
+            if (offs > d->dict_size) {
+                return TINF_DICT_ERROR;
+            }
+            d->lzOff = d->dict_idx - offs;
+            if (d->lzOff < 0) {
+                d->lzOff += d->dict_size;
+            }
+        } else {
+            d->lzOff = -offs;
+        }
+    }
+
+    /* copy next byte from dict substring */
+    if (d->dict_ring) {
+        TINF_PUT(d, d->dict_ring[d->lzOff]);
+        if ((unsigned)++d->lzOff == d->dict_size) {
+            d->lzOff = 0;
+        }
+    } else {
+        d->dest[0] = d->dest[d->lzOff];
+        d->dest++;
+    }
+    d->curlen--;
+    return TINF_OK;
+}
+
+/* inflate an uncompressed block of data */
+static int tinf_inflate_uncompressed_block(TINF_DATA *d)
+{
+    if (d->curlen == 0) {
+        unsigned int length, invlength;
+
+        /* get length */
+        length = uzlib_get_byte(d) + 256 * uzlib_get_byte(d);
+        /* get one's complement of length */
+        invlength = uzlib_get_byte(d) + 256 * uzlib_get_byte(d);
+        /* check length */
+        if (length != (~invlength & 0x0000ffff)) return TINF_DATA_ERROR;
+
+        /* increment length to properly return TINF_DONE below, without
+           producing data at the same time */
+        d->curlen = length + 1;
+
+        /* make sure we start next block on a byte boundary */
+        d->bitcount = 0;
+    }
+
+    if (--d->curlen == 0) {
+        return TINF_DONE;
+    }
+
+    unsigned char c = uzlib_get_byte(d);
+    TINF_PUT(d, c);
+    return TINF_OK;
+}
+
+/* ---------------------- *
+ * -- public functions -- *
+ * ---------------------- */
+
+/* initialize global (static) data */
+void uzlib_init(void)
+{
+#ifdef RUNTIME_BITS_TABLES
+   /* build extra bits and base tables */
+   tinf_build_bits_base(length_bits, length_base, 4, 3);
+   tinf_build_bits_base(dist_bits, dist_base, 2, 1);
+
+   /* fix a special case */
+   length_bits[28] = 0;
+   length_base[28] = 258;
+#endif
+}
+
+/* initialize decompression structure */
+void uzlib_uncompress_init(TINF_DATA *d, void *dict, unsigned int dictLen)
+{
+   d->bitcount = 0;
+   d->bfinal = 0;
+   d->btype = -1;
+   d->dict_size = dictLen;
+   d->dict_ring = dict;
+   d->dict_idx = 0;
+   d->curlen = 0;
+}
+
+/* inflate next byte of compressed stream */
+int uzlib_uncompress(TINF_DATA *d)
+{
+    do {
+        int res;
+
+        /* start a new block */
+        if (d->btype == -1) {
+next_blk:
+            /* read final block flag */
+            d->bfinal = tinf_getbit(d);
+            /* read block type (2 bits) */
+            d->btype = tinf_read_bits(d, 2, 0);
+
+            //printf("Started new block: type=%d final=%d\n", d->btype, d->bfinal);
+
+            if (d->btype == 1) {
+                /* build fixed huffman trees */
+                tinf_build_fixed_trees(&d->ltree, &d->dtree);
+            } else if (d->btype == 2) {
+                /* decode trees from stream */
+                tinf_decode_trees(d, &d->ltree, &d->dtree);
+            }
+        }
+
+        /* process current block */
+        switch (d->btype)
+        {
+        case 0:
+            /* decompress uncompressed block */
+            res = tinf_inflate_uncompressed_block(d);
+            break;
+        case 1:
+        case 2:
+            /* decompress block with fixed/dyanamic huffman trees */
+            /* trees were decoded previously, so it's the same routine for both */
+            res = tinf_inflate_block_data(d, &d->ltree, &d->dtree);
+            break;
+        default:
+            return TINF_DATA_ERROR;
+        }
+
+        if (res == TINF_DONE && !d->bfinal) {
+            /* the block has ended (without producing more data), but we
+               can't return without data, so start procesing next block */
+            goto next_blk;
+        }
+
+        if (res != TINF_OK) {
+            return res;
+        }
+
+    } while (--d->destSize);
+
+    return TINF_OK;
+}
+
+int uzlib_uncompress_chksum(TINF_DATA *d)
+{
+    int res;
+    unsigned char *data = d->dest;
+
+    res = uzlib_uncompress(d);
+
+    if (res < 0) return res;
+
+    switch (d->checksum_type) {
+
+    case TINF_CHKSUM_ADLER:
+        d->checksum = uzlib_adler32(data, d->dest - data, d->checksum);
+        break;
+
+    case TINF_CHKSUM_CRC:
+        d->checksum = uzlib_crc32(data, d->dest - data, d->checksum);
+        break;
+    }
+
+    if (res == TINF_DONE) {
+        unsigned int val;
+
+        switch (d->checksum_type) {
+
+        case TINF_CHKSUM_ADLER:
+            val = tinf_get_be_uint32(d);
+            if (d->checksum != val) {
+                return TINF_CHKSUM_ERROR;
+            }
+            break;
+
+        case TINF_CHKSUM_CRC:
+            val = tinf_get_le_uint32(d);
+            if (~d->checksum != val) {
+                return TINF_CHKSUM_ERROR;
+            }
+            // Uncompressed size. TODO: Check
+            val = tinf_get_le_uint32(d);
+            break;
+        }
+    }
+
+    return res;
+}

+ 66 - 0
extmod/uzlib/tinfzlib.c

@@ -0,0 +1,66 @@
+/*
+ * tinfzlib  -  tiny zlib decompressor
+ *
+ * Copyright (c) 2003 by Joergen Ibsen / Jibz
+ * All Rights Reserved
+ *
+ * http://www.ibsensoftware.com/
+ *
+ * Copyright (c) 2014-2016 by Paul Sokolovsky
+ *
+ * This software is provided 'as-is', without any express
+ * or implied warranty.  In no event will the authors be
+ * held liable for any damages arising from the use of
+ * this software.
+ *
+ * Permission is granted to anyone to use this software
+ * for any purpose, including commercial applications,
+ * and to alter it and redistribute it freely, subject to
+ * the following restrictions:
+ *
+ * 1. The origin of this software must not be
+ *    misrepresented; you must not claim that you
+ *    wrote the original software. If you use this
+ *    software in a product, an acknowledgment in
+ *    the product documentation would be appreciated
+ *    but is not required.
+ *
+ * 2. Altered source versions must be plainly marked
+ *    as such, and must not be misrepresented as
+ *    being the original software.
+ *
+ * 3. This notice may not be removed or altered from
+ *    any source distribution.
+ */
+
+#include "tinf.h"
+
+int uzlib_zlib_parse_header(TINF_DATA *d)
+{
+   unsigned char cmf, flg;
+
+   /* -- get header bytes -- */
+
+   cmf = uzlib_get_byte(d);
+   flg = uzlib_get_byte(d);
+
+   /* -- check format -- */
+
+   /* check checksum */
+   if ((256*cmf + flg) % 31) return TINF_DATA_ERROR;
+
+   /* check method is deflate */
+   if ((cmf & 0x0f) != 8) return TINF_DATA_ERROR;
+
+   /* check window size is valid */
+   if ((cmf >> 4) > 7) return TINF_DATA_ERROR;
+
+   /* check there is no preset dictionary */
+   if (flg & 0x20) return TINF_DATA_ERROR;
+
+   /* initialize for adler32 checksum */
+   d->checksum_type = TINF_CHKSUM_ADLER;
+   d->checksum = 1;
+
+   return cmf >> 4;
+}