sys_request_server.c 24 KB

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