inflatezlibblock.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include <flate.h>
  12. #include "zlib.h"
  13. typedef struct Block Block;
  14. struct Block
  15. {
  16. uint8_t *pos;
  17. uint8_t *limit;
  18. };
  19. static int
  20. blgetc(void *vb)
  21. {
  22. Block *b;
  23. b = vb;
  24. if(b->pos >= b->limit)
  25. return -1;
  26. return *b->pos++;
  27. }
  28. static int
  29. blwrite(void *vb, void *buf, int n)
  30. {
  31. Block *b;
  32. b = vb;
  33. if(n > b->limit - b->pos)
  34. n = b->limit - b->pos;
  35. memmove(b->pos, buf, n);
  36. b->pos += n;
  37. return n;
  38. }
  39. int
  40. inflatezlibblock(uint8_t *dst, int dsize, uint8_t *src, int ssize)
  41. {
  42. Block bd, bs;
  43. int ok;
  44. if(ssize < 6)
  45. return FlateInputFail;
  46. if(((src[0] << 8) | src[1]) % 31)
  47. return FlateCorrupted;
  48. if((src[0] & ZlibMeth) != ZlibDeflate
  49. || (src[0] & ZlibCInfo) > ZlibWin32k)
  50. return FlateCorrupted;
  51. bs.pos = src + 2;
  52. bs.limit = src + ssize - 6;
  53. bd.pos = dst;
  54. bd.limit = dst + dsize;
  55. ok = inflate(&bd, blwrite, &bs, blgetc);
  56. if(ok != FlateOk)
  57. return ok;
  58. if(adler32(1, dst, bs.pos - dst) != ((bs.pos[0] << 24) | (bs.pos[1] << 16) | (bs.pos[2] << 8) | bs.pos[3]))
  59. return FlateCorrupted;
  60. return bd.pos - dst;
  61. }