Packet.cpp 45 KB

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