Admin.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  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 "admin/Admin.h"
  16. #include "benc/String.h"
  17. #include "benc/Int.h"
  18. #include "benc/Dict.h"
  19. #include "benc/serialization/standard/BencMessageWriter.h"
  20. #include "benc/serialization/standard/BencMessageReader.h"
  21. #include "exception/Err.h"
  22. #include "memory/Allocator.h"
  23. #include "rust/cjdns_sys/RTypes.h"
  24. #include "rust/cjdns_sys/Rffi.h"
  25. #include "util/Assert.h"
  26. #include "util/Bits.h"
  27. #include "util/Hex.h"
  28. #include "util/log/Log.h"
  29. #include "util/events/Time.h"
  30. #include "util/events/Timeout.h"
  31. #include "util/Identity.h"
  32. #include "util/platform/Sockaddr.h"
  33. #include "util/Defined.h"
  34. #include <sodium/crypto_hash_sha256.h>
  35. #include <sodium/crypto_verify_32.h>
  36. #include <stdlib.h>
  37. #include <stdio.h>
  38. static String* TYPE = String_CONST_SO("type");
  39. static String* REQUIRED = String_CONST_SO("required");
  40. static String* STRING = String_CONST_SO("String");
  41. static String* INTEGER = String_CONST_SO("Int");
  42. static String* DICT = String_CONST_SO("Dict");
  43. static String* LIST = String_CONST_SO("List");
  44. static String* TXID = String_CONST_SO("txid");
  45. /** Number of milliseconds before a session times out and outgoing messages are failed. */
  46. #define TIMEOUT_MILLISECONDS 30000
  47. /** map values for tracking time of last message by source address */
  48. struct MapValue
  49. {
  50. /** time when the last incoming message was received. */
  51. uint64_t timeOfLastMessage;
  52. /** used to allocate the memory for the key (Sockaddr) and value (this). */
  53. struct Allocator* allocator;
  54. };
  55. //////// generate time-of-last-message-by-address map
  56. #define Map_USE_HASH
  57. #define Map_USE_COMPARATOR
  58. #define Map_NAME LastMessageTimeByAddr
  59. #define Map_KEY_TYPE struct Sockaddr*
  60. #define Map_VALUE_TYPE struct MapValue*
  61. #include "util/Map.h"
  62. static inline uint32_t Map_LastMessageTimeByAddr_hash(struct Sockaddr** key)
  63. {
  64. return Sockaddr_hash(*key);
  65. }
  66. static inline int Map_LastMessageTimeByAddr_compare(struct Sockaddr** keyA, struct Sockaddr** keyB)
  67. {
  68. return Sockaddr_compare(*keyA, *keyB);
  69. }
  70. /////// end map
  71. struct Function
  72. {
  73. String* name;
  74. Admin_Function call;
  75. void* context;
  76. bool needsAuth;
  77. Dict* args;
  78. };
  79. struct Admin_pvt
  80. {
  81. struct Admin pub;
  82. struct Iface iface;
  83. EventBase_t* eventBase;
  84. struct Function* functions;
  85. int functionCount;
  86. struct Allocator* allocator;
  87. String* password;
  88. struct Log* logger;
  89. struct Map_LastMessageTimeByAddr map;
  90. /** non-null if we are currently in an admin request. */
  91. Message_t* currentRequest;
  92. /** non-zero if this session able to receive asynchronous messages. */
  93. int asyncEnabled;
  94. Message_t* tempSendMsg;
  95. Identity
  96. };
  97. static Err_DEFUN sendMessage(
  98. Message_t* message, struct Sockaddr* dest, struct Admin_pvt* admin)
  99. {
  100. // stack overflow when used with admin logger.
  101. //Log_keys(admin->logger, "sending message to angel [%s]", message->bytes);
  102. Err(Message_epush(message, dest, dest->addrLen));
  103. return Iface_send(&admin->iface, message);
  104. }
  105. static Err_DEFUN sendBenc(Dict* message,
  106. struct Sockaddr* dest,
  107. struct Allocator* alloc,
  108. struct Admin_pvt* admin,
  109. int fd)
  110. {
  111. Message_reset(admin->tempSendMsg);
  112. Err(BencMessageWriter_write(message, admin->tempSendMsg));
  113. Message_t* msg = Message_new(0, Message_getLength(admin->tempSendMsg) + 32, alloc);
  114. Err(Message_epush(msg, Message_bytes(admin->tempSendMsg), Message_getLength(admin->tempSendMsg)));
  115. Message_setAssociatedFd(msg, fd);
  116. return sendMessage(msg, dest, admin);
  117. }
  118. /**
  119. * If no incoming data has been sent by this address in TIMEOUT_MILLISECONDS
  120. * then Admin_sendMessage() should fail so that it doesn't endlessly send
  121. * udp packets into outer space after a logging client disconnects.
  122. */
  123. static int checkAddress(struct Admin_pvt* admin, int index, uint64_t now)
  124. {
  125. uint64_t diff = now - admin->map.values[index]->timeOfLastMessage;
  126. // check for backwards time
  127. if (diff > TIMEOUT_MILLISECONDS && diff < ((uint64_t)INT64_MAX)) {
  128. Allocator_free(admin->map.values[index]->allocator);
  129. Map_LastMessageTimeByAddr_remove(index, &admin->map);
  130. return -1;
  131. }
  132. return 0;
  133. }
  134. static void clearExpiredAddresses(void* vAdmin)
  135. {
  136. struct Admin_pvt* admin = Identity_check((struct Admin_pvt*) vAdmin);
  137. uint64_t now = Time_currentTimeMilliseconds();
  138. int count = 0;
  139. for (int i = admin->map.count - 1; i >= 0; i--) {
  140. if (checkAddress(admin, i, now)) {
  141. count++;
  142. }
  143. }
  144. Log_debug(admin->logger, "Cleared [%d] expired sessions", count);
  145. }
  146. static int sendMessage0(Dict* message, String* txid, struct Admin* adminPub, int fd)
  147. {
  148. struct Admin_pvt* admin = Identity_check((struct Admin_pvt*) adminPub);
  149. if (!admin) {
  150. return 0;
  151. }
  152. Assert_true(txid && txid->len >= sizeof(struct Sockaddr));
  153. uint16_t addrLen = 0;
  154. Bits_memcpy(&addrLen, txid->bytes, 2);
  155. Assert_true(txid->len >= addrLen);
  156. struct Allocator* alloc = NULL;
  157. if (admin->currentRequest) {
  158. alloc = Message_getAlloc(admin->currentRequest);
  159. } else {
  160. alloc = Allocator_child(admin->allocator);
  161. }
  162. struct Sockaddr* addr = Sockaddr_clone((struct Sockaddr*) txid->bytes, alloc);
  163. // if this is an async call, check if we've got any input from that client.
  164. // if the client is nresponsive then fail the call so logs don't get sent
  165. // out forever after a disconnection.
  166. if (!admin->currentRequest) {
  167. int index = Map_LastMessageTimeByAddr_indexForKey(&addr, &admin->map);
  168. uint64_t now = Time_currentTimeMilliseconds();
  169. if (index < 0 || checkAddress(admin, index, now)) {
  170. Allocator_free(alloc);
  171. return Admin_sendMessage_CHANNEL_CLOSED;
  172. }
  173. }
  174. // Bounce back the user-supplied txid.
  175. if (txid->len > addr->addrLen) {
  176. String* userTxid =
  177. String_newBinary(&txid->bytes[addr->addrLen], txid->len - addr->addrLen, alloc);
  178. Dict_putString(message, TXID, userTxid, alloc);
  179. }
  180. RTypes_Error_t* err = sendBenc(message, addr, alloc, admin, fd);
  181. if (err) {
  182. Log_warn(admin->logger, "Error sending benc: %s", Rffi_printError(err, alloc));
  183. }
  184. Dict_remove(message, TXID);
  185. if (!admin->currentRequest) {
  186. Allocator_free(alloc);
  187. }
  188. return 0;
  189. }
  190. int Admin_sendMessage(Dict* message, String* txid, struct Admin* adminPub)
  191. {
  192. return sendMessage0(message, txid, adminPub, -1);
  193. }
  194. static inline bool authValid(Dict* message, Message_t* messageBytes, struct Admin_pvt* admin)
  195. {
  196. String* cookieStr = Dict_getStringC(message, "cookie");
  197. uint32_t cookie = (cookieStr != NULL) ? strtoll(cookieStr->bytes, NULL, 10) : 0;
  198. if (!cookie) {
  199. int64_t* cookieInt = Dict_getIntC(message, "cookie");
  200. cookie = (cookieInt) ? *cookieInt : 0;
  201. }
  202. uint64_t nowSecs = Time_currentTimeSeconds();
  203. String* submittedHash = Dict_getStringC(message, "hash");
  204. if (cookie > nowSecs || cookie < nowSecs - 20 || !submittedHash || submittedHash->len != 64) {
  205. return false;
  206. }
  207. uint8_t* hashPtr = CString_strstr(Message_bytes(messageBytes), submittedHash->bytes);
  208. if (!hashPtr || !admin->password) {
  209. return false;
  210. }
  211. uint8_t passAndCookie[64];
  212. snprintf((char*) passAndCookie, 64, "%s%u", admin->password->bytes, cookie);
  213. uint8_t hash[32];
  214. crypto_hash_sha256(hash, passAndCookie, CString_strlen((char*) passAndCookie));
  215. Hex_encode(hashPtr, 64, hash, 32);
  216. crypto_hash_sha256(hash, Message_bytes(messageBytes), Message_getLength(messageBytes));
  217. Hex_encode(hashPtr, 64, hash, 32);
  218. int res = crypto_verify_32(hashPtr, submittedHash->bytes);
  219. res |= crypto_verify_32(hashPtr + 32, submittedHash->bytes + 32);
  220. return res == 0;
  221. }
  222. static bool checkArgs(Dict* args,
  223. struct Function* func,
  224. String* txid,
  225. struct Allocator* requestAlloc,
  226. struct Admin_pvt* admin)
  227. {
  228. struct Dict_Entry* entry = *func->args;
  229. String* error = NULL;
  230. while (entry != NULL) {
  231. String* key = (String*) entry->key;
  232. Assert_ifParanoid(entry->val->type == Object_DICT);
  233. Dict* value = entry->val->as.dictionary;
  234. entry = entry->next;
  235. if (*Dict_getIntC(value, "required") == 0) {
  236. continue;
  237. }
  238. String* type = Dict_getStringC(value, "type");
  239. if ((type == STRING && !Dict_getString(args, key))
  240. || (type == DICT && !Dict_getDict(args, key))
  241. || (type == INTEGER && !Dict_getInt(args, key))
  242. || (type == LIST && !Dict_getList(args, key)))
  243. {
  244. error = String_printf(requestAlloc,
  245. "Entry [%s] is required and must be of type [%s]",
  246. key->bytes,
  247. type->bytes);
  248. break;
  249. }
  250. }
  251. if (error) {
  252. Dict d = Dict_CONST(String_CONST("error"), String_OBJ(error), NULL);
  253. Admin_sendMessage(&d, txid, &admin->pub);
  254. }
  255. return !error;
  256. }
  257. static void asyncEnabled(Dict* args, void* vAdmin, String* txid, struct Allocator* requestAlloc)
  258. {
  259. struct Admin_pvt* admin = Identity_check((struct Admin_pvt*) vAdmin);
  260. int64_t enabled = admin->asyncEnabled;
  261. Dict d = Dict_CONST(String_CONST("asyncEnabled"), Int_OBJ(enabled), NULL);
  262. Admin_sendMessage(&d, txid, &admin->pub);
  263. }
  264. #define ENTRIES_PER_PAGE 8
  265. static void availableFunctions(Dict* args, void* vAdmin, String* txid, struct Allocator* tempAlloc)
  266. {
  267. struct Admin_pvt* admin = Identity_check((struct Admin_pvt*) vAdmin);
  268. int64_t* page = Dict_getIntC(args, "page");
  269. uint32_t i = (page) ? *page * ENTRIES_PER_PAGE : 0;
  270. Dict* d = Dict_new(tempAlloc);
  271. Dict* functions = Dict_new(tempAlloc);
  272. int count = 0;
  273. for (; i < (uint32_t)admin->functionCount && count++ < ENTRIES_PER_PAGE; i++) {
  274. Dict_putDict(functions, admin->functions[i].name, admin->functions[i].args, tempAlloc);
  275. }
  276. if (count >= ENTRIES_PER_PAGE) {
  277. Dict_putIntC(d, "more", 1, tempAlloc);
  278. }
  279. Dict_putDictC(d, "availableFunctions", functions, tempAlloc);
  280. Admin_sendMessage(d, txid, &admin->pub);
  281. }
  282. static Err_DEFUN handleRequest(Dict* messageDict,
  283. Message_t* message,
  284. struct Sockaddr* src,
  285. struct Allocator* allocator,
  286. struct Admin_pvt* admin)
  287. {
  288. String* query = Dict_getStringC(messageDict, "q");
  289. if (!query) {
  290. Log_info(admin->logger, "Got a non-query from admin interface");
  291. return NULL;
  292. }
  293. // txid becomes the user supplied txid combined with the channel num.
  294. String* userTxid = Dict_getString(messageDict, TXID);
  295. uint32_t txidlen = ((userTxid) ? userTxid->len : 0) + src->addrLen;
  296. String* txid = String_newBinary(NULL, txidlen, allocator);
  297. Bits_memcpy(txid->bytes, src, src->addrLen);
  298. if (userTxid) {
  299. Bits_memcpy(txid->bytes + src->addrLen, userTxid->bytes, userTxid->len);
  300. }
  301. // If they're asking for a cookie then lets give them one.
  302. String* cookie = String_CONST("cookie");
  303. if (String_equals(query, cookie)) {
  304. //Log_debug(admin->logger, "Got a request for a cookie");
  305. Dict* d = Dict_new(allocator);
  306. char bytes[32];
  307. snprintf(bytes, 32, "%u", (uint32_t) Time_currentTimeSeconds());
  308. String* theCookie = &(String) { .len = CString_strlen(bytes), .bytes = bytes };
  309. Dict_putString(d, cookie, theCookie, allocator);
  310. Admin_sendMessage(d, txid, &admin->pub);
  311. return NULL;
  312. }
  313. // If this is a permitted query, make sure the cookie is right.
  314. String* auth = String_CONST("auth");
  315. bool authed = false;
  316. if (String_equals(query, auth)) {
  317. if (!authValid(messageDict, message, admin)) {
  318. Dict* d = Dict_new(allocator);
  319. Dict_putStringCC(d, "error", "Auth failed.", allocator);
  320. Admin_sendMessage(d, txid, &admin->pub);
  321. return NULL;
  322. }
  323. query = Dict_getStringC(messageDict, "aq");
  324. authed = true;
  325. }
  326. if (String_equals(admin->password, String_CONST("NONE"))) {
  327. // If there's no password then we'll consider everything to be authed
  328. authed = true;
  329. }
  330. // Then sent a valid authed query, lets track their address so they can receive
  331. // asynchronous messages.
  332. int index = Map_LastMessageTimeByAddr_indexForKey(&src, &admin->map);
  333. uint64_t now = Time_currentTimeMilliseconds();
  334. admin->asyncEnabled = 1;
  335. if (index >= 0) {
  336. admin->map.values[index]->timeOfLastMessage = now;
  337. } else if (authed) {
  338. struct Allocator* entryAlloc = Allocator_child(admin->allocator);
  339. struct MapValue* mv = Allocator_calloc(entryAlloc, sizeof(struct MapValue), 1);
  340. mv->timeOfLastMessage = now;
  341. mv->allocator = entryAlloc;
  342. struct Sockaddr* storedAddr = Sockaddr_clone(src, entryAlloc);
  343. Map_LastMessageTimeByAddr_put(&storedAddr, &mv, &admin->map);
  344. } else {
  345. admin->asyncEnabled = 0;
  346. }
  347. Dict* args = Dict_getDictC(messageDict, "args");
  348. bool noFunctionsCalled = true;
  349. for (int i = 0; i < admin->functionCount; i++) {
  350. if (String_equals(query, admin->functions[i].name)
  351. && (authed || !admin->functions[i].needsAuth))
  352. {
  353. if (checkArgs(args, &admin->functions[i], txid, Message_getAlloc(message), admin)) {
  354. admin->functions[i].call(args, admin->functions[i].context, txid, Message_getAlloc(message));
  355. }
  356. noFunctionsCalled = false;
  357. }
  358. }
  359. if (noFunctionsCalled) {
  360. Dict d = Dict_CONST(
  361. String_CONST("error"),
  362. String_OBJ(String_CONST("No functions matched your request, "
  363. "try Admin_availableFunctions()")),
  364. NULL
  365. );
  366. Admin_sendMessage(&d, txid, &admin->pub);
  367. }
  368. return NULL;
  369. }
  370. static Err_DEFUN handleMessage(Message_t* message,
  371. struct Sockaddr* src,
  372. struct Allocator* alloc,
  373. struct Admin_pvt* admin)
  374. {
  375. if (Defined(Log_KEYS)) {
  376. uint8_t lastChar = Message_bytes(message)[Message_getLength(message) - 1];
  377. Message_bytes(message)[Message_getLength(message) - 1] = '\0';
  378. Log_keys(admin->logger, "Got message from [%s] [%s]",
  379. Sockaddr_print(src, alloc), Message_bytes(message));
  380. Message_bytes(message)[Message_getLength(message) - 1] = lastChar;
  381. }
  382. // handle non empty message data
  383. if (Message_getLength(message) > Admin_MAX_REQUEST_SIZE) {
  384. #define TOO_BIG "d5:error16:Request too big.e"
  385. #define TOO_BIG_STRLEN (sizeof(TOO_BIG) - 1)
  386. Bits_memcpy(Message_bytes(message), TOO_BIG, TOO_BIG_STRLEN);
  387. Err(Message_truncate(message, TOO_BIG_STRLEN));
  388. return sendMessage(message, src, admin);
  389. }
  390. int origMessageLen = Message_getLength(message);
  391. Dict* messageDict = NULL;
  392. const char* err = BencMessageReader_readNoExcept(message, alloc, &messageDict);
  393. if (err) {
  394. Log_warn(admin->logger,
  395. "Unparsable data from [%s] content: [%s] error: [%s]",
  396. Sockaddr_print(src, alloc),
  397. Hex_print(Message_bytes(message), Message_getLength(message), alloc),
  398. err);
  399. return NULL;
  400. }
  401. if (Message_getLength(message)) {
  402. Log_warn(admin->logger,
  403. "Message from [%s] contained garbage after byte [%d] content: [%s]",
  404. Sockaddr_print(src, alloc), Message_getLength(message), Message_bytes(message));
  405. return NULL;
  406. }
  407. // put the data back in the front of the message because it is used by the auth checker.
  408. Err(Message_eshift(message, origMessageLen));
  409. return handleRequest(messageDict, message, src, alloc, admin);
  410. }
  411. static Iface_DEFUN receiveMessage(Message_t* message, struct Iface* iface)
  412. {
  413. struct Admin_pvt* admin = Identity_containerOf(iface, struct Admin_pvt, iface);
  414. struct Allocator* alloc = Allocator_child(admin->allocator);
  415. struct Sockaddr_storage addrStore;
  416. Err(AddrIface_popAddr(&addrStore, message));
  417. admin->currentRequest = message;
  418. RTypes_Error_t* err = handleMessage(message, Sockaddr_clone(&addrStore.addr, alloc), alloc, admin);
  419. admin->currentRequest = NULL;
  420. Allocator_free(alloc);
  421. return err;
  422. }
  423. void Admin_registerFunctionWithArgCount(char* name,
  424. Admin_Function callback,
  425. void* callbackContext,
  426. bool needsAuth,
  427. struct Admin_FunctionArg* arguments,
  428. int argCount,
  429. struct Admin* adminPub)
  430. {
  431. struct Admin_pvt* admin = Identity_check((struct Admin_pvt*) adminPub);
  432. String* str = String_new(name, admin->allocator);
  433. admin->functions =
  434. Allocator_realloc(admin->allocator,
  435. admin->functions,
  436. sizeof(struct Function) * (admin->functionCount + 1));
  437. struct Function* fu = &admin->functions[admin->functionCount];
  438. admin->functionCount++;
  439. fu->name = str;
  440. fu->call = callback;
  441. fu->context = callbackContext;
  442. fu->needsAuth = needsAuth;
  443. fu->args = Dict_new(admin->allocator);
  444. for (int i = 0; arguments && i < argCount; i++) {
  445. // "type" must be one of: [ "String", "Int", "Dict", "List" ]
  446. String* type = NULL;
  447. if (!CString_strcmp(arguments[i].type, STRING->bytes)) {
  448. type = STRING;
  449. } else if (!CString_strcmp(arguments[i].type, INTEGER->bytes)) {
  450. type = INTEGER;
  451. } else if (!CString_strcmp(arguments[i].type, DICT->bytes)) {
  452. type = DICT;
  453. } else if (!CString_strcmp(arguments[i].type, LIST->bytes)) {
  454. type = LIST;
  455. } else {
  456. abort();
  457. }
  458. Dict* arg = Dict_new(admin->allocator);
  459. Dict_putString(arg, TYPE, type, admin->allocator);
  460. Dict_putInt(arg, REQUIRED, arguments[i].required, admin->allocator);
  461. String* name = String_new(arguments[i].name, admin->allocator);
  462. Dict_putDict(fu->args, name, arg, admin->allocator);
  463. }
  464. }
  465. static void importFd(Dict* args, void* vAdmin, String* txid, struct Allocator* requestAlloc)
  466. {
  467. struct Admin_pvt* admin = Identity_check((struct Admin_pvt*) vAdmin);
  468. int fd = Message_getAssociatedFd(admin->currentRequest);
  469. Dict* res = Dict_new(requestAlloc);
  470. char* error = "none";
  471. if (fd < 0) {
  472. if (Defined(win32)) {
  473. error = "Admin_importFd() does not support win32";
  474. } else {
  475. error = "file descriptor was not attached to message";
  476. }
  477. } else {
  478. Dict_putIntC(res, "fd", fd, requestAlloc);
  479. }
  480. Dict_putStringCC(res, "error", error, requestAlloc);
  481. Admin_sendMessage(res, txid, &admin->pub);
  482. }
  483. static void exportFd(Dict* args, void* vAdmin, String* txid, struct Allocator* requestAlloc)
  484. {
  485. struct Admin_pvt* admin = Identity_check((struct Admin_pvt*) vAdmin);
  486. int64_t* fd_p = Dict_getIntC(args, "fd");
  487. if (!fd_p || *fd_p < 0) {
  488. Dict* res = Dict_new(requestAlloc);
  489. Dict_putStringCC(res, "error", "invalid fd", requestAlloc);
  490. Admin_sendMessage(res, txid, &admin->pub);
  491. return;
  492. }
  493. int fd = *fd_p;
  494. Dict* res = Dict_new(requestAlloc);
  495. char* error = "none";
  496. if (fd < 0) {
  497. if (Defined(win32)) {
  498. error = "Admin_exportFd() does not support win32";
  499. } else {
  500. error = "file descriptor was not attached to message";
  501. }
  502. }
  503. Dict_putStringCC(res, "error", error, requestAlloc);
  504. sendMessage0(res, txid, &admin->pub, fd);
  505. }
  506. struct Admin* Admin_new(AddrIface_t* ai,
  507. struct Log* logger,
  508. EventBase_t* eventBase,
  509. String* password)
  510. {
  511. struct Allocator* alloc = ai->alloc;
  512. struct Admin_pvt* admin = Allocator_calloc(alloc, sizeof(struct Admin_pvt), 1);
  513. Identity_set(admin);
  514. admin->allocator = alloc;
  515. admin->logger = logger;
  516. admin->eventBase = eventBase;
  517. admin->map.allocator = alloc;
  518. admin->iface.send = receiveMessage;
  519. Iface_plumb(&admin->iface, ai->iface);
  520. admin->tempSendMsg = Message_new(0, Admin_MAX_RESPONSE_SIZE, alloc);
  521. admin->password = String_clone(password, alloc);
  522. Timeout_setInterval(clearExpiredAddresses, admin, TIMEOUT_MILLISECONDS * 3, eventBase, alloc);
  523. Admin_registerFunction("Admin_asyncEnabled", asyncEnabled, admin, false, NULL, &admin->pub);
  524. Admin_registerFunction("Admin_availableFunctions", availableFunctions, admin, false,
  525. ((struct Admin_FunctionArg[]) {
  526. { .name = "page", .required = 0, .type = "Int" }
  527. }), &admin->pub);
  528. Admin_registerFunction("Admin_importFd", importFd, admin, true, NULL, &admin->pub);
  529. Admin_registerFunction("Admin_exportFd", exportFd, admin, true,
  530. ((struct Admin_FunctionArg[]) {
  531. { .name = "fd", .required = 1, .type = "Int" }
  532. }), &admin->pub);
  533. return &admin->pub;
  534. }