sys_request_server.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  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/value_utils.h>
  87. #include <ncd/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 (struct request *r, 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, (NCDObject_func_getvar)request_process_request_obj_func_getvar, NULL);
  398. return 1;
  399. }
  400. return 0;
  401. }
  402. static int request_process_request_obj_func_getvar (struct request *r, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  403. {
  404. struct instance *o = r->con->inst;
  405. if (name == strings[STRING_DATA].id) {
  406. *out = NCDVal_NewCopy(mem, r->request_data);
  407. if (NCDVal_IsInvalid(*out)) {
  408. ModuleLog(o->i, BLOG_ERROR, "NCDVal_NewCopy failed");
  409. }
  410. return 1;
  411. }
  412. if (name == strings[STRING_CLIENT_ADDR].id) {
  413. *out = ncd_make_baddr(r->con->addr, mem);
  414. if (NCDVal_IsInvalid(*out)) {
  415. ModuleLog(o->i, BLOG_ERROR, "ncd_make_baddr failed");
  416. }
  417. return 1;
  418. }
  419. return 0;
  420. }
  421. static void request_terminate (struct request *r)
  422. {
  423. ASSERT(!r->terminating)
  424. NCDModuleProcess_Terminate(&r->process);
  425. r->terminating = 1;
  426. }
  427. static struct reply * reply_init (struct connection *c, uint32_t request_id, NCDValRef reply_data)
  428. {
  429. struct instance *o = c->inst;
  430. ASSERT(c->state == CONNECTION_STATE_RUNNING)
  431. NCDVal_Assert(reply_data);
  432. struct reply *r = malloc(sizeof(*r));
  433. if (!r) {
  434. ModuleLog(o->i, BLOG_ERROR, "malloc failed");
  435. goto fail0;
  436. }
  437. r->con = c;
  438. LinkedList0_Prepend(&c->replies_list, &r->replies_list_node);
  439. PacketPassFifoQueueFlow_Init(&r->send_qflow, &c->send_queue);
  440. r->send_qflow_if = PacketPassFifoQueueFlow_GetInput(&r->send_qflow);
  441. PacketPassInterface_Sender_Init(r->send_qflow_if, (PacketPassInterface_handler_done)reply_send_qflow_if_handler_done, r);
  442. struct reply_header {
  443. struct packetproto_header pp;
  444. struct requestproto_header rp;
  445. } __attribute__((packed));
  446. ExpString str;
  447. if (!ExpString_Init(&str)) {
  448. ModuleLog(o->i, BLOG_ERROR, "ExpString_Init failed");
  449. goto fail1;
  450. }
  451. if (!ExpString_AppendZeros(&str, sizeof(struct reply_header))) {
  452. ModuleLog(o->i, BLOG_ERROR, "ExpString_AppendZeros failed");
  453. goto fail2;
  454. }
  455. if (!NCDVal_IsInvalid(reply_data) && !NCDValGenerator_AppendGenerate(reply_data, &str)) {
  456. ModuleLog(o->i, BLOG_ERROR, "NCDValGenerator_AppendGenerate failed");
  457. goto fail2;
  458. }
  459. size_t len = ExpString_Length(&str);
  460. if (len > INT_MAX || len > PACKETPROTO_ENCLEN(SEND_MTU) || len - sizeof(struct packetproto_header) > UINT16_MAX) {
  461. ModuleLog(o->i, BLOG_ERROR, "reply is too long");
  462. goto fail2;
  463. }
  464. r->send_buf = (uint8_t *)ExpString_Get(&str);
  465. struct reply_header *header = (void *)r->send_buf;
  466. header->pp.len = htol16(len - sizeof(header->pp));
  467. header->rp.request_id = htol32(request_id);
  468. return r;
  469. fail2:
  470. ExpString_Free(&str);
  471. fail1:
  472. PacketPassFifoQueueFlow_Free(&r->send_qflow);
  473. LinkedList0_Remove(&c->replies_list, &r->replies_list_node);
  474. free(r);
  475. fail0:
  476. return NULL;
  477. }
  478. static void reply_start (struct reply *r, uint32_t type)
  479. {
  480. struct reply_header {
  481. struct packetproto_header pp;
  482. struct requestproto_header rp;
  483. } __attribute__((packed));
  484. struct reply_header *header = (void *)r->send_buf;
  485. header->rp.type = htol32(type);
  486. int len = ltoh16(header->pp.len) + sizeof(struct packetproto_header);
  487. PacketPassInterface_Sender_Send(r->send_qflow_if, r->send_buf, len);
  488. }
  489. static void reply_free (struct reply *r)
  490. {
  491. struct connection *c = r->con;
  492. PacketPassFifoQueueFlow_AssertFree(&r->send_qflow);
  493. free(r->send_buf);
  494. PacketPassFifoQueueFlow_Free(&r->send_qflow);
  495. LinkedList0_Remove(&c->replies_list, &r->replies_list_node);
  496. free(r);
  497. }
  498. static void reply_send_qflow_if_handler_done (struct reply *r)
  499. {
  500. reply_free(r);
  501. }
  502. static void func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  503. {
  504. struct instance *o = vo;
  505. o->i = i;
  506. // check arguments
  507. NCDValRef listen_addr_arg;
  508. NCDValRef request_handler_template_arg;
  509. NCDValRef args_arg;
  510. if (!NCDVal_ListRead(params->args, 3, &listen_addr_arg, &request_handler_template_arg, &args_arg)) {
  511. ModuleLog(o->i, BLOG_ERROR, "wrong arity");
  512. goto fail0;
  513. }
  514. if (!NCDVal_IsString(request_handler_template_arg) || !NCDVal_IsList(args_arg)) {
  515. ModuleLog(o->i, BLOG_ERROR, "wrong type");
  516. goto fail0;
  517. }
  518. o->request_handler_template = request_handler_template_arg;
  519. o->args = args_arg;
  520. // read listen address
  521. struct BConnection_addr addr;
  522. if (!ncd_read_bconnection_addr(listen_addr_arg, &addr)) {
  523. ModuleLog(o->i, BLOG_ERROR, "wrong listen address");
  524. goto fail0;
  525. }
  526. // init listener
  527. if (!BListener_InitGeneric(&o->listener, addr, i->params->iparams->reactor, o, (BListener_handler)listener_handler)) {
  528. ModuleLog(o->i, BLOG_ERROR, "BListener_InitGeneric failed");
  529. goto fail0;
  530. }
  531. // init connections list
  532. LinkedList0_Init(&o->connections_list);
  533. // set not dying
  534. o->dying = 0;
  535. // signal up
  536. NCDModuleInst_Backend_Up(i);
  537. return;
  538. fail0:
  539. NCDModuleInst_Backend_SetError(i);
  540. NCDModuleInst_Backend_Dead(i);
  541. }
  542. static void instance_free (struct instance *o)
  543. {
  544. ASSERT(o->dying)
  545. ASSERT(LinkedList0_IsEmpty(&o->connections_list))
  546. NCDModuleInst_Backend_Dead(o->i);
  547. }
  548. static void func_die (void *vo)
  549. {
  550. struct instance *o = vo;
  551. ASSERT(!o->dying)
  552. // free listener
  553. BListener_Free(&o->listener);
  554. // terminate connections
  555. LinkedList0Node *next_ln;
  556. for (LinkedList0Node *ln = LinkedList0_GetFirst(&o->connections_list); ln && (next_ln = LinkedList0Node_Next(ln)), ln; ln = next_ln) {
  557. struct connection *c = UPPER_OBJECT(ln, struct connection, connections_list_node);
  558. ASSERT(c->inst == o)
  559. if (c->state != CONNECTION_STATE_TERMINATING) {
  560. connection_terminate(c);
  561. }
  562. }
  563. // set dying
  564. o->dying = 1;
  565. // if no connections, die right away
  566. if (LinkedList0_IsEmpty(&o->connections_list)) {
  567. instance_free(o);
  568. return;
  569. }
  570. }
  571. static void reply_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  572. {
  573. NCDValRef reply_data;
  574. if (!NCDVal_ListRead(params->args, 1, &reply_data)) {
  575. ModuleLog(i, BLOG_ERROR, "wrong arity");
  576. goto fail;
  577. }
  578. NCDModuleInst_Backend_Up(i);
  579. struct request *r = params->method_user;
  580. struct connection *c = r->con;
  581. if (r->terminating) {
  582. ModuleLog(i, BLOG_ERROR, "request is dying, cannot submit reply");
  583. goto fail;
  584. }
  585. struct reply *rpl = reply_init(c, r->request_id, reply_data);
  586. if (!rpl) {
  587. ModuleLog(i, BLOG_ERROR, "failed to submit reply");
  588. goto fail;
  589. }
  590. reply_start(rpl, REQUESTPROTO_TYPE_SERVER_REPLY);
  591. return;
  592. fail:
  593. NCDModuleInst_Backend_SetError(i);
  594. NCDModuleInst_Backend_Dead(i);
  595. }
  596. static void finish_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  597. {
  598. if (!NCDVal_ListRead(params->args, 0)) {
  599. ModuleLog(i, BLOG_ERROR, "wrong arity");
  600. goto fail;
  601. }
  602. NCDModuleInst_Backend_Up(i);
  603. struct request *r = params->method_user;
  604. if (r->terminating) {
  605. ModuleLog(i, BLOG_ERROR, "request is dying, cannot submit finished");
  606. goto fail;
  607. }
  608. r->got_finished = 1;
  609. request_terminate(r);
  610. return;
  611. fail:
  612. NCDModuleInst_Backend_SetError(i);
  613. NCDModuleInst_Backend_Dead(i);
  614. }
  615. static struct NCDModule modules[] = {
  616. {
  617. .type = "sys.request_server",
  618. .func_new2 = func_new,
  619. .func_die = func_die,
  620. .alloc_size = sizeof(struct instance)
  621. }, {
  622. .type = "sys.request_server.request::reply",
  623. .func_new2 = reply_func_new
  624. }, {
  625. .type = "sys.request_server.request::finish",
  626. .func_new2 = finish_func_new
  627. }, {
  628. .type = NULL
  629. }
  630. };
  631. const struct NCDModuleGroup ncdmodule_sys_request_server = {
  632. .modules = modules,
  633. .strings = strings
  634. };