sys_request_server.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  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 argument must be one of:
  49. * - {"unix", socket_path}
  50. * Listens on a Unix socket.
  51. * - {"tcp", ip_address, port_number}
  52. * Listens on a TCP socket. The address must be numeric and not a name.
  53. * For IPv6, the address must be enclosed in [].
  54. *
  55. * Predefined variables in request_handler_template:
  56. * _request.data - the request payload as sent by the client
  57. * _request.client_addr_type - type of client address; "none", "ipv4" or "ipv6"
  58. * _request.client_addr - client IP address. IPv4 addresses are standard dotted-decimal
  59. * without leading zeros, e.g. "14.6.0.251". IPv6 addresses are full 8
  60. * lower-case-hexadecimal numbers separated by 7 colons, without leading zeros,
  61. * e.g. "61:71a4:81f:98aa:57:0:5efa:17". If client_addr_type=="none", this too
  62. * is "none".
  63. *
  64. * Synopsis:
  65. * sys.request_server.request::reply(reply_data)
  66. *
  67. * Synopsis:
  68. * sys.request_server.request::finish()
  69. */
  70. #include <stdlib.h>
  71. #include <string.h>
  72. #include <limits.h>
  73. #include <inttypes.h>
  74. #include <unistd.h>
  75. #include <errno.h>
  76. #include <misc/offset.h>
  77. #include <misc/debug.h>
  78. #include <misc/byteorder.h>
  79. #include <misc/parse_number.h>
  80. #include <protocol/packetproto.h>
  81. #include <protocol/requestproto.h>
  82. #include <structure/LinkedList0.h>
  83. #include <system/BConnection.h>
  84. #include <system/BAddr.h>
  85. #include <flow/PacketProtoDecoder.h>
  86. #include <flow/PacketStreamSender.h>
  87. #include <flow/PacketPassFifoQueue.h>
  88. #include <ncd/NCDValueParser.h>
  89. #include <ncd/NCDValueGenerator.h>
  90. #include <ncd/NCDModule.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 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. const char *unix_socket_path;
  100. const char *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 (struct request *r, int event);
  151. static int request_process_func_getspecialobj (struct request *r, const char *name, NCDObject *out_object);
  152. static int request_process_request_obj_func_getvar (struct request *r, const char *name, NCDValMem *mem, NCDValRef *out_value);
  153. static void request_terminate (struct request *r);
  154. static struct reply * reply_init (struct connection *c, uint32_t request_id, NCDValRef reply_data);
  155. static void reply_start (struct reply *r, uint32_t type);
  156. static void reply_free (struct reply *r);
  157. static void reply_send_qflow_if_handler_done (struct reply *r);
  158. static int init_listen (struct instance *o, NCDValRef listen_addr_arg);
  159. static void instance_free (struct instance *o);
  160. static void listener_handler (struct instance *o)
  161. {
  162. ASSERT(!o->dying)
  163. BReactor *reactor = o->i->iparams->reactor;
  164. BPendingGroup *pg = BReactor_PendingGroup(reactor);
  165. struct connection *c = malloc(sizeof(*c));
  166. if (!c) {
  167. ModuleLog(o->i, BLOG_ERROR, "malloc failed");
  168. goto fail0;
  169. }
  170. c->inst = o;
  171. LinkedList0_Prepend(&o->connections_list, &c->connections_list_node);
  172. if (!BConnection_Init(&c->con, BConnection_source_listener(&o->listener, &c->addr), reactor, c, (BConnection_handler)connection_con_handler)) {
  173. ModuleLog(o->i, BLOG_ERROR, "BConnection_Init failed");
  174. goto fail1;
  175. }
  176. BConnection_SendAsync_Init(&c->con);
  177. BConnection_RecvAsync_Init(&c->con);
  178. StreamPassInterface *con_send_if = BConnection_SendAsync_GetIf(&c->con);
  179. StreamRecvInterface *con_recv_if = BConnection_RecvAsync_GetIf(&c->con);
  180. PacketPassInterface_Init(&c->recv_if, RECV_MTU, (PacketPassInterface_handler_send)connection_recv_if_handler_send, c, pg);
  181. if (!PacketProtoDecoder_Init(&c->recv_decoder, con_recv_if, &c->recv_if, pg, c, (PacketProtoDecoder_handler_error)connection_recv_decoder_handler_error)) {
  182. ModuleLog(o->i, BLOG_ERROR, "PacketProtoDecoder_Init failed");
  183. goto fail2;
  184. }
  185. PacketStreamSender_Init(&c->send_pss, con_send_if, PACKETPROTO_ENCLEN(SEND_MTU), pg);
  186. PacketPassFifoQueue_Init(&c->send_queue, PacketStreamSender_GetInput(&c->send_pss), pg);
  187. LinkedList0_Init(&c->requests_list);
  188. LinkedList0_Init(&c->replies_list);
  189. c->state = CONNECTION_STATE_RUNNING;
  190. ModuleLog(o->i, BLOG_INFO, "connection initialized");
  191. return;
  192. fail3:
  193. PacketStreamSender_Free(&c->send_pss);
  194. PacketProtoDecoder_Free(&c->recv_decoder);
  195. fail2:
  196. PacketPassInterface_Free(&c->recv_if);
  197. BConnection_RecvAsync_Free(&c->con);
  198. BConnection_SendAsync_Free(&c->con);
  199. BConnection_Free(&c->con);
  200. fail1:
  201. LinkedList0_Remove(&o->connections_list, &c->connections_list_node);
  202. free(c);
  203. fail0:
  204. return;
  205. }
  206. static void connection_free (struct connection *c)
  207. {
  208. struct instance *o = c->inst;
  209. ASSERT(c->state == CONNECTION_STATE_TERMINATING)
  210. ASSERT(LinkedList0_IsEmpty(&c->requests_list))
  211. ASSERT(LinkedList0_IsEmpty(&c->replies_list))
  212. LinkedList0_Remove(&o->connections_list, &c->connections_list_node);
  213. free(c);
  214. }
  215. static void connection_free_link (struct connection *c)
  216. {
  217. PacketPassFifoQueue_PrepareFree(&c->send_queue);
  218. LinkedList0Node *ln;
  219. while (ln = LinkedList0_GetFirst(&c->replies_list)) {
  220. struct reply *r = UPPER_OBJECT(ln, struct reply, replies_list_node);
  221. ASSERT(r->con == c)
  222. reply_free(r);
  223. }
  224. PacketPassFifoQueue_Free(&c->send_queue);
  225. PacketStreamSender_Free(&c->send_pss);
  226. PacketProtoDecoder_Free(&c->recv_decoder);
  227. PacketPassInterface_Free(&c->recv_if);
  228. BConnection_RecvAsync_Free(&c->con);
  229. BConnection_SendAsync_Free(&c->con);
  230. BConnection_Free(&c->con);
  231. }
  232. static void connection_terminate (struct connection *c)
  233. {
  234. ASSERT(c->state == CONNECTION_STATE_RUNNING)
  235. for (LinkedList0Node *ln = LinkedList0_GetFirst(&c->requests_list); ln; ln = LinkedList0Node_Next(ln)) {
  236. struct request *r = UPPER_OBJECT(ln, struct request, requests_list_node);
  237. if (!r->terminating) {
  238. request_terminate(r);
  239. }
  240. }
  241. connection_free_link(c);
  242. c->state = CONNECTION_STATE_TERMINATING;
  243. if (LinkedList0_IsEmpty(&c->requests_list)) {
  244. connection_free(c);
  245. return;
  246. }
  247. }
  248. static void connection_con_handler (struct connection *c, int event)
  249. {
  250. struct instance *o = c->inst;
  251. ASSERT(c->state == CONNECTION_STATE_RUNNING)
  252. ModuleLog(o->i, BLOG_INFO, "connection closed");
  253. connection_terminate(c);
  254. }
  255. static void connection_recv_decoder_handler_error (struct connection *c)
  256. {
  257. struct instance *o = c->inst;
  258. ASSERT(c->state == CONNECTION_STATE_RUNNING)
  259. ModuleLog(o->i, BLOG_ERROR, "decoder error");
  260. connection_terminate(c);
  261. }
  262. static void connection_recv_if_handler_send (struct connection *c, uint8_t *data, int data_len)
  263. {
  264. struct instance *o = c->inst;
  265. ASSERT(c->state == CONNECTION_STATE_RUNNING)
  266. ASSERT(data_len >= 0)
  267. ASSERT(data_len <= RECV_MTU)
  268. PacketPassInterface_Done(&c->recv_if);
  269. if (data_len < sizeof(struct requestproto_header)) {
  270. ModuleLog(o->i, BLOG_ERROR, "missing requestproto header");
  271. goto fail;
  272. }
  273. struct requestproto_header *header = (void *)data;
  274. uint32_t request_id = ltoh32(header->request_id);
  275. uint32_t type = ltoh32(header->type);
  276. switch (type) {
  277. case REQUESTPROTO_TYPE_CLIENT_REQUEST: {
  278. if (find_request(c, request_id)) {
  279. ModuleLog(o->i, BLOG_ERROR, "request with the same ID already exists");
  280. goto fail;
  281. }
  282. if (!request_init(c, request_id, data + sizeof(*header), data_len - sizeof(*header))) {
  283. goto fail;
  284. }
  285. } break;
  286. case REQUESTPROTO_TYPE_CLIENT_ABORT: {
  287. struct request *r = find_request(c, request_id);
  288. if (!r) {
  289. // this is expected if we finish before we get the abort
  290. return;
  291. }
  292. if (!r->terminating) {
  293. request_terminate(r);
  294. }
  295. } break;
  296. default:
  297. ModuleLog(o->i, BLOG_ERROR, "invalid requestproto type");
  298. goto fail;
  299. }
  300. return;
  301. fail:
  302. connection_terminate(c);
  303. }
  304. static int request_init (struct connection *c, uint32_t request_id, const uint8_t *data, int data_len)
  305. {
  306. struct instance *o = c->inst;
  307. ASSERT(c->state == CONNECTION_STATE_RUNNING)
  308. ASSERT(!find_request(c, request_id))
  309. ASSERT(data_len >= 0)
  310. ASSERT(data_len <= RECV_PAYLOAD_MTU)
  311. struct request *r = malloc(sizeof(*r));
  312. if (!r) {
  313. ModuleLog(o->i, BLOG_ERROR, "malloc failed");
  314. goto fail0;
  315. }
  316. r->con = c;
  317. r->request_id = request_id;
  318. LinkedList0_Prepend(&c->requests_list, &r->requests_list_node);
  319. NCDValMem_Init(&r->request_data_mem);
  320. if (!NCDValParser_Parse((const char *)data, data_len, &r->request_data_mem, &r->request_data)) {
  321. ModuleLog(o->i, BLOG_ERROR, "NCDValParser_Parse failed");
  322. goto fail1;
  323. }
  324. if (!(r->end_reply = reply_init(c, request_id, NCDVal_NewInvalid()))) {
  325. goto fail1;
  326. }
  327. if (!NCDModuleProcess_Init(&r->process, o->i, o->request_handler_template, o->args, r, (NCDModuleProcess_handler_event)request_process_handler_event)) {
  328. ModuleLog(o->i, BLOG_ERROR, "NCDModuleProcess_Init failed");
  329. goto fail3;
  330. }
  331. NCDModuleProcess_SetSpecialFuncs(&r->process, (NCDModuleProcess_func_getspecialobj)request_process_func_getspecialobj);
  332. r->terminating = 0;
  333. r->got_finished = 0;
  334. ModuleLog(o->i, BLOG_INFO, "request initialized");
  335. return 1;
  336. fail3:
  337. reply_free(r->end_reply);
  338. fail1:
  339. NCDValMem_Free(&r->request_data_mem);
  340. LinkedList0_Remove(&c->requests_list, &r->requests_list_node);
  341. free(r);
  342. fail0:
  343. return 0;
  344. }
  345. static void request_free (struct request *r)
  346. {
  347. struct connection *c = r->con;
  348. NCDModuleProcess_AssertFree(&r->process);
  349. if (c->state != CONNECTION_STATE_TERMINATING) {
  350. uint32_t type = r->got_finished ? REQUESTPROTO_TYPE_SERVER_FINISHED : REQUESTPROTO_TYPE_SERVER_ERROR;
  351. reply_start(r->end_reply, type);
  352. }
  353. NCDModuleProcess_Free(&r->process);
  354. NCDValMem_Free(&r->request_data_mem);
  355. LinkedList0_Remove(&c->requests_list, &r->requests_list_node);
  356. free(r);
  357. }
  358. static struct request * find_request (struct connection *c, uint32_t request_id)
  359. {
  360. for (LinkedList0Node *ln = LinkedList0_GetFirst(&c->requests_list); ln; ln = LinkedList0Node_Next(ln)) {
  361. struct request *r = UPPER_OBJECT(ln, struct request, requests_list_node);
  362. if (!r->terminating && r->request_id == request_id) {
  363. return r;
  364. }
  365. }
  366. return NULL;
  367. }
  368. static void request_process_handler_event (struct request *r, int event)
  369. {
  370. struct connection *c = r->con;
  371. struct instance *o = c->inst;
  372. switch (event) {
  373. case NCDMODULEPROCESS_EVENT_UP: {
  374. ASSERT(!r->terminating)
  375. } break;
  376. case NCDMODULEPROCESS_EVENT_DOWN: {
  377. ASSERT(!r->terminating)
  378. NCDModuleProcess_Continue(&r->process);
  379. } break;
  380. case NCDMODULEPROCESS_EVENT_TERMINATED: {
  381. ASSERT(r->terminating)
  382. request_free(r);
  383. if (c->state == CONNECTION_STATE_TERMINATING && LinkedList0_IsEmpty(&c->requests_list)) {
  384. connection_free(c);
  385. if (o->dying && LinkedList0_IsEmpty(&o->connections_list)) {
  386. instance_free(o);
  387. return;
  388. }
  389. }
  390. } break;
  391. default: ASSERT(0);
  392. }
  393. }
  394. static int request_process_func_getspecialobj (struct request *r, const char *name, NCDObject *out_object)
  395. {
  396. if (!strcmp(name, "_request")) {
  397. *out_object = NCDObject_Build("sys.request_server.request", 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, const char *name, NCDValMem *mem, NCDValRef *out)
  403. {
  404. struct instance *o = r->con->inst;
  405. if (!strcmp(name, "data")) {
  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 (!strcmp(name, "client_addr_type")) {
  413. const char *str = "none";
  414. switch (r->con->addr.type) {
  415. case BADDR_TYPE_IPV4:
  416. str = "ipv4";
  417. break;
  418. case BADDR_TYPE_IPV6:
  419. str = "ipv6";
  420. break;
  421. }
  422. *out = NCDVal_NewString(mem, str);
  423. if (NCDVal_IsInvalid(*out)) {
  424. ModuleLog(o->i, BLOG_ERROR, "NCDVal_NewString failed");
  425. }
  426. return 1;
  427. }
  428. if (!strcmp(name, "client_addr")) {
  429. char str[BIPADDR_MAX_PRINT_LEN] = "none";
  430. switch (r->con->addr.type) {
  431. case BADDR_TYPE_IPV4:
  432. case BADDR_TYPE_IPV6: {
  433. BIPAddr ipaddr;
  434. BAddr_GetIPAddr(&r->con->addr, &ipaddr);
  435. BIPAddr_Print(&ipaddr, str);
  436. } break;
  437. }
  438. *out = NCDVal_NewString(mem, str);
  439. if (NCDVal_IsInvalid(*out)) {
  440. ModuleLog(o->i, BLOG_ERROR, "NCDVal_NewString failed");
  441. }
  442. return 1;
  443. }
  444. return 0;
  445. }
  446. static void request_terminate (struct request *r)
  447. {
  448. ASSERT(!r->terminating)
  449. NCDModuleProcess_Terminate(&r->process);
  450. r->terminating = 1;
  451. }
  452. static struct reply * reply_init (struct connection *c, uint32_t request_id, NCDValRef reply_data)
  453. {
  454. struct instance *o = c->inst;
  455. ASSERT(c->state == CONNECTION_STATE_RUNNING)
  456. NCDVal_Assert(reply_data);
  457. struct reply *r = malloc(sizeof(*r));
  458. if (!r) {
  459. ModuleLog(o->i, BLOG_ERROR, "malloc failed");
  460. goto fail0;
  461. }
  462. r->con = c;
  463. LinkedList0_Prepend(&c->replies_list, &r->replies_list_node);
  464. PacketPassFifoQueueFlow_Init(&r->send_qflow, &c->send_queue);
  465. r->send_qflow_if = PacketPassFifoQueueFlow_GetInput(&r->send_qflow);
  466. PacketPassInterface_Sender_Init(r->send_qflow_if, (PacketPassInterface_handler_done)reply_send_qflow_if_handler_done, r);
  467. struct reply_header {
  468. struct packetproto_header pp;
  469. struct requestproto_header rp;
  470. } __attribute__((packed));
  471. ExpString str;
  472. if (!ExpString_Init(&str)) {
  473. ModuleLog(o->i, BLOG_ERROR, "ExpString_Init failed");
  474. goto fail1;
  475. }
  476. if (!ExpString_AppendZeros(&str, sizeof(struct reply_header))) {
  477. ModuleLog(o->i, BLOG_ERROR, "ExpString_AppendZeros failed");
  478. goto fail2;
  479. }
  480. if (!NCDVal_IsInvalid(reply_data) && !NCDValGenerator_AppendGenerate(reply_data, &str)) {
  481. ModuleLog(o->i, BLOG_ERROR, "NCDValGenerator_AppendGenerate failed");
  482. goto fail2;
  483. }
  484. size_t len = ExpString_Length(&str);
  485. if (len > INT_MAX || len > PACKETPROTO_ENCLEN(SEND_MTU) || len - sizeof(struct packetproto_header) > UINT16_MAX) {
  486. ModuleLog(o->i, BLOG_ERROR, "reply is too long");
  487. goto fail2;
  488. }
  489. r->send_buf = (uint8_t *)ExpString_Get(&str);
  490. struct reply_header *header = (void *)r->send_buf;
  491. header->pp.len = htol16(len - sizeof(header->pp));
  492. header->rp.request_id = htol32(request_id);
  493. return r;
  494. fail2:
  495. ExpString_Free(&str);
  496. fail1:
  497. PacketPassFifoQueueFlow_Free(&r->send_qflow);
  498. LinkedList0_Remove(&c->replies_list, &r->replies_list_node);
  499. free(r);
  500. fail0:
  501. return NULL;
  502. }
  503. static void reply_start (struct reply *r, uint32_t type)
  504. {
  505. struct reply_header {
  506. struct packetproto_header pp;
  507. struct requestproto_header rp;
  508. } __attribute__((packed));
  509. struct reply_header *header = (void *)r->send_buf;
  510. header->rp.type = htol32(type);
  511. int len = ltoh16(header->pp.len) + sizeof(struct packetproto_header);
  512. PacketPassInterface_Sender_Send(r->send_qflow_if, r->send_buf, len);
  513. }
  514. static void reply_free (struct reply *r)
  515. {
  516. struct connection *c = r->con;
  517. PacketPassFifoQueueFlow_AssertFree(&r->send_qflow);
  518. free(r->send_buf);
  519. PacketPassFifoQueueFlow_Free(&r->send_qflow);
  520. LinkedList0_Remove(&c->replies_list, &r->replies_list_node);
  521. free(r);
  522. }
  523. static void reply_send_qflow_if_handler_done (struct reply *r)
  524. {
  525. reply_free(r);
  526. }
  527. static int init_listen (struct instance *o, NCDValRef listen_addr_arg)
  528. {
  529. ASSERT(!NCDVal_IsInvalid(listen_addr_arg))
  530. if (!NCDVal_IsList(listen_addr_arg)) {
  531. goto bad;
  532. }
  533. if (NCDVal_ListCount(listen_addr_arg) < 1) {
  534. goto bad;
  535. }
  536. NCDValRef type_arg = NCDVal_ListGet(listen_addr_arg, 0);
  537. if (!NCDVal_IsStringNoNulls(type_arg)) {
  538. goto bad;
  539. }
  540. const char *type = NCDVal_StringValue(type_arg);
  541. o->unix_socket_path = NULL;
  542. if (!strcmp(type, "unix")) {
  543. NCDValRef socket_path_arg;
  544. if (!NCDVal_ListRead(listen_addr_arg, 2, &type_arg, &socket_path_arg)) {
  545. goto bad;
  546. }
  547. if (!NCDVal_IsStringNoNulls(socket_path_arg)) {
  548. goto bad;
  549. }
  550. // remember socket path
  551. o->unix_socket_path = NCDVal_StringValue(socket_path_arg);
  552. // make sure socket file doesn't exist
  553. if (unlink(o->unix_socket_path) < 0 && errno != ENOENT) {
  554. ModuleLog(o->i, BLOG_ERROR, "unlink failed");
  555. return 0;
  556. }
  557. // init listener
  558. if (!BListener_InitUnix(&o->listener, o->unix_socket_path, o->i->iparams->reactor, o, (BListener_handler)listener_handler)) {
  559. ModuleLog(o->i, BLOG_ERROR, "BListener_InitUnix failed");
  560. return 0;
  561. }
  562. }
  563. else if (!strcmp(type, "tcp")) {
  564. NCDValRef ip_address_arg;
  565. NCDValRef port_number_arg;
  566. if (!NCDVal_ListRead(listen_addr_arg, 3, &type_arg, &ip_address_arg, &port_number_arg)) {
  567. goto bad;
  568. }
  569. if (!NCDVal_IsStringNoNulls(ip_address_arg) || !NCDVal_IsStringNoNulls(port_number_arg)) {
  570. goto bad;
  571. }
  572. BIPAddr ipaddr;
  573. if (!BIPAddr_Resolve(&ipaddr, (char *)NCDVal_StringValue(ip_address_arg), 1)) {
  574. goto bad;
  575. }
  576. uintmax_t port;
  577. if (!parse_unsigned_integer(NCDVal_StringValue(port_number_arg), &port) || port > UINT16_MAX) {
  578. goto bad;
  579. }
  580. BAddr addr;
  581. BAddr_InitFromIpaddrAndPort(&addr, ipaddr, hton16(port));
  582. // init listener
  583. if (!BListener_Init(&o->listener, addr, o->i->iparams->reactor, o, (BListener_handler)listener_handler)) {
  584. ModuleLog(o->i, BLOG_ERROR, "BListener_Init failed");
  585. return 0;
  586. }
  587. }
  588. else {
  589. goto bad;
  590. }
  591. return 1;
  592. bad:
  593. ModuleLog(o->i, BLOG_ERROR, "bad listen address argument");
  594. return 0;
  595. }
  596. static void func_new (NCDModuleInst *i)
  597. {
  598. // allocate structure
  599. struct instance *o = malloc(sizeof(*o));
  600. if (!o) {
  601. ModuleLog(i, BLOG_ERROR, "malloc failed");
  602. goto fail0;
  603. }
  604. o->i = i;
  605. NCDModuleInst_Backend_SetUser(i, o);
  606. // check arguments
  607. NCDValRef listen_addr_arg;
  608. NCDValRef request_handler_template_arg;
  609. NCDValRef args_arg;
  610. if (!NCDVal_ListRead(i->args, 3, &listen_addr_arg, &request_handler_template_arg, &args_arg)) {
  611. ModuleLog(o->i, BLOG_ERROR, "wrong arity");
  612. goto fail1;
  613. }
  614. if (!NCDVal_IsStringNoNulls(request_handler_template_arg) || !NCDVal_IsList(args_arg)) {
  615. ModuleLog(o->i, BLOG_ERROR, "wrong type");
  616. goto fail1;
  617. }
  618. o->request_handler_template = NCDVal_StringValue(request_handler_template_arg);
  619. o->args = args_arg;
  620. // init listener
  621. if (!init_listen(o, listen_addr_arg)) {
  622. goto fail1;
  623. }
  624. // init connections list
  625. LinkedList0_Init(&o->connections_list);
  626. // set not dying
  627. o->dying = 0;
  628. // signal up
  629. NCDModuleInst_Backend_Up(i);
  630. return;
  631. fail1:
  632. free(o);
  633. fail0:
  634. NCDModuleInst_Backend_SetError(i);
  635. NCDModuleInst_Backend_Dead(i);
  636. }
  637. static void instance_free (struct instance *o)
  638. {
  639. NCDModuleInst *i = o->i;
  640. ASSERT(o->dying)
  641. ASSERT(LinkedList0_IsEmpty(&o->connections_list))
  642. // free structure
  643. free(o);
  644. NCDModuleInst_Backend_Dead(i);
  645. }
  646. static void func_die (void *vo)
  647. {
  648. struct instance *o = vo;
  649. ASSERT(!o->dying)
  650. // free listener
  651. BListener_Free(&o->listener);
  652. if (o->unix_socket_path) {
  653. // remove socket file
  654. if (unlink(o->unix_socket_path)) {
  655. ModuleLog(o->i, BLOG_ERROR, "unlink failed");
  656. }
  657. }
  658. // terminate connections
  659. LinkedList0Node *next_ln;
  660. for (LinkedList0Node *ln = LinkedList0_GetFirst(&o->connections_list); ln && (next_ln = LinkedList0Node_Next(ln)), ln; ln = next_ln) {
  661. struct connection *c = UPPER_OBJECT(ln, struct connection, connections_list_node);
  662. ASSERT(c->inst == o)
  663. if (c->state != CONNECTION_STATE_TERMINATING) {
  664. connection_terminate(c);
  665. }
  666. }
  667. // set dying
  668. o->dying = 1;
  669. // if no connections, die right away
  670. if (LinkedList0_IsEmpty(&o->connections_list)) {
  671. instance_free(o);
  672. return;
  673. }
  674. }
  675. static void reply_func_new (NCDModuleInst *i)
  676. {
  677. NCDValRef reply_data;
  678. if (!NCDVal_ListRead(i->args, 1, &reply_data)) {
  679. ModuleLog(i, BLOG_ERROR, "wrong arity");
  680. goto fail;
  681. }
  682. NCDModuleInst_Backend_Up(i);
  683. struct request *r = i->method_user;
  684. struct connection *c = r->con;
  685. if (r->terminating) {
  686. ModuleLog(i, BLOG_ERROR, "request is dying, cannot submit reply");
  687. goto fail;
  688. }
  689. struct reply *rpl = reply_init(c, r->request_id, reply_data);
  690. if (!rpl) {
  691. ModuleLog(i, BLOG_ERROR, "failed to submit reply");
  692. goto fail;
  693. }
  694. reply_start(rpl, REQUESTPROTO_TYPE_SERVER_REPLY);
  695. return;
  696. fail:
  697. NCDModuleInst_Backend_SetError(i);
  698. NCDModuleInst_Backend_Dead(i);
  699. }
  700. static void finish_func_new (NCDModuleInst *i)
  701. {
  702. if (!NCDVal_ListRead(i->args, 0)) {
  703. ModuleLog(i, BLOG_ERROR, "wrong arity");
  704. goto fail;
  705. }
  706. NCDModuleInst_Backend_Up(i);
  707. struct request *r = i->method_user;
  708. if (r->terminating) {
  709. ModuleLog(i, BLOG_ERROR, "request is dying, cannot submit finished");
  710. goto fail;
  711. }
  712. r->got_finished = 1;
  713. request_terminate(r);
  714. return;
  715. fail:
  716. NCDModuleInst_Backend_SetError(i);
  717. NCDModuleInst_Backend_Dead(i);
  718. }
  719. static const struct NCDModule modules[] = {
  720. {
  721. .type = "sys.request_server",
  722. .func_new = func_new,
  723. .func_die = func_die
  724. }, {
  725. .type = "sys.request_server.request::reply",
  726. .func_new = reply_func_new
  727. }, {
  728. .type = "sys.request_server.request::finish",
  729. .func_new = finish_func_new
  730. }, {
  731. .type = NULL
  732. }
  733. };
  734. const struct NCDModuleGroup ncdmodule_sys_request_server = {
  735. .modules = modules
  736. };