NCDRequestClient.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. /**
  2. * @file NCDRequestClient.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. #include <stdlib.h>
  30. #include <stddef.h>
  31. #include <stdint.h>
  32. #include <limits.h>
  33. #include <inttypes.h>
  34. #include <misc/byteorder.h>
  35. #include <misc/expstring.h>
  36. #include <misc/offset.h>
  37. #include <protocol/packetproto.h>
  38. #include <protocol/requestproto.h>
  39. #include <base/BLog.h>
  40. #include "NCDRequestClient.h"
  41. #include <generated/blog_channel_NCDRequestClient.h>
  42. #define SEND_PAYLOAD_MTU 32768
  43. #define RECV_PAYLOAD_MTU 32768
  44. #define SEND_MTU (SEND_PAYLOAD_MTU + sizeof(struct requestproto_header))
  45. #define RECV_MTU (RECV_PAYLOAD_MTU + sizeof(struct requestproto_header))
  46. #define CSTATE_CONNECTING 1
  47. #define CSTATE_CONNECTED 2
  48. #define RSTATE_SENDING_REQUEST 1
  49. #define RSTATE_READY 2
  50. #define RSTATE_SENDING_REQUEST_ABORT 3
  51. #define RSTATE_SENDING_ABORT 4
  52. #define RSTATE_WAITING_END 5
  53. #define RSTATE_DEAD_SENDING 6
  54. static int uint32_comparator (void *unused, void *vv1, void *vv2);
  55. static void report_error (NCDRequestClient *o);
  56. static void request_report_finished (NCDRequestClientRequest *o, int is_error);
  57. static void connector_handler (NCDRequestClient *o, int is_error);
  58. static void connection_handler (NCDRequestClient *o, int event);
  59. static void decoder_handler_error (NCDRequestClient *o);
  60. static void recv_if_handler_send (NCDRequestClient *o, uint8_t *data, int data_len);
  61. static struct NCDRequestClient_req * find_req (NCDRequestClient *o, uint32_t request_id);
  62. static int get_free_request_id (NCDRequestClient *o, uint32_t *out);
  63. static int build_requestproto_packet (uint32_t request_id, uint32_t type, NCDValue *payload_value, uint8_t **out_data, int *out_len);
  64. static void build_nodata_packet (uint32_t request_id, uint32_t type, uint8_t *data, int *out_len);
  65. static void req_free (struct NCDRequestClient_req *req);
  66. static void req_send_abort (struct NCDRequestClient_req *req);
  67. static void req_qflow_send_iface_handler_done (struct NCDRequestClient_req *req);
  68. static int uint32_comparator (void *unused, void *vv1, void *vv2)
  69. {
  70. uint32_t *v1 = vv1;
  71. uint32_t *v2 = vv2;
  72. return (*v1 > *v2) - (*v1 < *v2);
  73. }
  74. static void report_error (NCDRequestClient *o)
  75. {
  76. DEBUGERROR(&o->d_err, o->handler_error(o->user))
  77. }
  78. static void request_report_finished (NCDRequestClientRequest *o, int is_error)
  79. {
  80. o->req = NULL;
  81. DEBUGERROR(&o->d_err, o->handler_finished(o->user, is_error))
  82. }
  83. static void connector_handler (NCDRequestClient *o, int is_error)
  84. {
  85. DebugObject_Access(&o->d_obj);
  86. ASSERT(o->state == CSTATE_CONNECTING)
  87. // check error
  88. if (is_error) {
  89. BLog(BLOG_ERROR, "failed to connect to socket");
  90. goto fail0;
  91. }
  92. BPendingGroup *pg = BReactor_PendingGroup(o->reactor);
  93. // init connection
  94. if (!BConnection_Init(&o->con, BCONNECTION_SOURCE_CONNECTOR(&o->connector), o->reactor, o, (BConnection_handler)connection_handler)) {
  95. BLog(BLOG_ERROR, "BConnection_Init failed");
  96. goto fail0;
  97. }
  98. // init connection interfaces
  99. BConnection_SendAsync_Init(&o->con);
  100. BConnection_RecvAsync_Init(&o->con);
  101. StreamPassInterface *con_send_if = BConnection_SendAsync_GetIf(&o->con);
  102. StreamRecvInterface *con_recv_if = BConnection_RecvAsync_GetIf(&o->con);
  103. // init receive interface
  104. PacketPassInterface_Init(&o->recv_if, RECV_MTU, (PacketPassInterface_handler_send)recv_if_handler_send, o, pg);
  105. // init receive decoder
  106. if (!PacketProtoDecoder_Init(&o->recv_decoder, con_recv_if, &o->recv_if, pg, o, (PacketProtoDecoder_handler_error)decoder_handler_error)) {
  107. BLog(BLOG_ERROR, "PacketProtoDecoder_Init failed");
  108. goto fail1;
  109. }
  110. // init send sender
  111. PacketStreamSender_Init(&o->send_sender, con_send_if, PACKETPROTO_ENCLEN(SEND_MTU), pg);
  112. // init send queue
  113. PacketPassFifoQueue_Init(&o->send_queue, PacketStreamSender_GetInput(&o->send_sender), pg);
  114. // set state connected
  115. o->state = CSTATE_CONNECTED;
  116. // call connected handler
  117. o->handler_connected(o->user);
  118. return;
  119. fail1:
  120. PacketPassInterface_Free(&o->recv_if);
  121. BConnection_RecvAsync_Free(&o->con);
  122. BConnection_SendAsync_Free(&o->con);
  123. BConnection_Free(&o->con);
  124. fail0:
  125. report_error(o);
  126. }
  127. static void connection_handler (NCDRequestClient *o, int event)
  128. {
  129. DebugObject_Access(&o->d_obj);
  130. ASSERT(o->state == CSTATE_CONNECTED)
  131. BLog(BLOG_ERROR, "connection error");
  132. report_error(o);
  133. }
  134. static void decoder_handler_error (NCDRequestClient *o)
  135. {
  136. DebugObject_Access(&o->d_obj);
  137. ASSERT(o->state == CSTATE_CONNECTED)
  138. BLog(BLOG_ERROR, "decoder error");
  139. report_error(o);
  140. }
  141. static void recv_if_handler_send (NCDRequestClient *o, uint8_t *data, int data_len)
  142. {
  143. DebugObject_Access(&o->d_obj);
  144. ASSERT(o->state == CSTATE_CONNECTED)
  145. ASSERT(data_len >= 0)
  146. ASSERT(data_len <= RECV_MTU)
  147. // accept packet
  148. PacketPassInterface_Done(&o->recv_if);
  149. if (data_len < sizeof(struct requestproto_header)) {
  150. BLog(BLOG_ERROR, "missing requestproto header");
  151. goto fail;
  152. }
  153. struct requestproto_header *header = (struct requestproto_header *)data;
  154. uint32_t request_id = ltoh32(header->request_id);
  155. uint32_t type = ltoh32(header->type);
  156. uint8_t *payload = data + sizeof(*header);
  157. int payload_len = data_len - sizeof(*header);
  158. // find request
  159. struct NCDRequestClient_req *req = find_req(o, request_id);
  160. if (!req) {
  161. BLog(BLOG_ERROR, "received packet with unknown request ID");
  162. goto fail;
  163. }
  164. switch (type) {
  165. case REQUESTPROTO_TYPE_SERVER_REPLY: {
  166. switch (o->state) {
  167. case RSTATE_READY: {
  168. // parse payload
  169. NCDValue payload_value;
  170. if (!NCDValueParser_Parse((char *)payload, payload_len, &payload_value)) {
  171. BLog(BLOG_ERROR, "failed to parse reply payload");
  172. goto fail;
  173. }
  174. // call reply handler
  175. req->creq->handler_reply(req->creq->user, payload_value);
  176. return;
  177. } break;
  178. case RSTATE_SENDING_ABORT:
  179. case RSTATE_WAITING_END:
  180. return;
  181. default:
  182. BLog(BLOG_ERROR, "received unexpected reply");
  183. goto fail;
  184. }
  185. } break;
  186. case REQUESTPROTO_TYPE_SERVER_FINISHED:
  187. case REQUESTPROTO_TYPE_SERVER_ERROR: {
  188. if (payload_len != 0) {
  189. BLog(BLOG_ERROR, "finshed/aborted message has non-empty payload");
  190. goto fail;
  191. }
  192. switch (req->state) {
  193. case RSTATE_SENDING_ABORT: {
  194. // set state dying send
  195. req->state = RSTATE_DEAD_SENDING;
  196. return;
  197. } break;
  198. case RSTATE_WAITING_END: {
  199. // free req
  200. req_free(req);
  201. return;
  202. } break;
  203. case RSTATE_READY: {
  204. NCDRequestClientRequest *creq = req->creq;
  205. // free req
  206. req_free(req);
  207. // report finished
  208. request_report_finished(creq, type == REQUESTPROTO_TYPE_SERVER_ERROR);
  209. return;
  210. } break;
  211. default:
  212. BLog(BLOG_ERROR, "received unexpected finished/aborted");
  213. goto fail;
  214. }
  215. } break;
  216. default:
  217. BLog(BLOG_ERROR, "received invalid message type");
  218. goto fail;
  219. }
  220. ASSERT(0)
  221. fail:
  222. report_error(o);
  223. }
  224. static struct NCDRequestClient_req * find_req (NCDRequestClient *o, uint32_t request_id)
  225. {
  226. BAVLNode *tn = BAVL_LookupExact(&o->reqs_tree, &request_id);
  227. if (!tn) {
  228. return NULL;
  229. }
  230. struct NCDRequestClient_req *req = UPPER_OBJECT(tn, struct NCDRequestClient_req, reqs_tree_node);
  231. ASSERT(req->request_id == request_id)
  232. return req;
  233. }
  234. static int get_free_request_id (NCDRequestClient *o, uint32_t *out)
  235. {
  236. uint32_t first = o->next_request_id;
  237. do {
  238. if (!find_req(o, o->next_request_id)) {
  239. *out = o->next_request_id;
  240. return 1;
  241. }
  242. o->next_request_id++;
  243. } while (o->next_request_id != first);
  244. return 0;
  245. }
  246. static int build_requestproto_packet (uint32_t request_id, uint32_t type, NCDValue *payload_value, uint8_t **out_data, int *out_len)
  247. {
  248. struct header {
  249. struct packetproto_header pp;
  250. struct requestproto_header rp;
  251. } __attribute__((packed));
  252. ExpString str;
  253. if (!ExpString_Init(&str)) {
  254. BLog(BLOG_ERROR, "ExpString_Init failed");
  255. goto fail0;
  256. }
  257. if (!ExpString_AppendZeros(&str, sizeof(struct header))) {
  258. BLog(BLOG_ERROR, "ExpString_AppendBinary failed");
  259. goto fail1;
  260. }
  261. if (payload_value && !NCDValueGenerator_AppendGenerate(payload_value, &str)) {
  262. BLog(BLOG_ERROR, "NCDValueGenerator_AppendGenerate failed");
  263. goto fail1;
  264. }
  265. size_t len = ExpString_Length(&str);
  266. if (len > INT_MAX || len > PACKETPROTO_ENCLEN(SEND_MTU) || len - sizeof(struct packetproto_header) > UINT16_MAX) {
  267. BLog(BLOG_ERROR, "reply is too long");
  268. goto fail1;
  269. }
  270. uint8_t *packet = (uint8_t *)ExpString_Get(&str);
  271. struct header *header = (void *)packet;
  272. header->pp.len = htol16(len - sizeof(struct packetproto_header));
  273. header->rp.request_id = htol32(request_id);
  274. header->rp.type = htol32(type);
  275. *out_data = packet;
  276. *out_len = len;
  277. return 1;
  278. fail1:
  279. ExpString_Free(&str);
  280. fail0:
  281. return 0;
  282. }
  283. static void build_nodata_packet (uint32_t request_id, uint32_t type, uint8_t *data, int *out_len)
  284. {
  285. struct header {
  286. struct packetproto_header pp;
  287. struct requestproto_header rp;
  288. } __attribute__((packed));
  289. struct header *header = (void *)data;
  290. header->pp.len = htol16(sizeof(header->rp));
  291. header->rp.request_id = htol32(request_id);
  292. header->rp.type = htol32(type);
  293. *out_len = sizeof(*header);
  294. }
  295. static void req_free (struct NCDRequestClient_req *req)
  296. {
  297. NCDRequestClient *client = req->client;
  298. PacketPassFifoQueueFlow_AssertFree(&req->send_qflow);
  299. // free queue flow
  300. PacketPassFifoQueueFlow_Free(&req->send_qflow);
  301. // free request data
  302. free(req->request_data);
  303. // remove from reqs tree
  304. BAVL_Remove(&client->reqs_tree, &req->reqs_tree_node);
  305. // free structure
  306. free(req);
  307. }
  308. static void req_send_abort (struct NCDRequestClient_req *req)
  309. {
  310. // build packet
  311. build_nodata_packet(req->request_id, REQUESTPROTO_TYPE_CLIENT_ABORT, req->request_data, &req->request_len);
  312. // start sending
  313. PacketPassInterface_Sender_Send(req->send_qflow_iface, req->request_data, req->request_len);
  314. // set state sending abort
  315. req->state = RSTATE_SENDING_ABORT;
  316. }
  317. static void req_qflow_send_iface_handler_done (struct NCDRequestClient_req *req)
  318. {
  319. switch (req->state) {
  320. case RSTATE_SENDING_REQUEST: {
  321. // set state ready
  322. req->state = RSTATE_READY;
  323. // call sent handler
  324. req->creq->handler_sent(req->creq->user);
  325. return;
  326. } break;
  327. case RSTATE_SENDING_REQUEST_ABORT: {
  328. // send abort
  329. req_send_abort(req);
  330. } break;
  331. case RSTATE_SENDING_ABORT: {
  332. // set state waiting end
  333. req->state = RSTATE_WAITING_END;
  334. } break;
  335. case RSTATE_DEAD_SENDING: {
  336. // free req
  337. req_free(req);
  338. } break;
  339. default: ASSERT(0);
  340. }
  341. }
  342. int NCDRequestClient_Init (NCDRequestClient *o, const char *socket_path, BReactor *reactor, void *user,
  343. NCDRequestClient_handler_error handler_error,
  344. NCDRequestClient_handler_connected handler_connected)
  345. {
  346. ASSERT(socket_path)
  347. ASSERT(handler_error)
  348. ASSERT(handler_connected)
  349. // init arguments
  350. o->reactor = reactor;
  351. o->user = user;
  352. o->handler_error = handler_error;
  353. o->handler_connected = handler_connected;
  354. // init connector
  355. if (!BConnector_InitUnix(&o->connector, socket_path, reactor, o, (BConnector_handler)connector_handler)) {
  356. BLog(BLOG_ERROR, "BConnector_InitUnix failed");
  357. goto fail0;
  358. }
  359. // init reqs tree
  360. BAVL_Init(&o->reqs_tree, OFFSET_DIFF(struct NCDRequestClient_req, request_id, reqs_tree_node), uint32_comparator, NULL);
  361. // set next request ID
  362. o->next_request_id = 0;
  363. // set state connecting
  364. o->state = CSTATE_CONNECTING;
  365. DebugCounter_Init(&o->d_reqests_ctr);
  366. DebugError_Init(&o->d_err, BReactor_PendingGroup(reactor));
  367. DebugObject_Init(&o->d_obj);
  368. return 1;
  369. fail0:
  370. return 0;
  371. }
  372. void NCDRequestClient_Free (NCDRequestClient *o)
  373. {
  374. DebugObject_Free(&o->d_obj);
  375. DebugError_Free(&o->d_err);
  376. DebugCounter_Free(&o->d_reqests_ctr);
  377. if (o->state == CSTATE_CONNECTED) {
  378. // allow freeing queue flow
  379. PacketPassFifoQueue_PrepareFree(&o->send_queue);
  380. // free remaining reqs
  381. BAVLNode *tn;
  382. while (tn = BAVL_GetFirst(&o->reqs_tree)) {
  383. struct NCDRequestClient_req *req = UPPER_OBJECT(tn, struct NCDRequestClient_req, reqs_tree_node);
  384. ASSERT(req->state != RSTATE_SENDING_REQUEST)
  385. ASSERT(req->state != RSTATE_READY)
  386. req_free(req);
  387. }
  388. // free connection stuff
  389. PacketPassFifoQueue_Free(&o->send_queue);
  390. PacketStreamSender_Free(&o->send_sender);
  391. PacketProtoDecoder_Free(&o->recv_decoder);
  392. PacketPassInterface_Free(&o->recv_if);
  393. BConnection_RecvAsync_Free(&o->con);
  394. BConnection_SendAsync_Free(&o->con);
  395. BConnection_Free(&o->con);
  396. }
  397. // free connector
  398. BConnector_Free(&o->connector);
  399. }
  400. int NCDRequestClientRequest_Init (NCDRequestClientRequest *o, NCDRequestClient *client, NCDValue *payload_value, void *user,
  401. NCDRequestClientRequest_handler_sent handler_sent,
  402. NCDRequestClientRequest_handler_reply handler_reply,
  403. NCDRequestClientRequest_handler_finished handler_finished)
  404. {
  405. ASSERT(client->state == CSTATE_CONNECTED)
  406. DebugError_AssertNoError(&client->d_err);
  407. ASSERT(payload_value)
  408. ASSERT(handler_sent)
  409. ASSERT(handler_reply)
  410. ASSERT(handler_finished)
  411. // init arguments
  412. o->client = client;
  413. o->user = user;
  414. o->handler_sent = handler_sent;
  415. o->handler_reply = handler_reply;
  416. o->handler_finished = handler_finished;
  417. // allocate req structure
  418. struct NCDRequestClient_req *req = malloc(sizeof(*req));
  419. if (!req) {
  420. BLog(BLOG_ERROR, "malloc failed");
  421. goto fail0;
  422. }
  423. // allocate request ID
  424. if (!get_free_request_id(client, &req->request_id)) {
  425. BLog(BLOG_ERROR, "failed to allocate request ID");
  426. goto fail1;
  427. }
  428. // insert to reqs tree
  429. int res = BAVL_Insert(&client->reqs_tree, &req->reqs_tree_node, NULL);
  430. ASSERT(res)
  431. // set pointers
  432. o->req = req;
  433. req->creq = o;
  434. req->client = client;
  435. // build request
  436. if (!build_requestproto_packet(req->request_id, REQUESTPROTO_TYPE_CLIENT_REQUEST, payload_value, &req->request_data, &req->request_len)) {
  437. BLog(BLOG_ERROR, "failed to build request");
  438. goto fail2;
  439. }
  440. // init queue flow
  441. PacketPassFifoQueueFlow_Init(&req->send_qflow, &client->send_queue);
  442. // init send interface
  443. req->send_qflow_iface = PacketPassFifoQueueFlow_GetInput(&req->send_qflow);
  444. PacketPassInterface_Sender_Init(req->send_qflow_iface, (PacketPassInterface_handler_done)req_qflow_send_iface_handler_done, req);
  445. // start sending request
  446. PacketPassInterface_Sender_Send(req->send_qflow_iface, req->request_data, req->request_len);
  447. // set state sending request
  448. req->state = RSTATE_SENDING_REQUEST;
  449. DebugCounter_Increment(&client->d_reqests_ctr);
  450. DebugError_Init(&o->d_err, BReactor_PendingGroup(client->reactor));
  451. DebugObject_Init(&o->d_obj);
  452. return 1;
  453. fail2:
  454. BAVL_Remove(&client->reqs_tree, &req->reqs_tree_node);
  455. fail1:
  456. free(req);
  457. fail0:
  458. return 0;
  459. }
  460. void NCDRequestClientRequest_Free (NCDRequestClientRequest *o)
  461. {
  462. NCDRequestClient *client = o->client;
  463. struct NCDRequestClient_req *req = o->req;
  464. DebugObject_Free(&o->d_obj);
  465. DebugError_Free(&o->d_err);
  466. DebugCounter_Decrement(&client->d_reqests_ctr);
  467. if (req) {
  468. switch (req->state) {
  469. case RSTATE_SENDING_REQUEST: {
  470. req->state = RSTATE_SENDING_REQUEST_ABORT;
  471. } break;
  472. case RSTATE_READY: {
  473. req_send_abort(req);
  474. } break;
  475. default: ASSERT(0);
  476. }
  477. }
  478. }