socket.c 31 KB

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