Packet.cpp 33 KB

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