serialization.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. /*
  2. Minetest
  3. Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "serialization.h"
  17. #include "util/serialize.h"
  18. #include <zlib.h>
  19. #include <zstd.h>
  20. /* report a zlib or i/o error */
  21. static void zerr(int ret)
  22. {
  23. dstream<<"zerr: ";
  24. switch (ret) {
  25. case Z_ERRNO:
  26. if (ferror(stdin))
  27. dstream<<"error reading stdin"<<std::endl;
  28. if (ferror(stdout))
  29. dstream<<"error writing stdout"<<std::endl;
  30. break;
  31. case Z_STREAM_ERROR:
  32. dstream<<"invalid compression level"<<std::endl;
  33. break;
  34. case Z_DATA_ERROR:
  35. dstream<<"invalid or incomplete deflate data"<<std::endl;
  36. break;
  37. case Z_MEM_ERROR:
  38. dstream<<"out of memory"<<std::endl;
  39. break;
  40. case Z_VERSION_ERROR:
  41. dstream<<"zlib version mismatch!"<<std::endl;
  42. break;
  43. default:
  44. dstream<<"return value = "<<ret<<std::endl;
  45. }
  46. }
  47. // Make sure that z is deleted in case of exception
  48. template <int (*F)(z_stream*)>
  49. class ZlibAutoDeleter {
  50. public:
  51. ZlibAutoDeleter(z_stream *ptr) : ptr_(ptr) {}
  52. ~ZlibAutoDeleter() { F(ptr_); }
  53. private:
  54. z_stream *ptr_;
  55. };
  56. void compressZlib(const u8 *data, size_t data_size, std::ostream &os, int level)
  57. {
  58. z_stream z;
  59. const s32 bufsize = 16384;
  60. char output_buffer[bufsize];
  61. int status = 0;
  62. int ret;
  63. z.zalloc = Z_NULL;
  64. z.zfree = Z_NULL;
  65. z.opaque = Z_NULL;
  66. ret = deflateInit(&z, level);
  67. if(ret != Z_OK)
  68. throw SerializationError("compressZlib: deflateInit failed");
  69. ZlibAutoDeleter<deflateEnd> deleter(&z);
  70. // Point zlib to our input buffer
  71. z.next_in = (Bytef*)&data[0];
  72. z.avail_in = data_size;
  73. // And get all output
  74. for(;;)
  75. {
  76. z.next_out = (Bytef*)output_buffer;
  77. z.avail_out = bufsize;
  78. status = deflate(&z, Z_FINISH);
  79. if(status == Z_NEED_DICT || status == Z_DATA_ERROR
  80. || status == Z_MEM_ERROR)
  81. {
  82. zerr(status);
  83. throw SerializationError("compressZlib: deflate failed");
  84. }
  85. int count = bufsize - z.avail_out;
  86. if(count)
  87. os.write(output_buffer, count);
  88. // This determines zlib has given all output
  89. if(status == Z_STREAM_END)
  90. break;
  91. }
  92. }
  93. void decompressZlib(std::istream &is, std::ostream &os, size_t limit)
  94. {
  95. z_stream z;
  96. const s32 bufsize = 16384;
  97. char input_buffer[bufsize];
  98. char output_buffer[bufsize];
  99. int status = 0;
  100. int ret;
  101. int bytes_written = 0;
  102. int input_buffer_len = 0;
  103. z.zalloc = Z_NULL;
  104. z.zfree = Z_NULL;
  105. z.opaque = Z_NULL;
  106. ret = inflateInit(&z);
  107. if(ret != Z_OK)
  108. throw SerializationError("dcompressZlib: inflateInit failed");
  109. ZlibAutoDeleter<inflateEnd> deleter(&z);
  110. z.avail_in = 0;
  111. for(;;)
  112. {
  113. int output_size = bufsize;
  114. z.next_out = (Bytef*)output_buffer;
  115. z.avail_out = output_size;
  116. if (limit) {
  117. int limit_remaining = limit - bytes_written;
  118. if (limit_remaining <= 0) {
  119. // we're aborting ahead of time - throw an error?
  120. break;
  121. }
  122. if (limit_remaining < output_size) {
  123. z.avail_out = output_size = limit_remaining;
  124. }
  125. }
  126. if(z.avail_in == 0)
  127. {
  128. z.next_in = (Bytef*)input_buffer;
  129. is.read(input_buffer, bufsize);
  130. input_buffer_len = is.gcount();
  131. z.avail_in = input_buffer_len;
  132. }
  133. if(z.avail_in == 0)
  134. {
  135. break;
  136. }
  137. status = inflate(&z, Z_NO_FLUSH);
  138. if(status == Z_NEED_DICT || status == Z_DATA_ERROR
  139. || status == Z_MEM_ERROR)
  140. {
  141. zerr(status);
  142. throw SerializationError("decompressZlib: inflate failed");
  143. }
  144. int count = output_size - z.avail_out;
  145. if(count)
  146. os.write(output_buffer, count);
  147. bytes_written += count;
  148. if(status == Z_STREAM_END)
  149. {
  150. // Unget all the data that inflate didn't take
  151. is.clear(); // Just in case EOF is set
  152. for(u32 i=0; i < z.avail_in; i++)
  153. {
  154. is.unget();
  155. if(is.fail() || is.bad())
  156. {
  157. dstream<<"unget #"<<i<<" failed"<<std::endl;
  158. dstream<<"fail="<<is.fail()<<" bad="<<is.bad()<<std::endl;
  159. throw SerializationError("decompressZlib: unget failed");
  160. }
  161. }
  162. break;
  163. }
  164. }
  165. }
  166. struct ZSTD_Deleter {
  167. void operator() (ZSTD_CStream* cstream) {
  168. ZSTD_freeCStream(cstream);
  169. }
  170. void operator() (ZSTD_DStream* dstream) {
  171. ZSTD_freeDStream(dstream);
  172. }
  173. };
  174. void compressZstd(const u8 *data, size_t data_size, std::ostream &os, int level)
  175. {
  176. // reusing the context is recommended for performance
  177. // it will be destroyed when the thread ends
  178. thread_local std::unique_ptr<ZSTD_CStream, ZSTD_Deleter> stream(ZSTD_createCStream());
  179. ZSTD_initCStream(stream.get(), level);
  180. const size_t bufsize = 16384;
  181. char output_buffer[bufsize];
  182. ZSTD_inBuffer input = { data, data_size, 0 };
  183. ZSTD_outBuffer output = { output_buffer, bufsize, 0 };
  184. while (input.pos < input.size) {
  185. size_t ret = ZSTD_compressStream(stream.get(), &output, &input);
  186. if (ZSTD_isError(ret)) {
  187. dstream << ZSTD_getErrorName(ret) << std::endl;
  188. throw SerializationError("compressZstd: failed");
  189. }
  190. if (output.pos) {
  191. os.write(output_buffer, output.pos);
  192. output.pos = 0;
  193. }
  194. }
  195. size_t ret;
  196. do {
  197. ret = ZSTD_endStream(stream.get(), &output);
  198. if (ZSTD_isError(ret)) {
  199. dstream << ZSTD_getErrorName(ret) << std::endl;
  200. throw SerializationError("compressZstd: failed");
  201. }
  202. if (output.pos) {
  203. os.write(output_buffer, output.pos);
  204. output.pos = 0;
  205. }
  206. } while (ret != 0);
  207. }
  208. void decompressZstd(std::istream &is, std::ostream &os)
  209. {
  210. // reusing the context is recommended for performance
  211. // it will be destroyed when the thread ends
  212. thread_local std::unique_ptr<ZSTD_DStream, ZSTD_Deleter> stream(ZSTD_createDStream());
  213. ZSTD_initDStream(stream.get());
  214. const size_t bufsize = 16384;
  215. char output_buffer[bufsize];
  216. char input_buffer[bufsize];
  217. ZSTD_outBuffer output = { output_buffer, bufsize, 0 };
  218. ZSTD_inBuffer input = { input_buffer, 0, 0 };
  219. size_t ret;
  220. do
  221. {
  222. if (input.size == input.pos) {
  223. is.read(input_buffer, bufsize);
  224. input.size = is.gcount();
  225. input.pos = 0;
  226. }
  227. ret = ZSTD_decompressStream(stream.get(), &output, &input);
  228. if (ZSTD_isError(ret)) {
  229. dstream << ZSTD_getErrorName(ret) << std::endl;
  230. throw SerializationError("decompressZstd: failed");
  231. }
  232. if (output.pos) {
  233. os.write(output_buffer, output.pos);
  234. output.pos = 0;
  235. }
  236. } while (ret != 0);
  237. // Unget all the data that ZSTD_decompressStream didn't take
  238. is.clear(); // Just in case EOF is set
  239. for (u32 i = 0; i < input.size - input.pos; i++) {
  240. is.unget();
  241. if (is.fail() || is.bad())
  242. throw SerializationError("decompressZstd: unget failed");
  243. }
  244. }
  245. void compress(const u8 *data, u32 size, std::ostream &os, u8 version, int level)
  246. {
  247. if(version >= 29)
  248. {
  249. // map the zlib levels [0,9] to [1,10]. -1 becomes 0 which indicates the default (currently 3)
  250. compressZstd(data, size, os, level + 1);
  251. return;
  252. }
  253. if(version >= 11)
  254. {
  255. compressZlib(data, size, os, level);
  256. return;
  257. }
  258. if(size == 0)
  259. return;
  260. // Write length (u32)
  261. u8 tmp[4];
  262. writeU32(tmp, size);
  263. os.write((char*)tmp, 4);
  264. // We will be writing 8-bit pairs of more_count and byte
  265. u8 more_count = 0;
  266. u8 current_byte = data[0];
  267. for(u32 i=1; i<size; i++)
  268. {
  269. if(
  270. data[i] != current_byte
  271. || more_count == 255
  272. )
  273. {
  274. // write count and byte
  275. os.write((char*)&more_count, 1);
  276. os.write((char*)&current_byte, 1);
  277. more_count = 0;
  278. current_byte = data[i];
  279. }
  280. else
  281. {
  282. more_count++;
  283. }
  284. }
  285. // write count and byte
  286. os.write((char*)&more_count, 1);
  287. os.write((char*)&current_byte, 1);
  288. }
  289. void decompress(std::istream &is, std::ostream &os, u8 version)
  290. {
  291. if(version >= 29)
  292. {
  293. decompressZstd(is, os);
  294. return;
  295. }
  296. if(version >= 11)
  297. {
  298. decompressZlib(is, os);
  299. return;
  300. }
  301. // Read length (u32)
  302. u8 tmp[4];
  303. is.read((char*)tmp, 4);
  304. u32 len = readU32(tmp);
  305. // We will be reading 8-bit pairs of more_count and byte
  306. u32 count = 0;
  307. for(;;)
  308. {
  309. u8 more_count=0;
  310. u8 byte=0;
  311. is.read((char*)&more_count, 1);
  312. is.read((char*)&byte, 1);
  313. if(is.eof())
  314. throw SerializationError("decompress: stream ended halfway");
  315. for(s32 i=0; i<(u16)more_count+1; i++)
  316. os.write((char*)&byte, 1);
  317. count += (u16)more_count+1;
  318. if(count == len)
  319. break;
  320. }
  321. }