sys_request_server.c 25 KB

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