socket.c 34 KB

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