sys_request_server.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. /**
  2. * @file sys_request_server.c
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of the author nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *
  29. * @section DESCRIPTION
  30. *
  31. * A simple a IPC interface for NCD to talk to other processes over a Unix socket.
  32. *
  33. * Synopsis:
  34. * sys.request_server(listen_address, string request_handler_template, list args)
  35. *
  36. * Description:
  37. * Initializes a request server on the given socket path. Requests are served by
  38. * starting a template process for every request. Multiple such processes may
  39. * exist simultaneously. Termination of these processess may be initiated at
  40. * any time if the request server no longer needs the request in question served.
  41. * The payload of a request is a value, and can be accessed as _request.data
  42. * from within the handler process. Replies to the request can be sent using
  43. * _request->reply(data); replies are values too. Finally, _request->finish()
  44. * should be called to indicate that no further replies will be sent. Calling
  45. * finish() will immediately initiate termination of the handler process.
  46. * Requests can be sent to NCD using the badvpn-ncd-request program.
  47. *
  48. * The listen address should be in the same format as for the socket module.
  49. * In particular, it must be in one of the following forms:
  50. * - {"tcp", {"ipv4", ipv4_address, port_number}},
  51. * - {"tcp", {"ipv6", ipv6_address, port_number}},
  52. * - {"unix", socket_path}.
  53. *
  54. * Predefined variables in request_handler_template:
  55. * _request.data - the request payload as sent by the client
  56. * _request.client_addr_type - type of client address; "none", "ipv4" or "ipv6"
  57. * _request.client_addr - client IP address. IPv4 addresses are standard dotted-decimal
  58. * without leading zeros, e.g. "14.6.0.251". IPv6 addresses are full 8
  59. * lower-case-hexadecimal numbers separated by 7 colons, without leading zeros,
  60. * e.g. "61:71a4:81f:98aa:57:0:5efa:17". If client_addr_type=="none", this too
  61. * is "none".
  62. *
  63. * Synopsis:
  64. * sys.request_server.request::reply(reply_data)
  65. *
  66. * Synopsis:
  67. * sys.request_server.request::finish()
  68. */
  69. #include <stdlib.h>
  70. #include <string.h>
  71. #include <limits.h>
  72. #include <inttypes.h>
  73. #include <errno.h>
  74. #include <misc/offset.h>
  75. #include <misc/debug.h>
  76. #include <misc/byteorder.h>
  77. #include <protocol/packetproto.h>
  78. #include <protocol/requestproto.h>
  79. #include <structure/LinkedList0.h>
  80. #include <system/BConnection.h>
  81. #include <system/BConnectionGeneric.h>
  82. #include <system/BAddr.h>
  83. #include <flow/PacketProtoDecoder.h>
  84. #include <flow/PacketStreamSender.h>
  85. #include <flow/PacketPassFifoQueue.h>
  86. #include <ncd/NCDValParser.h>
  87. #include <ncd/NCDValGenerator.h>
  88. #include <ncd/NCDModule.h>
  89. #include <ncd/value_utils.h>
  90. #include <ncd/address_utils.h>
  91. #include <generated/blog_channel_ncd_sys_request_server.h>
  92. #define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__)
  93. #define SEND_PAYLOAD_MTU 32768
  94. #define RECV_PAYLOAD_MTU 32768
  95. #define SEND_MTU (SEND_PAYLOAD_MTU + sizeof(struct requestproto_header))
  96. #define RECV_MTU (RECV_PAYLOAD_MTU + sizeof(struct requestproto_header))
  97. struct instance {
  98. NCDModuleInst *i;
  99. NCDValRef request_handler_template;
  100. NCDValRef args;
  101. BListener listener;
  102. LinkedList0 connections_list;
  103. int dying;
  104. };
  105. #define CONNECTION_STATE_RUNNING 1
  106. #define CONNECTION_STATE_TERMINATING 2
  107. struct reply;
  108. struct connection {
  109. struct instance *inst;
  110. LinkedList0Node connections_list_node;
  111. BConnection con;
  112. BAddr addr;
  113. PacketProtoDecoder recv_decoder;
  114. PacketPassInterface recv_if;
  115. PacketPassFifoQueue send_queue;
  116. PacketStreamSender send_pss;
  117. LinkedList0 requests_list;
  118. LinkedList0 replies_list;
  119. int state;
  120. };
  121. struct request {
  122. struct connection *con;
  123. uint32_t request_id;
  124. LinkedList0Node requests_list_node;
  125. NCDValMem request_data_mem;
  126. NCDValRef request_data;
  127. struct reply *end_reply;
  128. NCDModuleProcess process;
  129. int terminating;
  130. int got_finished;
  131. };
  132. struct reply {
  133. struct connection *con;
  134. LinkedList0Node replies_list_node;
  135. PacketPassFifoQueueFlow send_qflow;
  136. PacketPassInterface *send_qflow_if;
  137. uint8_t *send_buf;
  138. };
  139. static void listener_handler (struct instance *o);
  140. static void connection_free (struct connection *c);
  141. static void connection_free_link (struct connection *c);
  142. static void connection_terminate (struct connection *c);
  143. static void connection_con_handler (struct connection *c, int event);
  144. static void connection_recv_decoder_handler_error (struct connection *c);
  145. static void connection_recv_if_handler_send (struct connection *c, uint8_t *data, int data_len);
  146. static int request_init (struct connection *c, uint32_t request_id, const uint8_t *data, int data_len);
  147. static void request_free (struct request *r);
  148. static struct request * find_request (struct connection *c, uint32_t request_id);
  149. static void request_process_handler_event (NCDModuleProcess *process, int event);
  150. static int request_process_func_getspecialobj (NCDModuleProcess *process, NCD_string_id_t name, NCDObject *out_object);
  151. static int request_process_request_obj_func_getvar (struct request *r, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out_value);
  152. static void request_terminate (struct request *r);
  153. static struct reply * reply_init (struct connection *c, uint32_t request_id, NCDValRef reply_data);
  154. static void reply_start (struct reply *r, uint32_t type);
  155. static void reply_free (struct reply *r);
  156. static void reply_send_qflow_if_handler_done (struct reply *r);
  157. static void instance_free (struct instance *o);
  158. enum {STRING_REQUEST, STRING_DATA, STRING_CLIENT_ADDR_TYPE, STRING_CLIENT_ADDR,
  159. STRING_SYS_REQUEST_SERVER_REQUEST};
  160. static struct NCD_string_request strings[] = {
  161. {"_request"}, {"data"}, {"client_addr_type"}, {"client_addr"},
  162. {"sys.request_server.request"}, {NULL}
  163. };
  164. static void listener_handler (struct instance *o)
  165. {
  166. ASSERT(!o->dying)
  167. BReactor *reactor = o->i->params->iparams->reactor;
  168. BPendingGroup *pg = BReactor_PendingGroup(reactor);
  169. struct connection *c = malloc(sizeof(*c));
  170. if (!c) {
  171. ModuleLog(o->i, BLOG_ERROR, "malloc failed");
  172. goto fail0;
  173. }
  174. c->inst = o;
  175. LinkedList0_Prepend(&o->connections_list, &c->connections_list_node);
  176. if (!BConnection_Init(&c->con, BConnection_source_listener(&o->listener, &c->addr), reactor, c, (BConnection_handler)connection_con_handler)) {
  177. ModuleLog(o->i, BLOG_ERROR, "BConnection_Init failed");
  178. goto fail1;
  179. }
  180. BConnection_SendAsync_Init(&c->con);
  181. BConnection_RecvAsync_Init(&c->con);
  182. StreamPassInterface *con_send_if = BConnection_SendAsync_GetIf(&c->con);
  183. StreamRecvInterface *con_recv_if = BConnection_RecvAsync_GetIf(&c->con);
  184. PacketPassInterface_Init(&c->recv_if, RECV_MTU, (PacketPassInterface_handler_send)connection_recv_if_handler_send, c, pg);
  185. if (!PacketProtoDecoder_Init(&c->recv_decoder, con_recv_if, &c->recv_if, pg, c, (PacketProtoDecoder_handler_error)connection_recv_decoder_handler_error)) {
  186. ModuleLog(o->i, BLOG_ERROR, "PacketProtoDecoder_Init failed");
  187. goto fail2;
  188. }
  189. PacketStreamSender_Init(&c->send_pss, con_send_if, PACKETPROTO_ENCLEN(SEND_MTU), pg);
  190. PacketPassFifoQueue_Init(&c->send_queue, PacketStreamSender_GetInput(&c->send_pss), pg);
  191. LinkedList0_Init(&c->requests_list);
  192. LinkedList0_Init(&c->replies_list);
  193. c->state = CONNECTION_STATE_RUNNING;
  194. ModuleLog(o->i, BLOG_INFO, "connection initialized");
  195. return;
  196. fail2:
  197. PacketPassInterface_Free(&c->recv_if);
  198. BConnection_RecvAsync_Free(&c->con);
  199. BConnection_SendAsync_Free(&c->con);
  200. BConnection_Free(&c->con);
  201. fail1:
  202. LinkedList0_Remove(&o->connections_list, &c->connections_list_node);
  203. free(c);
  204. fail0:
  205. return;
  206. }
  207. static void connection_free (struct connection *c)
  208. {
  209. struct instance *o = c->inst;
  210. ASSERT(c->state == CONNECTION_STATE_TERMINATING)
  211. ASSERT(LinkedList0_IsEmpty(&c->requests_list))
  212. ASSERT(LinkedList0_IsEmpty(&c->replies_list))
  213. LinkedList0_Remove(&o->connections_list, &c->connections_list_node);
  214. free(c);
  215. }
  216. static void connection_free_link (struct connection *c)
  217. {
  218. PacketPassFifoQueue_PrepareFree(&c->send_queue);
  219. LinkedList0Node *ln;
  220. while (ln = LinkedList0_GetFirst(&c->replies_list)) {
  221. struct reply *r = UPPER_OBJECT(ln, struct reply, replies_list_node);
  222. ASSERT(r->con == c)
  223. reply_free(r);
  224. }
  225. PacketPassFifoQueue_Free(&c->send_queue);
  226. PacketStreamSender_Free(&c->send_pss);
  227. PacketProtoDecoder_Free(&c->recv_decoder);
  228. PacketPassInterface_Free(&c->recv_if);
  229. BConnection_RecvAsync_Free(&c->con);
  230. BConnection_SendAsync_Free(&c->con);
  231. BConnection_Free(&c->con);
  232. }
  233. static void connection_terminate (struct connection *c)
  234. {
  235. ASSERT(c->state == CONNECTION_STATE_RUNNING)
  236. for (LinkedList0Node *ln = LinkedList0_GetFirst(&c->requests_list); ln; ln = LinkedList0Node_Next(ln)) {
  237. struct request *r = UPPER_OBJECT(ln, struct request, requests_list_node);
  238. if (!r->terminating) {
  239. request_terminate(r);
  240. }
  241. }
  242. connection_free_link(c);
  243. c->state = CONNECTION_STATE_TERMINATING;
  244. if (LinkedList0_IsEmpty(&c->requests_list)) {
  245. connection_free(c);
  246. return;
  247. }
  248. }
  249. static void connection_con_handler (struct connection *c, int event)
  250. {
  251. struct instance *o = c->inst;
  252. ASSERT(c->state == CONNECTION_STATE_RUNNING)
  253. ModuleLog(o->i, BLOG_INFO, "connection closed");
  254. connection_terminate(c);
  255. }
  256. static void connection_recv_decoder_handler_error (struct connection *c)
  257. {
  258. struct instance *o = c->inst;
  259. ASSERT(c->state == CONNECTION_STATE_RUNNING)
  260. ModuleLog(o->i, BLOG_ERROR, "decoder error");
  261. connection_terminate(c);
  262. }
  263. static void connection_recv_if_handler_send (struct connection *c, uint8_t *data, int data_len)
  264. {
  265. struct instance *o = c->inst;
  266. ASSERT(c->state == CONNECTION_STATE_RUNNING)
  267. ASSERT(data_len >= 0)
  268. ASSERT(data_len <= RECV_MTU)
  269. PacketPassInterface_Done(&c->recv_if);
  270. if (data_len < sizeof(struct requestproto_header)) {
  271. ModuleLog(o->i, BLOG_ERROR, "missing requestproto header");
  272. goto fail;
  273. }
  274. struct requestproto_header *header = (void *)data;
  275. uint32_t request_id = ltoh32(header->request_id);
  276. uint32_t type = ltoh32(header->type);
  277. switch (type) {
  278. case REQUESTPROTO_TYPE_CLIENT_REQUEST: {
  279. if (find_request(c, request_id)) {
  280. ModuleLog(o->i, BLOG_ERROR, "request with the same ID already exists");
  281. goto fail;
  282. }
  283. if (!request_init(c, request_id, data + sizeof(*header), data_len - sizeof(*header))) {
  284. goto fail;
  285. }
  286. } break;
  287. case REQUESTPROTO_TYPE_CLIENT_ABORT: {
  288. struct request *r = find_request(c, request_id);
  289. if (!r) {
  290. // this is expected if we finish before we get the abort
  291. return;
  292. }
  293. if (!r->terminating) {
  294. request_terminate(r);
  295. }
  296. } break;
  297. default:
  298. ModuleLog(o->i, BLOG_ERROR, "invalid requestproto type");
  299. goto fail;
  300. }
  301. return;
  302. fail:
  303. connection_terminate(c);
  304. }
  305. static int request_init (struct connection *c, uint32_t request_id, const uint8_t *data, int data_len)
  306. {
  307. struct instance *o = c->inst;
  308. ASSERT(c->state == CONNECTION_STATE_RUNNING)
  309. ASSERT(!find_request(c, request_id))
  310. ASSERT(data_len >= 0)
  311. ASSERT(data_len <= RECV_PAYLOAD_MTU)
  312. struct request *r = malloc(sizeof(*r));
  313. if (!r) {
  314. ModuleLog(o->i, BLOG_ERROR, "malloc failed");
  315. goto fail0;
  316. }
  317. r->con = c;
  318. r->request_id = request_id;
  319. LinkedList0_Prepend(&c->requests_list, &r->requests_list_node);
  320. NCDValMem_Init(&r->request_data_mem);
  321. if (!NCDValParser_Parse((const char *)data, data_len, &r->request_data_mem, &r->request_data)) {
  322. ModuleLog(o->i, BLOG_ERROR, "NCDValParser_Parse failed");
  323. goto fail1;
  324. }
  325. if (!(r->end_reply = reply_init(c, request_id, NCDVal_NewInvalid()))) {
  326. goto fail1;
  327. }
  328. if (!NCDModuleProcess_InitValue(&r->process, o->i, o->request_handler_template, o->args, request_process_handler_event)) {
  329. ModuleLog(o->i, BLOG_ERROR, "NCDModuleProcess_Init failed");
  330. goto fail3;
  331. }
  332. NCDModuleProcess_SetSpecialFuncs(&r->process, request_process_func_getspecialobj);
  333. r->terminating = 0;
  334. r->got_finished = 0;
  335. ModuleLog(o->i, BLOG_INFO, "request initialized");
  336. return 1;
  337. fail3:
  338. reply_free(r->end_reply);
  339. fail1:
  340. NCDValMem_Free(&r->request_data_mem);
  341. LinkedList0_Remove(&c->requests_list, &r->requests_list_node);
  342. free(r);
  343. fail0:
  344. return 0;
  345. }
  346. static void request_free (struct request *r)
  347. {
  348. struct connection *c = r->con;
  349. NCDModuleProcess_AssertFree(&r->process);
  350. if (c->state != CONNECTION_STATE_TERMINATING) {
  351. uint32_t type = r->got_finished ? REQUESTPROTO_TYPE_SERVER_FINISHED : REQUESTPROTO_TYPE_SERVER_ERROR;
  352. reply_start(r->end_reply, type);
  353. }
  354. NCDModuleProcess_Free(&r->process);
  355. NCDValMem_Free(&r->request_data_mem);
  356. LinkedList0_Remove(&c->requests_list, &r->requests_list_node);
  357. free(r);
  358. }
  359. static struct request * find_request (struct connection *c, uint32_t request_id)
  360. {
  361. for (LinkedList0Node *ln = LinkedList0_GetFirst(&c->requests_list); ln; ln = LinkedList0Node_Next(ln)) {
  362. struct request *r = UPPER_OBJECT(ln, struct request, requests_list_node);
  363. if (!r->terminating && r->request_id == request_id) {
  364. return r;
  365. }
  366. }
  367. return NULL;
  368. }
  369. static void request_process_handler_event (NCDModuleProcess *process, int event)
  370. {
  371. struct request *r = UPPER_OBJECT(process, struct request, process);
  372. struct connection *c = r->con;
  373. struct instance *o = c->inst;
  374. switch (event) {
  375. case NCDMODULEPROCESS_EVENT_UP: {
  376. ASSERT(!r->terminating)
  377. } break;
  378. case NCDMODULEPROCESS_EVENT_DOWN: {
  379. ASSERT(!r->terminating)
  380. NCDModuleProcess_Continue(&r->process);
  381. } break;
  382. case NCDMODULEPROCESS_EVENT_TERMINATED: {
  383. ASSERT(r->terminating)
  384. request_free(r);
  385. if (c->state == CONNECTION_STATE_TERMINATING && LinkedList0_IsEmpty(&c->requests_list)) {
  386. connection_free(c);
  387. if (o->dying && LinkedList0_IsEmpty(&o->connections_list)) {
  388. instance_free(o);
  389. return;
  390. }
  391. }
  392. } break;
  393. default: ASSERT(0);
  394. }
  395. }
  396. static int request_process_func_getspecialobj (NCDModuleProcess *process, NCD_string_id_t name, NCDObject *out_object)
  397. {
  398. struct request *r = UPPER_OBJECT(process, struct request, process);
  399. if (name == strings[STRING_REQUEST].id) {
  400. *out_object = NCDObject_Build(strings[STRING_SYS_REQUEST_SERVER_REQUEST].id, r, (NCDObject_func_getvar)request_process_request_obj_func_getvar, NULL);
  401. return 1;
  402. }
  403. return 0;
  404. }
  405. static int request_process_request_obj_func_getvar (struct request *r, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  406. {
  407. struct instance *o = r->con->inst;
  408. if (name == strings[STRING_DATA].id) {
  409. *out = NCDVal_NewCopy(mem, r->request_data);
  410. if (NCDVal_IsInvalid(*out)) {
  411. ModuleLog(o->i, BLOG_ERROR, "NCDVal_NewCopy failed");
  412. }
  413. return 1;
  414. }
  415. if (name == strings[STRING_CLIENT_ADDR_TYPE].id) {
  416. const char *str = "none";
  417. switch (r->con->addr.type) {
  418. case BADDR_TYPE_IPV4:
  419. str = "ipv4";
  420. break;
  421. case BADDR_TYPE_IPV6:
  422. str = "ipv6";
  423. break;
  424. }
  425. *out = NCDVal_NewString(mem, str);
  426. if (NCDVal_IsInvalid(*out)) {
  427. ModuleLog(o->i, BLOG_ERROR, "NCDVal_NewString failed");
  428. }
  429. return 1;
  430. }
  431. if (name == strings[STRING_CLIENT_ADDR].id) {
  432. char str[BIPADDR_MAX_PRINT_LEN] = "none";
  433. switch (r->con->addr.type) {
  434. case BADDR_TYPE_IPV4:
  435. case BADDR_TYPE_IPV6: {
  436. BIPAddr ipaddr;
  437. BAddr_GetIPAddr(&r->con->addr, &ipaddr);
  438. BIPAddr_Print(&ipaddr, str);
  439. } break;
  440. }
  441. *out = NCDVal_NewString(mem, str);
  442. if (NCDVal_IsInvalid(*out)) {
  443. ModuleLog(o->i, BLOG_ERROR, "NCDVal_NewString failed");
  444. }
  445. return 1;
  446. }
  447. return 0;
  448. }
  449. static void request_terminate (struct request *r)
  450. {
  451. ASSERT(!r->terminating)
  452. NCDModuleProcess_Terminate(&r->process);
  453. r->terminating = 1;
  454. }
  455. static struct reply * reply_init (struct connection *c, uint32_t request_id, NCDValRef reply_data)
  456. {
  457. struct instance *o = c->inst;
  458. ASSERT(c->state == CONNECTION_STATE_RUNNING)
  459. NCDVal_Assert(reply_data);
  460. struct reply *r = malloc(sizeof(*r));
  461. if (!r) {
  462. ModuleLog(o->i, BLOG_ERROR, "malloc failed");
  463. goto fail0;
  464. }
  465. r->con = c;
  466. LinkedList0_Prepend(&c->replies_list, &r->replies_list_node);
  467. PacketPassFifoQueueFlow_Init(&r->send_qflow, &c->send_queue);
  468. r->send_qflow_if = PacketPassFifoQueueFlow_GetInput(&r->send_qflow);
  469. PacketPassInterface_Sender_Init(r->send_qflow_if, (PacketPassInterface_handler_done)reply_send_qflow_if_handler_done, r);
  470. struct reply_header {
  471. struct packetproto_header pp;
  472. struct requestproto_header rp;
  473. } __attribute__((packed));
  474. ExpString str;
  475. if (!ExpString_Init(&str)) {
  476. ModuleLog(o->i, BLOG_ERROR, "ExpString_Init failed");
  477. goto fail1;
  478. }
  479. if (!ExpString_AppendZeros(&str, sizeof(struct reply_header))) {
  480. ModuleLog(o->i, BLOG_ERROR, "ExpString_AppendZeros failed");
  481. goto fail2;
  482. }
  483. if (!NCDVal_IsInvalid(reply_data) && !NCDValGenerator_AppendGenerate(reply_data, &str)) {
  484. ModuleLog(o->i, BLOG_ERROR, "NCDValGenerator_AppendGenerate failed");
  485. goto fail2;
  486. }
  487. size_t len = ExpString_Length(&str);
  488. if (len > INT_MAX || len > PACKETPROTO_ENCLEN(SEND_MTU) || len - sizeof(struct packetproto_header) > UINT16_MAX) {
  489. ModuleLog(o->i, BLOG_ERROR, "reply is too long");
  490. goto fail2;
  491. }
  492. r->send_buf = (uint8_t *)ExpString_Get(&str);
  493. struct reply_header *header = (void *)r->send_buf;
  494. header->pp.len = htol16(len - sizeof(header->pp));
  495. header->rp.request_id = htol32(request_id);
  496. return r;
  497. fail2:
  498. ExpString_Free(&str);
  499. fail1:
  500. PacketPassFifoQueueFlow_Free(&r->send_qflow);
  501. LinkedList0_Remove(&c->replies_list, &r->replies_list_node);
  502. free(r);
  503. fail0:
  504. return NULL;
  505. }
  506. static void reply_start (struct reply *r, uint32_t type)
  507. {
  508. struct reply_header {
  509. struct packetproto_header pp;
  510. struct requestproto_header rp;
  511. } __attribute__((packed));
  512. struct reply_header *header = (void *)r->send_buf;
  513. header->rp.type = htol32(type);
  514. int len = ltoh16(header->pp.len) + sizeof(struct packetproto_header);
  515. PacketPassInterface_Sender_Send(r->send_qflow_if, r->send_buf, len);
  516. }
  517. static void reply_free (struct reply *r)
  518. {
  519. struct connection *c = r->con;
  520. PacketPassFifoQueueFlow_AssertFree(&r->send_qflow);
  521. free(r->send_buf);
  522. PacketPassFifoQueueFlow_Free(&r->send_qflow);
  523. LinkedList0_Remove(&c->replies_list, &r->replies_list_node);
  524. free(r);
  525. }
  526. static void reply_send_qflow_if_handler_done (struct reply *r)
  527. {
  528. reply_free(r);
  529. }
  530. static void func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  531. {
  532. struct instance *o = vo;
  533. o->i = i;
  534. // check arguments
  535. NCDValRef listen_addr_arg;
  536. NCDValRef request_handler_template_arg;
  537. NCDValRef args_arg;
  538. if (!NCDVal_ListRead(params->args, 3, &listen_addr_arg, &request_handler_template_arg, &args_arg)) {
  539. ModuleLog(o->i, BLOG_ERROR, "wrong arity");
  540. goto fail0;
  541. }
  542. if (!NCDVal_IsString(request_handler_template_arg) || !NCDVal_IsList(args_arg)) {
  543. ModuleLog(o->i, BLOG_ERROR, "wrong type");
  544. goto fail0;
  545. }
  546. o->request_handler_template = request_handler_template_arg;
  547. o->args = args_arg;
  548. // read listen address
  549. struct BConnection_addr addr;
  550. if (!ncd_read_bconnection_addr(listen_addr_arg, &addr)) {
  551. ModuleLog(o->i, BLOG_ERROR, "wrong listen address");
  552. goto fail0;
  553. }
  554. // init listener
  555. if (!BListener_InitGeneric(&o->listener, addr, i->params->iparams->reactor, o, (BListener_handler)listener_handler)) {
  556. ModuleLog(o->i, BLOG_ERROR, "BListener_InitGeneric failed");
  557. goto fail0;
  558. }
  559. // init connections list
  560. LinkedList0_Init(&o->connections_list);
  561. // set not dying
  562. o->dying = 0;
  563. // signal up
  564. NCDModuleInst_Backend_Up(i);
  565. return;
  566. fail0:
  567. NCDModuleInst_Backend_SetError(i);
  568. NCDModuleInst_Backend_Dead(i);
  569. }
  570. static void instance_free (struct instance *o)
  571. {
  572. ASSERT(o->dying)
  573. ASSERT(LinkedList0_IsEmpty(&o->connections_list))
  574. NCDModuleInst_Backend_Dead(o->i);
  575. }
  576. static void func_die (void *vo)
  577. {
  578. struct instance *o = vo;
  579. ASSERT(!o->dying)
  580. // free listener
  581. BListener_Free(&o->listener);
  582. // terminate connections
  583. LinkedList0Node *next_ln;
  584. for (LinkedList0Node *ln = LinkedList0_GetFirst(&o->connections_list); ln && (next_ln = LinkedList0Node_Next(ln)), ln; ln = next_ln) {
  585. struct connection *c = UPPER_OBJECT(ln, struct connection, connections_list_node);
  586. ASSERT(c->inst == o)
  587. if (c->state != CONNECTION_STATE_TERMINATING) {
  588. connection_terminate(c);
  589. }
  590. }
  591. // set dying
  592. o->dying = 1;
  593. // if no connections, die right away
  594. if (LinkedList0_IsEmpty(&o->connections_list)) {
  595. instance_free(o);
  596. return;
  597. }
  598. }
  599. static void reply_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  600. {
  601. NCDValRef reply_data;
  602. if (!NCDVal_ListRead(params->args, 1, &reply_data)) {
  603. ModuleLog(i, BLOG_ERROR, "wrong arity");
  604. goto fail;
  605. }
  606. NCDModuleInst_Backend_Up(i);
  607. struct request *r = params->method_user;
  608. struct connection *c = r->con;
  609. if (r->terminating) {
  610. ModuleLog(i, BLOG_ERROR, "request is dying, cannot submit reply");
  611. goto fail;
  612. }
  613. struct reply *rpl = reply_init(c, r->request_id, reply_data);
  614. if (!rpl) {
  615. ModuleLog(i, BLOG_ERROR, "failed to submit reply");
  616. goto fail;
  617. }
  618. reply_start(rpl, REQUESTPROTO_TYPE_SERVER_REPLY);
  619. return;
  620. fail:
  621. NCDModuleInst_Backend_SetError(i);
  622. NCDModuleInst_Backend_Dead(i);
  623. }
  624. static void finish_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  625. {
  626. if (!NCDVal_ListRead(params->args, 0)) {
  627. ModuleLog(i, BLOG_ERROR, "wrong arity");
  628. goto fail;
  629. }
  630. NCDModuleInst_Backend_Up(i);
  631. struct request *r = params->method_user;
  632. if (r->terminating) {
  633. ModuleLog(i, BLOG_ERROR, "request is dying, cannot submit finished");
  634. goto fail;
  635. }
  636. r->got_finished = 1;
  637. request_terminate(r);
  638. return;
  639. fail:
  640. NCDModuleInst_Backend_SetError(i);
  641. NCDModuleInst_Backend_Dead(i);
  642. }
  643. static struct NCDModule modules[] = {
  644. {
  645. .type = "sys.request_server",
  646. .func_new2 = func_new,
  647. .func_die = func_die,
  648. .alloc_size = sizeof(struct instance)
  649. }, {
  650. .type = "sys.request_server.request::reply",
  651. .func_new2 = reply_func_new
  652. }, {
  653. .type = "sys.request_server.request::finish",
  654. .func_new2 = finish_func_new
  655. }, {
  656. .type = NULL
  657. }
  658. };
  659. const struct NCDModuleGroup ncdmodule_sys_request_server = {
  660. .modules = modules,
  661. .strings = strings
  662. };