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