Packet.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include <stdint.h>
  19. #include <stddef.h>
  20. #include <string.h>
  21. #include <stdlib.h>
  22. #include <stdio.h>
  23. #include "Packet.hpp"
  24. #ifdef ZT_USE_X64_ASM_SALSA2012
  25. #include "../ext/x64-salsa2012-asm/salsa2012.h"
  26. #endif
  27. #ifdef ZT_USE_ARM32_NEON_ASM_SALSA2012
  28. #include "../ext/arm32-neon-salsa2012-asm/salsa2012.h"
  29. #endif
  30. #ifdef _MSC_VER
  31. #define FORCE_INLINE static __forceinline
  32. #include <intrin.h>
  33. #pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  34. #pragma warning(disable : 4293) /* disable: C4293: too large shift (32-bits) */
  35. #else
  36. #define FORCE_INLINE static inline
  37. #endif
  38. namespace ZeroTier {
  39. /************************************************************************** */
  40. /* Set up macros for fast single-pass ASM Salsa20/12 crypto, if we have it */
  41. // x64 SSE crypto
  42. #ifdef ZT_USE_X64_ASM_SALSA2012
  43. #define ZT_HAS_FAST_CRYPTO() (true)
  44. #define ZT_FAST_SINGLE_PASS_SALSA2012(b,l,n,k) zt_salsa2012_amd64_xmm6(reinterpret_cast<unsigned char *>(b),(l),reinterpret_cast<const unsigned char *>(n),reinterpret_cast<const unsigned char *>(k))
  45. #endif
  46. // ARM (32-bit) NEON crypto (must be detected)
  47. #ifdef ZT_USE_ARM32_NEON_ASM_SALSA2012
  48. class _FastCryptoChecker
  49. {
  50. public:
  51. _FastCryptoChecker() : canHas(zt_arm_has_neon()) {}
  52. bool canHas;
  53. };
  54. static const _FastCryptoChecker _ZT_FAST_CRYPTO_CHECK;
  55. #define ZT_HAS_FAST_CRYPTO() (_ZT_FAST_CRYPTO_CHECK.canHas)
  56. #define ZT_FAST_SINGLE_PASS_SALSA2012(b,l,n,k) zt_salsa2012_armneon3_xor(reinterpret_cast<unsigned char *>(b),(const unsigned char *)0,(l),reinterpret_cast<const unsigned char *>(n),reinterpret_cast<const unsigned char *>(k))
  57. #endif
  58. // No fast crypto available
  59. #ifndef ZT_HAS_FAST_CRYPTO
  60. #define ZT_HAS_FAST_CRYPTO() (false)
  61. #define ZT_FAST_SINGLE_PASS_SALSA2012(b,l,n,k) {}
  62. #endif
  63. /************************************************************************** */
  64. /* LZ4 is shipped encapsulated into Packet in an anonymous namespace.
  65. *
  66. * We're doing this as a deliberate workaround for various Linux distribution
  67. * policies that forbid static linking of support libraries.
  68. *
  69. * The reason is that relying on distribution versions of LZ4 has been too
  70. * big a source of bugs and compatibility issues. The LZ4 API is not stable
  71. * enough across versions, and dependency hell ensues. So fark it. */
  72. /* Needless to say the code in this anonymous namespace should be considered
  73. * BSD 2-clause licensed. */
  74. namespace {
  75. /* lz4.h ------------------------------------------------------------------ */
  76. /*
  77. * LZ4 - Fast LZ compression algorithm
  78. * Header File
  79. * Copyright (C) 2011-2016, Yann Collet.
  80. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  81. Redistribution and use in source and binary forms, with or without
  82. modification, are permitted provided that the following conditions are
  83. met:
  84. * Redistributions of source code must retain the above copyright
  85. notice, this list of conditions and the following disclaimer.
  86. * Redistributions in binary form must reproduce the above
  87. copyright notice, this list of conditions and the following disclaimer
  88. in the documentation and/or other materials provided with the
  89. distribution.
  90. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  91. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  92. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  93. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  94. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  95. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  96. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  97. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  98. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  99. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  100. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  101. You can contact the author at :
  102. - LZ4 homepage : http://www.lz4.org
  103. - LZ4 source repository : https://github.com/lz4/lz4
  104. */
  105. /**
  106. Introduction
  107. LZ4 is lossless compression algorithm, providing compression speed at 400 MB/s per core,
  108. scalable with multi-cores CPU. It features an extremely fast decoder, with speed in
  109. multiple GB/s per core, typically reaching RAM speed limits on multi-core systems.
  110. The LZ4 compression library provides in-memory compression and decompression functions.
  111. Compression can be done in:
  112. - a single step (described as Simple Functions)
  113. - a single step, reusing a context (described in Advanced Functions)
  114. - unbounded multiple steps (described as Streaming compression)
  115. lz4.h provides block compression functions. It gives full buffer control to user.
  116. Decompressing an lz4-compressed block also requires metadata (such as compressed size).
  117. Each application is free to encode such metadata in whichever way it wants.
  118. An additional format, called LZ4 frame specification (doc/lz4_Frame_format.md),
  119. take care of encoding standard metadata alongside LZ4-compressed blocks.
  120. If your application requires interoperability, it's recommended to use it.
  121. A library is provided to take care of it, see lz4frame.h.
  122. */
  123. #define LZ4LIB_API
  124. /*========== Version =========== */
  125. #define LZ4_VERSION_MAJOR 1 /* for breaking interface changes */
  126. #define LZ4_VERSION_MINOR 7 /* for new (non-breaking) interface capabilities */
  127. #define LZ4_VERSION_RELEASE 5 /* for tweaks, bug-fixes, or development */
  128. #define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE)
  129. #define LZ4_LIB_VERSION LZ4_VERSION_MAJOR.LZ4_VERSION_MINOR.LZ4_VERSION_RELEASE
  130. #define LZ4_QUOTE(str) #str
  131. #define LZ4_EXPAND_AND_QUOTE(str) LZ4_QUOTE(str)
  132. #define LZ4_VERSION_STRING LZ4_EXPAND_AND_QUOTE(LZ4_LIB_VERSION)
  133. /*!
  134. * LZ4_MEMORY_USAGE :
  135. * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
  136. * Increasing memory usage improves compression ratio
  137. * Reduced memory usage can improve speed, due to cache effect
  138. * Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache
  139. */
  140. #define LZ4_MEMORY_USAGE 14
  141. #define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */
  142. #define LZ4_COMPRESSBOUND(isize) ((unsigned)(isize) > (unsigned)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16)
  143. /*-*********************************************
  144. * Streaming Compression Functions
  145. ***********************************************/
  146. typedef union LZ4_stream_u LZ4_stream_t; /* incomplete type (defined later) */
  147. /*! LZ4_resetStream() :
  148. * An LZ4_stream_t structure can be allocated once and re-used multiple times.
  149. * Use this function to init an allocated `LZ4_stream_t` structure and start a new compression.
  150. */
  151. LZ4LIB_API void LZ4_resetStream (LZ4_stream_t* streamPtr);
  152. /*^**********************************************
  153. * !!!!!! STATIC LINKING ONLY !!!!!!
  154. ***********************************************/
  155. /*-************************************
  156. * Private definitions
  157. **************************************
  158. * Do not use these definitions.
  159. * They are exposed to allow static allocation of `LZ4_stream_t` and `LZ4_streamDecode_t`.
  160. * Using these definitions will expose code to API and/or ABI break in future versions of the library.
  161. **************************************/
  162. #define LZ4_HASHLOG (LZ4_MEMORY_USAGE-2)
  163. #define LZ4_HASHTABLESIZE (1 << LZ4_MEMORY_USAGE)
  164. #define LZ4_HASH_SIZE_U32 (1 << LZ4_HASHLOG) /* required as macro for static allocation */
  165. typedef struct {
  166. uint32_t hashTable[LZ4_HASH_SIZE_U32];
  167. uint32_t currentOffset;
  168. uint32_t initCheck;
  169. const uint8_t* dictionary;
  170. uint8_t* bufferStart; /* obsolete, used for slideInputBuffer */
  171. uint32_t dictSize;
  172. } LZ4_stream_t_internal;
  173. typedef struct {
  174. const uint8_t* externalDict;
  175. size_t extDictSize;
  176. const uint8_t* prefixEnd;
  177. size_t prefixSize;
  178. } LZ4_streamDecode_t_internal;
  179. /*!
  180. * LZ4_stream_t :
  181. * information structure to track an LZ4 stream.
  182. * init this structure before first use.
  183. * note : only use in association with static linking !
  184. * this definition is not API/ABI safe,
  185. * and may change in a future version !
  186. */
  187. #define LZ4_STREAMSIZE_U64 ((1 << (LZ4_MEMORY_USAGE-3)) + 4)
  188. #define LZ4_STREAMSIZE (LZ4_STREAMSIZE_U64 * sizeof(unsigned long long))
  189. union LZ4_stream_u {
  190. unsigned long long table[LZ4_STREAMSIZE_U64];
  191. LZ4_stream_t_internal internal_donotuse;
  192. } ; /* previously typedef'd to LZ4_stream_t */
  193. /*!
  194. * LZ4_streamDecode_t :
  195. * information structure to track an LZ4 stream during decompression.
  196. * init this structure using LZ4_setStreamDecode (or memset()) before first use
  197. * note : only use in association with static linking !
  198. * this definition is not API/ABI safe,
  199. * and may change in a future version !
  200. */
  201. #define LZ4_STREAMDECODESIZE_U64 4
  202. #define LZ4_STREAMDECODESIZE (LZ4_STREAMDECODESIZE_U64 * sizeof(unsigned long long))
  203. union LZ4_streamDecode_u {
  204. unsigned long long table[LZ4_STREAMDECODESIZE_U64];
  205. LZ4_streamDecode_t_internal internal_donotuse;
  206. } ; /* previously typedef'd to LZ4_streamDecode_t */
  207. #ifndef HEAPMODE
  208. # define HEAPMODE 0
  209. #endif
  210. //#define ACCELERATION_DEFAULT 1
  211. /* LZ4_FORCE_MEMORY_ACCESS
  212. * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable.
  213. * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal.
  214. * The below switch allow to select different access method for improved performance.
  215. * Method 0 (default) : use `memcpy()`. Safe and portable.
  216. * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable).
  217. * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`.
  218. * Method 2 : direct access. This method is portable but violate C standard.
  219. * It can generate buggy code on targets which generate assembly depending on alignment.
  220. * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6)
  221. * See https://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details.
  222. * Prefer these methods in priority order (0 > 1 > 2)
  223. */
  224. #if 0
  225. #ifndef LZ4_FORCE_MEMORY_ACCESS /* can be defined externally, on command line for example */
  226. # if defined(__GNUC__) && ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) )
  227. # define LZ4_FORCE_MEMORY_ACCESS 2
  228. # elif defined(__INTEL_COMPILER) || \
  229. (defined(__GNUC__) && ( defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__) ))
  230. # define LZ4_FORCE_MEMORY_ACCESS 1
  231. # endif
  232. #endif
  233. #endif
  234. #ifdef ZT_NO_TYPE_PUNNING
  235. #define LZ4_FORCE_MEMORY_ACCESS 0
  236. #else
  237. #define LZ4_FORCE_MEMORY_ACCESS 2
  238. #endif
  239. /*
  240. * LZ4_FORCE_SW_BITCOUNT
  241. * Define this parameter if your target system or compiler does not support hardware bit count
  242. */
  243. #if defined(_MSC_VER) && defined(_WIN32_WCE) /* Visual Studio for Windows CE does not support Hardware bit count */
  244. # define LZ4_FORCE_SW_BITCOUNT
  245. #endif
  246. /*-************************************
  247. * Compiler Options
  248. **************************************/
  249. #if 0
  250. #ifdef _MSC_VER /* Visual Studio */
  251. # define FORCE_INLINE static __forceinline
  252. # include <intrin.h>
  253. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  254. # pragma warning(disable : 4293) /* disable: C4293: too large shift (32-bits) */
  255. #else
  256. # if defined(__GNUC__) || defined(__clang__)
  257. # define FORCE_INLINE static inline __attribute__((always_inline))
  258. # elif defined(__cplusplus) || (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  259. # define FORCE_INLINE static inline
  260. # else
  261. # define FORCE_INLINE static
  262. # endif
  263. #endif /* _MSC_VER */
  264. #endif
  265. #ifndef FORCE_INLINE
  266. #define FORCE_INLINE static inline
  267. #endif
  268. #if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__)
  269. # define expect(expr,value) (__builtin_expect ((expr),(value)) )
  270. #else
  271. # define expect(expr,value) (expr)
  272. #endif
  273. #define likely(expr) expect((expr) != 0, 1)
  274. #define unlikely(expr) expect((expr) != 0, 0)
  275. /*-************************************
  276. * Memory routines
  277. **************************************/
  278. //#include <stdlib.h> /* malloc, calloc, free */
  279. #define ALLOCATOR(n,s) calloc(n,s)
  280. #define FREEMEM free
  281. //#include <string.h> /* memset, memcpy */
  282. #define MEM_INIT memset
  283. /*-************************************
  284. * Basic Types
  285. **************************************/
  286. typedef uint8_t BYTE;
  287. typedef uint16_t U16;
  288. typedef uint32_t U32;
  289. typedef int32_t S32;
  290. typedef uint64_t U64;
  291. typedef uintptr_t uptrval;
  292. typedef uintptr_t reg_t;
  293. /*-************************************
  294. * Reading and writing into memory
  295. **************************************/
  296. static unsigned LZ4_isLittleEndian(void)
  297. {
  298. const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */
  299. return one.c[0];
  300. }
  301. #if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2)
  302. /* lie to the compiler about data alignment; use with caution */
  303. static U16 LZ4_read16(const void* memPtr) { return *(const U16*) memPtr; }
  304. static U32 LZ4_read32(const void* memPtr) { return *(const U32*) memPtr; }
  305. static reg_t LZ4_read_ARCH(const void* memPtr) { return *(const reg_t*) memPtr; }
  306. static void LZ4_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; }
  307. static void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; }
  308. #elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1)
  309. /* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */
  310. /* currently only defined for gcc and icc */
  311. typedef union { U16 u16; U32 u32; reg_t uArch; } __attribute__((packed)) unalign;
  312. static U16 LZ4_read16(const void* ptr) { return ((const unalign*)ptr)->u16; }
  313. static U32 LZ4_read32(const void* ptr) { return ((const unalign*)ptr)->u32; }
  314. static reg_t LZ4_read_ARCH(const void* ptr) { return ((const unalign*)ptr)->uArch; }
  315. static void LZ4_write16(void* memPtr, U16 value) { ((unalign*)memPtr)->u16 = value; }
  316. static void LZ4_write32(void* memPtr, U32 value) { ((unalign*)memPtr)->u32 = value; }
  317. #else /* safe and portable access through memcpy() */
  318. static inline U16 LZ4_read16(const void* memPtr)
  319. {
  320. U16 val; memcpy(&val, memPtr, sizeof(val)); return val;
  321. }
  322. static inline U32 LZ4_read32(const void* memPtr)
  323. {
  324. U32 val; memcpy(&val, memPtr, sizeof(val)); return val;
  325. }
  326. static inline reg_t LZ4_read_ARCH(const void* memPtr)
  327. {
  328. reg_t val; memcpy(&val, memPtr, sizeof(val)); return val;
  329. }
  330. static inline void LZ4_write16(void* memPtr, U16 value)
  331. {
  332. memcpy(memPtr, &value, sizeof(value));
  333. }
  334. static inline void LZ4_write32(void* memPtr, U32 value)
  335. {
  336. memcpy(memPtr, &value, sizeof(value));
  337. }
  338. #endif /* LZ4_FORCE_MEMORY_ACCESS */
  339. static inline U16 LZ4_readLE16(const void* memPtr)
  340. {
  341. if (LZ4_isLittleEndian()) {
  342. return LZ4_read16(memPtr);
  343. } else {
  344. const BYTE* p = (const BYTE*)memPtr;
  345. return (U16)((U16)p[0] + (p[1]<<8));
  346. }
  347. }
  348. static inline void LZ4_writeLE16(void* memPtr, U16 value)
  349. {
  350. if (LZ4_isLittleEndian()) {
  351. LZ4_write16(memPtr, value);
  352. } else {
  353. BYTE* p = (BYTE*)memPtr;
  354. p[0] = (BYTE) value;
  355. p[1] = (BYTE)(value>>8);
  356. }
  357. }
  358. static inline void LZ4_copy8(void* dst, const void* src)
  359. {
  360. memcpy(dst,src,8);
  361. }
  362. /* customized variant of memcpy, which can overwrite up to 8 bytes beyond dstEnd */
  363. static inline void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd)
  364. {
  365. BYTE* d = (BYTE*)dstPtr;
  366. const BYTE* s = (const BYTE*)srcPtr;
  367. BYTE* const e = (BYTE*)dstEnd;
  368. do { LZ4_copy8(d,s); d+=8; s+=8; } while (d<e);
  369. }
  370. /*-************************************
  371. * Common Constants
  372. **************************************/
  373. #define MINMATCH 4
  374. #define WILDCOPYLENGTH 8
  375. #define LASTLITERALS 5
  376. #define MFLIMIT (WILDCOPYLENGTH+MINMATCH)
  377. static const int LZ4_minLength = (MFLIMIT+1);
  378. #define KB *(1 <<10)
  379. #define MB *(1 <<20)
  380. #define GB *(1U<<30)
  381. #define MAXD_LOG 16
  382. #define MAX_DISTANCE ((1 << MAXD_LOG) - 1)
  383. #define ML_BITS 4
  384. #define ML_MASK ((1U<<ML_BITS)-1)
  385. #define RUN_BITS (8-ML_BITS)
  386. #define RUN_MASK ((1U<<RUN_BITS)-1)
  387. /*-************************************
  388. * Common Utils
  389. **************************************/
  390. #define LZ4_STATIC_ASSERT(c) { enum { LZ4_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
  391. /*-************************************
  392. * Common functions
  393. **************************************/
  394. static inline unsigned LZ4_NbCommonBytes (register reg_t val)
  395. {
  396. if (LZ4_isLittleEndian()) {
  397. if (sizeof(val)==8) {
  398. # if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
  399. unsigned long r = 0;
  400. _BitScanForward64( &r, (U64)val );
  401. return (int)(r>>3);
  402. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  403. return (__builtin_ctzll((U64)val) >> 3);
  404. # else
  405. static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 };
  406. return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];
  407. # endif
  408. } else /* 32 bits */ {
  409. # if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)
  410. unsigned long r;
  411. _BitScanForward( &r, (U32)val );
  412. return (int)(r>>3);
  413. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  414. return (__builtin_ctz((U32)val) >> 3);
  415. # else
  416. static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 };
  417. return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];
  418. # endif
  419. }
  420. } else /* Big Endian CPU */ {
  421. if (sizeof(val)==8) {
  422. # if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
  423. unsigned long r = 0;
  424. _BitScanReverse64( &r, val );
  425. return (unsigned)(r>>3);
  426. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  427. return (__builtin_clzll((U64)val) >> 3);
  428. # else
  429. unsigned r;
  430. if (!(val>>32)) { r=4; } else { r=0; val>>=32; }
  431. if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
  432. r += (!val);
  433. return r;
  434. # endif
  435. } else /* 32 bits */ {
  436. # if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)
  437. unsigned long r = 0;
  438. _BitScanReverse( &r, (unsigned long)val );
  439. return (unsigned)(r>>3);
  440. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  441. return (__builtin_clz((U32)val) >> 3);
  442. # else
  443. unsigned r;
  444. if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
  445. r += (!val);
  446. return r;
  447. # endif
  448. }
  449. }
  450. }
  451. #define STEPSIZE sizeof(reg_t)
  452. static inline unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit)
  453. {
  454. const BYTE* const pStart = pIn;
  455. while (likely(pIn<pInLimit-(STEPSIZE-1))) {
  456. reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
  457. if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; continue; }
  458. pIn += LZ4_NbCommonBytes(diff);
  459. return (unsigned)(pIn - pStart);
  460. }
  461. if ((STEPSIZE==8) && (pIn<(pInLimit-3)) && (LZ4_read32(pMatch) == LZ4_read32(pIn))) { pIn+=4; pMatch+=4; }
  462. if ((pIn<(pInLimit-1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn))) { pIn+=2; pMatch+=2; }
  463. if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;
  464. return (unsigned)(pIn - pStart);
  465. }
  466. /*-************************************
  467. * Local Constants
  468. **************************************/
  469. static const int LZ4_64Klimit = ((64 KB) + (MFLIMIT-1));
  470. static const U32 LZ4_skipTrigger = 6; /* Increase this value ==> compression run slower on incompressible data */
  471. /*-************************************
  472. * Local Structures and types
  473. **************************************/
  474. typedef enum { notLimited = 0, limitedOutput = 1 } limitedOutput_directive;
  475. typedef enum { byPtr, byU32, byU16 } tableType_t;
  476. typedef enum { noDict = 0, withPrefix64k, usingExtDict } dict_directive;
  477. typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive;
  478. typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive;
  479. typedef enum { full = 0, partial = 1 } earlyEnd_directive;
  480. /*-************************************
  481. * Local Utils
  482. **************************************/
  483. //int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; }
  484. //const char* LZ4_versionString(void) { return LZ4_VERSION_STRING; }
  485. int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); }
  486. //int LZ4_sizeofState() { return LZ4_STREAMSIZE; }
  487. /*-******************************
  488. * Compression functions
  489. ********************************/
  490. static inline U32 LZ4_hash4(U32 sequence, tableType_t const tableType)
  491. {
  492. if (tableType == byU16)
  493. return ((sequence * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1)));
  494. else
  495. return ((sequence * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG));
  496. }
  497. static inline U32 LZ4_hash5(U64 sequence, tableType_t const tableType)
  498. {
  499. static const U64 prime5bytes = 889523592379ULL;
  500. static const U64 prime8bytes = 11400714785074694791ULL;
  501. const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG;
  502. if (LZ4_isLittleEndian())
  503. return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog));
  504. else
  505. return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog));
  506. }
  507. FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tableType)
  508. {
  509. if ((sizeof(reg_t)==8) && (tableType != byU16)) return LZ4_hash5(LZ4_read_ARCH(p), tableType);
  510. return LZ4_hash4(LZ4_read32(p), tableType);
  511. }
  512. static inline void LZ4_putPositionOnHash(const BYTE* p, U32 h, void* tableBase, tableType_t const tableType, const BYTE* srcBase)
  513. {
  514. switch (tableType)
  515. {
  516. case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; }
  517. case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; }
  518. case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; }
  519. }
  520. }
  521. FORCE_INLINE void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)
  522. {
  523. U32 const h = LZ4_hashPosition(p, tableType);
  524. LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase);
  525. }
  526. static inline const BYTE* LZ4_getPositionOnHash(U32 h, void* tableBase, tableType_t tableType, const BYTE* srcBase)
  527. {
  528. if (tableType == byPtr) { const BYTE** hashTable = (const BYTE**) tableBase; return hashTable[h]; }
  529. if (tableType == byU32) { const U32* const hashTable = (U32*) tableBase; return hashTable[h] + srcBase; }
  530. { const U16* const hashTable = (U16*) tableBase; return hashTable[h] + srcBase; } /* default, to ensure a return */
  531. }
  532. FORCE_INLINE const BYTE* LZ4_getPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)
  533. {
  534. U32 const h = LZ4_hashPosition(p, tableType);
  535. return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase);
  536. }
  537. /** LZ4_compress_generic() :
  538. inlined, to ensure branches are decided at compilation time */
  539. FORCE_INLINE int LZ4_compress_generic(
  540. LZ4_stream_t_internal* const cctx,
  541. const char* const source,
  542. char* const dest,
  543. const int inputSize,
  544. const int maxOutputSize,
  545. const limitedOutput_directive outputLimited,
  546. const tableType_t tableType,
  547. const dict_directive dict,
  548. const dictIssue_directive dictIssue,
  549. const U32 acceleration)
  550. {
  551. const BYTE* ip = (const BYTE*) source;
  552. const BYTE* base;
  553. const BYTE* lowLimit;
  554. const BYTE* const lowRefLimit = ip - cctx->dictSize;
  555. const BYTE* const dictionary = cctx->dictionary;
  556. const BYTE* const dictEnd = dictionary + cctx->dictSize;
  557. const ptrdiff_t dictDelta = dictEnd - (const BYTE*)source;
  558. const BYTE* anchor = (const BYTE*) source;
  559. const BYTE* const iend = ip + inputSize;
  560. const BYTE* const mflimit = iend - MFLIMIT;
  561. const BYTE* const matchlimit = iend - LASTLITERALS;
  562. BYTE* op = (BYTE*) dest;
  563. BYTE* const olimit = op + maxOutputSize;
  564. U32 forwardH;
  565. /* Init conditions */
  566. if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported inputSize, too large (or negative) */
  567. switch(dict)
  568. {
  569. case noDict:
  570. default:
  571. base = (const BYTE*)source;
  572. lowLimit = (const BYTE*)source;
  573. break;
  574. case withPrefix64k:
  575. base = (const BYTE*)source - cctx->currentOffset;
  576. lowLimit = (const BYTE*)source - cctx->dictSize;
  577. break;
  578. case usingExtDict:
  579. base = (const BYTE*)source - cctx->currentOffset;
  580. lowLimit = (const BYTE*)source;
  581. break;
  582. }
  583. if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */
  584. if (inputSize<LZ4_minLength) goto _last_literals; /* Input too small, no compression (all literals) */
  585. /* First Byte */
  586. LZ4_putPosition(ip, cctx->hashTable, tableType, base);
  587. ip++; forwardH = LZ4_hashPosition(ip, tableType);
  588. /* Main Loop */
  589. for ( ; ; ) {
  590. ptrdiff_t refDelta = 0;
  591. const BYTE* match;
  592. BYTE* token;
  593. /* Find a match */
  594. { const BYTE* forwardIp = ip;
  595. unsigned step = 1;
  596. unsigned searchMatchNb = acceleration << LZ4_skipTrigger;
  597. do {
  598. U32 const h = forwardH;
  599. ip = forwardIp;
  600. forwardIp += step;
  601. step = (searchMatchNb++ >> LZ4_skipTrigger);
  602. if (unlikely(forwardIp > mflimit)) goto _last_literals;
  603. match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base);
  604. if (dict==usingExtDict) {
  605. if (match < (const BYTE*)source) {
  606. refDelta = dictDelta;
  607. lowLimit = dictionary;
  608. } else {
  609. refDelta = 0;
  610. lowLimit = (const BYTE*)source;
  611. } }
  612. forwardH = LZ4_hashPosition(forwardIp, tableType);
  613. LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base);
  614. } while ( ((dictIssue==dictSmall) ? (match < lowRefLimit) : 0)
  615. || ((tableType==byU16) ? 0 : (match + MAX_DISTANCE < ip))
  616. || (LZ4_read32(match+refDelta) != LZ4_read32(ip)) );
  617. }
  618. /* Catch up */
  619. while (((ip>anchor) & (match+refDelta > lowLimit)) && (unlikely(ip[-1]==match[refDelta-1]))) { ip--; match--; }
  620. /* Encode Literals */
  621. { unsigned const litLength = (unsigned)(ip - anchor);
  622. token = op++;
  623. if ((outputLimited) && /* Check output buffer overflow */
  624. (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit)))
  625. return 0;
  626. if (litLength >= RUN_MASK) {
  627. int len = (int)litLength-RUN_MASK;
  628. *token = (RUN_MASK<<ML_BITS);
  629. for(; len >= 255 ; len-=255) *op++ = 255;
  630. *op++ = (BYTE)len;
  631. }
  632. else *token = (BYTE)(litLength<<ML_BITS);
  633. /* Copy Literals */
  634. LZ4_wildCopy(op, anchor, op+litLength);
  635. op+=litLength;
  636. }
  637. _next_match:
  638. /* Encode Offset */
  639. LZ4_writeLE16(op, (U16)(ip-match)); op+=2;
  640. /* Encode MatchLength */
  641. { unsigned matchCode;
  642. if ((dict==usingExtDict) && (lowLimit==dictionary)) {
  643. const BYTE* limit;
  644. match += refDelta;
  645. limit = ip + (dictEnd-match);
  646. if (limit > matchlimit) limit = matchlimit;
  647. matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, limit);
  648. ip += MINMATCH + matchCode;
  649. if (ip==limit) {
  650. unsigned const more = LZ4_count(ip, (const BYTE*)source, matchlimit);
  651. matchCode += more;
  652. ip += more;
  653. }
  654. } else {
  655. matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit);
  656. ip += MINMATCH + matchCode;
  657. }
  658. if ( outputLimited && /* Check output buffer overflow */
  659. (unlikely(op + (1 + LASTLITERALS) + (matchCode>>8) > olimit)) )
  660. return 0;
  661. if (matchCode >= ML_MASK) {
  662. *token += ML_MASK;
  663. matchCode -= ML_MASK;
  664. LZ4_write32(op, 0xFFFFFFFF);
  665. while (matchCode >= 4*255) op+=4, LZ4_write32(op, 0xFFFFFFFF), matchCode -= 4*255;
  666. op += matchCode / 255;
  667. *op++ = (BYTE)(matchCode % 255);
  668. } else
  669. *token += (BYTE)(matchCode);
  670. }
  671. anchor = ip;
  672. /* Test end of chunk */
  673. if (ip > mflimit) break;
  674. /* Fill table */
  675. LZ4_putPosition(ip-2, cctx->hashTable, tableType, base);
  676. /* Test next position */
  677. match = LZ4_getPosition(ip, cctx->hashTable, tableType, base);
  678. if (dict==usingExtDict) {
  679. if (match < (const BYTE*)source) {
  680. refDelta = dictDelta;
  681. lowLimit = dictionary;
  682. } else {
  683. refDelta = 0;
  684. lowLimit = (const BYTE*)source;
  685. } }
  686. LZ4_putPosition(ip, cctx->hashTable, tableType, base);
  687. if ( ((dictIssue==dictSmall) ? (match>=lowRefLimit) : 1)
  688. && (match+MAX_DISTANCE>=ip)
  689. && (LZ4_read32(match+refDelta)==LZ4_read32(ip)) )
  690. { token=op++; *token=0; goto _next_match; }
  691. /* Prepare next loop */
  692. forwardH = LZ4_hashPosition(++ip, tableType);
  693. }
  694. _last_literals:
  695. /* Encode Last Literals */
  696. { size_t const lastRun = (size_t)(iend - anchor);
  697. if ( (outputLimited) && /* Check output buffer overflow */
  698. ((op - (BYTE*)dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize) )
  699. return 0;
  700. if (lastRun >= RUN_MASK) {
  701. size_t accumulator = lastRun - RUN_MASK;
  702. *op++ = RUN_MASK << ML_BITS;
  703. for(; accumulator >= 255 ; accumulator-=255) *op++ = 255;
  704. *op++ = (BYTE) accumulator;
  705. } else {
  706. *op++ = (BYTE)(lastRun<<ML_BITS);
  707. }
  708. memcpy(op, anchor, lastRun);
  709. op += lastRun;
  710. }
  711. /* End */
  712. return (int) (((char*)op)-dest);
  713. }
  714. static inline int LZ4_compress_fast_extState(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
  715. {
  716. LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)state)->internal_donotuse;
  717. LZ4_resetStream((LZ4_stream_t*)state);
  718. //if (acceleration < 1) acceleration = ACCELERATION_DEFAULT;
  719. if (maxOutputSize >= LZ4_compressBound(inputSize)) {
  720. if (inputSize < LZ4_64Klimit)
  721. return LZ4_compress_generic(ctx, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue, acceleration);
  722. else
  723. return LZ4_compress_generic(ctx, source, dest, inputSize, 0, notLimited, (sizeof(void*)==8) ? byU32 : byPtr, noDict, noDictIssue, acceleration);
  724. } else {
  725. if (inputSize < LZ4_64Klimit)
  726. return LZ4_compress_generic(ctx, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration);
  727. else
  728. return LZ4_compress_generic(ctx, source, dest, inputSize, maxOutputSize, limitedOutput, (sizeof(void*)==8) ? byU32 : byPtr, noDict, noDictIssue, acceleration);
  729. }
  730. }
  731. static inline int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
  732. {
  733. #if (HEAPMODE)
  734. void* ctxPtr = ALLOCATOR(1, sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */
  735. #else
  736. LZ4_stream_t ctx;
  737. void* const ctxPtr = &ctx;
  738. #endif
  739. int const result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration);
  740. #if (HEAPMODE)
  741. FREEMEM(ctxPtr);
  742. #endif
  743. return result;
  744. }
  745. void LZ4_resetStream (LZ4_stream_t* LZ4_stream)
  746. {
  747. MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t));
  748. }
  749. /*-*****************************
  750. * Decompression functions
  751. *******************************/
  752. /*! LZ4_decompress_generic() :
  753. * This generic decompression function cover all use cases.
  754. * It shall be instantiated several times, using different sets of directives
  755. * Note that it is important this generic function is really inlined,
  756. * in order to remove useless branches during compilation optimization.
  757. */
  758. FORCE_INLINE int LZ4_decompress_generic(
  759. const char* const source,
  760. char* const dest,
  761. int inputSize,
  762. int outputSize, /* If endOnInput==endOnInputSize, this value is the max size of Output Buffer. */
  763. int endOnInput, /* endOnOutputSize, endOnInputSize */
  764. int partialDecoding, /* full, partial */
  765. int targetOutputSize, /* only used if partialDecoding==partial */
  766. int dict, /* noDict, withPrefix64k, usingExtDict */
  767. const BYTE* const lowPrefix, /* == dest when no prefix */
  768. const BYTE* const dictStart, /* only if dict==usingExtDict */
  769. const size_t dictSize /* note : = 0 if noDict */
  770. )
  771. {
  772. /* Local Variables */
  773. const BYTE* ip = (const BYTE*) source;
  774. const BYTE* const iend = ip + inputSize;
  775. BYTE* op = (BYTE*) dest;
  776. BYTE* const oend = op + outputSize;
  777. BYTE* cpy;
  778. BYTE* oexit = op + targetOutputSize;
  779. const BYTE* const lowLimit = lowPrefix - dictSize;
  780. const BYTE* const dictEnd = (const BYTE*)dictStart + dictSize;
  781. const unsigned dec32table[] = {0, 1, 2, 1, 4, 4, 4, 4};
  782. const int dec64table[] = {0, 0, 0, -1, 0, 1, 2, 3};
  783. const int safeDecode = (endOnInput==endOnInputSize);
  784. const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB)));
  785. /* Special cases */
  786. if ((partialDecoding) && (oexit > oend-MFLIMIT)) oexit = oend-MFLIMIT; /* targetOutputSize too high => decode everything */
  787. if ((endOnInput) && (unlikely(outputSize==0))) return ((inputSize==1) && (*ip==0)) ? 0 : -1; /* Empty output buffer */
  788. if ((!endOnInput) && (unlikely(outputSize==0))) return (*ip==0?1:-1);
  789. /* Main Loop : decode sequences */
  790. while (1) {
  791. size_t length;
  792. const BYTE* match;
  793. size_t offset;
  794. /* get literal length */
  795. unsigned const token = *ip++;
  796. if ((length=(token>>ML_BITS)) == RUN_MASK) {
  797. unsigned s;
  798. do {
  799. s = *ip++;
  800. length += s;
  801. } while ( likely(endOnInput ? ip<iend-RUN_MASK : 1) & (s==255) );
  802. if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)(op))) goto _output_error; /* overflow detection */
  803. if ((safeDecode) && unlikely((uptrval)(ip)+length<(uptrval)(ip))) goto _output_error; /* overflow detection */
  804. }
  805. /* copy literals */
  806. cpy = op+length;
  807. if ( ((endOnInput) && ((cpy>(partialDecoding?oexit:oend-MFLIMIT)) || (ip+length>iend-(2+1+LASTLITERALS))) )
  808. || ((!endOnInput) && (cpy>oend-WILDCOPYLENGTH)) )
  809. {
  810. if (partialDecoding) {
  811. if (cpy > oend) goto _output_error; /* Error : write attempt beyond end of output buffer */
  812. if ((endOnInput) && (ip+length > iend)) goto _output_error; /* Error : read attempt beyond end of input buffer */
  813. } else {
  814. if ((!endOnInput) && (cpy != oend)) goto _output_error; /* Error : block decoding must stop exactly there */
  815. if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) goto _output_error; /* Error : input must be consumed */
  816. }
  817. memcpy(op, ip, length);
  818. ip += length;
  819. op += length;
  820. break; /* Necessarily EOF, due to parsing restrictions */
  821. }
  822. LZ4_wildCopy(op, ip, cpy);
  823. ip += length; op = cpy;
  824. /* get offset */
  825. offset = LZ4_readLE16(ip); ip+=2;
  826. match = op - offset;
  827. if ((checkOffset) && (unlikely(match < lowLimit))) goto _output_error; /* Error : offset outside buffers */
  828. LZ4_write32(op, (U32)offset); /* costs ~1%; silence an msan warning when offset==0 */
  829. /* get matchlength */
  830. length = token & ML_MASK;
  831. if (length == ML_MASK) {
  832. unsigned s;
  833. do {
  834. s = *ip++;
  835. if ((endOnInput) && (ip > iend-LASTLITERALS)) goto _output_error;
  836. length += s;
  837. } while (s==255);
  838. if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error; /* overflow detection */
  839. }
  840. length += MINMATCH;
  841. /* check external dictionary */
  842. if ((dict==usingExtDict) && (match < lowPrefix)) {
  843. if (unlikely(op+length > oend-LASTLITERALS)) goto _output_error; /* doesn't respect parsing restriction */
  844. if (length <= (size_t)(lowPrefix-match)) {
  845. /* match can be copied as a single segment from external dictionary */
  846. memmove(op, dictEnd - (lowPrefix-match), length);
  847. op += length;
  848. } else {
  849. /* match encompass external dictionary and current block */
  850. size_t const copySize = (size_t)(lowPrefix-match);
  851. size_t const restSize = length - copySize;
  852. memcpy(op, dictEnd - copySize, copySize);
  853. op += copySize;
  854. if (restSize > (size_t)(op-lowPrefix)) { /* overlap copy */
  855. BYTE* const endOfMatch = op + restSize;
  856. const BYTE* copyFrom = lowPrefix;
  857. while (op < endOfMatch) *op++ = *copyFrom++;
  858. } else {
  859. memcpy(op, lowPrefix, restSize);
  860. op += restSize;
  861. } }
  862. continue;
  863. }
  864. /* copy match within block */
  865. cpy = op + length;
  866. if (unlikely(offset<8)) {
  867. const int dec64 = dec64table[offset];
  868. op[0] = match[0];
  869. op[1] = match[1];
  870. op[2] = match[2];
  871. op[3] = match[3];
  872. match += dec32table[offset];
  873. memcpy(op+4, match, 4);
  874. match -= dec64;
  875. } else { LZ4_copy8(op, match); match+=8; }
  876. op += 8;
  877. if (unlikely(cpy>oend-12)) {
  878. BYTE* const oCopyLimit = oend-(WILDCOPYLENGTH-1);
  879. if (cpy > oend-LASTLITERALS) goto _output_error; /* Error : last LASTLITERALS bytes must be literals (uncompressed) */
  880. if (op < oCopyLimit) {
  881. LZ4_wildCopy(op, match, oCopyLimit);
  882. match += oCopyLimit - op;
  883. op = oCopyLimit;
  884. }
  885. while (op<cpy) *op++ = *match++;
  886. } else {
  887. LZ4_copy8(op, match);
  888. if (length>16) LZ4_wildCopy(op+8, match+8, cpy);
  889. }
  890. op=cpy; /* correction */
  891. }
  892. /* end of decoding */
  893. if (endOnInput)
  894. return (int) (((char*)op)-dest); /* Nb of output bytes decoded */
  895. else
  896. return (int) (((const char*)ip)-source); /* Nb of input bytes read */
  897. /* Overflow error detected */
  898. _output_error:
  899. return (int) (-(((const char*)ip)-source))-1;
  900. }
  901. static inline int LZ4_decompress_safe(const char* source, char* dest, int compressedSize, int maxDecompressedSize)
  902. {
  903. return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, endOnInputSize, full, 0, noDict, (BYTE*)dest, NULL, 0);
  904. }
  905. } // anonymous namespace
  906. /************************************************************************** */
  907. /************************************************************************** */
  908. const unsigned char Packet::ZERO_KEY[32] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
  909. #ifdef ZT_TRACE
  910. const char *Packet::verbString(Verb v)
  911. {
  912. switch(v) {
  913. case VERB_NOP: return "NOP";
  914. case VERB_HELLO: return "HELLO";
  915. case VERB_ERROR: return "ERROR";
  916. case VERB_OK: return "OK";
  917. case VERB_WHOIS: return "WHOIS";
  918. case VERB_RENDEZVOUS: return "RENDEZVOUS";
  919. case VERB_FRAME: return "FRAME";
  920. case VERB_EXT_FRAME: return "EXT_FRAME";
  921. case VERB_ECHO: return "ECHO";
  922. case VERB_MULTICAST_LIKE: return "MULTICAST_LIKE";
  923. case VERB_NETWORK_CREDENTIALS: return "NETWORK_CREDENTIALS";
  924. case VERB_NETWORK_CONFIG_REQUEST: return "NETWORK_CONFIG_REQUEST";
  925. case VERB_NETWORK_CONFIG: return "NETWORK_CONFIG";
  926. case VERB_MULTICAST_GATHER: return "MULTICAST_GATHER";
  927. case VERB_MULTICAST_FRAME: return "MULTICAST_FRAME";
  928. case VERB_PUSH_DIRECT_PATHS: return "PUSH_DIRECT_PATHS";
  929. case VERB_CIRCUIT_TEST: return "CIRCUIT_TEST";
  930. case VERB_CIRCUIT_TEST_REPORT: return "CIRCUIT_TEST_REPORT";
  931. case VERB_USER_MESSAGE: return "USER_MESSAGE";
  932. }
  933. return "(unknown)";
  934. }
  935. const char *Packet::errorString(ErrorCode e)
  936. {
  937. switch(e) {
  938. case ERROR_NONE: return "NONE";
  939. case ERROR_INVALID_REQUEST: return "INVALID_REQUEST";
  940. case ERROR_BAD_PROTOCOL_VERSION: return "BAD_PROTOCOL_VERSION";
  941. case ERROR_OBJ_NOT_FOUND: return "OBJECT_NOT_FOUND";
  942. case ERROR_IDENTITY_COLLISION: return "IDENTITY_COLLISION";
  943. case ERROR_UNSUPPORTED_OPERATION: return "UNSUPPORTED_OPERATION";
  944. case ERROR_NEED_MEMBERSHIP_CERTIFICATE: return "NEED_MEMBERSHIP_CERTIFICATE";
  945. case ERROR_NETWORK_ACCESS_DENIED_: return "NETWORK_ACCESS_DENIED";
  946. case ERROR_UNWANTED_MULTICAST: return "UNWANTED_MULTICAST";
  947. }
  948. return "(unknown)";
  949. }
  950. #endif // ZT_TRACE
  951. void Packet::armor(const void *key,bool encryptPayload,unsigned int counter)
  952. {
  953. uint8_t mangledKey[32];
  954. uint8_t *const data = reinterpret_cast<uint8_t *>(unsafeData());
  955. // Mask least significant 3 bits of packet ID with counter to embed packet send counter for QoS use
  956. data[7] = (data[7] & 0xf8) | (uint8_t)(counter & 0x07);
  957. // Set flag now, since it affects key mangle function
  958. setCipher(encryptPayload ? ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012 : ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE);
  959. _salsa20MangleKey((const unsigned char *)key,mangledKey);
  960. if (ZT_HAS_FAST_CRYPTO()) {
  961. const unsigned int encryptLen = (encryptPayload) ? (size() - ZT_PACKET_IDX_VERB) : 0;
  962. uint64_t keyStream[(ZT_PROTO_MAX_PACKET_LENGTH + 64 + 8) / 8];
  963. ZT_FAST_SINGLE_PASS_SALSA2012(keyStream,encryptLen + 64,(data + ZT_PACKET_IDX_IV),mangledKey);
  964. Salsa20::memxor(data + ZT_PACKET_IDX_VERB,reinterpret_cast<const uint8_t *>(keyStream + 8),encryptLen);
  965. uint64_t mac[2];
  966. Poly1305::compute(mac,data + ZT_PACKET_IDX_VERB,size() - ZT_PACKET_IDX_VERB,keyStream);
  967. #ifdef ZT_NO_TYPE_PUNNING
  968. memcpy(data + ZT_PACKET_IDX_MAC,mac,8);
  969. #else
  970. (*reinterpret_cast<uint64_t *>(data + ZT_PACKET_IDX_MAC)) = mac[0];
  971. #endif
  972. } else {
  973. Salsa20 s20(mangledKey,data + ZT_PACKET_IDX_IV);
  974. uint64_t macKey[4];
  975. s20.crypt12(ZERO_KEY,macKey,sizeof(macKey));
  976. uint8_t *const payload = data + ZT_PACKET_IDX_VERB;
  977. const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
  978. if (encryptPayload)
  979. s20.crypt12(payload,payload,payloadLen);
  980. uint64_t mac[2];
  981. Poly1305::compute(mac,payload,payloadLen,macKey);
  982. memcpy(data + ZT_PACKET_IDX_MAC,mac,8);
  983. }
  984. }
  985. bool Packet::dearmor(const void *key)
  986. {
  987. uint8_t mangledKey[32];
  988. uint8_t *const data = reinterpret_cast<uint8_t *>(unsafeData());
  989. const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
  990. unsigned char *const payload = data + ZT_PACKET_IDX_VERB;
  991. const unsigned int cs = cipher();
  992. if ((cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE)||(cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)) {
  993. _salsa20MangleKey((const unsigned char *)key,mangledKey);
  994. if (ZT_HAS_FAST_CRYPTO()) {
  995. uint64_t keyStream[(ZT_PROTO_MAX_PACKET_LENGTH + 64 + 8) / 8];
  996. ZT_FAST_SINGLE_PASS_SALSA2012(keyStream,((cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012) ? (payloadLen + 64) : 64),(data + ZT_PACKET_IDX_IV),mangledKey);
  997. uint64_t mac[2];
  998. Poly1305::compute(mac,payload,payloadLen,keyStream);
  999. #ifdef ZT_NO_TYPE_PUNNING
  1000. if (!Utils::secureEq(mac,data + ZT_PACKET_IDX_MAC,8))
  1001. return false;
  1002. #else
  1003. if ((*reinterpret_cast<const uint64_t *>(data + ZT_PACKET_IDX_MAC)) != mac[0]) // also secure, constant time
  1004. return false;
  1005. #endif
  1006. if (cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
  1007. Salsa20::memxor(data + ZT_PACKET_IDX_VERB,reinterpret_cast<const uint8_t *>(keyStream + 8),payloadLen);
  1008. } else {
  1009. Salsa20 s20(mangledKey,data + ZT_PACKET_IDX_IV);
  1010. uint64_t macKey[4];
  1011. s20.crypt12(ZERO_KEY,macKey,sizeof(macKey));
  1012. uint64_t mac[2];
  1013. Poly1305::compute(mac,payload,payloadLen,macKey);
  1014. #ifdef ZT_NO_TYPE_PUNNING
  1015. if (!Utils::secureEq(mac,data + ZT_PACKET_IDX_MAC,8))
  1016. return false;
  1017. #else
  1018. if ((*reinterpret_cast<const uint64_t *>(data + ZT_PACKET_IDX_MAC)) != mac[0]) // also secure, constant time
  1019. return false;
  1020. #endif
  1021. if (cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
  1022. s20.crypt12(payload,payload,payloadLen);
  1023. }
  1024. return true;
  1025. } else {
  1026. return false; // unrecognized cipher suite
  1027. }
  1028. }
  1029. void Packet::cryptField(const void *key,unsigned int start,unsigned int len)
  1030. {
  1031. uint8_t *const data = reinterpret_cast<uint8_t *>(unsafeData());
  1032. uint8_t iv[8];
  1033. for(int i=0;i<8;++i) iv[i] = data[i];
  1034. iv[7] &= 0xf8; // mask off least significant 3 bits of packet ID / IV since this is unset when this function gets called
  1035. Salsa20 s20(key,iv);
  1036. s20.crypt12(data + start,data + start,len);
  1037. }
  1038. bool Packet::compress()
  1039. {
  1040. char *const data = reinterpret_cast<char *>(unsafeData());
  1041. char buf[ZT_PROTO_MAX_PACKET_LENGTH * 2];
  1042. if ((!compressed())&&(size() > (ZT_PACKET_IDX_PAYLOAD + 64))) { // don't bother compressing tiny packets
  1043. int pl = (int)(size() - ZT_PACKET_IDX_PAYLOAD);
  1044. int cl = LZ4_compress_fast(data + ZT_PACKET_IDX_PAYLOAD,buf,pl,ZT_PROTO_MAX_PACKET_LENGTH * 2,2);
  1045. if ((cl > 0)&&(cl < pl)) {
  1046. data[ZT_PACKET_IDX_VERB] |= (char)ZT_PROTO_VERB_FLAG_COMPRESSED;
  1047. setSize((unsigned int)cl + ZT_PACKET_IDX_PAYLOAD);
  1048. memcpy(data + ZT_PACKET_IDX_PAYLOAD,buf,cl);
  1049. return true;
  1050. }
  1051. }
  1052. data[ZT_PACKET_IDX_VERB] &= (char)(~ZT_PROTO_VERB_FLAG_COMPRESSED);
  1053. return false;
  1054. }
  1055. bool Packet::uncompress()
  1056. {
  1057. char *const data = reinterpret_cast<char *>(unsafeData());
  1058. char buf[ZT_PROTO_MAX_PACKET_LENGTH];
  1059. if ((compressed())&&(size() >= ZT_PROTO_MIN_PACKET_LENGTH)) {
  1060. if (size() > ZT_PACKET_IDX_PAYLOAD) {
  1061. unsigned int compLen = size() - ZT_PACKET_IDX_PAYLOAD;
  1062. int ucl = LZ4_decompress_safe((const char *)data + ZT_PACKET_IDX_PAYLOAD,buf,compLen,sizeof(buf));
  1063. if ((ucl > 0)&&(ucl <= (int)(capacity() - ZT_PACKET_IDX_PAYLOAD))) {
  1064. setSize((unsigned int)ucl + ZT_PACKET_IDX_PAYLOAD);
  1065. memcpy(data + ZT_PACKET_IDX_PAYLOAD,buf,ucl);
  1066. } else {
  1067. return false;
  1068. }
  1069. }
  1070. data[ZT_PACKET_IDX_VERB] &= (char)(~ZT_PROTO_VERB_FLAG_COMPRESSED);
  1071. }
  1072. return true;
  1073. }
  1074. } // namespace ZeroTier