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