serialization.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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 compressZlib(const std::string &data, std::ostream &os, int level)
  94. {
  95. compressZlib((u8*)data.c_str(), data.size(), os, level);
  96. }
  97. void decompressZlib(std::istream &is, std::ostream &os, size_t limit)
  98. {
  99. z_stream z;
  100. const s32 bufsize = 16384;
  101. char input_buffer[bufsize];
  102. char output_buffer[bufsize];
  103. int status = 0;
  104. int ret;
  105. int bytes_written = 0;
  106. int input_buffer_len = 0;
  107. z.zalloc = Z_NULL;
  108. z.zfree = Z_NULL;
  109. z.opaque = Z_NULL;
  110. ret = inflateInit(&z);
  111. if(ret != Z_OK)
  112. throw SerializationError("dcompressZlib: inflateInit failed");
  113. ZlibAutoDeleter<inflateEnd> deleter(&z);
  114. z.avail_in = 0;
  115. for(;;)
  116. {
  117. int output_size = bufsize;
  118. z.next_out = (Bytef*)output_buffer;
  119. z.avail_out = output_size;
  120. if (limit) {
  121. int limit_remaining = limit - bytes_written;
  122. if (limit_remaining <= 0) {
  123. // we're aborting ahead of time - throw an error?
  124. break;
  125. }
  126. if (limit_remaining < output_size) {
  127. z.avail_out = output_size = limit_remaining;
  128. }
  129. }
  130. if(z.avail_in == 0)
  131. {
  132. z.next_in = (Bytef*)input_buffer;
  133. is.read(input_buffer, bufsize);
  134. input_buffer_len = is.gcount();
  135. z.avail_in = input_buffer_len;
  136. }
  137. if(z.avail_in == 0)
  138. {
  139. break;
  140. }
  141. status = inflate(&z, Z_NO_FLUSH);
  142. if(status == Z_NEED_DICT || status == Z_DATA_ERROR
  143. || status == Z_MEM_ERROR)
  144. {
  145. zerr(status);
  146. throw SerializationError("decompressZlib: inflate failed");
  147. }
  148. int count = output_size - z.avail_out;
  149. if(count)
  150. os.write(output_buffer, count);
  151. bytes_written += count;
  152. if(status == Z_STREAM_END)
  153. {
  154. // Unget all the data that inflate didn't take
  155. is.clear(); // Just in case EOF is set
  156. for(u32 i=0; i < z.avail_in; i++)
  157. {
  158. is.unget();
  159. if(is.fail() || is.bad())
  160. {
  161. dstream<<"unget #"<<i<<" failed"<<std::endl;
  162. dstream<<"fail="<<is.fail()<<" bad="<<is.bad()<<std::endl;
  163. throw SerializationError("decompressZlib: unget failed");
  164. }
  165. }
  166. break;
  167. }
  168. }
  169. }
  170. struct ZSTD_Deleter {
  171. void operator() (ZSTD_CStream* cstream) {
  172. ZSTD_freeCStream(cstream);
  173. }
  174. void operator() (ZSTD_DStream* dstream) {
  175. ZSTD_freeDStream(dstream);
  176. }
  177. };
  178. void compressZstd(const u8 *data, size_t data_size, std::ostream &os, int level)
  179. {
  180. // reusing the context is recommended for performance
  181. // it will be destroyed when the thread ends
  182. thread_local std::unique_ptr<ZSTD_CStream, ZSTD_Deleter> stream(ZSTD_createCStream());
  183. ZSTD_initCStream(stream.get(), level);
  184. const size_t bufsize = 16384;
  185. char output_buffer[bufsize];
  186. ZSTD_inBuffer input = { data, data_size, 0 };
  187. ZSTD_outBuffer output = { output_buffer, bufsize, 0 };
  188. while (input.pos < input.size) {
  189. size_t ret = ZSTD_compressStream(stream.get(), &output, &input);
  190. if (ZSTD_isError(ret)) {
  191. dstream << ZSTD_getErrorName(ret) << std::endl;
  192. throw SerializationError("compressZstd: failed");
  193. }
  194. if (output.pos) {
  195. os.write(output_buffer, output.pos);
  196. output.pos = 0;
  197. }
  198. }
  199. size_t ret;
  200. do {
  201. ret = ZSTD_endStream(stream.get(), &output);
  202. if (ZSTD_isError(ret)) {
  203. dstream << ZSTD_getErrorName(ret) << std::endl;
  204. throw SerializationError("compressZstd: failed");
  205. }
  206. if (output.pos) {
  207. os.write(output_buffer, output.pos);
  208. output.pos = 0;
  209. }
  210. } while (ret != 0);
  211. }
  212. void compressZstd(const std::string &data, std::ostream &os, int level)
  213. {
  214. compressZstd((u8*)data.c_str(), data.size(), os, level);
  215. }
  216. void decompressZstd(std::istream &is, std::ostream &os)
  217. {
  218. // reusing the context is recommended for performance
  219. // it will be destroyed when the thread ends
  220. thread_local std::unique_ptr<ZSTD_DStream, ZSTD_Deleter> stream(ZSTD_createDStream());
  221. ZSTD_initDStream(stream.get());
  222. const size_t bufsize = 16384;
  223. char output_buffer[bufsize];
  224. char input_buffer[bufsize];
  225. ZSTD_outBuffer output = { output_buffer, bufsize, 0 };
  226. ZSTD_inBuffer input = { input_buffer, 0, 0 };
  227. size_t ret;
  228. do
  229. {
  230. if (input.size == input.pos) {
  231. is.read(input_buffer, bufsize);
  232. input.size = is.gcount();
  233. input.pos = 0;
  234. }
  235. ret = ZSTD_decompressStream(stream.get(), &output, &input);
  236. if (ZSTD_isError(ret)) {
  237. dstream << ZSTD_getErrorName(ret) << std::endl;
  238. throw SerializationError("decompressZstd: failed");
  239. }
  240. if (output.pos) {
  241. os.write(output_buffer, output.pos);
  242. output.pos = 0;
  243. }
  244. } while (ret != 0);
  245. // Unget all the data that ZSTD_decompressStream didn't take
  246. is.clear(); // Just in case EOF is set
  247. for (u32 i = 0; i < input.size - input.pos; i++) {
  248. is.unget();
  249. if (is.fail() || is.bad())
  250. throw SerializationError("decompressZstd: unget failed");
  251. }
  252. }
  253. void compress(u8 *data, u32 size, std::ostream &os, u8 version, int level)
  254. {
  255. if(version >= 29)
  256. {
  257. // map the zlib levels [0,9] to [1,10]. -1 becomes 0 which indicates the default (currently 3)
  258. compressZstd(data, size, os, level + 1);
  259. return;
  260. }
  261. if(version >= 11)
  262. {
  263. compressZlib(data, size, os, level);
  264. return;
  265. }
  266. if(size == 0)
  267. return;
  268. // Write length (u32)
  269. u8 tmp[4];
  270. writeU32(tmp, size);
  271. os.write((char*)tmp, 4);
  272. // We will be writing 8-bit pairs of more_count and byte
  273. u8 more_count = 0;
  274. u8 current_byte = data[0];
  275. for(u32 i=1; i<size; i++)
  276. {
  277. if(
  278. data[i] != current_byte
  279. || more_count == 255
  280. )
  281. {
  282. // write count and byte
  283. os.write((char*)&more_count, 1);
  284. os.write((char*)&current_byte, 1);
  285. more_count = 0;
  286. current_byte = data[i];
  287. }
  288. else
  289. {
  290. more_count++;
  291. }
  292. }
  293. // write count and byte
  294. os.write((char*)&more_count, 1);
  295. os.write((char*)&current_byte, 1);
  296. }
  297. void compress(const SharedBuffer<u8> &data, std::ostream &os, u8 version, int level)
  298. {
  299. compress(*data, data.getSize(), os, version, level);
  300. }
  301. void compress(const std::string &data, std::ostream &os, u8 version, int level)
  302. {
  303. compress((u8*)data.c_str(), data.size(), os, version, level);
  304. }
  305. void decompress(std::istream &is, std::ostream &os, u8 version)
  306. {
  307. if(version >= 29)
  308. {
  309. decompressZstd(is, os);
  310. return;
  311. }
  312. if(version >= 11)
  313. {
  314. decompressZlib(is, os);
  315. return;
  316. }
  317. // Read length (u32)
  318. u8 tmp[4];
  319. is.read((char*)tmp, 4);
  320. u32 len = readU32(tmp);
  321. // We will be reading 8-bit pairs of more_count and byte
  322. u32 count = 0;
  323. for(;;)
  324. {
  325. u8 more_count=0;
  326. u8 byte=0;
  327. is.read((char*)&more_count, 1);
  328. is.read((char*)&byte, 1);
  329. if(is.eof())
  330. throw SerializationError("decompress: stream ended halfway");
  331. for(s32 i=0; i<(u16)more_count+1; i++)
  332. os.write((char*)&byte, 1);
  333. count += (u16)more_count+1;
  334. if(count == len)
  335. break;
  336. }
  337. }