NCDRequestClient.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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(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 = 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. }
  294. static void req_free (struct NCDRequestClient_req *req)
  295. {
  296. NCDRequestClient *client = req->client;
  297. PacketPassFifoQueueFlow_AssertFree(&req->send_qflow);
  298. // free queue flow
  299. PacketPassFifoQueueFlow_Free(&req->send_qflow);
  300. // free request data
  301. free(req->request_data);
  302. // remove from reqs tree
  303. BAVL_Remove(&client->reqs_tree, &req->reqs_tree_node);
  304. // free structure
  305. free(req);
  306. }
  307. static void req_send_abort (struct NCDRequestClient_req *req)
  308. {
  309. // build packet
  310. build_nodata_packet(req->request_id, REQUESTPROTO_TYPE_CLIENT_ABORT, req->request_data, &req->request_len);
  311. // start sending
  312. PacketPassInterface_Sender_Send(req->send_qflow_iface, req->request_data, req->request_len);
  313. // set state sending abort
  314. req->state = RSTATE_SENDING_ABORT;
  315. }
  316. static void req_qflow_send_iface_handler_done (struct NCDRequestClient_req *req)
  317. {
  318. switch (req->state) {
  319. case RSTATE_SENDING_REQUEST: {
  320. // set state ready
  321. req->state = RSTATE_READY;
  322. // call sent handler
  323. req->creq->handler_sent(req->creq->user);
  324. return;
  325. } break;
  326. case RSTATE_SENDING_REQUEST_ABORT: {
  327. // send abort
  328. req_send_abort(req);
  329. } break;
  330. case RSTATE_SENDING_ABORT: {
  331. // set state waiting end
  332. req->state = RSTATE_WAITING_END;
  333. } break;
  334. case RSTATE_DEAD_SENDING: {
  335. // free req
  336. req_free(req);
  337. } break;
  338. default: ASSERT(0);
  339. }
  340. }
  341. int NCDRequestClient_Init (NCDRequestClient *o, const char *socket_path, BReactor *reactor, void *user,
  342. NCDRequestClient_handler_error handler_error,
  343. NCDRequestClient_handler_connected handler_connected)
  344. {
  345. ASSERT(socket_path)
  346. ASSERT(handler_error)
  347. ASSERT(handler_connected)
  348. // init arguments
  349. o->reactor = reactor;
  350. o->user = user;
  351. o->handler_error = handler_error;
  352. o->handler_connected = handler_connected;
  353. // init connector
  354. if (!BConnector_InitUnix(&o->connector, socket_path, reactor, o, (BConnector_handler)connector_handler)) {
  355. BLog(BLOG_ERROR, "BConnector_InitUnix failed");
  356. goto fail0;
  357. }
  358. // init reqs tree
  359. BAVL_Init(&o->reqs_tree, OFFSET_DIFF(struct NCDRequestClient_req, request_id, reqs_tree_node), uint32_comparator, NULL);
  360. // set next request ID
  361. o->next_request_id = 0;
  362. // set state connecting
  363. o->state = CSTATE_CONNECTING;
  364. DebugCounter_Init(&o->d_reqests_ctr);
  365. DebugError_Init(&o->d_err, BReactor_PendingGroup(reactor));
  366. DebugObject_Init(&o->d_obj);
  367. return 1;
  368. fail0:
  369. return 0;
  370. }
  371. void NCDRequestClient_Free (NCDRequestClient *o)
  372. {
  373. DebugObject_Free(&o->d_obj);
  374. DebugError_Free(&o->d_err);
  375. DebugCounter_Free(&o->d_reqests_ctr);
  376. if (o->state == CSTATE_CONNECTED) {
  377. // allow freeing queue flow
  378. PacketPassFifoQueue_PrepareFree(&o->send_queue);
  379. // free remaining reqs
  380. BAVLNode *tn;
  381. while (tn = BAVL_GetFirst(&o->reqs_tree)) {
  382. struct NCDRequestClient_req *req = UPPER_OBJECT(tn, struct NCDRequestClient_req, reqs_tree_node);
  383. ASSERT(req->state != RSTATE_SENDING_REQUEST)
  384. ASSERT(req->state != RSTATE_READY)
  385. req_free(req);
  386. }
  387. // free connection stuff
  388. PacketPassFifoQueue_Free(&o->send_queue);
  389. PacketStreamSender_Free(&o->send_sender);
  390. PacketProtoDecoder_Free(&o->recv_decoder);
  391. PacketPassInterface_Free(&o->recv_if);
  392. BConnection_RecvAsync_Free(&o->con);
  393. BConnection_SendAsync_Free(&o->con);
  394. BConnection_Free(&o->con);
  395. }
  396. // free connector
  397. BConnector_Free(&o->connector);
  398. }
  399. int NCDRequestClientRequest_Init (NCDRequestClientRequest *o, NCDRequestClient *client, NCDValue *payload_value, void *user,
  400. NCDRequestClientRequest_handler_sent handler_sent,
  401. NCDRequestClientRequest_handler_reply handler_reply,
  402. NCDRequestClientRequest_handler_finished handler_finished)
  403. {
  404. ASSERT(client->state == CSTATE_CONNECTED)
  405. DebugError_AssertNoError(&client->d_err);
  406. ASSERT(payload_value)
  407. ASSERT(handler_sent)
  408. ASSERT(handler_reply)
  409. ASSERT(handler_finished)
  410. // init arguments
  411. o->client = client;
  412. o->user = user;
  413. o->handler_sent = handler_sent;
  414. o->handler_reply = handler_reply;
  415. o->handler_finished = handler_finished;
  416. // allocate req structure
  417. struct NCDRequestClient_req *req = malloc(sizeof(*req));
  418. if (!req) {
  419. BLog(BLOG_ERROR, "malloc failed");
  420. goto fail0;
  421. }
  422. // allocate request ID
  423. if (!get_free_request_id(client, &req->request_id)) {
  424. BLog(BLOG_ERROR, "failed to allocate request ID");
  425. goto fail1;
  426. }
  427. // insert to reqs tree
  428. int res = BAVL_Insert(&client->reqs_tree, &req->reqs_tree_node, NULL);
  429. ASSERT(res)
  430. // set pointers
  431. o->req = req;
  432. req->creq = o;
  433. req->client = client;
  434. // build request
  435. if (!build_requestproto_packet(req->request_id, REQUESTPROTO_TYPE_CLIENT_REQUEST, payload_value, &req->request_data, &req->request_len)) {
  436. BLog(BLOG_ERROR, "failed to build request");
  437. goto fail2;
  438. }
  439. // init queue flow
  440. PacketPassFifoQueueFlow_Init(&req->send_qflow, &client->send_queue);
  441. // init send interface
  442. req->send_qflow_iface = PacketPassFifoQueueFlow_GetInput(&req->send_qflow);
  443. PacketPassInterface_Sender_Init(req->send_qflow_iface, (PacketPassInterface_handler_done)req_qflow_send_iface_handler_done, req);
  444. // start sending request
  445. PacketPassInterface_Sender_Send(req->send_qflow_iface, req->request_data, req->request_len);
  446. // set state sending request
  447. req->state = RSTATE_SENDING_REQUEST;
  448. DebugCounter_Increment(&client->d_reqests_ctr);
  449. DebugError_Init(&o->d_err, BReactor_PendingGroup(client->reactor));
  450. DebugObject_Init(&o->d_obj);
  451. return 1;
  452. fail2:
  453. BAVL_Remove(&client->reqs_tree, &req->reqs_tree_node);
  454. fail1:
  455. free(req);
  456. fail0:
  457. return 0;
  458. }
  459. void NCDRequestClientRequest_Free (NCDRequestClientRequest *o)
  460. {
  461. NCDRequestClient *client = o->client;
  462. struct NCDRequestClient_req *req = o->req;
  463. DebugObject_Free(&o->d_obj);
  464. DebugError_Free(&o->d_err);
  465. DebugCounter_Decrement(&client->d_reqests_ctr);
  466. if (req) {
  467. switch (req->state) {
  468. case RSTATE_SENDING_REQUEST: {
  469. req->state = RSTATE_SENDING_REQUEST_ABORT;
  470. } break;
  471. case RSTATE_READY: {
  472. req_send_abort(req);
  473. } break;
  474. default: ASSERT(0);
  475. }
  476. }
  477. }