socket.c 35 KB

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