socket.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  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/value_utils.h>
  135. #include <ncd/address_utils.h>
  136. #include <generated/blog_channel_ncd_socket.h>
  137. #define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__)
  138. #define CONNECTION_TYPE_CONNECT 1
  139. #define CONNECTION_TYPE_LISTEN 2
  140. #define CONNECTION_STATE_CONNECTING 1
  141. #define CONNECTION_STATE_ESTABLISHED 2
  142. #define CONNECTION_STATE_ERROR 3
  143. #define CONNECTION_STATE_ABORTED 4
  144. #define READ_BUF_SIZE 1024
  145. struct connection {
  146. union {
  147. struct {
  148. NCDModuleInst *i;
  149. BConnector connector;
  150. } connect;
  151. struct {
  152. struct listen_instance *listen_inst;
  153. LinkedList0Node clients_list_node;
  154. BAddr addr;
  155. NCDModuleProcess process;
  156. } listen;
  157. };
  158. unsigned int type:2;
  159. unsigned int state:3;
  160. unsigned int recv_closed:1;
  161. BConnection connection;
  162. struct read_instance *read_inst;
  163. struct write_instance *write_inst;
  164. };
  165. struct read_instance {
  166. NCDModuleInst *i;
  167. struct connection *con_inst;
  168. size_t read_size;
  169. char buf[READ_BUF_SIZE];
  170. };
  171. struct write_instance {
  172. NCDModuleInst *i;
  173. struct connection *con_inst;
  174. const char *data;
  175. size_t length;
  176. };
  177. struct listen_instance {
  178. NCDModuleInst *i;
  179. unsigned int have_error:1;
  180. unsigned int dying:1;
  181. NCDValRef client_template;
  182. NCDValRef client_template_args;
  183. BListener listener;
  184. LinkedList0 clients_list;
  185. };
  186. enum {STRING_IS_ERROR, STRING_NOT_EOF, STRING_SOCKET, STRING_SYS_SOCKET, STRING_CLIENT_ADDR};
  187. static struct NCD_string_request strings[] = {
  188. {"is_error"}, {"not_eof"}, {"_socket"}, {"sys.socket"}, {"client_addr"}, {NULL}
  189. };
  190. static void connection_log (struct connection *o, int level, const char *fmt, ...);
  191. static void connection_free_connection (struct connection *o);
  192. static void connection_error (struct connection *o);
  193. static void connection_abort (struct connection *o);
  194. static void connection_connector_handler (void *user, int is_error);
  195. static void connection_connection_handler (void *user, int event);
  196. static void connection_send_handler_done (void *user, int data_len);
  197. static void connection_recv_handler_done (void *user, int data_len);
  198. static void connection_process_handler (struct NCDModuleProcess_s *process, int event);
  199. static int connection_process_func_getspecialobj (struct NCDModuleProcess_s *process, NCD_string_id_t name, NCDObject *out_object);
  200. static int connection_process_socket_obj_func_getvar (void *user, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out_value);
  201. static void listen_listener_handler (void *user);
  202. static void connection_log (struct connection *o, int level, const char *fmt, ...)
  203. {
  204. va_list vl;
  205. va_start(vl, fmt);
  206. switch (o->type) {
  207. case CONNECTION_TYPE_CONNECT: {
  208. NCDModuleInst_Backend_LogVarArg(o->connect.i, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  209. } break;
  210. case CONNECTION_TYPE_LISTEN: {
  211. if (BLog_WouldLog(BLOG_CURRENT_CHANNEL, level)) {
  212. char addr_str[BADDR_MAX_PRINT_LEN];
  213. BAddr_Print(&o->listen.addr, addr_str);
  214. BLog_Append("client %s: ", addr_str);
  215. NCDModuleInst_Backend_LogVarArg(o->listen.listen_inst->i, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  216. }
  217. } break;
  218. default: ASSERT(0);
  219. }
  220. va_end(vl);
  221. }
  222. static void connection_free_connection (struct connection *o)
  223. {
  224. // disconnect read instance
  225. if (o->read_inst) {
  226. ASSERT(o->read_inst->con_inst == o)
  227. o->read_inst->con_inst = NULL;
  228. }
  229. // disconnect write instance
  230. if (o->write_inst) {
  231. ASSERT(o->write_inst->con_inst == o)
  232. o->write_inst->con_inst = NULL;
  233. }
  234. // free connection interfaces
  235. BConnection_RecvAsync_Free(&o->connection);
  236. BConnection_SendAsync_Free(&o->connection);
  237. // free connection
  238. BConnection_Free(&o->connection);
  239. }
  240. static void connection_error (struct connection *o)
  241. {
  242. ASSERT(o->state == CONNECTION_STATE_CONNECTING ||
  243. o->state == CONNECTION_STATE_ESTABLISHED)
  244. // for listen clients, we don't report errors directly,
  245. // we just terminate the client process
  246. if (o->type == CONNECTION_TYPE_LISTEN) {
  247. ASSERT(o->state != CONNECTION_STATE_CONNECTING)
  248. connection_abort(o);
  249. return;
  250. }
  251. // free connector
  252. if (o->state == CONNECTION_STATE_CONNECTING) {
  253. BConnector_Free(&o->connect.connector);
  254. }
  255. // free connection resources
  256. if (o->state == CONNECTION_STATE_ESTABLISHED) {
  257. connection_free_connection(o);
  258. }
  259. // trigger reporting of failure
  260. if (o->state == CONNECTION_STATE_ESTABLISHED) {
  261. NCDModuleInst_Backend_Down(o->connect.i);
  262. }
  263. NCDModuleInst_Backend_Up(o->connect.i);
  264. // set state
  265. o->state = CONNECTION_STATE_ERROR;
  266. }
  267. static void connection_abort (struct connection *o)
  268. {
  269. ASSERT(o->state == CONNECTION_STATE_ESTABLISHED)
  270. // free connection resources
  271. connection_free_connection(o);
  272. // if this is a listen connection, terminate client process
  273. if (o->type == CONNECTION_TYPE_LISTEN) {
  274. NCDModuleProcess_Terminate(&o->listen.process);
  275. }
  276. // set state
  277. o->state = CONNECTION_STATE_ABORTED;
  278. }
  279. static void connection_connector_handler (void *user, int is_error)
  280. {
  281. struct connection *o = user;
  282. ASSERT(o->type == CONNECTION_TYPE_CONNECT)
  283. ASSERT(o->state == CONNECTION_STATE_CONNECTING)
  284. // check error
  285. if (is_error) {
  286. connection_log(o, BLOG_ERROR, "connection failed");
  287. goto fail;
  288. }
  289. // init connection
  290. if (!BConnection_Init(&o->connection, BConnection_source_connector(&o->connect.connector), o->connect.i->params->iparams->reactor, o, connection_connection_handler)) {
  291. connection_log(o, BLOG_ERROR, "BConnection_Init failed");
  292. goto fail;
  293. }
  294. // init connection interfaces
  295. BConnection_SendAsync_Init(&o->connection);
  296. BConnection_RecvAsync_Init(&o->connection);
  297. // setup send/recv done callbacks
  298. StreamPassInterface_Sender_Init(BConnection_SendAsync_GetIf(&o->connection), connection_send_handler_done, o);
  299. StreamRecvInterface_Receiver_Init(BConnection_RecvAsync_GetIf(&o->connection), connection_recv_handler_done, o);
  300. // set not reading, not writing, recv not closed
  301. o->read_inst = NULL;
  302. o->write_inst = NULL;
  303. o->recv_closed = 0;
  304. // free connector
  305. BConnector_Free(&o->connect.connector);
  306. // set state
  307. o->state = CONNECTION_STATE_ESTABLISHED;
  308. // go up
  309. NCDModuleInst_Backend_Up(o->connect.i);
  310. return;
  311. fail:
  312. connection_error(o);
  313. }
  314. static void connection_connection_handler (void *user, int event)
  315. {
  316. struct connection *o = user;
  317. ASSERT(o->state == CONNECTION_STATE_ESTABLISHED)
  318. ASSERT(event == BCONNECTION_EVENT_RECVCLOSED || event == BCONNECTION_EVENT_ERROR)
  319. ASSERT(event != BCONNECTION_EVENT_RECVCLOSED || !o->recv_closed)
  320. if (event == BCONNECTION_EVENT_RECVCLOSED) {
  321. // if we have read operation, make it finish with eof
  322. if (o->read_inst) {
  323. ASSERT(o->read_inst->con_inst == o)
  324. o->read_inst->con_inst = NULL;
  325. o->read_inst->read_size = 0;
  326. NCDModuleInst_Backend_Up(o->read_inst->i);
  327. o->read_inst = NULL;
  328. }
  329. // set recv closed
  330. o->recv_closed = 1;
  331. return;
  332. }
  333. connection_log(o, BLOG_ERROR, "connection error");
  334. // handle error
  335. connection_error(o);
  336. }
  337. static void connection_send_handler_done (void *user, int data_len)
  338. {
  339. struct connection *o = user;
  340. ASSERT(o->state == CONNECTION_STATE_ESTABLISHED)
  341. ASSERT(o->write_inst)
  342. ASSERT(o->write_inst->con_inst == o)
  343. ASSERT(o->write_inst->length > 0)
  344. ASSERT(data_len > 0)
  345. ASSERT(data_len <= o->write_inst->length)
  346. struct write_instance *wr = o->write_inst;
  347. // update send state
  348. wr->data += data_len;
  349. wr->length -= data_len;
  350. // if there's more to send, send again
  351. if (wr->length > 0) {
  352. size_t to_send = (wr->length > INT_MAX ? INT_MAX : wr->length);
  353. StreamPassInterface_Sender_Send(BConnection_SendAsync_GetIf(&o->connection), (uint8_t *)wr->data, to_send);
  354. return;
  355. }
  356. // finish write operation
  357. wr->con_inst = NULL;
  358. NCDModuleInst_Backend_Up(wr->i);
  359. o->write_inst = NULL;
  360. }
  361. static void connection_recv_handler_done (void *user, int data_len)
  362. {
  363. struct connection *o = user;
  364. ASSERT(o->state == CONNECTION_STATE_ESTABLISHED)
  365. ASSERT(o->read_inst)
  366. ASSERT(o->read_inst->con_inst == o)
  367. ASSERT(!o->recv_closed)
  368. ASSERT(data_len > 0)
  369. ASSERT(data_len <= READ_BUF_SIZE)
  370. struct read_instance *re = o->read_inst;
  371. // finish read operation
  372. re->con_inst = NULL;
  373. re->read_size = data_len;
  374. NCDModuleInst_Backend_Up(re->i);
  375. o->read_inst = NULL;
  376. }
  377. static void connection_process_handler (struct NCDModuleProcess_s *process, int event)
  378. {
  379. struct connection *o = UPPER_OBJECT(process, struct connection, listen.process);
  380. ASSERT(o->type == CONNECTION_TYPE_LISTEN)
  381. switch (event) {
  382. case NCDMODULEPROCESS_EVENT_UP: {
  383. ASSERT(o->state == CONNECTION_STATE_ESTABLISHED)
  384. } break;
  385. case NCDMODULEPROCESS_EVENT_DOWN: {
  386. ASSERT(o->state == CONNECTION_STATE_ESTABLISHED)
  387. NCDModuleProcess_Continue(&o->listen.process);
  388. } break;
  389. case NCDMODULEPROCESS_EVENT_TERMINATED: {
  390. ASSERT(o->state == CONNECTION_STATE_ABORTED)
  391. struct listen_instance *li = o->listen.listen_inst;
  392. ASSERT(!li->have_error)
  393. // remove from clients list
  394. LinkedList0_Remove(&li->clients_list, &o->listen.clients_list_node);
  395. // free process
  396. NCDModuleProcess_Free(&o->listen.process);
  397. // free connection structure
  398. free(o);
  399. // if listener is dying and this was the last process, have it die
  400. if (li->dying && LinkedList0_IsEmpty(&li->clients_list)) {
  401. NCDModuleInst_Backend_Dead(li->i);
  402. }
  403. } break;
  404. default: ASSERT(0);
  405. }
  406. }
  407. static int connection_process_func_getspecialobj (struct NCDModuleProcess_s *process, NCD_string_id_t name, NCDObject *out_object)
  408. {
  409. struct connection *o = UPPER_OBJECT(process, struct connection, listen.process);
  410. ASSERT(o->type == CONNECTION_TYPE_LISTEN)
  411. if (name == strings[STRING_SOCKET].id) {
  412. *out_object = NCDObject_Build(strings[STRING_SYS_SOCKET].id, o, connection_process_socket_obj_func_getvar, NULL);
  413. return 1;
  414. }
  415. return 0;
  416. }
  417. static int connection_process_socket_obj_func_getvar (void *user, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out_value)
  418. {
  419. struct connection *o = user;
  420. ASSERT(o->type == CONNECTION_TYPE_LISTEN)
  421. if (name == strings[STRING_CLIENT_ADDR].id) {
  422. *out_value = ncd_make_baddr(o->listen.addr, mem);
  423. if (NCDVal_IsInvalid(*out_value)) {
  424. connection_log(o, BLOG_ERROR, "ncd_make_baddr failed");
  425. }
  426. return 1;
  427. }
  428. return 0;
  429. }
  430. static void listen_listener_handler (void *user)
  431. {
  432. struct listen_instance *o = user;
  433. ASSERT(!o->have_error)
  434. ASSERT(!o->dying)
  435. // allocate connection structure
  436. struct connection *con = malloc(sizeof(*con));
  437. if (!con) {
  438. ModuleLog(o->i, BLOG_ERROR, "malloc failed");
  439. goto fail0;
  440. }
  441. // set connection type and listen instance
  442. con->type = CONNECTION_TYPE_LISTEN;
  443. con->listen.listen_inst = o;
  444. // init connection
  445. if (!BConnection_Init(&con->connection, BConnection_source_listener(&o->listener, &con->listen.addr), o->i->params->iparams->reactor, con, connection_connection_handler)) {
  446. ModuleLog(o->i, BLOG_ERROR, "BConnection_Init failed");
  447. goto fail1;
  448. }
  449. // init connection interfaces
  450. BConnection_SendAsync_Init(&con->connection);
  451. BConnection_RecvAsync_Init(&con->connection);
  452. // setup send/recv done callbacks
  453. StreamPassInterface_Sender_Init(BConnection_SendAsync_GetIf(&con->connection), connection_send_handler_done, con);
  454. StreamRecvInterface_Receiver_Init(BConnection_RecvAsync_GetIf(&con->connection), connection_recv_handler_done, con);
  455. // init process
  456. if (!NCDModuleProcess_InitValue(&con->listen.process, o->i, o->client_template, o->client_template_args, connection_process_handler)) {
  457. ModuleLog(o->i, BLOG_ERROR, "NCDModuleProcess_InitValue failed");
  458. goto fail2;
  459. }
  460. // set special objects callback
  461. NCDModuleProcess_SetSpecialFuncs(&con->listen.process, connection_process_func_getspecialobj);
  462. // insert to clients list
  463. LinkedList0_Prepend(&o->clients_list, &con->listen.clients_list_node);
  464. // set not reading, not writing, recv not closed
  465. con->read_inst = NULL;
  466. con->write_inst = NULL;
  467. con->recv_closed = 0;
  468. // set state
  469. con->state = CONNECTION_STATE_ESTABLISHED;
  470. return;
  471. fail2:
  472. BConnection_RecvAsync_Free(&con->connection);
  473. BConnection_SendAsync_Free(&con->connection);
  474. BConnection_Free(&con->connection);
  475. fail1:
  476. free(con);
  477. fail0:
  478. return;
  479. }
  480. static void connect_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  481. {
  482. struct connection *o = vo;
  483. o->type = CONNECTION_TYPE_CONNECT;
  484. o->connect.i = i;
  485. // pass connection pointer to methods so the same methods can work for
  486. // listen type connections
  487. NCDModuleInst_Backend_PassMemToMethods(i);
  488. // read arguments
  489. NCDValRef address_arg;
  490. if (!NCDVal_ListRead(params->args, 1, &address_arg)) {
  491. ModuleLog(i, BLOG_ERROR, "wrong arity");
  492. goto fail0;
  493. }
  494. // read address
  495. struct BConnection_addr address;
  496. if (!ncd_read_bconnection_addr(address_arg, &address)) {
  497. ModuleLog(i, BLOG_ERROR, "wrong address");
  498. goto error;
  499. }
  500. // init connector
  501. if (!BConnector_InitGeneric(&o->connect.connector, address, i->params->iparams->reactor, o, connection_connector_handler)) {
  502. ModuleLog(i, BLOG_ERROR, "BConnector_InitGeneric failed");
  503. goto error;
  504. }
  505. // set state
  506. o->state = CONNECTION_STATE_CONNECTING;
  507. return;
  508. error:
  509. // go up in error state
  510. o->state = CONNECTION_STATE_ERROR;
  511. NCDModuleInst_Backend_Up(i);
  512. return;
  513. fail0:
  514. NCDModuleInst_Backend_SetError(i);
  515. NCDModuleInst_Backend_Dead(i);
  516. }
  517. static void connect_func_die (void *vo)
  518. {
  519. struct connection *o = vo;
  520. ASSERT(o->type == CONNECTION_TYPE_CONNECT)
  521. // free connector
  522. if (o->state == CONNECTION_STATE_CONNECTING) {
  523. BConnector_Free(&o->connect.connector);
  524. }
  525. // free connection resources
  526. if (o->state == CONNECTION_STATE_ESTABLISHED) {
  527. connection_free_connection(o);
  528. }
  529. NCDModuleInst_Backend_Dead(o->connect.i);
  530. }
  531. static int connect_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  532. {
  533. struct connection *o = vo;
  534. ASSERT(o->type == CONNECTION_TYPE_CONNECT)
  535. ASSERT(o->state != CONNECTION_STATE_CONNECTING)
  536. if (name == strings[STRING_IS_ERROR].id) {
  537. int is_error = (o->state == CONNECTION_STATE_ERROR);
  538. *out = ncd_make_boolean(mem, is_error, o->connect.i->params->iparams->string_index);
  539. if (NCDVal_IsInvalid(*out)) {
  540. ModuleLog(o->connect.i, BLOG_ERROR, "ncd_make_boolean failed");
  541. }
  542. return 1;
  543. }
  544. return 0;
  545. }
  546. static void read_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  547. {
  548. struct read_instance *o = vo;
  549. o->i = i;
  550. // read arguments
  551. if (!NCDVal_ListRead(params->args, 0)) {
  552. ModuleLog(i, BLOG_ERROR, "wrong arity");
  553. goto fail0;
  554. }
  555. // get connection
  556. struct connection *con_inst = params->method_user;
  557. // check connection state
  558. if (con_inst->state != CONNECTION_STATE_ESTABLISHED) {
  559. ModuleLog(i, BLOG_ERROR, "connection is not established");
  560. goto fail0;
  561. }
  562. // check if there's already a read in progress
  563. if (con_inst->read_inst) {
  564. ModuleLog(i, BLOG_ERROR, "read is already in progress");
  565. goto fail0;
  566. }
  567. // if eof was reached, go up immediately
  568. if (con_inst->recv_closed) {
  569. o->con_inst = NULL;
  570. o->read_size = 0;
  571. NCDModuleInst_Backend_Up(i);
  572. return;
  573. }
  574. // set connection
  575. o->con_inst = con_inst;
  576. // register read operation in connection
  577. con_inst->read_inst = o;
  578. // receive
  579. StreamRecvInterface_Receiver_Recv(BConnection_RecvAsync_GetIf(&con_inst->connection), (uint8_t *)o->buf, READ_BUF_SIZE);
  580. return;
  581. fail0:
  582. NCDModuleInst_Backend_SetError(i);
  583. NCDModuleInst_Backend_Dead(i);
  584. }
  585. static void read_func_die (void *vo)
  586. {
  587. struct read_instance *o = vo;
  588. // if we're receiving, abort connection
  589. if (o->con_inst) {
  590. ASSERT(o->con_inst->state == CONNECTION_STATE_ESTABLISHED)
  591. ASSERT(o->con_inst->read_inst == o)
  592. connection_abort(o->con_inst);
  593. }
  594. NCDModuleInst_Backend_Dead(o->i);
  595. }
  596. static int read_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  597. {
  598. struct read_instance *o = vo;
  599. ASSERT(!o->con_inst)
  600. if (name == NCD_STRING_EMPTY) {
  601. *out = NCDVal_NewStringBin(mem, (const uint8_t *)o->buf, o->read_size);
  602. if (NCDVal_IsInvalid(*out)) {
  603. ModuleLog(o->i, BLOG_ERROR, "NCDVal_NewStringBin failed");
  604. }
  605. return 1;
  606. }
  607. if (name == strings[STRING_NOT_EOF].id) {
  608. *out = ncd_make_boolean(mem, (o->read_size != 0), o->i->params->iparams->string_index);
  609. if (NCDVal_IsInvalid(*out)) {
  610. ModuleLog(o->i, BLOG_ERROR, "ncd_make_boolean failed");
  611. }
  612. return 1;
  613. }
  614. return 0;
  615. }
  616. static void write_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  617. {
  618. struct write_instance *o = vo;
  619. o->i = i;
  620. // read arguments
  621. NCDValRef data_arg;
  622. if (!NCDVal_ListRead(params->args, 1, &data_arg)) {
  623. ModuleLog(i, BLOG_ERROR, "wrong arity");
  624. goto fail0;
  625. }
  626. if (!NCDVal_IsString(data_arg)) {
  627. ModuleLog(i, BLOG_ERROR, "wrong type");
  628. goto fail0;
  629. }
  630. // get connection
  631. struct connection *con_inst = params->method_user;
  632. // check connection state
  633. if (con_inst->state != CONNECTION_STATE_ESTABLISHED) {
  634. ModuleLog(i, BLOG_ERROR, "connection is not established");
  635. goto fail0;
  636. }
  637. // check if there's already a write in progress
  638. if (con_inst->write_inst) {
  639. ModuleLog(i, BLOG_ERROR, "write is already in progress");
  640. goto fail0;
  641. }
  642. // set send state
  643. o->data = NCDVal_StringValue(data_arg);
  644. o->length = NCDVal_StringLength(data_arg);
  645. // if there's nothing to send, go up immediately
  646. if (o->length == 0) {
  647. o->con_inst = NULL;
  648. NCDModuleInst_Backend_Up(i);
  649. return;
  650. }
  651. // set connection
  652. o->con_inst = con_inst;
  653. // register write operation in connection
  654. con_inst->write_inst = o;
  655. // send
  656. size_t to_send = (o->length > INT_MAX ? INT_MAX : o->length);
  657. StreamPassInterface_Sender_Send(BConnection_SendAsync_GetIf(&con_inst->connection), (uint8_t *)o->data, to_send);
  658. return;
  659. fail0:
  660. NCDModuleInst_Backend_SetError(i);
  661. NCDModuleInst_Backend_Dead(i);
  662. }
  663. static void write_func_die (void *vo)
  664. {
  665. struct write_instance *o = vo;
  666. // if we're sending, abort connection
  667. if (o->con_inst) {
  668. ASSERT(o->con_inst->state == CONNECTION_STATE_ESTABLISHED)
  669. ASSERT(o->con_inst->write_inst == o)
  670. connection_abort(o->con_inst);
  671. }
  672. NCDModuleInst_Backend_Dead(o->i);
  673. }
  674. static void close_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  675. {
  676. // read arguments
  677. if (!NCDVal_ListRead(params->args, 0)) {
  678. ModuleLog(i, BLOG_ERROR, "wrong arity");
  679. goto fail0;
  680. }
  681. // get connection
  682. struct connection *con_inst = params->method_user;
  683. // check connection state
  684. if (con_inst->state != CONNECTION_STATE_ESTABLISHED) {
  685. ModuleLog(i, BLOG_ERROR, "connection is not established");
  686. goto fail0;
  687. }
  688. // abort
  689. connection_abort(con_inst);
  690. // go up
  691. NCDModuleInst_Backend_Up(i);
  692. return;
  693. fail0:
  694. NCDModuleInst_Backend_SetError(i);
  695. NCDModuleInst_Backend_Dead(i);
  696. }
  697. static void listen_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  698. {
  699. struct listen_instance *o = vo;
  700. o->i = i;
  701. // read arguments
  702. NCDValRef address_arg;
  703. NCDValRef client_template_arg;
  704. NCDValRef args_arg;
  705. if (!NCDVal_ListRead(params->args, 3, &address_arg, &client_template_arg, &args_arg)) {
  706. ModuleLog(i, BLOG_ERROR, "wrong arity");
  707. goto fail0;
  708. }
  709. if (!NCDVal_IsString(client_template_arg) || !NCDVal_IsList(args_arg)) {
  710. ModuleLog(i, BLOG_ERROR, "wrong type");
  711. goto fail0;
  712. }
  713. // remember client template and arguments
  714. o->client_template = client_template_arg;
  715. o->client_template_args = args_arg;
  716. // set no error, not dying
  717. o->have_error = 0;
  718. o->dying = 0;
  719. // read address
  720. struct BConnection_addr address;
  721. if (!ncd_read_bconnection_addr(address_arg, &address)) {
  722. ModuleLog(i, BLOG_ERROR, "wrong address");
  723. goto error;
  724. }
  725. // init listener
  726. if (!BListener_InitGeneric(&o->listener, address, i->params->iparams->reactor, o, listen_listener_handler)) {
  727. ModuleLog(i, BLOG_ERROR, "BListener_InitGeneric failed");
  728. goto error;
  729. }
  730. // init clients list
  731. LinkedList0_Init(&o->clients_list);
  732. // go up
  733. NCDModuleInst_Backend_Up(i);
  734. return;
  735. error:
  736. // go up with error
  737. o->have_error = 1;
  738. NCDModuleInst_Backend_Up(i);
  739. return;
  740. fail0:
  741. NCDModuleInst_Backend_SetError(i);
  742. NCDModuleInst_Backend_Dead(i);
  743. }
  744. static void listen_func_die (void *vo)
  745. {
  746. struct listen_instance *o = vo;
  747. ASSERT(!o->dying)
  748. // free listener
  749. if (!o->have_error) {
  750. BListener_Free(&o->listener);
  751. }
  752. // if we have no clients, die right away
  753. if (o->have_error || LinkedList0_IsEmpty(&o->clients_list)) {
  754. NCDModuleInst_Backend_Dead(o->i);
  755. return;
  756. }
  757. // set dying
  758. o->dying = 1;
  759. // abort all clients and wait for them
  760. for (LinkedList0Node *ln = LinkedList0_GetFirst(&o->clients_list); ln; ln = LinkedList0Node_Next(ln)) {
  761. struct connection *con = UPPER_OBJECT(ln, struct connection, listen.clients_list_node);
  762. ASSERT(con->type == CONNECTION_TYPE_LISTEN)
  763. ASSERT(con->listen.listen_inst == o)
  764. ASSERT(con->state == CONNECTION_STATE_ESTABLISHED || con->state == CONNECTION_STATE_ABORTED)
  765. if (con->state != CONNECTION_STATE_ABORTED) {
  766. connection_abort(con);
  767. }
  768. }
  769. }
  770. static int listen_func_getvar (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
  771. {
  772. struct listen_instance *o = vo;
  773. if (name == strings[STRING_IS_ERROR].id) {
  774. *out = ncd_make_boolean(mem, o->have_error, o->i->params->iparams->string_index);
  775. if (NCDVal_IsInvalid(*out)) {
  776. ModuleLog(o->i, BLOG_ERROR, "ncd_make_boolean failed");
  777. }
  778. return 1;
  779. }
  780. return 0;
  781. }
  782. static struct NCDModule modules[] = {
  783. {
  784. .type = "sys.connect",
  785. .base_type = "sys.socket",
  786. .func_new2 = connect_func_new,
  787. .func_die = connect_func_die,
  788. .func_getvar2 = connect_func_getvar,
  789. .alloc_size = sizeof(struct connection)
  790. }, {
  791. .type = "sys.socket::read",
  792. .func_new2 = read_func_new,
  793. .func_die = read_func_die,
  794. .func_getvar2 = read_func_getvar,
  795. .alloc_size = sizeof(struct read_instance)
  796. }, {
  797. .type = "sys.socket::write",
  798. .func_new2 = write_func_new,
  799. .func_die = write_func_die,
  800. .alloc_size = sizeof(struct write_instance)
  801. }, {
  802. .type = "sys.socket::close",
  803. .func_new2 = close_func_new
  804. }, {
  805. .type = "sys.listen",
  806. .func_new2 = listen_func_new,
  807. .func_die = listen_func_die,
  808. .func_getvar2 = listen_func_getvar,
  809. .alloc_size = sizeof(struct listen_instance)
  810. }, {
  811. .type = NULL
  812. }
  813. };
  814. const struct NCDModuleGroup ncdmodule_socket = {
  815. .modules = modules,
  816. .strings = strings
  817. };