socket.c 33 KB

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