socket.c 34 KB

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