ReachabilityAnnouncer.c 31 KB

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