socket.c 33 KB

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