2
0

Packet.cpp 37 KB

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