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_config.c 120KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780
  1. /*
  2. * Copyright 2024 Vsevolod Stakhov
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "lua_common.h"
  17. #include "libmime/message.h"
  18. #include "libutil/expression.h"
  19. #include "src/libserver/composites/composites.h"
  20. #include "libserver/cfg_file_private.h"
  21. #include "libmime/lang_detection.h"
  22. #include "lua/lua_map.h"
  23. #include "lua/lua_thread_pool.h"
  24. #include "utlist.h"
  25. #include <math.h>
  26. /***
  27. * This module is used to configure rspamd and is normally available as global
  28. * variable named `rspamd_config`. Unlike other modules, it is not necessary to
  29. * require it before usage.
  30. * @module rspamd_config
  31. * @example
  32. -- Register some callback symbol
  33. local function foo(task)
  34. -- do something
  35. end
  36. rspamd_config:register_symbol('SYMBOL', 1.0, foo)
  37. -- Get configuration
  38. local tab = rspamd_config:get_all_opt('module') -- get table for module's options
  39. local opts = rspamd_config:get_key('options') -- get content of the specified key in rspamd configuration
  40. */
  41. /* Config file methods */
  42. /***
  43. * @method rspamd_config:get_module_opt(mname, optname)
  44. * Returns value of specified option `optname` for a module `mname`,
  45. * @param {string} mname name of module
  46. * @param {string} optname option to get
  47. * @return {string or table} value of the option or `nil` if option is not found
  48. */
  49. LUA_FUNCTION_DEF(config, get_module_opt);
  50. /***
  51. * @method rspamd_config:get_all_opt(mname)
  52. * Returns value of all options for a module `mname`, flattening values into a single table consisting
  53. * of all sections with such a name.
  54. * @param {string} mname name of module
  55. * @return {table} table of all options for `mname` or `nil` if a module's configuration is not found
  56. */
  57. LUA_FUNCTION_DEF(config, get_all_opt);
  58. /***
  59. * @method rspamd_config:get_ucl()
  60. * Returns full configuration as a native Lua object (ucl to lua conversion).
  61. * This method uses caching if possible.
  62. * @return {table} table of all options in the configuration
  63. */
  64. LUA_FUNCTION_DEF(config, get_ucl);
  65. /***
  66. * @method rspamd_config:get_mempool()
  67. * Returns static configuration memory pool.
  68. * @return {mempool} [memory pool](mempool.md) object
  69. */
  70. LUA_FUNCTION_DEF(config, get_mempool);
  71. /***
  72. * @method rspamd_config:get_resolver()
  73. * Returns DNS resolver.
  74. * @return {dns_resolver} opaque DNS resolver pointer if any
  75. */
  76. LUA_FUNCTION_DEF(config, get_resolver);
  77. /***
  78. * @method rspamd_config:add_radix_map(mapline[, description])
  79. * Creates new dynamic map of IP/mask addresses.
  80. * @param {string} mapline URL for a map
  81. * @param {string} description optional map description
  82. * @return {map} radix tree object
  83. * @example
  84. local ip_map = rspamd_config:add_radix_map ('file:///path/to/file', 'my radix map')
  85. ...
  86. local function foo(task)
  87. local ip = task:get_from_ip()
  88. if ip_map:get_key(ip) then
  89. return true
  90. end
  91. return false
  92. end
  93. */
  94. /***
  95. * @method rspamd_config:radix_from_config(mname, optname)
  96. * Creates new embedded map of IP/mask addresses from config.
  97. * @param {string} mname name of module
  98. * @param {string} optname option to get
  99. * @return {map} radix tree object
  100. * @example
  101. local ip_map = rspamd_config:radix_from_config ('mymodule', 'ips')
  102. ...
  103. local function foo(task)
  104. local ip = task:get_from_ip()
  105. if ip_map:get_key(ip) then
  106. return true
  107. end
  108. return false
  109. end
  110. */
  111. /***
  112. * @method rspamd_config:radix_from_ucl(obj)
  113. * Creates new embedded map of IP/mask addresses from object.
  114. * @param {ucl} obj object
  115. * @return {map} radix tree object
  116. */
  117. /***
  118. * @method rspamd_config:add_hash_map(mapline[, description])
  119. * Creates new dynamic map string objects.
  120. * @param {string} mapline URL for a map
  121. * @param {string} description optional map description
  122. * @return {map} hash set object
  123. * @example
  124. local hash_map = rspamd_config:add_hash_map ('file:///path/to/file', 'my hash map')
  125. ...
  126. local function foo(task)
  127. local from = task:get_from()
  128. if hash_map:get_key(from['user']) then
  129. return true
  130. end
  131. return false
  132. end
  133. */
  134. /***
  135. * @method rspamd_config:add_kv_map(mapline[, description])
  136. * Creates new dynamic map of key/values associations.
  137. * @param {string} mapline URL for a map
  138. * @param {string} description optional map description
  139. * @return {map} hash table object
  140. * @example
  141. local kv_map = rspamd_config:add_kv_map ('file:///path/to/file', 'my kv map')
  142. ...
  143. local function foo(task)
  144. local from = task:get_from()
  145. if from then
  146. local value = kv_map:get_key(from['user'])
  147. if value then
  148. return true,value
  149. end
  150. end
  151. return false
  152. end
  153. */
  154. /***
  155. * @method rspamd_config:add_map({args})
  156. * Creates new dynamic map according to the attributes passed.
  157. *
  158. * - `type`: type of map to be created, can be one of the following set:
  159. * + `set`: set of strings
  160. * + `radix`: map of IP addresses to strings
  161. * + `map`: map of strings to strings
  162. * + `regexp`: map of regexps to strings
  163. * + `callback`: map processed by lua callback
  164. * - `url`: url to load map from
  165. * - `description`: map's description
  166. * - `callback`: lua callback for the map
  167. *
  168. * @return {map} `true` if map has been added
  169. * @example
  170. local str = ''
  171. local function process_map(in)
  172. str = in
  173. end
  174. rspamd_config:add_map('http://example.com/map', "settings map", process_map)
  175. */
  176. /***
  177. * @method rspamd_config:get_maps()
  178. * Get all maps defined as an array of rspamd{map} objects
  179. *
  180. * @return {table|rspamd{map}}
  181. */
  182. /***
  183. * @method rspamd_config:get_classifier(name)
  184. * Returns classifier config.
  185. * @param {string} name name of classifier (e.g. `bayes`)
  186. * @return {classifier} classifier object or `nil`
  187. */
  188. LUA_FUNCTION_DEF(config, get_classifier);
  189. /***
  190. * @method rspamd_config:register_symbol(table)
  191. * Register symbol of a specified type in rspamd. This function accepts table of arguments:
  192. *
  193. * - `name`: name of symbol (can be missing for callback symbols)
  194. * - `callback`: function to be called for symbol's check (can be absent for virtual symbols)
  195. * - `weight`: weight of symbol (should normally be 1 or missing)
  196. * - `priority`: priority of symbol (normally 0 or missing)
  197. * - `type`: type of symbol:
  198. * + `normal`: executed after prefilters, according to dependency graph or in undefined order
  199. * + `callback`: a check that merely inserts virtual symbols
  200. * + `connfilter`: executed early; before message body is available
  201. * + `idempotent`: cannot change result in any way; executed last
  202. * + `postfilter`: executed after most other checks
  203. * + `prefilter`: executed before most other checks
  204. * + `virtual`: a symbol inserted by its parent check
  205. * - `flags`: various flags split by commas or spaces:
  206. * + `nice` if symbol can produce negative score;
  207. * + `empty` if symbol can be called for empty messages
  208. * + `skip` if symbol should be skipped now
  209. * + `nostat` if symbol should be excluded from stat tokens
  210. * + `trivial` symbol is trivial (e.g. no network requests)
  211. * + `explicit_disable` requires explicit disabling (e.g. via settings)
  212. * + `ignore_passthrough` executed even if passthrough result has been set
  213. * - `parent`: id of parent symbol (useful for virtual symbols)
  214. *
  215. * @return {number} id of symbol registered
  216. */
  217. LUA_FUNCTION_DEF(config, register_symbol);
  218. /***
  219. * @method rspamd_config:register_symbols(callback, [weight], callback_name, [, symbol, ...])
  220. * Register callback function to be called for a set of symbols with initial weight.
  221. * @param {function} callback callback function to be called for a specified symbol
  222. * @param {number} weight initial weight of symbol (can be less than zero to specify non-spam symbols)
  223. * @param {string} callback_name symbolic name of callback
  224. * @param {list of strings} symbol list of symbols registered by this function
  225. */
  226. LUA_FUNCTION_DEF(config, register_symbols);
  227. /***
  228. * @method rspamd_config:register_virtual_symbol(name, weight,)
  229. * Register virtual symbol that is not associated with any callback.
  230. *
  231. * **This method is deprecated and should not be used in newly written code **
  232. * @param {string} virtual name symbol's name
  233. * @param {number} weight initial weight of symbol (can be less than zero to specify non-spam symbols)
  234. */
  235. LUA_FUNCTION_DEF(config, register_virtual_symbol);
  236. /***
  237. * @method rspamd_config:register_callback_symbol(name, weight, callback)
  238. * Register callback function to be called for a specified symbol with initial weight. Symbol itself is
  239. * not registered in the metric and is not intended to be visible by a user.
  240. *
  241. * **This method is deprecated and should not be used in newly written code **
  242. * @param {string} name symbol's name (just for unique id purposes)
  243. * @param {number} weight initial weight of symbol (can be less than zero to specify non-spam symbols)
  244. * @param {function} callback callback function to be called for a specified symbol
  245. */
  246. LUA_FUNCTION_DEF(config, register_callback_symbol);
  247. LUA_FUNCTION_DEF(config, register_callback_symbol_priority);
  248. /***
  249. * @method rspamd_config:register_dependency(id|name, depname)
  250. * Create a dependency on symbol identified by name for symbol identified by ID or name.
  251. * This affects order of checks only (a symbol is still checked if its dependencies are disabled).
  252. * @param {number|string} id id or name of source (numeric id is returned by all register_*_symbol)
  253. * @param {string} depname dependency name
  254. * @example
  255. local function cb(task)
  256. ...
  257. end
  258. local id = rspamd_config:register_symbol('SYM', 1.0, cb)
  259. rspamd_config:register_dependency(id, 'OTHER_SYM')
  260. -- Alternative form
  261. -- Symbol MY_RULE needs result from SPF_CHECK
  262. rspamd_config:register_dependency('MY_RULE', 'SPF_CHECK')
  263. */
  264. LUA_FUNCTION_DEF(config, register_dependency);
  265. /***
  266. * @method rspamd_config:get_symbol_flags(name)
  267. * Returns symbol flags
  268. * @param {string} name symbols's name
  269. * @return {table|string} list of flags for symbol or nil
  270. */
  271. LUA_FUNCTION_DEF(config, get_symbol_flags);
  272. /***
  273. * @method rspamd_config:add_symbol_flags(name, flags)
  274. * Adds flags to a symbol
  275. * @param {string} name symbols's name
  276. * @param {table|string} flags flags to add
  277. * @return {table|string} new set of flags
  278. */
  279. LUA_FUNCTION_DEF(config, add_symbol_flags);
  280. /**
  281. * @method rspamd_config:register_re_selector(name, selector_str, [delimiter, [flatten]])
  282. * Registers selector with the specific name to use in regular expressions in form
  283. * name=/re/$ or name=/re/{selector}
  284. * @param {string} name name of the selector
  285. * @param {string} selector_str selector definition
  286. * @param {string} delimiter delimiter to use when joining strings if flatten is false
  287. * @param {bool} flatten if true then selector will return a table of captures instead of a single string
  288. * @return true if selector has been registered
  289. */
  290. LUA_FUNCTION_DEF(config, register_re_selector);
  291. /**
  292. * @method rspamd_config:set_symbol({table})
  293. * Sets the value of a specified symbol in a metric. This function accepts table with the following elements:
  294. *
  295. * - `name`: name of symbol (string)
  296. * - `score`: score for symbol (number)
  297. * - `metric`: name of metric (string, optional)
  298. * - `description`: description of symbol (string, optional)
  299. * - `group`: name of group for symbol (string, optional)
  300. * - `one_shot`: turn off multiple hits for a symbol (boolean, optional)
  301. * - `one_param`: turn off multiple options for a symbol (boolean, optional)
  302. * - `flags`: comma separated string of flags:
  303. * + `ignore`: do not strictly check validity of symbol and corresponding rule
  304. * + `one_shot`: turn off multiple hits for a symbol
  305. * + `one_param`: allow only one parameter for a symbol
  306. * - `priority`: priority of symbol's definition
  307. */
  308. LUA_FUNCTION_DEF(config, set_metric_symbol);
  309. /**
  310. * @method rspamd_config:set_action({table})
  311. * Sets the score of a specified action in a metric. This function accepts table with the following elements:
  312. *
  313. * - `action`: name of action (string)
  314. * - `score`: score for action (number)
  315. * - `metric`: name of metric (string, optional)
  316. * - `priority`: priority of action's definition
  317. */
  318. LUA_FUNCTION_DEF(config, set_metric_action);
  319. /**
  320. * @method rspamd_config:get_action(name)
  321. * Gets data for a specific action in config. This function returns number representing action's score
  322. *
  323. * @param {string} name name of action
  324. * @return {number} action's score or nil in case of undefined score or action
  325. */
  326. LUA_FUNCTION_DEF(config, get_metric_action);
  327. /**
  328. * @method rspamd_config:get_all_actions()
  329. * Gets data for all action in config
  330. * @return {table|str->num} action's score or nil in case of undefined score or action
  331. */
  332. LUA_FUNCTION_DEF(config, get_all_actions);
  333. /**
  334. * @method rspamd_config:add_composite(name, expression)
  335. * @param {string} name name of composite symbol
  336. * @param {string} expression symbolic expression of the composite rule
  337. * @return {bool} true if a composite has been added successfully
  338. */
  339. LUA_FUNCTION_DEF(config, add_composite);
  340. /***
  341. * @method rspamd_config:register_pre_filter(callback[, order])
  342. * Register function to be called prior to symbols processing.
  343. * @param {function} callback callback function
  344. * @param {number} order filters are called from lower orders to higher orders, order is equal to 0 by default
  345. * @example
  346. local function check_function(task)
  347. -- It is possible to manipulate the task object here: set settings, set pre-action and so on
  348. ...
  349. end
  350. rspamd_config:register_pre_filter(check_function)
  351. */
  352. LUA_FUNCTION_DEF(config, register_pre_filter);
  353. /***
  354. * @method rspamd_config:register_post_filter(callback[, order])
  355. * Register function to be called after symbols are processed.
  356. *
  357. * @param {function} callback callback function
  358. * @param {number} order filters are called from lower orders to higher orders, order is equal to 0 by default
  359. */
  360. LUA_FUNCTION_DEF(config, register_post_filter);
  361. /* XXX: obsoleted */
  362. LUA_FUNCTION_DEF(config, register_module_option);
  363. /* XXX: not needed now */
  364. LUA_FUNCTION_DEF(config, get_api_version);
  365. /***
  366. * @method rspamd_config:get_key(name)
  367. * Returns configuration section with the specified `name`.
  368. * @param {string} name name of config section
  369. * @return {variant} specific value of section
  370. * @example
  371. local set_section = rspamd_config:get_key("settings")
  372. if type(set_section) == "string" then
  373. -- Just a map of ucl
  374. if rspamd_config:add_map(set_section, "settings map", process_settings_map) then
  375. rspamd_config:register_pre_filter(check_settings)
  376. end
  377. elseif type(set_section) == "table" then
  378. if process_settings_table(set_section) then
  379. rspamd_config:register_pre_filter(check_settings)
  380. end
  381. end
  382. */
  383. LUA_FUNCTION_DEF(config, get_key);
  384. /***
  385. * @method rspamd_config:add_condition(symbol, condition)
  386. * Adds condition callback for specified symbol
  387. * @param {string} symbol symbol's name
  388. * @param {function} condition condition callback
  389. * @return {boolean} true if condition has been added
  390. * @example
  391. local condition_map = rspamd_config:add_map{
  392. type = "hash",
  393. urls = ['file:///path/to/file'],
  394. description = 'SMTP from map that allows FUZZY_DENIED skip for the listed addresses'
  395. }
  396. rspamd_config:add_condition('FUZZY_DENIED', function(task)
  397. local E = {}
  398. -- Check for the smtp from address adding fail safe checks
  399. if condition_map:find_key(((task:get_from('smtp') or E)[1] or E).addr) then
  400. return false
  401. end
  402. -- Allow execution otherwise
  403. return true
  404. end)
  405. */
  406. LUA_FUNCTION_DEF(config, add_condition);
  407. /***
  408. * @method rspamd_config:enable_symbol(symbol)
  409. * Enables execution for the specified symbol
  410. * @param {string} symbol symbol's name
  411. */
  412. LUA_FUNCTION_DEF(config, enable_symbol);
  413. /***
  414. * @method rspamd_config:disable_symbol(symbol, [disable_parent=true])
  415. * Disables execution for the specified symbol
  416. * @param {string} symbol symbol's name
  417. * @param {boolean} disable_parent if true then disable parent execution in case of a virtual symbol
  418. */
  419. LUA_FUNCTION_DEF(config, disable_symbol);
  420. /***
  421. * @method rspamd_config:get_symbol_parent(symbol)
  422. * Returns a parent symbol for specific symbol (or symbol itself if top level)
  423. * @param {string} symbol symbol's name
  424. */
  425. LUA_FUNCTION_DEF(config, get_symbol_parent);
  426. /***
  427. * @method rspamd_config:get_group_symbols(group)
  428. * Returns list of symbols for a specific group
  429. * @param {string} group group's name
  430. * @available 2.0+
  431. * @return {list|string} list of all symbols in a specific group
  432. */
  433. LUA_FUNCTION_DEF(config, get_group_symbols);
  434. /***
  435. * @method rspamd_config:get_groups([need_private])
  436. * Returns list of all groups defined
  437. * @param {boolean} need_private optional flag to include private groups
  438. * @available 2.3+
  439. * @return {list|table} list of all groups
  440. */
  441. LUA_FUNCTION_DEF(config, get_groups);
  442. /***
  443. * @method rspamd_config:register_settings_id(name, symbols_enabled, symbols_disabled)
  444. * Register new static settings id in config
  445. * @param {string} name id name (not numeric!)
  446. * @param {map|string->string} symbols_enabled map from symbol's name to boolean (currently)
  447. * @param {map|string->string} symbols_disabled map from symbol's name to boolean (currently)
  448. * @available 2.0+
  449. */
  450. LUA_FUNCTION_DEF(config, register_settings_id);
  451. /***
  452. * @method rspamd_config:__newindex(name, callback)
  453. * This metamethod is called if new indices are added to the `rspamd_config` object.
  454. * Technically, it is the equivalent of @see rspamd_config:register_symbol where `weight` is 1.0.
  455. * There is also table form invocation that allows to control more things:
  456. *
  457. * - `callback`: has the same meaning and acts as function of task
  458. * - `score`: default score for a symbol
  459. * - `group`: default group for a symbol
  460. * - `description`: default symbol's description
  461. * - `priority`: additional priority value
  462. * - `one_shot`: default value for one shot attribute
  463. * - `condition`: function of task that can enable or disable this specific rule's execution
  464. * @param {string} name index name
  465. * @param {function/table} callback callback to be called
  466. * @return {number} id of the new symbol added
  467. * @example
  468. rspamd_config.R_EMPTY_IMAGE = function (task)
  469. parts = task:get_text_parts()
  470. if parts then
  471. for _,part in ipairs(parts) do
  472. if part:is_empty() then
  473. images = task:get_images()
  474. if images then
  475. -- Symbol `R_EMPTY_IMAGE` is inserted
  476. return true
  477. end
  478. return false
  479. end
  480. end
  481. end
  482. return false
  483. end
  484. rspamd_config.SYMBOL = {
  485. callback = function(task)
  486. ...
  487. end,
  488. score = 5.1,
  489. description = 'sample symbol',
  490. group = 'sample symbols',
  491. condition = function(task)
  492. if task:get_from()[1]['addr'] == 'user@example.com' then
  493. return false
  494. end
  495. return true
  496. end
  497. }
  498. */
  499. LUA_FUNCTION_DEF(config, newindex);
  500. /***
  501. * @method rspamd_config:register_regexp(params)
  502. * Registers new re for further cached usage
  503. * Params is the table with the following fields (mandatory fields are marked with `*`):
  504. * - `re`* : regular expression object
  505. * - `type`*: type of regular expression:
  506. * + `mime`: mime regexp
  507. * + `rawmime`: raw mime regexp
  508. * + `header`: header regexp
  509. * + `rawheader`: raw header expression
  510. * + `body`: raw body regexp
  511. * + `url`: url regexp
  512. * - `header`: for header and rawheader regexp means the name of header
  513. * - `pcre_only`: flag regexp as pcre only regexp
  514. */
  515. LUA_FUNCTION_DEF(config, register_regexp);
  516. /***
  517. * @method rspamd_config:replace_regexp(params)
  518. * Replaces regexp with a new one
  519. * Params is the table with the following fields (mandatory fields are marked with `*`):
  520. * - `old_re`* : old regular expression object (must be in the cache)
  521. * - `new_re`* : old regular expression object (must not be in the cache)
  522. */
  523. LUA_FUNCTION_DEF(config, replace_regexp);
  524. /***
  525. * @method rspamd_config:register_worker_script(worker_type, script)
  526. * Registers the following script for workers of a specified type. The exact type
  527. * of script function depends on worker type
  528. * @param {string} worker_type worker type (e.g. "normal")
  529. * @param {function} script script for a worker
  530. * @return {boolean} `true` if a script has been registered
  531. */
  532. LUA_FUNCTION_DEF(config, register_worker_script);
  533. /***
  534. * @method rspamd_config:add_on_load(function(cfg, ev_base, worker) ... end)
  535. * Registers the following script to be executed when configuration is completely loaded
  536. * and the worker is already started (forked)
  537. * @param {function} script function to be executed
  538. * @example
  539. rspamd_config:add_on_load(function(cfg, ev_base, worker)
  540. rspamd_config:add_periodic(ev_base, 1.0, function(cfg, ev_base)
  541. local logger = require "rspamd_logger"
  542. logger.infox(cfg, "periodic function in worker %s", worker:get_name())
  543. return true
  544. end)
  545. end)
  546. */
  547. LUA_FUNCTION_DEF(config, add_on_load);
  548. /***
  549. * @method rspamd_config:add_periodic(event_base, timeout, function(cfg, ev_base) ... end, [jitter = false])
  550. * Registers function to be periodically executed by Rspamd
  551. * @param {ev_base} event_base event base that is needed for async events
  552. * @param {number} timeout time in seconds (could be fractional)
  553. * @param {function} script function to be executed
  554. * @param {boolean} jitter `true` if timeout jittering is needed
  555. * @example
  556. rspamd_config:add_on_load(function(cfg, ev_base)
  557. rspamd_config:add_periodic(ev_base, 1.0, function(cfg, ev_base)
  558. local logger = require "rspamd_logger"
  559. logger.infox(cfg, "periodic function")
  560. return true -- if return numeric, a new interval is set. if return false, then the periodic event is removed
  561. end)
  562. end)
  563. */
  564. LUA_FUNCTION_DEF(config, add_periodic);
  565. /***
  566. * @method rspamd_config:add_post_init(function(cfg) ... end)
  567. * Registers the following script to be executed when configuration is completely loaded
  568. * @available 2.0+
  569. * @param {function} script function to be executed
  570. */
  571. LUA_FUNCTION_DEF(config, add_post_init);
  572. /***
  573. * @method rspamd_config:add_config_unload(function(cfg) ... end)
  574. * Registers the following script to be executed when configuration is unloaded
  575. * @available 2.0+
  576. * @param {function} script function to be executed
  577. */
  578. LUA_FUNCTION_DEF(config, add_config_unload);
  579. /***
  580. * @method rspamd_config:get_symbols_count()
  581. * Returns number of symbols registered in rspamd configuration
  582. * @return {number} number of symbols registered in the configuration
  583. */
  584. LUA_FUNCTION_DEF(config, get_symbols_count);
  585. /***
  586. * @method rspamd_config:get_symbols_cksum()
  587. * Returns checksum for all symbols in the cache
  588. * @return {int64} boxed value of the 64 bit checksum
  589. */
  590. LUA_FUNCTION_DEF(config, get_symbols_cksum);
  591. /***
  592. * @method rspamd_config:get_symbols_counters()
  593. * Returns table of all counters in the cache (weights, frequencies etc)
  594. * @return {table|tables} all symbols indexed by name
  595. */
  596. LUA_FUNCTION_DEF(config, get_symbols_counters);
  597. /***
  598. * @method rspamd_config:get_symbols()
  599. * Returns table of all scores defined in config. From version 2.0 returns table:
  600. * - name
  601. * - score
  602. * - flags (e.g. `ignore` or `oneparam`)
  603. * - nshots (== maxhits)
  604. * - group - main group
  605. * - groups - array of all groups
  606. * @available 2.0+
  607. * @return {table|tables} all symbols indexed by name
  608. */
  609. LUA_FUNCTION_DEF(config, get_symbols);
  610. /***
  611. * @method rspamd_config:get_symbol(sym_name)
  612. * Returns table for a specific symbol getting data from the static config:
  613. * - name
  614. * - score
  615. * - flags (e.g. `ignore` or `oneparam`)
  616. * - nshots (== maxhits)
  617. * - group - main group
  618. * - groups - array of all groups
  619. * @available 3.3+
  620. * @return {table} symbol data (or nil)
  621. */
  622. LUA_FUNCTION_DEF(config, get_symbol);
  623. /***
  624. * @method rspamd_config:get_symbol_callback(name)
  625. * Returns callback function for the specified symbol if it is a lua registered callback
  626. * @return {function} callback function or nil
  627. */
  628. LUA_FUNCTION_DEF(config, get_symbol_callback);
  629. /***
  630. * @method rspamd_config:get_symbol_stat(name)
  631. * Returns table with statistics for a specific symbol:
  632. * - `frequency`: frequency for symbol's hits
  633. * - `stddev`: standard deviation of `frequency`
  634. * - `time`: average time in seconds (floating point)
  635. * - `count`: total number of hits
  636. * @return {table} symbol stats
  637. */
  638. LUA_FUNCTION_DEF(config, get_symbol_stat);
  639. /***
  640. * @method rspamd_config:set_symbol_callback(name, callback)
  641. * Sets callback for the specified symbol
  642. * @return {boolean} true if function has been replaced
  643. */
  644. LUA_FUNCTION_DEF(config, set_symbol_callback);
  645. /***
  646. * @method rspamd_config:register_finish_script(callback)
  647. * Adds new callback that is called on worker process termination when all
  648. * tasks pending are processed
  649. *
  650. * @param callback {function} a function with one argument (rspamd_task)
  651. */
  652. LUA_FUNCTION_DEF(config, register_finish_script);
  653. /***
  654. * @method rspamd_config:register_monitored(url, type, [{params}])
  655. * Registers monitored resource to watch its availability. Supported types:
  656. *
  657. * - `dns`: DNS monitored object
  658. *
  659. * Params are optional table specific for each type. For DNS it supports the
  660. * following options:
  661. *
  662. * - `prefix`: prefix to add before making request
  663. * - `type`: type of request (e.g. 'a' or 'txt')
  664. * - `ipnet`: array of ip/networks to expect on reply
  665. * - `rcode`: expected return code (e.g. `nxdomain`)
  666. *
  667. * Returned object has the following methods:
  668. *
  669. * - `alive`: returns `true` if monitored resource is alive
  670. * - `offline`: returns number of seconds of the current offline period (or 0 if alive)
  671. * - `total_offline`: returns number of seconds of the overall offline
  672. * - `latency`: returns the current average latency in seconds (or 0 if offline)
  673. *
  674. * @param {string} url resource to monitor
  675. * @param {string} type type of monitoring
  676. * @param {table} opts optional parameters
  677. * @return {rspamd_monitored} rspamd monitored object
  678. */
  679. LUA_FUNCTION_DEF(config, register_monitored);
  680. /***
  681. * @method rspamd_config:add_doc(path, option, doc_string, [{params}])
  682. * Adds new documentation string for an option `option` at path `path`
  683. * Options defines optional params, such as:
  684. *
  685. * - `default`: default option value
  686. * - `type`: type of an option (`string`, `number`, `object`, `array` etc)
  687. * - `required`: if an option is required
  688. *
  689. * @param {string} path documentation path (e.g. module name)
  690. * @param {string} option name of the option
  691. * @param {string} doc_string documentation string
  692. * @param {table} params optional parameters
  693. */
  694. LUA_FUNCTION_DEF(config, add_doc);
  695. /***
  696. * @method rspamd_config:add_example(path, option, doc_string, example)
  697. * Adds new documentation
  698. *
  699. * @param {string} path documentation path (e.g. module name or nil for top)
  700. * @param {string} option name of the option
  701. * @param {string} doc_string documentation string
  702. * @param {string} example example in ucl format, comments are also parsed
  703. */
  704. LUA_FUNCTION_DEF(config, add_example);
  705. /***
  706. * @method rspamd_config:set_peak_cb(function)
  707. * Sets a function that will be called when frequency of some symbol goes out of
  708. * stddev * 2 over the last period of refreshment.
  709. *
  710. * @example
  711. rspamd_config:set_peak_cb(function(ev_base, sym, mean, stddev, value, error)
  712. -- ev_base: event base for async events (e.g. redis)
  713. -- sym: symbol's name
  714. -- mean: mean frequency value
  715. -- stddev: standard deviation of frequency
  716. -- value: current frequency value
  717. -- error: squared error
  718. local logger = require "rspamd_logger"
  719. logger.infox(rspamd_config, "symbol %s has changed frequency significantly: %s(%s) over %s(%s)",
  720. sym, value, error, mean, stddev)
  721. end)
  722. */
  723. LUA_FUNCTION_DEF(config, set_peak_cb);
  724. /***
  725. * @method rspamd_config:get_cpu_flags()
  726. * Returns architecture dependent flags supported by the CPU
  727. * Currently, only x86 flags are supported:
  728. * - 'ssse3'
  729. * - 'sse42'
  730. * - 'avx'
  731. * - 'avx2'
  732. * @return {table} flag -> true table
  733. */
  734. LUA_FUNCTION_DEF(config, get_cpu_flags);
  735. /***
  736. * @method rspamd_config:has_torch()
  737. * Returns true if Rspamd is compiled with torch support and the runtime CPU
  738. * supports sse4.2 required for torch.
  739. * @return {boolean} true if torch is compiled and supported
  740. */
  741. LUA_FUNCTION_DEF(config, has_torch);
  742. /***
  743. * @method rspamd_config:experimental_enabled()
  744. * Returns true if experimental plugins are enabled
  745. * @return {boolean} true if experimental plugins are enabled
  746. */
  747. LUA_FUNCTION_DEF(config, experimental_enabled);
  748. /***
  749. * @method rspamd_config:load_ucl(filename[, include_trace])
  750. * Loads config from the UCL file (but does not perform parsing using rcl)
  751. * @param {string} filename file to load
  752. * @return true or false + error message
  753. */
  754. LUA_FUNCTION_DEF(config, load_ucl);
  755. /***
  756. * @method rspamd_config:parse_rcl([skip_sections])
  757. * Parses RCL using loaded ucl file
  758. * @param {table|string} sections to skip
  759. * @return true or false + error message
  760. */
  761. LUA_FUNCTION_DEF(config, parse_rcl);
  762. /***
  763. * @method rspamd_config:init_modules()
  764. * Initialize lua and internal modules
  765. * @return true or false
  766. */
  767. LUA_FUNCTION_DEF(config, init_modules);
  768. /***
  769. * @method rspamd_config:init_subsystem(str)
  770. * Initialize config subsystem from a comma separated list:
  771. * - `modules` - init modules
  772. * - `langdet` - language detector
  773. * - `dns` - DNS resolver
  774. * - TODO: add more
  775. */
  776. LUA_FUNCTION_DEF(config, init_subsystem);
  777. /***
  778. * @method rspamd_config:get_tld_path()
  779. * Returns path to TLD file
  780. * @return {string} path to tld file
  781. */
  782. LUA_FUNCTION_DEF(config, get_tld_path);
  783. /***
  784. * @method rspamd_config:get_dns_max_requests()
  785. * Returns limit of DNS requests per task
  786. * @return {number} number of dns requests allowed
  787. */
  788. LUA_FUNCTION_DEF(config, get_dns_max_requests);
  789. /***
  790. * @method rspamd_config:get_dns_timeout()
  791. * Returns timeout for a DNS request
  792. * @return {number} DNS timeout in second or 0 if not defined
  793. */
  794. LUA_FUNCTION_DEF(config, get_dns_timeout);
  795. static const struct luaL_reg configlib_m[] = {
  796. LUA_INTERFACE_DEF(config, get_module_opt),
  797. LUA_INTERFACE_DEF(config, get_mempool),
  798. LUA_INTERFACE_DEF(config, get_resolver),
  799. LUA_INTERFACE_DEF(config, get_all_opt),
  800. LUA_INTERFACE_DEF(config, get_ucl),
  801. LUA_INTERFACE_DEF(config, add_radix_map),
  802. LUA_INTERFACE_DEF(config, radix_from_config),
  803. LUA_INTERFACE_DEF(config, radix_from_ucl),
  804. LUA_INTERFACE_DEF(config, add_hash_map),
  805. LUA_INTERFACE_DEF(config, add_kv_map),
  806. LUA_INTERFACE_DEF(config, add_map),
  807. LUA_INTERFACE_DEF(config, get_maps),
  808. LUA_INTERFACE_DEF(config, get_classifier),
  809. LUA_INTERFACE_DEF(config, register_symbol),
  810. LUA_INTERFACE_DEF(config, register_symbols),
  811. LUA_INTERFACE_DEF(config, register_virtual_symbol),
  812. LUA_INTERFACE_DEF(config, register_callback_symbol),
  813. LUA_INTERFACE_DEF(config, register_callback_symbol_priority),
  814. LUA_INTERFACE_DEF(config, register_dependency),
  815. LUA_INTERFACE_DEF(config, register_settings_id),
  816. LUA_INTERFACE_DEF(config, get_symbol_flags),
  817. LUA_INTERFACE_DEF(config, set_metric_symbol),
  818. {"set_symbol", lua_config_set_metric_symbol},
  819. LUA_INTERFACE_DEF(config, set_metric_action),
  820. {"set_action", lua_config_set_metric_action},
  821. {"get_metric_symbol", lua_config_get_symbol},
  822. LUA_INTERFACE_DEF(config, get_metric_action),
  823. {"get_action", lua_config_get_metric_action},
  824. LUA_INTERFACE_DEF(config, get_all_actions),
  825. LUA_INTERFACE_DEF(config, add_composite),
  826. LUA_INTERFACE_DEF(config, register_module_option),
  827. LUA_INTERFACE_DEF(config, register_pre_filter),
  828. LUA_INTERFACE_DEF(config, register_post_filter),
  829. LUA_INTERFACE_DEF(config, get_api_version),
  830. LUA_INTERFACE_DEF(config, get_key),
  831. LUA_INTERFACE_DEF(config, add_condition),
  832. LUA_INTERFACE_DEF(config, enable_symbol),
  833. LUA_INTERFACE_DEF(config, disable_symbol),
  834. LUA_INTERFACE_DEF(config, register_regexp),
  835. LUA_INTERFACE_DEF(config, replace_regexp),
  836. LUA_INTERFACE_DEF(config, register_worker_script),
  837. LUA_INTERFACE_DEF(config, register_re_selector),
  838. LUA_INTERFACE_DEF(config, add_on_load),
  839. LUA_INTERFACE_DEF(config, add_periodic),
  840. LUA_INTERFACE_DEF(config, add_post_init),
  841. LUA_INTERFACE_DEF(config, add_config_unload),
  842. LUA_INTERFACE_DEF(config, get_symbols_count),
  843. LUA_INTERFACE_DEF(config, get_symbols_cksum),
  844. LUA_INTERFACE_DEF(config, get_symbols_counters),
  845. {"get_symbols_scores", lua_config_get_symbols},
  846. LUA_INTERFACE_DEF(config, get_symbols),
  847. LUA_INTERFACE_DEF(config, get_symbol),
  848. LUA_INTERFACE_DEF(config, get_groups),
  849. LUA_INTERFACE_DEF(config, get_symbol_callback),
  850. LUA_INTERFACE_DEF(config, set_symbol_callback),
  851. LUA_INTERFACE_DEF(config, get_symbol_stat),
  852. LUA_INTERFACE_DEF(config, get_symbol_parent),
  853. LUA_INTERFACE_DEF(config, get_group_symbols),
  854. LUA_INTERFACE_DEF(config, register_finish_script),
  855. LUA_INTERFACE_DEF(config, register_monitored),
  856. LUA_INTERFACE_DEF(config, add_doc),
  857. LUA_INTERFACE_DEF(config, add_example),
  858. LUA_INTERFACE_DEF(config, set_peak_cb),
  859. LUA_INTERFACE_DEF(config, get_cpu_flags),
  860. LUA_INTERFACE_DEF(config, has_torch),
  861. LUA_INTERFACE_DEF(config, experimental_enabled),
  862. LUA_INTERFACE_DEF(config, load_ucl),
  863. LUA_INTERFACE_DEF(config, parse_rcl),
  864. LUA_INTERFACE_DEF(config, init_modules),
  865. LUA_INTERFACE_DEF(config, init_subsystem),
  866. LUA_INTERFACE_DEF(config, get_tld_path),
  867. LUA_INTERFACE_DEF(config, get_dns_max_requests),
  868. LUA_INTERFACE_DEF(config, get_dns_timeout),
  869. {"__tostring", rspamd_lua_class_tostring},
  870. {"__newindex", lua_config_newindex},
  871. {NULL, NULL}};
  872. LUA_FUNCTION_DEF(monitored, alive);
  873. LUA_FUNCTION_DEF(monitored, latency);
  874. LUA_FUNCTION_DEF(monitored, offline);
  875. LUA_FUNCTION_DEF(monitored, total_offline);
  876. static const struct luaL_reg monitoredlib_m[] = {
  877. LUA_INTERFACE_DEF(monitored, alive),
  878. LUA_INTERFACE_DEF(monitored, latency),
  879. LUA_INTERFACE_DEF(monitored, offline),
  880. LUA_INTERFACE_DEF(monitored, total_offline),
  881. {"__tostring", rspamd_lua_class_tostring},
  882. {NULL, NULL}};
  883. static const guint64 rspamd_lua_callback_magic = 0x32c118af1e3263c7ULL;
  884. struct rspamd_config *
  885. lua_check_config(lua_State *L, gint pos)
  886. {
  887. void *ud = rspamd_lua_check_udata(L, pos, "rspamd{config}");
  888. luaL_argcheck(L, ud != NULL, pos, "'config' expected");
  889. return ud ? *((struct rspamd_config **) ud) : NULL;
  890. }
  891. static struct rspamd_monitored *
  892. lua_check_monitored(lua_State *L, gint pos)
  893. {
  894. void *ud = rspamd_lua_check_udata(L, pos, "rspamd{monitored}");
  895. luaL_argcheck(L, ud != NULL, pos, "'monitored' expected");
  896. return ud ? *((struct rspamd_monitored **) ud) : NULL;
  897. }
  898. /*** Config functions ***/
  899. static gint
  900. lua_config_get_api_version(lua_State *L)
  901. {
  902. msg_warn("get_api_version is deprecated, do not use it");
  903. lua_pushnumber(L, 100);
  904. return 1;
  905. }
  906. static gint
  907. lua_config_get_module_opt(lua_State *L)
  908. {
  909. LUA_TRACE_POINT;
  910. struct rspamd_config *cfg = lua_check_config(L, 1);
  911. const gchar *mname, *optname;
  912. const ucl_object_t *obj;
  913. if (cfg) {
  914. mname = luaL_checkstring(L, 2);
  915. optname = luaL_checkstring(L, 3);
  916. if (mname && optname) {
  917. obj = rspamd_config_get_module_opt(cfg, mname, optname);
  918. if (obj) {
  919. return ucl_object_push_lua(L, obj, TRUE);
  920. }
  921. }
  922. }
  923. lua_pushnil(L);
  924. return 1;
  925. }
  926. static int
  927. lua_config_get_mempool(lua_State *L)
  928. {
  929. LUA_TRACE_POINT;
  930. rspamd_mempool_t **ppool;
  931. struct rspamd_config *cfg = lua_check_config(L, 1);
  932. if (cfg != NULL) {
  933. ppool = lua_newuserdata(L, sizeof(rspamd_mempool_t *));
  934. rspamd_lua_setclass(L, "rspamd{mempool}", -1);
  935. *ppool = cfg->cfg_pool;
  936. }
  937. else {
  938. lua_pushnil(L);
  939. }
  940. return 1;
  941. }
  942. static int
  943. lua_config_get_resolver(lua_State *L)
  944. {
  945. LUA_TRACE_POINT;
  946. struct rspamd_dns_resolver **pres;
  947. struct rspamd_config *cfg = lua_check_config(L, 1);
  948. if (cfg != NULL && cfg->dns_resolver) {
  949. pres = lua_newuserdata(L, sizeof(*pres));
  950. rspamd_lua_setclass(L, "rspamd{resolver}", -1);
  951. *pres = cfg->dns_resolver;
  952. }
  953. else {
  954. lua_pushnil(L);
  955. }
  956. return 1;
  957. }
  958. static gint
  959. lua_config_get_all_opt(lua_State *L)
  960. {
  961. LUA_TRACE_POINT;
  962. struct rspamd_config *cfg = lua_check_config(L, 1);
  963. const gchar *mname;
  964. const ucl_object_t *obj, *cur, *cur_elt;
  965. ucl_object_iter_t it = NULL;
  966. gint i;
  967. if (cfg) {
  968. mname = luaL_checkstring(L, 2);
  969. if (mname) {
  970. obj = ucl_obj_get_key(cfg->cfg_ucl_obj, mname);
  971. /* Flatten object */
  972. if (obj != NULL && (ucl_object_type(obj) == UCL_OBJECT ||
  973. ucl_object_type(obj) == UCL_ARRAY)) {
  974. lua_newtable(L);
  975. it = ucl_object_iterate_new(obj);
  976. LL_FOREACH(obj, cur)
  977. {
  978. it = ucl_object_iterate_reset(it, cur);
  979. while ((cur_elt = ucl_object_iterate_safe(it, true))) {
  980. lua_pushstring(L, ucl_object_key(cur_elt));
  981. ucl_object_push_lua(L, cur_elt, true);
  982. lua_settable(L, -3);
  983. }
  984. }
  985. ucl_object_iterate_free(it);
  986. return 1;
  987. }
  988. else if (obj != NULL) {
  989. lua_newtable(L);
  990. i = 1;
  991. LL_FOREACH(obj, cur)
  992. {
  993. lua_pushinteger(L, i++);
  994. ucl_object_push_lua(L, cur, true);
  995. lua_settable(L, -3);
  996. }
  997. return 1;
  998. }
  999. }
  1000. }
  1001. lua_pushnil(L);
  1002. return 1;
  1003. }
  1004. struct rspamd_lua_cached_config {
  1005. lua_State *L;
  1006. gint ref;
  1007. };
  1008. static void
  1009. lua_config_ucl_dtor(gpointer p)
  1010. {
  1011. struct rspamd_lua_cached_config *cached = p;
  1012. luaL_unref(cached->L, LUA_REGISTRYINDEX, cached->ref);
  1013. }
  1014. static gint
  1015. lua_config_get_ucl(lua_State *L)
  1016. {
  1017. LUA_TRACE_POINT;
  1018. struct rspamd_config *cfg = lua_check_config(L, 1);
  1019. struct rspamd_lua_cached_config *cached;
  1020. if (cfg) {
  1021. cached = rspamd_mempool_get_variable(cfg->cfg_pool, "ucl_cached");
  1022. if (cached) {
  1023. lua_rawgeti(L, LUA_REGISTRYINDEX, cached->ref);
  1024. }
  1025. else {
  1026. if (cfg->cfg_ucl_obj) {
  1027. ucl_object_push_lua(L, cfg->cfg_ucl_obj, true);
  1028. lua_pushvalue(L, -1);
  1029. cached = rspamd_mempool_alloc(cfg->cfg_pool, sizeof(*cached));
  1030. cached->L = L;
  1031. cached->ref = luaL_ref(L, LUA_REGISTRYINDEX);
  1032. rspamd_mempool_set_variable(cfg->cfg_pool, "ucl_cached",
  1033. cached, lua_config_ucl_dtor);
  1034. }
  1035. else {
  1036. lua_pushnil(L);
  1037. }
  1038. }
  1039. }
  1040. else {
  1041. return luaL_error(L, "invalid arguments");
  1042. }
  1043. return 1;
  1044. }
  1045. static gint
  1046. lua_config_get_classifier(lua_State *L)
  1047. {
  1048. LUA_TRACE_POINT;
  1049. struct rspamd_config *cfg = lua_check_config(L, 1);
  1050. struct rspamd_classifier_config *clc = NULL, **pclc = NULL;
  1051. const gchar *name;
  1052. GList *cur;
  1053. if (cfg) {
  1054. name = luaL_checkstring(L, 2);
  1055. cur = g_list_first(cfg->classifiers);
  1056. while (cur) {
  1057. clc = cur->data;
  1058. if (g_ascii_strcasecmp(clc->name, name) == 0) {
  1059. pclc = &clc;
  1060. break;
  1061. }
  1062. cur = g_list_next(cur);
  1063. }
  1064. if (pclc) {
  1065. pclc = lua_newuserdata(L,
  1066. sizeof(struct rspamd_classifier_config *));
  1067. rspamd_lua_setclass(L, "rspamd{classifier}", -1);
  1068. *pclc = clc;
  1069. return 1;
  1070. }
  1071. }
  1072. lua_pushnil(L);
  1073. return 1;
  1074. }
  1075. struct lua_callback_data {
  1076. guint64 magic;
  1077. lua_State *L;
  1078. gchar *symbol;
  1079. union {
  1080. gchar *name;
  1081. gint ref;
  1082. } callback;
  1083. gboolean cb_is_ref;
  1084. /* Dynamic data */
  1085. gint stack_level;
  1086. gint order;
  1087. struct rspamd_symcache_dynamic_item *item;
  1088. };
  1089. /*
  1090. * Unref symbol if it is local reference
  1091. */
  1092. static void
  1093. lua_destroy_cfg_symbol(gpointer ud)
  1094. {
  1095. struct lua_callback_data *cd = ud;
  1096. /* Unref callback */
  1097. if (cd->cb_is_ref) {
  1098. luaL_unref(cd->L, LUA_REGISTRYINDEX, cd->callback.ref);
  1099. }
  1100. }
  1101. static gint
  1102. lua_config_register_module_option(lua_State *L)
  1103. {
  1104. return 0;
  1105. }
  1106. static gint
  1107. rspamd_compare_order_func(gconstpointer a, gconstpointer b)
  1108. {
  1109. const struct lua_callback_data *cb1 = a, *cb2 = b;
  1110. /* order of call goes from lower to higher */
  1111. return cb2->order - cb1->order;
  1112. }
  1113. static void
  1114. lua_metric_symbol_callback(struct rspamd_task *task,
  1115. struct rspamd_symcache_dynamic_item *item,
  1116. gpointer ud)
  1117. {
  1118. struct lua_callback_data *cd = ud;
  1119. struct rspamd_task **ptask;
  1120. gint level = lua_gettop(cd->L), nresults, err_idx, ret;
  1121. lua_State *L = cd->L;
  1122. struct rspamd_symbol_result *s;
  1123. cd->item = item;
  1124. rspamd_symcache_item_async_inc(task, item, "lua symbol");
  1125. lua_pushcfunction(L, &rspamd_lua_traceback);
  1126. err_idx = lua_gettop(L);
  1127. level++;
  1128. if (cd->cb_is_ref) {
  1129. lua_rawgeti(L, LUA_REGISTRYINDEX, cd->callback.ref);
  1130. }
  1131. else {
  1132. lua_getglobal(L, cd->callback.name);
  1133. }
  1134. ptask = lua_newuserdata(L, sizeof(struct rspamd_task *));
  1135. rspamd_lua_setclass(L, rspamd_task_classname, -1);
  1136. *ptask = task;
  1137. if ((ret = lua_pcall(L, 1, LUA_MULTRET, err_idx)) != 0) {
  1138. msg_err_task("call to (%s) failed (%d): %s", cd->symbol, ret,
  1139. lua_tostring(L, -1));
  1140. lua_settop(L, err_idx); /* Not -1 here, as err_func is popped below */
  1141. }
  1142. else {
  1143. nresults = lua_gettop(L) - level;
  1144. if (nresults >= 1) {
  1145. /* Function returned boolean, so maybe we need to insert result? */
  1146. gint res = 0;
  1147. gint i;
  1148. gdouble flag = 1.0;
  1149. gint type;
  1150. type = lua_type(cd->L, level + 1);
  1151. if (type == LUA_TBOOLEAN) {
  1152. res = lua_toboolean(L, level + 1);
  1153. }
  1154. else if (type == LUA_TNUMBER) {
  1155. res = lua_tonumber(L, level + 1);
  1156. }
  1157. else if (type == LUA_TNIL) {
  1158. /* Can happen sometimes... */
  1159. res = FALSE;
  1160. }
  1161. else {
  1162. /* Something bogus has been returned, so we should log it */
  1163. msg_err_task("invalid return value for %s: %s",
  1164. cd->symbol, lua_typename(L, type));
  1165. res = FALSE;
  1166. }
  1167. if (res) {
  1168. gint first_opt = 2;
  1169. if (lua_type(L, level + 2) == LUA_TNUMBER) {
  1170. flag = lua_tonumber(L, level + 2);
  1171. /* Shift opt index */
  1172. first_opt = 3;
  1173. }
  1174. else {
  1175. flag = res;
  1176. }
  1177. s = rspamd_task_insert_result(task, cd->symbol, flag, NULL);
  1178. if (s) {
  1179. guint last_pos = lua_gettop(L);
  1180. for (i = level + first_opt; i <= last_pos; i++) {
  1181. if (lua_type(L, i) == LUA_TSTRING) {
  1182. gsize optlen;
  1183. const char *opt = lua_tolstring(L, i, &optlen);
  1184. rspamd_task_add_result_option(task, s, opt, optlen);
  1185. }
  1186. else if (lua_type(L, i) == LUA_TUSERDATA) {
  1187. struct rspamd_lua_text *t = lua_check_text(L, i);
  1188. if (t) {
  1189. rspamd_task_add_result_option(task, s, t->start,
  1190. t->len);
  1191. }
  1192. }
  1193. else if (lua_type(L, i) == LUA_TTABLE) {
  1194. gsize objlen = rspamd_lua_table_size(L, i);
  1195. for (guint j = 1; j <= objlen; j++) {
  1196. lua_rawgeti(L, i, j);
  1197. if (lua_type(L, -1) == LUA_TSTRING) {
  1198. gsize optlen;
  1199. const char *opt = lua_tolstring(L, -1, &optlen);
  1200. rspamd_task_add_result_option(task, s, opt, optlen);
  1201. }
  1202. else if (lua_type(L, -1) == LUA_TUSERDATA) {
  1203. struct rspamd_lua_text *t = lua_check_text(L, -1);
  1204. if (t) {
  1205. rspamd_task_add_result_option(task, s, t->start,
  1206. t->len);
  1207. }
  1208. }
  1209. lua_pop(L, 1);
  1210. }
  1211. }
  1212. }
  1213. }
  1214. }
  1215. lua_pop(L, nresults);
  1216. }
  1217. }
  1218. lua_pop(L, 1); /* Error function */
  1219. rspamd_symcache_item_async_dec_check(task, cd->item, "lua symbol");
  1220. g_assert(lua_gettop(L) == level - 1);
  1221. }
  1222. static void lua_metric_symbol_callback_return(struct thread_entry *thread_entry,
  1223. int ret);
  1224. static void lua_metric_symbol_callback_error(struct thread_entry *thread_entry,
  1225. int ret,
  1226. const char *msg);
  1227. static void
  1228. lua_metric_symbol_callback_coro(struct rspamd_task *task,
  1229. struct rspamd_symcache_dynamic_item *item,
  1230. gpointer ud)
  1231. {
  1232. struct lua_callback_data *cd = ud;
  1233. struct rspamd_task **ptask;
  1234. struct thread_entry *thread_entry;
  1235. cd->item = item;
  1236. rspamd_symcache_item_async_inc(task, item, "lua coro symbol");
  1237. thread_entry = lua_thread_pool_get_for_task(task);
  1238. g_assert(thread_entry->cd == NULL);
  1239. thread_entry->cd = cd;
  1240. lua_State *thread = thread_entry->lua_state;
  1241. cd->stack_level = lua_gettop(thread);
  1242. if (cd->cb_is_ref) {
  1243. lua_rawgeti(thread, LUA_REGISTRYINDEX, cd->callback.ref);
  1244. }
  1245. else {
  1246. lua_getglobal(thread, cd->callback.name);
  1247. }
  1248. ptask = lua_newuserdata(thread, sizeof(struct rspamd_task *));
  1249. rspamd_lua_setclass(thread, rspamd_task_classname, -1);
  1250. *ptask = task;
  1251. thread_entry->finish_callback = lua_metric_symbol_callback_return;
  1252. thread_entry->error_callback = lua_metric_symbol_callback_error;
  1253. lua_thread_call(thread_entry, 1);
  1254. }
  1255. static void
  1256. lua_metric_symbol_callback_error(struct thread_entry *thread_entry,
  1257. int ret,
  1258. const char *msg)
  1259. {
  1260. struct lua_callback_data *cd = thread_entry->cd;
  1261. struct rspamd_task *task = thread_entry->task;
  1262. msg_err_task("call to coroutine (%s) failed (%d): %s", cd->symbol, ret, msg);
  1263. rspamd_symcache_item_async_dec_check(task, cd->item, "lua coro symbol");
  1264. }
  1265. static void
  1266. lua_metric_symbol_callback_return(struct thread_entry *thread_entry, int ret)
  1267. {
  1268. struct lua_callback_data *cd = thread_entry->cd;
  1269. struct rspamd_task *task = thread_entry->task;
  1270. int nresults;
  1271. struct rspamd_symbol_result *s;
  1272. (void) ret;
  1273. lua_State *L = thread_entry->lua_state;
  1274. nresults = lua_gettop(L) - cd->stack_level;
  1275. if (nresults >= 1) {
  1276. /* Function returned boolean, so maybe we need to insert result? */
  1277. gint res = 0;
  1278. gint i;
  1279. gdouble flag = 1.0;
  1280. gint type;
  1281. type = lua_type(L, cd->stack_level + 1);
  1282. if (type == LUA_TBOOLEAN) {
  1283. res = lua_toboolean(L, cd->stack_level + 1);
  1284. }
  1285. else if (type == LUA_TFUNCTION) {
  1286. g_assert_not_reached();
  1287. }
  1288. else {
  1289. res = lua_tonumber(L, cd->stack_level + 1);
  1290. }
  1291. if (res) {
  1292. gint first_opt = 2;
  1293. if (lua_type(L, cd->stack_level + 2) == LUA_TNUMBER) {
  1294. flag = lua_tonumber(L, cd->stack_level + 2);
  1295. /* Shift opt index */
  1296. first_opt = 3;
  1297. }
  1298. else {
  1299. flag = res;
  1300. }
  1301. s = rspamd_task_insert_result(task, cd->symbol, flag, NULL);
  1302. if (s) {
  1303. guint last_pos = lua_gettop(L);
  1304. for (i = cd->stack_level + first_opt; i <= last_pos; i++) {
  1305. if (lua_type(L, i) == LUA_TSTRING) {
  1306. gsize optlen;
  1307. const char *opt = lua_tolstring(L, i, &optlen);
  1308. rspamd_task_add_result_option(task, s, opt, optlen);
  1309. }
  1310. else if (lua_type(L, i) == LUA_TUSERDATA) {
  1311. struct rspamd_lua_text *t = lua_check_text(L, i);
  1312. if (t) {
  1313. rspamd_task_add_result_option(task, s, t->start,
  1314. t->len);
  1315. }
  1316. }
  1317. else if (lua_type(L, i) == LUA_TTABLE) {
  1318. gsize objlen = rspamd_lua_table_size(L, i);
  1319. for (guint j = 1; j <= objlen; j++) {
  1320. lua_rawgeti(L, i, j);
  1321. if (lua_type(L, -1) == LUA_TSTRING) {
  1322. gsize optlen;
  1323. const char *opt = lua_tolstring(L, -1, &optlen);
  1324. rspamd_task_add_result_option(task, s, opt, optlen);
  1325. }
  1326. else if (lua_type(L, -1) == LUA_TUSERDATA) {
  1327. struct rspamd_lua_text *t = lua_check_text(L, -1);
  1328. if (t) {
  1329. rspamd_task_add_result_option(task, s, t->start,
  1330. t->len);
  1331. }
  1332. }
  1333. lua_pop(L, 1);
  1334. }
  1335. }
  1336. }
  1337. }
  1338. }
  1339. lua_pop(L, nresults);
  1340. }
  1341. g_assert(lua_gettop(L) == cd->stack_level); /* we properly cleaned up the stack */
  1342. cd->stack_level = 0;
  1343. rspamd_symcache_item_async_dec_check(task, cd->item, "lua coro symbol");
  1344. }
  1345. static GArray *
  1346. rspamd_process_id_list(const gchar *entries)
  1347. {
  1348. gchar **sym_elts;
  1349. GArray *ret;
  1350. sym_elts = g_strsplit_set(entries, ",;", -1);
  1351. guint nids = g_strv_length(sym_elts);
  1352. ret = g_array_sized_new(FALSE, FALSE, sizeof(guint32), nids);
  1353. for (guint i = 0; i < nids; i++) {
  1354. guint32 v = rspamd_config_name_to_id(sym_elts[i], strlen(sym_elts[i]));
  1355. g_array_append_val(ret, v);
  1356. }
  1357. g_strfreev(sym_elts);
  1358. return ret;
  1359. }
  1360. static gint
  1361. rspamd_register_symbol_fromlua(lua_State *L,
  1362. struct rspamd_config *cfg,
  1363. const gchar *name,
  1364. gint ref,
  1365. gdouble weight,
  1366. gint priority,
  1367. enum rspamd_symbol_type type,
  1368. gint parent,
  1369. GArray *allowed_ids,
  1370. GArray *forbidden_ids,
  1371. gboolean optional)
  1372. {
  1373. struct lua_callback_data *cd;
  1374. gint ret = -1;
  1375. if (priority == 0 && weight < 0) {
  1376. priority = 1;
  1377. }
  1378. if ((ret = rspamd_symcache_find_symbol(cfg->cache, name)) != -1) {
  1379. if (optional) {
  1380. msg_debug_config("duplicate symbol: %s, skip registering", name);
  1381. return ret;
  1382. }
  1383. else {
  1384. msg_err_config("duplicate symbol: %s, skip registering", name);
  1385. return -1;
  1386. }
  1387. }
  1388. if (allowed_ids && !(type & SYMBOL_TYPE_EXPLICIT_DISABLE)) {
  1389. /* Mark symbol as explicit allow */
  1390. msg_info_config("mark symbol %s as explicit enable as its execution is"
  1391. "allowed merely on specific settings ids",
  1392. name);
  1393. type |= SYMBOL_TYPE_EXPLICIT_ENABLE;
  1394. }
  1395. if (ref != -1) {
  1396. cd = rspamd_mempool_alloc0(cfg->cfg_pool,
  1397. sizeof(struct lua_callback_data));
  1398. cd->magic = rspamd_lua_callback_magic;
  1399. cd->cb_is_ref = TRUE;
  1400. cd->callback.ref = ref;
  1401. cd->L = L;
  1402. if (name) {
  1403. cd->symbol = rspamd_mempool_strdup(cfg->cfg_pool, name);
  1404. }
  1405. if (type & SYMBOL_TYPE_USE_CORO) {
  1406. ret = rspamd_symcache_add_symbol(cfg->cache,
  1407. name,
  1408. priority,
  1409. lua_metric_symbol_callback_coro,
  1410. cd,
  1411. type,
  1412. parent);
  1413. }
  1414. else {
  1415. ret = rspamd_symcache_add_symbol(cfg->cache,
  1416. name,
  1417. priority,
  1418. lua_metric_symbol_callback,
  1419. cd,
  1420. type,
  1421. parent);
  1422. }
  1423. rspamd_mempool_add_destructor(cfg->cfg_pool,
  1424. (rspamd_mempool_destruct_t) lua_destroy_cfg_symbol,
  1425. cd);
  1426. }
  1427. else {
  1428. /* No callback */
  1429. ret = rspamd_symcache_add_symbol(cfg->cache,
  1430. name,
  1431. priority,
  1432. NULL,
  1433. NULL,
  1434. type,
  1435. parent);
  1436. }
  1437. if (allowed_ids) {
  1438. rspamd_symcache_set_allowed_settings_ids(cfg->cache, name,
  1439. &g_array_index(allowed_ids, guint32, 0), allowed_ids->len);
  1440. }
  1441. if (forbidden_ids) {
  1442. rspamd_symcache_set_forbidden_settings_ids(cfg->cache, name,
  1443. &g_array_index(forbidden_ids, guint32, 0), forbidden_ids->len);
  1444. }
  1445. return ret;
  1446. }
  1447. static gint
  1448. lua_config_register_post_filter(lua_State *L)
  1449. {
  1450. LUA_TRACE_POINT;
  1451. struct rspamd_config *cfg = lua_check_config(L, 1);
  1452. gint order = 0, cbref, ret;
  1453. if (cfg) {
  1454. if (lua_type(L, 3) == LUA_TNUMBER) {
  1455. order = lua_tonumber(L, 3);
  1456. }
  1457. if (lua_type(L, 2) == LUA_TFUNCTION) {
  1458. lua_pushvalue(L, 2);
  1459. /* Get a reference */
  1460. cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  1461. }
  1462. else {
  1463. return luaL_error(L, "invalid type for callback: %s",
  1464. lua_typename(L, lua_type(L, 2)));
  1465. }
  1466. msg_warn_config("register_post_filter function is deprecated, "
  1467. "use register_symbol instead");
  1468. ret = rspamd_register_symbol_fromlua(L,
  1469. cfg,
  1470. NULL,
  1471. cbref,
  1472. 1.0,
  1473. order,
  1474. SYMBOL_TYPE_POSTFILTER | SYMBOL_TYPE_CALLBACK,
  1475. -1,
  1476. NULL, NULL,
  1477. FALSE);
  1478. lua_pushboolean(L, ret);
  1479. }
  1480. else {
  1481. return luaL_error(L, "invalid arguments");
  1482. }
  1483. return 1;
  1484. }
  1485. static gint
  1486. lua_config_register_pre_filter(lua_State *L)
  1487. {
  1488. LUA_TRACE_POINT;
  1489. struct rspamd_config *cfg = lua_check_config(L, 1);
  1490. gint order = 0, cbref, ret;
  1491. if (cfg) {
  1492. if (lua_type(L, 3) == LUA_TNUMBER) {
  1493. order = lua_tonumber(L, 3);
  1494. }
  1495. if (lua_type(L, 2) == LUA_TFUNCTION) {
  1496. lua_pushvalue(L, 2);
  1497. /* Get a reference */
  1498. cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  1499. }
  1500. else {
  1501. return luaL_error(L, "invalid type for callback: %s",
  1502. lua_typename(L, lua_type(L, 2)));
  1503. }
  1504. msg_warn_config("register_pre_filter function is deprecated, "
  1505. "use register_symbol instead");
  1506. ret = rspamd_register_symbol_fromlua(L,
  1507. cfg,
  1508. NULL,
  1509. cbref,
  1510. 1.0,
  1511. order,
  1512. SYMBOL_TYPE_PREFILTER | SYMBOL_TYPE_CALLBACK,
  1513. -1,
  1514. NULL, NULL,
  1515. FALSE);
  1516. lua_pushboolean(L, ret);
  1517. }
  1518. else {
  1519. return luaL_error(L, "invalid arguments");
  1520. }
  1521. return 1;
  1522. }
  1523. static gint
  1524. lua_config_get_key(lua_State *L)
  1525. {
  1526. LUA_TRACE_POINT;
  1527. struct rspamd_config *cfg = lua_check_config(L, 1);
  1528. const gchar *name;
  1529. size_t namelen;
  1530. const ucl_object_t *val;
  1531. name = luaL_checklstring(L, 2, &namelen);
  1532. if (name && cfg) {
  1533. val = ucl_object_lookup_len(cfg->cfg_ucl_obj, name, namelen);
  1534. if (val != NULL) {
  1535. ucl_object_push_lua(L, val, val->type != UCL_ARRAY);
  1536. }
  1537. else {
  1538. lua_pushnil(L);
  1539. }
  1540. }
  1541. else {
  1542. return luaL_error(L, "invalid arguments");
  1543. }
  1544. return 1;
  1545. }
  1546. static guint
  1547. lua_parse_symbol_flags(const gchar *str)
  1548. {
  1549. guint ret = 0;
  1550. if (str) {
  1551. if (strstr(str, "fine") != NULL) {
  1552. ret |= SYMBOL_TYPE_FINE;
  1553. }
  1554. if (strstr(str, "nice") != NULL) {
  1555. ret |= SYMBOL_TYPE_FINE;
  1556. }
  1557. if (strstr(str, "empty") != NULL) {
  1558. ret |= SYMBOL_TYPE_EMPTY;
  1559. }
  1560. if (strstr(str, "skip") != NULL) {
  1561. ret |= SYMBOL_TYPE_SKIPPED;
  1562. }
  1563. if (strstr(str, "nostat") != NULL) {
  1564. ret |= SYMBOL_TYPE_NOSTAT;
  1565. }
  1566. if (strstr(str, "idempotent") != NULL) {
  1567. ret |= SYMBOL_TYPE_IDEMPOTENT;
  1568. }
  1569. if (strstr(str, "trivial") != NULL) {
  1570. ret |= SYMBOL_TYPE_TRIVIAL;
  1571. }
  1572. if (strstr(str, "ghost") != NULL) {
  1573. ret |= SYMBOL_TYPE_GHOST;
  1574. }
  1575. if (strstr(str, "mime") != NULL) {
  1576. ret |= SYMBOL_TYPE_MIME_ONLY;
  1577. }
  1578. if (strstr(str, "ignore_passthrough") != NULL) {
  1579. ret |= SYMBOL_TYPE_IGNORE_PASSTHROUGH;
  1580. }
  1581. if (strstr(str, "explicit_disable") != NULL) {
  1582. ret |= SYMBOL_TYPE_EXPLICIT_DISABLE;
  1583. }
  1584. if (strstr(str, "explicit_enable") != NULL) {
  1585. ret |= SYMBOL_TYPE_EXPLICIT_ENABLE;
  1586. }
  1587. if (strstr(str, "coro") != NULL) {
  1588. ret |= SYMBOL_TYPE_USE_CORO;
  1589. }
  1590. }
  1591. return ret;
  1592. }
  1593. static guint
  1594. lua_parse_symbol_type(const gchar *str)
  1595. {
  1596. guint ret = SYMBOL_TYPE_NORMAL;
  1597. gchar **vec;
  1598. guint i, l;
  1599. if (str) {
  1600. vec = g_strsplit_set(str, ",;", -1);
  1601. if (vec) {
  1602. l = g_strv_length(vec);
  1603. for (i = 0; i < l; i++) {
  1604. str = vec[i];
  1605. /* TODO: total shit, rework some day */
  1606. if (g_ascii_strcasecmp(str, "virtual") == 0) {
  1607. ret |= SYMBOL_TYPE_VIRTUAL;
  1608. ret &= ~SYMBOL_TYPE_NORMAL;
  1609. ret &= ~SYMBOL_TYPE_CALLBACK;
  1610. }
  1611. else if (g_ascii_strcasecmp(str, "callback") == 0) {
  1612. ret |= SYMBOL_TYPE_CALLBACK;
  1613. ret &= ~SYMBOL_TYPE_NORMAL;
  1614. ret &= ~SYMBOL_TYPE_VIRTUAL;
  1615. }
  1616. else if (g_ascii_strcasecmp(str, "normal") == 0) {
  1617. ret |= SYMBOL_TYPE_NORMAL;
  1618. ret &= ~SYMBOL_TYPE_CALLBACK;
  1619. ret &= ~SYMBOL_TYPE_VIRTUAL;
  1620. }
  1621. else if (g_ascii_strcasecmp(str, "prefilter") == 0) {
  1622. ret |= SYMBOL_TYPE_PREFILTER | SYMBOL_TYPE_GHOST;
  1623. }
  1624. else if (g_ascii_strcasecmp(str, "postfilter") == 0) {
  1625. ret |= SYMBOL_TYPE_POSTFILTER | SYMBOL_TYPE_GHOST;
  1626. }
  1627. else if (g_ascii_strcasecmp(str, "connfilter") == 0 ||
  1628. g_ascii_strcasecmp(str, "conn_filter") == 0) {
  1629. ret |= SYMBOL_TYPE_CONNFILTER | SYMBOL_TYPE_GHOST;
  1630. }
  1631. else if (g_ascii_strcasecmp(str, "idempotent") == 0) {
  1632. ret |= SYMBOL_TYPE_GHOST |
  1633. SYMBOL_TYPE_IDEMPOTENT | SYMBOL_TYPE_CALLBACK;
  1634. }
  1635. else {
  1636. gint fl = 0;
  1637. fl = lua_parse_symbol_flags(str);
  1638. if (fl == 0) {
  1639. msg_warn("bad type: %s", str);
  1640. }
  1641. else {
  1642. ret |= fl;
  1643. }
  1644. }
  1645. }
  1646. g_strfreev(vec);
  1647. }
  1648. }
  1649. return ret;
  1650. }
  1651. enum lua_push_symbol_flags_opts {
  1652. LUA_SYMOPT_FLAG_CREATE_ARRAY = 1u << 0u,
  1653. LUA_SYMOPT_FLAG_CREATE_MAP = 1u << 1u,
  1654. LUA_SYMOPT_FLAG_USE_MAP = 1u << 2u,
  1655. LUA_SYMOPT_FLAG_USE_ARRAY = 1u << 3u,
  1656. };
  1657. #define LUA_SYMOPT_IS_ARRAY(f) ((f) & (LUA_SYMOPT_FLAG_CREATE_ARRAY | LUA_SYMOPT_FLAG_USE_ARRAY))
  1658. #define LUA_SYMOPT_IS_CREATE(f) ((f) & (LUA_SYMOPT_FLAG_CREATE_ARRAY | LUA_SYMOPT_FLAG_CREATE_MAP))
  1659. #define LUA_OPTION_PUSH(nm) \
  1660. do { \
  1661. if (LUA_SYMOPT_IS_ARRAY(fl)) { \
  1662. lua_pushstring(L, #nm); \
  1663. lua_rawseti(L, -2, i++); \
  1664. } \
  1665. else { \
  1666. lua_pushboolean(L, true); \
  1667. lua_setfield(L, -2, #nm); \
  1668. } \
  1669. } while (0)
  1670. static void
  1671. lua_push_symbol_flags(lua_State *L, guint flags, enum lua_push_symbol_flags_opts fl)
  1672. {
  1673. guint i = 1;
  1674. if (LUA_SYMOPT_IS_CREATE(fl)) {
  1675. lua_newtable(L);
  1676. }
  1677. if (flags & SYMBOL_TYPE_FINE) {
  1678. LUA_OPTION_PUSH(fine);
  1679. }
  1680. if (flags & SYMBOL_TYPE_EMPTY) {
  1681. LUA_OPTION_PUSH(empty);
  1682. }
  1683. if (flags & SYMBOL_TYPE_EXPLICIT_DISABLE) {
  1684. LUA_OPTION_PUSH(explicit_disable);
  1685. }
  1686. if (flags & SYMBOL_TYPE_EXPLICIT_ENABLE) {
  1687. LUA_OPTION_PUSH(explicit_enable);
  1688. }
  1689. if (flags & SYMBOL_TYPE_IGNORE_PASSTHROUGH) {
  1690. LUA_OPTION_PUSH(ignore_passthrough);
  1691. }
  1692. if (flags & SYMBOL_TYPE_NOSTAT) {
  1693. LUA_OPTION_PUSH(nostat);
  1694. }
  1695. if (flags & SYMBOL_TYPE_IDEMPOTENT) {
  1696. LUA_OPTION_PUSH(idempotent);
  1697. }
  1698. if (flags & SYMBOL_TYPE_MIME_ONLY) {
  1699. LUA_OPTION_PUSH(mime);
  1700. }
  1701. if (flags & SYMBOL_TYPE_TRIVIAL) {
  1702. LUA_OPTION_PUSH(trivial);
  1703. }
  1704. if (flags & SYMBOL_TYPE_SKIPPED) {
  1705. LUA_OPTION_PUSH(skip);
  1706. }
  1707. if (flags & SYMBOL_TYPE_COMPOSITE) {
  1708. LUA_OPTION_PUSH(composite);
  1709. }
  1710. }
  1711. static gint
  1712. lua_config_get_symbol_flags(lua_State *L)
  1713. {
  1714. struct rspamd_config *cfg = lua_check_config(L, 1);
  1715. const gchar *name = luaL_checkstring(L, 2);
  1716. guint flags;
  1717. if (cfg && name) {
  1718. flags = rspamd_symcache_get_symbol_flags(cfg->cache,
  1719. name);
  1720. if (flags != 0) {
  1721. lua_push_symbol_flags(L, flags, LUA_SYMOPT_FLAG_CREATE_ARRAY);
  1722. }
  1723. else {
  1724. lua_pushnil(L);
  1725. }
  1726. }
  1727. else {
  1728. return luaL_error(L, "invalid arguments");
  1729. }
  1730. return 1;
  1731. }
  1732. static gint
  1733. lua_config_register_symbol(lua_State *L)
  1734. {
  1735. LUA_TRACE_POINT;
  1736. struct rspamd_config *cfg = lua_check_config(L, 1);
  1737. const gchar *name = NULL, *type_str = NULL,
  1738. *description = NULL, *group = NULL;
  1739. double weight = 0, score = NAN, parent_float = NAN;
  1740. gboolean one_shot = FALSE;
  1741. gint ret = -1, cbref = -1;
  1742. guint type = 0, flags = 0;
  1743. gint64 parent = 0, priority = 0, nshots = 0;
  1744. GArray *allowed_ids = NULL, *forbidden_ids = NULL;
  1745. GError *err = NULL;
  1746. int prev_top = lua_gettop(L);
  1747. if (cfg) {
  1748. if (!rspamd_lua_parse_table_arguments(L, 2, &err,
  1749. RSPAMD_LUA_PARSE_ARGUMENTS_DEFAULT,
  1750. "name=S;weight=N;callback=F;type=S;priority=I;parent=D;"
  1751. "score=D;description=S;group=S;one_shot=B;nshots=I",
  1752. &name, &weight, &cbref, &type_str,
  1753. &priority, &parent_float,
  1754. &score, &description, &group, &one_shot, &nshots)) {
  1755. msg_err_config("bad arguments: %e", err);
  1756. g_error_free(err);
  1757. lua_settop(L, prev_top);
  1758. return luaL_error(L, "invalid arguments");
  1759. }
  1760. /* Deal with flags and ids */
  1761. lua_pushstring(L, "flags");
  1762. lua_gettable(L, 2);
  1763. if (lua_type(L, -1) == LUA_TSTRING) {
  1764. flags = lua_parse_symbol_flags(lua_tostring(L, -1));
  1765. }
  1766. else if (lua_type(L, -1) == LUA_TTABLE) {
  1767. for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
  1768. flags |= lua_parse_symbol_flags(lua_tostring(L, -1));
  1769. }
  1770. }
  1771. lua_pop(L, 1); /* Clean flags */
  1772. lua_pushstring(L, "allowed_ids");
  1773. lua_gettable(L, 2);
  1774. if (lua_type(L, -1) == LUA_TSTRING) {
  1775. allowed_ids = rspamd_process_id_list(lua_tostring(L, -1));
  1776. }
  1777. else if (lua_type(L, -1) == LUA_TTABLE) {
  1778. allowed_ids = g_array_sized_new(FALSE, FALSE, sizeof(guint32),
  1779. rspamd_lua_table_size(L, -1));
  1780. for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
  1781. guint32 v = lua_tointeger(L, -1);
  1782. g_array_append_val(allowed_ids, v);
  1783. }
  1784. }
  1785. lua_pop(L, 1);
  1786. lua_pushstring(L, "forbidden_ids");
  1787. lua_gettable(L, 2);
  1788. if (lua_type(L, -1) == LUA_TSTRING) {
  1789. forbidden_ids = rspamd_process_id_list(lua_tostring(L, -1));
  1790. }
  1791. else if (lua_type(L, -1) == LUA_TTABLE) {
  1792. forbidden_ids = g_array_sized_new(FALSE, FALSE, sizeof(guint32),
  1793. rspamd_lua_table_size(L, -1));
  1794. for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
  1795. guint32 v = lua_tointeger(L, -1);
  1796. g_array_append_val(forbidden_ids, v);
  1797. }
  1798. }
  1799. lua_pop(L, 1);
  1800. if (nshots == 0) {
  1801. nshots = cfg->default_max_shots;
  1802. }
  1803. type = lua_parse_symbol_type(type_str);
  1804. if (!name && !(type & SYMBOL_TYPE_CALLBACK)) {
  1805. lua_settop(L, prev_top);
  1806. return luaL_error(L, "no symbol name but type is not callback");
  1807. }
  1808. else if (!(type & SYMBOL_TYPE_VIRTUAL) && cbref == -1) {
  1809. lua_settop(L, prev_top);
  1810. return luaL_error(L, "no callback for symbol %s", name);
  1811. }
  1812. if (isnan(parent_float)) {
  1813. parent = -1;
  1814. }
  1815. else {
  1816. parent = parent_float;
  1817. }
  1818. ret = rspamd_register_symbol_fromlua(L,
  1819. cfg,
  1820. name,
  1821. cbref,
  1822. weight == 0 ? 1.0 : weight,
  1823. priority,
  1824. type | flags,
  1825. parent,
  1826. allowed_ids, forbidden_ids,
  1827. FALSE);
  1828. if (allowed_ids) {
  1829. g_array_free(allowed_ids, TRUE);
  1830. }
  1831. if (forbidden_ids) {
  1832. g_array_free(forbidden_ids, TRUE);
  1833. }
  1834. if (ret != -1) {
  1835. if (!isnan(score) || group) {
  1836. if (one_shot) {
  1837. nshots = 1;
  1838. }
  1839. rspamd_config_add_symbol(cfg, name,
  1840. score, description, group, flags,
  1841. 0, nshots);
  1842. lua_pushstring(L, "groups");
  1843. lua_gettable(L, 2);
  1844. if (lua_istable(L, -1)) {
  1845. for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
  1846. if (lua_isstring(L, -1)) {
  1847. rspamd_config_add_symbol_group(cfg, name,
  1848. lua_tostring(L, -1));
  1849. }
  1850. else {
  1851. lua_settop(L, prev_top);
  1852. return luaL_error(L, "invalid groups element");
  1853. }
  1854. }
  1855. }
  1856. lua_pop(L, 1);
  1857. }
  1858. lua_pushstring(L, "augmentations");
  1859. lua_gettable(L, 2);
  1860. if (lua_type(L, -1) == LUA_TTABLE) {
  1861. int tbl_idx = lua_gettop(L);
  1862. for (lua_pushnil(L); lua_next(L, tbl_idx); lua_pop(L, 1)) {
  1863. size_t len;
  1864. const char *augmentation = lua_tolstring(L, -1, &len), *eqsign_pos;
  1865. /* Find `=` symbol and use it as a separator */
  1866. eqsign_pos = memchr(augmentation, '=', len);
  1867. if (eqsign_pos != NULL && eqsign_pos + 1 < augmentation + len) {
  1868. rspamd_ftok_t tok;
  1869. tok.begin = augmentation;
  1870. tok.len = eqsign_pos - augmentation;
  1871. char *augentation_name = rspamd_ftokdup(&tok);
  1872. tok.begin = eqsign_pos + 1;
  1873. tok.len = (augmentation + len) - tok.begin;
  1874. char *augmentation_value = rspamd_ftokdup(&tok);
  1875. if (!rspamd_symcache_add_symbol_augmentation(cfg->cache, ret,
  1876. augentation_name, augmentation_value)) {
  1877. lua_settop(L, prev_top);
  1878. g_free(augmentation_value);
  1879. g_free(augentation_name);
  1880. return luaL_error(L, "unknown or invalid augmentation %s in symbol %s",
  1881. augmentation, name);
  1882. }
  1883. g_free(augmentation_value);
  1884. g_free(augentation_name);
  1885. }
  1886. else {
  1887. /* Just a value */
  1888. if (!rspamd_symcache_add_symbol_augmentation(cfg->cache, ret,
  1889. augmentation, NULL)) {
  1890. lua_settop(L, prev_top);
  1891. return luaL_error(L, "unknown augmentation %s in symbol %s",
  1892. augmentation, name);
  1893. }
  1894. }
  1895. }
  1896. }
  1897. }
  1898. }
  1899. else {
  1900. lua_settop(L, prev_top);
  1901. return luaL_error(L, "invalid arguments");
  1902. }
  1903. lua_settop(L, prev_top);
  1904. lua_pushinteger(L, ret);
  1905. return 1;
  1906. }
  1907. static gint
  1908. lua_config_register_symbols(lua_State *L)
  1909. {
  1910. LUA_TRACE_POINT;
  1911. struct rspamd_config *cfg = lua_check_config(L, 1);
  1912. gint i, top, idx, ret = -1;
  1913. const gchar *sym;
  1914. gdouble weight = 1.0;
  1915. if (lua_gettop(L) < 3) {
  1916. if (cfg) {
  1917. msg_err_config("not enough arguments to register a function");
  1918. }
  1919. lua_error(L);
  1920. return 0;
  1921. }
  1922. if (cfg) {
  1923. if (lua_type(L, 2) == LUA_TSTRING) {
  1924. lua_getglobal(L, luaL_checkstring(L, 2));
  1925. }
  1926. else {
  1927. lua_pushvalue(L, 2);
  1928. }
  1929. idx = luaL_ref(L, LUA_REGISTRYINDEX);
  1930. if (lua_type(L, 3) == LUA_TNUMBER) {
  1931. weight = lua_tonumber(L, 3);
  1932. top = 4;
  1933. }
  1934. else {
  1935. top = 3;
  1936. }
  1937. sym = luaL_checkstring(L, top++);
  1938. ret = rspamd_register_symbol_fromlua(L,
  1939. cfg,
  1940. sym,
  1941. idx,
  1942. weight,
  1943. 0,
  1944. SYMBOL_TYPE_CALLBACK,
  1945. -1,
  1946. NULL, NULL,
  1947. FALSE);
  1948. for (i = top; i <= lua_gettop(L); i++) {
  1949. if (lua_type(L, i) == LUA_TTABLE) {
  1950. lua_pushvalue(L, i);
  1951. lua_pushnil(L);
  1952. while (lua_next(L, -2)) {
  1953. lua_pushvalue(L, -2);
  1954. sym = luaL_checkstring(L, -2);
  1955. rspamd_symcache_add_symbol(cfg->cache, sym,
  1956. 0, NULL, NULL,
  1957. SYMBOL_TYPE_VIRTUAL, ret);
  1958. lua_pop(L, 2);
  1959. }
  1960. lua_pop(L, 1);
  1961. }
  1962. else if (lua_type(L, i) == LUA_TSTRING) {
  1963. sym = luaL_checkstring(L, i);
  1964. rspamd_symcache_add_symbol(cfg->cache, sym,
  1965. 0, NULL, NULL,
  1966. SYMBOL_TYPE_VIRTUAL, ret);
  1967. }
  1968. }
  1969. }
  1970. lua_pushinteger(L, ret);
  1971. return 1;
  1972. }
  1973. static gint
  1974. lua_config_register_virtual_symbol(lua_State *L)
  1975. {
  1976. LUA_TRACE_POINT;
  1977. struct rspamd_config *cfg = lua_check_config(L, 1);
  1978. const gchar *name;
  1979. double weight;
  1980. gint ret = -1, parent = -1;
  1981. if (cfg) {
  1982. name = luaL_checkstring(L, 2);
  1983. weight = luaL_checknumber(L, 3);
  1984. if (lua_gettop(L) > 3) {
  1985. parent = lua_tonumber(L, 4);
  1986. }
  1987. if (name) {
  1988. ret = rspamd_symcache_add_symbol(cfg->cache, name,
  1989. weight > 0 ? 0 : -1, NULL, NULL,
  1990. SYMBOL_TYPE_VIRTUAL, parent);
  1991. }
  1992. }
  1993. lua_pushinteger(L, ret);
  1994. return 1;
  1995. }
  1996. static gint
  1997. lua_config_register_callback_symbol(lua_State *L)
  1998. {
  1999. LUA_TRACE_POINT;
  2000. struct rspamd_config *cfg = lua_check_config(L, 1);
  2001. const gchar *name = NULL;
  2002. double weight;
  2003. gint ret = -1, top = 2;
  2004. if (cfg) {
  2005. if (lua_type(L, 2) == LUA_TSTRING) {
  2006. /* Legacy syntax */
  2007. name = luaL_checkstring(L, 2);
  2008. top++;
  2009. }
  2010. weight = luaL_checknumber(L, top);
  2011. if (lua_type(L, top + 1) == LUA_TSTRING) {
  2012. lua_getglobal(L, luaL_checkstring(L, top + 1));
  2013. }
  2014. else {
  2015. lua_pushvalue(L, top + 1);
  2016. }
  2017. ret = rspamd_register_symbol_fromlua(L,
  2018. cfg,
  2019. name,
  2020. luaL_ref(L, LUA_REGISTRYINDEX),
  2021. weight,
  2022. 0,
  2023. SYMBOL_TYPE_CALLBACK,
  2024. -1,
  2025. NULL, NULL,
  2026. FALSE);
  2027. }
  2028. lua_pushinteger(L, ret);
  2029. return 1;
  2030. }
  2031. static gint
  2032. lua_config_register_callback_symbol_priority(lua_State *L)
  2033. {
  2034. LUA_TRACE_POINT;
  2035. struct rspamd_config *cfg = lua_check_config(L, 1);
  2036. const gchar *name = NULL;
  2037. double weight;
  2038. gint priority, ret = -1, top = 2;
  2039. if (cfg) {
  2040. if (lua_type(L, 2) == LUA_TSTRING) {
  2041. /* Legacy syntax */
  2042. name = luaL_checkstring(L, 2);
  2043. top++;
  2044. }
  2045. weight = luaL_checknumber(L, top);
  2046. priority = luaL_checknumber(L, top + 1);
  2047. if (lua_type(L, top + 2) == LUA_TSTRING) {
  2048. lua_getglobal(L, luaL_checkstring(L, top + 2));
  2049. }
  2050. else {
  2051. lua_pushvalue(L, top + 2);
  2052. }
  2053. ret = rspamd_register_symbol_fromlua(L,
  2054. cfg,
  2055. name,
  2056. luaL_ref(L, LUA_REGISTRYINDEX),
  2057. weight,
  2058. priority,
  2059. SYMBOL_TYPE_CALLBACK,
  2060. -1,
  2061. NULL, NULL,
  2062. FALSE);
  2063. }
  2064. lua_pushinteger(L, ret);
  2065. return 1;
  2066. }
  2067. static gint
  2068. lua_config_register_dependency(lua_State *L)
  2069. {
  2070. LUA_TRACE_POINT;
  2071. struct rspamd_config *cfg = lua_check_config(L, 1);
  2072. const gchar *parent = NULL, *child = NULL;
  2073. gint child_id;
  2074. if (cfg == NULL) {
  2075. lua_error(L);
  2076. return 0;
  2077. }
  2078. if (lua_type(L, 2) == LUA_TNUMBER) {
  2079. child_id = luaL_checknumber(L, 2);
  2080. parent = luaL_checkstring(L, 3);
  2081. return luaL_error(L, "calling for obsolete method to register deps for symbol %d->%s",
  2082. child_id, parent);
  2083. }
  2084. else {
  2085. child = luaL_checkstring(L, 2);
  2086. parent = luaL_checkstring(L, 3);
  2087. if (child != NULL && parent != NULL) {
  2088. rspamd_symcache_add_delayed_dependency(cfg->cache, child,
  2089. parent);
  2090. }
  2091. }
  2092. return 0;
  2093. }
  2094. static gint
  2095. lua_config_set_metric_symbol(lua_State *L)
  2096. {
  2097. LUA_TRACE_POINT;
  2098. struct rspamd_config *cfg = lua_check_config(L, 1);
  2099. const gchar *description = NULL,
  2100. *group = NULL, *name = NULL, *flags_str = NULL;
  2101. double score;
  2102. gboolean one_shot = FALSE, one_param = FALSE;
  2103. GError *err = NULL;
  2104. gdouble priority = 0.0;
  2105. guint flags = 0;
  2106. gint64 nshots = 0;
  2107. if (cfg) {
  2108. if (lua_type(L, 2) == LUA_TTABLE) {
  2109. if (!rspamd_lua_parse_table_arguments(L, 2, &err,
  2110. RSPAMD_LUA_PARSE_ARGUMENTS_DEFAULT,
  2111. "*name=S;score=N;description=S;"
  2112. "group=S;one_shot=B;one_param=B;priority=N;flags=S;"
  2113. "nshots=I",
  2114. &name, &score, &description,
  2115. &group, &one_shot, &one_param,
  2116. &priority, &flags_str, &nshots)) {
  2117. msg_err_config("bad arguments: %e", err);
  2118. g_error_free(err);
  2119. return 0;
  2120. }
  2121. }
  2122. else {
  2123. name = luaL_checkstring(L, 2);
  2124. score = luaL_checknumber(L, 3);
  2125. if (lua_gettop(L) > 3 && lua_type(L, 4) == LUA_TSTRING) {
  2126. description = luaL_checkstring(L, 4);
  2127. }
  2128. if (lua_gettop(L) > 4 && lua_type(L, 5) == LUA_TSTRING) {
  2129. /* XXX: metrics */
  2130. }
  2131. if (lua_gettop(L) > 5 && lua_type(L, 6) == LUA_TSTRING) {
  2132. group = luaL_checkstring(L, 6);
  2133. }
  2134. if (lua_gettop(L) > 6 && lua_type(L, 7) == LUA_TBOOLEAN) {
  2135. one_shot = lua_toboolean(L, 7);
  2136. }
  2137. }
  2138. if (nshots == 0) {
  2139. nshots = cfg->default_max_shots;
  2140. }
  2141. if (one_shot) {
  2142. nshots = 1;
  2143. }
  2144. if (one_param) {
  2145. flags |= RSPAMD_SYMBOL_FLAG_ONEPARAM;
  2146. }
  2147. if (flags_str) {
  2148. if (strstr(flags_str, "one_shot") != NULL) {
  2149. nshots = 1;
  2150. }
  2151. if (strstr(flags_str, "ignore") != NULL) {
  2152. flags |= RSPAMD_SYMBOL_FLAG_IGNORE_METRIC;
  2153. }
  2154. if (strstr(flags_str, "one_param") != NULL) {
  2155. flags |= RSPAMD_SYMBOL_FLAG_ONEPARAM;
  2156. }
  2157. }
  2158. rspamd_config_add_symbol(cfg, name,
  2159. score, description, group, flags, (guint) priority, nshots);
  2160. if (lua_type(L, 2) == LUA_TTABLE) {
  2161. lua_pushstring(L, "groups");
  2162. lua_gettable(L, 2);
  2163. if (lua_istable(L, -1)) {
  2164. for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
  2165. if (lua_isstring(L, -1)) {
  2166. rspamd_config_add_symbol_group(cfg, name,
  2167. lua_tostring(L, -1));
  2168. }
  2169. else {
  2170. return luaL_error(L, "invalid groups element");
  2171. }
  2172. }
  2173. }
  2174. lua_pop(L, 1);
  2175. }
  2176. }
  2177. else {
  2178. return luaL_error(L, "invalid arguments, rspamd_config expected");
  2179. }
  2180. return 0;
  2181. }
  2182. static gint
  2183. lua_config_set_metric_action(lua_State *L)
  2184. {
  2185. LUA_TRACE_POINT;
  2186. struct rspamd_config *cfg = lua_check_config(L, 1);
  2187. const gchar *name = NULL;
  2188. double threshold = NAN;
  2189. GError *err = NULL;
  2190. gdouble priority = 0.0;
  2191. ucl_object_t *obj_tbl = NULL;
  2192. if (cfg) {
  2193. if (lua_type(L, 2) == LUA_TTABLE) {
  2194. if (!rspamd_lua_parse_table_arguments(L, 2, &err,
  2195. RSPAMD_LUA_PARSE_ARGUMENTS_DEFAULT,
  2196. "*action=S;score=N;"
  2197. "priority=N",
  2198. &name, &threshold,
  2199. &priority)) {
  2200. msg_err_config("bad arguments: %e", err);
  2201. g_error_free(err);
  2202. return 0;
  2203. }
  2204. }
  2205. else if (lua_type(L, 2) == LUA_TSTRING && lua_type(L, 3) == LUA_TTABLE) {
  2206. name = lua_tostring(L, 2);
  2207. obj_tbl = ucl_object_lua_import(L, 3);
  2208. if (obj_tbl) {
  2209. if (name) {
  2210. rspamd_config_set_action_score(cfg, name, obj_tbl);
  2211. ucl_object_unref(obj_tbl);
  2212. }
  2213. else {
  2214. ucl_object_unref(obj_tbl);
  2215. return luaL_error(L, "invalid first argument, action name expected");
  2216. }
  2217. }
  2218. else {
  2219. return luaL_error(L, "invalid second argument, table expected");
  2220. }
  2221. }
  2222. else {
  2223. return luaL_error(L, "invalid arguments, table expected");
  2224. }
  2225. if (name != NULL && !isnan(threshold) && threshold != 0) {
  2226. obj_tbl = ucl_object_typed_new(UCL_OBJECT);
  2227. ucl_object_insert_key(obj_tbl, ucl_object_fromdouble(threshold),
  2228. "score", 0, false);
  2229. ucl_object_insert_key(obj_tbl, ucl_object_fromdouble(priority),
  2230. "priority", 0, false);
  2231. rspamd_config_set_action_score(cfg, name, obj_tbl);
  2232. ucl_object_unref(obj_tbl);
  2233. }
  2234. }
  2235. else {
  2236. return luaL_error(L, "invalid arguments, rspamd_config expected");
  2237. }
  2238. return 0;
  2239. }
  2240. static gint
  2241. lua_config_get_metric_action(lua_State *L)
  2242. {
  2243. LUA_TRACE_POINT;
  2244. struct rspamd_config *cfg = lua_check_config(L, 1);
  2245. const gchar *act_name = luaL_checkstring(L, 2);
  2246. struct rspamd_action *act;
  2247. if (cfg && act_name) {
  2248. act = rspamd_config_get_action(cfg, act_name);
  2249. if (act) {
  2250. if (!isnan(act->threshold)) {
  2251. lua_pushnumber(L, act->threshold);
  2252. }
  2253. else {
  2254. lua_pushnil(L);
  2255. }
  2256. }
  2257. else {
  2258. lua_pushnil(L);
  2259. }
  2260. }
  2261. else {
  2262. return luaL_error(L, "invalid arguments, rspamd_config expected");
  2263. }
  2264. return 1;
  2265. }
  2266. static void
  2267. lua_config_actions_cb(struct rspamd_action *act, void *cbd)
  2268. {
  2269. lua_State *L = (lua_State *) cbd;
  2270. if (!isnan(act->threshold)) {
  2271. lua_pushstring(L, act->name);
  2272. lua_pushnumber(L, act->threshold);
  2273. lua_settable(L, -3);
  2274. }
  2275. }
  2276. static gint
  2277. lua_config_get_all_actions(lua_State *L)
  2278. {
  2279. LUA_TRACE_POINT;
  2280. struct rspamd_config *cfg = lua_check_config(L, 1);
  2281. if (cfg) {
  2282. lua_createtable(L, 0, rspamd_config_actions_size(cfg));
  2283. rspamd_config_actions_foreach(cfg, lua_config_actions_cb, L);
  2284. }
  2285. else {
  2286. return luaL_error(L, "invalid arguments, rspamd_config expected");
  2287. }
  2288. return 1;
  2289. }
  2290. static gint
  2291. lua_config_add_composite(lua_State *L)
  2292. {
  2293. LUA_TRACE_POINT;
  2294. struct rspamd_config *cfg = lua_check_config(L, 1);
  2295. gchar *name;
  2296. const gchar *expr_str;
  2297. struct rspamd_composite *composite;
  2298. gboolean ret = FALSE;
  2299. if (cfg) {
  2300. name = rspamd_mempool_strdup(cfg->cfg_pool, luaL_checkstring(L, 2));
  2301. expr_str = luaL_checkstring(L, 3);
  2302. if (name && expr_str) {
  2303. composite = rspamd_composites_manager_add_from_string(cfg->composites_manager,
  2304. name, expr_str);
  2305. if (composite) {
  2306. rspamd_symcache_add_symbol(cfg->cache, name,
  2307. 0, NULL, composite, SYMBOL_TYPE_COMPOSITE, -1);
  2308. ret = TRUE;
  2309. }
  2310. }
  2311. }
  2312. lua_pushboolean(L, ret);
  2313. return 1;
  2314. }
  2315. static gint
  2316. lua_config_newindex(lua_State *L)
  2317. {
  2318. LUA_TRACE_POINT;
  2319. struct rspamd_config *cfg = lua_check_config(L, 1);
  2320. const gchar *name;
  2321. GArray *allowed_ids = NULL, *forbidden_ids = NULL;
  2322. gint id, nshots;
  2323. guint flags = 0;
  2324. gboolean optional = FALSE;
  2325. name = luaL_checkstring(L, 2);
  2326. if (cfg != NULL && name != NULL && lua_gettop(L) == 3) {
  2327. if (lua_type(L, 3) == LUA_TFUNCTION) {
  2328. /* Normal symbol from just a function */
  2329. lua_pushvalue(L, 3);
  2330. rspamd_register_symbol_fromlua(L,
  2331. cfg,
  2332. name,
  2333. luaL_ref(L, LUA_REGISTRYINDEX),
  2334. 1.0,
  2335. 0,
  2336. SYMBOL_TYPE_NORMAL,
  2337. -1,
  2338. NULL, NULL,
  2339. FALSE);
  2340. }
  2341. else if (lua_type(L, 3) == LUA_TTABLE) {
  2342. guint type = SYMBOL_TYPE_NORMAL, priority = 0;
  2343. gint idx;
  2344. gdouble weight = 1.0, score = NAN;
  2345. const char *type_str, *group = NULL, *description = NULL;
  2346. /*
  2347. * Table can have the following attributes:
  2348. * "callback" - should be a callback function
  2349. * "weight" - optional weight
  2350. * "priority" - optional priority
  2351. * "type" - optional type (normal, virtual, callback)
  2352. * "flags" - optional flags
  2353. * -- Metric options
  2354. * "score" - optional default score (overridden by metric)
  2355. * "group" - optional default group
  2356. * "one_shot" - optional one shot mode
  2357. * "description" - optional description
  2358. */
  2359. lua_pushvalue(L, 3);
  2360. lua_pushstring(L, "callback");
  2361. lua_gettable(L, -2);
  2362. if (lua_type(L, -1) != LUA_TFUNCTION) {
  2363. lua_pop(L, 2);
  2364. msg_info_config("cannot find callback definition for %s",
  2365. name);
  2366. return 0;
  2367. }
  2368. idx = luaL_ref(L, LUA_REGISTRYINDEX);
  2369. /* Optional fields */
  2370. lua_pushstring(L, "weight");
  2371. lua_gettable(L, -2);
  2372. if (lua_type(L, -1) == LUA_TNUMBER) {
  2373. weight = lua_tonumber(L, -1);
  2374. }
  2375. lua_pop(L, 1);
  2376. lua_pushstring(L, "priority");
  2377. lua_gettable(L, -2);
  2378. if (lua_type(L, -1) == LUA_TNUMBER) {
  2379. priority = lua_tointeger(L, -1);
  2380. }
  2381. lua_pop(L, 1);
  2382. lua_pushstring(L, "optional");
  2383. lua_gettable(L, -2);
  2384. if (lua_type(L, -1) == LUA_TBOOLEAN) {
  2385. optional = lua_toboolean(L, -1);
  2386. }
  2387. lua_pop(L, 1);
  2388. lua_pushstring(L, "type");
  2389. lua_gettable(L, -2);
  2390. if (lua_type(L, -1) == LUA_TSTRING) {
  2391. type_str = lua_tostring(L, -1);
  2392. type = lua_parse_symbol_type(type_str);
  2393. }
  2394. lua_pop(L, 1);
  2395. /* Deal with flags and ids */
  2396. lua_pushstring(L, "flags");
  2397. lua_gettable(L, -2);
  2398. if (lua_type(L, -1) == LUA_TSTRING) {
  2399. flags = lua_parse_symbol_flags(lua_tostring(L, -1));
  2400. }
  2401. else if (lua_type(L, -1) == LUA_TTABLE) {
  2402. for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
  2403. flags |= lua_parse_symbol_flags(lua_tostring(L, -1));
  2404. }
  2405. }
  2406. lua_pop(L, 1); /* Clean flags */
  2407. lua_pushstring(L, "allowed_ids");
  2408. lua_gettable(L, -2);
  2409. if (lua_type(L, -1) == LUA_TSTRING) {
  2410. allowed_ids = rspamd_process_id_list(lua_tostring(L, -1));
  2411. }
  2412. else if (lua_type(L, -1) == LUA_TTABLE) {
  2413. allowed_ids = g_array_sized_new(FALSE, FALSE, sizeof(guint32),
  2414. rspamd_lua_table_size(L, -1));
  2415. for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
  2416. guint32 v = lua_tointeger(L, -1);
  2417. g_array_append_val(allowed_ids, v);
  2418. }
  2419. }
  2420. lua_pop(L, 1);
  2421. lua_pushstring(L, "forbidden_ids");
  2422. lua_gettable(L, -2);
  2423. if (lua_type(L, -1) == LUA_TSTRING) {
  2424. forbidden_ids = rspamd_process_id_list(lua_tostring(L, -1));
  2425. }
  2426. else if (lua_type(L, -1) == LUA_TTABLE) {
  2427. forbidden_ids = g_array_sized_new(FALSE, FALSE, sizeof(guint32),
  2428. rspamd_lua_table_size(L, -1));
  2429. for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
  2430. guint32 v = lua_tointeger(L, -1);
  2431. g_array_append_val(forbidden_ids, v);
  2432. }
  2433. }
  2434. lua_pop(L, 1);
  2435. id = rspamd_register_symbol_fromlua(L,
  2436. cfg,
  2437. name,
  2438. idx,
  2439. weight,
  2440. priority,
  2441. type | flags,
  2442. -1,
  2443. allowed_ids, forbidden_ids,
  2444. optional);
  2445. if (allowed_ids) {
  2446. g_array_free(allowed_ids, TRUE);
  2447. }
  2448. if (forbidden_ids) {
  2449. g_array_free(forbidden_ids, TRUE);
  2450. }
  2451. if (id != -1) {
  2452. /* Check for condition */
  2453. lua_pushstring(L, "condition");
  2454. lua_gettable(L, -2);
  2455. if (lua_type(L, -1) == LUA_TFUNCTION) {
  2456. gint condref;
  2457. /* Here we pop function from the stack, so no lua_pop is required */
  2458. condref = luaL_ref(L, LUA_REGISTRYINDEX);
  2459. g_assert(name != NULL);
  2460. rspamd_symcache_add_condition_delayed(cfg->cache,
  2461. name, L, condref);
  2462. }
  2463. else {
  2464. lua_pop(L, 1);
  2465. }
  2466. /* Check for augmentations */
  2467. lua_pushstring(L, "augmentations");
  2468. lua_gettable(L, -2);
  2469. if (lua_type(L, -1) == LUA_TTABLE) {
  2470. int tbl_idx = lua_gettop(L);
  2471. for (lua_pushnil(L); lua_next(L, tbl_idx); lua_pop(L, 1)) {
  2472. rspamd_symcache_add_symbol_augmentation(cfg->cache, id,
  2473. lua_tostring(L, -1), NULL);
  2474. }
  2475. }
  2476. lua_pop(L, 1);
  2477. }
  2478. /*
  2479. * Now check if a symbol has not been registered in any metric and
  2480. * insert default value if applicable
  2481. */
  2482. struct rspamd_symbol *sym = g_hash_table_lookup(cfg->symbols, name);
  2483. if (sym == NULL || (sym->flags & RSPAMD_SYMBOL_FLAG_UNSCORED)) {
  2484. nshots = cfg->default_max_shots;
  2485. lua_pushstring(L, "score");
  2486. lua_gettable(L, -2);
  2487. if (lua_type(L, -1) == LUA_TNUMBER) {
  2488. score = lua_tonumber(L, -1);
  2489. if (sym) {
  2490. /* Reset unscored flag */
  2491. sym->flags &= ~RSPAMD_SYMBOL_FLAG_UNSCORED;
  2492. }
  2493. }
  2494. lua_pop(L, 1);
  2495. lua_pushstring(L, "group");
  2496. lua_gettable(L, -2);
  2497. if (lua_type(L, -1) == LUA_TSTRING) {
  2498. group = lua_tostring(L, -1);
  2499. }
  2500. lua_pop(L, 1);
  2501. if (!isnan(score) || group != NULL) {
  2502. lua_pushstring(L, "description");
  2503. lua_gettable(L, -2);
  2504. if (lua_type(L, -1) == LUA_TSTRING) {
  2505. description = lua_tostring(L, -1);
  2506. }
  2507. lua_pop(L, 1);
  2508. lua_pushstring(L, "one_shot");
  2509. lua_gettable(L, -2);
  2510. if (lua_type(L, -1) == LUA_TBOOLEAN) {
  2511. if (lua_toboolean(L, -1)) {
  2512. nshots = 1;
  2513. }
  2514. }
  2515. lua_pop(L, 1);
  2516. lua_pushstring(L, "one_param");
  2517. lua_gettable(L, -2);
  2518. if (lua_type(L, -1) == LUA_TBOOLEAN) {
  2519. if (lua_toboolean(L, -1)) {
  2520. flags |= RSPAMD_SYMBOL_FLAG_ONEPARAM;
  2521. }
  2522. }
  2523. lua_pop(L, 1);
  2524. /*
  2525. * Do not override the existing symbols (using zero priority),
  2526. * since we are defining default values here
  2527. */
  2528. if (!isnan(score)) {
  2529. rspamd_config_add_symbol(cfg, name, score,
  2530. description, group, flags, 0, nshots);
  2531. }
  2532. else if (group) {
  2533. /* Add with zero score */
  2534. rspamd_config_add_symbol(cfg, name, NAN,
  2535. description, group, flags, 0, nshots);
  2536. }
  2537. lua_pushstring(L, "groups");
  2538. lua_gettable(L, -2);
  2539. if (lua_istable(L, -1)) {
  2540. for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
  2541. if (lua_isstring(L, -1)) {
  2542. rspamd_config_add_symbol_group(cfg, name,
  2543. lua_tostring(L, -1));
  2544. }
  2545. else {
  2546. return luaL_error(L, "invalid groups element");
  2547. }
  2548. }
  2549. }
  2550. lua_pop(L, 1);
  2551. }
  2552. }
  2553. else {
  2554. /* Fill in missing fields from lua definition if they are not set */
  2555. if (sym->description == NULL) {
  2556. lua_pushstring(L, "description");
  2557. lua_gettable(L, -2);
  2558. if (lua_type(L, -1) == LUA_TSTRING) {
  2559. description = lua_tostring(L, -1);
  2560. }
  2561. lua_pop(L, 1);
  2562. if (description) {
  2563. sym->description = rspamd_mempool_strdup(cfg->cfg_pool, description);
  2564. }
  2565. }
  2566. /* If ungrouped and there is a group defined in lua, change the primary group
  2567. * Otherwise, add to the list of groups for this symbol. */
  2568. lua_pushstring(L, "group");
  2569. lua_gettable(L, -2);
  2570. if (lua_type(L, -1) == LUA_TSTRING) {
  2571. group = lua_tostring(L, -1);
  2572. }
  2573. lua_pop(L, 1);
  2574. if (group) {
  2575. if (sym->flags & RSPAMD_SYMBOL_FLAG_UNGROUPED) {
  2576. /* Unset the "ungrouped" group */
  2577. sym->gr = NULL;
  2578. }
  2579. /* Add the group. If the symbol was ungrouped, this will
  2580. * clear RSPAMD_SYMBOL_FLAG_UNGROUPED from the flags. */
  2581. rspamd_config_add_symbol_group(cfg, name, group);
  2582. }
  2583. }
  2584. /* Remove table from stack */
  2585. lua_pop(L, 1);
  2586. }
  2587. }
  2588. else {
  2589. return luaL_error(L, "invalid arguments");
  2590. }
  2591. return 0;
  2592. }
  2593. static gint
  2594. lua_config_add_condition(lua_State *L)
  2595. {
  2596. LUA_TRACE_POINT;
  2597. struct rspamd_config *cfg = lua_check_config(L, 1);
  2598. const gchar *sym = luaL_checkstring(L, 2);
  2599. gboolean ret = FALSE;
  2600. gint condref;
  2601. if (cfg && sym && lua_type(L, 3) == LUA_TFUNCTION) {
  2602. lua_pushvalue(L, 3);
  2603. condref = luaL_ref(L, LUA_REGISTRYINDEX);
  2604. ret = rspamd_symcache_add_condition_delayed(cfg->cache, sym, L,
  2605. condref);
  2606. if (!ret) {
  2607. luaL_unref(L, LUA_REGISTRYINDEX, condref);
  2608. }
  2609. }
  2610. lua_pushboolean(L, ret);
  2611. return 1;
  2612. }
  2613. static gint
  2614. lua_config_set_peak_cb(lua_State *L)
  2615. {
  2616. LUA_TRACE_POINT;
  2617. struct rspamd_config *cfg = lua_check_config(L, 1);
  2618. gint condref;
  2619. if (cfg && lua_type(L, 2) == LUA_TFUNCTION) {
  2620. lua_pushvalue(L, 2);
  2621. condref = luaL_ref(L, LUA_REGISTRYINDEX);
  2622. rspamd_symcache_set_peak_callback(cfg->cache,
  2623. condref);
  2624. }
  2625. return 0;
  2626. }
  2627. static gint
  2628. lua_config_enable_symbol(lua_State *L)
  2629. {
  2630. struct rspamd_config *cfg = lua_check_config(L, 1);
  2631. const char *sym = luaL_checkstring(L, 2);
  2632. if (!sym || !cfg) {
  2633. return luaL_error(L, "invalid arguments");
  2634. }
  2635. rspamd_symcache_enable_symbol_static(cfg->cache, sym);
  2636. return 0;
  2637. }
  2638. static gint
  2639. lua_config_disable_symbol(lua_State *L)
  2640. {
  2641. struct rspamd_config *cfg = lua_check_config(L, 1);
  2642. const char *sym = luaL_checkstring(L, 2);
  2643. if (!sym || !cfg) {
  2644. return luaL_error(L, "invalid arguments");
  2645. }
  2646. rspamd_symcache_disable_symbol_static(cfg->cache, sym);
  2647. return 0;
  2648. }
  2649. static gint
  2650. lua_config_register_regexp(lua_State *L)
  2651. {
  2652. LUA_TRACE_POINT;
  2653. struct rspamd_config *cfg = lua_check_config(L, 1);
  2654. struct rspamd_lua_regexp *re = NULL;
  2655. rspamd_regexp_t *cache_re;
  2656. const gchar *type_str = NULL, *header_str = NULL;
  2657. gsize header_len = 0;
  2658. GError *err = NULL;
  2659. enum rspamd_re_type type = RSPAMD_RE_BODY;
  2660. gboolean pcre_only = FALSE;
  2661. /*
  2662. * - `re`* : regular expression object
  2663. * - `type`*: type of regular expression:
  2664. * + `mime`: mime regexp
  2665. * + `rawmime`: raw mime regexp
  2666. * + `header`: header regexp
  2667. * + `rawheader`: raw header expression
  2668. * + `body`: raw body regexp
  2669. * + `url`: url regexp
  2670. * - `header`: for header and rawheader regexp means the name of header
  2671. * - `pcre_only`: allow merely pcre for this regexp
  2672. */
  2673. if (cfg != NULL) {
  2674. if (!rspamd_lua_parse_table_arguments(L, 2, &err,
  2675. RSPAMD_LUA_PARSE_ARGUMENTS_DEFAULT,
  2676. "*re=U{regexp};*type=S;header=S;pcre_only=B",
  2677. &re, &type_str, &header_str, &pcre_only)) {
  2678. msg_err_config("cannot get parameters list: %e", err);
  2679. if (err) {
  2680. g_error_free(err);
  2681. }
  2682. }
  2683. else {
  2684. type = rspamd_re_cache_type_from_string(type_str);
  2685. if ((type == RSPAMD_RE_HEADER ||
  2686. type == RSPAMD_RE_RAWHEADER ||
  2687. type == RSPAMD_RE_MIMEHEADER) &&
  2688. header_str == NULL) {
  2689. msg_err_config(
  2690. "header argument is mandatory for header/rawheader regexps");
  2691. }
  2692. else {
  2693. if (pcre_only) {
  2694. rspamd_regexp_set_flags(re->re,
  2695. rspamd_regexp_get_flags(re->re) | RSPAMD_REGEXP_FLAG_PCRE_ONLY);
  2696. }
  2697. if (header_str != NULL) {
  2698. /* Include the last \0 */
  2699. header_len = strlen(header_str) + 1;
  2700. }
  2701. cache_re = rspamd_re_cache_add(cfg->re_cache, re->re, type,
  2702. (gpointer) header_str, header_len, -1);
  2703. /*
  2704. * XXX: here are dragons!
  2705. * Actually, lua regexp contains internal rspamd_regexp_t
  2706. * and it owns it.
  2707. * However, after this operation we have some OTHER regexp,
  2708. * which we really would like to use.
  2709. * So we do the following:
  2710. * 1) Remove old re and unref it
  2711. * 2) Replace the internal re with cached one
  2712. * 3) Increase its refcount to share ownership between cache and
  2713. * lua object
  2714. */
  2715. if (cache_re != re->re) {
  2716. rspamd_regexp_unref(re->re);
  2717. re->re = rspamd_regexp_ref(cache_re);
  2718. if (pcre_only) {
  2719. rspamd_regexp_set_flags(re->re,
  2720. rspamd_regexp_get_flags(re->re) | RSPAMD_REGEXP_FLAG_PCRE_ONLY);
  2721. }
  2722. }
  2723. }
  2724. }
  2725. }
  2726. return 0;
  2727. }
  2728. static gint
  2729. lua_config_replace_regexp(lua_State *L)
  2730. {
  2731. LUA_TRACE_POINT;
  2732. struct rspamd_config *cfg = lua_check_config(L, 1);
  2733. struct rspamd_lua_regexp *old_re = NULL, *new_re = NULL;
  2734. gboolean pcre_only = FALSE;
  2735. GError *err = NULL;
  2736. if (cfg != NULL) {
  2737. if (!rspamd_lua_parse_table_arguments(L, 2, &err,
  2738. RSPAMD_LUA_PARSE_ARGUMENTS_DEFAULT,
  2739. "*old_re=U{regexp};*new_re=U{regexp};pcre_only=B",
  2740. &old_re, &new_re, &pcre_only)) {
  2741. gint ret = luaL_error(L, "cannot get parameters list: %s",
  2742. err ? err->message : "invalid arguments");
  2743. if (err) {
  2744. g_error_free(err);
  2745. }
  2746. return ret;
  2747. }
  2748. else {
  2749. if (pcre_only) {
  2750. rspamd_regexp_set_flags(new_re->re,
  2751. rspamd_regexp_get_flags(new_re->re) | RSPAMD_REGEXP_FLAG_PCRE_ONLY);
  2752. }
  2753. rspamd_re_cache_replace(cfg->re_cache, old_re->re, new_re->re);
  2754. }
  2755. }
  2756. return 0;
  2757. }
  2758. static gint
  2759. lua_config_register_worker_script(lua_State *L)
  2760. {
  2761. LUA_TRACE_POINT;
  2762. struct rspamd_config *cfg = lua_check_config(L, 1);
  2763. const gchar *worker_type = luaL_checkstring(L, 2), *wtype;
  2764. struct rspamd_worker_conf *cf;
  2765. GList *cur;
  2766. struct rspamd_worker_lua_script *sc;
  2767. gboolean found = FALSE;
  2768. if (cfg == NULL || worker_type == NULL || lua_type(L, 3) != LUA_TFUNCTION) {
  2769. return luaL_error(L, "invalid arguments");
  2770. }
  2771. for (cur = g_list_first(cfg->workers); cur != NULL; cur = g_list_next(cur)) {
  2772. cf = cur->data;
  2773. wtype = g_quark_to_string(cf->type);
  2774. if (g_ascii_strcasecmp(wtype, worker_type) == 0) {
  2775. sc = rspamd_mempool_alloc0(cfg->cfg_pool, sizeof(*sc));
  2776. lua_pushvalue(L, 3);
  2777. sc->cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  2778. DL_APPEND(cf->scripts, sc);
  2779. found = TRUE;
  2780. }
  2781. }
  2782. lua_pushboolean(L, found);
  2783. return 1;
  2784. }
  2785. static gint
  2786. lua_config_add_on_load(lua_State *L)
  2787. {
  2788. LUA_TRACE_POINT;
  2789. struct rspamd_config *cfg = lua_check_config(L, 1);
  2790. struct rspamd_config_cfg_lua_script *sc;
  2791. if (cfg == NULL || lua_type(L, 2) != LUA_TFUNCTION) {
  2792. return luaL_error(L, "invalid arguments");
  2793. }
  2794. sc = rspamd_mempool_alloc0(cfg->cfg_pool, sizeof(*sc));
  2795. lua_pushvalue(L, 2);
  2796. sc->cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  2797. DL_APPEND(cfg->on_load_scripts, sc);
  2798. return 0;
  2799. }
  2800. static inline int
  2801. rspamd_post_init_sc_sort(const struct rspamd_config_cfg_lua_script *pra,
  2802. const struct rspamd_config_cfg_lua_script *prb)
  2803. {
  2804. /* Inverse sort */
  2805. return prb->priority - pra->priority;
  2806. }
  2807. static gint
  2808. lua_config_add_post_init(lua_State *L)
  2809. {
  2810. LUA_TRACE_POINT;
  2811. struct rspamd_config *cfg = lua_check_config(L, 1);
  2812. struct rspamd_config_cfg_lua_script *sc;
  2813. guint priority = 0;
  2814. lua_Debug d;
  2815. gchar tmp[256], *p;
  2816. if (cfg == NULL || lua_type(L, 2) != LUA_TFUNCTION) {
  2817. return luaL_error(L, "invalid arguments");
  2818. }
  2819. if (lua_type(L, 3) == LUA_TNUMBER) {
  2820. priority = lua_tointeger(L, 3);
  2821. }
  2822. if (lua_getstack(L, 1, &d) == 1) {
  2823. (void) lua_getinfo(L, "Sl", &d);
  2824. if ((p = strrchr(d.short_src, '/')) == NULL) {
  2825. p = d.short_src;
  2826. }
  2827. else {
  2828. p++;
  2829. }
  2830. if (strlen(p) > 200) {
  2831. rspamd_snprintf(tmp, sizeof(tmp), "%10s...]:%d", p,
  2832. d.currentline);
  2833. }
  2834. else {
  2835. rspamd_snprintf(tmp, sizeof(tmp), "%s:%d", p,
  2836. d.currentline);
  2837. }
  2838. }
  2839. sc = rspamd_mempool_alloc0(cfg->cfg_pool, sizeof(*sc));
  2840. lua_pushvalue(L, 2);
  2841. sc->cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  2842. sc->priority = priority;
  2843. sc->lua_src_pos = rspamd_mempool_strdup(cfg->cfg_pool, tmp);
  2844. DL_APPEND(cfg->post_init_scripts, sc);
  2845. DL_SORT(cfg->post_init_scripts, rspamd_post_init_sc_sort);
  2846. return 0;
  2847. }
  2848. static gint
  2849. lua_config_add_config_unload(lua_State *L)
  2850. {
  2851. LUA_TRACE_POINT;
  2852. struct rspamd_config *cfg = lua_check_config(L, 1);
  2853. struct rspamd_config_cfg_lua_script *sc;
  2854. lua_Debug d;
  2855. gchar tmp[256], *p;
  2856. if (cfg == NULL || lua_type(L, 2) != LUA_TFUNCTION) {
  2857. return luaL_error(L, "invalid arguments");
  2858. }
  2859. if (lua_getstack(L, 1, &d) == 1) {
  2860. (void) lua_getinfo(L, "Sl", &d);
  2861. if ((p = strrchr(d.short_src, '/')) == NULL) {
  2862. p = d.short_src;
  2863. }
  2864. else {
  2865. p++;
  2866. }
  2867. if (strlen(p) > 20) {
  2868. rspamd_snprintf(tmp, sizeof(tmp), "%10s...]:%d", p,
  2869. d.currentline);
  2870. }
  2871. else {
  2872. rspamd_snprintf(tmp, sizeof(tmp), "%s:%d", p,
  2873. d.currentline);
  2874. }
  2875. }
  2876. sc = rspamd_mempool_alloc0(cfg->cfg_pool, sizeof(*sc));
  2877. lua_pushvalue(L, 2);
  2878. sc->cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  2879. sc->lua_src_pos = rspamd_mempool_strdup(cfg->cfg_pool, tmp);
  2880. DL_APPEND(cfg->config_unload_scripts, sc);
  2881. return 0;
  2882. }
  2883. static void lua_periodic_callback_finish(struct thread_entry *thread, int ret);
  2884. static void lua_periodic_callback_error(struct thread_entry *thread, int ret, const char *msg);
  2885. struct rspamd_lua_periodic {
  2886. struct ev_loop *event_loop;
  2887. struct rspamd_config *cfg;
  2888. gchar *lua_src_pos;
  2889. lua_State *L;
  2890. gdouble timeout;
  2891. ev_timer ev;
  2892. gint cbref;
  2893. gboolean need_jitter;
  2894. ref_entry_t ref;
  2895. };
  2896. static void
  2897. lua_periodic_dtor(struct rspamd_lua_periodic *periodic)
  2898. {
  2899. luaL_unref(periodic->L, LUA_REGISTRYINDEX, periodic->cbref);
  2900. ev_timer_stop(periodic->event_loop, &periodic->ev);
  2901. }
  2902. static void
  2903. lua_periodic_fin(gpointer p)
  2904. {
  2905. struct rspamd_lua_periodic *periodic = (struct rspamd_lua_periodic *) p;
  2906. REF_RELEASE(periodic);
  2907. }
  2908. static void
  2909. lua_periodic_callback(struct ev_loop *loop, ev_timer *w, int revents)
  2910. {
  2911. struct rspamd_lua_periodic *periodic = (struct rspamd_lua_periodic *) w->data;
  2912. struct rspamd_config **pcfg, *cfg;
  2913. struct ev_loop **pev_base;
  2914. struct thread_entry *thread;
  2915. lua_State *L;
  2916. REF_RETAIN(periodic);
  2917. thread = lua_thread_pool_get_for_config(periodic->cfg);
  2918. thread->cd = periodic;
  2919. thread->finish_callback = lua_periodic_callback_finish;
  2920. thread->error_callback = lua_periodic_callback_error;
  2921. L = thread->lua_state;
  2922. lua_rawgeti(L, LUA_REGISTRYINDEX, periodic->cbref);
  2923. pcfg = lua_newuserdata(L, sizeof(*pcfg));
  2924. rspamd_lua_setclass(L, "rspamd{config}", -1);
  2925. cfg = periodic->cfg;
  2926. *pcfg = cfg;
  2927. pev_base = lua_newuserdata(L, sizeof(*pev_base));
  2928. rspamd_lua_setclass(L, "rspamd{ev_base}", -1);
  2929. *pev_base = periodic->event_loop;
  2930. lua_pushnumber(L, ev_now(periodic->event_loop));
  2931. lua_thread_call(thread, 3);
  2932. }
  2933. static void
  2934. lua_periodic_callback_finish(struct thread_entry *thread, int ret)
  2935. {
  2936. lua_State *L;
  2937. struct rspamd_lua_periodic *periodic = thread->cd;
  2938. gboolean plan_more = FALSE;
  2939. gdouble timeout = 0.0;
  2940. L = thread->lua_state;
  2941. ev_now_update(periodic->event_loop);
  2942. if (ret == 0) {
  2943. if (lua_type(L, -1) == LUA_TBOOLEAN) {
  2944. plan_more = lua_toboolean(L, -1);
  2945. timeout = periodic->timeout;
  2946. }
  2947. else if (lua_type(L, -1) == LUA_TNUMBER) {
  2948. timeout = lua_tonumber(L, -1);
  2949. plan_more = timeout > 0 ? TRUE : FALSE;
  2950. }
  2951. lua_pop(L, 1); /* Return value */
  2952. }
  2953. if (periodic->cfg->cur_worker) {
  2954. if (periodic->cfg->cur_worker->state != rspamd_worker_state_running) {
  2955. /* We are terminating, no more periodics */
  2956. plan_more = FALSE;
  2957. }
  2958. }
  2959. if (plan_more) {
  2960. if (periodic->need_jitter) {
  2961. timeout = rspamd_time_jitter(timeout, 0.0);
  2962. }
  2963. periodic->ev.repeat = timeout;
  2964. ev_timer_again(periodic->event_loop, &periodic->ev);
  2965. }
  2966. else {
  2967. ev_timer_stop(periodic->event_loop, &periodic->ev);
  2968. }
  2969. REF_RELEASE(periodic);
  2970. }
  2971. static void
  2972. lua_periodic_callback_error(struct thread_entry *thread, int ret, const char *msg)
  2973. {
  2974. struct rspamd_config *cfg;
  2975. struct rspamd_lua_periodic *periodic = thread->cd;
  2976. cfg = periodic->cfg;
  2977. msg_err_config("call to periodic script (registered at %s) failed: %s",
  2978. periodic->lua_src_pos, msg);
  2979. lua_periodic_callback_finish(thread, ret);
  2980. }
  2981. static gint
  2982. lua_config_add_periodic(lua_State *L)
  2983. {
  2984. LUA_TRACE_POINT;
  2985. struct rspamd_config *cfg = lua_check_config(L, 1);
  2986. struct ev_loop *ev_base = lua_check_ev_base(L, 2);
  2987. gdouble timeout = lua_tonumber(L, 3);
  2988. struct rspamd_lua_periodic *periodic;
  2989. gboolean need_jitter = FALSE;
  2990. lua_Debug d;
  2991. gchar tmp[256], *p;
  2992. if (cfg == NULL || timeout < 0 || lua_type(L, 4) != LUA_TFUNCTION) {
  2993. return luaL_error(L, "invalid arguments");
  2994. }
  2995. if (lua_type(L, 5) == LUA_TBOOLEAN) {
  2996. need_jitter = lua_toboolean(L, 5);
  2997. }
  2998. if (lua_getstack(L, 1, &d) == 1) {
  2999. (void) lua_getinfo(L, "Sl", &d);
  3000. if ((p = strrchr(d.short_src, '/')) == NULL) {
  3001. p = d.short_src;
  3002. }
  3003. else {
  3004. p++;
  3005. }
  3006. if (strlen(p) > 20) {
  3007. rspamd_snprintf(tmp, sizeof(tmp), "%10s...]:%d", p,
  3008. d.currentline);
  3009. }
  3010. else {
  3011. rspamd_snprintf(tmp, sizeof(tmp), "%s:%d", p,
  3012. d.currentline);
  3013. }
  3014. }
  3015. periodic = rspamd_mempool_alloc0(cfg->cfg_pool, sizeof(*periodic));
  3016. periodic->timeout = timeout;
  3017. periodic->L = L;
  3018. periodic->cfg = cfg;
  3019. periodic->event_loop = ev_base;
  3020. periodic->need_jitter = need_jitter;
  3021. periodic->lua_src_pos = rspamd_mempool_strdup(cfg->cfg_pool, tmp);
  3022. lua_pushvalue(L, 4);
  3023. periodic->cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  3024. if (need_jitter) {
  3025. timeout = rspamd_time_jitter(timeout, 0.0);
  3026. }
  3027. ev_timer_init(&periodic->ev, lua_periodic_callback, timeout, 0.0);
  3028. periodic->ev.data = periodic;
  3029. ev_timer_start(ev_base, &periodic->ev);
  3030. REF_INIT_RETAIN(periodic, lua_periodic_dtor);
  3031. rspamd_mempool_add_destructor(cfg->cfg_pool, lua_periodic_fin,
  3032. periodic);
  3033. return 0;
  3034. }
  3035. static gint
  3036. lua_config_get_symbols_count(lua_State *L)
  3037. {
  3038. LUA_TRACE_POINT;
  3039. struct rspamd_config *cfg = lua_check_config(L, 1);
  3040. guint res = 0;
  3041. if (cfg != NULL) {
  3042. res = rspamd_symcache_stats_symbols_count(cfg->cache);
  3043. }
  3044. else {
  3045. return luaL_error(L, "invalid arguments");
  3046. }
  3047. lua_pushinteger(L, res);
  3048. return 1;
  3049. }
  3050. static gint
  3051. lua_config_get_symbols_cksum(lua_State *L)
  3052. {
  3053. LUA_TRACE_POINT;
  3054. struct rspamd_config *cfg = lua_check_config(L, 1);
  3055. guint64 res = 0, *pres;
  3056. if (cfg != NULL) {
  3057. res = rspamd_symcache_get_cksum(cfg->cache);
  3058. }
  3059. else {
  3060. return luaL_error(L, "invalid arguments");
  3061. }
  3062. pres = lua_newuserdata(L, sizeof(res));
  3063. *pres = res;
  3064. rspamd_lua_setclass(L, "rspamd{int64}", -1);
  3065. return 1;
  3066. }
  3067. static gint
  3068. lua_config_get_symbols_counters(lua_State *L)
  3069. {
  3070. LUA_TRACE_POINT;
  3071. struct rspamd_config *cfg = lua_check_config(L, 1);
  3072. ucl_object_t *counters;
  3073. if (cfg != NULL) {
  3074. counters = rspamd_symcache_counters(cfg->cache);
  3075. ucl_object_push_lua(L, counters, true);
  3076. ucl_object_unref(counters);
  3077. }
  3078. else {
  3079. return luaL_error(L, "invalid arguments");
  3080. }
  3081. return 1;
  3082. }
  3083. struct lua_metric_symbols_cbdata {
  3084. lua_State *L;
  3085. struct rspamd_config *cfg;
  3086. bool is_table;
  3087. };
  3088. static void
  3089. lua_metric_symbol_inserter(gpointer k, gpointer v, gpointer ud)
  3090. {
  3091. struct lua_metric_symbols_cbdata *cbd = (struct lua_metric_symbols_cbdata *) ud;
  3092. lua_State *L;
  3093. const gchar *sym = k;
  3094. struct rspamd_symbol *s = (struct rspamd_symbol *) v;
  3095. struct rspamd_symbols_group *gr;
  3096. gint i;
  3097. L = cbd->L;
  3098. if (cbd->is_table) {
  3099. lua_pushstring(L, sym); /* Symbol name */
  3100. }
  3101. lua_createtable(L, 0, 6);
  3102. lua_pushstring(L, "score");
  3103. lua_pushnumber(L, s->score);
  3104. lua_settable(L, -3);
  3105. lua_pushstring(L, "description");
  3106. lua_pushstring(L, s->description);
  3107. lua_settable(L, -3);
  3108. lua_pushstring(L, "flags");
  3109. lua_createtable(L, 0, 3);
  3110. if (s->flags & RSPAMD_SYMBOL_FLAG_IGNORE_METRIC) {
  3111. lua_pushstring(L, "ignore");
  3112. lua_pushboolean(L, true);
  3113. lua_settable(L, -3);
  3114. }
  3115. if (s->flags & RSPAMD_SYMBOL_FLAG_ONEPARAM) {
  3116. lua_pushstring(L, "oneparam");
  3117. lua_pushboolean(L, true);
  3118. lua_settable(L, -3);
  3119. }
  3120. if (s->flags & RSPAMD_SYMBOL_FLAG_UNGROUPED) {
  3121. lua_pushstring(L, "ungrouped");
  3122. lua_pushboolean(L, true);
  3123. lua_settable(L, -3);
  3124. }
  3125. if (s->flags & RSPAMD_SYMBOL_FLAG_DISABLED) {
  3126. lua_pushstring(L, "disabled");
  3127. lua_pushboolean(L, true);
  3128. lua_settable(L, -3);
  3129. }
  3130. if (s->cache_item) {
  3131. guint sflags = rspamd_symcache_get_symbol_flags(cbd->cfg->cache, sym);
  3132. lua_push_symbol_flags(L, sflags, LUA_SYMOPT_FLAG_USE_MAP);
  3133. guint nids;
  3134. const guint *allowed_ids = rspamd_symcache_get_allowed_settings_ids(cbd->cfg->cache,
  3135. sym, &nids);
  3136. if (allowed_ids && nids > 0) {
  3137. lua_createtable(L, nids, 0);
  3138. for (i = 0; i < nids; i++) {
  3139. lua_pushinteger(L, allowed_ids[i]);
  3140. lua_rawseti(L, -2, i + 1);
  3141. }
  3142. lua_setfield(L, -2, "allowed_ids");
  3143. }
  3144. const guint *forbidden_ids = rspamd_symcache_get_forbidden_settings_ids(
  3145. cbd->cfg->cache,
  3146. sym, &nids);
  3147. if (forbidden_ids && nids > 0) {
  3148. lua_createtable(L, nids, 0);
  3149. for (i = 0; i < nids; i++) {
  3150. lua_pushinteger(L, forbidden_ids[i]);
  3151. lua_rawseti(L, -2, i + 1);
  3152. }
  3153. lua_setfield(L, -2, "forbidden_ids");
  3154. }
  3155. }
  3156. lua_settable(L, -3); /* Flags -> flags_table */
  3157. lua_pushstring(L, "nshots");
  3158. lua_pushinteger(L, s->nshots);
  3159. lua_settable(L, -3);
  3160. if (s->gr) {
  3161. lua_pushstring(L, "group");
  3162. lua_pushstring(L, s->gr->name);
  3163. lua_settable(L, -3);
  3164. }
  3165. if (s->groups && s->groups->len > 0) {
  3166. lua_pushstring(L, "groups");
  3167. lua_createtable(L, s->groups->len, 0);
  3168. PTR_ARRAY_FOREACH(s->groups, i, gr)
  3169. {
  3170. lua_pushstring(L, gr->name);
  3171. lua_rawseti(L, -2, i + 1); /* Groups[i + 1] = group_name */
  3172. }
  3173. lua_settable(L, -3); /* Groups -> groups_table */
  3174. }
  3175. else {
  3176. lua_createtable(L, 0, 0);
  3177. lua_setfield(L, -2, "groups");
  3178. }
  3179. if (cbd->is_table) {
  3180. lua_settable(L, -3); /* Symname -> table */
  3181. }
  3182. }
  3183. static gint
  3184. lua_config_get_symbols(lua_State *L)
  3185. {
  3186. LUA_TRACE_POINT;
  3187. struct rspamd_config *cfg = lua_check_config(L, 1);
  3188. if (cfg != NULL) {
  3189. struct lua_metric_symbols_cbdata cbd;
  3190. cbd.L = L;
  3191. cbd.cfg = cfg;
  3192. cbd.is_table = true;
  3193. lua_createtable(L, 0, g_hash_table_size(cfg->symbols));
  3194. g_hash_table_foreach(cfg->symbols,
  3195. lua_metric_symbol_inserter,
  3196. &cbd);
  3197. }
  3198. else {
  3199. return luaL_error(L, "invalid arguments");
  3200. }
  3201. return 1;
  3202. }
  3203. static gint
  3204. lua_config_get_symbol(lua_State *L)
  3205. {
  3206. LUA_TRACE_POINT;
  3207. struct rspamd_config *cfg = lua_check_config(L, 1);
  3208. const gchar *sym_name = luaL_checkstring(L, 2);
  3209. if (cfg != NULL && sym_name != NULL) {
  3210. struct lua_metric_symbols_cbdata cbd;
  3211. struct rspamd_symbol *s = g_hash_table_lookup(cfg->symbols, sym_name);
  3212. if (s) {
  3213. cbd.L = L;
  3214. cbd.cfg = cfg;
  3215. cbd.is_table = false;
  3216. lua_metric_symbol_inserter((void *) sym_name, s, &cbd);
  3217. }
  3218. else {
  3219. /* No config for a symbol */
  3220. lua_pushnil(L);
  3221. }
  3222. }
  3223. else {
  3224. return luaL_error(L, "invalid arguments");
  3225. }
  3226. return 1;
  3227. }
  3228. static gint
  3229. lua_config_get_symbol_callback(lua_State *L)
  3230. {
  3231. LUA_TRACE_POINT;
  3232. struct rspamd_config *cfg = lua_check_config(L, 1);
  3233. const gchar *sym = luaL_checkstring(L, 2);
  3234. struct rspamd_abstract_callback_data *abs_cbdata;
  3235. struct lua_callback_data *cbd;
  3236. if (cfg != NULL && sym != NULL) {
  3237. abs_cbdata = rspamd_symcache_get_cbdata(cfg->cache, sym);
  3238. if (abs_cbdata == NULL || abs_cbdata->magic != rspamd_lua_callback_magic) {
  3239. lua_pushnil(L);
  3240. }
  3241. else {
  3242. cbd = (struct lua_callback_data *) abs_cbdata;
  3243. if (cbd->cb_is_ref) {
  3244. lua_rawgeti(L, LUA_REGISTRYINDEX, cbd->callback.ref);
  3245. }
  3246. else {
  3247. lua_getglobal(L, cbd->callback.name);
  3248. }
  3249. }
  3250. }
  3251. else {
  3252. return luaL_error(L, "invalid arguments");
  3253. }
  3254. return 1;
  3255. }
  3256. static gint
  3257. lua_config_set_symbol_callback(lua_State *L)
  3258. {
  3259. LUA_TRACE_POINT;
  3260. struct rspamd_config *cfg = lua_check_config(L, 1);
  3261. const gchar *sym = luaL_checkstring(L, 2);
  3262. struct rspamd_abstract_callback_data *abs_cbdata;
  3263. struct lua_callback_data *cbd;
  3264. if (cfg != NULL && sym != NULL && lua_type(L, 3) == LUA_TFUNCTION) {
  3265. abs_cbdata = rspamd_symcache_get_cbdata(cfg->cache, sym);
  3266. if (abs_cbdata == NULL || abs_cbdata->magic != rspamd_lua_callback_magic) {
  3267. lua_pushboolean(L, FALSE);
  3268. }
  3269. else {
  3270. cbd = (struct lua_callback_data *) abs_cbdata;
  3271. if (cbd->cb_is_ref) {
  3272. luaL_unref(L, LUA_REGISTRYINDEX, cbd->callback.ref);
  3273. }
  3274. else {
  3275. cbd->cb_is_ref = TRUE;
  3276. }
  3277. lua_pushvalue(L, 3);
  3278. cbd->callback.ref = luaL_ref(L, LUA_REGISTRYINDEX);
  3279. lua_pushboolean(L, TRUE);
  3280. }
  3281. }
  3282. else {
  3283. return luaL_error(L, "invalid arguments");
  3284. }
  3285. return 1;
  3286. }
  3287. static gint
  3288. lua_config_get_symbol_stat(lua_State *L)
  3289. {
  3290. LUA_TRACE_POINT;
  3291. struct rspamd_config *cfg = lua_check_config(L, 1);
  3292. const gchar *sym = luaL_checkstring(L, 2);
  3293. gdouble freq, stddev, tm;
  3294. guint hits;
  3295. if (cfg != NULL && sym != NULL) {
  3296. if (!rspamd_symcache_stat_symbol(cfg->cache, sym, &freq,
  3297. &stddev, &tm, &hits)) {
  3298. lua_pushnil(L);
  3299. }
  3300. else {
  3301. lua_createtable(L, 0, 4);
  3302. lua_pushstring(L, "frequency");
  3303. lua_pushnumber(L, freq);
  3304. lua_settable(L, -3);
  3305. lua_pushstring(L, "sttdev");
  3306. lua_pushnumber(L, stddev);
  3307. lua_settable(L, -3);
  3308. lua_pushstring(L, "time");
  3309. lua_pushnumber(L, tm);
  3310. lua_settable(L, -3);
  3311. lua_pushstring(L, "hits");
  3312. lua_pushinteger(L, hits);
  3313. lua_settable(L, -3);
  3314. }
  3315. }
  3316. else {
  3317. return luaL_error(L, "invalid arguments");
  3318. }
  3319. return 1;
  3320. }
  3321. static gint
  3322. lua_config_get_symbol_parent(lua_State *L)
  3323. {
  3324. LUA_TRACE_POINT;
  3325. struct rspamd_config *cfg = lua_check_config(L, 1);
  3326. const gchar *sym = luaL_checkstring(L, 2), *parent;
  3327. if (cfg != NULL && sym != NULL) {
  3328. parent = rspamd_symcache_get_parent(cfg->cache, sym);
  3329. if (parent) {
  3330. lua_pushstring(L, parent);
  3331. }
  3332. else {
  3333. lua_pushnil(L);
  3334. }
  3335. }
  3336. else {
  3337. return luaL_error(L, "invalid arguments");
  3338. }
  3339. return 1;
  3340. }
  3341. static gint
  3342. lua_config_get_group_symbols(lua_State *L)
  3343. {
  3344. LUA_TRACE_POINT;
  3345. struct rspamd_config *cfg = lua_check_config(L, 1);
  3346. const gchar *gr_name = luaL_checkstring(L, 2);
  3347. if (cfg != NULL && gr_name != NULL) {
  3348. struct rspamd_symbols_group *group;
  3349. group = g_hash_table_lookup(cfg->groups, gr_name);
  3350. if (group == NULL) {
  3351. lua_pushnil(L);
  3352. }
  3353. else {
  3354. guint i = 1;
  3355. gpointer k, v;
  3356. GHashTableIter it;
  3357. lua_createtable(L, g_hash_table_size(group->symbols), 0);
  3358. g_hash_table_iter_init(&it, group->symbols);
  3359. while (g_hash_table_iter_next(&it, &k, &v)) {
  3360. lua_pushstring(L, k);
  3361. lua_rawseti(L, -2, i);
  3362. i++;
  3363. }
  3364. }
  3365. }
  3366. else {
  3367. return luaL_error(L, "invalid arguments");
  3368. }
  3369. return 1;
  3370. }
  3371. static gint
  3372. lua_config_get_groups(lua_State *L)
  3373. {
  3374. LUA_TRACE_POINT;
  3375. struct rspamd_config *cfg = lua_check_config(L, 1);
  3376. gboolean need_private;
  3377. struct rspamd_symbols_group *gr;
  3378. GHashTableIter it;
  3379. gpointer k, v;
  3380. if (cfg) {
  3381. if (lua_isboolean(L, 2)) {
  3382. need_private = lua_toboolean(L, 2);
  3383. }
  3384. else {
  3385. need_private = !(cfg->public_groups_only);
  3386. }
  3387. lua_createtable(L, 0, g_hash_table_size(cfg->groups));
  3388. g_hash_table_iter_init(&it, cfg->groups);
  3389. while (g_hash_table_iter_next(&it, &k, &v)) {
  3390. gr = (struct rspamd_symbols_group *) v;
  3391. if (need_private || (gr->flags & RSPAMD_SYMBOL_GROUP_PUBLIC)) {
  3392. lua_createtable(L, 0, 4);
  3393. lua_pushstring(L, gr->description);
  3394. lua_setfield(L, -2, "description");
  3395. lua_pushnumber(L, gr->max_score);
  3396. lua_setfield(L, -2, "max_score");
  3397. lua_pushboolean(L, (gr->flags & RSPAMD_SYMBOL_GROUP_PUBLIC) != 0);
  3398. lua_setfield(L, -2, "is_public");
  3399. /* TODO: maybe push symbols as well */
  3400. /* Parent table indexed by group name */
  3401. lua_setfield(L, -2, gr->name);
  3402. }
  3403. }
  3404. }
  3405. else {
  3406. return luaL_error(L, "invalid arguments");
  3407. }
  3408. return 1;
  3409. }
  3410. static gint
  3411. lua_config_register_finish_script(lua_State *L)
  3412. {
  3413. LUA_TRACE_POINT;
  3414. struct rspamd_config *cfg = lua_check_config(L, 1);
  3415. struct rspamd_config_cfg_lua_script *sc;
  3416. if (cfg != NULL && lua_type(L, 2) == LUA_TFUNCTION) {
  3417. sc = rspamd_mempool_alloc0(cfg->cfg_pool, sizeof(*sc));
  3418. lua_pushvalue(L, 2);
  3419. sc->cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  3420. DL_APPEND(cfg->on_term_scripts, sc);
  3421. }
  3422. else {
  3423. return luaL_error(L, "invalid arguments");
  3424. }
  3425. return 0;
  3426. }
  3427. static inline bool
  3428. rspamd_lua_config_check_settings_symbols_object(const ucl_object_t *obj)
  3429. {
  3430. if (obj == NULL) {
  3431. /* Semantically valid */
  3432. return true;
  3433. }
  3434. if (ucl_object_type(obj) == UCL_OBJECT) {
  3435. /* Key-value mapping - should be okay */
  3436. return true;
  3437. }
  3438. if (ucl_object_type(obj) == UCL_ARRAY) {
  3439. /* Okay if empty */
  3440. if (obj->len == 0) {
  3441. return true;
  3442. }
  3443. }
  3444. /* Everything else not okay */
  3445. return false;
  3446. }
  3447. static gint
  3448. lua_config_register_settings_id(lua_State *L)
  3449. {
  3450. LUA_TRACE_POINT;
  3451. struct rspamd_config *cfg = lua_check_config(L, 1);
  3452. const gchar *settings_name = luaL_checkstring(L, 2);
  3453. if (cfg != NULL && settings_name) {
  3454. ucl_object_t *sym_enabled, *sym_disabled;
  3455. enum rspamd_config_settings_policy policy = RSPAMD_SETTINGS_POLICY_DEFAULT;
  3456. sym_enabled = ucl_object_lua_import(L, 3);
  3457. if (!rspamd_lua_config_check_settings_symbols_object(sym_enabled)) {
  3458. ucl_object_unref(sym_enabled);
  3459. return luaL_error(L, "invalid symbols enabled");
  3460. }
  3461. sym_disabled = ucl_object_lua_import(L, 4);
  3462. if (!rspamd_lua_config_check_settings_symbols_object(sym_disabled)) {
  3463. ucl_object_unref(sym_enabled);
  3464. ucl_object_unref(sym_disabled);
  3465. return luaL_error(L, "invalid symbols enabled");
  3466. }
  3467. /* Check policy */
  3468. if (lua_isstring(L, 5)) {
  3469. const gchar *policy_str = lua_tostring(L, 5);
  3470. if (strcmp(policy_str, "default") == 0) {
  3471. policy = RSPAMD_SETTINGS_POLICY_DEFAULT;
  3472. }
  3473. else if (strcmp(policy_str, "implicit_allow") == 0) {
  3474. policy = RSPAMD_SETTINGS_POLICY_IMPLICIT_ALLOW;
  3475. }
  3476. else if (strcmp(policy_str, "implicit_deny") == 0) {
  3477. policy = RSPAMD_SETTINGS_POLICY_IMPLICIT_DENY;
  3478. }
  3479. else {
  3480. return luaL_error(L, "invalid settings policy: %s", policy_str);
  3481. }
  3482. }
  3483. else {
  3484. /* Apply heuristic */
  3485. if (!sym_enabled) {
  3486. policy = RSPAMD_SETTINGS_POLICY_IMPLICIT_ALLOW;
  3487. }
  3488. }
  3489. rspamd_config_register_settings_id(cfg, settings_name, sym_enabled,
  3490. sym_disabled, policy);
  3491. if (sym_enabled) {
  3492. ucl_object_unref(sym_enabled);
  3493. }
  3494. if (sym_disabled) {
  3495. ucl_object_unref(sym_disabled);
  3496. }
  3497. }
  3498. else {
  3499. return luaL_error(L, "invalid arguments");
  3500. }
  3501. return 0;
  3502. }
  3503. static gint
  3504. lua_config_register_monitored(lua_State *L)
  3505. {
  3506. LUA_TRACE_POINT;
  3507. struct rspamd_config *cfg = lua_check_config(L, 1);
  3508. struct rspamd_monitored *m, **pm;
  3509. const gchar *url, *type;
  3510. ucl_object_t *params = NULL;
  3511. url = lua_tostring(L, 2);
  3512. type = lua_tostring(L, 3);
  3513. if (cfg != NULL && url != NULL && type != NULL) {
  3514. if (g_ascii_strcasecmp(type, "dns") == 0) {
  3515. lua_Debug ar;
  3516. if (lua_type(L, 4) == LUA_TTABLE) {
  3517. params = ucl_object_lua_import(L, 4);
  3518. }
  3519. /* Get lua line and source */
  3520. lua_getstack(L, 1, &ar);
  3521. lua_getinfo(L, "nSl", &ar);
  3522. m = rspamd_monitored_create_(cfg->monitored_ctx, url,
  3523. RSPAMD_MONITORED_DNS, RSPAMD_MONITORED_DEFAULT,
  3524. params, ar.short_src);
  3525. if (m) {
  3526. pm = lua_newuserdata(L, sizeof(*pm));
  3527. *pm = m;
  3528. rspamd_lua_setclass(L, "rspamd{monitored}", -1);
  3529. }
  3530. else {
  3531. lua_pushnil(L);
  3532. }
  3533. if (params) {
  3534. ucl_object_unref(params);
  3535. }
  3536. }
  3537. else {
  3538. return luaL_error(L, "invalid monitored type: %s", type);
  3539. }
  3540. }
  3541. else {
  3542. return luaL_error(L, "invalid arguments");
  3543. }
  3544. return 1;
  3545. }
  3546. static gint
  3547. lua_config_add_doc(lua_State *L)
  3548. {
  3549. LUA_TRACE_POINT;
  3550. struct rspamd_config *cfg;
  3551. const gchar *path = NULL, *option, *doc_string;
  3552. const gchar *type_str = NULL, *default_value = NULL;
  3553. ucl_type_t type = UCL_NULL;
  3554. gboolean required = FALSE;
  3555. GError *err = NULL;
  3556. cfg = lua_check_config(L, 1);
  3557. if (lua_type(L, 2) == LUA_TSTRING) {
  3558. path = luaL_checkstring(L, 2);
  3559. }
  3560. option = luaL_checkstring(L, 3);
  3561. doc_string = luaL_checkstring(L, 4);
  3562. if (cfg && option && doc_string) {
  3563. if (lua_type(L, 5) == LUA_TTABLE) {
  3564. if (!rspamd_lua_parse_table_arguments(L, 5, &err,
  3565. RSPAMD_LUA_PARSE_ARGUMENTS_DEFAULT,
  3566. "type=S;default=S;required=B",
  3567. &type_str, &default_value, &required)) {
  3568. msg_err_config("cannot get parameters list: %e", err);
  3569. if (err) {
  3570. g_error_free(err);
  3571. }
  3572. if (type_str) {
  3573. if (!ucl_object_string_to_type(type_str, &type)) {
  3574. msg_err_config("invalid type: %s", type_str);
  3575. }
  3576. }
  3577. }
  3578. }
  3579. rspamd_rcl_add_doc_by_path(cfg, path, doc_string, option,
  3580. type, NULL, 0, default_value, required);
  3581. }
  3582. else {
  3583. return luaL_error(L, "invalid arguments");
  3584. }
  3585. return 0;
  3586. }
  3587. static gint
  3588. lua_config_add_example(lua_State *L)
  3589. {
  3590. LUA_TRACE_POINT;
  3591. struct rspamd_config *cfg;
  3592. const gchar *path = NULL, *option, *doc_string, *example;
  3593. gsize example_len;
  3594. cfg = lua_check_config(L, 1);
  3595. if (lua_type(L, 2) == LUA_TSTRING) {
  3596. path = luaL_checkstring(L, 2);
  3597. }
  3598. option = luaL_checkstring(L, 3);
  3599. doc_string = luaL_checkstring(L, 4);
  3600. example = luaL_checklstring(L, 5, &example_len);
  3601. if (cfg && option && doc_string && example) {
  3602. rspamd_rcl_add_doc_by_example(cfg, path, doc_string, option,
  3603. example, example_len);
  3604. }
  3605. else {
  3606. return luaL_error(L, "invalid arguments");
  3607. }
  3608. return 0;
  3609. }
  3610. static gint
  3611. lua_config_get_cpu_flags(lua_State *L)
  3612. {
  3613. LUA_TRACE_POINT;
  3614. struct rspamd_config *cfg = lua_check_config(L, 1);
  3615. struct rspamd_cryptobox_library_ctx *crypto_ctx;
  3616. if (cfg != NULL) {
  3617. crypto_ctx = cfg->libs_ctx->crypto_ctx;
  3618. lua_newtable(L);
  3619. if (crypto_ctx->cpu_config & CPUID_SSSE3) {
  3620. lua_pushstring(L, "ssse3");
  3621. lua_pushboolean(L, true);
  3622. lua_settable(L, -3);
  3623. }
  3624. if (crypto_ctx->cpu_config & CPUID_SSE41) {
  3625. lua_pushstring(L, "sse41");
  3626. lua_pushboolean(L, true);
  3627. lua_settable(L, -3);
  3628. }
  3629. if (crypto_ctx->cpu_config & CPUID_SSE42) {
  3630. lua_pushstring(L, "sse42");
  3631. lua_pushboolean(L, true);
  3632. lua_settable(L, -3);
  3633. }
  3634. if (crypto_ctx->cpu_config & CPUID_SSE2) {
  3635. lua_pushstring(L, "sse2");
  3636. lua_pushboolean(L, true);
  3637. lua_settable(L, -3);
  3638. }
  3639. if (crypto_ctx->cpu_config & CPUID_SSE3) {
  3640. lua_pushstring(L, "sse3");
  3641. lua_pushboolean(L, true);
  3642. lua_settable(L, -3);
  3643. }
  3644. if (crypto_ctx->cpu_config & CPUID_AVX) {
  3645. lua_pushstring(L, "avx");
  3646. lua_pushboolean(L, true);
  3647. lua_settable(L, -3);
  3648. }
  3649. if (crypto_ctx->cpu_config & CPUID_AVX2) {
  3650. lua_pushstring(L, "avx2");
  3651. lua_pushboolean(L, true);
  3652. lua_settable(L, -3);
  3653. }
  3654. }
  3655. else {
  3656. return luaL_error(L, "invalid arguments");
  3657. }
  3658. return 1;
  3659. }
  3660. static gint
  3661. lua_config_has_torch(lua_State *L)
  3662. {
  3663. msg_warn("use of the obsoleted `has_torch` function");
  3664. lua_pushboolean(L, false);
  3665. return 1;
  3666. }
  3667. static gint
  3668. lua_config_experimental_enabled(lua_State *L)
  3669. {
  3670. LUA_TRACE_POINT;
  3671. struct rspamd_config *cfg = lua_check_config(L, 1);
  3672. if (cfg != NULL) {
  3673. lua_pushboolean(L, cfg->enable_experimental);
  3674. }
  3675. else {
  3676. return luaL_error(L, "invalid arguments");
  3677. }
  3678. return 1;
  3679. }
  3680. struct rspamd_lua_include_trace_cbdata {
  3681. lua_State *L;
  3682. gint cbref;
  3683. };
  3684. static void
  3685. lua_include_trace_cb(struct ucl_parser *parser,
  3686. const ucl_object_t *parent,
  3687. const ucl_object_t *args,
  3688. const char *path,
  3689. size_t pathlen,
  3690. void *user_data)
  3691. {
  3692. struct rspamd_lua_include_trace_cbdata *cbdata =
  3693. (struct rspamd_lua_include_trace_cbdata *) user_data;
  3694. gint err_idx;
  3695. lua_State *L;
  3696. L = cbdata->L;
  3697. lua_pushcfunction(L, &rspamd_lua_traceback);
  3698. err_idx = lua_gettop(L);
  3699. lua_rawgeti(L, LUA_REGISTRYINDEX, cbdata->cbref);
  3700. /* Current filename */
  3701. lua_pushstring(L, ucl_parser_get_cur_file(parser));
  3702. /* Included filename */
  3703. lua_pushlstring(L, path, pathlen);
  3704. /* Params */
  3705. if (args) {
  3706. ucl_object_push_lua(L, args, true);
  3707. }
  3708. else {
  3709. lua_newtable(L);
  3710. }
  3711. /* Parent */
  3712. if (parent) {
  3713. lua_pushstring(L, ucl_object_key(parent));
  3714. }
  3715. else {
  3716. lua_pushnil(L);
  3717. }
  3718. if (lua_pcall(L, 4, 0, err_idx) != 0) {
  3719. msg_err("lua call to local include trace failed: %s", lua_tostring(L, -1));
  3720. }
  3721. lua_settop(L, err_idx - 1);
  3722. }
  3723. #define LUA_TABLE_TO_HASH(htb, idx) \
  3724. do { \
  3725. lua_pushstring(L, (idx)); \
  3726. lua_gettable(L, -2); \
  3727. if (lua_isstring(L, -1)) { \
  3728. g_hash_table_insert((htb), (idx), g_strdup(lua_tostring(L, -1))); \
  3729. } \
  3730. lua_pop(L, 1); \
  3731. } while (0)
  3732. static gint
  3733. lua_config_load_ucl(lua_State *L)
  3734. {
  3735. struct rspamd_config *cfg = lua_check_config(L, 1);
  3736. const gchar *filename;
  3737. GHashTable *paths = g_hash_table_new_full(rspamd_str_hash, rspamd_str_equal,
  3738. NULL, g_free);
  3739. GError *err = NULL;
  3740. if (cfg) {
  3741. if (lua_isstring(L, 2)) {
  3742. filename = lua_tostring(L, 2);
  3743. }
  3744. else {
  3745. filename = RSPAMD_CONFDIR "/rspamd.conf";
  3746. }
  3747. /* Convert rspamd_paths */
  3748. lua_getglobal(L, "rspamd_paths");
  3749. if (lua_istable(L, -1)) {
  3750. LUA_TABLE_TO_HASH(paths, RSPAMD_CONFDIR_INDEX);
  3751. LUA_TABLE_TO_HASH(paths, RSPAMD_LOCAL_CONFDIR_INDEX);
  3752. LUA_TABLE_TO_HASH(paths, RSPAMD_RUNDIR_INDEX);
  3753. LUA_TABLE_TO_HASH(paths, RSPAMD_DBDIR_INDEX);
  3754. LUA_TABLE_TO_HASH(paths, RSPAMD_LOGDIR_INDEX);
  3755. LUA_TABLE_TO_HASH(paths, RSPAMD_WWWDIR_INDEX);
  3756. LUA_TABLE_TO_HASH(paths, RSPAMD_PLUGINSDIR_INDEX);
  3757. LUA_TABLE_TO_HASH(paths, RSPAMD_RULESDIR_INDEX);
  3758. LUA_TABLE_TO_HASH(paths, RSPAMD_LUALIBDIR_INDEX);
  3759. LUA_TABLE_TO_HASH(paths, RSPAMD_PREFIX_INDEX);
  3760. }
  3761. lua_pop(L, 1);
  3762. if (lua_isfunction(L, 3)) {
  3763. struct rspamd_lua_include_trace_cbdata cbd;
  3764. lua_pushvalue(L, 3);
  3765. cbd.cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  3766. cbd.L = L;
  3767. if (!rspamd_config_parse_ucl(cfg, filename, paths,
  3768. lua_include_trace_cb, &cbd, lua_toboolean(L, 4), &err)) {
  3769. luaL_unref(L, LUA_REGISTRYINDEX, cbd.cbref);
  3770. lua_pushboolean(L, false);
  3771. lua_pushfstring(L, "failed to load config: %s", err->message);
  3772. g_error_free(err);
  3773. g_hash_table_unref(paths);
  3774. return 2;
  3775. }
  3776. luaL_unref(L, LUA_REGISTRYINDEX, cbd.cbref);
  3777. }
  3778. else {
  3779. if (!rspamd_config_parse_ucl(cfg, filename, paths, NULL, NULL,
  3780. lua_toboolean(L, 3), &err)) {
  3781. lua_pushboolean(L, false);
  3782. lua_pushfstring(L, "failed to load config: %s", err->message);
  3783. g_error_free(err);
  3784. g_hash_table_unref(paths);
  3785. return 2;
  3786. }
  3787. }
  3788. rspamd_rcl_maybe_apply_lua_transform(cfg);
  3789. rspamd_config_calculate_cksum(cfg);
  3790. }
  3791. else {
  3792. return luaL_error(L, "invalid arguments");
  3793. }
  3794. g_hash_table_unref(paths);
  3795. lua_pushboolean(L, true);
  3796. return 1;
  3797. }
  3798. #undef IDX_TO_HASH
  3799. static gint
  3800. lua_config_parse_rcl(lua_State *L)
  3801. {
  3802. LUA_TRACE_POINT;
  3803. struct rspamd_config *cfg = lua_check_config(L, 1);
  3804. GHashTable *excluded = g_hash_table_new_full(rspamd_str_hash, rspamd_str_equal,
  3805. g_free, NULL);
  3806. GError *err = NULL;
  3807. struct rspamd_rcl_sections_map *top;
  3808. if (cfg) {
  3809. if (lua_istable(L, 2)) {
  3810. lua_pushvalue(L, 2);
  3811. for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
  3812. g_hash_table_insert(excluded, g_strdup(lua_tostring(L, -1)),
  3813. GINT_TO_POINTER(-1));
  3814. }
  3815. lua_pop(L, 1);
  3816. }
  3817. top = rspamd_rcl_config_init(cfg, excluded);
  3818. if (!rspamd_rcl_parse(top, cfg, cfg, cfg->cfg_pool, cfg->cfg_ucl_obj, &err)) {
  3819. lua_pushboolean(L, false);
  3820. lua_pushfstring(L, "failed to load config: %s", err->message);
  3821. g_error_free(err);
  3822. g_hash_table_unref(excluded);
  3823. rspamd_rcl_sections_free(top);
  3824. return 2;
  3825. }
  3826. }
  3827. else {
  3828. return luaL_error(L, "invalid arguments");
  3829. }
  3830. g_hash_table_unref(excluded);
  3831. rspamd_rcl_sections_free(top);
  3832. lua_pushboolean(L, true);
  3833. return 1;
  3834. }
  3835. static gint
  3836. lua_config_init_modules(lua_State *L)
  3837. {
  3838. LUA_TRACE_POINT;
  3839. struct rspamd_config *cfg = lua_check_config(L, 1);
  3840. if (cfg != NULL) {
  3841. rspamd_lua_post_load_config(cfg);
  3842. lua_pushboolean(L, rspamd_init_filters(cfg, false, false));
  3843. }
  3844. else {
  3845. return luaL_error(L, "invalid arguments");
  3846. }
  3847. return 1;
  3848. }
  3849. static gint
  3850. lua_config_init_subsystem(lua_State *L)
  3851. {
  3852. LUA_TRACE_POINT;
  3853. struct rspamd_config *cfg = lua_check_config(L, 1);
  3854. const gchar *subsystem = luaL_checkstring(L, 2);
  3855. gchar **parts;
  3856. guint nparts, i;
  3857. if (cfg != NULL && subsystem != NULL) {
  3858. parts = g_strsplit_set(subsystem, ";,", -1);
  3859. nparts = g_strv_length(parts);
  3860. for (i = 0; i < nparts; i++) {
  3861. if (strcmp(parts[i], "filters") == 0) {
  3862. rspamd_lua_post_load_config(cfg);
  3863. rspamd_init_filters(cfg, false, false);
  3864. }
  3865. else if (strcmp(parts[i], "langdet") == 0) {
  3866. if (!cfg->lang_det) {
  3867. cfg->lang_det = rspamd_language_detector_init(cfg);
  3868. rspamd_mempool_add_destructor(cfg->cfg_pool,
  3869. (rspamd_mempool_destruct_t) rspamd_language_detector_unref,
  3870. cfg->lang_det);
  3871. }
  3872. }
  3873. else if (strcmp(parts[i], "stat") == 0) {
  3874. rspamd_stat_init(cfg, NULL);
  3875. }
  3876. else if (strcmp(parts[i], "dns") == 0) {
  3877. struct ev_loop *ev_base = lua_check_ev_base(L, 3);
  3878. if (ev_base) {
  3879. cfg->dns_resolver = rspamd_dns_resolver_init(rspamd_log_default_logger(),
  3880. ev_base,
  3881. cfg);
  3882. }
  3883. else {
  3884. g_strfreev(parts);
  3885. return luaL_error(L, "no event base specified");
  3886. }
  3887. }
  3888. else if (strcmp(parts[i], "symcache") == 0) {
  3889. rspamd_symcache_init(cfg->cache);
  3890. }
  3891. else {
  3892. int ret = luaL_error(L, "invalid param: %s", parts[i]);
  3893. g_strfreev(parts);
  3894. return ret;
  3895. }
  3896. }
  3897. g_strfreev(parts);
  3898. }
  3899. else {
  3900. return luaL_error(L, "invalid arguments");
  3901. }
  3902. return 0;
  3903. }
  3904. static gint
  3905. lua_config_register_re_selector(lua_State *L)
  3906. {
  3907. LUA_TRACE_POINT;
  3908. struct rspamd_config *cfg = lua_check_config(L, 1);
  3909. const gchar *name = luaL_checkstring(L, 2);
  3910. const gchar *selector_str = luaL_checkstring(L, 3);
  3911. const gchar *delimiter = "";
  3912. bool flatten = false;
  3913. gint top = lua_gettop(L);
  3914. bool res = false;
  3915. if (cfg && name && selector_str) {
  3916. if (lua_gettop(L) >= 4) {
  3917. delimiter = luaL_checkstring(L, 4);
  3918. if (lua_isboolean(L, 5)) {
  3919. flatten = lua_toboolean(L, 5);
  3920. }
  3921. }
  3922. if (luaL_dostring(L, "return require \"lua_selectors\"") != 0) {
  3923. msg_warn_config("cannot require lua_selectors: %s",
  3924. lua_tostring(L, -1));
  3925. }
  3926. else {
  3927. if (lua_type(L, -1) != LUA_TTABLE) {
  3928. msg_warn_config("lua selectors must return "
  3929. "table and not %s",
  3930. lua_typename(L, lua_type(L, -1)));
  3931. }
  3932. else {
  3933. lua_pushstring(L, "create_selector_closure");
  3934. lua_gettable(L, -2);
  3935. if (lua_type(L, -1) != LUA_TFUNCTION) {
  3936. msg_warn_config("create_selector_closure must return "
  3937. "function and not %s",
  3938. lua_typename(L, lua_type(L, -1)));
  3939. }
  3940. else {
  3941. gint err_idx, ret;
  3942. struct rspamd_config **pcfg;
  3943. lua_pushcfunction(L, &rspamd_lua_traceback);
  3944. err_idx = lua_gettop(L);
  3945. /* Push function */
  3946. lua_pushvalue(L, -2);
  3947. pcfg = lua_newuserdata(L, sizeof(*pcfg));
  3948. rspamd_lua_setclass(L, "rspamd{config}", -1);
  3949. *pcfg = cfg;
  3950. lua_pushstring(L, selector_str);
  3951. lua_pushstring(L, delimiter);
  3952. lua_pushboolean(L, flatten);
  3953. if ((ret = lua_pcall(L, 4, 1, err_idx)) != 0) {
  3954. msg_err_config("call to create_selector_closure lua "
  3955. "script failed (%d): %s",
  3956. ret,
  3957. lua_tostring(L, -1));
  3958. }
  3959. else {
  3960. if (lua_type(L, -1) != LUA_TFUNCTION) {
  3961. msg_warn_config("create_selector_closure "
  3962. "invocation must return "
  3963. "function and not %s",
  3964. lua_typename(L, lua_type(L, -1)));
  3965. }
  3966. else {
  3967. ret = luaL_ref(L, LUA_REGISTRYINDEX);
  3968. rspamd_re_cache_add_selector(cfg->re_cache,
  3969. name, ret);
  3970. res = true;
  3971. }
  3972. }
  3973. }
  3974. }
  3975. }
  3976. }
  3977. else {
  3978. return luaL_error(L, "invalid arguments");
  3979. }
  3980. lua_settop(L, top);
  3981. lua_pushboolean(L, res);
  3982. if (res) {
  3983. msg_info_config("registered regexp selector %s", name);
  3984. }
  3985. return 1;
  3986. }
  3987. static gint
  3988. lua_config_get_tld_path(lua_State *L)
  3989. {
  3990. LUA_TRACE_POINT;
  3991. struct rspamd_config *cfg = lua_check_config(L, 1);
  3992. if (cfg != NULL) {
  3993. lua_pushstring(L, cfg->tld_file);
  3994. }
  3995. else {
  3996. return luaL_error(L, "invalid arguments");
  3997. }
  3998. return 1;
  3999. }
  4000. static gint
  4001. lua_config_get_dns_max_requests(lua_State *L)
  4002. {
  4003. LUA_TRACE_POINT;
  4004. struct rspamd_config *cfg = lua_check_config(L, 1);
  4005. if (cfg != NULL) {
  4006. lua_pushinteger(L, cfg->dns_max_requests);
  4007. }
  4008. else {
  4009. return luaL_error(L, "invalid arguments");
  4010. }
  4011. return 1;
  4012. }
  4013. static gint
  4014. lua_config_get_dns_timeout(lua_State *L)
  4015. {
  4016. LUA_TRACE_POINT;
  4017. struct rspamd_config *cfg = lua_check_config(L, 1);
  4018. if (cfg != NULL) {
  4019. lua_pushnumber(L, cfg->dns_timeout);
  4020. }
  4021. else {
  4022. return luaL_error(L, "invalid arguments");
  4023. }
  4024. return 1;
  4025. }
  4026. static gint
  4027. lua_monitored_alive(lua_State *L)
  4028. {
  4029. LUA_TRACE_POINT;
  4030. struct rspamd_monitored *m = lua_check_monitored(L, 1);
  4031. if (m) {
  4032. lua_pushboolean(L, rspamd_monitored_alive(m));
  4033. }
  4034. else {
  4035. return luaL_error(L, "invalid arguments");
  4036. }
  4037. return 1;
  4038. }
  4039. static gint
  4040. lua_monitored_offline(lua_State *L)
  4041. {
  4042. LUA_TRACE_POINT;
  4043. struct rspamd_monitored *m = lua_check_monitored(L, 1);
  4044. if (m) {
  4045. lua_pushnumber(L, rspamd_monitored_offline_time(m));
  4046. }
  4047. else {
  4048. return luaL_error(L, "invalid arguments");
  4049. }
  4050. return 1;
  4051. }
  4052. static gint
  4053. lua_monitored_total_offline(lua_State *L)
  4054. {
  4055. LUA_TRACE_POINT;
  4056. struct rspamd_monitored *m = lua_check_monitored(L, 1);
  4057. if (m) {
  4058. lua_pushnumber(L, rspamd_monitored_total_offline_time(m));
  4059. }
  4060. else {
  4061. return luaL_error(L, "invalid arguments");
  4062. }
  4063. return 1;
  4064. }
  4065. static gint
  4066. lua_monitored_latency(lua_State *L)
  4067. {
  4068. LUA_TRACE_POINT;
  4069. struct rspamd_monitored *m = lua_check_monitored(L, 1);
  4070. if (m) {
  4071. lua_pushnumber(L, rspamd_monitored_latency(m));
  4072. }
  4073. else {
  4074. return luaL_error(L, "invalid arguments");
  4075. }
  4076. return 1;
  4077. }
  4078. void luaopen_config(lua_State *L)
  4079. {
  4080. rspamd_lua_new_class(L, "rspamd{config}", configlib_m);
  4081. lua_pop(L, 1);
  4082. rspamd_lua_new_class(L, "rspamd{monitored}", monitoredlib_m);
  4083. lua_pop(L, 1);
  4084. }
  4085. void lua_call_finish_script(struct rspamd_config_cfg_lua_script *sc,
  4086. struct rspamd_task *task)
  4087. {
  4088. struct rspamd_task **ptask;
  4089. struct thread_entry *thread;
  4090. thread = lua_thread_pool_get_for_task(task);
  4091. thread->task = task;
  4092. lua_State *L = thread->lua_state;
  4093. lua_rawgeti(L, LUA_REGISTRYINDEX, sc->cbref);
  4094. ptask = lua_newuserdata(L, sizeof(struct rspamd_task *));
  4095. rspamd_lua_setclass(L, rspamd_task_classname, -1);
  4096. *ptask = task;
  4097. lua_thread_call(thread, 1);
  4098. }