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_util.c 80KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627
  1. /*-
  2. * Copyright 2016 Vsevolod Stakhov
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "lua_common.h"
  17. #include "html.h"
  18. #include "tokenizers/tokenizers.h"
  19. #include "unix-std.h"
  20. #include "contrib/zstd/zstd.h"
  21. #include "contrib/uthash/utlist.h"
  22. #include "libmime/email_addr.h"
  23. #include "libmime/content_type.h"
  24. #include "libmime/mime_headers.h"
  25. #include "linenoise.h"
  26. #include <math.h>
  27. #include <glob.h>
  28. #include <zlib.h>
  29. #include "unicode/uspoof.h"
  30. /***
  31. * @module rspamd_util
  32. * This module contains some generic purpose utilities that could be useful for
  33. * testing and production rules.
  34. */
  35. /***
  36. * @function util.create_event_base()
  37. * Creates new event base for processing asynchronous events
  38. * @return {ev_base} new event processing base
  39. */
  40. LUA_FUNCTION_DEF (util, create_event_base);
  41. /***
  42. * @function util.load_rspamd_config(filename)
  43. * Load rspamd config from the specified file
  44. * @return {confg} new configuration object suitable for access
  45. */
  46. LUA_FUNCTION_DEF (util, load_rspamd_config);
  47. /***
  48. * @function util.config_from_ucl(any, string)
  49. * Load rspamd config from ucl reperesented by any lua table
  50. * @return {confg} new configuration object suitable for access
  51. */
  52. LUA_FUNCTION_DEF (util, config_from_ucl);
  53. /***
  54. * @function util.encode_base64(input[, str_len, [newlines_type]])
  55. * Encodes data in base64 breaking lines if needed
  56. * @param {text or string} input input data
  57. * @param {number} str_len optional size of lines or 0 if split is not needed
  58. * @return {rspamd_text} encoded data chunk
  59. */
  60. LUA_FUNCTION_DEF (util, encode_base64);
  61. /***
  62. * @function util.encode_qp(input[, str_len, [newlines_type]])
  63. * Encodes data in quouted printable breaking lines if needed
  64. * @param {text or string} input input data
  65. * @param {number} str_len optional size of lines or 0 if split is not needed
  66. * @return {rspamd_text} encoded data chunk
  67. */
  68. LUA_FUNCTION_DEF (util, encode_qp);
  69. /***
  70. * @function util.decode_base64(input)
  71. * Decodes data from base64 ignoring whitespace characters
  72. * @param {text or string} input data to decode; if `rspamd{text}` is used then the string is modified **in-place**
  73. * @return {rspamd_text} decoded data chunk
  74. */
  75. LUA_FUNCTION_DEF (util, decode_base64);
  76. /***
  77. * @function util.encode_base32(input)
  78. * Encodes data in base32 breaking lines if needed
  79. * @param {text or string} input input data
  80. * @return {rspamd_text} encoded data chunk
  81. */
  82. LUA_FUNCTION_DEF (util, encode_base32);
  83. /***
  84. * @function util.decode_base32(input)
  85. * Decodes data from base32 ignoring whitespace characters
  86. * @param {text or string} input data to decode
  87. * @return {rspamd_text} decoded data chunk
  88. */
  89. LUA_FUNCTION_DEF (util, decode_base32);
  90. /***
  91. * @function util.decode_url(input)
  92. * Decodes data from url encoding
  93. * @param {text or string} input data to decode
  94. * @return {rspamd_text} decoded data chunk
  95. */
  96. LUA_FUNCTION_DEF (util, decode_url);
  97. /***
  98. * @function util.tokenize_text(input[, exceptions])
  99. * Create tokens from a text using optional exceptions list
  100. * @param {text/string} input input data
  101. * @param {table} exceptions, a table of pairs containing <start_pos,length> of exceptions in the input
  102. * @return {table/strings} list of strings representing words in the text
  103. */
  104. LUA_FUNCTION_DEF (util, tokenize_text);
  105. LUA_FUNCTION_DEF (util, process_message);
  106. /***
  107. * @function util.tanh(num)
  108. * Calculates hyperbolic tanhent of the specified floating point value
  109. * @param {number} num input number
  110. * @return {number} hyperbolic tanhent of the variable
  111. */
  112. LUA_FUNCTION_DEF (util, tanh);
  113. /***
  114. * @function util.parse_html(input)
  115. * Parses HTML and returns the according text
  116. * @param {string|text} in input HTML
  117. * @return {rspamd_text} processed text with no HTML tags
  118. */
  119. LUA_FUNCTION_DEF (util, parse_html);
  120. /***
  121. * @function util.levenshtein_distance(s1, s2)
  122. * Returns levenstein distance between two strings
  123. * @param {string} s1 the first string
  124. * @param {string} s2 the second string
  125. * @return {number} number of differences in two strings
  126. */
  127. LUA_FUNCTION_DEF (util, levenshtein_distance);
  128. /***
  129. * @function util.parse_addr(str)
  130. * Parse rfc822 address to components. Returns a table of components:
  131. *
  132. * - `name`: name of address (e.g. Some User)
  133. * - `addr`: address part (e.g. user@example.com)
  134. *
  135. * @param {string} str input string
  136. * @return {table} resulting table of components
  137. */
  138. LUA_FUNCTION_DEF (util, parse_addr);
  139. /***
  140. * @function util.fold_header(name, value, [how, [stop_chars]])
  141. * Fold rfc822 header according to the folding rules
  142. *
  143. * @param {string} name name of the header
  144. * @param {string} value value of the header
  145. * @param {string} how "cr" for \r, "lf" for \n and "crlf" for \r\n (default)
  146. * @param {string} stop_chars also fold header when the
  147. * @return {string} Folded value of the header
  148. */
  149. LUA_FUNCTION_DEF (util, fold_header);
  150. /***
  151. * @function util.is_uppercase(str)
  152. * Returns true if a string is all uppercase
  153. *
  154. * @param {string} str input string
  155. * @return {bool} true if a string is all uppercase
  156. */
  157. LUA_FUNCTION_DEF (util, is_uppercase);
  158. /***
  159. * @function util.humanize_number(num)
  160. * Returns humanized representation of given number (like 1k instead of 1000)
  161. *
  162. * @param {number} num number to humanize
  163. * @return {string} humanized representation of a number
  164. */
  165. LUA_FUNCTION_DEF (util, humanize_number);
  166. /***
  167. * @function util.get_tld(host)
  168. * Returns effective second level domain part (eSLD) for the specified host
  169. *
  170. * @param {string} host hostname
  171. * @return {string} eSLD part of the hostname or the full hostname if eSLD was not found
  172. */
  173. LUA_FUNCTION_DEF (util, get_tld);
  174. /***
  175. * @function util.glob(pattern)
  176. * Returns results for the glob match for the specified pattern
  177. *
  178. * @param {string} pattern glob pattern to match ('?' and '*' are supported)
  179. * @return {table/string} list of matched files
  180. */
  181. LUA_FUNCTION_DEF (util, glob);
  182. /***
  183. * @function util.parse_mail_address(str, pool)
  184. * Parses email address and returns a table of tables in the following format:
  185. *
  186. * - `name` - name of internet address in UTF8, e.g. for `Vsevolod Stakhov <blah@foo.com>` it returns `Vsevolod Stakhov`
  187. * - `addr` - address part of the address
  188. * - `user` - user part (if present) of the address, e.g. `blah`
  189. * - `domain` - domain part (if present), e.g. `foo.com`
  190. *
  191. * @param {string} str input string
  192. * @param {rspamd_mempool} pool memory pool to use
  193. * @return {table/tables} parsed list of mail addresses
  194. */
  195. LUA_FUNCTION_DEF (util, parse_mail_address);
  196. /***
  197. * @function util.strlen_utf8(str)
  198. * Returns length of string encoded in utf-8 in characters.
  199. * If invalid characters are found, then this function returns number of bytes.
  200. * @param {string} str utf8 encoded string
  201. * @return {number} number of characters in string
  202. */
  203. LUA_FUNCTION_DEF (util, strlen_utf8);
  204. /***
  205. * @function util.strcasecmp(str1, str2)
  206. * Compares two ascii strings regardless of their case. Return value >0, 0 and <0
  207. * if `str1` is more, equal or less than `str2`
  208. * @param {string} str1 plain string
  209. * @param {string} str2 plain string
  210. * @return {number} result of comparison
  211. */
  212. LUA_FUNCTION_DEF (util, strcasecmp_ascii);
  213. /***
  214. * @function util.strequal_caseless(str1, str2)
  215. * Compares two utf8 strings regardless of their case. Return `true` if `str1` is
  216. * equal to `str2`
  217. * @param {string} str1 utf8 encoded string
  218. * @param {string} str2 utf8 encoded string
  219. * @return {bool} result of comparison
  220. */
  221. LUA_FUNCTION_DEF (util, strequal_caseless);
  222. /***
  223. * @function util.get_ticks()
  224. * Returns current number of ticks as floating point number
  225. * @return {number} number of current clock ticks (monotonically increasing)
  226. */
  227. LUA_FUNCTION_DEF (util, get_ticks);
  228. /***
  229. * @function util.get_time()
  230. * Returns current time as unix time in floating point representation
  231. * @return {number} number of seconds since 01.01.1970
  232. */
  233. LUA_FUNCTION_DEF (util, get_time);
  234. /***
  235. * @function util.time_to_string(seconds)
  236. * Converts time from Unix time to HTTP date format
  237. * @param {number} seconds unix timestamp
  238. * @return {string} date as HTTP date
  239. */
  240. LUA_FUNCTION_DEF (util, time_to_string);
  241. /***
  242. * @function util.stat(fname)
  243. * Performs stat(2) on a specified filepath and returns table of values
  244. *
  245. * - `size`: size of file in bytes
  246. * - `type`: type of filepath: `regular`, `directory`, `special`
  247. * - `mtime`: modification time as unix time
  248. *
  249. * @return {string,table} string is returned when error is occurred
  250. * @example
  251. *
  252. * local err,st = util.stat('/etc/password')
  253. *
  254. * if err then
  255. * -- handle error
  256. * else
  257. * print(st['size'])
  258. * end
  259. */
  260. LUA_FUNCTION_DEF (util, stat);
  261. /***
  262. * @function util.unlink(fname)
  263. * Removes the specified file from the filesystem
  264. *
  265. * @param {string} fname filename to remove
  266. * @return {boolean,[string]} true if file has been deleted or false,'error string'
  267. */
  268. LUA_FUNCTION_DEF (util, unlink);
  269. /***
  270. * @function util.lock_file(fname, [fd])
  271. * Lock the specified file. This function returns {number} which must be passed to `util.unlock_file` after usage
  272. * or you'll have a resource leak
  273. *
  274. * @param {string} fname filename to lock
  275. * @param {number} fd use the specified fd instead of opening one
  276. * @return {number|nil,string} number if locking was successful or nil + error otherwise
  277. */
  278. LUA_FUNCTION_DEF (util, lock_file);
  279. /***
  280. * @function util.unlock_file(fd, [close_fd])
  281. * Unlock the specified file closing the file descriptor associated.
  282. *
  283. * @param {number} fd descriptor to unlock
  284. * @param {boolean} close_fd close descriptor on unlocking (default: TRUE)
  285. * @return {boolean[,string]} true if a file was unlocked
  286. */
  287. LUA_FUNCTION_DEF (util, unlock_file);
  288. /***
  289. * @function util.create_file(fname, [mode])
  290. * Creates the specified file with the default mode 0644
  291. *
  292. * @param {string} fname filename to create
  293. * @param {number} mode open mode (you should use octal number here)
  294. * @return {number|nil,string} file descriptor or pair nil + error string
  295. */
  296. LUA_FUNCTION_DEF (util, create_file);
  297. /***
  298. * @function util.close_file(fd)
  299. * Closes descriptor fd
  300. *
  301. * @param {number} fd descriptor to close
  302. * @return {boolean[,string]} true if a file was closed
  303. */
  304. LUA_FUNCTION_DEF (util, close_file);
  305. /***
  306. * @function util.random_hex(size)
  307. * Returns random hex string of the specified size
  308. *
  309. * @param {number} len length of desired string in bytes
  310. * @return {string} string with random hex digests
  311. */
  312. LUA_FUNCTION_DEF (util, random_hex);
  313. /***
  314. * @function util.zstd_compress(data)
  315. * Compresses input using zstd compression
  316. *
  317. * @param {string/rspamd_text} data input data
  318. * @return {rspamd_text} compressed data
  319. */
  320. LUA_FUNCTION_DEF (util, zstd_compress);
  321. /***
  322. * @function util.zstd_decompress(data)
  323. * Decompresses input using zstd algorithm
  324. *
  325. * @param {string/rspamd_text} data compressed data
  326. * @return {error,rspamd_text} pair of error + decompressed text
  327. */
  328. LUA_FUNCTION_DEF (util, zstd_decompress);
  329. /***
  330. * @function util.gzip_decompress(data)
  331. * Decompresses input using gzip algorithm
  332. *
  333. * @param {string/rspamd_text} data compressed data
  334. * @return {error,rspamd_text} pair of error + decompressed text
  335. */
  336. LUA_FUNCTION_DEF (util, gzip_decompress);
  337. /***
  338. * @function util.gzip_compress(data)
  339. * Compresses input using gzip compression
  340. *
  341. * @param {string/rspamd_text} data input data
  342. * @return {rspamd_text} compressed data
  343. */
  344. LUA_FUNCTION_DEF (util, gzip_compress);
  345. /***
  346. * @function util.normalize_prob(prob, [bias = 0.5])
  347. * Normalize probabilities using polynom
  348. *
  349. * @param {number} prob probability param
  350. * @param {number} bias number to subtract for making the final solution
  351. * @return {number} normalized number
  352. */
  353. LUA_FUNCTION_DEF (util, normalize_prob);
  354. /***
  355. * @function util.is_utf_spoofed(str, [str2])
  356. * Returns true if a string is spoofed (possibly with another string `str2`)
  357. * @return {boolean} true if a string is spoofed
  358. */
  359. LUA_FUNCTION_DEF (util, is_utf_spoofed);
  360. /***
  361. * @function util.is_valid_utf8(str)
  362. * Returns true if a string is valid UTF8 string
  363. * @return {boolean} true if a string is spoofed
  364. */
  365. LUA_FUNCTION_DEF (util, is_valid_utf8);
  366. /***
  367. * @function util.has_obscured_unicode(str)
  368. * Returns true if a string has obscure UTF symbols (zero width spaces, order marks), ignores invalid utf characters
  369. * @return {boolean} true if a has obscured unicode characters (+ character and offset if found)
  370. */
  371. LUA_FUNCTION_DEF (util, has_obscured_unicode);
  372. /***
  373. * @function util.readline([prompt])
  374. * Returns string read from stdin with history and editing support
  375. * @return {string} string read from the input (with line endings stripped)
  376. */
  377. LUA_FUNCTION_DEF (util, readline);
  378. /***
  379. * @function util.readpassphrase([prompt])
  380. * Returns string read from stdin disabling echo
  381. * @return {string} string read from the input (with line endings stripped)
  382. */
  383. LUA_FUNCTION_DEF (util, readpassphrase);
  384. /***
  385. * @function util.file_exists(file)
  386. * Checks if a specified file exists and is available for reading
  387. * @return {boolean,string} true if file exists + string error if not
  388. */
  389. LUA_FUNCTION_DEF (util, file_exists);
  390. /***
  391. * @function util.mkdir(dir[, recursive])
  392. * Creates a specified directory
  393. * @return {boolean[,error]} true if directory has been created
  394. */
  395. LUA_FUNCTION_DEF (util, mkdir);
  396. /***
  397. * @function util.umask(mask)
  398. * Sets new umask. Accepts either numeric octal string, e.g. '022' or a plain
  399. * number, e.g. 0x12 (since Lua does not support octal integrals)
  400. * @return {number} old umask
  401. */
  402. LUA_FUNCTION_DEF (util, umask);
  403. /***
  404. * @function util.isatty()
  405. * Returns if stdout is a tty
  406. * @return {boolean} true in case of output being tty
  407. */
  408. LUA_FUNCTION_DEF (util, isatty);
  409. /***
  410. * @function util.pack(fmt, ...)
  411. *
  412. * Backport of Lua 5.3 `string.pack` function:
  413. * Returns a binary string containing the values v1, v2, etc. packed (that is,
  414. * serialized in binary form) according to the format string `fmt`
  415. * A format string is a sequence of conversion options. The conversion
  416. * options are as follows:
  417. *
  418. * * <: sets little endian
  419. * * >: sets big endian
  420. * * =: sets native endian
  421. * * ![n]: sets maximum alignment to n (default is native alignment)
  422. * * b: a signed byte (char)
  423. * * B: an unsigned byte (char)
  424. * * h: a signed short (native size)
  425. * * H: an unsigned short (native size)
  426. * * l: a signed long (native size)
  427. * * L: an unsigned long (native size)
  428. * * j: a lua_Integer
  429. * * J: a lua_Unsigned
  430. * * T: a size_t (native size)
  431. * * i[n]: a signed int with n bytes (default is native size)
  432. * * I[n]: an unsigned int with n bytes (default is native size)
  433. * * f: a float (native size)
  434. * * d: a double (native size)
  435. * * n: a lua_Number
  436. * * cn: a fixed-sized string with n bytes
  437. * * z: a zero-terminated string
  438. * * s[n]: a string preceded by its length coded as an unsigned integer with
  439. * * n bytes (default is a size_t)
  440. * * x: one byte of padding
  441. * * Xop: an empty item that aligns according to option op (which is otherwise ignored)
  442. * * ' ': (empty space) ignored
  443. *
  444. * (A "[n]" means an optional integral numeral.) Except for padding, spaces,
  445. * and configurations (options "xX <=>!"), each option corresponds to an
  446. * argument (in string.pack) or a result (in string.unpack).
  447. *
  448. * For options "!n", "sn", "in", and "In", n can be any integer between 1 and
  449. * All integral options check overflows; string.pack checks whether the given
  450. * value fits in the given size; string.unpack checks whether the read value
  451. * fits in a Lua integer.
  452. *
  453. * Any format string starts as if prefixed by "!1=", that is, with maximum
  454. * alignment of 1 (no alignment) and native endianness.
  455. *
  456. * Alignment works as follows: For each option, the format gets extra padding
  457. * until the data starts at an offset that is a multiple of the minimum
  458. * between the option size and the maximum alignment; this minimum must be a
  459. * power of 2. Options "c" and "z" are not aligned; option "s" follows the
  460. * alignment of its starting integer.
  461. *
  462. * All padding is filled with zeros by string.pack (and ignored by unpack).
  463. */
  464. LUA_FUNCTION_DEF (util, pack);
  465. /***
  466. * @function util.packsize(fmt)
  467. *
  468. * Returns size of the packed binary string returned for the same `fmt` argument
  469. * by @see util.pack
  470. */
  471. LUA_FUNCTION_DEF (util, packsize);
  472. /***
  473. * @function util.unpack(fmt, s [, pos])
  474. * Unpacks string `s` according to the format string `fmt` as described in
  475. * @see util.pack
  476. *
  477. * @returns {multiple} list of unpacked values according to `fmt`
  478. */
  479. LUA_FUNCTION_DEF (util, unpack);
  480. /***
  481. * @function util.caseless_hash(str[, seed])
  482. * Calculates caseless non-crypto hash from a string or rspamd text
  483. * @param str string or lua_text
  484. * @param seed mandatory seed (0xdeadbabe by default)
  485. * @return {int64} boxed int64_t
  486. */
  487. LUA_FUNCTION_DEF (util, caseless_hash);
  488. /***
  489. * @function util.caseless_hash_fast(str[, seed])
  490. * Calculates caseless non-crypto hash from a string or rspamd text
  491. * @param str string or lua_text
  492. * @param seed mandatory seed (0xdeadbabe by default)
  493. * @return {number} number from int64_t
  494. */
  495. LUA_FUNCTION_DEF (util, caseless_hash_fast);
  496. /***
  497. * @function util.get_hostname()
  498. * Returns hostname for this machine
  499. * @return {string} hostname
  500. */
  501. LUA_FUNCTION_DEF (util, get_hostname);
  502. /***
  503. * @function util.parse_content_type(ct_string, mempool)
  504. * Parses content-type string to a table:
  505. * - `type`
  506. * - `subtype`
  507. * - `charset`
  508. * - `boundary`
  509. * - other attributes
  510. *
  511. * @param {string} ct_string content type as string
  512. * @param {rspamd_mempool} mempool needed to store temporary data (e.g. task pool)
  513. * @return table or nil if cannot parse content type
  514. */
  515. LUA_FUNCTION_DEF (util, parse_content_type);
  516. /***
  517. * @function util.mime_header_encode(hdr)
  518. * Encodes header if needed
  519. * @param {string} hdr input header
  520. * @return encoded header
  521. */
  522. LUA_FUNCTION_DEF (util, mime_header_encode);
  523. static const struct luaL_reg utillib_f[] = {
  524. LUA_INTERFACE_DEF (util, create_event_base),
  525. LUA_INTERFACE_DEF (util, load_rspamd_config),
  526. LUA_INTERFACE_DEF (util, config_from_ucl),
  527. LUA_INTERFACE_DEF (util, process_message),
  528. LUA_INTERFACE_DEF (util, encode_base64),
  529. LUA_INTERFACE_DEF (util, encode_qp),
  530. LUA_INTERFACE_DEF (util, decode_base64),
  531. LUA_INTERFACE_DEF (util, encode_base32),
  532. LUA_INTERFACE_DEF (util, decode_base32),
  533. LUA_INTERFACE_DEF (util, decode_url),
  534. LUA_INTERFACE_DEF (util, tokenize_text),
  535. LUA_INTERFACE_DEF (util, tanh),
  536. LUA_INTERFACE_DEF (util, parse_html),
  537. LUA_INTERFACE_DEF (util, levenshtein_distance),
  538. LUA_INTERFACE_DEF (util, parse_addr),
  539. LUA_INTERFACE_DEF (util, fold_header),
  540. LUA_INTERFACE_DEF (util, is_uppercase),
  541. LUA_INTERFACE_DEF (util, humanize_number),
  542. LUA_INTERFACE_DEF (util, get_tld),
  543. LUA_INTERFACE_DEF (util, glob),
  544. LUA_INTERFACE_DEF (util, parse_mail_address),
  545. LUA_INTERFACE_DEF (util, strlen_utf8),
  546. LUA_INTERFACE_DEF (util, strcasecmp_ascii),
  547. LUA_INTERFACE_DEF (util, strequal_caseless),
  548. LUA_INTERFACE_DEF (util, get_ticks),
  549. LUA_INTERFACE_DEF (util, get_time),
  550. LUA_INTERFACE_DEF (util, time_to_string),
  551. LUA_INTERFACE_DEF (util, stat),
  552. LUA_INTERFACE_DEF (util, unlink),
  553. LUA_INTERFACE_DEF (util, lock_file),
  554. LUA_INTERFACE_DEF (util, unlock_file),
  555. LUA_INTERFACE_DEF (util, create_file),
  556. LUA_INTERFACE_DEF (util, close_file),
  557. LUA_INTERFACE_DEF (util, random_hex),
  558. LUA_INTERFACE_DEF (util, zstd_compress),
  559. LUA_INTERFACE_DEF (util, zstd_decompress),
  560. LUA_INTERFACE_DEF (util, gzip_compress),
  561. LUA_INTERFACE_DEF (util, gzip_decompress),
  562. LUA_INTERFACE_DEF (util, normalize_prob),
  563. LUA_INTERFACE_DEF (util, caseless_hash),
  564. LUA_INTERFACE_DEF (util, caseless_hash_fast),
  565. LUA_INTERFACE_DEF (util, is_utf_spoofed),
  566. LUA_INTERFACE_DEF (util, is_valid_utf8),
  567. LUA_INTERFACE_DEF (util, has_obscured_unicode),
  568. LUA_INTERFACE_DEF (util, readline),
  569. LUA_INTERFACE_DEF (util, readpassphrase),
  570. LUA_INTERFACE_DEF (util, file_exists),
  571. LUA_INTERFACE_DEF (util, mkdir),
  572. LUA_INTERFACE_DEF (util, umask),
  573. LUA_INTERFACE_DEF (util, isatty),
  574. LUA_INTERFACE_DEF (util, get_hostname),
  575. LUA_INTERFACE_DEF (util, parse_content_type),
  576. LUA_INTERFACE_DEF (util, mime_header_encode),
  577. LUA_INTERFACE_DEF (util, pack),
  578. LUA_INTERFACE_DEF (util, unpack),
  579. LUA_INTERFACE_DEF (util, packsize),
  580. {NULL, NULL}
  581. };
  582. LUA_FUNCTION_DEF (int64, tostring);
  583. LUA_FUNCTION_DEF (int64, tonumber);
  584. LUA_FUNCTION_DEF (int64, hex);
  585. static const struct luaL_reg int64lib_m[] = {
  586. LUA_INTERFACE_DEF (int64, tostring),
  587. LUA_INTERFACE_DEF (int64, tonumber),
  588. LUA_INTERFACE_DEF (int64, hex),
  589. {"__tostring", lua_int64_tostring},
  590. {NULL, NULL}
  591. };
  592. LUA_FUNCTION_DEF (ev_base, loop);
  593. static const struct luaL_reg ev_baselib_m[] = {
  594. LUA_INTERFACE_DEF (ev_base, loop),
  595. {"__tostring", rspamd_lua_class_tostring},
  596. {NULL, NULL}
  597. };
  598. static gint64
  599. lua_check_int64 (lua_State * L, gint pos)
  600. {
  601. void *ud = rspamd_lua_check_udata (L, pos, "rspamd{int64}");
  602. luaL_argcheck (L, ud != NULL, pos, "'int64' expected");
  603. return ud ? *((gint64 *)ud) : 0LL;
  604. }
  605. static gint
  606. lua_util_create_event_base (lua_State *L)
  607. {
  608. LUA_TRACE_POINT;
  609. struct event_base **pev_base;
  610. pev_base = lua_newuserdata (L, sizeof (struct event_base *));
  611. rspamd_lua_setclass (L, "rspamd{ev_base}", -1);
  612. *pev_base = event_init ();
  613. return 1;
  614. }
  615. static gint
  616. lua_util_load_rspamd_config (lua_State *L)
  617. {
  618. LUA_TRACE_POINT;
  619. struct rspamd_config *cfg, **pcfg;
  620. const gchar *cfg_name;
  621. cfg_name = luaL_checkstring (L, 1);
  622. if (cfg_name) {
  623. cfg = rspamd_config_new (RSPAMD_CONFIG_INIT_SKIP_LUA);
  624. cfg->lua_state = L;
  625. if (rspamd_config_read (cfg, cfg_name, NULL, NULL, NULL)) {
  626. msg_err_config ("cannot load config from %s", cfg_name);
  627. lua_pushnil (L);
  628. }
  629. else {
  630. rspamd_config_post_load (cfg, 0);
  631. pcfg = lua_newuserdata (L, sizeof (struct rspamd_config *));
  632. rspamd_lua_setclass (L, "rspamd{config}", -1);
  633. *pcfg = cfg;
  634. }
  635. }
  636. return 1;
  637. }
  638. static gint
  639. parse_config_options (const char *str_options)
  640. {
  641. gint ret = 0;
  642. gchar **vec;
  643. const gchar *str;
  644. guint i, l;
  645. vec = g_strsplit_set (str_options, ",;", -1);
  646. if (vec) {
  647. l = g_strv_length (vec);
  648. for (i = 0; i < l; i ++) {
  649. str = vec[i];
  650. if (g_ascii_strcasecmp (str, "INIT_URL") == 0) {
  651. ret |= RSPAMD_CONFIG_INIT_URL;
  652. } else if (g_ascii_strcasecmp (str, "INIT_LIBS") == 0) {
  653. ret |= RSPAMD_CONFIG_INIT_LIBS;
  654. } else if (g_ascii_strcasecmp (str, "INIT_SYMCACHE") == 0) {
  655. ret |= RSPAMD_CONFIG_INIT_SYMCACHE;
  656. } else if (g_ascii_strcasecmp (str, "INIT_VALIDATE") == 0) {
  657. ret |= RSPAMD_CONFIG_INIT_VALIDATE;
  658. } else if (g_ascii_strcasecmp (str, "INIT_NO_TLD") == 0) {
  659. ret |= RSPAMD_CONFIG_INIT_NO_TLD;
  660. } else if (g_ascii_strcasecmp (str, "INIT_PRELOAD_MAPS") == 0) {
  661. ret |= RSPAMD_CONFIG_INIT_PRELOAD_MAPS;
  662. } else {
  663. msg_warn ("bad type: %s", str);
  664. }
  665. }
  666. g_strfreev (vec);
  667. }
  668. return ret;
  669. }
  670. static gint
  671. lua_util_config_from_ucl (lua_State *L)
  672. {
  673. LUA_TRACE_POINT;
  674. struct rspamd_config *cfg = NULL, **pcfg;
  675. struct rspamd_rcl_section *top;
  676. GError *err = NULL;
  677. ucl_object_t *obj;
  678. const char *str_options = NULL;
  679. gint int_options = 0;
  680. obj = ucl_object_lua_import (L, 1);
  681. if (lua_gettop (L) == 2) {
  682. if (lua_type (L, 2) == LUA_TSTRING) {
  683. str_options = lua_tostring (L, 2);
  684. int_options = parse_config_options(str_options);
  685. }
  686. else {
  687. msg_err ("config_from_ucl: second parameter is expected to be string");
  688. ucl_object_unref (obj);
  689. lua_pushnil (L);
  690. }
  691. }
  692. if (obj) {
  693. cfg = rspamd_config_new (RSPAMD_CONFIG_INIT_SKIP_LUA);
  694. cfg->lua_state = L;
  695. cfg->rcl_obj = obj;
  696. cfg->cache = rspamd_symcache_new (cfg);
  697. top = rspamd_rcl_config_init (cfg, NULL);
  698. if (!rspamd_rcl_parse (top, cfg, cfg, cfg->cfg_pool, cfg->rcl_obj, &err)) {
  699. msg_err ("rcl parse error: %s", err->message);
  700. ucl_object_unref (obj);
  701. lua_pushnil (L);
  702. }
  703. else {
  704. if (int_options & RSPAMD_CONFIG_INIT_LIBS) {
  705. cfg->libs_ctx = rspamd_init_libs ();
  706. }
  707. rspamd_config_post_load (cfg, int_options);
  708. pcfg = lua_newuserdata (L, sizeof (struct rspamd_config *));
  709. rspamd_lua_setclass (L, "rspamd{config}", -1);
  710. *pcfg = cfg;
  711. }
  712. }
  713. return 1;
  714. }
  715. static gboolean
  716. lua_util_task_fin (struct rspamd_task *task, void *ud)
  717. {
  718. ucl_object_t **target = ud;
  719. *target = rspamd_protocol_write_ucl (task, RSPAMD_PROTOCOL_DEFAULT);
  720. rdns_resolver_release (task->resolver->r);
  721. return TRUE;
  722. }
  723. static gint
  724. lua_util_process_message (lua_State *L)
  725. {
  726. LUA_TRACE_POINT;
  727. struct rspamd_config *cfg = lua_check_config (L, 1);
  728. const gchar *message;
  729. gsize mlen;
  730. struct rspamd_task *task;
  731. struct event_base *base;
  732. ucl_object_t *res = NULL;
  733. message = luaL_checklstring (L, 2, &mlen);
  734. if (cfg != NULL && message != NULL) {
  735. base = event_init ();
  736. rspamd_init_filters (cfg, FALSE);
  737. task = rspamd_task_new (NULL, cfg, NULL, NULL, base);
  738. task->msg.begin = rspamd_mempool_alloc (task->task_pool, mlen);
  739. rspamd_strlcpy ((gpointer)task->msg.begin, message, mlen);
  740. task->msg.len = mlen;
  741. task->fin_callback = lua_util_task_fin;
  742. task->fin_arg = &res;
  743. task->resolver = dns_resolver_init (NULL, base, cfg);
  744. task->s = rspamd_session_create (task->task_pool, rspamd_task_fin,
  745. rspamd_task_restore, (event_finalizer_t)rspamd_task_free, task);
  746. if (!rspamd_task_load_message (task, NULL, message, mlen)) {
  747. lua_pushnil (L);
  748. }
  749. else {
  750. if (rspamd_task_process (task, RSPAMD_TASK_PROCESS_ALL)) {
  751. event_base_loop (base, 0);
  752. if (res != NULL) {
  753. ucl_object_push_lua (L, res, true);
  754. ucl_object_unref (res);
  755. }
  756. else {
  757. ucl_object_push_lua (L,
  758. rspamd_protocol_write_ucl (task, RSPAMD_PROTOCOL_DEFAULT),
  759. true);
  760. rdns_resolver_release (task->resolver->r);
  761. rspamd_session_destroy (task->s);
  762. }
  763. }
  764. else {
  765. lua_pushnil (L);
  766. }
  767. }
  768. event_base_free (base);
  769. }
  770. else {
  771. lua_pushnil (L);
  772. }
  773. return 1;
  774. }
  775. static gint
  776. lua_util_encode_base64 (lua_State *L)
  777. {
  778. LUA_TRACE_POINT;
  779. struct rspamd_lua_text *t;
  780. const gchar *s = NULL;
  781. gchar *out;
  782. gsize inlen, outlen;
  783. guint str_lim = 0;
  784. gboolean fold = FALSE;
  785. if (lua_type (L, 1) == LUA_TSTRING) {
  786. s = luaL_checklstring (L, 1, &inlen);
  787. }
  788. else if (lua_type (L, 1) == LUA_TUSERDATA) {
  789. t = lua_check_text (L, 1);
  790. if (t != NULL) {
  791. s = t->start;
  792. inlen = t->len;
  793. }
  794. }
  795. if (lua_gettop (L) > 1) {
  796. str_lim = luaL_checknumber (L, 2);
  797. fold = !!(str_lim > 0);
  798. }
  799. if (s == NULL) {
  800. lua_pushnil (L);
  801. }
  802. else {
  803. if (fold) {
  804. out = rspamd_encode_base64 (s, inlen, str_lim, &outlen);
  805. }
  806. else {
  807. enum rspamd_newlines_type how = RSPAMD_TASK_NEWLINES_CRLF;
  808. if (lua_type (L, 3) == LUA_TSTRING) {
  809. const gchar *how_str = lua_tostring (L, 3);
  810. if (g_ascii_strcasecmp (how_str, "cr") == 0) {
  811. how = RSPAMD_TASK_NEWLINES_CR;
  812. }
  813. else if (g_ascii_strcasecmp (how_str, "lf") == 0) {
  814. how = RSPAMD_TASK_NEWLINES_LF;
  815. }
  816. else if (g_ascii_strcasecmp (how_str, "crlf") != 0) {
  817. return luaL_error (L, "invalid newline style: %s", how_str);
  818. }
  819. }
  820. out = rspamd_encode_base64_fold (s, inlen, str_lim, &outlen, how);
  821. }
  822. if (out != NULL) {
  823. t = lua_newuserdata (L, sizeof (*t));
  824. rspamd_lua_setclass (L, "rspamd{text}", -1);
  825. t->start = out;
  826. t->len = outlen;
  827. /* Need destruction */
  828. t->flags = RSPAMD_TEXT_FLAG_OWN;
  829. }
  830. else {
  831. lua_pushnil (L);
  832. }
  833. }
  834. return 1;
  835. }
  836. static gint
  837. lua_util_encode_qp (lua_State *L)
  838. {
  839. LUA_TRACE_POINT;
  840. struct rspamd_lua_text *t;
  841. const gchar *s = NULL;
  842. gchar *out;
  843. gsize inlen, outlen;
  844. guint str_lim = 0;
  845. if (lua_type (L, 1) == LUA_TSTRING) {
  846. s = luaL_checklstring (L, 1, &inlen);
  847. }
  848. else if (lua_type (L, 1) == LUA_TUSERDATA) {
  849. t = lua_check_text (L, 1);
  850. if (t != NULL) {
  851. s = t->start;
  852. inlen = t->len;
  853. }
  854. }
  855. if (lua_gettop (L) > 1) {
  856. str_lim = luaL_checknumber (L, 2);
  857. }
  858. if (s == NULL) {
  859. lua_pushnil (L);
  860. }
  861. else {
  862. enum rspamd_newlines_type how = RSPAMD_TASK_NEWLINES_CRLF;
  863. if (lua_type (L, 3) == LUA_TSTRING) {
  864. const gchar *how_str = lua_tostring (L, 3);
  865. if (g_ascii_strcasecmp (how_str, "cr") == 0) {
  866. how = RSPAMD_TASK_NEWLINES_CR;
  867. }
  868. else if (g_ascii_strcasecmp (how_str, "lf") == 0) {
  869. how = RSPAMD_TASK_NEWLINES_LF;
  870. }
  871. else if (g_ascii_strcasecmp (how_str, "crlf") != 0) {
  872. return luaL_error (L, "invalid newline style: %s", how_str);
  873. }
  874. }
  875. out = rspamd_encode_qp_fold (s, inlen, str_lim, &outlen, how);
  876. if (out != NULL) {
  877. t = lua_newuserdata (L, sizeof (*t));
  878. rspamd_lua_setclass (L, "rspamd{text}", -1);
  879. t->start = out;
  880. t->len = outlen;
  881. /* Need destruction */
  882. t->flags = RSPAMD_TEXT_FLAG_OWN;
  883. }
  884. else {
  885. lua_pushnil (L);
  886. }
  887. }
  888. return 1;
  889. }
  890. static gint
  891. lua_util_decode_base64 (lua_State *L)
  892. {
  893. LUA_TRACE_POINT;
  894. struct rspamd_lua_text *t;
  895. const gchar *s = NULL;
  896. gsize inlen, outlen;
  897. gboolean zero_copy = FALSE, grab_own = FALSE;
  898. gint state = 0;
  899. guint save = 0;
  900. if (lua_type (L, 1) == LUA_TSTRING) {
  901. s = luaL_checklstring (L, 1, &inlen);
  902. }
  903. else if (lua_type (L, 1) == LUA_TUSERDATA) {
  904. t = lua_check_text (L, 1);
  905. if (t != NULL) {
  906. s = t->start;
  907. inlen = t->len;
  908. }
  909. }
  910. if (s != NULL) {
  911. if (zero_copy) {
  912. /* Decode in place */
  913. outlen = g_base64_decode_step (s, inlen, (guchar *)s, &state, &save);
  914. t = lua_newuserdata (L, sizeof (*t));
  915. rspamd_lua_setclass (L, "rspamd{text}", -1);
  916. t->start = s;
  917. t->len = outlen;
  918. if (grab_own) {
  919. t->flags |= RSPAMD_TEXT_FLAG_OWN;
  920. }
  921. else {
  922. t->flags = 0;
  923. }
  924. }
  925. else {
  926. t = lua_newuserdata (L, sizeof (*t));
  927. rspamd_lua_setclass (L, "rspamd{text}", -1);
  928. t->len = (inlen / 4) * 3 + 3;
  929. t->start = g_malloc (t->len);
  930. outlen = g_base64_decode_step (s, inlen, (guchar *)t->start,
  931. &state, &save);
  932. t->len = outlen;
  933. t->flags = RSPAMD_TEXT_FLAG_OWN;
  934. }
  935. }
  936. else {
  937. lua_pushnil (L);
  938. }
  939. return 1;
  940. }
  941. static gint
  942. lua_util_encode_base32 (lua_State *L)
  943. {
  944. LUA_TRACE_POINT;
  945. struct rspamd_lua_text *t;
  946. const gchar *s = NULL;
  947. gchar *out;
  948. gsize inlen, outlen;
  949. if (lua_type (L, 1) == LUA_TSTRING) {
  950. s = luaL_checklstring (L, 1, &inlen);
  951. }
  952. else if (lua_type (L, 1) == LUA_TUSERDATA) {
  953. t = lua_check_text (L, 1);
  954. if (t != NULL) {
  955. s = t->start;
  956. inlen = t->len;
  957. }
  958. }
  959. if (s == NULL) {
  960. lua_pushnil (L);
  961. }
  962. else {
  963. out = rspamd_encode_base32 (s, inlen);
  964. if (out != NULL) {
  965. t = lua_newuserdata (L, sizeof (*t));
  966. outlen = strlen (out);
  967. rspamd_lua_setclass (L, "rspamd{text}", -1);
  968. t->start = out;
  969. t->len = outlen;
  970. /* Need destruction */
  971. t->flags = RSPAMD_TEXT_FLAG_OWN;
  972. }
  973. else {
  974. lua_pushnil (L);
  975. }
  976. }
  977. return 1;
  978. }
  979. static gint
  980. lua_util_decode_base32 (lua_State *L)
  981. {
  982. LUA_TRACE_POINT;
  983. struct rspamd_lua_text *t;
  984. const gchar *s = NULL;
  985. gsize inlen, outlen;
  986. if (lua_type (L, 1) == LUA_TSTRING) {
  987. s = luaL_checklstring (L, 1, &inlen);
  988. }
  989. else if (lua_type (L, 1) == LUA_TUSERDATA) {
  990. t = lua_check_text (L, 1);
  991. if (t != NULL) {
  992. s = t->start;
  993. inlen = t->len;
  994. }
  995. }
  996. if (s != NULL) {
  997. t = lua_newuserdata (L, sizeof (*t));
  998. rspamd_lua_setclass (L, "rspamd{text}", -1);
  999. t->start = rspamd_decode_base32 (s, inlen, &outlen);
  1000. t->len = outlen;
  1001. t->flags = RSPAMD_TEXT_FLAG_OWN;
  1002. }
  1003. else {
  1004. lua_pushnil (L);
  1005. }
  1006. return 1;
  1007. }
  1008. static gint
  1009. lua_util_decode_url (lua_State *L)
  1010. {
  1011. LUA_TRACE_POINT;
  1012. struct rspamd_lua_text *t;
  1013. const gchar *s = NULL;
  1014. gsize inlen;
  1015. if (lua_type (L, 1) == LUA_TSTRING) {
  1016. s = luaL_checklstring (L, 1, &inlen);
  1017. }
  1018. else if (lua_type (L, 1) == LUA_TUSERDATA) {
  1019. t = lua_check_text (L, 1);
  1020. if (t != NULL) {
  1021. s = t->start;
  1022. inlen = t->len;
  1023. }
  1024. }
  1025. if (s != NULL) {
  1026. t = lua_newuserdata (L, sizeof (*t));
  1027. rspamd_lua_setclass (L, "rspamd{text}", -1);
  1028. t->start = g_malloc (inlen);
  1029. memcpy ((char *)t->start, s, inlen);
  1030. t->len = rspamd_url_decode ((char *)t->start, s, inlen);
  1031. t->flags = RSPAMD_TEXT_FLAG_OWN;
  1032. }
  1033. else {
  1034. lua_pushnil (L);
  1035. }
  1036. return 1;
  1037. }
  1038. static gint
  1039. lua_util_tokenize_text (lua_State *L)
  1040. {
  1041. LUA_TRACE_POINT;
  1042. const gchar *in = NULL;
  1043. gsize len = 0, pos, ex_len, i;
  1044. GList *exceptions = NULL, *cur;
  1045. struct rspamd_lua_text *t;
  1046. struct rspamd_process_exception *ex;
  1047. UText utxt = UTEXT_INITIALIZER;
  1048. GArray *res;
  1049. rspamd_stat_token_t *w;
  1050. if (lua_type (L, 1) == LUA_TSTRING) {
  1051. in = luaL_checklstring (L, 1, &len);
  1052. }
  1053. else if (lua_type (L, 1) == LUA_TUSERDATA) {
  1054. t = lua_check_text (L, 1);
  1055. if (t) {
  1056. in = t->start;
  1057. len = t->len;
  1058. }
  1059. }
  1060. if (in == NULL) {
  1061. lua_pushnil (L);
  1062. return 1;
  1063. }
  1064. if (lua_gettop (L) > 1 && lua_type (L, 2) == LUA_TTABLE) {
  1065. lua_pushvalue (L, 2);
  1066. lua_pushnil (L);
  1067. while (lua_next (L, -2) != 0) {
  1068. if (lua_type (L, -1) == LUA_TTABLE) {
  1069. lua_rawgeti (L, -1, 1);
  1070. pos = luaL_checknumber (L, -1);
  1071. lua_pop (L, 1);
  1072. lua_rawgeti (L, -1, 2);
  1073. ex_len = luaL_checknumber (L, -1);
  1074. lua_pop (L, 1);
  1075. if (ex_len > 0) {
  1076. ex = g_malloc0 (sizeof (*ex));
  1077. ex->pos = pos;
  1078. ex->len = ex_len;
  1079. ex->type = RSPAMD_EXCEPTION_GENERIC;
  1080. exceptions = g_list_prepend (exceptions, ex);
  1081. }
  1082. }
  1083. lua_pop (L, 1);
  1084. }
  1085. lua_pop (L, 1);
  1086. }
  1087. if (exceptions) {
  1088. exceptions = g_list_reverse (exceptions);
  1089. }
  1090. UErrorCode uc_err = U_ZERO_ERROR;
  1091. utext_openUTF8 (&utxt,
  1092. in,
  1093. len,
  1094. &uc_err);
  1095. res = rspamd_tokenize_text ((gchar *)in, len,
  1096. &utxt,
  1097. RSPAMD_TOKENIZE_UTF, NULL,
  1098. exceptions,
  1099. NULL, NULL);
  1100. if (res == NULL) {
  1101. lua_pushnil (L);
  1102. }
  1103. else {
  1104. lua_createtable (L, res->len, 0);
  1105. for (i = 0; i < res->len; i ++) {
  1106. w = &g_array_index (res, rspamd_stat_token_t, i);
  1107. lua_pushlstring (L, w->original.begin, w->original.len);
  1108. lua_rawseti (L, -2, i + 1);
  1109. }
  1110. }
  1111. cur = exceptions;
  1112. while (cur) {
  1113. ex = cur->data;
  1114. g_free (ex);
  1115. cur = g_list_next (cur);
  1116. }
  1117. g_list_free (exceptions);
  1118. utext_close (&utxt);
  1119. return 1;
  1120. }
  1121. static gint
  1122. lua_util_tanh (lua_State *L)
  1123. {
  1124. LUA_TRACE_POINT;
  1125. gdouble in = luaL_checknumber (L, 1);
  1126. lua_pushnumber (L, tanh (in));
  1127. return 1;
  1128. }
  1129. static gint
  1130. lua_util_parse_html (lua_State *L)
  1131. {
  1132. LUA_TRACE_POINT;
  1133. struct rspamd_lua_text *t;
  1134. const gchar *start = NULL;
  1135. gsize len;
  1136. GByteArray *res, *in;
  1137. rspamd_mempool_t *pool;
  1138. struct html_content *hc;
  1139. if (lua_type (L, 1) == LUA_TUSERDATA) {
  1140. t = lua_check_text (L, 1);
  1141. if (t != NULL) {
  1142. start = t->start;
  1143. len = t->len;
  1144. }
  1145. }
  1146. else if (lua_type (L, 1) == LUA_TSTRING) {
  1147. start = luaL_checklstring (L, 1, &len);
  1148. }
  1149. if (start != NULL) {
  1150. pool = rspamd_mempool_new (rspamd_mempool_suggest_size (), NULL);
  1151. hc = rspamd_mempool_alloc0 (pool, sizeof (*hc));
  1152. in = g_byte_array_sized_new (len);
  1153. g_byte_array_append (in, start, len);
  1154. res = rspamd_html_process_part (pool, hc, in);
  1155. t = lua_newuserdata (L, sizeof (*t));
  1156. rspamd_lua_setclass (L, "rspamd{text}", -1);
  1157. t->start = res->data;
  1158. t->len = res->len;
  1159. t->flags = RSPAMD_TEXT_FLAG_OWN;
  1160. g_byte_array_free (res, FALSE);
  1161. g_byte_array_free (in, TRUE);
  1162. rspamd_mempool_delete (pool);
  1163. }
  1164. else {
  1165. lua_pushnil (L);
  1166. }
  1167. return 1;
  1168. }
  1169. static gint
  1170. lua_util_levenshtein_distance (lua_State *L)
  1171. {
  1172. LUA_TRACE_POINT;
  1173. const gchar *s1, *s2;
  1174. gsize s1len, s2len;
  1175. gint dist = 0;
  1176. guint replace_cost = 1;
  1177. s1 = luaL_checklstring (L, 1, &s1len);
  1178. s2 = luaL_checklstring (L, 2, &s2len);
  1179. if (lua_isnumber (L, 3)) {
  1180. replace_cost = lua_tonumber (L, 3);
  1181. }
  1182. if (s1 && s2) {
  1183. dist = rspamd_strings_levenshtein_distance (s1, s1len, s2, s2len,
  1184. replace_cost);
  1185. }
  1186. lua_pushinteger (L, dist);
  1187. return 1;
  1188. }
  1189. static gint
  1190. lua_util_parse_addr (lua_State *L)
  1191. {
  1192. LUA_TRACE_POINT;
  1193. GPtrArray *addrs;
  1194. gsize len;
  1195. const gchar *str = luaL_checklstring (L, 1, &len);
  1196. rspamd_mempool_t *pool;
  1197. gboolean own_pool = FALSE;
  1198. if (str) {
  1199. if (lua_type (L, 2) == LUA_TUSERDATA) {
  1200. pool = rspamd_lua_check_mempool (L, 2);
  1201. if (pool == NULL) {
  1202. return luaL_error (L, "invalid arguments");
  1203. }
  1204. }
  1205. else {
  1206. pool = rspamd_mempool_new (rspamd_mempool_suggest_size (), "lua util");
  1207. own_pool = TRUE;
  1208. }
  1209. addrs = rspamd_email_address_from_mime (pool, str, len, NULL);
  1210. if (addrs == NULL) {
  1211. lua_pushnil (L);
  1212. }
  1213. else {
  1214. lua_push_emails_address_list (L, addrs);
  1215. }
  1216. if (own_pool) {
  1217. rspamd_mempool_delete (pool);
  1218. }
  1219. }
  1220. else {
  1221. lua_pushnil (L);
  1222. }
  1223. return 1;
  1224. }
  1225. static gint
  1226. lua_util_fold_header (lua_State *L)
  1227. {
  1228. LUA_TRACE_POINT;
  1229. const gchar *name, *value, *how, *stop_chars = NULL;
  1230. GString *folded;
  1231. name = luaL_checkstring (L, 1);
  1232. value = luaL_checkstring (L, 2);
  1233. if (name && value) {
  1234. if (lua_isstring (L, 3)) {
  1235. how = lua_tostring (L, 3);
  1236. if (lua_isstring (L, 4)) {
  1237. stop_chars = lua_tostring (L, 4);
  1238. }
  1239. if (strcmp (how, "cr") == 0) {
  1240. folded = rspamd_header_value_fold (name, value, 0,
  1241. RSPAMD_TASK_NEWLINES_CR, stop_chars);
  1242. }
  1243. else if (strcmp (how, "lf") == 0) {
  1244. folded = rspamd_header_value_fold (name, value, 0,
  1245. RSPAMD_TASK_NEWLINES_LF, stop_chars);
  1246. }
  1247. else {
  1248. folded = rspamd_header_value_fold (name, value, 0,
  1249. RSPAMD_TASK_NEWLINES_CRLF, stop_chars);
  1250. }
  1251. }
  1252. else {
  1253. folded = rspamd_header_value_fold (name, value, 0,
  1254. RSPAMD_TASK_NEWLINES_CRLF, stop_chars);
  1255. }
  1256. if (folded) {
  1257. lua_pushlstring (L, folded->str, folded->len);
  1258. g_string_free (folded, TRUE);
  1259. return 1;
  1260. }
  1261. }
  1262. lua_pushnil (L);
  1263. return 1;
  1264. }
  1265. static gint
  1266. lua_util_is_uppercase (lua_State *L)
  1267. {
  1268. LUA_TRACE_POINT;
  1269. const gchar *str;
  1270. gsize sz;
  1271. gint32 i = 0;
  1272. UChar32 uc;
  1273. guint nlc = 0, nuc = 0;
  1274. str = luaL_checklstring (L, 1, &sz);
  1275. if (str && sz > 0) {
  1276. while (i >= 0 && i < sz) {
  1277. U8_NEXT (str, i, sz, uc);
  1278. if (uc < 0) {
  1279. break;
  1280. }
  1281. if (u_isupper (uc)) {
  1282. nuc++;
  1283. }
  1284. else if (u_islower (uc)) {
  1285. nlc++;
  1286. }
  1287. }
  1288. }
  1289. if (nuc > 0 && nlc == 0) {
  1290. lua_pushboolean (L, TRUE);
  1291. }
  1292. else {
  1293. lua_pushboolean (L, FALSE);
  1294. }
  1295. return 1;
  1296. }
  1297. static gint
  1298. lua_util_humanize_number (lua_State *L)
  1299. {
  1300. LUA_TRACE_POINT;
  1301. gdouble number = luaL_checknumber (L, 1);
  1302. gchar numbuf[32];
  1303. rspamd_snprintf (numbuf, sizeof (numbuf), "%hL", (gint64)number);
  1304. lua_pushstring (L, numbuf);
  1305. return 1;
  1306. }
  1307. static gint
  1308. lua_util_get_tld (lua_State *L)
  1309. {
  1310. LUA_TRACE_POINT;
  1311. const gchar *host;
  1312. gsize hostlen;
  1313. rspamd_ftok_t tld;
  1314. host = luaL_checklstring (L, 1, &hostlen);
  1315. if (host) {
  1316. if (!rspamd_url_find_tld (host, hostlen, &tld)) {
  1317. lua_pushlstring (L, host, hostlen);
  1318. }
  1319. else {
  1320. lua_pushlstring (L, tld.begin, tld.len);
  1321. }
  1322. }
  1323. else {
  1324. lua_pushnil (L);
  1325. }
  1326. return 1;
  1327. }
  1328. static gint
  1329. lua_util_glob (lua_State *L)
  1330. {
  1331. LUA_TRACE_POINT;
  1332. const gchar *pattern;
  1333. glob_t gl;
  1334. gint top, i, flags;
  1335. top = lua_gettop (L);
  1336. memset (&gl, 0, sizeof (gl));
  1337. flags = GLOB_NOSORT;
  1338. for (i = 1; i <= top; i ++, flags |= GLOB_APPEND) {
  1339. pattern = luaL_checkstring (L, i);
  1340. if (pattern) {
  1341. glob (pattern, flags, NULL, &gl);
  1342. }
  1343. }
  1344. lua_createtable (L, gl.gl_pathc, 0);
  1345. /* Push results */
  1346. for (i = 0; i < (gint)gl.gl_pathc; i ++) {
  1347. lua_pushstring (L, gl.gl_pathv[i]);
  1348. lua_rawseti (L, -2, i + 1);
  1349. }
  1350. globfree (&gl);
  1351. return 1;
  1352. }
  1353. static gint
  1354. lua_util_parse_mail_address (lua_State *L)
  1355. {
  1356. LUA_TRACE_POINT;
  1357. GPtrArray *addrs;
  1358. gsize len;
  1359. const gchar *str = luaL_checklstring (L, 1, &len);
  1360. rspamd_mempool_t *pool;
  1361. gboolean own_pool = FALSE;
  1362. if (str) {
  1363. if (lua_type (L, 2) == LUA_TUSERDATA) {
  1364. pool = rspamd_lua_check_mempool (L, 2);
  1365. if (pool == NULL) {
  1366. return luaL_error (L, "invalid arguments");
  1367. }
  1368. }
  1369. else {
  1370. pool = rspamd_mempool_new (rspamd_mempool_suggest_size (), "lua util");
  1371. own_pool = TRUE;
  1372. }
  1373. addrs = rspamd_email_address_from_mime (pool, str, len, NULL);
  1374. if (addrs == NULL) {
  1375. lua_pushnil (L);
  1376. }
  1377. else {
  1378. lua_push_emails_address_list (L, addrs);
  1379. }
  1380. if (own_pool) {
  1381. rspamd_mempool_delete (pool);
  1382. }
  1383. }
  1384. else {
  1385. lua_pushnil (L);
  1386. }
  1387. return 1;
  1388. }
  1389. static gint
  1390. lua_util_strlen_utf8 (lua_State *L)
  1391. {
  1392. LUA_TRACE_POINT;
  1393. const gchar *str, *end;
  1394. gsize len;
  1395. str = lua_tolstring (L, 1, &len);
  1396. if (str) {
  1397. if (g_utf8_validate (str, len, &end)) {
  1398. len = g_utf8_strlen (str, len);
  1399. }
  1400. else if (end != NULL && end > str) {
  1401. len = (g_utf8_strlen (str, end - str)) /* UTF part */
  1402. + (len - (end - str)) /* raw part */;
  1403. }
  1404. lua_pushinteger (L, len);
  1405. }
  1406. else {
  1407. return luaL_error (L, "invalid arguments");
  1408. }
  1409. return 1;
  1410. }
  1411. static gint
  1412. lua_util_strcasecmp_ascii (lua_State *L)
  1413. {
  1414. LUA_TRACE_POINT;
  1415. const gchar *str1, *str2;
  1416. gsize len1, len2;
  1417. gint ret = -1;
  1418. str1 = lua_tolstring (L, 1, &len1);
  1419. str2 = lua_tolstring (L, 2, &len2);
  1420. if (str1 && str2) {
  1421. if (len1 == len2) {
  1422. ret = g_ascii_strncasecmp (str1, str2, len1);
  1423. }
  1424. else {
  1425. ret = len1 - len2;
  1426. }
  1427. }
  1428. else {
  1429. return luaL_error (L, "invalid arguments");
  1430. }
  1431. lua_pushinteger (L, ret);
  1432. return 1;
  1433. }
  1434. static gint
  1435. lua_util_strequal_caseless (lua_State *L)
  1436. {
  1437. LUA_TRACE_POINT;
  1438. const gchar *str1, *str2;
  1439. gsize len1, len2;
  1440. gint ret = -1;
  1441. str1 = lua_tolstring (L, 1, &len1);
  1442. str2 = lua_tolstring (L, 2, &len2);
  1443. if (str1 && str2) {
  1444. if (len1 == len2) {
  1445. ret = rspamd_lc_cmp (str1, str2, len1);
  1446. }
  1447. else {
  1448. ret = len1 - len2;
  1449. }
  1450. }
  1451. else {
  1452. return luaL_error (L, "invalid arguments");
  1453. }
  1454. lua_pushboolean (L, (ret == 0) ? true : false);
  1455. return 1;
  1456. }
  1457. static gint
  1458. lua_util_get_ticks (lua_State *L)
  1459. {
  1460. LUA_TRACE_POINT;
  1461. gdouble ticks;
  1462. gboolean rdtsc = FALSE;
  1463. if (lua_isboolean (L, 1)) {
  1464. rdtsc = lua_toboolean (L, 1);
  1465. }
  1466. ticks = rspamd_get_ticks (rdtsc);
  1467. lua_pushnumber (L, ticks);
  1468. return 1;
  1469. }
  1470. static gint
  1471. lua_util_get_time (lua_State *L)
  1472. {
  1473. LUA_TRACE_POINT;
  1474. gdouble seconds;
  1475. struct timeval tv;
  1476. if (gettimeofday (&tv, NULL) == 0) {
  1477. seconds = tv_to_double (&tv);
  1478. }
  1479. else {
  1480. seconds = time (NULL);
  1481. }
  1482. lua_pushnumber (L, seconds);
  1483. return 1;
  1484. }
  1485. static gint
  1486. lua_util_time_to_string (lua_State *L)
  1487. {
  1488. LUA_TRACE_POINT;
  1489. gdouble seconds;
  1490. struct timeval tv;
  1491. char timebuf[128];
  1492. if (lua_isnumber (L, 1)) {
  1493. seconds = lua_tonumber (L, 1);
  1494. }
  1495. else {
  1496. if (gettimeofday (&tv, NULL) == 0) {
  1497. seconds = tv_to_double (&tv);
  1498. }
  1499. else {
  1500. seconds = time (NULL);
  1501. }
  1502. }
  1503. rspamd_http_date_format (timebuf, sizeof (timebuf), seconds);
  1504. lua_pushstring (L, timebuf);
  1505. return 1;
  1506. }
  1507. static gint
  1508. lua_util_stat (lua_State *L)
  1509. {
  1510. LUA_TRACE_POINT;
  1511. const gchar *fpath;
  1512. struct stat st;
  1513. fpath = luaL_checkstring (L, 1);
  1514. if (fpath) {
  1515. if (stat (fpath, &st) == -1) {
  1516. lua_pushstring (L, strerror (errno));
  1517. lua_pushnil (L);
  1518. }
  1519. else {
  1520. lua_pushnil (L);
  1521. lua_createtable (L, 0, 3);
  1522. lua_pushstring (L, "size");
  1523. lua_pushinteger (L, st.st_size);
  1524. lua_settable (L, -3);
  1525. lua_pushstring (L, "mtime");
  1526. lua_pushinteger (L, st.st_mtime);
  1527. lua_settable (L, -3);
  1528. lua_pushstring (L, "type");
  1529. if (S_ISREG (st.st_mode)) {
  1530. lua_pushstring (L, "regular");
  1531. }
  1532. else if (S_ISDIR (st.st_mode)) {
  1533. lua_pushstring (L, "directory");
  1534. }
  1535. else {
  1536. lua_pushstring (L, "special");
  1537. }
  1538. lua_settable (L, -3);
  1539. }
  1540. }
  1541. else {
  1542. return luaL_error (L, "invalid arguments");
  1543. }
  1544. return 2;
  1545. }
  1546. static gint
  1547. lua_util_unlink (lua_State *L)
  1548. {
  1549. LUA_TRACE_POINT;
  1550. const gchar *fpath;
  1551. gint ret;
  1552. fpath = luaL_checkstring (L, 1);
  1553. if (fpath) {
  1554. ret = unlink (fpath);
  1555. if (ret == -1) {
  1556. lua_pushboolean (L, false);
  1557. lua_pushstring (L, strerror (errno));
  1558. return 2;
  1559. }
  1560. lua_pushboolean (L, true);
  1561. }
  1562. else {
  1563. return luaL_error (L, "invalid arguments");
  1564. }
  1565. return 1;
  1566. }
  1567. static gint
  1568. lua_util_lock_file (lua_State *L)
  1569. {
  1570. LUA_TRACE_POINT;
  1571. const gchar *fpath;
  1572. gint fd = -1;
  1573. gboolean own = FALSE;
  1574. #if !HAVE_FLOCK
  1575. struct flock fl = {
  1576. .l_type = F_WRLCK,
  1577. .l_whence = SEEK_SET,
  1578. .l_start = 0,
  1579. .l_len = 0
  1580. };
  1581. #endif
  1582. fpath = luaL_checkstring (L, 1);
  1583. if (fpath) {
  1584. if (lua_isnumber (L, 2)) {
  1585. fd = lua_tonumber (L, 2);
  1586. }
  1587. else {
  1588. fd = open (fpath, O_RDONLY);
  1589. own = TRUE;
  1590. }
  1591. if (fd == -1) {
  1592. lua_pushnil (L);
  1593. lua_pushstring (L, strerror (errno));
  1594. return 2;
  1595. }
  1596. #if HAVE_FLOCK
  1597. if (flock (fd, LOCK_EX) == -1) {
  1598. #else
  1599. if (fcntl (fd, F_SETLKW, &fl) == -1) {
  1600. #endif
  1601. lua_pushnil (L);
  1602. lua_pushstring (L, strerror (errno));
  1603. if (own) {
  1604. close (fd);
  1605. }
  1606. return 2;
  1607. }
  1608. lua_pushinteger (L, fd);
  1609. }
  1610. else {
  1611. return luaL_error (L, "invalid arguments");
  1612. }
  1613. return 1;
  1614. }
  1615. static gint
  1616. lua_util_unlock_file (lua_State *L)
  1617. {
  1618. LUA_TRACE_POINT;
  1619. gint fd = -1, ret, serrno;
  1620. gboolean do_close = TRUE;
  1621. #if !HAVE_FLOCK
  1622. struct flock fl = {
  1623. .l_type = F_UNLCK,
  1624. .l_whence = SEEK_SET,
  1625. .l_start = 0,
  1626. .l_len = 0
  1627. };
  1628. #endif
  1629. if (lua_isnumber (L, 1)) {
  1630. fd = lua_tointeger (L, 1);
  1631. if (lua_isboolean (L, 2)) {
  1632. do_close = lua_toboolean (L, 2);
  1633. }
  1634. #if HAVE_FLOCK
  1635. ret = flock (fd, LOCK_UN);
  1636. #else
  1637. ret = fcntl (fd, F_SETLKW, &fl);
  1638. #endif
  1639. if (do_close) {
  1640. serrno = errno;
  1641. close (fd);
  1642. errno = serrno;
  1643. }
  1644. if (ret == -1) {
  1645. lua_pushboolean (L, false);
  1646. lua_pushstring (L, strerror (errno));
  1647. return 2;
  1648. }
  1649. lua_pushboolean (L, true);
  1650. }
  1651. else {
  1652. return luaL_error (L, "invalid arguments");
  1653. }
  1654. return 1;
  1655. }
  1656. static gint
  1657. lua_util_create_file (lua_State *L)
  1658. {
  1659. LUA_TRACE_POINT;
  1660. gint fd, mode = 00644;
  1661. const gchar *fpath;
  1662. fpath = luaL_checkstring (L, 1);
  1663. if (fpath) {
  1664. if (lua_isnumber (L, 2)) {
  1665. mode = lua_tointeger (L, 2);
  1666. }
  1667. fd = rspamd_file_xopen (fpath, O_RDWR | O_CREAT | O_TRUNC, mode, 0);
  1668. if (fd == -1) {
  1669. lua_pushnil (L);
  1670. lua_pushstring (L, strerror (errno));
  1671. return 2;
  1672. }
  1673. lua_pushinteger (L, fd);
  1674. }
  1675. else {
  1676. return luaL_error (L, "invalid arguments");
  1677. }
  1678. return 1;
  1679. }
  1680. static gint
  1681. lua_util_close_file (lua_State *L)
  1682. {
  1683. LUA_TRACE_POINT;
  1684. gint fd = -1;
  1685. if (lua_isnumber (L, 1)) {
  1686. fd = lua_tointeger (L, 1);
  1687. if (close (fd) == -1) {
  1688. lua_pushboolean (L, false);
  1689. lua_pushstring (L, strerror (errno));
  1690. return 2;
  1691. }
  1692. lua_pushboolean (L, true);
  1693. }
  1694. else {
  1695. return luaL_error (L, "invalid arguments");
  1696. }
  1697. return 1;
  1698. }
  1699. static gint
  1700. lua_util_random_hex (lua_State *L)
  1701. {
  1702. LUA_TRACE_POINT;
  1703. gchar *buf;
  1704. gint buflen;
  1705. buflen = lua_tointeger (L, 1);
  1706. if (buflen <= 0) {
  1707. return luaL_error (L, "invalid arguments");
  1708. }
  1709. buf = g_malloc (buflen);
  1710. rspamd_random_hex (buf, buflen);
  1711. lua_pushlstring (L, buf, buflen);
  1712. g_free (buf);
  1713. return 1;
  1714. }
  1715. static gint
  1716. lua_util_zstd_compress (lua_State *L)
  1717. {
  1718. LUA_TRACE_POINT;
  1719. struct rspamd_lua_text *t = NULL, *res, tmp;
  1720. gsize sz, r;
  1721. if (lua_type (L, 1) == LUA_TSTRING) {
  1722. t = &tmp;
  1723. t->start = lua_tolstring (L, 1, &sz);
  1724. t->len = sz;
  1725. }
  1726. else {
  1727. t = lua_check_text (L, 1);
  1728. }
  1729. if (t == NULL || t->start == NULL) {
  1730. return luaL_error (L, "invalid arguments");
  1731. }
  1732. sz = ZSTD_compressBound (t->len);
  1733. if (ZSTD_isError (sz)) {
  1734. msg_err ("cannot compress data: %s", ZSTD_getErrorName (sz));
  1735. lua_pushnil (L);
  1736. return 1;
  1737. }
  1738. res = lua_newuserdata (L, sizeof (*res));
  1739. res->start = g_malloc (sz);
  1740. res->flags = RSPAMD_TEXT_FLAG_OWN;
  1741. rspamd_lua_setclass (L, "rspamd{text}", -1);
  1742. r = ZSTD_compress ((void *)res->start, sz, t->start, t->len, 1);
  1743. if (ZSTD_isError (r)) {
  1744. msg_err ("cannot compress data: %s", ZSTD_getErrorName (r));
  1745. lua_pop (L, 1); /* Text will be freed here */
  1746. lua_pushnil (L);
  1747. return 1;
  1748. }
  1749. res->len = r;
  1750. return 1;
  1751. }
  1752. static gint
  1753. lua_util_zstd_decompress (lua_State *L)
  1754. {
  1755. LUA_TRACE_POINT;
  1756. struct rspamd_lua_text *t = NULL, *res;
  1757. gsize outlen, sz, r;
  1758. ZSTD_DStream *zstream;
  1759. ZSTD_inBuffer zin;
  1760. ZSTD_outBuffer zout;
  1761. gchar *out;
  1762. if (lua_type (L, 1) == LUA_TSTRING) {
  1763. t = g_alloca (sizeof (*t));
  1764. t->start = lua_tolstring (L, 1, &sz);
  1765. t->len = sz;
  1766. }
  1767. else {
  1768. t = lua_check_text (L, 1);
  1769. }
  1770. if (t == NULL || t->start == NULL) {
  1771. return luaL_error (L, "invalid arguments");
  1772. }
  1773. zstream = ZSTD_createDStream ();
  1774. ZSTD_initDStream (zstream);
  1775. zin.pos = 0;
  1776. zin.src = t->start;
  1777. zin.size = t->len;
  1778. if ((outlen = ZSTD_getDecompressedSize (zin.src, zin.size)) == 0) {
  1779. outlen = ZSTD_DStreamOutSize ();
  1780. }
  1781. out = g_malloc (outlen);
  1782. zout.dst = out;
  1783. zout.pos = 0;
  1784. zout.size = outlen;
  1785. while (zin.pos < zin.size) {
  1786. r = ZSTD_decompressStream (zstream, &zout, &zin);
  1787. if (ZSTD_isError (r)) {
  1788. msg_err ("cannot decompress data: %s", ZSTD_getErrorName (r));
  1789. ZSTD_freeDStream (zstream);
  1790. g_free (out);
  1791. lua_pushstring (L, ZSTD_getErrorName (r));
  1792. lua_pushnil (L);
  1793. return 2;
  1794. }
  1795. if (zin.pos < zin.size && zout.pos == zout.size) {
  1796. /* We need to extend output buffer */
  1797. zout.size = zout.size * 1.5 + 1.0;
  1798. out = g_realloc (zout.dst, zout.size);
  1799. zout.dst = out;
  1800. }
  1801. }
  1802. ZSTD_freeDStream (zstream);
  1803. lua_pushnil (L); /* Error */
  1804. res = lua_newuserdata (L, sizeof (*res));
  1805. res->start = out;
  1806. res->flags = RSPAMD_TEXT_FLAG_OWN;
  1807. rspamd_lua_setclass (L, "rspamd{text}", -1);
  1808. res->len = zout.pos;
  1809. return 2;
  1810. }
  1811. static gint
  1812. lua_util_gzip_compress (lua_State *L)
  1813. {
  1814. LUA_TRACE_POINT;
  1815. struct rspamd_lua_text *t = NULL, *res, tmp;
  1816. gsize sz;
  1817. z_stream strm;
  1818. gint rc;
  1819. guchar *p;
  1820. gsize remain;
  1821. if (lua_type (L, 1) == LUA_TSTRING) {
  1822. t = &tmp;
  1823. t->start = lua_tolstring (L, 1, &sz);
  1824. t->len = sz;
  1825. }
  1826. else {
  1827. t = lua_check_text (L, 1);
  1828. }
  1829. if (t == NULL || t->start == NULL) {
  1830. return luaL_error (L, "invalid arguments");
  1831. }
  1832. memset (&strm, 0, sizeof (strm));
  1833. rc = deflateInit2 (&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
  1834. MAX_WBITS + 16, MAX_MEM_LEVEL - 1, Z_DEFAULT_STRATEGY);
  1835. if (rc != Z_OK) {
  1836. return luaL_error (L, "cannot init zlib: %s", zError (rc));
  1837. }
  1838. sz = deflateBound (&strm, t->len);
  1839. strm.avail_in = t->len;
  1840. strm.next_in = (guchar *)t->start;
  1841. res = lua_newuserdata (L, sizeof (*res));
  1842. res->start = g_malloc (sz);
  1843. res->flags = RSPAMD_TEXT_FLAG_OWN;
  1844. rspamd_lua_setclass (L, "rspamd{text}", -1);
  1845. p = (guchar *)res->start;
  1846. remain = sz;
  1847. while (strm.avail_in != 0) {
  1848. strm.avail_out = remain;
  1849. strm.next_out = p;
  1850. rc = deflate (&strm, Z_FINISH);
  1851. if (rc != Z_OK && rc != Z_BUF_ERROR) {
  1852. if (rc == Z_STREAM_END) {
  1853. break;
  1854. }
  1855. else {
  1856. msg_err ("cannot compress data: %s", zError (rc));
  1857. lua_pop (L, 1); /* Text will be freed here */
  1858. lua_pushnil (L);
  1859. deflateEnd (&strm);
  1860. return 1;
  1861. }
  1862. }
  1863. res->len = strm.total_out;
  1864. if (strm.avail_out == 0 && strm.avail_in != 0) {
  1865. /* Need to allocate more */
  1866. remain = res->len;
  1867. res->start = g_realloc ((gpointer)res->start, strm.avail_in + sz);
  1868. sz = strm.avail_in + sz;
  1869. p = (guchar *)res->start + remain;
  1870. remain = sz - remain;
  1871. }
  1872. }
  1873. deflateEnd (&strm);
  1874. res->len = strm.total_out;
  1875. return 1;
  1876. }
  1877. static gint
  1878. lua_util_gzip_decompress (lua_State *L)
  1879. {
  1880. LUA_TRACE_POINT;
  1881. struct rspamd_lua_text *t = NULL, *res, tmp;
  1882. gsize sz;
  1883. z_stream strm;
  1884. gint rc;
  1885. guchar *p;
  1886. gsize remain;
  1887. if (lua_type (L, 1) == LUA_TSTRING) {
  1888. t = &tmp;
  1889. t->start = lua_tolstring (L, 1, &sz);
  1890. t->len = sz;
  1891. }
  1892. else {
  1893. t = lua_check_text (L, 1);
  1894. }
  1895. if (t == NULL || t->start == NULL) {
  1896. return luaL_error (L, "invalid arguments");
  1897. }
  1898. sz = t->len;
  1899. memset (&strm, 0, sizeof (strm));
  1900. /* windowBits +16 to decode gzip, zlib 1.2.0.4+ */
  1901. rc = inflateInit2 (&strm, MAX_WBITS + 16);
  1902. if (rc != Z_OK) {
  1903. return luaL_error (L, "cannot init zlib");
  1904. }
  1905. strm.avail_in = t->len;
  1906. strm.next_in = (guchar *)t->start;
  1907. res = lua_newuserdata (L, sizeof (*res));
  1908. res->start = g_malloc (sz);
  1909. res->flags = RSPAMD_TEXT_FLAG_OWN;
  1910. rspamd_lua_setclass (L, "rspamd{text}", -1);
  1911. p = (guchar *)res->start;
  1912. remain = sz;
  1913. while (strm.avail_in != 0) {
  1914. strm.avail_out = remain;
  1915. strm.next_out = p;
  1916. rc = inflate (&strm, Z_FINISH);
  1917. if (rc != Z_OK && rc != Z_BUF_ERROR) {
  1918. if (rc == Z_STREAM_END) {
  1919. break;
  1920. }
  1921. else {
  1922. msg_err ("cannot decompress data: %s", zError (rc));
  1923. lua_pop (L, 1); /* Text will be freed here */
  1924. lua_pushnil (L);
  1925. inflateEnd (&strm);
  1926. return 1;
  1927. }
  1928. }
  1929. res->len = strm.total_out;
  1930. if (strm.avail_out == 0 && strm.avail_in != 0) {
  1931. /* Need to allocate more */
  1932. remain = res->len;
  1933. res->start = g_realloc ((gpointer)res->start, strm.avail_in + sz);
  1934. sz = strm.avail_in + sz;
  1935. p = (guchar *)res->start + remain;
  1936. remain = sz - remain;
  1937. }
  1938. }
  1939. inflateEnd (&strm);
  1940. res->len = strm.total_out;
  1941. return 2;
  1942. }
  1943. static gint
  1944. lua_util_normalize_prob (lua_State *L)
  1945. {
  1946. LUA_TRACE_POINT;
  1947. gdouble x, bias = 0.5;
  1948. x = lua_tonumber (L, 1);
  1949. if (lua_type (L, 2) == LUA_TNUMBER) {
  1950. bias = lua_tonumber (L, 2);
  1951. }
  1952. lua_pushnumber (L, rspamd_normalize_probability (x, bias));
  1953. return 1;
  1954. }
  1955. static gint
  1956. lua_util_caseless_hash (lua_State *L)
  1957. {
  1958. LUA_TRACE_POINT;
  1959. guint64 seed = 0xdeadbabe, h;
  1960. struct rspamd_lua_text *t = NULL;
  1961. gint64 *r;
  1962. gsize sz;
  1963. if (lua_type (L, 1) == LUA_TSTRING) {
  1964. t = g_alloca (sizeof (*t));
  1965. t->start = lua_tolstring (L, 1, &sz);
  1966. t->len = sz;
  1967. }
  1968. else {
  1969. t = lua_check_text (L, 1);
  1970. }
  1971. if (t == NULL || t->start == NULL) {
  1972. return luaL_error (L, "invalid arguments");
  1973. }
  1974. if (lua_type (L, 2) == LUA_TNUMBER) {
  1975. seed = lua_tonumber (L, 2);
  1976. }
  1977. else if (lua_type (L, 2) == LUA_TUSERDATA) {
  1978. seed = lua_check_int64 (L, 2);
  1979. }
  1980. h = rspamd_icase_hash (t->start, t->len, seed);
  1981. r = lua_newuserdata (L, sizeof (*r));
  1982. *r = h;
  1983. rspamd_lua_setclass (L, "rspamd{int64}", -1);
  1984. return 1;
  1985. }
  1986. static gint
  1987. lua_util_caseless_hash_fast (lua_State *L)
  1988. {
  1989. LUA_TRACE_POINT;
  1990. guint64 seed = 0xdeadbabe, h;
  1991. struct rspamd_lua_text *t = NULL;
  1992. gsize sz;
  1993. union {
  1994. guint64 i;
  1995. double d;
  1996. } u;
  1997. if (lua_type (L, 1) == LUA_TSTRING) {
  1998. t = g_alloca (sizeof (*t));
  1999. t->start = lua_tolstring (L, 1, &sz);
  2000. t->len = sz;
  2001. }
  2002. else {
  2003. t = lua_check_text (L, 1);
  2004. }
  2005. if (t == NULL || t->start == NULL) {
  2006. return luaL_error (L, "invalid arguments");
  2007. }
  2008. if (lua_type (L, 2) == LUA_TNUMBER) {
  2009. seed = lua_tonumber (L, 2);
  2010. }
  2011. else if (lua_type (L, 2) == LUA_TUSERDATA) {
  2012. seed = lua_check_int64 (L, 2);
  2013. }
  2014. /*
  2015. * Here, we loose entropy from 64 bits to 52 bits roughly, however,
  2016. * it is still fine for practical applications
  2017. */
  2018. h = rspamd_icase_hash (t->start, t->len, seed);
  2019. u.i = G_GUINT64_CONSTANT(0x3FF) << 52 | h >> 12;
  2020. lua_pushnumber (L, u.d - 1.0);
  2021. return 1;
  2022. }
  2023. static gint
  2024. lua_util_is_utf_spoofed (lua_State *L)
  2025. {
  2026. LUA_TRACE_POINT;
  2027. gsize l1, l2;
  2028. gint ret, nres = 2;
  2029. const gchar *s1 = lua_tolstring (L, 1, &l1),
  2030. *s2 = lua_tolstring (L, 2, &l2);
  2031. static USpoofChecker *spc, *spc_sgl;
  2032. UErrorCode uc_err = U_ZERO_ERROR;
  2033. if (s1 && s2) {
  2034. if (spc == NULL) {
  2035. spc = uspoof_open (&uc_err);
  2036. if (uc_err != U_ZERO_ERROR) {
  2037. msg_err ("cannot init spoof checker: %s", u_errorName (uc_err));
  2038. lua_pushboolean (L, false);
  2039. return 1;
  2040. }
  2041. }
  2042. ret = uspoof_areConfusableUTF8 (spc, s1, l1, s2, l2, &uc_err);
  2043. }
  2044. else if (s1) {
  2045. /* We have just s1, not s2 */
  2046. if (spc_sgl == NULL) {
  2047. spc_sgl = uspoof_open (&uc_err);
  2048. if (uc_err != U_ZERO_ERROR) {
  2049. msg_err ("cannot init spoof checker: %s", u_errorName (uc_err));
  2050. lua_pushboolean (L, false);
  2051. return 1;
  2052. }
  2053. uspoof_setChecks (spc_sgl,
  2054. USPOOF_INVISIBLE | USPOOF_MIXED_SCRIPT_CONFUSABLE | USPOOF_ANY_CASE,
  2055. &uc_err);
  2056. }
  2057. ret = uspoof_checkUTF8 (spc_sgl, s1, l1, NULL, &uc_err);
  2058. }
  2059. else {
  2060. return luaL_error (L, "invalid arguments");
  2061. }
  2062. lua_pushboolean (L, !!(ret != 0));
  2063. switch (ret) {
  2064. case 0:
  2065. nres = 1;
  2066. break;
  2067. case USPOOF_SINGLE_SCRIPT_CONFUSABLE:
  2068. lua_pushstring (L, "single");
  2069. break;
  2070. case USPOOF_MIXED_SCRIPT_CONFUSABLE:
  2071. lua_pushstring (L, "multiple");
  2072. break;
  2073. case USPOOF_WHOLE_SCRIPT_CONFUSABLE:
  2074. lua_pushstring (L, "whole");
  2075. break;
  2076. default:
  2077. lua_pushstring (L, "unknown");
  2078. break;
  2079. }
  2080. return nres;
  2081. }
  2082. static gint
  2083. lua_util_get_hostname (lua_State *L)
  2084. {
  2085. LUA_TRACE_POINT;
  2086. gchar *hostbuf;
  2087. gsize hostlen;
  2088. hostlen = sysconf (_SC_HOST_NAME_MAX);
  2089. if (hostlen <= 0) {
  2090. hostlen = 256;
  2091. }
  2092. else {
  2093. hostlen ++;
  2094. }
  2095. hostbuf = g_alloca (hostlen);
  2096. memset (hostbuf, 0, hostlen);
  2097. gethostname (hostbuf, hostlen - 1);
  2098. lua_pushstring (L, hostbuf);
  2099. return 1;
  2100. }
  2101. static gint
  2102. lua_util_parse_content_type (lua_State *L)
  2103. {
  2104. LUA_TRACE_POINT;
  2105. gsize len;
  2106. const gchar *ct_str = luaL_checklstring (L, 1, &len);
  2107. rspamd_mempool_t *pool = rspamd_lua_check_mempool (L, 2);
  2108. struct rspamd_content_type *ct;
  2109. if (!ct_str || !pool) {
  2110. return luaL_error (L, "invalid arguments");
  2111. }
  2112. ct = rspamd_content_type_parse (ct_str, len, pool);
  2113. if (ct == NULL) {
  2114. lua_pushnil (L);
  2115. }
  2116. else {
  2117. GHashTableIter it;
  2118. gpointer k, v;
  2119. lua_createtable (L, 0, 4 + (ct->attrs ? g_hash_table_size (ct->attrs) : 0));
  2120. if (ct->type.len > 0) {
  2121. lua_pushstring (L, "type");
  2122. lua_pushlstring (L, ct->type.begin, ct->type.len);
  2123. lua_settable (L, -3);
  2124. }
  2125. if (ct->subtype.len > 0) {
  2126. lua_pushstring (L, "subtype");
  2127. lua_pushlstring (L, ct->subtype.begin, ct->subtype.len);
  2128. lua_settable (L, -3);
  2129. }
  2130. if (ct->charset.len > 0) {
  2131. lua_pushstring (L, "charset");
  2132. lua_pushlstring (L, ct->charset.begin, ct->charset.len);
  2133. lua_settable (L, -3);
  2134. }
  2135. if (ct->orig_boundary.len > 0) {
  2136. lua_pushstring (L, "boundary");
  2137. lua_pushlstring (L, ct->orig_boundary.begin, ct->orig_boundary.len);
  2138. lua_settable (L, -3);
  2139. }
  2140. if (ct->attrs) {
  2141. g_hash_table_iter_init (&it, ct->attrs);
  2142. while (g_hash_table_iter_next (&it, &k, &v)) {
  2143. struct rspamd_content_type_param *param =
  2144. (struct rspamd_content_type_param *)v, *cur;
  2145. guint i = 1;
  2146. lua_pushlstring (L, param->name.begin, param->name.len);
  2147. lua_createtable (L, 1, 0);
  2148. DL_FOREACH (param, cur) {
  2149. lua_pushlstring (L, cur->value.begin, cur->value.len);
  2150. lua_rawseti (L, -2, i++);
  2151. }
  2152. lua_settable (L, -3);
  2153. }
  2154. }
  2155. }
  2156. return 1;
  2157. }
  2158. static gint
  2159. lua_util_mime_header_encode (lua_State *L)
  2160. {
  2161. LUA_TRACE_POINT;
  2162. gsize len;
  2163. const gchar *hdr = luaL_checklstring (L, 1, &len);
  2164. gchar *encoded;
  2165. if (!hdr) {
  2166. return luaL_error (L, "invalid arguments");
  2167. }
  2168. encoded = rspamd_mime_header_encode (hdr, len);
  2169. lua_pushstring (L, encoded);
  2170. g_free (encoded);
  2171. return 1;
  2172. }
  2173. static gint
  2174. lua_util_is_valid_utf8 (lua_State *L)
  2175. {
  2176. LUA_TRACE_POINT;
  2177. const gchar *str;
  2178. gsize len;
  2179. str = lua_tolstring (L, 1, &len);
  2180. if (str) {
  2181. lua_pushboolean (L, g_utf8_validate (str, len, NULL));
  2182. }
  2183. else {
  2184. return luaL_error (L, "invalid arguments");
  2185. }
  2186. return 1;
  2187. }
  2188. static gint
  2189. lua_util_has_obscured_unicode (lua_State *L)
  2190. {
  2191. LUA_TRACE_POINT;
  2192. const gchar *str;
  2193. gsize len;
  2194. gint32 i = 0, prev_i;
  2195. UChar32 uc;
  2196. str = lua_tolstring (L, 1, &len);
  2197. while (i < len) {
  2198. prev_i = i;
  2199. U8_NEXT (str, i, len, uc);
  2200. if (uc > 0) {
  2201. if (IS_OBSCURED_CHAR (uc)) {
  2202. lua_pushboolean (L, true);
  2203. lua_pushnumber (L, uc); /* Character */
  2204. lua_pushnumber (L, prev_i); /* Offset */
  2205. return 3;
  2206. }
  2207. }
  2208. }
  2209. lua_pushboolean (L, false);
  2210. return 1;
  2211. }
  2212. static gint
  2213. lua_util_readline (lua_State *L)
  2214. {
  2215. LUA_TRACE_POINT;
  2216. const gchar *prompt = "";
  2217. gchar *input;
  2218. if (lua_type (L, 1) == LUA_TSTRING) {
  2219. prompt = lua_tostring (L, 1);
  2220. }
  2221. input = linenoise (prompt);
  2222. if (input) {
  2223. lua_pushstring (L, input);
  2224. linenoiseHistoryAdd (input);
  2225. linenoiseFree (input);
  2226. }
  2227. else {
  2228. lua_pushnil (L);
  2229. }
  2230. return 1;
  2231. }
  2232. static gint
  2233. lua_util_readpassphrase (lua_State *L)
  2234. {
  2235. LUA_TRACE_POINT;
  2236. gchar test_password[8192];
  2237. gsize r;
  2238. r = rspamd_read_passphrase (test_password, sizeof (test_password), 0, NULL);
  2239. if (r > 0) {
  2240. lua_pushlstring (L, test_password, r);
  2241. }
  2242. else {
  2243. lua_pushnil (L);
  2244. }
  2245. /* In fact, we still pass it to Lua which is not very safe */
  2246. rspamd_explicit_memzero (test_password, sizeof (test_password));
  2247. return 1;
  2248. }
  2249. static gint
  2250. lua_util_file_exists (lua_State *L)
  2251. {
  2252. LUA_TRACE_POINT;
  2253. const gchar *fname = luaL_checkstring (L, 1);
  2254. gint serrno;
  2255. if (fname) {
  2256. if (access (fname, R_OK) == -1) {
  2257. serrno = errno;
  2258. lua_pushboolean (L, false);
  2259. lua_pushstring (L, strerror (serrno));
  2260. }
  2261. else {
  2262. lua_pushboolean (L, true);
  2263. lua_pushnil (L);
  2264. }
  2265. }
  2266. else {
  2267. return luaL_error (L, "invalid arguments");
  2268. }
  2269. return 2;
  2270. }
  2271. static gint
  2272. lua_util_mkdir (lua_State *L)
  2273. {
  2274. LUA_TRACE_POINT;
  2275. const gchar *dname = luaL_checkstring (L, 1);
  2276. gboolean recursive = FALSE;
  2277. gint r = -1;
  2278. if (dname) {
  2279. if (lua_isboolean (L, 2)) {
  2280. recursive = lua_toboolean (L, 2);
  2281. }
  2282. if (recursive) {
  2283. char path[PATH_MAX];
  2284. gsize len, i;
  2285. len = rspamd_strlcpy (path, dname, sizeof (path));
  2286. /* Strip last / */
  2287. if (path[len - 1] == '/') {
  2288. path[len - 1] = '\0';
  2289. len --;
  2290. }
  2291. for (i = 1; i < len; i ++) {
  2292. if (path[i] == '/') {
  2293. path[i] = '\0';
  2294. errno = 0;
  2295. r = mkdir (path, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
  2296. if (r == -1 && errno != EEXIST) {
  2297. break;
  2298. }
  2299. path[i] = '/';
  2300. }
  2301. }
  2302. /* Final path component */
  2303. r = mkdir (path, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
  2304. }
  2305. else {
  2306. r = mkdir (dname, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
  2307. }
  2308. if (r == -1 && errno != EEXIST) {
  2309. lua_pushboolean (L, false);
  2310. lua_pushstring (L, strerror (errno));
  2311. return 2;
  2312. }
  2313. lua_pushboolean (L, true);
  2314. }
  2315. else {
  2316. return luaL_error (L, "invalid arguments");
  2317. }
  2318. return 1;
  2319. }
  2320. static gint
  2321. lua_util_umask (lua_State *L)
  2322. {
  2323. LUA_TRACE_POINT;
  2324. mode_t mask = 0, old;
  2325. if (lua_type (L, 1) == LUA_TSTRING) {
  2326. const gchar *str = lua_tostring (L, 1);
  2327. if (str[0] == '0') {
  2328. /* e.g. '022' */
  2329. mask = strtol (str, NULL, 8);
  2330. }
  2331. else {
  2332. /* XXX: implement modestring parsing at some point */
  2333. return luaL_error (L, "invalid arguments");
  2334. }
  2335. }
  2336. else if (lua_type (L, 1) == LUA_TNUMBER) {
  2337. mask = lua_tonumber (L, 1);
  2338. }
  2339. else {
  2340. return luaL_error (L, "invalid arguments");
  2341. }
  2342. old = umask (mask);
  2343. lua_pushinteger (L, old);
  2344. return 1;
  2345. }
  2346. static gint
  2347. lua_util_isatty (lua_State *L)
  2348. {
  2349. LUA_TRACE_POINT;
  2350. if (isatty (STDOUT_FILENO)) {
  2351. lua_pushboolean (L, true);
  2352. }
  2353. else {
  2354. lua_pushboolean (L, false);
  2355. }
  2356. return 1;
  2357. }
  2358. /* Backport from Lua 5.3 */
  2359. /******************************************************************************
  2360. * Copyright (C) 1994-2016 Lua.org, PUC-Rio.
  2361. *
  2362. * Permission is hereby granted, free of charge, to any person obtaining
  2363. * a copy of this software and associated documentation files (the
  2364. * "Software"), to deal in the Software without restriction, including
  2365. * without limitation the rights to use, copy, modify, merge, publish,
  2366. * distribute, sublicense, and/or sell copies of the Software, and to
  2367. * permit persons to whom the Software is furnished to do so, subject to
  2368. * the following conditions:
  2369. *
  2370. * The above copyright notice and this permission notice shall be
  2371. * included in all copies or substantial portions of the Software.
  2372. *
  2373. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  2374. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2375. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  2376. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  2377. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  2378. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  2379. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  2380. ******************************************************************************/
  2381. /*
  2382. ** {======================================================
  2383. ** PACK/UNPACK
  2384. ** =======================================================
  2385. */
  2386. /* value used for padding */
  2387. #if !defined(LUA_PACKPADBYTE)
  2388. #define LUA_PACKPADBYTE 0x00
  2389. #endif
  2390. /* maximum size for the binary representation of an integer */
  2391. #define MAXINTSIZE 16
  2392. /* number of bits in a character */
  2393. #define NB CHAR_BIT
  2394. /* mask for one character (NB 1's) */
  2395. #define MC ((1 << NB) - 1)
  2396. /* size of a lua_Integer */
  2397. #define SZINT ((int)sizeof(lua_Integer))
  2398. #define MAX_SIZET ((size_t)(~(size_t)0))
  2399. #define MAXSIZE \
  2400. (sizeof(size_t) < sizeof(int) ? MAX_SIZET : (size_t)(INT_MAX))
  2401. /* dummy union to get native endianness */
  2402. static const union {
  2403. int dummy;
  2404. char little; /* true if machine is little endian */
  2405. } nativeendian = {1};
  2406. /* dummy structure to get native alignment requirements */
  2407. struct cD {
  2408. char c;
  2409. union {
  2410. double d;
  2411. void *p;
  2412. lua_Integer i;
  2413. lua_Number n;
  2414. } u;
  2415. };
  2416. #define MAXALIGN (offsetof(struct cD, u))
  2417. /*
  2418. ** Union for serializing floats
  2419. */
  2420. typedef union Ftypes {
  2421. float f;
  2422. double d;
  2423. lua_Number n;
  2424. char buff[5 * sizeof (lua_Number)]; /* enough for any float type */
  2425. } Ftypes;
  2426. /*
  2427. ** information to pack/unpack stuff
  2428. */
  2429. typedef struct Header {
  2430. lua_State *L;
  2431. int islittle;
  2432. int maxalign;
  2433. } Header;
  2434. /*
  2435. ** options for pack/unpack
  2436. */
  2437. typedef enum KOption {
  2438. Kint, /* signed integers */
  2439. Kuint, /* unsigned integers */
  2440. Kfloat, /* floating-point numbers */
  2441. Kchar, /* fixed-length strings */
  2442. Kstring, /* strings with prefixed length */
  2443. Kzstr, /* zero-terminated strings */
  2444. Kpadding, /* padding */
  2445. Kpaddalign, /* padding for alignment */
  2446. Knop /* no-op (configuration or spaces) */
  2447. } KOption;
  2448. #if LUA_VERSION_NUM < 503
  2449. #define lua_Unsigned size_t
  2450. typedef struct luaL_Buffer_53 {
  2451. luaL_Buffer b; /* make incorrect code crash! */
  2452. char *ptr;
  2453. size_t nelems;
  2454. size_t capacity;
  2455. lua_State *L2;
  2456. } luaL_Buffer_53;
  2457. #define luaL_Buffer luaL_Buffer_53
  2458. #define COMPAT53_PREFIX lua
  2459. #undef COMPAT53_API
  2460. #if defined(__GNUC__) || defined(__clang__)
  2461. # define COMPAT53_API __attribute__((__unused__)) static
  2462. #else
  2463. # define COMPAT53_API static
  2464. #endif
  2465. #define COMPAT53_CONCAT_HELPER(a, b) a##b
  2466. #define COMPAT53_CONCAT(a, b) COMPAT53_CONCAT_HELPER(a, b)
  2467. #define luaL_buffinit COMPAT53_CONCAT(COMPAT53_PREFIX, _buffinit_53)
  2468. COMPAT53_API void luaL_buffinit (lua_State *L, luaL_Buffer_53 *B);
  2469. #define luaL_prepbuffsize COMPAT53_CONCAT(COMPAT53_PREFIX, _prepbufsize_53)
  2470. COMPAT53_API char *luaL_prepbuffsize (luaL_Buffer_53 *B, size_t s);
  2471. #define luaL_addlstring COMPAT53_CONCAT(COMPAT53_PREFIX, _addlstring_53)
  2472. COMPAT53_API void luaL_addlstring (luaL_Buffer_53 *B, const char *s, size_t l);
  2473. #define luaL_addvalue COMPAT53_CONCAT(COMPAT53_PREFIX, _addvalue_53)
  2474. COMPAT53_API void luaL_addvalue (luaL_Buffer_53 *B);
  2475. #define luaL_pushresult COMPAT53_CONCAT(COMPAT53_PREFIX, _pushresult_53)
  2476. COMPAT53_API void luaL_pushresult (luaL_Buffer_53 *B);
  2477. #undef luaL_buffinitsize
  2478. #define luaL_buffinitsize(L, B, s) \
  2479. (luaL_buffinit(L, B), luaL_prepbuffsize(B, s))
  2480. #undef luaL_prepbuffer
  2481. #define luaL_prepbuffer(B) \
  2482. luaL_prepbuffsize(B, LUAL_BUFFERSIZE)
  2483. #undef luaL_addchar
  2484. #define luaL_addchar(B, c) \
  2485. ((void)((B)->nelems < (B)->capacity || luaL_prepbuffsize(B, 1)), \
  2486. ((B)->ptr[(B)->nelems++] = (c)))
  2487. #undef luaL_addsize
  2488. #define luaL_addsize(B, s) \
  2489. ((B)->nelems += (s))
  2490. #undef luaL_addstring
  2491. #define luaL_addstring(B, s) \
  2492. luaL_addlstring(B, s, strlen(s))
  2493. #undef luaL_pushresultsize
  2494. #define luaL_pushresultsize(B, s) \
  2495. (luaL_addsize(B, s), luaL_pushresult(B))
  2496. COMPAT53_API void
  2497. luaL_buffinit (lua_State *L, luaL_Buffer_53 *B)
  2498. {
  2499. /* make it crash if used via pointer to a 5.1-style luaL_Buffer */
  2500. #if LUA_VERSION_NUM < 502
  2501. B->b.p = NULL;
  2502. B->b.L = NULL;
  2503. B->b.lvl = 0;
  2504. /* reuse the buffer from the 5.1-style luaL_Buffer though! */
  2505. B->ptr = B->b.buffer;
  2506. B->nelems = 0;
  2507. #elif LUA_VERSION_NUM == 502
  2508. B->ptr = B->b.b;
  2509. B->nelems = B->b.n;
  2510. #endif
  2511. B->capacity = LUAL_BUFFERSIZE;
  2512. B->L2 = L;
  2513. }
  2514. COMPAT53_API char *
  2515. luaL_prepbuffsize (luaL_Buffer_53 *B, size_t s)
  2516. {
  2517. if (B->capacity - B->nelems < s) { /* needs to grow */
  2518. char *newptr = NULL;
  2519. size_t newcap = B->capacity * 2;
  2520. if (newcap - B->nelems < s)
  2521. newcap = B->nelems + s;
  2522. if (newcap < B->capacity) /* overflow */
  2523. luaL_error (B->L2, "buffer too large");
  2524. newptr = (char *) lua_newuserdata (B->L2, newcap);
  2525. memcpy(newptr, B->ptr, B->nelems);
  2526. #if LUA_VERSION_NUM < 502
  2527. if (B->ptr != B->b.buffer)
  2528. #elif LUA_VERSION_NUM == 502
  2529. if (B->ptr != B->b.b)
  2530. #endif
  2531. lua_replace (B->L2, -2); /* remove old buffer */
  2532. B->ptr = newptr;
  2533. B->capacity = newcap;
  2534. }
  2535. return B->ptr + B->nelems;
  2536. }
  2537. COMPAT53_API void
  2538. luaL_addlstring (luaL_Buffer_53 *B, const char *s, size_t l)
  2539. {
  2540. memcpy(luaL_prepbuffsize (B, l), s, l);
  2541. luaL_addsize(B, l);
  2542. }
  2543. COMPAT53_API void
  2544. luaL_addvalue (luaL_Buffer_53 *B)
  2545. {
  2546. size_t len = 0;
  2547. const char *s = lua_tolstring (B->L2, -1, &len);
  2548. if (!s)
  2549. luaL_error (B->L2, "cannot convert value to string");
  2550. #if LUA_VERSION_NUM < 502
  2551. if (B->ptr != B->b.buffer)
  2552. #elif LUA_VERSION_NUM == 502
  2553. if (B->ptr != B->b.b)
  2554. #endif
  2555. lua_insert (B->L2, -2); /* userdata buffer must be at stack top */
  2556. luaL_addlstring (B, s, len);
  2557. #if LUA_VERSION_NUM < 502
  2558. lua_remove (B->L2, B->ptr != B->b.buffer ? -2 : -1);
  2559. #elif LUA_VERSION_NUM == 502
  2560. lua_remove (B->L2, B->ptr != B->b.b ? -2 : -1);
  2561. #endif
  2562. }
  2563. COMPAT53_API void
  2564. luaL_pushresult (luaL_Buffer_53 *B)
  2565. {
  2566. lua_pushlstring (B->L2, B->ptr, B->nelems);
  2567. #if LUA_VERSION_NUM < 502
  2568. if (B->ptr != B->b.buffer)
  2569. #elif LUA_VERSION_NUM == 502
  2570. if (B->ptr != B->b.b)
  2571. #endif
  2572. lua_replace (B->L2, -2); /* remove userdata buffer */
  2573. }
  2574. #endif
  2575. /*
  2576. ** Read an integer numeral from string 'fmt' or return 'df' if
  2577. ** there is no numeral
  2578. */
  2579. static int
  2580. digit (int c)
  2581. {
  2582. return '0' <= c && c <= '9';
  2583. }
  2584. static int
  2585. getnum (const char **fmt, int df)
  2586. {
  2587. if (!digit (**fmt)) /* no number? */
  2588. return df; /* return default value */
  2589. else {
  2590. int a = 0;
  2591. do {
  2592. a = a * 10 + (*((*fmt)++) - '0');
  2593. } while (digit (**fmt) && a <= ((int) MAXSIZE - 9) / 10);
  2594. return a;
  2595. }
  2596. }
  2597. /*
  2598. ** Read an integer numeral and raises an error if it is larger
  2599. ** than the maximum size for integers.
  2600. */
  2601. static int
  2602. getnumlimit (Header *h, const char **fmt, int df)
  2603. {
  2604. int sz = getnum (fmt, df);
  2605. if (sz > MAXINTSIZE || sz <= 0)
  2606. luaL_error (h->L, "integral size (%d) out of limits [1,%d]",
  2607. sz, MAXINTSIZE);
  2608. return sz;
  2609. }
  2610. /*
  2611. ** Initialize Header
  2612. */
  2613. static void
  2614. initheader (lua_State *L, Header *h)
  2615. {
  2616. h->L = L;
  2617. h->islittle = nativeendian.little;
  2618. h->maxalign = 1;
  2619. }
  2620. /*
  2621. ** Read and classify next option. 'size' is filled with option's size.
  2622. */
  2623. static KOption
  2624. getoption (Header *h, const char **fmt, int *size)
  2625. {
  2626. int opt = *((*fmt)++);
  2627. *size = 0; /* default */
  2628. switch (opt) {
  2629. case 'b':
  2630. *size = sizeof (char);
  2631. return Kint;
  2632. case 'B':
  2633. *size = sizeof (char);
  2634. return Kuint;
  2635. case 'h':
  2636. *size = sizeof (short);
  2637. return Kint;
  2638. case 'H':
  2639. *size = sizeof (short);
  2640. return Kuint;
  2641. case 'l':
  2642. *size = sizeof (long);
  2643. return Kint;
  2644. case 'L':
  2645. *size = sizeof (long);
  2646. return Kuint;
  2647. case 'j':
  2648. *size = sizeof (lua_Integer);
  2649. return Kint;
  2650. case 'J':
  2651. *size = sizeof (lua_Integer);
  2652. return Kuint;
  2653. case 'T':
  2654. *size = sizeof (size_t);
  2655. return Kuint;
  2656. case 'f':
  2657. *size = sizeof (float);
  2658. return Kfloat;
  2659. case 'd':
  2660. *size = sizeof (double);
  2661. return Kfloat;
  2662. case 'n':
  2663. *size = sizeof (lua_Number);
  2664. return Kfloat;
  2665. case 'i':
  2666. *size = getnumlimit (h, fmt, sizeof (int));
  2667. return Kint;
  2668. case 'I':
  2669. *size = getnumlimit (h, fmt, sizeof (int));
  2670. return Kuint;
  2671. case 's':
  2672. *size = getnumlimit (h, fmt, sizeof (size_t));
  2673. return Kstring;
  2674. case 'c':
  2675. *size = getnum (fmt, -1);
  2676. if (*size == -1)
  2677. luaL_error (h->L, "missing size for format option 'c'");
  2678. return Kchar;
  2679. case 'z':
  2680. return Kzstr;
  2681. case 'x':
  2682. *size = 1;
  2683. return Kpadding;
  2684. case 'X':
  2685. return Kpaddalign;
  2686. case ' ':
  2687. break;
  2688. case '<':
  2689. h->islittle = 1;
  2690. break;
  2691. case '>':
  2692. h->islittle = 0;
  2693. break;
  2694. case '=':
  2695. h->islittle = nativeendian.little;
  2696. break;
  2697. case '!':
  2698. h->maxalign = getnumlimit (h, fmt, MAXALIGN);
  2699. break;
  2700. default:
  2701. luaL_error (h->L, "invalid format option '%c'", opt);
  2702. }
  2703. return Knop;
  2704. }
  2705. /*
  2706. ** Read, classify, and fill other details about the next option.
  2707. ** 'psize' is filled with option's size, 'notoalign' with its
  2708. ** alignment requirements.
  2709. ** Local variable 'size' gets the size to be aligned. (Kpadal option
  2710. ** always gets its full alignment, other options are limited by
  2711. ** the maximum alignment ('maxalign'). Kchar option needs no alignment
  2712. ** despite its size.
  2713. */
  2714. static KOption
  2715. getdetails (Header *h, size_t totalsize,
  2716. const char **fmt, int *psize, int *ntoalign)
  2717. {
  2718. KOption opt = getoption (h, fmt, psize);
  2719. int align = *psize; /* usually, alignment follows size */
  2720. if (opt == Kpaddalign) { /* 'X' gets alignment from following option */
  2721. if (**fmt == '\0' || getoption (h, fmt, &align) == Kchar || align == 0)
  2722. luaL_argerror (h->L, 1, "invalid next option for option 'X'");
  2723. }
  2724. if (align <= 1 || opt == Kchar) /* need no alignment? */
  2725. *ntoalign = 0;
  2726. else {
  2727. if (align > h->maxalign) /* enforce maximum alignment */
  2728. align = h->maxalign;
  2729. if ((align & (align - 1)) != 0) /* is 'align' not a power of 2? */
  2730. luaL_argerror (h->L, 1, "format asks for alignment not power of 2");
  2731. *ntoalign = (align - (int) (totalsize & (align - 1))) & (align - 1);
  2732. }
  2733. return opt;
  2734. }
  2735. /*
  2736. ** Pack integer 'n' with 'size' bytes and 'islittle' endianness.
  2737. ** The final 'if' handles the case when 'size' is larger than
  2738. ** the size of a Lua integer, correcting the extra sign-extension
  2739. ** bytes if necessary (by default they would be zeros).
  2740. */
  2741. static void
  2742. packint (luaL_Buffer *b, lua_Unsigned n,
  2743. int islittle, int size, int neg)
  2744. {
  2745. char *buff = luaL_prepbuffsize (b, size);
  2746. int i;
  2747. buff[islittle ? 0 : size - 1] = (char) (n & MC); /* first byte */
  2748. for (i = 1; i < size; i++) {
  2749. n >>= NB;
  2750. buff[islittle ? i : size - 1 - i] = (char) (n & MC);
  2751. }
  2752. if (neg && size > SZINT) { /* negative number need sign extension? */
  2753. for (i = SZINT; i < size; i++) /* correct extra bytes */
  2754. buff[islittle ? i : size - 1 - i] = (char) MC;
  2755. }
  2756. luaL_addsize(b, size); /* add result to buffer */
  2757. }
  2758. /*
  2759. ** Copy 'size' bytes from 'src' to 'dest', correcting endianness if
  2760. ** given 'islittle' is different from native endianness.
  2761. */
  2762. static void
  2763. copywithendian (volatile char *dest, volatile const char *src,
  2764. int size, int islittle)
  2765. {
  2766. if (islittle == nativeendian.little) {
  2767. while (size-- != 0)
  2768. *(dest++) = *(src++);
  2769. }
  2770. else {
  2771. dest += size - 1;
  2772. while (size-- != 0)
  2773. *(dest--) = *(src++);
  2774. }
  2775. }
  2776. static int
  2777. lua_util_pack (lua_State *L)
  2778. {
  2779. luaL_Buffer b;
  2780. Header h;
  2781. const char *fmt = luaL_checkstring(L, 1); /* format string */
  2782. int arg = 1; /* current argument to pack */
  2783. size_t totalsize = 0; /* accumulate total size of result */
  2784. initheader (L, &h);
  2785. lua_pushnil (L); /* mark to separate arguments from string buffer */
  2786. luaL_buffinit (L, &b);
  2787. while (*fmt != '\0') {
  2788. int size, ntoalign;
  2789. KOption opt = getdetails (&h, totalsize, &fmt, &size, &ntoalign);
  2790. totalsize += ntoalign + size;
  2791. while (ntoalign-- > 0)
  2792. luaL_addchar(&b, LUA_PACKPADBYTE); /* fill alignment */
  2793. arg++;
  2794. switch (opt) {
  2795. case Kint: { /* signed integers */
  2796. lua_Integer n = luaL_checkinteger (L, arg);
  2797. if (size < SZINT) { /* need overflow check? */
  2798. lua_Integer lim = (lua_Integer) 1 << ((size * NB) - 1);
  2799. luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow");
  2800. }
  2801. packint (&b, (lua_Unsigned) n, h.islittle, size, (n < 0));
  2802. break;
  2803. }
  2804. case Kuint: { /* unsigned integers */
  2805. lua_Integer n = luaL_checkinteger (L, arg);
  2806. if (size < SZINT) /* need overflow check? */
  2807. luaL_argcheck(L,
  2808. (lua_Unsigned) n < ((lua_Unsigned) 1 << (size * NB)),
  2809. arg,
  2810. "unsigned overflow");
  2811. packint (&b, (lua_Unsigned) n, h.islittle, size, 0);
  2812. break;
  2813. }
  2814. case Kfloat: { /* floating-point options */
  2815. volatile Ftypes u;
  2816. char *buff = luaL_prepbuffsize (&b, size);
  2817. lua_Number n = luaL_checknumber (L, arg); /* get argument */
  2818. if (size == sizeof (u.f))
  2819. u.f = (float) n; /* copy it into 'u' */
  2820. else if (size == sizeof (u.d))
  2821. u.d = (double) n;
  2822. else
  2823. u.n = n;
  2824. /* move 'u' to final result, correcting endianness if needed */
  2825. copywithendian (buff, u.buff, size, h.islittle);
  2826. luaL_addsize(&b, size);
  2827. break;
  2828. }
  2829. case Kchar: { /* fixed-size string */
  2830. size_t len;
  2831. const char *s = luaL_checklstring (L, arg, &len);
  2832. if ((size_t) size <=
  2833. len) /* string larger than (or equal to) needed? */
  2834. luaL_addlstring (&b,
  2835. s,
  2836. size); /* truncate string to asked size */
  2837. else { /* string smaller than needed */
  2838. luaL_addlstring (&b, s, len); /* add it all */
  2839. while (len++ < (size_t) size) /* pad extra space */
  2840. luaL_addchar(&b, LUA_PACKPADBYTE);
  2841. }
  2842. break;
  2843. }
  2844. case Kstring: { /* strings with length count */
  2845. size_t len;
  2846. const char *s = luaL_checklstring (L, arg, &len);
  2847. luaL_argcheck(L, size >= (int) sizeof (size_t) ||
  2848. len < ((size_t) 1 << (size * NB)),
  2849. arg, "string length does not fit in given size");
  2850. packint (&b,
  2851. (lua_Unsigned) len,
  2852. h.islittle,
  2853. size,
  2854. 0); /* pack length */
  2855. luaL_addlstring (&b, s, len);
  2856. totalsize += len;
  2857. break;
  2858. }
  2859. case Kzstr: { /* zero-terminated string */
  2860. size_t len;
  2861. const char *s = luaL_checklstring (L, arg, &len);
  2862. luaL_argcheck(L, strlen (s) == len, arg, "string contains zeros");
  2863. luaL_addlstring (&b, s, len);
  2864. luaL_addchar(&b, '\0'); /* add zero at the end */
  2865. totalsize += len + 1;
  2866. break;
  2867. }
  2868. case Kpadding:
  2869. luaL_addchar(&b, LUA_PACKPADBYTE); /* FALLTHROUGH */
  2870. case Kpaddalign:
  2871. case Knop:
  2872. arg--; /* undo increment */
  2873. break;
  2874. }
  2875. }
  2876. luaL_pushresult (&b);
  2877. return 1;
  2878. }
  2879. static int
  2880. lua_util_packsize (lua_State *L)
  2881. {
  2882. Header h;
  2883. const char *fmt = luaL_checkstring(L, 1); /* format string */
  2884. size_t totalsize = 0; /* accumulate total size of result */
  2885. initheader (L, &h);
  2886. while (*fmt != '\0') {
  2887. int size, ntoalign;
  2888. KOption opt = getdetails (&h, totalsize, &fmt, &size, &ntoalign);
  2889. size += ntoalign; /* total space used by option */
  2890. luaL_argcheck(L, totalsize <= MAXSIZE - size, 1,
  2891. "format result too large");
  2892. totalsize += size;
  2893. switch (opt) {
  2894. case Kstring: /* strings with length count */
  2895. case Kzstr: /* zero-terminated string */
  2896. luaL_argerror (L, 1, "variable-length format");
  2897. /* call never return, but to avoid warnings: *//* FALLTHROUGH */
  2898. default:
  2899. break;
  2900. }
  2901. }
  2902. lua_pushinteger (L, (lua_Integer) totalsize);
  2903. return 1;
  2904. }
  2905. /*
  2906. ** Unpack an integer with 'size' bytes and 'islittle' endianness.
  2907. ** If size is smaller than the size of a Lua integer and integer
  2908. ** is signed, must do sign extension (propagating the sign to the
  2909. ** higher bits); if size is larger than the size of a Lua integer,
  2910. ** it must check the unread bytes to see whether they do not cause an
  2911. ** overflow.
  2912. */
  2913. static lua_Integer
  2914. unpackint (lua_State *L, const char *str,
  2915. int islittle, int size, int issigned)
  2916. {
  2917. lua_Unsigned res = 0;
  2918. int i;
  2919. int limit = (size <= SZINT) ? size : SZINT;
  2920. for (i = limit - 1; i >= 0; i--) {
  2921. res <<= NB;
  2922. res |= (lua_Unsigned) (
  2923. unsigned char)str[islittle ? i : size - 1 - i];
  2924. }
  2925. if (size < SZINT) { /* real size smaller than lua_Integer? */
  2926. if (issigned) { /* needs sign extension? */
  2927. lua_Unsigned mask = (lua_Unsigned) 1 << (size * NB - 1);
  2928. res = ((res ^ mask) - mask); /* do sign extension */
  2929. }
  2930. }
  2931. else if (size > SZINT) { /* must check unread bytes */
  2932. int mask = (!issigned || (lua_Integer) res >= 0) ? 0 : MC;
  2933. for (i = limit; i < size; i++) {
  2934. if ((unsigned char) str[islittle ? i : size - 1 - i] != mask)
  2935. luaL_error (L,
  2936. "%d-byte integer does not fit into Lua Integer",
  2937. size);
  2938. }
  2939. }
  2940. return (lua_Integer) res;
  2941. }
  2942. static lua_Integer
  2943. posrelat (lua_Integer pos, size_t len)
  2944. {
  2945. if (pos >= 0)
  2946. return pos;
  2947. else if (0u - (size_t) pos > len)
  2948. return 0;
  2949. else
  2950. return (lua_Integer) len + pos + 1;
  2951. }
  2952. static int
  2953. lua_util_unpack (lua_State *L)
  2954. {
  2955. Header h;
  2956. const char *fmt = luaL_checkstring(L, 1);
  2957. size_t ld;
  2958. const char *data = luaL_checklstring (L, 2, &ld);
  2959. size_t pos = (size_t) posrelat (luaL_optinteger (L, 3, 1), ld) - 1;
  2960. int n = 0; /* number of results */
  2961. luaL_argcheck(L, pos <= ld, 3, "initial position out of string");
  2962. initheader (L, &h);
  2963. while (*fmt != '\0') {
  2964. int size, ntoalign;
  2965. KOption opt = getdetails (&h, pos, &fmt, &size, &ntoalign);
  2966. if ((size_t) ntoalign + size > ~pos || pos + ntoalign + size > ld)
  2967. luaL_argerror (L, 2, "data string too short");
  2968. pos += ntoalign; /* skip alignment */
  2969. /* stack space for item + next position */
  2970. luaL_checkstack (L, 2, "too many results");
  2971. n++;
  2972. switch (opt) {
  2973. case Kint:
  2974. case Kuint: {
  2975. lua_Integer res = unpackint (L, data + pos, h.islittle, size,
  2976. (opt == Kint));
  2977. lua_pushinteger (L, res);
  2978. break;
  2979. }
  2980. case Kfloat: {
  2981. volatile Ftypes u;
  2982. lua_Number num;
  2983. copywithendian (u.buff, data + pos, size, h.islittle);
  2984. if (size == sizeof (u.f))
  2985. num = (lua_Number) u.f;
  2986. else if (size == sizeof (u.d))
  2987. num = (lua_Number) u.d;
  2988. else
  2989. num = u.n;
  2990. lua_pushnumber (L, num);
  2991. break;
  2992. }
  2993. case Kchar: {
  2994. lua_pushlstring (L, data + pos, size);
  2995. break;
  2996. }
  2997. case Kstring: {
  2998. size_t len = (size_t) unpackint (L,
  2999. data + pos,
  3000. h.islittle,
  3001. size,
  3002. 0);
  3003. luaL_argcheck(L,
  3004. pos + len + size <= ld,
  3005. 2,
  3006. "data string too short");
  3007. lua_pushlstring (L, data + pos + size, len);
  3008. pos += len; /* skip string */
  3009. break;
  3010. }
  3011. case Kzstr: {
  3012. size_t len = (int) strlen (data + pos);
  3013. lua_pushlstring (L, data + pos, len);
  3014. pos += len + 1; /* skip string plus final '\0' */
  3015. break;
  3016. }
  3017. case Kpaddalign:
  3018. case Kpadding:
  3019. case Knop:
  3020. n--; /* undo increment */
  3021. break;
  3022. }
  3023. pos += size;
  3024. }
  3025. lua_pushinteger (L, pos + 1); /* next position */
  3026. return n + 1;
  3027. }
  3028. static gint
  3029. lua_load_util (lua_State * L)
  3030. {
  3031. lua_newtable (L);
  3032. luaL_register (L, NULL, utillib_f);
  3033. return 1;
  3034. }
  3035. void
  3036. luaopen_util (lua_State * L)
  3037. {
  3038. rspamd_lua_new_class (L, "rspamd{ev_base}", ev_baselib_m);
  3039. lua_pop (L, 1);
  3040. rspamd_lua_new_class (L, "rspamd{int64}", int64lib_m);
  3041. lua_pop (L, 1);
  3042. rspamd_lua_add_preload (L, "rspamd_util", lua_load_util);
  3043. }
  3044. static int
  3045. lua_int64_tostring (lua_State *L)
  3046. {
  3047. gint64 n = lua_check_int64 (L, 1);
  3048. gchar buf[32];
  3049. rspamd_snprintf (buf, sizeof (buf), "%uL", n);
  3050. lua_pushstring (L, buf);
  3051. return 1;
  3052. }
  3053. static int
  3054. lua_int64_tonumber (lua_State *L)
  3055. {
  3056. gint64 n = lua_check_int64 (L, 1);
  3057. gdouble d;
  3058. d = n;
  3059. lua_pushnumber (L, d);
  3060. return 1;
  3061. }
  3062. static int
  3063. lua_int64_hex (lua_State *L)
  3064. {
  3065. gint64 n = lua_check_int64 (L, 1);
  3066. gchar buf[32];
  3067. rspamd_snprintf (buf, sizeof (buf), "%XL", n);
  3068. lua_pushstring (L, buf);
  3069. return 1;
  3070. }
  3071. static int
  3072. lua_ev_base_loop (lua_State *L)
  3073. {
  3074. int flags = 0;
  3075. struct event_base *ev_base;
  3076. ev_base = lua_check_ev_base (L, 1);
  3077. if (lua_isnumber (L, 2)) {
  3078. flags = lua_tonumber (L, 2);
  3079. }
  3080. int ret = event_base_loop (ev_base, flags);
  3081. lua_pushinteger (L, ret);
  3082. return 1;
  3083. }