MsgCore.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. if (pp->pub.cb) {
  100. pp->pub.cb((rc) ? rc->content : NULL,
  101. (rc) ? rc->src : NULL,
  102. &pp->pub);
  103. }
  104. }
  105. static void sendMsg(struct MsgCore_pvt* mcp,
  106. Dict* msgDict,
  107. struct Address* addr,
  108. struct Allocator* allocator)
  109. {
  110. struct Allocator* alloc = Allocator_child(allocator);
  111. // Send the encoding scheme definition
  112. Dict_putString(msgDict, CJDHTConstants_ENC_SCHEME, mcp->schemeDefinition, allocator);
  113. // And tell the asker which interface the message came from
  114. int encIdx = EncodingScheme_getFormNum(mcp->scheme, addr->path);
  115. Assert_true(encIdx != EncodingScheme_getFormNum_INVALID);
  116. Dict_putInt(msgDict, CJDHTConstants_ENC_INDEX, encIdx, allocator);
  117. // send the protocol version
  118. Dict_putInt(msgDict, CJDHTConstants_PROTOCOL, Version_CURRENT_PROTOCOL, allocator);
  119. if (!Defined(SUBNODE)) {
  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 + 1, alloc);
  129. Bits_memcpy(&newTxid->bytes[1], txid->bytes, txid->len);
  130. newTxid->bytes[0] = '1';
  131. if (String_equals(q, String_CONST("gp"))) {
  132. // direct all GP requests to the old system because the new one is broken :(
  133. newTxid->bytes[0] = '0';
  134. }
  135. Dict_putStringC(msgDict, "txid", newTxid, alloc);
  136. }
  137. }
  138. struct Message* msg = Message_new(0, 2048, alloc);
  139. BencMessageWriter_write(msgDict, msg, NULL);
  140. //Log_debug(mcp->log, "Sending msg [%s]", Escape_getEscaped(msg->bytes, msg->length, alloc));
  141. // Sanity check (make sure the addr was actually calculated)
  142. Assert_true(AddressCalc_validAddress(addr->ip6.bytes));
  143. struct DataHeader data;
  144. Bits_memset(&data, 0, sizeof(struct DataHeader));
  145. DataHeader_setVersion(&data, DataHeader_CURRENT_VERSION);
  146. DataHeader_setContentType(&data, ContentType_CJDHT);
  147. Message_push(msg, &data, sizeof(struct DataHeader), NULL);
  148. struct RouteHeader route;
  149. Bits_memset(&route, 0, sizeof(struct RouteHeader));
  150. Bits_memcpy(route.ip6, addr->ip6.bytes, 16);
  151. route.version_be = Endian_hostToBigEndian32(addr->protocolVersion);
  152. route.sh.label_be = Endian_hostToBigEndian64(addr->path);
  153. Bits_memcpy(route.publicKey, addr->key, 32);
  154. Message_push(msg, &route, sizeof(struct RouteHeader), NULL);
  155. Iface_send(&mcp->pub.interRouterIf, msg);
  156. }
  157. void MsgCore_sendResponse(struct MsgCore* core,
  158. Dict* msgDict,
  159. struct Address* target,
  160. struct Allocator* alloc)
  161. {
  162. struct MsgCore_pvt* mcp = Identity_check((struct MsgCore_pvt*) core);
  163. sendMsg(mcp, msgDict, target, alloc);
  164. }
  165. static void pingerSendPing(String* data, void* context)
  166. {
  167. struct MsgCore_Promise_pvt* pp = Identity_check((struct MsgCore_Promise_pvt*) context);
  168. Assert_true(pp->pub.target);
  169. Assert_true(pp->pub.msg);
  170. Dict_putStringC(pp->pub.msg, "txid", data, pp->pub.alloc);
  171. sendMsg(pp->mcp, pp->pub.msg, pp->pub.target, pp->pub.alloc);
  172. }
  173. struct MsgCore_Promise* MsgCore_createQuery(struct MsgCore* core,
  174. uint32_t timeoutMilliseconds,
  175. struct Allocator* allocator)
  176. {
  177. struct MsgCore_pvt* mcp = Identity_check((struct MsgCore_pvt*) core);
  178. if (!timeoutMilliseconds) {
  179. timeoutMilliseconds = DEFAULT_TIMEOUT_MILLISECONDS;
  180. }
  181. struct Pinger_Ping* p = Pinger_newPing(
  182. NULL, pingerOnResponse, pingerSendPing, timeoutMilliseconds, allocator, mcp->pinger);
  183. struct MsgCore_Promise_pvt* out =
  184. Allocator_calloc(p->pingAlloc, sizeof(struct MsgCore_Promise_pvt), 1);
  185. Identity_set(out);
  186. p->context = out;
  187. out->pub.alloc = p->pingAlloc;
  188. out->mcp = mcp;
  189. out->ping = p;
  190. return &out->pub;
  191. }
  192. static Iface_DEFUN queryMsg(struct MsgCore_pvt* mcp,
  193. Dict* content,
  194. struct Address* src,
  195. struct Message* msg)
  196. {
  197. String* q = Dict_getStringC(content, "q");
  198. struct QueryHandler* qh = NULL;
  199. for (int i = 0; i < mcp->qh->length; i++) {
  200. struct QueryHandler* qhx = ArrayList_OfQueryHandlers_get(mcp->qh, i);
  201. Identity_check(qhx);
  202. if (String_equals(qhx->queryType, q)) {
  203. qh = qhx;
  204. break;
  205. }
  206. }
  207. if (!qh) {
  208. Log_debug(mcp->log, "Unhandled query type [%s]", q->bytes);
  209. return NULL;
  210. }
  211. if (!qh->pub.cb) {
  212. Log_info(mcp->log, "Query handler for [%s] not setup", q->bytes);
  213. return NULL;
  214. }
  215. qh->pub.cb(content, src, msg->alloc, &qh->pub);
  216. return NULL;
  217. }
  218. static int qhOnFree(struct Allocator_OnFreeJob* job)
  219. {
  220. struct QueryHandler* qh = Identity_check((struct QueryHandler*) job->userData);
  221. struct MsgCore_pvt* mcp = Identity_check((struct MsgCore_pvt*) qh->mcp);
  222. for (int i = 0; i < mcp->qh->length; i++) {
  223. struct QueryHandler* qhx = ArrayList_OfQueryHandlers_get(mcp->qh, i);
  224. if (qhx == qh) {
  225. ArrayList_OfQueryHandlers_remove(mcp->qh, i);
  226. return 0;
  227. }
  228. }
  229. return 0;
  230. }
  231. struct MsgCore_Handler* MsgCore_onQuery(struct MsgCore* core,
  232. char* queryType,
  233. struct Allocator* allocator)
  234. {
  235. struct MsgCore_pvt* mcp = Identity_check((struct MsgCore_pvt*) core);
  236. struct Allocator* alloc = Allocator_child(allocator);
  237. struct QueryHandler* qh = Allocator_calloc(alloc, sizeof(struct QueryHandler), 1);
  238. qh->queryType = String_new(queryType, alloc);
  239. qh->alloc = alloc;
  240. qh->mcp = mcp;
  241. Identity_set(qh);
  242. ArrayList_OfQueryHandlers_add(mcp->qh, qh);
  243. Allocator_onFree(alloc, qhOnFree, qh);
  244. return &qh->pub;
  245. }
  246. static Iface_DEFUN incoming(struct Message* msg, struct Iface* interRouterIf)
  247. {
  248. struct MsgCore_pvt* mcp =
  249. Identity_containerOf(interRouterIf, struct MsgCore_pvt, pub.interRouterIf);
  250. struct Address addr = { .padding = 0 };
  251. struct RouteHeader* hdr = (struct RouteHeader*) msg->bytes;
  252. Message_shift(msg, -(RouteHeader_SIZE + DataHeader_SIZE), NULL);
  253. Bits_memcpy(addr.ip6.bytes, hdr->ip6, 16);
  254. Bits_memcpy(addr.key, hdr->publicKey, 32);
  255. addr.protocolVersion = Endian_bigEndianToHost32(hdr->version_be);
  256. addr.path = Endian_bigEndianToHost64(hdr->sh.label_be);
  257. Dict* content = NULL;
  258. uint8_t* msgBytes = msg->bytes;
  259. int length = msg->length;
  260. //Log_debug(mcp->log, "Receive msg [%s] from [%s]",
  261. // Escape_getEscaped(msg->bytes, msg->length, msg->alloc),
  262. // Address_toString(&addr, msg->alloc)->bytes);
  263. //
  264. BencMessageReader_readNoExcept(msg, msg->alloc, &content);
  265. if (!content) {
  266. char* esc = Escape_getEscaped(msgBytes, length, msg->alloc);
  267. Log_debug(mcp->log, "DROP Malformed message [%s]", esc);
  268. return NULL;
  269. }
  270. int64_t* verP = Dict_getIntC(content, "p");
  271. if (!verP) {
  272. Log_debug(mcp->log, "DROP Message without version");
  273. return NULL;
  274. }
  275. addr.protocolVersion = *verP;
  276. String* q = Dict_getStringC(content, "q");
  277. if (!Defined(SUBNODE)) {
  278. String* txid = Dict_getStringC(content, "txid");
  279. Assert_true(txid);
  280. if (q) {
  281. if (txid->bytes[0] != '1') {
  282. Log_debug(mcp->log, "DROP query which begins with 0 and is for old pathfinder");
  283. return NULL;
  284. }
  285. } else {
  286. String* newTxid = String_newBinary(NULL, txid->len - 1, msg->alloc);
  287. Bits_memcpy(newTxid->bytes, &txid->bytes[1], txid->len - 1);
  288. Dict_putStringC(content, "txid", newTxid, msg->alloc);
  289. txid = newTxid;
  290. }
  291. }
  292. if (q) {
  293. return queryMsg(mcp, content, &addr, msg);
  294. } else {
  295. return replyMsg(mcp, content, &addr, msg);
  296. }
  297. }
  298. struct MsgCore* MsgCore_new(struct EventBase* base,
  299. struct Random* rand,
  300. struct Allocator* allocator,
  301. struct Log* log,
  302. struct EncodingScheme* scheme)
  303. {
  304. struct Allocator* alloc = Allocator_child(allocator);
  305. struct MsgCore_pvt* mcp = Allocator_calloc(alloc, sizeof(struct MsgCore_pvt), 1);
  306. Identity_set(mcp);
  307. mcp->pub.interRouterIf.send = incoming;
  308. mcp->qh = ArrayList_OfQueryHandlers_new(alloc);
  309. mcp->pinger = Pinger_new(base, rand, log, alloc);
  310. mcp->log = log;
  311. mcp->scheme = scheme;
  312. mcp->schemeDefinition = EncodingScheme_serialize(scheme, alloc);
  313. return &mcp->pub;
  314. }