1
0

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