Packet.hpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifndef _ZT_N_PACKET_HPP
  28. #define _ZT_N_PACKET_HPP
  29. #include <stdint.h>
  30. #include <string.h>
  31. #include <stdio.h>
  32. #include <string>
  33. #include <iostream>
  34. #include "Address.hpp"
  35. #include "Poly1305.hpp"
  36. #include "Salsa20.hpp"
  37. #include "Utils.hpp"
  38. #include "Constants.hpp"
  39. #include "Buffer.hpp"
  40. #include "../ext/lz4/lz4.h"
  41. /**
  42. * Protocol version -- incremented only for MAJOR changes
  43. *
  44. * 1 - 0.2.0 ... 0.2.5
  45. * 2 - 0.3.0 ... 0.4.5
  46. * * Added signature and originating peer to multicast frame
  47. * * Double size of multicast frame bloom filter
  48. * 3 - 0.5.0 ... 0.6.0
  49. * * Yet another multicast redesign
  50. * * New crypto completely changes key agreement cipher
  51. * 4 - 0.6.0 ...
  52. * * New identity format based on hashcash design
  53. *
  54. * This isn't going to change again for a long time unless your
  55. * author wakes up again at 4am with another great idea. :P
  56. */
  57. #define ZT_PROTO_VERSION 4
  58. /**
  59. * Maximum hop count allowed by packet structure (3 bits, 0-7)
  60. *
  61. * This is not necessarily the maximum hop counter after which
  62. * relaying is no longer performed.
  63. */
  64. #define ZT_PROTO_MAX_HOPS 7
  65. /**
  66. * Header flag indicating that a packet is encrypted with Salsa20
  67. *
  68. * If this is not set, then the packet's payload is in the clear and the
  69. * MAC is over this (since there is no ciphertext). Otherwise the MAC is
  70. * of the ciphertext after encryption.
  71. */
  72. #define ZT_PROTO_FLAG_ENCRYPTED 0x80
  73. /**
  74. * Header flag indicating that a packet is fragmented
  75. *
  76. * If this flag is set, the receiver knows to expect more than one fragment.
  77. * See Packet::Fragment for details.
  78. */
  79. #define ZT_PROTO_FLAG_FRAGMENTED 0x40
  80. /**
  81. * Verb flag indicating payload is compressed with LZ4
  82. */
  83. #define ZT_PROTO_VERB_FLAG_COMPRESSED 0x80
  84. // Indices of fields in normal packet header -- do not change as this
  85. // might require both code rework and will break compatibility.
  86. #define ZT_PACKET_IDX_IV 0
  87. #define ZT_PACKET_IDX_DEST 8
  88. #define ZT_PACKET_IDX_SOURCE 13
  89. #define ZT_PACKET_IDX_FLAGS 18
  90. #define ZT_PACKET_IDX_MAC 19
  91. #define ZT_PACKET_IDX_VERB 27
  92. #define ZT_PACKET_IDX_PAYLOAD 28
  93. /**
  94. * Packet buffer size (can be changed)
  95. */
  96. #define ZT_PROTO_MAX_PACKET_LENGTH (ZT_MAX_PACKET_FRAGMENTS * ZT_UDP_DEFAULT_PAYLOAD_MTU)
  97. /**
  98. * Minimum viable packet length (also length of header)
  99. */
  100. #define ZT_PROTO_MIN_PACKET_LENGTH ZT_PACKET_IDX_PAYLOAD
  101. // Indexes of fields in fragment header -- also can't be changed without
  102. // breaking compatibility.
  103. #define ZT_PACKET_FRAGMENT_IDX_PACKET_ID 0
  104. #define ZT_PACKET_FRAGMENT_IDX_DEST 8
  105. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR 13
  106. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO 14
  107. #define ZT_PACKET_FRAGMENT_IDX_HOPS 15
  108. #define ZT_PACKET_FRAGMENT_IDX_PAYLOAD 16
  109. /**
  110. * Value found at ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR in fragments
  111. */
  112. #define ZT_PACKET_FRAGMENT_INDICATOR ZT_ADDRESS_RESERVED_PREFIX
  113. /**
  114. * Minimum viable fragment length
  115. */
  116. #define ZT_PROTO_MIN_FRAGMENT_LENGTH ZT_PACKET_FRAGMENT_IDX_PAYLOAD
  117. // Size of bloom filter used in multicast propagation graph exploration
  118. #define ZT_PROTO_VERB_MULTICAST_FRAME_BLOOM_FILTER_SIZE_BITS 512
  119. #define ZT_PROTO_VERB_MULTICAST_FRAME_BLOOM_FILTER_SIZE_BYTES 64
  120. // Field incides for parsing verbs -------------------------------------------
  121. #define ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION (ZT_PACKET_IDX_PAYLOAD)
  122. #define ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION + 1)
  123. #define ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION + 1)
  124. #define ZT_PROTO_VERB_HELLO_IDX_REVISION (ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION + 1)
  125. #define ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP (ZT_PROTO_VERB_HELLO_IDX_REVISION + 2)
  126. #define ZT_PROTO_VERB_HELLO_IDX_IDENTITY (ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP + 8)
  127. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  128. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB + 1)
  129. #define ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE (ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID + 8)
  130. #define ZT_PROTO_VERB_ERROR_IDX_PAYLOAD (ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE + 1)
  131. #define ZT_PROTO_VERB_OK_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  132. #define ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_OK_IDX_IN_RE_VERB + 1)
  133. #define ZT_PROTO_VERB_OK_IDX_PAYLOAD (ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID + 8)
  134. #define ZT_PROTO_VERB_WHOIS_IDX_ZTADDRESS (ZT_PACKET_IDX_PAYLOAD)
  135. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS (ZT_PACKET_IDX_PAYLOAD)
  136. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS + 1)
  137. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT (ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS + 5)
  138. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN (ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT + 2)
  139. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN + 1)
  140. #define ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  141. #define ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID + 8)
  142. #define ZT_PROTO_VERB_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE + 2)
  143. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_DEPTH (ZT_PACKET_IDX_PAYLOAD)
  144. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_DEPTH 2
  145. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_FIFO (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_DEPTH + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_DEPTH)
  146. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_FIFO 320
  147. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_BLOOM (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_FIFO + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_FIFO)
  148. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_BLOOM 1024
  149. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_BLOOM + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_BLOOM)
  150. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_FLAGS 1
  151. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX__START_OF_SIGNED_PORTION (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS)
  152. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_FLAGS)
  153. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_NETWORK_ID 8
  154. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_BLOOM_NONCE (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_NETWORK_ID)
  155. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_BLOOM_NONCE 2
  156. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_PREFIX_BITS (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_BLOOM_NONCE + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_BLOOM_NONCE)
  157. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_PREFIX_BITS 1
  158. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_PREFIX (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_PREFIX_BITS + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_PREFIX_BITS)
  159. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_PREFIX 1
  160. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ORIGIN (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_PREFIX + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_PREFIX)
  161. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_ORIGIN 5
  162. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ORIGIN_MCID (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ORIGIN + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_ORIGIN)
  163. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_ORIGIN_MCID 3
  164. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_GUID (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ORIGIN)
  165. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_GUID 8
  166. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ORIGIN_MCID + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_ORIGIN_MCID)
  167. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_SOURCE_MAC 6
  168. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_SOURCE_MAC)
  169. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_DEST_MAC 6
  170. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_DEST_MAC)
  171. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_DEST_ADI 4
  172. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_DEST_ADI)
  173. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_ETHERTYPE 2
  174. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME_LEN (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_ETHERTYPE)
  175. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_FRAME_LEN 2
  176. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME_LEN + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_FRAME_LEN)
  177. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  178. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID + 8)
  179. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN + 2)
  180. #define ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  181. #define ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP + 8)
  182. #define ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION + 1)
  183. #define ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION + 1)
  184. #define ZT_PROTO_VERB_HELLO__OK__IDX_REVISION (ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION + 1)
  185. #define ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  186. #define ZT_PROTO_VERB_WHOIS__ERROR__IDX_ZTADDRESS (ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)
  187. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  188. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID + 8)
  189. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN + 2)
  190. // ---------------------------------------------------------------------------
  191. namespace ZeroTier {
  192. /**
  193. * ZeroTier packet
  194. *
  195. * Packet format:
  196. * <[8] random initialization vector (doubles as 64-bit packet ID)>
  197. * <[5] destination ZT address>
  198. * <[5] source ZT address>
  199. * <[1] flags (LS 5 bits) and ZT hop count (MS 3 bits)>
  200. * <[8] 8-bit MAC (currently first 8 bytes of poly1305 tag)>
  201. * [... -- begin encryption envelope -- ...]
  202. * <[1] encrypted flags (MS 3 bits) and verb (LS 5 bits)>
  203. * [... verb-specific payload ...]
  204. *
  205. * Packets smaller than 28 bytes are invalid and silently discarded.
  206. *
  207. * MAC is computed on ciphertext *after* encryption. See also:
  208. *
  209. * http://tonyarcieri.com/all-the-crypto-code-youve-ever-written-is-probably-broken
  210. *
  211. * For unencrypted packets, MAC is computed on plaintext. Only HELLO is ever
  212. * sent in the clear, as it's the "here is my public key" message.
  213. */
  214. class Packet : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  215. {
  216. public:
  217. /**
  218. * A packet fragment
  219. *
  220. * Fragments are sent if a packet is larger than UDP MTU. The first fragment
  221. * is sent with its normal header with the fragmented flag set. Remaining
  222. * fragments are sent this way.
  223. *
  224. * The fragmented bit indicates that there is at least one fragment. Fragments
  225. * themselves contain the total, so the receiver must "learn" this from the
  226. * first fragment it receives.
  227. *
  228. * Fragments are sent with the following format:
  229. * <[8] packet ID of packet whose fragment this belongs to>
  230. * <[5] destination ZT address>
  231. * <[1] 0xff, a reserved address, signals that this isn't a normal packet>
  232. * <[1] total fragments (most significant 4 bits), fragment no (LS 4 bits)>
  233. * <[1] ZT hop count>
  234. * <[...] fragment data>
  235. *
  236. * The protocol supports a maximum of 16 fragments. If a fragment is received
  237. * before its main packet header, it should be cached for a brief period of
  238. * time to see if its parent arrives. Loss of any fragment constitutes packet
  239. * loss; there is no retransmission mechanism. The receiver must wait for full
  240. * receipt to authenticate and decrypt; there is no per-fragment MAC. (But if
  241. * fragments are corrupt, the MAC will fail for the whole assembled packet.)
  242. */
  243. class Fragment : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  244. {
  245. public:
  246. Fragment() :
  247. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>()
  248. {
  249. }
  250. template<unsigned int C2>
  251. Fragment(const Buffer<C2> &b)
  252. throw(std::out_of_range) :
  253. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  254. {
  255. }
  256. /**
  257. * Initialize from a packet
  258. *
  259. * @param p Original assembled packet
  260. * @param fragStart Start of fragment (raw index in packet data)
  261. * @param fragLen Length of fragment in bytes
  262. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  263. * @param fragTotal Total number of fragments (including 0)
  264. * @throws std::out_of_range Packet size would exceed buffer
  265. */
  266. Fragment(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  267. throw(std::out_of_range)
  268. {
  269. init(p,fragStart,fragLen,fragNo,fragTotal);
  270. }
  271. /**
  272. * Initialize from a packet
  273. *
  274. * @param p Original assembled packet
  275. * @param fragStart Start of fragment (raw index in packet data)
  276. * @param fragLen Length of fragment in bytes
  277. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  278. * @param fragTotal Total number of fragments (including 0)
  279. * @throws std::out_of_range Packet size would exceed buffer
  280. */
  281. inline void init(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  282. throw(std::out_of_range)
  283. {
  284. if ((fragStart + fragLen) > p.size())
  285. throw std::out_of_range("Packet::Fragment: tried to construct fragment of packet past its length");
  286. setSize(fragLen + ZT_PROTO_MIN_FRAGMENT_LENGTH);
  287. // NOTE: this copies both the IV/packet ID and the destination address.
  288. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PACKET_ID,13),p.data() + ZT_PACKET_IDX_IV,13);
  289. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] = ZT_PACKET_FRAGMENT_INDICATOR;
  290. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO] = (char)(((fragTotal & 0xf) << 4) | (fragNo & 0xf));
  291. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = 0;
  292. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,fragLen),p.data() + fragStart,fragLen);
  293. }
  294. /**
  295. * Get this fragment's destination
  296. *
  297. * @return Destination ZT address
  298. */
  299. inline Address destination() const { return Address(field(ZT_PACKET_FRAGMENT_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  300. /**
  301. * @return True if fragment is of a valid length
  302. */
  303. inline bool lengthValid() const { return (size() >= ZT_PACKET_FRAGMENT_IDX_PAYLOAD); }
  304. /**
  305. * @return ID of packet this is a fragment of
  306. */
  307. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_FRAGMENT_IDX_PACKET_ID); }
  308. /**
  309. * @return Total number of fragments in packet
  310. */
  311. inline unsigned int totalFragments() const { return (((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) >> 4) & 0xf); }
  312. /**
  313. * @return Fragment number of this fragment
  314. */
  315. inline unsigned int fragmentNumber() const { return ((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) & 0xf); }
  316. /**
  317. * @return Fragment ZT hop count
  318. */
  319. inline unsigned int hops() const { return (unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]); }
  320. /**
  321. * Increment this packet's hop count
  322. */
  323. inline void incrementHops()
  324. {
  325. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = (((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]) + 1) & ZT_PROTO_MAX_HOPS;
  326. }
  327. /**
  328. * @return Length of payload in bytes
  329. */
  330. inline unsigned int payloadLength() const { return ((size() > ZT_PACKET_FRAGMENT_IDX_PAYLOAD) ? (size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD) : 0); }
  331. /**
  332. * @return Raw packet payload
  333. */
  334. inline const unsigned char *payload() const
  335. {
  336. return field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD);
  337. }
  338. };
  339. /**
  340. * ZeroTier protocol verbs
  341. */
  342. enum Verb /* Max value: 32 (5 bits) */
  343. {
  344. /* No operation, payload ignored, no reply */
  345. VERB_NOP = 0,
  346. /* Announcement of a node's existence:
  347. * <[1] protocol version>
  348. * <[1] software major version>
  349. * <[1] software minor version>
  350. * <[2] software revision>
  351. * <[8] timestamp (ms since epoch)>
  352. * <[...] binary serialized identity (see Identity)>
  353. *
  354. * OK payload:
  355. * <[8] timestamp (echoed from original HELLO)>
  356. * <[1] protocol version (of responder)>
  357. * <[1] software major version (of responder)>
  358. * <[1] software minor version (of responder)>
  359. * <[2] software revision (of responder)>
  360. *
  361. * ERROR has no payload.
  362. */
  363. VERB_HELLO = 1,
  364. /* Error response:
  365. * <[1] in-re verb>
  366. * <[8] in-re packet ID>
  367. * <[1] error code>
  368. * <[...] error-dependent payload>
  369. */
  370. VERB_ERROR = 2,
  371. /* Success response:
  372. * <[1] in-re verb>
  373. * <[8] in-re packet ID>
  374. * <[...] request-specific payload>
  375. */
  376. VERB_OK = 3,
  377. /* Query an identity by address:
  378. * <[5] address to look up>
  379. *
  380. * OK response payload:
  381. * <[...] binary serialized identity>
  382. *
  383. * ERROR response payload:
  384. * <[5] address>
  385. */
  386. VERB_WHOIS = 4,
  387. /* Meet another node at a given protocol address:
  388. * <[1] flags (unused, currently 0)>
  389. * <[5] ZeroTier address of peer that might be found at this address>
  390. * <[2] 16-bit protocol address port>
  391. * <[1] protocol address length (4 for IPv4, 16 for IPv6)>
  392. * <[...] protocol address (network byte order)>
  393. *
  394. * This is sent by a relaying node to initiate NAT traversal between two
  395. * peers that are communicating by way of indirect relay. The relay will
  396. * send this to both peers at the same time on a periodic basis, telling
  397. * each where it might find the other on the network.
  398. *
  399. * Upon receipt, a peer sends a message such as NOP or HELLO to the other
  400. * peer. Peers only "learn" one anothers' direct addresses when they
  401. * successfully *receive* a message and authenticate it. Optionally, peers
  402. * will usually preface these messages with one or more firewall openers
  403. * to clear the path.
  404. *
  405. * Nodes should implement rate control, limiting the rate at which they
  406. * respond to these packets to prevent their use in DDOS attacks. Nodes
  407. * may also ignore these messages if a peer is not known or is not being
  408. * actively communicated with.
  409. *
  410. * No OK or ERROR is generated.
  411. */
  412. VERB_RENDEZVOUS = 5,
  413. /* A ZT-to-ZT unicast ethernet frame:
  414. * <[8] 64-bit network ID>
  415. * <[2] 16-bit ethertype>
  416. * <[...] ethernet payload>
  417. *
  418. * MAC addresses are derived from the packet's source and destination
  419. * ZeroTier addresses.
  420. *
  421. * ERROR may be generated if a membership certificate is needed for a
  422. * closed network. Payload will be network ID.
  423. */
  424. VERB_FRAME = 6,
  425. /* TODO: not implemented yet */
  426. VERB_BRIDGED_FRAME = 7,
  427. /* A multicast frame:
  428. * <[2] 16-bit propagation depth or 0xffff for "do not forward">
  429. * <[320] propagation FIFO>
  430. * <[1024] propagation bloom filter>
  431. * [... begin signed portion ...]
  432. * <[1] 8-bit flags, currently unused and must be 0>
  433. * <[8] 64-bit network ID>
  434. * <[2] 16-bit random propagation bloom filter nonce>
  435. * <[1] number of significant bits in propagation restrict prefix>
  436. * <[1] propagation restriction prefix (sig bits right to left)>
  437. * <[5] ZeroTier address of node of origin>
  438. * <[3] 24-bit multicast ID, together with origin forms GUID>
  439. * <[6] source MAC address>
  440. * <[6] destination multicast group MAC address>
  441. * <[4] destination multicast group ADI field>
  442. * <[2] 16-bit frame ethertype>
  443. * <[2] 16-bit length of payload>
  444. * <[...] ethernet frame payload>
  445. * [... end of signed portion ...]
  446. * <[2] 16-bit length of signature>
  447. * <[...] signature (currently Ed25519/SHA-512, 96 bytes in length)>
  448. *
  449. * When a multicast frame is received:
  450. *
  451. * (1) Check the signature of the signed portion of packet, discard on fail
  452. * (2) Check for duplicate multicast, STOP if duplicate
  453. * (3) Check rate limits, STOP if over limit
  454. * (4) Inject into tap if member of network and packet passes other checks
  455. * (5) Increment propagation depth, STOP if over limit
  456. * (6) Pop topmost element off FIFO -- this is next hop
  457. * (7) Push suggested next hops onto FIFO until full -- set corresponding
  458. * bits in bloom filter
  459. * (8) Send to next hop, or to a supernode if none
  460. *
  461. * When choosing next hops, exclude addresses corresponding to bits already
  462. * set in the bloom filter and addresses outside the propagation restrict
  463. * prefix.
  464. *
  465. * Algorithm for setting bits in bloom filter:
  466. *
  467. * (1) Place the address in the least significant 40 bits of a 64-bit int.
  468. * (2) Add the bloom filter nonce to this value.
  469. * (3) XOR the least significant 13 bits of this value with the next most
  470. * significant 13 bits and so on, 4 times.
  471. * (4) This value ANDed with 0x1fff is the bit to set in the bloom filter.
  472. * (5) Set this bit via: byte[bit >> 3] |= (0x80 >> (bit & 7))
  473. *
  474. * To check bits in bloom filter perform the same computation but mask the
  475. * bit instead of ORing it.
  476. *
  477. * Propagation occurs within a restrict prefix. The restrict prefix is
  478. * applied to the least significant 16 bits of an address. The original
  479. * sender of the multicast sets the restrict prefix and sends 2^N copies
  480. * of the multicast frame, one for each address prefix.
  481. *
  482. * ERROR may be generated if a membership certificate is needed for a
  483. * closed network. Payload will be network ID.
  484. */
  485. VERB_MULTICAST_FRAME = 8,
  486. /* Announce interest in multicast group(s):
  487. * <[8] 64-bit network ID>
  488. * <[6] multicast Ethernet address>
  489. * <[4] multicast additional distinguishing information (ADI)>
  490. * [... additional tuples of network/address/adi ...]
  491. *
  492. * LIKEs are sent to peers with whom you have a direct peer to peer
  493. * connection, and always including supernodes.
  494. *
  495. * OK/ERROR are not generated.
  496. */
  497. VERB_MULTICAST_LIKE = 9,
  498. /* Network member certificate:
  499. * <[...] serialized certificate of membership>
  500. * [ ... additional certificates may follow ...]
  501. *
  502. * Certificate contains network ID, peer it was issued for, etc.
  503. *
  504. * OK/ERROR are not generated.
  505. */
  506. VERB_NETWORK_MEMBERSHIP_CERTIFICATE = 10,
  507. /* Network configuration request:
  508. * <[8] 64-bit network ID>
  509. * <[2] 16-bit length of request meta-data dictionary>
  510. * <[...] string-serialized request meta-data>
  511. *
  512. * This message requests network configuration from a node capable of
  513. * providing it. Such nodes run the netconf service, which must be
  514. * installed into the ZeroTier home directory.
  515. *
  516. * OK response payload:
  517. * <[8] 64-bit network ID>
  518. * <[2] 16-bit length of network configuration dictionary>
  519. * <[...] network configuration dictionary>
  520. *
  521. * OK returns a Dictionary (string serialized) containing the network's
  522. * configuration and IP address assignment information for the querying
  523. * node. It also contains a membership certificate that the querying
  524. * node can push to other peers to demonstrate its right to speak on
  525. * a given network.
  526. *
  527. * ERROR response payload:
  528. * <[8] 64-bit network ID>
  529. */
  530. VERB_NETWORK_CONFIG_REQUEST = 11,
  531. /* Network configuration refresh request:
  532. * <[...] array of 64-bit network IDs>
  533. *
  534. * This message can be sent by the network configuration master node
  535. * to request that nodes refresh their network configuration. It can
  536. * thus be used to "push" updates so that network config changes will
  537. * take effect quickly.
  538. *
  539. * It does not generate an OK or ERROR message, and is treated only as
  540. * a hint to refresh now.
  541. */
  542. VERB_NETWORK_CONFIG_REFRESH = 12
  543. };
  544. /**
  545. * Error codes for VERB_ERROR
  546. */
  547. enum ErrorCode
  548. {
  549. /* No error, not actually used in transit */
  550. ERROR_NONE = 0,
  551. /* Invalid request */
  552. ERROR_INVALID_REQUEST = 1,
  553. /* Bad/unsupported protocol version */
  554. ERROR_BAD_PROTOCOL_VERSION = 2,
  555. /* Unknown object queried (e.g. with WHOIS) */
  556. ERROR_OBJ_NOT_FOUND = 3,
  557. /* HELLO pushed an identity whose address is already claimed */
  558. ERROR_IDENTITY_COLLISION = 4,
  559. /* Verb or use case not supported/enabled by this node */
  560. ERROR_UNSUPPORTED_OPERATION = 5,
  561. /* Message to private network rejected -- no unexpired certificate on file */
  562. ERROR_NEED_MEMBERSHIP_CERTIFICATE = 6,
  563. /* Tried to join network, but you're not a member */
  564. ERROR_NETWORK_ACCESS_DENIED = 7
  565. };
  566. /**
  567. * @param v Verb
  568. * @return String representation (e.g. HELLO, OK)
  569. */
  570. static const char *verbString(Verb v)
  571. throw();
  572. /**
  573. * @param e Error code
  574. * @return String error name
  575. */
  576. static const char *errorString(ErrorCode e)
  577. throw();
  578. template<unsigned int C2>
  579. Packet(const Buffer<C2> &b)
  580. throw(std::out_of_range) :
  581. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  582. {
  583. }
  584. /**
  585. * Construct a new empty packet with a unique random packet ID
  586. *
  587. * Flags and hops will be zero. Other fields and data region are undefined.
  588. * Use the header access methods (setDestination() and friends) to fill out
  589. * the header. Payload should be appended; initial size is header size.
  590. */
  591. Packet() :
  592. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  593. {
  594. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  595. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  596. }
  597. /**
  598. * Construct a new empty packet with a unique random packet ID
  599. *
  600. * @param dest Destination ZT address
  601. * @param source Source ZT address
  602. * @param v Verb
  603. */
  604. Packet(const Address &dest,const Address &source,const Verb v) :
  605. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  606. {
  607. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  608. setDestination(dest);
  609. setSource(source);
  610. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  611. setVerb(v);
  612. }
  613. /**
  614. * Reset this packet structure for reuse in place
  615. *
  616. * @param dest Destination ZT address
  617. * @param source Source ZT address
  618. * @param v Verb
  619. */
  620. inline void reset(const Address &dest,const Address &source,const Verb v)
  621. {
  622. setSize(ZT_PROTO_MIN_PACKET_LENGTH);
  623. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  624. setDestination(dest);
  625. setSource(source);
  626. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  627. setVerb(v);
  628. }
  629. /**
  630. * Generate a new IV / packet ID in place
  631. *
  632. * This can be used to re-use a packet buffer multiple times to send
  633. * technically different but otherwise identical copies of the same
  634. * packet.
  635. */
  636. inline void newInitializationVector()
  637. {
  638. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  639. }
  640. /**
  641. * Set this packet's destination
  642. *
  643. * @param dest ZeroTier address of destination
  644. */
  645. inline void setDestination(const Address &dest)
  646. {
  647. unsigned char *d = field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH);
  648. for(unsigned int i=0;i<ZT_ADDRESS_LENGTH;++i)
  649. d[i] = dest[i];
  650. }
  651. /**
  652. * Set this packet's source
  653. *
  654. * @param source ZeroTier address of source
  655. */
  656. inline void setSource(const Address &source)
  657. {
  658. unsigned char *s = field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH);
  659. for(unsigned int i=0;i<ZT_ADDRESS_LENGTH;++i)
  660. s[i] = source[i];
  661. }
  662. /**
  663. * Get this packet's destination
  664. *
  665. * @return Destination ZT address
  666. */
  667. inline Address destination() const { return Address(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  668. /**
  669. * Get this packet's source
  670. *
  671. * @return Source ZT address
  672. */
  673. inline Address source() const { return Address(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  674. /**
  675. * @return True if packet is of valid length
  676. */
  677. inline bool lengthValid() const { return (size() >= ZT_PROTO_MIN_PACKET_LENGTH); }
  678. /**
  679. * @return True if packet is encrypted
  680. */
  681. inline bool encrypted() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_ENCRYPTED) != 0); }
  682. /**
  683. * @return True if packet is fragmented (expect fragments)
  684. */
  685. inline bool fragmented() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0); }
  686. /**
  687. * Set this packet's fragmented flag
  688. *
  689. * @param f Fragmented flag value
  690. */
  691. inline void setFragmented(bool f)
  692. {
  693. if (f)
  694. (*this)[ZT_PACKET_IDX_FLAGS] |= (char)ZT_PROTO_FLAG_FRAGMENTED;
  695. else (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_FRAGMENTED);
  696. }
  697. /**
  698. * @return True if compressed (result only valid if unencrypted)
  699. */
  700. inline bool compressed() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_VERB] & ZT_PROTO_VERB_FLAG_COMPRESSED) != 0); }
  701. /**
  702. * @return ZeroTier forwarding hops (0 to 7)
  703. */
  704. inline unsigned int hops() const { return ((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x07); }
  705. /**
  706. * Increment this packet's hop count
  707. */
  708. inline void incrementHops()
  709. {
  710. (*this)[ZT_PACKET_IDX_FLAGS] = (char)((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & 0xf8) | (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] + 1) & 0x07);
  711. }
  712. /**
  713. * Get this packet's unique ID (the IV field interpreted as uint64_t)
  714. *
  715. * @return Packet ID
  716. */
  717. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_IDX_IV); }
  718. /**
  719. * Set packet verb
  720. *
  721. * This also has the side-effect of clearing any verb flags, such as
  722. * compressed, and so must only be done during packet composition.
  723. *
  724. * @param v New packet verb
  725. */
  726. inline void setVerb(Verb v) { (*this)[ZT_PACKET_IDX_VERB] = (char)v; }
  727. /**
  728. * @return Packet verb (not including flag bits)
  729. */
  730. inline Verb verb() const { return (Verb)((*this)[ZT_PACKET_IDX_VERB] & 0x1f); }
  731. /**
  732. * @return Length of packet payload
  733. */
  734. inline unsigned int payloadLength() const { return ((size() < ZT_PROTO_MIN_PACKET_LENGTH) ? 0 : (size() - ZT_PROTO_MIN_PACKET_LENGTH)); }
  735. /**
  736. * @return Raw packet payload
  737. */
  738. inline const unsigned char *payload() const
  739. {
  740. return field(ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD);
  741. }
  742. /**
  743. * Armor packet for transport
  744. *
  745. * @param key 32-byte key
  746. * @param encryptPayload If true, encrypt packet payload, else just MAC
  747. */
  748. inline void armor(const void *key,bool encryptPayload)
  749. {
  750. unsigned char mangledKey[32];
  751. unsigned char macKey[32];
  752. unsigned char mac[16];
  753. const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
  754. unsigned char *const payload = field(ZT_PACKET_IDX_VERB,payloadLen);
  755. // Set flag now, since it affects key mangle function
  756. if (encryptPayload)
  757. (*this)[ZT_PACKET_IDX_FLAGS] |= (char)ZT_PROTO_FLAG_ENCRYPTED;
  758. else (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_ENCRYPTED);
  759. _mangleKey((const unsigned char *)key,mangledKey);
  760. Salsa20 s20(mangledKey,256,field(ZT_PACKET_IDX_IV,8));
  761. // MAC key is always the first 32 bytes of the Salsa20 key stream
  762. // This is the same construction DJB's NaCl library uses
  763. s20.encrypt(ZERO_KEY,macKey,sizeof(macKey));
  764. if (encryptPayload)
  765. s20.encrypt(payload,payload,payloadLen);
  766. Poly1305::compute(mac,payload,payloadLen,macKey);
  767. memcpy(field(ZT_PACKET_IDX_MAC,8),mac,8);
  768. }
  769. /**
  770. * Verify and (if encrypted) decrypt packet
  771. *
  772. * @param key 32-byte key
  773. * @return False if packet is invalid or failed MAC authenticity check
  774. */
  775. inline bool dearmor(const void *key)
  776. {
  777. unsigned char mangledKey[32];
  778. unsigned char macKey[32];
  779. unsigned char mac[16];
  780. const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
  781. unsigned char *const payload = field(ZT_PACKET_IDX_VERB,payloadLen);
  782. _mangleKey((const unsigned char *)key,mangledKey);
  783. Salsa20 s20(mangledKey,256,field(ZT_PACKET_IDX_IV,8));
  784. s20.encrypt(ZERO_KEY,macKey,sizeof(macKey));
  785. Poly1305::compute(mac,payload,payloadLen,macKey);
  786. if (!Utils::secureEq(mac,field(ZT_PACKET_IDX_MAC,8),8))
  787. return false;
  788. if (((*this)[ZT_PACKET_IDX_FLAGS] & (char)ZT_PROTO_FLAG_ENCRYPTED)) {
  789. s20.decrypt(payload,payload,payloadLen);
  790. (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_ENCRYPTED);
  791. }
  792. return true;
  793. }
  794. /**
  795. * Attempt to compress payload if not already (must be unencrypted)
  796. *
  797. * This requires that the payload at least contain the verb byte already
  798. * set. The compressed flag in the verb is set if compression successfully
  799. * results in a size reduction. If no size reduction occurs, compression
  800. * is not done and the flag is left cleared.
  801. *
  802. * @return True if compression occurred
  803. */
  804. inline bool compress()
  805. {
  806. unsigned char buf[ZT_PROTO_MAX_PACKET_LENGTH * 2];
  807. if ((!compressed())&&(size() > (ZT_PACKET_IDX_PAYLOAD + 32))) {
  808. int pl = (int)(size() - ZT_PACKET_IDX_PAYLOAD);
  809. int cl = LZ4_compress((const char *)field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)pl),(char *)buf,pl);
  810. if ((cl > 0)&&(cl < pl)) {
  811. (*this)[ZT_PACKET_IDX_VERB] |= (char)ZT_PROTO_VERB_FLAG_COMPRESSED;
  812. setSize((unsigned int)cl + ZT_PACKET_IDX_PAYLOAD);
  813. memcpy(field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)cl),buf,cl);
  814. return true;
  815. }
  816. }
  817. (*this)[ZT_PACKET_IDX_VERB] &= (char)(~ZT_PROTO_VERB_FLAG_COMPRESSED);
  818. return false;
  819. }
  820. /**
  821. * Attempt to decompress payload if it is compressed (must be unencrypted)
  822. *
  823. * If payload is compressed, it is decompressed and the compressed verb
  824. * flag is cleared. Otherwise nothing is done and true is returned.
  825. *
  826. * @return True if data is now decompressed and valid, false on error
  827. */
  828. inline bool uncompress()
  829. {
  830. unsigned char buf[ZT_PROTO_MAX_PACKET_LENGTH];
  831. if ((compressed())&&(size() >= ZT_PROTO_MIN_PACKET_LENGTH)) {
  832. if (size() > ZT_PACKET_IDX_PAYLOAD) {
  833. unsigned int compLen = size() - ZT_PACKET_IDX_PAYLOAD;
  834. int ucl = LZ4_uncompress_unknownOutputSize((const char *)field(ZT_PACKET_IDX_PAYLOAD,compLen),(char *)buf,compLen,sizeof(buf));
  835. if ((ucl > 0)&&(ucl <= (int)(capacity() - ZT_PACKET_IDX_PAYLOAD))) {
  836. setSize((unsigned int)ucl + ZT_PACKET_IDX_PAYLOAD);
  837. memcpy(field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)ucl),buf,ucl);
  838. } else return false;
  839. }
  840. (*this)[ZT_PACKET_IDX_VERB] &= (char)(~ZT_PROTO_VERB_FLAG_COMPRESSED);
  841. }
  842. return true;
  843. }
  844. private:
  845. static const unsigned char ZERO_KEY[32];
  846. /**
  847. * Deterministically mangle a 256-bit crypto key based on packet
  848. *
  849. * @param in Input key (32 bytes)
  850. * @param out Output buffer (32 bytes)
  851. */
  852. inline void _mangleKey(const unsigned char *in,unsigned char *out) const
  853. {
  854. // IV and source/destination addresses. Using the addresses divides the
  855. // key space into two halves-- A->B and B->A (since order will change).
  856. for(unsigned int i=0;i<18;++i) // 8 + (ZT_ADDRESS_LENGTH * 2) == 18
  857. out[i] = in[i] ^ (unsigned char)(*this)[i];
  858. // Flags, but with hop count masked off. Hop count is altered by forwarding
  859. // nodes. It's one of the only parts of a packet modifiable by people
  860. // without the key.
  861. out[18] = in[18] ^ ((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & 0xf8);
  862. // Raw packet size in bytes -- thus each packet size defines a new
  863. // key space.
  864. out[19] = in[19] ^ (unsigned char)(size() & 0xff);
  865. out[20] = in[20] ^ (unsigned char)((size() >> 8) & 0xff); // little endian
  866. // Rest of raw key is used unchanged
  867. for(unsigned int i=21;i<32;++i)
  868. out[i] = in[i];
  869. }
  870. };
  871. } // namespace ZeroTier
  872. #endif