sys_request_server.c 27 KB

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