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 79KB

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