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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577
  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 represented 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 quoted 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 quoted 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 tangent of the specified floating point value
  120. * @param {number} num input number
  121. * @return {number} hyperbolic tangent 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, fromstring);
  655. LUA_FUNCTION_DEF (int64, tonumber);
  656. LUA_FUNCTION_DEF (int64, hex);
  657. static const struct luaL_reg int64lib_f[] = {
  658. LUA_INTERFACE_DEF (int64, fromstring),
  659. {NULL, NULL}
  660. };
  661. static const struct luaL_reg int64lib_m[] = {
  662. LUA_INTERFACE_DEF (int64, tostring),
  663. LUA_INTERFACE_DEF (int64, tonumber),
  664. LUA_INTERFACE_DEF (int64, hex),
  665. {"__tostring", lua_int64_tostring},
  666. {NULL, NULL}
  667. };
  668. LUA_FUNCTION_DEF (ev_base, loop);
  669. static const struct luaL_reg ev_baselib_m[] = {
  670. LUA_INTERFACE_DEF (ev_base, loop),
  671. {"__tostring", rspamd_lua_class_tostring},
  672. {NULL, NULL}
  673. };
  674. static gint64
  675. lua_check_int64 (lua_State * L, gint pos)
  676. {
  677. void *ud = rspamd_lua_check_udata (L, pos, "rspamd{int64}");
  678. luaL_argcheck (L, ud != NULL, pos, "'int64' expected");
  679. return ud ? *((gint64 *)ud) : 0LL;
  680. }
  681. static gint
  682. lua_util_create_event_base (lua_State *L)
  683. {
  684. LUA_TRACE_POINT;
  685. struct ev_loop **pev_base;
  686. pev_base = lua_newuserdata (L, sizeof (struct ev_loop *));
  687. rspamd_lua_setclass (L, "rspamd{ev_base}", -1);
  688. *pev_base = ev_loop_new (EVFLAG_SIGNALFD|EVBACKEND_ALL);
  689. return 1;
  690. }
  691. static gint
  692. lua_util_load_rspamd_config (lua_State *L)
  693. {
  694. LUA_TRACE_POINT;
  695. struct rspamd_config *cfg, **pcfg;
  696. const gchar *cfg_name;
  697. cfg_name = luaL_checkstring (L, 1);
  698. if (cfg_name) {
  699. cfg = rspamd_config_new (RSPAMD_CONFIG_INIT_SKIP_LUA);
  700. cfg->lua_state = L;
  701. if (rspamd_config_read (cfg, cfg_name, NULL, NULL, NULL, FALSE, NULL)) {
  702. msg_err_config ("cannot load config from %s", cfg_name);
  703. lua_pushnil (L);
  704. }
  705. else {
  706. rspamd_config_post_load (cfg, 0);
  707. pcfg = lua_newuserdata (L, sizeof (struct rspamd_config *));
  708. rspamd_lua_setclass (L, "rspamd{config}", -1);
  709. *pcfg = cfg;
  710. }
  711. }
  712. return 1;
  713. }
  714. static gint
  715. parse_config_options (const char *str_options)
  716. {
  717. gint ret = 0;
  718. gchar **vec;
  719. const gchar *str;
  720. guint i, l;
  721. vec = g_strsplit_set (str_options, ",;", -1);
  722. if (vec) {
  723. l = g_strv_length (vec);
  724. for (i = 0; i < l; i ++) {
  725. str = vec[i];
  726. if (g_ascii_strcasecmp (str, "INIT_URL") == 0) {
  727. ret |= RSPAMD_CONFIG_INIT_URL;
  728. } else if (g_ascii_strcasecmp (str, "INIT_LIBS") == 0) {
  729. ret |= RSPAMD_CONFIG_INIT_LIBS;
  730. } else if (g_ascii_strcasecmp (str, "INIT_SYMCACHE") == 0) {
  731. ret |= RSPAMD_CONFIG_INIT_SYMCACHE;
  732. } else if (g_ascii_strcasecmp (str, "INIT_VALIDATE") == 0) {
  733. ret |= RSPAMD_CONFIG_INIT_VALIDATE;
  734. } else if (g_ascii_strcasecmp (str, "INIT_NO_TLD") == 0) {
  735. ret |= RSPAMD_CONFIG_INIT_NO_TLD;
  736. } else if (g_ascii_strcasecmp (str, "INIT_PRELOAD_MAPS") == 0) {
  737. ret |= RSPAMD_CONFIG_INIT_PRELOAD_MAPS;
  738. } else {
  739. msg_warn ("bad type: %s", str);
  740. }
  741. }
  742. g_strfreev (vec);
  743. }
  744. return ret;
  745. }
  746. static gint
  747. lua_util_config_from_ucl (lua_State *L)
  748. {
  749. LUA_TRACE_POINT;
  750. struct rspamd_config *cfg = NULL, **pcfg;
  751. struct rspamd_rcl_section *top;
  752. GError *err = NULL;
  753. ucl_object_t *obj;
  754. const char *str_options = NULL;
  755. gint int_options = 0;
  756. obj = ucl_object_lua_import (L, 1);
  757. if (lua_gettop (L) == 2) {
  758. if (lua_type (L, 2) == LUA_TSTRING) {
  759. str_options = lua_tostring (L, 2);
  760. int_options = parse_config_options(str_options);
  761. }
  762. else {
  763. msg_err ("config_from_ucl: second parameter is expected to be string");
  764. ucl_object_unref (obj);
  765. lua_pushnil (L);
  766. }
  767. }
  768. if (obj) {
  769. cfg = rspamd_config_new (RSPAMD_CONFIG_INIT_SKIP_LUA);
  770. cfg->lua_state = L;
  771. cfg->rcl_obj = obj;
  772. top = rspamd_rcl_config_init (cfg, NULL);
  773. if (!rspamd_rcl_parse (top, cfg, cfg, cfg->cfg_pool, cfg->rcl_obj, &err)) {
  774. msg_err ("rcl parse error: %s", err->message);
  775. ucl_object_unref (obj);
  776. lua_pushnil (L);
  777. }
  778. else {
  779. if (int_options & RSPAMD_CONFIG_INIT_LIBS) {
  780. cfg->libs_ctx = rspamd_init_libs ();
  781. }
  782. rspamd_config_post_load (cfg, int_options);
  783. pcfg = lua_newuserdata (L, sizeof (struct rspamd_config *));
  784. rspamd_lua_setclass (L, "rspamd{config}", -1);
  785. *pcfg = cfg;
  786. }
  787. }
  788. return 1;
  789. }
  790. static gboolean
  791. lua_util_task_fin (struct rspamd_task *task, void *ud)
  792. {
  793. ucl_object_t **target = ud;
  794. *target = rspamd_protocol_write_ucl (task, RSPAMD_PROTOCOL_DEFAULT);
  795. rdns_resolver_release (task->resolver->r);
  796. return TRUE;
  797. }
  798. static gint
  799. lua_util_process_message (lua_State *L)
  800. {
  801. LUA_TRACE_POINT;
  802. struct rspamd_config *cfg = lua_check_config (L, 1);
  803. const gchar *message;
  804. gsize mlen;
  805. struct rspamd_task *task;
  806. struct ev_loop *base;
  807. ucl_object_t *res = NULL;
  808. message = luaL_checklstring (L, 2, &mlen);
  809. if (cfg != NULL && message != NULL) {
  810. base = ev_loop_new (EVFLAG_SIGNALFD|EVBACKEND_ALL);
  811. rspamd_init_filters (cfg, false, false);
  812. task = rspamd_task_new (NULL, cfg, NULL, NULL, base, FALSE);
  813. task->msg.begin = rspamd_mempool_alloc (task->task_pool, mlen);
  814. rspamd_strlcpy ((gpointer)task->msg.begin, message, mlen);
  815. task->msg.len = mlen;
  816. task->fin_callback = lua_util_task_fin;
  817. task->fin_arg = &res;
  818. task->resolver = rspamd_dns_resolver_init (NULL, base, cfg);
  819. task->s = rspamd_session_create (task->task_pool, rspamd_task_fin,
  820. rspamd_task_restore, (event_finalizer_t)rspamd_task_free, task);
  821. if (!rspamd_task_load_message (task, NULL, message, mlen)) {
  822. lua_pushnil (L);
  823. }
  824. else {
  825. if (rspamd_task_process (task, RSPAMD_TASK_PROCESS_ALL)) {
  826. ev_loop (base, 0);
  827. if (res != NULL) {
  828. ucl_object_push_lua (L, res, true);
  829. ucl_object_unref (res);
  830. }
  831. else {
  832. ucl_object_push_lua (L,
  833. rspamd_protocol_write_ucl (task, RSPAMD_PROTOCOL_DEFAULT),
  834. true);
  835. rdns_resolver_release (task->resolver->r);
  836. rspamd_session_destroy (task->s);
  837. }
  838. }
  839. else {
  840. lua_pushnil (L);
  841. }
  842. }
  843. ev_loop_destroy (base);
  844. }
  845. else {
  846. lua_pushnil (L);
  847. }
  848. return 1;
  849. }
  850. static gint
  851. lua_util_encode_base64 (lua_State *L)
  852. {
  853. LUA_TRACE_POINT;
  854. struct rspamd_lua_text *t;
  855. const gchar *s = NULL;
  856. gchar *out;
  857. gsize inlen, outlen;
  858. guint str_lim = 0;
  859. gboolean fold = FALSE;
  860. if (lua_type (L, 1) == LUA_TSTRING) {
  861. s = luaL_checklstring (L, 1, &inlen);
  862. }
  863. else if (lua_type (L, 1) == LUA_TUSERDATA) {
  864. t = lua_check_text (L, 1);
  865. if (t != NULL) {
  866. s = t->start;
  867. inlen = t->len;
  868. }
  869. }
  870. if (lua_gettop (L) > 1) {
  871. str_lim = luaL_checknumber (L, 2);
  872. fold = !!(str_lim > 0);
  873. }
  874. if (s == NULL) {
  875. lua_pushnil (L);
  876. }
  877. else {
  878. if (fold) {
  879. out = rspamd_encode_base64 (s, inlen, str_lim, &outlen);
  880. }
  881. else {
  882. enum rspamd_newlines_type how = RSPAMD_TASK_NEWLINES_CRLF;
  883. if (lua_type (L, 3) == LUA_TSTRING) {
  884. const gchar *how_str = lua_tostring (L, 3);
  885. if (g_ascii_strcasecmp (how_str, "cr") == 0) {
  886. how = RSPAMD_TASK_NEWLINES_CR;
  887. }
  888. else if (g_ascii_strcasecmp (how_str, "lf") == 0) {
  889. how = RSPAMD_TASK_NEWLINES_LF;
  890. }
  891. else if (g_ascii_strcasecmp (how_str, "crlf") != 0) {
  892. return luaL_error (L, "invalid newline style: %s", how_str);
  893. }
  894. }
  895. out = rspamd_encode_base64_fold (s, inlen, str_lim, &outlen, how);
  896. }
  897. if (out != NULL) {
  898. t = lua_newuserdata (L, sizeof (*t));
  899. rspamd_lua_setclass (L, "rspamd{text}", -1);
  900. t->start = out;
  901. t->len = outlen;
  902. /* Need destruction */
  903. t->flags = RSPAMD_TEXT_FLAG_OWN;
  904. }
  905. else {
  906. lua_pushnil (L);
  907. }
  908. }
  909. return 1;
  910. }
  911. static gint
  912. lua_util_encode_qp (lua_State *L)
  913. {
  914. LUA_TRACE_POINT;
  915. struct rspamd_lua_text *t;
  916. const gchar *s = NULL;
  917. gchar *out;
  918. gsize inlen, outlen;
  919. guint str_lim = 0;
  920. if (lua_type (L, 1) == LUA_TSTRING) {
  921. s = luaL_checklstring (L, 1, &inlen);
  922. }
  923. else if (lua_type (L, 1) == LUA_TUSERDATA) {
  924. t = lua_check_text (L, 1);
  925. if (t != NULL) {
  926. s = t->start;
  927. inlen = t->len;
  928. }
  929. }
  930. if (lua_gettop (L) > 1) {
  931. str_lim = luaL_checknumber (L, 2);
  932. }
  933. if (s == NULL) {
  934. lua_pushnil (L);
  935. }
  936. else {
  937. enum rspamd_newlines_type how = RSPAMD_TASK_NEWLINES_CRLF;
  938. if (lua_type (L, 3) == LUA_TSTRING) {
  939. const gchar *how_str = lua_tostring (L, 3);
  940. if (g_ascii_strcasecmp (how_str, "cr") == 0) {
  941. how = RSPAMD_TASK_NEWLINES_CR;
  942. }
  943. else if (g_ascii_strcasecmp (how_str, "lf") == 0) {
  944. how = RSPAMD_TASK_NEWLINES_LF;
  945. }
  946. else if (g_ascii_strcasecmp (how_str, "crlf") != 0) {
  947. return luaL_error (L, "invalid newline style: %s", how_str);
  948. }
  949. }
  950. out = rspamd_encode_qp_fold (s, inlen, str_lim, &outlen, how);
  951. if (out != NULL) {
  952. t = lua_newuserdata (L, sizeof (*t));
  953. rspamd_lua_setclass (L, "rspamd{text}", -1);
  954. t->start = out;
  955. t->len = outlen;
  956. /* Need destruction */
  957. t->flags = RSPAMD_TEXT_FLAG_OWN;
  958. }
  959. else {
  960. lua_pushnil (L);
  961. }
  962. }
  963. return 1;
  964. }
  965. static gint
  966. lua_util_decode_qp (lua_State *L)
  967. {
  968. LUA_TRACE_POINT;
  969. struct rspamd_lua_text *t, *out;
  970. const gchar *s = NULL;
  971. gsize inlen = 0;
  972. gssize outlen;
  973. if (lua_type (L, 1) == LUA_TSTRING) {
  974. s = luaL_checklstring (L, 1, &inlen);
  975. }
  976. else if (lua_type (L, 1) == LUA_TUSERDATA) {
  977. t = lua_check_text (L, 1);
  978. if (t != NULL) {
  979. s = t->start;
  980. inlen = t->len;
  981. }
  982. }
  983. if (s == NULL) {
  984. lua_pushnil (L);
  985. }
  986. else {
  987. out = lua_newuserdata (L, sizeof (*t));
  988. rspamd_lua_setclass (L, "rspamd{text}", -1);
  989. out->start = g_malloc (inlen + 1);
  990. out->flags = RSPAMD_TEXT_FLAG_OWN;
  991. outlen = rspamd_decode_qp_buf (s, inlen, (gchar *)out->start, inlen + 1);
  992. if (outlen > 0) {
  993. out->len = outlen;
  994. }
  995. else {
  996. /*
  997. * It removes out and frees memory on gc due to RSPAMD_TEXT_FLAG_OWN
  998. */
  999. lua_pop (L, 1);
  1000. lua_pushnil (L);
  1001. }
  1002. }
  1003. return 1;
  1004. }
  1005. static gint
  1006. lua_util_decode_base64 (lua_State *L)
  1007. {
  1008. LUA_TRACE_POINT;
  1009. struct rspamd_lua_text *t;
  1010. const gchar *s = NULL;
  1011. gsize inlen = 0, outlen;
  1012. if (lua_type (L, 1) == LUA_TSTRING) {
  1013. s = luaL_checklstring (L, 1, &inlen);
  1014. }
  1015. else if (lua_type (L, 1) == LUA_TUSERDATA) {
  1016. t = lua_check_text (L, 1);
  1017. if (t != NULL) {
  1018. s = t->start;
  1019. inlen = t->len;
  1020. }
  1021. }
  1022. if (s != NULL) {
  1023. t = lua_newuserdata (L, sizeof (*t));
  1024. rspamd_lua_setclass (L, "rspamd{text}", -1);
  1025. t->len = (inlen / 4) * 3 + 3;
  1026. t->start = g_malloc (t->len);
  1027. rspamd_cryptobox_base64_decode (s, inlen, (guchar *)t->start,
  1028. &outlen);
  1029. t->len = outlen;
  1030. t->flags = RSPAMD_TEXT_FLAG_OWN;
  1031. }
  1032. else {
  1033. lua_pushnil (L);
  1034. }
  1035. return 1;
  1036. }
  1037. static gint
  1038. lua_util_encode_base32 (lua_State *L)
  1039. {
  1040. LUA_TRACE_POINT;
  1041. struct rspamd_lua_text *t;
  1042. const gchar *s = NULL;
  1043. gchar *out;
  1044. enum rspamd_base32_type btype = RSPAMD_BASE32_DEFAULT;
  1045. gsize inlen, outlen;
  1046. if (lua_type (L, 1) == LUA_TSTRING) {
  1047. s = luaL_checklstring (L, 1, &inlen);
  1048. }
  1049. else if (lua_type (L, 1) == LUA_TUSERDATA) {
  1050. t = lua_check_text (L, 1);
  1051. if (t != NULL) {
  1052. s = t->start;
  1053. inlen = t->len;
  1054. }
  1055. }
  1056. if (lua_type (L, 2) == LUA_TSTRING) {
  1057. btype = rspamd_base32_decode_type_from_str (lua_tostring (L, 2));
  1058. if (btype == RSPAMD_BASE32_INVALID) {
  1059. return luaL_error (L, "invalid b32 type: %s", lua_tostring (L, 2));
  1060. }
  1061. }
  1062. if (s == NULL) {
  1063. return luaL_error (L, "invalid arguments");
  1064. }
  1065. else {
  1066. out = rspamd_encode_base32 (s, inlen, btype);
  1067. if (out != NULL) {
  1068. t = lua_newuserdata (L, sizeof (*t));
  1069. outlen = strlen (out);
  1070. rspamd_lua_setclass (L, "rspamd{text}", -1);
  1071. t->start = out;
  1072. t->len = outlen;
  1073. /* Need destruction */
  1074. t->flags = RSPAMD_TEXT_FLAG_OWN;
  1075. }
  1076. else {
  1077. lua_pushnil (L);
  1078. }
  1079. }
  1080. return 1;
  1081. }
  1082. static gint
  1083. lua_util_decode_base32 (lua_State *L)
  1084. {
  1085. LUA_TRACE_POINT;
  1086. struct rspamd_lua_text *t;
  1087. const gchar *s = NULL;
  1088. gsize inlen, outlen;
  1089. enum rspamd_base32_type btype = RSPAMD_BASE32_DEFAULT;
  1090. if (lua_type (L, 1) == LUA_TSTRING) {
  1091. s = luaL_checklstring (L, 1, &inlen);
  1092. }
  1093. else if (lua_type (L, 1) == LUA_TUSERDATA) {
  1094. t = lua_check_text (L, 1);
  1095. if (t != NULL) {
  1096. s = t->start;
  1097. inlen = t->len;
  1098. }
  1099. }
  1100. if (lua_type (L, 2) == LUA_TSTRING) {
  1101. btype = rspamd_base32_decode_type_from_str (lua_tostring (L, 2));
  1102. if (btype == RSPAMD_BASE32_INVALID) {
  1103. return luaL_error (L, "invalid b32 type: %s", lua_tostring (L, 2));
  1104. }
  1105. }
  1106. if (s != NULL) {
  1107. guchar *decoded;
  1108. decoded = rspamd_decode_base32 (s, inlen, &outlen, btype);
  1109. if (decoded) {
  1110. t = lua_newuserdata (L, sizeof (*t));
  1111. rspamd_lua_setclass (L, "rspamd{text}", -1);
  1112. t->start = (const gchar *)decoded;
  1113. t->len = outlen;
  1114. t->flags = RSPAMD_TEXT_FLAG_OWN;
  1115. }
  1116. else {
  1117. lua_pushnil (L);
  1118. }
  1119. }
  1120. else {
  1121. lua_pushnil (L);
  1122. }
  1123. return 1;
  1124. }
  1125. static gint
  1126. lua_util_decode_url (lua_State *L)
  1127. {
  1128. LUA_TRACE_POINT;
  1129. struct rspamd_lua_text *t;
  1130. const gchar *s = NULL;
  1131. gsize inlen;
  1132. if (lua_type (L, 1) == LUA_TSTRING) {
  1133. s = luaL_checklstring (L, 1, &inlen);
  1134. }
  1135. else if (lua_type (L, 1) == LUA_TUSERDATA) {
  1136. t = lua_check_text (L, 1);
  1137. if (t != NULL) {
  1138. s = t->start;
  1139. inlen = t->len;
  1140. }
  1141. }
  1142. if (s != NULL) {
  1143. t = lua_newuserdata (L, sizeof (*t));
  1144. rspamd_lua_setclass (L, "rspamd{text}", -1);
  1145. t->start = g_malloc (inlen);
  1146. memcpy ((char *)t->start, s, inlen);
  1147. t->len = rspamd_url_decode ((char *)t->start, s, inlen);
  1148. t->flags = RSPAMD_TEXT_FLAG_OWN;
  1149. }
  1150. else {
  1151. lua_pushnil (L);
  1152. }
  1153. return 1;
  1154. }
  1155. static gint
  1156. lua_util_tokenize_text (lua_State *L)
  1157. {
  1158. return lua_parsers_tokenize_text (L);
  1159. }
  1160. static gint
  1161. lua_util_tanh (lua_State *L)
  1162. {
  1163. LUA_TRACE_POINT;
  1164. gdouble in = luaL_checknumber (L, 1);
  1165. lua_pushnumber (L, tanh (in));
  1166. return 1;
  1167. }
  1168. static gint
  1169. lua_util_parse_html (lua_State *L)
  1170. {
  1171. return lua_parsers_parse_html (L);
  1172. }
  1173. static gint
  1174. lua_util_levenshtein_distance (lua_State *L)
  1175. {
  1176. LUA_TRACE_POINT;
  1177. const gchar *s1, *s2;
  1178. gsize s1len, s2len;
  1179. gint dist = 0;
  1180. guint replace_cost = 1;
  1181. s1 = luaL_checklstring (L, 1, &s1len);
  1182. s2 = luaL_checklstring (L, 2, &s2len);
  1183. if (lua_isnumber (L, 3)) {
  1184. replace_cost = lua_tonumber (L, 3);
  1185. }
  1186. if (s1 && s2) {
  1187. dist = rspamd_strings_levenshtein_distance (s1, s1len, s2, s2len,
  1188. replace_cost);
  1189. }
  1190. lua_pushinteger (L, dist);
  1191. return 1;
  1192. }
  1193. static gint
  1194. lua_util_fold_header (lua_State *L)
  1195. {
  1196. LUA_TRACE_POINT;
  1197. const gchar *how, *stop_chars = NULL;
  1198. struct rspamd_lua_text *name, *value;
  1199. GString *folded;
  1200. name = lua_check_text_or_string (L, 1);
  1201. value = lua_check_text_or_string (L, 2);
  1202. if (name && value) {
  1203. if (lua_isstring (L, 3)) {
  1204. how = lua_tostring (L, 3);
  1205. if (lua_isstring (L, 4)) {
  1206. stop_chars = lua_tostring (L, 4);
  1207. }
  1208. if (strcmp (how, "cr") == 0) {
  1209. folded = rspamd_header_value_fold (name->start, name->len,
  1210. value->start, value->len,
  1211. 0,
  1212. RSPAMD_TASK_NEWLINES_CR, stop_chars);
  1213. }
  1214. else if (strcmp (how, "lf") == 0) {
  1215. folded = rspamd_header_value_fold (name->start, name->len,
  1216. value->start, value->len, 0,
  1217. RSPAMD_TASK_NEWLINES_LF, stop_chars);
  1218. }
  1219. else {
  1220. folded = rspamd_header_value_fold (name->start, name->len,
  1221. value->start, value->len, 0,
  1222. RSPAMD_TASK_NEWLINES_CRLF, stop_chars);
  1223. }
  1224. }
  1225. else {
  1226. folded = rspamd_header_value_fold (name->start, name->len,
  1227. value->start, value->len, 0,
  1228. RSPAMD_TASK_NEWLINES_CRLF, stop_chars);
  1229. }
  1230. if (folded) {
  1231. lua_pushlstring (L, folded->str, folded->len);
  1232. g_string_free (folded, TRUE);
  1233. return 1;
  1234. }
  1235. }
  1236. lua_pushnil (L);
  1237. return 1;
  1238. }
  1239. static gint
  1240. lua_util_is_uppercase (lua_State *L)
  1241. {
  1242. LUA_TRACE_POINT;
  1243. const gchar *str;
  1244. gsize sz;
  1245. gint32 i = 0;
  1246. UChar32 uc;
  1247. guint nlc = 0, nuc = 0;
  1248. str = luaL_checklstring (L, 1, &sz);
  1249. if (str && sz > 0) {
  1250. while (i >= 0 && i < sz) {
  1251. U8_NEXT (str, i, sz, uc);
  1252. if (uc < 0) {
  1253. break;
  1254. }
  1255. if (u_isupper (uc)) {
  1256. nuc++;
  1257. }
  1258. else if (u_islower (uc)) {
  1259. nlc++;
  1260. }
  1261. }
  1262. }
  1263. if (nuc > 0 && nlc == 0) {
  1264. lua_pushboolean (L, TRUE);
  1265. }
  1266. else {
  1267. lua_pushboolean (L, FALSE);
  1268. }
  1269. return 1;
  1270. }
  1271. static gint
  1272. lua_util_humanize_number (lua_State *L)
  1273. {
  1274. LUA_TRACE_POINT;
  1275. gdouble number = luaL_checknumber (L, 1);
  1276. gchar numbuf[32];
  1277. rspamd_snprintf (numbuf, sizeof (numbuf), "%hL", (gint64)number);
  1278. lua_pushstring (L, numbuf);
  1279. return 1;
  1280. }
  1281. static gint
  1282. lua_util_get_tld (lua_State *L)
  1283. {
  1284. LUA_TRACE_POINT;
  1285. const gchar *host;
  1286. gsize hostlen;
  1287. rspamd_ftok_t tld;
  1288. host = luaL_checklstring (L, 1, &hostlen);
  1289. if (host) {
  1290. if (!rspamd_url_find_tld (host, hostlen, &tld)) {
  1291. lua_pushlstring (L, host, hostlen);
  1292. }
  1293. else {
  1294. lua_pushlstring (L, tld.begin, tld.len);
  1295. }
  1296. }
  1297. else {
  1298. lua_pushnil (L);
  1299. }
  1300. return 1;
  1301. }
  1302. static gint
  1303. lua_util_glob (lua_State *L)
  1304. {
  1305. LUA_TRACE_POINT;
  1306. const gchar *pattern;
  1307. glob_t gl;
  1308. gint top, i, flags = 0;
  1309. top = lua_gettop (L);
  1310. memset (&gl, 0, sizeof (gl));
  1311. for (i = 1; i <= top; i ++, flags |= GLOB_APPEND) {
  1312. pattern = luaL_checkstring (L, i);
  1313. if (pattern) {
  1314. if (glob (pattern, flags, NULL, &gl) != 0) {
  1315. /* There is no way to return error here, so just create an table */
  1316. lua_createtable (L, 0, 0);
  1317. globfree (&gl);
  1318. return 1;
  1319. }
  1320. }
  1321. }
  1322. lua_createtable (L, gl.gl_pathc, 0);
  1323. /* Push results */
  1324. for (i = 0; i < (gint)gl.gl_pathc; i ++) {
  1325. lua_pushstring (L, gl.gl_pathv[i]);
  1326. lua_rawseti (L, -2, i + 1);
  1327. }
  1328. globfree (&gl);
  1329. return 1;
  1330. }
  1331. static gint
  1332. lua_util_parse_mail_address (lua_State *L)
  1333. {
  1334. return lua_parsers_parse_mail_address (L);
  1335. }
  1336. static gint
  1337. lua_util_strlen_utf8 (lua_State *L)
  1338. {
  1339. LUA_TRACE_POINT;
  1340. struct rspamd_lua_text *t;
  1341. t = lua_check_text_or_string (L, 1);
  1342. if (t) {
  1343. gint32 i = 0, nchars = 0;
  1344. UChar32 uc;
  1345. while (i < t->len) {
  1346. U8_NEXT ((guint8 *)t->start, i, t->len, uc);
  1347. nchars ++;
  1348. }
  1349. lua_pushinteger (L, nchars);
  1350. }
  1351. else {
  1352. return luaL_error (L, "invalid arguments");
  1353. }
  1354. return 1;
  1355. }
  1356. static gint
  1357. lua_util_lower_utf8 (lua_State *L)
  1358. {
  1359. LUA_TRACE_POINT;
  1360. struct rspamd_lua_text *t;
  1361. gchar *dst;
  1362. UChar32 uc;
  1363. UBool err = 0;
  1364. gint32 i = 0, j = 0;
  1365. t = lua_check_text_or_string (L, 1);
  1366. if (t) {
  1367. dst = g_malloc (t->len);
  1368. while (i < t->len && err == 0) {
  1369. U8_NEXT ((guint8 *) t->start, i, t->len, uc);
  1370. uc = u_tolower (uc);
  1371. U8_APPEND (dst, j, t->len, uc, err);
  1372. }
  1373. if (lua_isstring (L, 1)) {
  1374. lua_pushlstring (L, dst, j);
  1375. g_free (dst);
  1376. }
  1377. else {
  1378. t = lua_new_text (L, dst, j, FALSE);
  1379. /* We have actually allocated text data before */
  1380. t->flags |= RSPAMD_TEXT_FLAG_OWN;
  1381. }
  1382. }
  1383. else {
  1384. return luaL_error (L, "invalid arguments");
  1385. }
  1386. return 1;
  1387. }
  1388. static gint
  1389. lua_util_strequal_caseless (lua_State *L)
  1390. {
  1391. LUA_TRACE_POINT;
  1392. struct rspamd_lua_text *t1, *t2;
  1393. gint ret = -1;
  1394. t1 = lua_check_text_or_string (L, 1);
  1395. t2 = lua_check_text_or_string (L, 2);
  1396. if (t1 && t2) {
  1397. if (t1->len == t2->len) {
  1398. ret = rspamd_lc_cmp (t1->start, t2->start, t1->len);
  1399. }
  1400. else {
  1401. ret = t1->len - t2->len;
  1402. }
  1403. }
  1404. else {
  1405. return luaL_error (L, "invalid arguments");
  1406. }
  1407. lua_pushboolean (L, (ret == 0) ? true : false);
  1408. return 1;
  1409. }
  1410. static gint
  1411. lua_util_strequal_caseless_utf8 (lua_State *L)
  1412. {
  1413. LUA_TRACE_POINT;
  1414. struct rspamd_lua_text *t1, *t2;
  1415. gint ret = -1;
  1416. t1 = lua_check_text_or_string (L, 1);
  1417. t2 = lua_check_text_or_string (L, 2);
  1418. if (t1 && t2) {
  1419. ret = rspamd_utf8_strcmp_sizes(t1->start, t1->len, t2->start, t2->len);
  1420. }
  1421. else {
  1422. return luaL_error (L, "invalid arguments");
  1423. }
  1424. lua_pushboolean (L, (ret == 0) ? true : false);
  1425. return 1;
  1426. }
  1427. static gint
  1428. lua_util_get_ticks (lua_State *L)
  1429. {
  1430. LUA_TRACE_POINT;
  1431. gdouble ticks;
  1432. gboolean rdtsc = FALSE;
  1433. if (lua_isboolean (L, 1)) {
  1434. rdtsc = lua_toboolean (L, 1);
  1435. }
  1436. ticks = rspamd_get_ticks (rdtsc);
  1437. lua_pushnumber (L, ticks);
  1438. return 1;
  1439. }
  1440. static gint
  1441. lua_util_get_time (lua_State *L)
  1442. {
  1443. LUA_TRACE_POINT;
  1444. lua_pushnumber (L, ev_time ());
  1445. return 1;
  1446. }
  1447. static gint
  1448. lua_util_time_to_string (lua_State *L)
  1449. {
  1450. LUA_TRACE_POINT;
  1451. gdouble seconds;
  1452. char timebuf[128];
  1453. if (lua_isnumber (L, 1)) {
  1454. seconds = lua_tonumber (L, 1);
  1455. }
  1456. else {
  1457. seconds = ev_time ();
  1458. }
  1459. rspamd_http_date_format (timebuf, sizeof (timebuf), seconds);
  1460. lua_pushstring (L, timebuf);
  1461. return 1;
  1462. }
  1463. static gint
  1464. lua_util_stat (lua_State *L)
  1465. {
  1466. LUA_TRACE_POINT;
  1467. const gchar *fpath;
  1468. struct stat st;
  1469. fpath = luaL_checkstring (L, 1);
  1470. if (fpath) {
  1471. if (stat (fpath, &st) == -1) {
  1472. lua_pushstring (L, strerror (errno));
  1473. lua_pushnil (L);
  1474. }
  1475. else {
  1476. lua_pushnil (L);
  1477. lua_createtable (L, 0, 3);
  1478. lua_pushstring (L, "size");
  1479. lua_pushinteger (L, st.st_size);
  1480. lua_settable (L, -3);
  1481. lua_pushstring (L, "mtime");
  1482. lua_pushinteger (L, st.st_mtime);
  1483. lua_settable (L, -3);
  1484. lua_pushstring (L, "type");
  1485. if (S_ISREG (st.st_mode)) {
  1486. lua_pushstring (L, "regular");
  1487. }
  1488. else if (S_ISDIR (st.st_mode)) {
  1489. lua_pushstring (L, "directory");
  1490. }
  1491. else {
  1492. lua_pushstring (L, "special");
  1493. }
  1494. lua_settable (L, -3);
  1495. }
  1496. }
  1497. else {
  1498. return luaL_error (L, "invalid arguments");
  1499. }
  1500. return 2;
  1501. }
  1502. static gint
  1503. lua_util_unlink (lua_State *L)
  1504. {
  1505. LUA_TRACE_POINT;
  1506. const gchar *fpath;
  1507. gint ret;
  1508. fpath = luaL_checkstring (L, 1);
  1509. if (fpath) {
  1510. ret = unlink (fpath);
  1511. if (ret == -1) {
  1512. lua_pushboolean (L, false);
  1513. lua_pushstring (L, strerror (errno));
  1514. return 2;
  1515. }
  1516. lua_pushboolean (L, true);
  1517. }
  1518. else {
  1519. return luaL_error (L, "invalid arguments");
  1520. }
  1521. return 1;
  1522. }
  1523. static gint
  1524. lua_util_lock_file (lua_State *L)
  1525. {
  1526. LUA_TRACE_POINT;
  1527. const gchar *fpath;
  1528. gint fd = -1;
  1529. gboolean own = FALSE;
  1530. #if !HAVE_FLOCK
  1531. struct flock fl = {
  1532. .l_type = F_WRLCK,
  1533. .l_whence = SEEK_SET,
  1534. .l_start = 0,
  1535. .l_len = 0
  1536. };
  1537. #endif
  1538. fpath = luaL_checkstring (L, 1);
  1539. if (fpath) {
  1540. if (lua_isnumber (L, 2)) {
  1541. fd = lua_tonumber (L, 2);
  1542. }
  1543. else {
  1544. fd = open (fpath, O_RDONLY);
  1545. own = TRUE;
  1546. }
  1547. if (fd == -1) {
  1548. lua_pushnil (L);
  1549. lua_pushstring (L, strerror (errno));
  1550. return 2;
  1551. }
  1552. #if HAVE_FLOCK
  1553. if (flock (fd, LOCK_EX) == -1) {
  1554. #else
  1555. if (fcntl (fd, F_SETLKW, &fl) == -1) {
  1556. #endif
  1557. lua_pushnil (L);
  1558. lua_pushstring (L, strerror (errno));
  1559. if (own) {
  1560. close (fd);
  1561. }
  1562. return 2;
  1563. }
  1564. lua_pushinteger (L, fd);
  1565. }
  1566. else {
  1567. return luaL_error (L, "invalid arguments");
  1568. }
  1569. return 1;
  1570. }
  1571. static gint
  1572. lua_util_unlock_file (lua_State *L)
  1573. {
  1574. LUA_TRACE_POINT;
  1575. gint fd = -1, ret, serrno;
  1576. gboolean do_close = TRUE;
  1577. #if !HAVE_FLOCK
  1578. struct flock fl = {
  1579. .l_type = F_UNLCK,
  1580. .l_whence = SEEK_SET,
  1581. .l_start = 0,
  1582. .l_len = 0
  1583. };
  1584. #endif
  1585. if (lua_isnumber (L, 1)) {
  1586. fd = lua_tointeger (L, 1);
  1587. if (lua_isboolean (L, 2)) {
  1588. do_close = lua_toboolean (L, 2);
  1589. }
  1590. #if HAVE_FLOCK
  1591. ret = flock (fd, LOCK_UN);
  1592. #else
  1593. ret = fcntl (fd, F_SETLKW, &fl);
  1594. #endif
  1595. if (do_close) {
  1596. serrno = errno;
  1597. close (fd);
  1598. errno = serrno;
  1599. }
  1600. if (ret == -1) {
  1601. lua_pushboolean (L, false);
  1602. lua_pushstring (L, strerror (errno));
  1603. return 2;
  1604. }
  1605. lua_pushboolean (L, true);
  1606. }
  1607. else {
  1608. return luaL_error (L, "invalid arguments");
  1609. }
  1610. return 1;
  1611. }
  1612. static gint
  1613. lua_util_create_file (lua_State *L)
  1614. {
  1615. LUA_TRACE_POINT;
  1616. gint fd, mode = 00644;
  1617. const gchar *fpath;
  1618. fpath = luaL_checkstring (L, 1);
  1619. if (fpath) {
  1620. if (lua_isnumber (L, 2)) {
  1621. mode = lua_tointeger (L, 2);
  1622. }
  1623. fd = rspamd_file_xopen (fpath, O_RDWR | O_CREAT | O_TRUNC, mode, 0);
  1624. if (fd == -1) {
  1625. lua_pushnil (L);
  1626. lua_pushstring (L, strerror (errno));
  1627. return 2;
  1628. }
  1629. lua_pushinteger (L, fd);
  1630. }
  1631. else {
  1632. return luaL_error (L, "invalid arguments");
  1633. }
  1634. return 1;
  1635. }
  1636. static gint
  1637. lua_util_close_file (lua_State *L)
  1638. {
  1639. LUA_TRACE_POINT;
  1640. gint fd = -1;
  1641. if (lua_isnumber (L, 1)) {
  1642. fd = lua_tointeger (L, 1);
  1643. if (close (fd) == -1) {
  1644. lua_pushboolean (L, false);
  1645. lua_pushstring (L, strerror (errno));
  1646. return 2;
  1647. }
  1648. lua_pushboolean (L, true);
  1649. }
  1650. else {
  1651. return luaL_error (L, "invalid arguments");
  1652. }
  1653. return 1;
  1654. }
  1655. static gint
  1656. lua_util_random_hex (lua_State *L)
  1657. {
  1658. LUA_TRACE_POINT;
  1659. gchar *buf;
  1660. gint buflen;
  1661. buflen = lua_tointeger (L, 1);
  1662. if (buflen <= 0) {
  1663. return luaL_error (L, "invalid arguments");
  1664. }
  1665. buf = g_malloc (buflen);
  1666. rspamd_random_hex (buf, buflen);
  1667. lua_pushlstring (L, buf, buflen);
  1668. g_free (buf);
  1669. return 1;
  1670. }
  1671. static gint
  1672. lua_util_zstd_compress (lua_State *L)
  1673. {
  1674. return lua_compress_zstd_compress (L);
  1675. }
  1676. static gint
  1677. lua_util_zstd_decompress (lua_State *L)
  1678. {
  1679. return lua_compress_zstd_decompress (L);
  1680. }
  1681. static gint
  1682. lua_util_gzip_compress (lua_State *L)
  1683. {
  1684. return lua_compress_zlib_compress (L);
  1685. }
  1686. static gint
  1687. lua_util_gzip_decompress (lua_State *L)
  1688. {
  1689. return lua_compress_zlib_decompress (L, true);
  1690. }
  1691. static gint
  1692. lua_util_inflate (lua_State *L)
  1693. {
  1694. return lua_compress_zlib_decompress (L, false);
  1695. }
  1696. static gint
  1697. lua_util_normalize_prob (lua_State *L)
  1698. {
  1699. LUA_TRACE_POINT;
  1700. gdouble x, bias = 0.5;
  1701. x = lua_tonumber (L, 1);
  1702. if (lua_type (L, 2) == LUA_TNUMBER) {
  1703. bias = lua_tonumber (L, 2);
  1704. }
  1705. lua_pushnumber (L, rspamd_normalize_probability (x, bias));
  1706. return 1;
  1707. }
  1708. static gint
  1709. lua_util_caseless_hash (lua_State *L)
  1710. {
  1711. LUA_TRACE_POINT;
  1712. guint64 seed = 0xdeadbabe, h;
  1713. struct rspamd_lua_text *t = NULL;
  1714. gint64 *r;
  1715. gsize sz;
  1716. if (lua_type (L, 1) == LUA_TSTRING) {
  1717. t = g_alloca (sizeof (*t));
  1718. t->start = lua_tolstring (L, 1, &sz);
  1719. t->len = sz;
  1720. }
  1721. else {
  1722. t = lua_check_text (L, 1);
  1723. }
  1724. if (t == NULL || t->start == NULL) {
  1725. return luaL_error (L, "invalid arguments");
  1726. }
  1727. if (lua_type (L, 2) == LUA_TNUMBER) {
  1728. seed = lua_tonumber (L, 2);
  1729. }
  1730. else if (lua_type (L, 2) == LUA_TUSERDATA) {
  1731. seed = lua_check_int64 (L, 2);
  1732. }
  1733. h = rspamd_icase_hash (t->start, t->len, seed);
  1734. r = lua_newuserdata (L, sizeof (*r));
  1735. *r = h;
  1736. rspamd_lua_setclass (L, "rspamd{int64}", -1);
  1737. return 1;
  1738. }
  1739. static gint
  1740. lua_util_caseless_hash_fast (lua_State *L)
  1741. {
  1742. LUA_TRACE_POINT;
  1743. guint64 seed = 0xdeadbabe, h;
  1744. struct rspamd_lua_text *t = NULL;
  1745. gsize sz;
  1746. union {
  1747. guint64 i;
  1748. double d;
  1749. } u;
  1750. if (lua_type (L, 1) == LUA_TSTRING) {
  1751. t = g_alloca (sizeof (*t));
  1752. t->start = lua_tolstring (L, 1, &sz);
  1753. t->len = sz;
  1754. }
  1755. else {
  1756. t = lua_check_text (L, 1);
  1757. }
  1758. if (t == NULL || t->start == NULL) {
  1759. return luaL_error (L, "invalid arguments");
  1760. }
  1761. if (lua_type (L, 2) == LUA_TNUMBER) {
  1762. seed = lua_tonumber (L, 2);
  1763. }
  1764. else if (lua_type (L, 2) == LUA_TUSERDATA) {
  1765. seed = lua_check_int64 (L, 2);
  1766. }
  1767. /*
  1768. * Here, we loose entropy from 64 bits to 52 bits roughly, however,
  1769. * it is still fine for practical applications
  1770. */
  1771. h = rspamd_icase_hash (t->start, t->len, seed);
  1772. u.i = G_GUINT64_CONSTANT(0x3FF) << 52 | h >> 12;
  1773. lua_pushnumber (L, u.d - 1.0);
  1774. return 1;
  1775. }
  1776. static gint
  1777. lua_util_is_utf_spoofed (lua_State *L)
  1778. {
  1779. LUA_TRACE_POINT;
  1780. gsize l1, l2;
  1781. gint ret, nres = 2;
  1782. const gchar *s1 = lua_tolstring (L, 1, &l1),
  1783. *s2 = lua_tolstring (L, 2, &l2);
  1784. static USpoofChecker *spc, *spc_sgl;
  1785. UErrorCode uc_err = U_ZERO_ERROR;
  1786. if (s1 && s2) {
  1787. if (spc == NULL) {
  1788. spc = uspoof_open (&uc_err);
  1789. if (uc_err != U_ZERO_ERROR) {
  1790. msg_err ("cannot init spoof checker: %s", u_errorName (uc_err));
  1791. lua_pushboolean (L, false);
  1792. return 1;
  1793. }
  1794. }
  1795. ret = uspoof_areConfusableUTF8 (spc, s1, l1, s2, l2, &uc_err);
  1796. }
  1797. else if (s1) {
  1798. /* We have just s1, not s2 */
  1799. if (spc_sgl == NULL) {
  1800. spc_sgl = uspoof_open (&uc_err);
  1801. if (uc_err != U_ZERO_ERROR) {
  1802. msg_err ("cannot init spoof checker: %s", u_errorName (uc_err));
  1803. lua_pushboolean (L, false);
  1804. return 1;
  1805. }
  1806. uspoof_setChecks (spc_sgl,
  1807. USPOOF_INVISIBLE | USPOOF_MIXED_SCRIPT_CONFUSABLE | USPOOF_ANY_CASE,
  1808. &uc_err);
  1809. if (uc_err != U_ZERO_ERROR) {
  1810. msg_err ("Cannot set proper checks for uspoof: %s", u_errorName (uc_err));
  1811. lua_pushboolean (L, false);
  1812. uspoof_close(spc);
  1813. return 1;
  1814. }
  1815. }
  1816. ret = uspoof_checkUTF8 (spc_sgl, s1, l1, NULL, &uc_err);
  1817. }
  1818. else {
  1819. return luaL_error (L, "invalid arguments");
  1820. }
  1821. lua_pushboolean (L, !!(ret != 0));
  1822. switch (ret) {
  1823. case 0:
  1824. nres = 1;
  1825. break;
  1826. case USPOOF_SINGLE_SCRIPT_CONFUSABLE:
  1827. lua_pushstring (L, "single");
  1828. break;
  1829. case USPOOF_MIXED_SCRIPT_CONFUSABLE:
  1830. lua_pushstring (L, "multiple");
  1831. break;
  1832. case USPOOF_WHOLE_SCRIPT_CONFUSABLE:
  1833. lua_pushstring (L, "whole");
  1834. break;
  1835. default:
  1836. lua_pushstring (L, "unknown");
  1837. break;
  1838. }
  1839. return nres;
  1840. }
  1841. static gint
  1842. lua_util_is_utf_mixed_script (lua_State *L)
  1843. {
  1844. LUA_TRACE_POINT;
  1845. gsize len_of_string;
  1846. const guchar *string_to_check = lua_tolstring (L, 1, &len_of_string);
  1847. UScriptCode last_script_code = USCRIPT_INVALID_CODE;
  1848. UErrorCode uc_err = U_ZERO_ERROR;
  1849. if (string_to_check) {
  1850. uint index = 0;
  1851. UChar32 char_to_check = 0;
  1852. while (index < len_of_string) {
  1853. U8_NEXT (string_to_check, index, len_of_string, char_to_check);
  1854. if (char_to_check < 0) {
  1855. return luaL_error (L, "passed string is not valid utf");
  1856. }
  1857. UScriptCode current_script_code = uscript_getScript (char_to_check, &uc_err);
  1858. if (uc_err != U_ZERO_ERROR) {
  1859. msg_err ("cannot get unicode script for character, error: %s",
  1860. u_errorName (uc_err));
  1861. lua_pushboolean (L, false);
  1862. return 1;
  1863. }
  1864. if (current_script_code != USCRIPT_COMMON &&
  1865. current_script_code != USCRIPT_INHERITED) {
  1866. if (last_script_code == USCRIPT_INVALID_CODE) {
  1867. last_script_code = current_script_code;
  1868. }
  1869. else {
  1870. if (last_script_code != current_script_code) {
  1871. lua_pushboolean (L, true);
  1872. return 1;
  1873. }
  1874. }
  1875. }
  1876. }
  1877. }
  1878. else {
  1879. return luaL_error (L, "invalid arguments");
  1880. }
  1881. lua_pushboolean (L, false);
  1882. return 1;
  1883. }
  1884. static gint
  1885. lua_util_get_string_stats (lua_State *L)
  1886. {
  1887. LUA_TRACE_POINT;
  1888. gsize len_of_string;
  1889. gint num_of_digits = 0, num_of_letters = 0;
  1890. const gchar *string_to_check = lua_tolstring (L, 1, &len_of_string);
  1891. if (string_to_check) {
  1892. while (*string_to_check != '\0') {
  1893. if (g_ascii_isdigit(*string_to_check)) {
  1894. num_of_digits++;
  1895. }
  1896. else if (g_ascii_isalpha(*string_to_check)) {
  1897. num_of_letters++;
  1898. }
  1899. string_to_check++;
  1900. }
  1901. }
  1902. else {
  1903. return luaL_error (L, "invalid arguments");
  1904. }
  1905. lua_createtable (L, 0, 2);
  1906. lua_pushstring (L, "digits");
  1907. lua_pushinteger (L, num_of_digits);
  1908. lua_settable (L, -3);
  1909. lua_pushstring (L, "letters");
  1910. lua_pushinteger (L, num_of_letters);
  1911. lua_settable (L, -3);
  1912. return 1;
  1913. }
  1914. static gint
  1915. lua_util_is_utf_outside_range (lua_State *L)
  1916. {
  1917. LUA_TRACE_POINT;
  1918. gsize len_of_string;
  1919. gint ret;
  1920. const gchar *string_to_check = lua_tolstring (L, 1, &len_of_string);
  1921. guint32 range_start = lua_tointeger (L, 2);
  1922. guint32 range_end = lua_tointeger (L, 3);
  1923. static rspamd_lru_hash_t *validators;
  1924. if (validators == NULL) {
  1925. validators = rspamd_lru_hash_new_full (16, g_free, (GDestroyNotify) uspoof_close, g_int64_hash, g_int64_equal);
  1926. }
  1927. if (string_to_check) {
  1928. guint64 hash_key = (guint64) range_end << 32 || range_start;
  1929. USpoofChecker *validator = rspamd_lru_hash_lookup (validators, &hash_key, 0);
  1930. UErrorCode uc_err = U_ZERO_ERROR;
  1931. if (validator == NULL) {
  1932. USet *allowed_chars;
  1933. guint64 *creation_hash_key = g_malloc (sizeof (guint64));
  1934. *creation_hash_key = hash_key;
  1935. validator = uspoof_open (&uc_err);
  1936. if (uc_err != U_ZERO_ERROR) {
  1937. msg_err ("cannot init spoof checker: %s", u_errorName (uc_err));
  1938. lua_pushboolean (L, false);
  1939. uspoof_close (validator);
  1940. g_free (creation_hash_key);
  1941. return 1;
  1942. }
  1943. allowed_chars = uset_openEmpty ();
  1944. uset_addRange (allowed_chars, range_start, range_end);
  1945. uspoof_setAllowedChars (validator, allowed_chars, &uc_err);
  1946. uspoof_setChecks (validator,
  1947. USPOOF_CHAR_LIMIT | USPOOF_ANY_CASE, &uc_err);
  1948. uset_close (allowed_chars);
  1949. if (uc_err != U_ZERO_ERROR) {
  1950. msg_err ("Cannot configure uspoof: %s", u_errorName (uc_err));
  1951. lua_pushboolean (L, false);
  1952. uspoof_close (validator);
  1953. g_free (creation_hash_key);
  1954. return 1;
  1955. }
  1956. rspamd_lru_hash_insert (validators, creation_hash_key, validator,
  1957. 0, 0);
  1958. }
  1959. gint32 pos = 0;
  1960. ret = uspoof_checkUTF8 (validator, string_to_check, len_of_string, &pos,
  1961. &uc_err);
  1962. }
  1963. else {
  1964. return luaL_error (L, "invalid arguments");
  1965. }
  1966. lua_pushboolean (L, !!(ret != 0));
  1967. return 1;
  1968. }
  1969. static gint
  1970. lua_util_get_hostname (lua_State *L)
  1971. {
  1972. LUA_TRACE_POINT;
  1973. gchar *hostbuf;
  1974. gsize hostlen;
  1975. hostlen = sysconf (_SC_HOST_NAME_MAX);
  1976. if (hostlen <= 0) {
  1977. hostlen = 256;
  1978. }
  1979. else {
  1980. hostlen++;
  1981. }
  1982. hostbuf = g_alloca (hostlen);
  1983. memset (hostbuf, 0, hostlen);
  1984. gethostname (hostbuf, hostlen - 1);
  1985. lua_pushstring (L, hostbuf);
  1986. return 1;
  1987. }
  1988. static gint
  1989. lua_util_parse_content_type (lua_State *L)
  1990. {
  1991. return lua_parsers_parse_content_type (L);
  1992. }
  1993. static gint
  1994. lua_util_mime_header_encode (lua_State *L)
  1995. {
  1996. LUA_TRACE_POINT;
  1997. gsize len;
  1998. const gchar *hdr = luaL_checklstring (L, 1, &len);
  1999. gchar *encoded;
  2000. if (!hdr) {
  2001. return luaL_error (L, "invalid arguments");
  2002. }
  2003. encoded = rspamd_mime_header_encode (hdr, len);
  2004. lua_pushstring (L, encoded);
  2005. g_free (encoded);
  2006. return 1;
  2007. }
  2008. static gint
  2009. lua_util_is_valid_utf8 (lua_State *L)
  2010. {
  2011. LUA_TRACE_POINT;
  2012. const gchar *str;
  2013. gsize len;
  2014. if (lua_isstring (L, 1)) {
  2015. str = lua_tolstring (L, 1, &len);
  2016. }
  2017. else {
  2018. struct rspamd_lua_text *t = lua_check_text (L, 1);
  2019. if (t) {
  2020. str = t->start;
  2021. len = t->len;
  2022. }
  2023. else {
  2024. return luaL_error (L, "invalid arguments (text expected)");
  2025. }
  2026. }
  2027. if (str) {
  2028. goffset error_offset = rspamd_fast_utf8_validate (str, len);
  2029. if (error_offset == 0) {
  2030. lua_pushboolean (L, true);
  2031. }
  2032. else {
  2033. lua_pushboolean (L, false);
  2034. lua_pushnumber (L, error_offset);
  2035. return 2;
  2036. }
  2037. }
  2038. else {
  2039. return luaL_error (L, "invalid arguments");
  2040. }
  2041. return 1;
  2042. }
  2043. static gint
  2044. lua_util_has_obscured_unicode (lua_State *L)
  2045. {
  2046. LUA_TRACE_POINT;
  2047. const gchar *str;
  2048. gsize len;
  2049. gint32 i = 0, prev_i;
  2050. UChar32 uc;
  2051. str = lua_tolstring (L, 1, &len);
  2052. while (i < len) {
  2053. prev_i = i;
  2054. U8_NEXT (str, i, len, uc);
  2055. if (uc > 0) {
  2056. if (IS_OBSCURED_CHAR (uc)) {
  2057. lua_pushboolean (L, true);
  2058. lua_pushnumber (L, uc); /* Character */
  2059. lua_pushnumber (L, prev_i); /* Offset */
  2060. return 3;
  2061. }
  2062. }
  2063. }
  2064. lua_pushboolean (L, false);
  2065. return 1;
  2066. }
  2067. static gint
  2068. lua_util_readline (lua_State *L)
  2069. {
  2070. LUA_TRACE_POINT;
  2071. const gchar *prompt = "";
  2072. gchar *input;
  2073. if (lua_type (L, 1) == LUA_TSTRING) {
  2074. prompt = lua_tostring (L, 1);
  2075. }
  2076. #ifdef WITH_LUA_REPL
  2077. static Replxx *rx_instance = NULL;
  2078. if (rx_instance == NULL) {
  2079. rx_instance = replxx_init ();
  2080. }
  2081. input = (gchar *)replxx_input (rx_instance, prompt);
  2082. if (input) {
  2083. lua_pushstring (L, input);
  2084. }
  2085. else {
  2086. lua_pushnil (L);
  2087. }
  2088. #else
  2089. size_t linecap = 0;
  2090. ssize_t linelen;
  2091. fprintf (stdout, "%s ", prompt);
  2092. linelen = getline (&input, &linecap, stdin);
  2093. if (linelen > 0) {
  2094. if (input[linelen - 1] == '\n') {
  2095. linelen --;
  2096. }
  2097. lua_pushlstring (L, input, linelen);
  2098. free (input);
  2099. }
  2100. else {
  2101. lua_pushnil (L);
  2102. }
  2103. #endif
  2104. return 1;
  2105. }
  2106. static gint
  2107. lua_util_readpassphrase (lua_State *L)
  2108. {
  2109. LUA_TRACE_POINT;
  2110. gchar test_password[8192];
  2111. gsize r;
  2112. r = rspamd_read_passphrase (test_password, sizeof (test_password), 0, NULL);
  2113. if (r > 0) {
  2114. lua_pushlstring (L, test_password, r);
  2115. }
  2116. else {
  2117. lua_pushnil (L);
  2118. }
  2119. /* In fact, we still pass it to Lua which is not very safe */
  2120. rspamd_explicit_memzero (test_password, sizeof (test_password));
  2121. return 1;
  2122. }
  2123. static gint
  2124. lua_util_file_exists (lua_State *L)
  2125. {
  2126. LUA_TRACE_POINT;
  2127. const gchar *fname = luaL_checkstring (L, 1);
  2128. gint serrno;
  2129. if (fname) {
  2130. if (access (fname, R_OK) == -1) {
  2131. serrno = errno;
  2132. lua_pushboolean (L, false);
  2133. lua_pushstring (L, strerror (serrno));
  2134. }
  2135. else {
  2136. lua_pushboolean (L, true);
  2137. lua_pushnil (L);
  2138. }
  2139. }
  2140. else {
  2141. return luaL_error (L, "invalid arguments");
  2142. }
  2143. return 2;
  2144. }
  2145. static gint
  2146. lua_util_mkdir (lua_State *L)
  2147. {
  2148. LUA_TRACE_POINT;
  2149. const gchar *dname = luaL_checkstring (L, 1);
  2150. gboolean recursive = FALSE;
  2151. gint r = -1;
  2152. if (dname) {
  2153. if (lua_isboolean (L, 2)) {
  2154. recursive = lua_toboolean (L, 2);
  2155. }
  2156. if (recursive) {
  2157. char path[PATH_MAX];
  2158. gsize len, i;
  2159. len = rspamd_strlcpy (path, dname, sizeof (path));
  2160. /* Strip last / */
  2161. if (path[len - 1] == '/') {
  2162. path[len - 1] = '\0';
  2163. len --;
  2164. }
  2165. for (i = 1; i < len; i ++) {
  2166. if (path[i] == '/') {
  2167. path[i] = '\0';
  2168. errno = 0;
  2169. r = mkdir (path, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
  2170. if (r == -1 && errno != EEXIST) {
  2171. break;
  2172. }
  2173. path[i] = '/';
  2174. }
  2175. }
  2176. /* Final path component */
  2177. r = mkdir (path, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
  2178. }
  2179. else {
  2180. r = mkdir (dname, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
  2181. }
  2182. if (r == -1 && errno != EEXIST) {
  2183. lua_pushboolean (L, false);
  2184. lua_pushstring (L, strerror (errno));
  2185. return 2;
  2186. }
  2187. lua_pushboolean (L, true);
  2188. }
  2189. else {
  2190. return luaL_error (L, "invalid arguments");
  2191. }
  2192. return 1;
  2193. }
  2194. static gint
  2195. lua_util_umask (lua_State *L)
  2196. {
  2197. LUA_TRACE_POINT;
  2198. mode_t mask = 0, old;
  2199. if (lua_type (L, 1) == LUA_TSTRING) {
  2200. const gchar *str = lua_tostring (L, 1);
  2201. if (str[0] == '0') {
  2202. /* e.g. '022' */
  2203. mask = strtol (str, NULL, 8);
  2204. }
  2205. else {
  2206. /* XXX: implement modestring parsing at some point */
  2207. return luaL_error (L, "invalid arguments");
  2208. }
  2209. }
  2210. else if (lua_type (L, 1) == LUA_TNUMBER) {
  2211. mask = lua_tonumber (L, 1);
  2212. }
  2213. else {
  2214. return luaL_error (L, "invalid arguments");
  2215. }
  2216. old = umask (mask);
  2217. lua_pushinteger (L, old);
  2218. return 1;
  2219. }
  2220. static gint
  2221. lua_util_isatty (lua_State *L)
  2222. {
  2223. LUA_TRACE_POINT;
  2224. if (isatty (STDOUT_FILENO)) {
  2225. lua_pushboolean (L, true);
  2226. }
  2227. else {
  2228. lua_pushboolean (L, false);
  2229. }
  2230. return 1;
  2231. }
  2232. /* Backport from Lua 5.3 */
  2233. /******************************************************************************
  2234. * Copyright (C) 1994-2016 Lua.org, PUC-Rio.
  2235. *
  2236. * Permission is hereby granted, free of charge, to any person obtaining
  2237. * a copy of this software and associated documentation files (the
  2238. * "Software"), to deal in the Software without restriction, including
  2239. * without limitation the rights to use, copy, modify, merge, publish,
  2240. * distribute, sublicense, and/or sell copies of the Software, and to
  2241. * permit persons to whom the Software is furnished to do so, subject to
  2242. * the following conditions:
  2243. *
  2244. * The above copyright notice and this permission notice shall be
  2245. * included in all copies or substantial portions of the Software.
  2246. *
  2247. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  2248. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2249. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  2250. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  2251. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  2252. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  2253. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  2254. ******************************************************************************/
  2255. /*
  2256. ** {======================================================
  2257. ** PACK/UNPACK
  2258. ** =======================================================
  2259. */
  2260. /* value used for padding */
  2261. #if !defined(LUA_PACKPADBYTE)
  2262. #define LUA_PACKPADBYTE 0x00
  2263. #endif
  2264. /* maximum size for the binary representation of an integer */
  2265. #define MAXINTSIZE 16
  2266. /* number of bits in a character */
  2267. #define NB CHAR_BIT
  2268. /* mask for one character (NB 1's) */
  2269. #define MC ((1 << NB) - 1)
  2270. /* size of a lua_Integer */
  2271. #define SZINT ((int)sizeof(lua_Integer))
  2272. #define MAX_SIZET ((size_t)(~(size_t)0))
  2273. #define MAXSIZE \
  2274. (sizeof(size_t) < sizeof(int) ? MAX_SIZET : (size_t)(INT_MAX))
  2275. /* dummy union to get native endianness */
  2276. static const union {
  2277. int dummy;
  2278. char little; /* true if machine is little endian */
  2279. } nativeendian = {1};
  2280. /* dummy structure to get native alignment requirements */
  2281. struct cD {
  2282. char c;
  2283. union {
  2284. double d;
  2285. void *p;
  2286. lua_Integer i;
  2287. lua_Number n;
  2288. } u;
  2289. };
  2290. #define MAXALIGN (offsetof(struct cD, u))
  2291. /*
  2292. ** Union for serializing floats
  2293. */
  2294. typedef union Ftypes {
  2295. float f;
  2296. double d;
  2297. lua_Number n;
  2298. char buff[5 * sizeof (lua_Number)]; /* enough for any float type */
  2299. } Ftypes;
  2300. /*
  2301. ** information to pack/unpack stuff
  2302. */
  2303. typedef struct Header {
  2304. lua_State *L;
  2305. int islittle;
  2306. int maxalign;
  2307. } Header;
  2308. /*
  2309. ** options for pack/unpack
  2310. */
  2311. typedef enum KOption {
  2312. Kint, /* signed integers */
  2313. Kuint, /* unsigned integers */
  2314. Kfloat, /* floating-point numbers */
  2315. Kchar, /* fixed-length strings */
  2316. Kstring, /* strings with prefixed length */
  2317. Kzstr, /* zero-terminated strings */
  2318. Kpadding, /* padding */
  2319. Kpaddalign, /* padding for alignment */
  2320. Knop /* no-op (configuration or spaces) */
  2321. } KOption;
  2322. #if LUA_VERSION_NUM <= 502
  2323. #define lua_Unsigned size_t
  2324. #endif
  2325. #if LUA_VERSION_NUM < 502
  2326. #define lua_Unsigned size_t
  2327. typedef struct luaL_Buffer_53 {
  2328. luaL_Buffer b; /* make incorrect code crash! */
  2329. char *ptr;
  2330. size_t nelems;
  2331. size_t capacity;
  2332. lua_State *L2;
  2333. } luaL_Buffer_53;
  2334. #define luaL_Buffer luaL_Buffer_53
  2335. #define COMPAT53_PREFIX lua
  2336. #undef COMPAT53_API
  2337. #if defined(__GNUC__) || defined(__clang__)
  2338. # define COMPAT53_API __attribute__((__unused__)) static
  2339. #else
  2340. # define COMPAT53_API static
  2341. #endif
  2342. #define COMPAT53_CONCAT_HELPER(a, b) a##b
  2343. #define COMPAT53_CONCAT(a, b) COMPAT53_CONCAT_HELPER(a, b)
  2344. #define luaL_buffinit COMPAT53_CONCAT(COMPAT53_PREFIX, _buffinit_53)
  2345. COMPAT53_API void luaL_buffinit (lua_State *L, luaL_Buffer_53 *B);
  2346. #define luaL_prepbuffsize COMPAT53_CONCAT(COMPAT53_PREFIX, _prepbufsize_53)
  2347. COMPAT53_API char *luaL_prepbuffsize (luaL_Buffer_53 *B, size_t s);
  2348. #define luaL_addlstring COMPAT53_CONCAT(COMPAT53_PREFIX, _addlstring_53)
  2349. COMPAT53_API void luaL_addlstring (luaL_Buffer_53 *B, const char *s, size_t l);
  2350. #define luaL_addvalue COMPAT53_CONCAT(COMPAT53_PREFIX, _addvalue_53)
  2351. COMPAT53_API void luaL_addvalue (luaL_Buffer_53 *B);
  2352. #define luaL_pushresult COMPAT53_CONCAT(COMPAT53_PREFIX, _pushresult_53)
  2353. COMPAT53_API void luaL_pushresult (luaL_Buffer_53 *B);
  2354. #undef luaL_buffinitsize
  2355. #define luaL_buffinitsize(L, B, s) \
  2356. (luaL_buffinit(L, B), luaL_prepbuffsize(B, s))
  2357. #undef luaL_prepbuffer
  2358. #define luaL_prepbuffer(B) \
  2359. luaL_prepbuffsize(B, LUAL_BUFFERSIZE)
  2360. #undef luaL_addchar
  2361. #define luaL_addchar(B, c) \
  2362. ((void)((B)->nelems < (B)->capacity || luaL_prepbuffsize(B, 1)), \
  2363. ((B)->ptr[(B)->nelems++] = (c)))
  2364. #undef luaL_addsize
  2365. #define luaL_addsize(B, s) \
  2366. ((B)->nelems += (s))
  2367. #undef luaL_addstring
  2368. #define luaL_addstring(B, s) \
  2369. luaL_addlstring(B, s, strlen(s))
  2370. #undef luaL_pushresultsize
  2371. #define luaL_pushresultsize(B, s) \
  2372. (luaL_addsize(B, s), luaL_pushresult(B))
  2373. COMPAT53_API void
  2374. luaL_buffinit (lua_State *L, luaL_Buffer_53 *B)
  2375. {
  2376. /* make it crash if used via pointer to a 5.1-style luaL_Buffer */
  2377. B->b.p = NULL;
  2378. B->b.L = NULL;
  2379. B->b.lvl = 0;
  2380. /* reuse the buffer from the 5.1-style luaL_Buffer though! */
  2381. B->ptr = B->b.buffer;
  2382. B->nelems = 0;
  2383. B->capacity = LUAL_BUFFERSIZE;
  2384. B->L2 = L;
  2385. }
  2386. COMPAT53_API char *
  2387. luaL_prepbuffsize (luaL_Buffer_53 *B, size_t s)
  2388. {
  2389. if (B->capacity - B->nelems < s) { /* needs to grow */
  2390. char *newptr = NULL;
  2391. size_t newcap = B->capacity * 2;
  2392. if (newcap - B->nelems < s)
  2393. newcap = B->nelems + s;
  2394. if (newcap < B->capacity) /* overflow */
  2395. luaL_error (B->L2, "buffer too large");
  2396. newptr = (char *) lua_newuserdata (B->L2, newcap);
  2397. memcpy(newptr, B->ptr, B->nelems);
  2398. if (B->ptr != B->b.buffer) {
  2399. lua_replace (B->L2, -2); /* remove old buffer */
  2400. }
  2401. B->ptr = newptr;
  2402. B->capacity = newcap;
  2403. }
  2404. return B->ptr + B->nelems;
  2405. }
  2406. COMPAT53_API void
  2407. luaL_addlstring (luaL_Buffer_53 *B, const char *s, size_t l)
  2408. {
  2409. memcpy(luaL_prepbuffsize (B, l), s, l);
  2410. luaL_addsize(B, l);
  2411. }
  2412. COMPAT53_API void
  2413. luaL_addvalue (luaL_Buffer_53 *B)
  2414. {
  2415. size_t len = 0;
  2416. const char *s = lua_tolstring (B->L2, -1, &len);
  2417. if (!s)
  2418. luaL_error (B->L2, "cannot convert value to string");
  2419. if (B->ptr != B->b.buffer) {
  2420. lua_insert (B->L2, -2); /* userdata buffer must be at stack top */
  2421. }
  2422. luaL_addlstring (B, s, len);
  2423. lua_remove (B->L2, B->ptr != B->b.buffer ? -2 : -1);
  2424. }
  2425. COMPAT53_API void
  2426. luaL_pushresult (luaL_Buffer_53 *B)
  2427. {
  2428. lua_pushlstring (B->L2, B->ptr, B->nelems);
  2429. if (B->ptr != B->b.buffer) {
  2430. lua_replace (B->L2, -2); /* remove userdata buffer */
  2431. }
  2432. }
  2433. #endif
  2434. /*
  2435. ** Read an integer numeral from string 'fmt' or return 'df' if
  2436. ** there is no numeral
  2437. */
  2438. static int
  2439. digit (int c)
  2440. {
  2441. return '0' <= c && c <= '9';
  2442. }
  2443. static int
  2444. getnum (const char **fmt, int df)
  2445. {
  2446. if (!digit (**fmt)) /* no number? */
  2447. return df; /* return default value */
  2448. else {
  2449. int a = 0;
  2450. do {
  2451. a = a * 10 + (*((*fmt)++) - '0');
  2452. } while (digit (**fmt) && a <= ((int) MAXSIZE - 9) / 10);
  2453. return a;
  2454. }
  2455. }
  2456. /*
  2457. ** Read an integer numeral and raises an error if it is larger
  2458. ** than the maximum size for integers.
  2459. */
  2460. static int
  2461. getnumlimit (Header *h, const char **fmt, int df)
  2462. {
  2463. int sz = getnum (fmt, df);
  2464. if (sz > MAXINTSIZE || sz <= 0)
  2465. luaL_error (h->L, "integral size (%d) out of limits [1,%d]",
  2466. sz, MAXINTSIZE);
  2467. return sz;
  2468. }
  2469. /*
  2470. ** Initialize Header
  2471. */
  2472. static void
  2473. initheader (lua_State *L, Header *h)
  2474. {
  2475. h->L = L;
  2476. h->islittle = nativeendian.little;
  2477. h->maxalign = 1;
  2478. }
  2479. /*
  2480. ** Read and classify next option. 'size' is filled with option's size.
  2481. */
  2482. static KOption
  2483. getoption (Header *h, const char **fmt, int *size)
  2484. {
  2485. int opt = *((*fmt)++);
  2486. *size = 0; /* default */
  2487. switch (opt) {
  2488. case 'b':
  2489. *size = sizeof (char);
  2490. return Kint;
  2491. case 'B':
  2492. *size = sizeof (char);
  2493. return Kuint;
  2494. case 'h':
  2495. *size = sizeof (short);
  2496. return Kint;
  2497. case 'H':
  2498. *size = sizeof (short);
  2499. return Kuint;
  2500. case 'l':
  2501. *size = sizeof (long);
  2502. return Kint;
  2503. case 'L':
  2504. *size = sizeof (long);
  2505. return Kuint;
  2506. case 'j':
  2507. *size = sizeof (lua_Integer);
  2508. return Kint;
  2509. case 'J':
  2510. *size = sizeof (lua_Integer);
  2511. return Kuint;
  2512. case 'T':
  2513. *size = sizeof (size_t);
  2514. return Kuint;
  2515. case 'f':
  2516. *size = sizeof (float);
  2517. return Kfloat;
  2518. case 'd':
  2519. *size = sizeof (double);
  2520. return Kfloat;
  2521. case 'n':
  2522. *size = sizeof (lua_Number);
  2523. return Kfloat;
  2524. case 'i':
  2525. *size = getnumlimit (h, fmt, sizeof (int));
  2526. return Kint;
  2527. case 'I':
  2528. *size = getnumlimit (h, fmt, sizeof (int));
  2529. return Kuint;
  2530. case 's':
  2531. *size = getnumlimit (h, fmt, sizeof (size_t));
  2532. return Kstring;
  2533. case 'c':
  2534. *size = getnum (fmt, -1);
  2535. if (*size == -1)
  2536. luaL_error (h->L, "missing size for format option 'c'");
  2537. return Kchar;
  2538. case 'z':
  2539. return Kzstr;
  2540. case 'x':
  2541. *size = 1;
  2542. return Kpadding;
  2543. case 'X':
  2544. return Kpaddalign;
  2545. case ' ':
  2546. break;
  2547. case '<':
  2548. h->islittle = 1;
  2549. break;
  2550. case '>':
  2551. h->islittle = 0;
  2552. break;
  2553. case '=':
  2554. h->islittle = nativeendian.little;
  2555. break;
  2556. case '!':
  2557. h->maxalign = getnumlimit (h, fmt, MAXALIGN);
  2558. break;
  2559. default:
  2560. luaL_error (h->L, "invalid format option '%c'", opt);
  2561. }
  2562. return Knop;
  2563. }
  2564. /*
  2565. ** Read, classify, and fill other details about the next option.
  2566. ** 'psize' is filled with option's size, 'notoalign' with its
  2567. ** alignment requirements.
  2568. ** Local variable 'size' gets the size to be aligned. (Kpadal option
  2569. ** always gets its full alignment, other options are limited by
  2570. ** the maximum alignment ('maxalign'). Kchar option needs no alignment
  2571. ** despite its size.
  2572. */
  2573. static KOption
  2574. getdetails (Header *h, size_t totalsize,
  2575. const char **fmt, int *psize, int *ntoalign)
  2576. {
  2577. KOption opt = getoption (h, fmt, psize);
  2578. int align = *psize; /* usually, alignment follows size */
  2579. if (opt == Kpaddalign) { /* 'X' gets alignment from following option */
  2580. if (**fmt == '\0' || getoption (h, fmt, &align) == Kchar || align == 0)
  2581. luaL_argerror (h->L, 1, "invalid next option for option 'X'");
  2582. }
  2583. if (align <= 1 || opt == Kchar) /* need no alignment? */
  2584. *ntoalign = 0;
  2585. else {
  2586. if (align > h->maxalign) /* enforce maximum alignment */
  2587. align = h->maxalign;
  2588. if ((align & (align - 1)) != 0) /* is 'align' not a power of 2? */
  2589. luaL_argerror (h->L, 1, "format asks for alignment not power of 2");
  2590. *ntoalign = (align - (int) (totalsize & (align - 1))) & (align - 1);
  2591. }
  2592. return opt;
  2593. }
  2594. /*
  2595. ** Pack integer 'n' with 'size' bytes and 'islittle' endianness.
  2596. ** The final 'if' handles the case when 'size' is larger than
  2597. ** the size of a Lua integer, correcting the extra sign-extension
  2598. ** bytes if necessary (by default they would be zeros).
  2599. */
  2600. static void
  2601. packint (luaL_Buffer *b, lua_Unsigned n,
  2602. int islittle, int size, int neg)
  2603. {
  2604. char *buff = luaL_prepbuffsize (b, size);
  2605. int i;
  2606. buff[islittle ? 0 : size - 1] = (char) (n & MC); /* first byte */
  2607. for (i = 1; i < size; i++) {
  2608. n >>= NB;
  2609. buff[islittle ? i : size - 1 - i] = (char) (n & MC);
  2610. }
  2611. if (neg && size > SZINT) { /* negative number need sign extension? */
  2612. for (i = SZINT; i < size; i++) /* correct extra bytes */
  2613. buff[islittle ? i : size - 1 - i] = (char) MC;
  2614. }
  2615. luaL_addsize(b, size); /* add result to buffer */
  2616. }
  2617. /*
  2618. ** Copy 'size' bytes from 'src' to 'dest', correcting endianness if
  2619. ** given 'islittle' is different from native endianness.
  2620. */
  2621. static void
  2622. copywithendian (volatile char *dest, volatile const char *src,
  2623. int size, int islittle)
  2624. {
  2625. if (islittle == nativeendian.little) {
  2626. while (size-- != 0)
  2627. *(dest++) = *(src++);
  2628. }
  2629. else {
  2630. dest += size - 1;
  2631. while (size-- != 0)
  2632. *(dest--) = *(src++);
  2633. }
  2634. }
  2635. static int
  2636. lua_util_pack (lua_State *L)
  2637. {
  2638. luaL_Buffer b;
  2639. Header h;
  2640. const char *fmt = luaL_checkstring(L, 1); /* format string */
  2641. int arg = 1; /* current argument to pack */
  2642. size_t totalsize = 0; /* accumulate total size of result */
  2643. initheader (L, &h);
  2644. lua_pushnil (L); /* mark to separate arguments from string buffer */
  2645. luaL_buffinit (L, &b);
  2646. while (*fmt != '\0') {
  2647. int size, ntoalign;
  2648. KOption opt = getdetails (&h, totalsize, &fmt, &size, &ntoalign);
  2649. totalsize += ntoalign + size;
  2650. while (ntoalign-- > 0)
  2651. luaL_addchar(&b, LUA_PACKPADBYTE); /* fill alignment */
  2652. arg++;
  2653. switch (opt) {
  2654. case Kint: { /* signed integers */
  2655. lua_Integer n = luaL_checkinteger (L, arg);
  2656. if (size < SZINT) { /* need overflow check? */
  2657. lua_Integer lim = (lua_Integer) 1 << ((size * NB) - 1);
  2658. luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow");
  2659. }
  2660. packint (&b, (lua_Unsigned) n, h.islittle, size, (n < 0));
  2661. break;
  2662. }
  2663. case Kuint: { /* unsigned integers */
  2664. lua_Integer n = luaL_checkinteger (L, arg);
  2665. if (size < SZINT) /* need overflow check? */
  2666. luaL_argcheck(L,
  2667. (lua_Unsigned) n < ((lua_Unsigned) 1 << (size * NB)),
  2668. arg,
  2669. "unsigned overflow");
  2670. packint (&b, (lua_Unsigned) n, h.islittle, size, 0);
  2671. break;
  2672. }
  2673. case Kfloat: { /* floating-point options */
  2674. volatile Ftypes u;
  2675. char *buff = luaL_prepbuffsize (&b, size);
  2676. lua_Number n = luaL_checknumber (L, arg); /* get argument */
  2677. if (size == sizeof (u.f))
  2678. u.f = (float) n; /* copy it into 'u' */
  2679. else if (size == sizeof (u.d))
  2680. u.d = (double) n;
  2681. else
  2682. u.n = n;
  2683. /* move 'u' to final result, correcting endianness if needed */
  2684. copywithendian (buff, u.buff, size, h.islittle);
  2685. luaL_addsize(&b, size);
  2686. break;
  2687. }
  2688. case Kchar: { /* fixed-size string */
  2689. size_t len;
  2690. const char *s = luaL_checklstring (L, arg, &len);
  2691. if ((size_t) size <=
  2692. len) /* string larger than (or equal to) needed? */
  2693. luaL_addlstring (&b,
  2694. s,
  2695. size); /* truncate string to asked size */
  2696. else { /* string smaller than needed */
  2697. luaL_addlstring (&b, s, len); /* add it all */
  2698. while (len++ < (size_t) size) /* pad extra space */
  2699. luaL_addchar(&b, LUA_PACKPADBYTE);
  2700. }
  2701. break;
  2702. }
  2703. case Kstring: { /* strings with length count */
  2704. size_t len;
  2705. const char *s = luaL_checklstring (L, arg, &len);
  2706. luaL_argcheck(L, size >= (int) sizeof (size_t) ||
  2707. len < ((size_t) 1 << (size * NB)),
  2708. arg, "string length does not fit in given size");
  2709. packint (&b,
  2710. (lua_Unsigned) len,
  2711. h.islittle,
  2712. size,
  2713. 0); /* pack length */
  2714. luaL_addlstring (&b, s, len);
  2715. totalsize += len;
  2716. break;
  2717. }
  2718. case Kzstr: { /* zero-terminated string */
  2719. size_t len;
  2720. const char *s = luaL_checklstring (L, arg, &len);
  2721. luaL_argcheck(L, strlen (s) == len, arg, "string contains zeros");
  2722. luaL_addlstring (&b, s, len);
  2723. luaL_addchar(&b, '\0'); /* add zero at the end */
  2724. totalsize += len + 1;
  2725. break;
  2726. }
  2727. case Kpadding:
  2728. luaL_addchar(&b, LUA_PACKPADBYTE); /* FALLTHROUGH */
  2729. case Kpaddalign:
  2730. case Knop:
  2731. arg--; /* undo increment */
  2732. break;
  2733. }
  2734. }
  2735. luaL_pushresult (&b);
  2736. return 1;
  2737. }
  2738. static int
  2739. lua_util_packsize (lua_State *L)
  2740. {
  2741. Header h;
  2742. const char *fmt = luaL_checkstring(L, 1); /* format string */
  2743. size_t totalsize = 0; /* accumulate total size of result */
  2744. initheader (L, &h);
  2745. while (*fmt != '\0') {
  2746. int size, ntoalign;
  2747. KOption opt = getdetails (&h, totalsize, &fmt, &size, &ntoalign);
  2748. size += ntoalign; /* total space used by option */
  2749. luaL_argcheck(L, totalsize <= MAXSIZE - size, 1,
  2750. "format result too large");
  2751. totalsize += size;
  2752. switch (opt) {
  2753. case Kstring: /* strings with length count */
  2754. case Kzstr: /* zero-terminated string */
  2755. luaL_argerror (L, 1, "variable-length format");
  2756. /* call never return, but to avoid warnings: *//* FALLTHROUGH */
  2757. default:
  2758. break;
  2759. }
  2760. }
  2761. lua_pushinteger (L, (lua_Integer) totalsize);
  2762. return 1;
  2763. }
  2764. /*
  2765. ** Unpack an integer with 'size' bytes and 'islittle' endianness.
  2766. ** If size is smaller than the size of a Lua integer and integer
  2767. ** is signed, must do sign extension (propagating the sign to the
  2768. ** higher bits); if size is larger than the size of a Lua integer,
  2769. ** it must check the unread bytes to see whether they do not cause an
  2770. ** overflow.
  2771. */
  2772. static lua_Integer
  2773. unpackint (lua_State *L, const char *str,
  2774. int islittle, int size, int issigned)
  2775. {
  2776. lua_Unsigned res = 0;
  2777. int i;
  2778. int limit = (size <= SZINT) ? size : SZINT;
  2779. for (i = limit - 1; i >= 0; i--) {
  2780. res <<= NB;
  2781. res |= (lua_Unsigned) (
  2782. unsigned char)str[islittle ? i : size - 1 - i];
  2783. }
  2784. if (size < SZINT) { /* real size smaller than lua_Integer? */
  2785. if (issigned) { /* needs sign extension? */
  2786. lua_Unsigned mask = (lua_Unsigned) 1 << (size * NB - 1);
  2787. res = ((res ^ mask) - mask); /* do sign extension */
  2788. }
  2789. }
  2790. else if (size > SZINT) { /* must check unread bytes */
  2791. int mask = (!issigned || (lua_Integer) res >= 0) ? 0 : MC;
  2792. for (i = limit; i < size; i++) {
  2793. if ((unsigned char) str[islittle ? i : size - 1 - i] != mask)
  2794. luaL_error (L,
  2795. "%d-byte integer does not fit into Lua Integer",
  2796. size);
  2797. }
  2798. }
  2799. return (lua_Integer) res;
  2800. }
  2801. static lua_Integer
  2802. posrelat (lua_Integer pos, size_t len)
  2803. {
  2804. if (pos >= 0)
  2805. return pos;
  2806. else if (0u - (size_t) pos > len)
  2807. return 0;
  2808. else
  2809. return (lua_Integer) len + pos + 1;
  2810. }
  2811. static int
  2812. lua_util_unpack (lua_State *L)
  2813. {
  2814. Header h;
  2815. const char *fmt = luaL_checkstring(L, 1);
  2816. size_t ld;
  2817. const char *data;
  2818. int n = 0; /* number of results */
  2819. if (lua_type (L, 2) == LUA_TUSERDATA) {
  2820. struct rspamd_lua_text *t = lua_check_text (L, 2);
  2821. if (!t) {
  2822. return luaL_error (L, "invalid arguments");
  2823. }
  2824. data = t->start;
  2825. ld = t->len;
  2826. }
  2827. else {
  2828. data = luaL_checklstring (L, 2, &ld);
  2829. }
  2830. size_t pos = (size_t) posrelat (luaL_optinteger (L, 3, 1), ld) - 1;
  2831. luaL_argcheck(L, pos <= ld, 3, "initial position out of string");
  2832. initheader (L, &h);
  2833. while (*fmt != '\0') {
  2834. int size, ntoalign;
  2835. KOption opt = getdetails (&h, pos, &fmt, &size, &ntoalign);
  2836. if ((size_t) ntoalign + size > ~pos || pos + ntoalign + size > ld)
  2837. luaL_argerror (L, 2, "data string too short");
  2838. pos += ntoalign; /* skip alignment */
  2839. /* stack space for item + next position */
  2840. luaL_checkstack (L, 2, "too many results");
  2841. n++;
  2842. switch (opt) {
  2843. case Kint:
  2844. case Kuint: {
  2845. lua_Integer res = unpackint (L, data + pos, h.islittle, size,
  2846. (opt == Kint));
  2847. lua_pushinteger (L, res);
  2848. break;
  2849. }
  2850. case Kfloat: {
  2851. volatile Ftypes u;
  2852. lua_Number num;
  2853. copywithendian (u.buff, data + pos, size, h.islittle);
  2854. if (size == sizeof (u.f))
  2855. num = (lua_Number) u.f;
  2856. else if (size == sizeof (u.d))
  2857. num = (lua_Number) u.d;
  2858. else
  2859. num = u.n;
  2860. lua_pushnumber (L, num);
  2861. break;
  2862. }
  2863. case Kchar: {
  2864. lua_pushlstring (L, data + pos, size);
  2865. break;
  2866. }
  2867. case Kstring: {
  2868. size_t len = (size_t) unpackint (L,
  2869. data + pos,
  2870. h.islittle,
  2871. size,
  2872. 0);
  2873. luaL_argcheck(L,
  2874. pos + len + size <= ld,
  2875. 2,
  2876. "data string too short");
  2877. lua_pushlstring (L, data + pos + size, len);
  2878. pos += len; /* skip string */
  2879. break;
  2880. }
  2881. case Kzstr: {
  2882. size_t len = (int) strlen (data + pos);
  2883. lua_pushlstring (L, data + pos, len);
  2884. pos += len + 1; /* skip string plus final '\0' */
  2885. break;
  2886. }
  2887. case Kpaddalign:
  2888. case Kpadding:
  2889. case Knop:
  2890. n--; /* undo increment */
  2891. break;
  2892. }
  2893. pos += size;
  2894. }
  2895. lua_pushinteger (L, pos + 1); /* next position */
  2896. return n + 1;
  2897. }
  2898. static int
  2899. lua_util_btc_polymod (lua_State *L)
  2900. {
  2901. guint64 c = 1;
  2902. if (lua_type (L, 1) != LUA_TTABLE) {
  2903. return luaL_error (L, "invalid arguments");
  2904. }
  2905. for (lua_pushnil (L); lua_next (L, 1); lua_pop (L, 1)) {
  2906. guint8 c0 = c >> 35;
  2907. guint64 d = lua_tointeger (L, -1);
  2908. c = ((c & 0x07ffffffff) << 5) ^ d;
  2909. if (c0 & 0x01) c ^= 0x98f2bc8e61;
  2910. if (c0 & 0x02) c ^= 0x79b76d99e2;
  2911. if (c0 & 0x04) c ^= 0xf33e5fb3c4;
  2912. if (c0 & 0x08) c ^= 0xae2eabe2a8;
  2913. if (c0 & 0x10) c ^= 0x1e4f43e470;
  2914. }
  2915. if ((c ^ 1) == 0) {
  2916. lua_pushboolean (L, true);
  2917. }
  2918. else {
  2919. lua_pushboolean (L, false);
  2920. }
  2921. return 1;
  2922. }
  2923. static int
  2924. lua_util_parse_smtp_date (lua_State *L)
  2925. {
  2926. return lua_parsers_parse_smtp_date (L);
  2927. }
  2928. static gint
  2929. lua_load_util (lua_State * L)
  2930. {
  2931. lua_newtable (L);
  2932. luaL_register (L, NULL, utillib_f);
  2933. return 1;
  2934. }
  2935. static gint
  2936. lua_load_int64 (lua_State * L)
  2937. {
  2938. lua_newtable (L);
  2939. luaL_register (L, NULL, int64lib_f);
  2940. return 1;
  2941. }
  2942. void
  2943. luaopen_util (lua_State * L)
  2944. {
  2945. rspamd_lua_new_class (L, "rspamd{ev_base}", ev_baselib_m);
  2946. lua_pop (L, 1);
  2947. rspamd_lua_new_class (L, "rspamd{int64}", int64lib_m);
  2948. lua_pop (L, 1);
  2949. rspamd_lua_add_preload (L, "rspamd_util", lua_load_util);
  2950. rspamd_lua_add_preload (L, "rspamd_int64", lua_load_int64);
  2951. }
  2952. static int
  2953. lua_int64_tostring (lua_State *L)
  2954. {
  2955. gint64 n = lua_check_int64 (L, 1);
  2956. gchar buf[32];
  2957. bool is_signed = false;
  2958. if (lua_isboolean (L, 2)) {
  2959. is_signed = lua_toboolean (L, 2);
  2960. }
  2961. if (is_signed) {
  2962. rspamd_snprintf(buf, sizeof(buf), "%L", n);
  2963. }
  2964. else {
  2965. rspamd_snprintf(buf, sizeof(buf), "%uL", n);
  2966. }
  2967. lua_pushstring (L, buf);
  2968. return 1;
  2969. }
  2970. static int
  2971. lua_int64_fromstring (lua_State *L)
  2972. {
  2973. struct rspamd_lua_text *t = lua_check_text_or_string (L, 1);
  2974. if (t && t->len > 0) {
  2975. guint64 u64;
  2976. const char *p = t->start;
  2977. gsize len = t->len;
  2978. bool neg = false;
  2979. /*
  2980. * We use complicated negation to allow both signed and unsinged values to
  2981. * fit into result.
  2982. * So we read int64 as unsigned and copy it to signed number.
  2983. * If we wanted u64 this allows to have the same memory representation of
  2984. * signed and unsigned.
  2985. * If we wanted signed i64 we still can use -1000500 and it will be parsed
  2986. * properly
  2987. */
  2988. if (*p == '-') {
  2989. neg = true;
  2990. p ++;
  2991. len --;
  2992. }
  2993. if (!rspamd_strtou64(p, len, &u64)) {
  2994. lua_pushnil (L);
  2995. lua_pushstring (L, "invalid number");
  2996. return 2;
  2997. }
  2998. gint64* i64_p = lua_newuserdata (L, sizeof (gint64));
  2999. rspamd_lua_setclass (L, "rspamd{int64}", -1);
  3000. memcpy (i64_p, &u64, sizeof(u64));
  3001. if (neg) {
  3002. *i64_p = -(*i64_p);
  3003. }
  3004. }
  3005. else {
  3006. }
  3007. return 1;
  3008. }
  3009. static int
  3010. lua_int64_tonumber (lua_State *L)
  3011. {
  3012. gint64 n = lua_check_int64 (L, 1);
  3013. gdouble d;
  3014. d = n;
  3015. lua_pushinteger (L, d);
  3016. return 1;
  3017. }
  3018. static int
  3019. lua_int64_hex (lua_State *L)
  3020. {
  3021. gint64 n = lua_check_int64 (L, 1);
  3022. gchar buf[32];
  3023. rspamd_snprintf (buf, sizeof (buf), "%XL", n);
  3024. lua_pushstring (L, buf);
  3025. return 1;
  3026. }
  3027. static int
  3028. lua_ev_base_loop (lua_State *L)
  3029. {
  3030. int flags = 0;
  3031. struct ev_loop *ev_base;
  3032. ev_base = lua_check_ev_base (L, 1);
  3033. if (lua_isnumber (L, 2)) {
  3034. flags = lua_tointeger (L, 2);
  3035. }
  3036. int ret = ev_run (ev_base, flags);
  3037. lua_pushinteger (L, ret);
  3038. return 1;
  3039. }