AdminClient.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 <http://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 <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. BencMessageWriter_write(message, msg, NULL);
  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. Message_pop(msg, &source, ctx->targetAddr->addrLen, NULL);
  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. return NULL;
  107. }
  108. // we don't yet know with which message this data belongs,
  109. // the message alloc lives the length of the message reception.
  110. struct Allocator* alloc = Allocator_child(msg->alloc);
  111. int origLen = msg->length;
  112. Dict* d = NULL;
  113. char* err = BencMessageReader_readNoExcept(msg, alloc, &d);
  114. if (err) { return NULL; }
  115. Message_shift(msg, origLen, NULL);
  116. String* txid = Dict_getString(d, String_CONST("txid"));
  117. if (!txid || txid->len != 8) { return NULL; }
  118. // look up the result
  119. uint32_t handle = ~0u;
  120. Hex_decode((uint8_t*)&handle, 4, txid->bytes, 8);
  121. int idx = Map_OfRequestByHandle_indexForHandle(handle, &ctx->outstandingRequests);
  122. if (idx < 0) { return NULL; }
  123. struct Request* req = ctx->outstandingRequests.values[idx];
  124. // now this data will outlive the life of the message.
  125. Allocator_adopt(req->promise->alloc, alloc);
  126. req->res.responseDict = d;
  127. int len =
  128. (msg->length > AdminClient_MAX_MESSAGE_SIZE) ? AdminClient_MAX_MESSAGE_SIZE : msg->length;
  129. Bits_memset(req->res.messageBytes, 0, AdminClient_MAX_MESSAGE_SIZE);
  130. Bits_memcpy(req->res.messageBytes, msg->bytes, len);
  131. done(req, AdminClient_Error_NONE);
  132. return NULL;
  133. }
  134. static int requestOnFree(struct Allocator_OnFreeJob* job)
  135. {
  136. struct Request* req = Identity_check((struct Request*) job->userData);
  137. int idx = Map_OfRequestByHandle_indexForHandle(req->handle, &req->ctx->outstandingRequests);
  138. if (idx > -1) {
  139. Map_OfRequestByHandle_remove(idx, &req->ctx->outstandingRequests);
  140. }
  141. return 0;
  142. }
  143. static struct Request* sendRaw(Dict* messageDict,
  144. struct AdminClient_Promise* promise,
  145. struct Context* ctx,
  146. String* cookie,
  147. AdminClient_RespHandler callback)
  148. {
  149. struct Allocator* reqAlloc = Allocator_child(promise->alloc);
  150. struct Request* req = Allocator_clone(reqAlloc, (&(struct Request) {
  151. .alloc = reqAlloc,
  152. .ctx = ctx,
  153. .promise = promise
  154. }));
  155. Identity_set(req);
  156. int idx = Map_OfRequestByHandle_put(&req, &ctx->outstandingRequests);
  157. req->handle = ctx->outstandingRequests.handles[idx];
  158. String* id = String_newBinary(NULL, 8, req->alloc);
  159. Hex_encode(id->bytes, 8, (int8_t*) &req->handle, 4);
  160. Dict_putString(messageDict, String_CONST("txid"), id, req->alloc);
  161. if (cookie) {
  162. Assert_true(!calculateAuth(messageDict, ctx->password, cookie, req->alloc));
  163. }
  164. struct Allocator* child = Allocator_child(req->alloc);
  165. struct Message* msg = Message_new(0, AdminClient_MAX_MESSAGE_SIZE + 256, child);
  166. BencMessageWriter_write(messageDict, msg, NULL);
  167. req->timeoutAlloc = Allocator_child(req->alloc);
  168. req->timeout = Timeout_setTimeout(timeout,
  169. req,
  170. ctx->pub.millisecondsToWait,
  171. ctx->eventBase,
  172. req->timeoutAlloc);
  173. Allocator_onFree(req->timeoutAlloc, requestOnFree, req);
  174. req->callback = callback;
  175. Message_push(msg, ctx->targetAddr, ctx->targetAddr->addrLen, NULL);
  176. Iface_send(&ctx->addrIface, msg);
  177. Allocator_free(child);
  178. return req;
  179. }
  180. static void requestCallback(struct Request* req)
  181. {
  182. if (req->promise->callback) {
  183. req->promise->callback(req->promise, &req->res);
  184. }
  185. Allocator_free(req->promise->alloc);
  186. }
  187. static void cookieCallback(struct Request* req)
  188. {
  189. if (req->res.err) {
  190. requestCallback(req);
  191. return;
  192. }
  193. String* cookie = Dict_getString(req->res.responseDict, String_CONST("cookie"));
  194. if (!cookie) {
  195. req->res.err = AdminClient_Error_NO_COOKIE;
  196. requestCallback(req);
  197. return;
  198. }
  199. Dict* message = req->requestMessage;
  200. sendRaw(message, req->promise, req->ctx, cookie, requestCallback);
  201. Allocator_free(req->alloc);
  202. }
  203. static struct AdminClient_Promise* doCall(Dict* message,
  204. struct Context* ctx,
  205. struct Allocator* alloc)
  206. {
  207. struct Allocator* promiseAlloc = Allocator_child(alloc);
  208. struct AdminClient_Promise* promise =
  209. Allocator_calloc(promiseAlloc, sizeof(struct AdminClient_Promise), 1);
  210. promise->alloc = promiseAlloc;
  211. Dict gc = Dict_CONST(String_CONST("q"), String_OBJ(String_CONST("cookie")), NULL);
  212. struct Request* req = sendRaw(&gc, promise, ctx, NULL, cookieCallback);
  213. req->requestMessage = Cloner_cloneDict(message, promiseAlloc);
  214. return promise;
  215. }
  216. struct AdminClient_Promise* AdminClient_rpcCall(String* function,
  217. Dict* args,
  218. struct AdminClient* client,
  219. struct Allocator* alloc)
  220. {
  221. struct Context* ctx = Identity_check((struct Context*) client);
  222. Dict a = (args) ? *args : NULL;
  223. Dict message = Dict_CONST(
  224. String_CONST("q"), String_OBJ(String_CONST("auth")), Dict_CONST(
  225. String_CONST("aq"), String_OBJ(function), Dict_CONST(
  226. String_CONST("args"), Dict_OBJ(&a), NULL
  227. )));
  228. return doCall(&message, ctx, alloc);
  229. }
  230. char* AdminClient_errorString(enum AdminClient_Error err)
  231. {
  232. switch (err) {
  233. case AdminClient_Error_NONE:
  234. return "Success";
  235. case AdminClient_Error_OVERLONG_RESPONSE:
  236. return "Overlong resonse message";
  237. case AdminClient_Error_ERROR_READING_FROM_SOCKET:
  238. return "Error reading from socket, check errno.";
  239. case AdminClient_Error_SOCKET_NOT_READY:
  240. return "Socket not ready for reading";
  241. case AdminClient_Error_DESERIALIZATION_FAILED:
  242. return "Failed to deserialize response";
  243. case AdminClient_Error_SERIALIZATION_FAILED:
  244. return "Failed to serialize request";
  245. case AdminClient_Error_TIMEOUT:
  246. return "Timed out waiting for a response";
  247. case AdminClient_Error_NO_COOKIE:
  248. return "Cookie request returned with no cookie";
  249. default:
  250. return "Internal error";
  251. };
  252. }
  253. struct AdminClient* AdminClient_new(struct AddrIface* ai,
  254. struct Sockaddr* connectToAddress,
  255. String* adminPassword,
  256. struct EventBase* eventBase,
  257. struct Log* logger,
  258. struct Allocator* alloc)
  259. {
  260. struct Context* context = Allocator_clone(alloc, (&(struct Context) {
  261. .eventBase = eventBase,
  262. .logger = logger,
  263. .password = adminPassword,
  264. .pub = {
  265. .millisecondsToWait = 5000,
  266. },
  267. .outstandingRequests = {
  268. .allocator = alloc
  269. },
  270. .alloc = alloc
  271. }));
  272. context->addrIface.send = receiveMessage;
  273. Identity_set(context);
  274. context->targetAddr = Sockaddr_clone(connectToAddress, alloc);
  275. if (Sockaddr_getFamily(context->targetAddr) == Sockaddr_AF_INET) {
  276. uint8_t* addrBytes;
  277. int len = Sockaddr_getAddress(context->targetAddr, &addrBytes);
  278. if (Bits_isZero(addrBytes, len)) {
  279. // 127.0.0.1
  280. uint32_t loopback = Endian_hostToBigEndian32(0x7f000001);
  281. Bits_memcpyConst(addrBytes, &loopback, 4);
  282. }
  283. }
  284. Log_debug(logger, "Connecting to [%s]", Sockaddr_print(context->targetAddr, alloc));
  285. Iface_plumb(&ai->iface, &context->addrIface);
  286. return &context->pub;
  287. }