1
0

ReachabilityAnnouncer.c 31 KB

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