1
0

AdminClient.c 12 KB

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