Packet.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 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 LZ4_VERSION_MAJOR 1 /* for breaking interface changes */
  132. #define LZ4_VERSION_MINOR 7 /* for new (non-breaking) interface capabilities */
  133. #define LZ4_VERSION_RELEASE 5 /* for tweaks, bug-fixes, or development */
  134. #define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE)
  135. #define LZ4_LIB_VERSION LZ4_VERSION_MAJOR.LZ4_VERSION_MINOR.LZ4_VERSION_RELEASE
  136. #define LZ4_QUOTE(str) #str
  137. #define LZ4_EXPAND_AND_QUOTE(str) LZ4_QUOTE(str)
  138. #define LZ4_VERSION_STRING LZ4_EXPAND_AND_QUOTE(LZ4_LIB_VERSION)
  139. #define LZ4_MEMORY_USAGE 14
  140. #define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */
  141. #define LZ4_COMPRESSBOUND(isize) ((unsigned)(isize) > (unsigned)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16)
  142. typedef union LZ4_stream_u LZ4_stream_t; /* incomplete type (defined later) */
  143. static inline void LZ4_resetStream (LZ4_stream_t* streamPtr);
  144. #define LZ4_HASHLOG (LZ4_MEMORY_USAGE-2)
  145. #define LZ4_HASHTABLESIZE (1 << LZ4_MEMORY_USAGE)
  146. #define LZ4_HASH_SIZE_U32 (1 << LZ4_HASHLOG) /* required as macro for static allocation */
  147. typedef struct {
  148. uint32_t hashTable[LZ4_HASH_SIZE_U32];
  149. uint32_t currentOffset;
  150. uint32_t initCheck;
  151. const uint8_t* dictionary;
  152. uint8_t* bufferStart; /* obsolete, used for slideInputBuffer */
  153. uint32_t dictSize;
  154. } LZ4_stream_t_internal;
  155. typedef struct {
  156. const uint8_t* externalDict;
  157. size_t extDictSize;
  158. const uint8_t* prefixEnd;
  159. size_t prefixSize;
  160. } LZ4_streamDecode_t_internal;
  161. #define LZ4_STREAMSIZE_U64 ((1 << (LZ4_MEMORY_USAGE-3)) + 4)
  162. #define LZ4_STREAMSIZE (LZ4_STREAMSIZE_U64 * sizeof(unsigned long long))
  163. union LZ4_stream_u {
  164. unsigned long long table[LZ4_STREAMSIZE_U64];
  165. LZ4_stream_t_internal internal_donotuse;
  166. } ; /* previously typedef'd to LZ4_stream_t */
  167. #define LZ4_STREAMDECODESIZE_U64 4
  168. #define LZ4_STREAMDECODESIZE (LZ4_STREAMDECODESIZE_U64 * sizeof(unsigned long long))
  169. union LZ4_streamDecode_u {
  170. unsigned long long table[LZ4_STREAMDECODESIZE_U64];
  171. LZ4_streamDecode_t_internal internal_donotuse;
  172. } ; /* previously typedef'd to LZ4_streamDecode_t */
  173. #ifndef HEAPMODE
  174. #define HEAPMODE 0
  175. #endif
  176. #ifdef ZT_NO_TYPE_PUNNING
  177. #define LZ4_FORCE_MEMORY_ACCESS 0
  178. #else
  179. #define LZ4_FORCE_MEMORY_ACCESS 2
  180. #endif
  181. #if defined(_MSC_VER) && defined(_WIN32_WCE) /* Visual Studio for Windows CE does not support Hardware bit count */
  182. #define LZ4_FORCE_SW_BITCOUNT
  183. #endif
  184. #ifndef FORCE_INLINE
  185. #define FORCE_INLINE static inline
  186. #endif
  187. #define ALLOCATOR(n,s) calloc(n,s)
  188. #define FREEMEM free
  189. #define MEM_INIT memset
  190. typedef uint8_t BYTE;
  191. typedef uint16_t U16;
  192. typedef uint32_t U32;
  193. typedef int32_t S32;
  194. typedef uint64_t U64;
  195. typedef uintptr_t uptrval;
  196. typedef uintptr_t reg_t;
  197. static inline unsigned LZ4_isLittleEndian(void)
  198. {
  199. const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */
  200. return one.c[0];
  201. }
  202. #if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2)
  203. static U16 LZ4_read16(const void* memPtr) { return *(const U16*) memPtr; }
  204. static U32 LZ4_read32(const void* memPtr) { return *(const U32*) memPtr; }
  205. static reg_t LZ4_read_ARCH(const void* memPtr) { return *(const reg_t*) memPtr; }
  206. static void LZ4_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; }
  207. static void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; }
  208. #elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1)
  209. typedef union { U16 u16; U32 u32; reg_t uArch; } __attribute__((packed)) unalign;
  210. static U16 LZ4_read16(const void* ptr) { return ((const unalign*)ptr)->u16; }
  211. static U32 LZ4_read32(const void* ptr) { return ((const unalign*)ptr)->u32; }
  212. static reg_t LZ4_read_ARCH(const void* ptr) { return ((const unalign*)ptr)->uArch; }
  213. static void LZ4_write16(void* memPtr, U16 value) { ((unalign*)memPtr)->u16 = value; }
  214. static void LZ4_write32(void* memPtr, U32 value) { ((unalign*)memPtr)->u32 = value; }
  215. #else /* safe and portable access through memcpy() */
  216. static inline U16 LZ4_read16(const void* memPtr)
  217. {
  218. U16 val; memcpy(&val, memPtr, sizeof(val)); return val;
  219. }
  220. static inline U32 LZ4_read32(const void* memPtr)
  221. {
  222. U32 val; memcpy(&val, memPtr, sizeof(val)); return val;
  223. }
  224. static inline reg_t LZ4_read_ARCH(const void* memPtr)
  225. {
  226. reg_t val; memcpy(&val, memPtr, sizeof(val)); return val;
  227. }
  228. static inline void LZ4_write16(void* memPtr, U16 value)
  229. {
  230. memcpy(memPtr, &value, sizeof(value));
  231. }
  232. static inline void LZ4_write32(void* memPtr, U32 value)
  233. {
  234. memcpy(memPtr, &value, sizeof(value));
  235. }
  236. #endif /* LZ4_FORCE_MEMORY_ACCESS */
  237. static inline U16 LZ4_readLE16(const void* memPtr)
  238. {
  239. if (LZ4_isLittleEndian()) {
  240. return LZ4_read16(memPtr);
  241. } else {
  242. const BYTE* p = (const BYTE*)memPtr;
  243. return (U16)((U16)p[0] + (p[1]<<8));
  244. }
  245. }
  246. static inline void LZ4_writeLE16(void* memPtr, U16 value)
  247. {
  248. if (LZ4_isLittleEndian()) {
  249. LZ4_write16(memPtr, value);
  250. } else {
  251. BYTE* p = (BYTE*)memPtr;
  252. p[0] = (BYTE) value;
  253. p[1] = (BYTE)(value>>8);
  254. }
  255. }
  256. static inline void LZ4_copy8(void* dst, const void* src)
  257. {
  258. memcpy(dst,src,8);
  259. }
  260. static inline void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd)
  261. {
  262. BYTE* d = (BYTE*)dstPtr;
  263. const BYTE* s = (const BYTE*)srcPtr;
  264. BYTE* const e = (BYTE*)dstEnd;
  265. do { LZ4_copy8(d,s); d+=8; s+=8; } while (d<e);
  266. }
  267. #define MINMATCH 4
  268. #define WILDCOPYLENGTH 8
  269. #define LASTLITERALS 5
  270. #define MFLIMIT (WILDCOPYLENGTH+MINMATCH)
  271. static const int LZ4_minLength = (MFLIMIT+1);
  272. #define KB *(1 <<10)
  273. #define MB *(1 <<20)
  274. #define GB *(1U<<30)
  275. #define MAXD_LOG 16
  276. #define MAX_DISTANCE ((1 << MAXD_LOG) - 1)
  277. #define ML_BITS 4
  278. #define ML_MASK ((1U<<ML_BITS)-1)
  279. #define RUN_BITS (8-ML_BITS)
  280. #define RUN_MASK ((1U<<RUN_BITS)-1)
  281. #define LZ4_STATIC_ASSERT(c) { enum { LZ4_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
  282. static inline unsigned LZ4_NbCommonBytes (reg_t val)
  283. {
  284. if (LZ4_isLittleEndian()) {
  285. if (sizeof(val)==8) {
  286. # if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
  287. unsigned long r = 0;
  288. _BitScanForward64( &r, (U64)val );
  289. return (int)(r>>3);
  290. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  291. return (__builtin_ctzll((U64)val) >> 3);
  292. # else
  293. 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 };
  294. return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];
  295. # endif
  296. } else /* 32 bits */ {
  297. # if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)
  298. unsigned long r;
  299. _BitScanForward( &r, (U32)val );
  300. return (int)(r>>3);
  301. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  302. return (__builtin_ctz((U32)val) >> 3);
  303. # else
  304. 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 };
  305. return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];
  306. # endif
  307. }
  308. } else /* Big Endian CPU */ {
  309. if (sizeof(val)==8) {
  310. # if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
  311. unsigned long r = 0;
  312. _BitScanReverse64( &r, val );
  313. return (unsigned)(r>>3);
  314. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  315. return (__builtin_clzll((U64)val) >> 3);
  316. # else
  317. unsigned r;
  318. if (!(val>>32)) { r=4; } else { r=0; val>>=32; }
  319. if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
  320. r += (!val);
  321. return r;
  322. # endif
  323. } else /* 32 bits */ {
  324. # if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)
  325. unsigned long r = 0;
  326. _BitScanReverse( &r, (unsigned long)val );
  327. return (unsigned)(r>>3);
  328. # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
  329. return (__builtin_clz((U32)val) >> 3);
  330. # else
  331. unsigned r;
  332. if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
  333. r += (!val);
  334. return r;
  335. # endif
  336. }
  337. }
  338. }
  339. #define STEPSIZE sizeof(reg_t)
  340. static inline unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit)
  341. {
  342. const BYTE* const pStart = pIn;
  343. while (likely(pIn<pInLimit-(STEPSIZE-1))) {
  344. reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
  345. if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; continue; }
  346. pIn += LZ4_NbCommonBytes(diff);
  347. return (unsigned)(pIn - pStart);
  348. }
  349. if ((STEPSIZE==8) && (pIn<(pInLimit-3)) && (LZ4_read32(pMatch) == LZ4_read32(pIn))) { pIn+=4; pMatch+=4; }
  350. if ((pIn<(pInLimit-1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn))) { pIn+=2; pMatch+=2; }
  351. if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;
  352. return (unsigned)(pIn - pStart);
  353. }
  354. static const int LZ4_64Klimit = ((64 KB) + (MFLIMIT-1));
  355. static const U32 LZ4_skipTrigger = 6; /* Increase this value ==> compression run slower on incompressible data */
  356. typedef enum { notLimited = 0, limitedOutput = 1 } limitedOutput_directive;
  357. typedef enum { byPtr, byU32, byU16 } tableType_t;
  358. typedef enum { noDict = 0, withPrefix64k, usingExtDict } dict_directive;
  359. typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive;
  360. typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive;
  361. typedef enum { full = 0, partial = 1 } earlyEnd_directive;
  362. static inline int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); }
  363. static inline U32 LZ4_hash4(U32 sequence, tableType_t const tableType)
  364. {
  365. if (tableType == byU16)
  366. return ((sequence * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1)));
  367. else
  368. return ((sequence * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG));
  369. }
  370. static inline U32 LZ4_hash5(U64 sequence, tableType_t const tableType)
  371. {
  372. static const U64 prime5bytes = 889523592379ULL;
  373. static const U64 prime8bytes = 11400714785074694791ULL;
  374. const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG;
  375. if (LZ4_isLittleEndian())
  376. return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog));
  377. else
  378. return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog));
  379. }
  380. FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tableType)
  381. {
  382. if ((sizeof(reg_t)==8) && (tableType != byU16)) return LZ4_hash5(LZ4_read_ARCH(p), tableType);
  383. return LZ4_hash4(LZ4_read32(p), tableType);
  384. }
  385. static inline void LZ4_putPositionOnHash(const BYTE* p, U32 h, void* tableBase, tableType_t const tableType, const BYTE* srcBase)
  386. {
  387. switch (tableType)
  388. {
  389. case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; }
  390. case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; }
  391. case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; }
  392. }
  393. }
  394. FORCE_INLINE void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)
  395. {
  396. U32 const h = LZ4_hashPosition(p, tableType);
  397. LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase);
  398. }
  399. static inline const BYTE* LZ4_getPositionOnHash(U32 h, void* tableBase, tableType_t tableType, const BYTE* srcBase)
  400. {
  401. if (tableType == byPtr) { const BYTE** hashTable = (const BYTE**) tableBase; return hashTable[h]; }
  402. if (tableType == byU32) { const U32* const hashTable = (U32*) tableBase; return hashTable[h] + srcBase; }
  403. { const U16* const hashTable = (U16*) tableBase; return hashTable[h] + srcBase; } /* default, to ensure a return */
  404. }
  405. FORCE_INLINE const BYTE* LZ4_getPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)
  406. {
  407. U32 const h = LZ4_hashPosition(p, tableType);
  408. return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase);
  409. }
  410. FORCE_INLINE int LZ4_compress_generic(
  411. LZ4_stream_t_internal* const cctx,
  412. const char* const source,
  413. char* const dest,
  414. const int inputSize,
  415. const int maxOutputSize,
  416. const limitedOutput_directive outputLimited,
  417. const tableType_t tableType,
  418. const dict_directive dict,
  419. const dictIssue_directive dictIssue,
  420. const U32 acceleration)
  421. {
  422. const BYTE* ip = (const BYTE*) source;
  423. const BYTE* base;
  424. const BYTE* lowLimit;
  425. const BYTE* const lowRefLimit = ip - cctx->dictSize;
  426. const BYTE* const dictionary = cctx->dictionary;
  427. const BYTE* const dictEnd = dictionary + cctx->dictSize;
  428. const ptrdiff_t dictDelta = dictEnd - (const BYTE*)source;
  429. const BYTE* anchor = (const BYTE*) source;
  430. const BYTE* const iend = ip + inputSize;
  431. const BYTE* const mflimit = iend - MFLIMIT;
  432. const BYTE* const matchlimit = iend - LASTLITERALS;
  433. BYTE* op = (BYTE*) dest;
  434. BYTE* const olimit = op + maxOutputSize;
  435. U32 forwardH;
  436. /* Init conditions */
  437. if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported inputSize, too large (or negative) */
  438. switch(dict)
  439. {
  440. case noDict:
  441. default:
  442. base = (const BYTE*)source;
  443. lowLimit = (const BYTE*)source;
  444. break;
  445. case withPrefix64k:
  446. base = (const BYTE*)source - cctx->currentOffset;
  447. lowLimit = (const BYTE*)source - cctx->dictSize;
  448. break;
  449. case usingExtDict:
  450. base = (const BYTE*)source - cctx->currentOffset;
  451. lowLimit = (const BYTE*)source;
  452. break;
  453. }
  454. if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */
  455. if (inputSize<LZ4_minLength) goto _last_literals; /* Input too small, no compression (all literals) */
  456. /* First Byte */
  457. LZ4_putPosition(ip, cctx->hashTable, tableType, base);
  458. ip++; forwardH = LZ4_hashPosition(ip, tableType);
  459. /* Main Loop */
  460. for ( ; ; ) {
  461. ptrdiff_t refDelta = 0;
  462. const BYTE* match;
  463. BYTE* token;
  464. /* Find a match */
  465. { const BYTE* forwardIp = ip;
  466. unsigned step = 1;
  467. unsigned searchMatchNb = acceleration << LZ4_skipTrigger;
  468. do {
  469. U32 const h = forwardH;
  470. ip = forwardIp;
  471. forwardIp += step;
  472. step = (searchMatchNb++ >> LZ4_skipTrigger);
  473. if (unlikely(forwardIp > mflimit)) goto _last_literals;
  474. match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base);
  475. if (dict==usingExtDict) {
  476. if (match < (const BYTE*)source) {
  477. refDelta = dictDelta;
  478. lowLimit = dictionary;
  479. } else {
  480. refDelta = 0;
  481. lowLimit = (const BYTE*)source;
  482. } }
  483. forwardH = LZ4_hashPosition(forwardIp, tableType);
  484. LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base);
  485. } while ( ((dictIssue==dictSmall) ? (match < lowRefLimit) : 0)
  486. || ((tableType==byU16) ? 0 : (match + MAX_DISTANCE < ip))
  487. || (LZ4_read32(match+refDelta) != LZ4_read32(ip)) );
  488. }
  489. /* Catch up */
  490. while (((ip>anchor) & (match+refDelta > lowLimit)) && (unlikely(ip[-1]==match[refDelta-1]))) { ip--; match--; }
  491. /* Encode Literals */
  492. { unsigned const litLength = (unsigned)(ip - anchor);
  493. token = op++;
  494. if ((outputLimited) && /* Check output buffer overflow */
  495. (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit)))
  496. return 0;
  497. if (litLength >= RUN_MASK) {
  498. int len = (int)litLength-RUN_MASK;
  499. *token = (RUN_MASK<<ML_BITS);
  500. for(; len >= 255 ; len-=255) *op++ = 255;
  501. *op++ = (BYTE)len;
  502. }
  503. else *token = (BYTE)(litLength<<ML_BITS);
  504. /* Copy Literals */
  505. LZ4_wildCopy(op, anchor, op+litLength);
  506. op+=litLength;
  507. }
  508. _next_match:
  509. /* Encode Offset */
  510. LZ4_writeLE16(op, (U16)(ip-match)); op+=2;
  511. /* Encode MatchLength */
  512. { unsigned matchCode;
  513. if ((dict==usingExtDict) && (lowLimit==dictionary)) {
  514. const BYTE* limit;
  515. match += refDelta;
  516. limit = ip + (dictEnd-match);
  517. if (limit > matchlimit) limit = matchlimit;
  518. matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, limit);
  519. ip += MINMATCH + matchCode;
  520. if (ip==limit) {
  521. unsigned const more = LZ4_count(ip, (const BYTE*)source, matchlimit);
  522. matchCode += more;
  523. ip += more;
  524. }
  525. } else {
  526. matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit);
  527. ip += MINMATCH + matchCode;
  528. }
  529. if ( outputLimited && /* Check output buffer overflow */
  530. (unlikely(op + (1 + LASTLITERALS) + (matchCode>>8) > olimit)) )
  531. return 0;
  532. if (matchCode >= ML_MASK) {
  533. *token += ML_MASK;
  534. matchCode -= ML_MASK;
  535. LZ4_write32(op, 0xFFFFFFFF);
  536. while (matchCode >= 4*255) op+=4, LZ4_write32(op, 0xFFFFFFFF), matchCode -= 4*255;
  537. op += matchCode / 255;
  538. *op++ = (BYTE)(matchCode % 255);
  539. } else
  540. *token += (BYTE)(matchCode);
  541. }
  542. anchor = ip;
  543. /* Test end of chunk */
  544. if (ip > mflimit) break;
  545. /* Fill table */
  546. LZ4_putPosition(ip-2, cctx->hashTable, tableType, base);
  547. /* Test next position */
  548. match = LZ4_getPosition(ip, cctx->hashTable, tableType, base);
  549. if (dict==usingExtDict) {
  550. if (match < (const BYTE*)source) {
  551. refDelta = dictDelta;
  552. lowLimit = dictionary;
  553. } else {
  554. refDelta = 0;
  555. lowLimit = (const BYTE*)source;
  556. } }
  557. LZ4_putPosition(ip, cctx->hashTable, tableType, base);
  558. if ( ((dictIssue==dictSmall) ? (match>=lowRefLimit) : 1)
  559. && (match+MAX_DISTANCE>=ip)
  560. && (LZ4_read32(match+refDelta)==LZ4_read32(ip)) )
  561. { token=op++; *token=0; goto _next_match; }
  562. /* Prepare next loop */
  563. forwardH = LZ4_hashPosition(++ip, tableType);
  564. }
  565. _last_literals:
  566. /* Encode Last Literals */
  567. { size_t const lastRun = (size_t)(iend - anchor);
  568. if ( (outputLimited) && /* Check output buffer overflow */
  569. ((op - (BYTE*)dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize) )
  570. return 0;
  571. if (lastRun >= RUN_MASK) {
  572. size_t accumulator = lastRun - RUN_MASK;
  573. *op++ = RUN_MASK << ML_BITS;
  574. for(; accumulator >= 255 ; accumulator-=255) *op++ = 255;
  575. *op++ = (BYTE) accumulator;
  576. } else {
  577. *op++ = (BYTE)(lastRun<<ML_BITS);
  578. }
  579. memcpy(op, anchor, lastRun);
  580. op += lastRun;
  581. }
  582. /* End */
  583. return (int) (((char*)op)-dest);
  584. }
  585. static inline int LZ4_compress_fast_extState(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
  586. {
  587. LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)state)->internal_donotuse;
  588. LZ4_resetStream((LZ4_stream_t*)state);
  589. //if (acceleration < 1) acceleration = ACCELERATION_DEFAULT;
  590. if (maxOutputSize >= LZ4_compressBound(inputSize)) {
  591. if (inputSize < LZ4_64Klimit)
  592. return LZ4_compress_generic(ctx, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue, acceleration);
  593. else
  594. return LZ4_compress_generic(ctx, source, dest, inputSize, 0, notLimited, (sizeof(void*)==8) ? byU32 : byPtr, noDict, noDictIssue, acceleration);
  595. } else {
  596. if (inputSize < LZ4_64Klimit)
  597. return LZ4_compress_generic(ctx, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration);
  598. else
  599. return LZ4_compress_generic(ctx, source, dest, inputSize, maxOutputSize, limitedOutput, (sizeof(void*)==8) ? byU32 : byPtr, noDict, noDictIssue, acceleration);
  600. }
  601. }
  602. static inline int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
  603. {
  604. #if (HEAPMODE)
  605. void* ctxPtr = ALLOCATOR(1, sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */
  606. #else
  607. LZ4_stream_t ctx;
  608. void* const ctxPtr = &ctx;
  609. #endif
  610. int const result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration);
  611. #if (HEAPMODE)
  612. FREEMEM(ctxPtr);
  613. #endif
  614. return result;
  615. }
  616. static inline void LZ4_resetStream (LZ4_stream_t* LZ4_stream)
  617. {
  618. MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t));
  619. }
  620. FORCE_INLINE int LZ4_decompress_generic(
  621. const char* const source,
  622. char* const dest,
  623. int inputSize,
  624. int outputSize, /* If endOnInput==endOnInputSize, this value is the max size of Output Buffer. */
  625. int endOnInput, /* endOnOutputSize, endOnInputSize */
  626. int partialDecoding, /* full, partial */
  627. int targetOutputSize, /* only used if partialDecoding==partial */
  628. int dict, /* noDict, withPrefix64k, usingExtDict */
  629. const BYTE* const lowPrefix, /* == dest when no prefix */
  630. const BYTE* const dictStart, /* only if dict==usingExtDict */
  631. const size_t dictSize /* note : = 0 if noDict */
  632. )
  633. {
  634. /* Local Variables */
  635. const BYTE* ip = (const BYTE*) source;
  636. const BYTE* const iend = ip + inputSize;
  637. BYTE* op = (BYTE*) dest;
  638. BYTE* const oend = op + outputSize;
  639. BYTE* cpy;
  640. BYTE* oexit = op + targetOutputSize;
  641. const BYTE* const lowLimit = lowPrefix - dictSize;
  642. const BYTE* const dictEnd = (const BYTE*)dictStart + dictSize;
  643. const unsigned dec32table[] = {0, 1, 2, 1, 4, 4, 4, 4};
  644. const int dec64table[] = {0, 0, 0, -1, 0, 1, 2, 3};
  645. const int safeDecode = (endOnInput==endOnInputSize);
  646. const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB)));
  647. /* Special cases */
  648. if ((partialDecoding) && (oexit > oend-MFLIMIT)) oexit = oend-MFLIMIT; /* targetOutputSize too high => decode everything */
  649. if ((endOnInput) && (unlikely(outputSize==0))) return ((inputSize==1) && (*ip==0)) ? 0 : -1; /* Empty output buffer */
  650. if ((!endOnInput) && (unlikely(outputSize==0))) return (*ip==0?1:-1);
  651. /* Main Loop : decode sequences */
  652. while (1) {
  653. size_t length;
  654. const BYTE* match;
  655. size_t offset;
  656. /* get literal length */
  657. unsigned const token = *ip++;
  658. if ((length=(token>>ML_BITS)) == RUN_MASK) {
  659. unsigned s;
  660. do {
  661. s = *ip++;
  662. length += s;
  663. } while ( likely(endOnInput ? ip<iend-RUN_MASK : 1) & (s==255) );
  664. if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)(op))) goto _output_error; /* overflow detection */
  665. if ((safeDecode) && unlikely((uptrval)(ip)+length<(uptrval)(ip))) goto _output_error; /* overflow detection */
  666. }
  667. /* copy literals */
  668. cpy = op+length;
  669. if ( ((endOnInput) && ((cpy>(partialDecoding?oexit:oend-MFLIMIT)) || (ip+length>iend-(2+1+LASTLITERALS))) )
  670. || ((!endOnInput) && (cpy>oend-WILDCOPYLENGTH)) )
  671. {
  672. if (partialDecoding) {
  673. if (cpy > oend) goto _output_error; /* Error : write attempt beyond end of output buffer */
  674. if ((endOnInput) && (ip+length > iend)) goto _output_error; /* Error : read attempt beyond end of input buffer */
  675. } else {
  676. if ((!endOnInput) && (cpy != oend)) goto _output_error; /* Error : block decoding must stop exactly there */
  677. if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) goto _output_error; /* Error : input must be consumed */
  678. }
  679. memcpy(op, ip, length);
  680. ip += length;
  681. op += length;
  682. break; /* Necessarily EOF, due to parsing restrictions */
  683. }
  684. LZ4_wildCopy(op, ip, cpy);
  685. ip += length; op = cpy;
  686. /* get offset */
  687. offset = LZ4_readLE16(ip); ip+=2;
  688. match = op - offset;
  689. if ((checkOffset) && (unlikely(match < lowLimit))) goto _output_error; /* Error : offset outside buffers */
  690. LZ4_write32(op, (U32)offset); /* costs ~1%; silence an msan warning when offset==0 */
  691. /* get matchlength */
  692. length = token & ML_MASK;
  693. if (length == ML_MASK) {
  694. unsigned s;
  695. do {
  696. s = *ip++;
  697. if ((endOnInput) && (ip > iend-LASTLITERALS)) goto _output_error;
  698. length += s;
  699. } while (s==255);
  700. if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error; /* overflow detection */
  701. }
  702. length += MINMATCH;
  703. /* check external dictionary */
  704. if ((dict==usingExtDict) && (match < lowPrefix)) {
  705. if (unlikely(op+length > oend-LASTLITERALS)) goto _output_error; /* doesn't respect parsing restriction */
  706. if (length <= (size_t)(lowPrefix-match)) {
  707. /* match can be copied as a single segment from external dictionary */
  708. memmove(op, dictEnd - (lowPrefix-match), length);
  709. op += length;
  710. } else {
  711. /* match encompass external dictionary and current block */
  712. size_t const copySize = (size_t)(lowPrefix-match);
  713. size_t const restSize = length - copySize;
  714. memcpy(op, dictEnd - copySize, copySize);
  715. op += copySize;
  716. if (restSize > (size_t)(op-lowPrefix)) { /* overlap copy */
  717. BYTE* const endOfMatch = op + restSize;
  718. const BYTE* copyFrom = lowPrefix;
  719. while (op < endOfMatch) *op++ = *copyFrom++;
  720. } else {
  721. memcpy(op, lowPrefix, restSize);
  722. op += restSize;
  723. } }
  724. continue;
  725. }
  726. /* copy match within block */
  727. cpy = op + length;
  728. if (unlikely(offset<8)) {
  729. const int dec64 = dec64table[offset];
  730. op[0] = match[0];
  731. op[1] = match[1];
  732. op[2] = match[2];
  733. op[3] = match[3];
  734. match += dec32table[offset];
  735. memcpy(op+4, match, 4);
  736. match -= dec64;
  737. } else { LZ4_copy8(op, match); match+=8; }
  738. op += 8;
  739. if (unlikely(cpy>oend-12)) {
  740. BYTE* const oCopyLimit = oend-(WILDCOPYLENGTH-1);
  741. if (cpy > oend-LASTLITERALS) goto _output_error; /* Error : last LASTLITERALS bytes must be literals (uncompressed) */
  742. if (op < oCopyLimit) {
  743. LZ4_wildCopy(op, match, oCopyLimit);
  744. match += oCopyLimit - op;
  745. op = oCopyLimit;
  746. }
  747. while (op<cpy) *op++ = *match++;
  748. } else {
  749. LZ4_copy8(op, match);
  750. if (length>16) LZ4_wildCopy(op+8, match+8, cpy);
  751. }
  752. op=cpy; /* correction */
  753. }
  754. /* end of decoding */
  755. if (endOnInput)
  756. return (int) (((char*)op)-dest); /* Nb of output bytes decoded */
  757. else
  758. return (int) (((const char*)ip)-source); /* Nb of input bytes read */
  759. /* Overflow error detected */
  760. _output_error:
  761. return (int) (-(((const char*)ip)-source))-1;
  762. }
  763. static inline int LZ4_decompress_safe(const char* source, char* dest, int compressedSize, int maxDecompressedSize)
  764. {
  765. return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, endOnInputSize, full, 0, noDict, (BYTE*)dest, NULL, 0);
  766. }
  767. } // anonymous namespace
  768. /************************************************************************** */
  769. /************************************************************************** */
  770. 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 };
  771. void Packet::armor(const void *key,bool encryptPayload)
  772. {
  773. uint8_t mangledKey[32];
  774. uint8_t *const data = reinterpret_cast<uint8_t *>(unsafeData());
  775. // Set flag now, since it affects key mangle function
  776. setCipher(encryptPayload ? ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012 : ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE);
  777. _salsa20MangleKey((const unsigned char *)key,mangledKey);
  778. if (ZT_HAS_FAST_CRYPTO()) {
  779. const unsigned int encryptLen = (encryptPayload) ? (size() - ZT_PACKET_IDX_VERB) : 0;
  780. uint64_t keyStream[(ZT_PROTO_MAX_PACKET_LENGTH + 64 + 8) / 8];
  781. ZT_FAST_SINGLE_PASS_SALSA2012(keyStream,encryptLen + 64,(data + ZT_PACKET_IDX_IV),mangledKey);
  782. Salsa20::memxor(data + ZT_PACKET_IDX_VERB,reinterpret_cast<const uint8_t *>(keyStream + 8),encryptLen);
  783. uint64_t mac[2];
  784. Poly1305::compute(mac,data + ZT_PACKET_IDX_VERB,size() - ZT_PACKET_IDX_VERB,keyStream);
  785. #ifdef ZT_NO_TYPE_PUNNING
  786. memcpy(data + ZT_PACKET_IDX_MAC,mac,8);
  787. #else
  788. (*reinterpret_cast<uint64_t *>(data + ZT_PACKET_IDX_MAC)) = mac[0];
  789. #endif
  790. } else {
  791. Salsa20 s20(mangledKey,data + ZT_PACKET_IDX_IV);
  792. uint64_t macKey[4];
  793. s20.crypt12(ZERO_KEY,macKey,sizeof(macKey));
  794. uint8_t *const payload = data + ZT_PACKET_IDX_VERB;
  795. const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
  796. if (encryptPayload)
  797. s20.crypt12(payload,payload,payloadLen);
  798. uint64_t mac[2];
  799. Poly1305::compute(mac,payload,payloadLen,macKey);
  800. memcpy(data + ZT_PACKET_IDX_MAC,mac,8);
  801. }
  802. }
  803. bool Packet::dearmor(const void *key)
  804. {
  805. uint8_t mangledKey[32];
  806. uint8_t *const data = reinterpret_cast<uint8_t *>(unsafeData());
  807. const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
  808. unsigned char *const payload = data + ZT_PACKET_IDX_VERB;
  809. const unsigned int cs = cipher();
  810. if ((cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE)||(cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)) {
  811. _salsa20MangleKey((const unsigned char *)key,mangledKey);
  812. if (ZT_HAS_FAST_CRYPTO()) {
  813. uint64_t keyStream[(ZT_PROTO_MAX_PACKET_LENGTH + 64 + 8) / 8];
  814. ZT_FAST_SINGLE_PASS_SALSA2012(keyStream,((cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012) ? (payloadLen + 64) : 64),(data + ZT_PACKET_IDX_IV),mangledKey);
  815. uint64_t mac[2];
  816. Poly1305::compute(mac,payload,payloadLen,keyStream);
  817. #ifdef ZT_NO_TYPE_PUNNING
  818. if (!Utils::secureEq(mac,data + ZT_PACKET_IDX_MAC,8))
  819. return false;
  820. #else
  821. if ((*reinterpret_cast<const uint64_t *>(data + ZT_PACKET_IDX_MAC)) != mac[0]) // also secure, constant time
  822. return false;
  823. #endif
  824. if (cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
  825. Salsa20::memxor(data + ZT_PACKET_IDX_VERB,reinterpret_cast<const uint8_t *>(keyStream + 8),payloadLen);
  826. } else {
  827. Salsa20 s20(mangledKey,data + ZT_PACKET_IDX_IV);
  828. uint64_t macKey[4];
  829. s20.crypt12(ZERO_KEY,macKey,sizeof(macKey));
  830. uint64_t mac[2];
  831. Poly1305::compute(mac,payload,payloadLen,macKey);
  832. #ifdef ZT_NO_TYPE_PUNNING
  833. if (!Utils::secureEq(mac,data + ZT_PACKET_IDX_MAC,8))
  834. return false;
  835. #else
  836. if ((*reinterpret_cast<const uint64_t *>(data + ZT_PACKET_IDX_MAC)) != mac[0]) // also secure, constant time
  837. return false;
  838. #endif
  839. if (cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
  840. s20.crypt12(payload,payload,payloadLen);
  841. }
  842. return true;
  843. } else {
  844. return false; // unrecognized cipher suite
  845. }
  846. }
  847. void Packet::cryptField(const void *key,unsigned int start,unsigned int len)
  848. {
  849. uint8_t *const data = reinterpret_cast<uint8_t *>(unsafeData());
  850. uint8_t iv[8];
  851. for(int i=0;i<8;++i) iv[i] = data[i];
  852. iv[7] &= 0xf8; // mask off least significant 3 bits of packet ID / IV since this is unset when this function gets called
  853. Salsa20 s20(key,iv);
  854. s20.crypt12(data + start,data + start,len);
  855. }
  856. bool Packet::compress()
  857. {
  858. char *const data = reinterpret_cast<char *>(unsafeData());
  859. char buf[ZT_PROTO_MAX_PACKET_LENGTH * 2];
  860. if ((!compressed())&&(size() > (ZT_PACKET_IDX_PAYLOAD + 64))) { // don't bother compressing tiny packets
  861. int pl = (int)(size() - ZT_PACKET_IDX_PAYLOAD);
  862. int cl = LZ4_compress_fast(data + ZT_PACKET_IDX_PAYLOAD,buf,pl,ZT_PROTO_MAX_PACKET_LENGTH * 2,1);
  863. if ((cl > 0)&&(cl < pl)) {
  864. data[ZT_PACKET_IDX_VERB] |= (char)ZT_PROTO_VERB_FLAG_COMPRESSED;
  865. setSize((unsigned int)cl + ZT_PACKET_IDX_PAYLOAD);
  866. memcpy(data + ZT_PACKET_IDX_PAYLOAD,buf,cl);
  867. return true;
  868. }
  869. }
  870. data[ZT_PACKET_IDX_VERB] &= (char)(~ZT_PROTO_VERB_FLAG_COMPRESSED);
  871. return false;
  872. }
  873. bool Packet::uncompress()
  874. {
  875. char *const data = reinterpret_cast<char *>(unsafeData());
  876. char buf[ZT_PROTO_MAX_PACKET_LENGTH];
  877. if ((compressed())&&(size() >= ZT_PROTO_MIN_PACKET_LENGTH)) {
  878. if (size() > ZT_PACKET_IDX_PAYLOAD) {
  879. unsigned int compLen = size() - ZT_PACKET_IDX_PAYLOAD;
  880. int ucl = LZ4_decompress_safe((const char *)data + ZT_PACKET_IDX_PAYLOAD,buf,compLen,sizeof(buf));
  881. if ((ucl > 0)&&(ucl <= (int)(capacity() - ZT_PACKET_IDX_PAYLOAD))) {
  882. setSize((unsigned int)ucl + ZT_PACKET_IDX_PAYLOAD);
  883. memcpy(data + ZT_PACKET_IDX_PAYLOAD,buf,ucl);
  884. } else {
  885. return false;
  886. }
  887. }
  888. data[ZT_PACKET_IDX_VERB] &= (char)(~ZT_PROTO_VERB_FLAG_COMPRESSED);
  889. }
  890. return true;
  891. }
  892. } // namespace ZeroTier