MsgCore.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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 "benc/Dict.h"
  16. #include "crypto/AddressCalc.h"
  17. #include "memory/Allocator.h"
  18. #include "dht/Address.h"
  19. #include "dht/CJDHTConstants.h"
  20. #include "util/Pinger.h"
  21. #include "subnode/MsgCore.h"
  22. #include "benc/serialization/standard/BencMessageReader.h"
  23. #include "benc/serialization/standard/BencMessageWriter.h"
  24. #include "switch/EncodingScheme.h"
  25. #include "util/Escape.h"
  26. #include "util/Defined.h"
  27. #include "wire/Message.h"
  28. #include "wire/DataHeader.h"
  29. #include "wire/RouteHeader.h"
  30. #define DEFAULT_TIMEOUT_MILLISECONDS 6000
  31. struct ReplyContext
  32. {
  33. struct Address* src;
  34. Dict* content;
  35. struct Message* msg;
  36. Identity
  37. };
  38. struct QueryHandler
  39. {
  40. struct MsgCore_Handler pub;
  41. String* queryType;
  42. struct Allocator* alloc;
  43. struct MsgCore_pvt* mcp;
  44. Identity
  45. };
  46. #define ArrayList_TYPE struct QueryHandler
  47. #define ArrayList_NAME OfQueryHandlers
  48. #include "util/ArrayList.h"
  49. struct MsgCore_pvt
  50. {
  51. struct MsgCore pub;
  52. struct ArrayList_OfQueryHandlers* qh;
  53. struct Pinger* pinger;
  54. struct Log* log;
  55. String* schemeDefinition;
  56. struct EncodingScheme* scheme;
  57. /** Hack hack hack: This should be passed through Pinger.h but the API doesn't exist. */
  58. struct ReplyContext* currentReply;
  59. Identity
  60. };
  61. struct MsgCore_Promise_pvt
  62. {
  63. struct MsgCore_Promise pub;
  64. struct MsgCore_pvt* mcp;
  65. struct Pinger_Ping* ping;
  66. Identity
  67. };
  68. static Iface_DEFUN replyMsg(struct MsgCore_pvt* mcp,
  69. Dict* content,
  70. struct Address* src,
  71. struct Message* msg)
  72. {
  73. Log_debug(mcp->log, "Got reply from [%s]", Address_toString(src, msg->alloc)->bytes);
  74. String* txid = Dict_getStringC(content, "txid");
  75. if (!txid) {
  76. Log_debug(mcp->log, "DROP Message with no txid");
  77. return NULL;
  78. }
  79. struct ReplyContext* rc = Allocator_calloc(msg->alloc, sizeof(struct ReplyContext), 1);
  80. rc->src = src;
  81. rc->content = content;
  82. rc->msg = msg;
  83. Identity_set(rc);
  84. Assert_true(!mcp->currentReply);
  85. mcp->currentReply = rc;
  86. // Pops out in pingerOnResponse() if the reply is indeed valid...
  87. Pinger_pongReceived(txid, mcp->pinger);
  88. mcp->currentReply = NULL;
  89. return NULL;
  90. }
  91. static void pingerOnResponse(String* data, uint32_t milliseconds, void* context)
  92. {
  93. struct MsgCore_Promise_pvt* pp = Identity_check((struct MsgCore_Promise_pvt*) context);
  94. struct MsgCore_pvt* mcp = Identity_check(pp->mcp);
  95. struct ReplyContext* rc = NULL;
  96. if (mcp->currentReply) {
  97. rc = Identity_check(mcp->currentReply);
  98. }
  99. pp->pub.lag = milliseconds;
  100. if (pp->pub.cb) {
  101. pp->pub.cb((rc) ? rc->content : NULL,
  102. (rc) ? rc->src : NULL,
  103. &pp->pub);
  104. }
  105. }
  106. static void sendMsg(struct MsgCore_pvt* mcp,
  107. Dict* msgDict,
  108. struct Address* addr,
  109. struct Allocator* allocator)
  110. {
  111. struct Allocator* alloc = Allocator_child(allocator);
  112. // Send the encoding scheme definition
  113. Dict_putString(msgDict, CJDHTConstants_ENC_SCHEME, mcp->schemeDefinition, allocator);
  114. // And tell the asker which interface the message came from
  115. int encIdx = EncodingScheme_getFormNum(mcp->scheme, addr->path);
  116. Assert_true(encIdx != EncodingScheme_getFormNum_INVALID);
  117. Dict_putInt(msgDict, CJDHTConstants_ENC_INDEX, encIdx, allocator);
  118. // send the protocol version
  119. Dict_putInt(msgDict, CJDHTConstants_PROTOCOL, Version_CURRENT_PROTOCOL, allocator);
  120. String* q = Dict_getStringC(msgDict, "q");
  121. String* sq = Dict_getStringC(msgDict, "sq");
  122. if (q || sq) {
  123. Log_debug(mcp->log, "Send query [%s] to [%s]",
  124. ((q) ? q->bytes : sq->bytes),
  125. Address_toString(addr, alloc)->bytes);
  126. String* txid = Dict_getStringC(msgDict, "txid");
  127. Assert_true(txid);
  128. String* newTxid = String_newBinary(NULL, txid->len + 2, alloc);
  129. Bits_memcpy(&newTxid->bytes[2], txid->bytes, txid->len);
  130. // Always direct queries to the old pathfinder
  131. newTxid->bytes[0] = '0';
  132. newTxid->bytes[1] = '1';
  133. Dict_putStringC(msgDict, "txid", newTxid, alloc);
  134. }
  135. struct Message* msg = Message_new(0, 2048, alloc);
  136. Er_assert(BencMessageWriter_write(msgDict, msg));
  137. //Log_debug(mcp->log, "Sending msg [%s]", Escape_getEscaped(msg->bytes, msg->length, alloc));
  138. // Sanity check (make sure the addr was actually calculated)
  139. Assert_true(AddressCalc_validAddress(addr->ip6.bytes));
  140. struct DataHeader data;
  141. Bits_memset(&data, 0, sizeof(struct DataHeader));
  142. DataHeader_setVersion(&data, DataHeader_CURRENT_VERSION);
  143. DataHeader_setContentType(&data, ContentType_CJDHT);
  144. Er_assert(Message_epush(msg, &data, sizeof(struct DataHeader)));
  145. struct RouteHeader route;
  146. Bits_memset(&route, 0, sizeof(struct RouteHeader));
  147. Bits_memcpy(route.ip6, addr->ip6.bytes, 16);
  148. route.version_be = Endian_hostToBigEndian32(addr->protocolVersion);
  149. route.sh.label_be = Endian_hostToBigEndian64(addr->path);
  150. route.flags |= RouteHeader_flags_PATHFINDER;
  151. Bits_memcpy(route.publicKey, addr->key, 32);
  152. Er_assert(Message_epush(msg, &route, sizeof(struct RouteHeader)));
  153. Iface_send(&mcp->pub.interRouterIf, msg);
  154. }
  155. void MsgCore_sendResponse(struct MsgCore* core,
  156. Dict* msgDict,
  157. struct Address* target,
  158. struct Allocator* alloc)
  159. {
  160. struct MsgCore_pvt* mcp = Identity_check((struct MsgCore_pvt*) core);
  161. sendMsg(mcp, msgDict, target, alloc);
  162. }
  163. static void pingerSendPing(String* data, void* context)
  164. {
  165. struct MsgCore_Promise_pvt* pp = Identity_check((struct MsgCore_Promise_pvt*) context);
  166. Assert_true(pp->pub.target);
  167. Assert_true(pp->pub.msg);
  168. Dict_putStringC(pp->pub.msg, "txid", data, pp->pub.alloc);
  169. sendMsg(pp->mcp, pp->pub.msg, pp->pub.target, pp->pub.alloc);
  170. }
  171. struct MsgCore_Promise* MsgCore_createQuery(struct MsgCore* core,
  172. uint32_t timeoutMilliseconds,
  173. struct Allocator* allocator)
  174. {
  175. struct MsgCore_pvt* mcp = Identity_check((struct MsgCore_pvt*) core);
  176. if (!timeoutMilliseconds) {
  177. timeoutMilliseconds = DEFAULT_TIMEOUT_MILLISECONDS;
  178. }
  179. struct Pinger_Ping* p = Pinger_newPing(
  180. NULL, pingerOnResponse, pingerSendPing, timeoutMilliseconds, allocator, mcp->pinger);
  181. struct MsgCore_Promise_pvt* out =
  182. Allocator_calloc(p->pingAlloc, sizeof(struct MsgCore_Promise_pvt), 1);
  183. Identity_set(out);
  184. p->context = out;
  185. out->pub.alloc = p->pingAlloc;
  186. out->mcp = mcp;
  187. out->ping = p;
  188. return &out->pub;
  189. }
  190. static struct QueryHandler* getQueryHandler(struct MsgCore_pvt* mcp, String* q)
  191. {
  192. for (int i = 0; i < mcp->qh->length; i++) {
  193. struct QueryHandler* qhx = ArrayList_OfQueryHandlers_get(mcp->qh, i);
  194. Identity_check(qhx);
  195. if (String_equals(qhx->queryType, q)) {
  196. return qhx;
  197. }
  198. }
  199. return NULL;
  200. }
  201. static Iface_DEFUN queryMsg(struct MsgCore_pvt* mcp,
  202. Dict* content,
  203. struct Address* src,
  204. struct Message* msg)
  205. {
  206. String* q = Dict_getStringC(content, "q");
  207. struct QueryHandler* qh = getQueryHandler(mcp, q);
  208. if (!qh) {
  209. qh = getQueryHandler(mcp, String_CONST("pn"));
  210. }
  211. if (!qh) {
  212. Log_debug(mcp->log, "Unhandled query type [%s]", q->bytes);
  213. } else if (!qh->pub.cb) {
  214. Log_info(mcp->log, "Query handler for [%s] not setup", q->bytes);
  215. } else {
  216. qh->pub.cb(content, src, msg->alloc, &qh->pub);
  217. }
  218. return NULL;
  219. }
  220. static int qhOnFree(struct Allocator_OnFreeJob* job)
  221. {
  222. struct QueryHandler* qh = Identity_check((struct QueryHandler*) job->userData);
  223. struct MsgCore_pvt* mcp = Identity_check((struct MsgCore_pvt*) qh->mcp);
  224. for (int i = 0; i < mcp->qh->length; i++) {
  225. struct QueryHandler* qhx = ArrayList_OfQueryHandlers_get(mcp->qh, i);
  226. if (qhx == qh) {
  227. ArrayList_OfQueryHandlers_remove(mcp->qh, i);
  228. return 0;
  229. }
  230. }
  231. return 0;
  232. }
  233. struct MsgCore_Handler* MsgCore_onQuery(struct MsgCore* core,
  234. char* queryType,
  235. struct Allocator* allocator)
  236. {
  237. struct MsgCore_pvt* mcp = Identity_check((struct MsgCore_pvt*) core);
  238. struct Allocator* alloc = Allocator_child(allocator);
  239. struct QueryHandler* qh = Allocator_calloc(alloc, sizeof(struct QueryHandler), 1);
  240. qh->queryType = String_new(queryType, alloc);
  241. qh->alloc = alloc;
  242. qh->mcp = mcp;
  243. Identity_set(qh);
  244. ArrayList_OfQueryHandlers_add(mcp->qh, qh);
  245. Allocator_onFree(alloc, qhOnFree, qh);
  246. return &qh->pub;
  247. }
  248. static Iface_DEFUN incoming(struct Message* msg, struct Iface* interRouterIf)
  249. {
  250. struct MsgCore_pvt* mcp =
  251. Identity_containerOf(interRouterIf, struct MsgCore_pvt, pub.interRouterIf);
  252. struct Address addr = { .padding = 0 };
  253. struct RouteHeader* hdr = (struct RouteHeader*) msg->bytes;
  254. Er_assert(Message_eshift(msg, -(RouteHeader_SIZE + DataHeader_SIZE)));
  255. Bits_memcpy(addr.ip6.bytes, hdr->ip6, 16);
  256. Bits_memcpy(addr.key, hdr->publicKey, 32);
  257. addr.protocolVersion = Endian_bigEndianToHost32(hdr->version_be);
  258. addr.path = Endian_bigEndianToHost64(hdr->sh.label_be);
  259. Dict* content = NULL;
  260. uint8_t* msgBytes = msg->bytes;
  261. int length = msg->length;
  262. //Log_debug(mcp->log, "Receive msg [%s] from [%s]",
  263. // Escape_getEscaped(msg->bytes, msg->length, msg->alloc),
  264. // Address_toString(&addr, msg->alloc)->bytes);
  265. //
  266. BencMessageReader_readNoExcept(msg, msg->alloc, &content);
  267. if (!content) {
  268. char* esc = Escape_getEscaped(msgBytes, length, msg->alloc);
  269. Log_debug(mcp->log, "DROP Malformed message [%s]", esc);
  270. return NULL;
  271. }
  272. int64_t* verP = Dict_getIntC(content, "p");
  273. if (!verP) {
  274. Log_debug(mcp->log, "DROP Message without version");
  275. return NULL;
  276. }
  277. addr.protocolVersion = *verP;
  278. if (!addr.protocolVersion) {
  279. Log_debug(mcp->log, "DROP Message with zero version");
  280. return NULL;
  281. }
  282. String* q = Dict_getStringC(content, "q");
  283. String* txid = Dict_getStringC(content, "txid");
  284. if (!txid || !txid->len) {
  285. Log_debug(mcp->log, "Message with no txid [%s]", q ? (q->bytes) : "(no query)");
  286. return NULL;
  287. }
  288. if (q) {
  289. if (Defined(SUBNODE)) {
  290. return queryMsg(mcp, content, &addr, msg);
  291. } else {
  292. // Let the old pathfinder handle every query if it is present
  293. return NULL;
  294. }
  295. } else if (txid->len >= 2 && txid->bytes[0] == '0' && txid->bytes[1] == '1') {
  296. txid->bytes = &txid->bytes[2];
  297. txid->len -= 2;
  298. return replyMsg(mcp, content, &addr, msg);
  299. }
  300. return NULL;
  301. }
  302. struct MsgCore* MsgCore_new(struct EventBase* base,
  303. struct Random* rand,
  304. struct Allocator* allocator,
  305. struct Log* log,
  306. struct EncodingScheme* scheme)
  307. {
  308. struct Allocator* alloc = Allocator_child(allocator);
  309. struct MsgCore_pvt* mcp = Allocator_calloc(alloc, sizeof(struct MsgCore_pvt), 1);
  310. Identity_set(mcp);
  311. mcp->pub.interRouterIf.send = incoming;
  312. mcp->qh = ArrayList_OfQueryHandlers_new(alloc);
  313. mcp->pinger = Pinger_new(base, rand, log, alloc);
  314. mcp->log = log;
  315. mcp->scheme = scheme;
  316. mcp->schemeDefinition = EncodingScheme_serialize(scheme, alloc);
  317. return &mcp->pub;
  318. }