AdminClient.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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 "client/AdminClient.h"
  16. #include "benc/serialization/standard/BencMessageReader.h"
  17. #include "benc/serialization/standard/BencMessageWriter.h"
  18. #include "benc/serialization/cloner/Cloner.h"
  19. #include "exception/Except.h"
  20. #include "util/Bits.h"
  21. #include "util/Endian.h"
  22. #include "util/Hex.h"
  23. #include "util/events/Timeout.h"
  24. #include "util/Identity.h"
  25. #include "wire/Message.h"
  26. #include <sodium/crypto_hash_sha256.h>
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. struct Request;
  30. typedef void (* AdminClient_RespHandler)(struct Request* req);
  31. struct Request
  32. {
  33. struct AdminClient_Result res;
  34. struct AdminClient_Promise* promise;
  35. AdminClient_RespHandler callback;
  36. struct Context* ctx;
  37. struct Allocator* alloc;
  38. /** Need a special allocator for the timeout so it can be axed before the request is complete */
  39. struct Allocator* timeoutAlloc;
  40. struct Timeout* timeout;
  41. Dict* requestMessage;
  42. /** the handle in the ctx->outstandingRequests map */
  43. uint32_t handle;
  44. Identity
  45. };
  46. #define Map_NAME OfRequestByHandle
  47. #define Map_ENABLE_HANDLES
  48. #define Map_VALUE_TYPE struct Request*
  49. #include "util/Map.h"
  50. struct Context
  51. {
  52. struct AdminClient pub;
  53. struct EventBase* eventBase;
  54. struct Iface addrIface;
  55. struct Sockaddr* targetAddr;
  56. struct Log* logger;
  57. String* password;
  58. struct Map_OfRequestByHandle outstandingRequests;
  59. struct Allocator* alloc;
  60. Identity
  61. };
  62. static int calculateAuth(Dict* message,
  63. String* password,
  64. String* cookieStr,
  65. struct Allocator* alloc)
  66. {
  67. // Calculate the hash of the password.
  68. String* hashHex = String_newBinary(NULL, 64, alloc);
  69. uint8_t passAndCookie[64];
  70. uint32_t cookie = (cookieStr != NULL) ? strtoll(cookieStr->bytes, NULL, 10) : 0;
  71. snprintf((char*) passAndCookie, 64, "%s%u", password->bytes, cookie);
  72. uint8_t hash[32];
  73. crypto_hash_sha256(hash, passAndCookie, CString_strlen((char*) passAndCookie));
  74. Hex_encode((uint8_t*)hashHex->bytes, 64, hash, 32);
  75. Dict_putString(message, String_new("hash", alloc), hashHex, alloc);
  76. Dict_putString(message, String_new("cookie", alloc), cookieStr, alloc);
  77. // serialize the message with the password hash
  78. struct Message* msg = Message_new(0, AdminClient_MAX_MESSAGE_SIZE, alloc);
  79. Er_assert(BencMessageWriter_write(message, msg));
  80. // calculate the hash of the message with the password hash
  81. crypto_hash_sha256(hash, msg->bytes, msg->length);
  82. // swap the hash of the message with the password hash into the location
  83. // where the password hash was.
  84. Hex_encode((uint8_t*)hashHex->bytes, 64, hash, 32);
  85. return 0;
  86. }
  87. static void done(struct Request* req, enum AdminClient_Error err)
  88. {
  89. req->res.err = err;
  90. req->callback(req);
  91. Allocator_free(req->timeoutAlloc);
  92. }
  93. static void timeout(void* vreq)
  94. {
  95. done((struct Request*) vreq, AdminClient_Error_TIMEOUT);
  96. }
  97. static Iface_DEFUN receiveMessage(struct Message* msg, struct Iface* addrIface)
  98. {
  99. struct Context* ctx = Identity_containerOf(addrIface, struct Context, addrIface);
  100. struct Sockaddr_storage source;
  101. Er_assert(Message_epop(msg, &source, ctx->targetAddr->addrLen));
  102. if (Bits_memcmp(&source, ctx->targetAddr, ctx->targetAddr->addrLen)) {
  103. Log_info(ctx->logger, "Got spurious message from [%s], expecting messages from [%s]",
  104. Sockaddr_print(&source.addr, msg->alloc),
  105. Sockaddr_print(ctx->targetAddr, msg->alloc));
  106. // The UDP interface can't make use of an error but we'll inform anyway
  107. return Error(INVALID);
  108. }
  109. // we don't yet know with which message this data belongs,
  110. // the message alloc lives the length of the message reception.
  111. struct Allocator* alloc = Allocator_child(msg->alloc);
  112. int origLen = msg->length;
  113. Dict* d = NULL;
  114. const char* err = BencMessageReader_readNoExcept(msg, alloc, &d);
  115. if (err) { return Error(INVALID); }
  116. Er_assert(Message_eshift(msg, origLen));
  117. String* txid = Dict_getStringC(d, "txid");
  118. if (!txid || txid->len != 8) { return Error(INVALID); }
  119. // look up the result
  120. uint32_t handle = ~0u;
  121. Hex_decode((uint8_t*)&handle, 4, txid->bytes, 8);
  122. int idx = Map_OfRequestByHandle_indexForHandle(handle, &ctx->outstandingRequests);
  123. if (idx < 0) { return Error(INVALID); }
  124. struct Request* req = ctx->outstandingRequests.values[idx];
  125. // now this data will outlive the life of the message.
  126. Allocator_adopt(req->promise->alloc, alloc);
  127. req->res.responseDict = d;
  128. int len =
  129. (msg->length > AdminClient_MAX_MESSAGE_SIZE) ? AdminClient_MAX_MESSAGE_SIZE : msg->length;
  130. Bits_memset(req->res.messageBytes, 0, AdminClient_MAX_MESSAGE_SIZE);
  131. Bits_memcpy(req->res.messageBytes, msg->bytes, len);
  132. done(req, AdminClient_Error_NONE);
  133. return Error(NONE);
  134. }
  135. static int requestOnFree(struct Allocator_OnFreeJob* job)
  136. {
  137. struct Request* req = Identity_check((struct Request*) job->userData);
  138. int idx = Map_OfRequestByHandle_indexForHandle(req->handle, &req->ctx->outstandingRequests);
  139. if (idx > -1) {
  140. Map_OfRequestByHandle_remove(idx, &req->ctx->outstandingRequests);
  141. }
  142. return 0;
  143. }
  144. static struct Request* sendRaw(Dict* messageDict,
  145. struct AdminClient_Promise* promise,
  146. struct Context* ctx,
  147. String* cookie,
  148. AdminClient_RespHandler callback)
  149. {
  150. struct Allocator* reqAlloc = Allocator_child(promise->alloc);
  151. struct Request* req = Allocator_clone(reqAlloc, (&(struct Request) {
  152. .alloc = reqAlloc,
  153. .ctx = ctx,
  154. .promise = promise
  155. }));
  156. Identity_set(req);
  157. int idx = Map_OfRequestByHandle_put(&req, &ctx->outstandingRequests);
  158. req->handle = ctx->outstandingRequests.handles[idx];
  159. String* id = String_newBinary(NULL, 8, req->alloc);
  160. Hex_encode(id->bytes, 8, (int8_t*) &req->handle, 4);
  161. Dict_putStringC(messageDict, "txid", id, req->alloc);
  162. if (cookie) {
  163. Assert_true(!calculateAuth(messageDict, ctx->password, cookie, req->alloc));
  164. }
  165. struct Allocator* child = Allocator_child(req->alloc);
  166. struct Message* msg = Message_new(0, AdminClient_MAX_MESSAGE_SIZE + 256, child);
  167. Er_assert(BencMessageWriter_write(messageDict, msg));
  168. req->timeoutAlloc = Allocator_child(req->alloc);
  169. req->timeout = Timeout_setTimeout(timeout,
  170. req,
  171. ctx->pub.millisecondsToWait,
  172. ctx->eventBase,
  173. req->timeoutAlloc);
  174. Allocator_onFree(req->timeoutAlloc, requestOnFree, req);
  175. req->callback = callback;
  176. Er_assert(Message_epush(msg, ctx->targetAddr, ctx->targetAddr->addrLen));
  177. Iface_send(&ctx->addrIface, msg);
  178. Allocator_free(child);
  179. return req;
  180. }
  181. static void requestCallback(struct Request* req)
  182. {
  183. if (req->promise->callback) {
  184. req->promise->callback(req->promise, &req->res);
  185. }
  186. Allocator_free(req->promise->alloc);
  187. }
  188. static void cookieCallback(struct Request* req)
  189. {
  190. if (req->res.err) {
  191. requestCallback(req);
  192. return;
  193. }
  194. String* cookie = Dict_getStringC(req->res.responseDict, "cookie");
  195. if (!cookie) {
  196. req->res.err = AdminClient_Error_NO_COOKIE;
  197. requestCallback(req);
  198. return;
  199. }
  200. Dict* message = req->requestMessage;
  201. sendRaw(message, req->promise, req->ctx, cookie, requestCallback);
  202. Allocator_free(req->alloc);
  203. }
  204. static struct AdminClient_Promise* doCall(Dict* message,
  205. struct Context* ctx,
  206. struct Allocator* alloc)
  207. {
  208. struct Allocator* promiseAlloc = Allocator_child(alloc);
  209. struct AdminClient_Promise* promise =
  210. Allocator_calloc(promiseAlloc, sizeof(struct AdminClient_Promise), 1);
  211. promise->alloc = promiseAlloc;
  212. Dict gc = Dict_CONST(String_CONST("q"), String_OBJ(String_CONST("cookie")), NULL);
  213. struct Request* req = sendRaw(&gc, promise, ctx, NULL, cookieCallback);
  214. req->requestMessage = Cloner_cloneDict(message, promiseAlloc);
  215. return promise;
  216. }
  217. struct AdminClient_Promise* AdminClient_rpcCall(String* function,
  218. Dict* args,
  219. struct AdminClient* client,
  220. struct Allocator* alloc)
  221. {
  222. struct Context* ctx = Identity_check((struct Context*) client);
  223. Dict a = (args) ? *args : NULL;
  224. Dict message = Dict_CONST(
  225. String_CONST("q"), String_OBJ(String_CONST("auth")), Dict_CONST(
  226. String_CONST("aq"), String_OBJ(function), Dict_CONST(
  227. String_CONST("args"), Dict_OBJ(&a), NULL
  228. )));
  229. return doCall(&message, ctx, alloc);
  230. }
  231. char* AdminClient_errorString(enum AdminClient_Error err)
  232. {
  233. switch (err) {
  234. case AdminClient_Error_NONE:
  235. return "Success";
  236. case AdminClient_Error_OVERLONG_RESPONSE:
  237. return "Overlong resonse message";
  238. case AdminClient_Error_ERROR_READING_FROM_SOCKET:
  239. return "Error reading from socket, check errno.";
  240. case AdminClient_Error_SOCKET_NOT_READY:
  241. return "Socket not ready for reading";
  242. case AdminClient_Error_DESERIALIZATION_FAILED:
  243. return "Failed to deserialize response";
  244. case AdminClient_Error_SERIALIZATION_FAILED:
  245. return "Failed to serialize request";
  246. case AdminClient_Error_TIMEOUT:
  247. return "Timed out waiting for a response";
  248. case AdminClient_Error_NO_COOKIE:
  249. return "Cookie request returned with no cookie";
  250. default:
  251. return "Internal error";
  252. };
  253. }
  254. struct AdminClient* AdminClient_new(struct AddrIface* ai,
  255. struct Sockaddr* connectToAddress,
  256. String* adminPassword,
  257. struct EventBase* eventBase,
  258. struct Log* logger,
  259. struct Allocator* alloc)
  260. {
  261. struct Context* context = Allocator_clone(alloc, (&(struct Context) {
  262. .eventBase = eventBase,
  263. .logger = logger,
  264. .password = adminPassword,
  265. .pub = {
  266. .millisecondsToWait = 5000,
  267. },
  268. .outstandingRequests = {
  269. .allocator = alloc
  270. },
  271. .alloc = alloc
  272. }));
  273. context->addrIface.send = receiveMessage;
  274. Identity_set(context);
  275. context->targetAddr = Sockaddr_clone(connectToAddress, alloc);
  276. if (Sockaddr_getFamily(context->targetAddr) == Sockaddr_AF_INET) {
  277. uint8_t* addrBytes;
  278. int len = Sockaddr_getAddress(context->targetAddr, &addrBytes);
  279. if (Bits_isZero(addrBytes, len)) {
  280. // 127.0.0.1
  281. uint32_t loopback = Endian_hostToBigEndian32(0x7f000001);
  282. Bits_memcpy(addrBytes, &loopback, 4);
  283. }
  284. }
  285. Log_debug(logger, "Connecting to [%s]", Sockaddr_print(context->targetAddr, alloc));
  286. Iface_plumb(&ai->iface, &context->addrIface);
  287. return &context->pub;
  288. }