socket.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. /**
  2. * @file socket.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. * Synopsis:
  32. * sys.socket sys.connect(string addr)
  33. *
  34. * Variables:
  35. * string is_error - "true" if there was an error with the connection,
  36. * "false" if not
  37. *
  38. * Description:
  39. * Attempts to establish a connection to a server. The address should be
  40. * in one of the following forms:
  41. * - {"tcp", {"ipv4", ipv4_address, port_number}},
  42. * - {"tcp", {"ipv6", ipv6_address, port_number}},
  43. * - {"unix", socket_path}.
  44. * When the connection attempt is finished, the sys.connect() statement goes
  45. * up, and the 'is_error' variable should be used to check for connection
  46. * failure. If there was no error, the read(), write() and close() methods
  47. * can be used to work with the connection.
  48. * If an error occurs after the connection has been established, the
  49. * sys.connect() statement will automatically trigger backtracking, and the
  50. * 'is_error' variable will be changed to "true". This means that all
  51. * errors with the connection can be handled at the place of sys.connect(),
  52. * and no special care is normally needed to handle error in read() and
  53. * write().
  54. * WARNING: when you're not trying to either send or receive data, the
  55. * connection may be unable to detect any events with the connection.
  56. * You should never be neither sending nor receiving for an indefinite time.
  57. *
  58. * Synopsis:
  59. * sys.socket::read()
  60. *
  61. * Variables:
  62. * string (empty) - some data received from the socket, or empty on EOF
  63. * string not_eof - "true" if EOF was not encountered, "false" if it was
  64. *
  65. * Description:
  66. * Receives data from the connection. If EOF was encountered (remote host
  67. * has closed the connection), this returns no data. Otherwise it returns
  68. * at least one byte.
  69. * WARNING: after you receive EOF from a sys.listen() type socket, is is
  70. * your responsibility to call close() eventually, else the cline process
  71. * may remain alive indefinitely.
  72. * WARNING: this may return an arbitrarily small chunk of data. There is
  73. * no significance to the size of the chunks. Correct code will behave
  74. * the same no matter how the incoming data stream is split up.
  75. * WARNING: if a read() is terminated while it is still in progress, i.e.
  76. * has not gone up yet, then the connection is automatically closed, as
  77. * if close() was called.
  78. *
  79. * Synopsis:
  80. * sys.socket::write(string data)
  81. *
  82. * Description:
  83. * Sends data to the connection.
  84. * WARNING: this may block if the operating system's internal send buffer
  85. * is full. Be careful not to enter a deadlock where both ends of the
  86. * connection are trying to send data to the other, but neither is trying
  87. * to receive any data.
  88. * WARNING: if a write() is terminated while it is still in progress, i.e.
  89. * has not gone up yet, then the connection is automatically closed, as
  90. * if close() was called.
  91. *
  92. * Synopsis:
  93. * sys.socket::close()
  94. *
  95. * Description:
  96. * Closes the connection. After this, any further read(), write() or close()
  97. * will trigger an error with the interpreter. For client sockets created
  98. * via sys.listen(), this will immediately trigger termination of the client
  99. * process.
  100. *
  101. * Synopsis:
  102. * sys.listen(string address, string client_template, list args)
  103. *
  104. * Variables:
  105. * string is_error - "true" if listening failed to inittialize, "false" if
  106. * not
  107. *
  108. * Special objects and variables in client_template:
  109. * sys.socket _socket - the socket object for the client
  110. * string _socket.client_addr - the address of the client. The form is
  111. * like the second part of the sys.connect() address format, e.g.
  112. * {"ipv4", "1.2.3.4", "4000"}.
  113. *
  114. * Description:
  115. * Starts listening on the specified address. The 'is_error' variable
  116. * reflects the success of listening initiation. If listening succeeds,
  117. * then for every client that connects, a process is automatically created
  118. * from the template specified by 'client_template', and the 'args' list
  119. * is used as template arguments. Inside such processes, a special object
  120. * '_socket' is available, which represents the connection, and supports
  121. * the same methods as sys.connect(), i.e. read(), write() and close().
  122. * When an error occurs with the connection, the socket is automatically
  123. * closed, triggering process termination.
  124. */
  125. #include <stdlib.h>
  126. #include <limits.h>
  127. #include <stdarg.h>
  128. #include <misc/offset.h>
  129. #include <misc/debug.h>
  130. #include <structure/LinkedList0.h>
  131. #include <system/BConnection.h>
  132. #include <system/BConnectionGeneric.h>
  133. #include <ncd/NCDModule.h>
  134. #include <ncd/extra/value_utils.h>
  135. #include <ncd/extra/address_utils.h>
  136. #include <ncd/extra/NCDBuf.h>
  137. #include <generated/blog_channel_ncd_socket.h>
  138. #define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__)
  139. #define CONNECTION_TYPE_CONNECT 1
  140. #define CONNECTION_TYPE_LISTEN 2
  141. #define CONNECTION_STATE_CONNECTING 1
  142. #define CONNECTION_STATE_ESTABLISHED 2
  143. #define CONNECTION_STATE_ERROR 3
  144. #define CONNECTION_STATE_ABORTED 4
  145. #define READ_BUF_SIZE 1024
  146. struct connection {
  147. union {
  148. struct {
  149. NCDModuleInst *i;
  150. BConnector connector;
  151. } connect;
  152. struct {
  153. struct listen_instance *listen_inst;
  154. LinkedList0Node clients_list_node;
  155. BAddr addr;
  156. NCDModuleProcess process;
  157. } listen;
  158. };
  159. unsigned int type:2;
  160. unsigned int state:3;
  161. unsigned int recv_closed:1;
  162. BConnection connection;
  163. NCDBufStore store;
  164. struct read_instance *read_inst;
  165. struct write_instance *write_inst;
  166. };
  167. struct read_instance {
  168. NCDModuleInst *i;
  169. struct connection *con_inst;
  170. NCDBuf *buf;
  171. size_t read_size;
  172. };
  173. struct write_instance {
  174. NCDModuleInst *i;
  175. struct connection *con_inst;
  176. const char *data;
  177. size_t length;
  178. };
  179. struct listen_instance {
  180. NCDModuleInst *i;
  181. unsigned int have_error:1;
  182. unsigned int dying:1;
  183. NCDValRef client_template;
  184. NCDValRef client_template_args;
  185. BListener listener;
  186. LinkedList0 clients_list;
  187. };
  188. enum {STRING_IS_ERROR, STRING_NOT_EOF, STRING_SOCKET, STRING_SYS_SOCKET, STRING_CLIENT_ADDR};
  189. static struct NCD_string_request strings[] = {
  190. {"is_error"}, {"not_eof"}, {"_socket"}, {"sys.socket"}, {"client_addr"}, {NULL}
  191. };
  192. static void connection_log (struct connection *o, int level, const char *fmt, ...);
  193. static void connection_free_connection (struct connection *o);
  194. static void connection_error (struct connection *o);
  195. static void connection_abort (struct connection *o);
  196. static void connection_connector_handler (void *user, int is_error);
  197. static void connection_connection_handler (void *user, int event);
  198. static void connection_send_handler_done (void *user, int data_len);
  199. static void connection_recv_handler_done (void *user, int data_len);
  200. static void connection_process_handler (struct NCDModuleProcess_s *process, int event);
  201. static int connection_process_func_getspecialobj (struct NCDModuleProcess_s *process, NCD_string_id_t name, NCDObject *out_object);
  202. static int connection_process_socket_obj_func_getvar (const NCDObject *obj, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out_value);
  203. static void listen_listener_handler (void *user);
  204. static void connection_log (struct connection *o, int level, const char *fmt, ...)
  205. {
  206. va_list vl;
  207. va_start(vl, fmt);
  208. switch (o->type) {
  209. case CONNECTION_TYPE_CONNECT: {
  210. NCDModuleInst_Backend_LogVarArg(o->connect.i, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  211. } break;
  212. case CONNECTION_TYPE_LISTEN: {
  213. if (BLog_WouldLog(BLOG_CURRENT_CHANNEL, level)) {
  214. char addr_str[BADDR_MAX_PRINT_LEN];
  215. BAddr_Print(&o->listen.addr, addr_str);
  216. BLog_Append("client %s: ", addr_str);
  217. NCDModuleInst_Backend_LogVarArg(o->listen.listen_inst->i, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  218. }
  219. } break;
  220. default: ASSERT(0);
  221. }
  222. va_end(vl);
  223. }
  224. static void connection_free_connection (struct connection *o)
  225. {
  226. // disconnect read instance
  227. if (o->read_inst) {
  228. ASSERT(o->read_inst->con_inst == o)
  229. o->read_inst->con_inst = NULL;
  230. }
  231. // disconnect write instance
  232. if (o->write_inst) {
  233. ASSERT(o->write_inst->con_inst == o)
  234. o->write_inst->con_inst = NULL;
  235. }
  236. // free connection interfaces
  237. BConnection_RecvAsync_Free(&o->connection);
  238. BConnection_SendAsync_Free(&o->connection);
  239. // free connection
  240. BConnection_Free(&o->connection);
  241. // free store
  242. NCDBufStore_Free(&o->store);
  243. }
  244. static void connection_error (struct connection *o)
  245. {
  246. ASSERT(o->state == CONNECTION_STATE_CONNECTING ||
  247. o->state == CONNECTION_STATE_ESTABLISHED)
  248. // for listen clients, we don't report errors directly,
  249. // we just terminate the client process
  250. if (o->type == CONNECTION_TYPE_LISTEN) {
  251. ASSERT(o->state != CONNECTION_STATE_CONNECTING)
  252. connection_abort(o);
  253. return;
  254. }
  255. // free connector
  256. if (o->state == CONNECTION_STATE_CONNECTING) {
  257. BConnector_Free(&o->connect.connector);
  258. }
  259. // free connection resources
  260. if (o->state == CONNECTION_STATE_ESTABLISHED) {
  261. connection_free_connection(o);
  262. }
  263. // trigger reporting of failure
  264. if (o->state == CONNECTION_STATE_ESTABLISHED) {
  265. NCDModuleInst_Backend_Down(o->connect.i);
  266. }
  267. NCDModuleInst_Backend_Up(o->connect.i);
  268. // set state
  269. o->state = CONNECTION_STATE_ERROR;
  270. }
  271. static void connection_abort (struct connection *o)
  272. {
  273. ASSERT(o->state == CONNECTION_STATE_ESTABLISHED)
  274. // free connection resources
  275. connection_free_connection(o);
  276. // if this is a listen connection, terminate client process
  277. if (o->type == CONNECTION_TYPE_LISTEN) {
  278. NCDModuleProcess_Terminate(&o->listen.process);
  279. }
  280. // set state
  281. o->state = CONNECTION_STATE_ABORTED;
  282. }
  283. static void connection_connector_handler (void *user, int is_error)
  284. {
  285. struct connection *o = user;
  286. ASSERT(o->type == CONNECTION_TYPE_CONNECT)
  287. ASSERT(o->state == CONNECTION_STATE_CONNECTING)
  288. // check error
  289. if (is_error) {
  290. connection_log(o, BLOG_ERROR, "connection failed");
  291. goto fail;
  292. }
  293. // init connection
  294. if (!BConnection_Init(&o->connection, BConnection_source_connector(&o->connect.connector), o->connect.i->params->iparams->reactor, o, connection_connection_handler)) {
  295. connection_log(o, BLOG_ERROR, "BConnection_Init failed");
  296. goto fail;
  297. }
  298. // init connection interfaces
  299. BConnection_SendAsync_Init(&o->connection);
  300. BConnection_RecvAsync_Init(&o->connection);
  301. // setup send/recv done callbacks
  302. StreamPassInterface_Sender_Init(BConnection_SendAsync_GetIf(&o->connection), connection_send_handler_done, o);
  303. StreamRecvInterface_Receiver_Init(BConnection_RecvAsync_GetIf(&o->connection), connection_recv_handler_done, o);
  304. // init store
  305. NCDBufStore_Init(&o->store, READ_BUF_SIZE);
  306. // set not reading, not writing, recv not closed
  307. o->read_inst = NULL;
  308. o->write_inst = NULL;
  309. o->recv_closed = 0;
  310. // free connector
  311. BConnector_Free(&o->connect.connector);
  312. // set state
  313. o->state = CONNECTION_STATE_ESTABLISHED;
  314. // go up
  315. NCDModuleInst_Backend_Up(o->connect.i);
  316. return;
  317. fail:
  318. connection_error(o);
  319. }
  320. static void connection_connection_handler (void *user, int event)
  321. {
  322. struct connection *o = user;
  323. ASSERT(o->state == CONNECTION_STATE_ESTABLISHED)
  324. ASSERT(event == BCONNECTION_EVENT_RECVCLOSED || event == BCONNECTION_EVENT_ERROR)
  325. ASSERT(event != BCONNECTION_EVENT_RECVCLOSED || !o->recv_closed)
  326. if (event == BCONNECTION_EVENT_RECVCLOSED) {
  327. // if we have read operation, make it finish with eof
  328. if (o->read_inst) {
  329. ASSERT(o->read_inst->con_inst == o)
  330. o->read_inst->con_inst = NULL;
  331. o->read_inst->read_size = 0;
  332. NCDModuleInst_Backend_Up(o->read_inst->i);
  333. o->read_inst = NULL;
  334. }
  335. // set recv closed
  336. o->recv_closed = 1;
  337. return;
  338. }
  339. connection_log(o, BLOG_ERROR, "connection error");
  340. // handle error
  341. connection_error(o);
  342. }
  343. static void connection_send_handler_done (void *user, int data_len)
  344. {
  345. struct connection *o = user;
  346. ASSERT(o->state == CONNECTION_STATE_ESTABLISHED)
  347. ASSERT(o->write_inst)
  348. ASSERT(o->write_inst->con_inst == o)
  349. ASSERT(o->write_inst->length > 0)
  350. ASSERT(data_len > 0)
  351. ASSERT(data_len <= o->write_inst->length)
  352. struct write_instance *wr = o->write_inst;
  353. // update send state
  354. wr->data += data_len;
  355. wr->length -= data_len;
  356. // if there's more to send, send again
  357. if (wr->length > 0) {
  358. size_t to_send = (wr->length > INT_MAX ? INT_MAX : wr->length);
  359. StreamPassInterface_Sender_Send(BConnection_SendAsync_GetIf(&o->connection), (uint8_t *)wr->data, to_send);
  360. return;
  361. }
  362. // finish write operation
  363. wr->con_inst = NULL;
  364. NCDModuleInst_Backend_Up(wr->i);
  365. o->write_inst = NULL;
  366. }
  367. static void connection_recv_handler_done (void *user, int data_len)
  368. {
  369. struct connection *o = user;
  370. ASSERT(o->state == CONNECTION_STATE_ESTABLISHED)
  371. ASSERT(o->read_inst)
  372. ASSERT(o->read_inst->con_inst == o)
  373. ASSERT(!o->recv_closed)
  374. ASSERT(data_len > 0)
  375. ASSERT(data_len <= NCDBufStore_BufSize(&o->store))
  376. struct read_instance *re = o->read_inst;
  377. // finish read operation
  378. re->con_inst = NULL;
  379. re->read_size = data_len;
  380. NCDModuleInst_Backend_Up(re->i);
  381. o->read_inst = NULL;
  382. }
  383. static void connection_process_handler (struct NCDModuleProcess_s *process, int event)
  384. {
  385. struct connection *o = UPPER_OBJECT(process, struct connection, listen.process);
  386. ASSERT(o->type == CONNECTION_TYPE_LISTEN)
  387. switch (event) {
  388. case NCDMODULEPROCESS_EVENT_UP: {
  389. ASSERT(o->state == CONNECTION_STATE_ESTABLISHED)
  390. } break;
  391. case NCDMODULEPROCESS_EVENT_DOWN: {
  392. ASSERT(o->state == CONNECTION_STATE_ESTABLISHED)
  393. NCDModuleProcess_Continue(&o->listen.process);
  394. } break;
  395. case NCDMODULEPROCESS_EVENT_TERMINATED: {
  396. ASSERT(o->state == CONNECTION_STATE_ABORTED)
  397. struct listen_instance *li = o->listen.listen_inst;
  398. ASSERT(!li->have_error)
  399. // remove from clients list
  400. LinkedList0_Remove(&li->clients_list, &o->listen.clients_list_node);
  401. // free process
  402. NCDModuleProcess_Free(&o->listen.process);
  403. // free connection structure
  404. free(o);
  405. // if listener is dying and this was the last process, have it die
  406. if (li->dying && LinkedList0_IsEmpty(&li->clients_list)) {
  407. NCDModuleInst_Backend_Dead(li->i);
  408. }
  409. } break;
  410. default: ASSERT(0);
  411. }
  412. }
  413. static int connection_process_func_getspecialobj (struct NCDModuleProcess_s *process, NCD_string_id_t name, NCDObject *out_object)
  414. {
  415. struct connection *o = UPPER_OBJECT(process, struct connection, listen.process);
  416. ASSERT(o->type == CONNECTION_TYPE_LISTEN)
  417. if (name == strings[STRING_SOCKET].id) {
  418. *out_object = NCDObject_Build(strings[STRING_SYS_SOCKET].id, o, connection_process_socket_obj_func_getvar, NCDObject_no_getobj);
  419. return 1;
  420. }
  421. return 0;
  422. }
  423. static int connection_process_socket_obj_func_getvar (const NCDObject *obj, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out_value)
  424. {
  425. struct connection *o = NCDObject_DataPtr(obj);
  426. ASSERT(o->type == CONNECTION_TYPE_LISTEN)
  427. if (name == strings[STRING_CLIENT_ADDR].id) {
  428. *out_value = ncd_make_baddr(o->listen.addr, mem);
  429. if (NCDVal_IsInvalid(*out_value)) {
  430. connection_log(o, BLOG_ERROR, "ncd_make_baddr failed");
  431. }
  432. return 1;
  433. }
  434. return 0;
  435. }
  436. static void listen_listener_handler (void *user)
  437. {
  438. struct listen_instance *o = user;
  439. ASSERT(!o->have_error)
  440. ASSERT(!o->dying)
  441. // allocate connection structure
  442. struct connection *con = malloc(sizeof(*con));
  443. if (!con) {
  444. ModuleLog(o->i, BLOG_ERROR, "malloc failed");
  445. goto fail0;
  446. }
  447. // set connection type and listen instance
  448. con->type = CONNECTION_TYPE_LISTEN;
  449. con->listen.listen_inst = o;
  450. // init connection
  451. if (!BConnection_Init(&con->connection, BConnection_source_listener(&o->listener, &con->listen.addr), o->i->params->iparams->reactor, con, connection_connection_handler)) {
  452. ModuleLog(o->i, BLOG_ERROR, "BConnection_Init failed");
  453. goto fail1;
  454. }
  455. // init connection interfaces
  456. BConnection_SendAsync_Init(&con->connection);
  457. BConnection_RecvAsync_Init(&con->connection);
  458. // setup send/recv done callbacks
  459. StreamPassInterface_Sender_Init(BConnection_SendAsync_GetIf(&con->connection), connection_send_handler_done, con);
  460. StreamRecvInterface_Receiver_Init(BConnection_RecvAsync_GetIf(&con->connection), connection_recv_handler_done, con);
  461. // init process
  462. if (!NCDModuleProcess_InitValue(&con->listen.process, o->i, o->client_template, o->client_template_args, connection_process_handler)) {
  463. ModuleLog(o->i, BLOG_ERROR, "NCDModuleProcess_InitValue failed");
  464. goto fail2;
  465. }
  466. // set special objects callback
  467. NCDModuleProcess_SetSpecialFuncs(&con->listen.process, connection_process_func_getspecialobj);
  468. // insert to clients list
  469. LinkedList0_Prepend(&o->clients_list, &con->listen.clients_list_node);
  470. // init store
  471. NCDBufStore_Init(&con->store, READ_BUF_SIZE);
  472. // set not reading, not writing, recv not closed
  473. con->read_inst = NULL;
  474. con->write_inst = NULL;
  475. con->recv_closed = 0;
  476. // set state
  477. con->state = CONNECTION_STATE_ESTABLISHED;
  478. return;
  479. fail2:
  480. BConnection_RecvAsync_Free(&con->connection);
  481. BConnection_SendAsync_Free(&con->connection);
  482. BConnection_Free(&con->connection);
  483. fail1:
  484. free(con);
  485. fail0:
  486. return;
  487. }
  488. static void connect_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  489. {
  490. struct connection *o = vo;
  491. o->type = CONNECTION_TYPE_CONNECT;
  492. o->connect.i = i;
  493. // pass connection pointer to methods so the same methods can work for
  494. // listen type connections
  495. NCDModuleInst_Backend_PassMemToMethods(i);
  496. // read arguments
  497. NCDValRef address_arg;
  498. if (!NCDVal_ListRead(params->args, 1, &address_arg)) {
  499. ModuleLog(i, BLOG_ERROR, "wrong arity");
  500. goto fail0;
  501. }
  502. // read address
  503. struct BConnection_addr address;
  504. if (!ncd_read_bconnection_addr(address_arg, &address)) {
  505. ModuleLog(i, BLOG_ERROR, "wrong address");
  506. goto error;
  507. }
  508. // init connector
  509. if (!BConnector_InitGeneric(&o->connect.connector, address, i->params->iparams->reactor, o, connection_connector_handler)) {
  510. ModuleLog(i, BLOG_ERROR, "BConnector_InitGeneric failed");
  511. goto error;
  512. }
  513. // set state
  514. o->state = CONNECTION_STATE_CONNECTING;
  515. return;
  516. error:
  517. // go up in error state
  518. o->state = CONNECTION_STATE_ERROR;
  519. NCDModuleInst_Backend_Up(i);
  520. return;
  521. fail0:
  522. NCDModuleInst_Backend_SetError(i);
  523. NCDModuleInst_Backend_Dead(i);
  524. }
  525. static void connect_func_die (void *vo)
  526. {
  527. struct connection *o = vo;
  528. ASSERT(o->type == CONNECTION_TYPE_CONNECT)
  529. // free connector
  530. if (o->state == CONNECTION_STATE_CONNECTING) {
  531. BConnector_Free(&o->connect.connector);
  532. }
  533. // free connection resources
  534. if (o->state == CONNECTION_STATE_ESTABLISHED) {
  535. connection_free_connection(o);
  536. }
  537. NCDModuleInst_Backend_Dead(o->connect.i);
  538. }
  539. static int connect_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  540. {
  541. struct connection *o = vo;
  542. ASSERT(o->type == CONNECTION_TYPE_CONNECT)
  543. ASSERT(o->state != CONNECTION_STATE_CONNECTING)
  544. if (name == strings[STRING_IS_ERROR].id) {
  545. int is_error = (o->state == CONNECTION_STATE_ERROR);
  546. *out = ncd_make_boolean(mem, is_error, o->connect.i->params->iparams->string_index);
  547. if (NCDVal_IsInvalid(*out)) {
  548. ModuleLog(o->connect.i, BLOG_ERROR, "ncd_make_boolean failed");
  549. }
  550. return 1;
  551. }
  552. return 0;
  553. }
  554. static void read_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  555. {
  556. struct read_instance *o = vo;
  557. o->i = i;
  558. // read arguments
  559. if (!NCDVal_ListRead(params->args, 0)) {
  560. ModuleLog(i, BLOG_ERROR, "wrong arity");
  561. goto fail0;
  562. }
  563. // get connection
  564. struct connection *con_inst = params->method_user;
  565. // check connection state
  566. if (con_inst->state != CONNECTION_STATE_ESTABLISHED) {
  567. ModuleLog(i, BLOG_ERROR, "connection is not established");
  568. goto fail0;
  569. }
  570. // check if there's already a read in progress
  571. if (con_inst->read_inst) {
  572. ModuleLog(i, BLOG_ERROR, "read is already in progress");
  573. goto fail0;
  574. }
  575. // get buffer
  576. o->buf = NCDBufStore_GetBuf(&con_inst->store);
  577. if (!o->buf) {
  578. ModuleLog(i, BLOG_ERROR, "NCDBufStore_GetBuf failed");
  579. goto fail0;
  580. }
  581. // if eof was reached, go up immediately
  582. if (con_inst->recv_closed) {
  583. o->con_inst = NULL;
  584. o->read_size = 0;
  585. NCDModuleInst_Backend_Up(i);
  586. return;
  587. }
  588. // set connection
  589. o->con_inst = con_inst;
  590. // register read operation in connection
  591. con_inst->read_inst = o;
  592. // receive
  593. size_t buf_size = NCDBufStore_BufSize(&con_inst->store);
  594. int to_read = (buf_size > INT_MAX ? INT_MAX : buf_size);
  595. StreamRecvInterface_Receiver_Recv(BConnection_RecvAsync_GetIf(&con_inst->connection), (uint8_t *)NCDBuf_Data(o->buf), to_read);
  596. return;
  597. fail0:
  598. NCDModuleInst_Backend_SetError(i);
  599. NCDModuleInst_Backend_Dead(i);
  600. }
  601. static void read_func_die (void *vo)
  602. {
  603. struct read_instance *o = vo;
  604. // if we're receiving, abort connection
  605. if (o->con_inst) {
  606. ASSERT(o->con_inst->state == CONNECTION_STATE_ESTABLISHED)
  607. ASSERT(o->con_inst->read_inst == o)
  608. connection_abort(o->con_inst);
  609. }
  610. // release buffer
  611. NCDRefTarget_Deref(NCDBuf_RefTarget(o->buf));
  612. NCDModuleInst_Backend_Dead(o->i);
  613. }
  614. static int read_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  615. {
  616. struct read_instance *o = vo;
  617. ASSERT(!o->con_inst)
  618. if (name == NCD_STRING_EMPTY) {
  619. *out = NCDVal_NewStringBin(mem, (const uint8_t *)NCDBuf_Data(o->buf), o->read_size);
  620. if (NCDVal_IsInvalid(*out)) {
  621. ModuleLog(o->i, BLOG_ERROR, "NCDVal_NewStringBin failed");
  622. }
  623. return 1;
  624. }
  625. if (name == strings[STRING_NOT_EOF].id) {
  626. *out = ncd_make_boolean(mem, (o->read_size != 0), o->i->params->iparams->string_index);
  627. if (NCDVal_IsInvalid(*out)) {
  628. ModuleLog(o->i, BLOG_ERROR, "ncd_make_boolean failed");
  629. }
  630. return 1;
  631. }
  632. return 0;
  633. }
  634. static void write_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  635. {
  636. struct write_instance *o = vo;
  637. o->i = i;
  638. // read arguments
  639. NCDValRef data_arg;
  640. if (!NCDVal_ListRead(params->args, 1, &data_arg)) {
  641. ModuleLog(i, BLOG_ERROR, "wrong arity");
  642. goto fail0;
  643. }
  644. if (!NCDVal_IsString(data_arg)) {
  645. ModuleLog(i, BLOG_ERROR, "wrong type");
  646. goto fail0;
  647. }
  648. // get connection
  649. struct connection *con_inst = params->method_user;
  650. // check connection state
  651. if (con_inst->state != CONNECTION_STATE_ESTABLISHED) {
  652. ModuleLog(i, BLOG_ERROR, "connection is not established");
  653. goto fail0;
  654. }
  655. // check if there's already a write in progress
  656. if (con_inst->write_inst) {
  657. ModuleLog(i, BLOG_ERROR, "write is already in progress");
  658. goto fail0;
  659. }
  660. // set send state
  661. o->data = NCDVal_StringData(data_arg);
  662. o->length = NCDVal_StringLength(data_arg);
  663. // if there's nothing to send, go up immediately
  664. if (o->length == 0) {
  665. o->con_inst = NULL;
  666. NCDModuleInst_Backend_Up(i);
  667. return;
  668. }
  669. // set connection
  670. o->con_inst = con_inst;
  671. // register write operation in connection
  672. con_inst->write_inst = o;
  673. // send
  674. size_t to_send = (o->length > INT_MAX ? INT_MAX : o->length);
  675. StreamPassInterface_Sender_Send(BConnection_SendAsync_GetIf(&con_inst->connection), (uint8_t *)o->data, to_send);
  676. return;
  677. fail0:
  678. NCDModuleInst_Backend_SetError(i);
  679. NCDModuleInst_Backend_Dead(i);
  680. }
  681. static void write_func_die (void *vo)
  682. {
  683. struct write_instance *o = vo;
  684. // if we're sending, abort connection
  685. if (o->con_inst) {
  686. ASSERT(o->con_inst->state == CONNECTION_STATE_ESTABLISHED)
  687. ASSERT(o->con_inst->write_inst == o)
  688. connection_abort(o->con_inst);
  689. }
  690. NCDModuleInst_Backend_Dead(o->i);
  691. }
  692. static void close_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  693. {
  694. // read arguments
  695. if (!NCDVal_ListRead(params->args, 0)) {
  696. ModuleLog(i, BLOG_ERROR, "wrong arity");
  697. goto fail0;
  698. }
  699. // get connection
  700. struct connection *con_inst = params->method_user;
  701. // check connection state
  702. if (con_inst->state != CONNECTION_STATE_ESTABLISHED) {
  703. ModuleLog(i, BLOG_ERROR, "connection is not established");
  704. goto fail0;
  705. }
  706. // abort
  707. connection_abort(con_inst);
  708. // go up
  709. NCDModuleInst_Backend_Up(i);
  710. return;
  711. fail0:
  712. NCDModuleInst_Backend_SetError(i);
  713. NCDModuleInst_Backend_Dead(i);
  714. }
  715. static void listen_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  716. {
  717. struct listen_instance *o = vo;
  718. o->i = i;
  719. // read arguments
  720. NCDValRef address_arg;
  721. NCDValRef client_template_arg;
  722. NCDValRef args_arg;
  723. if (!NCDVal_ListRead(params->args, 3, &address_arg, &client_template_arg, &args_arg)) {
  724. ModuleLog(i, BLOG_ERROR, "wrong arity");
  725. goto fail0;
  726. }
  727. if (!NCDVal_IsString(client_template_arg) || !NCDVal_IsList(args_arg)) {
  728. ModuleLog(i, BLOG_ERROR, "wrong type");
  729. goto fail0;
  730. }
  731. // remember client template and arguments
  732. o->client_template = client_template_arg;
  733. o->client_template_args = args_arg;
  734. // set no error, not dying
  735. o->have_error = 0;
  736. o->dying = 0;
  737. // read address
  738. struct BConnection_addr address;
  739. if (!ncd_read_bconnection_addr(address_arg, &address)) {
  740. ModuleLog(i, BLOG_ERROR, "wrong address");
  741. goto error;
  742. }
  743. // init listener
  744. if (!BListener_InitGeneric(&o->listener, address, i->params->iparams->reactor, o, listen_listener_handler)) {
  745. ModuleLog(i, BLOG_ERROR, "BListener_InitGeneric failed");
  746. goto error;
  747. }
  748. // init clients list
  749. LinkedList0_Init(&o->clients_list);
  750. // go up
  751. NCDModuleInst_Backend_Up(i);
  752. return;
  753. error:
  754. // go up with error
  755. o->have_error = 1;
  756. NCDModuleInst_Backend_Up(i);
  757. return;
  758. fail0:
  759. NCDModuleInst_Backend_SetError(i);
  760. NCDModuleInst_Backend_Dead(i);
  761. }
  762. static void listen_func_die (void *vo)
  763. {
  764. struct listen_instance *o = vo;
  765. ASSERT(!o->dying)
  766. // free listener
  767. if (!o->have_error) {
  768. BListener_Free(&o->listener);
  769. }
  770. // if we have no clients, die right away
  771. if (o->have_error || LinkedList0_IsEmpty(&o->clients_list)) {
  772. NCDModuleInst_Backend_Dead(o->i);
  773. return;
  774. }
  775. // set dying
  776. o->dying = 1;
  777. // abort all clients and wait for them
  778. for (LinkedList0Node *ln = LinkedList0_GetFirst(&o->clients_list); ln; ln = LinkedList0Node_Next(ln)) {
  779. struct connection *con = UPPER_OBJECT(ln, struct connection, listen.clients_list_node);
  780. ASSERT(con->type == CONNECTION_TYPE_LISTEN)
  781. ASSERT(con->listen.listen_inst == o)
  782. ASSERT(con->state == CONNECTION_STATE_ESTABLISHED || con->state == CONNECTION_STATE_ABORTED)
  783. if (con->state != CONNECTION_STATE_ABORTED) {
  784. connection_abort(con);
  785. }
  786. }
  787. }
  788. static int listen_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  789. {
  790. struct listen_instance *o = vo;
  791. if (name == strings[STRING_IS_ERROR].id) {
  792. *out = ncd_make_boolean(mem, o->have_error, o->i->params->iparams->string_index);
  793. if (NCDVal_IsInvalid(*out)) {
  794. ModuleLog(o->i, BLOG_ERROR, "ncd_make_boolean failed");
  795. }
  796. return 1;
  797. }
  798. return 0;
  799. }
  800. static struct NCDModule modules[] = {
  801. {
  802. .type = "sys.connect",
  803. .base_type = "sys.socket",
  804. .func_new2 = connect_func_new,
  805. .func_die = connect_func_die,
  806. .func_getvar2 = connect_func_getvar,
  807. .alloc_size = sizeof(struct connection)
  808. }, {
  809. .type = "sys.socket::read",
  810. .func_new2 = read_func_new,
  811. .func_die = read_func_die,
  812. .func_getvar2 = read_func_getvar,
  813. .alloc_size = sizeof(struct read_instance)
  814. }, {
  815. .type = "sys.socket::write",
  816. .func_new2 = write_func_new,
  817. .func_die = write_func_die,
  818. .alloc_size = sizeof(struct write_instance)
  819. }, {
  820. .type = "sys.socket::close",
  821. .func_new2 = close_func_new
  822. }, {
  823. .type = "sys.listen",
  824. .func_new2 = listen_func_new,
  825. .func_die = listen_func_die,
  826. .func_getvar2 = listen_func_getvar,
  827. .alloc_size = sizeof(struct listen_instance)
  828. }, {
  829. .type = NULL
  830. }
  831. };
  832. const struct NCDModuleGroup ncdmodule_socket = {
  833. .modules = modules,
  834. .strings = strings
  835. };