socket.c 33 KB

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