ReachabilityAnnouncer.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "subnode/ReachabilityAnnouncer.h"
  16. #include "subnode/PeeringSeeder.h"
  17. #include "util/events/Timeout.h"
  18. #include "util/Identity.h"
  19. #include "util/events/Time.h"
  20. #include "wire/Announce.h"
  21. #include "crypto/AddressCalc.h"
  22. #include "crypto/Sign.h"
  23. #include "util/AddrTools.h"
  24. #include "util/Hex.h"
  25. #include "util/Hash.h"
  26. #include "rust/cjdns_sys/Rffi.h"
  27. #include "util/Defined.h"
  28. #include "benc/Dict.h"
  29. #include <inttypes.h>
  30. // This is the time between the timestamp of the newest message and the point where
  31. // snode and subnode agree to drop messages from the snode state.
  32. #define AGREED_TIMEOUT_MS (1000 * 60 * 20)
  33. #define MSG_SIZE_LIMIT 700
  34. // Initial time between messages is 60 seconds, adjusted based on amount of full messages
  35. #define INITIAL_TBA 60000
  36. #define ArrayList_TYPE Message_t
  37. #define ArrayList_NAME OfMessages
  38. #include "util/ArrayList.h"
  39. #define ArrayList_TYPE struct Announce_ItemHeader
  40. #define ArrayList_NAME OfAnnItems
  41. #include "util/ArrayList.h"
  42. #define ArrayList_TYPE struct Announce_Peer
  43. #define ArrayList_NAME OfBarePeers
  44. #include "util/ArrayList.h"
  45. // -- Generic Functions -- //
  46. // We must reannounce before the agreed timeout because if it happens that there are
  47. // too many peers to fit in one packet, the packet will go out and re-announce the ones
  48. // who fit but the others will not fit in the packet and once the timestamp comes in,
  49. // they will be pulled by the route server.
  50. //
  51. // We could just declare that we are re-announcing everything at minute 15 but if we
  52. // do so then there will potentially be be a flood of full packets every 15 minutes
  53. // and link state will not be communicated.
  54. //
  55. // To fix this, we begin re-announcing after 14 minutes, which peers are eligable to be
  56. // re-announced is randomized by the timestamp of the previous announcement (something
  57. // which changes each cycle). Re-announcements occur between minutes 14 and minutes 19
  58. // with the last minute reserved as a 1 minute "quiet period" where announcements can
  59. // catch up before minute 20 when peers will be dropped by the route server.
  60. //
  61. #define QUIET_PERIOD_MS (1000 * 60)
  62. static int64_t timeUntilReannounce(
  63. int64_t nowServerTime,
  64. int64_t lastAnnouncedTime,
  65. struct Announce_ItemHeader* item)
  66. {
  67. uint32_t hash = Hash_compute((uint8_t*)item, item->length);
  68. int64_t timeSince = nowServerTime - lastAnnouncedTime;
  69. int64_t random5Min = (((uint64_t)lastAnnouncedTime + hash) % 600) * 1000;
  70. return (AGREED_TIMEOUT_MS - QUIET_PERIOD_MS) - (timeSince + random5Min);
  71. }
  72. static int64_t timestampFromMsg(Message_t* msg)
  73. {
  74. struct Announce_Header* hdr = (struct Announce_Header*) Message_bytes(msg);
  75. Assert_true(Message_getLength(msg) >= Announce_Header_SIZE);
  76. return Announce_Header_getTimestamp(hdr);
  77. }
  78. static struct Announce_ItemHeader* itemFromSnodeState(struct ArrayList_OfMessages* snodeState,
  79. struct Announce_ItemHeader* ref,
  80. int64_t sinceTime,
  81. int64_t* timeOut)
  82. {
  83. for (int i = snodeState->length - 1; i >= 0; i--) {
  84. Message_t* msg = ArrayList_OfMessages_get(snodeState, i);
  85. struct Announce_ItemHeader* item = Announce_itemInMessage(msg, ref);
  86. if (!item) { continue; }
  87. int64_t ts = timestampFromMsg(msg);
  88. if (sinceTime > ts) { return NULL; }
  89. if (timeOut) { *timeOut = ts; }
  90. return item;
  91. }
  92. return NULL;
  93. }
  94. // Calculate the sha512 of a message list where a given set of signed messages will corrispond
  95. // to a given hash.
  96. static void hashMsgList(struct ArrayList_OfMessages* msgList, uint8_t out[64])
  97. {
  98. uint8_t hash[64] = {0};
  99. for (int i = 0; i < msgList->length; i++) {
  100. Message_t* msg = ArrayList_OfMessages_get(msgList, i);
  101. Err_assert(Message_epush(msg, hash, 64));
  102. Rffi_crypto_hash_sha512(hash, Message_bytes(msg), Message_getLength(msg));
  103. Err_assert(Message_epop(msg, NULL, 64));
  104. }
  105. Bits_memcpy(out, hash, 64);
  106. }
  107. static int64_t estimateClockSkew(int64_t sentTime, int64_t snodeRecvTime, int64_t now)
  108. {
  109. // We estimate that the snode received our message at time: 1/2 the RTT
  110. int64_t halfRtt = sentTime + ((now - sentTime) / 2);
  111. return halfRtt - snodeRecvTime;
  112. }
  113. // We'll try to halve our estimated clock skew each RTT so on average it should eventually
  114. // target in on the exact skew. Ideal would be to use a rolling average such that one
  115. // screwy RTT has little effect but that's more work.
  116. static int64_t estimateImprovedClockSkew(int64_t sentTime,
  117. int64_t snodeRecvTime,
  118. int64_t now,
  119. int64_t lastSkew)
  120. {
  121. int64_t thisSkew = estimateClockSkew(sentTime, snodeRecvTime, now);
  122. int64_t skewDiff = thisSkew - lastSkew;
  123. return lastSkew + (skewDiff / 2);
  124. }
  125. // -- Context -- //
  126. // Depending on what news we have learned, we will adopt one of a set of possible states
  127. // whcih inform how often we contact our supernode. The numeric representation of the
  128. // state corrisponds to the number of milliseconds between messages to be sent to our
  129. // supernode.
  130. enum ReachabilityAnnouncer_State
  131. {
  132. // The message we build up from our local state is full, we obviously need to send it
  133. // asap in order that we can finish informing the snode of our peers.
  134. ReachabilityAnnouncer_State_MSGFULL = 500,
  135. // In this state we know how to reach the snode but we have no announced reachability
  136. // (so we are effectively offline) we have to announce quickly in order to be online.
  137. ReachabilityAnnouncer_State_FIRSTPEER = 1000,
  138. // We have just dropped a peer, we should announce quickly in order to help the snode
  139. // know that our link is dead.
  140. ReachabilityAnnouncer_State_PEERGONE = 6000,
  141. // We have picked up a new peer, we should announce moderately fast in order to make
  142. // sure that the snode picks the best path out of the possible options.
  143. ReachabilityAnnouncer_State_NEWPEER = 12000,
  144. // No new peers or dropped peers, we'll just send announcements at a low interval in
  145. // order to keep our snode up to date on latencies and drop percentages of different
  146. // links. Cadence is regulated by timeBetweenAnns.
  147. ReachabilityAnnouncer_State_NORMAL = -1
  148. };
  149. static const char* printState(enum ReachabilityAnnouncer_State s)
  150. {
  151. switch (s) {
  152. case ReachabilityAnnouncer_State_FIRSTPEER: return "FIRSTPEER";
  153. case ReachabilityAnnouncer_State_PEERGONE: return "PEERGONE";
  154. case ReachabilityAnnouncer_State_NEWPEER: return "NEWPEER";
  155. case ReachabilityAnnouncer_State_NORMAL: return "NORMAL";
  156. default: return "unknown";
  157. }
  158. }
  159. struct ReachabilityAnnouncer_pvt;
  160. struct Query {
  161. struct ReachabilityAnnouncer_pvt* rap;
  162. Message_t* msg;
  163. struct Address target;
  164. Identity
  165. };
  166. struct ReachabilityAnnouncer_pvt
  167. {
  168. struct ReachabilityAnnouncer pub;
  169. struct Timeout* announceCycle;
  170. struct Allocator* alloc;
  171. struct Log* log;
  172. EventBase_t* base;
  173. struct MsgCore* msgCore;
  174. struct Random* rand;
  175. struct SupernodeHunter* snh;
  176. struct EncodingScheme* myScheme;
  177. struct ReachabilityCollector* rc;
  178. PeeringSeeder_t* ps;
  179. String* encodingSchemeStr;
  180. struct Announce_ItemHeader* mySchemeItem;
  181. uint8_t signingKeypair[64];
  182. uint8_t pubSigningKey[32];
  183. int64_t timeOfLastReply;
  184. // The cjdns clock is monotonic and is calibrated once on launch so clockSkew
  185. // will be reliable even if the machine also has NTP and NTP also changes the clock
  186. // clockSkew is literally the number of milliseconds which we believe our clock is ahead of
  187. // our supernode's clock.
  188. int64_t clockSkew;
  189. struct Address snode;
  190. // This is effectively a log which means we add messages to it as time goes but we remove
  191. // messages which are more than AGREED_TIMEOUT_MS (20 minutes) older than the most recent
  192. // message in the list (the one at the highest index). We also identify messages in the list
  193. // which update only peers that have been updated again since and we remove those as well.
  194. // IMPORTANT: The removal of messages from this list is using the same algorithm that is used
  195. // on the supernode and if it changes then they will desync and go into a reset
  196. // loop.
  197. struct ArrayList_OfMessages* snodeState;
  198. struct Query* onTheWire;
  199. // this is by our clock, not skewed to the snode time.
  200. int64_t msgOnWireSentTime;
  201. // If true then when we send nextMsg, it will be a state reset of the node.
  202. bool resetState;
  203. enum ReachabilityAnnouncer_State state;
  204. int timeBetweenAnns;
  205. Identity
  206. };
  207. // -- "Methods" -- //
  208. static int64_t ourTime(struct ReachabilityAnnouncer_pvt* rap)
  209. {
  210. uint64_t now = Time_currentTimeMilliseconds();
  211. Assert_true(!(now >> 63));
  212. return (int64_t) now;
  213. }
  214. static int64_t snTime(struct ReachabilityAnnouncer_pvt* rap)
  215. {
  216. return ourTime(rap) - rap->clockSkew;
  217. }
  218. static char* printPeer(
  219. char out[60],
  220. struct ReachabilityAnnouncer_pvt* rap,
  221. struct Announce_Peer* p)
  222. {
  223. uint64_t path = Endian_bigEndianToHost16(p->peerNum_be);
  224. AddrTools_printPath(out, path);
  225. out[19] = '.';
  226. AddrTools_printIp(&out[20], p->peerIpv6);
  227. return out;
  228. }
  229. static char* printItem(
  230. char out[60],
  231. struct ReachabilityAnnouncer_pvt* rap,
  232. struct Announce_ItemHeader* item)
  233. {
  234. if (item->type == Announce_Type_PEER) {
  235. struct Announce_Peer* p = (struct Announce_Peer*) item;
  236. return printPeer(out, rap, p);
  237. } else if (item->type == Announce_Type_ENCODING_SCHEME) {
  238. return "encoding scheme";
  239. } else if (item->type == Announce_Type_VERSION) {
  240. return "version";
  241. } else {
  242. return "unknown";
  243. }
  244. }
  245. static bool pushLinkState(struct ReachabilityAnnouncer_pvt* rap,
  246. Message_t* msg)
  247. {
  248. for (int i = 0;; i++) {
  249. struct ReachabilityCollector_PeerInfo* pi = ReachabilityCollector_getPeerInfo(rap->rc, i);
  250. if (!pi || !pi->pathThemToUs) { break; }
  251. int lastLen = Message_getLength(msg);
  252. pi->linkState.nodeId = pi->addr.path & 0xffff;
  253. if (LinkState_encode(msg, &pi->linkState, pi->lastAnnouncedSamples)) {
  254. Log_debug(rap->log, "Failed to add link state for [%s]",
  255. Address_toString(&pi->addr, Message_getAlloc(msg))->bytes);
  256. }
  257. if (Message_getLength(msg) > MSG_SIZE_LIMIT) {
  258. Err_assert(Message_epop(msg, NULL, Message_getLength(msg) - lastLen));
  259. Log_debug(rap->log, "Couldn't add link state for [%s] (out of space)",
  260. Address_toString(&pi->addr, Message_getAlloc(msg))->bytes);
  261. return true;
  262. } else {
  263. Log_debug(rap->log, "Updated link state for [%s]",
  264. Address_toString(&pi->addr, Message_getAlloc(msg))->bytes);
  265. pi->lastAnnouncedSamples = pi->linkState.samples;
  266. }
  267. }
  268. return false;
  269. }
  270. // Insert or update the state information for a peer in a msgList
  271. #define updateItem_NOOP 0
  272. #define updateItem_ADD 1
  273. #define updateItem_UPDATE 2
  274. #define updateItem_ENOSPACE -1
  275. static int updateItem(struct ReachabilityAnnouncer_pvt* rap,
  276. Message_t* msg,
  277. struct Announce_ItemHeader* refItem)
  278. {
  279. char buf[60];
  280. const char* logInfo = "";
  281. if (Defined(Log_DEBUG)) {
  282. logInfo = printItem(buf, rap, refItem);
  283. }
  284. int64_t serverTime = snTime(rap);
  285. int64_t sinceTime = serverTime - AGREED_TIMEOUT_MS;
  286. struct Announce_ItemHeader* item = NULL;
  287. if (rap->onTheWire) {
  288. item = Announce_itemInMessage(rap->onTheWire->msg, refItem);
  289. }
  290. if (!item) {
  291. int64_t peerTime = 0;
  292. item = itemFromSnodeState(rap->snodeState, refItem, sinceTime, &peerTime);
  293. if (item && Announce_ItemHeader_equals(item, refItem)) {
  294. int64_t tur = timeUntilReannounce(serverTime, peerTime, item);
  295. if (tur < 0) {
  296. Log_debug(rap->log, "updateItem [%s] needs re-announce", logInfo);
  297. } else {
  298. Log_debug(rap->log, "updateItem [%s] no re-announce for [%d] sec",
  299. logInfo, (int)(tur / 1000));
  300. return updateItem_NOOP;
  301. }
  302. } else if (item) {
  303. Log_debug(rap->log, "updateItem [%s] needs update (changed)", logInfo);
  304. } else {
  305. Log_debug(rap->log, "updateItem [%s] not found in snodeState", logInfo);
  306. }
  307. } else if (Announce_ItemHeader_equals(item, refItem)) {
  308. Log_debug(rap->log, "updateItem [%s] found onTheWire, noop", logInfo);
  309. return updateItem_NOOP;
  310. } else {
  311. Log_debug(rap->log, "updateItem [%s] found onTheWire but needs update", logInfo);
  312. }
  313. if (Message_getLength(msg) > MSG_SIZE_LIMIT) {
  314. Log_debug(rap->log, "updateItem [%s] msg is too big to [%s] item",
  315. logInfo, item ? "UPDATE" : "INSERT");
  316. return updateItem_ENOSPACE;
  317. }
  318. Err_assert(Message_epush(msg, refItem, refItem->length));
  319. while ((uintptr_t)Message_bytes(msg) % 4) {
  320. // Ensure alignment
  321. Err_assert(Message_epush8(msg, 1));
  322. }
  323. return (item) ? updateItem_UPDATE : updateItem_ADD;
  324. }
  325. static void stateUpdate(struct ReachabilityAnnouncer_pvt* rap, enum ReachabilityAnnouncer_State st)
  326. {
  327. if (rap->state < st) { return; }
  328. rap->state = st;
  329. }
  330. static void annPeerForPi(struct ReachabilityAnnouncer_pvt* rap,
  331. struct Announce_Peer* apOut,
  332. struct ReachabilityCollector_PeerInfo* pi)
  333. {
  334. Assert_true(pi);
  335. Announce_Peer_init(apOut);
  336. apOut->encodingFormNum = EncodingScheme_getFormNum(rap->myScheme, pi->addr.path);
  337. apOut->peerNum_be = Endian_hostToBigEndian16(pi->addr.path & 0xffff);
  338. Bits_memcpy(apOut->peerIpv6, pi->addr.ip6.bytes, 16);
  339. apOut->label_be = Endian_hostToBigEndian32(pi->pathThemToUs);
  340. }
  341. static bool pushPeers(struct ReachabilityAnnouncer_pvt* rap, Message_t* msg)
  342. {
  343. for (int i = 0;; i++) {
  344. struct ReachabilityCollector_PeerInfo* pi = ReachabilityCollector_getPeerInfo(rap->rc, i);
  345. if (!pi || !pi->pathThemToUs) { return false; }
  346. struct Announce_Peer annP;
  347. annPeerForPi(rap, &annP, pi);
  348. if (updateItem(rap, msg, (struct Announce_ItemHeader*) &annP) == updateItem_ENOSPACE) {
  349. return true;
  350. }
  351. }
  352. }
  353. static void stateReset(struct ReachabilityAnnouncer_pvt* rap)
  354. {
  355. for (int i = rap->snodeState->length - 1; i >= 0; i--) {
  356. Message_t* msg = ArrayList_OfMessages_remove(rap->snodeState, i);
  357. Allocator_free(Message_getAlloc(msg));
  358. }
  359. if (rap->onTheWire) {
  360. // this message is owned by a ping allocator so it will be freed by that
  361. rap->onTheWire = NULL;
  362. }
  363. // we must force the state to FIRSTPEER
  364. rap->state = ReachabilityAnnouncer_State_FIRSTPEER;
  365. rap->timeBetweenAnns = INITIAL_TBA;
  366. rap->resetState = true;
  367. }
  368. static void addServerStateMsg(struct ReachabilityAnnouncer_pvt* rap, Message_t* msg)
  369. {
  370. Assert_true(Message_getLength(msg) >= Announce_Header_SIZE);
  371. int64_t mostRecentTime = timestampFromMsg(msg);
  372. int64_t sinceTime = mostRecentTime - AGREED_TIMEOUT_MS;
  373. ArrayList_OfMessages_add(rap->snodeState, msg);
  374. // Filter completely redundant messages and messages older than sinceTime
  375. struct Allocator* tempAlloc = Allocator_child(rap->alloc);
  376. struct ArrayList_OfAnnItems* knownItems = ArrayList_OfAnnItems_new(tempAlloc);
  377. for (int i = rap->snodeState->length - 1; i >= 0; i--) {
  378. bool redundant = true;
  379. Message_t* m = ArrayList_OfMessages_get(rap->snodeState, i);
  380. struct Announce_ItemHeader* item = Announce_ItemHeader_next(m, NULL);
  381. for (; item; item = Announce_ItemHeader_next(m, item)) {
  382. if (Announce_ItemHeader_isEphimeral(item)) {
  383. // Ephimeral items do not make a message non-redundant
  384. continue;
  385. }
  386. bool inList = false;
  387. for (int j = 0; j < knownItems->length; j++) {
  388. struct Announce_ItemHeader* knownItem = ArrayList_OfAnnItems_get(knownItems, j);
  389. if (Announce_ItemHeader_doesReplace(knownItem, item)) {
  390. inList = true;
  391. break;
  392. }
  393. }
  394. if (!inList) {
  395. ArrayList_OfAnnItems_add(knownItems, item);
  396. redundant = false;
  397. }
  398. }
  399. if (redundant && m != msg) {
  400. ArrayList_OfMessages_remove(rap->snodeState, i);
  401. Allocator_free(Message_getAlloc(m));
  402. } else if (timestampFromMsg(m) < sinceTime) {
  403. // this will cause an immediate reset of state because we don't remove it and
  404. // the server side will.
  405. Log_warn(rap->log, "Announcement expiring which has not been replaced in time");
  406. }
  407. }
  408. Allocator_free(tempAlloc);
  409. }
  410. static struct ArrayList_OfBarePeers* getSnodeStatePeers(
  411. struct ReachabilityAnnouncer_pvt* rap,
  412. struct Allocator* alloc)
  413. {
  414. struct ArrayList_OfBarePeers* out = ArrayList_OfBarePeers_new(alloc);
  415. for (int i = 0; i < rap->snodeState->length; i++) {
  416. Message_t* snm = ArrayList_OfMessages_get(rap->snodeState, i);
  417. struct Announce_Peer* p = NULL;
  418. for (p = Announce_Peer_next(snm, NULL); p; p = Announce_Peer_next(snm, p)) {
  419. bool found = false;
  420. for (int j = 0; j < out->length; j++) {
  421. struct Announce_Peer* p1 = ArrayList_OfBarePeers_get(out, j);
  422. if (p1->peerNum_be == p->peerNum_be) {
  423. Bits_memcpy(p1, p, sizeof(struct Announce_Peer));
  424. found = true;
  425. }
  426. }
  427. if (!found) {
  428. struct Announce_Peer* p1 = Allocator_clone(alloc, p);
  429. ArrayList_OfBarePeers_add(out, p1);
  430. }
  431. }
  432. }
  433. for (int j = out->length - 1; j >= 0; j--) {
  434. struct Announce_Peer* p1 = ArrayList_OfBarePeers_get(out, j);
  435. if (!p1->label_be) { ArrayList_OfBarePeers_remove(out, j); }
  436. }
  437. return out;
  438. }
  439. // -- Public -- //
  440. void ReachabilityAnnouncer_updatePeer(struct ReachabilityAnnouncer* ra,
  441. struct Address* nodeAddr,
  442. struct ReachabilityCollector_PeerInfo* pi)
  443. {
  444. struct ReachabilityAnnouncer_pvt* rap = Identity_check((struct ReachabilityAnnouncer_pvt*) ra);
  445. struct Allocator* tempAlloc = Allocator_child(rap->alloc);
  446. if (!pi) {
  447. Log_debug(rap->log, "Update for [%s] - gone", Address_toString(nodeAddr, tempAlloc)->bytes);
  448. stateUpdate(rap, ReachabilityAnnouncer_State_PEERGONE);
  449. } else {
  450. struct ArrayList_OfBarePeers* snodeState = getSnodeStatePeers(rap, tempAlloc);
  451. if (snodeState->length == 0) {
  452. Log_debug(rap->log, "Update for [%s] - first peer",
  453. Address_toString(nodeAddr, tempAlloc)->bytes);
  454. stateUpdate(rap, ReachabilityAnnouncer_State_FIRSTPEER);
  455. } else {
  456. Log_debug(rap->log, "Update for [%s] - new peer",
  457. Address_toString(nodeAddr, tempAlloc)->bytes);
  458. stateUpdate(rap, ReachabilityAnnouncer_State_NEWPEER);
  459. }
  460. }
  461. Allocator_free(tempAlloc);
  462. }
  463. // -- Event Callbacks -- //
  464. static void onReplyTimeout(struct ReachabilityAnnouncer_pvt* rap, struct Query* q)
  465. {
  466. // TODO(cjd): one lost packet shouldn't trigger unreachable state
  467. if (!Bits_memcmp(&q->target, &rap->snode, Address_SIZE)) {
  468. rap->snh->snodeIsReachable = false;
  469. if (rap->snh->onSnodeUnreachable) {
  470. rap->snh->onSnodeUnreachable(rap->snh, 0, 0);
  471. }
  472. }
  473. }
  474. static void onReply(Dict* msg, struct Address* src, struct MsgCore_Promise* prom)
  475. {
  476. struct Query* q = Identity_check((struct Query*) prom->userData);
  477. struct ReachabilityAnnouncer_pvt* rap = Identity_check(q->rap);
  478. if (rap->onTheWire != q) {
  479. Log_debug(rap->log, "Got a reply from [%s] which was outstanding when "
  480. "we triggered a state reset, discarding",
  481. Address_toString(prom->target, prom->alloc)->bytes);
  482. return;
  483. }
  484. rap->onTheWire = NULL;
  485. if (!src) {
  486. onReplyTimeout(rap, q);
  487. return;
  488. }
  489. int64_t* snodeRecvTime = Dict_getIntC(msg, "recvTime");
  490. if (!snodeRecvTime) {
  491. Log_warn(rap->log, "snode did not send back recvTime");
  492. onReplyTimeout(rap, q);
  493. return;
  494. }
  495. int64_t sentTime = rap->msgOnWireSentTime;
  496. Log_debug(rap->log, "snode messages before [%d]", rap->snodeState->length);
  497. // We need to takeover the message allocator because it belongs to the ping message which
  498. // will auto-free at the end of this cycle.
  499. Allocator_adopt(rap->alloc, Message_getAlloc(q->msg));
  500. addServerStateMsg(rap, q->msg);
  501. Log_debug(rap->log, "snode messages after [%d]", rap->snodeState->length);
  502. rap->resetState = false;
  503. int64_t now = rap->timeOfLastReply = ourTime(rap);
  504. int64_t oldClockSkew = rap->clockSkew;
  505. Log_debug(rap->log, "sentTime [%lld]", (long long int) sentTime);
  506. Log_debug(rap->log, "snodeRecvTime [%lld]", (long long int) *snodeRecvTime);
  507. Log_debug(rap->log, "now [%lld]", (long long int) now);
  508. Log_debug(rap->log, "oldClockSkew [%lld]", (long long int) oldClockSkew);
  509. rap->clockSkew = estimateImprovedClockSkew(sentTime, *snodeRecvTime, now, oldClockSkew);
  510. Log_debug(rap->log, "Adjusting clock skew by [%lld]",
  511. (long long int) (rap->clockSkew - oldClockSkew));
  512. Log_debug(rap->log, "State [%s]", printState(rap->state));
  513. Log_debug(rap->log, "TBA [%d]", rap->timeBetweenAnns);
  514. rap->state = ReachabilityAnnouncer_State_NORMAL;
  515. String* snodeStateHash = Dict_getStringC(msg, "stateHash");
  516. uint8_t ourStateHash[64];
  517. hashMsgList(rap->snodeState, ourStateHash);
  518. if (!snodeStateHash) {
  519. Log_warn(rap->log, "no stateHash in reply from snode");
  520. } else if (snodeStateHash->len != 64) {
  521. Log_warn(rap->log, "bad stateHash in reply from snode");
  522. } else if (Bits_memcmp(snodeStateHash->bytes, ourStateHash, 64)) {
  523. uint8_t snodeHash[129];
  524. Assert_true(128 == Hex_encode(snodeHash, 129, snodeStateHash->bytes, 64));
  525. uint8_t ourHash[129];
  526. Assert_true(128 == Hex_encode(ourHash, 129, ourStateHash, 64));
  527. Log_warn(rap->log, "state mismatch with snode, [%u] announces\n[%s]\n[%s]",
  528. rap->snodeState->length, snodeHash, ourHash);
  529. } else {
  530. return;
  531. }
  532. Log_warn(rap->log, "desynchronized with snode, resetting state");
  533. stateReset(rap);
  534. }
  535. static bool pushMeta(struct ReachabilityAnnouncer_pvt* rap, Message_t* msg)
  536. {
  537. struct Announce_Version version;
  538. Announce_Version_init(&version);
  539. if (updateItem(rap, msg, (struct Announce_ItemHeader*)&version) == updateItem_ENOSPACE) {
  540. return true;
  541. } else if (updateItem(rap, msg, rap->mySchemeItem) == updateItem_ENOSPACE) {
  542. return true;
  543. }
  544. return false;
  545. }
  546. static bool pushWithdrawLinks(struct ReachabilityAnnouncer_pvt* rap, Message_t* msg)
  547. {
  548. // First withdraw any announcements which are nolonger valid
  549. struct Allocator* tempAlloc = Allocator_child(rap->alloc);
  550. struct ArrayList_OfBarePeers* snodePeers = getSnodeStatePeers(rap, tempAlloc);
  551. bool outOfSpace = false;
  552. for (int i = 0; i < snodePeers->length; i++) {
  553. struct Announce_Peer* p = ArrayList_OfBarePeers_get(snodePeers, i);
  554. uint64_t path = Endian_bigEndianToHost16(p->peerNum_be);
  555. struct ReachabilityCollector_PeerInfo* pi =
  556. ReachabilityCollector_piForLabel(rap->rc, path);
  557. if (pi && pi->pathThemToUs) { continue; }
  558. char buf[60];
  559. Log_debug(rap->log, "Withdrawing route to [%s]", printPeer(buf, rap, p));
  560. p->label_be = 0;
  561. if (updateItem(rap, msg, (struct Announce_ItemHeader*) p) == updateItem_ENOSPACE) {
  562. outOfSpace = true;
  563. break;
  564. }
  565. }
  566. Allocator_free(tempAlloc);
  567. return outOfSpace;
  568. }
  569. static void onAnnounceCycle(void* vRap)
  570. {
  571. struct ReachabilityAnnouncer_pvt* rap =
  572. Identity_check((struct ReachabilityAnnouncer_pvt*) vRap);
  573. // Message out on the wire...
  574. if (rap->onTheWire) { return; }
  575. if (!rap->snode.path) { return; }
  576. int64_t now = ourTime(rap);
  577. int64_t snNow = snTime(rap);
  578. // Not time to send yet?
  579. int64_t delay = now - rap->timeOfLastReply;
  580. if (rap->state == ReachabilityAnnouncer_State_NORMAL) {
  581. if (delay < rap->timeBetweenAnns) { return; }
  582. } else {
  583. if (delay < rap->state) { return; }
  584. }
  585. struct MsgCore_Promise* qp = MsgCore_createQuery(rap->msgCore, 0, rap->alloc);
  586. struct Allocator* queryAlloc = Allocator_child(qp->alloc);
  587. Message_t* msg = Message_new(0, 1300, queryAlloc);
  588. Log_debug(rap->log, "\n");
  589. do {
  590. if (pushMeta(rap, msg)) {
  591. Log_debug(rap->log, "Out of space pushing metadata o_O");
  592. } else if (pushWithdrawLinks(rap, msg)) {
  593. Log_debug(rap->log, "Out of space pushing peer withdrawals");
  594. } else if (pushPeers(rap, msg)) {
  595. Log_debug(rap->log, "Out of space pushing peers");
  596. } else if (pushLinkState(rap, msg)) {
  597. Log_debug(rap->log, "Out of space pushing link state");
  598. } else {
  599. // Inch the tba up whenever there's a "small" message
  600. if (Message_getLength(msg) < 500) { rap->timeBetweenAnns += 100; }
  601. // Cap at 60 seconds, going over this requires changing when
  602. // nodes are re-announced.
  603. if (rap->timeBetweenAnns > 60000) { rap->timeBetweenAnns = 60000; }
  604. break;
  605. }
  606. stateUpdate(rap, ReachabilityAnnouncer_State_MSGFULL);
  607. // Cut the tba in half every time there's a MSGFULL
  608. rap->timeBetweenAnns /= 2;
  609. // minimum tba is 500ms
  610. if (rap->timeBetweenAnns < 500) { rap->timeBetweenAnns = 500; }
  611. } while (0);
  612. Err_assert(Message_epush(msg, NULL, Announce_Header_SIZE));
  613. struct Announce_Header* hdr = (struct Announce_Header*) Message_bytes(msg);
  614. Bits_memset(hdr, 0, Announce_Header_SIZE);
  615. Announce_Header_setVersion(hdr, Announce_Header_CURRENT_VERSION);
  616. Announce_Header_setReset(hdr, rap->resetState);
  617. Assert_true(Announce_Header_isReset(hdr) == rap->resetState);
  618. Announce_Header_setTimestamp(hdr, snNow);
  619. Bits_memcpy(hdr->pubSigningKey, rap->pubSigningKey, 32);
  620. Bits_memcpy(hdr->snodeIp, rap->snode.ip6.bytes, 16);
  621. Err_assert(Message_epop(msg, NULL, 64));
  622. Sign_signMsg(rap->signingKeypair, msg, rap->rand);
  623. Dict* dict = qp->msg = Dict_new(qp->alloc);
  624. qp->cb = onReply;
  625. struct Query* q = Allocator_calloc(qp->alloc, sizeof(struct Query), 1);
  626. Identity_set(q);
  627. q->rap = rap;
  628. q->msg = msg;
  629. Assert_true(AddressCalc_validAddress(rap->snode.ip6.bytes));
  630. Bits_memcpy(&q->target, &rap->snode, Address_SIZE);
  631. qp->userData = q;
  632. qp->target = &q->target;
  633. Dict_putStringCC(dict, "sq", "ann", qp->alloc);
  634. String* annString = String_newBinary(Message_bytes(msg), Message_getLength(msg), qp->alloc);
  635. Dict_putStringC(dict, "ann", annString, qp->alloc);
  636. rap->onTheWire = q;
  637. rap->msgOnWireSentTime = now;
  638. }
  639. static void onSnodeChange(struct SupernodeHunter* sh,
  640. int64_t sendTime,
  641. int64_t snodeRecvTime)
  642. {
  643. struct ReachabilityAnnouncer_pvt* rap =
  644. Identity_check((struct ReachabilityAnnouncer_pvt*) sh->userData);
  645. int64_t clockSkew = estimateClockSkew(sendTime, snodeRecvTime, ourTime(rap));
  646. uint64_t clockSkewDiff = (clockSkew > rap->clockSkew)
  647. ? (clockSkew - rap->clockSkew)
  648. : (rap->clockSkew - clockSkew);
  649. // If the node is the same and the clock skew difference is less than 10 seconds,
  650. // just change path and continue.
  651. if (Bits_memcmp(rap->snode.key, sh->snodeAddr.key, 32)) {
  652. if (Defined(Log_DEBUG)) {
  653. uint8_t oldSnode[40];
  654. AddrTools_printIp(oldSnode, rap->snode.ip6.bytes);
  655. uint8_t newSnode[40];
  656. AddrTools_printIp(newSnode, sh->snodeAddr.ip6.bytes);
  657. Log_debug(rap->log, "Change Supernode [%s] -> [%s]", oldSnode, newSnode);
  658. }
  659. } else if (clockSkewDiff > 5000) {
  660. Log_debug(rap->log,
  661. "Change Supernode (no change but clock skew diff [%" PRIu64 "] > 5000ms)",
  662. clockSkewDiff);
  663. } else if (rap->snode.path == sh->snodeAddr.path) {
  664. Log_debug(rap->log, "Change Supernode (not really, false call)");
  665. return;
  666. } else {
  667. uint8_t oldPath[20];
  668. uint8_t newPath[20];
  669. AddrTools_printPath(oldPath, rap->snode.path);
  670. AddrTools_printPath(newPath, sh->snodeAddr.path);
  671. Log_debug(rap->log, "Change Supernode path [%s] -> [%s]", oldPath, newPath);
  672. Bits_memcpy(&rap->snode, &sh->snodeAddr, Address_SIZE);
  673. PeeringSeeder_setSnode(rap->ps, &rap->snode);
  674. return;
  675. }
  676. Bits_memcpy(&rap->snode, &sh->snodeAddr, Address_SIZE);
  677. PeeringSeeder_setSnode(rap->ps, &rap->snode);
  678. rap->clockSkew = clockSkew;
  679. stateReset(rap);
  680. }
  681. static struct Announce_ItemHeader* mkEncodingSchemeItem(
  682. struct Allocator* alloc,
  683. String* compressedScheme)
  684. {
  685. struct Allocator* tmpAlloc = Allocator_child(alloc);
  686. Message_t* esMsg = Message_new(0, 256, tmpAlloc);
  687. Assert_true(compressedScheme->len + 2 < 256);
  688. Err_assert(Message_epush(esMsg, compressedScheme->bytes, compressedScheme->len));
  689. Err_assert(Message_epush8(esMsg, Announce_Type_ENCODING_SCHEME));
  690. Err_assert(Message_epush8(esMsg, compressedScheme->len + 2));
  691. struct Announce_ItemHeader* item = Allocator_calloc(alloc, Message_getLength(esMsg), 1);
  692. Bits_memcpy(item, Message_bytes(esMsg), Message_getLength(esMsg));
  693. Allocator_free(tmpAlloc);
  694. return item;
  695. }
  696. struct ReachabilityAnnouncer* ReachabilityAnnouncer_new(struct Allocator* allocator,
  697. struct Log* log,
  698. EventBase_t* base,
  699. struct Random* rand,
  700. struct MsgCore* msgCore,
  701. struct SupernodeHunter* snh,
  702. uint8_t* privateKey,
  703. struct EncodingScheme* myScheme,
  704. struct ReachabilityCollector* rc,
  705. PeeringSeeder_t* ps)
  706. {
  707. struct Allocator* alloc = Allocator_child(allocator);
  708. struct ReachabilityAnnouncer_pvt* rap =
  709. Allocator_calloc(alloc, sizeof(struct ReachabilityAnnouncer_pvt), 1);
  710. Identity_set(rap);
  711. rap->alloc = alloc;
  712. rap->log = log;
  713. rap->base = base;
  714. rap->msgCore = msgCore;
  715. rap->announceCycle = Timeout_setInterval(onAnnounceCycle, rap, 250, base, alloc);
  716. rap->rand = rand;
  717. rap->snodeState = ArrayList_OfMessages_new(alloc);
  718. rap->myScheme = myScheme;
  719. rap->encodingSchemeStr = EncodingScheme_serialize(myScheme, alloc);
  720. rap->rc = rc;
  721. rap->ps = ps;
  722. rap->mySchemeItem =
  723. (struct Announce_ItemHeader*) mkEncodingSchemeItem(alloc, rap->encodingSchemeStr);
  724. rap->snh = snh;
  725. snh->onSnodeChange = onSnodeChange;
  726. snh->userData = rap;
  727. Sign_signingKeyPairFromCurve25519(rap->signingKeypair, privateKey);
  728. Sign_publicKeyFromKeyPair(rap->pubSigningKey, rap->signingKeypair);
  729. return &rap->pub;
  730. }