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_common.c 53KB

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