1
0

ReachabilityAnnouncer.c 32 KB

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