socket.c 33 KB

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