Packet.cpp 33 KB

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