AdminClient.c 12 KB

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