You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lua_tcp.c 59KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566
  1. /*
  2. * Copyright 2024 Vsevolod Stakhov
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "lua_common.h"
  17. #include "lua_thread_pool.h"
  18. #include "libserver/ssl_util.h"
  19. #include "utlist.h"
  20. #include "unix-std.h"
  21. #include <math.h>
  22. static const char *M = "rspamd lua tcp";
  23. /***
  24. * @module rspamd_tcp
  25. * Rspamd TCP module represents generic TCP asynchronous client available from LUA code.
  26. * This module hides all complexity: DNS resolving, sessions management, zero-copy
  27. * text transfers and so on under the hood. It can work in partial or complete modes:
  28. *
  29. * - partial mode is used when you need to call a continuation routine each time data is available for read
  30. * - complete mode calls for continuation merely when all data is read from socket (e.g. when a server sends reply and closes a connection)
  31. * @example
  32. local logger = require "rspamd_logger"
  33. local tcp = require "rspamd_tcp"
  34. rspamd_config.SYM = function(task)
  35. local function cb(err, data)
  36. logger.infox('err: %1, data: %2', err, tostring(data))
  37. end
  38. tcp.request({
  39. task = task,
  40. host = "google.com",
  41. port = 80,
  42. data = {"GET / HTTP/1.0\r\n", "Host: google.com\r\n", "\r\n"},
  43. callback = cb})
  44. end
  45. -- New TCP syntax test
  46. rspamd_config:register_symbol({
  47. name = 'TCP_TEST',
  48. type = "normal",
  49. callback = function(task)
  50. local logger = require "rspamd_logger"
  51. local function rcpt_done_cb(err, data, conn)
  52. logger.errx(task, 'RCPT: got reply: %s, error: %s', data, err)
  53. conn:close()
  54. end
  55. local function rcpt_cb(err, conn)
  56. logger.errx(task, 'written rcpt, error: %s', err)
  57. conn:add_read(rcpt_done_cb, '\r\n')
  58. end
  59. local function from_done_cb(err, data, conn)
  60. logger.errx(task, 'FROM: got reply: %s, error: %s', data, err)
  61. conn:add_write(rcpt_cb, 'RCPT TO: <test@yandex.ru>\r\n')
  62. end
  63. local function from_cb(err, conn)
  64. logger.errx(task, 'written from, error: %s', err)
  65. conn:add_read(from_done_cb, '\r\n')
  66. end
  67. local function hello_done_cb(err, data, conn)
  68. logger.errx(task, 'HELO: got reply: %s, error: %s', data, err)
  69. conn:add_write(from_cb, 'MAIL FROM: <>\r\n')
  70. end
  71. local function hello_cb(err, conn)
  72. logger.errx(task, 'written hello, error: %s', err)
  73. conn:add_read(hello_done_cb, '\r\n')
  74. end
  75. local function init_cb(err, data, conn)
  76. logger.errx(task, 'got reply: %s, error: %s', data, err)
  77. conn:add_write(hello_cb, 'HELO example.com\r\n')
  78. end
  79. tcp.request{
  80. task = task,
  81. callback = init_cb,
  82. stop_pattern = '\r\n',
  83. host = 'mx.yandex.ru',
  84. port = 25
  85. }
  86. end,
  87. priority = 10,
  88. })
  89. */
  90. LUA_FUNCTION_DEF(tcp, request);
  91. /***
  92. * @function rspamd_tcp.connect_sync()
  93. *
  94. * Creates pseudo-synchronous TCP connection.
  95. * Each method of the connection requiring IO, becomes a yielding point,
  96. * i.e. current thread Lua thread is get suspended and resumes as soon as IO is done
  97. *
  98. * This class represents low-level API, using of "lua_tcp_sync" module is recommended.
  99. *
  100. * @example
  101. local rspamd_tcp = require "rspamd_tcp"
  102. local logger = require "rspamd_logger"
  103. local function http_simple_tcp_symbol(task)
  104. local err
  105. local is_ok, connection = rspamd_tcp.connect_sync {
  106. task = task,
  107. host = '127.0.0.1',
  108. timeout = 20,
  109. port = 18080,
  110. ssl = false, -- If SSL connection is needed
  111. ssl_verify = true, -- set to false if verify is not needed
  112. }
  113. is_ok, err = connection:write('GET /request_sync HTTP/1.1\r\nConnection: keep-alive\r\n\r\n')
  114. logger.errx(task, 'write %1, %2', is_ok, err)
  115. if not is_ok then
  116. logger.errx(task, 'write error: %1', err)
  117. end
  118. local data
  119. is_ok, data = connection:read_once();
  120. logger.errx(task, 'read_once: is_ok: %1, data: %2', is_ok, data)
  121. is_ok, err = connection:write("POST /request2 HTTP/1.1\r\n\r\n")
  122. logger.errx(task, 'write[2] %1, %2', is_ok, err)
  123. is_ok, data = connection:read_once();
  124. logger.errx(task, 'read_once[2]: is_ok %1, data: %2', is_ok, data)
  125. connection:close()
  126. end
  127. rspamd_config:register_symbol({
  128. name = 'SIMPLE_TCP_TEST',
  129. score = 1.0,
  130. callback = http_simple_tcp_symbol,
  131. no_squeeze = true
  132. })
  133. *
  134. */
  135. LUA_FUNCTION_DEF(tcp, connect_sync);
  136. /***
  137. * @method tcp:close()
  138. *
  139. * Closes TCP connection
  140. */
  141. LUA_FUNCTION_DEF(tcp, close);
  142. /***
  143. * @method tcp:add_read(callback, [pattern])
  144. *
  145. * Adds new read event to the tcp connection
  146. * @param {function} callback to be called when data is read
  147. * @param {string} pattern optional stop pattern
  148. */
  149. LUA_FUNCTION_DEF(tcp, add_read);
  150. /***
  151. * @method tcp:add_write(callback, data)
  152. *
  153. * Adds new write event to the tcp connection
  154. * @param {function} optional callback to be called when data is completely written
  155. * @param {table/string/text} data to send to a remote server
  156. */
  157. LUA_FUNCTION_DEF(tcp, add_write);
  158. /***
  159. * @method tcp:shift_callback()
  160. *
  161. * Shifts the current callback and go to the next one (if any)
  162. */
  163. LUA_FUNCTION_DEF(tcp, shift_callback);
  164. /***
  165. * @method tcp:starttls([no_verify])
  166. *
  167. * Starts tls connection
  168. * @param {boolean} no_verify used to skip ssl verification
  169. */
  170. LUA_FUNCTION_DEF(tcp, starttls);
  171. static const struct luaL_reg tcp_libf[] = {
  172. LUA_INTERFACE_DEF(tcp, request),
  173. {"new", lua_tcp_request},
  174. {"connect", lua_tcp_request},
  175. {"connect_sync", lua_tcp_connect_sync},
  176. {NULL, NULL}};
  177. static const struct luaL_reg tcp_libm[] = {
  178. LUA_INTERFACE_DEF(tcp, close),
  179. LUA_INTERFACE_DEF(tcp, add_read),
  180. LUA_INTERFACE_DEF(tcp, add_write),
  181. LUA_INTERFACE_DEF(tcp, shift_callback),
  182. LUA_INTERFACE_DEF(tcp, starttls),
  183. {"__tostring", rspamd_lua_class_tostring},
  184. {NULL, NULL}};
  185. /***
  186. * @method tcp:close()
  187. *
  188. * Closes TCP connection
  189. */
  190. LUA_FUNCTION_DEF(tcp_sync, close);
  191. /***
  192. * @method read_once()
  193. *
  194. * Performs one read operation. If syscall returned with EAGAIN/EINT,
  195. * restarts the operation, so it always returns either data or error.
  196. */
  197. LUA_FUNCTION_DEF(tcp_sync, read_once);
  198. /***
  199. * @method eof()
  200. *
  201. * True if last IO operation ended with EOF, i.e. endpoint closed connection
  202. */
  203. LUA_FUNCTION_DEF(tcp_sync, eof);
  204. /***
  205. * @method shutdown()
  206. *
  207. * Half-shutdown TCP connection
  208. */
  209. LUA_FUNCTION_DEF(tcp_sync, shutdown);
  210. /***
  211. * @method write()
  212. *
  213. * Writes data into the stream. If syscall returned with EAGAIN/EINT
  214. * restarts the operation. If performs write() until all the passed
  215. * data is written completely.
  216. */
  217. LUA_FUNCTION_DEF(tcp_sync, write);
  218. LUA_FUNCTION_DEF(tcp_sync, gc);
  219. static void lua_tcp_sync_session_dtor(gpointer ud);
  220. static const struct luaL_reg tcp_sync_libm[] = {
  221. LUA_INTERFACE_DEF(tcp_sync, close),
  222. LUA_INTERFACE_DEF(tcp_sync, read_once),
  223. LUA_INTERFACE_DEF(tcp_sync, write),
  224. LUA_INTERFACE_DEF(tcp_sync, eof),
  225. LUA_INTERFACE_DEF(tcp_sync, shutdown),
  226. {"__gc", lua_tcp_sync_gc},
  227. {"__tostring", rspamd_lua_class_tostring},
  228. {NULL, NULL}};
  229. struct lua_tcp_read_handler {
  230. char *stop_pattern;
  231. unsigned int plen;
  232. int cbref;
  233. };
  234. struct lua_tcp_write_handler {
  235. struct iovec *iov;
  236. unsigned int iovlen;
  237. int cbref;
  238. gsize pos;
  239. gsize total_bytes;
  240. };
  241. enum lua_tcp_handler_type {
  242. LUA_WANT_WRITE = 0,
  243. LUA_WANT_READ,
  244. LUA_WANT_CONNECT
  245. };
  246. struct lua_tcp_handler {
  247. union {
  248. struct lua_tcp_read_handler r;
  249. struct lua_tcp_write_handler w;
  250. } h;
  251. enum lua_tcp_handler_type type;
  252. };
  253. struct lua_tcp_dtor {
  254. rspamd_mempool_destruct_t dtor;
  255. void *data;
  256. struct lua_tcp_dtor *next;
  257. };
  258. #define LUA_TCP_FLAG_PARTIAL (1u << 0u)
  259. #define LUA_TCP_FLAG_SHUTDOWN (1u << 2u)
  260. #define LUA_TCP_FLAG_CONNECTED (1u << 3u)
  261. #define LUA_TCP_FLAG_FINISHED (1u << 4u)
  262. #define LUA_TCP_FLAG_SYNC (1u << 5u)
  263. #define LUA_TCP_FLAG_RESOLVED (1u << 6u)
  264. #define LUA_TCP_FLAG_SSL (1u << 7u)
  265. #define LUA_TCP_FLAG_SSL_NOVERIFY (1u << 8u)
  266. #undef TCP_DEBUG_REFS
  267. #ifdef TCP_DEBUG_REFS
  268. #define TCP_RETAIN(x) \
  269. do { \
  270. msg_info("retain ref %p, refcount: %d", (x), (x)->ref.refcount); \
  271. REF_RETAIN(x); \
  272. } while (0)
  273. #define TCP_RELEASE(x) \
  274. do { \
  275. msg_info("release ref %p, refcount: %d", (x), (x)->ref.refcount); \
  276. REF_RELEASE(x); \
  277. } while (0)
  278. #else
  279. #define TCP_RETAIN(x) REF_RETAIN(x)
  280. #define TCP_RELEASE(x) REF_RELEASE(x)
  281. #endif
  282. struct lua_tcp_cbdata {
  283. struct rspamd_async_session *session;
  284. struct rspamd_async_event *async_ev;
  285. struct ev_loop *event_loop;
  286. rspamd_inet_addr_t *addr;
  287. GByteArray *in;
  288. GQueue *handlers;
  289. int fd;
  290. int connect_cb;
  291. unsigned int port;
  292. unsigned int flags;
  293. char tag[7];
  294. struct rspamd_io_ev ev;
  295. struct lua_tcp_dtor *dtors;
  296. ref_entry_t ref;
  297. struct rspamd_task *task;
  298. struct rspamd_symcache_dynamic_item *item;
  299. struct thread_entry *thread;
  300. struct rspamd_config *cfg;
  301. struct rspamd_ssl_connection *ssl_conn;
  302. char *hostname;
  303. struct upstream *up;
  304. gboolean eof;
  305. };
  306. #define IS_SYNC(c) (((c)->flags & LUA_TCP_FLAG_SYNC) != 0)
  307. #define msg_debug_tcp(...) rspamd_conditional_debug_fast(NULL, cbd->addr, \
  308. rspamd_lua_tcp_log_id, "lua_tcp", cbd->tag, \
  309. G_STRFUNC, \
  310. __VA_ARGS__)
  311. INIT_LOG_MODULE(lua_tcp)
  312. static void lua_tcp_handler(int fd, short what, gpointer ud);
  313. static void lua_tcp_plan_handler_event(struct lua_tcp_cbdata *cbd,
  314. gboolean can_read, gboolean can_write);
  315. static void lua_tcp_unregister_event(struct lua_tcp_cbdata *cbd);
  316. static void
  317. lua_tcp_void_finalyser(gpointer arg)
  318. {
  319. }
  320. static const double default_tcp_timeout = 5.0;
  321. static struct rspamd_dns_resolver *
  322. lua_tcp_global_resolver(struct ev_loop *ev_base,
  323. struct rspamd_config *cfg)
  324. {
  325. static struct rspamd_dns_resolver *global_resolver;
  326. if (cfg && cfg->dns_resolver) {
  327. return cfg->dns_resolver;
  328. }
  329. if (global_resolver == NULL) {
  330. global_resolver = rspamd_dns_resolver_init(NULL, ev_base, cfg);
  331. }
  332. return global_resolver;
  333. }
  334. static gboolean
  335. lua_tcp_shift_handler(struct lua_tcp_cbdata *cbd)
  336. {
  337. struct lua_tcp_handler *hdl;
  338. hdl = g_queue_pop_head(cbd->handlers);
  339. if (hdl == NULL) {
  340. /* We are done */
  341. return FALSE;
  342. }
  343. if (hdl->type == LUA_WANT_READ) {
  344. msg_debug_tcp("switch from read handler %d", hdl->h.r.cbref);
  345. if (hdl->h.r.cbref && hdl->h.r.cbref != -1) {
  346. luaL_unref(cbd->cfg->lua_state, LUA_REGISTRYINDEX, hdl->h.r.cbref);
  347. }
  348. if (hdl->h.r.stop_pattern) {
  349. g_free(hdl->h.r.stop_pattern);
  350. }
  351. }
  352. else if (hdl->type == LUA_WANT_WRITE) {
  353. msg_debug_tcp("switch from write handler %d", hdl->h.r.cbref);
  354. if (hdl->h.w.cbref && hdl->h.w.cbref != -1) {
  355. luaL_unref(cbd->cfg->lua_state, LUA_REGISTRYINDEX, hdl->h.w.cbref);
  356. }
  357. if (hdl->h.w.iov) {
  358. g_free(hdl->h.w.iov);
  359. }
  360. }
  361. else {
  362. msg_debug_tcp("removing connect handler");
  363. /* LUA_WANT_CONNECT: it doesn't allocate anything, nothing to do here */
  364. }
  365. g_free(hdl);
  366. return TRUE;
  367. }
  368. static void
  369. lua_tcp_fin(gpointer arg)
  370. {
  371. struct lua_tcp_cbdata *cbd = (struct lua_tcp_cbdata *) arg;
  372. struct lua_tcp_dtor *dtor, *dttmp;
  373. if (IS_SYNC(cbd) && cbd->task) {
  374. /*
  375. pointer is now becoming invalid, we should remove registered destructor,
  376. all the necessary steps are done here
  377. */
  378. rspamd_mempool_replace_destructor(cbd->task->task_pool,
  379. lua_tcp_sync_session_dtor, cbd, NULL);
  380. }
  381. msg_debug_tcp("finishing TCP %s connection", IS_SYNC(cbd) ? "sync" : "async");
  382. if (cbd->connect_cb != -1) {
  383. luaL_unref(cbd->cfg->lua_state, LUA_REGISTRYINDEX, cbd->connect_cb);
  384. }
  385. if (cbd->ssl_conn) {
  386. /* TODO: postpone close in case ssl is used ! */
  387. rspamd_ssl_connection_free(cbd->ssl_conn);
  388. }
  389. if (cbd->fd != -1) {
  390. rspamd_ev_watcher_stop(cbd->event_loop, &cbd->ev);
  391. close(cbd->fd);
  392. cbd->fd = -1;
  393. }
  394. if (cbd->addr) {
  395. rspamd_inet_address_free(cbd->addr);
  396. }
  397. if (cbd->up) {
  398. rspamd_upstream_unref(cbd->up);
  399. }
  400. while (lua_tcp_shift_handler(cbd)) {}
  401. g_queue_free(cbd->handlers);
  402. LL_FOREACH_SAFE(cbd->dtors, dtor, dttmp)
  403. {
  404. dtor->dtor(dtor->data);
  405. g_free(dtor);
  406. }
  407. g_byte_array_unref(cbd->in);
  408. g_free(cbd->hostname);
  409. g_free(cbd);
  410. }
  411. static struct lua_tcp_cbdata *
  412. lua_check_tcp(lua_State *L, int pos)
  413. {
  414. void *ud = rspamd_lua_check_udata(L, pos, rspamd_tcp_classname);
  415. luaL_argcheck(L, ud != NULL, pos, "'tcp' expected");
  416. return ud ? *((struct lua_tcp_cbdata **) ud) : NULL;
  417. }
  418. static void
  419. lua_tcp_maybe_free(struct lua_tcp_cbdata *cbd)
  420. {
  421. if (IS_SYNC(cbd)) {
  422. /*
  423. * in this mode, we don't remove object, we only remove the event
  424. * Object is owned by lua and will be destroyed on __gc()
  425. */
  426. if (cbd->item) {
  427. rspamd_symcache_item_async_dec_check(cbd->task, cbd->item, M);
  428. cbd->item = NULL;
  429. }
  430. if (cbd->async_ev) {
  431. rspamd_session_remove_event(cbd->session, lua_tcp_void_finalyser, cbd);
  432. }
  433. cbd->async_ev = NULL;
  434. }
  435. else {
  436. if (cbd->item) {
  437. rspamd_symcache_item_async_dec_check(cbd->task, cbd->item, M);
  438. cbd->item = NULL;
  439. }
  440. if (cbd->async_ev) {
  441. rspamd_session_remove_event(cbd->session, lua_tcp_fin, cbd);
  442. }
  443. else {
  444. lua_tcp_fin(cbd);
  445. }
  446. }
  447. }
  448. #ifdef __GNUC__
  449. static void
  450. lua_tcp_push_error(struct lua_tcp_cbdata *cbd, gboolean is_fatal,
  451. const char *err, ...) __attribute__((format(printf, 3, 4)));
  452. #endif
  453. static void lua_tcp_resume_thread_error_argp(struct lua_tcp_cbdata *cbd, const char *error, va_list argp);
  454. static void
  455. lua_tcp_push_error(struct lua_tcp_cbdata *cbd, gboolean is_fatal,
  456. const char *err, ...)
  457. {
  458. va_list ap, ap_copy;
  459. struct lua_tcp_cbdata **pcbd;
  460. struct lua_tcp_handler *hdl;
  461. int cbref, top;
  462. struct lua_callback_state cbs;
  463. lua_State *L;
  464. gboolean callback_called = FALSE;
  465. if (is_fatal && cbd->up) {
  466. rspamd_upstream_fail(cbd->up, false, err);
  467. }
  468. if (cbd->thread) {
  469. va_start(ap, err);
  470. lua_tcp_resume_thread_error_argp(cbd, err, ap);
  471. va_end(ap);
  472. return;
  473. }
  474. lua_thread_pool_prepare_callback(cbd->cfg->lua_thread_pool, &cbs);
  475. L = cbs.L;
  476. va_start(ap, err);
  477. for (;;) {
  478. hdl = g_queue_peek_head(cbd->handlers);
  479. if (hdl == NULL) {
  480. break;
  481. }
  482. if (hdl->type == LUA_WANT_READ) {
  483. cbref = hdl->h.r.cbref;
  484. }
  485. else {
  486. cbref = hdl->h.w.cbref;
  487. }
  488. if (cbref != -1) {
  489. top = lua_gettop(L);
  490. lua_rawgeti(L, LUA_REGISTRYINDEX, cbref);
  491. /* Error message */
  492. va_copy(ap_copy, ap);
  493. lua_pushvfstring(L, err, ap_copy);
  494. va_end(ap_copy);
  495. /* Body */
  496. lua_pushnil(L);
  497. /* Connection */
  498. pcbd = lua_newuserdata(L, sizeof(*pcbd));
  499. *pcbd = cbd;
  500. rspamd_lua_setclass(L, rspamd_tcp_classname, -1);
  501. TCP_RETAIN(cbd);
  502. if (cbd->item) {
  503. rspamd_symcache_set_cur_item(cbd->task, cbd->item);
  504. }
  505. if (lua_pcall(L, 3, 0, 0) != 0) {
  506. msg_info("callback call failed: %s", lua_tostring(L, -1));
  507. }
  508. lua_settop(L, top);
  509. TCP_RELEASE(cbd);
  510. if ((cbd->flags & (LUA_TCP_FLAG_FINISHED | LUA_TCP_FLAG_CONNECTED)) ==
  511. (LUA_TCP_FLAG_FINISHED | LUA_TCP_FLAG_CONNECTED)) {
  512. /* A callback has called `close` method, so we need to release a refcount */
  513. TCP_RELEASE(cbd);
  514. }
  515. callback_called = TRUE;
  516. }
  517. if (!is_fatal) {
  518. if (callback_called) {
  519. /* Stop on the first callback found */
  520. break;
  521. }
  522. else {
  523. /* Shift to another callback to inform about non fatal error */
  524. msg_debug_tcp("non fatal error find matching callback");
  525. lua_tcp_shift_handler(cbd);
  526. continue;
  527. }
  528. }
  529. else {
  530. msg_debug_tcp("fatal error rollback all handlers");
  531. lua_tcp_shift_handler(cbd);
  532. }
  533. }
  534. va_end(ap);
  535. lua_thread_pool_restore_callback(&cbs);
  536. }
  537. static void lua_tcp_resume_thread(struct lua_tcp_cbdata *cbd, const uint8_t *str, gsize len);
  538. static void
  539. lua_tcp_push_data(struct lua_tcp_cbdata *cbd, const uint8_t *str, gsize len)
  540. {
  541. struct rspamd_lua_text *t;
  542. struct lua_tcp_cbdata **pcbd;
  543. struct lua_tcp_handler *hdl;
  544. int cbref, arg_cnt, top;
  545. struct lua_callback_state cbs;
  546. lua_State *L;
  547. if (cbd->thread) {
  548. lua_tcp_resume_thread(cbd, str, len);
  549. return;
  550. }
  551. lua_thread_pool_prepare_callback(cbd->cfg->lua_thread_pool, &cbs);
  552. L = cbs.L;
  553. hdl = g_queue_peek_head(cbd->handlers);
  554. g_assert(hdl != NULL);
  555. if (hdl->type == LUA_WANT_READ) {
  556. cbref = hdl->h.r.cbref;
  557. }
  558. else {
  559. cbref = hdl->h.w.cbref;
  560. }
  561. if (cbref != -1) {
  562. top = lua_gettop(L);
  563. lua_rawgeti(L, LUA_REGISTRYINDEX, cbref);
  564. /* Error */
  565. lua_pushnil(L);
  566. /* Body */
  567. if (hdl->type == LUA_WANT_READ) {
  568. t = lua_newuserdata(L, sizeof(*t));
  569. rspamd_lua_setclass(L, rspamd_text_classname, -1);
  570. t->start = (const char *) str;
  571. t->len = len;
  572. t->flags = 0;
  573. arg_cnt = 3;
  574. }
  575. else {
  576. arg_cnt = 2;
  577. }
  578. /* Connection */
  579. pcbd = lua_newuserdata(L, sizeof(*pcbd));
  580. *pcbd = cbd;
  581. rspamd_lua_setclass(L, rspamd_tcp_classname, -1);
  582. TCP_RETAIN(cbd);
  583. if (cbd->item) {
  584. rspamd_symcache_set_cur_item(cbd->task, cbd->item);
  585. }
  586. if (lua_pcall(L, arg_cnt, 0, 0) != 0) {
  587. msg_info("callback call failed: %s", lua_tostring(L, -1));
  588. }
  589. lua_settop(L, top);
  590. TCP_RELEASE(cbd);
  591. if ((cbd->flags & (LUA_TCP_FLAG_FINISHED | LUA_TCP_FLAG_CONNECTED)) ==
  592. (LUA_TCP_FLAG_FINISHED | LUA_TCP_FLAG_CONNECTED)) {
  593. /* A callback has called `close` method, so we need to release a refcount */
  594. TCP_RELEASE(cbd);
  595. }
  596. }
  597. lua_thread_pool_restore_callback(&cbs);
  598. }
  599. static void
  600. lua_tcp_resume_thread_error_argp(struct lua_tcp_cbdata *cbd, const char *error, va_list argp)
  601. {
  602. struct thread_entry *thread = cbd->thread;
  603. lua_State *L = thread->lua_state;
  604. lua_pushboolean(L, FALSE);
  605. lua_pushvfstring(L, error, argp);
  606. lua_tcp_shift_handler(cbd);
  607. // lua_tcp_unregister_event (cbd);
  608. lua_thread_pool_set_running_entry(cbd->cfg->lua_thread_pool, cbd->thread);
  609. lua_thread_resume(thread, 2);
  610. TCP_RELEASE(cbd);
  611. }
  612. static void
  613. lua_tcp_resume_thread(struct lua_tcp_cbdata *cbd, const uint8_t *str, gsize len)
  614. {
  615. /*
  616. * typical call returns:
  617. *
  618. * read:
  619. * error:
  620. * (nil, error message)
  621. * got data:
  622. * (true, data)
  623. * write/connect:
  624. * error:
  625. * (nil, error message)
  626. * wrote
  627. * (true)
  628. */
  629. lua_State *L = cbd->thread->lua_state;
  630. struct lua_tcp_handler *hdl;
  631. hdl = g_queue_peek_head(cbd->handlers);
  632. lua_pushboolean(L, TRUE);
  633. if (hdl->type == LUA_WANT_READ) {
  634. lua_pushlstring(L, str, len);
  635. }
  636. else {
  637. lua_pushnil(L);
  638. }
  639. lua_tcp_shift_handler(cbd);
  640. lua_thread_pool_set_running_entry(cbd->cfg->lua_thread_pool,
  641. cbd->thread);
  642. if (cbd->item) {
  643. rspamd_symcache_set_cur_item(cbd->task, cbd->item);
  644. }
  645. lua_thread_resume(cbd->thread, 2);
  646. TCP_RELEASE(cbd);
  647. }
  648. static void
  649. lua_tcp_plan_read(struct lua_tcp_cbdata *cbd)
  650. {
  651. rspamd_ev_watcher_reschedule(cbd->event_loop, &cbd->ev, EV_READ);
  652. }
  653. static void
  654. lua_tcp_connect_helper(struct lua_tcp_cbdata *cbd)
  655. {
  656. /* This is used for sync mode only */
  657. lua_State *L = cbd->thread->lua_state;
  658. struct lua_tcp_cbdata **pcbd;
  659. lua_pushboolean(L, TRUE);
  660. lua_thread_pool_set_running_entry(cbd->cfg->lua_thread_pool, cbd->thread);
  661. pcbd = lua_newuserdata(L, sizeof(*pcbd));
  662. *pcbd = cbd;
  663. rspamd_lua_setclass(L, rspamd_tcp_sync_classname, -1);
  664. msg_debug_tcp("tcp connected");
  665. lua_tcp_shift_handler(cbd);
  666. // lua_tcp_unregister_event (cbd);
  667. lua_thread_resume(cbd->thread, 2);
  668. TCP_RELEASE(cbd);
  669. }
  670. static void
  671. lua_tcp_write_helper(struct lua_tcp_cbdata *cbd)
  672. {
  673. struct iovec *start;
  674. unsigned int niov, i;
  675. int flags = 0;
  676. bool allocated_iov = false;
  677. gsize remain;
  678. gssize r;
  679. struct iovec *cur_iov;
  680. struct lua_tcp_handler *hdl;
  681. struct lua_tcp_write_handler *wh;
  682. struct msghdr msg;
  683. hdl = g_queue_peek_head(cbd->handlers);
  684. g_assert(hdl != NULL && hdl->type == LUA_WANT_WRITE);
  685. wh = &hdl->h.w;
  686. if (wh->pos == wh->total_bytes) {
  687. goto call_finish_handler;
  688. }
  689. start = &wh->iov[0];
  690. niov = wh->iovlen;
  691. remain = wh->pos;
  692. /* We know that niov is small enough for that */
  693. if (niov < 1024) {
  694. cur_iov = g_alloca(niov * sizeof(struct iovec));
  695. }
  696. else {
  697. cur_iov = g_malloc0(niov * sizeof(struct iovec));
  698. allocated_iov = true;
  699. }
  700. memcpy(cur_iov, wh->iov, niov * sizeof(struct iovec));
  701. for (i = 0; i < wh->iovlen && remain > 0; i++) {
  702. /* Find out the first iov required */
  703. start = &cur_iov[i];
  704. if (start->iov_len <= remain) {
  705. remain -= start->iov_len;
  706. start = &cur_iov[i + 1];
  707. niov--;
  708. }
  709. else {
  710. start->iov_base = (void *) ((char *) start->iov_base + remain);
  711. start->iov_len -= remain;
  712. remain = 0;
  713. }
  714. }
  715. memset(&msg, 0, sizeof(msg));
  716. msg.msg_iov = start;
  717. msg.msg_iovlen = MIN(IOV_MAX, niov);
  718. g_assert(niov > 0);
  719. #ifdef MSG_NOSIGNAL
  720. flags = MSG_NOSIGNAL;
  721. #endif
  722. msg_debug_tcp("want write %d io vectors of %d", (int) msg.msg_iovlen,
  723. (int) niov);
  724. if (cbd->ssl_conn) {
  725. r = rspamd_ssl_writev(cbd->ssl_conn, msg.msg_iov, msg.msg_iovlen);
  726. }
  727. else {
  728. r = sendmsg(cbd->fd, &msg, flags);
  729. }
  730. if (allocated_iov) {
  731. g_free(cur_iov);
  732. }
  733. if (r == -1) {
  734. if (!(cbd->ssl_conn)) {
  735. if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
  736. msg_debug_tcp("got temporary failure, retry write");
  737. lua_tcp_plan_handler_event(cbd, TRUE, TRUE);
  738. return;
  739. }
  740. else {
  741. lua_tcp_push_error(cbd, TRUE,
  742. "IO write error while trying to write %d bytes: %s",
  743. (int) remain, strerror(errno));
  744. msg_debug_tcp("write error, terminate connection");
  745. TCP_RELEASE(cbd);
  746. }
  747. }
  748. return;
  749. }
  750. else {
  751. wh->pos += r;
  752. }
  753. msg_debug_tcp("written %z bytes: %z/%z", r,
  754. wh->pos, wh->total_bytes);
  755. if (wh->pos >= wh->total_bytes) {
  756. goto call_finish_handler;
  757. }
  758. else {
  759. /* Want to write more */
  760. if (r > 0) {
  761. /* XXX: special case: we know that we want to write more data
  762. * than it is available in iov function.
  763. *
  764. * Hence, we need to check if we can write more at some point...
  765. */
  766. lua_tcp_write_helper(cbd);
  767. }
  768. }
  769. return;
  770. call_finish_handler:
  771. msg_debug_tcp("finishing TCP write, calling TCP handler");
  772. if ((cbd->flags & LUA_TCP_FLAG_SHUTDOWN)) {
  773. /* Half close the connection */
  774. shutdown(cbd->fd, SHUT_WR);
  775. cbd->flags &= ~LUA_TCP_FLAG_SHUTDOWN;
  776. }
  777. if (cbd->up) {
  778. rspamd_upstream_ok(cbd->up);
  779. }
  780. lua_tcp_push_data(cbd, NULL, 0);
  781. if (!IS_SYNC(cbd)) {
  782. lua_tcp_shift_handler(cbd);
  783. lua_tcp_plan_handler_event(cbd, TRUE, TRUE);
  784. }
  785. }
  786. static gboolean
  787. lua_tcp_process_read_handler(struct lua_tcp_cbdata *cbd,
  788. struct lua_tcp_read_handler *rh, gboolean eof)
  789. {
  790. unsigned int slen;
  791. goffset pos;
  792. if (rh->stop_pattern) {
  793. slen = rh->plen;
  794. if (cbd->in->len >= slen) {
  795. if ((pos = rspamd_substring_search(cbd->in->data, cbd->in->len,
  796. rh->stop_pattern, slen)) != -1) {
  797. msg_debug_tcp("found TCP stop pattern");
  798. lua_tcp_push_data(cbd, cbd->in->data, pos);
  799. if (!IS_SYNC(cbd)) {
  800. lua_tcp_shift_handler(cbd);
  801. }
  802. if (pos + slen < cbd->in->len) {
  803. /* We have a leftover */
  804. memmove(cbd->in->data, cbd->in->data + pos + slen,
  805. cbd->in->len - (pos + slen));
  806. cbd->in->len = cbd->in->len - (pos + slen);
  807. }
  808. else {
  809. cbd->in->len = 0;
  810. }
  811. return TRUE;
  812. }
  813. else {
  814. /* Plan new read */
  815. msg_debug_tcp("NOT found TCP stop pattern");
  816. if (!cbd->eof) {
  817. lua_tcp_plan_read(cbd);
  818. }
  819. else {
  820. /* Got session finished but no stop pattern */
  821. lua_tcp_push_error(cbd, TRUE,
  822. "IO read error: connection terminated");
  823. }
  824. }
  825. }
  826. }
  827. else {
  828. msg_debug_tcp("read TCP partial data %d bytes", cbd->in->len);
  829. slen = cbd->in->len;
  830. /* we have eaten all the data, handler should not know that there is something */
  831. cbd->in->len = 0;
  832. lua_tcp_push_data(cbd, cbd->in->data, slen);
  833. if (!IS_SYNC(cbd)) {
  834. lua_tcp_shift_handler(cbd);
  835. }
  836. return TRUE;
  837. }
  838. return FALSE;
  839. }
  840. static void
  841. lua_tcp_process_read(struct lua_tcp_cbdata *cbd,
  842. unsigned char *in, gssize r)
  843. {
  844. struct lua_tcp_handler *hdl;
  845. struct lua_tcp_read_handler *rh;
  846. hdl = g_queue_peek_head(cbd->handlers);
  847. g_assert(hdl != NULL && hdl->type == LUA_WANT_READ);
  848. rh = &hdl->h.r;
  849. if (r > 0) {
  850. if (cbd->flags & LUA_TCP_FLAG_PARTIAL) {
  851. lua_tcp_push_data(cbd, in, r);
  852. /* Plan next event */
  853. lua_tcp_plan_read(cbd);
  854. }
  855. else {
  856. g_byte_array_append(cbd->in, in, r);
  857. if (!lua_tcp_process_read_handler(cbd, rh, FALSE)) {
  858. /* Plan more read */
  859. lua_tcp_plan_read(cbd);
  860. }
  861. else {
  862. /* Go towards the next handler */
  863. if (!IS_SYNC(cbd)) {
  864. lua_tcp_plan_handler_event(cbd, TRUE, TRUE);
  865. }
  866. }
  867. }
  868. }
  869. else if (r == 0) {
  870. /* EOF */
  871. cbd->eof = TRUE;
  872. if (cbd->in->len > 0) {
  873. /* We have some data to process */
  874. lua_tcp_process_read_handler(cbd, rh, TRUE);
  875. }
  876. else {
  877. lua_tcp_push_error(cbd, TRUE, "IO read error: connection terminated");
  878. if ((cbd->flags & LUA_TCP_FLAG_FINISHED)) {
  879. /* A callback has called `close` method, so we need to release a refcount */
  880. TCP_RELEASE(cbd);
  881. }
  882. }
  883. lua_tcp_plan_handler_event(cbd, FALSE, FALSE);
  884. }
  885. else {
  886. /* An error occurred */
  887. if (errno == EAGAIN || errno == EINTR) {
  888. /* Restart call */
  889. lua_tcp_plan_read(cbd);
  890. return;
  891. }
  892. /* Fatal error */
  893. cbd->eof = TRUE;
  894. if (cbd->in->len > 0) {
  895. /* We have some data to process */
  896. lua_tcp_process_read_handler(cbd, rh, TRUE);
  897. }
  898. else {
  899. lua_tcp_push_error(cbd, TRUE,
  900. "IO read error while trying to read data: %s",
  901. strerror(errno));
  902. if ((cbd->flags & LUA_TCP_FLAG_FINISHED)) {
  903. /* A callback has called `close` method, so we need to release a refcount */
  904. TCP_RELEASE(cbd);
  905. }
  906. }
  907. lua_tcp_plan_handler_event(cbd, FALSE, FALSE);
  908. }
  909. }
  910. static void
  911. lua_tcp_handler(int fd, short what, gpointer ud)
  912. {
  913. struct lua_tcp_cbdata *cbd = ud;
  914. unsigned char inbuf[8192];
  915. gssize r;
  916. int so_error = 0;
  917. socklen_t so_len = sizeof(so_error);
  918. struct lua_callback_state cbs;
  919. lua_State *L;
  920. enum lua_tcp_handler_type event_type;
  921. TCP_RETAIN(cbd);
  922. msg_debug_tcp("processed TCP event: %d", what);
  923. struct lua_tcp_handler *rh = g_queue_peek_head(cbd->handlers);
  924. event_type = rh->type;
  925. rspamd_ev_watcher_stop(cbd->event_loop, &cbd->ev);
  926. if (what == EV_READ) {
  927. if (cbd->ssl_conn) {
  928. r = rspamd_ssl_read(cbd->ssl_conn, inbuf, sizeof(inbuf));
  929. }
  930. else {
  931. r = read(cbd->fd, inbuf, sizeof(inbuf));
  932. }
  933. lua_tcp_process_read(cbd, inbuf, r);
  934. }
  935. else if (what == EV_WRITE) {
  936. if (!(cbd->flags & LUA_TCP_FLAG_CONNECTED)) {
  937. if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &so_error, &so_len) == -1) {
  938. lua_tcp_push_error(cbd, TRUE, "Cannot get socket error: %s",
  939. strerror(errno));
  940. TCP_RELEASE(cbd);
  941. goto out;
  942. }
  943. else if (so_error != 0) {
  944. lua_tcp_push_error(cbd, TRUE, "Socket error detected: %s",
  945. strerror(so_error));
  946. TCP_RELEASE(cbd);
  947. goto out;
  948. }
  949. else {
  950. cbd->flags |= LUA_TCP_FLAG_CONNECTED;
  951. if (cbd->connect_cb != -1) {
  952. struct lua_tcp_cbdata **pcbd;
  953. int top;
  954. lua_thread_pool_prepare_callback(cbd->cfg->lua_thread_pool, &cbs);
  955. L = cbs.L;
  956. top = lua_gettop(L);
  957. lua_rawgeti(L, LUA_REGISTRYINDEX, cbd->connect_cb);
  958. pcbd = lua_newuserdata(L, sizeof(*pcbd));
  959. *pcbd = cbd;
  960. TCP_RETAIN(cbd);
  961. rspamd_lua_setclass(L, rspamd_tcp_classname, -1);
  962. if (cbd->item) {
  963. rspamd_symcache_set_cur_item(cbd->task, cbd->item);
  964. }
  965. if (lua_pcall(L, 1, 0, 0) != 0) {
  966. msg_info("callback call failed: %s", lua_tostring(L, -1));
  967. }
  968. lua_settop(L, top);
  969. TCP_RELEASE(cbd);
  970. lua_thread_pool_restore_callback(&cbs);
  971. if ((cbd->flags & (LUA_TCP_FLAG_FINISHED | LUA_TCP_FLAG_CONNECTED)) ==
  972. (LUA_TCP_FLAG_FINISHED | LUA_TCP_FLAG_CONNECTED)) {
  973. /* A callback has called `close` method, so we need to release a refcount */
  974. TCP_RELEASE(cbd);
  975. }
  976. }
  977. }
  978. }
  979. if (event_type == LUA_WANT_WRITE) {
  980. lua_tcp_write_helper(cbd);
  981. }
  982. else if (event_type == LUA_WANT_CONNECT) {
  983. lua_tcp_connect_helper(cbd);
  984. }
  985. else {
  986. g_assert_not_reached();
  987. }
  988. if ((cbd->flags & (LUA_TCP_FLAG_FINISHED | LUA_TCP_FLAG_CONNECTED)) ==
  989. (LUA_TCP_FLAG_FINISHED | LUA_TCP_FLAG_CONNECTED)) {
  990. /* A callback has called `close` method, so we need to release a refcount */
  991. TCP_RELEASE(cbd);
  992. }
  993. }
  994. else {
  995. lua_tcp_push_error(cbd, TRUE, "IO timeout");
  996. TCP_RELEASE(cbd);
  997. }
  998. out:
  999. TCP_RELEASE(cbd);
  1000. }
  1001. static void
  1002. lua_tcp_plan_handler_event(struct lua_tcp_cbdata *cbd, gboolean can_read,
  1003. gboolean can_write)
  1004. {
  1005. struct lua_tcp_handler *hdl;
  1006. hdl = g_queue_peek_head(cbd->handlers);
  1007. if (hdl == NULL) {
  1008. if (!(cbd->flags & LUA_TCP_FLAG_FINISHED)) {
  1009. /* We are finished with a connection */
  1010. msg_debug_tcp("no handlers left, finish session");
  1011. cbd->flags |= LUA_TCP_FLAG_FINISHED;
  1012. TCP_RELEASE(cbd);
  1013. }
  1014. }
  1015. else {
  1016. if (hdl->type == LUA_WANT_READ) {
  1017. /* We need to check if we have some leftover in the buffer */
  1018. if (cbd->in->len > 0) {
  1019. msg_debug_tcp("process read buffer leftover");
  1020. if (lua_tcp_process_read_handler(cbd, &hdl->h.r, FALSE)) {
  1021. if (!IS_SYNC(cbd)) {
  1022. /* We can go to the next handler */
  1023. lua_tcp_plan_handler_event(cbd, can_read, can_write);
  1024. }
  1025. }
  1026. }
  1027. else {
  1028. if (can_read) {
  1029. /* We need to plan a new event */
  1030. msg_debug_tcp("plan new read");
  1031. rspamd_ev_watcher_reschedule(cbd->event_loop, &cbd->ev,
  1032. EV_READ);
  1033. }
  1034. else {
  1035. /* Cannot read more */
  1036. msg_debug_tcp("cannot read more");
  1037. lua_tcp_push_error(cbd, FALSE, "EOF, cannot read more data");
  1038. if (!IS_SYNC(cbd)) {
  1039. lua_tcp_shift_handler(cbd);
  1040. lua_tcp_plan_handler_event(cbd, can_read, can_write);
  1041. }
  1042. }
  1043. }
  1044. }
  1045. else if (hdl->type == LUA_WANT_WRITE) {
  1046. /*
  1047. * We need to plan write event if there is something in the
  1048. * write request
  1049. */
  1050. if (hdl->h.w.pos < hdl->h.w.total_bytes) {
  1051. msg_debug_tcp("plan new write");
  1052. if (can_write) {
  1053. rspamd_ev_watcher_reschedule(cbd->event_loop, &cbd->ev,
  1054. EV_WRITE);
  1055. }
  1056. else {
  1057. /* Cannot write more */
  1058. lua_tcp_push_error(cbd, FALSE, "EOF, cannot write more data");
  1059. if (!IS_SYNC(cbd)) {
  1060. lua_tcp_shift_handler(cbd);
  1061. lua_tcp_plan_handler_event(cbd, can_read, can_write);
  1062. }
  1063. }
  1064. }
  1065. else {
  1066. /* We shouldn't have empty write handlers */
  1067. g_assert_not_reached();
  1068. }
  1069. }
  1070. else { /* LUA_WANT_CONNECT */
  1071. msg_debug_tcp("plan new connect");
  1072. rspamd_ev_watcher_reschedule(cbd->event_loop, &cbd->ev,
  1073. EV_WRITE);
  1074. }
  1075. }
  1076. }
  1077. static gboolean
  1078. lua_tcp_register_event(struct lua_tcp_cbdata *cbd)
  1079. {
  1080. if (cbd->session) {
  1081. event_finalizer_t fin = IS_SYNC(cbd) ? lua_tcp_void_finalyser : lua_tcp_fin;
  1082. if (cbd->item) {
  1083. cbd->async_ev = rspamd_session_add_event_full(cbd->session, fin, cbd, M,
  1084. rspamd_symcache_dyn_item_name(cbd->task, cbd->item));
  1085. }
  1086. else {
  1087. cbd->async_ev = rspamd_session_add_event(cbd->session, fin, cbd, M);
  1088. }
  1089. if (!cbd->async_ev) {
  1090. return FALSE;
  1091. }
  1092. }
  1093. return TRUE;
  1094. }
  1095. static void
  1096. lua_tcp_register_watcher(struct lua_tcp_cbdata *cbd)
  1097. {
  1098. if (cbd->item && cbd->task) {
  1099. rspamd_symcache_item_async_inc(cbd->task, cbd->item, M);
  1100. }
  1101. }
  1102. static void
  1103. lua_tcp_ssl_on_error(gpointer ud, GError *err)
  1104. {
  1105. struct lua_tcp_cbdata *cbd = (struct lua_tcp_cbdata *) ud;
  1106. if (err) {
  1107. lua_tcp_push_error(cbd, TRUE, "ssl error: %s", err->message);
  1108. }
  1109. else {
  1110. lua_tcp_push_error(cbd, TRUE, "ssl error: unknown error");
  1111. }
  1112. TCP_RELEASE(cbd);
  1113. }
  1114. static gboolean
  1115. lua_tcp_make_connection(struct lua_tcp_cbdata *cbd)
  1116. {
  1117. int fd;
  1118. rspamd_inet_address_set_port(cbd->addr, cbd->port);
  1119. fd = rspamd_inet_address_connect(cbd->addr, SOCK_STREAM, TRUE);
  1120. if (fd == -1) {
  1121. if (cbd->session) {
  1122. rspamd_mempool_t *pool = rspamd_session_mempool(cbd->session);
  1123. msg_info_pool("cannot connect to %s (%s): %s",
  1124. rspamd_inet_address_to_string(cbd->addr),
  1125. cbd->hostname,
  1126. strerror(errno));
  1127. }
  1128. else {
  1129. msg_info("cannot connect to %s (%s): %s",
  1130. rspamd_inet_address_to_string(cbd->addr),
  1131. cbd->hostname,
  1132. strerror(errno));
  1133. }
  1134. return FALSE;
  1135. }
  1136. cbd->fd = fd;
  1137. #if 0
  1138. if (!(cbd->flags & LUA_TCP_FLAG_RESOLVED)) {
  1139. /* We come here without resolving, so we need to add a watcher */
  1140. lua_tcp_register_watcher (cbd);
  1141. }
  1142. else {
  1143. cbd->flags |= LUA_TCP_FLAG_RESOLVED;
  1144. }
  1145. #endif
  1146. if (cbd->flags & LUA_TCP_FLAG_SSL) {
  1147. gpointer ssl_ctx;
  1148. gboolean verify_peer;
  1149. if (cbd->flags & LUA_TCP_FLAG_SSL_NOVERIFY) {
  1150. ssl_ctx = cbd->cfg->libs_ctx->ssl_ctx_noverify;
  1151. verify_peer = FALSE;
  1152. }
  1153. else {
  1154. ssl_ctx = cbd->cfg->libs_ctx->ssl_ctx;
  1155. verify_peer = TRUE;
  1156. }
  1157. cbd->ssl_conn = rspamd_ssl_connection_new(ssl_ctx,
  1158. cbd->event_loop,
  1159. verify_peer,
  1160. cbd->tag);
  1161. if (!rspamd_ssl_connect_fd(cbd->ssl_conn, fd, cbd->hostname, &cbd->ev,
  1162. cbd->ev.timeout, lua_tcp_handler, lua_tcp_ssl_on_error, cbd)) {
  1163. lua_tcp_push_error(cbd, TRUE, "ssl connection failed: %s",
  1164. strerror(errno));
  1165. return FALSE;
  1166. }
  1167. else {
  1168. lua_tcp_register_event(cbd);
  1169. }
  1170. }
  1171. else {
  1172. rspamd_ev_watcher_init(&cbd->ev, cbd->fd, EV_WRITE,
  1173. lua_tcp_handler, cbd);
  1174. lua_tcp_register_event(cbd);
  1175. lua_tcp_plan_handler_event(cbd, TRUE, TRUE);
  1176. }
  1177. return TRUE;
  1178. }
  1179. static void
  1180. lua_tcp_dns_handler(struct rdns_reply *reply, gpointer ud)
  1181. {
  1182. struct lua_tcp_cbdata *cbd = (struct lua_tcp_cbdata *) ud;
  1183. const struct rdns_request_name *rn;
  1184. if (reply->code != RDNS_RC_NOERROR) {
  1185. rn = rdns_request_get_name(reply->request, NULL);
  1186. lua_tcp_push_error(cbd, TRUE, "unable to resolve host: %s",
  1187. rn->name);
  1188. TCP_RELEASE(cbd);
  1189. }
  1190. else {
  1191. /*
  1192. * We set this flag as it means that we have already registered the watcher
  1193. * when started DNS query
  1194. */
  1195. struct rdns_reply_entry *entry;
  1196. DL_FOREACH(reply->entries, entry)
  1197. {
  1198. if (entry->type == RDNS_REQUEST_A) {
  1199. cbd->addr = rspamd_inet_address_new(AF_INET,
  1200. &entry->content.a.addr);
  1201. break;
  1202. }
  1203. else if (entry->type == RDNS_REQUEST_AAAA) {
  1204. cbd->addr = rspamd_inet_address_new(AF_INET6,
  1205. &entry->content.aaa.addr);
  1206. break;
  1207. }
  1208. }
  1209. if (cbd->addr == NULL) {
  1210. rn = rdns_request_get_name(reply->request, NULL);
  1211. lua_tcp_push_error(cbd, TRUE, "unable to resolve host: %s; no records with this name",
  1212. rn->name);
  1213. TCP_RELEASE(cbd);
  1214. return;
  1215. }
  1216. cbd->flags |= LUA_TCP_FLAG_RESOLVED;
  1217. rspamd_inet_address_set_port(cbd->addr, cbd->port);
  1218. if (!lua_tcp_make_connection(cbd)) {
  1219. lua_tcp_push_error(cbd, TRUE, "unable to make connection to the host %s",
  1220. rspamd_inet_address_to_string(cbd->addr));
  1221. TCP_RELEASE(cbd);
  1222. }
  1223. }
  1224. }
  1225. static gboolean
  1226. lua_tcp_arg_toiovec(lua_State *L, int pos, struct lua_tcp_cbdata *cbd,
  1227. struct iovec *vec)
  1228. {
  1229. struct rspamd_lua_text *t;
  1230. gsize len;
  1231. const char *str;
  1232. struct lua_tcp_dtor *dtor;
  1233. if (lua_type(L, pos) == LUA_TUSERDATA) {
  1234. t = lua_check_text(L, pos);
  1235. if (t) {
  1236. vec->iov_base = (void *) t->start;
  1237. vec->iov_len = t->len;
  1238. if (t->flags & RSPAMD_TEXT_FLAG_OWN) {
  1239. /* Steal ownership */
  1240. t->flags = 0;
  1241. dtor = g_malloc0(sizeof(*dtor));
  1242. dtor->dtor = g_free;
  1243. dtor->data = (void *) t->start;
  1244. LL_PREPEND(cbd->dtors, dtor);
  1245. }
  1246. }
  1247. else {
  1248. msg_err("bad userdata argument at position %d", pos);
  1249. return FALSE;
  1250. }
  1251. }
  1252. else if (lua_type(L, pos) == LUA_TSTRING) {
  1253. str = luaL_checklstring(L, pos, &len);
  1254. vec->iov_base = g_malloc(len);
  1255. dtor = g_malloc0(sizeof(*dtor));
  1256. dtor->dtor = g_free;
  1257. dtor->data = vec->iov_base;
  1258. LL_PREPEND(cbd->dtors, dtor);
  1259. memcpy(vec->iov_base, str, len);
  1260. vec->iov_len = len;
  1261. }
  1262. else {
  1263. msg_err("bad argument at position %d", pos);
  1264. return FALSE;
  1265. }
  1266. return TRUE;
  1267. }
  1268. /***
  1269. * @function rspamd_tcp.request({params})
  1270. * This function creates and sends TCP request to the specified host and port,
  1271. * resolves hostname (if needed) and invokes continuation callback upon data received
  1272. * from the remote peer. This function accepts table of arguments with the following
  1273. * attributes
  1274. *
  1275. * - `task`: rspamd task objects (implies `pool`, `session`, `ev_base` and `resolver` arguments)
  1276. * - `ev_base`: event base (if no task specified)
  1277. * - `resolver`: DNS resolver (no task)
  1278. * - `session`: events session (no task)
  1279. * - `host`: IP or name of the peer (required)
  1280. * - `port`: remote port to use
  1281. * - `data`: a table of strings or `rspamd_text` objects that contains data pieces
  1282. * - `callback`: continuation function (required)
  1283. * - `on_connect`: callback called on connection success
  1284. * - `timeout`: floating point value that specifies timeout for IO operations in **seconds**
  1285. * - `partial`: boolean flag that specifies that callback should be called on any data portion received
  1286. * - `stop_pattern`: stop reading on finding a certain pattern (e.g. \r\n.\r\n for smtp)
  1287. * - `shutdown`: half-close socket after writing (boolean: default false)
  1288. * - `read`: read response after sending request (boolean: default true)
  1289. * - `upstream`: optional upstream object that would be used to get an address
  1290. * @return {boolean} true if request has been sent
  1291. */
  1292. static int
  1293. lua_tcp_request(lua_State *L)
  1294. {
  1295. LUA_TRACE_POINT;
  1296. const char *host;
  1297. char *stop_pattern = NULL;
  1298. unsigned int port;
  1299. int cbref, tp, conn_cbref = -1;
  1300. gsize plen = 0;
  1301. struct ev_loop *event_loop = NULL;
  1302. struct lua_tcp_cbdata *cbd;
  1303. struct rspamd_dns_resolver *resolver = NULL;
  1304. struct rspamd_async_session *session = NULL;
  1305. struct rspamd_task *task = NULL;
  1306. struct rspamd_config *cfg = NULL;
  1307. struct iovec *iov = NULL;
  1308. struct upstream *up = NULL;
  1309. unsigned int niov = 0, total_out;
  1310. uint64_t h;
  1311. double timeout = default_tcp_timeout;
  1312. gboolean partial = FALSE, do_shutdown = FALSE, do_read = TRUE,
  1313. ssl = FALSE, ssl_noverify = FALSE;
  1314. if (lua_type(L, 1) == LUA_TTABLE) {
  1315. lua_pushstring(L, "host");
  1316. lua_gettable(L, -2);
  1317. host = luaL_checkstring(L, -1);
  1318. lua_pop(L, 1);
  1319. lua_pushstring(L, "port");
  1320. lua_gettable(L, -2);
  1321. if (lua_type(L, -1) == LUA_TNUMBER) {
  1322. port = lua_tointeger(L, -1);
  1323. }
  1324. else {
  1325. /* We assume that it is a unix socket */
  1326. port = 0;
  1327. }
  1328. lua_pop(L, 1);
  1329. lua_pushstring(L, "callback");
  1330. lua_gettable(L, -2);
  1331. if (host == NULL || lua_type(L, -1) != LUA_TFUNCTION) {
  1332. lua_pop(L, 1);
  1333. msg_err("tcp request has bad params");
  1334. lua_pushboolean(L, FALSE);
  1335. return 1;
  1336. }
  1337. cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  1338. cbd = g_malloc0(sizeof(*cbd));
  1339. lua_pushstring(L, "task");
  1340. lua_gettable(L, -2);
  1341. if (lua_type(L, -1) == LUA_TUSERDATA) {
  1342. task = lua_check_task(L, -1);
  1343. event_loop = task->event_loop;
  1344. resolver = task->resolver;
  1345. session = task->s;
  1346. cfg = task->cfg;
  1347. }
  1348. lua_pop(L, 1);
  1349. if (task == NULL) {
  1350. lua_pushstring(L, "ev_base");
  1351. lua_gettable(L, -2);
  1352. if (rspamd_lua_check_udata_maybe(L, -1, rspamd_ev_base_classname)) {
  1353. event_loop = *(struct ev_loop **) lua_touserdata(L, -1);
  1354. }
  1355. else {
  1356. g_free(cbd);
  1357. return luaL_error(L, "event loop is required");
  1358. }
  1359. lua_pop(L, 1);
  1360. lua_pushstring(L, "session");
  1361. lua_gettable(L, -2);
  1362. if (rspamd_lua_check_udata_maybe(L, -1, rspamd_session_classname)) {
  1363. session = *(struct rspamd_async_session **) lua_touserdata(L, -1);
  1364. }
  1365. else {
  1366. session = NULL;
  1367. }
  1368. lua_pop(L, 1);
  1369. lua_pushstring(L, "config");
  1370. lua_gettable(L, -2);
  1371. if (rspamd_lua_check_udata_maybe(L, -1, rspamd_config_classname)) {
  1372. cfg = *(struct rspamd_config **) lua_touserdata(L, -1);
  1373. }
  1374. else {
  1375. cfg = NULL;
  1376. }
  1377. lua_pop(L, 1);
  1378. lua_pushstring(L, "resolver");
  1379. lua_gettable(L, -2);
  1380. if (rspamd_lua_check_udata_maybe(L, -1, rspamd_resolver_classname)) {
  1381. resolver = *(struct rspamd_dns_resolver **) lua_touserdata(L, -1);
  1382. }
  1383. else {
  1384. resolver = lua_tcp_global_resolver(event_loop, cfg);
  1385. }
  1386. lua_pop(L, 1);
  1387. }
  1388. lua_pushstring(L, "timeout");
  1389. lua_gettable(L, -2);
  1390. if (lua_type(L, -1) == LUA_TNUMBER) {
  1391. timeout = lua_tonumber(L, -1);
  1392. }
  1393. lua_pop(L, 1);
  1394. lua_pushstring(L, "stop_pattern");
  1395. lua_gettable(L, -2);
  1396. if (lua_type(L, -1) == LUA_TSTRING) {
  1397. const char *p;
  1398. p = lua_tolstring(L, -1, &plen);
  1399. if (p && plen > 0) {
  1400. stop_pattern = g_malloc(plen);
  1401. memcpy(stop_pattern, p, plen);
  1402. }
  1403. }
  1404. lua_pop(L, 1);
  1405. lua_pushstring(L, "partial");
  1406. lua_gettable(L, -2);
  1407. if (lua_type(L, -1) == LUA_TBOOLEAN) {
  1408. partial = lua_toboolean(L, -1);
  1409. }
  1410. lua_pop(L, 1);
  1411. lua_pushstring(L, "shutdown");
  1412. lua_gettable(L, -2);
  1413. if (lua_type(L, -1) == LUA_TBOOLEAN) {
  1414. do_shutdown = lua_toboolean(L, -1);
  1415. }
  1416. lua_pop(L, 1);
  1417. lua_pushstring(L, "read");
  1418. lua_gettable(L, -2);
  1419. if (lua_type(L, -1) == LUA_TBOOLEAN) {
  1420. do_read = lua_toboolean(L, -1);
  1421. }
  1422. lua_pop(L, 1);
  1423. lua_pushstring(L, "ssl");
  1424. lua_gettable(L, -2);
  1425. if (lua_type(L, -1) == LUA_TBOOLEAN) {
  1426. ssl = lua_toboolean(L, -1);
  1427. }
  1428. lua_pop(L, 1);
  1429. lua_pushstring(L, "ssl_noverify");
  1430. lua_gettable(L, -2);
  1431. if (lua_type(L, -1) == LUA_TBOOLEAN) {
  1432. ssl_noverify = lua_toboolean(L, -1);
  1433. lua_pop(L, 1);
  1434. }
  1435. else {
  1436. lua_pop(L, 1); /* Previous nil... */
  1437. /* Similar to lua http, meh... */
  1438. lua_pushstring(L, "no_ssl_verify");
  1439. lua_gettable(L, -2);
  1440. if (lua_type(L, -1) == LUA_TBOOLEAN) {
  1441. ssl_noverify = lua_toboolean(L, -1);
  1442. }
  1443. lua_pop(L, 1);
  1444. }
  1445. lua_pushstring(L, "on_connect");
  1446. lua_gettable(L, -2);
  1447. if (lua_type(L, -1) == LUA_TFUNCTION) {
  1448. conn_cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  1449. }
  1450. else {
  1451. lua_pop(L, 1);
  1452. }
  1453. lua_pushstring(L, "upstream");
  1454. lua_gettable(L, 1);
  1455. if (lua_type(L, -1) == LUA_TUSERDATA) {
  1456. struct rspamd_lua_upstream *lup = lua_check_upstream(L, -1);
  1457. if (lup) {
  1458. /* Preserve pointer in case if lup is destructed */
  1459. up = lup->up;
  1460. }
  1461. }
  1462. lua_pop(L, 1);
  1463. lua_pushstring(L, "data");
  1464. lua_gettable(L, -2);
  1465. total_out = 0;
  1466. tp = lua_type(L, -1);
  1467. if (tp == LUA_TSTRING || tp == LUA_TUSERDATA) {
  1468. iov = g_malloc(sizeof(*iov));
  1469. niov = 1;
  1470. if (!lua_tcp_arg_toiovec(L, -1, cbd, iov)) {
  1471. lua_pop(L, 1);
  1472. msg_err("tcp request has bad data argument");
  1473. lua_pushboolean(L, FALSE);
  1474. g_free(iov);
  1475. g_free(cbd);
  1476. return 1;
  1477. }
  1478. total_out = iov[0].iov_len;
  1479. }
  1480. else if (tp == LUA_TTABLE) {
  1481. /* Count parts */
  1482. lua_pushnil(L);
  1483. while (lua_next(L, -2) != 0) {
  1484. niov++;
  1485. lua_pop(L, 1);
  1486. }
  1487. iov = g_malloc(sizeof(*iov) * niov);
  1488. lua_pushnil(L);
  1489. niov = 0;
  1490. while (lua_next(L, -2) != 0) {
  1491. if (!lua_tcp_arg_toiovec(L, -1, cbd, &iov[niov])) {
  1492. lua_pop(L, 2);
  1493. msg_err("tcp request has bad data argument at pos %d", niov);
  1494. lua_pushboolean(L, FALSE);
  1495. g_free(iov);
  1496. g_free(cbd);
  1497. return 1;
  1498. }
  1499. total_out += iov[niov].iov_len;
  1500. niov++;
  1501. lua_pop(L, 1);
  1502. }
  1503. }
  1504. lua_pop(L, 1);
  1505. }
  1506. else {
  1507. return luaL_error(L, "tcp request has bad params");
  1508. }
  1509. if (resolver == NULL && cfg == NULL && task == NULL) {
  1510. g_free(cbd);
  1511. g_free(iov);
  1512. return luaL_error(L, "tcp request has bad params: one of "
  1513. "{resolver,task,config} should be set");
  1514. }
  1515. cbd->task = task;
  1516. if (task) {
  1517. cbd->item = rspamd_symcache_get_cur_item(task);
  1518. }
  1519. cbd->cfg = cfg;
  1520. h = rspamd_random_uint64_fast();
  1521. rspamd_snprintf(cbd->tag, sizeof(cbd->tag), "%uxL", h);
  1522. cbd->handlers = g_queue_new();
  1523. cbd->hostname = g_strdup(host);
  1524. if (total_out > 0) {
  1525. struct lua_tcp_handler *wh;
  1526. wh = g_malloc0(sizeof(*wh));
  1527. wh->type = LUA_WANT_WRITE;
  1528. wh->h.w.iov = iov;
  1529. wh->h.w.iovlen = niov;
  1530. wh->h.w.total_bytes = total_out;
  1531. wh->h.w.pos = 0;
  1532. /* Cannot set write handler here */
  1533. wh->h.w.cbref = -1;
  1534. if (cbref != -1 && !do_read) {
  1535. /* We have write only callback */
  1536. wh->h.w.cbref = cbref;
  1537. }
  1538. else {
  1539. /* We have simple client callback */
  1540. wh->h.w.cbref = -1;
  1541. }
  1542. g_queue_push_tail(cbd->handlers, wh);
  1543. }
  1544. cbd->event_loop = event_loop;
  1545. cbd->fd = -1;
  1546. cbd->port = port;
  1547. cbd->ev.timeout = timeout;
  1548. if (ssl) {
  1549. cbd->flags |= LUA_TCP_FLAG_SSL;
  1550. if (ssl_noverify) {
  1551. cbd->flags |= LUA_TCP_FLAG_SSL_NOVERIFY;
  1552. }
  1553. }
  1554. if (do_read) {
  1555. cbd->in = g_byte_array_sized_new(8192);
  1556. }
  1557. else {
  1558. /* Save some space... */
  1559. cbd->in = g_byte_array_new();
  1560. }
  1561. if (partial) {
  1562. cbd->flags |= LUA_TCP_FLAG_PARTIAL;
  1563. }
  1564. if (do_shutdown) {
  1565. cbd->flags |= LUA_TCP_FLAG_SHUTDOWN;
  1566. }
  1567. if (do_read) {
  1568. struct lua_tcp_handler *rh;
  1569. rh = g_malloc0(sizeof(*rh));
  1570. rh->type = LUA_WANT_READ;
  1571. rh->h.r.cbref = cbref;
  1572. rh->h.r.stop_pattern = stop_pattern;
  1573. rh->h.r.plen = plen;
  1574. g_queue_push_tail(cbd->handlers, rh);
  1575. }
  1576. cbd->connect_cb = conn_cbref;
  1577. REF_INIT_RETAIN(cbd, lua_tcp_maybe_free);
  1578. if (up) {
  1579. cbd->up = rspamd_upstream_ref(up);
  1580. }
  1581. if (session) {
  1582. cbd->session = session;
  1583. if (rspamd_session_blocked(session)) {
  1584. lua_tcp_push_error(cbd, TRUE, "async session is the blocked state");
  1585. TCP_RELEASE(cbd);
  1586. cbd->item = NULL; /* To avoid decrease with no watcher */
  1587. lua_pushboolean(L, FALSE);
  1588. return 1;
  1589. }
  1590. }
  1591. if (cbd->up) {
  1592. /* Use upstream to get addr */
  1593. cbd->addr = rspamd_inet_address_copy(rspamd_upstream_addr_next(cbd->up), NULL);
  1594. /* Host is numeric IP, no need to resolve */
  1595. lua_tcp_register_watcher(cbd);
  1596. if (!lua_tcp_make_connection(cbd)) {
  1597. lua_tcp_push_error(cbd, TRUE, "cannot connect to the host: %s", host);
  1598. lua_pushboolean(L, FALSE);
  1599. rspamd_upstream_fail(cbd->up, true, "failed to connect");
  1600. /* No reset of the item as watcher has been registered */
  1601. TCP_RELEASE(cbd);
  1602. return 1;
  1603. }
  1604. }
  1605. else if (rspamd_parse_inet_address(&cbd->addr,
  1606. host, strlen(host), RSPAMD_INET_ADDRESS_PARSE_DEFAULT)) {
  1607. rspamd_inet_address_set_port(cbd->addr, port);
  1608. /* Host is numeric IP, no need to resolve */
  1609. lua_tcp_register_watcher(cbd);
  1610. if (!lua_tcp_make_connection(cbd)) {
  1611. lua_tcp_push_error(cbd, TRUE, "cannot connect to the host: %s", host);
  1612. lua_pushboolean(L, FALSE);
  1613. /* No reset of the item as watcher has been registered */
  1614. TCP_RELEASE(cbd);
  1615. return 1;
  1616. }
  1617. }
  1618. else {
  1619. if (task == NULL) {
  1620. if (!rspamd_dns_resolver_request(resolver, session, NULL, lua_tcp_dns_handler, cbd,
  1621. RDNS_REQUEST_A, host)) {
  1622. lua_tcp_push_error(cbd, TRUE, "cannot resolve host: %s", host);
  1623. lua_pushboolean(L, FALSE);
  1624. cbd->item = NULL; /* To avoid decrease with no watcher */
  1625. TCP_RELEASE(cbd);
  1626. return 1;
  1627. }
  1628. else {
  1629. lua_tcp_register_watcher(cbd);
  1630. }
  1631. }
  1632. else {
  1633. if (!rspamd_dns_resolver_request_task(task, lua_tcp_dns_handler, cbd,
  1634. RDNS_REQUEST_A, host)) {
  1635. lua_tcp_push_error(cbd, TRUE, "cannot resolve host: %s", host);
  1636. lua_pushboolean(L, FALSE);
  1637. cbd->item = NULL; /* To avoid decrease with no watcher */
  1638. TCP_RELEASE(cbd);
  1639. return 1;
  1640. }
  1641. else {
  1642. lua_tcp_register_watcher(cbd);
  1643. }
  1644. }
  1645. }
  1646. lua_pushboolean(L, TRUE);
  1647. return 1;
  1648. }
  1649. /***
  1650. * @function rspamd_tcp.connect_sync({params})
  1651. * Creates new pseudo-synchronous connection to the specific address:port
  1652. *
  1653. * - `task`: rspamd task objects (implies `pool`, `session`, `ev_base` and `resolver` arguments)
  1654. * - `ev_base`: event base (if no task specified)
  1655. * - `resolver`: DNS resolver (no task)
  1656. * - `session`: events session (no task)
  1657. * - `config`: config (no task)
  1658. * - `host`: IP or name of the peer (required)
  1659. * - `port`: remote port to use
  1660. * - `timeout`: floating point value that specifies timeout for IO operations in **seconds**
  1661. * @return {boolean} true if request has been sent
  1662. */
  1663. static int
  1664. lua_tcp_connect_sync(lua_State *L)
  1665. {
  1666. LUA_TRACE_POINT;
  1667. GError *err = NULL;
  1668. int64_t port = -1;
  1669. double timeout = default_tcp_timeout;
  1670. const char *host = NULL;
  1671. int ret;
  1672. uint64_t h;
  1673. struct rspamd_task *task = NULL;
  1674. struct rspamd_async_session *session = NULL;
  1675. struct rspamd_dns_resolver *resolver = NULL;
  1676. struct rspamd_config *cfg = NULL;
  1677. struct ev_loop *ev_base = NULL;
  1678. struct lua_tcp_cbdata *cbd;
  1679. int arguments_validated = rspamd_lua_parse_table_arguments(L, 1, &err,
  1680. RSPAMD_LUA_PARSE_ARGUMENTS_DEFAULT,
  1681. "task=U{task};session=U{session};resolver=U{resolver};ev_base=U{ev_base};"
  1682. "*host=S;*port=I;timeout=D;config=U{config}",
  1683. &task, &session, &resolver, &ev_base,
  1684. &host, &port, &timeout, &cfg);
  1685. if (!arguments_validated) {
  1686. if (err) {
  1687. ret = luaL_error(L, "invalid arguments: %s", err->message);
  1688. g_error_free(err);
  1689. return ret;
  1690. }
  1691. return luaL_error(L, "invalid arguments");
  1692. }
  1693. if (0 > port || port > 65535) {
  1694. return luaL_error(L, "invalid port given (correct values: 1..65535)");
  1695. }
  1696. if (task == NULL && (cfg == NULL || ev_base == NULL || session == NULL)) {
  1697. return luaL_error(L, "invalid arguments: either task or config+ev_base+session should be set");
  1698. }
  1699. if (isnan(timeout)) {
  1700. /* rspamd_lua_parse_table_arguments() sets missing N field to zero */
  1701. timeout = default_tcp_timeout;
  1702. }
  1703. cbd = g_new0(struct lua_tcp_cbdata, 1);
  1704. if (task) {
  1705. static const char hexdigests[16] = "0123456789abcdef";
  1706. cfg = task->cfg;
  1707. ev_base = task->event_loop;
  1708. session = task->s;
  1709. /* Make a readable tag */
  1710. memcpy(cbd->tag, task->task_pool->tag.uid, sizeof(cbd->tag) - 2);
  1711. cbd->tag[sizeof(cbd->tag) - 2] = hexdigests[GPOINTER_TO_INT(cbd) & 0xf];
  1712. cbd->tag[sizeof(cbd->tag) - 1] = 0;
  1713. }
  1714. else {
  1715. h = rspamd_random_uint64_fast();
  1716. rspamd_snprintf(cbd->tag, sizeof(cbd->tag), "%uxL", h);
  1717. }
  1718. if (resolver == NULL) {
  1719. if (task) {
  1720. resolver = task->resolver;
  1721. }
  1722. else {
  1723. resolver = lua_tcp_global_resolver(ev_base, cfg);
  1724. }
  1725. }
  1726. cbd->task = task;
  1727. cbd->cfg = cfg;
  1728. cbd->thread = lua_thread_pool_get_running_entry(cfg->lua_thread_pool);
  1729. cbd->handlers = g_queue_new();
  1730. cbd->event_loop = ev_base;
  1731. cbd->flags |= LUA_TCP_FLAG_SYNC;
  1732. cbd->fd = -1;
  1733. cbd->port = (uint16_t) port;
  1734. cbd->in = g_byte_array_new();
  1735. cbd->connect_cb = -1;
  1736. REF_INIT_RETAIN(cbd, lua_tcp_maybe_free);
  1737. if (task) {
  1738. rspamd_mempool_add_destructor(task->task_pool, lua_tcp_sync_session_dtor, cbd);
  1739. }
  1740. struct lua_tcp_handler *wh;
  1741. wh = g_malloc0(sizeof(*wh));
  1742. wh->type = LUA_WANT_CONNECT;
  1743. g_queue_push_tail(cbd->handlers, wh);
  1744. if (session) {
  1745. cbd->session = session;
  1746. if (rspamd_session_blocked(session)) {
  1747. TCP_RELEASE(cbd);
  1748. lua_pushboolean(L, FALSE);
  1749. lua_pushliteral(L, "Session is being destroyed, requests are not allowed");
  1750. return 2;
  1751. }
  1752. }
  1753. if (rspamd_parse_inet_address(&cbd->addr,
  1754. host, strlen(host), RSPAMD_INET_ADDRESS_PARSE_DEFAULT)) {
  1755. rspamd_inet_address_set_port(cbd->addr, (uint16_t) port);
  1756. /* Host is numeric IP, no need to resolve */
  1757. if (!lua_tcp_make_connection(cbd)) {
  1758. lua_pushboolean(L, FALSE);
  1759. lua_pushliteral(L, "Failed to initiate connection");
  1760. TCP_RELEASE(cbd);
  1761. return 2;
  1762. }
  1763. }
  1764. else {
  1765. if (task == NULL) {
  1766. if (!rspamd_dns_resolver_request(resolver, session, NULL, lua_tcp_dns_handler, cbd,
  1767. RDNS_REQUEST_A, host)) {
  1768. lua_pushboolean(L, FALSE);
  1769. lua_pushliteral(L, "Failed to initiate dns request");
  1770. TCP_RELEASE(cbd);
  1771. return 2;
  1772. }
  1773. else {
  1774. lua_tcp_register_watcher(cbd);
  1775. }
  1776. }
  1777. else {
  1778. cbd->item = rspamd_symcache_get_cur_item(task);
  1779. if (!rspamd_dns_resolver_request_task(task, lua_tcp_dns_handler, cbd,
  1780. RDNS_REQUEST_A, host)) {
  1781. cbd->item = NULL; /* We have not registered watcher */
  1782. lua_pushboolean(L, FALSE);
  1783. lua_pushliteral(L, "Failed to initiate dns request");
  1784. TCP_RELEASE(cbd);
  1785. return 2;
  1786. }
  1787. else {
  1788. lua_tcp_register_watcher(cbd);
  1789. }
  1790. }
  1791. }
  1792. return lua_thread_yield(cbd->thread, 0);
  1793. }
  1794. static int
  1795. lua_tcp_close(lua_State *L)
  1796. {
  1797. LUA_TRACE_POINT;
  1798. struct lua_tcp_cbdata *cbd = lua_check_tcp(L, 1);
  1799. if (cbd == NULL) {
  1800. return luaL_error(L, "invalid arguments");
  1801. }
  1802. cbd->flags |= LUA_TCP_FLAG_FINISHED;
  1803. if (cbd->ssl_conn) {
  1804. /* TODO: postpone close in case ssl is used ! */
  1805. rspamd_ssl_connection_free(cbd->ssl_conn);
  1806. cbd->ssl_conn = NULL;
  1807. }
  1808. if (cbd->fd != -1) {
  1809. rspamd_ev_watcher_stop(cbd->event_loop, &cbd->ev);
  1810. close(cbd->fd);
  1811. cbd->fd = -1;
  1812. }
  1813. if (cbd->addr) {
  1814. rspamd_inet_address_free(cbd->addr);
  1815. cbd->addr = NULL;
  1816. }
  1817. if (cbd->up) {
  1818. rspamd_upstream_unref(cbd->up);
  1819. cbd->up = NULL;
  1820. }
  1821. /* Do not release refcount as it will be handled elsewhere */
  1822. /* TCP_RELEASE (cbd); */
  1823. return 0;
  1824. }
  1825. static int
  1826. lua_tcp_add_read(lua_State *L)
  1827. {
  1828. LUA_TRACE_POINT;
  1829. struct lua_tcp_cbdata *cbd = lua_check_tcp(L, 1);
  1830. struct lua_tcp_handler *rh;
  1831. char *stop_pattern = NULL;
  1832. const char *p;
  1833. gsize plen = 0;
  1834. int cbref = -1;
  1835. if (cbd == NULL) {
  1836. return luaL_error(L, "invalid arguments");
  1837. }
  1838. if (lua_type(L, 2) == LUA_TFUNCTION) {
  1839. lua_pushvalue(L, 2);
  1840. cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  1841. }
  1842. if (lua_type(L, 3) == LUA_TSTRING) {
  1843. p = lua_tolstring(L, 3, &plen);
  1844. if (p && plen > 0) {
  1845. stop_pattern = g_malloc(plen);
  1846. memcpy(stop_pattern, p, plen);
  1847. }
  1848. }
  1849. rh = g_malloc0(sizeof(*rh));
  1850. rh->type = LUA_WANT_READ;
  1851. rh->h.r.cbref = cbref;
  1852. rh->h.r.stop_pattern = stop_pattern;
  1853. rh->h.r.plen = plen;
  1854. msg_debug_tcp("added read event, cbref: %d", cbref);
  1855. g_queue_push_tail(cbd->handlers, rh);
  1856. return 0;
  1857. }
  1858. static int
  1859. lua_tcp_add_write(lua_State *L)
  1860. {
  1861. LUA_TRACE_POINT;
  1862. struct lua_tcp_cbdata *cbd = lua_check_tcp(L, 1);
  1863. struct lua_tcp_handler *wh;
  1864. int cbref = -1, tp;
  1865. struct iovec *iov = NULL;
  1866. unsigned int niov = 0, total_out = 0;
  1867. if (cbd == NULL) {
  1868. return luaL_error(L, "invalid arguments");
  1869. }
  1870. if (lua_type(L, 2) == LUA_TFUNCTION) {
  1871. lua_pushvalue(L, 2);
  1872. cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  1873. }
  1874. tp = lua_type(L, 3);
  1875. if (tp == LUA_TSTRING || tp == LUA_TUSERDATA) {
  1876. iov = g_malloc(sizeof(*iov));
  1877. niov = 1;
  1878. if (!lua_tcp_arg_toiovec(L, 3, cbd, iov)) {
  1879. msg_err("tcp request has bad data argument");
  1880. lua_pushboolean(L, FALSE);
  1881. g_free(iov);
  1882. return 1;
  1883. }
  1884. total_out = iov[0].iov_len;
  1885. }
  1886. else if (tp == LUA_TTABLE) {
  1887. /* Count parts */
  1888. lua_pushvalue(L, 3);
  1889. lua_pushnil(L);
  1890. while (lua_next(L, -2) != 0) {
  1891. niov++;
  1892. lua_pop(L, 1);
  1893. }
  1894. iov = g_malloc(sizeof(*iov) * niov);
  1895. lua_pushnil(L);
  1896. niov = 0;
  1897. while (lua_next(L, -2) != 0) {
  1898. if (!lua_tcp_arg_toiovec(L, -1, cbd, &iov[niov])) {
  1899. lua_pop(L, 2);
  1900. msg_err("tcp request has bad data argument at pos %d", niov);
  1901. lua_pushboolean(L, FALSE);
  1902. g_free(iov);
  1903. g_free(cbd);
  1904. return 1;
  1905. }
  1906. total_out += iov[niov].iov_len;
  1907. niov++;
  1908. lua_pop(L, 1);
  1909. }
  1910. lua_pop(L, 1);
  1911. }
  1912. wh = g_malloc0(sizeof(*wh));
  1913. wh->type = LUA_WANT_WRITE;
  1914. wh->h.w.iov = iov;
  1915. wh->h.w.iovlen = niov;
  1916. wh->h.w.total_bytes = total_out;
  1917. wh->h.w.pos = 0;
  1918. /* Cannot set write handler here */
  1919. wh->h.w.cbref = cbref;
  1920. msg_debug_tcp("added write event, cbref: %d", cbref);
  1921. g_queue_push_tail(cbd->handlers, wh);
  1922. lua_pushboolean(L, TRUE);
  1923. return 1;
  1924. }
  1925. static int
  1926. lua_tcp_shift_callback(lua_State *L)
  1927. {
  1928. LUA_TRACE_POINT;
  1929. struct lua_tcp_cbdata *cbd = lua_check_tcp(L, 1);
  1930. if (cbd == NULL) {
  1931. return luaL_error(L, "invalid arguments");
  1932. }
  1933. lua_tcp_shift_handler(cbd);
  1934. lua_tcp_plan_handler_event(cbd, TRUE, TRUE);
  1935. return 0;
  1936. }
  1937. static struct lua_tcp_cbdata *
  1938. lua_check_sync_tcp(lua_State *L, int pos)
  1939. {
  1940. void *ud = rspamd_lua_check_udata(L, pos, rspamd_tcp_sync_classname);
  1941. luaL_argcheck(L, ud != NULL, pos, "'tcp' expected");
  1942. return ud ? *((struct lua_tcp_cbdata **) ud) : NULL;
  1943. }
  1944. static int
  1945. lua_tcp_sync_close(lua_State *L)
  1946. {
  1947. LUA_TRACE_POINT;
  1948. struct lua_tcp_cbdata *cbd = lua_check_sync_tcp(L, 1);
  1949. if (cbd == NULL) {
  1950. return luaL_error(L, "invalid arguments [self is not rspamd{tcp_sync}]");
  1951. }
  1952. cbd->flags |= LUA_TCP_FLAG_FINISHED;
  1953. if (cbd->fd != -1) {
  1954. rspamd_ev_watcher_stop(cbd->event_loop, &cbd->ev);
  1955. close(cbd->fd);
  1956. cbd->fd = -1;
  1957. }
  1958. return 0;
  1959. }
  1960. static void
  1961. lua_tcp_sync_session_dtor(gpointer ud)
  1962. {
  1963. struct lua_tcp_cbdata *cbd = ud;
  1964. cbd->flags |= LUA_TCP_FLAG_FINISHED;
  1965. if (cbd->fd != -1) {
  1966. msg_debug("closing sync TCP connection");
  1967. rspamd_ev_watcher_stop(cbd->event_loop, &cbd->ev);
  1968. close(cbd->fd);
  1969. cbd->fd = -1;
  1970. }
  1971. /* Task is gone, we should not try use it anymore */
  1972. cbd->task = NULL;
  1973. /* All events are removed when task is done, we should not refer them */
  1974. cbd->async_ev = NULL;
  1975. }
  1976. static int
  1977. lua_tcp_sync_read_once(lua_State *L)
  1978. {
  1979. LUA_TRACE_POINT;
  1980. struct lua_tcp_cbdata *cbd = lua_check_sync_tcp(L, 1);
  1981. struct lua_tcp_handler *rh;
  1982. if (cbd == NULL) {
  1983. return luaL_error(L, "invalid arguments [self is not rspamd{tcp_sync}]");
  1984. }
  1985. struct thread_entry *thread = lua_thread_pool_get_running_entry(cbd->cfg->lua_thread_pool);
  1986. rh = g_malloc0(sizeof(*rh));
  1987. rh->type = LUA_WANT_READ;
  1988. rh->h.r.cbref = -1;
  1989. msg_debug_tcp("added read sync event, thread: %p", thread);
  1990. g_queue_push_tail(cbd->handlers, rh);
  1991. lua_tcp_plan_handler_event(cbd, TRUE, TRUE);
  1992. TCP_RETAIN(cbd);
  1993. return lua_thread_yield(thread, 0);
  1994. }
  1995. static int
  1996. lua_tcp_sync_write(lua_State *L)
  1997. {
  1998. LUA_TRACE_POINT;
  1999. struct lua_tcp_cbdata *cbd = lua_check_sync_tcp(L, 1);
  2000. struct lua_tcp_handler *wh;
  2001. int tp;
  2002. struct iovec *iov = NULL;
  2003. unsigned int niov = 0;
  2004. gsize total_out = 0;
  2005. if (cbd == NULL) {
  2006. return luaL_error(L, "invalid arguments [self is not rspamd{tcp_sync}]");
  2007. }
  2008. struct thread_entry *thread = lua_thread_pool_get_running_entry(cbd->cfg->lua_thread_pool);
  2009. tp = lua_type(L, 2);
  2010. if (tp == LUA_TSTRING || tp == LUA_TUSERDATA) {
  2011. iov = g_malloc(sizeof(*iov));
  2012. niov = 1;
  2013. if (!lua_tcp_arg_toiovec(L, 2, cbd, iov)) {
  2014. msg_err("tcp request has bad data argument");
  2015. g_free(iov);
  2016. g_free(cbd);
  2017. return luaL_error(L, "invalid arguments second parameter (data) is expected to be either string or rspamd{text}");
  2018. }
  2019. total_out = iov[0].iov_len;
  2020. }
  2021. else if (tp == LUA_TTABLE) {
  2022. /* Count parts */
  2023. lua_pushvalue(L, 3);
  2024. lua_pushnil(L);
  2025. while (lua_next(L, -2) != 0) {
  2026. niov++;
  2027. lua_pop(L, 1);
  2028. }
  2029. iov = g_malloc(sizeof(*iov) * niov);
  2030. lua_pushnil(L);
  2031. niov = 0;
  2032. while (lua_next(L, -2) != 0) {
  2033. if (!lua_tcp_arg_toiovec(L, -1, cbd, &iov[niov])) {
  2034. msg_err("tcp request has bad data argument at pos %d", niov);
  2035. g_free(iov);
  2036. g_free(cbd);
  2037. return luaL_error(L, "invalid arguments second parameter (data) is expected to be either string or rspamd{text}");
  2038. }
  2039. total_out += iov[niov].iov_len;
  2040. niov++;
  2041. lua_pop(L, 1);
  2042. }
  2043. lua_pop(L, 1);
  2044. }
  2045. wh = g_malloc0(sizeof(*wh));
  2046. wh->type = LUA_WANT_WRITE;
  2047. wh->h.w.iov = iov;
  2048. wh->h.w.iovlen = niov;
  2049. wh->h.w.total_bytes = total_out;
  2050. wh->h.w.pos = 0;
  2051. wh->h.w.cbref = -1;
  2052. msg_debug_tcp("added sync write event, thread: %p", thread);
  2053. g_queue_push_tail(cbd->handlers, wh);
  2054. lua_tcp_plan_handler_event(cbd, TRUE, TRUE);
  2055. TCP_RETAIN(cbd);
  2056. return lua_thread_yield(thread, 0);
  2057. }
  2058. static int
  2059. lua_tcp_sync_eof(lua_State *L)
  2060. {
  2061. LUA_TRACE_POINT;
  2062. struct lua_tcp_cbdata *cbd = lua_check_sync_tcp(L, 1);
  2063. if (cbd == NULL) {
  2064. return luaL_error(L, "invalid arguments [self is not rspamd{tcp_sync}]");
  2065. }
  2066. lua_pushboolean(L, cbd->eof);
  2067. return 1;
  2068. }
  2069. static int
  2070. lua_tcp_sync_shutdown(lua_State *L)
  2071. {
  2072. LUA_TRACE_POINT;
  2073. struct lua_tcp_cbdata *cbd = lua_check_sync_tcp(L, 1);
  2074. if (cbd == NULL) {
  2075. return luaL_error(L, "invalid arguments [self is not rspamd{tcp_sync}]");
  2076. }
  2077. shutdown(cbd->fd, SHUT_WR);
  2078. return 0;
  2079. }
  2080. static int
  2081. lua_tcp_starttls(lua_State *L)
  2082. {
  2083. LUA_TRACE_POINT;
  2084. struct lua_tcp_cbdata *cbd = lua_check_tcp(L, 1);
  2085. gpointer ssl_ctx;
  2086. gboolean verify_peer;
  2087. if (cbd == NULL || cbd->ssl_conn != NULL) {
  2088. return luaL_error(L, "invalid arguments");
  2089. }
  2090. if (cbd->flags & LUA_TCP_FLAG_SSL_NOVERIFY) {
  2091. ssl_ctx = cbd->cfg->libs_ctx->ssl_ctx_noverify;
  2092. verify_peer = FALSE;
  2093. }
  2094. else {
  2095. ssl_ctx = cbd->cfg->libs_ctx->ssl_ctx;
  2096. verify_peer = TRUE;
  2097. }
  2098. cbd->ssl_conn = rspamd_ssl_connection_new(ssl_ctx,
  2099. cbd->event_loop,
  2100. verify_peer,
  2101. cbd->tag);
  2102. if (!rspamd_ssl_connect_fd(cbd->ssl_conn, cbd->fd, cbd->hostname, &cbd->ev,
  2103. cbd->ev.timeout, lua_tcp_handler, lua_tcp_ssl_on_error, cbd)) {
  2104. lua_tcp_push_error(cbd, TRUE, "ssl connection failed: %s",
  2105. strerror(errno));
  2106. }
  2107. return 0;
  2108. }
  2109. static int
  2110. lua_tcp_sync_gc(lua_State *L)
  2111. {
  2112. struct lua_tcp_cbdata *cbd = lua_check_sync_tcp(L, 1);
  2113. if (!cbd) {
  2114. return luaL_error(L, "invalid arguments [self is not rspamd{tcp_sync}]");
  2115. }
  2116. lua_tcp_maybe_free(cbd);
  2117. lua_tcp_fin(cbd);
  2118. return 0;
  2119. }
  2120. static int
  2121. lua_load_tcp(lua_State *L)
  2122. {
  2123. lua_newtable(L);
  2124. luaL_register(L, NULL, tcp_libf);
  2125. return 1;
  2126. }
  2127. void luaopen_tcp(lua_State *L)
  2128. {
  2129. rspamd_lua_add_preload(L, "rspamd_tcp", lua_load_tcp);
  2130. rspamd_lua_new_class(L, rspamd_tcp_classname, tcp_libm);
  2131. rspamd_lua_new_class(L, rspamd_tcp_sync_classname, tcp_sync_libm);
  2132. lua_pop(L, 1);
  2133. }