diff options
Diffstat (limited to 'tinySIGCOMP/src')
65 files changed, 17410 insertions, 0 deletions
diff --git a/tinySIGCOMP/src/adler32.c b/tinySIGCOMP/src/adler32.c new file mode 100644 index 0000000..f7844d1 --- /dev/null +++ b/tinySIGCOMP/src/adler32.c @@ -0,0 +1,152 @@ +#if !HAS_ZLIB +/* adler32.c -- compute the Adler-32 checksum of a data stream + * Copyright (C) 1995-2004 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "zlib.h" + +#define BASE 65521UL /* largest prime smaller than 65536 */ +#define NMAX 5552 +/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ + +#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} +#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); +#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); +#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); +#define DO16(buf) DO8(buf,0); DO8(buf,8); + +/* use NO_DIVIDE if your processor does not do division in hardware */ +#ifdef NO_DIVIDE +# define MOD(a) \ + do { \ + if (a >= (BASE << 16)) a -= (BASE << 16); \ + if (a >= (BASE << 15)) a -= (BASE << 15); \ + if (a >= (BASE << 14)) a -= (BASE << 14); \ + if (a >= (BASE << 13)) a -= (BASE << 13); \ + if (a >= (BASE << 12)) a -= (BASE << 12); \ + if (a >= (BASE << 11)) a -= (BASE << 11); \ + if (a >= (BASE << 10)) a -= (BASE << 10); \ + if (a >= (BASE << 9)) a -= (BASE << 9); \ + if (a >= (BASE << 8)) a -= (BASE << 8); \ + if (a >= (BASE << 7)) a -= (BASE << 7); \ + if (a >= (BASE << 6)) a -= (BASE << 6); \ + if (a >= (BASE << 5)) a -= (BASE << 5); \ + if (a >= (BASE << 4)) a -= (BASE << 4); \ + if (a >= (BASE << 3)) a -= (BASE << 3); \ + if (a >= (BASE << 2)) a -= (BASE << 2); \ + if (a >= (BASE << 1)) a -= (BASE << 1); \ + if (a >= BASE) a -= BASE; \ + } while (0) +# define MOD4(a) \ + do { \ + if (a >= (BASE << 4)) a -= (BASE << 4); \ + if (a >= (BASE << 3)) a -= (BASE << 3); \ + if (a >= (BASE << 2)) a -= (BASE << 2); \ + if (a >= (BASE << 1)) a -= (BASE << 1); \ + if (a >= BASE) a -= BASE; \ + } while (0) +#else +# define MOD(a) a %= BASE +# define MOD4(a) a %= BASE +#endif + +/* ========================================================================= */ +uLong ZEXPORT adler32(adler, buf, len) + uLong adler; + const Bytef *buf; + uInt len; +{ + unsigned long sum2; + unsigned n; + + /* split Adler-32 into component sums */ + sum2 = (adler >> 16) & 0xffff; + adler &= 0xffff; + + /* in case user likes doing a byte at a time, keep it fast */ + if (len == 1) { + adler += buf[0]; + if (adler >= BASE) + adler -= BASE; + sum2 += adler; + if (sum2 >= BASE) + sum2 -= BASE; + return adler | (sum2 << 16); + } + + /* initial Adler-32 value (deferred check for len == 1 speed) */ + if (buf == Z_NULL) + return 1L; + + /* in case short lengths are provided, keep it somewhat fast */ + if (len < 16) { + while (len--) { + adler += *buf++; + sum2 += adler; + } + if (adler >= BASE) + adler -= BASE; + MOD4(sum2); /* only added so many BASE's */ + return adler | (sum2 << 16); + } + + /* do length NMAX blocks -- requires just one modulo operation */ + while (len >= NMAX) { + len -= NMAX; + n = NMAX / 16; /* NMAX is divisible by 16 */ + do { + DO16(buf); /* 16 sums unrolled */ + buf += 16; + } while (--n); + MOD(adler); + MOD(sum2); + } + + /* do remaining bytes (less than NMAX, still just one modulo) */ + if (len) { /* avoid modulos if none remaining */ + while (len >= 16) { + len -= 16; + DO16(buf); + buf += 16; + } + while (len--) { + adler += *buf++; + sum2 += adler; + } + MOD(adler); + MOD(sum2); + } + + /* return recombined sums */ + return adler | (sum2 << 16); +} + +/* ========================================================================= */ +uLong ZEXPORT adler32_combine(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off_t len2; +{ + unsigned long sum1; + unsigned long sum2; + unsigned rem; + + /* the derivation of this formula is left as an exercise for the reader */ + rem = (unsigned)(len2 % BASE); + sum1 = adler1 & 0xffff; + sum2 = rem * sum1; + MOD(sum2); + sum1 += (adler2 & 0xffff) + BASE - 1; + sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; + if (sum1 > BASE) sum1 -= BASE; + if (sum1 > BASE) sum1 -= BASE; + if (sum2 > (BASE << 1)) sum2 -= (BASE << 1); + if (sum2 > BASE) sum2 -= BASE; + return sum1 | (sum2 << 16); +} +#endif // HAS_ZLIB + diff --git a/tinySIGCOMP/src/compress.c b/tinySIGCOMP/src/compress.c new file mode 100644 index 0000000..ca01fbf --- /dev/null +++ b/tinySIGCOMP/src/compress.c @@ -0,0 +1,82 @@ +#if !HAS_ZLIB +/* compress.c -- compress a memory buffer + * Copyright (C) 1995-2003 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "zlib.h" + +/* =========================================================================== + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least 0.1% larger than sourceLen plus + 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ +int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; + int level; +{ + z_stream stream; + int err; + + stream.next_in = (Bytef*)source; + stream.avail_in = (uInt)sourceLen; +#ifdef MAXSEG_64K + /* Check for source > 64K on 16-bit machine: */ + if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; +#endif + stream.next_out = dest; + stream.avail_out = (uInt)*destLen; + if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; + + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + stream.opaque = (voidpf)0; + + err = deflateInit(&stream, level); + if (err != Z_OK) return err; + + err = deflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + deflateEnd(&stream); + return err == Z_OK ? Z_BUF_ERROR : err; + } + *destLen = stream.total_out; + + err = deflateEnd(&stream); + return err; +} + +/* =========================================================================== + */ +int ZEXPORT compress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + return compress2(dest, destLen, source, sourceLen, Z_BEST_SPEED); +} + +/* =========================================================================== + If the default memLevel or windowBits for deflateInit() is changed, then + this function needs to be updated. + */ +uLong ZEXPORT compressBound (sourceLen) + uLong sourceLen; +{ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11; +} +#endif // HAS_ZLIB + diff --git a/tinySIGCOMP/src/deflate.c b/tinySIGCOMP/src/deflate.c new file mode 100644 index 0000000..a3c208e --- /dev/null +++ b/tinySIGCOMP/src/deflate.c @@ -0,0 +1,1740 @@ +#if !HAS_ZLIB +/* deflate.c -- compress data using the deflation algorithm + * Copyright (C) 1995-2005 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process depends on being able to identify portions + * of the input text which are identical to earlier input (within a + * sliding window trailing behind the input currently being processed). + * + * The most straightforward technique turns out to be the fastest for + * most input files: try all possible matches and select the longest. + * The key feature of this algorithm is that insertions into the string + * dictionary are very simple and thus fast, and deletions are avoided + * completely. Insertions are performed at each input character, whereas + * string matches are performed only when the previous match ends. So it + * is preferable to spend more time in matches to allow very fast string + * insertions and avoid deletions. The matching algorithm for small + * strings is inspired from that of Rabin & Karp. A brute force approach + * is used to find longer strings when a small match has been found. + * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze + * (by Leonid Broukhis). + * A previous version of this file used a more sophisticated algorithm + * (by Fiala and Greene) which is guaranteed to run in linear amortized + * time, but has a larger average cost, uses more memory and is patented. + * However the F&G algorithm may be faster for some highly redundant + * files if the parameter max_chain_length (described below) is too large. + * + * ACKNOWLEDGEMENTS + * + * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and + * I found it in 'freeze' written by Leonid Broukhis. + * Thanks to many people for bug reports and testing. + * + * REFERENCES + * + * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". + * Available in http://www.ietf.org/rfc/rfc1951.txt + * + * A description of the Rabin and Karp algorithm is given in the book + * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. + * + * Fiala,E.R., and Greene,D.H. + * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 + * + */ + +/* @(#) $Id$ */ + +#include "deflate.h" + +const char deflate_copyright[] = + " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* =========================================================================== + * Function prototypes. + */ +typedef enum { + need_more, /* block not completed, need more input or more output */ + block_done, /* block flush performed */ + finish_started, /* finish started, need only more output at next deflate */ + finish_done /* finish done, accept no more input or output */ +} block_state; + +typedef block_state (*compress_func) OF((deflate_state *s, int flush)); +/* Compression function. Returns the block state after the call. */ + +local void fill_window OF((deflate_state *s)); +local block_state deflate_stored OF((deflate_state *s, int flush)); +local block_state deflate_fast OF((deflate_state *s, int flush)); +#ifndef FASTEST +local block_state deflate_slow OF((deflate_state *s, int flush)); +#endif +local void lm_init OF((deflate_state *s)); +local void putShortMSB OF((deflate_state *s, uInt b)); +local void flush_pending OF((z_streamp strm)); +local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); +#ifndef FASTEST +#ifdef ASMV + void match_init OF((void)); /* asm code initialization */ + uInt longest_match OF((deflate_state *s, IPos cur_match)); +#else +local uInt longest_match OF((deflate_state *s, IPos cur_match)); +#endif +#endif +local uInt longest_match_fast OF((deflate_state *s, IPos cur_match)); + +#ifdef DEBUG +local void check_match OF((deflate_state *s, IPos start, IPos match, + int length)); +#endif + +/* =========================================================================== + * Local data + */ + +#define NIL 0 +/* Tail of hash chains */ + +#ifndef TOO_FAR +# define TOO_FAR 4096 +#endif +/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ + +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) +/* Minimum amount of lookahead, except at the end of the input file. + * See deflate.c for comments about the MIN_MATCH+1. + */ + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +typedef struct config_s { + ush good_length; /* reduce lazy search above this match length */ + ush max_lazy; /* do not perform lazy search above this match length */ + ush nice_length; /* quit search above this match length */ + ush max_chain; + compress_func func; +} config; + +#ifdef FASTEST +local const config configuration_table[2] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ +#else +local const config configuration_table[10] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ +/* 2 */ {4, 5, 16, 8, deflate_fast}, +/* 3 */ {4, 6, 32, 32, deflate_fast}, + +/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ +/* 5 */ {8, 16, 32, 32, deflate_slow}, +/* 6 */ {8, 16, 128, 128, deflate_slow}, +/* 7 */ {8, 32, 128, 256, deflate_slow}, +/* 8 */ {32, 128, 258, 1024, deflate_slow}, +/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ +#endif + +/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 + * For deflate_fast() (levels <= 3) good is ignored and lazy has a different + * meaning. + */ + +#define EQUAL 0 +/* result of memcmp for equal strings */ + +#ifndef NO_DUMMY_DECL +struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ +#endif + +/* =========================================================================== + * Update a hash value with the given input byte + * IN assertion: all calls to to UPDATE_HASH are made with consecutive + * input characters, so that a running hash key can be computed from the + * previous key instead of complete recalculation each time. + */ +#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask) + + +/* =========================================================================== + * Insert string str in the dictionary and set match_head to the previous head + * of the hash chain (the most recent string with same hash key). Return + * the previous length of the hash chain. + * If this file is compiled with -DFASTEST, the compression level is forced + * to 1, and no hash chains are maintained. + * IN assertion: all calls to to INSERT_STRING are made with consecutive + * input characters and the first MIN_MATCH bytes of str are valid + * (except for the last MIN_MATCH-1 bytes of the input file). + */ +#ifdef FASTEST +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#else +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#endif + +/* =========================================================================== + * Initialize the hash table (avoiding 64K overflow for 16 bit systems). + * prev[] will be initialized on the fly. + */ +#define CLEAR_HASH(s) \ + s->head[s->hash_size-1] = NIL; \ + zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); + +/* ========================================================================= */ +int ZEXPORT deflateInit_(strm, level, version, stream_size) + z_streamp strm; + int level; + const char *version; + int stream_size; +{ + return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, + Z_DEFAULT_STRATEGY, version, stream_size); + /* To do: ignore strm->next_in if we use it as window */ +} + +/* ========================================================================= */ +int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + version, stream_size) + z_streamp strm; + int level; + int method; + int windowBits; + int memLevel; + int strategy; + const char *version; + int stream_size; +{ + deflate_state *s; + int wrap = 1; + static const char my_version[] = ZLIB_VERSION; + + ushf *overlay; + /* We overlay pending_buf and d_buf+l_buf. This works since the average + * output size for (length,distance) codes is <= 24 bits. + */ + + if (version == Z_NULL || version[0] != my_version[0] || + stream_size != sizeof(z_stream)) { + return Z_VERSION_ERROR; + } + if (strm == Z_NULL) return Z_STREAM_ERROR; + + strm->msg = Z_NULL; + if (strm->zalloc == (alloc_func)0) { + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; + } + if (strm->zfree == (free_func)0) strm->zfree = zcfree; + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } +#ifdef GZIP + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } +#endif + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return Z_STREAM_ERROR; + } + if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ + s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); + if (s == Z_NULL) return Z_MEM_ERROR; + strm->state = (struct internal_state FAR *)s; + s->strm = strm; + + s->wrap = wrap; + s->gzhead = Z_NULL; + s->w_bits = windowBits; + s->w_size = 1 << s->w_bits; + s->w_mask = s->w_size - 1; + + s->hash_bits = memLevel + 7; + s->hash_size = 1 << s->hash_bits; + s->hash_mask = s->hash_size - 1; + s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); + + s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); + s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); + s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); + + s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + s->pending_buf = (uchf *) overlay; + s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); + + if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || + s->pending_buf == Z_NULL) { + s->status = FINISH_STATE; + strm->msg = (char*)ERR_MSG(Z_MEM_ERROR); + deflateEnd (strm); + return Z_MEM_ERROR; + } + s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + + s->level = level; + s->strategy = strategy; + s->method = (Byte)method; + + return deflateReset(strm); +} + +/* ========================================================================= */ +int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) + z_streamp strm; + const Bytef *dictionary; + uInt dictLength; +{ + deflate_state *s; + uInt length = dictLength; + uInt n; + IPos hash_head = 0; + + if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL || + strm->state->wrap == 2 || + (strm->state->wrap == 1 && strm->state->status != INIT_STATE)) + return Z_STREAM_ERROR; + + s = strm->state; + if (s->wrap) + strm->adler = adler32(strm->adler, dictionary, dictLength); + + if (length < MIN_MATCH) return Z_OK; + if (length > MAX_DIST(s)) { + length = MAX_DIST(s); + dictionary += dictLength - length; /* use the tail of the dictionary */ + } + zmemcpy(s->window, dictionary, length); + s->strstart = length; + s->block_start = (long)length; + + /* Insert all strings in the hash table (except for the last two bytes). + * s->lookahead stays null, so s->ins_h will be recomputed at the next + * call of fill_window. + */ + s->ins_h = s->window[0]; + UPDATE_HASH(s, s->ins_h, s->window[1]); + for (n = 0; n <= length - MIN_MATCH; n++) { + INSERT_STRING(s, n, hash_head); + } + if (hash_head) hash_head = 0; /* to make compiler happy */ + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateReset (strm) + z_streamp strm; +{ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) { + return Z_STREAM_ERROR; + } + + strm->total_in = strm->total_out = 0; + strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ + strm->data_type = Z_UNKNOWN; + + s = (deflate_state *)strm->state; + s->pending = 0; + s->pending_out = s->pending_buf; + + if (s->wrap < 0) { + s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ + } + s->status = s->wrap ? INIT_STATE : BUSY_STATE; + strm->adler = +#ifdef GZIP + s->wrap == 2 ? crc32(0L, Z_NULL, 0) : +#endif + adler32(0L, Z_NULL, 0); + s->last_flush = Z_NO_FLUSH; + + _tr_init(s); + lm_init(s); + + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateSetHeader (strm, head) + z_streamp strm; + gz_headerp head; +{ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + if (strm->state->wrap != 2) return Z_STREAM_ERROR; + strm->state->gzhead = head; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflatePrime (strm, bits, value) + z_streamp strm; + int bits; + int value; +{ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + strm->state->bi_valid = bits; + strm->state->bi_buf = (ush)(value & ((1 << bits) - 1)); + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateParams(strm, level, strategy) + z_streamp strm; + int level; + int strategy; +{ + deflate_state *s; + compress_func func; + int err = Z_OK; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + s = strm->state; + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { + return Z_STREAM_ERROR; + } + func = configuration_table[s->level].func; + + if (func != configuration_table[level].func && strm->total_in != 0) { + /* Flush the last buffer: */ + err = deflate(strm, Z_PARTIAL_FLUSH); + } + if (s->level != level) { + s->level = level; + s->max_lazy_match = configuration_table[level].max_lazy; + s->good_match = configuration_table[level].good_length; + s->nice_match = configuration_table[level].nice_length; + s->max_chain_length = configuration_table[level].max_chain; + } + s->strategy = strategy; + return err; +} + +/* ========================================================================= */ +int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) + z_streamp strm; + int good_length; + int max_lazy; + int nice_length; + int max_chain; +{ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + s = strm->state; + s->good_match = good_length; + s->max_lazy_match = max_lazy; + s->nice_match = nice_length; + s->max_chain_length = max_chain; + return Z_OK; +} + +/* ========================================================================= + * For the default windowBits of 15 and memLevel of 8, this function returns + * a close to exact, as well as small, upper bound on the compressed size. + * They are coded as constants here for a reason--if the #define's are + * changed, then this function needs to be changed as well. The return + * value for 15 and 8 only works for those exact settings. + * + * For any setting other than those defaults for windowBits and memLevel, + * the value returned is a conservative worst case for the maximum expansion + * resulting from using fixed blocks instead of stored blocks, which deflate + * can emit on compressed data for some combinations of the parameters. + * + * This function could be more sophisticated to provide closer upper bounds + * for every combination of windowBits and memLevel, as well as wrap. + * But even the conservative upper bound of about 14% expansion does not + * seem onerous for output buffer allocation. + */ +uLong ZEXPORT deflateBound(strm, sourceLen) + z_streamp strm; + uLong sourceLen; +{ + deflate_state *s; + uLong destLen; + + /* conservative upper bound */ + destLen = sourceLen + + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11; + + /* if can't get parameters, return conservative bound */ + if (strm == Z_NULL || strm->state == Z_NULL) + return destLen; + + /* if not default parameters, return conservative bound */ + s = strm->state; + if (s->w_bits != 15 || s->hash_bits != 8 + 7) + return destLen; + + /* default settings: return tight bound for that case */ + return compressBound(sourceLen); +} + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +local void putShortMSB (s, b) + deflate_state *s; + uInt b; +{ + put_byte(s, (Byte)(b >> 8)); + put_byte(s, (Byte)(b & 0xff)); +} + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->next_out buffer and copying into it. + * (See also read_buf()). + */ +local void flush_pending(strm) + z_streamp strm; +{ + unsigned len = strm->state->pending; + + if (len > strm->avail_out) len = strm->avail_out; + if (len == 0) return; + + zmemcpy(strm->next_out, strm->state->pending_out, len); + strm->next_out += len; + strm->state->pending_out += len; + strm->total_out += len; + strm->avail_out -= len; + strm->state->pending -= len; + if (strm->state->pending == 0) { + strm->state->pending_out = strm->state->pending_buf; + } +} + +/* ========================================================================= */ +int ZEXPORT deflate (strm, flush) + z_streamp strm; + int flush; +{ + int old_flush; /* value of flush param for previous deflate call */ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL || + flush > Z_FINISH || flush < 0) { + return Z_STREAM_ERROR; + } + s = strm->state; + + if (strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0) || + (s->status == FINISH_STATE && flush != Z_FINISH)) { + ERR_RETURN(strm, Z_STREAM_ERROR); + } + if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); + + s->strm = strm; /* just in case */ + old_flush = s->last_flush; + s->last_flush = flush; + + /* Write the header */ + if (s->status == INIT_STATE) { +#ifdef GZIP + if (s->wrap == 2) { + strm->adler = crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (s->gzhead == NULL) { + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s->status = BUSY_STATE; + } + else { + put_byte(s, (s->gzhead->text ? 1 : 0) + + (s->gzhead->hcrc ? 2 : 0) + + (s->gzhead->extra == Z_NULL ? 0 : 4) + + (s->gzhead->name == Z_NULL ? 0 : 8) + + (s->gzhead->comment == Z_NULL ? 0 : 16) + ); + put_byte(s, (Byte)(s->gzhead->time & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, s->gzhead->os & 0xff); + if (s->gzhead->extra != NULL) { + put_byte(s, s->gzhead->extra_len & 0xff); + put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); + } + if (s->gzhead->hcrc) + strm->adler = crc32(strm->adler, s->pending_buf, + s->pending); + s->gzindex = 0; + s->status = EXTRA_STATE; + } + } + else +#endif + { + uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; + uInt level_flags; + + if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) + level_flags = 0; + else if (s->level < 6) + level_flags = 1; + else if (s->level == 6) + level_flags = 2; + else + level_flags = 3; + header |= (level_flags << 6); + if (s->strstart != 0) header |= PRESET_DICT; + header += 31 - (header % 31); + + s->status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s->strstart != 0) { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + strm->adler = adler32(0L, Z_NULL, 0); + } + } +#ifdef GZIP + if (s->status == EXTRA_STATE) { + if (s->gzhead->extra != NULL) { + uInt beg = s->pending; /* start of bytes to update crc */ + + while (s->gzindex < (s->gzhead->extra_len & 0xffff)) { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) + break; + } + put_byte(s, s->gzhead->extra[s->gzindex]); + s->gzindex++; + } + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + if (s->gzindex == s->gzhead->extra_len) { + s->gzindex = 0; + s->status = NAME_STATE; + } + } + else + s->status = NAME_STATE; + } + if (s->status == NAME_STATE) { + if (s->gzhead->name != NULL) { + uInt beg = s->pending; /* start of bytes to update crc */ + int val; + + do { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) { + val = 1; + break; + } + } + val = s->gzhead->name[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + if (val == 0) { + s->gzindex = 0; + s->status = COMMENT_STATE; + } + } + else + s->status = COMMENT_STATE; + } + if (s->status == COMMENT_STATE) { + if (s->gzhead->comment != NULL) { + uInt beg = s->pending; /* start of bytes to update crc */ + int val; + + do { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) { + val = 1; + break; + } + } + val = s->gzhead->comment[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + if (val == 0) + s->status = HCRC_STATE; + } + else + s->status = HCRC_STATE; + } + if (s->status == HCRC_STATE) { + if (s->gzhead->hcrc) { + if (s->pending + 2 > s->pending_buf_size) + flush_pending(strm); + if (s->pending + 2 <= s->pending_buf_size) { + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + strm->adler = crc32(0L, Z_NULL, 0); + s->status = BUSY_STATE; + } + } + else + s->status = BUSY_STATE; + } +#endif + + /* Flush as much pending output as possible */ + if (s->pending != 0) { + flush_pending(strm); + if (strm->avail_out == 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s->last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm->avail_in == 0 && flush <= old_flush && + flush != Z_FINISH) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s->status == FINISH_STATE && strm->avail_in != 0) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm->avail_in != 0 || s->lookahead != 0 || + (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { + block_state bstate; + + bstate = (*(configuration_table[s->level].func))(s, flush); + + if (bstate == finish_started || bstate == finish_done) { + s->status = FINISH_STATE; + } + if (bstate == need_more || bstate == finish_started) { + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate == block_done) { + if (flush == Z_PARTIAL_FLUSH) { + _tr_align(s); + } else { /* FULL_FLUSH or SYNC_FLUSH */ + _tr_stored_block(s, (char*)0, 0L, 0); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush == Z_FULL_FLUSH) { + CLEAR_HASH(s); /* forget history */ + } + } + flush_pending(strm); + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + Assert(strm->avail_out > 0, "bug2"); + + if (flush != Z_FINISH) return Z_OK; + if (s->wrap <= 0) return Z_STREAM_END; + + /* Write the trailer */ +#ifdef GZIP + if (s->wrap == 2) { + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); + put_byte(s, (Byte)(strm->total_in & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); + } + else +#endif + { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ + return s->pending != 0 ? Z_OK : Z_STREAM_END; +} + +/* ========================================================================= */ +int ZEXPORT deflateEnd (strm) + z_streamp strm; +{ + int status; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + + status = strm->state->status; + if (status != INIT_STATE && + status != EXTRA_STATE && + status != NAME_STATE && + status != COMMENT_STATE && + status != HCRC_STATE && + status != BUSY_STATE && + status != FINISH_STATE) { + return Z_STREAM_ERROR; + } + + /* Deallocate in reverse order of allocations: */ + TRY_FREE(strm, strm->state->pending_buf); + TRY_FREE(strm, strm->state->head); + TRY_FREE(strm, strm->state->prev); + TRY_FREE(strm, strm->state->window); + + ZFREE(strm, strm->state); + strm->state = Z_NULL; + + return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; +} + +/* ========================================================================= + * Copy the source state to the destination state. + * To simplify the source, this is not supported for 16-bit MSDOS (which + * doesn't have enough memory anyway to duplicate compression states). + */ +int ZEXPORT deflateCopy (dest, source) + z_streamp dest; + z_streamp source; +{ +#ifdef MAXSEG_64K + return Z_STREAM_ERROR; +#else + deflate_state *ds; + deflate_state *ss; + ushf *overlay; + + + if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) { + return Z_STREAM_ERROR; + } + + ss = source->state; + + zmemcpy(dest, source, sizeof(z_stream)); + + ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); + if (ds == Z_NULL) return Z_MEM_ERROR; + dest->state = (struct internal_state FAR *) ds; + zmemcpy(ds, ss, sizeof(deflate_state)); + ds->strm = dest; + + ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); + ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); + ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); + overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); + ds->pending_buf = (uchf *) overlay; + + if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || + ds->pending_buf == Z_NULL) { + deflateEnd (dest); + return Z_MEM_ERROR; + } + /* following zmemcpy do not work for 16-bit MSDOS */ + zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); + zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos)); + zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos)); + zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); + + ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); + ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); + ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; + + ds->l_desc.dyn_tree = ds->dyn_ltree; + ds->d_desc.dyn_tree = ds->dyn_dtree; + ds->bl_desc.dyn_tree = ds->bl_tree; + + return Z_OK; +#endif /* MAXSEG_64K */ +} + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->next_in buffer and copying from it. + * (See also flush_pending()). + */ +local int read_buf(strm, buf, size) + z_streamp strm; + Bytef *buf; + unsigned size; +{ + unsigned len = strm->avail_in; + + if (len > size) len = size; + if (len == 0) return 0; + + strm->avail_in -= len; + + if (strm->state->wrap == 1) { + strm->adler = adler32(strm->adler, strm->next_in, len); + } +#ifdef GZIP + else if (strm->state->wrap == 2) { + strm->adler = crc32(strm->adler, strm->next_in, len); + } +#endif + zmemcpy(buf, strm->next_in, len); + strm->next_in += len; + strm->total_in += len; + + return (int)len; +} + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +local void lm_init (s) + deflate_state *s; +{ + s->window_size = (ulg)2L*s->w_size; + + CLEAR_HASH(s); + + /* Set the default configuration parameters: + */ + s->max_lazy_match = configuration_table[s->level].max_lazy; + s->good_match = configuration_table[s->level].good_length; + s->nice_match = configuration_table[s->level].nice_length; + s->max_chain_length = configuration_table[s->level].max_chain; + + s->strstart = 0; + s->block_start = 0L; + s->lookahead = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + s->ins_h = 0; +#ifndef FASTEST +#ifdef ASMV + match_init(); /* initialize the asm code */ +#endif +#endif +} + +#ifndef FASTEST +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +#ifndef ASMV +/* For 80x86 and 680x0, an optimized version will be provided in match.asm or + * match.S. The code will be functionally equivalent. + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + unsigned chain_length = s->max_chain_length;/* max hash chain length */ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + int best_len = s->prev_length; /* best match length so far */ + int nice_match = s->nice_match; /* stop if match long enough */ + IPos limit = s->strstart > (IPos)MAX_DIST(s) ? + s->strstart - (IPos)MAX_DIST(s) : NIL; + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + Posf *prev = s->prev; + uInt wmask = s->w_mask; + +#ifdef UNALIGNED_OK + /* Compare two bytes at a time. Note: this is not always beneficial. + * Try with and without -DUNALIGNED_OK to check. + */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; + register ush scan_start = *(ushf*)scan; + register ush scan_end = *(ushf*)(scan+best_len-1); +#else + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + register Byte scan_end1 = scan[best_len-1]; + register Byte scan_end = scan[best_len]; +#endif + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s->prev_length >= s->good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + Assert(cur_match < s->strstart, "no future"); + match = s->window + cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ +#if (defined(UNALIGNED_OK) && MAX_MATCH == 258) + /* This code assumes sizeof(unsigned short) == 2. Do not use + * UNALIGNED_OK if your compiler uses a different size. + */ + if (*(ushf*)(match+best_len-1) != scan_end || + *(ushf*)match != scan_start) continue; + + /* It is not necessary to compare scan[2] and match[2] since they are + * always equal when the other bytes match, given that the hash keys + * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at + * strstart+3, +5, ... up to strstart+257. We check for insufficient + * lookahead only every 4th comparison; the 128th check will be made + * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is + * necessary to put more guard bytes at the end of the window, or + * to check more often for insufficient lookahead. + */ + Assert(scan[2] == match[2], "scan[2]?"); + scan++, match++; + do { + } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + scan < strend); + /* The funny "do {}" generates better code on most compilers */ + + /* Here, scan <= window+strstart+257 */ + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + if (*scan == *match) scan++; + + len = (MAX_MATCH - 1) - (int)(strend-scan); + scan = strend - (MAX_MATCH-1); + +#else /* UNALIGNED_OK */ + + if (match[best_len] != scan_end || + match[best_len-1] != scan_end1 || + *match != *scan || + *++match != scan[1]) continue; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match++; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + scan = strend - MAX_MATCH; + +#endif /* UNALIGNED_OK */ + + if (len > best_len) { + s->match_start = cur_match; + best_len = len; + if (len >= nice_match) break; +#ifdef UNALIGNED_OK + scan_end = *(ushf*)(scan+best_len-1); +#else + scan_end1 = scan[best_len-1]; + scan_end = scan[best_len]; +#endif + } + } while ((cur_match = prev[cur_match & wmask]) > limit + && --chain_length != 0); + + if ((uInt)best_len <= s->lookahead) return (uInt)best_len; + return s->lookahead; +} +#endif /* ASMV */ +#endif /* FASTEST */ + +/* --------------------------------------------------------------------------- + * Optimized version for level == 1 or strategy == Z_RLE only + */ +local uInt longest_match_fast(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + Assert(cur_match < s->strstart, "no future"); + + match = s->window + cur_match; + + /* Return failure if the match length is less than 2: + */ + if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match += 2; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + + if (len < MIN_MATCH) return MIN_MATCH - 1; + + s->match_start = cur_match; + return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; +} + +#ifdef DEBUG +/* =========================================================================== + * Check that the match at match_start is indeed a match. + */ +local void check_match(s, start, match, length) + deflate_state *s; + IPos start, match; + int length; +{ + /* check that the match is indeed a match */ + if (zmemcmp(s->window + match, + s->window + start, length) != EQUAL) { + fprintf(stderr, " start %u, match %u, length %d\n", + start, match, length); + do { + fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); + } while (--length != 0); + z_error("invalid match"); + } + if (z_verbose > 1) { + fprintf(stderr,"\\[%d,%d]", start-match, length); + do { putc(s->window[start++], stderr); } while (--length != 0); + } +} +#else +# define check_match(s, start, match, length) +#endif /* DEBUG */ + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +local void fill_window(s) + deflate_state *s; +{ + register unsigned n, m; + register Posf *p; + unsigned more; /* Amount of free space at the end of the window. */ + uInt wsize = s->w_size; + + do { + more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); + + /* Deal with !@#$% 64K limit: */ + if (sizeof(int) <= 2) { + if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + more = wsize; + + } else if (more == (unsigned)(-1)) { + /* Very unlikely, but possible on 16 bit machine if + * strstart == 0 && lookahead == 1 (input done a byte at time) + */ + more--; + } + } + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s->strstart >= wsize+MAX_DIST(s)) { + + zmemcpy(s->window, s->window+wsize, (unsigned)wsize); + s->match_start -= wsize; + s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ + s->block_start -= (long) wsize; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + /* %%% avoid this when Z_RLE */ + n = s->hash_size; + p = &s->head[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m-wsize : NIL); + } while (--n); + + n = wsize; +#ifndef FASTEST + p = &s->prev[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m-wsize : NIL); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); +#endif + more += wsize; + } + if (s->strm->avail_in == 0) return; + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + Assert(more >= 2, "more < 2"); + + n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); + s->lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s->lookahead >= MIN_MATCH) { + s->ins_h = s->window[s->strstart]; + UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); +} + +/* =========================================================================== + * Flush the current block, with given end-of-file flag. + * IN assertion: strstart is set to the end of the current match. + */ +#define FLUSH_BLOCK_ONLY(s, eof) { \ + _tr_flush_block(s, (s->block_start >= 0L ? \ + (charf *)&s->window[(unsigned)s->block_start] : \ + (charf *)Z_NULL), \ + (ulg)((long)s->strstart - s->block_start), \ + (eof)); \ + s->block_start = s->strstart; \ + flush_pending(s->strm); \ + Tracev((stderr,"[FLUSH]")); \ +} + +/* Same but force premature exit if necessary. */ +#define FLUSH_BLOCK(s, eof) { \ + FLUSH_BLOCK_ONLY(s, eof); \ + if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \ +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +local block_state deflate_stored(s, flush) + deflate_state *s; + int flush; +{ + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + ulg max_block_size = 0xffff; + ulg max_start; + + if (max_block_size > s->pending_buf_size - 5) { + max_block_size = s->pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s->lookahead <= 1) { + + Assert(s->strstart < s->w_size+MAX_DIST(s) || + s->block_start >= (long)s->w_size, "slide too late"); + + fill_window(s); + if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; + + if (s->lookahead == 0) break; /* flush the current block */ + } + Assert(s->block_start >= 0L, "block gone"); + + s->strstart += s->lookahead; + s->lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + max_start = s->block_start + max_block_size; + if (s->strstart == 0 || (ulg)s->strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s->lookahead = (uInt)(s->strstart - max_start); + s->strstart = (uInt)max_start; + FLUSH_BLOCK(s, 0); + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { + FLUSH_BLOCK(s, 0); + } + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return flush == Z_FINISH ? finish_done : block_done; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +local block_state deflate_fast(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head = NIL; /* head of the hash chain */ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ +#ifdef FASTEST + if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) || + (s->strategy == Z_RLE && s->strstart - hash_head == 1)) { + s->match_length = longest_match_fast (s, hash_head); + } +#else + if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) { + s->match_length = longest_match (s, hash_head); + } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { + s->match_length = longest_match_fast (s, hash_head); + } +#endif + /* longest_match() or longest_match_fast() sets match_start */ + } + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->match_start, s->match_length); + + _tr_tally_dist(s, s->strstart - s->match_start, + s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ +#ifndef FASTEST + if (s->match_length <= s->max_insert_length && + s->lookahead >= MIN_MATCH) { + s->match_length--; /* string at strstart already in table */ + do { + s->strstart++; + INSERT_STRING(s, s->strstart, hash_head); + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s->match_length != 0); + s->strstart++; + } else +#endif + { + s->strstart += s->match_length; + s->match_length = 0; + s->ins_h = s->window[s->strstart]; + UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return flush == Z_FINISH ? finish_done : block_done; +} + +#ifndef FASTEST +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +local block_state deflate_slow(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head = NIL; /* head of hash chain */ + int bflush; /* set if current block must be flushed */ + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + */ + s->prev_length = s->match_length, s->prev_match = s->match_start; + s->match_length = MIN_MATCH-1; + + if (hash_head != NIL && s->prev_length < s->max_lazy_match && + s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) { + s->match_length = longest_match (s, hash_head); + } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { + s->match_length = longest_match_fast (s, hash_head); + } + /* longest_match() or longest_match_fast() sets match_start */ + + if (s->match_length <= 5 && (s->strategy == Z_FILTERED +#if TOO_FAR <= 32767 + || (s->match_length == MIN_MATCH && + s->strstart - s->match_start > TOO_FAR) +#endif + )) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s->match_length = MIN_MATCH-1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { + uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + check_match(s, s->strstart-1, s->prev_match, s->prev_length); + + _tr_tally_dist(s, s->strstart -1 - s->prev_match, + s->prev_length - MIN_MATCH, bflush); + + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s->lookahead -= s->prev_length-1; + s->prev_length -= 2; + do { + if (++s->strstart <= max_insert) { + INSERT_STRING(s, s->strstart, hash_head); + } + } while (--s->prev_length != 0); + s->match_available = 0; + s->match_length = MIN_MATCH-1; + s->strstart++; + + if (bflush) FLUSH_BLOCK(s, 0); + + } else if (s->match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + if (bflush) { + FLUSH_BLOCK_ONLY(s, 0); + } + s->strstart++; + s->lookahead--; + if (s->strm->avail_out == 0) return need_more; + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s->match_available = 1; + s->strstart++; + s->lookahead--; + } + } + Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s->match_available) { + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + s->match_available = 0; + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return flush == Z_FINISH ? finish_done : block_done; +} +#endif /* FASTEST */ + +#if 0 +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +local block_state deflate_rle(s, flush) + deflate_state *s; + int flush; +{ + int bflush; /* set if current block must be flushed */ + uInt run; /* length of run */ + uInt max; /* maximum length of run */ + uInt prev; /* byte at distance one to match */ + Bytef *scan; /* scan for end of run */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest encodable run. + */ + if (s->lookahead < MAX_MATCH) { + fill_window(s); + if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + run = 0; + if (s->strstart > 0) { /* if there is a previous byte, that is */ + max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH; + scan = s->window + s->strstart - 1; + prev = *scan++; + do { + if (*scan++ != prev) + break; + } while (++run < max); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (run >= MIN_MATCH) { + check_match(s, s->strstart, s->strstart - 1, run); + _tr_tally_dist(s, 1, run - MIN_MATCH, bflush); + s->lookahead -= run; + s->strstart += run; + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return flush == Z_FINISH ? finish_done : block_done; +} +#endif + +#endif // HAS_ZLIB + diff --git a/tinySIGCOMP/src/deflate.h b/tinySIGCOMP/src/deflate.h new file mode 100644 index 0000000..a4fbdfb --- /dev/null +++ b/tinySIGCOMP/src/deflate.h @@ -0,0 +1,335 @@ +#if !HAS_ZLIB +/* deflate.h -- internal compression state + * Copyright (C) 1995-2004 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef DEFLATE_H +#define DEFLATE_H + +#include "zutil.h" + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer creation by deflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip encoding + should be left enabled. */ +#ifndef NO_GZIP +# define GZIP +#endif + +/* =========================================================================== + * Internal compression state. + */ + +#define LENGTH_CODES 29 +/* number of length codes, not counting the special END_BLOCK code */ + +#define LITERALS 256 +/* number of literal bytes 0..255 */ + +#define L_CODES (LITERALS+1+LENGTH_CODES) +/* number of Literal or Length codes, including the END_BLOCK code */ + +#define D_CODES 30 +/* number of distance codes */ + +#define BL_CODES 19 +/* number of codes used to transfer the bit lengths */ + +#define HEAP_SIZE (2*L_CODES+1) +/* maximum heap size */ + +#define MAX_BITS 15 +/* All codes must not exceed MAX_BITS bits */ + +#define INIT_STATE 42 +#define EXTRA_STATE 69 +#define NAME_STATE 73 +#define COMMENT_STATE 91 +#define HCRC_STATE 103 +#define BUSY_STATE 113 +#define FINISH_STATE 666 +/* Stream status */ + + +/* Data structure describing a single value and its code string. */ +typedef struct ct_data_s { + union { + ush freq; /* frequency count */ + ush code; /* bit string */ + } fc; + union { + ush dad; /* father node in Huffman tree */ + ush len; /* length of bit string */ + } dl; +} FAR ct_data; + +#define Freq fc.freq +#define Code fc.code +#define Dad dl.dad +#define Len dl.len + +typedef struct static_tree_desc_s static_tree_desc; + +typedef struct tree_desc_s { + ct_data *dyn_tree; /* the dynamic tree */ + int max_code; /* largest code with non zero frequency */ + static_tree_desc *stat_desc; /* the corresponding static tree */ +} FAR tree_desc; + +typedef ush Pos; +typedef Pos FAR Posf; +typedef unsigned IPos; + +/* A Pos is an index in the character window. We use short instead of int to + * save space in the various tables. IPos is used only for parameter passing. + */ + +typedef struct internal_state { + z_streamp strm; /* pointer back to this zlib stream */ + int status; /* as the name implies */ + Bytef *pending_buf; /* output still pending */ + ulg pending_buf_size; /* size of pending_buf */ + Bytef *pending_out; /* next pending byte to output to the stream */ + uInt pending; /* nb of bytes in the pending buffer */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + gz_headerp gzhead; /* gzip header information to write */ + uInt gzindex; /* where in extra, name, or comment */ + Byte method; /* STORED (for zip only) or DEFLATED */ + int last_flush; /* value of flush param for previous deflate call */ + + /* used by deflate.c: */ + + uInt w_size; /* LZ77 window size (32K by default) */ + uInt w_bits; /* log2(w_size) (8..16) */ + uInt w_mask; /* w_size - 1 */ + + Bytef *window; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. Also, it limits + * the window size to 64K, which is quite useful on MSDOS. + * To do: use the user input buffer as sliding window. + */ + + ulg window_size; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + Posf *prev; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + Posf *head; /* Heads of the hash chains or NIL. */ + + uInt ins_h; /* hash index of string to be inserted */ + uInt hash_size; /* number of elements in hash table */ + uInt hash_bits; /* log2(hash_size) */ + uInt hash_mask; /* hash_size-1 */ + + uInt hash_shift; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + long block_start; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + uInt match_length; /* length of best match */ + IPos prev_match; /* previous match */ + int match_available; /* set if previous match exists */ + uInt strstart; /* start of string to insert */ + uInt match_start; /* start of matching string */ + uInt lookahead; /* number of valid bytes ahead in window */ + + uInt prev_length; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + uInt max_chain_length; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + uInt max_lazy_match; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ +# define max_insert_length max_lazy_match + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + int level; /* compression level (1..9) */ + int strategy; /* favor or force Huffman coding*/ + + uInt good_match; + /* Use a faster search when the previous match is longer than this */ + + int nice_match; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + /* Didn't use ct_data typedef below to supress compiler warning */ + struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + struct tree_desc_s l_desc; /* desc. for literal tree */ + struct tree_desc_s d_desc; /* desc. for distance tree */ + struct tree_desc_s bl_desc; /* desc. for bit length tree */ + + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + int heap_len; /* number of elements in the heap */ + int heap_max; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + uch depth[2*L_CODES+1]; + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + uchf *l_buf; /* buffer for literals or lengths */ + + uInt lit_bufsize; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + uInt last_lit; /* running index in l_buf */ + + ushf *d_buf; + /* Buffer for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + ulg opt_len; /* bit length of current block with optimal trees */ + ulg static_len; /* bit length of current block with static trees */ + uInt matches; /* number of string matches in current block */ + int last_eob_len; /* bit length of EOB code for last block */ + +#ifdef DEBUG + ulg compressed_len; /* total bit length of compressed file mod 2^32 */ + ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ +#endif + + ush bi_buf; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + int bi_valid; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + +} FAR deflate_state; + +/* Output a byte on the stream. + * IN assertion: there is enough room in pending_buf. + */ +#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);} + + +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) +/* Minimum amount of lookahead, except at the end of the input file. + * See deflate.c for comments about the MIN_MATCH+1. + */ + +#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) +/* In order to simplify the code, particularly on 16 bit machines, match + * distances are limited to MAX_DIST instead of WSIZE. + */ + + /* in trees.c */ +void _tr_init OF((deflate_state *s)); +int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); +void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len, + int eof)); +void _tr_align OF((deflate_state *s)); +void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len, + int eof)); + +#define d_code(dist) \ + ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) +/* Mapping from a distance to a distance code. dist is the distance - 1 and + * must not have side effects. _dist_code[256] and _dist_code[257] are never + * used. + */ + +#ifndef DEBUG +/* Inline versions of _tr_tally for speed: */ + +#if defined(GEN_TREES_H) || !defined(STDC) + extern uch _length_code[]; + extern uch _dist_code[]; +#else + extern const uch _length_code[]; + extern const uch _dist_code[]; +#endif + +# define _tr_tally_lit(s, c, flush) \ + { uch cc = (c); \ + s->d_buf[s->last_lit] = 0; \ + s->l_buf[s->last_lit++] = cc; \ + s->dyn_ltree[cc].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +# define _tr_tally_dist(s, distance, length, flush) \ + { uch len = (length); \ + ush dist = (distance); \ + s->d_buf[s->last_lit] = dist; \ + s->l_buf[s->last_lit++] = len; \ + dist--; \ + s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ + s->dyn_dtree[d_code(dist)].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +#else +# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) +# define _tr_tally_dist(s, distance, length, flush) \ + flush = _tr_tally(s, distance, length) +#endif + +#endif /* DEFLATE_H */ + +#endif // HAS_ZLIB + diff --git a/tinySIGCOMP/src/tcomp.c b/tinySIGCOMP/src/tcomp.c new file mode 100644 index 0000000..cfb2b50 --- /dev/null +++ b/tinySIGCOMP/src/tcomp.c @@ -0,0 +1,183 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp.c + * @brief SigComp (RFC 3320) Implementation for 2.5G and 3G cellular networks. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp.h" + +/** @mainpage tinySigComp API Overview +* +* This file is an overview of <b>tinySigComp</b> API. +* +* <b>tinySigComp</b> is a tiny but fully featured SigComp implementation for 2.5G, 3G and 4G cellular networks. This library is also used in Doubango project to provide SigComp +* support for 3GPP IMS and OMA networks. +* This API is designed to efficiently work on embedded systems whith limited memory and low computing power. +* +* As many operators have begun to commercially deploy IMS, the relevance of using SigComp to lower bandwidth usage will come quickly. +* In my own opinion I think that most operators (especially those using RCS) will question how to reduce SIP signaling (registration, billing, presence, messaging …) +* bandwidth usage (who will pay bits?). +* These questions will especially concern using SIP (or all other text-based protocols) in wireless handsets as part of 2.5G, 3G and 4G cellular networks. +* +* SigComp stands for Signaling Compression and has been defined in <a href="http://www.ietf.org/rfc/rfc3320.txt">RFC 3320</a> by the Internet Engineering Task Force (IETF) ROHC working group. +* <br> <br> +* +* @image html SigComp_Architecture.png "SigComp Architecture" +* +* Many application protocols used for multimedia communications are text-based and engineered for bandwidth rich links. As a result the messages have not been optimized in +* terms of size. For example, typical IMS/SIP messages range from a few hundred bytes up to two thousand bytes or more. For this reason, SigComp is mandatory for +* 3GPP IMS netwoks and <a href="http://en.wikipedia.org/wiki/Push_to_Talk_over_Cellular">PoC systems</a>. +* +* SigComp could also be useful for RCS (Rich Communication Suite) networks because of the size of the SIP packets (more than three thousand bytes for presence publication). +* Using SigComp in IMS/RCS context will reduce the round-trip over slow radio links. +* +* @par Supported OS +* +* - Windows XX/Vista (Visual Studio 2005/2008 or Mingw32) +* - Windows Mobile 5 and later (Visual Studio 2005/2008 or Mingw32ce/cegcc toolchain) +* - Symbian S60 (Carbide.c++ v2.0 with S60_3rd_FP2_SDK_v1.1) +* - Google Android +* - Mac OS X, iPhone (Xcode) +* - All Linux, FreeBSD, ... (GCC 4.x) +* +* +* @par FEATURES +* +* The goal of this project is to provide a SigComp framework which: +* +* - Could be used as an external API or Framework +* - Highly portable (Coded in ANSI-C without any external dependencies) +* - Easily configurable (memory usage, priorities in static dictionaries, stateful/stateless modes, dynamic/static/shared compression types …) +* - Easy to integrate with any existing SIP/IMS stack, Proxy-CSCF, PoC client … +* - Allow to easily plug your own compressor (DEFLATE – RFC 1951- will be the default) +* - +* - Robust +* - Efficiently run on mobile handsets (small footprint) +* - Use small memory (UDVM decompression) +* - Run fast without high CPU usage +* - Supports both TCP and UDP compression modes +* - Thread-safe +* +* @par COMPLIANCE +* +* - <a href="http://www.ietf.org/rfc/rfc3320.txt">RFC 3320</a>: Signaling Compression (SigComp) +* - <a href="http://www.ietf.org/rfc/rfc3321.txt">RFC 3321</a>: Signaling Compression (SigComp) - Extended Operations +* - <a href="http://www.ietf.org/rfc/rfc3485.txt">RFC 3485</a>: The Session Initiation Protocol (SIP) and Session Description Protocol (SDP) Static Dictionary for Signaling Compression (SigComp) +* - <a href="http://www.ietf.org/rfc/rfc4077.txt">RFC 4077</a>: A Negative Acknowledgement Mechanism for Signaling Compression +* - <a href="http://www.ietf.org/rfc/rfc4464.txt">RFC 4464</a>: Signaling Compression (SigComp) Users' Guide +* - <a href="http://www.ietf.org/rfc/rfc4465.txt">RFC 4465</a>: Signaling Compression (SigComp) Torture Tests +* - <a href="http://www.ietf.org/rfc/rfc4896.txt">RFC 4896</a>: Signaling Compression (SigComp) Corrections and Clarifications +* - <a href="http://www.ietf.org/rfc/rfc5049.txt">RFC 5049</a>: Applying Signaling Compression (SigComp) to the Session Initiation Protocol (SIP) +* - <a href="http://www.ietf.org/rfc/rfc5112.txt">RFC 5112</a>: The Presence-Specific Static Dictionary for Signaling Compression (Sigcomp) +* - <a href="http://www.ietf.org/rfc/rfc1662.txt">RFC 1662</a>: PPP in HDLC-like Framing +* - <a href="http://www.ietf.org/rfc/rfc1951.txt">RFC 1951</a>: DEFLATE Compressed Data Format Specification version +* - <a href="http://www.ietf.org/rfc/rfc3174.txt">RFC 3174</a>: US Secure Hash Algorithm 1 (SHA1) +* - 3GPP TR23.979 Annex C: Required SigComp performance +* +* @par Getting started +* +* - @ref tcomp_udp_compression_page +* - @ref tcomp_udp_decompression_page +*/ + +/** @page tcomp_udp_compression_page SigComp UDP compression +* It is easy to compress SIP a message and send it over UDP connection. The compression can be safely done in multithreaded appilaction because +* <a href ="http://doubango.org/API/tinySigComp/">tinySigComp</a> is thread-safe. +* You need <a href ="http://doubango.org/API/tinySAK/">tinySAK</a> in order to compile the code below. +* +* Include header files: +* @code +* #include "tsk_debug.h" // tinySAK debugging functions. +* #include "tcomp_manager.h" // tinySigComp API functions. +* @endcode +* +* Compartment Identifier: Used in SIP messages (sigomp-id) and tinySigComp to allocate/deallocate memory associated +* to a compartment. +* @code +* #define COMPARTMENT_ID "urn:uuid:2e5fdc76-00be-4314-8202-1116fa82a475" +* @endcode +* +* Preparation: +* @code +* #define MAX_BUFFER_SIZE 0xFFFF +* +* int i = 0; +* tsk_size_t outLen = 0; +* tcomp_result_t *result = 0; +* char outputBuffer[MAX_BUFFER_SIZE]; +* +* tcomp_manager_handle_t *manager = 0; + +* // Create SigComp manager +* manager = TCOMP_MANAGER_CREATE(); + +* // Add SIP/Presence dictionnaries (not mandatory) +* tcomp_manager_addSipSdpDictionary(manager); +* tcomp_manager_addPresenceDictionary(manager); + +* // Create result object and set compartment id --> It is recomanded to use one result object per manager. +* result = TCOMP_RESULT_CREATE(); +* tcomp_result_setCompartmentId(result, COMPARTMENT_ID, strlen(COMPARTMENT_ID)); + +* // Set user parameters (not mandatory) +* tcomp_manager_setDecompression_Memory_Size(manager, 8192); +* tcomp_manager_setCycles_Per_Bit(manager, 64); +* tcomp_manager_setState_Memory_Size(manager, 8192); +* +* @endcode +* Compress one or several messages using the code below: +* @code +* // Compress the SIP message +* outLen = tcomp_manager_compress(manager, +* COMPARTMENT_ID, strlen(COMPARTMENT_ID), // Compartment +* "REGISTER ...", strlen("REGISTER ..."), // Sip message to compress and it's size +* outputBuffer, sizeof(outputBuffer), // The ouptut buffer and it's size +* FALSE // Indicates whether to compress as stream (SCTP, TCP...) message or not +* ); +* +* if(outLen){ +* // send SigComp message over UDP connection +* sendto(sock, outputBuffer, outLen , 0, (SOCKADDR *)address, sizeof(address)); +* } +* else{ +* // MUST never happen. +* } +* @endcode +* To safely release all resources: +* @code +* // Close the compartment +* tcomp_manager_closeCompartment(manager, COMPARTMENT_ID, strlen(COMPARTMENT_ID)); +* // Delete the result object +* TSK_OBJECT_SAFE_FREE(result); +* // Delete the manager +* TSK_OBJECT_SAFE_FREE(manager); +* @endcode +*/ + + +/** @page tcomp_udp_decompression_page SigComp UDP decompression +* Decompression is as easy as compression (thread-safe). +*/
\ No newline at end of file diff --git a/tinySIGCOMP/src/tcomp.h b/tinySIGCOMP/src/tcomp.h new file mode 100644 index 0000000..a49a9de --- /dev/null +++ b/tinySIGCOMP/src/tcomp.h @@ -0,0 +1,39 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp.h + * @brief SIGCOMP (RFC 3320) Implementation for 2.5G, 3G and 4G cellular networks. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ + +#ifndef _TINYSIGCOMPP_TCOMP_H_ +#define _TINYSIGCOMPP_TCOMP_H_ + +#include "tinysigcomp_config.h" + +TCOMP_BEGIN_DECLS +TCOMP_END_DECLS + +#endif /* _TINYSIGCOMPP_TCOMP_H_ */ diff --git a/tinySIGCOMP/src/tcomp_buffer.c b/tinySIGCOMP/src/tcomp_buffer.c new file mode 100644 index 0000000..b7bfd4d --- /dev/null +++ b/tinySIGCOMP/src/tcomp_buffer.c @@ -0,0 +1,661 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_buffer.c + * @brief SigComp Buffer. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_buffer.h" +#include "tsk_binaryutils.h" +#include "tsk_memory.h" +#include "tsk_debug.h" + +#include <string.h> + +/** SigComp buffer. +*/ +typedef struct tcomp_buffer_s +{ + TSK_DECLARE_OBJECT; + + tsk_size_t size; /**< The size of the buffer */ + uint8_t* lpbuffer; /**< Pointer to the buffer */ + tsk_size_t index_bytes; /**< Bytes (8bit size) cursor */ + tsk_size_t index_bits; /**< Bits (1-bit size) cursor */ + unsigned owner:1; /**< Indicates whether we are the owner of the buffer or not (external buffer) */ + uint8_t P_BIT; /**< P-BIT controller. */ +} +tcomp_buffer_t; + + +tcomp_buffer_handle_t* tcomp_buffer_create(const void* data, tsk_size_t len) +{ + tcomp_buffer_t* buffer; + if((buffer = tsk_object_new(tcomp_buffer_def_t))){ + buffer->owner = tsk_true; + // The P-bit controls the order in which bits are passed from the dispatcher to the INPUT instructions. + buffer->P_BIT = TCOMP_P_BIT_MSB_TO_LSB; + if(data && len){ + tcomp_buffer_appendBuff(buffer, data, len); + } + } + return buffer; +} + +tcomp_buffer_handle_t* tcomp_buffer_create_null() +{ + return tcomp_buffer_create(tsk_null, 0); +} + +/**Compares two sigomp buffers. +* @param handle1 First handle to compare. +* @param handle2 Second handle to compare. +* @retval @a tsk_true if the two handles are equals and @a tsk_false otherwise. +*/ +tsk_bool_t tcomp_buffer_equals(const tcomp_buffer_handle_t* handle1, const tcomp_buffer_handle_t* handle2) +{ + if( tcomp_buffer_getSize(handle1) == tcomp_buffer_getSize(handle2) ){ + return tcomp_buffer_startsWith(handle1, handle2); + } + + return tsk_false; +} + + +/**Checks if the first internal buffer starts with the second handle internal buffer. +* @param handle1 First handle +* @param handle2 Second handle +* @retval Returns @a tsk_true if the first internal buffer starts with the second handle internal buffer and @a tsk_false otherwise. +*/ +tsk_bool_t tcomp_buffer_startsWith(const tcomp_buffer_handle_t* handle1, const tcomp_buffer_handle_t* handle2) /*const*/ +{ + tsk_size_t i; + tcomp_buffer_t* buffer1 = (tcomp_buffer_t*)handle1; + tcomp_buffer_t* buffer2 = (tcomp_buffer_t*)handle2; + + if(buffer1->size < buffer2->size){ + return tsk_false; + } + + for(i = 0; i< buffer2->size; i++){ + if(buffer1->lpbuffer[i] != buffer2->lpbuffer[i]){ + return tsk_false; + } + } + return tsk_true; +} + +/**Gets a readonly pointer to the internal buffer. +* @param handle The handle for which to get the internal buffer. +* @param position Position pointer +* @retval Pointer to the internal buffer. +*/ +const uint8_t* tcomp_buffer_getReadOnlyBufferAtPos(const tcomp_buffer_handle_t* handle, tsk_size_t position)/*const*/ +{ + if(handle){ + return (((tcomp_buffer_t*)handle)->lpbuffer + position); + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle"); + } + + return tsk_null; +} + +/**Gets a read/write pointer to the internal buffer. +* @param handle The handle for which to get the internal buffer. +* @param position Position pointer +* @retval Pointer to the internal buffer. +*/ +uint8_t* tcomp_buffer_getBufferAtPos(const tcomp_buffer_handle_t* handle, tsk_size_t position) +{ + if(handle){ + if(position && ((tcomp_buffer_t*)handle)->size <= position){ + TSK_DEBUG_ERROR("%u <= %u", ((tcomp_buffer_t*)handle)->size, position); + return tsk_null; + } + return (((tcomp_buffer_t*)handle)->lpbuffer + position); + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle"); + } + + return tsk_null; +} + + +/** Gets the internal buffer size +* @retval The size of the internal buffer +*/ +tsk_size_t tcomp_buffer_getSize(const tcomp_buffer_handle_t* handle) /*const*/ +{ + if(handle){ + return ((tcomp_buffer_t*)handle)->size; + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle"); + } + + return 0; +} + +/**Gets the remainning bits. +* @param handle The handle for which to get the remaining bits. +*/ +tsk_size_t tcomp_buffer_getRemainingBits(const tcomp_buffer_handle_t* handle) /*const*/ +{ + if(handle){ + tcomp_buffer_t* buffer = (tcomp_buffer_t*)handle; + tsk_ssize_t result = ((buffer->size * 8) - ((buffer->index_bytes * 8) + buffer->index_bits)); + return (result < 0) ? 0: result; + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle"); + } + + return 0; +} + +/**Reads @a size bytes. +* @param handle The handle for which to read bytes. +* @param length Number of bytes to read. +* @retval Pointer to the resulting buffer. +*/ +uint8_t* tcomp_buffer_readBytes(tcomp_buffer_handle_t* handle, tsk_size_t length) +{ + if(handle){ + tcomp_buffer_t* buffer = (tcomp_buffer_t*)handle; + tsk_size_t old_index; + + if((buffer->index_bytes + length) > (buffer->size)) { + return tsk_null; + } + + old_index = buffer->index_bytes; + buffer->index_bytes += length; + + return tcomp_buffer_getBufferAtPos(handle, old_index); + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle"); + } + + return tsk_null; +} + +/**Reads the internal buffer from LSB to MSB as per RFC 3320 subclause 8.2. +* @param handle The SigComp handle holding the internal buffer to read. +* @param length The length of the buffer to read. +* @retval All bits as a 2-bytes integer value +*/ +uint32_t tcomp_buffer_readLsbToMsb(tcomp_buffer_handle_t* handle, tsk_size_t length) +{ + // UDV Memory is always MSB first + // MSB <-- LSB + // FIXME: use mask + if(handle) + { + tcomp_buffer_t* buffer = (tcomp_buffer_t*)handle; + uint8_t pos = 0; + char* end; + uint32_t result_val = 0; + char result_str[16]; memset(result_str, 0, 16); + while(pos < length){ + result_str[pos++] = (buffer->lpbuffer[buffer->index_bytes] + &(1 << (buffer->index_bits))) ? '1' : '0'; + if(++buffer->index_bits == 8){ + buffer->index_bytes++; + buffer->index_bits = 0; + } + } + + end = (result_str+length); + result_val = (uint32_t)strtol(result_str, &end, 2); + + return result_val; + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle"); + } + + return 0; +} + +/**Reads the internal buffer from MSB to LSB as per RFC 3320 subclause 8.2. +* @param handle The SigComp handle holding the internal buffer to read. +* @param length The length of the buffer to read. +* @retval All bits as a 2-bytes integer value +*/ +uint32_t tcomp_buffer_readMsbToLsb(tcomp_buffer_handle_t* handle, tsk_size_t length) +{ + // UDV Memory is always MSB first + // MSB --> LSB + // FIXME: use mask + if(handle){ + tcomp_buffer_t* buffer = (tcomp_buffer_t*)handle; + uint8_t pos = 0; + char* end; + uint32_t result_val = 0; + char result_str[16]; memset(result_str, 0, 16); + + while(pos < length){ + result_str[pos++] = (buffer->lpbuffer[buffer->index_bytes] + &(128 >> (buffer->index_bits))) ? '1' : '0'; + if(++buffer->index_bits == 8){ + buffer->index_bytes++; + buffer->index_bits = 0; + } + } + + end = (result_str + length); + result_val = (uint32_t)strtol(result_str, &end, 2); + + return result_val; + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle"); + } + + return 0; +} + +/**Discards bits as per RFC 3320 subclause 8.2. +* @param handle SigComp handle holding the internal buffer. +*/ +void tcomp_buffer_discardBits(tcomp_buffer_handle_t* handle) +{ + if(handle){ + tcomp_buffer_t* buffer = (tcomp_buffer_t*)handle; + if(buffer->index_bits){ + buffer->index_bits=0; + buffer->index_bytes++; + } + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle"); + } +} + +/**Discards last bytes as per RFC 3320 subclause 8.2. +* @param handle SigComp handle holding the internal buffer. +* @param count The number of bytes to discard. +*/ +void tcomp_buffer_discardLastBytes(tcomp_buffer_handle_t* handle, uint32_t count) +{ + if(handle){ + tcomp_buffer_t* buffer = (tcomp_buffer_t*)handle; + if(buffer->size > count){ + buffer->size -= count; + } + else{ + tcomp_buffer_freeBuff(handle); + } + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle"); + } +} + +/**Allocs the internal buffer. +* @param handle SigComp handle holding the internal buffer to alloc. +* @param size Number of bytes to allocate. +*/ +void tcomp_buffer_allocBuff(tcomp_buffer_handle_t* handle, tsk_size_t size) +{ + if(handle){ + tcomp_buffer_t* buffer = (tcomp_buffer_t*)handle; + if(!buffer->owner){ + TSK_DEBUG_ERROR("The SigComp is not the owner of the internal buffer to alloc."); + return; + } + if(!size){ + TSK_DEBUG_WARN("Cannot allocate zero bytes."); + return; + } + buffer->index_bits = buffer->index_bytes = 0; + buffer->size = 0; + if((buffer->lpbuffer = tsk_realloc(buffer->lpbuffer, size))){ + buffer->size = size; + } + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle"); + } +} + +/**Adds a buffer as a reference (not owned). +* @param handle SigComp handle holding the internal buffer. +* @param externalBuff THe external buffer to reference. +* @param size The size of the external buffer. +*/ +void tcomp_buffer_referenceBuff(tcomp_buffer_handle_t* handle, uint8_t* externalBuff, tsk_size_t size) +{ + if(handle){ + tcomp_buffer_t* buffer = (tcomp_buffer_t*)handle; + if(buffer->size && buffer->owner){ + TSK_DEBUG_ERROR("The SigComp handle already hold an internal buffer."); + return; + } + + buffer->size = size; + buffer->lpbuffer = externalBuff; + buffer->index_bytes = 0; + buffer->index_bits = 0; + buffer->owner = 0; + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle"); + } +} + +/**Appends data to our internal buffer. +* @param handle The handle to the SigComp buffer. +* @param data Data to append to our internal buffer. +* @param size The size of the data +* @retval @a tsk_true if succeed an @a tsk_false otherwise. +*/ +tsk_bool_t tcomp_buffer_appendBuff(tcomp_buffer_handle_t* handle, const void* data, tsk_size_t size) +{ + if(handle){ + tcomp_buffer_t* buffer = (tcomp_buffer_t*)handle; + tsk_size_t oldSize = buffer->size; + tsk_size_t newSize = (oldSize + size); + { + // realloc buffer + if(!buffer->size){ + buffer->lpbuffer = (uint8_t*)tsk_calloc(1, newSize); + } + else{ + buffer->lpbuffer = (uint8_t*)tsk_realloc(buffer->lpbuffer, newSize); + } + } + + if(!buffer->lpbuffer){ + return tsk_false; + } + + if(data){ + memcpy((buffer->lpbuffer+oldSize), data, size); + } + else{ + memset((buffer->lpbuffer+oldSize), 0, size); + } + + buffer->size = newSize; + return tsk_true; + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle"); + } + + return tsk_false; +} + +/**Removes @a size bytes from the internal buffer. +* @param handle SigComp handle holding the internal buffer from which to remove bytes. +* @param pos The starting position from which to start removing bytes +* @param size The number of bytes to remove +* @retval @a tsk_true if succeed an @a tsk_false otherwise. +*/ +tsk_bool_t tcomp_buffer_removeBuff(tcomp_buffer_handle_t* handle, tsk_size_t pos, tsk_size_t size) +{ + if(handle){ + tcomp_buffer_t* buffer = (tcomp_buffer_t*)handle; + tsk_size_t oldSize, newSize; + + if(((pos + size) > buffer->size)) size = (buffer->size - pos); + memcpy((buffer->lpbuffer + pos), (buffer->lpbuffer + pos + size), (buffer->size - (pos + size))); + + oldSize = buffer->size; + newSize = (oldSize - size); + { + if(!(buffer->size)){ + buffer->lpbuffer = (uint8_t*)tsk_calloc(1, newSize); + } + else{ + buffer->lpbuffer = (uint8_t*)tsk_realloc(buffer->lpbuffer, newSize); + } + } + if(buffer->lpbuffer){ + buffer->size = newSize; + return tsk_true; + } + return tsk_false; + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle"); + } + + return tsk_false; +} + +/**Free the internal buffer. +* @param handle SigComp handle holding the internal buffer to free. +*/ +void tcomp_buffer_freeBuff(tcomp_buffer_handle_t* handle) +{ + if(handle){ + tcomp_buffer_t* buffer = (tcomp_buffer_t*)handle; + if(buffer->lpbuffer && buffer->size && buffer->owner) { + tsk_free((void**)&(buffer->lpbuffer)); + } + buffer->size = buffer->index_bytes = buffer->index_bits = 0; + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle"); + } +} + +/**Gets the bytes cursor position. +* @param handle SigComp handle holding the internal buffer. +* @retval The cursor position. +*/ +tsk_size_t* tcomp_buffer_getIndexBytes(const tcomp_buffer_handle_t* handle) +{ + if(handle){ + return &(((tcomp_buffer_t*)handle)->index_bytes); + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle"); + } + + return 0; +} + +/**Gets the bits cursor position. +* @param handle SigComp handle holding the internal buffer. +* @retval The cursor position. +*/ +tsk_size_t* tcomp_buffer_getIndexBits(const tcomp_buffer_handle_t* handle) +{ + if(handle){ + return &(((tcomp_buffer_t*)handle)->index_bits); + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle"); + } + + return tsk_null; +} + +/**Gets the P-bit controller value. +* The P-bit controls the order in which bits are passed from the dispatcher to the INPUT instructions. If set to 0, it indicates that +* the bits within an individual byte are passed to the INPUT instructions in MSB to LSB order. If it is set to 1, the bits are +* passed in LSB to MSB order. +* @param handle SigComp handle holding the internal buffer. +* @retval The P-Bit value. +*/ +uint8_t* tcomp_buffer_getP_BIT(const tcomp_buffer_handle_t* handle) +{ + if(handle){ + return &(((tcomp_buffer_t*)handle)->P_BIT); + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle"); + } + + return tsk_null; +} + +/**Creates a random HASH number. +*/ +uint64_t tcomp_buffer_createHash(const void *data, tsk_size_t len) +{ + if(!data || !len){ + TSK_DEBUG_ERROR("Null data."); + return 0; + } + { +#define PRIME_1 500237 +#define PRIME_2 700241 + uint64_t hash = 0; + uint8_t* strid = (uint8_t*)data; + + /* Generate Hash code from id */ + { + uint64_t b = PRIME_1, a = PRIME_2; + tsk_size_t i; + for(i = 0; i < len; strid++, i++) + { + hash = hash * a + (*strid); + a = a * b; + } + } + return hash; + +#undef PRIME_1 +#undef PRIME_2 + } +} + +/**Prints the internal buffer. +* @param handle SigComp handle holding the internal buffer to print. +* @param size The number of bytes to print. +*/ +void tcomp_buffer_nprint(const tcomp_buffer_handle_t* handle, tsk_ssize_t size) +{ +#if defined(_DEBUG) || defined(DEBUG) + + if(handle){ + tsk_size_t i, tsk_size_to_print; + tcomp_buffer_t* buffer = (tcomp_buffer_t*)handle; + tsk_size_to_print = (size<0) ? buffer->size : size; + + if( !tsk_size_to_print || !buffer->lpbuffer) return; + + for(i = 0; i < tsk_size_to_print; i+=2){ + char s[10]; + uint32_t value; + memset(s, 0, 10); + + if((i+1) == tsk_size_to_print){ + // last 2-byte lay in 1byte + value = buffer->lpbuffer[i]; +#if 0 + sprintf_s(s, 10, i?"%0.2x":"0x%0.2x", value); +#else + sprintf(s, i ? "%0.2x" : "0x%0.2x", value); +#endif + } + else{ + uint8_t *b_ptr = tcomp_buffer_getBufferAtPos(handle, i); + value = TSK_BINARY_GET_2BYTES(b_ptr); +#if 0 + sprintf_s(s, 10, i?"%0.4x":"0x%0.4x", value); +#else + sprintf(s, i?"%0.4x":"0x%0.4x", value); +#endif + } + printf("%s ", s); + } + printf("\n"); + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle"); + } +#endif +} + +/**Resets a sigcomp buffer. +* @param handle Handle holding the internal buffer to reset. +*/ +void tcomp_buffer_reset(tcomp_buffer_handle_t* handle) +{ + if(handle){ + tcomp_buffer_t* buffer = (tcomp_buffer_t*)handle; + + buffer->index_bytes = 0; + buffer->index_bits = 0; + if(buffer->lpbuffer){ + memset(buffer->lpbuffer, 0, buffer->size); + } + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle"); + } +} + + + + + + + + + + +//======================================================== +// SigComp buffer object definition +// +static tsk_object_t* tcomp_buffer_ctor(tsk_object_t *self, va_list * app) +{ + tcomp_buffer_t* buffer = self; + if(buffer){ + } + return self; +} + +static tsk_object_t* tcomp_buffer_dtor(tsk_object_t *self) +{ + tcomp_buffer_t* buffer = self; + if(buffer){ + tcomp_buffer_freeBuff(buffer); + } + else{ + TSK_DEBUG_ERROR("Null SigComp handle."); + } + + return self; +} + +static const tsk_object_def_t tcomp_buffer_def_s = +{ + sizeof(tcomp_buffer_t), + tcomp_buffer_ctor, + tcomp_buffer_dtor, + tsk_null +}; +const tsk_object_def_t *tcomp_buffer_def_t = &tcomp_buffer_def_s; + diff --git a/tinySIGCOMP/src/tcomp_buffer.h b/tinySIGCOMP/src/tcomp_buffer.h new file mode 100644 index 0000000..d89b691 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_buffer.h @@ -0,0 +1,90 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_buffer.h + * @brief SigComp Buffer + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#ifndef TCOMP_BUFFER_H +#define TCOMP_BUFFER_H + +#include "tinysigcomp_config.h" + +#include "tsk_object.h" + + +TCOMP_BEGIN_DECLS + +#define TCOMP_P_BIT_MSB_TO_LSB 0 +#define TCOMP_P_BIT_LSB_TO_MSB 1 + +/**Sigcomp Buffer handle +*/ +typedef void tcomp_buffer_handle_t; + +tcomp_buffer_handle_t* tcomp_buffer_create(const void* data, tsk_size_t len); +tcomp_buffer_handle_t* tcomp_buffer_create_null(); + +tsk_bool_t tcomp_buffer_equals(const tcomp_buffer_handle_t* handle1, const tcomp_buffer_handle_t* handle2); +tsk_bool_t tcomp_buffer_startsWith(const tcomp_buffer_handle_t* handle1, const tcomp_buffer_handle_t* handle2) /*const*/; + +const uint8_t* tcomp_buffer_getReadOnlyBufferAtPos(const tcomp_buffer_handle_t* handle, tsk_size_t position) /*const*/; +#define tcomp_buffer_getReadOnlyBuffer(buffer) tcomp_buffer_getReadOnlyBufferAtPos(buffer, 0) + +TINYSIGCOMP_API uint8_t* tcomp_buffer_getBufferAtPos(const tcomp_buffer_handle_t* handle, tsk_size_t position); +#define tcomp_buffer_getBuffer(handle) tcomp_buffer_getBufferAtPos(handle, 0) + +TINYSIGCOMP_API tsk_size_t tcomp_buffer_getSize(const tcomp_buffer_handle_t* handle) /*const*/; +tsk_size_t tcomp_buffer_getRemainingBits(const tcomp_buffer_handle_t* handle) /*const*/; + +uint8_t* tcomp_buffer_readBytes(tcomp_buffer_handle_t* handle, tsk_size_t size); +uint32_t tcomp_buffer_readLsbToMsb(tcomp_buffer_handle_t* handle, tsk_size_t length); +uint32_t tcomp_buffer_readMsbToLsb(tcomp_buffer_handle_t* handle, tsk_size_t length); +void tcomp_buffer_discardBits(tcomp_buffer_handle_t* handle); +void tcomp_buffer_discardLastBytes(tcomp_buffer_handle_t* handle, uint32_t count); + +void tcomp_buffer_allocBuff(tcomp_buffer_handle_t* handle, tsk_size_t size); +void tcomp_buffer_referenceBuff(tcomp_buffer_handle_t* handle, uint8_t* externalBuff, tsk_size_t size); +tsk_bool_t tcomp_buffer_appendBuff(tcomp_buffer_handle_t* handle, const void* data, tsk_size_t size); +tsk_bool_t tcomp_buffer_removeBuff(tcomp_buffer_handle_t* handle, tsk_size_t pos, tsk_size_t size); +void tcomp_buffer_freeBuff(tcomp_buffer_handle_t* handle); + +tsk_size_t* tcomp_buffer_getIndexBytes(const tcomp_buffer_handle_t* handle); +tsk_size_t* tcomp_buffer_getIndexBits(const tcomp_buffer_handle_t* handle); + +uint8_t* tcomp_buffer_getP_BIT(const tcomp_buffer_handle_t* handle); + +uint64_t tcomp_buffer_createHash(const void *data, tsk_size_t len); + +void tcomp_buffer_nprint(const tcomp_buffer_handle_t* handle, tsk_ssize_t size); +#define tcomp_buffer_print(handle) tcomp_buffer_nprint(handle, -1) + +void tcomp_buffer_reset(tcomp_buffer_handle_t* handle); + +TINYSIGCOMP_GEXTERN const tsk_object_def_t *tcomp_buffer_def_t; + +TCOMP_END_DECLS + +#endif /* TCOMP_BUFFER_H */ diff --git a/tinySIGCOMP/src/tcomp_compartment.c b/tinySIGCOMP/src/tcomp_compartment.c new file mode 100644 index 0000000..5d774a2 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_compartment.c @@ -0,0 +1,552 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_compartment.c + * @brief SigComp compartment. + * An application-specific grouping of messages that relate to a peer endpoint. Depending on the signaling protocol, this grouping may + * relate to application concepts such as "session", "dialog", "connection", or "association". The application allocates state + * memory on a per-compartment basis, and determines when a compartment should be created or closed. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_compartment.h" + +#include "tsk_debug.h" + +#include <assert.h> + +static void _tcomp_compartment_freeState(tcomp_compartment_t *compartment, tcomp_state_t **lpState); + +tcomp_compartment_t* tcomp_compartment_create(uint64_t id, uint32_t sigCompParameters, tsk_bool_t useOnlyACKedStates) +{ + tcomp_compartment_t *compartment; + if((compartment = tsk_object_new(tcomp_compartment_def_t))){ + + + /* + +---+---+---+---+---+---+---+---+ + | cpb | dms | sms | + +---+---+---+---+---+---+---+---+ + | SigComp_version | + +---+---+---+---+---+---+---+---+ + */ + + // I always assume that remote params are equal to local params + + /* Identifier */ + compartment->identifier = id; + + /* Remote parameters */ + compartment->remote_parameters = tcomp_params_create(); + tcomp_params_setParameters(compartment->remote_parameters, sigCompParameters); + + /* Local parameters */ + compartment->local_parameters = tcomp_params_create(); + tcomp_params_setParameters(compartment->local_parameters, sigCompParameters); + + /* Total size */ + compartment->total_memory_size = compartment->total_memory_left = compartment->local_parameters->smsValue; + + /* Empty list. */ + compartment->nacks = tsk_list_create(); + + /* Empty list. */ + compartment->local_states = tsk_list_create(); + + /* Whether to use only ACKed states */ + compartment->useOnlyACKedStates = useOnlyACKedStates; + } + else{ + TSK_DEBUG_ERROR("Null Compartment"); + } + + return compartment; +} + +int tcomp_compartment_setUseOnlyACKedStates(tcomp_compartment_t* self, tsk_bool_t useOnlyACKedStates) +{ + if(!self){ + TSK_DEBUG_ERROR("Invalid parameter"); + return -1; + } + self->useOnlyACKedStates = useOnlyACKedStates; + return 0; +} + +/**Sets remote parameters +*/ +void tcomp_compartment_setRemoteParams(tcomp_compartment_t *compartment, tcomp_params_t *lpParams) +{ + if(!compartment){ + TSK_DEBUG_ERROR("Invalid parameter"); + return; + } + + /* CPB||DMS||SMS [1-BYTE] */ + if(tcomp_params_hasCpbDmsSms(lpParams)){ + tcomp_params_setCpbCode(compartment->remote_parameters, lpParams->cpbCode); + tcomp_params_setDmsCode(compartment->remote_parameters, lpParams->dmsCode); + tcomp_params_setSmsCode(compartment->remote_parameters, lpParams->smsCode); + } + + /* SigComp version */ + if(lpParams->SigComp_version){ + compartment->remote_parameters->SigComp_version = lpParams->SigComp_version; + } + + /* + * Returned states + * FIXME: check states about quota + * FIXME: not tic tac + * FIXME: what about returned feedback? + */ + if(lpParams->returnedStates && tcomp_buffer_getSize(lpParams->returnedStates)){ + TSK_OBJECT_SAFE_FREE(compartment->remote_parameters->returnedStates); + /* swap */ + compartment->remote_parameters->returnedStates = lpParams->returnedStates; + lpParams->returnedStates = 0; + } +} + +/**Sets requested feedback +*/ +void tcomp_compartment_setReqFeedback(tcomp_compartment_t *compartment, tcomp_buffer_handle_t *feedback) +{ + if(!compartment){ + TSK_DEBUG_ERROR("Invalid parameter."); + return; + } + + tsk_safeobj_lock(compartment); + + /* Delete old */ + TSK_OBJECT_SAFE_FREE(compartment->lpReqFeedback); + + compartment->lpReqFeedback = tcomp_buffer_create(tcomp_buffer_getBuffer(feedback), tcomp_buffer_getSize(feedback)); + + tsk_safeobj_unlock(compartment); +} + +/**Sets returned feedback +*/ +void tcomp_compartment_setRetFeedback(tcomp_compartment_t *compartment, tcomp_buffer_handle_t *feedback) +{ + if(!compartment){ + TSK_DEBUG_ERROR("Invalid parameter."); + return; + } + + tsk_safeobj_lock(compartment); + + // Delete old + TSK_OBJECT_SAFE_FREE(compartment->lpRetFeedback); + + compartment->lpRetFeedback = tcomp_buffer_create(tcomp_buffer_getBuffer(feedback), tcomp_buffer_getSize(feedback)); + + /* + * ACK STATE ==> Returned feedback contains the partial state-id. + */ + if(compartment->compressorData/* && !compartment->compressorData_isStream*/){ + tcomp_buffer_handle_t *stateid = tcomp_buffer_create(tcomp_buffer_getBufferAtPos(feedback, 1), tcomp_buffer_getSize(feedback)-1); + compartment->ackGhost(compartment->compressorData, stateid); + TSK_OBJECT_SAFE_FREE(stateid); + } + + tsk_safeobj_unlock(compartment); +} + +/**Clears are compartment from the history. +*/ +void tcomp_compartment_clearStates(tcomp_compartment_t *compartment) +{ + if(!compartment){ + TSK_DEBUG_ERROR("NULL sigcomp compartment."); + return; + } + + tsk_safeobj_lock(compartment); + + tsk_list_clear_items(compartment->local_states); + compartment->total_memory_left = compartment->total_memory_size; + + tsk_safeobj_unlock(compartment); +} + +/**Removes a state from the compartment by priority. +*/ +void tcomp_compartment_freeStateByPriority(tcomp_compartment_t *compartment) +{ + tcomp_state_t *lpState; + tsk_list_item_t *item; + + if(!compartment){ + TSK_DEBUG_ERROR("Invalid parameter."); + return; + } + + tsk_safeobj_lock(compartment); + + lpState = 0; + item = 0; + + /* + * The order in which the existing state items are freed is determined by the state_retention_priority, which is set when the + * state items are created. The state_retention_priority of 65535 is reserved for locally available states; these states must always be + * freed first. Apart from this special case, states with the lowest state_retention_priority are always freed first. In the event of + * a tie, then the state item created first in the compartment is also the first to be freed. + */ + tsk_list_foreach(item, compartment->local_states){ + tcomp_state_t *curr = item->data; + + if(!curr){ + continue; + } + + /* Local state ? */ + if(curr->retention_priority == 65535){ + lpState = curr; + break; + } + + /* Lower priority? */ + if(!lpState || curr->retention_priority < lpState->retention_priority){ + lpState = curr; + continue; + } + } + + if(lpState){ + compartment->total_memory_left += TCOMP_GET_STATE_SIZE(lpState); + tsk_list_remove_item_by_data(compartment->local_states, lpState); + } + + tsk_safeobj_unlock(compartment); +} + +/**Removes a state from the compartment. +*/ +static void _tcomp_compartment_freeState(tcomp_compartment_t *compartment, tcomp_state_t **lpState) +{ + if(!compartment){ + TSK_DEBUG_ERROR("Invalid parameter."); + return; + } + + tsk_safeobj_lock(compartment); + + compartment->total_memory_left += TCOMP_GET_STATE_SIZE(*lpState); + tsk_list_remove_item_by_data(compartment->local_states, *lpState); + *lpState = tsk_null; + + tsk_safeobj_unlock(compartment); +} + +/**Remove states +* Called by UDVM after STATE_FREE instruction +*/ +void tcomp_compartment_freeStates(tcomp_compartment_t *compartment, tcomp_tempstate_to_free_t **tempStates, uint8_t size) +{ + uint8_t i; + tcomp_state_t *lpState; + tsk_list_item_t *item; + + if(!compartment){ + TSK_DEBUG_ERROR("Invalid parameter."); + return; + } + + if(!tempStates || !size){ + return; + } + + lpState = tsk_null; + item = tsk_null; + + for (i = 0; i < size; i++){ + /* lock */ + tsk_safeobj_lock(compartment); + + tsk_list_foreach(item, compartment->local_states){ + tcomp_state_t *curr = item->data; + + /* Compare current state with provided partial state */ + if(tcomp_buffer_startsWith(curr->identifier, tempStates[i]->identifier)){ + /* + * If more than one state item in the compartment matches the partial state identifier, + * then the state free request is ignored. + */ + TSK_DEBUG_INFO("Request to free state with usage_count=%d", curr->usage_count); + if(tcomp_state_dec_usage_count(curr) == 0){ + if(lpState){ + lpState = tsk_null; + break; + } + else{ + lpState = curr; + } + } + } + } + + /* unlock */ + tsk_safeobj_unlock(compartment); + + if(lpState){ + _tcomp_compartment_freeState(compartment, &lpState); + } + } +} + +/**Adds a state to the compartment. +*/ +void tcomp_compartment_addState(tcomp_compartment_t *compartment, tcomp_state_t **lpState) +{ + tsk_list_item_t *item; + int32_t usage_count = 0; + const tcomp_buffer_handle_t *identifier; + if(!compartment || !lpState || !*lpState){ + TSK_DEBUG_ERROR("Invalid parameter."); + return; + } + + tsk_safeobj_lock(compartment); + + tcomp_state_makeValid(*lpState); + identifier = (*lpState)->identifier; + + // check if the state exist + tsk_list_foreach(item, compartment->local_states){ + if(tcomp_buffer_startsWith(((tcomp_state_t*)item->data)->identifier, (*lpState)->identifier)){ + *lpState = ((tcomp_state_t*)item->data); // override + usage_count = tcomp_state_inc_usage_count(*lpState); + break; + } + } + + if(usage_count == 0){ // alread exist? + compartment->total_memory_left -= TCOMP_GET_STATE_SIZE(*lpState); + usage_count = tcomp_state_inc_usage_count(*lpState); + tsk_list_push_back_data(compartment->local_states, ((void**) lpState)); + } + + TSK_DEBUG_INFO("SigComp - Add new state with usage_count=%d and id=", usage_count); + tcomp_buffer_print(identifier); + + *lpState = tsk_null; + + tsk_safeobj_unlock(compartment); +} + +/**Finds a state. +*/ +uint32_t tcomp_compartment_findState(tcomp_compartment_t *compartment, const tcomp_buffer_handle_t *partial_identifier, tcomp_state_t **lpState) +{ + uint32_t count = 0; + tsk_list_item_t *item; + + if(!compartment){ + TSK_DEBUG_ERROR("Invalid parameter"); + return 0; + } + + tsk_safeobj_lock(compartment); + + tsk_list_foreach(item, compartment->local_states){ + tcomp_state_t *curr = item->data; + + if(tcomp_buffer_startsWith(curr->identifier, partial_identifier)){ + *lpState = curr; // override + count++; + } + } + + tsk_safeobj_unlock(compartment); + + return count; +} + +/**Removes a Ghost state. +*/ +void tcomp_compartment_freeGhostState(tcomp_compartment_t *compartment) +{ + if(!compartment){ + TSK_DEBUG_ERROR("Invalid parameter."); + return; + } + + tsk_safeobj_lock(compartment); + + if(compartment->compressorData){ + compartment->freeGhostState(compartment->compressorData); + } + else{ + TSK_DEBUG_WARN("No compression data to free."); + } + + tsk_safeobj_unlock(compartment); +} + +/**Adds a NACK to the compartment. +*/ +void tcomp_compartment_addNack(tcomp_compartment_t *compartment, const uint8_t nackId[TSK_SHA1_DIGEST_SIZE]) +{ + tcomp_buffer_handle_t *id; + + if(!compartment){ + TSK_DEBUG_ERROR("Invalid parameter."); + return; + } + +#if 0 + { + int i; + TSK_DEBUG_INFO("Save NACK with id:"); + for(i = 0; i < TSK_SHA1_DIGEST_SIZE; ++i){ + printf("%x ", nackId[i]); + } + printf("\n"); + } +#endif + + tsk_safeobj_lock(compartment); + + if(compartment->nacks_history_count >= NACK_MAX_HISTORY_SIZE){ + tsk_list_remove_last_item(compartment->nacks); + compartment->nacks_history_count--; + } + + id = tcomp_buffer_create(nackId, TSK_SHA1_DIGEST_SIZE); + tsk_list_push_back_data(compartment->nacks, ((void**) &id)); + compartment->nacks_history_count++; + + tsk_safeobj_unlock(compartment); +} + +/**Checks if the NACK exist. +*/ +tsk_bool_t tcomp_compartment_hasNack(tcomp_compartment_t *compartment, const tcomp_buffer_handle_t *nackId) +{ + tsk_bool_t ret = tsk_false; + tsk_list_item_t *item; + + if(!compartment){ + TSK_DEBUG_ERROR("Invalid parameter."); + return tsk_false; + } + + tsk_safeobj_lock(compartment); + + item = tsk_null; + + tsk_list_foreach(item, compartment->nacks){ + tcomp_buffer_handle_t *curr = item->data; + + if(tcomp_buffer_equals(curr, nackId)){ + TSK_DEBUG_INFO("SigComp - Nack found."); + ret = tsk_true; + break; + } + } + + tsk_safeobj_unlock(compartment); + + return ret; +} + + + + + + + + + + +//======================================================== +// State object definition +// + +static tsk_object_t* tcomp_compartment_ctor(tsk_object_t* self, va_list * app) +{ + tcomp_compartment_t *compartment = self; + if(compartment){ + /* Initialize safeobject */ + tsk_safeobj_init(compartment); + } + + return self; +} + +static tsk_object_t* tcomp_compartment_dtor(tsk_object_t* self) +{ + tcomp_compartment_t *compartment = self; + if(compartment){ + /* Deinitialize safeobject */ + tsk_safeobj_deinit(compartment); + + /* Delete feedbacks */ + TSK_OBJECT_SAFE_FREE(compartment->lpReqFeedback); + TSK_OBJECT_SAFE_FREE(compartment->lpRetFeedback); + + /* Delete Nacks */ + TSK_OBJECT_SAFE_FREE(compartment->nacks); + + /* Delete Compressor data */ + TSK_OBJECT_SAFE_FREE(compartment->compressorData); + compartment->ackGhost = tsk_null; + compartment->freeGhostState = tsk_null; + + /* Delete params */ + TSK_OBJECT_SAFE_FREE(compartment->local_parameters); + TSK_OBJECT_SAFE_FREE(compartment->remote_parameters); + + /* Delete NACKS */ + TSK_OBJECT_SAFE_FREE(compartment->nacks); + + /* Delete local states */ + TSK_OBJECT_SAFE_FREE(compartment->local_states); + } + else{ + TSK_DEBUG_ERROR("Null Compartment"); + } + + return self; +} + +static int tcomp_compartment_cmp(const tsk_object_t *obj1, const tsk_object_t *obj2) +{ + const tcomp_compartment_t *compartment1 = obj1; + const tcomp_compartment_t *compartment2 = obj2; + int64_t res = (compartment1->identifier - compartment2->identifier); + return res > 0 ? (int)1 : (res < 0 ? (int)-1 : (int)0); +} + +static const tsk_object_def_t tsk_compartment_def_s = +{ + sizeof(tcomp_compartment_t), + tcomp_compartment_ctor, + tcomp_compartment_dtor, + tcomp_compartment_cmp +}; +const tsk_object_def_t *tcomp_compartment_def_t = &tsk_compartment_def_s; diff --git a/tinySIGCOMP/src/tcomp_compartment.h b/tinySIGCOMP/src/tcomp_compartment.h new file mode 100644 index 0000000..f15ee82 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_compartment.h @@ -0,0 +1,107 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_compartment.h + * @brief SIGCOMP compartment. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#ifndef TCOMP_COMPARTMENT_H +#define TCOMP_COMPARTMENT_H + +#include "tinysigcomp_config.h" + +#include "tcomp_types.h" +#include "tcomp_params.h" +#include "tcomp_compressordata.h" +#include "tcomp_result.h" + +#include "tsk_safeobj.h" +#include "tsk_object.h" +#include "tsk_sha1.h" + +TCOMP_BEGIN_DECLS + +typedef struct tcomp_compartment_s +{ + TSK_DECLARE_OBJECT; + + /* + * An identifier (in a locally chosen format) that uniquely references a compartment. + */ + uint64_t identifier; + + tcomp_states_L_t *local_states; + tcomp_params_t *remote_parameters; + tcomp_params_t *local_parameters; + uint32_t total_memory_size; + uint32_t total_memory_left; + + tcomp_buffer_handle_t *lpReqFeedback; + tcomp_buffer_handle_t *lpRetFeedback; + + TCOMP_DECLARE_COMPRESSORDATA; + + tcomp_buffers_L_t* nacks; + uint8_t nacks_history_count; + + tsk_bool_t useOnlyACKedStates; + + TSK_DECLARE_SAFEOBJ; +} +tcomp_compartment_t; + +tcomp_compartment_t* tcomp_compartment_create(uint64_t id, uint32_t sigCompParameters, tsk_bool_t useOnlyACKedStates); +int tcomp_compartment_setUseOnlyACKedStates(tcomp_compartment_t* self, tsk_bool_t useOnlyACKedStates); + +// +// SigComp Parameters +// +void tcomp_compartment_setRemoteParams(tcomp_compartment_t *compartment, tcomp_params_t *lpParams); +// +// Feedbacks +// +void tcomp_compartment_setReqFeedback(tcomp_compartment_t *compartment, tcomp_buffer_handle_t *feedback); +void tcomp_compartment_setRetFeedback(tcomp_compartment_t *compartment, tcomp_buffer_handle_t *feedback); + +void tcomp_compartment_clearStates(tcomp_compartment_t *compartment); +void tcomp_compartment_freeStateByPriority(tcomp_compartment_t *compartment); +void tcomp_compartment_freeStates(tcomp_compartment_t *compartment, tcomp_tempstate_to_free_t **tempStates, uint8_t size); +void tcomp_compartment_addState(tcomp_compartment_t *compartment, tcomp_state_t **lpState); +uint32_t tcomp_compartment_findState(tcomp_compartment_t *compartment, const tcomp_buffer_handle_t *partial_identifier, tcomp_state_t **lpState); +void tcomp_compartment_freeGhostState(tcomp_compartment_t *compartment); + + +// +// Nacks +// +void tcomp_compartment_addNack(tcomp_compartment_t *compartment, const uint8_t nackId[TSK_SHA1_DIGEST_SIZE]); +tsk_bool_t tcomp_compartment_hasNack(tcomp_compartment_t *compartment, const tcomp_buffer_handle_t *nackId); + + +TINYSIGCOMP_GEXTERN const tsk_object_def_t *tcomp_compartment_def_t; + +TCOMP_END_DECLS + +#endif /* TCOMP_COMPARTMENT_H */ diff --git a/tinySIGCOMP/src/tcomp_compressor.h b/tinySIGCOMP/src/tcomp_compressor.h new file mode 100644 index 0000000..6d71401 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_compressor.h @@ -0,0 +1,51 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_compressor.h + * @brief Compression function definition. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#ifndef TCOMP_COMPRESSOR_H +#define TCOMP_COMPRESSOR_H + +#include "tinysigcomp_config.h" +#include "tcomp_compartment.h" + +TCOMP_BEGIN_DECLS + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// @typedef int (*tcomp_compressor_compress_f)(tcomp_compartment_t *lpCompartment, +/// const void *input_ptr, tsk_size_t input_size, void *output_ptr, tsk_size_t *output_size, +/// int stream) +/// +/// @brief Function pointer definition for compression method. +//////////////////////////////////////////////////////////////////////////////////////////////////// +typedef tsk_bool_t (*tcomp_compressor_compress_f)(tcomp_compartment_t *lpCompartment, const void *input_ptr, tsk_size_t input_size, void *output_ptr, tsk_size_t *output_size, tsk_bool_t stream); + +#define TCOMP_COMPRESSOR_COMPRESS_F(self) ((tcomp_compressor_compress_f)(self)) + +TCOMP_END_DECLS + +#endif /* TCOMP_COMPRESSOR_H */ diff --git a/tinySIGCOMP/src/tcomp_compressor_deflate.c b/tinySIGCOMP/src/tcomp_compressor_deflate.c new file mode 100644 index 0000000..fcce528 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_compressor_deflate.c @@ -0,0 +1,218 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_compressor.h + * @brief SigComp Deflate compressor. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_compressor_deflate.h" +#include "tcomp_deflatedata.h" + +#include "tsk_debug.h" + +#include <string.h> + +#define TCOMP_MIN(a, b) (a < b ? a : b) + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// @brief Compress SIgComp message using deflate algorithm. +/// +/// @param [in,out] lpCompartment If non-null, the pointer to a compartment. +/// @param [in,out] input_ptr If non-null, the input pointer. +/// @param input_size Size of the input. +/// @param [in,out] output_ptr If non-null, the output pointer. +/// @param [in,out] output_size If non-null, size of the output. +/// @param stream The stream. +/// +/// @return . +//////////////////////////////////////////////////////////////////////////////////////////////////// + +tsk_bool_t tcomp_compressor_deflate_compress(tcomp_compartment_t *lpCompartment, const void *input_ptr, tsk_size_t input_size, void *output_ptr, tsk_size_t *output_size, tsk_bool_t stream) +{ +#define GET_OUTPUT_BUFFER_AT(position) (((uint8_t*)output_ptr) + position) + + tsk_bool_t result = tsk_true; + int stateChanged, stateful, windowBits, zret; + tcomp_deflatedata_t *deflatedata = 0; + tsk_size_t pointer = 0, state_len_index = 0, compressedDataLen; + uint8_t smsCode, *header; + + tsk_safeobj_lock(lpCompartment); + + /* Compression Data */ + if(!lpCompartment->compressorData){ + lpCompartment->compressorData = tcomp_deflatedata_create(stream, lpCompartment->useOnlyACKedStates); + if(!lpCompartment->compressorData){ + TSK_DEBUG_ERROR("Failed to create deflate compressor data."); + result = tsk_false; + goto bail; + } + else{ + lpCompartment->ackGhost = tcomp_deflatedata_ackGhost; + lpCompartment->freeGhostState = tcomp_deflatedata_freeGhostState; + lpCompartment->compressorData_isStream = stream; + } + } + + deflatedata = lpCompartment->compressorData; + + /* State memory size code */ + smsCode = TCOMP_MIN(lpCompartment->remote_parameters->smsCode, lpCompartment->remote_parameters->dmsCode); + if(lpCompartment->useOnlyACKedStates){ + stateful = (deflatedata->ghostState && tcomp_deflatedata_isStateful(deflatedata)); + } + else{ + stateful = !!deflatedata->ghostState; + } + + /* + * Init zLIB + */ + windowBits = ( smsCode - (stream ? 2 : 1) ) + 10; + windowBits = TSK_CLAMP(8, windowBits, 15); /* Because of zlib limitation (windowsize MUST be between 8 and 15) */ + if(windowBits != deflatedata->zWindowBits){ + /* Window size changed */ + tcomp_deflatedata_freeGhostState(deflatedata); + tcomp_deflatedata_zSetWindowBits(deflatedata, windowBits); + + if( !(result = tcomp_deflatedata_zReset(deflatedata)) ) { + goto bail; + } + } + else if(!deflatedata->ghostState){ + /* No ghost --> reset zlib */ + deflatedata->ghost_copy_offset = 0; + if( !(result = tcomp_deflatedata_zReset(deflatedata)) ) { + goto bail; + } + } + + stateful &= !!deflatedata->ghostState; + + /* + * SigComp headers + */ + header = GET_OUTPUT_BUFFER_AT(pointer++); + + + /* SigComp Header */ + if(lpCompartment->lpReqFeedback && tcomp_buffer_getSize(lpCompartment->lpReqFeedback)){ + /* Return the requested feedback */ + *header = 0xfc; /* T=1 */ + memcpy(GET_OUTPUT_BUFFER_AT(pointer), tcomp_buffer_getBuffer(lpCompartment->lpReqFeedback), tcomp_buffer_getSize(lpCompartment->lpReqFeedback)); + pointer += tcomp_buffer_getSize(lpCompartment->lpReqFeedback); + } + else{ + *header = 0xf8; + } + + /* + * Stateless or stateful? + */ + if(stateful){ + TSK_DEBUG_INFO("SigComp - Compressing message with state id = "); + tcomp_buffer_print(deflatedata->ghostState->identifier); + memcpy(GET_OUTPUT_BUFFER_AT(pointer), tcomp_buffer_getBuffer(deflatedata->ghostState->identifier), TCOMP_PARTIAL_ID_LEN_VALUE); + + pointer += TCOMP_PARTIAL_ID_LEN_VALUE; + *header |= TCOMP_PARTIAL_ID_LEN_CODE; + } + else{ + uint32_t codeLen = DEFLATE_BYTECODE_LEN; + /* first byte for codelen */ + *GET_OUTPUT_BUFFER_AT(pointer++) = ((codeLen>>4)& 0x00ff); + /* last 4 bits for codelen */ + *GET_OUTPUT_BUFFER_AT(pointer) = ((codeLen & 0x000f)<<4); + /* first and last 4 bits for destination */ + *GET_OUTPUT_BUFFER_AT(pointer++) |= DEFLATE_BYTECODE_DESTINATION_CODE; + + /* + * Upload UDVM bytecode + */ + memcpy(GET_OUTPUT_BUFFER_AT(pointer), (const uint8_t*)DEFLATEDATA_DEFLATE_BYTECODE, codeLen); + pointer += codeLen; + + ////////////////////////////////////////////////// + // FIXME: check for overflow and >=320 + // + // [DMS]+[Req. Fed. Loc.]+[state_len]+[cpb||dms||sms]+[Sigcomp_version]+[states] + //*output_buffer.getBuffer(pointer++) = 0x04; //reserved=0, Q=1, S=0, I=0 + //*output_buffer.getBuffer(pointer++) = (this->req_feedback_item++); //requested feedback item + + state_len_index = pointer; + *GET_OUTPUT_BUFFER_AT(pointer) = 0x00, pointer += 4; /* [hash_len]+[state_len] */ + *GET_OUTPUT_BUFFER_AT(pointer++) = (tcomp_params_getParameters(lpCompartment->local_parameters)>>8); // [cpb||dms||sms] + *GET_OUTPUT_BUFFER_AT(pointer++) = (tcomp_params_getParameters(lpCompartment->local_parameters)&0x00ff); // [Sigcomp_version] +#if USE_DICTS_FOR_COMPRESSION + *output_buffer.getBuffer(pointer++) = 0x00; // First dict byte // FIXME + *output_buffer.getBuffer(pointer++) = DEFLATE_FIXME_DICT; // FIXME: also change ghost +#endif + } + + /* + * Compress data using ZLIB + */ + compressedDataLen = (*output_size - pointer); + zret = tcomp_deflatedata_zCompress(deflatedata, input_ptr, input_size, GET_OUTPUT_BUFFER_AT(pointer), &compressedDataLen, &stateChanged); + if(!zret){ + result = tsk_false; + goto bail; + } + pointer += compressedDataLen; + *output_size = (pointer); + + /* + * Update state length + */ + if(!stateful){ + uint32_t state_len = ( (1<<(deflatedata->zWindowBits)) + DEFLATE_UDVM_CIRCULAR_START_INDEX - 64 ); + uint32_t hash_len = (state_len + 8); + + // FIXME: 131072 could not go in 2-bytes + *GET_OUTPUT_BUFFER_AT(state_len_index) = (hash_len >> 8); + *GET_OUTPUT_BUFFER_AT(state_len_index+1) = (hash_len & 0x00ff); + *GET_OUTPUT_BUFFER_AT(state_len_index+2) = (state_len >> 8); + *GET_OUTPUT_BUFFER_AT(state_len_index+3) = (state_len & 0x00ff); + + /* First time or synchronize failure (NACK reason=STATE_NOT_FOUND) */ + if(!deflatedata->ghostState){ + tcomp_deflatedata_createGhost(deflatedata, state_len, lpCompartment->local_parameters); + } + } + if(!lpCompartment->useOnlyACKedStates || (lpCompartment->useOnlyACKedStates && stateChanged)) + { + tcomp_deflatedata_updateGhost(deflatedata, (const uint8_t*)input_ptr, input_size); + } + + //output_buffer.print(2000); + +bail: + tsk_safeobj_unlock(lpCompartment); + + return result; + +#undef GET_OUTPUT_BUFFER_AT +} diff --git a/tinySIGCOMP/src/tcomp_compressor_deflate.h b/tinySIGCOMP/src/tcomp_compressor_deflate.h new file mode 100644 index 0000000..81216ad --- /dev/null +++ b/tinySIGCOMP/src/tcomp_compressor_deflate.h @@ -0,0 +1,42 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_compressor.h + * @brief Deflate compressor. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#ifndef TCOMP_COMPRESSORDEFLATE_H +#define TCOMP_COMPRESSORDEFLATE_H + +#include "tinysigcomp_config.h" +#include "tcomp_compartment.h" + +TCOMP_BEGIN_DECLS + +tsk_bool_t tcomp_compressor_deflate_compress(tcomp_compartment_t *lpCompartment, const void *input_ptr, tsk_size_t input_size, void *output_ptr, tsk_size_t *output_size, tsk_bool_t stream); + +TCOMP_END_DECLS + +#endif /* TCOMP_COMPRESSORDEFLATE_H */ diff --git a/tinySIGCOMP/src/tcomp_compressor_dummy.c b/tinySIGCOMP/src/tcomp_compressor_dummy.c new file mode 100644 index 0000000..34d062d --- /dev/null +++ b/tinySIGCOMP/src/tcomp_compressor_dummy.c @@ -0,0 +1,104 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_compressor_dummy.h + * @brief SigComp Dummy compressor. Used if none match. See RFC 4896 subclause 11. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ + +#include "tcomp_compressor_dummy.h" +#include "tcomp_buffer.h" + +#include <string.h> + +#define UNCOMPRESSED_BYTECODE_LENGTH 13 +#define UNCOMPRESSED_BYTECODE_DESTINATION_CODE 0x01 /* 128 */ +#define DUMMYCOMPRESSOR_UNCOMPRESSED_BYTECODE \ + "\xf8\x00\xa1\x1c\x01\x86\x09\x22\x86\x01\x16\xf9\x23" + + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// @brief Dummy compressor as per RFC 4896 subclause 11. This function is used to create uncompressed sigcomp message. +/// Used if none match. +/// +/// @param [in,out] lpCompartment The compartment to use. +/// @param [in,out] input_ptr The input buffer containing the message to compress. +/// @param input_size The size of the input buffer. +/// @param [in,out] output_ptr The output buffer where to copy the compressed message. +/// @param [in,out] output_size The size of the output buffer. +/// @param stream Indicates whether it's a stream buffer or not. +/// +/// @return 1 if succedd and 0 otherwise. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t tcomp_compressor_dummy_compress(tcomp_compartment_t *lpCompartment, const void *input_ptr, tsk_size_t input_size, void *output_ptr, tsk_size_t *output_size, tsk_bool_t stream) +{ + tcomp_buffer_handle_t *output_buffer = tcomp_buffer_create_null(); + tsk_size_t pointer = 0; + uint8_t *header; + uint32_t codeLen; + + tcomp_buffer_referenceBuff(output_buffer, (uint8_t*)output_ptr, *output_size); + header = tcomp_buffer_getBufferAtPos(output_buffer, pointer++); + + /* SigComp Header */ + if(lpCompartment->lpReqFeedback && tcomp_buffer_getSize(lpCompartment->lpReqFeedback)){ + /* Return the requested feedback */ + *header = 0xfc; /* T=1 */ + memcpy(tcomp_buffer_getBufferAtPos(output_buffer, pointer), tcomp_buffer_getBuffer(lpCompartment->lpReqFeedback), tcomp_buffer_getSize(lpCompartment->lpReqFeedback)); + pointer += tcomp_buffer_getSize(lpCompartment->lpReqFeedback); + } + else{ + *header = 0xf8; + } + + codeLen = UNCOMPRESSED_BYTECODE_LENGTH; + /* first byte for codelen */ + *tcomp_buffer_getBufferAtPos(output_buffer, pointer++) = ((codeLen>>4)& 0x00ff); + + /* last 4 bits for codelen */ + *tcomp_buffer_getBufferAtPos(output_buffer, pointer) = ((codeLen & 0x000f)<<4); + + /* first and last 4 bits for destination */ + *tcomp_buffer_getBufferAtPos(output_buffer, pointer++) |= UNCOMPRESSED_BYTECODE_DESTINATION_CODE; + + /* + * Upload UDVM bytecode + */ + memcpy(tcomp_buffer_getBufferAtPos(output_buffer, pointer), (uint8_t*)DUMMYCOMPRESSOR_UNCOMPRESSED_BYTECODE, codeLen); + pointer += codeLen; + + /* + * Copy data uncompressed + */ + memcpy(tcomp_buffer_getBufferAtPos(output_buffer, pointer), input_ptr, input_size); + pointer += input_size; + *output_size = (pointer); + + TSK_OBJECT_SAFE_FREE(output_buffer); + + return tsk_true; +} diff --git a/tinySIGCOMP/src/tcomp_compressor_dummy.h b/tinySIGCOMP/src/tcomp_compressor_dummy.h new file mode 100644 index 0000000..50c7c88 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_compressor_dummy.h @@ -0,0 +1,43 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_compressor_dummy.h + * @brief SigComp dummy compresor. Used if none match. See RFC 4896 subclause 11. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#ifndef TCOMP_COMPRESSOR_DUMMY_H +#define TCOMP_COMPRESSOR_DUMMY_H + +#include "tinysigcomp_config.h" +#include "tcomp_compartment.h" + +TCOMP_BEGIN_DECLS + +tsk_bool_t tcomp_compressor_dummy_compress(tcomp_compartment_t *lpCompartment, const void *input_ptr, tsk_size_t input_size, void *output_ptr, tsk_size_t *output_size, tsk_bool_t stream); + +TCOMP_END_DECLS + +#endif /* TCOMP_COMPRESSOR_DUMMY_H */ + diff --git a/tinySIGCOMP/src/tcomp_compressordata.c b/tinySIGCOMP/src/tcomp_compressordata.c new file mode 100644 index 0000000..1d8fe54 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_compressordata.c @@ -0,0 +1,115 @@ +///* +//* Copyright (C) 2010-2011 Mamadou Diop. +//* +//* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +//* +//* This file is part of Open Source Doubango Framework. +//* +//* DOUBANGO is free software: you can redistribute it and/or modify +//* it under the terms of the GNU General Public License as published by +//* the Free Software Foundation, either version 3 of the License, or +//* (at your option) any later version. +//* +//* DOUBANGO is distributed in the hope that it will be useful, +//* but WITHOUT ANY WARRANTY; without even the implied warranty of +//* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +//* GNU General Public License for more details. +//* +//* You should have received a copy of the GNU General Public License +//* along with DOUBANGO. +//* +//*/ +// +///**@file tcomp_compressordata.c +// * @brief SigComp compressor data. +// * +// * @author Mamadou Diop <diopmamadou(at)yahoo.fr> +// * +// +// */ +//#include "tcomp_compressordata.h" +// +//#include "tsk_debug.h" +// +//#include <assert.h> +// +// +///**@ingroup tcomp_compressordata_group +//*/ +//void tcomp_compressordata_ackGhost(tcomp_compressordata_t *compdata, const tcomp_buffer_handle_t *stateid) +//{ +// if(compdata) +// { +// tsk_safeobj_lock(compdata); +// assert(0); +// tsk_safeobj_unlock(compdata); +// } +// else +// { +// TSK_DEBUG_ERROR("NULL compressor data."); +// } +//} +// +///**@ingroup tcomp_compressordata_group +//*/ +//void tcomp_compressordata_freeGhostState(tcomp_compressordata_t *compdata) +//{ +// if(compdata) +// { +// tsk_safeobj_lock(compdata); +// assert(0); +// tsk_safeobj_unlock(compdata); +// } +// else +// { +// TSK_DEBUG_ERROR("NULL compressor data."); +// } +//} +// +// +// +// +// +// +// +// +// +////======================================================== +//// SigComp compressor data object definition +//// +//static void* tcomp_compressordata_create(void * self, va_list * app) +//{ +// tcomp_compressordata_t *compdata = self; +// if(compdata) +// { +// /* Initialize safeobject */ +// tsk_safeobj_init(compdata); +// +// compdata->isStream = va_arg(*app, int); +// } +// +// return self; +//} +// +//static void* tcomp_compressordata_destroy(void *self) +//{ +// tcomp_compressordata_t *compdata = self; +// if(compdata) +// { +// /* Deinitialize safeobject */ +// tsk_safeobj_deinit(compdata); +// +// TSK_OBJECT_SAFE_FREE(compdata->ghostState); +// } +// +// return self; +//} +// +//static const tsk_object_def_t tsk_compressordata_def_s = +//{ +// sizeof(tcomp_compressordata_t), +// tcomp_compressordata_create, +// tcomp_compressordata_destroy, +// 0 +//}; +//const void *tcomp_compressordata_def_t = &tsk_compressordata_def_s; diff --git a/tinySIGCOMP/src/tcomp_compressordata.h b/tinySIGCOMP/src/tcomp_compressordata.h new file mode 100644 index 0000000..917fa5e --- /dev/null +++ b/tinySIGCOMP/src/tcomp_compressordata.h @@ -0,0 +1,75 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_compressordata.h + * @brief SigComp compressor data. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#ifndef TCOMP_COMPRESSOR_DATA_H +#define TCOMP_COMPRESSOR_DATA_H + +#include "tinysigcomp_config.h" +#include "tcomp_buffer.h" + +TCOMP_BEGIN_DECLS + +typedef void tcomp_compressordata_t; + +typedef void (*tcomp_xxx_freeGhostState)(tcomp_compressordata_t *data); +typedef void (*tcomp_xxx_ackGhost)(tcomp_compressordata_t *data, const tcomp_buffer_handle_t *stateid); + +#define TCOMP_DECLARE_COMPRESSORDATA \ + void *compressorData; \ + unsigned compressorData_isStream; \ + tcomp_xxx_freeGhostState freeGhostState; \ + tcomp_xxx_ackGhost ackGhost + +//#include "tcomp_state.h" +//#include "tcomp_buffer.h" +// +//#include "tsk_object.h" +//#include "tsk_safeobj.h" +// +//#define TCOMP_COMPRESSORDATA_CREATE(isStream) tsk_object_new(tsk_compressordata_def_t, isStream) +// +//typedef struct tcomp_compressordata_s +//{ +// TSK_DECLARE_OBJECT; +// +// tcomp_state_t *ghostState; +// unsigned isStream:1; +// +// TSK_DECLARE_SAFEOBJ; +//} +//tcomp_compressordata_t; +// +//void tcomp_compressordata_ackGhost(tcomp_compressordata_t *compdata, const tcomp_buffer_handle_t *stateid); +//void tcomp_compressordata_freeGhostState(tcomp_compressordata_t *compdata); +// +//TINYSIGCOMP_GEXTERN const void *tcomp_compressordata_def_t; + +TCOMP_END_DECLS + +#endif /* TCOMP_COMPRESSOR_DATA_H */ diff --git a/tinySIGCOMP/src/tcomp_compressordisp.c b/tinySIGCOMP/src/tcomp_compressordisp.c new file mode 100644 index 0000000..13ab5fd --- /dev/null +++ b/tinySIGCOMP/src/tcomp_compressordisp.c @@ -0,0 +1,237 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_compressordisp.h + * @brief Entity that receives application messages, invokes a compressor,and forwards the resulting SigComp compressed messages to a remote + * endpoint. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_compressordisp.h" +#include "tcomp_compressor_dummy.h" +#include "tcomp_compressor_deflate.h" + +#include "tsk_memory.h" +#include "tsk_debug.h" + +#include <string.h> + +/**Checks whether NACK (RFC 4077) handling is supported +*/ +#define TCOMP_NACK_SUPPORTED (dispatcher->stateHandler->sigcomp_parameters->SigComp_version >= 0x02) + + +/**Creates new compressor dispatcher. +*/ +tcomp_compressordisp_t* tcomp_compressordisp_create(const tcomp_statehandler_t* statehandler) +{ + return tsk_object_new(tcomp_compressordisp_def_t, statehandler); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// Compress a message. +/// +/// @param [in,out] dispatcher The compressor dispatcher. +/// @param compartmentId The compartment to use to compress the message. +/// @param [in,out] input_ptr The message to compress. +/// @param input_size The size of the input buffer. +/// @param [in,out] output_ptr The output buffer to copy the compressed data. +/// @param [in,out] output_size The size of the output buffer. +/// @param stream Indicates whether it's a stream buffer or not. +/// +/// @return @a tsk_true if succeed and @a tsk_false otherwize. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t tcomp_compressordisp_compress(tcomp_compressordisp_t *dispatcher, uint64_t compartmentId, const void *input_ptr, tsk_size_t input_size, void *output_ptr, tsk_size_t *output_size, tsk_bool_t stream) +{ + tsk_bool_t ret = tsk_true; + int i = 0; + + /* For each compartment id create/retrieve one compressor instance */ + tcomp_compartment_t *lpCompartment = tcomp_statehandler_getCompartment(dispatcher->stateHandler, compartmentId); + + if(!lpCompartment){ + TSK_DEBUG_ERROR("You must provide a valid compartment to perform compression."); + return tsk_false; + } + + + /* + * Performs compression. + */ + tsk_safeobj_lock(dispatcher); + + for( i = 0; (i < TCOMP_MAX_COMPRESSORS && dispatcher->compressors[i]); i++ ){ + if((ret = dispatcher->compressors[i](lpCompartment, input_ptr, input_size, output_ptr, output_size, stream))) { + break; + } + } + + tsk_safeobj_unlock(dispatcher); + + + /* + * STREAM case. FIXME:Because I'm a lazy man I only support 0xFF00 case + */ + if(stream){ + uint8_t* escapedBuffer; + tsk_size_t i, j; + tsk_size_t escapedBufferSize = (*output_size + 2); /* 2 = strlen(0xffff) */ + + for(i = 0; i < *output_size ; i++) { + escapedBufferSize += ((uint8_t*)output_ptr)[i] == 0xff ? 1 : 0; + } + escapedBuffer = (uint8_t*)tsk_calloc(escapedBufferSize, sizeof(uint8_t)); + + for(i = 0, j = 0; i < *output_size; i++, j++){ + escapedBuffer[j] = ((uint8_t*)output_ptr)[i]; + if(escapedBuffer[j] == 0xff) { + escapedBuffer[++j] = 0x00; + } + } + + /* End stream */ + escapedBuffer[escapedBufferSize-1] = escapedBuffer[escapedBufferSize-2] = 0xff; + memcpy(output_ptr, escapedBuffer, escapedBufferSize); + + *output_size = escapedBufferSize; /* Update size */ + TSK_FREE(escapedBuffer); /* free */ + } + + /* + * NACK + */ + if(ret && TCOMP_NACK_SUPPORTED){ + /* store nack for later retrieval in case of errors */ + uint8_t nackId[TSK_SHA1_DIGEST_SIZE]; + tsk_sha1context_t sha; + + tsk_sha1reset(&sha); + tsk_sha1input(&sha, (const uint8_t*)output_ptr, *output_size); + tsk_sha1result(&sha, (uint8_t*)nackId); + tcomp_compartment_addNack(lpCompartment, nackId); + } + + return ret; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// Adds new compressor the list of the compressors. +/// +/// +/// @param [in,out] dispatcher The compressor dispatcher. +/// @param compressor A function pointer to the new compressor. +//////////////////////////////////////////////////////////////////////////////////////////////////// +int tcomp_compressordisp_addCompressor(tcomp_compressordisp_t *dispatcher, tcomp_compressor_compress_f compressor) +{ + tsk_size_t i; + + if(!dispatcher){ + TSK_DEBUG_ERROR("Invalid parameter"); + return -1; + } + + for(i = 0; i < TCOMP_MAX_COMPRESSORS; i++){ + if(!dispatcher->compressors[i]){ + dispatcher->compressors[i] = compressor; + return 0; + } + } + return -2; +} + +/** Removes a compressor +*/ +int tcomp_compressordisp_removeCompressor(tcomp_compressordisp_t *dispatcher, tcomp_compressor_compress_f compressor) +{ + tsk_size_t i; + + if(!dispatcher){ + TSK_DEBUG_ERROR("Invalid parameter"); + return -1; + } + + for(i = 0; i < TCOMP_MAX_COMPRESSORS; i++){ + if(dispatcher->compressors[i] == compressor){ + dispatcher->compressors[i] = tsk_null; + return 0; + } + } + return -2; +} + + + + + + + + +//======================================================== +// SigComp compressor dispatcher object definition +// +static tsk_object_t* tcomp_compressordisp_ctor(tsk_object_t * self, va_list * app) +{ + tcomp_compressordisp_t *compressordisp = self; + if(compressordisp){ + int i = 0; + compressordisp->stateHandler = va_arg(*app, const tcomp_statehandler_t*); + + compressordisp->compressors[0] = tcomp_compressor_deflate_compress; /* If you don't want deflate compressor then remove this line. */ + compressordisp->compressors[1] = tcomp_compressor_dummy_compress; /* RFC 4896 [11. Uncompressed Bytecode]. */ + + /* Initialize safeobject */ + tsk_safeobj_init(compressordisp); + } + else{ + TSK_DEBUG_ERROR("Failed to create new compressor dispatcher."); + } + + return self; +} + +static tsk_object_t* tcomp_compressordisp_dtor(tsk_object_t *self) +{ + tcomp_compressordisp_t *compressordisp = self; + if(compressordisp){ + /* Deinitialize safeobject */ + tsk_safeobj_deinit(compressordisp); + + memset(compressordisp->compressors, 0 , sizeof(compressordisp->compressors)); + compressordisp->stateHandler = tsk_null; // not owner + } + else{ + TSK_DEBUG_ERROR("Null dispatcher."); + } + + return self; +} + +static const tsk_object_def_t tcomp_compressordisp_def_s = +{ + sizeof(tcomp_compressordisp_t), + tcomp_compressordisp_ctor, + tcomp_compressordisp_dtor, + tsk_null +}; +const tsk_object_def_t *tcomp_compressordisp_def_t = &tcomp_compressordisp_def_s; diff --git a/tinySIGCOMP/src/tcomp_compressordisp.h b/tinySIGCOMP/src/tcomp_compressordisp.h new file mode 100644 index 0000000..17146f5 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_compressordisp.h @@ -0,0 +1,74 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_compressordisp.h + * @brief Entity that receives application messages, invokes a compressor,and forwards the resulting SigComp compressed messages to a remote + * endpoint. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#ifndef TCOMP_COMPRESSORDISP_H +#define TCOMP_COMPRESSORDISP_H + +#include "tinysigcomp_config.h" +#include "tcomp_statehandler.h" +#include "tcomp_buffer.h" +#include "tcomp_types.h" +#include "tcomp_result.h" +#include "tcomp_compressor.h" + +#include "tsk_list.h" +#include "tsk_object.h" +#include "tsk_safeobj.h" + +TCOMP_BEGIN_DECLS + + +#define TCOMP_MAX_COMPRESSORS 5 + +/**Compressor dispatcher. +*/ +typedef struct tcomp_compressordisp_s +{ + TSK_DECLARE_OBJECT; + + tcomp_compressor_compress_f compressors[TCOMP_MAX_COMPRESSORS]; + const tcomp_statehandler_t* stateHandler; + + TSK_DECLARE_SAFEOBJ; +} +tcomp_compressordisp_t; + +tcomp_compressordisp_t* tcomp_compressordisp_create(const tcomp_statehandler_t* statehandler); + +tsk_bool_t tcomp_compressordisp_compress(tcomp_compressordisp_t *dispatcher, uint64_t compartmentId, const void *input_ptr, tsk_size_t input_size, void *output_ptr, tsk_size_t *output_size, tsk_bool_t stream); + +int tcomp_compressordisp_addCompressor(tcomp_compressordisp_t *dispatcher, tcomp_compressor_compress_f compressor); +int tcomp_compressordisp_removeCompressor(tcomp_compressordisp_t *dispatcher, tcomp_compressor_compress_f compressor); + +TINYSIGCOMP_GEXTERN const tsk_object_def_t *tcomp_compressordisp_def_t; + +TCOMP_END_DECLS + +#endif /* TCOMP_COMPRESSORDISP_H */ diff --git a/tinySIGCOMP/src/tcomp_decompressordisp.c b/tinySIGCOMP/src/tcomp_decompressordisp.c new file mode 100644 index 0000000..fbf6192 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_decompressordisp.c @@ -0,0 +1,418 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_decompressordisp.c + * @brief Entity that receives SigComp messages, invokes a UDVM, and forwards the resulting decompressed messages to the application. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_decompressordisp.h" +#include "tcomp_message.h" +#include "tcomp_udvm.h" + +#include "tsk_debug.h" + +#include <assert.h> +#include <string.h> + +#define TCOMP_MAX_STREAM_BUFFER_SIZE 65535 +#define TCOMP_NACK_SUPPORTED(dispatcher) (dispatcher->stateHandler->sigcomp_parameters->SigComp_version >= 0x02) + + +/**Prefdicate function +*/ +static int pred_find_streambuffer_by_id(const tsk_list_item_t *item, const void *id) +{ + if(item && item->data) + { + tcomp_stream_buffer_t *streambuffer = item->data; + int64_t res = (streambuffer->id - *((int64_t*)id)); + return res > 0 ? (int)1 : (res < 0 ? (int)-1 : (int)0); + } + return -1; +} + +tcomp_stream_buffer_t* tcomp_stream_buffer_create(uint64_t id) +{ + return tsk_object_new(tcomp_stream_buffer_def_t, id); +} + +tcomp_decompressordisp_t* tcomp_decompressordisp_create(const tcomp_statehandler_t* statehandler) +{ + return tsk_object_new(tcomp_decompressordisp_def_t, statehandler); +} + +/**Decompress a message. +*/ +tsk_bool_t tcomp_decompressordisp_decompress(tcomp_decompressordisp_t *dispatcher, const void* input_ptr, tsk_size_t input_size, tcomp_result_t *lpResult) +{ + tsk_bool_t ret = tsk_true; + uint64_t streamId = 0; + const tsk_list_item_t *item_const; + + if(!dispatcher){ + TSK_DEBUG_ERROR("Invalid parameter."); + return tsk_false; + } + + /* + * Check if transport type changed. + */ + if(lpResult->isStreamBased){ + if(!dispatcher->streamBuffers){ + dispatcher->streamBuffers = tsk_list_create(); + } + + streamId = lpResult->streamId; + ret = tcomp_decompressordisp_appendStream(dispatcher, input_ptr, input_size, streamId); + if(!ret){ + TSK_DEBUG_ERROR("Failed to append new stream buffer."); + return 0; + } + } + + if(lpResult->isStreamBased){ + tsk_size_t size = 0; + uint32_t discard_count = 0; + tcomp_stream_buffer_t *lpBuffer; + + item_const = tsk_list_find_item_by_pred(dispatcher->streamBuffers, pred_find_streambuffer_by_id, &streamId); + if(!item_const || !(lpBuffer = item_const->data)){ + TSK_DEBUG_ERROR("Failed to find stream buffer by id %llu.", streamId); + return 0; + } + + if(ret && tcomp_decompressordisp_getNextStreamMsg(dispatcher, streamId, &discard_count, &size)){ + ret &= tcomp_decompressordisp_internalDecompress(dispatcher, tcomp_buffer_getBuffer(lpBuffer->buffer), size, &lpResult); + + /* remove buffer and discard */ + tcomp_buffer_discardLastBytes(lpBuffer->buffer, discard_count); + ret &= tcomp_buffer_removeBuff(lpBuffer->buffer, 0, size); + } + if(discard_count){ + tcomp_buffer_discardLastBytes(lpBuffer->buffer, discard_count); + } + if(size){ + //ret&= lpBuffer->removeBuff(0, (size)); + } + } + else{ + ret &= tcomp_decompressordisp_internalDecompress(dispatcher, input_ptr, input_size, &lpResult); + } + + return ret; +} + +/**Gets the next message from the queue. +*/ +tsk_bool_t tcomp_decompressordisp_getNextMessage(tcomp_decompressordisp_t *dispatcher, tcomp_result_t *lpResult) +{ + tsk_bool_t ret = tsk_true; + tsk_size_t size=0; + uint32_t discard_count = 0; + uint64_t streamId; + tcomp_stream_buffer_t *lpBuffer; + const tsk_list_item_t *item_const; + + if(!dispatcher){ + TSK_DEBUG_ERROR("Invalid parameter."); + return tsk_false; + } + + streamId = lpResult->streamId; + + item_const = tsk_list_find_item_by_pred(dispatcher->streamBuffers, pred_find_streambuffer_by_id, &streamId); + if(!item_const || !(lpBuffer = item_const->data)){ + TSK_DEBUG_ERROR("Failed to find stream buffer by id %llu.", streamId); + return tsk_false; + } + + if(ret && tcomp_decompressordisp_getNextStreamMsg(dispatcher, streamId, &discard_count, &size)){ + ret &= tcomp_decompressordisp_internalDecompress(dispatcher, tcomp_buffer_getBuffer(lpBuffer->buffer), size, &lpResult); + + /* remove buffer and discard */ + tcomp_buffer_discardLastBytes(lpBuffer->buffer, discard_count); + ret &= tcomp_buffer_removeBuff(lpBuffer->buffer, 0, size); + } + else { + ret = tsk_false; /* Is it right? */ + } + + if(discard_count){ + tcomp_buffer_discardLastBytes(lpBuffer->buffer, discard_count); + } + return ret; +} + +/**Decompress a message. +*/ +tsk_bool_t tcomp_decompressordisp_internalDecompress(tcomp_decompressordisp_t *dispatcher, const void* input_ptr, const tsk_size_t input_size, tcomp_result_t **lpResult) +{ + tcomp_message_t *sigCompMessage = tsk_null; + tcomp_udvm_t *sigCompUDVM = tsk_null; + tsk_bool_t ret = tsk_false; + int32_t nack_code = NACK_NONE; + + if(!dispatcher){ + TSK_DEBUG_ERROR("Invalid parameter."); + goto bail; + } + + sigCompMessage = tcomp_message_create(input_ptr, input_size, (*lpResult)->isStreamBased, &nack_code); + if(!sigCompMessage || !sigCompMessage->isOK){ + TSK_DEBUG_ERROR("Failed to create new sigcomp message"); + if(nack_code != NACK_NONE && ((*lpResult)->isNack = TCOMP_NACK_SUPPORTED(dispatcher))){ + tcomp_nackinfo_write_3((*lpResult)->nack_info, + nack_code, + input_ptr, input_size); + } + goto bail; + } + else if(sigCompMessage->isNack && TCOMP_NACK_SUPPORTED(dispatcher)){ + /* Remote party send us a NACK --> handle it */ + tcomp_statehandler_handleNack((tcomp_statehandler_t*)dispatcher->stateHandler, (const tcomp_nackinfo_t*)sigCompMessage->nack_info); + (*lpResult)->isNack = tsk_true; + + goto bail; + } + + /* Create new UDVM entity for each SigComp message */ + sigCompUDVM = tcomp_udvm_create(sigCompMessage, (tcomp_statehandler_t*)dispatcher->stateHandler, *lpResult); + + /* Decompress message */ + ret = tcomp_udvm_decompress(sigCompUDVM); + + /* decompression failed --> returns nack if supported */ + if(!ret){ + /* Decompression failed --> return NACK message to the application layer */ + (*lpResult)->isNack = TCOMP_NACK_SUPPORTED(dispatcher); + } + +bail: + /* Delete Message */ + TSK_OBJECT_SAFE_FREE(sigCompMessage); + + /* Delete UDVM entity */ + TSK_OBJECT_SAFE_FREE(sigCompUDVM); + + return ret; +} + +/**Appends stream buffer. +*/ +tsk_bool_t tcomp_decompressordisp_appendStream(tcomp_decompressordisp_t *dispatcher, const void* input_ptr, tsk_size_t input_size, uint64_t streamId) +{ + tcomp_stream_buffer_t* lpBuffer = tsk_null; + const tsk_list_item_t *item_const; + + if(!dispatcher){ + TSK_DEBUG_ERROR("Invalid parameter."); + return tsk_false; + } + + item_const = tsk_list_find_item_by_pred(dispatcher->streamBuffers, pred_find_streambuffer_by_id, &streamId); + if(!item_const || !(lpBuffer = item_const->data)){ + /* First time we get this stream ID */ + tcomp_buffer_handle_t *newbuf = tcomp_stream_buffer_create(streamId); + if(newbuf){ + lpBuffer = newbuf; + lpBuffer->buffer = tcomp_buffer_create_null(); + tsk_list_push_back_data(dispatcher->streamBuffers, ((void**) &newbuf)); + } + else{ + TSK_DEBUG_ERROR("Failed to create new stream buffer."); + return tsk_false; + } + } + + /* Check if buffer is too large */ + if(lpBuffer->buffer && (tcomp_buffer_getSize(lpBuffer->buffer) + input_size) > TCOMP_MAX_STREAM_BUFFER_SIZE){ + tcomp_buffer_freeBuff(lpBuffer->buffer); + return tsk_false; + } + + /* append new buffer */ + if(!tcomp_buffer_appendBuff(lpBuffer->buffer, input_ptr, input_size)){ + TSK_DEBUG_ERROR("Failed to append new buffer."); + tcomp_buffer_freeBuff(lpBuffer->buffer); + return tsk_false; + } + + return tsk_true; +} + +/**Gets the next message from the queue. +*/ +tsk_bool_t tcomp_decompressordisp_getNextStreamMsg(tcomp_decompressordisp_t *dispatcher, uint64_t streamId, uint32_t *discard_count, tsk_size_t *size) +{ + tcomp_stream_buffer_t *lpBuffer; + const tsk_list_item_t *item_const; + + uint8_t quote_count = 0; + uint8_t* start; + uint8_t* end; + + if(!dispatcher){ + TSK_DEBUG_ERROR("Invalid parameter."); + return tsk_false; + } + + /* + * RFC 3320 - 4.2.1. Decompressor Dispatcher Strategies [strategie 1] + */ + item_const = tsk_list_find_item_by_pred(dispatcher->streamBuffers, pred_find_streambuffer_by_id, &streamId); + if(!item_const || !(lpBuffer = item_const->data)){ + TSK_DEBUG_ERROR("Failed to find stream buffer by id %llu.", streamId); + return tsk_false; + } + + *size = 0; + *discard_count = 0; + + quote_count = 0; + start = tcomp_buffer_getBuffer(lpBuffer->buffer); + end = (start + tcomp_buffer_getSize(lpBuffer->buffer)); + + while(start<end){ + if(*start==0xff){ + start++; + if(*start==0xff) + { /* end message */ + if(*size) return tsk_true; + else /* message is empty --> delete this empty message(length=2) */ + { + start--; + memcpy(start, (start+2), (end-start)); + (*discard_count)+=2; + end-=2; + continue; + } + } + + quote_count = *start; + memcpy((start), (start+1), (end-start)); + end--; + (*discard_count)++; + start+=(quote_count); + (*size)+=(1+quote_count); + }else { start++; (*size)++; } + } + + return tsk_false; +} + + + + + + + + + + +//======================================================== +// SigComp decompressor dispatcher object definition +// +static tsk_object_t* tcomp_decompressordisp_ctor(tsk_object_t* self, va_list * app) +{ + tcomp_decompressordisp_t *decompressordisp = self; + if(decompressordisp){ + decompressordisp->stateHandler = va_arg(*app, const tcomp_statehandler_t*); + + /* Initialize safeobject */ + tsk_safeobj_init(decompressordisp); + } + else{ + TSK_DEBUG_ERROR("Failed to create new decompressor dispatcher."); + } + + return self; +} + +static tsk_object_t* tcomp_decompressordisp_dtor(tsk_object_t *self) +{ + tcomp_decompressordisp_t *decompressordisp = self; + if(decompressordisp){ + /* Deinitialize safeobject */ + tsk_safeobj_deinit(decompressordisp); + + TSK_OBJECT_SAFE_FREE(decompressordisp->streamBuffers); + } + else{ + TSK_DEBUG_ERROR("Null dispatcher."); + } + + return self; +} + +static const tsk_object_def_t tcomp_decompressordisp_def_s = +{ + sizeof(tcomp_decompressordisp_t), + tcomp_decompressordisp_ctor, + tcomp_decompressordisp_dtor, + tsk_null +}; +const tsk_object_def_t *tcomp_decompressordisp_def_t = &tcomp_decompressordisp_def_s; + + + + +//======================================================== +// SigComp stream buffer object definition +// + +static tsk_object_t* tcomp_stream_buffer_ctor(tsk_object_t* self, va_list * app) +{ + tcomp_stream_buffer_t *stream_buffer = self; + if(stream_buffer){ + stream_buffer->id = va_arg(*app, uint64_t); + } + else{ + TSK_DEBUG_ERROR("Failed to create new stream buffer."); + } + + return self; +} + +static tsk_object_t* tcomp_stream_buffer_dtor(tsk_object_t* self) +{ + tcomp_stream_buffer_t *stream_buffer = self; + if(stream_buffer){ + TSK_OBJECT_SAFE_FREE(stream_buffer->buffer); + } + else{ + TSK_DEBUG_ERROR("Null stream buffer."); + } + + return self; +} + +static const tsk_object_def_t tcomp_stream_buffer_def_s = +{ + sizeof(tcomp_stream_buffer_t), + tcomp_stream_buffer_ctor, + tcomp_stream_buffer_dtor, + tsk_null +}; +const tsk_object_def_t* tcomp_stream_buffer_def_t = &tcomp_stream_buffer_def_s; diff --git a/tinySIGCOMP/src/tcomp_decompressordisp.h b/tinySIGCOMP/src/tcomp_decompressordisp.h new file mode 100644 index 0000000..79bb635 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_decompressordisp.h @@ -0,0 +1,81 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_decompressordisp.h + * @brief Entity that receives SigComp messages, invokes a UDVM, and forwards the resulting decompressed messages to the application. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#ifndef TCOMP_DECOMPRESSORDISP_H +#define TCOMP_DECOMPRESSORDISP_H + +#include "tinysigcomp_config.h" +#include "tcomp_statehandler.h" +#include "tcomp_buffer.h" +#include "tcomp_types.h" +#include "tcomp_result.h" + + +#include "tsk_object.h" +#include "tsk_safeobj.h" + +TCOMP_BEGIN_DECLS + +typedef struct tcomp_stream_buffer_s +{ + TSK_DECLARE_OBJECT; + + uint64_t id; /**< Buffer identifier */ + tcomp_buffer_handle_t *buffer; /**< Buffer handle */ + + TSK_DECLARE_SAFEOBJ; +} +tcomp_stream_buffer_t; + +typedef struct tcomp_decompressordisp_s +{ + TSK_DECLARE_OBJECT; + + const tcomp_statehandler_t* stateHandler; + tcomp_stream_buffer_L_t *streamBuffers; + + TSK_DECLARE_SAFEOBJ; +} +tcomp_decompressordisp_t; + +tcomp_decompressordisp_t* tcomp_decompressordisp_create(const tcomp_statehandler_t* statehandler); + +tsk_bool_t tcomp_decompressordisp_decompress(tcomp_decompressordisp_t *dispatcher, const void* input_ptr, tsk_size_t input_size, tcomp_result_t *lpResult); +tsk_bool_t tcomp_decompressordisp_getNextMessage(tcomp_decompressordisp_t *dispatcher, tcomp_result_t *lpResult); + +tsk_bool_t tcomp_decompressordisp_internalDecompress(tcomp_decompressordisp_t *dispatcher, const void* input_ptr, const tsk_size_t input_size, tcomp_result_t **lpResult); +tsk_bool_t tcomp_decompressordisp_appendStream(tcomp_decompressordisp_t *dispatcher, const void* input_ptr, tsk_size_t input_size, uint64_t streamId); +tsk_bool_t tcomp_decompressordisp_getNextStreamMsg(tcomp_decompressordisp_t *dispatcher, uint64_t streamId, uint32_t *discard_count, tsk_size_t *size); + +TINYSIGCOMP_GEXTERN const tsk_object_def_t *tcomp_stream_buffer_def_t; +TINYSIGCOMP_GEXTERN const tsk_object_def_t *tcomp_decompressordisp_def_t; + +TCOMP_END_DECLS + +#endif /*TCOMP_DECOMPRESSORDISP_H*/ diff --git a/tinySIGCOMP/src/tcomp_deflatedata.c b/tinySIGCOMP/src/tcomp_deflatedata.c new file mode 100644 index 0000000..12a8fdd --- /dev/null +++ b/tinySIGCOMP/src/tcomp_deflatedata.c @@ -0,0 +1,115 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_compressor.h + * @brief SigComp Deflate compressor(Compressor data). + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_deflatedata.h" + +#include "tsk_debug.h" + +tcomp_deflatedata_t* tcomp_deflatedata_create_2(tsk_bool_t isStream, int z_level, int z_windowBits) +{ + tcomp_deflatedata_t *deflatedata; + if((deflatedata = tsk_object_new(tcomp_deflatedata_def_t))){ + deflatedata->isStream = isStream; + deflatedata->zLevel = z_level; + deflatedata->zWindowBits = z_windowBits; + } + else{ + TSK_DEBUG_ERROR("Null SigComp defalte data."); + } + + return deflatedata; +} + +tcomp_deflatedata_t* tcomp_deflatedata_create(tsk_bool_t isStream, tsk_bool_t useOnlyACKedStates) +{ + tcomp_deflatedata_t* deflatedata; + if((deflatedata = tcomp_deflatedata_create_2(isStream, Z_BEST_COMPRESSION, Z_DEFAULT_WINDOW_BITS))){ + deflatedata->useOnlyACKedStates = useOnlyACKedStates; + } + return deflatedata; +} + +tsk_bool_t tcomp_deflatedata_isStateful(tcomp_deflatedata_t *deflatedata) +{ + if(!deflatedata){ + TSK_DEBUG_ERROR("NULL defalte data."); + return tsk_false; + } + + return deflatedata->stream_acked.stateful; +} + + + + + + + + +//======================================================== +// Deflate compressor data object definition +// + +static void* tcomp_deflatedata_ctor(void * self, va_list * app) +{ + tcomp_deflatedata_t *deflatedata = self; + if(deflatedata){ + /* Initialize safeobject */ + tsk_safeobj_init(deflatedata); + } + + return self; +} + +static void* tcomp_deflatedata_dtor(void *self) +{ + tcomp_deflatedata_t *deflatedata = self; + if(deflatedata){ + /* Deinitialize safeobject */ + tsk_safeobj_deinit(deflatedata); + + TSK_OBJECT_SAFE_FREE(deflatedata->ghostState); + + tcomp_deflatedata_zUnInit(deflatedata); + } + else{ + TSK_DEBUG_ERROR("Null SigComp defalte data."); + } + + return self; +} + +static const tsk_object_def_t tsk_deflatedata_def_s = +{ + sizeof(tcomp_deflatedata_t), + tcomp_deflatedata_ctor, + tcomp_deflatedata_dtor, + tsk_null, +}; +const tsk_object_def_t *tcomp_deflatedata_def_t = &tsk_deflatedata_def_s; diff --git a/tinySIGCOMP/src/tcomp_deflatedata.ghost.c b/tinySIGCOMP/src/tcomp_deflatedata.ghost.c new file mode 100644 index 0000000..bfcb927 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_deflatedata.ghost.c @@ -0,0 +1,272 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_compressor.h + * @brief SigComp Deflate compressor(Ghost). + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_deflatedata.h" + +#include "tsk_binaryutils.h" +#include "tsk_debug.h" + +#include <string.h> + +/* + |<----------------------------DMS--------------------------------->| + |<-----SigComp message---->|<------------UDVM memory size--------->| + +-+----------+-------------+-----+----------+----------------------+ + | | bytecode | comp msg | | bytecode | circular buffer | + +-+----------+-------------+-----+----------+----------------------+ + ^ ^ + | | + SigComp header Low bytes of UDVM + +I suppose we would like to compress this message "libsigcomp": + GHOST STRUCTURE: + 0x02bb --> Circular Buffer size (DEFLATE_UDVM_CIRCULAR_START_INDEX = 699) + 0x2000 --> DMS (8192) + 0x0005 --> See 'libsigcomp/asm/deflate.asm' (MULTILOAD param number five) + 0x02c5 --> 709 (DEFLATE_UDVM_CIRCULAR_START_INDEX + strlen("libsigcomp")) + ...... --> Remaining MULTILOAD words + 0x0682 --> 1666 (HASH_LEN = SMS+8) + 0x067a --> 1658 (SMS) + 0x1902 --> [CPB+DMS+SMS]+[SigComp version] + ------------------------------------------------------------ + 0x0003 --> DEFLATE_NO_DICT + ...... --> Dictionnary words + 0x0000 --> FIXME + 0x0000 --> FIXME + ...... --> Deflate byte code (DeflateCompressor::deflate_bytecode) + ...... --> no compressed message +*/ + + +#define GHOST_CB_START_INDEX (0) +#define GHOST_DMS_INDEX (GHOST_CB_START_INDEX + 2) +#define GHOST_0x0005_INDEX (GHOST_DMS_INDEX + 2) +#define GHOST_CB_END_INDEX (GHOST_0x0005_INDEX + 2) +#define GHOST_HASH_LEN_INDEX (GHOST_CB_END_INDEX + 2 + 236) +#define GHOST_SMS_INDEX (GHOST_HASH_LEN_INDEX + 2) +#define GHOST_CPB_DMS_SMS_INDEX (GHOST_SMS_INDEX + 2) +#define GHOST_VERSION_INDEX (GHOST_CPB_DMS_SMS_INDEX + 1) + + +#define GHOST_BYTECODE1_SIZE (GHOST_VERSION_INDEX + 1) + + +static const char* DeflateData_deflate_bytecode1_ghost = +{ + "\xff\xff" // Circular buffer Size (CBS) + "\xff\xff" // State Memory Size (DMS) + "\x00\x05" // See 'libsigcomp/asm/deflate.asm' + "\xff\xff" // (CBS + strlen(input)) + + "\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\x09\x00\x00" + "\x00\x0a\x00\x01\x00\x0b\x00\x01\x00\x0d\x00\x01\x00\x0f\x00\x01\x00\x11\x00\x02\x00\x13\x00\x02\x00\x17\x00\x02\x00\x1b" + "\x00\x02\x00\x1f\x00\x03\x00\x23\x00\x03\x00\x2b\x00\x03\x00\x33\x00\x03\x00\x3b\x00\x04\x00\x43\x00\x04\x00\x53\x00\x04" + "\x00\x63\x00\x04\x00\x73\x00\x05\x00\x83\x00\x05\x00\xa3\x00\x05\x00\xc3\x00\x05\x00\xe3\x00\x00\x01\x02\x00\x00\x00\x01" + "\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x01\x00\x05\x00\x01\x00\x07\x00\x02\x00\x09\x00\x02\x00\x0d\x00\x03" + "\x00\x11\x00\x03\x00\x19\x00\x04\x00\x21\x00\x04\x00\x31\x00\x05\x00\x41\x00\x05\x00\x61\x00\x06\x00\x81\x00\x06\x00\xc1" + "\x00\x07\x01\x01\x00\x07\x01\x81\x00\x08\x02\x01\x00\x08\x03\x01\x00\x09\x04\x01\x00\x09\x06\x01\x00\x0a\x08\x01\x00\x0a" + "\x0c\x01\x00\x0b\x10\x01\x00\x0b\x18\x01\x00\x0c\x20\x01\x00\x0c\x30\x01\x00\x0d\x40\x01\x00\x0d\x60\x01" + + "\xff\xff" // HASH_LEN + "\xff\xff" // SMS + "\xff" // [CPB+DMS+SMS] + "\xff" // SigComp Version +}; + + +#define GHOST_STATE_ADDRESS 64 +#define GHOST_STATE_INSTRUCTION 492 +#define GHOST_STATE_MIN_ACCESS_LEN 6 +#define GHOST_STATE_RETENTION_PRIORITY 0 + +/**Creates a Ghost state. +*/ +void tcomp_deflatedata_createGhost(tcomp_deflatedata_t *deflatedata, uint32_t state_length, tcomp_params_t *params) +{ + uint8_t *ghostvalue_ptr = 0; +#define GHOSTVALUE_AT(position) (ghostvalue_ptr + position) + + if(!deflatedata){ + TSK_DEBUG_ERROR("NULL defalte data."); + return; + } + + if(deflatedata->ghostState){ + TSK_DEBUG_ERROR("The defalte data already have a ghost state. This MUST never happen."); + return; + } + + tsk_safeobj_lock(deflatedata); + + deflatedata->ghostState = tcomp_state_create(state_length, GHOST_STATE_ADDRESS, GHOST_STATE_INSTRUCTION, GHOST_STATE_MIN_ACCESS_LEN, GHOST_STATE_RETENTION_PRIORITY); + tcomp_buffer_allocBuff(deflatedata->ghostState->value, state_length); + ghostvalue_ptr = tcomp_buffer_getBuffer(deflatedata->ghostState->value); + + memcpy(ghostvalue_ptr, DeflateData_deflate_bytecode1_ghost, GHOST_BYTECODE1_SIZE); + + TSK_BINARY_SET_2BYTES( GHOSTVALUE_AT(GHOST_CB_START_INDEX), DEFLATE_UDVM_CIRCULAR_START_INDEX ); + TSK_BINARY_SET_2BYTES( GHOSTVALUE_AT(GHOST_DMS_INDEX), state_length+GHOST_STATE_ADDRESS ); + TSK_BINARY_SET_2BYTES( GHOSTVALUE_AT(GHOST_CB_END_INDEX), (DEFLATE_UDVM_CIRCULAR_START_INDEX + 0/*input_size*/) ); + // ...... + TSK_BINARY_SET_2BYTES( GHOSTVALUE_AT(GHOST_HASH_LEN_INDEX), (state_length+8) ); + TSK_BINARY_SET_2BYTES( GHOSTVALUE_AT(GHOST_SMS_INDEX), state_length ); + TSK_BINARY_SET_2BYTES( GHOSTVALUE_AT(GHOST_CPB_DMS_SMS_INDEX), tcomp_params_getParameters(params) ); // [cpb+dms+sms]+[version] + + // ------------------------------------------------------------ + +#define GHOST_DICT_CODE_INDEX (GHOST_BYTECODE1_SIZE) +#define GHOST_DICT_WORDS_INDEX (GHOST_DICT_CODE_INDEX + 2) +#if USE_DICTS_FOR_COMPRESSION +# define GHOST_FIXME2_INDEX (GHOST_DICT_WORDS_INDEX + 4/*Sip dict id len*/) +#else +# define GHOST_FIXME2_INDEX (GHOST_DICT_WORDS_INDEX + 0) +#endif +#define GHOST_DEFLATE_BYTECODE_INDEX (GHOST_FIXME2_INDEX + 4) +#define GHOST_INPUT_INDEX (GHOST_DEFLATE_BYTECODE_INDEX + DEFLATE_BYTECODE_LEN) + +#if USE_DICTS_FOR_COMPRESSION + BINARY_SET_2BYTES( ghostState->getStateValue()->getBuffer(GHOST_DICT_CODE_INDEX), DEFLATE_FIXME_DICT ); + if( DEFLATE_FIXME_DICT == DEFLATE_NO_DICT ){ + // Nothing to append + }else{ + if(DEFLATE_FIXME_DICT == DEFLATE_SIP_DICT_ONLY){ + ::memmove( ghostState->getStateValue()->getBuffer(GHOST_DICT_WORDS_INDEX), RFC3485_DICTIONARY_SIP_IDENTIFIER, 4 ); + }else{ + assert(1==0); + } + } +#endif + memcpy( GHOSTVALUE_AT(GHOST_DEFLATE_BYTECODE_INDEX), (const char*)DEFLATEDATA_DEFLATE_BYTECODE, DEFLATE_BYTECODE_LEN ); + + tsk_safeobj_unlock(deflatedata); + +#undef GHOSTVALUE_AT +} + +/**Acknowledge a Ghost state. +*/ +void tcomp_deflatedata_ackGhost(tcomp_compressordata_t *data, const tcomp_buffer_handle_t *stateid) +{ + tcomp_deflatedata_t *deflatedata = data; + if(!deflatedata){ + TSK_DEBUG_ERROR("NULL defalte data."); + return; + } + + tsk_safeobj_lock(deflatedata); + + if(deflatedata->ghostState){ + /* Update ghost */ + if(tcomp_buffer_startsWith(deflatedata->ghostState->identifier, stateid)){ + /* END() + COPY() */ + tcomp_deflateStream_end(&(deflatedata->stream_acked)); + tcomp_deflateStream_copy(&(deflatedata->stream_acked), &(deflatedata->stream_1)); + deflatedata->stream_acked.stateful = 1; + deflatedata->stream_acked.dataWaitingAck = 0; + TSK_DEBUG_INFO("SigComp - ACKed State id="); + tcomp_buffer_print(stateid); + } + } + + tsk_safeobj_unlock(deflatedata); +} + +/**Updates a Ghost state. +*/ +void tcomp_deflatedata_updateGhost(tcomp_deflatedata_t *deflatedata, const uint8_t *input_ptr, tsk_size_t input_size) +{ + uint32_t i; + uint8_t *ghostvalue_ptr = 0; + +#define GHOSTVALUE_AT(position) (ghostvalue_ptr + position) + + if(!deflatedata){ + TSK_DEBUG_ERROR("NULL defalte data."); + return; + } + + if(!deflatedata->ghostState){ + TSK_DEBUG_ERROR("NULL ghost state."); + return; + } + + tsk_safeobj_lock(deflatedata); + + ghostvalue_ptr = tcomp_buffer_getBuffer(deflatedata->ghostState->value); + +#define ZBUFF_LEN (0x0001 << deflatedata->zWindowBits) + for(i = 0; i < input_size; i++){ +#if 0 + *GHOSTVALUE_AT(GHOST_INPUT_INDEX + ghost_copy_offset) = 0x00; +#else + *GHOSTVALUE_AT(GHOST_INPUT_INDEX + deflatedata->ghost_copy_offset) = input_ptr[i]; +#endif + deflatedata->ghost_copy_offset = (deflatedata->ghost_copy_offset + 1) % ZBUFF_LEN; + } + + /* Update Circular Buffer Index */ + TSK_BINARY_SET_2BYTES( GHOSTVALUE_AT(GHOST_CB_END_INDEX), (DEFLATE_UDVM_CIRCULAR_START_INDEX + deflatedata->ghost_copy_offset) ); + + /* Compute State Identifier (20 bytes) */ + tcomp_state_makeValid(deflatedata->ghostState); + // new state identifer not acked yet + if(deflatedata->useOnlyACKedStates){ + deflatedata->stream_acked.stateful = 0; + deflatedata->stream_acked.dataWaitingAck = 1; + } + + TSK_DEBUG_INFO("SigComp - Making Ghost state valid with id = "); + tcomp_buffer_print(deflatedata->ghostState->identifier); + + tsk_safeobj_unlock(deflatedata); + +#undef GHOSTVALUE_AT +} + + +uint32_t* tcomp_deflatedata_getGhostCopyOffset(tcomp_deflatedata_t *deflatedata) +{ + if(!deflatedata){ + TSK_DEBUG_ERROR("NULL defalte data."); + return 0; + } + + return &(deflatedata->ghost_copy_offset); +} + +void tcomp_deflatedata_freeGhostState(tcomp_compressordata_t *data) +{ + tcomp_deflatedata_t *deflatedata = data; + if(!deflatedata){ + TSK_DEBUG_ERROR("NULL defalte data."); + return; + } + + TSK_OBJECT_SAFE_FREE(deflatedata->ghostState); +} diff --git a/tinySIGCOMP/src/tcomp_deflatedata.h b/tinySIGCOMP/src/tcomp_deflatedata.h new file mode 100644 index 0000000..d266572 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_deflatedata.h @@ -0,0 +1,175 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_compressor.h + * @brief SigComp Deflate compressor(Compressor data). + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#ifndef TCOMP_COMPRESSORDEFLATE_DATA_H +#define TCOMP_COMPRESSORDEFLATE_DATA_H + +#include "tinysigcomp_config.h" +#include "tcomp_params.h" +#include "tcomp_state.h" +#include "tcomp_compressordata.h" + +#if HAS_ZLIB +# include <zlib.h> +#else +# include "zlib.h" +#endif + +TCOMP_BEGIN_DECLS + +//============================================================// +#define USE_DICTS_FOR_COMPRESSION 0 + +#define Z_DEFAULT_WINDOW_BITS 10 /* 1024*/ + + +#define DEFLATE_DECOMPRESSION_PTR_INDEX 70 +#if USE_DICTS_FOR_COMPRESSION +# define DEFLATE_UDVM_CIRCULAR_START_INDEX 701 +#else +# define DEFLATE_UDVM_CIRCULAR_START_INDEX 630 +#endif + + +#define DEFLATE_SIP_DICT_ONLY 0x00 +#define DEFLATE_PRES_DICT_ONLY 0x01 +#define DEFLATE_SIP_PRES_DICTS 0x02 +#define DEFLATE_NO_DICT 0x03 +#define DEFLATE_FIXME_DICT DEFLATE_NO_DICT + + + +#define DEFLATE_BYTECODE_DESTINATION_START 320 +#define DEFLATE_BYTECODE_DESTINATION_CODE 0x04 // 320 +#if USE_DICTS_FOR_COMPRESSION +# define DEFLATE_BYTECODE_LEN 381 +#else +# define DEFLATE_BYTECODE_LEN 310 +#endif +//==========================================================// + + +#if USE_DICTS_FOR_COMPRESSION +#define DEFLATEDATA_DEFLATE_BYTECODE \ + "\x0f\x86\x7a\xa2\xbd\x8d\x05\xa2\xbd\x00\x03\x00\x04\x00\x05\x00\x06\x00\x07\x00\x08\x00" \ + "\x09\x00\x0a\x01\x0b\x01\x0d\x01\x0f\x01\x11\x02\x13\x02\x17\x02\x1b\x02\x1f\x03\x23\x03" \ + "\x2b\x03\x33\x03\x3b\x04\xa0\x43\x04\xa0\x53\x04\xa0\x63\x04\xa0\x73\x05\xa0\x83\x05\xa0" \ + "\xa3\x05\xa0\xc3\x05\xa0\xe3\x00\xa1\x02\x00\x01\x00\x02\x00\x03\x00\x04\x01\x05\x01\x07" \ + "\x02\x09\x02\x0d\x03\x11\x03\x19\x04\x21\x04\x31\x05\xa0\x41\x05\xa0\x61\x06\xa0\x81\x06" \ + "\xa0\xc1\x07\xa1\x01\x07\xa1\x81\x08\xa2\x01\x08\xa3\x01\x09\xa4\x01\x09\xa6\x01\x0a\xa8" \ + "\x01\x0a\xac\x01\x0b\xb0\x01\x0b\xb8\x01\x0c\x80\x20\x01\x0c\x80\x30\x01\x0d\x80\x40\x01" \ + "\x0d\x80\x60\x01\x1c\x08\xa1\x34\xa0\xde\x0e\xa0\x42\xc1\x36\x06\x21\x86\x1a\x04\xc1\x3a" \ + "\xa0\x0c\xa0\x1e\xa0\x30\xa0\x47\x0f\xa1\x3a\x04\xa6\xfb\x80\xe5\x07\x80\xdf\xe5\x80\xe6" \ + "\x00\x16\xa0\x2c\x0f\xa1\x3a\x04\xa6\xd9\x80\x42\x29\x80\x7d\x0b\x80\xb3\x00\x16\xa0\x1a" \ + "\x0f\xa1\x3a\x07\xa6\xfb\x80\xe5\x07\x80\xdf\xe5\x80\xe6\x06\x80\xd9\x42\x80\x29\x7d\xab" \ + "\xb3\x1d\x03\x22\xa0\x89\x1e\x20\xa0\x68\x04\x07\x00\x17\x80\x40\x11\x01\x30\xa0\xbf\x00" \ + "\x00\xa0\xc0\xa0\xc7\x80\x40\x29\x01\xa1\x90\xa1\xff\xa0\x90\x17\x50\x80\x40\x11\xa0\x0b" \ + "\xa0\x49\xa0\x15\x22\x21\x01\x13\x21\x01\x23\x16\x9f\xcf\x08\x10\x04\x12\x50\x04\x22\x1d" \ + "\x51\x22\xa0\x49\x06\x12\x51\x1e\x20\xa0\x41\x01\x05\x00\x1f\x2f\x08\x10\x04\x12\x50\x04" \ + "\x26\x1d\x53\x26\xa0\x31\x06\x14\x53\x0e\x20\x63\x14\x54\x52\x23\x22\x50\x52\x16\x9f\x9b" \ + "\x0e\x2a\xa4\x86\x0f\x38\x04\xc1\x36\x86\xa1\xec\x06\x0d\x38\xc1\x34\x2c\x23\x2a\xa1\x38" \ + "\xc1\x36\x86\xa1\xec\x06\x00" +#else +#define DEFLATEDATA_DEFLATE_BYTECODE \ + "\x0f\x86\x7a\xa2\x76\x8d\x05\xa2\x76\x00\x03\x00\x04\x00\x05\x00\x06\x00\x07\x00\x08\x00" \ + "\x09\x00\x0a\x01\x0b\x01\x0d\x01\x0f\x01\x11\x02\x13\x02\x17\x02\x1b\x02\x1f\x03\x23\x03" \ + "\x2b\x03\x33\x03\x3b\x04\xa0\x43\x04\xa0\x53\x04\xa0\x63\x04\xa0\x73\x05\xa0\x83\x05\xa0" \ + "\xa3\x05\xa0\xc3\x05\xa0\xe3\x00\xa1\x02\x00\x01\x00\x02\x00\x03\x00\x04\x01\x05\x01\x07" \ + "\x02\x09\x02\x0d\x03\x11\x03\x19\x04\x21\x04\x31\x05\xa0\x41\x05\xa0\x61\x06\xa0\x81\x06" \ + "\xa0\xc1\x07\xa1\x01\x07\xa1\x81\x08\xa2\x01\x08\xa3\x01\x09\xa4\x01\x09\xa6\x01\x0a\xa8" \ + "\x01\x0a\xac\x01\x0b\xb0\x01\x0b\xb8\x01\x0c\x80\x20\x01\x0c\x80\x30\x01\x0d\x80\x40\x01" \ + "\x0d\x80\x60\x01\x1c\x06\xa1\x34\xa0\x97\x0e\xa0\x42\xc1\x36\x06\x21\x86\x1d\x03\x22\xa0" \ + "\x89\x1e\x20\xa0\x68\x04\x07\x00\x17\x80\x40\x11\x01\x30\xa0\xbf\x00\x00\xa0\xc0\xa0\xc7" \ + "\x80\x40\x29\x01\xa1\x90\xa1\xff\xa0\x90\x17\x50\x80\x40\x11\xa0\x0b\xa0\x49\xa0\x15\x22" \ + "\x21\x01\x13\x21\x01\x23\x16\x9f\xcf\x08\x10\x04\x12\x50\x04\x22\x1d\x51\x22\xa0\x49\x06" \ + "\x12\x51\x1e\x20\xa0\x41\x01\x05\x00\x1f\x2f\x08\x10\x04\x12\x50\x04\x26\x1d\x53\x26\xa0" \ + "\x31\x06\x14\x53\x0e\x20\x63\x14\x54\x52\x23\x22\x50\x52\x16\x9f\x9b\x0e\x2a\xa4\x86\x0f" \ + "\x38\x04\xc1\x36\x86\xa1\xec\x06\x0d\x38\xc1\x34\x2c\x23\x2a\xa1\x38\xc1\x36\x86\xa1\xec" \ + "\x06\x00" + +#endif /* USE_DICTS_FOR_COMPRESSION */ + + +typedef struct tcomp_deflateStream_s +{ + z_stream zs; + unsigned dataWaitingAck:1; + unsigned stateful:1; +} +tcomp_deflateStream_t; + +tsk_bool_t tcomp_deflateStream_end(tcomp_deflateStream_t *stream); +tsk_bool_t tcomp_deflateStream_copy(tcomp_deflateStream_t *stream, tcomp_deflateStream_t *source); + + +typedef struct tcomp_deflatedata_s +{ + TSK_DECLARE_OBJECT; + + tcomp_deflateStream_t stream_1; + tcomp_deflateStream_t stream_acked; + int zLevel; + int zWindowBits; + + tsk_bool_t isInitialized; + + uint32_t ghost_copy_offset; + tcomp_state_t *ghostState; + + tsk_bool_t isStream; + + tsk_bool_t useOnlyACKedStates; + + TSK_DECLARE_SAFEOBJ; +} +tcomp_deflatedata_t; + +tcomp_deflatedata_t* tcomp_deflatedata_create(tsk_bool_t isStream, tsk_bool_t useOnlyACKedStates); + +void tcomp_deflatedata_freeGhostState(tcomp_compressordata_t *deflatedata); +void tcomp_deflatedata_ackGhost(tcomp_compressordata_t *deflatedata, const tcomp_buffer_handle_t *stateid); +void tcomp_deflatedata_createGhost(tcomp_deflatedata_t *deflatedata, uint32_t state_len, tcomp_params_t *params); +void tcomp_deflatedata_updateGhost(tcomp_deflatedata_t *deflatedata, const uint8_t *input_ptr, tsk_size_t input_size); +uint32_t* tcomp_deflatedata_getGhostCopyOffset(tcomp_deflatedata_t *deflatedata); + +tsk_bool_t tcomp_deflatedata_zReset(tcomp_deflatedata_t *deflatedata); +tsk_bool_t tcomp_deflatedata_zCompress(tcomp_deflatedata_t *deflatedata, const void* in, tsk_size_t inLen, void* out, tsk_size_t* outLen, tsk_bool_t *stateChanged); + +int tcomp_deflatedata_zGetWindowBits(tcomp_deflatedata_t *deflatedata); +void tcomp_deflatedata_zSetWindowBits(tcomp_deflatedata_t *deflatedata, int windowSize); + +tsk_bool_t tcomp_deflatedata_isStateful(tcomp_deflatedata_t *deflatedata); +tsk_bool_t tcomp_deflatedata_zInit(tcomp_deflatedata_t *deflatedata); +tsk_bool_t tcomp_deflatedata_zUnInit(tcomp_deflatedata_t *deflatedata); + +TINYSIGCOMP_GEXTERN const tsk_object_def_t *tcomp_deflatedata_def_t; + +TCOMP_END_DECLS + +#endif /* TCOMP_COMPRESSORDEFLATE_DATA_H */ diff --git a/tinySIGCOMP/src/tcomp_deflatedata.zlib.c b/tinySIGCOMP/src/tcomp_deflatedata.zlib.c new file mode 100644 index 0000000..6d8c628 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_deflatedata.zlib.c @@ -0,0 +1,217 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_compressor.h + * @brief SiComp Deflate compressor (zlib). + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_deflatedata.h" +#include "tsk_debug.h" + + +tsk_bool_t tcomp_deflateStream_end(tcomp_deflateStream_t *stream) +{ + if(!stream){ + TSK_DEBUG_ERROR("NULL defalte stream."); + return tsk_false; + } + + return deflateEnd(&(stream->zs)); +} + +tsk_bool_t tcomp_deflateStream_copy(tcomp_deflateStream_t *stream, tcomp_deflateStream_t *source) +{ + if(!stream){ + TSK_DEBUG_ERROR("NULL defalte stream."); + return tsk_false; + } + + return deflateCopy(&(stream->zs), &(source->zs)); +} + +tsk_bool_t tcomp_deflatedata_zInit(tcomp_deflatedata_t *deflatedata) +{ + if(!deflatedata){ + TSK_DEBUG_ERROR("NULL defalte data."); + return tsk_false; + } + + /* Already initialized? */ + if(deflatedata->isInitialized) { + return tsk_true; + } + + /* allocate deflate state */ + deflatedata->stream_1.zs.zalloc = deflatedata->stream_acked.zs.zalloc = Z_NULL; + deflatedata->stream_1.zs.zfree = deflatedata->stream_acked.zs.zfree = Z_NULL; + deflatedata->stream_1.zs.opaque = deflatedata->stream_acked.zs.opaque = Z_NULL; +#ifndef __SYMBIAN32__ + deflatedata->stream_1.zs.data_type = deflatedata->stream_acked.zs.data_type = Z_TEXT; +#endif + + //bool ret = (deflateInit(&this->zStream, this->zLevel) == Z_OK); + if( deflateInit2(&deflatedata->stream_1.zs, deflatedata->zLevel, Z_DEFLATED, -deflatedata->zWindowBits, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY) != Z_OK + || deflateInit2(&deflatedata->stream_acked.zs, deflatedata->zLevel, Z_DEFLATED, -deflatedata->zWindowBits, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY) != Z_OK ) + { + return tsk_false; + } +#if USE_DICTS_FOR_COMPRESSION + if( deflateSetDictionary(this->stream_1.zs, (const Bytef*)RFC3485_DICTIONARY_SIP_VALUE, RFC3485_DICTIONARY_SIP_VALUE_LENGTH) != Z_OK + || deflateSetDictionary(this->stream_acked.zs, (const Bytef*)RFC3485_DICTIONARY_SIP_VALUE, RFC3485_DICTIONARY_SIP_VALUE_LENGTH) != Z_OK ) + { + return false; + } +#endif + + deflatedata->stream_1.stateful = deflatedata->stream_acked.stateful = 0; + deflatedata->stream_1.dataWaitingAck = deflatedata->stream_acked.dataWaitingAck = 0; + deflatedata->isInitialized = tsk_true; + + return tsk_true; +} + +tsk_bool_t tcomp_deflatedata_zUnInit(tcomp_deflatedata_t *deflatedata) +{ + if(!deflatedata){ + TSK_DEBUG_ERROR("NULL defalte data."); + return tsk_false; + } + + if(deflatedata->isInitialized){ + deflatedata->isInitialized = tsk_false; + + deflatedata->stream_1.dataWaitingAck = deflatedata->stream_acked.dataWaitingAck = 0; + deflatedata->stream_1.stateful = deflatedata->stream_acked.stateful = 0; + + return (tcomp_deflateStream_end(&deflatedata->stream_1) != Z_STREAM_ERROR) && (tcomp_deflateStream_end(&deflatedata->stream_acked) != Z_STREAM_ERROR); + } + return tsk_true; +} + +tsk_bool_t tcomp_deflatedata_zReset(tcomp_deflatedata_t *deflatedata) +{ + tsk_bool_t ret; + + if(!deflatedata){ + TSK_DEBUG_ERROR("NULL defalte data."); + return tsk_false; + } + + ret = deflatedata->isInitialized ? tcomp_deflatedata_zUnInit(deflatedata) : tsk_true; + ret &= tcomp_deflatedata_zInit(deflatedata); + + return ret; +} + +tsk_bool_t tcomp_deflatedata_zCompress(tcomp_deflatedata_t *deflatedata, const void* in, tsk_size_t inLen, void* out, tsk_size_t* outLen, tsk_bool_t *stateChanged) +{ + int ret = tsk_false; +/* + Two streams [1] and [2] + + * ZINIT/ZUNINIT/ZRESET + XXX([1]) + XXX([2]) + + * COMPRESSION + [1]->END() + [1]<-COPY-[2] + [1]->COMPRESS() + + * ACK + [2]->END() + [2]<-COPY-[1] + updateGhost([1]) +*/ + if(!deflatedata){ + TSK_DEBUG_ERROR("Invalid parameter"); + return tsk_false; + } + + tsk_safeobj_lock(deflatedata); + + /* Initialized? */ + if(!deflatedata->isInitialized){ + if(!tcomp_deflatedata_zInit(deflatedata)){ + TSK_DEBUG_ERROR("Failed to initialize zlib resources.."); + tsk_safeobj_unlock(deflatedata); + return tsk_false; + } + } + + if(deflatedata->useOnlyACKedStates){ + if(!deflatedata->stream_acked.dataWaitingAck){ + deflatedata->stream_acked.dataWaitingAck = 1; + *stateChanged = tsk_true; + } + else{ + *stateChanged = tsk_false; + } + + /* END() + COPY() ==> use acked state */ + tcomp_deflateStream_end(&(deflatedata->stream_1)); + tcomp_deflateStream_copy(&(deflatedata->stream_1), &(deflatedata->stream_acked)); + } + else{ + *stateChanged = tsk_true; + } + + // IN + deflatedata->stream_1.zs.next_in = (Bytef*)in; + deflatedata->stream_1.zs.avail_in = (uInt)inLen; + + // OUT + deflatedata->stream_1.zs.next_out = (Bytef*)out; + deflatedata->stream_1.zs.avail_out = (uInt)*outLen; + + ret = deflate(&(deflatedata->stream_1.zs), Z_SYNC_FLUSH); + + *outLen -= deflatedata->stream_1.zs.avail_out; + + tsk_safeobj_unlock(deflatedata); + + return (ret == Z_OK); +} + +int tcomp_deflatedata_zGetWindowBits(tcomp_deflatedata_t *deflatedata) +{ + if(!deflatedata){ + TSK_DEBUG_ERROR("Invalid parameter"); + return 0; + } + + return deflatedata->zWindowBits; +} + +void tcomp_deflatedata_zSetWindowBits(tcomp_deflatedata_t *deflatedata, int windowSize) +{ + if(!deflatedata){ + TSK_DEBUG_ERROR("Invalid parameter"); + return; + } + + deflatedata->zWindowBits = windowSize; +} + diff --git a/tinySIGCOMP/src/tcomp_dicts.c b/tinySIGCOMP/src/tcomp_dicts.c new file mode 100644 index 0000000..b5e11ca --- /dev/null +++ b/tinySIGCOMP/src/tcomp_dicts.c @@ -0,0 +1,96 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_dicts.c + * @brief SigComp Dictionaries + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_dicts.h" +#include "tcomp_buffer.h" + +#include "tcomp_rfc3485_dictionary_sip.h" +#include "tcomp_rfc5112_dictionary_presence.h" + +#include "tsk_debug.h" + +/**Presence-Specific Static Dictionary for Signaling Compression as per RFC 5112. +*/ +tcomp_dictionary_t* tcomp_dicts_create_presence_dict() +{ + static const char *pres_dict_data = RFC5112_DICTIONARY_PRESENCE_VALUE; + static tcomp_dictionary_t * pres_dict = tsk_null; + + if(!pres_dict){ + pres_dict = tcomp_state_create( + RFC5112_DICTIONARY_PRESENCE_VALUE_LENGTH, + RFC5112_DICTIONARY_PRESENCE_STATE_ADDRESS, + RFC5112_DICTIONARY_PRESENCE_STATE_INSTRUCTION, + RFC5112_DICTIONARY_PRESENCE_MINIMUM_ACCESS_LENGTH, + 65535); + + if(pres_dict){ + tcomp_buffer_referenceBuff(pres_dict->value, (uint8_t*)pres_dict_data, RFC5112_DICTIONARY_PRESENCE_VALUE_LENGTH); + tcomp_state_makeValid(pres_dict); + TSK_DEBUG_INFO("SigComp - Presence dict State id="); + tcomp_buffer_print(pres_dict->identifier); + } + else{ + TSK_DEBUG_ERROR("Failed to create Presence dictionary."); + } + } + + return tsk_object_ref(pres_dict); +} + +/**The Session Initiation Protocol (SIP) and Session Description Protocol (SDP) Static Dictionary for Signaling Compression as per RFC 3485. +*/ +tcomp_dictionary_t* tcomp_dicts_create_sip_dict() +{ + + static const char *sip_dict_data = RFC3485_DICTIONARY_SIP_VALUE; + static tcomp_dictionary_t *sip_dict = tsk_null; + + if(!sip_dict){ + sip_dict = tcomp_state_create( + RFC3485_DICTIONARY_SIP_VALUE_LENGTH, + RFC3485_DICTIONARY_SIP_STATE_ADDRESS, + RFC3485_DICTIONARY_SIP_STATE_INSTRUCTION, + RFC3485_DICTIONARY_SIP_MINIMUM_ACCESS_LENGTH, + 65535); + + if(sip_dict){ + tcomp_buffer_referenceBuff(sip_dict->value, (uint8_t*)sip_dict_data, RFC3485_DICTIONARY_SIP_VALUE_LENGTH); + tcomp_state_makeValid(sip_dict); + TSK_DEBUG_INFO("SigComp - SIP dict State id="); + tcomp_buffer_print(sip_dict->identifier); + } + else{ + TSK_DEBUG_ERROR("Failed to create SIP/SDP dictionary."); + } + } + + return tsk_object_ref(sip_dict); +} + diff --git a/tinySIGCOMP/src/tcomp_dicts.h b/tinySIGCOMP/src/tcomp_dicts.h new file mode 100644 index 0000000..dab3d88 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_dicts.h @@ -0,0 +1,44 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_dicts.h + * @brief SigComp Dictionaries + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ + +#ifndef _TINYSIGCOMP_DICTS_H_ +#define _TINYSIGCOMP_DICTS_H_ + +#include "tinysigcomp_config.h" +#include "tcomp_state.h" + +TCOMP_BEGIN_DECLS + +extern tcomp_dictionary_t* tcomp_dicts_create_presence_dict(); +extern tcomp_dictionary_t* tcomp_dicts_create_sip_dict(); + +TCOMP_END_DECLS + +#endif /* _TINYSIGCOMP_DICTS_H_ */ diff --git a/tinySIGCOMP/src/tcomp_headers_index.h b/tinySIGCOMP/src/tcomp_headers_index.h new file mode 100644 index 0000000..0402deb --- /dev/null +++ b/tinySIGCOMP/src/tcomp_headers_index.h @@ -0,0 +1,83 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_headers_index.h + * @brief SigComp headers index. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ + +#ifndef TCOMP_UDVM_HEADERS_INDEX_H +#define TCOMP_UDVM_HEADERS_INDEX_H + +/* + 0 7 8 15 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | UDVM_memory_size | 0 - 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | cycles_per_bit | 2 - 3 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | SigComp_version | 4 - 5 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | partial_state_ID_length | 6 - 7 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | state_length | 8 - 9 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | | + : reserved : 10 - 31 + | | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + */ +#define TCOMP_UDVM_HEADER_UDVM_MEMORY_SIZE_INDEX 0 +#define TCOMP_UDVM_HEADER_CYCLES_PER_BIT_INDEX 2 +#define TCOMP_UDVM_HEADER_SIGCOMP_VERSION_INDEX 4 +#define TCOMP_UDVM_HEADER_PARTIAL_STATE_ID_LENGTH_INDEX 6 +#define TCOMP_UDVM_HEADER_STATE_LENGTH_INDEX 8 +#define TCOMP_UDVM_HEADER_RESERVED_INDEX 10 + + +/* +0 7 8 15 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| byte_copy_left | 64 - 65 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| byte_copy_right | 66 - 67 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| input_bit_order | 68 - 69 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| stack_location | 70 - 71 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +0 7 8 15 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| reserved |F|H|P| 68 - 69 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +*/ +#define TCOMP_UDVM_HEADER_BYTE_COPY_LEFT_INDEX 64 +#define TCOMP_UDVM_HEADER_BYTE_COPY_RIGHT_INDEX 66 +#define TCOMP_UDVM_HEADER_INPUT_BIT_ORDER_INDEX 68 +#define TCOMP_UDVM_HEADER_STACK_LOCATION_INDEX 70 + +#endif /* TCOMP_UDVM_HEADERS_INDEX_H */ diff --git a/tinySIGCOMP/src/tcomp_instructions.h b/tinySIGCOMP/src/tcomp_instructions.h new file mode 100644 index 0000000..ae2c5b4 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_instructions.h @@ -0,0 +1,121 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_instructions.h + * @brief List of all supported UDVM instructions as per RFC 3320 subclause 9. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ + +#ifndef TCOMP_INSTRUCTIONS_H +#define TCOMP_INSTRUCTIONS_H + +/************************************************************************************ +* Instruction Bytecode value Cost in UDVM cycles * +*************************************************************************************/ +#define TCOMP_UDVM_INST__DECOMPRESSION_FAILURE 0 //1 +#define TCOMP_UDVM_INST__AND 1 //1 +#define TCOMP_UDVM_INST__OR 2 //1 +#define TCOMP_UDVM_INST__NOT 3 //1 +#define TCOMP_UDVM_INST__LSHIFT 4 //1 +#define TCOMP_UDVM_INST__RSHIFT 5 //1 +#define TCOMP_UDVM_INST__ADD 6 //1 +#define TCOMP_UDVM_INST__SUBTRACT 7 //1 +#define TCOMP_UDVM_INST__MULTIPLY 8 //1 +#define TCOMP_UDVM_INST__DIVIDE 9 //1 +#define TCOMP_UDVM_INST__REMAINDER 10 //1 +#define TCOMP_UDVM_INST__SORT_ASCENDING 11 //1 + k * (ceiling(log2(k)) + n) +#define TCOMP_UDVM_INST__SORT_DESCENDING 12 //1 + k * (ceiling(log2(k)) + n) +#define TCOMP_UDVM_INST__SHA_1 13 //1 + length +#define TCOMP_UDVM_INST__LOAD 14 //1 +#define TCOMP_UDVM_INST__MULTILOAD 15 //1 + n +#define TCOMP_UDVM_INST__PUSH 16 //1 +#define TCOMP_UDVM_INST__POP 17 //1 +#define TCOMP_UDVM_INST__COPY 18 //1 + length +#define TCOMP_UDVM_INST__COPY_LITERAL 19 //1 + length +#define TCOMP_UDVM_INST__COPY_OFFSET 20 //1 + length +#define TCOMP_UDVM_INST__MEMSET 21 //1 + length +#define TCOMP_UDVM_INST__JUMP 22 //1 +#define TCOMP_UDVM_INST__COMPARE 23 //1 +#define TCOMP_UDVM_INST__CALL 24 //1 +#define TCOMP_UDVM_INST__RETURN 25 //1 +#define TCOMP_UDVM_INST__SWITCH 26 //1 + n +#define TCOMP_UDVM_INST__CRC 27 //1 + length +#define TCOMP_UDVM_INST__INPUT_BYTES 28 //1 + length +#define TCOMP_UDVM_INST__INPUT_BITS 29 //1 +#define TCOMP_UDVM_INST__INPUT_HUFFMAN 30 //1 + n +#define TCOMP_UDVM_INST__STATE_ACCESS 31 //1 + state_length +#define TCOMP_UDVM_INST__STATE_CREATE 32 //1 + state_length +#define TCOMP_UDVM_INST__STATE_FREE 33 //1 +#define TCOMP_UDVM_INST__OUTPUT 34 //1 + output_length +#define TCOMP_UDVM_INST__END_MESSAGE 35 //1 + state_length + +typedef struct tcomp_inst_desc_s +{ + int32_t code; + const char* desc; +} +tcomp_inst_desc_t; + +static const tcomp_inst_desc_t TCOMP_INST_DESCRIPTIONS[] = +{ + { TCOMP_UDVM_INST__DECOMPRESSION_FAILURE, "DECOMPRESSION_FAILURE"}, + { TCOMP_UDVM_INST__AND, "AND"}, + { TCOMP_UDVM_INST__OR, "OR"}, + { TCOMP_UDVM_INST__NOT, "NOT"}, + { TCOMP_UDVM_INST__LSHIFT, "LSHIFT"}, + { TCOMP_UDVM_INST__RSHIFT, "RSHIFT"}, + { TCOMP_UDVM_INST__ADD, "ADD"}, + { TCOMP_UDVM_INST__SUBTRACT, "SUBTRACT"}, + { TCOMP_UDVM_INST__MULTIPLY, "MULTIPLY"}, + { TCOMP_UDVM_INST__DIVIDE, "DIVIDE"}, + { TCOMP_UDVM_INST__REMAINDER, "REMAINDER"}, + { TCOMP_UDVM_INST__SORT_ASCENDING, "SORT-ASCENDING"}, + { TCOMP_UDVM_INST__SORT_DESCENDING, "SORT-DESCENDING"}, + { TCOMP_UDVM_INST__SHA_1, "SHA-1"}, + { TCOMP_UDVM_INST__LOAD, "LOAD"}, + { TCOMP_UDVM_INST__MULTILOAD, "MULTILOAD"}, + { TCOMP_UDVM_INST__PUSH, "PUSH"}, + { TCOMP_UDVM_INST__POP, "POP"}, + { TCOMP_UDVM_INST__COPY, "COPY"}, + { TCOMP_UDVM_INST__COPY_LITERAL, "COPY-LITERAL"}, + { TCOMP_UDVM_INST__COPY_OFFSET, "COPY-OFFSET"}, + { TCOMP_UDVM_INST__MEMSET, "MEMSET"}, + { TCOMP_UDVM_INST__JUMP, "JUMP"}, + { TCOMP_UDVM_INST__COMPARE, "COMPARE"}, + { TCOMP_UDVM_INST__CALL, "CALL"}, + { TCOMP_UDVM_INST__RETURN, "RETURN"}, + { TCOMP_UDVM_INST__SWITCH, "SWITCH"}, + { TCOMP_UDVM_INST__CRC, "CRC"}, + { TCOMP_UDVM_INST__INPUT_BYTES, "INPUT-BYTES"}, + { TCOMP_UDVM_INST__INPUT_BITS, "INPUT-BITS"}, + { TCOMP_UDVM_INST__INPUT_HUFFMAN, "INPUT-HUFFMAN"}, + { TCOMP_UDVM_INST__STATE_ACCESS, "STATE-ACCESS"}, + { TCOMP_UDVM_INST__STATE_CREATE, "STATE-CREATE"}, + { TCOMP_UDVM_INST__STATE_FREE, "STATE-FREE"}, + { TCOMP_UDVM_INST__OUTPUT, "OUTPUT"}, + { TCOMP_UDVM_INST__END_MESSAGE, "END-MESSAGE"}, +}; + +#endif /* TCOMP_INSTRUCTIONS_H */ diff --git a/tinySIGCOMP/src/tcomp_manager.c b/tinySIGCOMP/src/tcomp_manager.c new file mode 100644 index 0000000..0818439 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_manager.c @@ -0,0 +1,392 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_manager.c + * @brief SigComp Manager. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_manager.h" +#include "tsk_debug.h" + +#include "tcomp_compressordisp.h" +#include "tcomp_decompressordisp.h" +#include "tcomp_statehandler.h" + +#include "tsk_object.h" +#include "tsk_safeobj.h" + +#define MAX_DMS 131072 +#define MAX_SMS 131072 +#define MAX_CPB 128 + +/**@defgroup tcomp_manager_group SigComp manager. +*/ + +/**SigComp manager. +*/ +typedef struct tcomp_manager_s +{ + TSK_DECLARE_OBJECT; + + tcomp_compressordisp_t *dispatcher_compressor; + tcomp_decompressordisp_t *dispatcher_decompressor; + tcomp_statehandler_t *stateHandler; + + TSK_DECLARE_SAFEOBJ; +} +tcomp_manager_t; + + +/**Creates new SigComp manager. +*/ +tcomp_manager_handle_t* tcomp_manager_create() +{ + return tsk_object_new(tcomp_manager_def_t); +} + +/** Defines whether the compressor must only use ACKed states (should be false) +*/ +int tcomp_manager_setUseOnlyACKedStates(tcomp_manager_handle_t* self, tsk_bool_t useOnlyACKedStates) +{ + if(!self){ + TSK_DEBUG_ERROR("Invalid parameter"); + return -1; + } + return tcomp_statehandler_setUseOnlyACKedStates(((tcomp_manager_t*)self)->stateHandler, useOnlyACKedStates); +} + +/**@ingroup tcomp_manager_group +*/ +tsk_size_t tcomp_manager_compress(tcomp_manager_handle_t *handle, const void* compartmentId, tsk_size_t compartmentIdSize, const void* input_ptr, tsk_size_t input_size, void* output_ptr, tsk_size_t output_size, tsk_bool_t stream) +{ + tcomp_manager_t *manager = handle; + tsk_size_t ret_size = output_size; + + if(!manager){ + TSK_DEBUG_ERROR("Invalid parameter"); + return 0; + } + + if(tcomp_compressordisp_compress(manager->dispatcher_compressor, tcomp_buffer_createHash(compartmentId, compartmentIdSize), + input_ptr, input_size, output_ptr, &ret_size, stream)) + { + return ret_size; + } + + return 0; +} + +/**@ingroup tcomp_manager_group +*/ +tsk_size_t tcomp_manager_decompress(tcomp_manager_handle_t *handle, const void* input_ptr, tsk_size_t input_size, tcomp_result_t *lpResult) +{ + tcomp_manager_t *manager = handle; + + if(!manager){ + TSK_DEBUG_ERROR("Invalid parameter"); + return 0; + } + + if(!lpResult || !lpResult->output_buffer){ + TSK_DEBUG_ERROR("You MUST initialize the sigcomp result and set a valid output buffer."); + return 0; + } + + /* Reset previous values */ + tcomp_result_reset(lpResult); + + if(tcomp_decompressordisp_decompress(manager->dispatcher_decompressor, input_ptr, input_size, lpResult)){ + return *tcomp_buffer_getIndexBytes(lpResult->output_buffer); + } + + return 0; +} + +/**@ingroup tcomp_manager_group +*/ +tsk_size_t tcomp_manager_getNextStreamMessage(tcomp_manager_handle_t *handle, tcomp_result_t *lpResult) +{ + tcomp_manager_t *manager = handle; + if(!manager){ + TSK_DEBUG_ERROR("Invalid parameter"); + return 0; + } + + if(!lpResult || !tcomp_buffer_getSize(lpResult->output_buffer)){ + TSK_DEBUG_ERROR("Invalid result."); + return 0; + } + + if(!lpResult->isStreamBased){ + TSK_DEBUG_ERROR("You MUST provide stream buffer."); + return 0; + } + + _tcomp_result_reset(lpResult, tsk_false, tsk_false); + + if(tcomp_decompressordisp_getNextMessage(manager->dispatcher_decompressor, lpResult)){ + return *tcomp_buffer_getIndexBytes(lpResult->output_buffer); + } + + return 0; +} + +/**@ingroup tcomp_manager_group +*/ +void tcomp_manager_provideCompartmentId(tcomp_manager_handle_t *handle, tcomp_result_t *lpResult) +{ + tcomp_manager_t *manager = handle; + if(!manager){ + TSK_DEBUG_ERROR("Invalid parameter"); + return; + } + + tcomp_statehandler_handleResult(manager->stateHandler, &lpResult); +} + +/**@ingroup tcomp_manager_group +*/ +void tcomp_manager_closeCompartment(tcomp_manager_handle_t *handle, const void *compartmentId, tsk_size_t compartmentIdSize) +{ + tcomp_manager_t *manager = handle; + if(!manager){ + TSK_DEBUG_ERROR("Invalid parameter"); + return; + } + + tcomp_statehandler_deleteCompartment(manager->stateHandler, tcomp_buffer_createHash(compartmentId, compartmentIdSize)); +} + +/**@ingroup tcomp_manager_group +* Sets the decompression memory size (RFC 3320 section 3.3). +* @param handle The SigComp manager. +* @param dms The new decompression memory size value. +* @retval Zero if succeed and non-zero error code otherwise. +*/ +int tcomp_manager_setDecompression_Memory_Size(tcomp_manager_handle_t *handle, uint32_t dms) +{ + tcomp_manager_t *manager = handle; + if(!manager){ + TSK_DEBUG_ERROR("Invalid parameter"); + return -1; + } + + return tcomp_params_setDmsValue(manager->stateHandler->sigcomp_parameters, (dms > MAX_DMS ? MAX_DMS : dms)); +} + +/**@ingroup tcomp_manager_group +* Gets the decompression memory size (RFC 3320 section 3.3). +* @param handle The SigComp manager. +* @retval The current decompression memory size value. +*/ +uint32_t tcomp_manager_getDecompression_Memory_Size(tcomp_manager_handle_t *handle) +{ + tcomp_manager_t *manager = handle; + if(!manager){ + TSK_DEBUG_ERROR("Invalid parameter"); + return 0; + } + return (manager->stateHandler && manager->stateHandler->sigcomp_parameters) + ? manager->stateHandler->sigcomp_parameters->dmsValue + : 0; +} + +/**@ingroup tcomp_manager_group +* Sets the state memory size (RFC 3320 section 3.3). +* @param handle The SigComp manager. +* @param sms The new state memory size value. +* @retval Zero if succeed and non-zero error code otherwise. +*/ +int tcomp_manager_setState_Memory_Size(tcomp_manager_handle_t *handle, uint32_t sms) +{ + tcomp_manager_t *manager = handle; + if(!manager){ + TSK_DEBUG_ERROR("Invalid parameter"); + return -1; + } + + return tcomp_params_setSmsValue(manager->stateHandler->sigcomp_parameters, (sms > MAX_SMS ? MAX_SMS : sms)); +} + +/**@ingroup tcomp_manager_group +* Sets the Cycle Per Bit (RFC 3320 section 3.3). +* @param handle The SigComp manager. +* @param cpb The new cycle per bit value. +* @retval Zero if succeed and non-zero error code otherwise. +*/ +int tcomp_manager_setCycles_Per_Bit(tcomp_manager_handle_t *handle, uint8_t cpb) +{ + tcomp_manager_t *manager = handle; + if(!manager){ + TSK_DEBUG_ERROR("Invalid parameter"); + return -1; + } + + return tcomp_params_setCpbValue(manager->stateHandler->sigcomp_parameters, (cpb > MAX_CPB ? MAX_CPB : cpb)); +} + +/**@ingroup tcomp_manager_group +* Sets the SigComp version (RFC 3320 section 3.3). +* @param handle The SigComp manager. +* @param version The SigComp version. Only 2.0 is supported. +* @retval Zero if succeed and non-zero error code otherwise. +*/ +int tcomp_manager_setSigComp_Version(tcomp_manager_handle_t *handle, uint8_t version) +{ + tcomp_manager_t *manager = handle; + if(!manager){ + TSK_DEBUG_ERROR("Invalid parameter"); + return -1; + } + + manager->stateHandler->sigcomp_parameters->SigComp_version = version; + return 0; +} + +/**@ingroup tcomp_manager_group +* Adds a new compressor to the dispatcher. +* @param handle The SigComp manager holding the dispatcher. +* @param compressor The compressor to add. +* @retval Zero if succeed and non-zero error code otherwise. +*/ +int tcomp_manager_addCompressor(tcomp_manager_handle_t *handle, tcomp_compressor_compress_f compressor) +{ + tcomp_manager_t *manager = handle; + if(!manager){ + TSK_DEBUG_ERROR("Invalid parameter"); + return -1; + } + + return tcomp_compressordisp_addCompressor(manager->dispatcher_compressor, compressor); +} + +/**@ingroup tcomp_manager_group +* Removes the compressor from the dispatcher. +* @param handle The SigComp manager holding the dispatcher. +* @param compressor The compressor to add. +* @retval Zero if succeed and non-zero error code otherwise. +*/ +int tcomp_manager_removeCompressor(tcomp_manager_handle_t *handle, tcomp_compressor_compress_f compressor) +{ + tcomp_manager_t *manager = handle; + if(!manager){ + TSK_DEBUG_ERROR("Invalid parameter"); + return -1; + } + + return tcomp_compressordisp_removeCompressor(manager->dispatcher_compressor, compressor); +} + +/**@ingroup tcomp_manager_group +* Adds SIP/SDP dictionary (RFC 3485) to the state handler. +* @param handle The SigComp manager holding the state handler. +* @retval Zero if succeed and non-zero otherwise. +*/ +int tcomp_manager_addSipSdpDictionary(tcomp_manager_handle_t *handle) +{ + tcomp_manager_t *manager = handle; + if(!manager){ + TSK_DEBUG_ERROR("Invalid parameter"); + return -1; + } + + return tcomp_statehandler_addSipSdpDictionary(manager->stateHandler); +} + +/**@ingroup tcomp_manager_group +* Adds Presence dictionary (RFC 5112) to the state handler. +* @param handle The SigComp manager holding the state handler. +* @retval Zero if succeed and non-zero otherwise. +*/ +int tcomp_manager_addPresenceDictionary(tcomp_manager_handle_t *handle) +{ + tcomp_manager_t *manager = handle; + if(!manager){ + TSK_DEBUG_ERROR("Invalid parameter"); + return -1; + } + + return tcomp_statehandler_addPresenceDictionary(manager->stateHandler); +} + + + + + + + + + + + +//======================================================== +// SigComp manager object definition +// + +static void* tcomp_manager_ctor(void * self, va_list * app) +{ + tcomp_manager_t *manager = self; + if(manager) + { + manager->stateHandler = tcomp_statehandler_create(); + manager->dispatcher_compressor = tcomp_compressordisp_create(manager->stateHandler); + manager->dispatcher_decompressor = tcomp_decompressordisp_create(manager->stateHandler); + + /* Initialize safeobject */ + tsk_safeobj_init(manager); + } + else{ + TSK_DEBUG_ERROR("Failed to create new manager."); + } + + return self; +} + +static void* tcomp_manager_dtor(void *self) +{ + tcomp_manager_t *manager = self; + if(manager){ + TSK_OBJECT_SAFE_FREE(manager->stateHandler); + TSK_OBJECT_SAFE_FREE(manager->dispatcher_compressor); + TSK_OBJECT_SAFE_FREE(manager->dispatcher_decompressor); + + /* Deinitialize safeobject */ + tsk_safeobj_deinit(manager); + } + else{ + TSK_DEBUG_ERROR("Null manager."); + } + + return self; +} + +static const tsk_object_def_t tcomp_manager_def_s = +{ + sizeof(tcomp_manager_t), + tcomp_manager_ctor, + tcomp_manager_dtor, + tsk_null +}; +const tsk_object_def_t *tcomp_manager_def_t = &tcomp_manager_def_s; diff --git a/tinySIGCOMP/src/tcomp_manager.h b/tinySIGCOMP/src/tcomp_manager.h new file mode 100644 index 0000000..477c438 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_manager.h @@ -0,0 +1,88 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_manager.h + * @brief SigComp Manager. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#ifndef TCOMP_MANAGER_H +#define TCOMP_MANAGER_H + +#include "tinysigcomp_config.h" + +#include "tcomp_result.h" +#include "tcomp_compressor.h" +#include "tcomp_nackinfo.h" + +TCOMP_BEGIN_DECLS + +typedef void tcomp_manager_handle_t; + +TINYSIGCOMP_API tcomp_manager_handle_t* tcomp_manager_create(); +TINYSIGCOMP_API int tcomp_manager_setUseOnlyACKedStates(tcomp_manager_handle_t* self, tsk_bool_t useOnlyACKedStates); + +// +// Compression / Decompression +// +TINYSIGCOMP_API tsk_size_t tcomp_manager_compress(tcomp_manager_handle_t *handle, const void* compartmentId, tsk_size_t compartmentIdSize, const void* input_ptr, tsk_size_t input_size, void* output_ptr, tsk_size_t output_size, tsk_bool_t stream); +#define tcomp_manager_compressUDP(handle, compartmentId, compartmentIdSize, input_ptr, input_size, output_ptr, output_size) tcomp_manager_compress((tcomp_manager_handle_t *)handle, (const void*) compartmentId, (tsk_size_t) compartmentIdSize, (const void*) input_ptr, (tsk_size_t) input_size, (void*) output_ptr, (tsk_size_t) output_size, tsk_false) +#define tcomp_manager_compressTCP(handle, compartmentId, compartmentIdSize, input_ptr, input_size, output_ptr, output_size) tcomp_manager_compress((tcomp_manager_handle_t *)handle, (const void*) compartmentId, (tsk_size_t) compartmentIdSize, (const void*) input_ptr, (tsk_size_t) input_size, (void*) output_ptr, (tsk_size_t) output_size, tsk_true) +#define tcomp_manager_compressSCTP compressTCP + +TINYSIGCOMP_API tsk_size_t tcomp_manager_decompress(tcomp_manager_handle_t *handle, const void* input_ptr, tsk_size_t input_size, tcomp_result_t *lpResult); +TINYSIGCOMP_API tsk_size_t tcomp_manager_getNextStreamMessage(tcomp_manager_handle_t *handle, tcomp_result_t *lpResult); + +/* +* Compartment management +*/ +TINYSIGCOMP_API void tcomp_manager_provideCompartmentId(tcomp_manager_handle_t *handle, tcomp_result_t *lpResult); +TINYSIGCOMP_API void tcomp_manager_closeCompartment(tcomp_manager_handle_t *handle, const void *compartmentId, tsk_size_t compartmentIdSize); + +/* +* SigComp Parameters +*/ +TINYSIGCOMP_API int tcomp_manager_setDecompression_Memory_Size(tcomp_manager_handle_t *handle, uint32_t dms); +TINYSIGCOMP_API uint32_t tcomp_manager_getDecompression_Memory_Size(tcomp_manager_handle_t *handle); +TINYSIGCOMP_API int tcomp_manager_setState_Memory_Size(tcomp_manager_handle_t *handle, uint32_t sms); +TINYSIGCOMP_API int tcomp_manager_setCycles_Per_Bit(tcomp_manager_handle_t *handle, uint8_t cpb); +TINYSIGCOMP_API int tcomp_manager_setSigComp_Version(tcomp_manager_handle_t *handle, uint8_t version); + +/* +* Compressors +*/ +TINYSIGCOMP_API int tcomp_manager_addCompressor(tcomp_manager_handle_t *handle, tcomp_compressor_compress_f compressor); +TINYSIGCOMP_API int tcomp_manager_removeCompressor(tcomp_manager_handle_t *handle, tcomp_compressor_compress_f compressor); + +/* +* Dictionnaries +*/ +TINYSIGCOMP_API int tcomp_manager_addSipSdpDictionary(tcomp_manager_handle_t *handle); +TINYSIGCOMP_API int tcomp_manager_addPresenceDictionary(tcomp_manager_handle_t *handle); + +TINYSIGCOMP_GEXTERN const tsk_object_def_t *tcomp_manager_def_t; + +TCOMP_END_DECLS + +#endif /* TCOMP_MANAGER_H */ diff --git a/tinySIGCOMP/src/tcomp_message.c b/tinySIGCOMP/src/tcomp_message.c new file mode 100644 index 0000000..6cecb79 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_message.c @@ -0,0 +1,390 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_message.c + * @brief SIGCOMP message as per RFC 3320 subclause 7. + * A message sent from the compressor dispatcher to the decompressordispatcher. In case of a message-based transport such as UDP, a + * SigComp message corresponds to exactly one datagram. For a stream-based transport such as TCP, the SigComp messages are + * separated by reserved delimiters. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_message.h" +#include "tcomp_nack_codes.h" + +#include "tsk_memory.h" +#include "tsk_debug.h" +#include "tsk_binaryutils.h" +#include "tsk_sha1.h" + +#include <string.h> + +#define MIN_LEN 2 +#define HEADER_GET_LEN(message) (message->headerSigComp & 0x03) +#define HEADER_GET_T(message) (message->headerSigComp & 0x04) +#define HEADER_IS_VALID(message) (message->headerSigComp >= 0xf8) + +#define HEADER_GET_DEST_VALUE(destination) ( sigcomp_encoding_destination[destination] ) +#define HEADER_GET_STATE_LENGTH(length) ( sigcomp_encoding_partial_id_length[length] ) + +static void initFeedbackItem(tcomp_message_t *message, uint8_t** start_ptr); +static void initStateId(tcomp_message_t *message, uint8_t** start_ptr, uint8_t state_len); +static void initStateful(tcomp_message_t *message, uint8_t** start_ptr, uint8_t* end_ptr); +static void initStateless(tcomp_message_t *message, uint8_t** start_ptr, uint8_t* end_ptr, int32_t *nack_code); +static void initNack(tcomp_message_t *message, uint8_t** start_ptr, uint8_t* end_ptr, int32_t* nack_code); + +/* +Creates new SigComp message. +*/ +tcomp_message_t* tcomp_message_create(const void* input_ptr, tsk_size_t input_size, tsk_bool_t stream, int32_t* nack_code) +{ + tcomp_message_t *message; + + if(!nack_code){ + TSK_DEBUG_ERROR("Invalid parameter"); + return tsk_null; + } + + if(!input_ptr){ + TSK_DEBUG_ERROR("Invalid parameter"); + *nack_code = NACK_INTERNAL_ERROR; + return tsk_null; + } + + if(input_size < MIN_LEN){ + TSK_DEBUG_ERROR("MESSAGE_TOO_SHORT"); + *nack_code = NACK_MESSAGE_TOO_SHORT; + return tsk_null; + } + + if((message = tsk_object_new(tcomp_message_def_t))){ + uint8_t *dummy_ptr, *end_ptr; + uint8_t state_len; + + message->startPtr = input_ptr; + message->stateId = tcomp_buffer_create_null(); + message->remaining_sigcomp_buffer = tcomp_buffer_create_null(); + message->uploaded_UDVM_buffer = tcomp_buffer_create_null(); + message->ret_feedback_buffer= tcomp_buffer_create_null(); + + message->isNack = 0; + dummy_ptr = ((uint8_t*)input_ptr); + end_ptr = (dummy_ptr + input_size); + + // + message->totalSize = input_size; + message->stream_based = stream; + message->bytecodes_destination = 0; + + /* Get sigcomp header */ + message->headerSigComp = *dummy_ptr; + dummy_ptr++; + + /* Check message validity --> magic code (11111)? */ + message->isOK = HEADER_IS_VALID(message); + if(!message->isOK){ + TSK_DEBUG_ERROR("SigComp Message not valid (magic code mismatch)"); + *nack_code = NACK_INTERNAL_ERROR; + goto bail; + } + + /* Feedback item */ + if((HEADER_GET_T(message)!=0)){ + initFeedbackItem(message, &dummy_ptr); + if(!message->isOK){ + goto bail; + } + } + + /* + * If the len field is non-zero, then the SigComp message contains a state identifier + * to access a state item at the receiving endpoint. + */ + state_len = HEADER_GET_STATE_LENGTH( HEADER_GET_LEN(message) ); + if(state_len){ + initStateId(message, &dummy_ptr, state_len); + initStateful(message, &dummy_ptr, end_ptr); + TSK_DEBUG_INFO("SigComp - Decompressing stateful message with state id ="); + tcomp_buffer_print(message->stateId); + } + else + { + if( !*dummy_ptr && !(*(dummy_ptr+1)&0xf0) ){ + // "code_len" field of zero --> it's a nack + initNack(message, &dummy_ptr, end_ptr, nack_code); + } + else{ + initStateless(message, &dummy_ptr, end_ptr, nack_code); + } + } + + /* + * The fields (RFC 3320 section 7) except for the "remaining SigComp message" are referred to + * as the "SigComp header" (note that this may include the uploaded UDVM bytecode). + */ + if(message->isOK){ + message->header_size = ( message->totalSize - tcomp_buffer_getSize(message->remaining_sigcomp_buffer)); + } + } + else{ + TSK_DEBUG_ERROR("Failed to create new SigComp message"); + } + +bail: + if(message && !message->isOK){ + TSK_OBJECT_SAFE_FREE(message); + } + + return message; +} + +/* +Iniatizes the feedback item field. +*/ +static void initFeedbackItem(tcomp_message_t *message, uint8_t** start_ptr) +{ + /* + 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 + +---+---+---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+ + | 0 | returned_feedback_field | | 1 | returned_feedback_length | + +---+---+---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+ + | | + : returned_feedback_field : + | | + +---+---+---+---+---+---+---+---+ + */ + if((**start_ptr) <= 128){ + tcomp_buffer_referenceBuff(message->ret_feedback_buffer, *start_ptr, 1); + (void)(*start_ptr++); + } + else{ + tcomp_buffer_referenceBuff(message->ret_feedback_buffer, *start_ptr, 1+(**start_ptr&0x7f)); + *start_ptr += tcomp_buffer_getSize(message->ret_feedback_buffer); + } +} + +/* +Initializes the state identifier field. +*/ +static void initStateId(tcomp_message_t *message, uint8_t** start_ptr, uint8_t state_len) +{ + tcomp_buffer_referenceBuff(message->stateId, *start_ptr, state_len); + *start_ptr += state_len; +} + +/* +Initializes a stateful SigComp message. +*/ +static void initStateful(tcomp_message_t *message, uint8_t** start_ptr, uint8_t* end_ptr) +{ + /* + +---+---+---+---+---+---+---+---+ + | | + : partial state identifier : + | | + +---+---+---+---+---+---+---+---+ + | | + : remaining SigComp message : + | | + +---+---+---+---+---+---+---+---+ + */ + message->isOK &= (*start_ptr<=end_ptr); + if(message->isOK){ + tcomp_buffer_referenceBuff(message->remaining_sigcomp_buffer, *start_ptr, + ((end_ptr-*start_ptr))); + } +} + +/* +Initializes a stateless SigComp message. +*/ +static void initStateless(tcomp_message_t *message, uint8_t** start_ptr, uint8_t* end_ptr, int32_t *nack_code) +{ + int has_bytecode = (HEADER_GET_LEN(message) == 0); // No state ==> message contains udvm bytecode + message->isOK &= has_bytecode; + if(!message->isOK) return; + + /* + +---+---+---+---+---+---+---+---+ + | code_len | + +---+---+---+---+---+---+---+---+ + | code_len | destination | + +---+---+---+---+---+---+---+---+ + | | + : uploaded UDVM bytecode : + | | + +---+---+---+---+---+---+---+---+ + | | + : remaining SigComp message : + | | + +---+---+---+---+---+---+---+---+ + */ + { + uint32_t code_len1, bytecodes_len; + uint8_t code_len2, destination, *bytecodes_uploaded_udvm, *remaining_SigComp_message; + + uint8_t* dummy_ptr = ((uint8_t*)*start_ptr); + + /* Code_len --> 12bits [8+4] */ + code_len1 = *dummy_ptr; dummy_ptr++; /* skip first code_len 8bits */ + code_len2 = (*dummy_ptr) & 0xf0; /* code_len 4 remaining bits */ + destination = (*dummy_ptr) & 0x0f; /* 4bits after code_len */ + dummy_ptr++; /* skip code_len 4bits + destination 4bits ==> 1-byte */ + + /* Get bytecodes length (12bits) */ + bytecodes_len = ( (code_len1<<4)|(code_len2>>4) ); + + /* Starting memory address (code destination address). In UDVM. */ + message->bytecodes_destination = HEADER_GET_DEST_VALUE(destination); + if((message->bytecodes_destination < 128) || (message->bytecodes_destination > 1024)){ + TSK_DEBUG_ERROR("INVALID_CODE_LOCATION"); + *nack_code = NACK_INVALID_CODE_LOCATION; + message->isOK = 0; + return; + } + + /* Uploaded UDVM pointer */ + bytecodes_uploaded_udvm = dummy_ptr; /* SigComp header, feedback_item, code_len and destination have been skipped */ + + /* Skip uploaded udvm */ + dummy_ptr += bytecodes_len; + + /* remaining SigComp message */ + remaining_SigComp_message = dummy_ptr; + + /* check that remaining sigcomp message is valide */ + if( !(message->isOK &= (remaining_SigComp_message <= end_ptr )) ){ + TSK_DEBUG_ERROR("MESSAGE_TOO_SHORT"); + *nack_code = NACK_MESSAGE_TOO_SHORT; + return; + } + + // + // Setting buffers + // + tcomp_buffer_referenceBuff(message->uploaded_UDVM_buffer, bytecodes_uploaded_udvm, bytecodes_len); + tcomp_buffer_referenceBuff(message->remaining_sigcomp_buffer, remaining_SigComp_message, ((end_ptr-remaining_SigComp_message))); + } +} + +/* +Initializes a NACK message as per RFC 4077. +*/ +static void initNack(tcomp_message_t *message, uint8_t** start_ptr, uint8_t* end_ptr, int32_t* nack_code) +{ + /* + +---+---+---+---+---+---+---+---+ + | code_len = 0 | + +---+---+---+---+---+---+---+---+ + | code_len = 0 | version = 1 | + +---+---+---+---+---+---+---+---+ + | Reason Code | + +---+---+---+---+---+---+---+---+ + | OPCODE of failed instruction | + +---+---+---+---+---+---+---+---+ + | PC of failed instruction | + | | + +---+---+---+---+---+---+---+---+ + | | + : SHA-1 Hash of failed message : + | | + +---+---+---+---+---+---+---+---+ + | | + : Error Details : + | | + +---+---+---+---+---+---+---+---+*/ + + uint8_t* dummy_ptr; + message->isNack = 1; + if( (end_ptr - *start_ptr)<25 ){ + *nack_code = NACK_MESSAGE_TOO_SHORT; + TSK_DEBUG_ERROR("MESSAGE_TOO_SHORT"); + message->isOK = 0; + return; + } + + dummy_ptr = ((uint8_t*)*start_ptr); + dummy_ptr++; /* skip first code_len byte */ + if(!(message->isOK = (*dummy_ptr++ == NACK_VERSION))) { + return; + } + + if(!message->nack_info){ + message->nack_info = tcomp_nackinfo_create(); + } + + message->nack_info->reasonCode = *dummy_ptr++; + message->nack_info->opcode = *dummy_ptr++; + message->nack_info->pc = TSK_BINARY_GET_2BYTES(dummy_ptr); dummy_ptr+=2; + memcpy(message->nack_info->sha1, dummy_ptr, TSK_SHA1_DIGEST_SIZE); dummy_ptr += TSK_SHA1_DIGEST_SIZE; + if(dummy_ptr < end_ptr){ + /* Has error details */ + tcomp_buffer_appendBuff(message->nack_info->details, dummy_ptr, (end_ptr-dummy_ptr)); + } +} + + + + + +//======================================================== +// SigComp message object definition +// + +static tsk_object_t* tcomp_message_ctor(tsk_object_t *self, va_list * app) +{ + tcomp_message_t *message = self; + + if(message){ + } + + return self; +} + +static tsk_object_t* tcomp_message_dtor(tsk_object_t *self) +{ + tcomp_message_t *message = self; + + if(message){ + TSK_OBJECT_SAFE_FREE(message->stateId); + TSK_OBJECT_SAFE_FREE(message->remaining_sigcomp_buffer); + TSK_OBJECT_SAFE_FREE(message->uploaded_UDVM_buffer); + TSK_OBJECT_SAFE_FREE(message->ret_feedback_buffer); + TSK_OBJECT_SAFE_FREE(message->nack_info); + } + else{ + TSK_DEBUG_WARN("NULL SigComp message."); + } + + return self; +} + +static const tsk_object_def_t tcomp_message_def_s = +{ + sizeof(tcomp_message_t), + tcomp_message_ctor, + tcomp_message_dtor, + tsk_null +}; +const tsk_object_def_t* tcomp_message_def_t = &tcomp_message_def_s; diff --git a/tinySIGCOMP/src/tcomp_message.h b/tinySIGCOMP/src/tcomp_message.h new file mode 100644 index 0000000..9d5b41d --- /dev/null +++ b/tinySIGCOMP/src/tcomp_message.h @@ -0,0 +1,74 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_message.h + * @brief SIGCOMP message as per RFC 3320 subclause 7. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#ifndef TCOMP_MESSAGE_H +#define TCOMP_MESSAGE_H + +#include "tinysigcomp_config.h" +#include "tcomp_buffer.h" +#include "tcomp_nackinfo.h" +#include "tsk_object.h" + +TCOMP_BEGIN_DECLS + + +/** +* SigComp Message Format as per RFC 3320 subclause 7. +*/ +typedef struct tcomp_message_s +{ + TSK_DECLARE_OBJECT; + + uint8_t headerSigComp; /**< SigComp header */ + + unsigned isOK:1; /**< Message validity. */ + unsigned isNack:1; /**< If it's a NACK message. */ + unsigned stream_based:1; /**< If it's stream message (e.g. TCP) */ + const uint8_t* startPtr; /**< Message pointer. */ + tsk_size_t totalSize; /**< The total message size. */ + tsk_size_t header_size; /**< The size of the message header */ + + tcomp_buffer_handle_t* stateId; /**< */ + + uint32_t bytecodes_destination; /**< */ + tcomp_buffer_handle_t* remaining_sigcomp_buffer; /**< */ + tcomp_buffer_handle_t* uploaded_UDVM_buffer; /**< */ + tcomp_buffer_handle_t* ret_feedback_buffer; /**< */ + + tcomp_nackinfo_t* nack_info; /**< */ +} +tcomp_message_t; + +tcomp_message_t* tcomp_message_create(const void* input_ptr, tsk_size_t input_size, tsk_bool_t stream, int32_t *nack_code); + +TINYSIGCOMP_GEXTERN const tsk_object_def_t *tcomp_message_def_t; + +TCOMP_END_DECLS + +#endif /* TCOMP_MESSAGE_H */ diff --git a/tinySIGCOMP/src/tcomp_nack_codes.h b/tinySIGCOMP/src/tcomp_nack_codes.h new file mode 100644 index 0000000..76eb33f --- /dev/null +++ b/tinySIGCOMP/src/tcomp_nack_codes.h @@ -0,0 +1,135 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_nack_codes.h + * @brief List of NACK codes as per RFC 4077 subclause 3.2. + * + */ + +#ifndef TCOMP_NACKCODES_H +#define TCOMP_NACKCODES_H + +/* 0 1 2 3 4 5 6 7 + +---+---+---+---+---+---+---+---+ + | 1 1 1 1 1 | T | 0 | + +---+---+---+---+---+---+---+---+ + | | + : returned feedback item : + | | + +---+---+---+---+---+---+---+---+ + | code_len = 0 | + +---+---+---+---+---+---+---+---+ + | code_len = 0 | version = 1 | + +---+---+---+---+---+---+---+---+ + | Reason Code | + +---+---+---+---+---+---+---+---+ + | OPCODE of failed instruction | + +---+---+---+---+---+---+---+---+ + | PC of failed instruction | + | | + +---+---+---+---+---+---+---+---+ + | | + : SHA-1 Hash of failed message : + | | + +---+---+---+---+---+---+---+---+ + | | + : Error Details : + | | + +---+---+---+---+---+---+---+---+ +*/ +#define INDEX_NACK_HEADER 0 +#define INDEX_NACK_VERSION (INDEX_NACK_HEADER+ 2) +#define INDEX_NACK_REASON_CODE (INDEX_NACK_VERSION + 1) +#define INDEX_NACK_OPCODE (INDEX_NACK_REASON_CODE + 1) +#define INDEX_NACK_PC (INDEX_NACK_OPCODE + 1) +#define INDEX_NACK_SHA1 (INDEX_NACK_PC + 2) +#define INDEX_NACK_DETAILS (INDEX_NACK_PC + SHA1HashSize) + +/************************************************************************************ +* Error code details +*************************************************************************************/ +#define NACK_NONE 0 // For internal use only +#define NACK_STATE_NOT_FOUND 1 // State ID (6 - 20 bytes) +#define NACK_CYCLES_EXHAUSTED 2 // Cycles Per Bit (1 byte) +#define NACK_USER_REQUESTED 3 +#define NACK_SEGFAULT 4 +#define NACK_TOO_MANY_STATE_REQUESTS 5 +#define NACK_INVALID_STATE_ID_LENGTH 6 +#define NACK_INVALID_STATE_PRIORITY 7 +#define NACK_OUTPUT_OVERFLOW 8 +#define NACK_STACK_UNDERFLOW 9 +#define NACK_BAD_INPUT_BITORDER 10 +#define NACK_DIV_BY_ZERO 11 +#define NACK_SWITCH_VALUE_TOO_HIGH 12 +#define NACK_TOO_MANY_BITS_REQUESTED 13 +#define NACK_INVALID_OPERAND 14 +#define NACK_HUFFMAN_NO_MATCH 15 +#define NACK_MESSAGE_TOO_SHORT 16 +#define NACK_INVALID_CODE_LOCATION 17 +#define NACK_BYTECODES_TOO_LARGE 18 // Memory size (2 bytes) +#define NACK_INVALID_OPCODE 19 +#define NACK_INVALID_STATE_PROBE 20 +#define NACK_ID_NOT_UNIQUE 21 // State ID (6 - 20 bytes) +#define NACK_MULTILOAD_OVERWRITTEN 22 +#define NACK_STATE_TOO_SHORT 23 // State ID (6 - 20 bytes) +#define NACK_INTERNAL_ERROR 24 +#define NACK_FRAMING_ERROR 25 + + +typedef struct tcomp_nack_desc_s +{ + int32_t code; + const char* desc; +} +tcomp_nack_desc_t; + +static const tcomp_nack_desc_t TCOMP_NACK_DESCRIPTIONS[] = +{ + { NACK_NONE, "NONE" }, + { NACK_STATE_NOT_FOUND, "STATE_NOT_FOUND" }, + { NACK_CYCLES_EXHAUSTED, "CYCLES_EXHAUSTED" }, + { NACK_USER_REQUESTED, "USER_REQUESTED" }, + { NACK_SEGFAULT, "SEGFAULT" }, + { NACK_TOO_MANY_STATE_REQUESTS, "TOO_MANY_STATE_REQUESTS" }, + { NACK_INVALID_STATE_ID_LENGTH, "INVALID_STATE_ID_LENGTH" }, + { NACK_INVALID_STATE_PRIORITY, "INVALID_STATE_PRIORITY" }, + { NACK_OUTPUT_OVERFLOW, "OUTPUT_OVERFLOW" }, + { NACK_STACK_UNDERFLOW, "STACK_UNDERFLOW" }, + { NACK_BAD_INPUT_BITORDER, "BAD_INPUT_BITORDER" }, + { NACK_DIV_BY_ZERO, "DIV_BY_ZERO" }, + { NACK_SWITCH_VALUE_TOO_HIGH, "SWITCH_VALUE_TOO_HIGH" }, + { NACK_TOO_MANY_BITS_REQUESTED, "TOO_MANY_BITS_REQUESTED" }, + { NACK_INVALID_OPERAND, "INVALID_OPERAND" }, + { NACK_HUFFMAN_NO_MATCH, "HUFFMAN_NO_MATCH" }, + { NACK_MESSAGE_TOO_SHORT, "MESSAGE_TOO_SHORT" }, + { NACK_INVALID_CODE_LOCATION, "INVALID_CODE_LOCATION" }, + { NACK_BYTECODES_TOO_LARGE, "BYTECODES_TOO_LARGE" }, + { NACK_INVALID_OPCODE, "INVALID_OPCODE" }, + { NACK_INVALID_STATE_PROBE, "INVALID_STATE_PROBE" }, + { NACK_ID_NOT_UNIQUE, "ID_NOT_UNIQUE" }, + { NACK_MULTILOAD_OVERWRITTEN, "MULTILOAD_OVERWRITTEN" }, + { NACK_STATE_TOO_SHORT, "STATE_TOO_SHORT" }, + { NACK_INTERNAL_ERROR, "INTERNAL_ERROR" }, + { NACK_FRAMING_ERROR, "FRAMING_ERROR" } +}; + +#endif /* TCOMP_NACKCODES_H */ diff --git a/tinySIGCOMP/src/tcomp_nackinfo.c b/tinySIGCOMP/src/tcomp_nackinfo.c new file mode 100644 index 0000000..fb7b58c --- /dev/null +++ b/tinySIGCOMP/src/tcomp_nackinfo.c @@ -0,0 +1,227 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_nackinfo.c + * @brief RFC 4077 - A Negative Acknowledgement Mechanism for Signaling Compression (NACK). + */ +#include "tcomp_nackinfo.h" +#include "tcomp_message.h" +#include "tcomp_nack_codes.h" + +#include "tsk_sha1.h" +#include "tsk_memory.h" +#include "tsk_debug.h" + +/* "OPCODE of failed instruction" is a one-byte field that includes +the opcode to which the PC was pointing when the failure occurred. +If failure occurred before the UDVM began executing any code, this +field is set to 0. +*/ +#define OPCODE_UNKNOWN 0 +/* "PC of failed instruction" is a two-byte field containing the + value of the program counter when failure occurred (i.e., the + memory address of the failed UDVM instruction). The field is + encoded with the most significant byte of the PC first (i.e., in + network or big endian order). If failure occurred before the UDVM + began executing any code, this field is set to 0. +*/ +#define PC_UNKNOWN 0 + +/** Creates new NACK object */ +tcomp_nackinfo_t* tcomp_nackinfo_create() +{ + tcomp_nackinfo_t *nackinfo; + if((nackinfo = tsk_object_new(tcomp_nackinfo_def_t))){ + nackinfo->version = NACK_VERSION; + nackinfo->details = tcomp_buffer_create_null(); + } + return nackinfo; +} + +int tcomp_nackinfo_write(tcomp_buffer_handle_t* buffer, + uint8_t reasonCode, + uint8_t opCode, + int16_t memory_address_of_instruction, + const void* sigCompMessagePtr, tsk_size_t sigCompMessageSize, + tcomp_buffer_handle_t* lpDetails, + uint16_t udvm_size, + uint8_t cpbValue) +{ + tsk_sha1context_t sha; + uint8_t *nackbuffer_ptr; + + if(!buffer || !sigCompMessagePtr || !sigCompMessageSize){ + TSK_DEBUG_ERROR("Invalid parameter"); + return -1; + } + + tcomp_buffer_allocBuff(buffer, INDEX_NACK_SHA1 + TSK_SHA1_DIGEST_SIZE); + if(!(nackbuffer_ptr = tcomp_buffer_getBuffer(buffer))){ + TSK_DEBUG_ERROR("NACK buffer is null"); + return -2; + } + + nackbuffer_ptr[INDEX_NACK_HEADER] = 0xf8; + nackbuffer_ptr[INDEX_NACK_VERSION] = NACK_VERSION; + nackbuffer_ptr[INDEX_NACK_REASON_CODE] = reasonCode; + nackbuffer_ptr[INDEX_NACK_OPCODE] = opCode; + nackbuffer_ptr[INDEX_NACK_PC] = (memory_address_of_instruction >> 8); + nackbuffer_ptr[INDEX_NACK_PC + 1] = (memory_address_of_instruction & 0x00ff); + + // SHA-1(message) computation + tsk_sha1reset(&sha); + tsk_sha1input(&sha, sigCompMessagePtr, sigCompMessageSize); + tsk_sha1result(&sha, &nackbuffer_ptr[INDEX_NACK_SHA1]); + +#if 0 + { + int i; + TSK_DEBUG_INFO("Create NACK with id:"); + for(i = 0; i < TSK_SHA1_DIGEST_SIZE; ++i){ + printf("%x ", nackbuffer_ptr[INDEX_NACK_SHA1 + i]); + } + printf("\n"); + } +#endif + + // Details + if(lpDetails && tcomp_buffer_getSize(lpDetails)){ + tcomp_buffer_appendBuff(buffer, tcomp_buffer_getBuffer(lpDetails), tcomp_buffer_getSize(lpDetails)); + } + else if(reasonCode == NACK_BYTECODES_TOO_LARGE){ + tcomp_buffer_appendBuff(buffer, &udvm_size, 2); + } + else if(reasonCode == NACK_CYCLES_EXHAUSTED){ + tcomp_buffer_appendBuff(buffer, &cpbValue, 1); + } + + return 0; + +} + +int tcomp_nackinfo_write_2(tcomp_buffer_handle_t* buffer, + uint8_t reasonCode, + uint8_t opCode, + int16_t memory_address_of_instruction, + const tcomp_message_t* sigCompMessage, + tcomp_buffer_handle_t* lpDetails, + uint16_t udvm_size, + uint8_t cpbValue) +{ + return tcomp_nackinfo_write(buffer, + reasonCode, + opCode, + memory_address_of_instruction, + sigCompMessage->startPtr, sigCompMessage->totalSize, + lpDetails, + udvm_size, + cpbValue); +} + +int tcomp_nackinfo_write_3(tcomp_buffer_handle_t* buffer, + uint8_t reasonCode, + const void* sigCompMessagePtr, tsk_size_t sigCompMessageSize) +{ + return tcomp_nackinfo_write(buffer, + reasonCode, + OPCODE_UNKNOWN, + PC_UNKNOWN, + sigCompMessagePtr, sigCompMessageSize, + tsk_null, + 0, + 0); +} + +int tcomp_nackinfo_write_4(tcomp_buffer_handle_t* buffer, + uint8_t reasonCode, + const tcomp_message_t* sigCompMessage) +{ + return tcomp_nackinfo_write_2(buffer, + reasonCode, + OPCODE_UNKNOWN, + PC_UNKNOWN, + sigCompMessage, + tsk_null, + 0, + 0); +} + +const char* tcomp_nackinfo_get_description(const tcomp_buffer_handle_t* buffer) +{ + uint8_t reasonCode; + if(!buffer){ + TSK_DEBUG_ERROR("Invalid parameter"); + return tsk_null; + } + if(tcomp_buffer_getSize(buffer) < 3){ + TSK_DEBUG_ERROR("Too short"); + return tsk_null; + } + reasonCode = *((const uint8_t*)tcomp_buffer_getBufferAtPos(buffer, 3)); + if(reasonCode >= (sizeof(TCOMP_NACK_DESCRIPTIONS)/sizeof(TCOMP_NACK_DESCRIPTIONS[0]))){ + TSK_DEBUG_ERROR("%d not valid as reasonCode", (int32_t)reasonCode); + return tsk_null; + } + return TCOMP_NACK_DESCRIPTIONS[reasonCode].desc; +} + +//======================================================== +// NackInfo object definition +// + +/* +* Creates a nack info message. You MUST use @ref tcomp_nackinfo_destroy to free the nackinfo. +* @retval The NACK info message. +* @sa @ref tcomp_nackinfo_destroy. +*/ +static tsk_object_t* tcomp_nackinfo_ctor(tsk_object_t *self, va_list* app) +{ + tcomp_nackinfo_t *nackinfo = self; + if(nackinfo){ + } + return self; +} + +/* +* Destroy a nackinfo message previously created using @ref tcomp_nackinfo_create. +* @param nackinfo The NACK info message to free. +* @sa @ref tcomp_nackinfo_create. +*/ +static tsk_object_t* tcomp_nackinfo_dtor(tsk_object_t* self) +{ + tcomp_nackinfo_t *nackinfo = self; + if(nackinfo){ + TSK_OBJECT_SAFE_FREE(nackinfo->details); + } + return self; +} + + +static const tsk_object_def_t tcomp_nackinfo_def_s = +{ + sizeof(tcomp_nackinfo_t), + tcomp_nackinfo_ctor, + tcomp_nackinfo_dtor, + tsk_null +}; +const tsk_object_def_t* tcomp_nackinfo_def_t = &tcomp_nackinfo_def_s; + diff --git a/tinySIGCOMP/src/tcomp_nackinfo.h b/tinySIGCOMP/src/tcomp_nackinfo.h new file mode 100644 index 0000000..5a1e427 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_nackinfo.h @@ -0,0 +1,111 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_nackinfo.h + * @brief RFC 4077 - A Negative Acknowledgement Mechanism for Signaling Compression (NACK) + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#ifndef TCOMP_NAKINFO_H +#define TCOMP_NAKINFO_H + +#include "tinysigcomp_config.h" +#include "tcomp_buffer.h" + +#include "tsk_sha1.h" +#include "tsk_object.h" + +TCOMP_BEGIN_DECLS + +struct tcomp_message_s; + +/* ++---+---+---+---+---+---+---+---+ +| code_len = 0 | ++---+---+---+---+---+---+---+---+ +| code_len = 0 | version = 1 | ++---+---+---+---+---+---+---+---+ +| Reason Code | ++---+---+---+---+---+---+---+---+ +| OPCODE of failed instruction | ++---+---+---+---+---+---+---+---+ +| PC of failed instruction | +| | ++---+---+---+---+---+---+---+---+ +| | +: SHA-1 Hash of failed message : +| | ++---+---+---+---+---+---+---+---+ +| | +: Error Details : +| | ++---+---+---+---+---+---+---+---+ +*/ +/**NACK info as per rfc 4077 subclause 3.1. +* You MUST use @ref tcomp_nackinfo_create() to create new nackinfo object. +*/ +typedef struct tcomp_nackinfo_s +{ + TSK_DECLARE_OBJECT; + + uint8_t version; /**< Gives the version of the NACK mechanism being employed. */ + uint8_t reasonCode; /**< The Reason Code is a one-byte value that indicates the nature of the decompression failure. */ + uint8_t opcode; /**< The "OPCODE of failed instruction" is a one-byte field that includes the opcode to which the PC was pointing when the failure occurred */ + uint32_t pc; /**< "PC of failed instruction" is a two-byte field containing the value of the program counter when failure occurred (i.e., the memory address of the failed UDVM instruction) */ + uint8_t sha1[TSK_SHA1_DIGEST_SIZE]; /**<"SHA-1 Hash of failed message" contains the full 20-byte SHA-1 hash of the SigComp message that could not be decompressed */ + tcomp_buffer_handle_t *details; /**< "Error Details" provides additional information that might be useful in correcting the problem that caused decompression failure.*/ +} +tcomp_nackinfo_t; + +tcomp_nackinfo_t* tcomp_nackinfo_create(); +int tcomp_nackinfo_write(tcomp_buffer_handle_t* buffer, + uint8_t reasonCode, + uint8_t opCode, + int16_t memory_address_of_instruction, + const void* sigCompMessagePtr, tsk_size_t sigCompMessageSize, + tcomp_buffer_handle_t* lpDetails, + uint16_t udvm_size, + uint8_t cpbValue); +int tcomp_nackinfo_write_2(tcomp_buffer_handle_t* buffer, + uint8_t reasonCode, + uint8_t opCode, + int16_t memory_address_of_instruction, + const struct tcomp_message_s* sigCompMessage, + tcomp_buffer_handle_t* lpDetails, + uint16_t udvm_size, + uint8_t cpbValue); +int tcomp_nackinfo_write_3(tcomp_buffer_handle_t* buffer, + uint8_t reasonCode, + const void* sigCompMessagePtr, tsk_size_t sigCompMessageSize); +int tcomp_nackinfo_write_4(tcomp_buffer_handle_t* buffer, + uint8_t reasonCode, + const struct tcomp_message_s* sigCompMessage); +TINYSIGCOMP_API const char* tcomp_nackinfo_get_description(const tcomp_buffer_handle_t* buffer); + + +TINYSIGCOMP_GEXTERN const tsk_object_def_t *tcomp_nackinfo_def_t; + +TCOMP_END_DECLS + +#endif /* TCOMP_NAKINFO_H */ diff --git a/tinySIGCOMP/src/tcomp_operands.h b/tinySIGCOMP/src/tcomp_operands.h new file mode 100644 index 0000000..985391a --- /dev/null +++ b/tinySIGCOMP/src/tcomp_operands.h @@ -0,0 +1,39 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_operands.h + * @brief SigComp UDVM operands as per RFC 3312 subclause 8.5. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ + +#ifndef TCOMP_OPERANDS_H +#define TCOMP_OPERANDS_H + +#define UDVM_OPERAND__LITERAL 0 /*#*/ +#define UDVM_OPERAND__REFERENCE 1 /*$*/ +#define UDVM_OPERAND__MULTITYPE 2 /*%*/ +#define UDVM_OPERAND__ADDRESS 3 /*@*/ + +#endif /* TCOMP_NACKCODES_H */ diff --git a/tinySIGCOMP/src/tcomp_params.c b/tinySIGCOMP/src/tcomp_params.c new file mode 100644 index 0000000..c7d7c54 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_params.c @@ -0,0 +1,297 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_params.c + * @brief SigComp parameters as per rfc 3320 subclause 3.3. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_params.h" +#include "tsk_binaryutils.h" +#include "tsk_memory.h" +#include "tsk_debug.h" + +tcomp_params_t* tcomp_params_create() +{ + return tsk_object_new(tcomp_params_def_t); +} + +/** +* Checks if CPB, DMS and SMS values have been initialized. +* @param params The sigcomp parameters containing the values to check. +* @retval @a tsk_true if values have been set and @a tsk_false otherwise. +*/ +tsk_bool_t tcomp_params_hasCpbDmsSms(tcomp_params_t* params) +{ + if(params){ + return (params->cpbCode || params->dmsCode || params->smsCode) ? tsk_true : tsk_false; + } + else{ + TSK_DEBUG_WARN("Invalid parameter."); + } + + return tsk_false; +} + +/** +* Sets CPB bits. +* @param params The sigcomp parameters containing cpb bits to set. +* @param cpbCode The new CPB code. +* @sa @ref tcomp_params_setCpbValue. +*/ +void tcomp_params_setCpbCode(tcomp_params_t* params, uint8_t cpbCode) +{ + if(params){ + params->cpbCode = cpbCode; + params->cpbValue = sigcomp_encoding_cpb[cpbCode]; + } + else{ + TSK_DEBUG_ERROR("Invalid parameter."); + } +} + +/** +* Sets CPB bits. +* @param params The sigcomp parameters containing cpb bits to set. +* @param cpbValue The new CPB value. +* @sa @ref tcomp_params_setCpbCode. +*/ +int tcomp_params_setCpbValue(tcomp_params_t* params, uint8_t cpbValue) +{ + if(params) + { + uint8_t code; + for(code=0; code<4; code++){ + if( cpbValue <= sigcomp_encoding_cpb[code]){ + params->cpbCode = code; + break; + } + } + params->cpbValue = cpbValue; + return 0; + } + else{ + TSK_DEBUG_ERROR("Invalid parameter."); + return -1; + } +} + +/** +* Sets DMS bits. +* @param params The sigcomp parameters containing dms bits to set. +* @param dmsCode The new DMS code. +* @sa @ref tcomp_params_setDmsValue. +*/ +void tcomp_params_setDmsCode(tcomp_params_t* params, uint8_t dmsCode) +{ + if(params){ + params->dmsCode = dmsCode; + params->dmsValue = sigcomp_encoding_dms[dmsCode]; + } + else{ + TSK_DEBUG_ERROR("Invalid parameter."); + } +} + +/** +* Sets DMS bits. +* @param params The sigcomp parameters containing dms bits to set. +* @param dmsValue The new DMS value. +* @sa @ref tcomp_params_setDmsCode. +*/ +int tcomp_params_setDmsValue(tcomp_params_t* params, uint32_t dmsValue) +{ + if(params){ + uint8_t code; + for(code=1; code<8; code++){ + if(dmsValue <= sigcomp_encoding_dms[code]){ + params->dmsCode = code; + break; + } + } + params->dmsValue = dmsValue; + return 0; + } + else{ + TSK_DEBUG_ERROR("Invalid parameter."); + return -1; + } +} + +/** +* Sets SMS bits. +* @param params The sigcomp parameters containing sms bits to set. +* @param smsCode The new SMS code. +* @sa @ref tcomp_params_setSmsValue. +*/ +void tcomp_params_setSmsCode(tcomp_params_t* params, uint8_t smsCode) +{ + if(params){ + params->smsCode = smsCode; + params->smsValue = sigcomp_encoding_sms[smsCode]; + } + else{ + TSK_DEBUG_ERROR("Invalid parameter."); + } +} + +/** +* Sets SMS bits. +* @param params The sigcomp parameters containing sms bits to set. +* @param smsValue The new SMS value. +* @sa @ref tcomp_params_setSmsCode +*/ +int tcomp_params_setSmsValue(tcomp_params_t* params, uint32_t smsValue) +{ + if(params){ + uint8_t code; + for(code = 0; code < 8; code++){ + if(smsValue <= sigcomp_encoding_sms[code]){ + params->smsCode = code; + break; + } + } + params->smsValue = smsValue; + return 0; + } + else{ + TSK_DEBUG_ERROR("Invalid parameter."); + return -1; + } +} + +/** +* Gets CPB, DMS and SMS values as a single 2-bytes value. +* @param params The sigcomp parameters containing the values. +* @retval CPB||DMS||SMS as 2-bytes value. +* @sa @ref tcomp_params_setParameters +*/ +uint32_t tcomp_params_getParameters(tcomp_params_t* params) +{ + if(params){ + /* + +---+---+---+---+---+---+---+---+ + | cpb | dms | sms | + +---+---+---+---+---+---+---+---+ + | SigComp_version | + +---+---+---+---+---+---+---+---+ + */ + uint32_t result = ((params->cpbCode<<6)|(params->dmsCode<<3)|params->smsCode); + result <<=8; + return (result | params->SigComp_version); + } + else{ + TSK_DEBUG_ERROR("Invalid parameter."); + } + + return 0; +} + +/** +* Sets CPB, DMS and SMS values. +* @param params The sigcomp parameters containing the values to set. +* @param sigCompParameters New values as 2-bytes value. +* @sa @ref tcomp_params_getParameters. +*/ +void tcomp_params_setParameters(tcomp_params_t* params, uint32_t sigCompParameters) +{ + if(params){ + /* + +---+---+---+---+---+---+---+---+ + | cpb | dms | sms | + +---+---+---+---+---+---+---+---+ + | SigComp_version | + +---+---+---+---+---+---+---+---+ + */ + tcomp_params_setCpbCode( params, (sigCompParameters>>14) ); + tcomp_params_setDmsCode( params, ((sigCompParameters>>11) & 0x07) ); + tcomp_params_setSmsCode( params, ((sigCompParameters>>8) & 0x07) ); + params->SigComp_version = ( (sigCompParameters & 0x00ff) ); + } + else{ + TSK_DEBUG_ERROR("Invalid parameter."); + } +} + +/** +* Resets all parameters. +* @param params The params to reset. +*/ +void tcomp_params_reset(tcomp_params_t* params) +{ + if(params){ + params->cpbCode = params->dmsCode = params->smsCode = params->SigComp_version = 0; + params->cpbValue = params->dmsValue = params->smsValue = 0; + + tsk_list_clear_items(params->returnedStates); + } + else{ + TSK_DEBUG_WARN("Invalid parameter."); + } +} + + + + + + + + +//======================================================== +// SigComp parameters object definition +// +static tsk_object_t* tcomp_params_ctor(tsk_object_t *self, va_list * app) +{ + tcomp_params_t *params = self; + if(params){ + //tcomp_params_reset(params); + params->returnedStates = tsk_list_create(); + } + else{ + TSK_DEBUG_ERROR("Failed to create new sigcomp params."); + } + + return self; +} +static tsk_object_t* tcomp_params_dtor(tsk_object_t *self) +{ + tcomp_params_t *params = self; + if(params){ + TSK_OBJECT_SAFE_FREE(params->returnedStates); + } + else{ + TSK_DEBUG_WARN("NULL sigcomp parameters."); + } + + return self; +} + +static const tsk_object_def_t tcomp_params_def_s = +{ + sizeof(tcomp_params_t), + tcomp_params_ctor, + tcomp_params_dtor, + tsk_null +}; +const tsk_object_def_t *tcomp_params_def_t = &tcomp_params_def_s; diff --git a/tinySIGCOMP/src/tcomp_params.h b/tinySIGCOMP/src/tcomp_params.h new file mode 100644 index 0000000..85d96dc --- /dev/null +++ b/tinySIGCOMP/src/tcomp_params.h @@ -0,0 +1,83 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_params.h + * @brief SIGCOMP parameters as per rfc 3320 subclause 3.3. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#ifndef TCOMP_PARAMS_H +#define TCOMP_PARAMS_H + +#include "tinysigcomp_config.h" +#include "tcomp_types.h" +#include "tsk_object.h" + +/**@typedef tcomp_params_t +* SIGCOMP parameters as per rfc 3320 subclause 3.3. +*/ + +TCOMP_BEGIN_DECLS + + +typedef struct tcomp_params_s +{ + TSK_DECLARE_OBJECT; + + uint8_t cpbCode; /**< 'Cycles Per Bit' binary code. You MUST use @ref tcomp_params_setCpbCode to set this value. */ + uint8_t dmsCode; /**< 'Decompression Memory' Size binary code. You MUST use @ref tcomp_params_setDmsCode to set this value. */ + uint8_t smsCode; /**< 'State Memory Size' binary code. You MUST use @ref tcomp_params_setSmsCode to set this value. */ + + uint8_t cpbValue; /**< 'Cycles Per Bit' value. You MUST use @ref tcomp_params_setCpbValue to set this value. */ + uint32_t dmsValue; /**< 'Decompression Memory Size' value. You MUST use @ref tcomp_params_setDmsValue to set this value. */ + uint32_t smsValue; /**< 'State Memory Size' value You MUST use @ref tcomp_params_setSmsValue to set this value. */ + + uint8_t SigComp_version; /**< SigComp version. */ + tcomp_buffers_L_t* returnedStates; /**< List of the returned states. */ +} +tcomp_params_t; + +tcomp_params_t* tcomp_params_create(); + +tsk_bool_t tcomp_params_hasCpbDmsSms(tcomp_params_t*); + +void tcomp_params_setCpbCode(tcomp_params_t*, uint8_t _cpbCode); +int tcomp_params_setCpbValue(tcomp_params_t*, uint8_t _cpbValue); + +void tcomp_params_setDmsCode(tcomp_params_t*, uint8_t _dmsCode); +int tcomp_params_setDmsValue(tcomp_params_t*, uint32_t _dmsValue); + +void tcomp_params_setSmsCode(tcomp_params_t*, uint8_t _smsCode); +int tcomp_params_setSmsValue(tcomp_params_t*, uint32_t _smsValue); + +uint32_t tcomp_params_getParameters(tcomp_params_t*); +void tcomp_params_setParameters(tcomp_params_t*, uint32_t sigCompParameters); + +void tcomp_params_reset(tcomp_params_t*); + +TINYSIGCOMP_GEXTERN const tsk_object_def_t *tcomp_params_def_t; + +TCOMP_END_DECLS + +#endif /* TCOMP_PARAMS_H */ diff --git a/tinySIGCOMP/src/tcomp_reqfeed.c b/tinySIGCOMP/src/tcomp_reqfeed.c new file mode 100644 index 0000000..0969c04 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_reqfeed.c @@ -0,0 +1,97 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_reqfeed.c + * @brief SIGCOMP requested feedback item as per rfc 3320 subclause 9.4.9. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_reqfeed.h" +#include "tcomp_buffer.h" + +#include "tsk_memory.h" +#include "tsk_debug.h" + +/** Creates new Requested feedback. +*/ +tcomp_reqfeed_t* tcomp_reqfeed_create() +{ + return tsk_object_new(tcomp_reqfeed_def_t); +} + +/** +* Reset the feedback. +* @param feedback The feedback to reset. +*/ +void tcomp_reqfeed_reset(tcomp_reqfeed_t* feedback) +{ + if(feedback){ + tcomp_buffer_freeBuff(feedback->item); + tcomp_buffer_reset(feedback->item); + + feedback->Q = feedback->S = feedback->I = 0; + } + else{ + TSK_DEBUG_ERROR("Invalid parameter."); + } +} + + + + +//======================================================== +// Requested feedback object definition +// +static void* tcomp_reqfeed_ctor(void * self, va_list * app) +{ + tcomp_reqfeed_t *feedback = self; + if(feedback){ + feedback->item = tcomp_buffer_create_null(); + } + else{ + TSK_DEBUG_WARN("NULL feedback"); + } + + return self; +} +static void* tcomp_reqfeed_dtor(void* self) +{ + tcomp_reqfeed_t *feedback = self; + if(feedback){ + TSK_OBJECT_SAFE_FREE(feedback->item); + } + else{ + TSK_DEBUG_WARN("NULL feedback"); + } + return self; +} + +static const tsk_object_def_t tcomp_reqfeed_def_s = +{ + sizeof(tcomp_reqfeed_t), + tcomp_reqfeed_ctor, + tcomp_reqfeed_dtor, + tsk_null +}; +const tsk_object_def_t *tcomp_reqfeed_def_t = &tcomp_reqfeed_def_s; diff --git a/tinySIGCOMP/src/tcomp_reqfeed.h b/tinySIGCOMP/src/tcomp_reqfeed.h new file mode 100644 index 0000000..a3f9089 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_reqfeed.h @@ -0,0 +1,75 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_reqfeed.h + * @brief SIGCOMP requested feedback item as per rfc 3320 subclause 9.4.9. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#ifndef TCOMP_REQ_FEEDBACK_H +#define TCOMP_REQ_FEEDBACK_H + +#include "tinysigcomp_config.h" +#include "tcomp_buffer.h" +#include "tsk_object.h" + +TCOMP_BEGIN_DECLS + +/* +0 1 2 3 4 5 6 7 ++---+---+---+---+---+---+---+---+ +| reserved | Q | S | I | requested_feedback_location ++---+---+---+---+---+---+---+---+ +| | +: requested feedback item : if Q = 1 +| | ++---+---+---+---+---+---+---+---+ +*/ + +/** SigComp Requested feedback item as per RFC 3320 subclause 9.4.9. +*/ +typedef struct tcomp_reqfeed_s +{ + TSK_DECLARE_OBJECT; + + unsigned Q:1; /**< The Q-bit indicates whether a requested feedback item is present or not.*/ + unsigned S:1; /**< The compressor sets the S-bit to 1 if it does not wish (or no longer + wishes) to save state information at the receiving endpoint and also + does not wish to access state information that it has previously saved.*/ + unsigned I:1; /**< Similarly the compressor sets the I-bit to 1 if it does not wish (or + no longer wishes) to access any of the locally available state items + offered by the receiving endpoint.*/ + tcomp_buffer_handle_t *item; /**< The requested item feedback data */ +} +tcomp_reqfeed_t; + +tcomp_reqfeed_t* tcomp_reqfeed_create(); + +void tcomp_reqfeed_reset(tcomp_reqfeed_t*); + +TINYSIGCOMP_GEXTERN const tsk_object_def_t *tcomp_reqfeed_def_t; + +TCOMP_END_DECLS + +#endif /* TCOMP_REQ_FEEDBACK_H */ diff --git a/tinySIGCOMP/src/tcomp_result.c b/tinySIGCOMP/src/tcomp_result.c new file mode 100644 index 0000000..457ba65 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_result.c @@ -0,0 +1,273 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_result.c + * @brief SigComp decompresion result. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_result.h" +#include "tsk_memory.h" +#include "tsk_debug.h" + +/** Creates new SigComp result object. +*/ +tcomp_result_t* tcomp_result_create() +{ + return tsk_object_new(tcomp_result_def_t); +} + +tcomp_tempstate_to_free_t* tcomp_tempstate_to_free_create() +{ + return tsk_object_new(tcomp_tempstate_to_free_def_t); +} + +/**Resets the result. +*/ +void _tcomp_result_reset(tcomp_result_t *result, tsk_bool_t isDestructor, tsk_bool_t isResetOutput) +{ + if(result){ + uint8_t i; + for(i = 0; i < result->statesToCreateIndex; i++){ + TSK_OBJECT_SAFE_FREE(result->statesToCreate[i]); + } + + for(i = 0; i < result->statesToFreeIndex; i++){ + TSK_OBJECT_SAFE_FREE(result->statesToFree[i]); + } + + if(!isDestructor){ + result->statesToCreateIndex = 0; + result->statesToFreeIndex = 0; + result->consumed_cycles = 0; + + tcomp_params_reset(result->remote_parameters); + + if(isResetOutput){ + tcomp_buffer_reset(result->output_buffer); + } + + tcomp_reqfeed_reset(result->req_feedback); + tcomp_buffer_freeBuff(result->ret_feedback); + + result->isNack = 0; + tcomp_buffer_freeBuff(result->nack_info); + } + } + else{ + TSK_DEBUG_ERROR("NULL SigComp result."); + } +} + +/**Sets the output buffer. +*/ +void tcomp_result_setOutputBuffer(tcomp_result_t *result, void *output_ptr, tsk_size_t output_size, tsk_bool_t isStream, uint64_t streamId) +{ + if(result){ + tcomp_buffer_referenceBuff(result->output_buffer, (uint8_t*)output_ptr, output_size); + result->isStreamBased = isStream; + result->streamId = streamId; + } + else{ + TSK_DEBUG_ERROR("NULL SigComp result."); + } +} + +/**Sets the compartment identifier. +*/ +void tcomp_result_setCompartmentId(tcomp_result_t *result, const void *id, tsk_size_t len) +{ + if(result){ + result->compartmentId = tcomp_buffer_createHash(id, len); + } + else{ + TSK_DEBUG_ERROR("NULL SigComp result."); + } +} + +/**Adds temporary state. +*/ +void tcomp_result_addTempStateToCreate(tcomp_result_t *result, tcomp_state_t* lpState) +{ + if(result){ + /* + * Note that there is a maximum limit of four state creation requests per instance of the UDVM. + */ + if(result->statesToCreateIndex >= MAX_TEMP_SATES) { + TSK_DEBUG_ERROR("Maximum limit for %d state creation requests reached", MAX_TEMP_SATES); + return; + } + + // Add state + result->statesToCreate[result->statesToCreateIndex++] = lpState; + } + else{ + TSK_DEBUG_ERROR("NULL SigComp result."); + } +} + +/**Gets the number of temporary state (to be created). +*/ +uint8_t tcomp_result_getTempStatesToCreateSize(const tcomp_result_t *result) +{ + if(result){ + return result->statesToCreateIndex; + } + else{ + TSK_DEBUG_ERROR("NULL SigComp result."); + } + return 0; +} + +/**Adds temporary state (to be freed). +*/ +void tcomp_result_addTempStateToFree(tcomp_result_t *result, tcomp_tempstate_to_free_t* lpDesc) +{ + if(result){ + /* + * Decompression failure MUST occur if more than four state free + * requests are made before the END-MESSAGE instruction is encountered. + */ + if(result->statesToFreeIndex >= MAX_TEMP_SATES) { + return; + } + result->statesToFree[result->statesToFreeIndex++] = lpDesc; + } + else{ + TSK_DEBUG_ERROR("NULL SigComp result."); + } +} + +/**Gets the number of temporary state (to be be freed). +*/ +uint8_t tcomp_result_getTempStatesToFreeSize(const tcomp_result_t *result) +{ + if(result){ + return result->statesToFreeIndex; + } + else{ + TSK_DEBUG_ERROR("NULL SigComp result."); + } + return 0; +} + + + + + +//======================================================== +// SigComp result object definition +// + +static tsk_object_t* tcomp_result_ctor(tsk_object_t *self, va_list * app) +{ + tcomp_result_t* result = self; + + if(result){ + result->output_buffer = tcomp_buffer_create_null(); + result->ret_feedback = tcomp_buffer_create_null(); + result->nack_info = tcomp_buffer_create_null(); + + result->remote_parameters = tcomp_params_create(); + + result->req_feedback = tcomp_reqfeed_create(); + } + else{ + TSK_DEBUG_ERROR("Null result object"); + } + + return self; +} + +static tsk_object_t* tcomp_result_dtor(tsk_object_t * self) +{ + tcomp_result_t* result = self; + + if(result){ + _tcomp_result_reset(result, tsk_true, tsk_true); + TSK_OBJECT_SAFE_FREE(result->output_buffer); + TSK_OBJECT_SAFE_FREE(result->ret_feedback); + TSK_OBJECT_SAFE_FREE(result->nack_info); + + TSK_OBJECT_SAFE_FREE(result->remote_parameters); + + TSK_OBJECT_SAFE_FREE(result->req_feedback); + } + else{ + TSK_DEBUG_ERROR("Null result object"); + } + + return self; +} + +static const tsk_object_def_t tcomp_result_def_s = +{ + sizeof(tcomp_result_t), + tcomp_result_ctor, + tcomp_result_dtor, + tsk_null +}; +const tsk_object_def_t *tcomp_result_def_t = &tcomp_result_def_s; + + +//======================================================== +// SigComp temporary state object definition +// + +static tsk_object_t* tcomp_tempstate_to_free_ctor(tsk_object_t* self, va_list * app) +{ + tcomp_tempstate_to_free_t* tempstate_to_free = self; + + if(tempstate_to_free){ + tempstate_to_free->identifier = tcomp_buffer_create_null(); + } + else{ + TSK_DEBUG_ERROR("Null object"); + } + + return self; +} + +static tsk_object_t* tcomp_tempstate_to_free_dtor(tsk_object_t* self) +{ + tcomp_tempstate_to_free_t* tempstate_to_free = self; + + if(tempstate_to_free){ + TSK_OBJECT_SAFE_FREE(tempstate_to_free->identifier); + } + else{ + TSK_DEBUG_ERROR("Null object"); + } + + return self; +} + +static const tsk_object_def_t tcomp_tempstate_to_free_def_s = +{ + sizeof(tcomp_tempstate_to_free_t), + tcomp_tempstate_to_free_ctor, + tcomp_tempstate_to_free_dtor, + tsk_null +}; +const tsk_object_def_t* tcomp_tempstate_to_free_def_t = &tcomp_tempstate_to_free_def_s; diff --git a/tinySIGCOMP/src/tcomp_result.h b/tinySIGCOMP/src/tcomp_result.h new file mode 100644 index 0000000..3a44249 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_result.h @@ -0,0 +1,112 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_result.h + * @brief SIGCOMP decompresion result. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#ifndef TCOMP_RESULT_H +#define TCOMP_RESULT_H + +#include "tinysigcomp_config.h" + +#include "tcomp_state.h" +#include "tcomp_reqfeed.h" +#include "tcomp_params.h" +#include "tcomp_buffer.h" + +#include "tsk_object.h" + +TCOMP_BEGIN_DECLS + +#define MAX_TEMP_SATES 4 + +typedef struct tcomp_tempstate_to_free_s +{ + TSK_DECLARE_OBJECT; + + // Operands + uint32_t partial_identifier_start; + uint32_t partial_identifier_length; + // identifier + tcomp_buffer_handle_t *identifier; +} +tcomp_tempstate_to_free_t; + +TINYSIGCOMP_GEXTERN const tsk_object_def_t *tcomp_tempstate_to_free_def_t; + +/**SigComp decompression result. +*/ +typedef struct tcomp_result_s +{ + TSK_DECLARE_OBJECT; + + uint64_t compartmentId; + tcomp_state_t* statesToCreate[MAX_TEMP_SATES]; + uint8_t statesToCreateIndex; + + tcomp_tempstate_to_free_t* statesToFree[MAX_TEMP_SATES]; + uint8_t statesToFreeIndex; + + uint64_t streamId; + unsigned isStreamBased:1; + tcomp_buffer_handle_t *output_buffer; + + tcomp_reqfeed_t *req_feedback; + tcomp_params_t *remote_parameters; + tcomp_buffer_handle_t *ret_feedback; + + unsigned isNack:1; + tcomp_buffer_handle_t *nack_info; + + uint64_t consumed_cycles; +} +tcomp_result_t; + +TINYSIGCOMP_API tcomp_result_t* tcomp_result_create(); +tcomp_tempstate_to_free_t* tcomp_tempstate_to_free_create(); + +void _tcomp_result_reset(tcomp_result_t *result, int isDestructor, int isResetOutput); +#define tcomp_result_reset(result) _tcomp_result_reset((tcomp_result_t *)result, tsk_false, tsk_true) + +TINYSIGCOMP_API void tcomp_result_setOutputBuffer(tcomp_result_t *result, void *output_ptr, tsk_size_t output_size, tsk_bool_t isStream, uint64_t streamId); +#define tcomp_result_setOutputUDPBuffer(result, output_ptr, output_size) tcomp_result_setOutputBuffer((tcomp_result_t *)result, (void *)output_ptr, (tsk_size_t) output_size, tsk_false, 0) +#define tcomp_result_setOutputTCPBuffer(result, output_ptr, output_size, streamId) tcomp_result_setOutputBuffer((tcomp_result_t *)result, (void *)output_ptr, (tsk_size_t) output_size, tsk_true, (uint64_t)streamId) +#define tcomp_result_setOutputSCTPBuffer(result, output_ptr, output_size) tcomp_result_setOutputTCPBuffer + +TINYSIGCOMP_API void tcomp_result_setCompartmentId(tcomp_result_t *result, const void *id, tsk_size_t len); + +void tcomp_result_addTempStateToCreate(tcomp_result_t *result, tcomp_state_t* lpState); +uint8_t tcomp_result_getTempStatesToCreateSize(const tcomp_result_t *result); + +void tcomp_result_addTempStateToFree(tcomp_result_t *result, tcomp_tempstate_to_free_t* lpDesc); +uint8_t tcomp_result_getTempStatesToFreeSize(const tcomp_result_t *result); + +TINYSIGCOMP_GEXTERN const tsk_object_def_t *tcomp_result_def_t; +TINYSIGCOMP_GEXTERN const tsk_object_def_t *tcomp_tempstate_to_free_def_t; + +TCOMP_END_DECLS + +#endif /* TCOMP_RESULT_H */ diff --git a/tinySIGCOMP/src/tcomp_rfc3485_dictionary_sip.h b/tinySIGCOMP/src/tcomp_rfc3485_dictionary_sip.h new file mode 100644 index 0000000..e1fdbc1 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_rfc3485_dictionary_sip.h @@ -0,0 +1,272 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_rfc3485_dictionary_sip.h + * @brief RFC 3485 - The Session Initiation Protocol (SIP) and Session Description Protocol + * (SDP) Static Dictionary for Signaling Compression (SigComp) + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ + +#ifndef _TINYSIGCOMPP_RFC3485_H_ +#define _TINYSIGCOMPP_RFC3485_H_ + +TCOMP_BEGIN_DECLS + +#define RFC3485_DICTIONARY_SIP_VALUE_LENGTH 0x12e4 +#define RFC3485_DICTIONARY_SIP_STATE_ADDRESS 0 /*(not relevant for the dictionary) */ +#define RFC3485_DICTIONARY_SIP_STATE_INSTRUCTION 0 /*(not relevant for the dictionary) */ +#define RFC3485_DICTIONARY_SIP_MINIMUM_ACCESS_LENGTH 6 + +#define RFC3485_DICTIONARY_SIP_IDENTIFIER_LENGTH 20 + +#define RFC3485_DICTIONARY_SIP_IDENTIFIER \ + "\xfb\xe5\x07\xdf\xe5\xe6\xaa\x5a\xf2\xab\xb9\x14\xce\xaa\x05\xf9\x9c\xe6\x1b\xa5" + +#define RFC3485_DICTIONARY_SIP_VALUE \ + "\x0d\x0a\x52\x65\x6a\x65\x63\x74\x2d\x43\x6f\x6e\x74\x61\x63\x74\x3a\x20\x0d\x0a\x45\x72" \ + "\x72\x6f\x72\x2d\x49\x6e\x66\x6f\x3a\x20\x0d\x0a\x54\x69\x6d\x65\x73\x74\x61\x6d\x70\x3a" \ + "\x20\x0d\x0a\x43\x61\x6c\x6c\x2d\x49\x6e\x66\x6f\x3a\x20\x0d\x0a\x52\x65\x70\x6c\x79\x2d" \ + "\x54\x6f\x3a\x20\x0d\x0a\x57\x61\x72\x6e\x69\x6e\x67\x3a\x20\x0d\x0a\x53\x75\x62\x6a\x65" \ + "\x63\x74\x3a\x20\x3b\x68\x61\x6e\x64\x6c\x69\x6e\x67\x3d\x69\x6d\x61\x67\x65\x3b\x70\x75" \ + "\x72\x70\x6f\x73\x65\x3d\x3b\x63\x61\x75\x73\x65\x3d\x3b\x74\x65\x78\x74\x3d\x63\x61\x72" \ + "\x64\x33\x30\x30\x20\x4d\x75\x6c\x74\x69\x70\x6c\x65\x20\x43\x68\x6f\x69\x63\x65\x73\x6d" \ + "\x69\x6d\x65\x73\x73\x61\x67\x65\x2f\x73\x69\x70\x66\x72\x61\x67\x34\x30\x37\x20\x50\x72" \ + "\x6f\x78\x79\x20\x41\x75\x74\x68\x65\x6e\x74\x69\x63\x61\x74\x69\x6f\x6e\x20\x52\x65\x71" \ + "\x75\x69\x72\x65\x64\x69\x67\x65\x73\x74\x2d\x69\x6e\x74\x65\x67\x72\x69\x74\x79\x34\x38" \ + "\x34\x20\x41\x64\x64\x72\x65\x73\x73\x20\x49\x6e\x63\x6f\x6d\x70\x6c\x65\x74\x65\x6c\x65" \ + "\x70\x68\x6f\x6e\x65\x2d\x65\x76\x65\x6e\x74\x73\x34\x39\x34\x20\x53\x65\x63\x75\x72\x69" \ + "\x74\x79\x20\x41\x67\x72\x65\x65\x6d\x65\x6e\x74\x20\x52\x65\x71\x75\x69\x72\x65\x64\x65" \ + "\x61\x63\x74\x69\x76\x61\x74\x65\x64\x34\x38\x31\x20\x43\x61\x6c\x6c\x2f\x54\x72\x61\x6e" \ + "\x73\x61\x63\x74\x69\x6f\x6e\x20\x44\x6f\x65\x73\x20\x4e\x6f\x74\x20\x45\x78\x69\x73\x74" \ + "\x61\x6c\x65\x3d\x35\x30\x30\x20\x53\x65\x72\x76\x65\x72\x20\x49\x6e\x74\x65\x72\x6e\x61" \ + "\x6c\x20\x45\x72\x72\x6f\x72\x6f\x62\x75\x73\x74\x2d\x73\x6f\x72\x74\x69\x6e\x67\x3d\x34" \ + "\x31\x36\x20\x55\x6e\x73\x75\x70\x70\x6f\x72\x74\x65\x64\x20\x55\x52\x49\x20\x53\x63\x68" \ + "\x65\x6d\x65\x72\x67\x65\x6e\x63\x79\x34\x31\x35\x20\x55\x6e\x73\x75\x70\x70\x6f\x72\x74" \ + "\x65\x64\x20\x4d\x65\x64\x69\x61\x20\x54\x79\x70\x65\x6e\x64\x69\x6e\x67\x34\x38\x38\x20" \ + "\x4e\x6f\x74\x20\x41\x63\x63\x65\x70\x74\x61\x62\x6c\x65\x20\x48\x65\x72\x65\x6a\x65\x63" \ + "\x74\x65\x64\x34\x32\x33\x20\x49\x6e\x74\x65\x72\x76\x61\x6c\x20\x54\x6f\x6f\x20\x42\x72" \ + "\x69\x65\x66\x72\x6f\x6d\x2d\x74\x61\x67\x51\x2e\x38\x35\x30\x35\x20\x56\x65\x72\x73\x69" \ + "\x6f\x6e\x20\x4e\x6f\x74\x20\x53\x75\x70\x70\x6f\x72\x74\x65\x64\x34\x30\x33\x20\x46\x6f" \ + "\x72\x62\x69\x64\x64\x65\x6e\x6f\x6e\x2d\x75\x72\x67\x65\x6e\x74\x34\x32\x39\x20\x50\x72" \ + "\x6f\x76\x69\x64\x65\x20\x52\x65\x66\x65\x72\x72\x6f\x72\x20\x49\x64\x65\x6e\x74\x69\x74" \ + "\x79\x34\x32\x30\x20\x42\x61\x64\x20\x45\x78\x74\x65\x6e\x73\x69\x6f\x6e\x6f\x72\x65\x73" \ + "\x6f\x75\x72\x63\x65\x0d\x0a\x61\x3d\x6b\x65\x79\x2d\x6d\x67\x6d\x74\x3a\x6d\x69\x6b\x65" \ + "\x79\x4f\x50\x54\x49\x4f\x4e\x53\x20\x4c\x61\x6e\x67\x75\x61\x67\x65\x3a\x20\x35\x30\x34" \ + "\x20\x53\x65\x72\x76\x65\x72\x20\x54\x69\x6d\x65\x2d\x6f\x75\x74\x6f\x2d\x74\x61\x67\x0d" \ + "\x0a\x41\x75\x74\x68\x65\x6e\x74\x69\x63\x61\x74\x69\x6f\x6e\x2d\x49\x6e\x66\x6f\x3a\x20" \ + "\x44\x65\x63\x20\x33\x38\x30\x20\x41\x6c\x74\x65\x72\x6e\x61\x74\x69\x76\x65\x20\x53\x65" \ + "\x72\x76\x69\x63\x65\x35\x30\x33\x20\x53\x65\x72\x76\x69\x63\x65\x20\x55\x6e\x61\x76\x61" \ + "\x69\x6c\x61\x62\x6c\x65\x34\x32\x31\x20\x45\x78\x74\x65\x6e\x73\x69\x6f\x6e\x20\x52\x65" \ + "\x71\x75\x69\x72\x65\x64\x34\x30\x35\x20\x4d\x65\x74\x68\x6f\x64\x20\x4e\x6f\x74\x20\x41" \ + "\x6c\x6c\x6f\x77\x65\x64\x34\x38\x37\x20\x52\x65\x71\x75\x65\x73\x74\x20\x54\x65\x72\x6d" \ + "\x69\x6e\x61\x74\x65\x64\x61\x75\x74\x68\x2d\x69\x6e\x74\x65\x72\x6c\x65\x61\x76\x69\x6e" \ + "\x67\x3d\x0d\x0a\x6d\x3d\x61\x70\x70\x6c\x69\x63\x61\x74\x69\x6f\x6e\x20\x41\x75\x67\x20" \ + "\x35\x31\x33\x20\x4d\x65\x73\x73\x61\x67\x65\x20\x54\x6f\x6f\x20\x4c\x61\x72\x67\x65\x36" \ + "\x38\x37\x20\x44\x69\x61\x6c\x6f\x67\x20\x54\x65\x72\x6d\x69\x6e\x61\x74\x65\x64\x33\x30" \ + "\x32\x20\x4d\x6f\x76\x65\x64\x20\x54\x65\x6d\x70\x6f\x72\x61\x72\x69\x6c\x79\x33\x30\x31" \ + "\x20\x4d\x6f\x76\x65\x64\x20\x50\x65\x72\x6d\x61\x6e\x65\x6e\x74\x6c\x79\x6d\x75\x6c\x74" \ + "\x69\x70\x61\x72\x74\x2f\x73\x69\x67\x6e\x65\x64\x0d\x0a\x52\x65\x74\x72\x79\x2d\x41\x66" \ + "\x74\x65\x72\x3a\x20\x47\x4d\x54\x68\x75\x2c\x20\x34\x30\x32\x20\x50\x61\x79\x6d\x65\x6e" \ + "\x74\x20\x52\x65\x71\x75\x69\x72\x65\x64\x0d\x0a\x61\x3d\x6f\x72\x69\x65\x6e\x74\x3a\x6c" \ + "\x61\x6e\x64\x73\x63\x61\x70\x65\x34\x30\x30\x20\x42\x61\x64\x20\x52\x65\x71\x75\x65\x73" \ + "\x74\x72\x75\x65\x34\x39\x31\x20\x52\x65\x71\x75\x65\x73\x74\x20\x50\x65\x6e\x64\x69\x6e" \ + "\x67\x35\x30\x31\x20\x4e\x6f\x74\x20\x49\x6d\x70\x6c\x65\x6d\x65\x6e\x74\x65\x64\x34\x30" \ + "\x36\x20\x4e\x6f\x74\x20\x41\x63\x63\x65\x70\x74\x61\x62\x6c\x65\x36\x30\x36\x20\x4e\x6f" \ + "\x74\x20\x41\x63\x63\x65\x70\x74\x61\x62\x6c\x65\x0d\x0a\x61\x3d\x74\x79\x70\x65\x3a\x62" \ + "\x72\x6f\x61\x64\x63\x61\x73\x74\x6f\x6e\x65\x34\x39\x33\x20\x55\x6e\x64\x65\x63\x69\x70" \ + "\x68\x65\x72\x61\x62\x6c\x65\x0d\x0a\x4d\x49\x4d\x45\x2d\x56\x65\x72\x73\x69\x6f\x6e\x3a" \ + "\x20\x4d\x61\x79\x20\x34\x38\x32\x20\x4c\x6f\x6f\x70\x20\x44\x65\x74\x65\x63\x74\x65\x64" \ + "\x0d\x0a\x4f\x72\x67\x61\x6e\x69\x7a\x61\x74\x69\x6f\x6e\x3a\x20\x4a\x75\x6e\x20\x6d\x6f" \ + "\x64\x65\x2d\x63\x68\x61\x6e\x67\x65\x2d\x6e\x65\x69\x67\x68\x62\x6f\x72\x3d\x63\x72\x69" \ + "\x74\x69\x63\x61\x6c\x65\x72\x74\x63\x70\x2d\x66\x62\x34\x38\x39\x20\x42\x61\x64\x20\x45" \ + "\x76\x65\x6e\x74\x6c\x73\x0d\x0a\x55\x6e\x73\x75\x70\x70\x6f\x72\x74\x65\x64\x3a\x20\x4a" \ + "\x61\x6e\x20\x35\x30\x32\x20\x42\x61\x64\x20\x47\x61\x74\x65\x77\x61\x79\x6d\x6f\x64\x65" \ + "\x2d\x63\x68\x61\x6e\x67\x65\x2d\x70\x65\x72\x69\x6f\x64\x3d\x0d\x0a\x61\x3d\x6f\x72\x69" \ + "\x65\x6e\x74\x3a\x73\x65\x61\x73\x63\x61\x70\x65\x0d\x0a\x61\x3d\x74\x79\x70\x65\x3a\x6d" \ + "\x6f\x64\x65\x72\x61\x74\x65\x64\x34\x30\x34\x20\x4e\x6f\x74\x20\x46\x6f\x75\x6e\x64\x33" \ + "\x30\x35\x20\x55\x73\x65\x20\x50\x72\x6f\x78\x79\x0d\x0a\x61\x3d\x74\x79\x70\x65\x3a\x72" \ + "\x65\x63\x76\x6f\x6e\x6c\x79\x0d\x0a\x61\x3d\x74\x79\x70\x65\x3a\x6d\x65\x65\x74\x69\x6e" \ + "\x67\x0d\x0a\x6b\x3d\x70\x72\x6f\x6d\x70\x74\x3a\x0d\x0a\x52\x65\x66\x65\x72\x72\x65\x64" \ + "\x2d\x42\x79\x3a\x20\x0d\x0a\x49\x6e\x2d\x52\x65\x70\x6c\x79\x2d\x54\x6f\x3a\x20\x54\x52" \ + "\x55\x45\x6e\x63\x6f\x64\x69\x6e\x67\x3a\x20\x31\x38\x32\x20\x51\x75\x65\x75\x65\x64\x41" \ + "\x75\x74\x68\x65\x6e\x74\x69\x63\x61\x74\x65\x3a\x20\x0d\x0a\x55\x73\x65\x72\x2d\x41\x67" \ + "\x65\x6e\x74\x3a\x20\x0d\x0a\x61\x3d\x66\x72\x61\x6d\x65\x72\x61\x74\x65\x3a\x0d\x0a\x41" \ + "\x6c\x65\x72\x74\x2d\x49\x6e\x66\x6f\x3a\x20\x43\x41\x4e\x43\x45\x4c\x20\x0d\x0a\x61\x3d" \ + "\x6d\x61\x78\x70\x74\x69\x6d\x65\x3a\x3b\x72\x65\x74\x72\x79\x2d\x61\x66\x74\x65\x72\x3d" \ + "\x75\x61\x63\x68\x61\x6e\x6e\x65\x6c\x73\x3d\x34\x31\x30\x20\x47\x6f\x6e\x65\x0d\x0a\x52" \ + "\x65\x66\x65\x72\x2d\x54\x6f\x3a\x20\x0d\x0a\x50\x72\x69\x6f\x72\x69\x74\x79\x3a\x20\x0d" \ + "\x0a\x6d\x3d\x63\x6f\x6e\x74\x72\x6f\x6c\x20\x0d\x0a\x61\x3d\x71\x75\x61\x6c\x69\x74\x79" \ + "\x3a\x0d\x0a\x61\x3d\x73\x64\x70\x6c\x61\x6e\x67\x3a\x0d\x0a\x61\x3d\x63\x68\x61\x72\x73" \ + "\x65\x74\x3a\x0d\x0a\x52\x65\x70\x6c\x61\x63\x65\x73\x3a\x20\x52\x45\x46\x45\x52\x20\x69" \ + "\x70\x73\x65\x63\x2d\x69\x6b\x65\x3b\x74\x72\x61\x6e\x73\x70\x6f\x72\x74\x3d\x0d\x0a\x61" \ + "\x3d\x6b\x65\x79\x77\x64\x73\x3a\x0d\x0a\x6b\x3d\x62\x61\x73\x65\x36\x34\x3a\x3b\x72\x65" \ + "\x66\x72\x65\x73\x68\x65\x72\x3d\x0d\x0a\x61\x3d\x70\x74\x69\x6d\x65\x3a\x0d\x0a\x6b\x3d" \ + "\x63\x6c\x65\x61\x72\x3a\x3b\x72\x65\x63\x65\x69\x76\x65\x64\x3d\x3b\x64\x75\x72\x61\x74" \ + "\x69\x6f\x6e\x3d\x0d\x0a\x41\x63\x63\x65\x70\x74\x3a\x20\x0d\x0a\x61\x3d\x67\x72\x6f\x75" \ + "\x70\x3a\x46\x41\x4c\x53\x45\x3a\x20\x49\x4e\x46\x4f\x20\x0d\x0a\x41\x63\x63\x65\x70\x74" \ + "\x2d\x0d\x0a\x61\x3d\x6c\x61\x6e\x67\x3a\x0d\x0a\x6d\x3d\x64\x61\x74\x61\x20\x6d\x6f\x64" \ + "\x65\x2d\x73\x65\x74\x3d\x0d\x0a\x61\x3d\x74\x6f\x6f\x6c\x3a\x54\x4c\x53\x75\x6e\x2c\x20" \ + "\x0d\x0a\x44\x61\x74\x65\x3a\x20\x0d\x0a\x61\x3d\x63\x61\x74\x3a\x0d\x0a\x6b\x3d\x75\x72" \ + "\x69\x3a\x0d\x0a\x50\x72\x6f\x78\x79\x2d\x3b\x72\x65\x61\x73\x6f\x6e\x3d\x3b\x6d\x65\x74" \ + "\x68\x6f\x64\x3d\x0d\x0a\x61\x3d\x6d\x69\x64\x3a\x3b\x6d\x61\x64\x64\x72\x3d\x6f\x70\x61" \ + "\x71\x75\x65\x3d\x0d\x0a\x4d\x69\x6e\x2d\x3b\x61\x6c\x67\x3d\x4d\x6f\x6e\x2c\x20\x54\x75" \ + "\x65\x2c\x20\x57\x65\x64\x2c\x20\x46\x72\x69\x2c\x20\x53\x61\x74\x2c\x20\x3b\x74\x74\x6c" \ + "\x3d\x61\x75\x74\x73\x3d\x0d\x0a\x72\x3d\x0d\x0a\x7a\x3d\x0d\x0a\x65\x3d\x3b\x69\x64\x3d" \ + "\x0d\x0a\x69\x3d\x63\x72\x63\x3d\x0d\x0a\x75\x3d\x3b\x71\x3d\x75\x61\x73\x34\x31\x34\x20" \ + "\x52\x65\x71\x75\x65\x73\x74\x2d\x55\x52\x49\x20\x54\x6f\x6f\x20\x4c\x6f\x6e\x67\x69\x76" \ + "\x65\x75\x70\x72\x69\x76\x61\x63\x79\x75\x64\x70\x72\x65\x66\x65\x72\x36\x30\x30\x20\x42" \ + "\x75\x73\x79\x20\x45\x76\x65\x72\x79\x77\x68\x65\x72\x65\x71\x75\x69\x72\x65\x64\x34\x38" \ + "\x30\x20\x54\x65\x6d\x70\x6f\x72\x61\x72\x69\x6c\x79\x20\x55\x6e\x61\x76\x61\x69\x6c\x61" \ + "\x62\x6c\x65\x0d\x0a\x61\x3d\x74\x79\x70\x65\x3a\x48\x2e\x33\x33\x32\x30\x32\x20\x41\x63" \ + "\x63\x65\x70\x74\x65\x64\x0d\x0a\x53\x65\x73\x73\x69\x6f\x6e\x2d\x45\x78\x70\x69\x72\x65" \ + "\x73\x3a\x20\x0d\x0a\x53\x75\x62\x73\x63\x72\x69\x70\x74\x69\x6f\x6e\x2d\x53\x74\x61\x74" \ + "\x65\x3a\x20\x4e\x6f\x76\x20\x0d\x0a\x53\x65\x72\x76\x69\x63\x65\x2d\x52\x6f\x75\x74\x65" \ + "\x3a\x20\x53\x65\x70\x20\x0d\x0a\x41\x6c\x6c\x6f\x77\x2d\x45\x76\x65\x6e\x74\x73\x3a\x20" \ + "\x46\x65\x62\x20\x0d\x0a\x61\x3d\x69\x6e\x61\x63\x74\x69\x76\x65\x52\x54\x50\x2f\x53\x41" \ + "\x56\x50\x20\x52\x54\x50\x2f\x41\x56\x50\x46\x20\x41\x6e\x6f\x6e\x79\x6d\x6f\x75\x73\x69" \ + "\x70\x73\x3a\x0d\x0a\x61\x3d\x74\x79\x70\x65\x3a\x74\x65\x73\x74\x65\x6c\x3a\x4d\x45\x53" \ + "\x53\x41\x47\x45\x20\x0d\x0a\x61\x3d\x72\x65\x63\x76\x6f\x6e\x6c\x79\x0d\x0a\x61\x3d\x73" \ + "\x65\x6e\x64\x6f\x6e\x6c\x79\x0d\x0a\x63\x3d\x49\x4e\x20\x49\x50\x34\x20\x0d\x0a\x52\x65" \ + "\x61\x73\x6f\x6e\x3a\x20\x0d\x0a\x41\x6c\x6c\x6f\x77\x3a\x20\x0d\x0a\x45\x76\x65\x6e\x74" \ + "\x3a\x20\x0d\x0a\x50\x61\x74\x68\x3a\x20\x3b\x75\x73\x65\x72\x3d\x0d\x0a\x62\x3d\x41\x53" \ + "\x20\x43\x54\x20\x0d\x0a\x57\x57\x57\x2d\x41\x75\x74\x68\x65\x6e\x74\x69\x63\x61\x74\x65" \ + "\x3a\x20\x44\x69\x67\x65\x73\x74\x20\x0d\x0a\x61\x3d\x73\x65\x6e\x64\x72\x65\x63\x76\x69" \ + "\x64\x65\x6f\x63\x74\x65\x74\x2d\x61\x6c\x69\x67\x6e\x3d\x61\x70\x70\x6c\x69\x63\x61\x74" \ + "\x69\x6f\x6e\x2f\x73\x64\x70\x61\x74\x68\x65\x61\x64\x65\x72\x73\x70\x61\x75\x74\x68\x3d" \ + "\x0d\x0a\x61\x3d\x6f\x72\x69\x65\x6e\x74\x3a\x70\x6f\x72\x74\x72\x61\x69\x74\x69\x6d\x65" \ + "\x6f\x75\x74\x74\x72\x2d\x69\x6e\x74\x69\x63\x6f\x6e\x63\x3d\x34\x38\x33\x20\x54\x6f\x6f" \ + "\x20\x4d\x61\x6e\x79\x20\x48\x6f\x70\x73\x6c\x69\x6e\x66\x6f\x70\x74\x69\x6f\x6e\x61\x6c" \ + "\x67\x6f\x72\x69\x74\x68\x6d\x3d\x36\x30\x34\x20\x44\x6f\x65\x73\x20\x4e\x6f\x74\x20\x45" \ + "\x78\x69\x73\x74\x20\x41\x6e\x79\x77\x68\x65\x72\x65\x73\x70\x6f\x6e\x73\x65\x3d\x0d\x0a" \ + "\x0d\x0a\x52\x65\x71\x75\x65\x73\x74\x2d\x44\x69\x73\x70\x6f\x73\x69\x74\x69\x6f\x6e\x3a" \ + "\x20\x4d\x44\x35\x38\x30\x20\x50\x72\x65\x63\x6f\x6e\x64\x69\x74\x69\x6f\x6e\x20\x46\x61" \ + "\x69\x6c\x75\x72\x65\x70\x6c\x61\x63\x65\x73\x34\x32\x32\x20\x53\x65\x73\x73\x69\x6f\x6e" \ + "\x20\x49\x6e\x74\x65\x72\x76\x61\x6c\x20\x54\x6f\x6f\x20\x53\x6d\x61\x6c\x6c\x6f\x63\x61" \ + "\x6c\x31\x38\x31\x20\x43\x61\x6c\x6c\x20\x49\x73\x20\x42\x65\x69\x6e\x67\x20\x46\x6f\x72" \ + "\x77\x61\x72\x64\x65\x64\x6f\x6d\x61\x69\x6e\x3d\x66\x61\x69\x6c\x75\x72\x65\x6e\x64\x65" \ + "\x72\x65\x61\x6c\x6d\x3d\x53\x55\x42\x53\x43\x52\x49\x42\x45\x20\x70\x72\x65\x63\x6f\x6e" \ + "\x64\x69\x74\x69\x6f\x6e\x6f\x72\x6d\x61\x6c\x69\x70\x73\x65\x63\x2d\x6d\x61\x6e\x64\x61" \ + "\x74\x6f\x72\x79\x34\x31\x33\x20\x52\x65\x71\x75\x65\x73\x74\x20\x45\x6e\x74\x69\x74\x79" \ + "\x20\x54\x6f\x6f\x20\x4c\x61\x72\x67\x65\x32\x65\x31\x38\x33\x20\x53\x65\x73\x73\x69\x6f" \ + "\x6e\x20\x50\x72\x6f\x67\x72\x65\x73\x73\x63\x74\x70\x34\x38\x36\x20\x42\x75\x73\x79\x20" \ + "\x48\x65\x72\x65\x6d\x6f\x74\x65\x72\x6d\x69\x6e\x61\x74\x65\x64\x41\x4b\x41\x76\x31\x2d" \ + "\x4d\x44\x35\x2d\x73\x65\x73\x73\x69\x6f\x6e\x6f\x6e\x65\x0d\x0a\x41\x75\x74\x68\x6f\x72" \ + "\x69\x7a\x61\x74\x69\x6f\x6e\x3a\x20\x36\x30\x33\x20\x44\x65\x63\x6c\x69\x6e\x65\x78\x74" \ + "\x6e\x6f\x6e\x63\x65\x3d\x34\x38\x35\x20\x41\x6d\x62\x69\x67\x75\x6f\x75\x73\x65\x72\x6e" \ + "\x61\x6d\x65\x3d\x61\x75\x64\x69\x6f\x0d\x0a\x43\x6f\x6e\x74\x65\x6e\x74\x2d\x54\x79\x70" \ + "\x65\x3a\x20\x4d\x61\x72\x20\x0d\x0a\x52\x65\x63\x6f\x72\x64\x2d\x52\x6f\x75\x74\x65\x3a" \ + "\x20\x4a\x75\x6c\x20\x34\x30\x31\x20\x55\x6e\x61\x75\x74\x68\x6f\x72\x69\x7a\x65\x64\x0d" \ + "\x0a\x52\x65\x71\x75\x69\x72\x65\x3a\x20\x0d\x0a\x74\x3d\x30\x20\x30\x2e\x30\x2e\x30\x2e" \ + "\x30\x0d\x0a\x53\x65\x72\x76\x65\x72\x3a\x20\x52\x45\x47\x49\x53\x54\x45\x52\x20\x0d\x0a" \ + "\x63\x3d\x49\x4e\x20\x49\x50\x36\x20\x31\x38\x30\x20\x52\x69\x6e\x67\x69\x6e\x67\x31\x30" \ + "\x30\x20\x54\x72\x79\x69\x6e\x67\x76\x3d\x30\x0d\x0a\x6f\x3d\x55\x50\x44\x41\x54\x45\x20" \ + "\x4e\x4f\x54\x49\x46\x59\x20\x0d\x0a\x53\x75\x70\x70\x6f\x72\x74\x65\x64\x3a\x20\x75\x6e" \ + "\x6b\x6e\x6f\x77\x6e\x41\x4d\x52\x54\x50\x2f\x41\x56\x50\x20\x0d\x0a\x50\x72\x69\x76\x61" \ + "\x63\x79\x3a\x20\x0d\x0a\x53\x65\x63\x75\x72\x69\x74\x79\x2d\x0d\x0a\x45\x78\x70\x69\x72" \ + "\x65\x73\x3a\x20\x0d\x0a\x61\x3d\x72\x74\x70\x6d\x61\x70\x3a\x0d\x0a\x6d\x3d\x76\x69\x64" \ + "\x65\x6f\x20\x0d\x0a\x6d\x3d\x61\x75\x64\x69\x6f\x20\x0d\x0a\x73\x3d\x20\x66\x61\x6c\x73" \ + "\x65\x0d\x0a\x61\x3d\x63\x6f\x6e\x66\x3a\x3b\x65\x78\x70\x69\x72\x65\x73\x3d\x0d\x0a\x52" \ + "\x6f\x75\x74\x65\x3a\x20\x0d\x0a\x61\x3d\x66\x6d\x74\x70\x3a\x0d\x0a\x61\x3d\x63\x75\x72" \ + "\x72\x3a\x43\x6c\x69\x65\x6e\x74\x3a\x20\x56\x65\x72\x69\x66\x79\x3a\x20\x0d\x0a\x61\x3d" \ + "\x64\x65\x73\x3a\x0d\x0a\x52\x41\x63\x6b\x3a\x20\x0d\x0a\x52\x53\x65\x71\x3a\x20\x42\x59" \ + "\x45\x20\x63\x6e\x6f\x6e\x63\x65\x3d\x31\x30\x30\x72\x65\x6c\x75\x72\x69\x3d\x71\x6f\x70" \ + "\x3d\x54\x43\x50\x55\x44\x50\x71\x6f\x73\x78\x6d\x6c\x3b\x6c\x72\x0d\x0a\x56\x69\x61\x3a" \ + "\x20\x53\x49\x50\x2f\x32\x2e\x30\x2f\x54\x43\x50\x20\x34\x30\x38\x20\x52\x65\x71\x75\x65" \ + "\x73\x74\x20\x54\x69\x6d\x65\x6f\x75\x74\x69\x6d\x65\x72\x70\x73\x69\x70\x3a\x0d\x0a\x43" \ + "\x6f\x6e\x74\x65\x6e\x74\x2d\x4c\x65\x6e\x67\x74\x68\x3a\x20\x4f\x63\x74\x20\x0d\x0a\x56" \ + "\x69\x61\x3a\x20\x53\x49\x50\x2f\x32\x2e\x30\x2f\x55\x44\x50\x20\x3b\x63\x6f\x6d\x70\x3d" \ + "\x73\x69\x67\x63\x6f\x6d\x70\x72\x6f\x62\x61\x74\x69\x6f\x6e\x61\x63\x6b\x3b\x62\x72\x61" \ + "\x6e\x63\x68\x3d\x7a\x39\x68\x47\x34\x62\x4b\x0d\x0a\x4d\x61\x78\x2d\x46\x6f\x72\x77\x61" \ + "\x72\x64\x73\x3a\x20\x41\x70\x72\x20\x53\x43\x54\x50\x52\x41\x43\x4b\x20\x49\x4e\x56\x49" \ + "\x54\x45\x20\x0d\x0a\x43\x61\x6c\x6c\x2d\x49\x44\x3a\x20\x0d\x0a\x43\x6f\x6e\x74\x61\x63" \ + "\x74\x3a\x20\x32\x30\x30\x20\x4f\x4b\x0d\x0a\x46\x72\x6f\x6d\x3a\x20\x0d\x0a\x43\x53\x65" \ + "\x71\x3a\x20\x0d\x0a\x54\x6f\x3a\x20\x3b\x74\x61\x67\x3d\x04\x10\xdd\x10\x11\x31\x0d\x11" \ + "\x0a\x07\x10\xb9\x0c\x10\xfe\x12\x10\xe1\x06\x11\x4e\x07\x11\x4e\x03\x11\x4a\x04\x11\x4a" \ + "\x07\x10\xb2\x08\x11\x79\x06\x11\x81\x0f\x11\x22\x0b\x11\x55\x06\x11\x6b\x0b\x11\x60\x13" \ + "\x10\xb2\x08\x11\x71\x05\x11\x87\x13\x10\xf7\x09\x0e\x8d\x08\x0d\xae\x0c\x10\xb9\x07\x10" \ + "\x8e\x03\x0d\x96\x03\x10\x8a\x04\x10\x8a\x09\x0d\xd7\x0a\x0f\x12\x08\x0f\x8f\x09\x0f\x8f" \ + "\x08\x0d\x6c\x06\x0e\x66\x09\x0e\x6c\x0a\x0e\x6c\x06\x0f\xc6\x07\x0f\xc6\x05\x11\x48\x06" \ + "\x11\x48\x06\x0f\xbf\x07\x0f\xbf\x07\x0e\x55\x06\x0f\x16\x04\x0e\xf4\x03\x0e\xb1\x03\x10" \ + "\xa6\x09\x10\x50\x03\x10\xa3\x0a\x0d\xb4\x05\x0e\x36\x06\x0e\xd6\x03\x0d\xf9\x11\x0e\xf8" \ + "\x04\x0c\xd9\x08\x0e\xea\x04\x09\x53\x03\x0a\x4b\x04\x0e\xe4\x10\x0f\x35\x09\x0e\xe4\x08" \ + "\x0d\x3f\x03\x0f\xe1\x0b\x10\x01\x03\x10\xac\x06\x10\x95\x0c\x0e\x76\x0b\x0f\xeb\x0a\x0f" \ + "\xae\x05\x10\x2b\x04\x10\x2b\x08\x10\x7a\x10\x0f\x49\x07\x0f\xb8\x09\x10\x3e\x0b\x10\x0c" \ + "\x07\x0f\x78\x0b\x0f\x6d\x09\x10\x47\x08\x10\x82\x0b\x0f\xf6\x08\x10\x62\x08\x0f\x87\x08" \ + "\x10\x6a\x04\x0f\x78\x0d\x0f\xcd\x08\x0d\xae\x10\x0f\x5d\x0b\x0f\x98\x14\x0d\x20\x1b\x0d" \ + "\x20\x04\x0d\xe0\x14\x0e\xb4\x0b\x0f\xa3\x0b\x07\x34\x0f\x0d\x56\x04\x0e\xf4\x03\x10\xaf" \ + "\x07\x0d\x34\x09\x0f\x27\x04\x10\x9b\x04\x10\x9f\x09\x10\x59\x08\x10\x72\x09\x10\x35\x0a" \ + "\x10\x21\x0a\x10\x17\x08\x0f\xe3\x03\x10\xa9\x05\x0c\xac\x04\x0c\xbd\x07\x0c\xc1\x08\x0c" \ + "\xc1\x09\x0c\xf6\x10\x0c\x72\x0c\x0c\x86\x04\x0d\x64\x0c\x0c\xd5\x09\x0c\xff\x1b\x0b\xfc" \ + "\x11\x0c\x5d\x13\x0c\x30\x09\x0c\xa4\x0c\x0c\x24\x0c\x0d\x3b\x03\x0d\x1a\x03\x0d\x1d\x16" \ + "\x0c\x43\x09\x0c\x92\x09\x0c\x9b\x0d\x0e\xcb\x04\x0d\x16\x06\x0d\x10\x05\x04\xf2\x0b\x0c" \ + "\xe1\x05\x0b\xde\x0a\x0c\xec\x13\x0b\xe3\x07\x0b\xd4\x08\x0d\x08\x0c\x0c\xc9\x09\x0c\x3a" \ + "\x04\x0a\xe5\x0c\x0a\x23\x08\x0b\x3a\x0e\x09\xab\x0f\x0e\xfa\x09\x0f\x6f\x0c\x0a\x17\x0f" \ + "\x09\x76\x0c\x0a\x5f\x17\x0d\xe2\x0f\x07\xa8\x0a\x0f\x85\x0f\x08\xd6\x0e\x09\xb9\x0b\x0a" \ + "\x7a\x03\x0b\xdb\x03\x08\xc1\x04\x0e\xc7\x03\x08\xd3\x02\x04\x8d\x08\x0b\x4a\x05\x0b\x8c" \ + "\x07\x0b\x61\x06\x05\x48\x04\x07\xf4\x05\x10\x30\x04\x07\x1e\x08\x07\x1e\x05\x0b\x91\x10" \ + "\x04\xca\x09\x0a\x71\x09\x0e\x87\x05\x04\x98\x05\x0b\x6e\x0b\x04\x9b\x0f\x04\x9b\x07\x04" \ + "\x9b\x03\x04\xa3\x07\x04\xa3\x10\x07\x98\x09\x07\x98\x05\x0b\x73\x05\x0b\x78\x05\x0b\x7d" \ + "\x05\x07\xb9\x05\x0b\x82\x05\x0b\x87\x05\x0b\x1d\x05\x08\xe4\x05\x0c\x81\x05\x0f\x44\x05" \ + "\x11\x40\x05\x08\x78\x05\x08\x9d\x05\x0f\x58\x05\x07\x3f\x05\x0c\x6d\x05\x10\xf2\x05\x0c" \ + "\x58\x05\x06\xa9\x04\x07\xb6\x09\x05\x8c\x06\x06\x1a\x06\x0e\x81\x0a\x06\x16\x0a\x0a\xc4" \ + "\x07\x0b\x5a\x0a\x0a\xba\x03\x0b\x1b\x04\x11\x45\x06\x0c\x8c\x07\x05\xad\x0a\x0e\xda\x08" \ + "\x0b\x42\x0d\x09\xf7\x0b\x05\x1c\x09\x11\x16\x08\x05\xc9\x07\x0d\x86\x06\x0b\xcf\x0a\x06" \ + "\x4d\x04\x0b\xa2\x06\x06\x8d\x08\x05\xe6\x08\x0e\x11\x0b\x0a\x9b\x03\x0a\x04\x03\x0b\xb5" \ + "\x05\x10\xd7\x04\x09\x94\x05\x0a\xe2\x03\x0b\xb2\x06\x0d\x67\x04\x0d\x11\x08\x08\xb7\x1b" \ + "\x0e\x3b\x0a\x09\xa1\x14\x04\x85\x15\x07\x83\x15\x07\x6e\x0d\x09\x3d\x17\x06\xae\x0f\x07" \ + "\xe6\x14\x07\xbe\x0d\x06\x0a\x0d\x09\x30\x16\x06\xf2\x12\x08\x1e\x21\x04\xaa\x13\x10\xc5" \ + "\x08\x0a\x0f\x1c\x0e\x96\x18\x0b\xb8\x1a\x05\x95\x1a\x05\x75\x11\x06\x3d\x16\x06\xdc\x1e" \ + "\x0e\x19\x16\x05\xd1\x1d\x06\x20\x23\x05\x27\x11\x08\x7d\x11\x0d\x99\x16\x04\xda\x0d\x0f" \ + "\x1c\x16\x07\x08\x17\x05\xb4\x0d\x08\xc7\x13\x07\xf8\x12\x08\x57\x1f\x04\xfe\x19\x05\x4e" \ + "\x13\x08\x0b\x0f\x08\xe9\x17\x06\xc5\x13\x06\x7b\x19\x05\xf1\x15\x07\x44\x18\x0d\xfb\x0b" \ + "\x0f\x09\x1b\x0d\xbe\x12\x08\x30\x15\x07\x59\x04\x0b\xa6\x04\x0b\xae\x04\x0b\x9e\x04\x0b" \ + "\x96\x04\x0b\x9a\x0a\x0a\xb0\x0b\x0a\x90\x08\x0b\x32\x0b\x09\x6b\x08\x0b\x2a\x0b\x0a\x85" \ + "\x09\x0b\x12\x0a\x0a\xa6\x0d\x09\xea\x13\x0d\x74\x14\x07\xd2\x13\x09\x0b\x12\x08\x42\x10" \ + "\x09\x5b\x12\x09\x1e\x0d\x0c\xb1\x0e\x0c\x17\x11\x09\x4a\x0c\x0a\x53\x0c\x0a\x47\x09\x0a" \ + "\xf7\x0e\x09\xc7\x0c\x0a\x3b\x07\x06\x69\x08\x06\x69\x06\x09\xe3\x08\x0b\x52\x0a\x0a\xd8" \ + "\x12\x06\x57\x0d\x06\x57\x07\x09\xe3\x04\x0a\xe9\x10\x07\x30\x09\x0b\x00\x0c\x0a\x2f\x05" \ + "\x0a\xe9\x05\x0a\x6b\x06\x0a\x6b\x0a\x0a\xce\x09\x0a\xee\x03\x0b\xdb\x07\x0f\x7e\x0a\x09" \ + "\x97\x0a\x06\x71\x0e\x09\xd5\x17\x06\x93\x07\x0e\x5c\x07\x0f\xda\x0a\x0f\x35\x0d\x0d\xec" \ + "\x0a\x09\x97\x0a\x06\x71\x08\x0b\x22\x0f\x09\x85\x06\x0b\x68\x0c\x0d\x4a\x09\x0b\x09\x13" \ + "\x08\xf8\x15\x08\xa2\x04\x0b\xaa\x0f\x05\x66\x0d\x07\x23\x09\x0a\x06\x0b\x0d\x4a\x0f\x04" \ + "\xee\x06\x04\xf8\x04\x09\x2b\x04\x08\x53\x07\x08\xc0\x03\x11\x1f\x04\x11\x1e\x07\x0d\x8c" \ + "\x03\x07\x34\x04\x10\xdb\x03\x07\x36\x03\x0d\xa9\x0d\x04\x20\x0b\x04\x51\x0c\x04\x3a\x04" \ + "\x0b\xb8\x04\x0c\x24\x04\x05\x95\x04\x04\x7c\x04\x05\x75\x04\x04\x85\x04\x09\x6b\x04\x06" \ + "\x3d\x06\x04\x7b\x04\x06\xdc\x04\x07\x83\x04\x0e\x19\x12\x04\x00\x10\x08\x8e\x10\x08\x69" \ + "\x0e\x04\x12\x0d\x04\x2d\x03\x10\xb9\x04\x05\xd1\x04\x07\x6e\x04\x06\x20\x07\x04\x74\x04" \ + "\x0b\xfc\x0a\x04\x5c\x04\x05\x27\x04\x09\x3d\x04\x08\x7d\x04\x0f\xae\x04\x0d\x99\x04\x06" \ + "\xae\x04\x04\xda\x09\x04\x09\x08\x11\x22\x04\x0f\x1c\x04\x07\xe6\x04\x0e\xcb\x05\x08\xbd" \ + "\x04\x07\x08\x04\x0f\xa3\x04\x06\x57\x04\x05\xb4\x04\x0f\x5d\x04\x08\xc7\x08\x0b\xf4\x04" \ + "\x07\xf8\x04\x07\x30\x04\x07\xbe\x04\x08\x57\x05\x0d\x46\x04\x04\xfe\x04\x06\x0a\x04\x05" \ + "\x4e\x04\x0e\x3b\x04\x08\x0b\x04\x09\x30\x04\x08\xe9\x05\x05\xee\x04\x06\xc5\x04\x06\xf2" \ + "\x04\x06\x7b\x04\x09\xa1\x04\x05\xf1\x04\x08\x1e\x04\x07\x44\x04\x0b\xdd\x04\x0d\xfb\x04" \ + "\x04\xaa\x04\x0b\xe3\x07\x0e\xee\x04\x0f\x09\x04\x0e\xb4\x04\x0d\xbe\x04\x10\xc5\x04\x08" \ + "\x30\x05\x0f\x30\x04\x07\x59\x04\x0a\x0f\x06\x0e\x61\x04\x04\x81\x04\x0d\xab\x04\x0d\x93" \ + "\x04\x11\x6b\x04\x0e\x96\x05\x04\x66\x09\x04\x6b\x0b\x04\x46\x04\x0c\xe1" + +TCOMP_END_DECLS + +#endif /* _TINYSIGCOMPP_RFC3485_H_ */ + diff --git a/tinySIGCOMP/src/tcomp_rfc5049_sip.h b/tinySIGCOMP/src/tcomp_rfc5049_sip.h new file mode 100644 index 0000000..581e837 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_rfc5049_sip.h @@ -0,0 +1,54 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_rfc5049_sip.h + * @brief RFC 5049 - Applying Signaling Compression (SigComp) to the Session Initiation Protocol (SIP) + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ + +#ifndef _TINYSIGCOMPP_RFC5049_H_ +#define _TINYSIGCOMPP_RFC5049_H_ + +/***** +Applying Signaling Compression (SigComp) + to the Session Initiation Protocol (SIP) +*****/ +/** 4.1. decompression_memory_size (DMS) for SIP/SigComp*/ +#define SIP_RFC5049_DECOMPRESSION_MEMORY_SIZE 8192 + +/** 4.2. state_memory_size (SMS) for SIP/SigComp (per compartment) */ +#define SIP_RFC5049_STATE_MEMORY_SIZE 8192 + +/** 4.3. cycles_per_bit (CPB) for SIP/SigComp */ +#define SIP_RFC5049_CYCLES_PER_BIT 64 + +/** 4.4. SigComp_version (SV) for SIP/SigComp */ +#define SIP_RFC5049_SIGCOMP_VERSION 0x02 // (at least SigComp + NACK) + +// 4.5. locally available state (LAS) for SIP/SigComp +// Minimum LAS for SIP/SigComp: the SIP/SDP static dictionary as defined + //in [RFC3485]. + +#endif /* _TINYSIGCOMPP_RFC5049_H_ */ diff --git a/tinySIGCOMP/src/tcomp_rfc5112_dictionary_presence.h b/tinySIGCOMP/src/tcomp_rfc5112_dictionary_presence.h new file mode 100644 index 0000000..b4ee068 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_rfc5112_dictionary_presence.h @@ -0,0 +1,209 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_rfc3485_dictionary_sip.h + * @brief RFC 3485 - The Session Initiation Protocol (SIP) and Session Description Protocol + * (SDP) Static Dictionary for Signaling Compression (SigComp) + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ + +#ifndef _TINYSIGCOMPP_RFC5112_H_ +#define _TINYSIGCOMPP_RFC5112_H_ + +TCOMP_BEGIN_DECLS + +#define RFC5112_DICTIONARY_PRESENCE_VALUE_LENGTH 0x0d93 +#define RFC5112_DICTIONARY_PRESENCE_STATE_ADDRESS 0 /*(not relevant for the dictionary) */ +#define RFC5112_DICTIONARY_PRESENCE_STATE_INSTRUCTION 0 /*(not relevant for the dictionary) */ +#define RFC5112_DICTIONARY_PRESENCE_MINIMUM_ACCESS_LENGTH 6 + +#define RFC5112_DICTIONARY_PRESENCE_IDENTIFIER_LENGTH 20 + +#define RFC5112_DICTIONARY_PRESENCE_IDENTIFIER \ + "\xd9\x42\x29\x7d\x0b\xb3\x8f\xc0\x1d\x67\x41\xd6\xb3\xb4\x81\x57\xac\x8e\x1b\xe0" + +#define RFC5112_DICTIONARY_PRESENCE_VALUE \ + "\x63\x6f\x6e\x76\x65\x6e\x74\x69\x6f\x6e\x2d\x63\x65\x6e\x74\x65\x72\x6d\x69\x6e\x61\x74" \ + "\x65\x64\x65\x70\x72\x65\x73\x73\x65\x64\x69\x73\x67\x75\x73\x74\x65\x64\x69\x6e\x64\x75" \ + "\x73\x74\x72\x69\x61\x6c\x61\x73\x74\x2d\x69\x6e\x70\x75\x74\x3d\x68\x75\x6d\x69\x6c\x69" \ + "\x61\x74\x65\x64\x6f\x6d\x61\x69\x6e\x3d\x61\x75\x74\x6f\x6d\x6f\x62\x69\x6c\x65\x63\x75" \ + "\x72\x69\x6f\x75\x73\x70\x69\x72\x69\x74\x73\x2d\x49\x4e\x44\x50\x73\x65\x6e\x64\x2d\x6f" \ + "\x6e\x6c\x79\x70\x61\x74\x68\x65\x61\x74\x65\x72\x65\x73\x74\x6c\x65\x73\x73\x6c\x65\x65" \ + "\x70\x79\x69\x6e\x2d\x70\x65\x72\x73\x6f\x6e\x61\x6c\x6f\x6e\x65\x6c\x79\x70\x6c\x61\x79" \ + "\x66\x75\x6c\x6f\x77\x65\x72\x74\x68\x61\x6e\x6e\x6f\x79\x65\x64\x75\x6e\x63\x6f\x6d\x66" \ + "\x6f\x72\x74\x61\x62\x6c\x65\x78\x63\x6c\x75\x64\x65\x3d\x63\x6f\x6e\x66\x75\x73\x65\x64" \ + "\x76\x61\x63\x61\x74\x69\x6f\x6e\x63\x6c\x75\x62\x75\x73\x2d\x73\x74\x61\x74\x69\x6f\x6e" \ + "\x61\x69\x72\x63\x72\x61\x66\x74\x68\x69\x72\x73\x74\x79\x63\x6f\x75\x72\x69\x65\x72\x65" \ + "\x6a\x65\x63\x74\x65\x64\x68\x69\x73\x74\x69\x6e\x66\x6f\x66\x66\x69\x63\x65\x72\x65\x6d" \ + "\x6f\x76\x65\x3d\x61\x72\x65\x6e\x61\x62\x6c\x65\x64\x3d\x52\x45\x46\x45\x52\x45\x47\x49" \ + "\x53\x54\x45\x52\x77\x61\x69\x74\x69\x6e\x67\x72\x75\x6d\x70\x79\x70\x72\x65\x66\x69\x78" \ + "\x3d\x68\x61\x6c\x66\x72\x65\x69\x67\x68\x74\x6d\x65\x61\x6e\x67\x72\x79\x53\x55\x42\x53" \ + "\x43\x52\x49\x42\x45\x70\x72\x6f\x76\x61\x74\x69\x6f\x6e\x69\x6e\x63\x6c\x75\x64\x65\x3d" \ + "\x61\x70\x70\x72\x6f\x76\x65\x64\x68\x6f\x6c\x69\x64\x61\x79\x75\x6e\x6b\x6e\x6f\x77\x6e" \ + "\x70\x61\x72\x6b\x69\x6e\x67\x4d\x45\x53\x53\x41\x47\x45\x77\x6f\x72\x72\x69\x65\x64\x68" \ + "\x75\x6d\x62\x6c\x65\x64\x61\x69\x72\x70\x6f\x72\x74\x61\x73\x68\x61\x6d\x65\x64\x70\x6c" \ + "\x61\x79\x69\x6e\x67\x50\x55\x42\x4c\x49\x53\x48\x68\x75\x6e\x67\x72\x79\x63\x72\x61\x6e" \ + "\x6b\x79\x61\x6d\x61\x7a\x65\x64\x61\x66\x72\x61\x69\x64\x55\x50\x44\x41\x54\x45\x4e\x4f" \ + "\x54\x49\x46\x59\x49\x4e\x56\x49\x54\x45\x43\x41\x4e\x43\x45\x4c\x66\x72\x69\x65\x6e\x64" \ + "\x70\x6f\x73\x74\x61\x6c\x66\x61\x6d\x69\x6c\x79\x70\x72\x69\x73\x6f\x6e\x69\x6e\x5f\x61" \ + "\x77\x65\x62\x72\x61\x76\x65\x71\x75\x69\x65\x74\x62\x6f\x72\x65\x64\x50\x52\x41\x43\x4b" \ + "\x70\x72\x6f\x75\x64\x66\x69\x78\x65\x64\x68\x6f\x74\x65\x6c\x68\x61\x70\x70\x79\x63\x61" \ + "\x66\x65\x63\x69\x64\x3d\x62\x61\x6e\x6b\x6d\x69\x6e\x3d\x61\x77\x61\x79\x6d\x61\x78\x3d" \ + "\x6d\x65\x61\x6c\x62\x75\x73\x79\x77\x6f\x72\x6b\x75\x72\x6e\x3d\x63\x6f\x6c\x64\x68\x75" \ + "\x72\x74\x6a\x65\x61\x6c\x6f\x75\x73\x70\x69\x72\x69\x74\x73\x2d\x75\x73\x65\x72\x2d\x70" \ + "\x72\x6f\x67\x6f\x76\x65\x72\x6e\x6d\x65\x6e\x74\x72\x61\x69\x6e\x2d\x73\x74\x61\x74\x69" \ + "\x6f\x6e\x6f\x72\x65\x66\x65\x72\x73\x75\x62\x73\x63\x72\x69\x62\x65\x66\x6f\x72\x65\x74" \ + "\x72\x61\x6e\x73\x6d\x69\x73\x73\x69\x6f\x6e\x2d\x61\x6c\x6c\x6f\x77\x65\x64\x75\x72\x61" \ + "\x74\x69\x6f\x6e\x2d\x73\x75\x62\x73\x63\x72\x69\x62\x65\x64\x3d\x68\x69\x67\x68\x65\x72" \ + "\x74\x68\x61\x6e\x78\x69\x6f\x75\x73\x65\x72\x76\x69\x63\x65\x2d\x64\x65\x73\x63\x72\x69" \ + "\x70\x74\x69\x6f\x6e\x3d\x62\x72\x65\x61\x6b\x66\x61\x73\x74\x61\x64\x69\x75\x6d\x73\x67" \ + "\x2d\x74\x61\x6b\x65\x72\x65\x6d\x6f\x72\x73\x65\x66\x75\x6c\x6c\x3a\x63\x69\x76\x69\x63" \ + "\x4c\x6f\x63\x6f\x6e\x66\x65\x72\x65\x6e\x63\x65\x71\x75\x61\x6c\x73\x74\x72\x65\x73\x73" \ + "\x65\x64\x77\x61\x74\x65\x72\x63\x72\x61\x66\x74\x65\x72\x61\x6e\x67\x65\x3a\x62\x61\x73" \ + "\x69\x63\x50\x6f\x6c\x69\x63\x79\x63\x6c\x65\x63\x6f\x75\x6e\x74\x72\x79\x63\x68\x61\x6e" \ + "\x67\x65\x64\x75\x6e\x74\x69\x6c\x3d\x61\x64\x64\x65\x64\x75\x72\x69\x3d\x77\x68\x61\x74" \ + "\x70\x65\x72\x6d\x61\x6e\x65\x6e\x74\x2d\x61\x62\x73\x65\x6e\x63\x65\x6d\x62\x61\x72\x72" \ + "\x61\x73\x73\x65\x64\x65\x61\x63\x74\x69\x76\x61\x74\x65\x64\x69\x73\x74\x72\x61\x63\x74" \ + "\x65\x64\x69\x6e\x6e\x65\x72\x76\x6f\x75\x73\x65\x6c\x66\x69\x6c\x74\x65\x72\x65\x6c\x69" \ + "\x65\x76\x65\x64\x66\x6c\x69\x72\x74\x61\x74\x69\x6f\x75\x73\x61\x67\x65\x2d\x72\x75\x6c" \ + "\x65\x73\x65\x72\x76\x63\x61\x70\x73\x70\x68\x65\x72\x65\x67\x69\x73\x74\x72\x61\x74\x69" \ + "\x6f\x6e\x2d\x73\x74\x61\x74\x65\x3d\x62\x61\x72\x72\x69\x6e\x67\x2d\x73\x74\x61\x74\x65" \ + "\x78\x74\x65\x72\x6e\x61\x6c\x2d\x72\x75\x6c\x65\x73\x65\x74\x69\x6d\x65\x2d\x6f\x66\x66" \ + "\x73\x65\x74\x64\x69\x61\x6c\x6f\x67\x69\x6e\x5f\x6c\x6f\x76\x65\x72\x72\x69\x64\x69\x6e" \ + "\x67\x2d\x77\x69\x6c\x6c\x69\x6e\x67\x6e\x65\x73\x73\x70\x65\x63\x74\x61\x74\x6f\x72\x65" \ + "\x73\x69\x64\x65\x6e\x63\x65\x76\x65\x6e\x74\x2d\x70\x61\x63\x6b\x61\x67\x65\x73\x75\x70" \ + "\x65\x72\x76\x69\x73\x6f\x72\x65\x73\x74\x61\x75\x72\x61\x6e\x74\x72\x75\x63\x6b\x70\x6c" \ + "\x6d\x6f\x62\x69\x6c\x69\x74\x79\x6a\x6f\x69\x6e\x61\x70\x70\x72\x6f\x70\x72\x69\x61\x74" \ + "\x65\x76\x65\x6e\x74\x6c\x69\x73\x74\x65\x65\x72\x69\x6e\x67\x69\x76\x65\x75\x70\x72\x69" \ + "\x6e\x63\x69\x70\x61\x6c\x61\x6e\x67\x75\x61\x67\x65\x73\x63\x68\x65\x6d\x65\x73\x73\x61" \ + "\x67\x65\x2d\x73\x75\x6d\x6d\x61\x72\x79\x70\x6c\x61\x63\x65\x2d\x6f\x66\x2d\x77\x6f\x72" \ + "\x73\x68\x69\x70\x6c\x61\x63\x65\x2d\x74\x79\x70\x65\x3d\x3a\x74\x69\x6d\x65\x64\x2d\x73" \ + "\x74\x61\x74\x75\x73\x2d\x69\x63\x6f\x6e\x73\x74\x72\x75\x63\x74\x69\x6f\x6e\x65\x75\x74" \ + "\x72\x61\x6c\x49\x4e\x46\x4f\x50\x54\x49\x4f\x4e\x53\x69\x65\x6d\x65\x6e\x73\x2d\x52\x54" \ + "\x50\x2d\x53\x74\x61\x74\x73\x65\x72\x76\x69\x63\x65\x2d\x69\x64\x6c\x65\x2d\x74\x68\x72" \ + "\x65\x73\x68\x6f\x6c\x64\x3d\x70\x75\x62\x6c\x69\x63\x2d\x74\x72\x61\x6e\x73\x70\x6f\x72" \ + "\x74\x6f\x6f\x62\x72\x69\x67\x68\x74\x72\x69\x67\x67\x65\x72\x65\x73\x6f\x75\x72\x63\x65" \ + "\x3d\x3a\x67\x65\x6f\x70\x72\x69\x76\x31\x30\x30\x72\x65\x6c\x61\x74\x69\x6f\x6e\x73\x68" \ + "\x69\x70\x6f\x63\x2d\x73\x65\x74\x74\x69\x6e\x67\x73\x75\x72\x70\x72\x69\x73\x65\x64\x61" \ + "\x72\x6b\x75\x72\x6e\x3a\x6f\x6d\x61\x3a\x78\x6d\x6c\x3a\x70\x72\x73\x3a\x70\x69\x64\x66" \ + "\x3a\x6f\x6d\x61\x2d\x70\x72\x65\x73\x65\x6e\x74\x61\x74\x69\x6f\x6e\x6f\x69\x73\x79\x3a" \ + "\x73\x69\x6d\x70\x6c\x65\x2d\x66\x69\x6c\x74\x65\x72\x2d\x73\x65\x74\x69\x6d\x65\x6f\x75" \ + "\x74\x64\x6f\x6f\x72\x73\x63\x68\x6f\x6f\x6c\x70\x61\x72\x74\x69\x61\x6c\x6f\x63\x61\x74" \ + "\x69\x6f\x6e\x2d\x69\x6e\x66\x6f\x72\x6d\x61\x74\x69\x6f\x6e\x61\x6d\x65\x65\x74\x69\x6e" \ + "\x67\x63\x61\x6c\x6d\x65\x74\x68\x6f\x64\x73\x74\x6f\x72\x65\x74\x65\x6e\x74\x69\x6f\x6e" \ + "\x2d\x65\x78\x70\x69\x72\x79\x3a\x77\x61\x74\x63\x68\x65\x72\x69\x6e\x66\x6f\x66\x66\x65" \ + "\x6e\x64\x65\x64\x63\x6f\x6e\x74\x72\x6f\x6c\x6f\x6f\x6b\x69\x6e\x67\x2d\x66\x6f\x72\x2d" \ + "\x77\x6f\x72\x6b\x69\x6e\x67\x77\x61\x74\x63\x68\x65\x72\x2d\x6c\x69\x73\x74\x72\x65\x65" \ + "\x74\x70\x6c\x61\x63\x65\x2d\x69\x73\x66\x6f\x63\x75\x73\x6f\x75\x6e\x64\x65\x72\x77\x61" \ + "\x79\x68\x6f\x6d\x65\x70\x61\x67\x65\x70\x72\x69\x76\x61\x63\x79\x77\x61\x72\x65\x68\x6f" \ + "\x75\x73\x65\x72\x2d\x69\x6e\x70\x75\x74\x72\x61\x76\x65\x6c\x62\x6f\x74\x68\x65\x72\x65" \ + "\x63\x65\x69\x76\x65\x2d\x6f\x6e\x6c\x79\x3a\x72\x6c\x6d\x69\x6e\x76\x61\x6c\x75\x65\x3d" \ + "\x3a\x63\x61\x70\x73\x6c\x65\x65\x70\x69\x6e\x67\x75\x69\x6c\x74\x79\x69\x6e\x76\x69\x6e" \ + "\x63\x69\x62\x6c\x65\x76\x65\x6e\x74\x3d\x6d\x6f\x6f\x64\x79\x70\x61\x63\x6b\x61\x67\x65" \ + "\x3d\x70\x72\x69\x6f\x72\x69\x74\x79\x76\x69\x64\x65\x6f\x66\x72\x6f\x6d\x3d\x61\x75\x64" \ + "\x69\x6f\x63\x61\x72\x64\x70\x6f\x73\x3d\x61\x75\x74\x6f\x6d\x61\x74\x61\x70\x70\x6c\x69" \ + "\x63\x61\x74\x69\x6f\x6e\x6f\x74\x73\x75\x70\x70\x6f\x72\x74\x65\x64\x65\x76\x69\x63\x65" \ + "\x49\x44\x69\x6d\x70\x72\x65\x73\x73\x65\x64\x69\x73\x61\x70\x70\x6f\x69\x6e\x74\x65\x64" \ + "\x6e\x6f\x74\x65\x2d\x77\x65\x6c\x6c\x69\x62\x72\x61\x72\x79\x3a\x64\x61\x74\x61\x2d\x6d" \ + "\x6f\x64\x65\x6c\x65\x63\x74\x72\x6f\x6e\x69\x63\x69\x76\x69\x63\x41\x64\x64\x72\x65\x73" \ + "\x73\x61\x72\x63\x61\x73\x74\x69\x63\x6f\x6e\x74\x65\x6e\x74\x65\x64\x69\x6e\x64\x69\x67" \ + "\x6e\x61\x6e\x74\x69\x6d\x65\x72\x65\x70\x6c\x61\x63\x65\x73\x68\x6f\x63\x6b\x65\x64\x63" \ + "\x6c\x61\x73\x73\x69\x73\x74\x61\x6e\x74\x69\x6d\x65\x73\x74\x61\x6d\x70\x72\x6f\x76\x69" \ + "\x64\x65\x64\x2d\x62\x79\x3a\x63\x69\x70\x69\x64\x66\x2d\x66\x75\x6c\x6c\x53\x74\x61\x74" \ + "\x65\x3d\x61\x63\x74\x6f\x72\x65\x6d\x6f\x76\x65\x64\x62\x75\x73\x69\x6e\x65\x73\x73\x65" \ + "\x72\x69\x6f\x75\x73\x65\x6c\x3d\x3a\x73\x63\x68\x65\x6d\x61\x78\x76\x61\x6c\x75\x65\x3d" \ + "\x3a\x72\x70\x69\x64\x75\x72\x6e\x3a\x69\x65\x74\x66\x3a\x70\x61\x72\x61\x6d\x73\x3a\x78" \ + "\x6d\x6c\x2d\x70\x61\x74\x63\x68\x2d\x6f\x70\x73\x65\x63\x2d\x61\x67\x72\x65\x65\x61\x72" \ + "\x6c\x79\x2d\x73\x65\x73\x73\x69\x6f\x6e\x2d\x70\x61\x74\x69\x63\x69\x70\x61\x74\x69\x6f" \ + "\x6e\x2d\x74\x68\x65\x2d\x70\x68\x6f\x6e\x65\x74\x77\x6f\x72\x6b\x2d\x61\x76\x61\x69\x6c" \ + "\x61\x62\x69\x6c\x69\x74\x79\x70\x65\x72\x66\x6f\x72\x6d\x61\x6e\x63\x65\x78\x63\x69\x74" \ + "\x65\x64\x70\x72\x65\x63\x6f\x6e\x64\x69\x74\x69\x6f\x6e\x6f\x72\x65\x73\x6f\x75\x72\x63" \ + "\x65\x2d\x70\x72\x69\x6f\x72\x69\x74\x79\x3d\x66\x61\x6c\x73\x65\x72\x76\x69\x63\x65\x2d" \ + "\x63\x6c\x61\x73\x73\x72\x6f\x6f\x6d\x75\x73\x74\x55\x6e\x64\x65\x72\x73\x74\x61\x6e\x64" \ + "\x69\x73\x70\x6c\x61\x79\x2d\x6e\x61\x6d\x65\x3d\x69\x6e\x73\x74\x61\x6e\x63\x65\x78\x74" \ + "\x65\x6e\x73\x69\x6f\x6e\x73\x2d\x62\x69\x6e\x64\x69\x6e\x67\x73\x64\x70\x2d\x61\x6e\x61" \ + "\x74\x74\x65\x6e\x64\x61\x6e\x74\x72\x75\x65\x3a\x70\x69\x64\x66\x2d\x64\x69\x66\x66\x72" \ + "\x75\x73\x74\x72\x61\x74\x65\x64\x75\x70\x6c\x65\x78\x70\x69\x72\x61\x74\x69\x6f\x6e\x3d" \ + "\x63\x6f\x6e\x74\x61\x63\x74\x69\x76\x69\x74\x69\x65\x73\x68\x6f\x70\x70\x69\x6e\x67\x2d" \ + "\x61\x72\x65\x61\x73\x6f\x6e\x3d\x61\x70\x70\x6f\x69\x6e\x74\x6d\x65\x6e\x74\x69\x74\x79" \ + "\x3d\x61\x73\x73\x6f\x63\x69\x61\x74\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x69\x6e\x74\x65" \ + "\x72\x65\x73\x74\x65\x64\x65\x76\x63\x61\x70\x73\x74\x61\x74\x75\x73\x3d\x61\x63\x74\x69" \ + "\x76\x65\x72\x73\x69\x6f\x6e\x3d\x77\x69\x6e\x66\x6f\x70\x65\x6e\x64\x69\x6e\x67\x69\x6e" \ + "\x2d\x74\x72\x61\x6e\x73\x69\x74\x75\x70\x6c\x65\x68\x6f\x73\x70\x69\x74\x61\x6c\x61\x6e" \ + "\x67\x3d\x3c\x3f\x78\x6d\x6c\x6e\x73\x3d\x73\x69\x63\x6b\x70\x72\x65\x73\x65\x6e\x63\x65" \ + "\x55\x54\x46\x2d\x38\x3f\x3e\x63\x6c\x6f\x73\x65\x64\x05\x0d\x34\x08\x0d\x06\x09\x0c\xe3" \ + "\x07\x0d\x48\x06\x0d\x36\x13\x0b\xab\x05\x09\x65\x07\x0c\xd4\x08\x0d\x40\x05\x0d\x23\x05" \ + "\x0c\x35\x07\x0c\xae\x05\x0d\x2f\x06\x08\xb9\x05\x07\x2b\x04\x0d\x12\x06\x0d\x4f\x09\x0c" \ + "\x2c\x04\x0c\x89\x04\x0a\xf6\x09\x0b\x57\x0b\x0b\x05\x08\x0a\xda\x06\x0a\xda\x06\x04\x89" \ + "\x05\x0b\xa6\x04\x0b\x94\x06\x05\x05\x07\x0b\x3f\x0e\x0b\xba\x07\x0b\x98\x0a\x0c\x8d\x09" \ + "\x0b\x6d\x09\x0c\x8e\x0e\x0c\x48\x0a\x0c\xb2\x1d\x09\x56\x0d\x0c\x38\x06\x07\xba\x0b\x08" \ + "\xb9\x0b\x07\xec\x06\x0d\x02\x0a\x0a\x46\x04\x08\xf4\x06\x0b\x6a\x04\x0a\xb6\x0c\x0c\x55" \ + "\x08\x0a\x31\x04\x0a\x92\x08\x0a\x1b\x05\x0a\xb1\x04\x08\xc0\x05\x0a\x27\x05\x0a\xa7\x05" \ + "\x0a\xac\x04\x0a\xba\x04\x07\xdc\x05\x08\xad\x0a\x09\x29\x0a\x08\xa7\x05\x0a\x56\x05\x0b" \ + "\x4d\x07\x09\x2a\x0d\x09\xa7\x0b\x07\xa9\x06\x09\xc6\x0b\x0b\x5f\x0c\x09\xdf\x0b\x09\xe0" \ + "\x06\x07\xcb\x0c\x0a\x0b\x09\x09\x20\x08\x0a\x97\x07\x09\xe0\x07\x0c\xfb\x06\x0a\x8c\x0e" \ + "\x09\x7f\x0a\x09\x87\x0b\x0c\x71\x0a\x0c\x71\x06\x07\x93\x05\x0a\x66\x04\x08\x67\x04\x09" \ + "\xba\x08\x09\x20\x0a\x0b\x72\x05\x0a\x72\x08\x07\xb3\x0b\x0a\xc5\x07\x09\xf2\x07\x08\x89" \ + "\x04\x08\xad\x08\x0a\xbe\x06\x0c\x9f\x0b\x06\xd0\x0e\x08\x26\x08\x0a\x9f\x07\x09\xc6\x0a" \ + "\x0c\x69\x07\x08\x85\x05\x0b\x7c\x07\x0a\x39\x0c\x09\x34\x07\x0a\x21\x09\x08\x7d\x07\x0c" \ + "\xf5\x0b\x0c\xa3\x14\x06\xa6\x0d\x08\xb2\x0c\x07\x2a\x0c\x08\xb3\x04\x07\x56\x07\x09\x1a" \ + "\x04\x07\x52\x07\x07\x40\x05\x07\x4d\x07\x0b\x80\x06\x07\x47\x16\x06\x91\x08\x0c\x62\x10" \ + "\x09\xcf\x10\x07\xdd\x09\x0a\xf6\x09\x06\xfc\x0c\x0b\x17\x07\x07\x39\x04\x06\xf8\x07\x09" \ + "\xa1\x06\x06\x8d\x05\x07\x21\x04\x0a\x55\x09\x0a\xd2\x0c\x0a\xcf\x13\x06\xc8\x0a\x08\xec" \ + "\x07\x0d\x06\x0b\x08\x0c\x14\x0b\xd5\x12\x07\xbe\x0d\x07\xd1\x16\x08\x01\x14\x0b\xf1\x06" \ + "\x05\xb4\x07\x04\x56\x09\x04\x17\x0c\x0a\xea\x09\x04\x1f\x0a\x07\x7e\x0b\x07\x6a\x07\x0c" \ + "\x0f\x0b\x07\xa0\x0a\x0c\x96\x06\x05\x28\x06\x0a\x7d\x05\x06\x1f\x07\x05\x8b\x0a\x04\x3c" \ + "\x06\x05\xae\x04\x06\x50\x09\x0a\xe2\x06\x05\xf6\x07\x07\xfd\x09\x0b\x33\x0a\x0c\xec\x0a" \ + "\x0a\x83\x07\x06\x54\x06\x04\x90\x04\x05\x3f\x05\x0a\x92\x07\x07\x8a\x07\x08\xcc\x08\x09" \ + "\xea\x07\x04\x96\x05\x06\x10\x08\x07\x98\x0a\x06\xf1\x08\x04\x79\x09\x0b\x22\x07\x0b\x8e" \ + "\x07\x0b\x46\x04\x0d\x3c\x06\x04\x80\x08\x07\x12\x09\x09\x4a\x07\x04\xe3\x07\x05\x84\x05" \ + "\x09\x7a\x05\x06\x01\x09\x09\x12\x04\x09\x52\x0d\x04\xaa\x0d\x08\x56\x08\x04\xdc\x07\x05" \ + "\x92\x05\x05\x0c\x0a\x04\x4c\x04\x06\x2c\x0b\x04\xd1\x04\x06\x24\x09\x0c\x40\x04\x04\xce" \ + "\x0c\x08\xc1\x11\x04\x00\x05\x07\x34\x0a\x06\x6a\x08\x0d\x28\x05\x06\x1a\x0a\x04\x28\x07" \ + "\x0a\xfe\x06\x04\xff\x08\x09\x94\x07\x05\x76\x10\x08\x98\x06\x05\xf0\x06\x09\x03\x10\x09" \ + "\x03\x09\x08\x1e\x0a\x08\x3c\x06\x09\x9b\x0d\x0c\xbb\x07\x06\xe3\x05\x09\xcc\x06\x0a\x15" \ + "\x07\x04\x73\x05\x06\x73\x0d\x06\x73\x05\x08\x45\x08\x0a\x29\x09\x0a\x40\x05\x07\x1a\x0a" \ + "\x07\x1a\x09\x0b\x4f\x09\x0c\xdb\x06\x05\xea\x06\x05\xde\x0a\x04\x0e\x0a\x0b\x0e\x09\x06" \ + "\x86\x08\x05\x60\x0b\x07\x74\x09\x05\x4f\x08\x04\xf0\x07\x09\x90\x06\x08\x70\x0a\x0c\x21" \ + "\x07\x05\x6f\x0b\x0c\xcc\x04\x07\x90\x07\x04\xea\x0a\x08\x33\x04\x06\x34\x09\x06\xdc\x04" \ + "\x06\x40\x07\x05\x2e\x04\x06\x48\x06\x07\x87\x07\x05\x68\x0a\x0d\x1a\x07\x04\x45\x07\x05" \ + "\x05\x08\x05\x0e\x08\x05\x58\x08\x04\xb6\x10\x09\xf8\x04\x06\x3c\x07\x09\xbc\x0c\x06\xd0" \ + "\x0c\x0b\xe7\x04\x06\x44\x04\x0a\x31\x0b\x0c\x05\x04\x06\x28\x11\x07\x5a\x07\x0c\xc5\x07" \ + "\x05\xa0\x0c\x09\x6f\x08\x0c\xbb\x08\x0a\x76\x09\x08\x16\x08\x08\x69\x06\x05\xe4\x09\x04" \ + "\x86\x07\x05\x38\x06\x0a\x4f\x08\x04\xc6\x0f\x08\xf4\x0b\x04\x31\x07\x0a\x04\x07\x08\xa1" \ + "\x0d\x0c\x55\x06\x05\xc0\x06\x05\xba\x05\x05\x41\x08\x0b\x87\x08\x04\x89\x04\x05\x35\x0c" \ + "\x0a\x5a\x09\x04\x68\x09\x04\x9c\x0a\x06\xba\x06\x07\x0d\x05\x07\x25\x09\x0b\x9d\x09\x0a" \ + "\x69\x06\x0a\x6c\x04\x06\x38\x04\x06\x30\x07\x0d\x13\x08\x08\x4c\x05\x06\x15\x06\x04\x50" \ + "\x0a\x07\x04\x06\x07\xf7\x04\x08\x49\x0f\x08\x89\x0c\x09\x3f\x05\x06\x81\x11\x08\xdc\x0d" \ + "\x04\x5c\x11\x06\x5a\x05\x0d\x0e\x06\x05\xd8\x04\x08\xd3\x06\x05\xd2\x07\x05\x7d\x06\x05" \ + "\xcc\x07\x08\xd6\x05\x06\x0b\x07\x05\xa7\x05\x05\x16\x08\x05\x1a\x09\x05\x46\x06\x05\xc6" \ + "\x06\x09\x31\x0d\x0b\xcf\x09\x08\x62\x08\x04\xf8\x04\x08\x54\x0a\x06\x7f\x04\x04\x71\x0c" \ + "\x0c\x16\x04\x05\x2e\x08\x0b\x3f\x11\x0c\x23\x08\x0c\x7b\x09\x0b\xc7\x07\x07\xf6\x05\x0b" \ + "\x3b\x09\x08\x75\x09\x0c\x81\x09\x06\xe9\x0b\x09\xb0\x07\x05\x22\x07\x04\xa3\x07\x06\xc2" \ + "\x07\x05\x99\x05\x06\x06\x05\x05\xfc\x04\x09\xc3\x04\x06\x4c\x08\x04\xbe\x09\x0b\x2a" + +TCOMP_END_DECLS + +#endif /* _TINYSIGCOMPP_RFC5112_H_ */ diff --git a/tinySIGCOMP/src/tcomp_state.c b/tinySIGCOMP/src/tcomp_state.c new file mode 100644 index 0000000..af9be22 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_state.c @@ -0,0 +1,207 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_state.c + * @brief SigComp state. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_state.h" +#include "tsk_memory.h" +#include "tsk_debug.h" +#include "tsk_sha1.h" + +/** Creates new SigComp state. +*/ +tcomp_state_t* tcomp_state_create(uint32_t length, uint32_t address, uint32_t instruction, uint32_t minimum_access_length, uint32_t retention_priority) +{ + tcomp_state_t *state; + if((state = tsk_object_new(tcomp_state_def_t))){ + state->length = length; + state->address = address; + state->instruction = instruction; + state->minimum_access_length = minimum_access_length; + state->retention_priority = retention_priority; + + state->value = tcomp_buffer_create_null(); + state->identifier = tcomp_buffer_create_null(); + } + else{ + TSK_DEBUG_ERROR("Failed to create new state."); + } + return state; +} + +/** Compares two sigomp states. +* @param state1 First state to compare. +* @param state2 Second state to compare. +* @retval 1 if the two handles are equals and 0 otherwise. +*/ +int tcomp_state_equals(const tcomp_state_t *state1, const tcomp_state_t *state2) +{ + if(state1 && state2) + { + return tcomp_buffer_equals(state1->identifier, state2->identifier); + } + else if(!state1 && !state2) return 1; + else return 0; +} + +/**Computes the state identifier by calculating a 20-byte SHA-1 hash [RFC-3174] over the +* byte string formed by concatenating the state_length, state_address, +* state_instruction, minimum_access_length and state_value (in the order given). +* @param state The state to make valid. +*/ +void tcomp_state_makeValid(tcomp_state_t* state) +{ + tsk_sha1context_t sha; + + if(!state){ + TSK_DEBUG_ERROR("Invalid parameter"); + return; + } + + /* Lock */ + tsk_safeobj_lock(state); + + tcomp_buffer_allocBuff(state->identifier, TSK_SHA1_DIGEST_SIZE); + + /*============= + * Calculates a 20-byte SHA-1 hash [RFC-3174] over the byte string formed by concatenating the state_length, state_address, + * state_instruction, minimum_access_length and state_value (in the order given). This is the state_identifier. + */ + { + uint8_t i; + int32_t err = tsk_sha1reset(&sha); + uint8_t firstPart[8]; + +#ifdef __SYMBIAN32__ + uint32_t values[4]; + values[0] = state->length, + values[1] = state->address, + values[2] = state->instruction, + values[3] = state->minimum_access_length; + +#else + uint32_t values[4] = { state->length, state->address, state->instruction, state->minimum_access_length }; +#endif + + for(i=0; i<4; i++) + { + #if 0 /*BIG_ENDIAN*/// Do not change this (it's for my own tests) + firstPart[i] = (values[i] & 0xff); + firstPart[i+1] = (values[i] >> 8); + #else + firstPart[2*i] = (values[i] >> 8); + firstPart[2*i+1] = (values[i]& 0xff); + #endif + } + + tsk_sha1input(&sha, firstPart, 8); + tsk_sha1input(&sha, tcomp_buffer_getBuffer(state->value), tcomp_buffer_getSize(state->value)); + err = tsk_sha1result(&sha, (uint8_t*)tcomp_buffer_getBuffer(state->identifier)); + } + + /* unlock */ + tsk_safeobj_unlock(state); +} + +int32_t tcomp_state_inc_usage_count(tcomp_state_t* self) +{ + if(!self){ + TSK_DEBUG_ERROR("Invalid parameter"); + return 0; + } + return ++self->usage_count; +} + +int32_t tcomp_state_dec_usage_count(tcomp_state_t* self) +{ + if(!self || self->usage_count <= 0){ + TSK_DEBUG_ERROR("Invalid parameter"); + return 0; + } + return --self->usage_count; +} + + + +//======================================================== +// State object definition +// +static tsk_object_t* tcomp_state_ctor(tsk_object_t * self, va_list * app) +{ + tcomp_state_t *state = self; + if(state){ + /* Initialize safeobject */ + tsk_safeobj_init(state); + } + else{ + TSK_DEBUG_ERROR("Failed to create new state."); + } + return state; +} + +static tsk_object_t* tcomp_state_dtor(tsk_object_t *self) +{ + tcomp_state_t *state = self; + if(state){ + TSK_DEBUG_INFO("==SigComp - Free state with id="); + tcomp_buffer_print(state->identifier); + + /* Deinitialize safeobject */ + tsk_safeobj_deinit(state); + + TSK_OBJECT_SAFE_FREE(state->identifier); + TSK_OBJECT_SAFE_FREE(state->value); + } + else{ + TSK_DEBUG_ERROR("Null SigComp state."); + } + + return self; +} + + +static int tcomp_state_cmp(const void *obj1, const void *obj2) +{ + const tcomp_state_t *state1 = obj1; + const tcomp_state_t *state2 = obj2; + + if(state1 && state2){ + return tcomp_buffer_equals(state1->identifier, state2->identifier) ? 0 : -1; + } + else if(!state1 && !state2) return 0; + else return -1; +} + +static const tsk_object_def_t tcomp_state_def_s = +{ + sizeof(tcomp_state_t), + tcomp_state_ctor, + tcomp_state_dtor, + tcomp_state_cmp +}; +const tsk_object_def_t *tcomp_state_def_t = &tcomp_state_def_s; + diff --git a/tinySIGCOMP/src/tcomp_state.h b/tinySIGCOMP/src/tcomp_state.h new file mode 100644 index 0000000..1e7ef70 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_state.h @@ -0,0 +1,82 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_state.h + * @brief SIGCOMP state. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#ifndef TCOMP_STATE_H +#define TCOMP_STATE_H + +#include "tinysigcomp_config.h" + +#include "tcomp_buffer.h" +#include "tsk_safeobj.h" +#include "tsk_list.h" + +TCOMP_BEGIN_DECLS + +#define TCOMP_PARTIAL_ID_LEN_CODE 0x01 +#define TCOMP_PARTIAL_ID_LEN_VALUE 0x06 + +/**For the purpose of calculation, each state item is considered to cost (state_length + 64) bytes. +*/ +#define TCOMP_GET_STATE_SIZE(state) ( (state) ? ((state)->length + 64) : 0 ) + +/**SigComp state. +*/ +typedef struct tcomp_state_s +{ + TSK_DECLARE_OBJECT; + + tcomp_buffer_handle_t *value; /**< State's value. */ + tcomp_buffer_handle_t *identifier; /**< State's identifier. */ + + uint32_t length; /**< State's length. */ + uint32_t address; /**< State's address. */ + uint32_t instruction; /**< State's instruction. */ + uint32_t minimum_access_length; /**< State's minimum access length. */ + uint32_t retention_priority; /**< State's retention priority. */ + + int32_t usage_count; /**< State's usage count (to avoid duplication). */ + + TSK_DECLARE_SAFEOBJ; +} +tcomp_state_t; + +typedef tcomp_state_t tcomp_dictionary_t; /**< Ad dictionary is a @ref tcomp_state_t. */ + +tcomp_state_t* tcomp_state_create(uint32_t length, uint32_t address, uint32_t instruction, uint32_t minimum_access_length, uint32_t retention_priority); + +int tcomp_state_equals(const tcomp_state_t *state1, const tcomp_state_t *state2); +void tcomp_state_makeValid(tcomp_state_t*); +int32_t tcomp_state_inc_usage_count(tcomp_state_t*); +int32_t tcomp_state_dec_usage_count(tcomp_state_t*); + +TINYSIGCOMP_GEXTERN const tsk_object_def_t *tcomp_state_def_t; + +TCOMP_END_DECLS + +#endif /* TCOMP_STATE_H */ diff --git a/tinySIGCOMP/src/tcomp_statehandler.c b/tinySIGCOMP/src/tcomp_statehandler.c new file mode 100644 index 0000000..596fdf9 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_statehandler.c @@ -0,0 +1,468 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_statehandler.c + * @brief SigComp state handler. + * Entity responsible for accessing and storing state information once permission is granted by the application. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_statehandler.h" +#include "tcomp_rfc5049_sip.h" +#include "tcomp_nack_codes.h" +#include "tcomp_dicts.h" +#include "tcomp_udvm.h" + +#include "tsk_debug.h" + +static int pred_find_compartment_by_id(const tsk_list_item_t *item, const void *id) +{ + if(item && item->data){ + tcomp_compartment_t *compartment = item->data; + int64_t res = (compartment->identifier - *((int64_t*)id)); + return res > 0 ? (int)1 : (res < 0 ? (int)-1 : (int)0); + } + return -1; +} + +/**Creates new SigComp state handler. +*/ +tcomp_statehandler_t* tcomp_statehandler_create() +{ + tcomp_statehandler_t* statehandler; + if((statehandler = tsk_object_new(tcomp_statehandler_def_t))){ + /* RFC 3320 - 3.3. SigComp Parameters */ + statehandler->sigcomp_parameters = tcomp_params_create(); + tcomp_params_setDmsValue(statehandler->sigcomp_parameters, SIP_RFC5049_DECOMPRESSION_MEMORY_SIZE); + tcomp_params_setSmsValue(statehandler->sigcomp_parameters, SIP_RFC5049_STATE_MEMORY_SIZE); + tcomp_params_setCpbValue(statehandler->sigcomp_parameters, SIP_RFC5049_CYCLES_PER_BIT); + + if(!(statehandler->dictionaries = tsk_list_create())){ + TSK_OBJECT_SAFE_FREE(statehandler); + goto bail; + } + if(!(statehandler->compartments = tsk_list_create())){ + TSK_OBJECT_SAFE_FREE(statehandler); + goto bail; + } + statehandler->sigcomp_parameters->SigComp_version = SIP_RFC5049_SIGCOMP_VERSION; +#if TCOMP_USE_ONLY_ACKED_STATES + statehandler->useOnlyACKedStates = tsk_true; +#endif + } +bail: + return statehandler; +} + +int tcomp_statehandler_setUseOnlyACKedStates(tcomp_statehandler_t* self, tsk_bool_t useOnlyACKedStates) +{ + tsk_list_item_t* item; + if(!self){ + TSK_DEBUG_ERROR("Invalid parameter"); + return -1; + } + self->useOnlyACKedStates = useOnlyACKedStates; + + tsk_safeobj_lock(self); + tsk_list_foreach(item, self->compartments){ + tcomp_compartment_setUseOnlyACKedStates((tcomp_compartment_t*)item->data, self->useOnlyACKedStates); + } + tsk_safeobj_unlock(self); + + return 0; +} + +tcomp_compartment_t *tcomp_statehandler_getCompartment(const tcomp_statehandler_t *statehandler, uint64_t id) +{ + tcomp_compartment_t *result = tsk_null; + tcomp_compartment_t* newcomp = tsk_null; + const tsk_list_item_t *item_const; + + if(!statehandler){ + TSK_DEBUG_ERROR("Invalid parameter"); + return 0; + } + + tsk_safeobj_lock(statehandler); + + item_const = tsk_list_find_item_by_pred(statehandler->compartments, pred_find_compartment_by_id, &id); + if(!item_const || !(result = item_const->data)){ + newcomp = tcomp_compartment_create(id, tcomp_params_getParameters(statehandler->sigcomp_parameters), statehandler->useOnlyACKedStates); + result = newcomp; + tsk_list_push_back_data(statehandler->compartments, ((void**) &newcomp)); + } + + tsk_safeobj_unlock(statehandler); + + return result; +} + +void tcomp_statehandler_deleteCompartment(tcomp_statehandler_t *statehandler, uint64_t id) +{ + tcomp_compartment_t *compartment; + const tsk_list_item_t *item_const; + + if(!statehandler){ + TSK_DEBUG_ERROR("Invalid parameter"); + return; + } + + tsk_safeobj_lock(statehandler); + + item_const = tsk_list_find_item_by_pred(statehandler->compartments, pred_find_compartment_by_id, &id); + if(item_const && (compartment = item_const->data)){ + TSK_DEBUG_INFO("SigComp - Delete compartment %lld", id); + tsk_list_remove_item_by_data(statehandler->compartments, compartment); + } + + tsk_safeobj_unlock(statehandler); +} + + +tsk_bool_t tcomp_statehandler_compartmentExist(tcomp_statehandler_t *statehandler, uint64_t id) +{ + tsk_bool_t exist; + + if(!statehandler){ + TSK_DEBUG_ERROR("Invalid parameter"); + return tsk_false; + } + + tsk_safeobj_lock(statehandler); + exist = (tsk_list_find_item_by_pred(statehandler->compartments, pred_find_compartment_by_id, &id) ? 1 : 0); + tsk_safeobj_unlock(statehandler); + + return exist; +} + + +uint32_t tcomp_statehandler_findState(tcomp_statehandler_t *statehandler, const tcomp_buffer_handle_t *partial_identifier, tcomp_state_t** lpState) +{ + uint32_t count = 0; + tsk_list_item_t *item; + + if(!statehandler){ + TSK_DEBUG_ERROR("Invalid parameter"); + return 0; + } + + tsk_safeobj_lock(statehandler); + + // + // Compartments + // + tsk_list_foreach(item, statehandler->compartments){ + tcomp_compartment_t *compartment = item->data; + count += tcomp_compartment_findState(compartment, partial_identifier, lpState); + } + + if(count){ + goto bail; + } + + // + // Dictionaries + // + tsk_list_foreach(item, statehandler->dictionaries){ + tcomp_dictionary_t *dictionary = item->data; + if(tcomp_buffer_startsWith(dictionary->identifier, partial_identifier)){ + *lpState = dictionary; + count++; + } + } +bail: + tsk_safeobj_unlock(statehandler); + + return count; +} + +void tcomp_statehandler_handleResult(tcomp_statehandler_t *statehandler, tcomp_result_t **lpResult) +{ + tcomp_compartment_t *lpCompartment; + uint32_t compartment_total_size; + uint8_t i; + + if(!statehandler){ + TSK_DEBUG_ERROR("Invalid parameter"); + return; + } + + /*== Do not lock --> all functions are thread-safe. */ + //tsk_safeobj_lock(statehandler); + + /* + * The compressor does not wish (or no longer wishes) to save state information? + */ + if((*lpResult)->ret_feedback && (*lpResult)->req_feedback->S){ + if(tcomp_statehandler_compartmentExist(statehandler, (*lpResult)->compartmentId)){ + tcomp_statehandler_deleteCompartment(statehandler, (*lpResult)->compartmentId); + } + return; + } + + /* + * Find corresponding compartment (only if !S) + */ + if((lpCompartment = tcomp_statehandler_getCompartment(statehandler, (*lpResult)->compartmentId))){ + compartment_total_size = lpCompartment->total_memory_size; + } + else{ + goto bail; + } + +//compartment_create_states: + /* + * Request state creation now we have the corresponding compartement. + */ + if(tcomp_result_getTempStatesToCreateSize(*lpResult)){ + uint8_t count; + /* Check compartment allocated size*/ + if(!compartment_total_size){ + goto compartment_free_states; + } + + count = tcomp_result_getTempStatesToCreateSize(*lpResult); + + // FIXME: lock + for (i = 0; i < count; i++) + { + tcomp_state_t **lpState = &((*lpResult)->statesToCreate[i]); + if(!lpState || !*lpState){ + continue; + } + + /* + * If the state creation request needs more state memory than the + * total state_memory_size for the compartment, the state handler + * deletes all but the first (state_memory_size - 64) bytes from the state_value. + */ + if(TCOMP_GET_STATE_SIZE(*lpState) > compartment_total_size){ + tsk_size_t oldSize, newSize; + tcomp_compartment_clearStates(lpCompartment); + oldSize = tcomp_buffer_getSize((*lpState)->value); + newSize = (compartment_total_size - 64); + tcomp_buffer_removeBuff((*lpState)->value, newSize, (oldSize-newSize)); + (*lpState)->length = newSize; + + tcomp_compartment_addState(lpCompartment, lpState); + } + + /* + * If the state creation request exceeds the state memory allocated + * to the compartment, sufficient items of state created by the same + * compartment are freed until enough memory is available to + * accommodate the new state. + */ + else{ + while(lpCompartment->total_memory_left < TCOMP_GET_STATE_SIZE(*lpState)){ + tcomp_compartment_freeStateByPriority(lpCompartment); + } + tcomp_compartment_addState(lpCompartment, lpState); + } + } + } + +compartment_free_states: + /* + * Request state free now we have the correponding comprtement + */ + if(tcomp_result_getTempStatesToFreeSize((const tcomp_result_t*)*lpResult)){ + tcomp_compartment_freeStates(lpCompartment, (*lpResult)->statesToFree, tcomp_result_getTempStatesToFreeSize((const tcomp_result_t*)*lpResult)); + } + +//compartment_remote_params: + /* + * Set remote -compressor- parameters. + */ + tcomp_compartment_setRemoteParams(lpCompartment, (*lpResult)->remote_parameters); + +//feedbacks: + /* + * Set both Returned and Requested feedbacks. + */ + + if(tcomp_buffer_getSize((*lpResult)->req_feedback->item)){ + tcomp_compartment_setReqFeedback(lpCompartment, (*lpResult)->req_feedback->item); + } + if(tcomp_buffer_getSize((*lpResult)->ret_feedback)){ + tcomp_compartment_setRetFeedback(lpCompartment, (*lpResult)->ret_feedback); + } + +bail: ; + //--tsk_safeobj_unlock(lpCompartment); + //--tsk_safeobj_unlock(statehandler); +} + +tsk_bool_t tcomp_statehandler_handleNack(tcomp_statehandler_t *statehandler, const tcomp_nackinfo_t * nackinfo) +{ + tcomp_buffer_handle_t* sha_id; + tsk_list_item_t *item; + tsk_bool_t found = tsk_false; + if(!statehandler){ + TSK_DEBUG_ERROR("Invalid parameter"); + return tsk_false; + } + + if(!(sha_id = tcomp_buffer_create_null())){ + TSK_DEBUG_ERROR("Failed to create buffer handle"); + return tsk_false; + } + + tcomp_buffer_referenceBuff(sha_id, ((tcomp_nackinfo_t*)nackinfo)->sha1, TSK_SHA1_DIGEST_SIZE); + + tsk_list_foreach(item, statehandler->compartments) + { + tcomp_compartment_t* lpCompartement = item->data; + if(tcomp_compartment_hasNack(lpCompartement, sha_id)) + { + // this compartment is responsible for this nack + switch(nackinfo->reasonCode) + { + case NACK_STATE_NOT_FOUND: + { + // Next commented because in this version remote state ids are never saved. + // Only the ghost has information on last partial state id to use --> reset the ghost + //SigCompState* lpState = NULL; + //lpCompartement->findState(&nack_info->details, &lpState); + //if(lpState) + //{ + // lpCompartement->freeState(lpState); + //} + tcomp_compartment_freeGhostState(lpCompartement); + } + break; + + default: + { + tcomp_compartment_freeGhostState(lpCompartement); + tcomp_compartment_clearStates(lpCompartement); + } + break; + } + TSK_DEBUG_INFO("Compartment has NACK :)"); + tcomp_buffer_print(sha_id); + found = tsk_true; + } + } + + if(!found) + { + TSK_DEBUG_ERROR("Compartments do not have NACK with id="); + tcomp_buffer_print(sha_id); + } + + TSK_OBJECT_SAFE_FREE(sha_id); + + return found; +} + +int tcomp_statehandler_addSipSdpDictionary(tcomp_statehandler_t *statehandler) +{ + if(!statehandler){ + TSK_DEBUG_ERROR("Invalid parameter"); + return -1; + } + + tsk_safeobj_lock(statehandler); + + if(!statehandler->hasSipSdpDictionary){ + tcomp_dictionary_t* sip_dict = tcomp_dicts_create_sip_dict(); + tsk_list_push_back_data(statehandler->dictionaries, ((void**) &sip_dict)); + statehandler->hasSipSdpDictionary = 1; + } + + tsk_safeobj_unlock(statehandler); + return 0; +} + +int tcomp_statehandler_addPresenceDictionary(tcomp_statehandler_t *statehandler) +{ + if(!statehandler){ + TSK_DEBUG_ERROR("NULL SigComp state handler."); + return -1; + } + + tsk_safeobj_lock(statehandler); + + if(!statehandler->hasPresenceDictionary){ + tcomp_dictionary_t* pres_dict = tcomp_dicts_create_presence_dict(); + tsk_list_push_back_data(statehandler->dictionaries, ((void**) &pres_dict)); + statehandler->hasPresenceDictionary = 1; + } + + tsk_safeobj_unlock(statehandler); + return 0; +} + + + + + + + +//======================================================== +// State hanlder object definition +// + +static tsk_object_t* tcomp_statehandler_ctor(tsk_object_t * self, va_list * app) +{ + tcomp_statehandler_t *statehandler = self; + if(statehandler){ + /* Initialize safeobject */ + tsk_safeobj_init(statehandler); + } + else{ + TSK_DEBUG_ERROR("Null SigComp state handler."); + } + + return self; +} + +static void* tcomp_statehandler_dtor(tsk_object_t *self) +{ + tcomp_statehandler_t *statehandler = self; + if(statehandler){ + /* Deinitialize safeobject */ + tsk_safeobj_deinit(statehandler); + + TSK_OBJECT_SAFE_FREE(statehandler->sigcomp_parameters); + + TSK_OBJECT_SAFE_FREE(statehandler->dictionaries); + TSK_OBJECT_SAFE_FREE(statehandler->compartments); + } + else{ + TSK_DEBUG_ERROR("Null SigComp state handler."); + } + + return self; +} + +static const tsk_object_def_t tsk_statehandler_def_s = +{ + sizeof(tcomp_statehandler_t), + tcomp_statehandler_ctor, + tcomp_statehandler_dtor, + tsk_null +}; +const tsk_object_def_t *tcomp_statehandler_def_t = &tsk_statehandler_def_s; diff --git a/tinySIGCOMP/src/tcomp_statehandler.h b/tinySIGCOMP/src/tcomp_statehandler.h new file mode 100644 index 0000000..23dd494 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_statehandler.h @@ -0,0 +1,84 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_statehandler.h + * @brief SigComp state handler. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#ifndef TCOMP_STATE_HANDLER_H +#define TCOMP_STATE_HANDLER_H + +#include "tinysigcomp_config.h" + +#include "tcomp_types.h" +#include "tcomp_params.h" +#include "tcomp_nackinfo.h" +#include "tcomp_result.h" +#include "tcomp_buffer.h" +#include "tcomp_compartment.h" +#include "tcomp_state.h" + +#include "tsk_safeobj.h" +#include "tsk_object.h" + +TCOMP_BEGIN_DECLS + +/**State handler. +*/ +typedef struct tcomp_statehandler_s +{ + TSK_DECLARE_OBJECT; + + tcomp_compartments_L_t *compartments; + tcomp_params_t *sigcomp_parameters; + + tcomp_dictionaries_L_t *dictionaries; + tsk_bool_t hasSipSdpDictionary; + tsk_bool_t hasPresenceDictionary; + tsk_bool_t useOnlyACKedStates; + + TSK_DECLARE_SAFEOBJ; +} +tcomp_statehandler_t; + +tcomp_statehandler_t* tcomp_statehandler_create(); + +tcomp_compartment_t *tcomp_statehandler_getCompartment(const tcomp_statehandler_t *statehandler, uint64_t id); +int tcomp_statehandler_setUseOnlyACKedStates(tcomp_statehandler_t* self, tsk_bool_t useOnlyACKedStates); +void tcomp_statehandler_deleteCompartment(tcomp_statehandler_t *statehandler, uint64_t id); +tsk_bool_t tcomp_statehandler_compartmentExist(tcomp_statehandler_t *statehandler, uint64_t id); +uint32_t tcomp_statehandler_findState(tcomp_statehandler_t *statehandler, const tcomp_buffer_handle_t *partial_identifier, tcomp_state_t** lpState); + +void tcomp_statehandler_handleResult(tcomp_statehandler_t *statehandler, tcomp_result_t **lpResult); +tsk_bool_t tcomp_statehandler_handleNack(tcomp_statehandler_t *statehandler, const tcomp_nackinfo_t *); + +int tcomp_statehandler_addSipSdpDictionary(tcomp_statehandler_t *statehandler); +int tcomp_statehandler_addPresenceDictionary(tcomp_statehandler_t *statehandler); + +TINYSIGCOMP_GEXTERN const tsk_object_def_t *tcomp_statehandler_def_t; + +TCOMP_END_DECLS + +#endif /* TCOMP_STATE_HANDLER_H */ diff --git a/tinySIGCOMP/src/tcomp_types.h b/tinySIGCOMP/src/tcomp_types.h new file mode 100644 index 0000000..0cb48c9 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_types.h @@ -0,0 +1,38 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +#ifndef TCOMP_TYPES_H +#define TCOMP_TYPES_H + +#include "tsk_list.h" + +TCOMP_BEGIN_DECLS + +typedef tsk_list_t tcomp_buffers_L_t; /**< List containing @ref tcomp_buffer_handle_t elements. */ +typedef tsk_list_t tcomp_states_L_t; /**< List containing @ref tcomp_state_t elements. */ +typedef tsk_list_t tcomp_dictionaries_L_t; /**< List containing @ref tcomp_dictionary_t elements. */ +typedef tsk_list_t tcomp_compartments_L_t; /** List containing @ref tcomp_compartment_t elements. */ +typedef tsk_list_t tcomp_stream_buffer_L_t; /** List containing @ref tcomp_stream_buffer_t elements. */ + +TCOMP_END_DECLS + +#endif /* TCOMP_TYPES_H */ diff --git a/tinySIGCOMP/src/tcomp_udvm.bytecopy.c b/tinySIGCOMP/src/tcomp_udvm.bytecopy.c new file mode 100644 index 0000000..246b25c --- /dev/null +++ b/tinySIGCOMP/src/tcomp_udvm.bytecopy.c @@ -0,0 +1,145 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_udvm.nack.c + * @brief SigComp UDVM machine (byte copying). + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_udvm.h" + +#include "tsk_debug.h" + + +#define TCOMP_UDVM_MEMORY_REGISTERS_PTR TCOMP_UDVM_GET_BUFFER_AT(UDVM_REGISTERS_START) + + +/**RFC3320-Setction_8.4. Byte copying +From UDVM to UDVM +*/ +tsk_bool_t tcomp_udvm_bytecopy_self(tcomp_udvm_t *udvm, uint32_t *destination, uint32_t source, uint32_t tsk_size_tocopy) +{ + uint32_t byte_copy_left, byte_copy_right; + uint8_t* destination_ptr; + + //if (*destination == TCOMP_UDVM_GET_SIZE() || source == TCOMP_UDVM_GET_SIZE()) + if (*destination >= TCOMP_UDVM_GET_SIZE() || source >= TCOMP_UDVM_GET_SIZE()) + { + /* SEGFAULT */ + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); + return tsk_false; + } + + /* + * The string of bytes is copied in ascending order of memory address, + * respecting the bounds set by byte_copy_left and byte_copy_right. + */ + byte_copy_left = TCOMP_UDVM_GET_2BYTES_VAL(TCOMP_UDVM_HEADER_BYTE_COPY_LEFT_INDEX); + byte_copy_right = TCOMP_UDVM_GET_2BYTES_VAL(TCOMP_UDVM_HEADER_BYTE_COPY_RIGHT_INDEX); + + // string of bytes is copied one byte at a time + while((tsk_size_tocopy--)) + { + if(!(destination_ptr = TCOMP_UDVM_GET_BUFFER_AT((*destination)++))){ + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); + return tsk_false; + } + *destination_ptr = *TCOMP_UDVM_GET_BUFFER_AT(source++); + *destination = (*destination == byte_copy_right)? byte_copy_left : *destination; + source = (source == byte_copy_right)? byte_copy_left : source; + } + + return tsk_true; +} + +/**RFC3320-Setction_8.4. Byte copying +From EXTERNAL to UDVM +*/ +tsk_bool_t tcomp_udvm_bytecopy_to(tcomp_udvm_t *udvm, uint32_t destination, const uint8_t* source, uint32_t tsk_size_tocopy) +{ + uint32_t byte_copy_left, byte_copy_right; + uint8_t* destination_ptr; + + if(destination == TCOMP_UDVM_GET_SIZE()) + { + /* SEGFAULT */ + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); + return tsk_false; + } + + /* + * The string of bytes is copied in ascending order of memory address, + * respecting the bounds set by byte_copy_left and byte_copy_right. + */ + byte_copy_left = TCOMP_UDVM_GET_2BYTES_VAL(TCOMP_UDVM_HEADER_BYTE_COPY_LEFT_INDEX); + byte_copy_right = TCOMP_UDVM_GET_2BYTES_VAL(TCOMP_UDVM_HEADER_BYTE_COPY_RIGHT_INDEX); + + // string of bytes is copied one byte at a time + while((tsk_size_tocopy--)) + { + if(!(destination_ptr = TCOMP_UDVM_GET_BUFFER_AT(destination++))){ + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); + return tsk_false; + } + *destination_ptr = *(source++); + destination = (destination == byte_copy_right)? byte_copy_left : destination; + } + + return tsk_true; +} + +/**RFC3320-Setction_8.4. Byte copying +From UDVM to EXTERNAL +*/ +tsk_bool_t tcomp_udvm_bytecopy_from(tcomp_udvm_t *udvm, uint8_t* destination, uint32_t source, uint32_t tsk_size_tocopy) +{ + uint32_t byte_copy_left, byte_copy_right; + uint8_t* source_ptr; + + if(source >= TCOMP_UDVM_GET_SIZE()){ + TSK_DEBUG_ERROR("SEGFAULT"); + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); + return tsk_false; + } + + /* + * The string of bytes is copied in ascending order of memory address, + * respecting the bounds set by byte_copy_left and byte_copy_right. + */ + byte_copy_left = TCOMP_UDVM_GET_2BYTES_VAL(TCOMP_UDVM_HEADER_BYTE_COPY_LEFT_INDEX); + byte_copy_right = TCOMP_UDVM_GET_2BYTES_VAL(TCOMP_UDVM_HEADER_BYTE_COPY_RIGHT_INDEX); + + + // string of bytes is copied one byte at a time + while((tsk_size_tocopy--)){ + if(!(source_ptr = TCOMP_UDVM_GET_BUFFER_AT(source++))){ + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); + return tsk_false; + } + *(destination++) = *source_ptr; + source = (source == byte_copy_right)? byte_copy_left : source; + } + + return tsk_true; +} diff --git a/tinySIGCOMP/src/tcomp_udvm.c b/tinySIGCOMP/src/tcomp_udvm.c new file mode 100644 index 0000000..6a7607f --- /dev/null +++ b/tinySIGCOMP/src/tcomp_udvm.c @@ -0,0 +1,557 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop +* Copyright (C) 2011-2013 Doubango Telecom <http://www.doubango.org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_udvm.c + * @brief SigComp UDVM machine. + */ +#include "tcomp_udvm.h" + +#include "tsk_memory.h" +#include "tsk_debug.h" + +#include <string.h> + +#define TCOMP_UDVM_HEADER_RESERVED_SIZE 22 + +tcomp_udvm_t* tcomp_udvm_create(tcomp_message_t* _sigCompMessage, tcomp_statehandler_t* stateHandler, tcomp_result_t* lpResult) +{ + tcomp_udvm_t *udvm; + if((udvm = tsk_object_new(tcomp_udvm_def_t))){ + /* RFC 3320 - 7. SigComp Message Format */ + udvm->sigCompMessage = tsk_object_ref(_sigCompMessage); + udvm->stateHandler = tsk_object_ref(stateHandler); + udvm->lpResult = tsk_object_ref(lpResult); + + udvm->isOK = tsk_true; + udvm->maximum_UDVM_cycles = 0; /* RFC 3320 subclause 8.6 */ + udvm->consumed_cycles = 0; + udvm->memory = tcomp_buffer_create_null(); + + /* Alloc UDVM memory */ + if(udvm->sigCompMessage->stream_based){ + /* + * If the transport is stream-based however, then a fixed-size input buffer is required to accommodate the stream, independently of the + * size of each SigComp message. So, for simplicity, the UDVM memory size is set to (decompression_memory_size / 2). + */ + + tcomp_buffer_allocBuff(udvm->memory, udvm->stateHandler->sigcomp_parameters->dmsValue/2); + } + else{ + /* + * If the transport is message-based then sufficient memory must be available + * to buffer the entire SigComp message before it is passed to the UDVM. So if the message is n bytes long, then the UDVM memory size is set + * to (decompression_memory_size - n), up to a maximum of 65536 bytes. + */ + tcomp_buffer_allocBuff(udvm->memory, (udvm->stateHandler->sigcomp_parameters->dmsValue-udvm->sigCompMessage->totalSize)); + } + + /* + * Has feedback with my state id? + */ + if(tcomp_buffer_getSize(udvm->sigCompMessage->ret_feedback_buffer)){ + tsk_size_t size = tcomp_buffer_getSize(udvm->sigCompMessage->ret_feedback_buffer); + tcomp_buffer_allocBuff(udvm->lpResult->ret_feedback, size); + memcpy(tcomp_buffer_getBuffer(udvm->lpResult->ret_feedback), tcomp_buffer_getBuffer(udvm->sigCompMessage->ret_feedback_buffer), size); + } + + /* + * Has state? + */ + if(tcomp_buffer_getSize(udvm->sigCompMessage->stateId)){ + /* Find the provided state */ + tcomp_state_t* lpState = NULL; + uint32_t match_count = tcomp_statehandler_findState(udvm->stateHandler, udvm->sigCompMessage->stateId, &lpState); + if( (match_count != 1 || !lpState) + || (lpState->minimum_access_length > tcomp_buffer_getSize(udvm->sigCompMessage->stateId)) + || ((tsk_size_t)(lpState->address + lpState->length) > TCOMP_UDVM_GET_SIZE()) ) + { + TSK_DEBUG_ERROR("NACK_STATE_NOT_FOUND for id = "); + tcomp_buffer_print(udvm->sigCompMessage->stateId); + tcomp_udvm_createNackInfo(udvm, NACK_STATE_NOT_FOUND, udvm->sigCompMessage->stateId, 0); + udvm->isOK = tsk_false; + goto bail; + } + /* + * Copy bytecodes to UDVM memory + */ + if( (tsk_size_t)(lpState->address + lpState->length) >= TCOMP_UDVM_GET_SIZE() ){ + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); + udvm->isOK = tsk_false; + goto bail; + } + memcpy( TCOMP_UDVM_GET_BUFFER_AT(lpState->address), + tcomp_buffer_getBuffer(lpState->value), + tcomp_buffer_getSize(lpState->value) ); + + //RFC 3320 - 7.2. Accessing Stored State (Useful values) + TCOMP_UDVM_SET_2BYTES_VAL(TCOMP_UDVM_HEADER_PARTIAL_STATE_ID_LENGTH_INDEX, tcomp_buffer_getSize(udvm->sigCompMessage->stateId)); + TCOMP_UDVM_SET_2BYTES_VAL(TCOMP_UDVM_HEADER_STATE_LENGTH_INDEX, tcomp_buffer_getSize(lpState->value)); + + udvm->executionPointer = lpState->instruction; + } + else // DON'T HAVE STATE + { + /* + * Copy bytecodes to UDVM memory + */ + tsk_size_t bytecodes_destination = udvm->sigCompMessage->bytecodes_destination; + if( (bytecodes_destination + tcomp_buffer_getSize(udvm->sigCompMessage->uploaded_UDVM_buffer)) >= TCOMP_UDVM_GET_SIZE() ){ + tcomp_udvm_createNackInfo2(udvm, NACK_BYTECODES_TOO_LARGE); + udvm->isOK = tsk_false; + goto bail; + } + memcpy( TCOMP_UDVM_GET_BUFFER_AT(bytecodes_destination), + tcomp_buffer_getBuffer(udvm->sigCompMessage->uploaded_UDVM_buffer), + tcomp_buffer_getSize(udvm->sigCompMessage->uploaded_UDVM_buffer)); + + // Set pointer indicating execution index + udvm->executionPointer = bytecodes_destination; + } + + /* RFC 3320-Section_8.6. UDVM Cycles + * + * the maximum number of UDVM cycles available for processing an n-byte SigComp message is given by the formula + * maximum_UDVM_cycles = (8 * n + 1000) * cycles_per_bit + */ + udvm->maximum_UDVM_cycles = ( (8 * udvm->sigCompMessage->header_size + 1000) * udvm->stateHandler->sigcomp_parameters->cpbValue ); + + // + // RFC 3320 - 7.2. Useful values + // + TCOMP_UDVM_SET_2BYTES_VAL(TCOMP_UDVM_HEADER_UDVM_MEMORY_SIZE_INDEX, TCOMP_UDVM_GET_SIZE()); + TCOMP_UDVM_SET_2BYTES_VAL(TCOMP_UDVM_HEADER_CYCLES_PER_BIT_INDEX, udvm->stateHandler->sigcomp_parameters->cpbValue); + TCOMP_UDVM_SET_2BYTES_VAL(TCOMP_UDVM_HEADER_SIGCOMP_VERSION_INDEX, udvm->stateHandler->sigcomp_parameters->SigComp_version); + memset(TCOMP_UDVM_GET_BUFFER_AT(TCOMP_UDVM_HEADER_RESERVED_INDEX), 0, TCOMP_UDVM_HEADER_RESERVED_SIZE); + } + else{ + TSK_DEBUG_ERROR("Failed to create new udvm machine."); + } + +bail: + return udvm; +} + +/**Executes the bytecode. +*/ +static tsk_bool_t tcomp_udvm_runByteCode(tcomp_udvm_t *udvm) +{ + uint32_t operand_1, operand_2, operand_3, operand_4, operand_5, operand_6, operand_7; + tsk_bool_t excution_failed = tsk_false, end_message = tsk_false; + if(!udvm->isOK) { + TSK_DEBUG_ERROR("Cannot run()/execute() invalid bytecode"); + return tsk_false; + } + + // LOOP - EXCUTE all bytecode + while( !excution_failed && !end_message ) + { + uint8_t udvm_instruction = * (TCOMP_UDVM_GET_BUFFER_AT(udvm->executionPointer)); + udvm->last_memory_address_of_instruction = udvm->executionPointer; + udvm->executionPointer++; /* Skip the 1-byte [INSTRUCTION]. */ + + switch(udvm_instruction) + { + case TCOMP_UDVM_INST__DECOMPRESSION_FAILURE: + { + TCOMP_UDVM_EXEC_INST__DECOMPRESSION_FAILURE(udvm); + excution_failed = tsk_true; + break; + } + + case TCOMP_UDVM_INST__AND: + { + operand_1 = tcomp_udvm_opget_reference_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__AND(udvm, operand_1, operand_2); + break; + } + + case TCOMP_UDVM_INST__OR: + { + operand_1 = tcomp_udvm_opget_reference_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__OR(udvm, operand_1, operand_2); + break; + } + + case TCOMP_UDVM_INST__NOT: + { + operand_1 = tcomp_udvm_opget_reference_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__NOT(udvm, operand_1); + break; + } + + case TCOMP_UDVM_INST__LSHIFT: + { + operand_1 = tcomp_udvm_opget_reference_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__LSHIFT(udvm, operand_1, operand_2); + break; + } + + case TCOMP_UDVM_INST__RSHIFT: + { + operand_1 = tcomp_udvm_opget_reference_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__RSHIFT(udvm, operand_1, operand_2); + break; + } + + case TCOMP_UDVM_INST__ADD: + { + operand_1 = tcomp_udvm_opget_reference_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__ADD(udvm, operand_1, operand_2); + break; + } + + case TCOMP_UDVM_INST__SUBTRACT: + { + operand_1 = tcomp_udvm_opget_reference_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__SUBTRACT(udvm, operand_1, operand_2); + break; + } + + case TCOMP_UDVM_INST__MULTIPLY: + { + operand_1 = tcomp_udvm_opget_reference_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__MULTIPLY(udvm, operand_1, operand_2); + break; + } + + case TCOMP_UDVM_INST__DIVIDE: + { + operand_1 = tcomp_udvm_opget_reference_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__DIVIDE(udvm, operand_1, operand_2); + break; + } + + case TCOMP_UDVM_INST__REMAINDER: + { + operand_1 = tcomp_udvm_opget_reference_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__REMAINDER(udvm, operand_1, operand_2); + break; + } + + case TCOMP_UDVM_INST__SORT_ASCENDING: + { + operand_1 = tcomp_udvm_opget_multitype_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + operand_3 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__SORT_ASCENDING(udvm, operand_1, operand_2, operand_3); + break; + } + + case TCOMP_UDVM_INST__SORT_DESCENDING: + { + operand_1 = tcomp_udvm_opget_multitype_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + operand_3 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__SORT_DESCENDING(udvm, operand_1, operand_2, operand_3); + break; + } + + case TCOMP_UDVM_INST__SHA_1: + { + operand_1 = tcomp_udvm_opget_multitype_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + operand_3 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__SHA_1(udvm, operand_1, operand_2, operand_3); + break; + } + + case TCOMP_UDVM_INST__LOAD: + { + operand_1 = tcomp_udvm_opget_multitype_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__LOAD(udvm, operand_1, operand_2); + break; + } + + case TCOMP_UDVM_INST__MULTILOAD: + { + operand_1 = tcomp_udvm_opget_multitype_param(udvm); + operand_2 = tcomp_udvm_opget_literal_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__MULTILOAD(udvm, operand_1, operand_2); + break; + } + + case TCOMP_UDVM_INST__PUSH: + { + excution_failed = !TCOMP_UDVM_EXEC_INST__PUSH2(udvm); + break; + } + + case TCOMP_UDVM_INST__POP: + { + excution_failed = !TCOMP_UDVM_EXEC_INST__POP2(udvm); + break; + } + + case TCOMP_UDVM_INST__COPY: + { + operand_1 = tcomp_udvm_opget_multitype_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + operand_3 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__COPY(udvm, operand_1, operand_2, operand_3); + break; + } + + case TCOMP_UDVM_INST__COPY_LITERAL: + { + operand_1 = tcomp_udvm_opget_multitype_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + operand_3 = tcomp_udvm_opget_reference_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__COPY_LITERAL(udvm, operand_1, operand_2, operand_3); + break; + } + + case TCOMP_UDVM_INST__COPY_OFFSET: + { + operand_1 = tcomp_udvm_opget_multitype_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + operand_3 = tcomp_udvm_opget_reference_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__COPY_OFFSET(udvm, operand_1, operand_2, operand_3); + break; + } + + case TCOMP_UDVM_INST__MEMSET: + { + operand_1 = tcomp_udvm_opget_multitype_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + operand_3 = tcomp_udvm_opget_multitype_param(udvm); + operand_4 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__MEMSET(udvm, operand_1, operand_2, operand_3, operand_4); + break; + } + + case TCOMP_UDVM_INST__JUMP: + { + excution_failed = !TCOMP_UDVM_EXEC_INST__JUMP2(udvm); + break; + } + + case TCOMP_UDVM_INST__COMPARE: + { + operand_1 = tcomp_udvm_opget_multitype_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + operand_3 = tcomp_udvm_opget_address_param(udvm, udvm->last_memory_address_of_instruction); + operand_4 = tcomp_udvm_opget_address_param(udvm, udvm->last_memory_address_of_instruction); + operand_5 = tcomp_udvm_opget_address_param(udvm, udvm->last_memory_address_of_instruction); + excution_failed = !TCOMP_UDVM_EXEC_INST__COMPARE(udvm, operand_1, operand_2, operand_3, operand_4, operand_5); + break; + } + + case TCOMP_UDVM_INST__CALL: + { + operand_1 = tcomp_udvm_opget_address_param(udvm, udvm->last_memory_address_of_instruction); + excution_failed = !TCOMP_UDVM_EXEC_INST__CALL(udvm, operand_1); + break; + } + + case TCOMP_UDVM_INST__RETURN: + { + excution_failed = !TCOMP_UDVM_EXEC_INST__RETURN(udvm); + break; + } + + case TCOMP_UDVM_INST__SWITCH: + { + operand_1 = tcomp_udvm_opget_literal_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__SWITCH(udvm, operand_1, operand_2); + break; + } + + case TCOMP_UDVM_INST__CRC: + { + operand_1 = tcomp_udvm_opget_multitype_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + operand_3 = tcomp_udvm_opget_multitype_param(udvm); + operand_4 = tcomp_udvm_opget_reference_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__CRC(udvm, operand_1, operand_2, operand_3, operand_4); + break; + } + + case TCOMP_UDVM_INST__INPUT_BYTES: + { + operand_1 = tcomp_udvm_opget_multitype_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + operand_3 = tcomp_udvm_opget_address_param(udvm, udvm->last_memory_address_of_instruction); + excution_failed = !TCOMP_UDVM_EXEC_INST__INPUT_BYTES(udvm, operand_1, operand_2, operand_3); + break; + } + + case TCOMP_UDVM_INST__INPUT_BITS: + { + operand_1 = tcomp_udvm_opget_multitype_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + operand_3 = tcomp_udvm_opget_address_param(udvm, udvm->last_memory_address_of_instruction); + excution_failed = !TCOMP_UDVM_EXEC_INST__INPUT_BITS(udvm, operand_1, operand_2, operand_3); + break; + } + + case TCOMP_UDVM_INST__INPUT_HUFFMAN: + { + operand_1 = tcomp_udvm_opget_multitype_param(udvm); + operand_2 = tcomp_udvm_opget_address_param(udvm, udvm->last_memory_address_of_instruction); + operand_3 = tcomp_udvm_opget_literal_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__INPUT_HUFFMAN(udvm, operand_1, operand_2, operand_3); + break; + } + + case TCOMP_UDVM_INST__STATE_ACCESS: + { + operand_1 = tcomp_udvm_opget_multitype_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + operand_3 = tcomp_udvm_opget_multitype_param(udvm); + operand_4 = tcomp_udvm_opget_multitype_param(udvm); + operand_5 = tcomp_udvm_opget_multitype_param(udvm); + operand_6 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__STATE_ACCESS(udvm, operand_1, operand_2, operand_3, operand_4, operand_5, operand_6); + break; + } + + case TCOMP_UDVM_INST__STATE_CREATE: + { + operand_1 = tcomp_udvm_opget_multitype_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + operand_3 = tcomp_udvm_opget_multitype_param(udvm); + operand_4 = tcomp_udvm_opget_multitype_param(udvm); + operand_5 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__STATE_CREATE(udvm, operand_1, operand_2, operand_3, operand_4, operand_5); + break; + } + + case TCOMP_UDVM_INST__STATE_FREE: + { + operand_1 = tcomp_udvm_opget_multitype_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__STATE_FREE(udvm, operand_1, operand_2); + break; + } + + case TCOMP_UDVM_INST__OUTPUT: + { + operand_1 = tcomp_udvm_opget_multitype_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__OUTPUT(udvm, operand_1, operand_2); + break; + } + + case TCOMP_UDVM_INST__END_MESSAGE: + { + operand_1 = tcomp_udvm_opget_multitype_param(udvm); + operand_2 = tcomp_udvm_opget_multitype_param(udvm); + operand_3 = tcomp_udvm_opget_multitype_param(udvm); + operand_4 = tcomp_udvm_opget_multitype_param(udvm); + operand_5 = tcomp_udvm_opget_multitype_param(udvm); + operand_6 = tcomp_udvm_opget_multitype_param(udvm); + operand_7 = tcomp_udvm_opget_multitype_param(udvm); + excution_failed = !TCOMP_UDVM_EXEC_INST__END_MESSAGE(udvm, operand_1, operand_2, operand_3, operand_4, operand_5, operand_6, operand_7); + end_message = 1; + break; + } + + default: + tcomp_udvm_createNackInfo2(udvm, NACK_INVALID_OPCODE); + goto bail; + } + + if(excution_failed){ + TSK_DEBUG_ERROR("Execution failed for instruction = %s", TCOMP_INST_DESCRIPTIONS[udvm_instruction].desc); + } + //TCOMP_UDVM_DEBUG_PRINT(200); + } + +bail: + udvm->lpResult->consumed_cycles = udvm->consumed_cycles; + return (!excution_failed); +} + +/**Decompress the bytecode. +*/ +tsk_bool_t tcomp_udvm_decompress(tcomp_udvm_t *udvm) +{ + return tcomp_udvm_runByteCode(udvm); +} + + + + + + + + + + + + + + + + + + + + +//======================================================== +// UDVM machine definition +// +static tsk_object_t* tcomp_udvm_ctor(tsk_object_t * self, va_list * app) +{ + tcomp_udvm_t *udvm = self; + if(udvm){ + + } + return self; +} + +static tsk_object_t* tcomp_udvm_dtor(tsk_object_t *self) +{ + tcomp_udvm_t *udvm = self; + if(udvm){ + TSK_OBJECT_SAFE_FREE(udvm->memory); + TSK_OBJECT_SAFE_FREE(udvm->sigCompMessage); + TSK_OBJECT_SAFE_FREE(udvm->stateHandler); + TSK_OBJECT_SAFE_FREE(udvm->lpResult); + + TSK_FREE(udvm->tmp_buff.ptr); + } + else{ + TSK_DEBUG_ERROR("Null udvm machine."); + } + + return self; +} + +static const tsk_object_def_t tcomp_udvm_def_s = +{ + sizeof(tcomp_udvm_t), + tcomp_udvm_ctor, + tcomp_udvm_dtor, + tsk_null +}; +const tsk_object_def_t *tcomp_udvm_def_t = &tcomp_udvm_def_s; diff --git a/tinySIGCOMP/src/tcomp_udvm.h b/tinySIGCOMP/src/tcomp_udvm.h new file mode 100644 index 0000000..cea9616 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_udvm.h @@ -0,0 +1,168 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_udvm.h + * @brief The machine architecture described in this document. The UDVM is used to decompress SigComp messages. + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#ifndef TCOMP_UDVM_H +#define TCOMP_UDVM_H + +#include "tinysigcomp_config.h" + +#include "tcomp_message.h" +#include "tcomp_result.h" +#include "tcomp_headers_index.h" +#include "tcomp_nack_codes.h" +#include "tcomp_statehandler.h" +#include "tcomp_headers_index.h" +#include "tcomp_instructions.h" + +#include "tsk_object.h" + +#include "tsk_binaryutils.h" + +TCOMP_BEGIN_DECLS + +#define TCOMP_UDVM_SET_2BYTES_VAL(position, value) TSK_BINARY_SET_2BYTES(tcomp_buffer_getBufferAtPos(udvm->memory, position), value) +#define TCOMP_UDVM_GET_2BYTES_VAL(position) TSK_BINARY_GET_2BYTES(tcomp_buffer_getBufferAtPos(udvm->memory, position)) + +#if defined(DEBUG) || defined(_DEBUG) +# define TCOMP_UDVM_DEBUG_PRINT(size) tcomp_buffer_nprint(udvm->memory, size) +#else +# define TCOMP_UDVM_DEBUG_PRINT(size) ((void)size) +#endif + +#define TCOMP_UDVM_GET_SIZE() tcomp_buffer_getSize(udvm->memory) +#define TCOMP_UDVM_GET_BUFFER() tcomp_buffer_getBuffer(udvm->memory) +#define TCOMP_UDVM_GET_BUFFER_AT(position) tcomp_buffer_getBufferAtPos(udvm->memory, position) + +typedef struct tcomp_udvm_s +{ + TSK_DECLARE_OBJECT; + + unsigned isOK:1; + tcomp_message_t *sigCompMessage; + tcomp_statehandler_t *stateHandler; + tcomp_result_t *lpResult; + + uint64_t maximum_UDVM_cycles; // RFC3320-Section_8.6 + uint64_t consumed_cycles; + + tcomp_buffer_handle_t *memory; + //header_udvm_memory memoryHeader; // RFC3320-Section_7.2 - // Default constructor will initial values (sip default) + + uint32_t executionPointer; + uint32_t last_memory_address_of_instruction; + + struct{ + void* ptr; + tsk_size_t size; + } tmp_buff; +} +tcomp_udvm_t; + +tcomp_udvm_t* tcomp_udvm_create(tcomp_message_t* _sigCompMessage,tcomp_statehandler_t* stateHandler, tcomp_result_t* lpResult); + +tsk_bool_t tcomp_udvm_decompress(tcomp_udvm_t *udvm); + +/* +* Operands +*/ +uint32_t tcomp_udvm_opget_literal_param(tcomp_udvm_t *udvm); +uint32_t tcomp_udvm_opget_reference_param(tcomp_udvm_t *udvm); +uint32_t tcomp_udvm_opget_multitype_param(tcomp_udvm_t *udvm); +uint32_t tcomp_udvm_opget_address_param(tcomp_udvm_t *udvm, uint32_t memory_address_of_instruction); + +/* +* ByteCopy +*/ +tsk_bool_t tcomp_udvm_bytecopy_self(tcomp_udvm_t *udvm, uint32_t *destination, uint32_t source, uint32_t tsk_size_tocopy); +tsk_bool_t tcomp_udvm_bytecopy_to(tcomp_udvm_t *udvm, uint32_t destination, const uint8_t* source, uint32_t tsk_size_tocopy); +tsk_bool_t tcomp_udvm_bytecopy_from(tcomp_udvm_t *udvm, uint8_t* destination, uint32_t source, uint32_t tsk_size_tocopy); + +/* +* State Management +*/ +int tcomp_udvm_byteCopy_TempStates(tcomp_udvm_t *udvm); +int tcomp_udvm_createTempState(tcomp_udvm_t *udvm, uint32_t state_length, uint32_t state_address, uint32_t state_instruction, + uint32_t minimum_access_length, uint32_t state_retention_priority, int end_msg); + +/* +* Nack creation +*/ +int tcomp_udvm_createNackInfo(tcomp_udvm_t *udvm, uint8_t reasonCode, tcomp_buffer_handle_t* lpDetails, int16_t memory_address_of_instruction); +#define tcomp_udvm_createNackInfo2(udvm, reasonCode) tcomp_udvm_createNackInfo(udvm, reasonCode, 0, -1) +#define tcomp_udvm_createNackInfo3(udvm, reasonCode, lpDetails) tcomp_udvm_createNackInfo(udvm, reasonCode, lpDetails, -1) + +/* +* Instructions +*/ +tsk_bool_t TCOMP_UDVM_EXEC_INST__DECOMPRESSION_FAILURE(tcomp_udvm_t *udvm); +tsk_bool_t TCOMP_UDVM_EXEC_INST__AND(tcomp_udvm_t *udvm, uint32_t operand_1, uint32_t operand_2); +tsk_bool_t TCOMP_UDVM_EXEC_INST__OR(tcomp_udvm_t *udvm, uint32_t operand_1, uint32_t operand_2); +tsk_bool_t TCOMP_UDVM_EXEC_INST__NOT(tcomp_udvm_t *udvm, uint32_t operand_1); +tsk_bool_t TCOMP_UDVM_EXEC_INST__LSHIFT(tcomp_udvm_t *udvm, uint32_t operand_1, uint32_t operand_2); +tsk_bool_t TCOMP_UDVM_EXEC_INST__RSHIFT(tcomp_udvm_t *udvm, uint32_t operand_1, uint32_t operand_2); +tsk_bool_t TCOMP_UDVM_EXEC_INST__ADD(tcomp_udvm_t *udvm, uint32_t operand_1, uint32_t operand_2); +tsk_bool_t TCOMP_UDVM_EXEC_INST__SUBTRACT(tcomp_udvm_t *udvm, uint32_t operand_1, uint32_t operand_2); +tsk_bool_t TCOMP_UDVM_EXEC_INST__MULTIPLY(tcomp_udvm_t *udvm, uint32_t operand_1, uint32_t operand_2); +tsk_bool_t TCOMP_UDVM_EXEC_INST__DIVIDE(tcomp_udvm_t *udvm, uint32_t operand_1, uint32_t operand_2); +tsk_bool_t TCOMP_UDVM_EXEC_INST__REMAINDER(tcomp_udvm_t *udvm, uint32_t operand_1, uint32_t operand_2); +tsk_bool_t TCOMP_UDVM_EXEC_INST__SORT_ASCENDING(tcomp_udvm_t *udvm, uint32_t start, uint32_t n, uint32_t k); +tsk_bool_t TCOMP_UDVM_EXEC_INST__SORT_DESCENDING(tcomp_udvm_t *udvm, uint32_t start, uint32_t n, uint32_t k); +tsk_bool_t TCOMP_UDVM_EXEC_INST__SHA_1(tcomp_udvm_t *udvm, uint32_t position, uint32_t length, uint32_t destination); +tsk_bool_t TCOMP_UDVM_EXEC_INST__LOAD(tcomp_udvm_t *udvm, uint32_t address, uint32_t value); +tsk_bool_t TCOMP_UDVM_EXEC_INST__MULTILOAD(tcomp_udvm_t *udvm, uint32_t address, uint32_t n); +tsk_bool_t TCOMP_UDVM_EXEC_INST__PUSH(tcomp_udvm_t *udvm, int16_t value); +#define TCOMP_UDVM_EXEC_INST__PUSH2(udvm) TCOMP_UDVM_EXEC_INST__PUSH(udvm, -1) +tsk_bool_t TCOMP_UDVM_EXEC_INST__POP(tcomp_udvm_t *udvm, uint32_t* value); +#define TCOMP_UDVM_EXEC_INST__POP2(udvm) TCOMP_UDVM_EXEC_INST__POP(udvm, 0) +tsk_bool_t TCOMP_UDVM_EXEC_INST__COPY(tcomp_udvm_t *udvm, uint32_t position, uint32_t length, uint32_t destination); +tsk_bool_t TCOMP_UDVM_EXEC_INST__COPY_LITERAL(tcomp_udvm_t *udvm, uint32_t position, uint32_t length, uint32_t destination); +tsk_bool_t TCOMP_UDVM_EXEC_INST__COPY_OFFSET(tcomp_udvm_t *udvm, uint32_t offset, uint32_t length, uint32_t destination); +tsk_bool_t TCOMP_UDVM_EXEC_INST__MEMSET(tcomp_udvm_t *udvm, uint32_t address, uint32_t length, uint32_t start_value, uint32_t offset); +tsk_bool_t TCOMP_UDVM_EXEC_INST__JUMP(tcomp_udvm_t *udvm, int16_t address); +#define TCOMP_UDVM_EXEC_INST__JUMP2(udvm) TCOMP_UDVM_EXEC_INST__JUMP(udvm, -1) +tsk_bool_t TCOMP_UDVM_EXEC_INST__COMPARE(tcomp_udvm_t *udvm, uint32_t value_1, uint32_t value_2, uint32_t address_1, uint32_t address_2, uint32_t address_3); +tsk_bool_t TCOMP_UDVM_EXEC_INST__CALL(tcomp_udvm_t *udvm, uint32_t address); +tsk_bool_t TCOMP_UDVM_EXEC_INST__RETURN(tcomp_udvm_t *udvm); +tsk_bool_t TCOMP_UDVM_EXEC_INST__SWITCH(tcomp_udvm_t *udvm, uint32_t n, uint32_t j); +tsk_bool_t TCOMP_UDVM_EXEC_INST__CRC(tcomp_udvm_t *udvm, uint32_t value, uint32_t position, uint32_t length, uint32_t address); +tsk_bool_t TCOMP_UDVM_EXEC_INST__INPUT_BYTES(tcomp_udvm_t *udvm, uint32_t length, uint32_t destination, uint32_t address); +tsk_bool_t TCOMP_UDVM_EXEC_INST__INPUT_BITS(tcomp_udvm_t *udvm, uint32_t length, uint32_t destination, uint32_t address); +tsk_bool_t TCOMP_UDVM_EXEC_INST__INPUT_HUFFMAN(tcomp_udvm_t *udvm, uint32_t destination, uint32_t address, uint32_t n); +tsk_bool_t TCOMP_UDVM_EXEC_INST__STATE_ACCESS(tcomp_udvm_t *udvm, uint32_t partial_identifier_start, uint32_t partial_identifier_length, uint32_t state_begin, uint32_t state_length, uint32_t state_address, uint32_t state_instruction); +tsk_bool_t TCOMP_UDVM_EXEC_INST__STATE_CREATE(tcomp_udvm_t *udvm, uint32_t state_length, uint32_t state_address, uint32_t state_instruction, uint32_t minimum_access_length, uint32_t state_retention_priority); +tsk_bool_t TCOMP_UDVM_EXEC_INST__STATE_FREE(tcomp_udvm_t *udvm, uint32_t partial_identifier_start, uint32_t partial_identifier_length); +tsk_bool_t TCOMP_UDVM_EXEC_INST__OUTPUT(tcomp_udvm_t *udvm, uint32_t output_start, uint32_t output_length); +tsk_bool_t TCOMP_UDVM_EXEC_INST__END_MESSAGE(tcomp_udvm_t *udvm, uint32_t requested_feedback_location, uint32_t returned_parameters_location, uint32_t state_length, uint32_t state_address, uint32_t state_instruction, uint32_t minimum_access_length, uint32_t state_retention_priority); + + +TINYSIGCOMP_GEXTERN const tsk_object_def_t *tcomp_udvm_def_t; + +TCOMP_END_DECLS + +#endif /* TCOMP_UDVM_H */ diff --git a/tinySIGCOMP/src/tcomp_udvm.instructions.c b/tinySIGCOMP/src/tcomp_udvm.instructions.c new file mode 100644 index 0000000..64b20b5 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_udvm.instructions.c @@ -0,0 +1,2010 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_udvm.instructions.c + * @brief SigComp UDVM machine (Instructions). + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_udvm.h" + +#include "tsk_memory.h" +#include "tsk_debug.h" +#include "tsk_ppfcs16.h" + +#include <string.h> /* memcpy */ +#include <stdlib.h> /* qsort */ +#include <math.h> /* ceil, log ... */ + +/* +* IMPORTANT: MSBs are stored before LSBs in the UDVM memory --> BIG ENDIAN +*/ + +#define F_BIT_MSB_TO_LSB 0 +#define F_BIT_LSB_TO_MSB 1 +#define H_BIT_MSB_TO_LSB F_BIT_MSB_TO_LSB +#define H_BIT_LSB_TO_MSB F_BIT_LSB_TO_MSB + +#define CEILLINGLOG2(x) ceil( (log((double)x)/log(2.0)) ) + +/* +* Consume cycles +*/ +#define CONSUME_CYCLES(cycles) \ + udvm->consumed_cycles += (uint64_t)(cycles); \ + if( udvm->consumed_cycles > udvm->maximum_UDVM_cycles ) \ + { \ + TSK_DEBUG_ERROR("%s (%llu > %llu)", TCOMP_NACK_DESCRIPTIONS[NACK_CYCLES_EXHAUSTED].desc, udvm->consumed_cycles, udvm->maximum_UDVM_cycles); \ + tcomp_udvm_createNackInfo2(udvm, NACK_CYCLES_EXHAUSTED); \ + return tsk_false; \ + } + +#define SET_2BYTES_VAL(position, value) \ + if(((position) + 1) >= TCOMP_UDVM_GET_SIZE()) \ + { \ + TSK_DEBUG_ERROR("%s (%u > %u)", TCOMP_NACK_DESCRIPTIONS[NACK_SEGFAULT].desc, ((position) + 1), TCOMP_UDVM_GET_SIZE()); \ + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); \ + return tsk_false; \ + }\ + TCOMP_UDVM_SET_2BYTES_VAL(position, value);\ + +#define GET_2BYTES_VAL(position, ret_val) \ + if(((position) + 1) >= TCOMP_UDVM_GET_SIZE()) \ + { \ + TSK_DEBUG_ERROR("%s (%u > %u)", TCOMP_NACK_DESCRIPTIONS[NACK_SEGFAULT].desc, ((position) + 1), TCOMP_UDVM_GET_SIZE()); \ + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); \ + return tsk_false; \ + }\ + ret_val = TCOMP_UDVM_GET_2BYTES_VAL((position)); + + +/** + This structure is used to keep index-value pairs after sorting. +*/ +typedef struct IndexValuePair_s +{ + uint16_t index; + uint16_t value; +} +IndexValuePair_t; + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// @brief Predicate to sort integers in ascending order. +/// +/// @param [in,out] a First integer. +/// @param [in,out] b Second integer. +/// +/// @retval Zero if @a a == @a b; negative if @a a < @a b and positive otherwise.. +//////////////////////////////////////////////////////////////////////////////////////////////////// + +static int SortAscendingPredicate(const void *a, const void *b) +{ + const IndexValuePair_t *el1 = a; + const IndexValuePair_t *el2 = b; + + /* If values are equal the original ordering of the integers must be preserved + * ==> We cannot use normal comparaison because the ANSI C implementation of qsort could swap values even if they are equal. + */ + return (el2->value == el1->value) ? (el1->index - el2->index) : (el1->value - el2->value); +} + +/** +* Sort Descending predicate. +*/ + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// @brief Predicate to sort integers in descending order. +/// @param [in,out] a First integer. +/// @param [in,out] b Second integer. +/// +/// @retval Zero if @a a == @a b; negative if @a a > @a b and positive otherwise. +//////////////////////////////////////////////////////////////////////////////////////////////////// +static int SortDescendingPredicate(const void *a, const void *b) +{ + const IndexValuePair_t *el1 = a; + const IndexValuePair_t *el2 = b; + + /* If values are equal the original ordering of the integers must be preserved. + * ==> We cannot use normal comparaison because the ANSI C implementation of qsort could swap values even if they are equal. + */ + return (el2->value == el1->value) ? (el1->index - el2->index) : (el2->value - el1->value); +}; + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief DECOMPRESSION-FAILURE +/// Reference: RFC3320 Section 9.4.1 +/// This instruction triggers a manual decompression failure. This is useful if the UDVM bytecode discovers that it +/// cannot successfully decompress the message (e.g., by using the CRC instruction). + + +/// @param [in,out] udvm The udvm state machine entity. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__DECOMPRESSION_FAILURE(tcomp_udvm_t *udvm) +{ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_USER_REQUESTED].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_USER_REQUESTED); + return tsk_false; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief AND ($operand_1, %operand_2) +/// Reference: RFC3320 Section 9.1.1 +/// Formula: [operand_1 := operand_1 & operand_2]. + +/// @param [in,out] udvm The udvm state machine entity. +/// @param operand_1 2-byte value encoded by the operand. After the operation is complete, the 2-byte word at the memory address specified by +/// this operand is overwritten with the result. +/// @param operand_2 The second operand. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// + +tsk_bool_t TCOMP_UDVM_EXEC_INST__AND(tcomp_udvm_t *udvm, uint32_t operand_1, uint32_t operand_2) +{ + uint16_t _2bytes; + + CONSUME_CYCLES(1); + + GET_2BYTES_VAL(operand_1, _2bytes); + SET_2BYTES_VAL( operand_1, (_2bytes & operand_2) ); + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief OR ($operand_1, %operand_2) +/// Reference: RFC3320 Section 9.1.1 +/// Formula: [operand_1 := operand_1 | operand_2]. + +/// @param [in,out] udvm The udvm state machine entity. +/// @param operand_1 2-byte value encoded by the operand. After the operation is complete, the 2-byte word at the memory address specified by +/// this operand is overwritten with the result. +/// @param operand_2 The second operand. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// + +tsk_bool_t TCOMP_UDVM_EXEC_INST__OR(tcomp_udvm_t *udvm, uint32_t operand_1, uint32_t operand_2) +{ + uint16_t _2bytes; + + CONSUME_CYCLES(1); + + GET_2BYTES_VAL(operand_1, _2bytes); + SET_2BYTES_VAL( operand_1, (_2bytes | operand_2) ); + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>NOT ($operand_1)</i><br><br> +/// Reference: RFC3320 Section 9.1.1<br> +/// Formula: [operand_1 := ~operand_1]. <br> + +/// @param [in,out] udvm The udvm state machine entity. +/// @param operand_1 2-byte value encoded by the operand. After the operation is complete, the 2-byte word at the memory address specified by +/// this operand is overwritten with the result. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// + +tsk_bool_t TCOMP_UDVM_EXEC_INST__NOT(tcomp_udvm_t *udvm, uint32_t operand_1) +{ + uint16_t _2bytes; + + CONSUME_CYCLES(1); + + GET_2BYTES_VAL(operand_1, _2bytes); + SET_2BYTES_VAL( operand_1, ~( _2bytes ) ); + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>LSHIFT ($operand_1, %operand_2)</i><br><br> +/// Reference: RFC3320 Section 9.1.1<br> +/// Formula: [LSHIFT (m, n) := m * 2^n (modulo 2^16)]. <br> + +/// @param [in,out] udvm The udvm state machine entity. +/// @param operand_1 2-byte value encoded by the operand. After the operation is complete, the 2-byte word at the memory address specified by +/// this operand is overwritten with the result. +/// @param operand_2 2-byte value encoded by the operand. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// + +tsk_bool_t TCOMP_UDVM_EXEC_INST__LSHIFT(tcomp_udvm_t *udvm, uint32_t operand_1, uint32_t operand_2) +{ + uint16_t _2bytes; + + CONSUME_CYCLES(1); + + // (m * 2^n) == (m<<n) + // (2^16) === 65536 + + GET_2BYTES_VAL(operand_1, _2bytes); + SET_2BYTES_VAL( operand_1, (_2bytes << operand_2) ); + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>RSHIFT ($operand_1, %operand_2)</i><br><br> +/// Reference: RFC3320 Section 9.1.1<br> +/// Formula: [RSHIFT (m, n) := floor(m / 2^n)]. <br> + +/// @param [in,out] udvm The udvm state machine entity. +/// @param operand_1 2-byte value encoded by the operand. After the operation is complete, the 2-byte word at the memory address specified by +// this operand is overwritten with the result. +/// @param operand_2 2-byte value encoded by the operand. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// + +tsk_bool_t TCOMP_UDVM_EXEC_INST__RSHIFT(tcomp_udvm_t *udvm, uint32_t operand_1, uint32_t operand_2) +{ + uint16_t _2bytes; + + CONSUME_CYCLES(1); + + // floor(m / 2^n) == (m>>n) + GET_2BYTES_VAL(operand_1, _2bytes); + SET_2BYTES_VAL(operand_1, (_2bytes >> operand_2) ); + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>ADD ($operand_1, %operand_2)</i><br><br> +/// Reference: RFC3320 Section 9.1.2<br> +/// Formula: [ADD (m, n) := m + n (modulo 2^16)]<br> +/// +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param operand_1 2-byte value encoded by the operand. After the operation is complete, the 2-byte word at the memory address specified by +/// this operand is overwritten with the result. +/// @param operand_2 2-byte value encoded by the operand. +/// +/// @retval True if succeed, otherwise return false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__ADD(tcomp_udvm_t *udvm, uint32_t operand_1, uint32_t operand_2) +{ + uint16_t _2bytes; + + CONSUME_CYCLES(1); + + GET_2BYTES_VAL(operand_1, _2bytes); + SET_2BYTES_VAL(operand_1, (_2bytes + operand_2) ); + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>SUBTRACT ($operand_1, %operand_2)</i><br><br> +/// Reference: RFC3320 Section 9.1.2<br> +/// Formula: [SUBTRACT (m, n) := m - n (modulo 2^16)]<br> +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param operand_1 2-byte value encoded by the operand. After the operation is complete, the 2-byte word at the memory address specified by +/// this operand is overwritten with the result. +/// @param operand_2 2-byte value encoded by the operand. +/// +/// @retval 1 if succeed, otherwise returns 0. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__SUBTRACT(tcomp_udvm_t *udvm, uint32_t operand_1, uint32_t operand_2) +{ + uint16_t _2bytes; + + CONSUME_CYCLES(1); + + GET_2BYTES_VAL(operand_1, _2bytes); + SET_2BYTES_VAL(operand_1, (_2bytes - operand_2) ); + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>MULTIPLY ($operand_1, %operand_2)</i><br><br> +/// Reference: RFC3320 Section 9.1.2<br> +/// Formula: [MULTIPLY (m, n) := m * n (modulo 2^16)]<br> +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param operand_1 2-byte value encoded by the operand. After the operation is complete, the 2-byte word at the memory address specified by +/// this operand is overwritten with the result. +/// @param operand_2 2-byte value encoded by the operand. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__MULTIPLY(tcomp_udvm_t *udvm, uint32_t operand_1, uint32_t operand_2) +{ + uint16_t _2bytes; + + CONSUME_CYCLES(1); + + GET_2BYTES_VAL(operand_1, _2bytes); + SET_2BYTES_VAL(operand_1, (_2bytes * operand_2) ); + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>DIVIDE ($operand_1, %operand_2)</i><br><br> +/// Reference: RFC3320 Section 9.1.2<br> +/// Formula: [DIVIDE (m, n) := floor(m / n)]<br> +/// +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param operand_1 2-byte value encoded by the operand. After the operation is complete, the 2-byte word at the memory address specified by +/// this operand is overwritten with the result. +/// @param operand_2 2-byte value encoded by the operand. Decompression failure occurs if this operand is zero. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__DIVIDE(tcomp_udvm_t *udvm, uint32_t operand_1, uint32_t operand_2) +{ + uint16_t _2bytes; + + CONSUME_CYCLES(1); + + if(!operand_2){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_DIV_BY_ZERO].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_DIV_BY_ZERO); + return tsk_false; + } + + GET_2BYTES_VAL(operand_1, _2bytes); + SET_2BYTES_VAL(operand_1, (_2bytes / operand_2) ); + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>REMAINDER ($operand_1, %operand_2)</i><br><br> +/// Reference: RFC3320 Section 9.1.2<br> +/// Formula: [REMAINDER (m, n) := m - n * floor(m / n)]<br> +/// +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param operand_1 2-byte value encoded by the operand. After the operation is complete, the 2-byte word at the memory address specified by +/// this operand is overwritten with the result. +/// @param operand_2 2-byte value encoded by the operand. Decompression failure occurs if this operand is zero. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__REMAINDER(tcomp_udvm_t *udvm, uint32_t operand_1, uint32_t operand_2) +{ + uint16_t _2bytes; + CONSUME_CYCLES(1); + + if(!operand_2){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_DIV_BY_ZERO].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_DIV_BY_ZERO); + return tsk_false; + } + + GET_2BYTES_VAL(operand_1, _2bytes); + SET_2BYTES_VAL(operand_1, (_2bytes % operand_2) ); + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>SORT-ASCENDING (%start, %n, %k)</i><br><br> +/// Reference: RFC3320 Section 9.1.3<br> +/// +/// This instruction sort lists of 2-byte words in ascending order. +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param start The starting memory address of the block of data to be sorted. +/// @param n Number of lists. +/// @param k Lists length (2-byte words). +/// +/// @retval True if succeed, otherwise return false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__SORT_ASCENDING(tcomp_udvm_t *udvm, uint32_t start, uint32_t n, uint32_t k) +{ + tsk_bool_t segfault = tsk_false; + uint16_t* list_temp = tsk_null; + IndexValuePair_t *list1_values = tsk_null; + uint32_t list_index, list_el; + uint32_t j, pos; + + CONSUME_CYCLES(( 1 + k *(CEILLINGLOG2(k) + n) )); /* 1 + k * (ceiling(log2(k)) + n) */ + + if(TCOMP_UDVM_GET_SIZE() <= (tsk_size_t)(start+(n*k*2)) ){ + segfault = tsk_true; + goto __SEGFAULT; + }; + + // + // Create FirstList with key-value pairs + // + list1_values = (IndexValuePair_t*)tsk_calloc(k, sizeof(IndexValuePair_t)); + if(!list1_values) { segfault = tsk_true; goto __SEGFAULT; }; + for(j=0, pos=0; pos<k; j+=2,pos++){ + list1_values[pos].index = pos; + GET_2BYTES_VAL((start+j), list1_values[pos].value); + } + + /* + * Sort Fisrt List Values + */ + qsort(list1_values, k, sizeof(IndexValuePair_t), SortAscendingPredicate); + + /* Sort all lists */ + list_temp = tsk_calloc(k, sizeof(uint32_t)); + if(!list1_values) { segfault = tsk_true; goto __SEGFAULT; }; + for(list_index = 0; list_index < n; list_index++){ + uint16_t* list_start = (uint16_t*)TCOMP_UDVM_GET_BUFFER_AT( start + (list_index*k*2) ); + memcpy(list_temp, list_start, k*2); + for(list_el=0; list_el<k; list_el++){ + list_start[(list_el)] = list_temp[ list1_values[list_el].index ]; + } + } + +__SEGFAULT: + TSK_FREE(list_temp); + TSK_FREE(list1_values); + + if(segfault) + { + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_SEGFAULT].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); + return tsk_false; + } + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>SORT-DESCENDING (%start, %n, %k)</i><br><br> +/// Reference: RFC3320 Section 9.1.3<br> +/// +/// This instruction sort lists of 2-byte words in descending order. +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param start The starting memory address of the block of data to be sorted. +/// @param n Number of lists. +/// @param k Lists length (2-byte words). +/// +/// @retval True if succeed, otherwise return false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__SORT_DESCENDING(tcomp_udvm_t *udvm, uint32_t start, uint32_t n, uint32_t k) +{ + tsk_bool_t segfault = tsk_false; + uint16_t* list_temp = tsk_null; + IndexValuePair_t *list1_values = tsk_null; + uint32_t list_index, list_el; + uint32_t j, pos; + + CONSUME_CYCLES(( 1 + k *(CEILLINGLOG2(k) + n) )); // 1 + k * (ceiling(log2(k)) + n) + + if(TCOMP_UDVM_GET_SIZE() <= (tsk_size_t)(start+(n*k*2)) ){ segfault = tsk_true; goto __SEGFAULT; }; + + // + // Create FirstList with key-value pairs. + // + list1_values = (IndexValuePair_t*)tsk_calloc(k, sizeof(IndexValuePair_t)); + if(!list1_values) { segfault = tsk_true; goto __SEGFAULT; }; + for(j=0, pos=0; pos<k; j+=2,pos++){ + list1_values[pos].index = pos; + GET_2BYTES_VAL((start+j), list1_values[pos].value); + } + + // Sort Fisrt List Values. + qsort(list1_values, k, sizeof(IndexValuePair_t), SortDescendingPredicate); + + + // Sort all lists + list_temp = tsk_calloc(k, sizeof(uint16_t)); + if(!list1_values) { segfault = tsk_true; goto __SEGFAULT; }; + for(list_index = 0; list_index < n; list_index++){ + uint16_t* list_start = (uint16_t*)TCOMP_UDVM_GET_BUFFER_AT(start + (list_index*k*2)); + memcpy(list_temp, list_start, k*2); + for(list_el=0; list_el<k; list_el++){ + list_start[(list_el)] = list_temp[ list1_values[list_el].index ]; + } + } + +__SEGFAULT: + TSK_FREE(list_temp); + TSK_FREE(list1_values); + + if(segfault){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_SEGFAULT].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); + return tsk_false; + } + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>SHA-1 (%position, %length, %destination)</i><br><br> +/// Reference: RFC3320 Section 9.1.4<br> +/// This instruction calculates a 20-byte SHA-1 hash [RFC-3174] over the specified area of UDVM memory. +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param position The starting memory address. +/// @param length The length of the byte string over which the SHA-1 hash is calculated. +/// @param destination The starting address to which the resulting 20-byte hash will be copied. +/// +/// @retval True if succeed, otherwise return false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__SHA_1(tcomp_udvm_t *udvm, uint32_t position, uint32_t length, uint32_t destination) +{ + tsk_bool_t ok = tsk_false; + tsk_sha1context_t sha; + int32_t err; + uint8_t Message_Digest[TSK_SHA1_DIGEST_SIZE]; + + // only check length + // (destination + length) could be > sizeof(udvm_memory) as copying is done byte by byte and could wrap + if(!length){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_SEGFAULT].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); + goto bail; + } + + CONSUME_CYCLES(1 + length); + + // The SHA-1 instruction calculates a 20-byte SHA-1 hash [RFC-3174] over the specified area of UDVM memory + if(udvm->tmp_buff.size < length){ + if(!(udvm->tmp_buff.ptr = tsk_realloc(udvm->tmp_buff.ptr, length))){ + udvm->tmp_buff.size = 0; + goto bail; + } + udvm->tmp_buff.size = length; + } + + if(!(ok = tcomp_udvm_bytecopy_from(udvm, udvm->tmp_buff.ptr, position, length))){ + goto bail; + } + + // Compute SHA-1 + if(!(ok = ((err = tsk_sha1reset(&sha)) == 0))){ + TSK_DEBUG_ERROR("%s: %d", TCOMP_NACK_DESCRIPTIONS[NACK_INTERNAL_ERROR].desc, err); + tcomp_udvm_createNackInfo2(udvm, NACK_INTERNAL_ERROR); + goto bail; + } + if(!(ok = ((err = tsk_sha1input(&sha, udvm->tmp_buff.ptr, length)) == 0))){ + TSK_DEBUG_ERROR("%s : %d", TCOMP_NACK_DESCRIPTIONS[NACK_INTERNAL_ERROR].desc, err); + tcomp_udvm_createNackInfo2(udvm, NACK_INTERNAL_ERROR); + goto bail; + } + if(!(ok = ((err = tsk_sha1result(&sha, (uint8_t*)Message_Digest)) == 0))){ + TSK_DEBUG_ERROR("%s : %d", TCOMP_NACK_DESCRIPTIONS[NACK_INTERNAL_ERROR].desc, ok); + tcomp_udvm_createNackInfo2(udvm, NACK_INTERNAL_ERROR); + goto bail; + } + + //Copy sha1 result to udvm memory + ok &= tcomp_udvm_bytecopy_to(udvm, destination, Message_Digest, TSK_SHA1_DIGEST_SIZE); + +bail: + return ok; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>LOAD(%address, %value)</i><br><br> +/// Reference: RFC3320 Section 9.2.1<br> +/// This instruction sets a 2-byte word to a certain specified value +/// As usual, MSBs are stored before LSBs in the UDVM memory. +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param address Specifies the starting address of a 2-byte word. +/// @param value Specifies the value to be loaded into this word. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__LOAD(tcomp_udvm_t *udvm, uint32_t address, uint32_t value) +{ + CONSUME_CYCLES(1); + + if( address >= TCOMP_UDVM_GET_SIZE() ){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_SEGFAULT].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); + return tsk_false; + } + + SET_2BYTES_VAL(address, value); + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>MULTILOAD(%address, \#n, %value_0, ..., %value_n-1)</i><br><br> +/// Reference: RFC3320 Section 9.2.2<br> +/// This instruction sets a contiguous block of 2-byte words in the UDVM memory to specified values. +/// value_0 through to value_n-1 specify the values to load into these words (in the same order as +/// they appear in the instruction). +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param address Starting address of the contiguous 2-byte words. +/// @param n Number of 2-bytes values to load. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__MULTILOAD(tcomp_udvm_t *udvm, uint32_t address, uint32_t n) +{ + uint32_t index, _address; + uint32_t overlap_start = udvm->last_memory_address_of_instruction; + #define overlap_end udvm->executionPointer + uint32_t write_start = address; + uint32_t write_end = (address + (n << 1)); + + CONSUME_CYCLES(1 + n); + +#define CHECK_MULTILOAD_OVERWRITTEN(__start, __address, __end) \ + if(( (__start) <= (__address) && (__address) <= (__end) ) || ( (__start) <= ((__address) + 1) && ((__address) + 1) <= (__end) )){ \ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_MULTILOAD_OVERWRITTEN].desc); \ + tcomp_udvm_createNackInfo2(udvm, NACK_MULTILOAD_OVERWRITTEN); \ + return tsk_false; \ + } + + // tcomp_udvm_opget_multitype_param() will move the execPtr => make the test before the for loop + CHECK_MULTILOAD_OVERWRITTEN(overlap_start, address, overlap_end); + CHECK_MULTILOAD_OVERWRITTEN(write_start, udvm->executionPointer, write_end); + + for(index = 0, _address = address; index < n; index++ , _address += 2){ + uint32_t value_n = tcomp_udvm_opget_multitype_param(udvm); + CHECK_MULTILOAD_OVERWRITTEN(overlap_start, _address, overlap_end); + CHECK_MULTILOAD_OVERWRITTEN(write_start, udvm->executionPointer, write_end); + SET_2BYTES_VAL(_address, value_n); + } + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>PUSH (%value)</i><br><br> +/// Reference: RFC3320 Section 9.2.3<br> +/// This instruction pushes the value specified by its operand on the stack.. +/// + +/// @date 11/27/2009 +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param value 2-byte word to push. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__PUSH(tcomp_udvm_t *udvm, int16_t value) +{ + tsk_bool_t callback = (value>=0); + uint32_t stack_location, stack_fill; + if(!callback){ + value = tcomp_udvm_opget_multitype_param(udvm); + } + + CONSUME_CYCLES(callback ? 0 : 1); + + + + GET_2BYTES_VAL(TCOMP_UDVM_HEADER_STACK_LOCATION_INDEX, stack_location); + GET_2BYTES_VAL(stack_location, stack_fill); + + /* + * copying the value to stack[stack_fill] + * stack[n] = stack_location+2*n+2 + */ + SET_2BYTES_VAL((stack_location+(2*stack_fill)+2), value); + + /* increasing stack_fill by 1*/ + SET_2BYTES_VAL(stack_location, (stack_fill+1)); + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>POP (%address)</i><br><br> +/// Reference: RFC3320 Section 9.2.3<br> +/// This instruction pops a value from the stack and then copies the value to the specified memory address.. +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param [in,out] value 2-byte word to pop from the stack. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__POP(tcomp_udvm_t *udvm, uint32_t* value) +{ + uint32_t address; + uint32_t stack_location, stack_fill, _value = 0; + + tsk_bool_t callback = (value != 0); + + CONSUME_CYCLES(callback?0:1); + + address = callback ? 0 : tcomp_udvm_opget_multitype_param(udvm); + + GET_2BYTES_VAL(TCOMP_UDVM_HEADER_STACK_LOCATION_INDEX, stack_location); + GET_2BYTES_VAL(stack_location, stack_fill); + + /* + * Decompression failure occurs if stack_fill is + * zero at the commencement of a popping operation. POP and RETURN pop + * values from the stack. + */ + if(stack_fill == 0){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_SEGFAULT].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); + _value = 0; + goto end; + } + + /* + * "Popping" a value from the stack is an abbreviation for decreasing + * stack_fill by 1, and then using the value stored in stack[stack_fill]. + */ + --stack_fill; + SET_2BYTES_VAL(stack_location, stack_fill); + /* stack[n] = stack_location+2*n+2 */ + GET_2BYTES_VAL((stack_location + (2*stack_fill) + 2), _value); + +end: + if(callback){ + *value = _value; + } + else{ + SET_2BYTES_VAL(address, _value); + } + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>COPY(%position, %length, %destination)</i><br><br> +/// Reference: RFC3320 Section 9.2.4<br> +/// This instruction is used to copy a string of bytes from one part of the UDVM memory to another. +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param position Specifies the memory address of the first byte in the string to be copied. +/// @param length Specifies the number of bytes to be copied. +/// @param destination Gives the address to which the first byte in the string will be copied. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__COPY(tcomp_udvm_t *udvm, uint32_t position, uint32_t length, uint32_t destination) +{ + tsk_bool_t ok = tsk_true; + + CONSUME_CYCLES(1+length); + + if( (position + length) > (int32_t)TCOMP_UDVM_GET_SIZE() || (destination + length) > (int32_t)TCOMP_UDVM_GET_SIZE() ){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_SEGFAULT].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); + return tsk_false; + } + + /* + * The COPY instruction is used to copy a string of bytes from one part + * of the UDVM memory to another. + */ + ok &= tcomp_udvm_bytecopy_self(udvm, &destination, position, length); + + return ok; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>COPY-LITERAL(%position, %length, $destination)</i><br><br> +/// Reference: RFC3320 Section 9.2.5<br> +/// The COPY-LITERAL instruction behaves as a COPY instruction except +/// that after copying is completed, the value of the destination operand +/// is replaced by the address to which the next byte of data would be copied.. +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param position Specifies the memory address of the first byte in the string to be copied. +/// @param length Specifies the number of bytes to be copied. +/// @param destination Gives the address to which the first byte in the string will be copied. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__COPY_LITERAL(tcomp_udvm_t *udvm, uint32_t position, uint32_t length, uint32_t destination) +{ + tsk_bool_t ok; + uint32_t destination_index; + + CONSUME_CYCLES(1+length); + + GET_2BYTES_VAL(destination, destination_index); + ok = tcomp_udvm_bytecopy_self(udvm, &destination_index, position, length); + if(ok){ + /* set next byte */ + SET_2BYTES_VAL(destination, destination_index); + } + + return ok; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>COPY-OFFSET(%offset, %length, $destination)</i><br><br> +/// Reference: RFC3320 Section 9.2.6<br> +/// This instruction behaves as a COPY-LITERAL instruction +/// except that an offset operand is given instead of a position operand.. +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param offset The offset value. +/// @param length Specifies the number of bytes to be copied. +/// @param destination Gives the address to which the first byte in the string will be copied. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__COPY_OFFSET(tcomp_udvm_t *udvm, uint32_t offset, uint32_t length, uint32_t destination) +{ + uint32_t DEST, LEFT, RIGTH; + int32_t position = -1; + uint32_t destination_index; + + int32_t D, T; + int32_t O; + + CONSUME_CYCLES(1+length); + + GET_2BYTES_VAL(destination, DEST); + GET_2BYTES_VAL(TCOMP_UDVM_HEADER_BYTE_COPY_LEFT_INDEX, LEFT); + GET_2BYTES_VAL(TCOMP_UDVM_HEADER_BYTE_COPY_RIGHT_INDEX, RIGTH); + + /* + DEST: ses + D: distance between LEFT and DEST + O: offset + T: total size between LEFT and RIGTH + + [***** + case 1: + -----LEFT--------DEST------------RIGTH---- + <-----D----> + <--O-> + <---------------T------------> + ****] + [***** + case 2: + -----LEFT--------DEST------------RIGTH---- + <-----D----> + <--------O--------> + <---------------T------------> + ****] + [***** + case 3: + -------DEST-----LEFT-------------RIGTH---- + ****] + */ + D = (DEST - LEFT); + T = (RIGTH - LEFT); + O = offset; + + if( D>=0 && O<=D ){ + /* case 1: easy case */ + position = (DEST-O); + } + else if( D>=0 && O>D ){ + /* case 2: */ + double PAD = (D + ((ceil(((double)O-(double)D)/(double)T))*T))-O; + position = LEFT+(int32_t)PAD; + } + else if( D<0 ){ + /* case 3: */ + position = DEST-O; + } + + /* Check position */ + if(position<0){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_SEGFAULT].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); + return tsk_false; + } + + /* EXEC_INST__COPY_LITERAL */ + GET_2BYTES_VAL(destination, destination_index); + if(tcomp_udvm_bytecopy_self(udvm, &destination_index, position, length) == tsk_true){ + SET_2BYTES_VAL(destination, destination_index); + } + else{ + return tsk_false; + } + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>MEMSET(%address, %length, %start_value, %offset)</i><br><br> +/// Reference: RFC3320 Section 9.2.7<br> +/// Formula: Seq[n] := (start_value + n * offset) modulo 256<br> +/// This instruction initializes an area of UDVM memory to a specified sequence of values. +/// + +/// @date 11/27/2009 +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param address The destination address. +/// @param length The number of 1-byte values to set. +/// @param start_value The starting value. +/// @param offset The offset used for computation. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__MEMSET(tcomp_udvm_t *udvm, uint32_t address, uint32_t length, uint32_t start_value, uint32_t offset) +{ + uint8_t* seqs_temp; + uint32_t n; + tsk_bool_t ok; + + CONSUME_CYCLES(1+length); + + /* + * The values Seq[0] to Seq[length - 1] inclusive are each interpreted + * as a single byte, and then concatenated to form a byte string where + * the first byte has value Seq[0], the second byte has value Seq[1] and + * so on up to the last byte which has value Seq[length - 1]. + */ + seqs_temp = tsk_calloc(length, sizeof(uint8_t)); + if(!seqs_temp){ + return tsk_false; + } + + for(n=0; n < length; n++){ + seqs_temp[n] = (start_value + n * offset)%256; + } + /* + * The string is then byte copied into the UDVM memory beginning at the + * memory address specified as an operand to the MEMSET instruction, + * obeying the rules of Section 8.4. + */ + ok = tcomp_udvm_bytecopy_to(udvm, address, seqs_temp, length); + + TSK_FREE(seqs_temp); + + return ok; +} + +/** +* @brief <i>JUMP (\@address)</i><br><br> +* Reference: RFC3320 Section 9.3.1<br> +* This instruction moves program execution to the specified memory address. +* Decompression failure occurs if the value of the address operand lies +* beyond the overall UDVM memory size. +* @param [in,out] udvm The udvm state machine entity. +* @param address defines the address to jump to +* @retval 1 if succeed, otherwise returns 0 +*/ +tsk_bool_t TCOMP_UDVM_EXEC_INST__JUMP(tcomp_udvm_t *udvm, int16_t address) +{ + int callback = (address >=0 ); + CONSUME_CYCLES(callback?0:1); + + if(!callback){ + address = tcomp_udvm_opget_address_param(udvm, udvm->last_memory_address_of_instruction); + } + + if(address > (int32_t)TCOMP_UDVM_GET_SIZE()){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_SEGFAULT].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); + return tsk_false; + } + udvm->executionPointer = address; + + return tsk_true; +} + + +/** + * + * @brief <i>COMPARE(%value_1, %value_2, \@address_1, \@address_2, \@address_3)</i><br><br> + * Reference: RFC3320 Section 9.3.2<br> + * + * This instruction compares two operands and then jumps to one of three specified + * memory addresses depending on the result.<br> + * if(value_1 < value_2) --> address_1<br> + * elif(value_1 = value_2) --> address_2<br> + * elif(value_1 > value_2) --> address_3. <br> + * + * + * @param [in,out] udvm The udvm state machine entity. + * @param value_1 The first value to compare. + * @param value_2 The second value to compare. + * @param address_1 The address to jump to if (value_1 < value_2). + * @param address_2 The address to jump to if (value_1 = value_2). + * @param address_3 address to jump to if (value_1 > value_2). + * @retval 1 if succeed, otherwise returns 0. +**/ +tsk_bool_t TCOMP_UDVM_EXEC_INST__COMPARE(tcomp_udvm_t *udvm, uint32_t value_1, uint32_t value_2, uint32_t address_1, uint32_t address_2, uint32_t address_3) +{ + tsk_bool_t ok = 1; + + CONSUME_CYCLES(1); + + if(value_1 < value_2){ + ok &= TCOMP_UDVM_EXEC_INST__JUMP(udvm, address_1); + goto end; + } + + if(value_1 == value_2){ + ok &= TCOMP_UDVM_EXEC_INST__JUMP(udvm, address_2); + goto end; + } + + if(value_1 > value_2){ + ok &= TCOMP_UDVM_EXEC_INST__JUMP(udvm, address_3); + goto end; + } + +end: + return ok; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>CALL(\@address)</i><br><br> +/// Reference: RFC3320 Section 9.3.3<br> +/// This instruction finds the memory address of the instruction immediately following +/// the CALL instruction and pushes this 2-byte value on the stack, ready for later retrieval. +/// It then continues instruction execution at the memory address specified by the address operand.. +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param address The next address. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__CALL(tcomp_udvm_t *udvm, uint32_t address) +{ + CONSUME_CYCLES(1); + + return TCOMP_UDVM_EXEC_INST__PUSH(udvm, udvm->executionPointer) + && TCOMP_UDVM_EXEC_INST__JUMP(udvm, address); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>RETURN</i><br><br> +/// Reference: RFC3320 Section 9.3.3<br> +/// This instruction pops a value from the stack and then continues instruction +/// execution at the memory address just popped.. +/// +/// @param [in,out] udvm The udvm state machine entity. +/// +/// @retval True if succeed, otherwise return false . +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__RETURN(tcomp_udvm_t *udvm) +{ + uint32_t value = 0; + tsk_bool_t ok = tsk_true; + + CONSUME_CYCLES(1); + + if( (ok = TCOMP_UDVM_EXEC_INST__POP(udvm, &value)) ){ + ok &= TCOMP_UDVM_EXEC_INST__JUMP(udvm, value); + } + + return ok; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>SWITCH(\#n, %j, \@address_0, \@address_1, ... , \@address_n-1)</i><br><br> +/// Reference: RFC3320 Section 9.3.4<br> +/// This instruction performs a conditional jump based on the value of one of its operands. +/// Decompression failure occurs if j specifies a value of n or more, or +/// if the address lies beyond the overall UDVM memory size.. + +/// @param [in,out] udvm The udvm state machine entity. +/// @param n The number of possibilities. +/// @param j The possibility. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__SWITCH(tcomp_udvm_t *udvm, uint32_t n, uint32_t j) +{ + uint32_t next = 0; + tsk_bool_t ok = tsk_true; + + CONSUME_CYCLES(1+n); + + /* Decompression failure occurs if j specifies a value of n or more. */ + if(j >= n){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_SWITCH_VALUE_TOO_HIGH].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_SWITCH_VALUE_TOO_HIGH); + ok = tsk_false; + goto end; + } + + do{ + next = tcomp_udvm_opget_address_param(udvm, udvm->last_memory_address_of_instruction); + } + while(j--); + +end: + if(ok){ + ok = TCOMP_UDVM_EXEC_INST__JUMP(udvm, next); + } + + return ok; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>CRC(%value, %position, %length, \@address)</i><br><br> +/// Reference: RFC3320 Section 9.3.5<br> +/// This instruction verifies a string of bytes using a 2-byte CRC. +/// The CRC value is computed exactly as defined for the 16-bit FCS calculation in [RFC-1662].. +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param value Contains the expected integer value of the 2-byte CRC. +/// @param position Defines the position of the string of bytes over which the CRC is evaluated. +/// @param length Defines the length of the string of bytes over which the CRC is evaluated. +/// @param address The address to jump to if the calculated CRC value do not match. +/// +/// @retval True if succeed, otherwise return false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__CRC(tcomp_udvm_t *udvm, uint32_t value, uint32_t position, uint32_t length, uint32_t address) +{ + uint32_t crc_value; + + CONSUME_CYCLES(1 + length); + + if(udvm->tmp_buff.size < length){ + if(!(udvm->tmp_buff.ptr = tsk_realloc(udvm->tmp_buff.ptr, length))){ + udvm->tmp_buff.size = 0; + tcomp_udvm_createNackInfo2(udvm, NACK_INTERNAL_ERROR); + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_INTERNAL_ERROR].desc); + return tsk_false; + } + udvm->tmp_buff.size = length; + } + + /* copy data */ + if(!tcomp_udvm_bytecopy_from(udvm, udvm->tmp_buff.ptr, position, length)){ + return tsk_false; + } + + /* + * The CRC value is computed exactly as defined for the 16-bit FCS + * calculation in [RFC-1662] + */ + crc_value = tsk_pppfcs16(TSK_PPPINITFCS16, udvm->tmp_buff.ptr, length); + + /* + * If the calculated CRC matches the expected value then the UDVM + * continues instruction execution at the following instruction. + * Otherwise the UDVM jumps to the memory address specified by the + * address operand. + */ + if(value != crc_value){ + TCOMP_UDVM_EXEC_INST__JUMP(udvm, address); + } + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>INPUT-BYTES (%length, %destination, \@address)</i><br><br> +/// Reference: RFC3320 Section 9.4.2<br> +/// This instruction requests a certain number of bytes of compressed data from the decompressor dispatcher. +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param length Indicates the requested number of bytes of compressed data. +/// @param destination Specifies the starting memory address to which they should be copied. +/// @param address Defines the address to jump to if the instruction requests data that lies beyond the end of the SigComp message. +/// +/// @retval True if succeed, otherwise return false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__INPUT_BYTES(tcomp_udvm_t *udvm, uint32_t length, uint32_t destination, uint32_t address) +{ + tsk_bool_t ok = tsk_true; + const uint8_t* compressedDataAddress; + uint8_t* destinationAddress; + + CONSUME_CYCLES(1+length); + + /* + * If the INPUT-BYTES is encountered after an INPUT-BITS or an INPUT- + * HUFFMAN instruction has been used, and the dispatcher currently holds + * a fraction of a byte, then the fraction MUST be discarded before any + * data is passed to the UDVM. The first byte to be passed is the byte + * immediately following the discarded data. + */ + tcomp_buffer_discardBits(udvm->sigCompMessage->remaining_sigcomp_buffer); + + compressedDataAddress = tcomp_buffer_readBytes(udvm->sigCompMessage->remaining_sigcomp_buffer, length); + destinationAddress = TCOMP_UDVM_GET_BUFFER_AT(destination); + if(compressedDataAddress){ + ok &= tcomp_udvm_bytecopy_to(udvm, destination, compressedDataAddress, length); + if(ok){ + /* FIXME: (8 * n + 1000) * cycles_per_bit */ + udvm->maximum_UDVM_cycles += ((8 * length /*+ 1000*/) * udvm->stateHandler->sigcomp_parameters->cpbValue); + } + } + else{ + /* + * If the instruction requests data that lies beyond the end of the + * SigComp message, no data is returned. Instead the UDVM moves program + * execution to the address specified by the address operand. + */ + ok &= TCOMP_UDVM_EXEC_INST__JUMP(udvm, address); + } + + return ok; +} + +/** + * + * @brief <i>INPUT-BITS (%length, %destination, \@address)</i><br><br> + * Reference: RFC3320 Section 9.4.3<br> + * The INPUT-BITS instruction requests a certain number of bits of + * compressed data from the decompressor dispatcher. + * + * + * @param [in,out] udvm The udvm state machine entity. + * @param length The length operand indicates the requested number of bits. + Decompression failure occurs if this operand does not lie between 0 + and 16 inclusive. + * @param destination The destination operand specifies the memory address to which the + compressed data should be copied. Note that the requested bits are + interpreted as a 2-byte integer ranging from 0 to 2^length - 1, as + explained in Section 8.2. + + * @param address The address of the destination. + * + * @retval 1 if succeed, otherwise returns 0. +**/ +tsk_bool_t TCOMP_UDVM_EXEC_INST__INPUT_BITS(tcomp_udvm_t *udvm, uint32_t length, uint32_t destination, uint32_t address) +{ + tsk_bool_t ok = tsk_true; + uint32_t input_bit_order, reserved; + uint8_t F_BIT, P_BIT; + uint8_t* old_P_BIT; + + /* + The input_bit_order register contains the following three flags: + 0 7 8 15 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | reserved |F|H|P| 68 - 69 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + */ + + CONSUME_CYCLES(1); + + GET_2BYTES_VAL(TCOMP_UDVM_HEADER_INPUT_BIT_ORDER_INDEX, input_bit_order); + reserved = (input_bit_order & 0xf8); + /* + * Decompression failure occurs if an INPUT-BITS or an INPUT-HUFFMAN + * instruction is encountered and the input_bit_order register does not + * lie between 0 and 7 inclusive. + */ + if(reserved){ + /* MUST BE ZEROS --> Only 3bits --> [0-7] */ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_BAD_INPUT_BITORDER].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_BAD_INPUT_BITORDER); + return tsk_false; + } + + /* F and P BITS */ + F_BIT = (input_bit_order & 0x0004) ? 1 : 0; + P_BIT = (input_bit_order & 0x0001); + + /* + * Decompression failure occurs if this operand (length) does not lie between 0 + * and 16 inclusive. + */ + if(/*length<0 ||*/ length>16){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_INVALID_OPERAND].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_INVALID_OPERAND); + return tsk_false; + } + + /* + * P:The P-bit controls the order in which bits are passed from the + * dispatcher to the INPUT instructions + * P=0 --> MSB_TO_LSB + * P=1 --> LSB_TO_MSB + */ + old_P_BIT = tcomp_buffer_getP_BIT(udvm->sigCompMessage->remaining_sigcomp_buffer); + if(*old_P_BIT != P_BIT){ + /* + * If the P-bit has changed since the last INPUT instruction, any fraction of a + * byte still held by the dispatcher MUST be discarded (even if the + * INPUT instruction requests zero bits) + */ + tcomp_buffer_discardBits(udvm->sigCompMessage->remaining_sigcomp_buffer); + *old_P_BIT = P_BIT; + } + + /* + * If the instruction requests data that lies beyond the end of the + * SigComp message, no data is returned. Instead the UDVM moves program + * execution to the address specified by the address operand. + */ + if( (length) > tcomp_buffer_getRemainingBits(udvm->sigCompMessage->remaining_sigcomp_buffer) ){ + ok &= TCOMP_UDVM_EXEC_INST__JUMP(udvm, address); + goto end; + } + + /* + * If the F-bit is set to 0, the INPUT-BITS instruction interprets the + * received bits as arriving MSBs first, and if it is set to 1, it interprets the bits as arriving LSBs first. + * F=0 --> MSB_TO_LSB + * F=1 --> LSB_TO_MSB + */ + if(P_BIT == TCOMP_P_BIT_MSB_TO_LSB){ + /* MSB_TO_LSB */ + uint32_t value = tcomp_buffer_readMsbToLsb(udvm->sigCompMessage->remaining_sigcomp_buffer, length); + if(F_BIT == F_BIT_LSB_TO_MSB){ + value = (TSK_BINARY_REVERSE_2BYTE(value)>>(16-length)); + } + SET_2BYTES_VAL(destination, value); + } + else{ + /* LSB_TO_MSB */ + uint32_t value = tcomp_buffer_readLsbToMsb(udvm->sigCompMessage->remaining_sigcomp_buffer, length); + if(F_BIT == F_BIT_LSB_TO_MSB) { + value = (TSK_BINARY_REVERSE_2BYTE(value)>>(16-length)); + } + SET_2BYTES_VAL(destination, value); + } + +end: + + udvm->maximum_UDVM_cycles += (length * udvm->stateHandler->sigcomp_parameters->cpbValue); + return ok; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>INPUT-HUFFMAN(%destination, \@address, \#n, %bits_1, %lower_bound_1, %upper_bound_1, %uncompressed_1, ... , %bits_n, %lower_bound_n, %upper_bound_n, %uncompressed_n)</i><br><br> +/// Reference: RFC3320 Section 9.4.4<br> +/// +/// This instruction requests a variable number of bits of compressed data from the decompressor dispatcher. The instruction +/// initially requests a small number of bits and compares the result against a certain criterion; if the criterion is not met, then +/// additional bits are requested until the criterion is achieved. +/// +/// @param [in,out] udvm The udvm state machine entity. +/// @param destination The udvm destination address. +/// @param address Address to jump to if data is requested that lies beyond the end of the SigComp message. +/// @param n Additional sets of operands count. +/// +/// @retval True if succeed, otherwise return false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__INPUT_HUFFMAN(tcomp_udvm_t *udvm, uint32_t destination, uint32_t address, uint32_t n) +{ + /* + The input_bit_order register contains the following three flags: + 0 7 8 15 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | reserved |F|H|P| 68 - 69 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + */ + tsk_bool_t ok = tsk_true; + uint32_t input_bit_order, reserved; + uint8_t H_BIT, P_BIT, *old_P_BIT; + + uint32_t bits_j, lower_bound_j, upper_bound_j, uncompressed_j; + uint32_t bits_total = 0, k = 0, H, J; + tsk_bool_t criterion_ok = tsk_false; + + CONSUME_CYCLES(1+n); + + /*Note that if n = 0 then the INPUT-HUFFMAN instruction is ignored and + program execution resumes at the following instruction.*/ + if(n == 0){ + //goto end; + return ok; + } + + GET_2BYTES_VAL(TCOMP_UDVM_HEADER_INPUT_BIT_ORDER_INDEX, input_bit_order); + reserved = (input_bit_order & 0xf8); + /* + * Decompression failure occurs if an INPUT-BITS or an INPUT-HUFFMAN + * instruction is encountered and the input_bit_order register does not + * lie between 0 and 7 inclusive. + */ + if(reserved){ + /* MUST BE ZEROS --> Only 3bits --> [0-7] */ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_BAD_INPUT_BITORDER].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_BAD_INPUT_BITORDER); + return tsk_false; + } + + /* H and P */ + H_BIT = (input_bit_order & 0x0002)?1:0; + P_BIT = (input_bit_order & 0x0001); + + /* + * P:The P-bit controls the order in which bits are passed from the + * dispatcher to the INPUT instructions + * P=0 --> MSB_TO_LSB + * P=1 --> LSB_TO_MSB + */ + old_P_BIT = tcomp_buffer_getP_BIT(udvm->sigCompMessage->remaining_sigcomp_buffer); + if( *old_P_BIT != P_BIT ){ + /* + * If the P-bit has changed since the last INPUT instruction, any fraction of a + * byte still held by the dispatcher MUST be discarded (even if the + * INPUT instruction requests zero bits) + */ + tcomp_buffer_discardBits(udvm->sigCompMessage->remaining_sigcomp_buffer); + *old_P_BIT = P_BIT; + } + + /* + * HUFFMAN COMPUTATION + */ + + /* 1. Set j := 1 and set H := 0. */ + for(J = 1, H = 0; J<=n; J++){ + /* + * Request bits_j compressed bits. Interpret the returned bits as an + * integer k from 0 to 2^bits_j - 1, as explained in Section 8.2. + */ + bits_j = tcomp_udvm_opget_multitype_param(udvm); + lower_bound_j = tcomp_udvm_opget_multitype_param(udvm); + upper_bound_j = tcomp_udvm_opget_multitype_param(udvm); + uncompressed_j = tcomp_udvm_opget_multitype_param(udvm); + bits_total += bits_j; + + /*Decompression failure occurs if (bits_1 + ... + bits_n) > 16.*/ + if(bits_total > 16){ + ok = tsk_false; + // FIXME: DECOMPRESSION failure TOO_MANY_BITS_REQUESTED + goto end; + } + + if(criterion_ok){ + continue; + } + +//==step_4: + /* + * 4.If data is requested that lies beyond the end of the SigComp + * message, terminate the INPUT-HUFFMAN instruction and move program + * execution to the memory address specified by the address operand. + */ + if( (bits_j) > tcomp_buffer_getRemainingBits(udvm->sigCompMessage->remaining_sigcomp_buffer) ){ + ok &= TCOMP_UDVM_EXEC_INST__JUMP(udvm, address); + goto end; + } + +//==step_2: + /* + * 2. Request bits_j compressed bits. Interpret the returned bits as an + * integer k from 0 to 2^bits_j - 1, as explained in Section 8.2. + */ + if(P_BIT == TCOMP_P_BIT_MSB_TO_LSB){ + k = tcomp_buffer_readMsbToLsb(udvm->sigCompMessage->remaining_sigcomp_buffer, bits_j); + if(H_BIT == H_BIT_LSB_TO_MSB) { + k = (TSK_BINARY_REVERSE_2BYTE(k)>>(16-bits_j)); + } + } + else{ + k = tcomp_buffer_readLsbToMsb(udvm->sigCompMessage->remaining_sigcomp_buffer, bits_j); + if(H_BIT == H_BIT_LSB_TO_MSB){ + k = (TSK_BINARY_REVERSE_2BYTE(k)>>(16-bits_j)); + } + } +//==step_3: + /* 3. Set H := H * 2^bits_j + k */ + H = H * (uint32_t)pow(2.0, bits_j) + k; + +//==step_5: + /* + * 5. If (H < lower_bound_j) or (H > upper_bound_j) then set j := j + 1. + * Then go back to Step 2, unless j > n in which case decompression + * failure occurs. + */ + if( (H < lower_bound_j) || (H > upper_bound_j) ){ + continue; + //goto step_2; + } + else{ + /* + * Copy (H + uncompressed_j - lower_bound_j) modulo 2^16 to the + * memory address specified by the destination operand. + */ + H = (H + uncompressed_j - lower_bound_j) % 65536; + criterion_ok = 1; + } + } + + if(!criterion_ok){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_HUFFMAN_NO_MATCH].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_HUFFMAN_NO_MATCH); + ok = tsk_false; + goto end; + } + else if(ok){ + SET_2BYTES_VAL(destination, H); + udvm->maximum_UDVM_cycles += (bits_total * udvm->stateHandler->sigcomp_parameters->cpbValue); + } +end: + return ok; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>STATE-ACCESS(%partial_identifier_start, %partial_identifier_length, %state_begin, %state_length, %state_address, %state_instruction)</i><br><br> +/// Reference: RFC3320 Section 9.4.5<br> +/// This instruction retrieves some previously stored state information.. + +/// @param [in,out] udvm If non-null, the udvm. +/// @param partial_identifier_start Specifies the location of the partial state identifier used to retrieve the state information. +/// @param partial_identifier_length Specifies the length of the partial state identifier used to retrieve the state information. +/// @param state_begin Defines the starting byte to copy from the state_value contained in the returned item of state. +/// @param state_length Defines the number of bytes to copy from the state_value contained in the returned item of state. +/// @param state_address Contains a UDVM memory address. +/// @param state_instruction Next instruction to jump to. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__STATE_ACCESS(tcomp_udvm_t *udvm, uint32_t partial_identifier_start, uint32_t partial_identifier_length, uint32_t state_begin, uint32_t state_length, uint32_t state_address, uint32_t state_instruction) +{ + tcomp_state_t* lpState = NULL; + tcomp_buffer_handle_t* partial_id; + uint32_t match_count; + + /* + * Decompression failure occurs if partial_identifier_length does not + * lie between 6 and 20 inclusive. + */ + if(partial_identifier_length<6 || partial_identifier_length>20){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_INVALID_STATE_ID_LENGTH].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_INVALID_STATE_ID_LENGTH); + return tsk_false; + } + /* + * decompression failure will always occur if the state_length operand + * is set to 0 but the state_begin operand is non-zero. + */ + if(!state_length && state_begin){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_INVALID_STATE_PROBE].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_INVALID_STATE_PROBE); + return tsk_false; + } + + /* + * Find matching state + */ + partial_id = tcomp_buffer_create_null(); + tcomp_buffer_referenceBuff(partial_id, TCOMP_UDVM_GET_BUFFER_AT(partial_identifier_start), partial_identifier_length); + match_count = tcomp_statehandler_findState(udvm->stateHandler, partial_id, &lpState); + + /* + * Decompression failure occurs if no state item matching the partial state identifier can be found, if + * more than one state item matches the partial identifier. + */ + if(!lpState || match_count != 1){ + int32_t nack_code = (match_count > 1) ? NACK_ID_NOT_UNIQUE : NACK_STATE_NOT_FOUND; + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[nack_code].desc); + tcomp_udvm_createNackInfo3(udvm, nack_code, partial_id); + TSK_OBJECT_SAFE_FREE(partial_id); + return tsk_false; + } + else if(partial_identifier_length < lpState->minimum_access_length){ + /* + * Decompression failure occurs if partial_identifier_length is less than the minimum_access_length of + * the matched state item. + */ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_STATE_NOT_FOUND].desc); + tcomp_udvm_createNackInfo3(udvm, NACK_STATE_NOT_FOUND, partial_id); + TSK_OBJECT_SAFE_FREE(partial_id); + return tsk_false; + } + TSK_OBJECT_SAFE_FREE(partial_id); + + /* + * If any of the operands state_address, state_instruction or + * state_length is set to 0 then its value is taken from the returned + * item of state instead. + */ + if(!state_address) { + state_address = lpState->address; + } + if(!state_instruction) { + state_instruction = lpState->instruction; + } + if(!state_length) { + state_length = lpState->length; + } + + CONSUME_CYCLES(1+state_length); + + /* Decompression failure occurs if bytes are copied from beyond the end of the state_value. */ + if((tsk_size_t)(state_begin + state_length) > tcomp_buffer_getSize(lpState->value)){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_STATE_TOO_SHORT].desc); + tcomp_udvm_createNackInfo3(udvm, NACK_STATE_TOO_SHORT, partial_id); + return tsk_false; + } + + /* + * The state_address operand contains a UDVM memory address. The + * requested portion of the state_value is byte copied to this memory + * address using the rules of Section 8.4. + */ + if(tcomp_udvm_bytecopy_to(udvm, state_address, tcomp_buffer_getBufferAtPos(lpState->value, state_begin), state_length) != tsk_true){ + return tsk_false; + } + + /* + * Program execution then resumes at the memory address specified by + * state_instruction, unless this address is 0 in which case program + * execution resumes at the next instruction following the STATE-ACCESS + * instruction. + */ + if(state_instruction){ + if(!TCOMP_UDVM_EXEC_INST__JUMP(udvm, state_instruction)){ + return tsk_false; + } + } + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>STATE-CREATE (%state_length, %state_address, %state_instruction, %minimum_access_length, %state_retention_priority)</i><br><br> +/// Reference: RFC3320 Section 9.4.6<br> +/// This instruction requests the creation of a state item at the receiving endpoint.. + +/// @param [in,out] udvm If non-null, the udvm. +/// @param state_length Defines the length of the state to create. +/// @param state_address Defines the udvm address of the state to create. +/// @param state_instruction Defines the state instruction. +/// @param minimum_access_length Defines the minimun access length. +/// @param state_retention_priority Defines the state retenion priority. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__STATE_CREATE(tcomp_udvm_t *udvm, uint32_t state_length, uint32_t state_address, uint32_t state_instruction, uint32_t minimum_access_length, uint32_t state_retention_priority) +{ + CONSUME_CYCLES(1 + state_length); + + /* + * Create temporary state? + */ + if(!tcomp_udvm_createTempState(udvm, state_length, state_address, state_instruction, + minimum_access_length, state_retention_priority, 0)){ + return tsk_false; + } + + return tsk_true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i>STATE-FREE(%partial_identifier_start, %partial_identifier_length)</i><br><br> +/// Reference: RFC3320 Section 9.4.7<br> +/// This instruction informs the receiving endpoint that the sender no longer wishes to use a particular state item.. + +/// @param [in,out] udvm If non-null, the udvm. +/// @param partial_identifier_start Defines the first byte address of partial start identifier. +/// @param partial_identifier_length Defines the partial identifier length. +/// +/// @retval True if succeed, otherwise return false . +//////////////////////////////////////////////////////////////////////////////////////////////////// +tsk_bool_t TCOMP_UDVM_EXEC_INST__STATE_FREE(tcomp_udvm_t *udvm, uint32_t partial_identifier_start, uint32_t partial_identifier_length) +{ + tcomp_tempstate_to_free_t *lpDesc; + + CONSUME_CYCLES(1); + + /* + * Decompression failure MUST occur if more than four state free + * requests are made before the END-MESSAGE instruction is encountered. + */ + if(tcomp_result_getTempStatesToFreeSize(udvm->lpResult) >=4){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_TOO_MANY_STATE_REQUESTS].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_TOO_MANY_STATE_REQUESTS); + return tsk_false; + } + + /* + * Decompression failure also occurs if partial_identifier_length does + * not lie between 6 and 20 inclusive. + */ + if(partial_identifier_length<6 || partial_identifier_length>20){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_INVALID_STATE_ID_LENGTH].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_INVALID_STATE_ID_LENGTH); + return tsk_false; + } + + lpDesc = tcomp_tempstate_to_free_create(); + lpDesc->partial_identifier_length = partial_identifier_length; + lpDesc->partial_identifier_start = partial_identifier_start; + tcomp_result_addTempStateToFree(udvm->lpResult, lpDesc); + + /*** Do not ByteCopy data, wait for END_MESSAGE --> see RFC 3320 subclause 9.4.9 **/ + + return tsk_true; +} + +/** +* @brief <i>OUTPUT (%output_start, %output_length)</i><br><br> +* Reference: RFC3320 Section 9.4.8<br> +* This instruction provides successfully decompressed data to the dispatcher. +* @param [in,out] udvm The udvm state machine entity. +* @param output_start defines the starting memory address of the byte string to be provided to the dispatcher +* @param output_length defines the length of the byte string to be provided to the dispatcher +* @retval 1 if succeed, otherwise returns 0 +*/ +tsk_bool_t TCOMP_UDVM_EXEC_INST__OUTPUT(tcomp_udvm_t *udvm, uint32_t output_start, uint32_t output_length) +{ + tsk_bool_t ok; + tsk_size_t *outputbuffer_size; + + CONSUME_CYCLES(1+output_length); + + outputbuffer_size = tcomp_buffer_getIndexBytes(udvm->lpResult->output_buffer); + if( (*outputbuffer_size + output_length) > 65536 ){ + /* + * Decompression failure occurs if the cumulative number of bytes + * provided to the dispatcher exceeds 65536 bytes. + */ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_OUTPUT_OVERFLOW].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_OUTPUT_OVERFLOW); + return tsk_false; + } + + // FIXME: do it once? + if((ok = tcomp_udvm_bytecopy_from(udvm, tcomp_buffer_getBufferAtPos(udvm->lpResult->output_buffer, *outputbuffer_size), output_start, output_length))){ + *outputbuffer_size += output_length; + } + +#if DEBUG || _DEBUG + //tcomp_buffer_nprint(udvm->lpResult->output_buffer, *outputbuffer_size); +#endif + return ok; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// +/// @brief <i> END-MESSAGE (%requested_feedback_location, %returned_parameters_location, %state_length, %state_address, %state_instruction, %minimum_access_length, %state_retention_priority)</i><br><br> +/// Reference: RFC3320 Section 9.4.9<br> +/// This instruction successfully terminates the UDVM and forwards the state creation and state free requests to the state +/// handler together with any supplied feedback data. +/// +/// @param [in,out] udvm Defines the requested feedback location. +/// @param requested_feedback_location The requested feedback location. +/// @param returned_parameters_location Defines the returned parameters location which contains remote party capabilities. +/// @param state_length Length of the state to create. +/// @param state_address UDVM memory address of the state to create. +/// @param state_instruction Defines the state instruction. +/// @param minimum_access_length Defines the state's minimum access length. +/// @param state_retention_priority Determines the order in which state will be deleted when the compartment exceeds its allocated state memory. +/// +/// @retval @a tsk_true if succeed, otherwise returns @a tsk_false. +//////////////////////////////////////////////////////////////////////////////////////////////////// + +tsk_bool_t TCOMP_UDVM_EXEC_INST__END_MESSAGE(tcomp_udvm_t *udvm, uint32_t requested_feedback_location, uint32_t returned_parameters_location, uint32_t state_length, uint32_t state_address, uint32_t state_instruction, uint32_t minimum_access_length, uint32_t state_retention_priority) +{ + tsk_size_t udvm_size; + + CONSUME_CYCLES(1+state_length); + + udvm_size = TCOMP_UDVM_GET_SIZE(); + + /* + * Create temporary state provided by END_MESSAGE? + */ + if(!tcomp_udvm_createTempState(udvm, state_length, state_address, state_instruction, minimum_access_length, state_retention_priority, 1)){ + return tsk_false; + } + + /* + * Byte copy all waiting STATE-FREE/STATE-CREATE/END-MESSAGE states + */ + if(!tcomp_udvm_byteCopy_TempStates(udvm)){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_INTERNAL_ERROR].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_INTERNAL_ERROR); + return tsk_false; + } + + /* + * Feedback has been requested? + */ + if(requested_feedback_location){ + uint8_t r_f_l; + if(requested_feedback_location >= udvm_size){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_SEGFAULT].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); + return tsk_false; + } + /* + 0 1 2 3 4 5 6 7 + +---+---+---+---+---+---+---+---+ + | reserved | Q | S | I | requested_feedback_location + +---+---+---+---+---+---+---+---+ + | | + : requested feedback item : if Q = 1 + | | + +---+---+---+---+---+---+---+---+ + */ + r_f_l = *TCOMP_UDVM_GET_BUFFER_AT(requested_feedback_location); + udvm->lpResult->req_feedback->I = (r_f_l & 0x01); + udvm->lpResult->req_feedback->S = (r_f_l & 0x02) ? 1 : 0; + udvm->lpResult->req_feedback->Q = (r_f_l & 0x04) ? 1 : 0; + + requested_feedback_location++; /* skip 1-byte header */ + if(udvm->lpResult->req_feedback->Q){ + /* we have a requested feedback item */ + uint8_t r_f_i = *TCOMP_UDVM_GET_BUFFER_AT(requested_feedback_location); + uint8_t length = 1; /* [1-128] */ + if(r_f_i & 0x80){ + /* case 2 */ + length += (r_f_i & 0x7f); /* seven last bits */ + } + + if(requested_feedback_location >= TCOMP_UDVM_GET_SIZE()){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_SEGFAULT].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); + return tsk_false; + } + /* copy from udvm */ + // FIXME: use realloc + tcomp_buffer_freeBuff(udvm->lpResult->req_feedback->item); + tcomp_buffer_allocBuff(udvm->lpResult->req_feedback->item, length); + if(!tcomp_udvm_bytecopy_from(udvm, tcomp_buffer_getBuffer(udvm->lpResult->req_feedback->item), requested_feedback_location, length)){ + return tsk_false; + } + } + } + + // + // SigComp parameters have been returned? + // + if(returned_parameters_location){ + uint8_t r_p_l, SigComp_version; + uint32_t index; + tcomp_buffer_handle_t *partial_id; + + /* + 0 1 2 3 4 5 6 7 + +---+---+---+---+---+---+---+---+ + | cpb | dms | sms | returned_parameters_location + +---+---+---+---+---+---+---+---+ + | SigComp_version | + +---+---+---+---+---+---+---+---+ + | length_of_partial_state_ID_1 | + +---+---+---+---+---+---+---+---+ + | | + : partial_state_identifier_1 : + | | + +---+---+---+---+---+---+---+---+ + : : + +---+---+---+---+---+---+---+---+ + | length_of_partial_state_ID_n | + +---+---+---+---+---+---+---+---+ + | | + : partial_state_identifier_n : + | | + +---+---+---+---+---+---+---+---+ + */ + + if(returned_parameters_location >= udvm_size){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_SEGFAULT].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); + return tsk_false; + } + + /* cpb+dms+sms */ + r_p_l = *TCOMP_UDVM_GET_BUFFER_AT(returned_parameters_location); + returned_parameters_location++; + if(r_p_l){ + tcomp_params_setCpbCode(udvm->lpResult->remote_parameters, ((r_p_l & 0xc0)>>6)); + tcomp_params_setDmsCode(udvm->lpResult->remote_parameters, ((r_p_l & 0x38)>>3)); + tcomp_params_setSmsCode(udvm->lpResult->remote_parameters, (r_p_l & 0x07)); + } + /* sigcomp version */ + SigComp_version = *TCOMP_UDVM_GET_BUFFER_AT(returned_parameters_location); + returned_parameters_location++; + if(SigComp_version){ + udvm->lpResult->remote_parameters->SigComp_version = SigComp_version; + } + /* state items */ + for(index = returned_parameters_location; index <(udvm_size-1); ){ + uint8_t length, *length_ptr = TCOMP_UDVM_GET_BUFFER_AT(index); + if(!length_ptr){ + return tsk_false; + } + length = *length_ptr; // 1-byte + if(length<6 || length>20){ + break; + } + index++; + if((index+length) >= (uint32_t)udvm_size){ + TSK_DEBUG_ERROR("%s", TCOMP_NACK_DESCRIPTIONS[NACK_SEGFAULT].desc); + tcomp_udvm_createNackInfo2(udvm, NACK_SEGFAULT); + return tsk_false; + } + partial_id = tcomp_buffer_create_null(); + tcomp_buffer_allocBuff(partial_id, length); + if(!tcomp_udvm_bytecopy_from(udvm, tcomp_buffer_getBuffer(partial_id), index, length)){ + return tsk_false; + } + if(!udvm->lpResult->remote_parameters->returnedStates){ + udvm->lpResult->remote_parameters->returnedStates = tsk_list_create(); + } + tsk_list_push_back_data(udvm->lpResult->remote_parameters->returnedStates, (void**)&partial_id); + index += length; + } + } + + return tsk_true; +} + diff --git a/tinySIGCOMP/src/tcomp_udvm.nack.c b/tinySIGCOMP/src/tcomp_udvm.nack.c new file mode 100644 index 0000000..a195a41 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_udvm.nack.c @@ -0,0 +1,56 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop +* Copyright (C) 2011-2013 Doubango Telecom <http://www.doubango.org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_udvm.nack.c + * @brief SigComp UDVM machine (NACK). + * + */ +#include "tcomp_udvm.h" + +#include "tsk_debug.h" + +int tcomp_udvm_createNackInfo(tcomp_udvm_t *udvm, uint8_t reasonCode, tcomp_buffer_handle_t* lpDetails, int16_t memory_address_of_instruction) +{ + uint32_t mem_add_instruction; + int ret; + + if(!udvm){ + TSK_DEBUG_ERROR("Invalid parameter"); + return -1; + } + + tcomp_buffer_allocBuff(udvm->lpResult->nack_info, INDEX_NACK_SHA1 + TSK_SHA1_DIGEST_SIZE); + mem_add_instruction = (memory_address_of_instruction >=0) ? memory_address_of_instruction : udvm->last_memory_address_of_instruction; + + if((ret = tcomp_nackinfo_write_2(udvm->lpResult->nack_info, + reasonCode, + *TCOMP_UDVM_GET_BUFFER_AT(mem_add_instruction), + mem_add_instruction, + udvm->sigCompMessage, + lpDetails, + TCOMP_UDVM_GET_SIZE(), + udvm->stateHandler->sigcomp_parameters->cpbValue)) == 0) + { + udvm->lpResult->isNack = 1; + } + + return ret; +}
\ No newline at end of file diff --git a/tinySIGCOMP/src/tcomp_udvm.operands.c b/tinySIGCOMP/src/tcomp_udvm.operands.c new file mode 100644 index 0000000..4d15d8c --- /dev/null +++ b/tinySIGCOMP/src/tcomp_udvm.operands.c @@ -0,0 +1,261 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_udvm.operands.c + * @brief SigComp UDVM machine (Operands). + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_udvm.h" + +#include "tsk_debug.h" + +#include <math.h> + +/** +literal (#)<br> +<table> +<tr> <td>Bytecode</td> <td>Operand value</td> <td>Range</td></tr> +<tr> <td>0nnnnnnn</td> <td>N</td> <td>0 - 127</td></tr> +<tr> <td>10nnnnnn nnnnnnnn</td> <td>N</td> <td>0 - 16383</td></tr> +<tr> <td>11000000 nnnnnnnn nnnnnnnn</td> <td>N</td> <td>0 - 65535</td></tr> +</table> +*/ +uint32_t tcomp_udvm_opget_literal_param(tcomp_udvm_t *udvm) +{ + uint32_t result = 0; + const uint8_t* memory_ptr = TCOMP_UDVM_GET_BUFFER_AT(udvm->executionPointer); + + switch( *memory_ptr & 0xc0) // 2 first bits + { + case 0x00: // 0nnnnnnn N 0 - 127 + case 0x40: // 0nnnnnnn N 0 - 127 + { + result = *(memory_ptr); + udvm->executionPointer++; + } + break; + + case 0x80: // 10nnnnnn nnnnnnnn N 0 - 16383 + { + result = TSK_BINARY_GET_2BYTES(memory_ptr)&0x3fff; // All except 2 first bits + udvm->executionPointer+=2; + } + break; + + case 0xc0: // 11000000 nnnnnnnn nnnnnnnn N 0 - 65535 + { + result = TSK_BINARY_GET_2BYTES((memory_ptr+1)); + udvm->executionPointer+=3; + } + break; + + default: + { + TSK_DEBUG_ERROR("Invalide opcode: %u", *memory_ptr); + tcomp_udvm_createNackInfo2(udvm, NACK_INVALID_OPERAND); + } + break; + } + return result; +} + +/** +reference ($)<br> +<table> +<tr><td>Bytecode</td> <td>Operand value</td> <td>Range</td></tr> +<tr><td>0nnnnnnn</td> <td>memory[2 * N]</td> <td>0 - 65535</td></tr> +<tr><td>10nnnnnn nnnnnnnn </td> <td>memory[2 * N]</td> <td>0 - 65535</td></tr> +<tr><td>11000000 nnnnnnnn nnnnnnnn</td> <td>memory[N]</td> <td>0 - 65535</td></tr> +</table> +*/ +uint32_t tcomp_udvm_opget_reference_param(tcomp_udvm_t *udvm) +{ + const uint8_t* memory_ptr = TCOMP_UDVM_GET_BUFFER_AT(udvm->executionPointer); + uint32_t result = 0; + + switch( *memory_ptr & 0xc0) // 2 first bits + { + case 0x00: // 0nnnnnnn memory[2 * N] 0 - 65535 + case 0x40: // 0nnnnnnn memory[2 * N] 0 - 65535 + { + uint8_t N = (*(memory_ptr) & 0x7f); // no effect first bit is already nil + result = 2*N; + udvm->executionPointer++; + } + break; + + case 0x80: // 10nnnnnn nnnnnnnn memory[2 * N] 0 - 65535 + { + uint32_t N = (TSK_BINARY_GET_2BYTES(memory_ptr) & 0x3fff); + result = 2*N; + udvm->executionPointer+=2; + } + break; + + case 0xc0: // 11000000 nnnnnnnn nnnnnnnn memory[N] 0 - 65535 + { + uint32_t N = TSK_BINARY_GET_2BYTES(memory_ptr+1); + result = N; + udvm->executionPointer+=3; + } + break; + + default: + { + TSK_DEBUG_ERROR("Invalide opcode: %u", *memory_ptr); + tcomp_udvm_createNackInfo2(udvm, NACK_INVALID_OPERAND); + } + break; + } + + return result; +} + +/** +multitype(%)<br> +<table> +<tr><td>Bytecode</td> <td>Operand value</td> <td>Range</td></tr> +<tr><td>00nnnnnn</td> <td>N</td> <td>0 - 63</td></tr> +<tr><td>01nnnnnn</td> <td>memory[2 * N]</td> <td>0 - 65535</td></tr> +<tr><td>1000011n</td> <td>2 ^ (N + 6)</td> <td>64 , 128</td></tr> +<tr><td>10001nnn</td> <td>2 ^ (N + 8)</td> <td>256 , ... , 32768</td></tr> +<tr><td>111nnnnn</td> <td>N + 65504</td> <td>65504 - 65535</td></tr> +<tr><td>1001nnnn nnnnnnnn</td> <td>N + 61440</td> <td>61440 - 65535</td></tr> +<tr><td>101nnnnn nnnnnnnn</td> <td>N</td> <td>0 - 8191</td></tr> +<tr><td>110nnnnn nnnnnnnn</td> <td>memory[N]</td> <td>0 - 65535</td></tr> +<tr><td>10000000 nnnnnnnn nnnnnnnn</td> <td>N</td> <td>0 - 65535</td></tr> +<tr><td>10000001 nnnnnnnn nnnnnnnn</td> <td>memory[N]</td> <td>0 - 65535</td></tr> +</table> +*/ +uint32_t tcomp_udvm_opget_multitype_param(tcomp_udvm_t *udvm) +{ + const uint8_t* memory_ptr = TCOMP_UDVM_GET_BUFFER_AT(udvm->executionPointer); + int8_t index = operand_multitype_indexes[*memory_ptr]; + uint32_t result = 0; + + switch(index) + { + case 1: // 00nnnnnn N 0 - 63 + { + result = *(memory_ptr); + udvm->executionPointer++; + } + break; + + case 2: // 01nnnnnn memory[2 * N] 0 - 65535 + { + uint8_t N = (*(memory_ptr) & 0x3f); + result = TSK_BINARY_GET_2BYTES( TCOMP_UDVM_GET_BUFFER_AT(2*N) ); + udvm->executionPointer++; + } + break; + + case 3: // 1000011n 2 ^ (N + 6) 64 , 128 + { + uint8_t N = (*(memory_ptr) & 0x01); + result = (uint32_t)pow( (double)2, (N + 6) ); + udvm->executionPointer++; + } + break; + + case 4: // 10001nnn 2 ^ (N + 8) 256 , ... , 32768 + { + uint8_t N = (*(memory_ptr) & 0x07); + result = (uint32_t)pow( (double)2, (N + 8) ); + udvm->executionPointer++; + } + break; + + case 5: // 111nnnnn N + 65504 65504 - 65535 + { + result = ((*(memory_ptr) & 0x1f) + 65504 ); + udvm->executionPointer++; + } + break; + + case 6: // 1001nnnn nnnnnnnn N + 61440 61440 - 65535 + { + result = (TSK_BINARY_GET_2BYTES(memory_ptr) & 0x0fff) + 61440; + udvm->executionPointer+=2; + } + break; + + case 7: // 101nnnnn nnnnnnnn N 0 - 8191 + { + result = (TSK_BINARY_GET_2BYTES(memory_ptr) & 0x1fff); + udvm->executionPointer+=2; + } + break; + + case 8: // 110nnnnn nnnnnnnn memory[N] 0 - 65535 + { + uint32_t N = TSK_BINARY_GET_2BYTES(memory_ptr) & 0x1fff; + result = TSK_BINARY_GET_2BYTES( TCOMP_UDVM_GET_BUFFER_AT(N) ); + udvm->executionPointer+=2; + } + break; + + case 9: // 10000000 nnnnnnnn nnnnnnnn N 0 - 65535 + { + result = TSK_BINARY_GET_2BYTES(memory_ptr+1); + udvm->executionPointer+=3; + } + break; + + case 10: // 10000001 nnnnnnnn nnnnnnnn memory[N] 0 - 65535 + { + uint32_t N = TSK_BINARY_GET_2BYTES(memory_ptr+1); + result = TSK_BINARY_GET_2BYTES( TCOMP_UDVM_GET_BUFFER_AT(N) ); + udvm->executionPointer+=3; + } + break; + + default: // -1 + { + TSK_DEBUG_ERROR("Invalide opcode: %u", *memory_ptr); + tcomp_udvm_createNackInfo2(udvm, NACK_INVALID_OPERAND); + } + break; + } + + return result; +} + +/** +address(@) +This operand is decoded as a multitype operand followed by a further step: the memory address +of the UDVM instruction containing the address operand is added to +obtain the correct operand value. So if the operand value from +Figure 10 is D then the actual operand value of an address is +calculated as follows: + + operand_value = (memory_address_of_instruction + D) modulo 2^16 +*/ +uint32_t tcomp_udvm_opget_address_param(tcomp_udvm_t *udvm, uint32_t memory_address_of_instruction) +{ + uint32_t D = tcomp_udvm_opget_multitype_param(udvm); + // (2^16) => 65536; + return ( (memory_address_of_instruction + D)%65536 ); +} diff --git a/tinySIGCOMP/src/tcomp_udvm.statemanagment.c b/tinySIGCOMP/src/tcomp_udvm.statemanagment.c new file mode 100644 index 0000000..2644c54 --- /dev/null +++ b/tinySIGCOMP/src/tcomp_udvm.statemanagment.c @@ -0,0 +1,134 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +/**@file tcomp_udvm.statemanagment.c + * @brief SigComp UDVM machine (State managment) + * + * @author Mamadou Diop <diopmamadou(at)yahoo.fr> + * + + */ +#include "tcomp_udvm.h" + + +int tcomp_udvm_byteCopy_TempStates(tcomp_udvm_t *udvm) +{ + int ok = 1; + uint8_t i; + uint8_t tocreate_size = tcomp_result_getTempStatesToCreateSize(udvm->lpResult); + uint8_t tofree_size = tcomp_result_getTempStatesToFreeSize(udvm->lpResult); + + + /* + * State Create + */ + for(i = 0; i < tocreate_size && ok; i++) + { + /* + * The UDVM byte copies a string of state_length bytes from the UDVM + * memory beginning at state_address (obeying the rules of Section 8.4). + * This is the state_value. + */ + tcomp_state_t* lpState = udvm->lpResult->statesToCreate[i]; + if(lpState->length){ + tcomp_buffer_allocBuff(lpState->value, lpState->length); + } + + ok &= tcomp_udvm_bytecopy_from(udvm, tcomp_buffer_getBuffer(lpState->value), lpState->address, lpState->length); + } + + /* + * State Free + */ + for(i = 0; i<tofree_size && ok; i++){ + tcomp_tempstate_to_free_t *lpDesc = udvm->lpResult->statesToFree[i]; + tcomp_buffer_allocBuff(lpDesc->identifier, lpDesc->partial_identifier_length); + ok &= tcomp_udvm_bytecopy_from(udvm, tcomp_buffer_getBuffer(lpDesc->identifier), lpDesc->partial_identifier_start, lpDesc->partial_identifier_length); + } + return ok; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +/// +/// @brief Creates temporary state. +/// +/// @param [in,out] udvm If non-null, the udvm. +/// @param state_length Length of the state. +/// @param state_address The state address. +/// @param state_instruction The state instruction. +/// @param minimum_access_length Length of the minimum access. +/// @param state_retention_priority The state retention priority. +/// @param end_msg Message describing the end. +/// +/// @return 1 if succeed an zero otherwise. +//////////////////////////////////////////////////////////////////////////////////////////////////// + +int tcomp_udvm_createTempState(tcomp_udvm_t *udvm, uint32_t state_length, uint32_t state_address, uint32_t state_instruction, + uint32_t minimum_access_length, uint32_t state_retention_priority, int end_msg) +{ + /* + * If the specified minimum_access_length does not lie between 6 and 20 inclusive, or if + * the state_retention_priority is 65535 then the END-MESSAGE + * instruction fails to make a state creation request of its own + * (however decompression failure does not occur and the state creation + * requests made by the STATE-CREATE instruction are still valid). + */ + int is_ok = ( (6<=minimum_access_length && minimum_access_length<=20) && state_retention_priority!=65535 ); + + // if not ok and not END_MESSAGE --> decompression failure MUST occurs + if(!is_ok) + { + if(end_msg) return 1; + + if(state_retention_priority == 65535) + { + tcomp_udvm_createNackInfo2(udvm, NACK_INVALID_STATE_PRIORITY); + } + else + { + tcomp_udvm_createNackInfo2(udvm, NACK_INVALID_STATE_ID_LENGTH); + } + return 0; + } + + /* + * decompression failure occurs if the END-MESSAGE instruction makes a state creation request and four + * instances of the STATE-CREATE instruction have already been encountered. + */ + if(tcomp_result_getTempStatesToCreateSize(udvm->lpResult) >= MAX_TEMP_SATES) + { + tcomp_udvm_createNackInfo2(udvm, NACK_TOO_MANY_STATE_REQUESTS); + return 0; + } + + /* + * Is there a state to create? + */ + if(is_ok) + { + // no byte copy () + tcomp_state_t *lpState = tcomp_state_create(state_length, state_address, state_instruction, minimum_access_length, state_retention_priority); + tcomp_result_addTempStateToCreate(udvm->lpResult, lpState); + } + + return 1; +} diff --git a/tinySIGCOMP/src/tinysigcomp_config.h b/tinySIGCOMP/src/tinysigcomp_config.h new file mode 100644 index 0000000..833b7b2 --- /dev/null +++ b/tinySIGCOMP/src/tinysigcomp_config.h @@ -0,0 +1,106 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop <diopmamadou(at)doubango[dot]org> +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* DOUBANGO is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with DOUBANGO. +* +*/ + +#ifndef TINYSIGCOMP_CONFIG_H +#define TINYSIGCOMP_CONFIG_H + +#ifdef __SYMBIAN32__ +#undef _WIN32 /* Because of WINSCW */ +#endif + +// Windows (XP/Vista/7/CE and Windows Mobile) macro definition. +#if defined(WIN32)|| defined(_WIN32) || defined(_WIN32_WCE) +# define TCOMP_UNDER_WINDOWS 1 +# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP || WINAPI_FAMILY == WINAPI_FAMILY_APP) +# define TCOMP_UNDER_WINDOWS_RT 1 +# endif +#endif + +#if !defined(__GNUC__) && defined(TINYSIGCOMP_EXPORTS) +# define TINYSIGCOMP_API __declspec(dllexport) +# define TINYSIGCOMP_GEXTERN __declspec(dllexport) +#elif !defined(__GNUC__) && !defined(TINYSIGCOMP_IMPORTS_IGNORE) +# define TINYSIGCOMP_API __declspec(dllimport) +# define TINYSIGCOMP_GEXTERN __declspec(dllimport) +#else +# define TINYSIGCOMP_API +# define TINYSIGCOMP_GEXTERN extern +#endif + +/* Guards against C++ name mangling +*/ +#ifdef __cplusplus +# define TCOMP_BEGIN_DECLS extern "C" { +# define TCOMP_END_DECLS } +#else +# define TCOMP_BEGIN_DECLS +# define TCOMP_END_DECLS +#endif + +/* DEFLATE block type 01 (data compressed with fixed Huffman codes) +*/ +#ifndef FORCE_STATIC +# define FORCE_STATIC /*zlib*/ +#endif + +// avoid linking in the crc code +#define NO_GZIP + +// +// Nack - RFC 4077 +// +#if !defined(NACK_VERSION) +# define NACK_VERSION 0x01 +#endif +#if !defined(NACK_MAX_HISTORY_SIZE) +# define NACK_MAX_HISTORY_SIZE 0x14 +#endif + +// +// Feedbacks +// +#if !defined(TCOMP_USE_ONLY_ACKED_STATES) +# define TCOMP_USE_ONLY_ACKED_STATES 0 +#endif + +/* Disable some well-known warnings +*/ +#ifdef _MSC_VER +# define _CRT_SECURE_NO_WARNINGS +#endif + +#if defined(_MSC_VER) +# define TCOMP_INLINE __forceinline +#elif defined(__GNUC__) && !defined(__APPLE__) +# define TCOMP_INLINE __inline +#else +# define TCOMP_INLINE +#endif + +#include <stdint.h> + +#if HAVE_CONFIG_H + #include <config.h> +#endif + +#endif // TINYSIGCOMP_CONFIG_H + diff --git a/tinySIGCOMP/src/trees.c b/tinySIGCOMP/src/trees.c new file mode 100644 index 0000000..fe8eda7 --- /dev/null +++ b/tinySIGCOMP/src/trees.c @@ -0,0 +1,1222 @@ +#if !HAS_ZLIB +/* trees.c -- output deflated data using Huffman coding + * Copyright (C) 1995-2005 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process uses several Huffman trees. The more + * common source values are represented by shorter bit sequences. + * + * Each code tree is stored in a compressed form which is itself + * a Huffman encoding of the lengths of all the code strings (in + * ascending order by source values). The actual code strings are + * reconstructed from the lengths in the inflate process, as described + * in the deflate specification. + * + * REFERENCES + * + * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". + * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc + * + * Storer, James A. + * Data Compression: Methods and Theory, pp. 49-50. + * Computer Science Press, 1988. ISBN 0-7167-8156-5. + * + * Sedgewick, R. + * Algorithms, p290. + * Addison-Wesley, 1983. ISBN 0-201-06672-6. + */ + +/* @(#) $Id$ */ + +/* #define GEN_TREES_H */ + +#include "deflate.h" + +#ifdef DEBUG +# include <ctype.h> +#endif + +/* =========================================================================== + * Constants + */ + +#define MAX_BL_BITS 7 +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +#define END_BLOCK 256 +/* end of block literal code */ + +#define REP_3_6 16 +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +#define REPZ_3_10 17 +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +#define REPZ_11_138 18 +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ + = {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,0}; + +local const int extra_dbits[D_CODES] /* extra bits for each distance code */ + = {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}; + +local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ + = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; + +local const uch bl_order[BL_CODES] + = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +#define Buf_size (8 * 2*sizeof(char)) +/* Number of bits used within bi_buf. (bi_buf might be implemented on + * more than 16 bits on some systems.) + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ + +#if defined(GEN_TREES_H) || !defined(STDC) +/* non ANSI compilers may not accept trees.h */ + +local ct_data static_ltree[L_CODES+2]; +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +local ct_data static_dtree[D_CODES]; +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +uch _dist_code[DIST_CODE_LEN]; +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +uch _length_code[MAX_MATCH-MIN_MATCH+1]; +/* length code for each normalized match length (0 == MIN_MATCH) */ + +local int base_length[LENGTH_CODES]; +/* First normalized length for each code (0 = MIN_MATCH) */ + +local int base_dist[D_CODES]; +/* First normalized distance for each code (0 = distance of 1) */ + +#else +# include "trees.h" +#endif /* GEN_TREES_H */ + +struct static_tree_desc_s { + const ct_data *static_tree; /* static tree or NULL */ + const intf *extra_bits; /* extra bits for each code or NULL */ + int extra_base; /* base index for extra_bits */ + int elems; /* max number of elements in the tree */ + int max_length; /* max bit length for the codes */ +}; + +local static_tree_desc static_l_desc = +{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; + +local static_tree_desc static_d_desc = +{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; + +local static_tree_desc static_bl_desc = +{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; + +/* =========================================================================== + * Local (static) routines in this file. + */ + +local void tr_static_init OF((void)); +local void init_block OF((deflate_state *s)); +local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); +local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); +local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); +local void build_tree OF((deflate_state *s, tree_desc *desc)); +local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local int build_bl_tree OF((deflate_state *s)); +local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, + int blcodes)); +local void compress_block OF((deflate_state *s, ct_data *ltree, + ct_data *dtree)); +local void set_data_type OF((deflate_state *s)); +local unsigned bi_reverse OF((unsigned value, int length)); +local void bi_windup OF((deflate_state *s)); +local void bi_flush OF((deflate_state *s)); +local void copy_block OF((deflate_state *s, charf *buf, unsigned len, + int header)); + +#ifdef GEN_TREES_H +local void gen_trees_header OF((void)); +#endif + +#ifndef DEBUG +# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) + /* Send a code of the given tree. c and tree must not have side effects */ + +#else /* DEBUG */ +# define send_code(s, c, tree) \ + { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ + send_bits(s, tree[c].Code, tree[c].Len); } +#endif + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +#define put_short(s, w) { \ + put_byte(s, (uch)((w) & 0xff)); \ + put_byte(s, (uch)((ush)(w) >> 8)); \ +} + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +#ifdef DEBUG +local void send_bits OF((deflate_state *s, int value, int length)); + +local void send_bits(s, value, length) + deflate_state *s; + int value; /* value to send */ + int length; /* number of bits */ +{ + Tracevv((stderr," l %2d v %4x ", length, value)); + Assert(length > 0 && length <= 15, "invalid length"); + s->bits_sent += (ulg)length; + + /* If not enough room in bi_buf, use (valid) bits from bi_buf and + * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) + * unused bits in value. + */ + if (s->bi_valid > (int)Buf_size - length) { + s->bi_buf |= (value << s->bi_valid); + put_short(s, s->bi_buf); + s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); + s->bi_valid += length - Buf_size; + } else { + s->bi_buf |= value << s->bi_valid; + s->bi_valid += length; + } +} +#else /* !DEBUG */ + +#define send_bits(s, value, length) \ +{ int len = length;\ + if (s->bi_valid > (int)Buf_size - len) {\ + int val = value;\ + s->bi_buf |= (val << s->bi_valid);\ + put_short(s, s->bi_buf);\ + s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ + s->bi_valid += len - Buf_size;\ + } else {\ + s->bi_buf |= (value) << s->bi_valid;\ + s->bi_valid += len;\ + }\ +} +#endif /* DEBUG */ + + +/* the arguments must not have side effects */ + +/* =========================================================================== + * Initialize the various 'constant' tables. + */ +local void tr_static_init() +{ +#if defined(GEN_TREES_H) || !defined(STDC) + static int static_init_done = 0; + int n; /* iterates over tree elements */ + int bits; /* bit counter */ + int length; /* length value */ + int code; /* code value */ + int dist; /* distance index */ + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + if (static_init_done) return; + + /* For some embedded targets, global variables are not initialized: */ + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES-1; code++) { + base_length[code] = length; + for (n = 0; n < (1<<extra_lbits[code]); n++) { + _length_code[length++] = (uch)code; + } + } + Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length-1] = (uch)code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0 ; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1<<extra_dbits[code]); n++) { + _dist_code[dist++] = (uch)code; + } + } + Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for ( ; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { + _dist_code[256 + dist++] = (uch)code; + } + } + Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; + n = 0; + while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; + while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; + while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; + while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n].Len = 5; + static_dtree[n].Code = bi_reverse((unsigned)n, 5); + } + static_init_done = 1; + +# ifdef GEN_TREES_H + gen_trees_header(); +# endif +#endif /* defined(GEN_TREES_H) || !defined(STDC) */ +} + +/* =========================================================================== + * Genererate the file trees.h describing the static trees. + */ +#ifdef GEN_TREES_H +# ifndef DEBUG +# include <stdio.h> +# endif + +# define SEPARATOR(i, last, width) \ + ((i) == (last)? "\n};\n\n" : \ + ((i) % (width) == (width)-1 ? ",\n" : ", ")) + +void gen_trees_header() +{ + FILE *header = fopen("trees.h", "w"); + int i; + + Assert (header != NULL, "Can't open trees.h"); + fprintf(header, + "/* header created automatically with -DGEN_TREES_H */\n\n"); + + fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); + for (i = 0; i < L_CODES+2; i++) { + fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, + static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); + } + + fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, + static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); + } + + fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n"); + for (i = 0; i < DIST_CODE_LEN; i++) { + fprintf(header, "%2u%s", _dist_code[i], + SEPARATOR(i, DIST_CODE_LEN-1, 20)); + } + + fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); + for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { + fprintf(header, "%2u%s", _length_code[i], + SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); + } + + fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); + for (i = 0; i < LENGTH_CODES; i++) { + fprintf(header, "%1u%s", base_length[i], + SEPARATOR(i, LENGTH_CODES-1, 20)); + } + + fprintf(header, "local const int base_dist[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "%5u%s", base_dist[i], + SEPARATOR(i, D_CODES-1, 10)); + } + + fclose(header); +} +#endif /* GEN_TREES_H */ + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +void _tr_init(s) + deflate_state *s; +{ + tr_static_init(); + + s->l_desc.dyn_tree = s->dyn_ltree; + s->l_desc.stat_desc = &static_l_desc; + + s->d_desc.dyn_tree = s->dyn_dtree; + s->d_desc.stat_desc = &static_d_desc; + + s->bl_desc.dyn_tree = s->bl_tree; + s->bl_desc.stat_desc = &static_bl_desc; + + s->bi_buf = 0; + s->bi_valid = 0; + s->last_eob_len = 8; /* enough lookahead for inflate */ +#ifdef DEBUG + s->compressed_len = 0L; + s->bits_sent = 0L; +#endif + + /* Initialize the first block of the first file: */ + init_block(s); +} + +/* =========================================================================== + * Initialize a new block. + */ +local void init_block(s) + deflate_state *s; +{ + int n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; + for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; + for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; + + s->dyn_ltree[END_BLOCK].Freq = 1; + s->opt_len = s->static_len = 0L; + s->last_lit = s->matches = 0; +} + +#define SMALLEST 1 +/* Index within the heap array of least frequent node in the Huffman tree */ + + +/* =========================================================================== + * Remove the smallest element from the heap and recreate the heap with + * one less element. Updates heap and heap_len. + */ +#define pqremove(s, tree, top) \ +{\ + top = s->heap[SMALLEST]; \ + s->heap[SMALLEST] = s->heap[s->heap_len--]; \ + pqdownheap(s, tree, SMALLEST); \ +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +#define smaller(tree, n, m, depth) \ + (tree[n].Freq < tree[m].Freq || \ + (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +local void pqdownheap(s, tree, k) + deflate_state *s; + ct_data *tree; /* the tree to restore */ + int k; /* node to move down */ +{ + int v = s->heap[k]; + int j = k << 1; /* left son of k */ + while (j <= s->heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s->heap_len && + smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s->heap[j], s->depth)) break; + + /* Exchange v with the smallest son */ + s->heap[k] = s->heap[j]; k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s->heap[k] = v; +} + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +local void gen_bitlen(s, desc) + deflate_state *s; + tree_desc *desc; /* the tree descriptor */ +{ + ct_data *tree = desc->dyn_tree; + int max_code = desc->max_code; + const ct_data *stree = desc->stat_desc->static_tree; + const intf *extra = desc->stat_desc->extra_bits; + int base = desc->stat_desc->extra_base; + int max_length = desc->stat_desc->max_length; + int h; /* heap index */ + int n, m; /* iterate over the tree elements */ + int bits; /* bit length */ + int xbits; /* extra bits */ + ush f; /* frequency */ + int overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ + + for (h = s->heap_max+1; h < HEAP_SIZE; h++) { + n = s->heap[h]; + bits = tree[tree[n].Dad].Len + 1; + if (bits > max_length) bits = max_length, overflow++; + tree[n].Len = (ush)bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) continue; /* not a leaf node */ + + s->bl_count[bits]++; + xbits = 0; + if (n >= base) xbits = extra[n-base]; + f = tree[n].Freq; + s->opt_len += (ulg)f * (bits + xbits); + if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); + } + if (overflow == 0) return; + + Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length-1; + while (s->bl_count[bits] == 0) bits--; + s->bl_count[bits]--; /* move one leaf down the tree */ + s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ + s->bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits != 0; bits--) { + n = s->bl_count[bits]; + while (n != 0) { + m = s->heap[--h]; + if (m > max_code) continue; + if ((unsigned) tree[m].Len != (unsigned) bits) { + Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s->opt_len += ((long)bits - (long)tree[m].Len) + *(long)tree[m].Freq; + tree[m].Len = (ush)bits; + } + n--; + } + } +} + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +local void gen_codes (tree, max_code, bl_count) + ct_data *tree; /* the tree to decorate */ + int max_code; /* largest code with non zero frequency */ + ushf *bl_count; /* number of codes at each bit length */ +{ + ush next_code[MAX_BITS+1]; /* next code value for each bit length */ + ush code = 0; /* running code value */ + int bits; /* bit index */ + int n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits-1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, + "inconsistent bit counts"); + Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); + + for (n = 0; n <= max_code; n++) { + int len = tree[n].Len; + if (len == 0) continue; + /* Now reverse the bits */ + tree[n].Code = bi_reverse(next_code[len]++, len); + + Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", + n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); + } +} + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +local void build_tree(s, desc) + deflate_state *s; + tree_desc *desc; /* the tree descriptor */ +{ + ct_data *tree = desc->dyn_tree; + const ct_data *stree = desc->stat_desc->static_tree; + int elems = desc->stat_desc->elems; + int n, m; /* iterate over heap elements */ + int max_code = -1; /* largest code with non zero frequency */ + int node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s->heap_len = 0, s->heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n].Freq != 0) { + s->heap[++(s->heap_len)] = max_code = n; + s->depth[n] = 0; + } else { + tree[n].Len = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s->heap_len < 2) { + node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); + tree[node].Freq = 1; + s->depth[node] = 0; + s->opt_len--; if (stree) s->static_len -= stree[node].Len; + /* node is 0 or 1 so it does not have extra bits */ + } + desc->max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + pqremove(s, tree, n); /* n = node of least frequency */ + m = s->heap[SMALLEST]; /* m = node of next least frequency */ + + s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ + s->heap[--(s->heap_max)] = m; + + /* Create a new node father of n and m */ + tree[node].Freq = tree[n].Freq + tree[m].Freq; + s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? + s->depth[n] : s->depth[m]) + 1); + tree[n].Dad = tree[m].Dad = (ush)node; +#ifdef DUMP_BL_TREE + if (tree == s->bl_tree) { + fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", + node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); + } +#endif + /* and insert the new node in the heap */ + s->heap[SMALLEST] = node++; + pqdownheap(s, tree, SMALLEST); + + } while (s->heap_len >= 2); + + s->heap[--(s->heap_max)] = s->heap[SMALLEST]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, (tree_desc *)desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes ((ct_data *)tree, max_code, s->bl_count); +} + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +local void scan_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + if (nextlen == 0) max_count = 138, min_count = 3; + tree[max_code+1].Len = (ush)0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + s->bl_tree[curlen].Freq += count; + } else if (curlen != 0) { + if (curlen != prevlen) s->bl_tree[curlen].Freq++; + s->bl_tree[REP_3_6].Freq++; + } else if (count <= 10) { + s->bl_tree[REPZ_3_10].Freq++; + } else { + s->bl_tree[REPZ_11_138].Freq++; + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +local void send_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen == 0) max_count = 138, min_count = 3; + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + do { send_code(s, curlen, s->bl_tree); } while (--count != 0); + + } else if (curlen != 0) { + if (curlen != prevlen) { + send_code(s, curlen, s->bl_tree); count--; + } + Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); + + } else { + send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +local int build_bl_tree(s) + deflate_state *s; +{ + int max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); + scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, (tree_desc *)(&(s->bl_desc))); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { + if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; + } + /* Update opt_len to include the bit length tree and counts */ + s->opt_len += 3*(max_blindex+1) + 5+5+4; + Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + s->opt_len, s->static_len)); + + return max_blindex; +} + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +local void send_all_trees(s, lcodes, dcodes, blcodes) + deflate_state *s; + int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + int rank; /* index in bl_order */ + + Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + "too many codes"); + Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes-1, 5); + send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); + } + Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ + Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ + Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + +/* =========================================================================== + * Send a stored block + */ +void _tr_stored_block(s, buf, stored_len, eof) + deflate_state *s; + charf *buf; /* input block */ + ulg stored_len; /* length of input block */ + int eof; /* true if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */ +#ifdef DEBUG + s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; + s->compressed_len += (stored_len + 4) << 3; +#endif + copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ +} + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + * The current inflate code requires 9 bits of lookahead. If the + * last two codes for the previous block (real code plus EOB) were coded + * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode + * the last real code. In this case we send two empty static blocks instead + * of one. (There are no problems if the previous block is stored or fixed.) + * To simplify the code, we assume the worst case of last real code encoded + * on one bit only. + */ +void _tr_align(s) + deflate_state *s; +{ + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); +#ifdef DEBUG + s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ +#endif + bi_flush(s); + /* Of the 10 bits for the empty block, we have already sent + * (10 - bi_valid) bits. The lookahead for the last real code (before + * the EOB of the previous block) was thus at least one plus the length + * of the EOB plus what we have just sent of the empty static block. + */ + if (1 + s->last_eob_len + 10 - s->bi_valid < 9) { + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); +#ifdef DEBUG + s->compressed_len += 10L; +#endif + bi_flush(s); + } + s->last_eob_len = 7; +} + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +void _tr_flush_block(s, buf, stored_len, eof) + deflate_state *s; + charf *buf; /* input block, or NULL if too old */ + ulg stored_len; /* length of input block */ + int eof; /* true if this is the last block for a file */ +{ + ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + int max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s->level > 0) { + + /* Check if the file is binary or text */ + if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN) + set_data_type(s); + + /* Construct the literal and distance trees */ + build_tree(s, (tree_desc *)(&(s->l_desc))); + Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + + build_tree(s, (tree_desc *)(&(s->d_desc))); + Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s->opt_len+3+7)>>3; + static_lenb = (s->static_len+3+7)>>3; + + Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + s->last_lit)); + + if (static_lenb <= opt_lenb) opt_lenb = static_lenb; + + } else { + Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + +#ifdef FORCE_STORED + if (buf != (char*)0) { /* force stored block */ +#else + if (stored_len+4 <= opt_lenb && buf != (char*)0) { + /* 4: two words for the lengths */ +#endif + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, eof); + +#ifdef FORCE_STATIC + } else if (static_lenb >= 0) { /* force static trees */ +#else + } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { +#endif + send_bits(s, (STATIC_TREES<<1)+eof, 3); + compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree); +#ifdef DEBUG + s->compressed_len += 3 + s->static_len; +#endif + } else { + send_bits(s, (DYN_TREES<<1)+eof, 3); + send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, + max_blindex+1); + compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree); +#ifdef DEBUG + s->compressed_len += 3 + s->opt_len; +#endif + } + Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (eof) { + bi_windup(s); +#ifdef DEBUG + s->compressed_len += 7; /* align on byte boundary */ +#endif + } + Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + s->compressed_len-7*eof)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +int _tr_tally (s, dist, lc) + deflate_state *s; + unsigned dist; /* distance of matched string */ + unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + s->d_buf[s->last_lit] = (ush)dist; + s->l_buf[s->last_lit++] = (uch)lc; + if (dist == 0) { + /* lc is the unmatched char */ + s->dyn_ltree[lc].Freq++; + } else { + s->matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + Assert((ush)dist < (ush)MAX_DIST(s) && + (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; + s->dyn_dtree[d_code(dist)].Freq++; + } + +#ifdef TRUNCATE_BLOCK + /* Try to guess if it is profitable to stop the current block here */ + if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { + /* Compute an upper bound for the compressed length */ + ulg out_length = (ulg)s->last_lit*8L; + ulg in_length = (ulg)((long)s->strstart - s->block_start); + int dcode; + for (dcode = 0; dcode < D_CODES; dcode++) { + out_length += (ulg)s->dyn_dtree[dcode].Freq * + (5L+extra_dbits[dcode]); + } + out_length >>= 3; + Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", + s->last_lit, in_length, out_length, + 100L - out_length*100L/in_length)); + if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; + } +#endif + return (s->last_lit == s->lit_bufsize-1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +local void compress_block(s, ltree, dtree) + deflate_state *s; + ct_data *ltree; /* literal tree */ + ct_data *dtree; /* distance tree */ +{ + unsigned dist; /* distance of matched string */ + int lc; /* match length or unmatched char (if dist == 0) */ + unsigned lx = 0; /* running index in l_buf */ + unsigned code; /* the code to send */ + int extra; /* number of extra bits to send */ + + if (s->last_lit != 0) do { + dist = s->d_buf[lx]; + lc = s->l_buf[lx++]; + if (dist == 0) { + send_code(s, lc, ltree); /* send a literal byte */ + Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code+LITERALS+1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra != 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra != 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + "pendingBuf overflow"); + + } while (lx < s->last_lit); + + send_code(s, END_BLOCK, ltree); + s->last_eob_len = ltree[END_BLOCK].Len; +} + +/* =========================================================================== + * Set the data type to BINARY or TEXT, using a crude approximation: + * set it to Z_TEXT if all symbols are either printable characters (33 to 255) + * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise. + * IN assertion: the fields Freq of dyn_ltree are set. + */ +local void set_data_type(s) + deflate_state *s; +{ + int n; + + for (n = 0; n < 9; n++) + if (s->dyn_ltree[n].Freq != 0) + break; + if (n == 9) + for (n = 14; n < 32; n++) + if (s->dyn_ltree[n].Freq != 0) + break; + s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY; +} + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +local unsigned bi_reverse(code, len) + unsigned code; /* the value to invert */ + int len; /* its bit length */ +{ + register unsigned res = 0; + do { + res |= code & 1; + code >>= 1, res <<= 1; + } while (--len > 0); + return res >> 1; +} + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +local void bi_flush(s) + deflate_state *s; +{ + if (s->bi_valid == 16) { + put_short(s, s->bi_buf); + s->bi_buf = 0; + s->bi_valid = 0; + } else if (s->bi_valid >= 8) { + put_byte(s, (Byte)s->bi_buf); + s->bi_buf >>= 8; + s->bi_valid -= 8; + } +} + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +local void bi_windup(s) + deflate_state *s; +{ + if (s->bi_valid > 8) { + put_short(s, s->bi_buf); + } else if (s->bi_valid > 0) { + put_byte(s, (Byte)s->bi_buf); + } + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef DEBUG + s->bits_sent = (s->bits_sent+7) & ~7; +#endif +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +local void copy_block(s, buf, len, header) + deflate_state *s; + charf *buf; /* the input data */ + unsigned len; /* its length */ + int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + s->last_eob_len = 8; /* enough lookahead for inflate */ + + if (header) { + put_short(s, (ush)len); + put_short(s, (ush)~len); +#ifdef DEBUG + s->bits_sent += 2*16; +#endif + } +#ifdef DEBUG + s->bits_sent += (ulg)len<<3; +#endif + while (len--) { + put_byte(s, *buf++); + } +} +#endif // HAS_ZLIB + diff --git a/tinySIGCOMP/src/trees.h b/tinySIGCOMP/src/trees.h new file mode 100644 index 0000000..f8ce546 --- /dev/null +++ b/tinySIGCOMP/src/trees.h @@ -0,0 +1,131 @@ +#if !HAS_ZLIB +/* header created automatically with -DGEN_TREES_H */ + +local const ct_data static_ltree[L_CODES+2] = { +{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, +{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, +{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, +{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, +{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, +{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, +{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, +{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, +{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, +{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, +{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, +{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, +{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, +{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, +{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, +{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, +{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, +{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, +{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, +{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, +{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, +{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, +{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, +{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, +{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, +{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, +{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, +{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, +{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, +{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, +{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, +{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, +{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, +{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, +{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, +{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, +{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, +{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, +{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, +{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, +{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, +{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, +{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, +{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, +{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, +{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, +{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, +{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, +{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, +{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, +{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, +{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, +{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, +{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, +{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, +{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, +{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, +{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} +}; + +local const ct_data static_dtree[D_CODES] = { +{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, +{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, +{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, +{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, +{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, +{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} +}; + +const uch _dist_code[DIST_CODE_LEN] = { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, + 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, +10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, +11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, +12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, +18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 +}; + +const uch _length_code[MAX_MATCH-MIN_MATCH+1]= { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, +13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, +17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, +19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, +21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, +22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 +}; + +local const int base_length[LENGTH_CODES] = { +0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, +64, 80, 96, 112, 128, 160, 192, 224, 0 +}; + +local const int base_dist[D_CODES] = { + 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, + 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, + 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 +}; + +#endif // HAS_ZLIB + diff --git a/tinySIGCOMP/src/zconf.h b/tinySIGCOMP/src/zconf.h new file mode 100644 index 0000000..789f0ed --- /dev/null +++ b/tinySIGCOMP/src/zconf.h @@ -0,0 +1,337 @@ +#if !HAS_ZLIB +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2005 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef ZCONF_H +#define ZCONF_H + +#include "tinysigcomp_config.h" + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + */ +#ifdef Z_PREFIX +# define deflateInit_ z_deflateInit_ +# define deflate z_deflate +# define deflateEnd z_deflateEnd +# define inflateInit_ z_inflateInit_ +# define inflate z_inflate +# define inflateEnd z_inflateEnd +# define deflateInit2_ z_deflateInit2_ +# define deflateSetDictionary z_deflateSetDictionary +# define deflateCopy z_deflateCopy +# define deflateReset z_deflateReset +# define deflateParams z_deflateParams +# define deflateBound z_deflateBound +# define deflatePrime z_deflatePrime +# define inflateInit2_ z_inflateInit2_ +# define inflateSetDictionary z_inflateSetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateCopy z_inflateCopy +# define inflateReset z_inflateReset +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# define uncompress z_uncompress +# define adler32 z_adler32 +# define crc32 z_crc32 +# define get_crc_table z_get_crc_table +# define zError z_zError + +# define alloc_func z_alloc_func +# define free_func z_free_func +# define in_func z_in_func +# define out_func z_out_func +# define Byte z_Byte +# define uInt z_uInt +# define uLong z_uLong +# define Bytef z_Bytef +# define charf z_charf +# define intf z_intf +# define uIntf z_uIntf +# define uLongf z_uLongf +# define voidpf z_voidpf +# define voidp z_voidp +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +/* Some Mac compilers merge all .h files incorrectly: */ +#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) +# define NO_DUMMY_DECL +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus a few kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) || defined(__SYMBIAN32__) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# include <windows.h> + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR CDECL +# endif +# endif +#endif + +#if defined (__BEOS__) +# ifdef ZLIB_DLL +# ifdef ZLIB_INTERNAL +# define ZEXPORT __declspec(dllexport) +# define ZEXPORTVA __declspec(dllexport) +# else +# define ZEXPORT __declspec(dllimport) +# define ZEXPORTVA __declspec(dllimport) +# endif +# endif +#endif + +#ifndef ZEXTERN +# define ZEXTERN extern +#endif +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */ +# include <sys/types.h> /* for off_t */ +# include <unistd.h> /* for SEEK_* and off_t */ +# ifdef VMS +# include <unixio.h> /* for off_t */ +# endif +# define z_off_t off_t +#endif +#ifndef SEEK_SET +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif +#ifndef z_off_t +# define z_off_t long +#endif + +#if defined(__OS400__) +# define NO_vsnprintf +#endif + +#if defined(__MVS__) +# define NO_vsnprintf +# ifdef FAR +# undef FAR +# endif +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) +# pragma map(deflateInit_,"DEIN") +# pragma map(deflateInit2_,"DEIN2") +# pragma map(deflateEnd,"DEEND") +# pragma map(deflateBound,"DEBND") +# pragma map(inflateInit_,"ININ") +# pragma map(inflateInit2_,"ININ2") +# pragma map(inflateEnd,"INEND") +# pragma map(inflateSync,"INSY") +# pragma map(inflateSetDictionary,"INSEDI") +# pragma map(compressBound,"CMBND") +# pragma map(inflate_table,"INTABL") +# pragma map(inflate_fast,"INFA") +# pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ +#endif // HAS_ZLIB + diff --git a/tinySIGCOMP/src/zlib.h b/tinySIGCOMP/src/zlib.h new file mode 100644 index 0000000..33ed30f --- /dev/null +++ b/tinySIGCOMP/src/zlib.h @@ -0,0 +1,1360 @@ +#if !HAS_ZLIB +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.3, July 18th, 2005 + + Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler + + 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. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt + (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). +*/ + +#ifndef ZLIB_H +#define ZLIB_H + +#include "zconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.2.3" +#define ZLIB_VERNUM 0x1230 + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed + data. This version of the library supports only one compression method + (deflation) but other algorithms will be added later and will have the same + stream interface. + + Compression can be done in a single step if the buffers are large + enough (for example if an input file is mmap'ed), or can be done by + repeated calls of the compression function. In the latter case, the + application must provide more input and/or consume the output + (providing more output space) before each call. + + The compressed data format used by default by the in-memory functions is + the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + around a deflate stream, which is itself documented in RFC 1951. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio using the functions that start + with "gz". The gzip format is different from the zlib format. gzip is a + gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + + This library can optionally read and write gzip streams in memory as well. + + The zlib format was designed to be compact and fast for use in memory + and on communications channels. The gzip format was designed for single- + file compression on file systems, has a larger header than zlib to maintain + directory information, and uses a different, slower check method than zlib. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never + crash even in case of corrupted input. +*/ + +typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); +typedef void (*free_func) OF((voidpf opaque, voidpf address)); + +struct internal_state; + +typedef struct z_stream_s { + Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total nb of input bytes read so far */ + + Bytef *next_out; /* next output byte should be put there */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total nb of bytes output so far */ + + char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: binary or text */ + uLong adler; /* adler32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + gzip header information passed to and from zlib routines. See RFC 1952 + for more details on the meanings of these fields. +*/ +typedef struct gz_header_s { + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; /* true when done reading gzip header (not used + when writing a gzip file) */ +} gz_header; + +typedef gz_header FAR *gz_headerp; + +/* + The application must update next_in and avail_in when avail_in has + dropped to zero. It must update next_out and avail_out when avail_out + has dropped to zero. The application must initialize zalloc, zfree and + opaque before calling the init function. All other fields are set by the + compression library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this + if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, + pointers returned by zalloc for objects of exactly 65536 bytes *must* + have their offset normalized to zero. The default allocation function + provided by this library ensures this (see zutil.c). To reduce memory + requirements and avoid any allocation of 64K objects, at the expense of + compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or + progress reports. After compression, total_in holds the total size of + the uncompressed data and may be saved for use in the decompressor + (particularly if the decompressor wants to decompress everything in + a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */ +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +/* Allowed flush values; see deflate() and inflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative + * values are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 +/* Possible values of the data_type field (though see inflate()) */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + /* basic functions */ + +ZEXTERN const char * ZEXPORT zlibVersion OF((void)); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is + not compatible with the zlib.h header file used by the application. + This check is automatically made by deflateInit and inflateInit. + */ + +/* +ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. + If zalloc and zfree are set to Z_NULL, deflateInit updates them to + use default allocation functions. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at + all (the input data is simply copied a block at a time). + Z_DEFAULT_COMPRESSION requests a default compromise between speed and + compression (currently equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if level is not a valid compression level, + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). + msg is set to null if there is no error message. deflateInit does not + perform any compression: this will be done by deflate(). +*/ + + +ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce some + output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary (in interactive applications). + Some output may be provided even if flush is not set. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming + more output, and updating avail_in or avail_out accordingly; avail_out + should never be zero before the call. The application can consume the + compressed output when it wants, for example when the output buffer is full + (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK + and with zero avail_out, it must be called again after making room in the + output buffer because there might be more output pending. + + Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + decide how much data to accumualte before producing output, in order to + maximize compression. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In particular + avail_in is zero after the call if enough output space has been provided + before the call.) Flushing may degrade compression for some compression + algorithms and so it should be used only when necessary. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + avail_out is greater than six to avoid repeated flush markers due to + avail_out == 0 on return. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there + was enough output space; if deflate returns with Z_OK, this function must be + called again with Z_FINISH and more output space (updated avail_out) but no + more input data, until it returns with Z_STREAM_END or an error. After + deflate has returned Z_STREAM_END, the only possible operations on the + stream are deflateReset or deflateEnd. + + Z_FINISH can be used immediately after deflateInit if all the compression + is to be done in a single step. In this case, avail_out must be at least + the value returned by deflateBound (see below). If deflate does not return + Z_STREAM_END, then it must be called again as described above. + + deflate() sets strm->adler to the adler32 checksum of all input read + so far (that is, total_in bytes). + + deflate() may update strm->data_type if it can make a good guess about + the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered + binary. This field is only for information purposes and does not affect + the compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible + (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not + fatal, and deflate() can be called again with more input and more output + space to continue compressing. +*/ + + +ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any + pending output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, + msg may be set but then points to a static string (which must not be + deallocated). +*/ + + +/* +ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. If next_in is not Z_NULL and avail_in is large enough (the exact + value depends on the compression method), inflateInit determines the + compression method from the zlib header and allocates all data structures + accordingly; otherwise the allocation will be deferred to the first call of + inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to + use default allocation functions. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller. msg is set to null if there is no error + message. inflateInit does not perform any decompression apart from reading + the zlib header if present: this will be done by inflate(). (So next_in and + avail_in may be modified, but next_out and avail_out are unchanged.) +*/ + + +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in is updated and processing + will resume at this point for the next call of inflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there + is no more input data or no more space in the output buffer (see below + about the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming + more output, and updating the next_* and avail_* values accordingly. + The application can consume the uncompressed output when it wants, for + example when the output buffer is full (avail_out == 0), or after each + call of inflate(). If inflate returns Z_OK and with zero avail_out, it + must be called again after making room in the output buffer because there + might be more output pending. + + The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, + Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much + output as possible to the output buffer. Z_BLOCK requests that inflate() stop + if and when it gets to the next deflate block boundary. When decoding the + zlib or gzip format, this will cause inflate() to return immediately after + the header and before the first block. When doing a raw inflate, inflate() + will go ahead and process the first block, and will return when it gets to + the end of that block, or when it runs out of data. + + The Z_BLOCK option assists in appending to or combining deflate streams. + Also to assist in this, on return inflate() will set strm->data_type to the + number of unused bits in the last byte taken from strm->next_in, plus 64 + if inflate() is currently decoding the last block in the deflate stream, + plus 128 if inflate() returned immediately after decoding an end-of-block + code or decoding the complete header up to just before the first byte of the + deflate stream. The end-of-block will not be indicated until all of the + uncompressed data from that block has been written to strm->next_out. The + number of unused bits may in general be greater than seven, except when + bit 7 of data_type is set, in which case the number of unused bits will be + less than eight. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step + (a single call of inflate), the parameter flush should be set to + Z_FINISH. In this case all pending input is processed and all pending + output is flushed; avail_out must be large enough to hold all the + uncompressed data. (The size of the uncompressed data may have been saved + by the compressor for this purpose.) The next operation on this stream must + be inflateEnd to deallocate the decompression state. The use of Z_FINISH + is never required, but can be used to inform inflate that a faster approach + may be used for the single inflate() call. + + In this implementation, inflate() always flushes as much output as + possible to the output buffer, and always uses the faster approach on the + first call. So the only effect of the flush parameter in this implementation + is on the return value of inflate(), as noted below, or when it returns early + because Z_BLOCK is used. + + If a preset dictionary is needed after this call (see inflateSetDictionary + below), inflate sets strm->adler to the adler32 checksum of the dictionary + chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + strm->adler to the adler32 checksum of all output produced so far (that is, + total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + below. At the end of the stream, inflate() checks that its computed adler32 + checksum is equal to that saved by the compressor and returns Z_STREAM_END + only if the checksum is correct. + + inflate() will decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically. Any information + contained in the gzip header is not retained, so applications that need that + information should instead use raw inflate, see inflateInit2() below, or + inflateBack() and perform their own processing of the gzip header and + trailer. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect check + value), Z_STREAM_ERROR if the stream structure was inconsistent (for example + if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory, + Z_BUF_ERROR if no progress is possible or if there was not enough room in the + output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + inflate() can be called again with more input and more output space to + continue decompressing. If Z_DATA_ERROR is returned, the application may then + call inflateSync() to look for a good compression block if a partial recovery + of the data is desired. +*/ + + +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any + pending output. + + inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state + was inconsistent. In the error case, msg may be set but then points to a + static string (which must not be deallocated). +*/ + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* +ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy)); + + This is another version of deflateInit with more compression options. The + fields next_in, zalloc, zfree and opaque must be initialized before by + the caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + determines the window size. deflate() will then generate raw deflate data + with no zlib header or trailer, and will not compute an adler32 check value. + + windowBits can also be greater than 15 for optional gzip encoding. Add + 16 to windowBits to write a simple gzip header and trailer around the + compressed data instead of a zlib wrapper. The gzip header will have no + file name, no extra data, no comment, no modification time (set to zero), + no header crc, and the operating system will be set to 255 (unknown). If a + gzip stream is being written, strm->adler is a crc32 instead of an adler32. + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but + is slow and reduces compression ratio; memLevel=9 uses maximum memory + for optimal speed. The default value is 8. See zconf.h for total memory + usage as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + string match), or Z_RLE to limit match distances to one (run-length + encoding). Filtered data consists mostly of small values with a somewhat + random distribution. In this case, the compression algorithm is tuned to + compress them better. The effect of Z_FILTERED is to force more Huffman + coding and less string matching; it is somewhat intermediate between + Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as + Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy + parameter only affects the compression ratio but not the correctness of the + compressed output even if it is not set appropriately. Z_FIXED prevents the + use of dynamic Huffman codes, allowing for a simpler decoder for special + applications. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid + method). msg is set to null if there is no error message. deflateInit2 does + not perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. This function must be called + immediately after deflateInit, deflateInit2 or deflateReset, before any + call of deflate. The compressor and decompressor must use exactly the same + dictionary (see inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size in + deflate or deflate2. Thus the strings most likely to be useful should be + put at the end of the dictionary, not at the front. In addition, the + current implementation of deflate will use at most the window size minus + 262 bytes of the provided dictionary. + + Upon return of this function, strm->adler is set to the adler32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The adler32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) If a raw deflate was requested, then the + adler32 value is not computed and strm->adler is not set. + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (such as NULL dictionary) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if the compression method is bsort). deflateSetDictionary does not + perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and + can consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +/* + This function is equivalent to deflateEnd followed by deflateInit, + but does not free and reallocate all the internal compression state. + The stream will keep the same compression level and any other attributes + that may have been set by deflateInit2. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being NULL). +*/ + +ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + int level, + int strategy)); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2. This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different + strategy. If the compression level is changed, the input available so far + is compressed with the old level (and may be flushed); the new level will + take effect only at the next call of deflate(). + + Before the call of deflateParams, the stream state must be set as for + a call of deflate(), since the currently available input may have to + be compressed and flushed. In particular, strm->avail_out must be non-zero. + + deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source + stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR + if strm->avail_out was zero. +*/ + +ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, + int good_length, + int max_lazy, + int nice_length, + int max_chain)); +/* + Fine tune deflate's internal compression parameters. This should only be + used by someone who understands the algorithm used by zlib's deflate for + searching for the best matching string, and even then only by the most + fanatic optimizer trying to squeeze out the last compressed bit for their + specific input data. Read the deflate.c source code for the meaning of the + max_lazy, good_length, nice_length, and max_chain parameters. + + deflateTune() can be called after deflateInit() or deflateInit2(), and + returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + */ + +ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, + uLong sourceLen)); +/* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() + or deflateInit2(). This would be used to allocate an output buffer + for deflation in a single pass, and so would be called before deflate(). +*/ + +ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the + bits leftover from a previous deflate stream when appending to it. As such, + this function can only be used for raw deflate, and must be used before the + first deflate() call after a deflateInit2() or deflateReset(). bits must be + less than or equal to 16, and that many of the least significant bits of + value will be inserted in the output. + + deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, + gz_headerp head)); +/* + deflateSetHeader() provides gzip header information for when a gzip + stream is requested by deflateInit2(). deflateSetHeader() may be called + after deflateInit2() or deflateReset() and before the first call of + deflate(). The text, time, os, extra field, name, and comment information + in the provided gz_header structure are written to the gzip header (xflag is + ignored -- the extra flags are set according to the compression level). The + caller must assure that, if not Z_NULL, name and comment are terminated with + a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + available there. If hcrc is true, a gzip header crc is included. Note that + the current versions of the command-line version of gzip (up through version + 1.3.x) do not support header crc's, and will report that it is a "multi-part + gzip file" and give up. + + If deflateSetHeader is not used, the default gzip header has text false, + the time set to zero, and os set to 255, with no extra, name, or comment + fields. The gzip header is returned to the default state by deflateReset(). + + deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + int windowBits)); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. windowBits must be greater than or equal to the windowBits value + provided to deflateInit2() while compressing, or it must be equal to 15 if + deflateInit2() was not used. If a compressed stream with a larger window + size is given as input, inflate() will return with the error code + Z_DATA_ERROR instead of trying to allocate a larger window. + + windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + determines the window size. inflate() will then process raw deflate data, + not looking for a zlib or gzip header, not generating a check value, and not + looking for any check values for comparison at the end of the stream. This + is for use with other formats that use the deflate compressed data format + such as zip. Those formats provide their own check values. If a custom + format is developed using the raw deflate format for compressed data, it is + recommended that a check value such as an adler32 or a crc32 be applied to + the uncompressed data as is done in the zlib, gzip, and zip formats. For + most applications, the zlib format should be used as is. Note that comments + above on the use in deflateInit2() applies to the magnitude of windowBits. + + windowBits can also be greater than 15 for optional gzip decoding. Add + 32 to windowBits to enable zlib and gzip decoding with automatic header + detection, or add 16 to decode only the gzip format (the zlib format will + return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is + a crc32 instead of an adler32. + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg + is set to null if there is no error message. inflateInit2 does not perform + any decompression apart from reading the zlib header if present: this will + be done by inflate(). (So next_in and avail_in may be modified, but next_out + and avail_out are unchanged.) +*/ + +ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate, + if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the adler32 value returned by that call of inflate. + The compressor and decompressor must use exactly the same dictionary (see + deflateSetDictionary). For raw inflate, this function can be called + immediately after inflateInit2() or inflateReset() and before any call of + inflate() to set the dictionary. The application must insure that the + dictionary that was used for compression is provided. + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (such as NULL dictionary) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect adler32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + +ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); +/* + Skips invalid compressed data until a full flush point (see above the + description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR + if no more input was provided, Z_DATA_ERROR if no flush point has been found, + or Z_STREAM_ERROR if the stream structure was inconsistent. In the success + case, the application may save the current current value of total_in which + indicates where valid compressed data was found. In the error case, the + application may repeatedly call inflateSync, providing more input each time, + until success or end of the input data. +*/ + +ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when randomly accessing a large stream. The + first pass through the stream can periodically record the inflate state, + allowing restarting inflate at those points when randomly accessing the + stream. + + inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate all the internal decompression state. + The stream will keep attributes that may have been set by inflateInit2. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being NULL). +*/ + +ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + This function inserts bits in the inflate input stream. The intent is + that this function is used to start inflating at a bit position in the + middle of a byte. The provided bits will be used before any bytes are used + from next_in. This function should only be used with raw inflate, and + should be used before the first inflate() call after inflateInit2() or + inflateReset(). bits must be less than or equal to 16, and that many of the + least significant bits of value will be inserted in the input. + + inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, + gz_headerp head)); +/* + inflateGetHeader() requests that gzip header information be stored in the + provided gz_header structure. inflateGetHeader() may be called after + inflateInit2() or inflateReset(), and before the first call of inflate(). + As inflate() processes the gzip stream, head->done is zero until the header + is completed, at which time head->done is set to one. If a zlib stream is + being decoded, then head->done is set to -1 to indicate that there will be + no gzip header information forthcoming. Note that Z_BLOCK can be used to + force inflate() to return immediately after header processing is complete + and before any actual data is decompressed. + + The text, time, xflags, and os fields are filled in with the gzip header + contents. hcrc is set to true if there is a header CRC. (The header CRC + was valid if done is set to one.) If extra is not Z_NULL, then extra_max + contains the maximum number of bytes to write to extra. Once done is true, + extra_len contains the actual extra field length, and extra contains the + extra field, or that field truncated if extra_max is less than extra_len. + If name is not Z_NULL, then up to name_max characters are written there, + terminated with a zero unless the length is greater than name_max. If + comment is not Z_NULL, then up to comm_max characters are written there, + terminated with a zero unless the length is greater than comm_max. When + any of extra, name, or comment are not Z_NULL and the respective field is + not present in the header, then that field is set to Z_NULL to signal its + absence. This allows the use of deflateSetHeader() with the returned + structure to duplicate the header. However if those fields are set to + allocated memory, then the application will need to save those pointers + elsewhere so that they can be eventually freed. + + If inflateGetHeader is not used, then the header information is simply + discarded. The header is always checked for validity, including the header + CRC if present. inflateReset() will reset the process to discard the header + information. The application would need to call inflateGetHeader() again to + retrieve the header from the next gzip stream. + + inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, + unsigned char FAR *window)); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized + before the call. If zalloc and zfree are Z_NULL, then the default library- + derived memory allocation routines are used. windowBits is the base two + logarithm of the window size, in the range 8..15. window is a caller + supplied buffer of that size. Except for special applications where it is + assured that deflate was used with small window sizes, windowBits must be 15 + and a 32K byte window must be supplied to be able to decompress general + deflate streams. + + See inflateBack() for the usage of these routines. + + inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + the paramaters are invalid, Z_MEM_ERROR if the internal state could not + be allocated, or Z_VERSION_ERROR if the version of the library does not + match the version of the header file. +*/ + +typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); +typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); + +ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +/* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is more efficient than inflate() for + file i/o applications in that it avoids copying between the output and the + sliding window by simply making the window itself the output buffer. This + function trusts the application to not change the output buffer passed by + the output function, at least until inflateBack() returns. + + inflateBackInit() must be called first to allocate the internal state + and to initialize the state with the user-provided window buffer. + inflateBack() may then be used multiple times to inflate a complete, raw + deflate stream with each call. inflateBackEnd() is then called to free + the allocated state. + + A raw deflate stream is one with no zlib or gzip header or trailer. + This routine would normally be used in a utility that reads zip or gzip + files and writes out uncompressed files. The utility would decode the + header and process the trailer on its own, hence this routine expects + only the raw deflate stream to decompress. This is different from the + normal behavior of inflate(), which expects either a zlib or gzip header and + trailer around the deflate stream. + + inflateBack() uses two subroutines supplied by the caller that are then + called by inflateBack() for input and output. inflateBack() calls those + routines until it reads a complete deflate stream and writes out all of the + uncompressed data, or until it encounters an error. The function's + parameters and return types are defined above in the in_func and out_func + typedefs. inflateBack() will call in(in_desc, &buf) which should return the + number of bytes of provided input, and a pointer to that input in buf. If + there is no input available, in() must return zero--buf is ignored in that + case--and inflateBack() will return a buffer error. inflateBack() will call + out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() + should return zero on success, or non-zero on failure. If out() returns + non-zero, inflateBack() will return with an error. Neither in() nor out() + are permitted to change the contents of the window provided to + inflateBackInit(), which is also the buffer that out() uses to write from. + The length written by out() will be at most the window size. Any non-zero + amount of input may be provided by in(). + + For convenience, inflateBack() can be provided input on the first call by + setting strm->next_in and strm->avail_in. If that input is exhausted, then + in() will be called. Therefore strm->next_in must be initialized before + calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + must also be initialized, and then if strm->avail_in is not zero, input will + initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + + The in_desc and out_desc parameters of inflateBack() is passed as the + first parameter of in() and out() respectively when they are called. These + descriptors can be optionally used to pass any information that the caller- + supplied in() and out() functions need to do their job. + + On return, inflateBack() will set strm->next_in and strm->avail_in to + pass back any unused input that was provided by the last in() call. The + return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + if in() or out() returned an error, Z_DATA_ERROR if there was a format + error in the deflate stream (in which case strm->msg is set to indicate the + nature of the error), or Z_STREAM_ERROR if the stream was not properly + initialized. In the case of Z_BUF_ERROR, an input or output error can be + distinguished using strm->next_in which will be Z_NULL only if in() returned + an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to + out() returning non-zero. (in() will always be called before out(), so + strm->next_in is assured to be defined if out() returns non-zero.) Note + that inflateBack() cannot return Z_OK. +*/ + +ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); +/* + All memory allocated by inflateBackInit() is freed. + + inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + state was inconsistent. +*/ + +ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); +/* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + 1.0: size of uInt + 3.2: size of uLong + 5.4: size of voidpf (pointer) + 7.6: size of z_off_t + + Compiler, assembler, and debug options: + 8: DEBUG + 9: ASMV or ASMINF -- use ASM code + 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + 11: 0 (reserved) + + One-time table building (smaller code, but not thread-safe if true): + 12: BUILDFIXED -- build static block decoding tables when needed + 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + 14,15: 0 (reserved) + + Library content (indicates missing functionality): + 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + deflate code when not needed) + 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + and decode gzip streams (to avoid linking crc code) + 18-19: 0 (reserved) + + Operation variations (changes in library functionality): + 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + 21: FASTEST -- deflate algorithm with only one, lowest compression level + 22,23: 0 (reserved) + + The sprintf variant used by gzprintf (zero is best): + 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + + Remainder: + 27-31: 0 (reserved) + */ + + + /* utility functions */ + +/* + The following utility functions are implemented on top of the + basic stream-oriented functions. To simplify the interface, some + default options are assumed (compression level and memory usage, + standard memory allocation functions). The source code of these + utility functions can easily be modified if you need special options. +*/ + +ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be at least the value returned + by compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + This function can be used to compress a whole file at once if the + input file is mmap'ed. + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + +ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level)); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + +ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); +/* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before + a compress() or compress2() call to allocate the destination buffer. +*/ + +ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be large enough to hold the + entire uncompressed data. (The size of the uncompressed data must have + been saved previously by the compressor and transmitted to the decompressor + by some mechanism outside the scope of this compression library.) + Upon exit, destLen is the actual size of the compressed buffer. + This function can be used to decompress a whole file at once if the + input file is mmap'ed. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. +*/ + + +typedef voidp gzFile; + +ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); +/* + Opens a gzip (.gz) file for reading or writing. The mode parameter + is as in fopen ("rb" or "wb") but can also include a compression level + ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for + Huffman only compression as in "wb1h", or 'R' for run-length encoding + as in "wb1R". (See the description of deflateInit2 for more information + about the strategy parameter.) + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. + + gzopen returns NULL if the file could not be opened or if there was + insufficient memory to allocate the (de)compression state; errno + can be checked to distinguish the two cases (if errno is zero, the + zlib error is Z_MEM_ERROR). */ + +ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); +/* + gzdopen() associates a gzFile with the file descriptor fd. File + descriptors are obtained from calls like open, dup, creat, pipe or + fileno (in the file has been previously opened with fopen). + The mode parameter is as in gzopen. + The next call of gzclose on the returned gzFile will also close the + file descriptor fd, just like fclose(fdopen(fd), mode) closes the file + descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode). + gzdopen returns NULL if there was insufficient memory to allocate + the (de)compression state. +*/ + +ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); +/* + Dynamically update the compression level or strategy. See the description + of deflateInit2 for the meaning of these parameters. + gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not + opened for writing. +*/ + +ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); +/* + Reads the given number of uncompressed bytes from the compressed file. + If the input file was not in gzip format, gzread copies the given number + of bytes into the buffer. + gzread returns the number of uncompressed bytes actually read (0 for + end of file, -1 for error). */ + +ZEXTERN int ZEXPORT gzwrite OF((gzFile file, + voidpc buf, unsigned len)); +/* + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of uncompressed bytes actually written + (0 in case of error). +*/ + +ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); +/* + Converts, formats, and writes the args to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written (0 in case of error). The number of + uncompressed bytes written is limited to 4095. The caller should assure that + this limit is not exceeded. If it is exceeded, then gzprintf() will return + return an error (0) with nothing written. In this case, there may also be a + buffer overflow with unpredictable consequences, which is possible only if + zlib was compiled with the insecure functions sprintf() or vsprintf() + because the secure snprintf() or vsnprintf() functions were not available. +*/ + +ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); +/* + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + gzputs returns the number of characters written, or -1 in case of error. +*/ + +ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +/* + Reads bytes from the compressed file until len-1 characters are read, or + a newline character is read and transferred to buf, or an end-of-file + condition is encountered. The string is then terminated with a null + character. + gzgets returns buf, or Z_NULL in case of error. +*/ + +ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); +/* + Writes c, converted to an unsigned char, into the compressed file. + gzputc returns the value that was written, or -1 in case of error. +*/ + +ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); +/* + Reads one byte from the compressed file. gzgetc returns this byte + or -1 in case of end of file or error. +*/ + +ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); +/* + Push one character back onto the stream to be read again later. + Only one character of push-back is allowed. gzungetc() returns the + character pushed, or -1 on failure. gzungetc() will fail if a + character has been pushed but not read yet, or if c is -1. The pushed + character will be discarded if the stream is repositioned with gzseek() + or gzrewind(). +*/ + +ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); +/* + Flushes all pending output into the compressed file. The parameter + flush is as in the deflate() function. The return value is the zlib + error number (see function gzerror below). gzflush returns Z_OK if + the flush parameter is Z_FINISH and all output could be flushed. + gzflush should be called only when strictly necessary because it can + degrade compression. +*/ + +ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, + z_off_t offset, int whence)); +/* + Sets the starting position for the next gzread or gzwrite on the + given compressed file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + +ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); +/* + Rewinds the given file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) +*/ + +ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); +/* + Returns the starting position for the next gzread or gzwrite on the + given compressed file. This position represents a number of bytes in the + uncompressed data stream. + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +ZEXTERN int ZEXPORT gzeof OF((gzFile file)); +/* + Returns 1 when EOF has previously been detected reading the given + input stream, otherwise zero. +*/ + +ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); +/* + Returns 1 if file is being read directly without decompression, otherwise + zero. +*/ + +ZEXTERN int ZEXPORT gzclose OF((gzFile file)); +/* + Flushes all pending output if necessary, closes the compressed file + and deallocates all the (de)compression state. The return value is the zlib + error number (see function gzerror below). +*/ + +ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +/* + Returns the error message for the last error which occurred on the + given compressed file. errnum is set to zlib error number. If an + error occurred in the file system and not in the compression library, + errnum is set to Z_ERRNO and the application may consult errno + to get the exact error code. +*/ + +ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); +/* + Clears the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip + file that is being written concurrently. +*/ + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the + compression library. +*/ + +ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. If buf is NULL, this function returns + the required initial value for the checksum. + An Adler-32 checksum is almost as reliable as a CRC32 but can be computed + much faster. Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, + z_off_t len2)); +/* + Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. +*/ + +ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); +/* + Update a running CRC-32 with the bytes buf[0..len-1] and return the + updated CRC-32. If buf is NULL, this function returns the required initial + value for the for the crc. Pre- and post-conditioning (one's complement) is + performed within this function so it shouldn't be done by the application. + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + +ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); + +/* + Combine two CRC-32 check values into one. For two sequences of bytes, + seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + len2. +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); +ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size)); +#define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) +#define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) +#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, sizeof(z_stream)) +#define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) +#define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, sizeof(z_stream)) + + +#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) + struct internal_state {int dummy;}; /* hack for buggy compilers */ +#endif + +ZEXTERN const char * ZEXPORT zError OF((int)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z)); +ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */ +#endif // HAS_ZLIB + diff --git a/tinySIGCOMP/src/zutil.c b/tinySIGCOMP/src/zutil.c new file mode 100644 index 0000000..dab7e2f --- /dev/null +++ b/tinySIGCOMP/src/zutil.c @@ -0,0 +1,322 @@ +#if !HAS_ZLIB +/* zutil.c -- target dependent utility functions for the compression library + * Copyright (C) 1995-2005 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zutil.h" + +#ifndef NO_DUMMY_DECL +struct internal_state {int dummy;}; /* for buggy compilers */ +#endif + +const char * const z_errmsg[10] = { +"need dictionary", /* Z_NEED_DICT 2 */ +"stream end", /* Z_STREAM_END 1 */ +"", /* Z_OK 0 */ +"file error", /* Z_ERRNO (-1) */ +"stream error", /* Z_STREAM_ERROR (-2) */ +"data error", /* Z_DATA_ERROR (-3) */ +"insufficient memory", /* Z_MEM_ERROR (-4) */ +"buffer error", /* Z_BUF_ERROR (-5) */ +"incompatible version",/* Z_VERSION_ERROR (-6) */ +""}; + + +const char * ZEXPORT zlibVersion() +{ + return ZLIB_VERSION; +} + +uLong ZEXPORT zlibCompileFlags() +{ + uLong flags; + + flags = 0; + switch (sizeof(uInt)) { + case 2: break; + case 4: flags += 1; break; + case 8: flags += 2; break; + default: flags += 3; + } + switch (sizeof(uLong)) { + case 2: break; + case 4: flags += 1 << 2; break; + case 8: flags += 2 << 2; break; + default: flags += 3 << 2; + } + switch (sizeof(voidpf)) { + case 2: break; + case 4: flags += 1 << 4; break; + case 8: flags += 2 << 4; break; + default: flags += 3 << 4; + } + switch (sizeof(z_off_t)) { + case 2: break; + case 4: flags += 1 << 6; break; + case 8: flags += 2 << 6; break; + default: flags += 3 << 6; + } +#ifdef DEBUG + flags += 1 << 8; +#endif +#if defined(ASMV) || defined(ASMINF) + flags += 1 << 9; +#endif +#ifdef ZLIB_WINAPI + flags += 1 << 10; +#endif +#ifdef BUILDFIXED + flags += 1 << 12; +#endif +#ifdef DYNAMIC_CRC_TABLE + flags += 1 << 13; +#endif +#ifdef NO_GZCOMPRESS + flags += 1L << 16; +#endif +#ifdef NO_GZIP + flags += 1L << 17; +#endif +#ifdef PKZIP_BUG_WORKAROUND + flags += 1L << 20; +#endif +#ifdef FASTEST + flags += 1L << 21; +#endif +#ifdef STDC +# ifdef NO_vsnprintf + flags += 1L << 25; +# ifdef HAS_vsprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_vsnprintf_void + flags += 1L << 26; +# endif +# endif +#else + flags += 1L << 24; +# ifdef NO_snprintf + flags += 1L << 25; +# ifdef HAS_sprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_snprintf_void + flags += 1L << 26; +# endif +# endif +#endif + return flags; +} + +#ifdef DEBUG + +# ifndef verbose +# define verbose 0 +# endif +int z_verbose = verbose; + +void z_error (m) + char *m; +{ + fprintf(stderr, "%s\n", m); + exit(1); +} +#endif + +/* exported to allow conversion of error code to string for compress() and + * uncompress() + */ +const char * ZEXPORT zError(err) + int err; +{ + return ERR_MSG(err); +} + +#if defined(_WIN32_WCE) + /* The Microsoft C Run-Time Library for Windows CE doesn't have + * errno. We define it as a global variable to simplify porting. + * Its value is always 0 and should not be used. + */ + int errno = 0; +#endif + +#ifndef HAVE_MEMCPY + +void zmemcpy(dest, source, len) + Bytef* dest; + const Bytef* source; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = *source++; /* ??? to be unrolled */ + } while (--len != 0); +} + +int zmemcmp(s1, s2, len) + const Bytef* s1; + const Bytef* s2; + uInt len; +{ + uInt j; + + for (j = 0; j < len; j++) { + if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; + } + return 0; +} + +void zmemzero(dest, len) + Bytef* dest; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = 0; /* ??? to be unrolled */ + } while (--len != 0); +} +#endif + + +#ifdef SYS16BIT + +#ifdef __TURBOC__ +/* Turbo C in 16-bit mode */ + +# define MY_ZCALLOC + +/* Turbo C malloc() does not allow dynamic allocation of 64K bytes + * and farmalloc(64K) returns a pointer with an offset of 8, so we + * must fix the pointer. Warning: the pointer must be put back to its + * original form in order to free it, use zcfree(). + */ + +#define MAX_PTR 10 +/* 10*64K = 640K */ + +local int next_ptr = 0; + +typedef struct ptr_table_s { + voidpf org_ptr; + voidpf new_ptr; +} ptr_table; + +local ptr_table table[MAX_PTR]; +/* This table is used to remember the original form of pointers + * to large buffers (64K). Such pointers are normalized with a zero offset. + * Since MSDOS is not a preemptive multitasking OS, this table is not + * protected from concurrent access. This hack doesn't work anyway on + * a protected system like OS/2. Use Microsoft C instead. + */ + +voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + voidpf buf = opaque; /* just to make some compilers happy */ + ulg bsize = (ulg)items*size; + + /* If we allocate less than 65520 bytes, we assume that farmalloc + * will return a usable pointer which doesn't have to be normalized. + */ + if (bsize < 65520L) { + buf = farmalloc(bsize); + if (*(ush*)&buf != 0) return buf; + } else { + buf = farmalloc(bsize + 16L); + } + if (buf == NULL || next_ptr >= MAX_PTR) return NULL; + table[next_ptr].org_ptr = buf; + + /* Normalize the pointer to seg:0 */ + *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; + *(ush*)&buf = 0; + table[next_ptr++].new_ptr = buf; + return buf; +} + +void zcfree (voidpf opaque, voidpf ptr) +{ + int n; + if (*(ush*)&ptr != 0) { /* object < 64K */ + farfree(ptr); + return; + } + /* Find the original pointer */ + for (n = 0; n < next_ptr; n++) { + if (ptr != table[n].new_ptr) continue; + + farfree(table[n].org_ptr); + while (++n < next_ptr) { + table[n-1] = table[n]; + } + next_ptr--; + return; + } + ptr = opaque; /* just to make some compilers happy */ + Assert(0, "zcfree: ptr not found"); +} + +#endif /* __TURBOC__ */ + + +#ifdef M_I86 +/* Microsoft C in 16-bit mode */ + +# define MY_ZCALLOC + +#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) +# define _halloc halloc +# define _hfree hfree +#endif + +voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + if (opaque) opaque = 0; /* to make compiler happy */ + return _halloc((long)items, size); +} + +void zcfree (voidpf opaque, voidpf ptr) +{ + if (opaque) opaque = 0; /* to make compiler happy */ + _hfree(ptr); +} + +#endif /* M_I86 */ + +#endif /* SYS16BIT */ + + +#ifndef MY_ZCALLOC /* Any system without a special alloc function */ + +#ifndef STDC +extern voidp malloc OF((uInt size)); +extern voidp calloc OF((uInt items, uInt size)); +extern void free OF((voidpf ptr)); +#endif + +voidpf zcalloc (opaque, items, size) + voidpf opaque; + unsigned items; + unsigned size; +{ + if (opaque) items += size - size; /* make compiler happy */ + return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : + (voidpf)calloc(items, size); +} + +void zcfree (opaque, ptr) + voidpf opaque; + voidpf ptr; +{ + free(ptr); + if (opaque) return; /* make compiler happy */ +} + +#endif /* MY_ZCALLOC */ + +#endif // HAS_ZLIB + diff --git a/tinySIGCOMP/src/zutil.h b/tinySIGCOMP/src/zutil.h new file mode 100644 index 0000000..3761182 --- /dev/null +++ b/tinySIGCOMP/src/zutil.h @@ -0,0 +1,272 @@ +#if !HAS_ZLIB +/* zutil.h -- internal interface and configuration of the compression library + * Copyright (C) 1995-2005 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef ZUTIL_H +#define ZUTIL_H + +#define ZLIB_INTERNAL +#include "zlib.h" + +#if defined(STDC) && !defined(__SYMBIAN32__) +# ifndef _WIN32_WCE +# include <stddef.h> +# endif +# include <string.h> +# include <stdlib.h> +#endif +#ifdef NO_ERRNO_H +# ifdef _WIN32_WCE + /* The Microsoft C Run-Time Library for Windows CE doesn't have + * errno. We define it as a global variable to simplify porting. + * Its value is always 0 and should not be used. We rename it to + * avoid conflict with other libraries that use the same workaround. + */ +# define errno z_errno +# endif + extern int errno; +#else +# ifndef _WIN32_WCE +# include <errno.h> +# endif +#endif + +#ifndef local +# define local static +#endif +/* compile with -Dlocal if your debugger can't find static symbols */ + +typedef unsigned char uch; +typedef uch FAR uchf; +typedef unsigned short ush; +typedef ush FAR ushf; +typedef unsigned long ulg; + +extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ +/* (size given to avoid silly warnings with Visual C++) */ + +#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] + +#define ERR_RETURN(strm,err) \ + return (strm->msg = (char*)ERR_MSG(err), (err)) +/* To be used only when the state is known to be valid */ + + /* common constants */ + +#ifndef DEF_WBITS +# define DEF_WBITS MAX_WBITS +#endif +/* default windowBits for decompression. MAX_WBITS is for compression only */ + +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif +/* default memLevel */ + +#define STORED_BLOCK 0 +#define STATIC_TREES 1 +#define DYN_TREES 2 +/* The three kinds of block type */ + +#define MIN_MATCH 3 +#define MAX_MATCH 258 +/* The minimum and maximum match lengths */ + +#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ + + /* target dependencies */ + +#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) +# define OS_CODE 0x00 +# if defined(__TURBOC__) || defined(__BORLANDC__) +# if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) + /* Allow compilation with ANSI keywords only enabled */ + void _Cdecl farfree( void *block ); + void *_Cdecl farmalloc( unsigned long nbytes ); +# else +# include <alloc.h> +# endif +# else /* MSC or DJGPP */ +# include <malloc.h> +# endif +#endif + +#ifdef AMIGA +# define OS_CODE 0x01 +#endif + +#if defined(VAXC) || defined(VMS) +# define OS_CODE 0x02 +# define F_OPEN(name, mode) \ + fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") +#endif + +#if defined(ATARI) || defined(atarist) +# define OS_CODE 0x05 +#endif + +#ifdef OS2 +# define OS_CODE 0x06 +# ifdef M_I86 + #include <malloc.h> +# endif +#endif + +#if defined(MACOS) || defined(TARGET_OS_MAC) +# define OS_CODE 0x07 +# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os +# include <unix.h> /* for fdopen */ +# else +# ifndef fdopen +# define fdopen(fd,mode) NULL /* No fdopen() */ +# endif +# endif +#endif + +#ifdef TOPS20 +# define OS_CODE 0x0a +#endif + +#ifdef WIN32 +# ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */ +# define OS_CODE 0x0b +# endif +#endif + +#ifdef __50SERIES /* Prime/PRIMOS */ +# define OS_CODE 0x0f +#endif + +#if defined(_BEOS_) || defined(RISCOS) +# define fdopen(fd,mode) NULL /* No fdopen() */ +#endif + +#if (defined(_MSC_VER) && (_MSC_VER > 600)) +# if defined(_WIN32_WCE) +# define fdopen(fd,mode) NULL /* No fdopen() */ +# ifndef _PTRDIFF_T_DEFINED + typedef int ptrdiff_t; +# define _PTRDIFF_T_DEFINED +# endif +# else +# define fdopen(fd,type) _fdopen(fd,type) +# endif +#endif + + /* common defaults */ + +#ifndef OS_CODE +# define OS_CODE 0x03 /* assume Unix */ +#endif + +#ifndef F_OPEN +# define F_OPEN(name, mode) fopen((name), (mode)) +#endif + + /* functions */ + +#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif +#if defined(__CYGWIN__) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif +#ifndef HAVE_VSNPRINTF +# ifdef MSDOS + /* vsnprintf may exist on some MS-DOS compilers (DJGPP?), + but for now we just assume it doesn't. */ +# define NO_vsnprintf +# endif +# ifdef __TURBOC__ +# define NO_vsnprintf +# endif +# ifdef WIN32 + /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ +# if !defined(vsnprintf) && !defined(NO_vsnprintf) +# define vsnprintf _vsnprintf +# endif +# endif +# ifdef __SASC +# define NO_vsnprintf +# endif +#endif +#ifdef VMS +# define NO_vsnprintf +#endif + +#if defined(pyr) +# define NO_MEMCPY +#endif +#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) + /* Use our own functions for small and medium model with MSC <= 5.0. + * You may have to use the same strategy for Borland C (untested). + * The __SC__ check is for Symantec. + */ +# define NO_MEMCPY +#endif +#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) +# define HAVE_MEMCPY +#endif +#ifdef HAVE_MEMCPY +# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ +# define zmemcpy _fmemcpy +# define zmemcmp _fmemcmp +# define zmemzero(dest, len) _fmemset(dest, 0, len) +# else +# define zmemcpy memcpy +# define zmemcmp memcmp +# define zmemzero(dest, len) memset(dest, 0, len) +# endif +#else + extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); + extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); + extern void zmemzero OF((Bytef* dest, uInt len)); +#endif + +/* Diagnostic functions */ +#ifdef DEBUG +# include <stdio.h> + extern int z_verbose; + extern void z_error OF((char *m)); +# define Assert(cond,msg) {if(!(cond)) z_error(msg);} +# define Trace(x) {if (z_verbose>=0) fprintf x ;} +# define Tracev(x) {if (z_verbose>0) fprintf x ;} +# define Tracevv(x) {if (z_verbose>1) fprintf x ;} +# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} +# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} +#else +# define Assert(cond,msg) +# define Trace(x) +# define Tracev(x) +# define Tracevv(x) +# define Tracec(c,x) +# define Tracecv(c,x) +#endif + + +voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size)); +void zcfree OF((voidpf opaque, voidpf ptr)); + +#define ZALLOC(strm, items, size) \ + (*((strm)->zalloc))((strm)->opaque, (items), (size)) +#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) +#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} + +#endif /* ZUTIL_H */ +#endif // HAS_ZLIB + |