Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

lua_common.c 55KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654
  1. /*-
  2. * Copyright 2016 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_compress.h"
  18. #include "lptree.h"
  19. #include "utlist.h"
  20. #include "unix-std.h"
  21. #include "ottery.h"
  22. #include "lua_thread_pool.h"
  23. #include "libstat/stat_api.h"
  24. #include "libserver/rspamd_control.h"
  25. #include <math.h>
  26. /* Lua module init function */
  27. #define MODULE_INIT_FUNC "module_init"
  28. #ifdef WITH_LUA_TRACE
  29. ucl_object_t *lua_traces;
  30. #endif
  31. const luaL_reg null_reg[] = {
  32. {"__tostring", rspamd_lua_class_tostring},
  33. {NULL, NULL}
  34. };
  35. static const char rspamd_modules_state_global[] = "rspamd_plugins_state";
  36. static GQuark
  37. lua_error_quark (void)
  38. {
  39. return g_quark_from_static_string ("lua-routines");
  40. }
  41. /*
  42. * Used to map string to a pointer
  43. */
  44. KHASH_INIT (lua_class_set, const char*, int, 1, rspamd_str_hash, rspamd_str_equal);
  45. struct rspamd_lua_context {
  46. lua_State *L;
  47. khash_t(lua_class_set) *classes;
  48. struct rspamd_lua_context *prev, *next; /* Expensive but we usually have exactly one lua state */
  49. };
  50. struct rspamd_lua_context *rspamd_lua_global_ctx = NULL;
  51. #define RSPAMD_LUA_NCLASSES 64
  52. static inline struct rspamd_lua_context*
  53. rspamd_lua_ctx_by_state (lua_State *L)
  54. {
  55. struct rspamd_lua_context *cur;
  56. DL_FOREACH(rspamd_lua_global_ctx, cur) {
  57. if (cur->L == L) {
  58. return cur;
  59. }
  60. }
  61. /* When we are using thread pool, this is the case... */
  62. return rspamd_lua_global_ctx;
  63. }
  64. /* Util functions */
  65. /**
  66. * Create new class and store metatable on top of the stack (must be popped if not needed)
  67. * @param L
  68. * @param classname name of class
  69. * @param func table of class methods
  70. */
  71. void
  72. rspamd_lua_new_class (lua_State * L,
  73. const gchar *classname,
  74. const struct luaL_reg *methods)
  75. {
  76. khiter_t k;
  77. gint r, nmethods = 0;
  78. gboolean seen_index = false;
  79. struct rspamd_lua_context *ctx = rspamd_lua_ctx_by_state(L);
  80. if (methods) {
  81. for (;;) {
  82. if (methods[nmethods].name != NULL) {
  83. if (strcmp (methods[nmethods].name, "__index") == 0) {
  84. seen_index = true;
  85. }
  86. nmethods ++;
  87. }
  88. else {
  89. break;
  90. }
  91. }
  92. }
  93. lua_createtable (L, 0, 3 + nmethods);
  94. if (!seen_index) {
  95. lua_pushstring (L, "__index");
  96. lua_pushvalue (L, -2); /* pushes the metatable */
  97. lua_settable (L, -3); /* metatable.__index = metatable */
  98. }
  99. lua_pushstring (L, "class");
  100. lua_pushstring (L, classname);
  101. lua_rawset (L, -3);
  102. if (methods) {
  103. luaL_register (L, NULL, methods); /* pushes all methods as MT fields */
  104. }
  105. lua_pushvalue (L, -1); /* Preserves metatable */
  106. int offset = luaL_ref (L, LUA_REGISTRYINDEX);
  107. k = kh_put (lua_class_set, ctx->classes, classname, &r);
  108. kh_value(ctx->classes, k) = offset;
  109. /* MT is left on stack ! */
  110. }
  111. static const gchar *
  112. rspamd_lua_class_tostring_buf (lua_State *L, gboolean print_pointer, gint pos)
  113. {
  114. static gchar buf[64];
  115. const gchar *ret = NULL;
  116. gint pop = 0;
  117. if (!lua_getmetatable (L, pos)) {
  118. goto err;
  119. }
  120. pop ++;
  121. lua_pushstring (L, "class");
  122. lua_gettable (L, -2);
  123. pop ++;
  124. if (!lua_isstring (L, -1)) {
  125. goto err;
  126. }
  127. if (print_pointer) {
  128. rspamd_snprintf (buf, sizeof (buf), "%s(%p)", lua_tostring (L, -1),
  129. lua_touserdata (L, 1));
  130. }
  131. else {
  132. rspamd_snprintf (buf, sizeof (buf), "%s", lua_tostring (L, -1));
  133. }
  134. ret = buf;
  135. err:
  136. lua_pop (L, pop);
  137. return ret;
  138. }
  139. gint
  140. rspamd_lua_class_tostring (lua_State * L)
  141. {
  142. const gchar *p;
  143. p = rspamd_lua_class_tostring_buf (L, TRUE, 1);
  144. if (!p) {
  145. lua_pushstring (L, "invalid object passed to 'lua_common.c:__tostring'");
  146. return lua_error (L);
  147. }
  148. lua_pushstring (L, p);
  149. return 1;
  150. }
  151. void
  152. rspamd_lua_setclass (lua_State * L, const gchar *classname, gint objidx)
  153. {
  154. khiter_t k;
  155. struct rspamd_lua_context *ctx = rspamd_lua_ctx_by_state(L);
  156. k = kh_get (lua_class_set, ctx->classes, classname);
  157. g_assert (k != kh_end (ctx->classes));
  158. lua_rawgeti (L, LUA_REGISTRYINDEX, kh_value(ctx->classes, k));
  159. if (objidx < 0) {
  160. objidx--;
  161. }
  162. lua_setmetatable (L, objidx);
  163. }
  164. void
  165. rspamd_lua_class_metatable (lua_State *L, const gchar *classname)
  166. {
  167. khiter_t k;
  168. struct rspamd_lua_context *ctx = rspamd_lua_ctx_by_state(L);
  169. k = kh_get (lua_class_set, ctx->classes, classname);
  170. g_assert (k != kh_end (ctx->classes));
  171. lua_rawgeti (L, LUA_REGISTRYINDEX, kh_value(ctx->classes, k));
  172. }
  173. void
  174. rspamd_lua_add_metamethod (lua_State *L, const gchar *classname,
  175. luaL_Reg *meth)
  176. {
  177. khiter_t k;
  178. struct rspamd_lua_context *ctx = rspamd_lua_ctx_by_state(L);
  179. k = kh_get (lua_class_set, ctx->classes, classname);
  180. g_assert (k != kh_end (ctx->classes));
  181. lua_rawgeti (L, LUA_REGISTRYINDEX, kh_value(ctx->classes, k));
  182. lua_pushcfunction (L, meth->func);
  183. lua_setfield (L, -2, meth->name);
  184. lua_pop (L, 1); /* remove metatable */
  185. }
  186. /* assume that table is at the top */
  187. void
  188. rspamd_lua_table_set (lua_State * L, const gchar *index, const gchar *value)
  189. {
  190. lua_pushstring (L, index);
  191. if (value) {
  192. lua_pushstring (L, value);
  193. }
  194. else {
  195. lua_pushnil (L);
  196. }
  197. lua_settable (L, -3);
  198. }
  199. const gchar *
  200. rspamd_lua_table_get (lua_State *L, const gchar *index)
  201. {
  202. const gchar *result;
  203. lua_pushstring (L, index);
  204. lua_gettable (L, -2);
  205. if (!lua_isstring (L, -1)) {
  206. return NULL;
  207. }
  208. result = lua_tostring (L, -1);
  209. lua_pop (L, 1);
  210. return result;
  211. }
  212. static void
  213. lua_add_actions_global (lua_State *L)
  214. {
  215. gint i;
  216. lua_newtable (L);
  217. for (i = METRIC_ACTION_REJECT; i <= METRIC_ACTION_NOACTION; i++) {
  218. lua_pushstring (L, rspamd_action_to_str (i));
  219. lua_pushinteger (L, i);
  220. lua_settable (L, -3);
  221. }
  222. /* Set global table */
  223. lua_setglobal (L, "rspamd_actions");
  224. }
  225. #ifndef __APPLE__
  226. #define OS_SO_SUFFIX ".so"
  227. #else
  228. #define OS_SO_SUFFIX ".dylib"
  229. #endif
  230. void
  231. rspamd_lua_set_path (lua_State *L, const ucl_object_t *cfg_obj, GHashTable *vars)
  232. {
  233. const gchar *old_path, *additional_path = NULL;
  234. const ucl_object_t *opts = NULL;
  235. const gchar *rulesdir = RSPAMD_RULESDIR,
  236. *lualibdir = RSPAMD_LUALIBDIR,
  237. *libdir = RSPAMD_LIBDIR;
  238. const gchar *t;
  239. gchar path_buf[PATH_MAX];
  240. lua_getglobal (L, "package");
  241. lua_getfield (L, -1, "path");
  242. old_path = luaL_checkstring (L, -1);
  243. if (strstr (old_path, RSPAMD_LUALIBDIR) != NULL) {
  244. /* Path has been already set, do not touch it */
  245. lua_pop (L, 2);
  246. return;
  247. }
  248. if (cfg_obj) {
  249. opts = ucl_object_lookup (cfg_obj, "options");
  250. if (opts != NULL) {
  251. opts = ucl_object_lookup (opts, "lua_path");
  252. if (opts != NULL && ucl_object_type (opts) == UCL_STRING) {
  253. additional_path = ucl_object_tostring (opts);
  254. }
  255. }
  256. }
  257. if (additional_path) {
  258. rspamd_snprintf (path_buf, sizeof (path_buf),
  259. "%s;"
  260. "%s",
  261. additional_path, old_path);
  262. }
  263. else {
  264. /* Try environment */
  265. t = getenv ("RULESDIR");
  266. if (t) {
  267. rulesdir = t;
  268. }
  269. t = getenv ("LUALIBDIR");
  270. if (t) {
  271. lualibdir = t;
  272. }
  273. t = getenv ("LIBDIR");
  274. if (t) {
  275. libdir = t;
  276. }
  277. t = getenv ("RSPAMD_LIBDIR");
  278. if (t) {
  279. libdir = t;
  280. }
  281. if (vars) {
  282. t = g_hash_table_lookup (vars, "RULESDIR");
  283. if (t) {
  284. rulesdir = t;
  285. }
  286. t = g_hash_table_lookup (vars, "LUALIBDIR");
  287. if (t) {
  288. lualibdir = t;
  289. }
  290. t = g_hash_table_lookup (vars, "LIBDIR");
  291. if (t) {
  292. libdir = t;
  293. }
  294. t = g_hash_table_lookup (vars, "RSPAMD_LIBDIR");
  295. if (t) {
  296. libdir = t;
  297. }
  298. }
  299. rspamd_snprintf (path_buf, sizeof (path_buf),
  300. "%s/lua/?.lua;"
  301. "%s/?.lua;"
  302. "%s/?.lua;"
  303. "%s/?/init.lua;"
  304. "%s",
  305. RSPAMD_CONFDIR,
  306. rulesdir,
  307. lualibdir, lualibdir,
  308. old_path);
  309. }
  310. lua_pop (L, 1);
  311. lua_pushstring (L, path_buf);
  312. lua_setfield (L, -2, "path");
  313. lua_getglobal (L, "package");
  314. lua_getfield (L, -1, "cpath");
  315. old_path = luaL_checkstring (L, -1);
  316. additional_path = NULL;
  317. if (opts != NULL) {
  318. opts = ucl_object_lookup (opts, "lua_cpath");
  319. if (opts != NULL && ucl_object_type (opts) == UCL_STRING) {
  320. additional_path = ucl_object_tostring (opts);
  321. }
  322. }
  323. if (additional_path) {
  324. rspamd_snprintf (path_buf, sizeof (path_buf),
  325. "%s/?%s;"
  326. "%s",
  327. additional_path,
  328. OS_SO_SUFFIX,
  329. old_path);
  330. }
  331. else {
  332. rspamd_snprintf (path_buf, sizeof (path_buf),
  333. "%s/?%s;"
  334. "%s",
  335. libdir,
  336. OS_SO_SUFFIX,
  337. old_path);
  338. }
  339. lua_pop (L, 1);
  340. lua_pushstring (L, path_buf);
  341. lua_setfield (L, -2, "cpath");
  342. lua_pop (L, 1);
  343. }
  344. static gint
  345. rspamd_lua_cmp_version_components (const gchar *comp1, const gchar *comp2)
  346. {
  347. guint v1, v2;
  348. v1 = strtoul (comp1, NULL, 10);
  349. v2 = strtoul (comp2, NULL, 10);
  350. return v1 - v2;
  351. }
  352. static int
  353. rspamd_lua_rspamd_version_cmp (lua_State *L)
  354. {
  355. const gchar *ver;
  356. gchar **components;
  357. gint ret = 0;
  358. if (lua_type (L, 2) == LUA_TSTRING) {
  359. ver = lua_tostring (L, 2);
  360. components = g_strsplit_set (ver, ".-_", -1);
  361. if (!components) {
  362. return luaL_error (L, "invalid arguments to 'cmp': %s", ver);
  363. }
  364. if (components[0]) {
  365. ret = rspamd_lua_cmp_version_components (components[0],
  366. RSPAMD_VERSION_MAJOR);
  367. }
  368. if (ret) {
  369. goto set;
  370. }
  371. if (components[1]) {
  372. ret = rspamd_lua_cmp_version_components (components[1],
  373. RSPAMD_VERSION_MINOR);
  374. }
  375. if (ret) {
  376. goto set;
  377. }
  378. /*
  379. * XXX: we don't compare git releases assuming that it is meaningless
  380. */
  381. }
  382. else {
  383. return luaL_error (L, "invalid arguments to 'cmp'");
  384. }
  385. set:
  386. g_strfreev (components);
  387. lua_pushinteger (L, ret);
  388. return 1;
  389. }
  390. static int
  391. rspamd_lua_rspamd_version_numeric (lua_State *L)
  392. {
  393. static gint64 version_num = RSPAMD_VERSION_NUM;
  394. const gchar *type;
  395. if (lua_gettop (L) >= 2 && lua_type (L, 1) == LUA_TSTRING) {
  396. type = lua_tostring (L, 1);
  397. if (g_ascii_strcasecmp (type, "short") == 0) {
  398. version_num = RSPAMD_VERSION_MAJOR_NUM * 1000 +
  399. RSPAMD_VERSION_MINOR_NUM * 100;
  400. }
  401. else if (g_ascii_strcasecmp (type, "main") == 0) {
  402. version_num = RSPAMD_VERSION_MAJOR_NUM * 1000 +
  403. RSPAMD_VERSION_MINOR_NUM * 100;
  404. }
  405. else if (g_ascii_strcasecmp (type, "major") == 0) {
  406. version_num = RSPAMD_VERSION_MAJOR_NUM;
  407. }
  408. else if (g_ascii_strcasecmp (type, "minor") == 0) {
  409. version_num = RSPAMD_VERSION_MINOR_NUM;
  410. }
  411. }
  412. lua_pushinteger (L, version_num);
  413. return 1;
  414. }
  415. static int
  416. rspamd_lua_rspamd_version (lua_State *L)
  417. {
  418. const gchar *result = NULL, *type;
  419. if (lua_gettop (L) == 0) {
  420. result = RVERSION;
  421. }
  422. else if (lua_gettop (L) >= 1 && lua_type (L, 1) == LUA_TSTRING) {
  423. /* We got something like string */
  424. type = lua_tostring (L, 1);
  425. if (g_ascii_strcasecmp (type, "short") == 0) {
  426. result = RSPAMD_VERSION_MAJOR
  427. "." RSPAMD_VERSION_MINOR;
  428. }
  429. else if (g_ascii_strcasecmp (type, "main") == 0) {
  430. result = RSPAMD_VERSION_MAJOR "." RSPAMD_VERSION_MINOR;
  431. }
  432. else if (g_ascii_strcasecmp (type, "major") == 0) {
  433. result = RSPAMD_VERSION_MAJOR;
  434. }
  435. else if (g_ascii_strcasecmp (type, "minor") == 0) {
  436. result = RSPAMD_VERSION_MINOR;
  437. }
  438. else if (g_ascii_strcasecmp (type, "id") == 0) {
  439. result = RID;
  440. }
  441. else if (g_ascii_strcasecmp (type, "num") == 0) {
  442. return rspamd_lua_rspamd_version_numeric (L);
  443. }
  444. else if (g_ascii_strcasecmp (type, "cmp") == 0) {
  445. return rspamd_lua_rspamd_version_cmp (L);
  446. }
  447. }
  448. lua_pushstring (L, result);
  449. return 1;
  450. }
  451. static gboolean
  452. rspamd_lua_load_env (lua_State *L, const char *fname, gint tbl_pos, GError **err)
  453. {
  454. gint orig_top = lua_gettop (L), err_idx;
  455. gboolean ret = TRUE;
  456. lua_pushcfunction (L, &rspamd_lua_traceback);
  457. err_idx = lua_gettop (L);
  458. if (luaL_loadfile (L, fname) != 0) {
  459. g_set_error (err, g_quark_from_static_string ("lua_env"), errno,
  460. "cannot load lua file %s: %s",
  461. fname,
  462. lua_tostring (L, -1));
  463. ret = FALSE;
  464. }
  465. if (ret && lua_pcall (L, 0, 1, err_idx) != 0) {
  466. g_set_error (err, g_quark_from_static_string ("lua_env"), errno,
  467. "cannot init lua file %s: %s",
  468. fname,
  469. lua_tostring (L, -1));
  470. ret = FALSE;
  471. }
  472. if (ret && lua_type (L, -1) == LUA_TTABLE) {
  473. for (lua_pushnil (L); lua_next (L, -2); lua_pop (L, 1)) {
  474. lua_pushvalue (L, -2); /* Store key */
  475. lua_pushvalue (L, -2); /* Store value */
  476. lua_settable (L, tbl_pos);
  477. }
  478. }
  479. else if (ret) {
  480. g_set_error (err, g_quark_from_static_string ("lua_env"), errno,
  481. "invalid return type when loading env from %s: %s",
  482. fname,
  483. lua_typename (L, lua_type (L, -1)));
  484. ret = FALSE;
  485. }
  486. lua_settop (L, orig_top);
  487. return ret;
  488. }
  489. gboolean
  490. rspamd_lua_set_env (lua_State *L, GHashTable *vars, char **lua_env, GError **err)
  491. {
  492. gint orig_top = lua_gettop (L);
  493. gchar **env = g_get_environ ();
  494. /* Set known paths as rspamd_paths global */
  495. lua_getglobal (L, "rspamd_paths");
  496. if (lua_isnil (L, -1)) {
  497. const gchar *confdir = RSPAMD_CONFDIR,
  498. *local_confdir = RSPAMD_LOCAL_CONFDIR,
  499. *rundir = RSPAMD_RUNDIR,
  500. *dbdir = RSPAMD_DBDIR,
  501. *logdir = RSPAMD_LOGDIR,
  502. *wwwdir = RSPAMD_WWWDIR,
  503. *pluginsdir = RSPAMD_PLUGINSDIR,
  504. *rulesdir = RSPAMD_RULESDIR,
  505. *lualibdir = RSPAMD_LUALIBDIR,
  506. *prefix = RSPAMD_PREFIX,
  507. *sharedir = RSPAMD_SHAREDIR;
  508. const gchar *t;
  509. /* Try environment */
  510. t = g_environ_getenv (env, "SHAREDIR");
  511. if (t) {
  512. sharedir = t;
  513. }
  514. t = g_environ_getenv (env, "PLUGINSDIR");
  515. if (t) {
  516. pluginsdir = t;
  517. }
  518. t = g_environ_getenv (env, "RULESDIR");
  519. if (t) {
  520. rulesdir = t;
  521. }
  522. t = g_environ_getenv (env, "DBDIR");
  523. if (t) {
  524. dbdir = t;
  525. }
  526. t = g_environ_getenv (env, "RUNDIR");
  527. if (t) {
  528. rundir = t;
  529. }
  530. t = g_environ_getenv (env, "LUALIBDIR");
  531. if (t) {
  532. lualibdir = t;
  533. }
  534. t = g_environ_getenv (env, "LOGDIR");
  535. if (t) {
  536. logdir = t;
  537. }
  538. t = g_environ_getenv (env, "WWWDIR");
  539. if (t) {
  540. wwwdir = t;
  541. }
  542. t = g_environ_getenv (env, "CONFDIR");
  543. if (t) {
  544. confdir = t;
  545. }
  546. t = g_environ_getenv (env, "LOCAL_CONFDIR");
  547. if (t) {
  548. local_confdir = t;
  549. }
  550. if (vars) {
  551. t = g_hash_table_lookup (vars, "SHAREDIR");
  552. if (t) {
  553. sharedir = t;
  554. }
  555. t = g_hash_table_lookup (vars, "PLUGINSDIR");
  556. if (t) {
  557. pluginsdir = t;
  558. }
  559. t = g_hash_table_lookup (vars, "RULESDIR");
  560. if (t) {
  561. rulesdir = t;
  562. }
  563. t = g_hash_table_lookup (vars, "LUALIBDIR");
  564. if (t) {
  565. lualibdir = t;
  566. }
  567. t = g_hash_table_lookup (vars, "RUNDIR");
  568. if (t) {
  569. rundir = t;
  570. }
  571. t = g_hash_table_lookup (vars, "WWWDIR");
  572. if (t) {
  573. wwwdir = t;
  574. }
  575. t = g_hash_table_lookup (vars, "CONFDIR");
  576. if (t) {
  577. confdir = t;
  578. }
  579. t = g_hash_table_lookup (vars, "LOCAL_CONFDIR");
  580. if (t) {
  581. local_confdir = t;
  582. }
  583. t = g_hash_table_lookup (vars, "DBDIR");
  584. if (t) {
  585. dbdir = t;
  586. }
  587. t = g_hash_table_lookup (vars, "LOGDIR");
  588. if (t) {
  589. logdir = t;
  590. }
  591. }
  592. lua_createtable (L, 0, 9);
  593. rspamd_lua_table_set (L, RSPAMD_SHAREDIR_INDEX, sharedir);
  594. rspamd_lua_table_set (L, RSPAMD_CONFDIR_INDEX, confdir);
  595. rspamd_lua_table_set (L, RSPAMD_LOCAL_CONFDIR_INDEX, local_confdir);
  596. rspamd_lua_table_set (L, RSPAMD_RUNDIR_INDEX, rundir);
  597. rspamd_lua_table_set (L, RSPAMD_DBDIR_INDEX, dbdir);
  598. rspamd_lua_table_set (L, RSPAMD_LOGDIR_INDEX, logdir);
  599. rspamd_lua_table_set (L, RSPAMD_WWWDIR_INDEX, wwwdir);
  600. rspamd_lua_table_set (L, RSPAMD_PLUGINSDIR_INDEX, pluginsdir);
  601. rspamd_lua_table_set (L, RSPAMD_RULESDIR_INDEX, rulesdir);
  602. rspamd_lua_table_set (L, RSPAMD_LUALIBDIR_INDEX, lualibdir);
  603. rspamd_lua_table_set (L, RSPAMD_PREFIX_INDEX, prefix);
  604. lua_setglobal (L, "rspamd_paths");
  605. }
  606. lua_getglobal (L, "rspamd_env");
  607. if (lua_isnil (L, -1)) {
  608. lua_newtable (L);
  609. if (vars != NULL) {
  610. GHashTableIter it;
  611. gpointer k, v;
  612. g_hash_table_iter_init (&it, vars);
  613. while (g_hash_table_iter_next (&it, &k, &v)) {
  614. rspamd_lua_table_set (L, k, v);
  615. }
  616. }
  617. gint hostlen = sysconf (_SC_HOST_NAME_MAX);
  618. if (hostlen <= 0) {
  619. hostlen = 256;
  620. }
  621. else {
  622. hostlen ++;
  623. }
  624. gchar *hostbuf = g_alloca (hostlen);
  625. memset (hostbuf, 0, hostlen);
  626. gethostname (hostbuf, hostlen - 1);
  627. rspamd_lua_table_set (L, "hostname", hostbuf);
  628. rspamd_lua_table_set (L, "version", RVERSION);
  629. rspamd_lua_table_set (L, "ver_major", RSPAMD_VERSION_MAJOR);
  630. rspamd_lua_table_set (L, "ver_minor", RSPAMD_VERSION_MINOR);
  631. rspamd_lua_table_set (L, "ver_id", RID);
  632. lua_pushstring (L, "ver_num");
  633. lua_pushinteger (L, RSPAMD_VERSION_NUM);
  634. lua_settable (L, -3);
  635. if (env) {
  636. gint lim = g_strv_length (env);
  637. for (gint i = 0; i < lim; i++) {
  638. if (RSPAMD_LEN_CHECK_STARTS_WITH(env[i], strlen (env[i]), "RSPAMD_")) {
  639. const char *var = env[i] + sizeof ("RSPAMD_") - 1, *value;
  640. gint varlen;
  641. varlen = strcspn (var, "=");
  642. value = var + varlen;
  643. if (*value == '=') {
  644. value ++;
  645. lua_pushlstring (L, var, varlen);
  646. lua_pushstring (L, value);
  647. lua_settable (L, -3);
  648. }
  649. }
  650. }
  651. }
  652. if (lua_env) {
  653. gint lim = g_strv_length (lua_env);
  654. for (gint i = 0; i < lim; i ++) {
  655. if (!rspamd_lua_load_env (L, lua_env[i], lua_gettop (L), err)) {
  656. return FALSE;
  657. }
  658. }
  659. }
  660. lua_setglobal (L, "rspamd_env");
  661. }
  662. lua_settop (L, orig_top);
  663. g_strfreev (env);
  664. return TRUE;
  665. }
  666. void
  667. rspamd_lua_set_globals (struct rspamd_config *cfg, lua_State *L)
  668. {
  669. struct rspamd_config **pcfg;
  670. gint orig_top = lua_gettop (L);
  671. /* First check for global variable 'config' */
  672. lua_getglobal (L, "config");
  673. if (lua_isnil (L, -1)) {
  674. /* Assign global table to set up attributes */
  675. lua_newtable (L);
  676. lua_setglobal (L, "config");
  677. }
  678. lua_getglobal (L, "metrics");
  679. if (lua_isnil (L, -1)) {
  680. lua_newtable (L);
  681. lua_setglobal (L, "metrics");
  682. }
  683. lua_getglobal (L, "composites");
  684. if (lua_isnil (L, -1)) {
  685. lua_newtable (L);
  686. lua_setglobal (L, "composites");
  687. }
  688. lua_getglobal (L, "rspamd_classifiers");
  689. if (lua_isnil (L, -1)) {
  690. lua_newtable (L);
  691. lua_setglobal (L, "rspamd_classifiers");
  692. }
  693. lua_getglobal (L, "classifiers");
  694. if (lua_isnil (L, -1)) {
  695. lua_newtable (L);
  696. lua_setglobal (L, "classifiers");
  697. }
  698. lua_getglobal (L, "rspamd_version");
  699. if (lua_isnil (L, -1)) {
  700. lua_pushcfunction (L, rspamd_lua_rspamd_version);
  701. lua_setglobal (L, "rspamd_version");
  702. }
  703. if (cfg != NULL) {
  704. pcfg = lua_newuserdata (L, sizeof (struct rspamd_config *));
  705. rspamd_lua_setclass (L, "rspamd{config}", -1);
  706. *pcfg = cfg;
  707. lua_setglobal (L, "rspamd_config");
  708. }
  709. lua_settop (L, orig_top);
  710. }
  711. #ifdef WITH_LUA_TRACE
  712. static gint
  713. lua_push_trace_data (lua_State *L)
  714. {
  715. if (lua_traces) {
  716. ucl_object_push_lua (L, lua_traces, true);
  717. }
  718. else {
  719. lua_pushnil (L);
  720. }
  721. return 1;
  722. }
  723. #endif
  724. static void *
  725. rspamd_lua_wipe_realloc (void *ud,
  726. void *ptr,
  727. size_t osize,
  728. size_t nsize) RSPAMD_ATTR_ALLOC_SIZE(4);
  729. static void *
  730. rspamd_lua_wipe_realloc (void *ud,
  731. void *ptr,
  732. size_t osize,
  733. size_t nsize)
  734. {
  735. if (nsize == 0) {
  736. if (ptr) {
  737. rspamd_explicit_memzero (ptr, osize);
  738. }
  739. free (ptr);
  740. }
  741. else if (ptr == NULL) {
  742. return malloc (nsize);
  743. }
  744. else {
  745. if (nsize < osize) {
  746. /* Wipe on shrinking (actually never used) */
  747. rspamd_explicit_memzero (((unsigned char *)ptr) + nsize, osize - nsize);
  748. }
  749. return realloc (ptr, nsize);
  750. }
  751. return NULL;
  752. }
  753. #ifndef WITH_LUAJIT
  754. extern int luaopen_bit(lua_State *L);
  755. #endif
  756. lua_State *
  757. rspamd_lua_init (bool wipe_mem)
  758. {
  759. lua_State *L;
  760. if (wipe_mem) {
  761. #ifdef WITH_LUAJIT
  762. /* TODO: broken on luajit without GC64 */
  763. L = luaL_newstate ();
  764. #else
  765. L = lua_newstate (rspamd_lua_wipe_realloc, NULL);
  766. #endif
  767. }
  768. else {
  769. L = luaL_newstate ();
  770. }
  771. struct rspamd_lua_context *ctx;
  772. ctx = (struct rspamd_lua_context *)g_malloc0 (sizeof (*ctx));
  773. ctx->L = L;
  774. ctx->classes = kh_init(lua_class_set);
  775. kh_resize(lua_class_set, ctx->classes, RSPAMD_LUA_NCLASSES);
  776. DL_APPEND(rspamd_lua_global_ctx, ctx);
  777. lua_gc (L, LUA_GCSTOP, 0);
  778. luaL_openlibs (L);
  779. luaopen_logger (L);
  780. luaopen_mempool (L);
  781. luaopen_config (L);
  782. luaopen_map (L);
  783. luaopen_trie (L);
  784. luaopen_task (L);
  785. luaopen_textpart (L);
  786. luaopen_mimepart (L);
  787. luaopen_image (L);
  788. luaopen_url (L);
  789. luaopen_classifier (L);
  790. luaopen_statfile (L);
  791. luaopen_regexp (L);
  792. luaopen_cdb (L);
  793. luaopen_xmlrpc (L);
  794. luaopen_http (L);
  795. luaopen_redis (L);
  796. luaopen_upstream (L);
  797. lua_add_actions_global (L);
  798. luaopen_dns_resolver (L);
  799. luaopen_rsa (L);
  800. luaopen_ip (L);
  801. luaopen_expression (L);
  802. luaopen_text (L);
  803. luaopen_util (L);
  804. luaopen_tcp (L);
  805. luaopen_html (L);
  806. luaopen_sqlite3 (L);
  807. luaopen_cryptobox (L);
  808. luaopen_dns (L);
  809. luaopen_udp (L);
  810. luaopen_worker (L);
  811. luaopen_kann (L);
  812. luaopen_spf (L);
  813. luaopen_tensor (L);
  814. luaopen_parsers (L);
  815. luaopen_compress (L);
  816. #ifndef WITH_LUAJIT
  817. rspamd_lua_add_preload (L, "bit", luaopen_bit);
  818. lua_settop (L, 0);
  819. #endif
  820. rspamd_lua_new_class (L, "rspamd{session}", NULL);
  821. lua_pop (L, 1);
  822. rspamd_lua_add_preload (L, "lpeg", luaopen_lpeg);
  823. luaopen_ucl (L);
  824. rspamd_lua_add_preload (L, "ucl", luaopen_ucl);
  825. /* Add plugins global */
  826. lua_newtable (L);
  827. lua_setglobal (L, "rspamd_plugins");
  828. /* Set PRNG */
  829. lua_getglobal (L, "math");
  830. lua_pushstring (L, "randomseed"); /* Push math.randomseed function on top of the stack */
  831. lua_gettable (L, -2);
  832. lua_pushinteger (L, ottery_rand_uint64 ());
  833. g_assert (lua_pcall (L, 1, 0, 0) == 0);
  834. lua_pop (L, 1); /* math table */
  835. /* Modules state */
  836. lua_newtable (L);
  837. /*
  838. * rspamd_plugins_state = {
  839. * enabled = {},
  840. * disabled_unconfigured = {},
  841. * disabled_redis = {},
  842. * disabled_explicitly = {},
  843. * disabled_failed = {},
  844. * disabled_experimental = {},
  845. * }
  846. */
  847. #define ADD_TABLE(name) do { \
  848. lua_pushstring (L, #name); \
  849. lua_newtable (L); \
  850. lua_settable (L, -3); \
  851. } while (0)
  852. ADD_TABLE (enabled);
  853. ADD_TABLE (disabled_unconfigured);
  854. ADD_TABLE (disabled_redis);
  855. ADD_TABLE (disabled_explicitly);
  856. ADD_TABLE (disabled_failed);
  857. ADD_TABLE (disabled_experimental);
  858. #undef ADD_TABLE
  859. lua_setglobal (L, rspamd_modules_state_global);
  860. #ifdef WITH_LUA_TRACE
  861. lua_pushcfunction (L, lua_push_trace_data);
  862. lua_setglobal (L, "get_traces");
  863. #endif
  864. return L;
  865. }
  866. void
  867. rspamd_lua_close (lua_State *L)
  868. {
  869. struct rspamd_lua_context *ctx = rspamd_lua_ctx_by_state(L);
  870. /* TODO: we will leak this memory, but I don't know how to resolve
  871. * the chicked-egg problem when lua_close calls GC for many
  872. * userdata that requires classes metatables to be represented
  873. * For now, it is safe to leave it as is, I'm afraid
  874. */
  875. #if 0
  876. int ref;
  877. kh_foreach_value(ctx->classes, ref, {
  878. luaL_unref(L, LUA_REGISTRYINDEX, ref);
  879. });
  880. #endif
  881. lua_close(L);
  882. DL_DELETE(rspamd_lua_global_ctx, ctx);
  883. kh_destroy(lua_class_set, ctx->classes);
  884. g_free(ctx);
  885. }
  886. void
  887. rspamd_lua_start_gc (struct rspamd_config *cfg)
  888. {
  889. lua_State *L = (lua_State *)cfg->lua_state;
  890. lua_settop (L, 0);
  891. /* Set up GC */
  892. lua_gc (L, LUA_GCCOLLECT, 0);
  893. lua_gc (L, LUA_GCSETSTEPMUL, cfg->lua_gc_step);
  894. lua_gc (L, LUA_GCSETPAUSE, cfg->lua_gc_pause);
  895. lua_gc (L, LUA_GCRESTART, 0);
  896. }
  897. void
  898. rspamd_plugins_table_push_elt (lua_State *L, const gchar *field_name,
  899. const gchar *new_elt)
  900. {
  901. lua_getglobal (L, rspamd_modules_state_global);
  902. if (lua_istable (L, -1)) {
  903. lua_pushstring (L, field_name);
  904. lua_gettable (L, -2);
  905. if (lua_istable (L, -1)) {
  906. lua_pushstring (L, new_elt);
  907. lua_newtable (L);
  908. lua_settable (L, -3);
  909. lua_pop (L, 2); /* Global + element */
  910. }
  911. else {
  912. lua_pop (L, 2); /* Global + element */
  913. }
  914. }
  915. else {
  916. lua_pop (L, 1);
  917. }
  918. }
  919. gboolean
  920. rspamd_init_lua_filters (struct rspamd_config *cfg, bool force_load, bool strict)
  921. {
  922. struct rspamd_config **pcfg;
  923. GList *cur;
  924. struct script_module *module;
  925. lua_State *L = cfg->lua_state;
  926. gint err_idx;
  927. pcfg = lua_newuserdata (L, sizeof (struct rspamd_config *));
  928. rspamd_lua_setclass (L, "rspamd{config}", -1);
  929. *pcfg = cfg;
  930. lua_setglobal (L, "rspamd_config");
  931. cur = g_list_first (cfg->script_modules);
  932. while (cur) {
  933. module = cur->data;
  934. if (module->path) {
  935. if (!force_load) {
  936. if (!rspamd_config_is_module_enabled (cfg, module->name)) {
  937. cur = g_list_next (cur);
  938. continue;
  939. }
  940. }
  941. lua_pushcfunction (L, &rspamd_lua_traceback);
  942. err_idx = lua_gettop (L);
  943. gsize fsize;
  944. guint8 *data = rspamd_file_xmap (module->path,
  945. PROT_READ, &fsize, TRUE);
  946. guchar digest[rspamd_cryptobox_HASHBYTES];
  947. gchar *lua_fname;
  948. if (data == NULL) {
  949. msg_err_config ("cannot mmap %s failed: %s", module->path,
  950. strerror (errno));
  951. lua_settop (L, err_idx - 1); /* Error function */
  952. rspamd_plugins_table_push_elt (L, "disabled_failed",
  953. module->name);
  954. if (strict) {
  955. return FALSE;
  956. }
  957. cur = g_list_next (cur);
  958. continue;
  959. }
  960. module->digest = rspamd_mempool_alloc (cfg->cfg_pool,
  961. rspamd_cryptobox_HASHBYTES * 2 + 1);
  962. rspamd_cryptobox_hash (digest, data, fsize, NULL, 0);
  963. rspamd_encode_hex_buf (digest, sizeof (digest),
  964. module->digest, rspamd_cryptobox_HASHBYTES * 2 + 1);
  965. module->digest[rspamd_cryptobox_HASHBYTES * 2] = '\0';
  966. lua_fname = g_malloc (strlen (module->path) + 2);
  967. rspamd_snprintf (lua_fname, strlen (module->path) + 2, "@%s",
  968. module->path);
  969. if (luaL_loadbuffer (L, data, fsize, lua_fname) != 0) {
  970. msg_err_config ("load of %s failed: %s", module->path,
  971. lua_tostring (L, -1));
  972. lua_settop (L, err_idx - 1); /* Error function */
  973. rspamd_plugins_table_push_elt (L, "disabled_failed",
  974. module->name);
  975. munmap (data, fsize);
  976. g_free (lua_fname);
  977. if (strict) {
  978. return FALSE;
  979. }
  980. cur = g_list_next (cur);
  981. continue;
  982. }
  983. munmap (data, fsize);
  984. g_free (lua_fname);
  985. if (lua_pcall (L, 0, 0, err_idx) != 0) {
  986. msg_err_config ("init of %s failed: %s",
  987. module->path,
  988. lua_tostring (L, -1));
  989. lua_settop (L, err_idx - 1);
  990. rspamd_plugins_table_push_elt (L, "disabled_failed",
  991. module->name);
  992. if (strict) {
  993. return FALSE;
  994. }
  995. cur = g_list_next (cur);
  996. continue;
  997. }
  998. if (!force_load) {
  999. msg_info_config ("init lua module %s from %s; digest: %*s",
  1000. module->name,
  1001. module->path,
  1002. 10, module->digest);
  1003. }
  1004. lua_pop (L, 1); /* Error function */
  1005. }
  1006. cur = g_list_next (cur);
  1007. }
  1008. return TRUE;
  1009. }
  1010. void
  1011. rspamd_lua_dumpstack (lua_State *L)
  1012. {
  1013. gint i, t, r = 0;
  1014. gint top = lua_gettop (L);
  1015. gchar buf[BUFSIZ];
  1016. r += rspamd_snprintf (buf + r, sizeof (buf) - r, "lua stack: ");
  1017. for (i = 1; i <= top; i++) { /* repeat for each level */
  1018. t = lua_type (L, i);
  1019. switch (t)
  1020. {
  1021. case LUA_TSTRING: /* strings */
  1022. r += rspamd_snprintf (buf + r,
  1023. sizeof (buf) - r,
  1024. "str: %s",
  1025. lua_tostring (L, i));
  1026. break;
  1027. case LUA_TBOOLEAN: /* booleans */
  1028. r += rspamd_snprintf (buf + r, sizeof (buf) - r,
  1029. lua_toboolean (L, i) ? "bool: true" : "bool: false");
  1030. break;
  1031. case LUA_TNUMBER: /* numbers */
  1032. r += rspamd_snprintf (buf + r,
  1033. sizeof (buf) - r,
  1034. "number: %.2f",
  1035. lua_tonumber (L, i));
  1036. break;
  1037. default: /* other values */
  1038. r += rspamd_snprintf (buf + r,
  1039. sizeof (buf) - r,
  1040. "type: %s",
  1041. lua_typename (L, t));
  1042. break;
  1043. }
  1044. if (i < top) {
  1045. r += rspamd_snprintf (buf + r, sizeof (buf) - r,
  1046. " -> "); /* put a separator */
  1047. }
  1048. }
  1049. msg_info ("%*s", r, buf);
  1050. }
  1051. gpointer
  1052. rspamd_lua_check_class (lua_State *L, gint index, const gchar *name)
  1053. {
  1054. gpointer p;
  1055. khiter_t k;
  1056. if (lua_type (L, index) == LUA_TUSERDATA) {
  1057. p = lua_touserdata (L, index);
  1058. if (p) {
  1059. if (lua_getmetatable (L, index)) {
  1060. struct rspamd_lua_context *ctx = rspamd_lua_ctx_by_state(L);
  1061. k = kh_get (lua_class_set, ctx->classes, name);
  1062. if (k == kh_end (ctx->classes)) {
  1063. lua_pop (L, 1);
  1064. return NULL;
  1065. }
  1066. lua_rawgeti (L, LUA_REGISTRYINDEX, kh_value(ctx->classes, k));
  1067. if (lua_rawequal (L, -1, -2)) { /* does it have the correct mt? */
  1068. lua_pop (L, 2); /* remove both metatables */
  1069. return p;
  1070. }
  1071. lua_pop (L, 2);
  1072. }
  1073. }
  1074. }
  1075. return NULL;
  1076. }
  1077. int
  1078. rspamd_lua_typerror (lua_State *L, int narg, const char *tname)
  1079. {
  1080. const char *msg = lua_pushfstring (L, "%s expected, got %s", tname,
  1081. luaL_typename (L, narg));
  1082. return luaL_argerror (L, narg, msg);
  1083. }
  1084. void
  1085. rspamd_lua_add_preload (lua_State *L, const gchar *name, lua_CFunction func)
  1086. {
  1087. lua_getglobal (L, "package");
  1088. lua_pushstring (L, "preload");
  1089. lua_gettable (L, -2);
  1090. lua_pushcfunction (L, func);
  1091. lua_setfield (L, -2, name);
  1092. lua_pop (L, 2); /* preload key + global package */
  1093. }
  1094. gboolean
  1095. rspamd_lua_parse_table_arguments (lua_State *L, gint pos,
  1096. GError **err,
  1097. enum rspamd_lua_parse_arguments_flags how,
  1098. const gchar *extraction_pattern, ...)
  1099. {
  1100. const gchar *p, *key = NULL, *end, *cls;
  1101. va_list ap;
  1102. gboolean required = FALSE, failed = FALSE, is_table;
  1103. gchar classbuf[128];
  1104. enum {
  1105. read_key = 0,
  1106. read_arg,
  1107. read_class_start,
  1108. read_class,
  1109. read_semicolon
  1110. } state = read_key;
  1111. gsize keylen = 0, *valuelen, clslen;
  1112. gint idx = 0, t, direct_userdata = 0;
  1113. g_assert (extraction_pattern != NULL);
  1114. if (pos < 0) {
  1115. /* Get absolute pos */
  1116. pos = lua_gettop (L) + pos + 1;
  1117. }
  1118. if (lua_type (L, pos) == LUA_TTABLE) {
  1119. is_table = TRUE;
  1120. }
  1121. else {
  1122. is_table = FALSE;
  1123. idx = pos;
  1124. }
  1125. p = extraction_pattern;
  1126. end = p + strlen (extraction_pattern);
  1127. va_start (ap, extraction_pattern);
  1128. while (p <= end) {
  1129. switch (state) {
  1130. case read_key:
  1131. if (*p == '=') {
  1132. if (key == NULL) {
  1133. g_set_error (err, lua_error_quark (), 1, "cannot read key");
  1134. va_end (ap);
  1135. return FALSE;
  1136. }
  1137. state = read_arg;
  1138. keylen = p - key;
  1139. }
  1140. else if (*p == '*' && key == NULL) {
  1141. required = TRUE;
  1142. }
  1143. else if (key == NULL) {
  1144. key = p;
  1145. }
  1146. p ++;
  1147. break;
  1148. case read_arg:
  1149. g_assert (keylen != 0);
  1150. if (is_table) {
  1151. lua_pushlstring (L, key, keylen);
  1152. lua_gettable (L, pos);
  1153. idx = -1;
  1154. }
  1155. t = lua_type (L, idx);
  1156. switch (*p) {
  1157. case 'S':
  1158. if (t == LUA_TSTRING) {
  1159. *(va_arg (ap, const gchar **)) = lua_tostring (L, idx);
  1160. }
  1161. else if (t == LUA_TNIL || t == LUA_TNONE) {
  1162. failed = TRUE;
  1163. if (how != RSPAMD_LUA_PARSE_ARGUMENTS_IGNORE_MISSING) {
  1164. *(va_arg (ap, const gchar **)) = NULL;
  1165. }
  1166. else {
  1167. (void)va_arg (ap, gchar **);
  1168. }
  1169. }
  1170. else {
  1171. g_set_error (err,
  1172. lua_error_quark (),
  1173. 1,
  1174. "bad type for key:"
  1175. " %.*s: '%s', '%s' is expected",
  1176. (gint) keylen,
  1177. key,
  1178. lua_typename (L, lua_type (L, idx)), "string");
  1179. va_end (ap);
  1180. return FALSE;
  1181. }
  1182. if (is_table) {
  1183. lua_pop (L, 1);
  1184. }
  1185. break;
  1186. case 'I':
  1187. if (t == LUA_TNUMBER) {
  1188. *(va_arg (ap, gint64 *)) = lua_tointeger (L, idx);
  1189. }
  1190. else if (t == LUA_TNIL || t == LUA_TNONE) {
  1191. failed = TRUE;
  1192. if (how != RSPAMD_LUA_PARSE_ARGUMENTS_IGNORE_MISSING) {
  1193. *(va_arg (ap, gint64 *)) = 0;
  1194. }
  1195. else {
  1196. (void)va_arg (ap, gint64 *);
  1197. }
  1198. }
  1199. else {
  1200. g_set_error (err,
  1201. lua_error_quark (),
  1202. 1,
  1203. "bad type for key:"
  1204. " %.*s: '%s', '%s' is expected",
  1205. (gint) keylen,
  1206. key,
  1207. lua_typename (L, lua_type (L, idx)),
  1208. "int64");
  1209. va_end (ap);
  1210. return FALSE;
  1211. }
  1212. if (is_table) {
  1213. lua_pop (L, 1);
  1214. }
  1215. break;
  1216. case 'i':
  1217. if (t == LUA_TNUMBER) {
  1218. *(va_arg (ap, gint32 *)) = lua_tointeger (L, idx);
  1219. }
  1220. else if (t == LUA_TNIL || t == LUA_TNONE) {
  1221. failed = TRUE;
  1222. if (how != RSPAMD_LUA_PARSE_ARGUMENTS_IGNORE_MISSING) {
  1223. *(va_arg (ap, gint32 *)) = 0;
  1224. }
  1225. else {
  1226. (void)va_arg (ap, gint32 *);
  1227. }
  1228. }
  1229. else {
  1230. g_set_error (err,
  1231. lua_error_quark (),
  1232. 1,
  1233. "bad type for key:"
  1234. " %.*s: '%s', '%s' is expected",
  1235. (gint) keylen,
  1236. key,
  1237. lua_typename (L, lua_type (L, idx)),
  1238. "int64");
  1239. va_end (ap);
  1240. return FALSE;
  1241. }
  1242. if (is_table) {
  1243. lua_pop (L, 1);
  1244. }
  1245. break;
  1246. case 'F':
  1247. if (t == LUA_TFUNCTION) {
  1248. if (!is_table) {
  1249. lua_pushvalue (L, idx);
  1250. }
  1251. *(va_arg (ap, gint *)) = luaL_ref (L, LUA_REGISTRYINDEX);
  1252. }
  1253. else if (t == LUA_TNIL || t == LUA_TNONE) {
  1254. failed = TRUE;
  1255. if (how != RSPAMD_LUA_PARSE_ARGUMENTS_IGNORE_MISSING) {
  1256. *(va_arg (ap, gint *)) = -1;
  1257. }
  1258. else {
  1259. (void)va_arg (ap, gint *);
  1260. }
  1261. if (is_table) {
  1262. lua_pop (L, 1);
  1263. }
  1264. }
  1265. else {
  1266. g_set_error (err,
  1267. lua_error_quark (),
  1268. 1,
  1269. "bad type for key:"
  1270. " %.*s: '%s', '%s' is expected",
  1271. (gint) keylen,
  1272. key,
  1273. lua_typename (L, lua_type (L, idx)),
  1274. "function");
  1275. va_end (ap);
  1276. if (is_table) {
  1277. lua_pop (L, 1);
  1278. }
  1279. return FALSE;
  1280. }
  1281. /* luaL_ref pops argument from the stack */
  1282. break;
  1283. case 'B':
  1284. if (t == LUA_TBOOLEAN) {
  1285. *(va_arg (ap, gboolean *)) = lua_toboolean (L, idx);
  1286. }
  1287. else if (t == LUA_TNIL || t == LUA_TNONE) {
  1288. failed = TRUE;
  1289. if (how != RSPAMD_LUA_PARSE_ARGUMENTS_IGNORE_MISSING) {
  1290. *(va_arg (ap, gboolean *)) = 0;
  1291. }
  1292. }
  1293. else {
  1294. g_set_error (err,
  1295. lua_error_quark (),
  1296. 1,
  1297. "bad type for key:"
  1298. " %.*s: '%s', '%s' is expected",
  1299. (gint) keylen,
  1300. key,
  1301. lua_typename (L, lua_type (L, idx)),
  1302. "bool");
  1303. va_end (ap);
  1304. return FALSE;
  1305. }
  1306. if (is_table) {
  1307. lua_pop (L, 1);
  1308. }
  1309. break;
  1310. case 'N':
  1311. if (t == LUA_TNUMBER) {
  1312. *(va_arg (ap, gdouble *)) = lua_tonumber (L, idx);
  1313. }
  1314. else if (t == LUA_TNIL || t == LUA_TNONE) {
  1315. failed = TRUE;
  1316. if (how != RSPAMD_LUA_PARSE_ARGUMENTS_IGNORE_MISSING) {
  1317. *(va_arg (ap, gdouble *)) = 0;
  1318. }
  1319. else {
  1320. (void)va_arg (ap, gdouble *);
  1321. }
  1322. }
  1323. else {
  1324. g_set_error (err,
  1325. lua_error_quark (),
  1326. 1,
  1327. "bad type for key:"
  1328. " %.*s: '%s', '%s' is expected",
  1329. (gint) keylen,
  1330. key,
  1331. lua_typename (L, lua_type (L, idx)),
  1332. "double");
  1333. va_end (ap);
  1334. return FALSE;
  1335. }
  1336. if (is_table) {
  1337. lua_pop (L, 1);
  1338. }
  1339. break;
  1340. case 'D':
  1341. if (t == LUA_TNUMBER) {
  1342. *(va_arg (ap, gdouble *)) = lua_tonumber (L, idx);
  1343. }
  1344. else if (t == LUA_TNIL || t == LUA_TNONE) {
  1345. failed = TRUE;
  1346. if (how != RSPAMD_LUA_PARSE_ARGUMENTS_IGNORE_MISSING) {
  1347. *(va_arg (ap, gdouble *)) = NAN;
  1348. }
  1349. else {
  1350. (void)va_arg (ap, gdouble *);
  1351. }
  1352. }
  1353. else {
  1354. g_set_error (err,
  1355. lua_error_quark (),
  1356. 1,
  1357. "bad type for key:"
  1358. " %.*s: '%s', '%s' is expected",
  1359. (gint) keylen,
  1360. key,
  1361. lua_typename (L, lua_type (L, idx)),
  1362. "double");
  1363. va_end (ap);
  1364. return FALSE;
  1365. }
  1366. if (is_table) {
  1367. lua_pop (L, 1);
  1368. }
  1369. break;
  1370. case 'V':
  1371. valuelen = va_arg (ap, gsize *);
  1372. if (t == LUA_TSTRING) {
  1373. *(va_arg (ap, const gchar **)) = lua_tolstring (L, idx,
  1374. valuelen);
  1375. }
  1376. else if (t == LUA_TNIL || t == LUA_TNONE) {
  1377. failed = TRUE;
  1378. if (how != RSPAMD_LUA_PARSE_ARGUMENTS_IGNORE_MISSING) {
  1379. *(va_arg (ap, const char **)) = NULL;
  1380. *valuelen = 0;
  1381. }
  1382. else {
  1383. (void)va_arg (ap, const char **);
  1384. }
  1385. }
  1386. else {
  1387. g_set_error (err,
  1388. lua_error_quark (),
  1389. 1,
  1390. "bad type for key:"
  1391. " %.*s: '%s', '%s' is expected",
  1392. (gint) keylen,
  1393. key,
  1394. lua_typename (L, lua_type (L, idx)),
  1395. "string");
  1396. va_end (ap);
  1397. return FALSE;
  1398. }
  1399. if (is_table) {
  1400. lua_pop (L, 1);
  1401. }
  1402. break;
  1403. case 'O':
  1404. if (t != LUA_TNONE) {
  1405. *(va_arg (ap, ucl_object_t **)) = ucl_object_lua_import (L,
  1406. idx);
  1407. }
  1408. else {
  1409. failed = TRUE;
  1410. if (how != RSPAMD_LUA_PARSE_ARGUMENTS_IGNORE_MISSING) {
  1411. *(va_arg (ap, ucl_object_t **)) = NULL;
  1412. }
  1413. else {
  1414. (void)va_arg (ap, ucl_object_t **);
  1415. }
  1416. }
  1417. if (is_table) {
  1418. lua_pop (L, 1);
  1419. }
  1420. break;
  1421. case 'U':
  1422. if (t == LUA_TNIL || t == LUA_TNONE) {
  1423. failed = TRUE;
  1424. if (how != RSPAMD_LUA_PARSE_ARGUMENTS_IGNORE_MISSING) {
  1425. *(va_arg (ap, void **)) = NULL;
  1426. }
  1427. else {
  1428. (void)va_arg (ap, void **);
  1429. }
  1430. }
  1431. else if (t != LUA_TUSERDATA) {
  1432. g_set_error (err,
  1433. lua_error_quark (),
  1434. 1,
  1435. "bad type for key:"
  1436. " %.*s: '%s', '%s' is expected",
  1437. (gint) keylen,
  1438. key,
  1439. lua_typename (L, lua_type (L, idx)),
  1440. "int64");
  1441. va_end (ap);
  1442. return FALSE;
  1443. }
  1444. state = read_class_start;
  1445. clslen = 0;
  1446. direct_userdata = 0;
  1447. cls = NULL;
  1448. p ++;
  1449. continue;
  1450. case 'u':
  1451. if (t == LUA_TNIL || t == LUA_TNONE) {
  1452. failed = TRUE;
  1453. if (how != RSPAMD_LUA_PARSE_ARGUMENTS_IGNORE_MISSING) {
  1454. *(va_arg (ap, void **)) = NULL;
  1455. }
  1456. else {
  1457. (void)va_arg (ap, void **);
  1458. }
  1459. }
  1460. else if (t != LUA_TUSERDATA) {
  1461. g_set_error (err,
  1462. lua_error_quark (),
  1463. 1,
  1464. "bad type for key:"
  1465. " %.*s: '%s', '%s' is expected",
  1466. (gint) keylen,
  1467. key,
  1468. lua_typename (L, lua_type (L, idx)),
  1469. "int64");
  1470. va_end (ap);
  1471. return FALSE;
  1472. }
  1473. state = read_class_start;
  1474. clslen = 0;
  1475. direct_userdata = 1;
  1476. cls = NULL;
  1477. p ++;
  1478. continue;
  1479. default:
  1480. g_assert (0);
  1481. break;
  1482. }
  1483. if (failed && required) {
  1484. g_set_error (err, lua_error_quark (), 2, "required parameter "
  1485. "%.*s is missing", (gint)keylen, key);
  1486. va_end (ap);
  1487. return FALSE;
  1488. }
  1489. if (!is_table) {
  1490. idx ++;
  1491. }
  1492. /* Reset read params */
  1493. state = read_semicolon;
  1494. failed = FALSE;
  1495. required = FALSE;
  1496. keylen = 0;
  1497. key = NULL;
  1498. p ++;
  1499. break;
  1500. case read_class_start:
  1501. if (*p == '{') {
  1502. cls = p + 1;
  1503. state = read_class;
  1504. }
  1505. else {
  1506. if (is_table) {
  1507. lua_pop (L, 1);
  1508. }
  1509. g_set_error (err, lua_error_quark (), 2, "missing classname for "
  1510. "%.*s", (gint)keylen, key);
  1511. va_end (ap);
  1512. return FALSE;
  1513. }
  1514. p ++;
  1515. break;
  1516. case read_class:
  1517. if (*p == '}') {
  1518. clslen = p - cls;
  1519. if (clslen == 0) {
  1520. if (is_table) {
  1521. lua_pop (L, 1);
  1522. }
  1523. g_set_error (err,
  1524. lua_error_quark (),
  1525. 2,
  1526. "empty classname for "
  1527. "%*.s",
  1528. (gint) keylen,
  1529. key);
  1530. va_end (ap);
  1531. return FALSE;
  1532. }
  1533. rspamd_snprintf (classbuf, sizeof (classbuf), "rspamd{%*s}",
  1534. (gint) clslen, cls);
  1535. /*
  1536. * We skip class check here for speed in non-table mode
  1537. */
  1538. if (!failed && (!is_table ||
  1539. rspamd_lua_check_class (L, idx, classbuf))) {
  1540. if (direct_userdata) {
  1541. void **arg_p = (va_arg (ap, void **));
  1542. *arg_p = lua_touserdata (L, idx);
  1543. }
  1544. else {
  1545. *(va_arg (ap,
  1546. void **)) = *(void **) lua_touserdata (L, idx);
  1547. }
  1548. }
  1549. else {
  1550. if (!failed) {
  1551. g_set_error (err,
  1552. lua_error_quark (),
  1553. 2,
  1554. "invalid class for key %.*s, expected %s, got %s",
  1555. (gint) keylen,
  1556. key,
  1557. classbuf,
  1558. rspamd_lua_class_tostring_buf (L, FALSE, idx));
  1559. va_end (ap);
  1560. return FALSE;
  1561. }
  1562. }
  1563. if (is_table) {
  1564. lua_pop (L, 1);
  1565. }
  1566. else {
  1567. idx ++;
  1568. }
  1569. if (failed && required) {
  1570. g_set_error (err,
  1571. lua_error_quark (),
  1572. 2,
  1573. "required parameter "
  1574. "%.*s is missing",
  1575. (gint) keylen,
  1576. key);
  1577. va_end (ap);
  1578. return FALSE;
  1579. }
  1580. /* Reset read params */
  1581. state = read_semicolon;
  1582. failed = FALSE;
  1583. required = FALSE;
  1584. keylen = 0;
  1585. key = NULL;
  1586. }
  1587. p ++;
  1588. break;
  1589. case read_semicolon:
  1590. if (*p == ';' || p == end) {
  1591. state = read_key;
  1592. key = NULL;
  1593. keylen = 0;
  1594. failed = FALSE;
  1595. }
  1596. else {
  1597. g_set_error (err, lua_error_quark (), 2, "bad format string: %s,"
  1598. " at char %c, position %d",
  1599. extraction_pattern, *p, (int)(p - extraction_pattern));
  1600. va_end (ap);
  1601. return FALSE;
  1602. }
  1603. p++;
  1604. break;
  1605. }
  1606. }
  1607. va_end (ap);
  1608. return TRUE;
  1609. }
  1610. static void
  1611. rspamd_lua_traceback_string (lua_State *L, luaL_Buffer *buf)
  1612. {
  1613. gint i = 1, r;
  1614. lua_Debug d;
  1615. gchar tmp[256];
  1616. while (lua_getstack (L, i++, &d)) {
  1617. lua_getinfo (L, "nSl", &d);
  1618. r = rspamd_snprintf (tmp, sizeof (tmp), " [%d]:{%s:%d - %s [%s]};",
  1619. i - 1, d.short_src, d.currentline,
  1620. (d.name ? d.name : "<unknown>"), d.what);
  1621. luaL_addlstring (buf, tmp, r);
  1622. }
  1623. }
  1624. gint
  1625. rspamd_lua_traceback (lua_State *L)
  1626. {
  1627. luaL_Buffer b;
  1628. luaL_buffinit (L, &b);
  1629. rspamd_lua_get_traceback_string (L, &b);
  1630. luaL_pushresult (&b);
  1631. return 1;
  1632. }
  1633. void
  1634. rspamd_lua_get_traceback_string (lua_State *L, luaL_Buffer *buf)
  1635. {
  1636. const gchar *msg = lua_tostring (L, -1);
  1637. if (msg) {
  1638. luaL_addstring (buf, msg);
  1639. lua_pop (L, 1); /* Error string */
  1640. }
  1641. else {
  1642. luaL_addstring (buf, "unknown error");
  1643. }
  1644. luaL_addstring (buf, "; trace:");
  1645. rspamd_lua_traceback_string (L, buf);
  1646. }
  1647. guint
  1648. rspamd_lua_table_size (lua_State *L, gint tbl_pos)
  1649. {
  1650. guint tbl_size = 0;
  1651. if (!lua_istable (L, tbl_pos)) {
  1652. return 0;
  1653. }
  1654. #if LUA_VERSION_NUM >= 502
  1655. tbl_size = lua_rawlen (L, tbl_pos);
  1656. #else
  1657. tbl_size = lua_objlen (L, tbl_pos);
  1658. #endif
  1659. return tbl_size;
  1660. }
  1661. static void *
  1662. rspamd_lua_check_udata_common (lua_State *L, gint pos, const gchar *classname,
  1663. gboolean fatal)
  1664. {
  1665. void *p = lua_touserdata (L, pos);
  1666. guint i, top = lua_gettop (L);
  1667. khiter_t k;
  1668. if (p == NULL) {
  1669. goto err;
  1670. }
  1671. else {
  1672. /* Match class */
  1673. if (lua_getmetatable (L, pos)) {
  1674. struct rspamd_lua_context *ctx = rspamd_lua_ctx_by_state(L);
  1675. k = kh_get (lua_class_set, ctx->classes, classname);
  1676. if (k == kh_end (ctx->classes)) {
  1677. goto err;
  1678. }
  1679. lua_rawgeti (L, LUA_REGISTRYINDEX, kh_value(ctx->classes, k));
  1680. if (!lua_rawequal (L, -1, -2)) {
  1681. goto err;
  1682. }
  1683. }
  1684. else {
  1685. goto err;
  1686. }
  1687. }
  1688. lua_settop (L, top);
  1689. return p;
  1690. err:
  1691. if (fatal) {
  1692. const gchar *actual_classname = NULL;
  1693. if (lua_type (L, pos) == LUA_TUSERDATA && lua_getmetatable (L, pos)) {
  1694. lua_pushstring (L, "__index");
  1695. lua_gettable (L, -2);
  1696. lua_pushstring (L, "class");
  1697. lua_gettable (L, -2);
  1698. actual_classname = lua_tostring (L, -1);
  1699. }
  1700. else {
  1701. actual_classname = lua_typename (L, lua_type (L, pos));
  1702. }
  1703. luaL_Buffer buf;
  1704. gchar tmp[512];
  1705. gint r;
  1706. luaL_buffinit (L, &buf);
  1707. r = rspamd_snprintf (tmp, sizeof (tmp),
  1708. "expected %s at position %d, but userdata has "
  1709. "%s metatable; trace: ",
  1710. classname, pos, actual_classname);
  1711. luaL_addlstring (&buf, tmp, r);
  1712. rspamd_lua_traceback_string (L, &buf);
  1713. r = rspamd_snprintf (tmp, sizeof (tmp), " stack(%d): ", top);
  1714. luaL_addlstring (&buf, tmp, r);
  1715. for (i = 1; i <= MIN (top, 10); i ++) {
  1716. if (lua_type (L, i) == LUA_TUSERDATA) {
  1717. const char *clsname;
  1718. if (lua_getmetatable (L, i)) {
  1719. lua_pushstring (L, "__index");
  1720. lua_gettable (L, -2);
  1721. lua_pushstring (L, "class");
  1722. lua_gettable (L, -2);
  1723. clsname = lua_tostring (L, -1);
  1724. }
  1725. else {
  1726. clsname = lua_typename (L, lua_type (L, i));
  1727. }
  1728. r = rspamd_snprintf (tmp, sizeof (tmp), "[%d: ud=%s] ", i,
  1729. clsname);
  1730. luaL_addlstring (&buf, tmp, r);
  1731. }
  1732. else {
  1733. r = rspamd_snprintf (tmp, sizeof (tmp), "[%d: %s] ", i,
  1734. lua_typename (L, lua_type (L, i)));
  1735. luaL_addlstring (&buf, tmp, r);
  1736. }
  1737. }
  1738. luaL_pushresult (&buf);
  1739. msg_err ("lua type error: %s", lua_tostring (L, -1));
  1740. }
  1741. lua_settop (L, top);
  1742. return NULL;
  1743. }
  1744. void *
  1745. rspamd_lua_check_udata (lua_State *L, gint pos, const gchar *classname)
  1746. {
  1747. return rspamd_lua_check_udata_common (L, pos, classname, TRUE);
  1748. }
  1749. void *
  1750. rspamd_lua_check_udata_maybe (lua_State *L, gint pos, const gchar *classname)
  1751. {
  1752. return rspamd_lua_check_udata_common (L, pos, classname, FALSE);
  1753. }
  1754. struct rspamd_async_session*
  1755. lua_check_session (lua_State * L, gint pos)
  1756. {
  1757. void *ud = rspamd_lua_check_udata (L, pos, "rspamd{session}");
  1758. luaL_argcheck (L, ud != NULL, pos, "'session' expected");
  1759. return ud ? *((struct rspamd_async_session **)ud) : NULL;
  1760. }
  1761. struct ev_loop*
  1762. lua_check_ev_base (lua_State * L, gint pos)
  1763. {
  1764. void *ud = rspamd_lua_check_udata (L, pos, "rspamd{ev_base}");
  1765. luaL_argcheck (L, ud != NULL, pos, "'event_base' expected");
  1766. return ud ? *((struct ev_loop **)ud) : NULL;
  1767. }
  1768. static void rspamd_lua_run_postloads_error (struct thread_entry *thread, int ret, const char *msg);
  1769. void
  1770. rspamd_lua_run_postloads (lua_State *L, struct rspamd_config *cfg,
  1771. struct ev_loop *ev_base, struct rspamd_worker *w)
  1772. {
  1773. struct rspamd_config_cfg_lua_script *sc;
  1774. struct rspamd_config **pcfg;
  1775. struct ev_loop **pev_base;
  1776. struct rspamd_worker **pw;
  1777. /* Execute post load scripts */
  1778. LL_FOREACH (cfg->on_load_scripts, sc) {
  1779. struct thread_entry *thread = lua_thread_pool_get_for_config (cfg);
  1780. thread->error_callback = rspamd_lua_run_postloads_error;
  1781. L = thread->lua_state;
  1782. lua_rawgeti (L, LUA_REGISTRYINDEX, sc->cbref);
  1783. pcfg = lua_newuserdata (L, sizeof (*pcfg));
  1784. *pcfg = cfg;
  1785. rspamd_lua_setclass (L, "rspamd{config}", -1);
  1786. pev_base = lua_newuserdata (L, sizeof (*pev_base));
  1787. *pev_base = ev_base;
  1788. rspamd_lua_setclass (L, "rspamd{ev_base}", -1);
  1789. pw = lua_newuserdata (L, sizeof (*pw));
  1790. *pw = w;
  1791. rspamd_lua_setclass (L, "rspamd{worker}", -1);
  1792. lua_thread_call (thread, 3);
  1793. }
  1794. }
  1795. void
  1796. rspamd_lua_run_config_post_init (lua_State *L, struct rspamd_config *cfg)
  1797. {
  1798. struct rspamd_config_cfg_lua_script *sc;
  1799. struct rspamd_config **pcfg;
  1800. LL_FOREACH (cfg->post_init_scripts, sc) {
  1801. lua_pushcfunction (L, &rspamd_lua_traceback);
  1802. gint err_idx = lua_gettop (L);
  1803. lua_rawgeti (L, LUA_REGISTRYINDEX, sc->cbref);
  1804. pcfg = lua_newuserdata (L, sizeof (*pcfg));
  1805. *pcfg = cfg;
  1806. rspamd_lua_setclass (L, "rspamd{config}", -1);
  1807. if (lua_pcall (L, 1, 0, err_idx) != 0) {
  1808. msg_err_config ("cannot run config post init script: %s; priority = %d",
  1809. lua_tostring (L, -1), sc->priority);
  1810. }
  1811. lua_settop (L, err_idx - 1);
  1812. }
  1813. }
  1814. void
  1815. rspamd_lua_run_config_unload (lua_State *L, struct rspamd_config *cfg)
  1816. {
  1817. struct rspamd_config_cfg_lua_script *sc;
  1818. struct rspamd_config **pcfg;
  1819. LL_FOREACH (cfg->config_unload_scripts, sc) {
  1820. lua_pushcfunction (L, &rspamd_lua_traceback);
  1821. gint err_idx = lua_gettop (L);
  1822. lua_rawgeti (L, LUA_REGISTRYINDEX, sc->cbref);
  1823. pcfg = lua_newuserdata (L, sizeof (*pcfg));
  1824. *pcfg = cfg;
  1825. rspamd_lua_setclass (L, "rspamd{config}", -1);
  1826. if (lua_pcall (L, 1, 0, err_idx) != 0) {
  1827. msg_err_config ("cannot run config post init script: %s",
  1828. lua_tostring (L, -1));
  1829. }
  1830. lua_settop (L, err_idx - 1);
  1831. }
  1832. }
  1833. static void
  1834. rspamd_lua_run_postloads_error (struct thread_entry *thread, int ret, const char *msg)
  1835. {
  1836. struct rspamd_config *cfg = thread->cfg;
  1837. msg_err_config ("error executing post load code: %s", msg);
  1838. }
  1839. struct rspamd_lua_ref_cbdata {
  1840. lua_State *L;
  1841. gint cbref;
  1842. };
  1843. static void
  1844. rspamd_lua_ref_dtor (gpointer p)
  1845. {
  1846. struct rspamd_lua_ref_cbdata *cbdata = p;
  1847. luaL_unref (cbdata->L, LUA_REGISTRYINDEX, cbdata->cbref);
  1848. }
  1849. void
  1850. rspamd_lua_add_ref_dtor (lua_State *L, rspamd_mempool_t *pool,
  1851. gint ref)
  1852. {
  1853. struct rspamd_lua_ref_cbdata *cbdata;
  1854. if (ref != -1) {
  1855. cbdata = rspamd_mempool_alloc (pool, sizeof (*cbdata));
  1856. cbdata->cbref = ref;
  1857. cbdata->L = L;
  1858. rspamd_mempool_add_destructor (pool, rspamd_lua_ref_dtor, cbdata);
  1859. }
  1860. }
  1861. gboolean
  1862. rspamd_lua_require_function (lua_State *L, const gchar *modname,
  1863. const gchar *funcname)
  1864. {
  1865. gint table_pos, err_pos;
  1866. lua_pushcfunction (L, &rspamd_lua_traceback);
  1867. err_pos = lua_gettop (L);
  1868. lua_getglobal (L, "require");
  1869. if (lua_isnil (L, -1)) {
  1870. lua_remove (L, err_pos);
  1871. lua_pop (L, 1);
  1872. return FALSE;
  1873. }
  1874. lua_pushstring (L, modname);
  1875. /* Now try to call */
  1876. if (lua_pcall (L, 1, 1, 0) != 0) {
  1877. lua_remove (L, err_pos);
  1878. msg_warn ("require of %s.%s failed: %s", modname,
  1879. funcname, lua_tostring (L, -1));
  1880. lua_pop (L, 1);
  1881. return FALSE;
  1882. }
  1883. lua_remove (L, err_pos);
  1884. /* Now we should have a table with results */
  1885. if (!lua_istable (L, -1)) {
  1886. msg_warn ("require of %s.%s failed: not a table but %s", modname,
  1887. funcname, lua_typename (L, lua_type (L, -1)));
  1888. lua_pop (L, 1);
  1889. return FALSE;
  1890. }
  1891. table_pos = lua_gettop (L);
  1892. lua_pushstring (L, funcname);
  1893. lua_gettable (L, -2);
  1894. if (lua_type (L, -1) == LUA_TFUNCTION) {
  1895. /* Remove table, preserve just a function */
  1896. lua_remove (L, table_pos);
  1897. return TRUE;
  1898. }
  1899. else {
  1900. msg_warn ("require of %s.%s failed: not a function but %s", modname,
  1901. funcname, lua_typename (L, lua_type (L, -1)));
  1902. }
  1903. lua_pop (L, 2);
  1904. return FALSE;
  1905. }
  1906. gint
  1907. rspamd_lua_function_ref_from_str (lua_State *L, const gchar *str, gsize slen,
  1908. const gchar *modname, GError **err)
  1909. {
  1910. gint err_idx, ref_idx;
  1911. lua_pushcfunction (L, &rspamd_lua_traceback);
  1912. err_idx = lua_gettop (L);
  1913. /* Load file */
  1914. if (luaL_loadbuffer (L, str, slen, modname) != 0) {
  1915. g_set_error (err,
  1916. lua_error_quark(),
  1917. EINVAL,
  1918. "%s: cannot load lua script: %s",
  1919. modname,
  1920. lua_tostring (L, -1));
  1921. lua_settop (L, err_idx - 1); /* Error function */
  1922. return LUA_NOREF;
  1923. }
  1924. /* Now call it */
  1925. if (lua_pcall (L, 0, 1, err_idx) != 0) {
  1926. g_set_error (err,
  1927. lua_error_quark(),
  1928. EINVAL,
  1929. "%s: cannot init lua script: %s",
  1930. modname,
  1931. lua_tostring (L, -1));
  1932. lua_settop (L, err_idx - 1);
  1933. return LUA_NOREF;
  1934. }
  1935. if (!lua_isfunction (L, -1)) {
  1936. g_set_error (err,
  1937. lua_error_quark(),
  1938. EINVAL,
  1939. "%s: cannot init lua script: "
  1940. "must return function not %s",
  1941. modname,
  1942. lua_typename (L, lua_type (L, -1)));
  1943. lua_settop (L, err_idx - 1);
  1944. return LUA_NOREF;
  1945. }
  1946. ref_idx = luaL_ref (L, LUA_REGISTRYINDEX);
  1947. lua_settop (L, err_idx - 1);
  1948. return ref_idx;
  1949. }
  1950. gboolean
  1951. rspamd_lua_try_load_redis (lua_State *L, const ucl_object_t *obj,
  1952. struct rspamd_config *cfg, gint *ref_id)
  1953. {
  1954. gint err_idx;
  1955. struct rspamd_config **pcfg;
  1956. lua_pushcfunction (L, &rspamd_lua_traceback);
  1957. err_idx = lua_gettop (L);
  1958. /* Obtain function */
  1959. if (!rspamd_lua_require_function (L, "lua_redis", "try_load_redis_servers")) {
  1960. msg_err_config ("cannot require lua_redis");
  1961. lua_pop (L, 2);
  1962. return FALSE;
  1963. }
  1964. /* Function arguments */
  1965. ucl_object_push_lua (L, obj, false);
  1966. pcfg = lua_newuserdata (L, sizeof (*pcfg));
  1967. rspamd_lua_setclass (L, "rspamd{config}", -1);
  1968. *pcfg = cfg;
  1969. lua_pushboolean (L, false); /* no_fallback */
  1970. if (lua_pcall (L, 3, 1, err_idx) != 0) {
  1971. msg_err_config ("cannot call lua try_load_redis_servers script: %s",
  1972. lua_tostring (L, -1));
  1973. lua_settop (L, 0);
  1974. return FALSE;
  1975. }
  1976. if (lua_istable (L, -1)) {
  1977. if (ref_id) {
  1978. /* Ref table */
  1979. lua_pushvalue (L, -1);
  1980. *ref_id = luaL_ref (L, LUA_REGISTRYINDEX);
  1981. lua_settop (L, 0);
  1982. }
  1983. else {
  1984. /* Leave it on the stack */
  1985. lua_insert (L, err_idx);
  1986. lua_settop (L, err_idx);
  1987. }
  1988. return TRUE;
  1989. }
  1990. else {
  1991. lua_settop (L, 0);
  1992. }
  1993. return FALSE;
  1994. }
  1995. void
  1996. rspamd_lua_push_full_word (lua_State *L, rspamd_stat_token_t *w)
  1997. {
  1998. gint fl_cnt;
  1999. lua_createtable (L, 4, 0);
  2000. if (w->stemmed.len > 0) {
  2001. lua_pushlstring (L, w->stemmed.begin, w->stemmed.len);
  2002. lua_rawseti (L, -2, 1);
  2003. }
  2004. else {
  2005. lua_pushstring (L, "");
  2006. lua_rawseti (L, -2, 1);
  2007. }
  2008. if (w->normalized.len > 0) {
  2009. lua_pushlstring (L, w->normalized.begin, w->normalized.len);
  2010. lua_rawseti (L, -2, 2);
  2011. }
  2012. else {
  2013. lua_pushstring (L, "");
  2014. lua_rawseti (L, -2, 2);
  2015. }
  2016. if (w->original.len > 0) {
  2017. lua_pushlstring (L, w->original.begin, w->original.len);
  2018. lua_rawseti (L, -2, 3);
  2019. }
  2020. else {
  2021. lua_pushstring (L, "");
  2022. lua_rawseti (L, -2, 3);
  2023. }
  2024. /* Flags part */
  2025. fl_cnt = 1;
  2026. lua_createtable (L, 4, 0);
  2027. if (w->flags & RSPAMD_STAT_TOKEN_FLAG_NORMALISED) {
  2028. lua_pushstring (L, "normalised");
  2029. lua_rawseti (L, -2, fl_cnt ++);
  2030. }
  2031. if (w->flags & RSPAMD_STAT_TOKEN_FLAG_BROKEN_UNICODE) {
  2032. lua_pushstring (L, "broken_unicode");
  2033. lua_rawseti (L, -2, fl_cnt ++);
  2034. }
  2035. if (w->flags & RSPAMD_STAT_TOKEN_FLAG_UTF) {
  2036. lua_pushstring (L, "utf");
  2037. lua_rawseti (L, -2, fl_cnt ++);
  2038. }
  2039. if (w->flags & RSPAMD_STAT_TOKEN_FLAG_TEXT) {
  2040. lua_pushstring (L, "text");
  2041. lua_rawseti (L, -2, fl_cnt ++);
  2042. }
  2043. if (w->flags & RSPAMD_STAT_TOKEN_FLAG_HEADER) {
  2044. lua_pushstring (L, "header");
  2045. lua_rawseti (L, -2, fl_cnt ++);
  2046. }
  2047. if (w->flags & (RSPAMD_STAT_TOKEN_FLAG_META|RSPAMD_STAT_TOKEN_FLAG_LUA_META)) {
  2048. lua_pushstring (L, "meta");
  2049. lua_rawseti (L, -2, fl_cnt ++);
  2050. }
  2051. if (w->flags & RSPAMD_STAT_TOKEN_FLAG_STOP_WORD) {
  2052. lua_pushstring (L, "stop_word");
  2053. lua_rawseti (L, -2, fl_cnt ++);
  2054. }
  2055. if (w->flags & RSPAMD_STAT_TOKEN_FLAG_INVISIBLE_SPACES) {
  2056. lua_pushstring (L, "invisible_spaces");
  2057. lua_rawseti (L, -2, fl_cnt ++);
  2058. }
  2059. if (w->flags & RSPAMD_STAT_TOKEN_FLAG_STEMMED) {
  2060. lua_pushstring (L, "stemmed");
  2061. lua_rawseti (L, -2, fl_cnt ++);
  2062. }
  2063. lua_rawseti (L, -2, 4);
  2064. }
  2065. gint
  2066. rspamd_lua_push_words (lua_State *L, GArray *words,
  2067. enum rspamd_lua_words_type how)
  2068. {
  2069. rspamd_stat_token_t *w;
  2070. guint i, cnt;
  2071. lua_createtable (L, words->len, 0);
  2072. for (i = 0, cnt = 1; i < words->len; i ++) {
  2073. w = &g_array_index (words, rspamd_stat_token_t, i);
  2074. switch (how) {
  2075. case RSPAMD_LUA_WORDS_STEM:
  2076. if (w->stemmed.len > 0) {
  2077. lua_pushlstring (L, w->stemmed.begin, w->stemmed.len);
  2078. lua_rawseti (L, -2, cnt ++);
  2079. }
  2080. break;
  2081. case RSPAMD_LUA_WORDS_NORM:
  2082. if (w->normalized.len > 0) {
  2083. lua_pushlstring (L, w->normalized.begin, w->normalized.len);
  2084. lua_rawseti (L, -2, cnt ++);
  2085. }
  2086. break;
  2087. case RSPAMD_LUA_WORDS_RAW:
  2088. if (w->original.len > 0) {
  2089. lua_pushlstring (L, w->original.begin, w->original.len);
  2090. lua_rawseti (L, -2, cnt ++);
  2091. }
  2092. break;
  2093. case RSPAMD_LUA_WORDS_FULL:
  2094. rspamd_lua_push_full_word (L, w);
  2095. /* Push to the resulting vector */
  2096. lua_rawseti (L, -2, cnt ++);
  2097. break;
  2098. default:
  2099. break;
  2100. }
  2101. }
  2102. return 1;
  2103. }
  2104. gchar *
  2105. rspamd_lua_get_module_name (lua_State *L)
  2106. {
  2107. lua_Debug d;
  2108. gchar *p;
  2109. gchar func_buf[128];
  2110. if (lua_getstack (L, 1, &d) == 1) {
  2111. (void) lua_getinfo (L, "Sl", &d);
  2112. if ((p = strrchr (d.short_src, '/')) == NULL) {
  2113. p = d.short_src;
  2114. }
  2115. else {
  2116. p++;
  2117. }
  2118. if (strlen (p) > 20) {
  2119. rspamd_snprintf (func_buf, sizeof (func_buf), "%10s...]:%d", p,
  2120. d.currentline);
  2121. }
  2122. else {
  2123. rspamd_snprintf (func_buf, sizeof (func_buf), "%s:%d", p,
  2124. d.currentline);
  2125. }
  2126. return g_strdup (func_buf);
  2127. }
  2128. return NULL;
  2129. }
  2130. bool
  2131. rspamd_lua_universal_pcall (lua_State *L, gint cbref, const gchar* strloc,
  2132. gint nret, const gchar *args, GError **err, ...)
  2133. {
  2134. va_list ap;
  2135. const gchar *argp = args, *classname;
  2136. gint err_idx, nargs = 0;
  2137. gpointer *cls_ptr;
  2138. gsize sz;
  2139. /* Error function */
  2140. lua_pushcfunction (L, &rspamd_lua_traceback);
  2141. err_idx = lua_gettop (L);
  2142. va_start (ap, err);
  2143. /* Called function */
  2144. lua_rawgeti (L, LUA_REGISTRYINDEX, cbref);
  2145. /*
  2146. * Possible arguments
  2147. * - i - lua_integer, argument - gint64
  2148. * - n - lua_number, argument - gdouble
  2149. * - s - lua_string, argument - const gchar * (zero terminated)
  2150. * - l - lua_lstring, argument - (size_t + const gchar *) pair
  2151. * - u - lua_userdata, argument - (const char * + void *) - classname + pointer
  2152. * - b - lua_boolean, argument - gboolean (not bool due to varargs promotion)
  2153. * - f - lua_function, argument - int - position of the function on stack (not lua_registry)
  2154. * - t - lua_text, argument - int - position of the lua_text on stack (not lua_registry)
  2155. */
  2156. while (*argp) {
  2157. switch (*argp) {
  2158. case 'i':
  2159. lua_pushinteger (L, va_arg (ap, gint64));
  2160. nargs ++;
  2161. break;
  2162. case 'n':
  2163. lua_pushnumber (L, va_arg (ap, gdouble));
  2164. nargs ++;
  2165. break;
  2166. case 's':
  2167. lua_pushstring (L, va_arg (ap, const gchar *));
  2168. nargs ++;
  2169. break;
  2170. case 'l':
  2171. sz = va_arg (ap, gsize);
  2172. lua_pushlstring (L, va_arg (ap, const gchar *), sz);
  2173. nargs ++;
  2174. break;
  2175. case 'b':
  2176. lua_pushboolean (L, va_arg (ap, gboolean));
  2177. nargs ++;
  2178. break;
  2179. case 'u':
  2180. classname = va_arg (ap, const gchar *);
  2181. cls_ptr = (gpointer *)lua_newuserdata (L, sizeof (gpointer));
  2182. *cls_ptr = va_arg (ap, gpointer);
  2183. rspamd_lua_setclass (L, classname, -1);
  2184. nargs ++;
  2185. break;
  2186. case 'f':
  2187. case 't':
  2188. lua_pushvalue (L, va_arg (ap, gint));
  2189. nargs ++;
  2190. break;
  2191. default:
  2192. lua_settop (L, err_idx - 1);
  2193. g_set_error (err, lua_error_quark (), EINVAL,
  2194. "invalid argument character: %c at %s",
  2195. *argp, argp);
  2196. va_end (ap);
  2197. return false;
  2198. }
  2199. argp ++;
  2200. }
  2201. if (lua_pcall (L, nargs, nret, err_idx) != 0) {
  2202. g_set_error (err, lua_error_quark (), EBADF,
  2203. "error when calling lua function from %s: %s",
  2204. strloc, lua_tostring (L, -1));
  2205. lua_settop (L, err_idx - 1);
  2206. va_end (ap);
  2207. return false;
  2208. }
  2209. lua_remove (L, err_idx);
  2210. va_end (ap);
  2211. return true;
  2212. }
  2213. #if defined( LUA_VERSION_NUM ) && LUA_VERSION_NUM <= 502
  2214. gint
  2215. rspamd_lua_geti (lua_State *L, int pos, int i)
  2216. {
  2217. pos = lua_absindex (L, pos);
  2218. lua_pushinteger (L, i);
  2219. lua_gettable (L, pos);
  2220. return lua_type (L, -1);
  2221. }
  2222. #endif