socket.c 33 KB

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