inflatezlibblock.c 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <flate.h>
  4. #include "zlib.h"
  5. typedef struct Block Block;
  6. struct Block
  7. {
  8. uchar *pos;
  9. uchar *limit;
  10. };
  11. static int
  12. blgetc(void *vb)
  13. {
  14. Block *b;
  15. b = vb;
  16. if(b->pos >= b->limit)
  17. return -1;
  18. return *b->pos++;
  19. }
  20. static int
  21. blwrite(void *vb, void *buf, int n)
  22. {
  23. Block *b;
  24. b = vb;
  25. if(n > b->limit - b->pos)
  26. n = b->limit - b->pos;
  27. memmove(b->pos, buf, n);
  28. b->pos += n;
  29. return n;
  30. }
  31. int
  32. inflatezlibblock(uchar *dst, int dsize, uchar *src, int ssize)
  33. {
  34. Block bd, bs;
  35. int ok;
  36. if(ssize < 6)
  37. return FlateInputFail;
  38. if(((src[0] << 8) | src[1]) % 31)
  39. return FlateCorrupted;
  40. if((src[0] & ZlibMeth) != ZlibDeflate
  41. || (src[0] & ZlibCInfo) > ZlibWin32k)
  42. return FlateCorrupted;
  43. bs.pos = src + 2;
  44. bs.limit = src + ssize - 6;
  45. bd.pos = dst;
  46. bd.limit = dst + dsize;
  47. ok = inflate(&bd, blwrite, &bs, blgetc);
  48. if(ok != FlateOk)
  49. return ok;
  50. if(adler32(1, dst, bs.pos - dst) != ((bs.pos[0] << 24) | (bs.pos[1] << 16) | (bs.pos[2] << 8) | bs.pos[3]))
  51. return FlateCorrupted;
  52. return bd.pos - dst;
  53. }