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