sys_request_server.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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 objects and variables in request_handler_template:
  55. * _caller - provides access to objects as seen from the sys.request_server()
  56. * command
  57. * _request.data - the request payload as sent by the client
  58. * string _request.client_addr - the address of the client. The form is
  59. * like the second part of the sys.request_server() address format, e.g.
  60. * {"ipv4", "1.2.3.4", "4000"}.
  61. *
  62. * Synopsis:
  63. * sys.request_server.request::reply(reply_data)
  64. *
  65. * Synopsis:
  66. * sys.request_server.request::finish()
  67. */
  68. #include <stdlib.h>
  69. #include <string.h>
  70. #include <limits.h>
  71. #include <inttypes.h>
  72. #include <errno.h>
  73. #include <misc/offset.h>
  74. #include <misc/debug.h>
  75. #include <misc/byteorder.h>
  76. #include <protocol/packetproto.h>
  77. #include <protocol/requestproto.h>
  78. #include <structure/LinkedList0.h>
  79. #include <system/BConnection.h>
  80. #include <system/BConnectionGeneric.h>
  81. #include <system/BAddr.h>
  82. #include <flow/PacketProtoDecoder.h>
  83. #include <flow/PacketStreamSender.h>
  84. #include <flow/PacketPassFifoQueue.h>
  85. #include <ncd/NCDValParser.h>
  86. #include <ncd/NCDValGenerator.h>
  87. #include <ncd/extra/address_utils.h>
  88. #include <ncd/module_common.h>
  89. #include <generated/blog_channel_ncd_sys_request_server.h>
  90. #define SEND_PAYLOAD_MTU 32768
  91. #define RECV_PAYLOAD_MTU 32768
  92. #define SEND_MTU (SEND_PAYLOAD_MTU + sizeof(struct requestproto_header))
  93. #define RECV_MTU (RECV_PAYLOAD_MTU + sizeof(struct requestproto_header))
  94. struct instance {
  95. NCDModuleInst *i;
  96. NCDValRef request_handler_template;
  97. NCDValRef args;
  98. BListener listener;
  99. LinkedList0 connections_list;
  100. int dying;
  101. };
  102. #define CONNECTION_STATE_RUNNING 1
  103. #define CONNECTION_STATE_TERMINATING 2
  104. struct reply;
  105. struct connection {
  106. struct instance *inst;
  107. LinkedList0Node connections_list_node;
  108. BConnection con;
  109. BAddr addr;
  110. PacketProtoDecoder recv_decoder;
  111. PacketPassInterface recv_if;
  112. PacketPassFifoQueue send_queue;
  113. PacketStreamSender send_pss;
  114. LinkedList0 requests_list;
  115. LinkedList0 replies_list;
  116. int state;
  117. };
  118. struct request {
  119. struct connection *con;
  120. uint32_t request_id;
  121. LinkedList0Node requests_list_node;
  122. NCDValMem request_data_mem;
  123. NCDValRef request_data;
  124. struct reply *end_reply;
  125. NCDModuleProcess process;
  126. int terminating;
  127. int got_finished;
  128. };
  129. struct reply {
  130. struct connection *con;
  131. LinkedList0Node replies_list_node;
  132. PacketPassFifoQueueFlow send_qflow;
  133. PacketPassInterface *send_qflow_if;
  134. uint8_t *send_buf;
  135. };
  136. static void listener_handler (struct instance *o);
  137. static void connection_free (struct connection *c);
  138. static void connection_free_link (struct connection *c);
  139. static void connection_terminate (struct connection *c);
  140. static void connection_con_handler (struct connection *c, int event);
  141. static void connection_recv_decoder_handler_error (struct connection *c);
  142. static void connection_recv_if_handler_send (struct connection *c, uint8_t *data, int data_len);
  143. static int request_init (struct connection *c, uint32_t request_id, const uint8_t *data, int data_len);
  144. static void request_free (struct request *r);
  145. static struct request * find_request (struct connection *c, uint32_t request_id);
  146. static void request_process_handler_event (NCDModuleProcess *process, int event);
  147. static int request_process_func_getspecialobj (NCDModuleProcess *process, NCD_string_id_t name, NCDObject *out_object);
  148. static int request_process_caller_obj_func_getobj (const NCDObject *obj, NCD_string_id_t name, NCDObject *out_object);
  149. static int request_process_request_obj_func_getvar (const NCDObject *obj, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out_value);
  150. static void request_terminate (struct request *r);
  151. static struct reply * reply_init (struct connection *c, uint32_t request_id, NCDValRef reply_data);
  152. static void reply_start (struct reply *r, uint32_t type);
  153. static void reply_free (struct reply *r);
  154. static void reply_send_qflow_if_handler_done (struct reply *r);
  155. static void instance_free (struct instance *o);
  156. enum {STRING_REQUEST, STRING_DATA, STRING_CLIENT_ADDR,
  157. STRING_SYS_REQUEST_SERVER_REQUEST};
  158. static const char *strings[] = {
  159. "_request", "data", "client_addr",
  160. "sys.request_server.request", NULL
  161. };
  162. static void listener_handler (struct instance *o)
  163. {
  164. ASSERT(!o->dying)
  165. BReactor *reactor = o->i->params->iparams->reactor;
  166. BPendingGroup *pg = BReactor_PendingGroup(reactor);
  167. struct connection *c = malloc(sizeof(*c));
  168. if (!c) {
  169. ModuleLog(o->i, BLOG_ERROR, "malloc failed");
  170. goto fail0;
  171. }
  172. c->inst = o;
  173. LinkedList0_Prepend(&o->connections_list, &c->connections_list_node);
  174. if (!BConnection_Init(&c->con, BConnection_source_listener(&o->listener, &c->addr), reactor, c, (BConnection_handler)connection_con_handler)) {
  175. ModuleLog(o->i, BLOG_ERROR, "BConnection_Init failed");
  176. goto fail1;
  177. }
  178. BConnection_SendAsync_Init(&c->con);
  179. BConnection_RecvAsync_Init(&c->con);
  180. StreamPassInterface *con_send_if = BConnection_SendAsync_GetIf(&c->con);
  181. StreamRecvInterface *con_recv_if = BConnection_RecvAsync_GetIf(&c->con);
  182. PacketPassInterface_Init(&c->recv_if, RECV_MTU, (PacketPassInterface_handler_send)connection_recv_if_handler_send, c, pg);
  183. if (!PacketProtoDecoder_Init(&c->recv_decoder, con_recv_if, &c->recv_if, pg, c, (PacketProtoDecoder_handler_error)connection_recv_decoder_handler_error)) {
  184. ModuleLog(o->i, BLOG_ERROR, "PacketProtoDecoder_Init failed");
  185. goto fail2;
  186. }
  187. PacketStreamSender_Init(&c->send_pss, con_send_if, PACKETPROTO_ENCLEN(SEND_MTU), pg);
  188. PacketPassFifoQueue_Init(&c->send_queue, PacketStreamSender_GetInput(&c->send_pss), pg);
  189. LinkedList0_Init(&c->requests_list);
  190. LinkedList0_Init(&c->replies_list);
  191. c->state = CONNECTION_STATE_RUNNING;
  192. ModuleLog(o->i, BLOG_INFO, "connection initialized");
  193. return;
  194. fail2:
  195. PacketPassInterface_Free(&c->recv_if);
  196. BConnection_RecvAsync_Free(&c->con);
  197. BConnection_SendAsync_Free(&c->con);
  198. BConnection_Free(&c->con);
  199. fail1:
  200. LinkedList0_Remove(&o->connections_list, &c->connections_list_node);
  201. free(c);
  202. fail0:
  203. return;
  204. }
  205. static void connection_free (struct connection *c)
  206. {
  207. struct instance *o = c->inst;
  208. ASSERT(c->state == CONNECTION_STATE_TERMINATING)
  209. ASSERT(LinkedList0_IsEmpty(&c->requests_list))
  210. ASSERT(LinkedList0_IsEmpty(&c->replies_list))
  211. LinkedList0_Remove(&o->connections_list, &c->connections_list_node);
  212. free(c);
  213. }
  214. static void connection_free_link (struct connection *c)
  215. {
  216. PacketPassFifoQueue_PrepareFree(&c->send_queue);
  217. LinkedList0Node *ln;
  218. while (ln = LinkedList0_GetFirst(&c->replies_list)) {
  219. struct reply *r = UPPER_OBJECT(ln, struct reply, replies_list_node);
  220. ASSERT(r->con == c)
  221. reply_free(r);
  222. }
  223. PacketPassFifoQueue_Free(&c->send_queue);
  224. PacketStreamSender_Free(&c->send_pss);
  225. PacketProtoDecoder_Free(&c->recv_decoder);
  226. PacketPassInterface_Free(&c->recv_if);
  227. BConnection_RecvAsync_Free(&c->con);
  228. BConnection_SendAsync_Free(&c->con);
  229. BConnection_Free(&c->con);
  230. }
  231. static void connection_terminate (struct connection *c)
  232. {
  233. ASSERT(c->state == CONNECTION_STATE_RUNNING)
  234. for (LinkedList0Node *ln = LinkedList0_GetFirst(&c->requests_list); ln; ln = LinkedList0Node_Next(ln)) {
  235. struct request *r = UPPER_OBJECT(ln, struct request, requests_list_node);
  236. if (!r->terminating) {
  237. request_terminate(r);
  238. }
  239. }
  240. connection_free_link(c);
  241. c->state = CONNECTION_STATE_TERMINATING;
  242. if (LinkedList0_IsEmpty(&c->requests_list)) {
  243. connection_free(c);
  244. return;
  245. }
  246. }
  247. static void connection_con_handler (struct connection *c, int event)
  248. {
  249. struct instance *o = c->inst;
  250. ASSERT(c->state == CONNECTION_STATE_RUNNING)
  251. ModuleLog(o->i, BLOG_INFO, "connection closed");
  252. connection_terminate(c);
  253. }
  254. static void connection_recv_decoder_handler_error (struct connection *c)
  255. {
  256. struct instance *o = c->inst;
  257. ASSERT(c->state == CONNECTION_STATE_RUNNING)
  258. ModuleLog(o->i, BLOG_ERROR, "decoder error");
  259. connection_terminate(c);
  260. }
  261. static void connection_recv_if_handler_send (struct connection *c, uint8_t *data, int data_len)
  262. {
  263. struct instance *o = c->inst;
  264. ASSERT(c->state == CONNECTION_STATE_RUNNING)
  265. ASSERT(data_len >= 0)
  266. ASSERT(data_len <= RECV_MTU)
  267. PacketPassInterface_Done(&c->recv_if);
  268. if (data_len < sizeof(struct requestproto_header)) {
  269. ModuleLog(o->i, BLOG_ERROR, "missing requestproto header");
  270. goto fail;
  271. }
  272. struct requestproto_header header;
  273. memcpy(&header, data, sizeof(header));
  274. uint32_t request_id = ltoh32(header.request_id);
  275. uint32_t type = ltoh32(header.type);
  276. switch (type) {
  277. case REQUESTPROTO_TYPE_CLIENT_REQUEST: {
  278. if (find_request(c, request_id)) {
  279. ModuleLog(o->i, BLOG_ERROR, "request with the same ID already exists");
  280. goto fail;
  281. }
  282. if (!request_init(c, request_id, data + sizeof(header), data_len - sizeof(header))) {
  283. goto fail;
  284. }
  285. } break;
  286. case REQUESTPROTO_TYPE_CLIENT_ABORT: {
  287. struct request *r = find_request(c, request_id);
  288. if (!r) {
  289. // this is expected if we finish before we get the abort
  290. return;
  291. }
  292. if (!r->terminating) {
  293. request_terminate(r);
  294. }
  295. } break;
  296. default:
  297. ModuleLog(o->i, BLOG_ERROR, "invalid requestproto type");
  298. goto fail;
  299. }
  300. return;
  301. fail:
  302. connection_terminate(c);
  303. }
  304. static int request_init (struct connection *c, uint32_t request_id, const uint8_t *data, int data_len)
  305. {
  306. struct instance *o = c->inst;
  307. ASSERT(c->state == CONNECTION_STATE_RUNNING)
  308. ASSERT(!find_request(c, request_id))
  309. ASSERT(data_len >= 0)
  310. ASSERT(data_len <= RECV_PAYLOAD_MTU)
  311. struct request *r = malloc(sizeof(*r));
  312. if (!r) {
  313. ModuleLog(o->i, BLOG_ERROR, "malloc failed");
  314. goto fail0;
  315. }
  316. r->con = c;
  317. r->request_id = request_id;
  318. LinkedList0_Prepend(&c->requests_list, &r->requests_list_node);
  319. NCDValMem_Init(&r->request_data_mem);
  320. if (!NCDValParser_Parse((const char *)data, data_len, &r->request_data_mem, &r->request_data)) {
  321. ModuleLog(o->i, BLOG_ERROR, "NCDValParser_Parse failed");
  322. goto fail1;
  323. }
  324. if (!(r->end_reply = reply_init(c, request_id, NCDVal_NewInvalid()))) {
  325. goto fail1;
  326. }
  327. if (!NCDModuleProcess_InitValue(&r->process, o->i, o->request_handler_template, o->args, request_process_handler_event)) {
  328. ModuleLog(o->i, BLOG_ERROR, "NCDModuleProcess_Init failed");
  329. goto fail3;
  330. }
  331. NCDModuleProcess_SetSpecialFuncs(&r->process, request_process_func_getspecialobj);
  332. r->terminating = 0;
  333. r->got_finished = 0;
  334. ModuleLog(o->i, BLOG_INFO, "request initialized");
  335. return 1;
  336. fail3:
  337. reply_free(r->end_reply);
  338. fail1:
  339. NCDValMem_Free(&r->request_data_mem);
  340. LinkedList0_Remove(&c->requests_list, &r->requests_list_node);
  341. free(r);
  342. fail0:
  343. return 0;
  344. }
  345. static void request_free (struct request *r)
  346. {
  347. struct connection *c = r->con;
  348. NCDModuleProcess_AssertFree(&r->process);
  349. if (c->state != CONNECTION_STATE_TERMINATING) {
  350. uint32_t type = r->got_finished ? REQUESTPROTO_TYPE_SERVER_FINISHED : REQUESTPROTO_TYPE_SERVER_ERROR;
  351. reply_start(r->end_reply, type);
  352. }
  353. NCDModuleProcess_Free(&r->process);
  354. NCDValMem_Free(&r->request_data_mem);
  355. LinkedList0_Remove(&c->requests_list, &r->requests_list_node);
  356. free(r);
  357. }
  358. static struct request * find_request (struct connection *c, uint32_t request_id)
  359. {
  360. for (LinkedList0Node *ln = LinkedList0_GetFirst(&c->requests_list); ln; ln = LinkedList0Node_Next(ln)) {
  361. struct request *r = UPPER_OBJECT(ln, struct request, requests_list_node);
  362. if (!r->terminating && r->request_id == request_id) {
  363. return r;
  364. }
  365. }
  366. return NULL;
  367. }
  368. static void request_process_handler_event (NCDModuleProcess *process, int event)
  369. {
  370. struct request *r = UPPER_OBJECT(process, struct request, process);
  371. struct connection *c = r->con;
  372. struct instance *o = c->inst;
  373. switch (event) {
  374. case NCDMODULEPROCESS_EVENT_UP: {
  375. ASSERT(!r->terminating)
  376. } break;
  377. case NCDMODULEPROCESS_EVENT_DOWN: {
  378. ASSERT(!r->terminating)
  379. NCDModuleProcess_Continue(&r->process);
  380. } break;
  381. case NCDMODULEPROCESS_EVENT_TERMINATED: {
  382. ASSERT(r->terminating)
  383. request_free(r);
  384. if (c->state == CONNECTION_STATE_TERMINATING && LinkedList0_IsEmpty(&c->requests_list)) {
  385. connection_free(c);
  386. if (o->dying && LinkedList0_IsEmpty(&o->connections_list)) {
  387. instance_free(o);
  388. return;
  389. }
  390. }
  391. } break;
  392. default: ASSERT(0);
  393. }
  394. }
  395. static int request_process_func_getspecialobj (NCDModuleProcess *process, NCD_string_id_t name, NCDObject *out_object)
  396. {
  397. struct request *r = UPPER_OBJECT(process, struct request, process);
  398. if (name == NCD_STRING_CALLER) {
  399. *out_object = NCDObject_Build(-1, r, NCDObject_no_getvar, request_process_caller_obj_func_getobj);
  400. return 1;
  401. }
  402. if (name == ModuleString(r->con->inst->i, STRING_REQUEST)) {
  403. *out_object = NCDObject_Build(ModuleString(r->con->inst->i, STRING_SYS_REQUEST_SERVER_REQUEST), r, request_process_request_obj_func_getvar, NCDObject_no_getobj);
  404. return 1;
  405. }
  406. return 0;
  407. }
  408. static int request_process_caller_obj_func_getobj (const NCDObject *obj, NCD_string_id_t name, NCDObject *out_object)
  409. {
  410. struct request *r = NCDObject_DataPtr(obj);
  411. return NCDModuleInst_Backend_GetObj(r->con->inst->i, name, out_object);
  412. }
  413. static int request_process_request_obj_func_getvar (const NCDObject *obj, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  414. {
  415. struct request *r = NCDObject_DataPtr(obj);
  416. if (name == ModuleString(r->con->inst->i, STRING_DATA)) {
  417. *out = NCDVal_NewCopy(mem, r->request_data);
  418. return 1;
  419. }
  420. if (name == ModuleString(r->con->inst->i, STRING_CLIENT_ADDR)) {
  421. *out = ncd_make_baddr(r->con->addr, mem);
  422. return 1;
  423. }
  424. return 0;
  425. }
  426. static void request_terminate (struct request *r)
  427. {
  428. ASSERT(!r->terminating)
  429. NCDModuleProcess_Terminate(&r->process);
  430. r->terminating = 1;
  431. }
  432. static struct reply * reply_init (struct connection *c, uint32_t request_id, NCDValRef reply_data)
  433. {
  434. struct instance *o = c->inst;
  435. ASSERT(c->state == CONNECTION_STATE_RUNNING)
  436. NCDVal_Assert(reply_data);
  437. struct reply *r = malloc(sizeof(*r));
  438. if (!r) {
  439. ModuleLog(o->i, BLOG_ERROR, "malloc failed");
  440. goto fail0;
  441. }
  442. r->con = c;
  443. LinkedList0_Prepend(&c->replies_list, &r->replies_list_node);
  444. PacketPassFifoQueueFlow_Init(&r->send_qflow, &c->send_queue);
  445. r->send_qflow_if = PacketPassFifoQueueFlow_GetInput(&r->send_qflow);
  446. PacketPassInterface_Sender_Init(r->send_qflow_if, (PacketPassInterface_handler_done)reply_send_qflow_if_handler_done, r);
  447. ExpString str;
  448. if (!ExpString_Init(&str)) {
  449. ModuleLog(o->i, BLOG_ERROR, "ExpString_Init failed");
  450. goto fail1;
  451. }
  452. if (!ExpString_AppendZeros(&str, sizeof(struct packetproto_header) + sizeof(struct requestproto_header))) {
  453. ModuleLog(o->i, BLOG_ERROR, "ExpString_AppendZeros failed");
  454. goto fail2;
  455. }
  456. if (!NCDVal_IsInvalid(reply_data) && !NCDValGenerator_AppendGenerate(reply_data, &str)) {
  457. ModuleLog(o->i, BLOG_ERROR, "NCDValGenerator_AppendGenerate failed");
  458. goto fail2;
  459. }
  460. size_t len = ExpString_Length(&str);
  461. if (len > INT_MAX || len > PACKETPROTO_ENCLEN(SEND_MTU) || len - sizeof(struct packetproto_header) > UINT16_MAX) {
  462. ModuleLog(o->i, BLOG_ERROR, "reply is too long");
  463. goto fail2;
  464. }
  465. r->send_buf = (uint8_t *)ExpString_Get(&str);
  466. struct packetproto_header pp;
  467. pp.len = htol16(len - sizeof(pp));
  468. struct requestproto_header rp;
  469. rp.request_id = htol32(request_id);
  470. memcpy(r->send_buf, &pp, sizeof(pp));
  471. memcpy(r->send_buf + sizeof(pp), &rp, sizeof(rp));
  472. return r;
  473. fail2:
  474. ExpString_Free(&str);
  475. fail1:
  476. PacketPassFifoQueueFlow_Free(&r->send_qflow);
  477. LinkedList0_Remove(&c->replies_list, &r->replies_list_node);
  478. free(r);
  479. fail0:
  480. return NULL;
  481. }
  482. static void reply_start (struct reply *r, uint32_t type)
  483. {
  484. struct requestproto_header rp;
  485. memcpy(&rp, r->send_buf + sizeof(struct packetproto_header), sizeof(rp));
  486. rp.type = htol32(type);
  487. memcpy(r->send_buf + sizeof(struct packetproto_header), &rp, sizeof(rp));
  488. struct packetproto_header pp;
  489. memcpy(&pp, r->send_buf, sizeof(pp));
  490. int len = ltoh16(pp.len) + sizeof(struct packetproto_header);
  491. PacketPassInterface_Sender_Send(r->send_qflow_if, r->send_buf, len);
  492. }
  493. static void reply_free (struct reply *r)
  494. {
  495. struct connection *c = r->con;
  496. PacketPassFifoQueueFlow_AssertFree(&r->send_qflow);
  497. free(r->send_buf);
  498. PacketPassFifoQueueFlow_Free(&r->send_qflow);
  499. LinkedList0_Remove(&c->replies_list, &r->replies_list_node);
  500. free(r);
  501. }
  502. static void reply_send_qflow_if_handler_done (struct reply *r)
  503. {
  504. reply_free(r);
  505. }
  506. static void func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  507. {
  508. struct instance *o = vo;
  509. o->i = i;
  510. // check arguments
  511. NCDValRef listen_addr_arg;
  512. NCDValRef request_handler_template_arg;
  513. NCDValRef args_arg;
  514. if (!NCDVal_ListRead(params->args, 3, &listen_addr_arg, &request_handler_template_arg, &args_arg)) {
  515. ModuleLog(o->i, BLOG_ERROR, "wrong arity");
  516. goto fail0;
  517. }
  518. if (!NCDVal_IsString(request_handler_template_arg) || !NCDVal_IsList(args_arg)) {
  519. ModuleLog(o->i, BLOG_ERROR, "wrong type");
  520. goto fail0;
  521. }
  522. o->request_handler_template = request_handler_template_arg;
  523. o->args = args_arg;
  524. // read listen address
  525. struct BConnection_addr addr;
  526. if (!ncd_read_bconnection_addr(listen_addr_arg, &addr)) {
  527. ModuleLog(o->i, BLOG_ERROR, "wrong listen address");
  528. goto fail0;
  529. }
  530. // init listener
  531. if (!BListener_InitGeneric(&o->listener, addr, i->params->iparams->reactor, o, (BListener_handler)listener_handler)) {
  532. ModuleLog(o->i, BLOG_ERROR, "BListener_InitGeneric failed");
  533. goto fail0;
  534. }
  535. // init connections list
  536. LinkedList0_Init(&o->connections_list);
  537. // set not dying
  538. o->dying = 0;
  539. // signal up
  540. NCDModuleInst_Backend_Up(i);
  541. return;
  542. fail0:
  543. NCDModuleInst_Backend_DeadError(i);
  544. }
  545. static void instance_free (struct instance *o)
  546. {
  547. ASSERT(o->dying)
  548. ASSERT(LinkedList0_IsEmpty(&o->connections_list))
  549. NCDModuleInst_Backend_Dead(o->i);
  550. }
  551. static void func_die (void *vo)
  552. {
  553. struct instance *o = vo;
  554. ASSERT(!o->dying)
  555. // free listener
  556. BListener_Free(&o->listener);
  557. // terminate connections
  558. LinkedList0Node *next_ln;
  559. for (LinkedList0Node *ln = LinkedList0_GetFirst(&o->connections_list); ln && (next_ln = LinkedList0Node_Next(ln)), ln; ln = next_ln) {
  560. struct connection *c = UPPER_OBJECT(ln, struct connection, connections_list_node);
  561. ASSERT(c->inst == o)
  562. if (c->state != CONNECTION_STATE_TERMINATING) {
  563. connection_terminate(c);
  564. }
  565. }
  566. // set dying
  567. o->dying = 1;
  568. // if no connections, die right away
  569. if (LinkedList0_IsEmpty(&o->connections_list)) {
  570. instance_free(o);
  571. return;
  572. }
  573. }
  574. static void reply_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  575. {
  576. NCDValRef reply_data;
  577. if (!NCDVal_ListRead(params->args, 1, &reply_data)) {
  578. ModuleLog(i, BLOG_ERROR, "wrong arity");
  579. goto fail;
  580. }
  581. NCDModuleInst_Backend_Up(i);
  582. struct request *r = params->method_user;
  583. struct connection *c = r->con;
  584. if (r->terminating) {
  585. ModuleLog(i, BLOG_ERROR, "request is dying, cannot submit reply");
  586. goto fail;
  587. }
  588. struct reply *rpl = reply_init(c, r->request_id, reply_data);
  589. if (!rpl) {
  590. ModuleLog(i, BLOG_ERROR, "failed to submit reply");
  591. goto fail;
  592. }
  593. reply_start(rpl, REQUESTPROTO_TYPE_SERVER_REPLY);
  594. return;
  595. fail:
  596. NCDModuleInst_Backend_DeadError(i);
  597. }
  598. static void finish_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  599. {
  600. if (!NCDVal_ListRead(params->args, 0)) {
  601. ModuleLog(i, BLOG_ERROR, "wrong arity");
  602. goto fail;
  603. }
  604. NCDModuleInst_Backend_Up(i);
  605. struct request *r = params->method_user;
  606. if (r->terminating) {
  607. ModuleLog(i, BLOG_ERROR, "request is dying, cannot submit finished");
  608. goto fail;
  609. }
  610. r->got_finished = 1;
  611. request_terminate(r);
  612. return;
  613. fail:
  614. NCDModuleInst_Backend_DeadError(i);
  615. }
  616. static struct NCDModule modules[] = {
  617. {
  618. .type = "sys.request_server",
  619. .func_new2 = func_new,
  620. .func_die = func_die,
  621. .alloc_size = sizeof(struct instance)
  622. }, {
  623. .type = "sys.request_server.request::reply",
  624. .func_new2 = reply_func_new
  625. }, {
  626. .type = "sys.request_server.request::finish",
  627. .func_new2 = finish_func_new
  628. }, {
  629. .type = NULL
  630. }
  631. };
  632. const struct NCDModuleGroup ncdmodule_sys_request_server = {
  633. .modules = modules,
  634. .strings = strings
  635. };