inflatezlib.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 ZWrite ZWrite;
  14. struct ZWrite
  15. {
  16. uint32_t adler;
  17. void *wr;
  18. int (*w)(void*, void*, int);
  19. };
  20. static int
  21. zlwrite(void *vzw, void *buf, int n)
  22. {
  23. ZWrite *zw;
  24. zw = vzw;
  25. zw->adler = adler32(zw->adler, buf, n);
  26. n = (*zw->w)(zw->wr, buf, n);
  27. if(n <= 0)
  28. return n;
  29. return n;
  30. }
  31. int
  32. inflatezlib(void *wr, int (*w)(void*, void*, int), void *getr, int (*get)(void*))
  33. {
  34. ZWrite zw;
  35. uint32_t v;
  36. int c, i;
  37. c = (*get)(getr);
  38. if(c < 0)
  39. return FlateInputFail;
  40. i = (*get)(getr);
  41. if(i < 0)
  42. return FlateInputFail;
  43. if(((c << 8) | i) % 31)
  44. return FlateCorrupted;
  45. if((c & ZlibMeth) != ZlibDeflate
  46. || (c & ZlibCInfo) > ZlibWin32k)
  47. return FlateCorrupted;
  48. zw.wr = wr;
  49. zw.w = w;
  50. zw.adler = 1;
  51. i = inflate(&zw, zlwrite, getr, get);
  52. if(i != FlateOk)
  53. return i;
  54. v = 0;
  55. for(i = 0; i < 4; i++){
  56. c = (*get)(getr);
  57. if(c < 0)
  58. return FlateInputFail;
  59. v = (v << 8) | c;
  60. }
  61. if(zw.adler != v)
  62. return FlateCorrupted;
  63. return FlateOk;
  64. }