SessionManager.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  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 "memory/Allocator.h"
  16. #include "wire/PFChan.h"
  17. #include "net/SessionManager.h"
  18. #include "crypto/AddressCalc.h"
  19. #include "util/AddrTools.h"
  20. #include "wire/Error.h"
  21. #include "util/events/Time.h"
  22. #include "util/Defined.h"
  23. #include "wire/RouteHeader.h"
  24. #include "util/events/Timeout.h"
  25. #include "util/Checksum.h"
  26. /** Handle numbers 0-3 are reserved for CryptoAuth nonces. */
  27. #define MIN_FIRST_HANDLE 4
  28. #define MAX_FIRST_HANDLE 100000
  29. struct BufferedMessage
  30. {
  31. struct Message* msg;
  32. struct Allocator* alloc;
  33. uint64_t timeSentMilliseconds;
  34. };
  35. struct Ip6 {
  36. uint8_t bytes[16];
  37. };
  38. #define Map_KEY_TYPE struct Ip6
  39. #define Map_VALUE_TYPE struct BufferedMessage*
  40. #define Map_NAME BufferedMessages
  41. #include "util/Map.h"
  42. #define Map_KEY_TYPE struct Ip6
  43. #define Map_VALUE_TYPE struct SessionManager_Session_pvt*
  44. #define Map_NAME OfSessionsByIp6
  45. #define Map_ENABLE_HANDLES
  46. #include "util/Map.h"
  47. struct SessionManager_pvt
  48. {
  49. struct SessionManager pub;
  50. struct Iface eventIf;
  51. struct Allocator* alloc;
  52. struct Map_BufferedMessages bufMap;
  53. struct Map_OfSessionsByIp6 ifaceMap;
  54. struct Log* log;
  55. struct CryptoAuth* cryptoAuth;
  56. struct EventBase* eventBase;
  57. uint32_t firstHandle;
  58. Identity
  59. };
  60. struct SessionManager_Session_pvt
  61. {
  62. struct SessionManager_Session pub;
  63. struct SessionManager_pvt* sessionManager;
  64. struct Allocator* alloc;
  65. bool foundKey;
  66. Identity
  67. };
  68. #define debugHandlesAndLabel(logger, session, label, message, ...) \
  69. do { \
  70. if (!Defined(Log_DEBUG)) { break; } \
  71. uint8_t path[20]; \
  72. AddrTools_printPath(path, label); \
  73. uint8_t ip[40]; \
  74. AddrTools_printIp(ip, session->pub.caSession->herIp6); \
  75. Log_debug(logger, "ver[%u] send[%d] recv[%u] ip[%s] path[%s] " message, \
  76. session->pub.version, \
  77. session->pub.sendHandle, \
  78. session->pub.receiveHandle, \
  79. ip, \
  80. path, \
  81. __VA_ARGS__); \
  82. } while (0)
  83. //CHECKFILES_IGNORE expecting a ;
  84. #define debugHandlesAndLabel0(logger, session, label, message) \
  85. debugHandlesAndLabel(logger, session, label, "%s", message)
  86. #define debugSession(logger, session, message, ...) \
  87. do { \
  88. if (!Defined(Log_DEBUG)) { break; } \
  89. uint8_t sendPath[20]; \
  90. uint8_t recvPath[20]; \
  91. uint8_t ip[40]; \
  92. AddrTools_printPath(sendPath, (session)->pub.sendSwitchLabel); \
  93. AddrTools_printPath(recvPath, (session)->pub.recvSwitchLabel); \
  94. AddrTools_printIp(ip, (session)->pub.caSession->herIp6); \
  95. Log_debug((logger), "Session sendPath[%s] recvPath[%s] ip[%s] " message, \
  96. sendPath, \
  97. recvPath, \
  98. ip, \
  99. __VA_ARGS__); \
  100. } while (0)
  101. //CHECKFILES_IGNORE ;
  102. #define debugSession0(logger, session, message) \
  103. debugSession(logger, session, "%s", message)
  104. static void sendSession(struct SessionManager_Session_pvt* sess,
  105. uint64_t path,
  106. uint32_t destPf,
  107. enum PFChan_Core ev)
  108. {
  109. struct PFChan_Node session = {
  110. .path_be = Endian_hostToBigEndian64(path),
  111. .metric_be = Endian_bigEndianToHost32(sess->pub.metric),
  112. .version_be = Endian_hostToBigEndian32(sess->pub.version)
  113. };
  114. Bits_memcpy(session.ip6, sess->pub.caSession->herIp6, 16);
  115. Bits_memcpy(session.publicKey, sess->pub.caSession->herPublicKey, 32);
  116. struct Allocator* alloc = Allocator_child(sess->alloc);
  117. struct Message* msg = Message_new(0, PFChan_Node_SIZE + 512, alloc);
  118. Message_push(msg, &session, PFChan_Node_SIZE, NULL);
  119. Message_push32(msg, destPf, NULL);
  120. Message_push32(msg, ev, NULL);
  121. Iface_send(&sess->sessionManager->eventIf, msg);
  122. Allocator_free(alloc);
  123. }
  124. static inline void check(struct SessionManager_pvt* sm, int mapIndex)
  125. {
  126. struct SessionManager_Session_pvt* ssp = Identity_check(sm->ifaceMap.values[mapIndex]);
  127. if (ssp->foundKey) { return; }
  128. uint8_t* herPubKey = ssp->pub.caSession->herPublicKey;
  129. if (!Bits_isZero(herPubKey, 32)) {
  130. uint8_t ip6[16];
  131. AddressCalc_addressForPublicKey(ip6, herPubKey);
  132. Assert_true(!Bits_memcmp(&sm->ifaceMap.keys[mapIndex], ip6, 16));
  133. ssp->foundKey = true;
  134. }
  135. }
  136. static inline struct SessionManager_Session_pvt* sessionForHandle(uint32_t handle,
  137. struct SessionManager_pvt* sm)
  138. {
  139. int index = Map_OfSessionsByIp6_indexForHandle(handle - sm->firstHandle, &sm->ifaceMap);
  140. if (index < 0) { return NULL; }
  141. check(sm, index);
  142. return Identity_check(sm->ifaceMap.values[index]);
  143. }
  144. struct SessionManager_Session* SessionManager_sessionForHandle(uint32_t handle,
  145. struct SessionManager* manager)
  146. {
  147. struct SessionManager_pvt* sm = Identity_check((struct SessionManager_pvt*) manager);
  148. return (struct SessionManager_Session*) sessionForHandle(handle, sm);
  149. }
  150. static inline struct SessionManager_Session_pvt* sessionForIp6(uint8_t ip6[16],
  151. struct SessionManager_pvt* sm)
  152. {
  153. int ifaceIndex = Map_OfSessionsByIp6_indexForKey((struct Ip6*)ip6, &sm->ifaceMap);
  154. if (ifaceIndex == -1) { return NULL; }
  155. check(sm, ifaceIndex);
  156. return Identity_check(sm->ifaceMap.values[ifaceIndex]);
  157. }
  158. struct SessionManager_Session* SessionManager_sessionForIp6(uint8_t* ip6,
  159. struct SessionManager* manager)
  160. {
  161. struct SessionManager_pvt* sm = Identity_check((struct SessionManager_pvt*) manager);
  162. return (struct SessionManager_Session*) sessionForIp6(ip6, sm);
  163. }
  164. struct SessionManager_HandleList* SessionManager_getHandleList(struct SessionManager* manager,
  165. struct Allocator* alloc)
  166. {
  167. struct SessionManager_pvt* sm = Identity_check((struct SessionManager_pvt*) manager);
  168. struct SessionManager_HandleList* out =
  169. Allocator_calloc(alloc, sizeof(struct SessionManager_HandleList), 1);
  170. uint32_t* buff = Allocator_calloc(alloc, 4, sm->ifaceMap.count);
  171. out->length = sm->ifaceMap.count;
  172. out->handles = buff;
  173. for (int i = 0; i < out->length; i++) {
  174. buff[i] = sm->ifaceMap.handles[i] + sm->firstHandle;
  175. }
  176. return out;
  177. }
  178. static struct SessionManager_Session_pvt* getSession(struct SessionManager_pvt* sm,
  179. uint8_t ip6[16],
  180. uint8_t pubKey[32],
  181. uint32_t version,
  182. uint64_t label,
  183. uint32_t metric)
  184. {
  185. Assert_true(AddressCalc_validAddress(ip6));
  186. struct SessionManager_Session_pvt* sess = sessionForIp6(ip6, sm);
  187. if (sess) {
  188. sess->pub.version = (sess->pub.version) ? sess->pub.version : version;
  189. if (metric == 0xffffffff) {
  190. // this is a broken path
  191. if (sess->pub.sendSwitchLabel == label) {
  192. debugSession0(sm->log, sess, "broken path");
  193. if (sess->pub.sendSwitchLabel == sess->pub.recvSwitchLabel) {
  194. sess->pub.sendSwitchLabel = 0;
  195. sess->pub.metric = 0xffffffff;
  196. } else {
  197. sess->pub.sendSwitchLabel = sess->pub.recvSwitchLabel;
  198. sess->pub.metric = 0xfffffff0;
  199. }
  200. }
  201. } else {
  202. if (metric <= sess->pub.metric) {
  203. sess->pub.sendSwitchLabel = label;
  204. sess->pub.version = (version) ? version : sess->pub.version;
  205. sess->pub.metric = metric;
  206. debugSession0(sm->log, sess, "discovered path");
  207. }
  208. }
  209. return sess;
  210. }
  211. struct Allocator* alloc = Allocator_child(sm->alloc);
  212. sess = Allocator_calloc(alloc, sizeof(struct SessionManager_Session_pvt), 1);
  213. Identity_set(sess);
  214. sess->pub.caSession = CryptoAuth_newSession(sm->cryptoAuth, alloc, pubKey, false, "inner");
  215. sess->foundKey = !Bits_isZero(pubKey, 32);
  216. if (sess->foundKey) {
  217. uint8_t realIp6[16];
  218. AddressCalc_addressForPublicKey(realIp6, pubKey);
  219. Assert_true(!Bits_memcmp(realIp6, ip6, 16));
  220. }
  221. int ifaceIndex = Map_OfSessionsByIp6_put((struct Ip6*)ip6, &sess, &sm->ifaceMap);
  222. sess->pub.receiveHandle = sm->ifaceMap.handles[ifaceIndex] + sm->firstHandle;
  223. if (Defined(Log_DEBUG)) {
  224. uint8_t printedIp6[40];
  225. AddrTools_printIp(printedIp6, ip6);
  226. Log_debug(sm->log, "Created session for [%s] handle [%u]",
  227. printedIp6, sess->pub.receiveHandle);
  228. }
  229. sess->alloc = alloc;
  230. sess->sessionManager = sm;
  231. sess->pub.version = version;
  232. sess->pub.timeOfLastIn = Time_currentTimeMilliseconds(sm->eventBase);
  233. sess->pub.timeOfKeepAliveIn = Time_currentTimeMilliseconds(sm->eventBase);
  234. sess->pub.timeOfLastOut = Time_currentTimeMilliseconds(sm->eventBase);
  235. sess->pub.sendSwitchLabel = label;
  236. sess->pub.metric = metric;
  237. //Allocator_onFree(alloc, sessionCleanup, sess);
  238. sendSession(sess, label, 0xffffffff, PFChan_Core_SESSION);
  239. check(sm, ifaceIndex);
  240. return sess;
  241. }
  242. static Iface_DEFUN ctrlFrame(struct Message* msg, struct SessionManager_pvt* sm)
  243. {
  244. struct RouteHeader rh;
  245. Bits_memset(&rh, 0, RouteHeader_SIZE);
  246. Message_pop(msg, &rh.sh, SwitchHeader_SIZE, NULL);
  247. Message_pop(msg, NULL, 4, NULL);
  248. rh.flags = RouteHeader_flags_INCOMING | RouteHeader_flags_CTRLMSG;
  249. Message_push(msg, &rh, RouteHeader_SIZE, NULL);
  250. return Iface_next(&sm->pub.insideIf, msg);
  251. }
  252. static Iface_DEFUN failedDecrypt(struct Message* msg,
  253. uint64_t label_be,
  254. struct SessionManager_pvt* sm)
  255. {
  256. Message_push32(msg, Error_AUTHENTICATION, NULL);
  257. Message_push16(msg, Control_ERROR, NULL);
  258. Message_push16(msg, 0, NULL);
  259. uint16_t csum = Checksum_engine(msg->bytes, msg->length);
  260. Message_pop16(msg, NULL);
  261. Message_push16(msg, csum, NULL);
  262. Message_push32(msg, 0xffffffff, NULL);
  263. struct SwitchHeader sh;
  264. Bits_memset(&sh, 0, SwitchHeader_SIZE);
  265. SwitchHeader_setSuppressErrors(&sh, true);
  266. SwitchHeader_setVersion(&sh, SwitchHeader_CURRENT_VERSION);
  267. sh.label_be = label_be;
  268. Message_push(msg, &sh, SwitchHeader_SIZE, NULL);
  269. return Iface_next(&sm->pub.switchIf, msg);
  270. }
  271. static Iface_DEFUN incomingFromSwitchIf(struct Message* msg, struct Iface* iface)
  272. {
  273. struct SessionManager_pvt* sm =
  274. Identity_containerOf(iface, struct SessionManager_pvt, pub.switchIf);
  275. // SwitchHeader, handle, 0 or more bytes of control frame
  276. if (msg->length < SwitchHeader_SIZE + 4) {
  277. Log_debug(sm->log, "DROP runt");
  278. return NULL;
  279. }
  280. struct SwitchHeader* switchHeader = (struct SwitchHeader*) msg->bytes;
  281. Message_shift(msg, -SwitchHeader_SIZE, NULL);
  282. // The label comes in reversed from the switch because the switch doesn't know that we aren't
  283. // another switch ready to parse more bits, bit reversing the label yields the source address.
  284. // (the field is still big endian!)
  285. switchHeader->label_be = Bits_bitReverse64(switchHeader->label_be);
  286. struct SessionManager_Session_pvt* session;
  287. uint32_t nonceOrHandle = Endian_bigEndianToHost32(((uint32_t*)msg->bytes)[0]);
  288. if (nonceOrHandle == 0xffffffff) {
  289. Message_shift(msg, SwitchHeader_SIZE, NULL);
  290. return ctrlFrame(msg, sm);
  291. }
  292. // handle, small cryptoAuth header
  293. if (msg->length < 4 + 20) {
  294. Log_debug(sm->log, "DROP runt");
  295. return NULL;
  296. }
  297. // This is for handling error situations and being able to send back some kind of a message.
  298. uint8_t firstSixteen[16];
  299. uint32_t length0 = msg->length;
  300. Assert_true(msg->length >= 16);
  301. Bits_memcpy(firstSixteen, msg->bytes, 16);
  302. if (nonceOrHandle > 3) {
  303. // > 3 it's a handle.
  304. session = sessionForHandle(nonceOrHandle, sm);
  305. if (!session) {
  306. Log_debug(sm->log, "DROP message with unrecognized handle [%u]", nonceOrHandle);
  307. return NULL;
  308. }
  309. Message_shift(msg, -4, NULL);
  310. uint32_t nonce = Endian_bigEndianToHost32(((uint32_t*)msg->bytes)[0]);
  311. if (nonce < 4) {
  312. Log_debug(sm->log, "DROP setup message [%u] with specified handle [%u]",
  313. nonce, nonceOrHandle);
  314. return NULL;
  315. }
  316. } else {
  317. // handle + big cryptoauth header
  318. if (msg->length < CryptoHeader_SIZE + 4) {
  319. Log_debug(sm->log, "DROP runt");
  320. return NULL;
  321. }
  322. struct CryptoHeader* caHeader = (struct CryptoHeader*) msg->bytes;
  323. uint8_t ip6[16];
  324. // a packet which claims to be "from us" causes problems
  325. if (!AddressCalc_addressForPublicKey(ip6, caHeader->publicKey)) {
  326. Log_debug(sm->log, "DROP Handshake with non-fc key");
  327. return NULL;
  328. }
  329. if (!Bits_memcmp(caHeader->publicKey, sm->cryptoAuth->publicKey, 32)) {
  330. Log_debug(sm->log, "DROP Handshake from 'ourselves'");
  331. return NULL;
  332. }
  333. uint64_t label = Endian_bigEndianToHost64(switchHeader->label_be);
  334. session = getSession(sm, ip6, caHeader->publicKey, 0, label, 0xfffff000);
  335. CryptoAuth_resetIfTimeout(session->pub.caSession);
  336. debugHandlesAndLabel(sm->log, session, label, "new session nonce[%d]", nonceOrHandle);
  337. }
  338. bool currentMessageSetup = (nonceOrHandle <= 3);
  339. enum CryptoAuth_DecryptErr ret = CryptoAuth_decrypt(session->pub.caSession, msg);
  340. if (ret) {
  341. debugHandlesAndLabel(sm->log, session,
  342. Endian_bigEndianToHost64(switchHeader->label_be),
  343. "DROP Failed decrypting message NoH[%d] state[%s]",
  344. nonceOrHandle,
  345. CryptoAuth_stateString(CryptoAuth_getState(session->pub.caSession)));
  346. Message_shift(msg, length0 - msg->length - 24, NULL);
  347. msg->length = 0;
  348. Message_push32(msg, CryptoAuth_getState(session->pub.caSession), NULL);
  349. Message_push32(msg, ret, NULL);
  350. Message_push(msg, firstSixteen, 16, NULL);
  351. Message_shift(msg, SwitchHeader_SIZE, NULL);
  352. Assert_true(msg->bytes == (uint8_t*)switchHeader);
  353. uint64_t label_be = switchHeader->label_be;
  354. switchHeader->label_be = Bits_bitReverse64(switchHeader->label_be);
  355. return failedDecrypt(msg, label_be, sm);
  356. }
  357. if (currentMessageSetup) {
  358. session->pub.sendHandle = Message_pop32(msg, NULL);
  359. }
  360. Message_shift(msg, RouteHeader_SIZE, NULL);
  361. struct RouteHeader* header = (struct RouteHeader*) msg->bytes;
  362. Assert_true(msg->length >= DataHeader_SIZE);
  363. struct DataHeader* dh = (struct DataHeader*) &header[1];
  364. if (DataHeader_getContentType(dh) != ContentType_CJDHT) {
  365. session->pub.timeOfLastIn = Time_currentTimeMilliseconds(sm->eventBase);
  366. }
  367. session->pub.bytesIn += msg->length;
  368. session->pub.timeOfKeepAliveIn = Time_currentTimeMilliseconds(sm->eventBase);
  369. if (currentMessageSetup) {
  370. Bits_memcpy(&header->sh, switchHeader, SwitchHeader_SIZE);
  371. debugHandlesAndLabel0(sm->log,
  372. session,
  373. Endian_bigEndianToHost64(switchHeader->label_be),
  374. "received start message");
  375. } else {
  376. // RouteHeader is laid out such that no copy of switch header should be needed.
  377. Assert_true(&header->sh == switchHeader);
  378. if (0) { // noisey
  379. debugHandlesAndLabel0(sm->log,
  380. session,
  381. Endian_bigEndianToHost64(switchHeader->label_be),
  382. "received run message");
  383. }
  384. }
  385. header->version_be = Endian_hostToBigEndian32(session->pub.version);
  386. Bits_memcpy(header->ip6, session->pub.caSession->herIp6, 16);
  387. Bits_memcpy(header->publicKey, session->pub.caSession->herPublicKey, 32);
  388. header->unused = 0;
  389. header->flags = RouteHeader_flags_INCOMING;
  390. uint64_t path = Endian_bigEndianToHost64(switchHeader->label_be);
  391. if (!session->pub.sendSwitchLabel) {
  392. session->pub.sendSwitchLabel = path;
  393. }
  394. if (path != session->pub.recvSwitchLabel) {
  395. session->pub.recvSwitchLabel = path;
  396. sendSession(session, path, 0xffffffff, PFChan_Core_DISCOVERED_PATH);
  397. }
  398. return Iface_next(&sm->pub.insideIf, msg);
  399. }
  400. static void checkTimedOutBuffers(struct SessionManager_pvt* sm)
  401. {
  402. for (int i = 0; i < (int)sm->bufMap.count; i++) {
  403. struct BufferedMessage* buffered = sm->bufMap.values[i];
  404. int64_t lag = Time_currentTimeMilliseconds(sm->eventBase) - buffered->timeSentMilliseconds;
  405. if (lag < 10000) { continue; }
  406. Map_BufferedMessages_remove(i, &sm->bufMap);
  407. Allocator_free(buffered->alloc);
  408. i--;
  409. }
  410. }
  411. static void unsetupSession(struct SessionManager_pvt* sm, struct SessionManager_Session_pvt* sess)
  412. {
  413. if (!sess->pub.version || !(sess->pub.sendSwitchLabel || sess->pub.recvSwitchLabel)) {
  414. // Nothing we can do here because it's not ok to send traffic without a version num.
  415. return;
  416. }
  417. struct Allocator* eventAlloc = Allocator_child(sm->alloc);
  418. struct Message* eventMsg = Message_new(0, 512, eventAlloc);
  419. struct PFChan_Node n;
  420. n.path_be = Endian_hostToBigEndian64(sess->pub.sendSwitchLabel ?
  421. sess->pub.sendSwitchLabel : sess->pub.recvSwitchLabel);
  422. n.version_be = Endian_hostToBigEndian32(sess->pub.version);
  423. Bits_memcpy(n.publicKey, sess->pub.caSession->herPublicKey, 32);
  424. Bits_memcpy(n.ip6, sess->pub.caSession->herIp6, 16);
  425. Message_push(eventMsg, &n, PFChan_Node_SIZE, NULL);
  426. Message_push32(eventMsg, 0xffffffff, NULL);
  427. Message_push32(eventMsg, PFChan_Core_UNSETUP_SESSION, NULL);
  428. Iface_send(&sm->eventIf, eventMsg);
  429. Allocator_free(eventAlloc);
  430. }
  431. static void triggerSearch(struct SessionManager_pvt* sm, uint8_t target[16], uint32_t version)
  432. {
  433. struct Allocator* eventAlloc = Allocator_child(sm->alloc);
  434. struct Message* eventMsg = Message_new(0, 512, eventAlloc);
  435. Message_push32(eventMsg, version, NULL);
  436. Message_push32(eventMsg, 0, NULL);
  437. Message_push(eventMsg, target, 16, NULL);
  438. Message_push32(eventMsg, 0xffffffff, NULL);
  439. Message_push32(eventMsg, PFChan_Core_SEARCH_REQ, NULL);
  440. Iface_send(&sm->eventIf, eventMsg);
  441. Allocator_free(eventAlloc);
  442. }
  443. static void checkTimedOutSessions(struct SessionManager_pvt* sm)
  444. {
  445. bool searchTriggered = false;
  446. for (int i = (int)sm->ifaceMap.count - 1; i >= 0; i--) {
  447. struct SessionManager_Session_pvt* sess = sm->ifaceMap.values[i];
  448. int64_t now = Time_currentTimeMilliseconds(sm->eventBase);
  449. // Check if the session is timed out...
  450. if (now - sess->pub.timeOfKeepAliveIn > sm->pub.sessionTimeoutMilliseconds) {
  451. debugSession0(sm->log, sess, "ended");
  452. sendSession(sess, sess->pub.sendSwitchLabel, 0xffffffff, PFChan_Core_SESSION_ENDED);
  453. Map_OfSessionsByIp6_remove(i, &sm->ifaceMap);
  454. Allocator_free(sess->alloc);
  455. continue;
  456. }
  457. if (now - sess->pub.lastSearchTime >= sm->pub.sessionSearchAfterMilliseconds) {
  458. // Session is not in idle state and requires a search
  459. // But we're only going to trigger one search per cycle.
  460. // Except for v20 because the snode will answer us.
  461. if (searchTriggered && sess->pub.version < 20) { continue; }
  462. debugSession0(sm->log, sess, "triggering search");
  463. triggerSearch(sm, sess->pub.caSession->herIp6, sess->pub.version);
  464. sess->pub.lastSearchTime = now;
  465. searchTriggered = true;
  466. } else if (CryptoAuth_getState(sess->pub.caSession) < CryptoAuth_State_RECEIVED_KEY) {
  467. debugSession0(sm->log, sess, "triggering unsetupSession");
  468. unsetupSession(sm, sess);
  469. }
  470. }
  471. }
  472. static void periodically(void* vSessionManager)
  473. {
  474. struct SessionManager_pvt* sm = Identity_check((struct SessionManager_pvt*) vSessionManager);
  475. checkTimedOutSessions(sm);
  476. checkTimedOutBuffers(sm);
  477. }
  478. static void needsLookup(struct SessionManager_pvt* sm, struct Message* msg, bool setupSession)
  479. {
  480. Assert_true(msg->length >= (RouteHeader_SIZE + DataHeader_SIZE));
  481. struct RouteHeader* header = (struct RouteHeader*) msg->bytes;
  482. // We should never be sending CJDHT messages without full version, key, path known.
  483. struct DataHeader* dataHeader = (struct DataHeader*) &header[1];
  484. Assert_true(DataHeader_getContentType(dataHeader) != ContentType_CJDHT);
  485. if (Defined(Log_DEBUG)) {
  486. uint8_t ipStr[40];
  487. AddrTools_printIp(ipStr, header->ip6);
  488. Log_debug(sm->log, "Buffering a packet to [%s] and beginning a search", ipStr);
  489. }
  490. int index = Map_BufferedMessages_indexForKey((struct Ip6*)header->ip6, &sm->bufMap);
  491. if (index > -1) {
  492. struct BufferedMessage* buffered = sm->bufMap.values[index];
  493. Map_BufferedMessages_remove(index, &sm->bufMap);
  494. Allocator_free(buffered->alloc);
  495. Log_debug(sm->log, "DROP message which needs lookup because new one received");
  496. }
  497. if ((int)sm->bufMap.count >= sm->pub.maxBufferedMessages) {
  498. checkTimedOutBuffers(sm);
  499. if ((int)sm->bufMap.count >= sm->pub.maxBufferedMessages) {
  500. Log_debug(sm->log, "DROP message needing lookup maxBufferedMessages ([%d]) is reached",
  501. sm->pub.maxBufferedMessages);
  502. return;
  503. }
  504. }
  505. struct Allocator* lookupAlloc = Allocator_child(sm->alloc);
  506. struct BufferedMessage* buffered =
  507. Allocator_calloc(lookupAlloc, sizeof(struct BufferedMessage), 1);
  508. buffered->msg = msg;
  509. buffered->alloc = lookupAlloc;
  510. buffered->timeSentMilliseconds = Time_currentTimeMilliseconds(sm->eventBase);
  511. Allocator_adopt(lookupAlloc, msg->alloc);
  512. Assert_true(Map_BufferedMessages_put((struct Ip6*)header->ip6, &buffered, &sm->bufMap) > -1);
  513. triggerSearch(sm, header->ip6, Endian_hostToBigEndian32(header->version_be));
  514. }
  515. static Iface_DEFUN readyToSend(struct Message* msg,
  516. struct SessionManager_pvt* sm,
  517. struct SessionManager_Session_pvt* sess)
  518. {
  519. struct RouteHeader* header = (struct RouteHeader*) msg->bytes;
  520. struct DataHeader* dh = (struct DataHeader*) &header[1];
  521. if (DataHeader_getContentType(dh) != ContentType_CJDHT) {
  522. sess->pub.timeOfLastOut = Time_currentTimeMilliseconds(sm->eventBase);
  523. }
  524. Message_shift(msg, -RouteHeader_SIZE, NULL);
  525. struct SwitchHeader* sh;
  526. CryptoAuth_resetIfTimeout(sess->pub.caSession);
  527. if (CryptoAuth_getState(sess->pub.caSession) < CryptoAuth_State_RECEIVED_KEY) {
  528. // Put the handle into the message so that it's authenticated.
  529. Message_push32(msg, sess->pub.receiveHandle, NULL);
  530. // Copy back the SwitchHeader so it is not clobbered.
  531. Message_shift(msg, (CryptoHeader_SIZE + SwitchHeader_SIZE), NULL);
  532. Bits_memcpy(msg->bytes, &header->sh, SwitchHeader_SIZE);
  533. sh = (struct SwitchHeader*) msg->bytes;
  534. Message_shift(msg, -(CryptoHeader_SIZE + SwitchHeader_SIZE), NULL);
  535. } else {
  536. sh = &header->sh;
  537. }
  538. // This pointer ceases to be useful.
  539. header = NULL;
  540. sess->pub.bytesOut += msg->length;
  541. Assert_true(!CryptoAuth_encrypt(sess->pub.caSession, msg));
  542. if (CryptoAuth_getState(sess->pub.caSession) >= CryptoAuth_State_RECEIVED_KEY) {
  543. if (0) { // Noisy
  544. debugHandlesAndLabel0(sm->log,
  545. sess,
  546. Endian_bigEndianToHost64(sh->label_be),
  547. "sending run message");
  548. }
  549. Message_push32(msg, sess->pub.sendHandle, NULL);
  550. } else {
  551. debugHandlesAndLabel0(sm->log,
  552. sess,
  553. Endian_bigEndianToHost64(sh->label_be),
  554. "sending start message");
  555. }
  556. // The SwitchHeader should have been moved to the correct location.
  557. Message_shift(msg, SwitchHeader_SIZE, NULL);
  558. Assert_true((uint8_t*)sh == msg->bytes);
  559. if (!sh->label_be) {
  560. Bits_memset(sh, 0, SwitchHeader_SIZE);
  561. sh->label_be = Endian_hostToBigEndian64(sess->pub.sendSwitchLabel);
  562. SwitchHeader_setVersion(sh, SwitchHeader_CURRENT_VERSION);
  563. }
  564. return Iface_next(&sm->pub.switchIf, msg);
  565. }
  566. static Iface_DEFUN outgoingCtrlFrame(struct Message* msg, struct SessionManager_pvt* sm)
  567. {
  568. Assert_true(msg->length >= RouteHeader_SIZE);
  569. struct RouteHeader* header = (struct RouteHeader*) msg->bytes;
  570. if (!Bits_isZero(header->publicKey, 32) || !Bits_isZero(header->ip6, 16)) {
  571. Log_debug(sm->log, "DROP Ctrl frame with non-zero destination key or IP");
  572. return NULL;
  573. }
  574. if (!(header->flags & RouteHeader_flags_CTRLMSG)) {
  575. Log_debug(sm->log, "DROP Ctrl frame w/o RouteHeader_flags_CTRLMSG flag");
  576. return NULL;
  577. }
  578. struct SwitchHeader sh;
  579. Bits_memcpy(&sh, &header->sh, SwitchHeader_SIZE);
  580. Message_pop(msg, NULL, RouteHeader_SIZE, NULL);
  581. Message_push32(msg, 0xffffffff, NULL);
  582. Message_push(msg, &sh, SwitchHeader_SIZE, NULL);
  583. return Iface_next(&sm->pub.switchIf, msg);
  584. }
  585. static Iface_DEFUN incomingFromInsideIf(struct Message* msg, struct Iface* iface)
  586. {
  587. struct SessionManager_pvt* sm =
  588. Identity_containerOf(iface, struct SessionManager_pvt, pub.insideIf);
  589. Assert_true(msg->length >= RouteHeader_SIZE);
  590. struct RouteHeader* header = (struct RouteHeader*) msg->bytes;
  591. if (header->flags & RouteHeader_flags_CTRLMSG) {
  592. return outgoingCtrlFrame(msg, sm);
  593. }
  594. Assert_true(msg->length >= RouteHeader_SIZE + DataHeader_SIZE);
  595. struct DataHeader* dataHeader = (struct DataHeader*) &header[1];
  596. struct SessionManager_Session_pvt* sess = sessionForIp6(header->ip6, sm);
  597. if (!sess) {
  598. if (!Bits_isZero(header->publicKey, 32) && header->version_be) {
  599. sess = getSession(sm,
  600. header->ip6,
  601. header->publicKey,
  602. Endian_bigEndianToHost32(header->version_be),
  603. Endian_bigEndianToHost64(header->sh.label_be),
  604. 0xfffffff0);
  605. } else {
  606. needsLookup(sm, msg, false);
  607. return NULL;
  608. }
  609. }
  610. if (header->version_be) { sess->pub.version = Endian_bigEndianToHost32(header->version_be); }
  611. if (!sess->pub.version) {
  612. needsLookup(sm, msg, false);
  613. return NULL;
  614. }
  615. if (header->sh.label_be) {
  616. // fallthrough
  617. } else if (sess->pub.sendSwitchLabel) {
  618. Bits_memset(&header->sh, 0, SwitchHeader_SIZE);
  619. header->sh.label_be = Endian_hostToBigEndian64(sess->pub.sendSwitchLabel);
  620. SwitchHeader_setVersion(&header->sh, SwitchHeader_CURRENT_VERSION);
  621. } else {
  622. needsLookup(sm, msg, false);
  623. return NULL;
  624. }
  625. // Forward secrecy, only send dht messages until the session is setup.
  626. CryptoAuth_resetIfTimeout(sess->pub.caSession);
  627. if (DataHeader_getContentType(dataHeader) != ContentType_CJDHT &&
  628. CryptoAuth_getState(sess->pub.caSession) < CryptoAuth_State_RECEIVED_KEY)
  629. {
  630. needsLookup(sm, msg, true);
  631. return NULL;
  632. }
  633. return readyToSend(msg, sm, sess);
  634. }
  635. static Iface_DEFUN sessions(struct SessionManager_pvt* sm,
  636. uint32_t sourcePf,
  637. struct Allocator* tempAlloc)
  638. {
  639. for (int i = 0; i < (int)sm->ifaceMap.count; i++) {
  640. struct SessionManager_Session_pvt* sess = sm->ifaceMap.values[i];
  641. sendSession(sess, sess->pub.sendSwitchLabel, sourcePf, PFChan_Core_SESSION);
  642. }
  643. return NULL;
  644. }
  645. static Iface_DEFUN incomingFromEventIf(struct Message* msg, struct Iface* iface)
  646. {
  647. struct SessionManager_pvt* sm = Identity_containerOf(iface, struct SessionManager_pvt, eventIf);
  648. enum PFChan_Pathfinder ev = Message_pop32(msg, NULL);
  649. uint32_t sourcePf = Message_pop32(msg, NULL);
  650. if (ev == PFChan_Pathfinder_SESSIONS) {
  651. Assert_true(!msg->length);
  652. return sessions(sm, sourcePf, msg->alloc);
  653. }
  654. Assert_true(ev == PFChan_Pathfinder_NODE);
  655. struct PFChan_Node node;
  656. Message_pop(msg, &node, PFChan_Node_SIZE, NULL);
  657. Assert_true(!msg->length);
  658. int index = Map_BufferedMessages_indexForKey((struct Ip6*)node.ip6, &sm->bufMap);
  659. struct SessionManager_Session_pvt* sess = sessionForIp6(node.ip6, sm);
  660. if (!sess) {
  661. // Node we don't care about.
  662. if (index == -1) { return NULL; }
  663. // Broken path to a node we don't have a session for...
  664. if (node.metric_be == 0xffffffff) { return NULL; }
  665. }
  666. sess = getSession(sm,
  667. node.ip6,
  668. node.publicKey,
  669. Endian_bigEndianToHost32(node.version_be),
  670. Endian_bigEndianToHost64(node.path_be),
  671. Endian_bigEndianToHost32(node.metric_be));
  672. // Send what's on the buffer...
  673. if (index > -1 && CryptoAuth_getState(sess->pub.caSession) >= CryptoAuth_State_RECEIVED_KEY) {
  674. struct BufferedMessage* bm = sm->bufMap.values[index];
  675. Iface_CALL(readyToSend, bm->msg, sm, sess);
  676. Map_BufferedMessages_remove(index, &sm->bufMap);
  677. Allocator_free(bm->alloc);
  678. } else if (CryptoAuth_getState(sess->pub.caSession) < CryptoAuth_State_RECEIVED_KEY) {
  679. unsetupSession(sm, sess);
  680. }
  681. return NULL;
  682. }
  683. struct SessionManager* SessionManager_new(struct Allocator* allocator,
  684. struct EventBase* eventBase,
  685. struct CryptoAuth* cryptoAuth,
  686. struct Random* rand,
  687. struct Log* log,
  688. struct EventEmitter* ee)
  689. {
  690. struct Allocator* alloc = Allocator_child(allocator);
  691. struct SessionManager_pvt* sm = Allocator_calloc(alloc, sizeof(struct SessionManager_pvt), 1);
  692. sm->alloc = alloc;
  693. sm->pub.switchIf.send = incomingFromSwitchIf;
  694. sm->pub.insideIf.send = incomingFromInsideIf;
  695. sm->bufMap.allocator = alloc;
  696. sm->ifaceMap.allocator = alloc;
  697. sm->log = log;
  698. sm->cryptoAuth = cryptoAuth;
  699. sm->eventBase = eventBase;
  700. sm->pub.sessionTimeoutMilliseconds = SessionManager_SESSION_TIMEOUT_MILLISECONDS_DEFAULT;
  701. sm->pub.maxBufferedMessages = SessionManager_MAX_BUFFERED_MESSAGES_DEFAULT;
  702. sm->pub.sessionSearchAfterMilliseconds =
  703. SessionManager_SESSION_SEARCH_AFTER_MILLISECONDS_DEFAULT;
  704. sm->eventIf.send = incomingFromEventIf;
  705. EventEmitter_regCore(ee, &sm->eventIf, PFChan_Pathfinder_NODE);
  706. EventEmitter_regCore(ee, &sm->eventIf, PFChan_Pathfinder_SESSIONS);
  707. sm->firstHandle =
  708. (Random_uint32(rand) % (MAX_FIRST_HANDLE - MIN_FIRST_HANDLE)) + MIN_FIRST_HANDLE;
  709. Timeout_setInterval(periodically, sm, 10000, eventBase, alloc);
  710. Identity_set(sm);
  711. return &sm->pub;
  712. }