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_text.c 38KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740
  1. /*-
  2. * Copyright 2019 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 "libcryptobox/cryptobox.h"
  18. #include "contrib/fastutf8/fastutf8.h"
  19. #include "unix-std.h"
  20. /***
  21. * @module rspamd_text
  22. * This module provides access to opaque text structures used widely to prevent
  23. * copying between Lua and C for various concerns: performance, security etc...
  24. *
  25. * You can convert rspamd_text into string but it will copy data.
  26. */
  27. /***
  28. * @function rspamd_text.fromstring(str)
  29. * Creates rspamd_text from Lua string (copied to the text)
  30. * @param {string} str string to use
  31. * @return {rspamd_text} resulting text
  32. */
  33. LUA_FUNCTION_DEF (text, fromstring);
  34. /***
  35. * @function rspamd_text.null()
  36. * Creates rspamd_text with NULL pointer for testing purposes
  37. * @param {string} str string to use
  38. * @return {rspamd_text} resulting text
  39. */
  40. LUA_FUNCTION_DEF (text, null);
  41. /***
  42. * @function rspamd_text.randombytes(nbytes)
  43. * Creates rspamd_text with random bytes inside (raw bytes)
  44. * @param {number} nbytes number of random bytes generated
  45. * @return {rspamd_text} random bytes text
  46. */
  47. LUA_FUNCTION_DEF (text, randombytes);
  48. /***
  49. * @function rspamd_text.fromtable(tbl[, delim])
  50. * Same as `table.concat` but generates rspamd_text instead of the Lua string
  51. * @param {table} tbl table to use
  52. * @param {string} delim optional delimiter
  53. * @return {rspamd_text} resulting text
  54. */
  55. LUA_FUNCTION_DEF (text, fromtable);
  56. /***
  57. * @method rspamd_text:byte(pos[, pos2])
  58. * Returns a byte at the position `pos` or bytes from `pos` to `pos2` if specified
  59. * @param {integer} pos index
  60. * @param {integer} pos2 index
  61. * @return {integer} byte at the position `pos` or varargs of bytes
  62. */
  63. LUA_FUNCTION_DEF (text, byte);
  64. /***
  65. * @method rspamd_text:len()
  66. * Returns length of a string
  67. * @return {number} length of string in **bytes**
  68. */
  69. LUA_FUNCTION_DEF (text, len);
  70. /***
  71. * @method rspamd_text:str()
  72. * Converts text to string by copying its content
  73. * @return {string} copy of text as Lua string
  74. */
  75. LUA_FUNCTION_DEF (text, str);
  76. /***
  77. * @method rspamd_text:ptr()
  78. * Converts text to lightuserdata
  79. * @return {lightuserdata} pointer value of rspamd_text
  80. */
  81. LUA_FUNCTION_DEF (text, ptr);
  82. /***
  83. * @method rspamd_text:save_in_file(fname[, mode])
  84. * Saves text in file
  85. * @return {boolean} true if save has been completed
  86. */
  87. LUA_FUNCTION_DEF (text, save_in_file);
  88. /***
  89. * @method rspamd_text:span(start[, len])
  90. * Returns a span for lua_text starting at pos [start] (1 indexed) and with
  91. * length `len` (or to the end of the text)
  92. * @param {integer} start start index
  93. * @param {integer} len length of span
  94. * @return {rspamd_text} new rspamd_text with span (must be careful when using with owned texts...)
  95. */
  96. LUA_FUNCTION_DEF (text, span);
  97. /***
  98. * @method rspamd_text:sub(start[, len])
  99. * Returns a substrin for lua_text similar to string.sub from Lua
  100. * @return {rspamd_text} new rspamd_text with span (must be careful when using with owned texts...)
  101. */
  102. LUA_FUNCTION_DEF (text, sub);
  103. /***
  104. * @method rspamd_text:lines([stringify])
  105. * Returns an iter over all lines as rspamd_text objects or as strings if `stringify` is true
  106. * @param {boolean} stringify stringify lines
  107. * @return {iterator} iterator triplet
  108. */
  109. LUA_FUNCTION_DEF (text, lines);
  110. /***
  111. * @method rspamd_text:split(regexp, [stringify])
  112. * Returns an iter over all encounters of the specific regexp as rspamd_text objects or as strings if `stringify` is true
  113. * @param {rspamd_regexp} regexp regexp (pcre syntax) used for splitting
  114. * @param {boolean} stringify stringify lines
  115. * @return {iterator} iterator triplet
  116. */
  117. LUA_FUNCTION_DEF (text, split);
  118. /***
  119. * @method rspamd_text:at(pos)
  120. * Returns a byte at the position `pos`
  121. * @param {integer} pos index
  122. * @return {integer} byte at the position `pos` or nil if pos out of bound
  123. */
  124. LUA_FUNCTION_DEF (text, at);
  125. /***
  126. * @method rspamd_text:memchr(chr, [reverse])
  127. * Returns the first or the last position of the character `chr` in the text or
  128. * -1 in case if a character has not been found. Indexes start from `1`
  129. * @param {string/number} chr character or a character code to find
  130. * @param {boolean} reverse last character if `true`
  131. * @return {integer} position of the character or `-1`
  132. */
  133. LUA_FUNCTION_DEF (text, memchr);
  134. /***
  135. * @method rspamd_text:bytes()
  136. * Converts text to an array of bytes
  137. * @return {table|integer} bytes in the array (as unsigned char)
  138. */
  139. LUA_FUNCTION_DEF (text, bytes);
  140. /***
  141. * @method rspamd_text:lower([is_utf, [inplace]])
  142. * Return a new text with lowercased characters, if is_utf is true then Rspamd applies utf8 lowercase
  143. * @param {boolean} is_utf apply utf8 lowercase
  144. * @param {boolean} inplace lowercase the original text
  145. * @return {rspamd_text} new rspamd_text (or the original text if inplace) with lowercased letters
  146. */
  147. LUA_FUNCTION_DEF (text, lower);
  148. LUA_FUNCTION_DEF (text, take_ownership);
  149. /***
  150. * @method rspamd_text:exclude_chars(set_to_exclude, [always_copy])
  151. * Returns a text (if owned, then the original text is modified, if not, then it is copied and owned)
  152. * where all chars from `set_to_exclude` are removed
  153. * Patterns supported:
  154. *
  155. * - %s - all space characters
  156. * - %n - all newline characters
  157. * - %c - all control characters (it includes 8bit characters and spaces)
  158. * - %8 - all 8 bit characters
  159. * - %% - just a percent character
  160. *
  161. * @param {string} set_to_exclude characters to exclude
  162. * @param {boolean} always_copy always copy the source text
  163. * @return {rspamd_text} modified or copied text
  164. */
  165. LUA_FUNCTION_DEF (text, exclude_chars);
  166. /***
  167. * @method rspamd_text:oneline([always_copy])
  168. * Returns a text (if owned, then the original text is modified, if not, then it is copied and owned)
  169. * where the following transformations are made:
  170. * - All spaces sequences are replaced with a single space
  171. * - All newlines sequences are replaced with a single space
  172. * - Trailing and leading spaces are removed
  173. * - Control characters are excluded
  174. * - UTF8 sequences are normalised
  175. *
  176. * @param {boolean} always_copy always copy the source text
  177. * @return {rspamd_text} modified or copied text
  178. */
  179. LUA_FUNCTION_DEF (text, oneline);
  180. /***
  181. * @method rspamd_text:base32([b32type])
  182. * Returns a text encoded in base32 (new rspamd_text is allocated)
  183. *
  184. * @param {string} b32type base32 type (default, bleach, rfc)
  185. * @return {rspamd_text} new text encoded in base32
  186. */
  187. LUA_FUNCTION_DEF (text, base32);
  188. /***
  189. * @method rspamd_text:base64([line_length, [nline, [fold]]])
  190. * Returns a text encoded in base64 (new rspamd_text is allocated)
  191. *
  192. * @param {number} line_length return text splited with newlines up to this attribute
  193. * @param {string} nline newline type: `cr`, `lf`, `crlf`
  194. * @param {boolean} fold use folding when splitting into lines (false by default)
  195. * @return {rspamd_text} new text encoded in base64
  196. */
  197. LUA_FUNCTION_DEF (text, base64);
  198. /***
  199. * @method rspamd_text:hex()
  200. * Returns a text encoded in hex (new rspamd_text is allocated)
  201. *
  202. * @return {rspamd_text} new text encoded in hex
  203. */
  204. LUA_FUNCTION_DEF (text, hex);
  205. /***
  206. * @method rspamd_text:find(pattern [, init])
  207. * Looks for the first match of pattern in the string s.
  208. * If it finds a match, then find returns the indices of s where this occurrence
  209. * starts and ends; otherwise, it returns nil. A third,
  210. * optional numerical argument init specifies where to start the search;
  211. * its default value is 1 and can be negative.
  212. * This method currently supports merely a plain search, no patterns.
  213. *
  214. * @param {string} pattern pattern to find
  215. * @param {number} init specifies where to start the search (1 default)
  216. * @return {number,number/nil} If it finds a match, then find returns the indices of s where this occurrence starts and ends; otherwise, it returns nil
  217. */
  218. LUA_FUNCTION_DEF (text, find);
  219. LUA_FUNCTION_DEF (text, gc);
  220. LUA_FUNCTION_DEF (text, eq);
  221. LUA_FUNCTION_DEF (text, lt);
  222. LUA_FUNCTION_DEF (text, concat);
  223. LUA_FUNCTION_DEF (text, strtoul);
  224. static const struct luaL_reg textlib_f[] = {
  225. LUA_INTERFACE_DEF (text, fromstring),
  226. {"from_string", lua_text_fromstring},
  227. LUA_INTERFACE_DEF (text, fromtable),
  228. {"from_table", lua_text_fromtable},
  229. LUA_INTERFACE_DEF (text, null),
  230. LUA_INTERFACE_DEF (text, randombytes),
  231. {NULL, NULL}
  232. };
  233. static const struct luaL_reg textlib_m[] = {
  234. LUA_INTERFACE_DEF (text, len),
  235. LUA_INTERFACE_DEF (text, str),
  236. LUA_INTERFACE_DEF (text, ptr),
  237. LUA_INTERFACE_DEF (text, take_ownership),
  238. LUA_INTERFACE_DEF (text, save_in_file),
  239. LUA_INTERFACE_DEF (text, span),
  240. LUA_INTERFACE_DEF (text, sub),
  241. LUA_INTERFACE_DEF (text, lines),
  242. LUA_INTERFACE_DEF (text, split),
  243. LUA_INTERFACE_DEF (text, at),
  244. LUA_INTERFACE_DEF (text, memchr),
  245. LUA_INTERFACE_DEF (text, byte),
  246. LUA_INTERFACE_DEF (text, bytes),
  247. LUA_INTERFACE_DEF (text, lower),
  248. LUA_INTERFACE_DEF (text, exclude_chars),
  249. LUA_INTERFACE_DEF (text, oneline),
  250. LUA_INTERFACE_DEF (text, base32),
  251. LUA_INTERFACE_DEF (text, base64),
  252. LUA_INTERFACE_DEF (text, hex),
  253. LUA_INTERFACE_DEF (text, find),
  254. LUA_INTERFACE_DEF (text, strtoul),
  255. {"write", lua_text_save_in_file},
  256. {"__len", lua_text_len},
  257. {"__tostring", lua_text_str},
  258. {"__gc", lua_text_gc},
  259. {"__eq", lua_text_eq},
  260. {"__lt", lua_text_lt},
  261. {"__concat", lua_text_concat},
  262. {NULL, NULL}
  263. };
  264. struct rspamd_lua_text *
  265. lua_check_text (lua_State * L, gint pos)
  266. {
  267. void *ud = rspamd_lua_check_udata (L, pos, "rspamd{text}");
  268. luaL_argcheck (L, ud != NULL, pos, "'text' expected");
  269. return ud ? (struct rspamd_lua_text *)ud : NULL;
  270. }
  271. struct rspamd_lua_text *
  272. lua_check_text_or_string (lua_State * L, gint pos)
  273. {
  274. gint pos_type = lua_type (L, pos);
  275. if (pos_type == LUA_TUSERDATA) {
  276. void *ud = rspamd_lua_check_udata (L, pos, "rspamd{text}");
  277. luaL_argcheck (L, ud != NULL, pos, "'text' expected");
  278. return ud ? (struct rspamd_lua_text *) ud : NULL;
  279. }
  280. else if (pos_type == LUA_TSTRING) {
  281. /*
  282. * Fake static lua_text, we allow to use this function multiple times
  283. * by having a small array of static structures.
  284. */
  285. static int cur_txt_idx = 0;
  286. static struct rspamd_lua_text fake_text[4];
  287. gsize len;
  288. int sel_idx;
  289. sel_idx = cur_txt_idx++ % G_N_ELEMENTS (fake_text);
  290. fake_text[sel_idx].start = lua_tolstring (L, pos, &len);
  291. if (len >= G_MAXUINT) {
  292. return NULL;
  293. }
  294. fake_text[sel_idx].len = len;
  295. fake_text[sel_idx].flags = RSPAMD_TEXT_FLAG_FAKE;
  296. return &fake_text[sel_idx];
  297. }
  298. return NULL;
  299. }
  300. struct rspamd_lua_text *
  301. lua_new_text (lua_State *L, const gchar *start, gsize len, gboolean own)
  302. {
  303. struct rspamd_lua_text *t;
  304. t = lua_newuserdata (L, sizeof (*t));
  305. t->flags = 0;
  306. if (own) {
  307. gchar *storage;
  308. if (len > 0) {
  309. storage = g_malloc (len);
  310. if (start != NULL) {
  311. memcpy (storage, start, len);
  312. }
  313. t->start = storage;
  314. t->flags = RSPAMD_TEXT_FLAG_OWN;
  315. }
  316. else {
  317. t->start = "";
  318. }
  319. }
  320. else {
  321. t->start = start;
  322. }
  323. t->len = len;
  324. rspamd_lua_setclass (L, "rspamd{text}", -1);
  325. return t;
  326. }
  327. static gint
  328. lua_text_fromstring (lua_State *L)
  329. {
  330. LUA_TRACE_POINT;
  331. const gchar *str;
  332. gsize l = 0;
  333. gboolean transparent = FALSE;
  334. str = luaL_checklstring (L, 1, &l);
  335. if (str) {
  336. if (lua_isboolean (L, 2)) {
  337. transparent = lua_toboolean (L, 2);
  338. }
  339. lua_new_text (L, str, l, !transparent);
  340. }
  341. else {
  342. return luaL_error (L, "invalid arguments");
  343. }
  344. return 1;
  345. }
  346. static gint
  347. lua_text_null (lua_State *L)
  348. {
  349. LUA_TRACE_POINT;
  350. lua_new_text (L, NULL, 0, false);
  351. return 1;
  352. }
  353. static gint
  354. lua_text_randombytes (lua_State *L)
  355. {
  356. LUA_TRACE_POINT;
  357. guint nbytes = luaL_checkinteger (L, 1);
  358. struct rspamd_lua_text *out;
  359. out = lua_new_text (L, NULL, nbytes, TRUE);
  360. randombytes_buf ((char *)out->start, nbytes);
  361. out->len = nbytes;
  362. return 1;
  363. }
  364. #define MAX_REC 10
  365. static void
  366. lua_text_tbl_length (lua_State *L, gsize dlen, gsize *dest, guint rec)
  367. {
  368. gsize tblen, stlen;
  369. struct rspamd_lua_text *elt;
  370. if (rec > MAX_REC) {
  371. luaL_error (L, "lua_text_tbl_length: recursion limit exceeded");
  372. return;
  373. }
  374. tblen = rspamd_lua_table_size (L, -1);
  375. for (gsize i = 0; i < tblen; i ++) {
  376. lua_rawgeti (L, -1, i + 1);
  377. if (lua_type (L, -1) == LUA_TSTRING) {
  378. #if LUA_VERSION_NUM >= 502
  379. stlen = lua_rawlen (L, -1);
  380. #else
  381. stlen = lua_objlen (L, -1);
  382. #endif
  383. (*dest) += stlen;
  384. }
  385. else if (lua_type (L, -1) == LUA_TUSERDATA){
  386. elt = (struct rspamd_lua_text *)lua_touserdata (L, -1);
  387. if (elt) {
  388. (*dest) += elt->len;
  389. }
  390. }
  391. else if (lua_type (L, -1) == LUA_TTABLE) {
  392. lua_text_tbl_length (L, dlen, dest, rec + 1);
  393. }
  394. if (i != tblen - 1) {
  395. (*dest) += dlen;
  396. }
  397. lua_pop (L, 1);
  398. }
  399. }
  400. static void
  401. lua_text_tbl_append (lua_State *L,
  402. const gchar *delim,
  403. gsize dlen,
  404. gchar **dest,
  405. guint rec)
  406. {
  407. const gchar *st;
  408. gsize tblen, stlen;
  409. struct rspamd_lua_text *elt;
  410. if (rec > MAX_REC) {
  411. luaL_error (L, "lua_text_tbl_length: recursion limit exceeded");
  412. return;
  413. }
  414. tblen = rspamd_lua_table_size (L, -1);
  415. for (guint i = 0; i < tblen; i ++) {
  416. lua_rawgeti (L, -1, i + 1);
  417. if (lua_type (L, -1) == LUA_TSTRING) {
  418. st = lua_tolstring (L, -1, &stlen);
  419. memcpy ((*dest), st, stlen);
  420. (*dest) += stlen;
  421. }
  422. else if (lua_type (L, -1) == LUA_TUSERDATA){
  423. elt = (struct rspamd_lua_text *)lua_touserdata (L, -1);
  424. if (elt) {
  425. memcpy ((*dest), elt->start, elt->len);
  426. (*dest) += elt->len;
  427. }
  428. }
  429. else if (lua_type (L, -1) == LUA_TTABLE) {
  430. lua_text_tbl_append (L, delim, dlen, dest, rec + 1);
  431. }
  432. if (dlen && i != tblen - 1) {
  433. memcpy ((*dest), delim, dlen);
  434. (*dest) += dlen;
  435. }
  436. lua_pop (L, 1);
  437. }
  438. }
  439. static gint
  440. lua_text_fromtable (lua_State *L)
  441. {
  442. LUA_TRACE_POINT;
  443. const gchar *delim = "";
  444. struct rspamd_lua_text *t;
  445. gsize textlen = 0, dlen, oldtop = lua_gettop (L);
  446. gchar *dest;
  447. if (!lua_istable (L, 1)) {
  448. return luaL_error (L, "invalid arguments");
  449. }
  450. if (lua_type (L, 2) == LUA_TSTRING) {
  451. delim = lua_tolstring (L, 2, &dlen);
  452. }
  453. else {
  454. dlen = 0;
  455. }
  456. /* Calculate length needed */
  457. lua_pushvalue (L, 1);
  458. lua_text_tbl_length (L, dlen, &textlen, 0);
  459. lua_pop (L, 1);
  460. /* Allocate new text */
  461. t = lua_newuserdata (L, sizeof (*t));
  462. dest = g_malloc (textlen);
  463. t->start = dest;
  464. t->len = textlen;
  465. t->flags = RSPAMD_TEXT_FLAG_OWN;
  466. rspamd_lua_setclass (L, "rspamd{text}", -1);
  467. lua_pushvalue (L, 1);
  468. lua_text_tbl_append (L, delim, dlen, &dest, 0);
  469. lua_pop (L, 1); /* Table arg */
  470. gint newtop = lua_gettop (L);
  471. g_assert ( newtop== oldtop + 1);
  472. return 1;
  473. }
  474. static gint
  475. lua_text_len (lua_State *L)
  476. {
  477. LUA_TRACE_POINT;
  478. struct rspamd_lua_text *t = lua_check_text (L, 1);
  479. gsize l = 0;
  480. if (t != NULL) {
  481. l = t->len;
  482. }
  483. else {
  484. return luaL_error (L, "invalid arguments");
  485. }
  486. lua_pushinteger (L, l);
  487. return 1;
  488. }
  489. static gint
  490. lua_text_str (lua_State *L)
  491. {
  492. LUA_TRACE_POINT;
  493. struct rspamd_lua_text *t = lua_check_text (L, 1);
  494. if (t != NULL) {
  495. lua_pushlstring (L, t->start, t->len);
  496. }
  497. else {
  498. return luaL_error (L, "invalid arguments");
  499. }
  500. return 1;
  501. }
  502. static gint
  503. lua_text_ptr (lua_State *L)
  504. {
  505. LUA_TRACE_POINT;
  506. struct rspamd_lua_text *t = lua_check_text (L, 1);
  507. if (t != NULL) {
  508. lua_pushlightuserdata (L, (gpointer)t->start);
  509. }
  510. else {
  511. return luaL_error (L, "invalid arguments");
  512. }
  513. return 1;
  514. }
  515. static gint
  516. lua_text_take_ownership (lua_State *L)
  517. {
  518. LUA_TRACE_POINT;
  519. struct rspamd_lua_text *t = lua_check_text (L, 1);
  520. gchar *dest;
  521. if (t != NULL) {
  522. if (t->flags & RSPAMD_TEXT_FLAG_OWN) {
  523. /* We already own it */
  524. lua_pushboolean (L, true);
  525. }
  526. else {
  527. dest = g_malloc (t->len);
  528. memcpy (dest, t->start, t->len);
  529. t->start = dest;
  530. t->flags |= RSPAMD_TEXT_FLAG_OWN;
  531. lua_pushboolean (L, true);
  532. }
  533. }
  534. else {
  535. return luaL_error (L, "invalid arguments");
  536. }
  537. return 1;
  538. }
  539. static gint
  540. lua_text_span (lua_State *L)
  541. {
  542. LUA_TRACE_POINT;
  543. struct rspamd_lua_text *t = lua_check_text (L, 1);
  544. gint64 start = lua_tointeger (L, 2), len = -1;
  545. if (t && start >= 1 && start <= t->len) {
  546. if (lua_isnumber (L, 3)) {
  547. len = lua_tonumber (L, 3);
  548. }
  549. if (len == -1) {
  550. len = t->len - (start - 1);
  551. }
  552. if (len < 0 || (len > (t->len - (start - 1)))) {
  553. return luaL_error (L, "invalid length");
  554. }
  555. lua_new_text (L, t->start + (start - 1), len, FALSE);
  556. }
  557. else {
  558. if (!t) {
  559. return luaL_error (L, "invalid arguments, text required");
  560. }
  561. else {
  562. return luaL_error (L, "invalid arguments: start offset %d "
  563. "is larger than text len %d", (int)start, (int)t->len);
  564. }
  565. }
  566. return 1;
  567. }
  568. /* Helpers to behave exactly as Lua does */
  569. static inline gsize
  570. relative_pos_start (gint pos, gsize len)
  571. {
  572. if (pos > 0) {
  573. return pos;
  574. }
  575. else if (pos == 0) {
  576. return 1;
  577. }
  578. else if (pos < -((gint) len)) {
  579. return 1;
  580. }
  581. /* Negative pos inside str */
  582. return len + ((gsize)pos) + 1;
  583. }
  584. static inline gsize
  585. relative_pos_end (gint pos, gsize len)
  586. {
  587. if (pos > (gint)len) {
  588. return len;
  589. }
  590. else if (pos >= 0) {
  591. return (size_t) pos;
  592. }
  593. else if (pos < -((gint)len)) {
  594. return 0;
  595. }
  596. return len + ((gsize)pos) + 1;
  597. }
  598. static gint
  599. lua_text_sub (lua_State *L)
  600. {
  601. LUA_TRACE_POINT;
  602. struct rspamd_lua_text *t = lua_check_text (L, 1);
  603. if (t) {
  604. size_t start = relative_pos_start (luaL_checkinteger (L, 2),
  605. t->len);
  606. size_t end = relative_pos_end (luaL_optinteger (L, 3, -1),
  607. t->len);
  608. if (start <= end) {
  609. lua_new_text (L, t->start + (start - 1),
  610. (end - start) + 1, FALSE);
  611. }
  612. else {
  613. lua_new_text (L, "", 0, TRUE);
  614. }
  615. }
  616. else {
  617. return luaL_error (L, "invalid arguments");
  618. }
  619. return 1;
  620. }
  621. static gint64
  622. rspamd_lua_text_push_line (lua_State *L,
  623. struct rspamd_lua_text *t,
  624. gint64 start_offset,
  625. const gchar *sep_pos,
  626. gboolean stringify)
  627. {
  628. const gchar *start;
  629. gsize len;
  630. gint64 ret;
  631. start = t->start + start_offset;
  632. len = sep_pos ? (sep_pos - start) : (t->len - start_offset);
  633. ret = start_offset + len;
  634. /* Trim line */
  635. while (len > 0) {
  636. if (start[len - 1] == '\r' || start[len - 1] == '\n') {
  637. len --;
  638. }
  639. else {
  640. break;
  641. }
  642. }
  643. if (stringify) {
  644. lua_pushlstring (L, start, len);
  645. }
  646. else {
  647. struct rspamd_lua_text *ntext;
  648. ntext = lua_newuserdata (L, sizeof (*ntext));
  649. rspamd_lua_setclass (L, "rspamd{text}", -1);
  650. ntext->start = start;
  651. ntext->len = len;
  652. ntext->flags = 0; /* Not own as it must be owned by a top object */
  653. }
  654. return ret;
  655. }
  656. static gint
  657. rspamd_lua_text_readline (lua_State *L)
  658. {
  659. struct rspamd_lua_text *t = lua_touserdata (L, lua_upvalueindex (1));
  660. gboolean stringify = lua_toboolean (L, lua_upvalueindex (2));
  661. gint64 pos = lua_tointeger (L, lua_upvalueindex (3));
  662. if (pos < 0) {
  663. return luaL_error (L, "invalid pos: %d", (gint)pos);
  664. }
  665. if (pos >= t->len) {
  666. /* We are done */
  667. return 0;
  668. }
  669. const gchar *sep_pos;
  670. /* We look just for `\n` ignoring `\r` as it is very rare nowadays */
  671. sep_pos = memchr (t->start + pos, '\n', t->len - pos);
  672. if (sep_pos == NULL) {
  673. /* Either last `\n` or `\r` separated text */
  674. sep_pos = memchr (t->start + pos, '\r', t->len - pos);
  675. }
  676. pos = rspamd_lua_text_push_line (L, t, pos, sep_pos, stringify);
  677. /* Skip separators */
  678. while (pos < t->len) {
  679. if (t->start[pos] == '\n' || t->start[pos] == '\r') {
  680. pos ++;
  681. }
  682. else {
  683. break;
  684. }
  685. }
  686. /* Update pos */
  687. lua_pushinteger (L, pos);
  688. lua_replace (L, lua_upvalueindex (3));
  689. return 1;
  690. }
  691. static gint
  692. lua_text_lines (lua_State *L)
  693. {
  694. LUA_TRACE_POINT;
  695. struct rspamd_lua_text *t = lua_check_text (L, 1);
  696. gboolean stringify = FALSE;
  697. if (t) {
  698. if (lua_isboolean (L, 2)) {
  699. stringify = lua_toboolean (L, 2);
  700. }
  701. lua_pushvalue (L, 1);
  702. lua_pushboolean (L, stringify);
  703. lua_pushinteger (L, 0); /* Current pos */
  704. lua_pushcclosure (L, rspamd_lua_text_readline, 3);
  705. }
  706. else {
  707. return luaL_error (L, "invalid arguments");
  708. }
  709. return 1;
  710. }
  711. static gint
  712. rspamd_lua_text_regexp_split (lua_State *L) {
  713. struct rspamd_lua_text *t = lua_touserdata (L, lua_upvalueindex (1)),
  714. *new_t;
  715. struct rspamd_lua_regexp *re = *(struct rspamd_lua_regexp **)
  716. lua_touserdata (L, lua_upvalueindex (2));
  717. gboolean stringify = lua_toboolean (L, lua_upvalueindex (3));
  718. gint64 pos = lua_tointeger (L, lua_upvalueindex (4));
  719. gboolean matched;
  720. if (pos < 0) {
  721. return luaL_error (L, "invalid pos: %d", (gint) pos);
  722. }
  723. if (pos >= t->len) {
  724. /* We are done */
  725. return 0;
  726. }
  727. const gchar *start, *end, *old_start;
  728. end = t->start + pos;
  729. for (;;) {
  730. old_start = end;
  731. matched = rspamd_regexp_search (re->re, t->start, t->len, &start, &end, FALSE,
  732. NULL);
  733. if (matched) {
  734. if (start - old_start > 0) {
  735. if (stringify) {
  736. lua_pushlstring (L, old_start, start - old_start);
  737. }
  738. else {
  739. new_t = lua_newuserdata (L, sizeof (*t));
  740. rspamd_lua_setclass (L, "rspamd{text}", -1);
  741. new_t->start = old_start;
  742. new_t->len = start - old_start;
  743. new_t->flags = 0;
  744. }
  745. break;
  746. }
  747. else {
  748. if (start == end) {
  749. matched = FALSE;
  750. break;
  751. }
  752. /*
  753. * All match separators (e.g. starting separator,
  754. * we need to skip it). Continue iterations.
  755. */
  756. }
  757. }
  758. else {
  759. /* No match, stop */
  760. break;
  761. }
  762. }
  763. if (!matched && (t->len > 0 && (end == NULL || end < t->start + t->len))) {
  764. /* No more matches, but we might need to push the last element */
  765. if (end == NULL) {
  766. end = t->start;
  767. }
  768. /* No separators, need to push the whole remaining part */
  769. if (stringify) {
  770. lua_pushlstring (L, end, (t->start + t->len) - end);
  771. }
  772. else {
  773. new_t = lua_newuserdata (L, sizeof (*t));
  774. rspamd_lua_setclass (L, "rspamd{text}", -1);
  775. new_t->start = end;
  776. new_t->len = (t->start + t->len) - end;
  777. new_t->flags = 0;
  778. }
  779. pos = t->len;
  780. }
  781. else {
  782. pos = end - t->start;
  783. }
  784. /* Update pos */
  785. lua_pushinteger (L, pos);
  786. lua_replace (L, lua_upvalueindex (4));
  787. return 1;
  788. }
  789. static gint
  790. lua_text_split (lua_State *L)
  791. {
  792. LUA_TRACE_POINT;
  793. struct rspamd_lua_text *t = lua_check_text (L, 1);
  794. struct rspamd_lua_regexp *re;
  795. gboolean stringify = FALSE, own_re = FALSE;
  796. if (t == NULL) {
  797. return luaL_error (L, "invalid arguments");
  798. }
  799. if (lua_type (L, 2) == LUA_TUSERDATA) {
  800. re = lua_check_regexp (L, 2);
  801. }
  802. else {
  803. rspamd_regexp_t *c_re;
  804. GError *err = NULL;
  805. c_re = rspamd_regexp_new (lua_tostring (L, 2), NULL, &err);
  806. if (c_re == NULL) {
  807. gint ret = luaL_error (L, "cannot parse regexp: %s, error: %s",
  808. lua_tostring (L, 2),
  809. err == NULL ? "undefined" : err->message);
  810. if (err) {
  811. g_error_free (err);
  812. }
  813. return ret;
  814. }
  815. re = g_malloc0 (sizeof (struct rspamd_lua_regexp));
  816. re->re = c_re;
  817. re->re_pattern = g_strdup (lua_tostring (L, 2));
  818. re->module = rspamd_lua_get_module_name (L);
  819. own_re = TRUE;
  820. }
  821. if (re) {
  822. if (lua_isboolean (L, 3)) {
  823. stringify = lua_toboolean (L, 3);
  824. }
  825. /* Upvalues */
  826. lua_pushvalue (L, 1); /* text */
  827. if (own_re) {
  828. struct rspamd_lua_regexp **pre;
  829. pre = lua_newuserdata (L, sizeof (struct rspamd_lua_regexp *));
  830. rspamd_lua_setclass (L, "rspamd{regexp}", -1);
  831. *pre = re;
  832. }
  833. else {
  834. lua_pushvalue (L, 2); /* regexp */
  835. }
  836. lua_pushboolean (L, stringify);
  837. lua_pushinteger (L, 0); /* Current pos */
  838. lua_pushcclosure (L, rspamd_lua_text_regexp_split, 4);
  839. }
  840. else {
  841. return luaL_error (L, "invalid arguments");
  842. }
  843. return 1;
  844. }
  845. static gint
  846. lua_text_at (lua_State *L)
  847. {
  848. return lua_text_byte(L);
  849. }
  850. static gint
  851. lua_text_byte (lua_State *L)
  852. {
  853. LUA_TRACE_POINT;
  854. struct rspamd_lua_text *t = lua_check_text (L, 1);
  855. if (!t) {
  856. return luaL_error (L, "invalid arguments");
  857. }
  858. gsize start = relative_pos_start (luaL_optinteger (L, 2, 1), t->len);
  859. gsize end = relative_pos_end (luaL_optinteger (L, 3, start), t->len);
  860. start--;
  861. if (start >= end) {
  862. return 0;
  863. }
  864. for (gsize i = start; i < end; i++) {
  865. lua_pushinteger (L, t->start[i]);
  866. }
  867. return end - start;
  868. }
  869. static gint
  870. lua_text_memchr (lua_State *L)
  871. {
  872. LUA_TRACE_POINT;
  873. struct rspamd_lua_text *t = lua_check_text (L, 1);
  874. int c;
  875. bool reverse = false;
  876. if (lua_isnumber (L, 2)) {
  877. c = lua_tonumber (L, 2);
  878. }
  879. else {
  880. gsize l;
  881. const gchar *str = lua_tolstring (L, 2, &l);
  882. if (str) {
  883. c = str[0];
  884. if (l != 1) {
  885. return luaL_error (L, "need exactly one character to search");
  886. }
  887. }
  888. else {
  889. return luaL_error (L, "invalid arguments");
  890. }
  891. }
  892. if (t) {
  893. void *f;
  894. if (lua_isboolean (L, 3)) {
  895. reverse = lua_toboolean (L, 3);
  896. }
  897. if (reverse) {
  898. f = rspamd_memrchr (t->start, c, t->len);
  899. }
  900. else {
  901. f = memchr (t->start, c, t->len);
  902. }
  903. if (f) {
  904. lua_pushinteger (L, ((const char *)f) - t->start + 1);
  905. }
  906. else {
  907. lua_pushinteger (L, -1);
  908. }
  909. }
  910. else {
  911. return luaL_error (L, "invalid arguments");
  912. }
  913. return 1;
  914. }
  915. static gint
  916. lua_text_bytes (lua_State *L)
  917. {
  918. LUA_TRACE_POINT;
  919. struct rspamd_lua_text *t = lua_check_text (L, 1);
  920. if (t) {
  921. lua_createtable (L, t->len, 0);
  922. for (gsize i = 0; i < t->len; i ++) {
  923. lua_pushinteger (L, (guchar)t->start[i]);
  924. lua_rawseti (L, -2, i + 1);
  925. }
  926. }
  927. else {
  928. return luaL_error (L, "invalid arguments");
  929. }
  930. return 1;
  931. }
  932. static gint
  933. lua_text_save_in_file (lua_State *L)
  934. {
  935. LUA_TRACE_POINT;
  936. struct rspamd_lua_text *t = lua_check_text (L, 1);
  937. const gchar *fname = NULL;
  938. guint mode = 00644;
  939. gint fd = -1;
  940. gboolean need_close = FALSE;
  941. if (t != NULL) {
  942. if (lua_type (L, 2) == LUA_TSTRING) {
  943. fname = luaL_checkstring (L, 2);
  944. if (lua_type (L, 3) == LUA_TNUMBER) {
  945. mode = lua_tonumber (L, 3);
  946. }
  947. }
  948. else if (lua_type (L, 2) == LUA_TNUMBER) {
  949. /* Created fd */
  950. fd = lua_tonumber (L, 2);
  951. }
  952. if (fd == -1) {
  953. if (fname) {
  954. fd = rspamd_file_xopen (fname, O_CREAT | O_WRONLY | O_EXCL, mode, 0);
  955. if (fd == -1) {
  956. lua_pushboolean (L, false);
  957. lua_pushstring (L, strerror (errno));
  958. return 2;
  959. }
  960. need_close = TRUE;
  961. }
  962. else {
  963. fd = STDOUT_FILENO;
  964. }
  965. }
  966. if (write (fd, t->start, t->len) == -1) {
  967. if (fd != STDOUT_FILENO) {
  968. close (fd);
  969. }
  970. lua_pushboolean (L, false);
  971. lua_pushstring (L, strerror (errno));
  972. return 2;
  973. }
  974. if (need_close) {
  975. close (fd);
  976. }
  977. lua_pushboolean (L, true);
  978. }
  979. else {
  980. return luaL_error (L, "invalid arguments");
  981. }
  982. return 1;
  983. }
  984. static gint
  985. lua_text_gc (lua_State *L)
  986. {
  987. LUA_TRACE_POINT;
  988. struct rspamd_lua_text *t = lua_check_text (L, 1);
  989. if (t != NULL) {
  990. g_assert (!(t->flags & RSPAMD_TEXT_FLAG_FAKE));
  991. if (t->flags & RSPAMD_TEXT_FLAG_OWN) {
  992. if (t->flags & RSPAMD_TEXT_FLAG_WIPE) {
  993. rspamd_explicit_memzero ((guchar *)t->start, t->len);
  994. }
  995. if (t->flags & RSPAMD_TEXT_FLAG_MMAPED) {
  996. munmap ((gpointer)t->start, t->len);
  997. }
  998. else {
  999. if (t->flags & RSPAMD_TEXT_FLAG_SYSMALLOC) {
  1000. free ((gpointer) t->start);
  1001. }
  1002. else {
  1003. g_free ((gpointer) t->start);
  1004. }
  1005. }
  1006. }
  1007. }
  1008. return 0;
  1009. }
  1010. static gint
  1011. lua_text_eq (lua_State *L)
  1012. {
  1013. LUA_TRACE_POINT;
  1014. struct rspamd_lua_text *t1 = lua_check_text_or_string (L, 1),
  1015. *t2 = lua_check_text_or_string (L, 2);
  1016. if (t1->len == t2->len) {
  1017. lua_pushboolean (L, memcmp (t1->start, t2->start, t1->len) == 0);
  1018. }
  1019. else {
  1020. lua_pushboolean (L, false);
  1021. }
  1022. return 1;
  1023. }
  1024. static gint
  1025. lua_text_lt (lua_State *L)
  1026. {
  1027. LUA_TRACE_POINT;
  1028. struct rspamd_lua_text *t1 = lua_check_text_or_string (L, 1),
  1029. *t2 = lua_check_text_or_string (L, 2);
  1030. if (t1 && t2) {
  1031. if (t1->len == t2->len) {
  1032. lua_pushboolean (L, memcmp (t1->start, t2->start, t1->len) < 0);
  1033. }
  1034. else {
  1035. lua_pushboolean (L, t1->len < t2->len);
  1036. }
  1037. }
  1038. return 1;
  1039. }
  1040. static gint
  1041. lua_text_concat (lua_State *L)
  1042. {
  1043. LUA_TRACE_POINT;
  1044. struct rspamd_lua_text *t1 = lua_check_text_or_string (L, 1),
  1045. *t2 = lua_check_text_or_string (L, 2);
  1046. if (t1 && t2) {
  1047. struct rspamd_lua_text *final;
  1048. final = lua_new_text (L, NULL, t1->len + t2->len, TRUE);
  1049. memcpy ((void *)final->start, t1->start, t1->len);
  1050. memcpy ((void *)(final->start + t1->len), t2->start, t2->len);
  1051. }
  1052. return 1;
  1053. }
  1054. static gint
  1055. lua_text_wipe (lua_State *L)
  1056. {
  1057. LUA_TRACE_POINT;
  1058. struct rspamd_lua_text *t = lua_check_text (L, 1);
  1059. if (t != NULL) {
  1060. if (t->flags & RSPAMD_TEXT_FLAG_OWN) {
  1061. rspamd_explicit_memzero ((guchar *)t->start, t->len);
  1062. }
  1063. else {
  1064. return luaL_error (L, "cannot wipe not owned text");
  1065. }
  1066. }
  1067. else {
  1068. return luaL_error (L, "invalid arguments");
  1069. }
  1070. return 0;
  1071. }
  1072. static gint
  1073. lua_text_base32 (lua_State *L)
  1074. {
  1075. LUA_TRACE_POINT;
  1076. struct rspamd_lua_text *t = lua_check_text (L, 1), *out;
  1077. enum rspamd_base32_type btype = RSPAMD_BASE32_DEFAULT;
  1078. if (t != NULL) {
  1079. if (lua_type (L, 2) == LUA_TSTRING) {
  1080. btype = rspamd_base32_decode_type_from_str (lua_tostring (L, 2));
  1081. if (btype == RSPAMD_BASE32_INVALID) {
  1082. return luaL_error (L, "invalid b32 type: %s", lua_tostring (L, 2));
  1083. }
  1084. }
  1085. out = lua_new_text (L, NULL, t->len * 8 / 5 + 2, TRUE);
  1086. out->len = rspamd_encode_base32_buf (t->start, t->len, (gchar *)out->start,
  1087. out->len, btype);
  1088. }
  1089. else {
  1090. return luaL_error (L, "invalid arguments");
  1091. }
  1092. return 1;
  1093. }
  1094. static gint
  1095. lua_text_base64 (lua_State *L)
  1096. {
  1097. LUA_TRACE_POINT;
  1098. struct rspamd_lua_text *t = lua_check_text (L, 1), *out;
  1099. gsize line_len = 0;
  1100. gboolean fold = FALSE;
  1101. if (t != NULL) {
  1102. if (lua_type (L, 2) == LUA_TNUMBER) {
  1103. line_len = lua_tointeger (L, 2);
  1104. if (line_len <= 8) {
  1105. return luaL_error (L, "too small line length (at least 8 is required)");
  1106. }
  1107. }
  1108. enum rspamd_newlines_type how = RSPAMD_TASK_NEWLINES_CRLF;
  1109. if (lua_type (L, 3) == LUA_TSTRING) {
  1110. const gchar *how_str = lua_tostring (L, 3);
  1111. if (g_ascii_strcasecmp (how_str, "cr") == 0) {
  1112. how = RSPAMD_TASK_NEWLINES_CR;
  1113. }
  1114. else if (g_ascii_strcasecmp (how_str, "lf") == 0) {
  1115. how = RSPAMD_TASK_NEWLINES_LF;
  1116. }
  1117. else if (g_ascii_strcasecmp (how_str, "crlf") != 0) {
  1118. return luaL_error (L, "invalid newline style: %s", how_str);
  1119. }
  1120. }
  1121. if (lua_type (L, 4) == LUA_TBOOLEAN) {
  1122. fold = lua_toboolean (L, 4);
  1123. }
  1124. gsize sz_len;
  1125. out = lua_newuserdata (L, sizeof (*t));
  1126. out->flags = RSPAMD_TEXT_FLAG_OWN;
  1127. out->start = rspamd_encode_base64_common (t->start, t->len,
  1128. line_len, &sz_len, fold, how);
  1129. out->len = sz_len;
  1130. rspamd_lua_setclass (L, "rspamd{text}", -1);
  1131. }
  1132. else {
  1133. return luaL_error (L, "invalid arguments");
  1134. }
  1135. return 1;
  1136. }
  1137. static gint
  1138. lua_text_hex (lua_State *L)
  1139. {
  1140. LUA_TRACE_POINT;
  1141. struct rspamd_lua_text *t = lua_check_text (L, 1), *out;
  1142. if (t != NULL) {
  1143. out = lua_new_text (L, NULL, t->len * 2, TRUE);
  1144. out->len = rspamd_encode_hex_buf (t->start, t->len, (gchar *)out->start,
  1145. out->len);
  1146. }
  1147. else {
  1148. return luaL_error (L, "invalid arguments");
  1149. }
  1150. return 1;
  1151. }
  1152. static gint
  1153. lua_text_find (lua_State *L)
  1154. {
  1155. LUA_TRACE_POINT;
  1156. struct rspamd_lua_text *t = lua_check_text (L, 1);
  1157. gsize patlen, init = 1;
  1158. const gchar *pat = luaL_checklstring (L, 2, &patlen);
  1159. if (t != NULL && pat != NULL) {
  1160. if (lua_isnumber (L, 3)) {
  1161. init = relative_pos_start (lua_tointeger (L, 3), t->len);
  1162. }
  1163. init --;
  1164. if (init > t->len) {
  1165. return luaL_error (L, "invalid arguments to find: init too large");
  1166. }
  1167. goffset pos = rspamd_substring_search (t->start + init,
  1168. t->len - init,
  1169. pat, patlen);
  1170. if (pos == -1) {
  1171. lua_pushnil (L);
  1172. return 1;
  1173. }
  1174. lua_pushinteger (L, pos + 1);
  1175. lua_pushinteger (L, pos + patlen);
  1176. }
  1177. else {
  1178. return luaL_error (L, "invalid arguments");
  1179. }
  1180. return 2;
  1181. }
  1182. #define BITOP(a,b,op) \
  1183. ((a)[(gsize)(b)/(8*sizeof *(a))] op (gsize)1<<((gsize)(b)%(8*sizeof *(a))))
  1184. static gint
  1185. lua_text_exclude_chars (lua_State *L)
  1186. {
  1187. LUA_TRACE_POINT;
  1188. struct rspamd_lua_text *t = lua_check_text (L, 1);
  1189. gssize patlen;
  1190. const gchar *pat = lua_tolstring (L, 2, &patlen), *p, *end;
  1191. gchar *dest, *d;
  1192. gsize byteset[32 / sizeof(gsize)]; /* Bitset for ascii */
  1193. gboolean copy = TRUE;
  1194. guint *plen;
  1195. if (t != NULL && pat && patlen > 0) {
  1196. if (lua_isboolean (L, 3)) {
  1197. copy = lua_toboolean (L, 3);
  1198. }
  1199. else if (t->flags & RSPAMD_TEXT_FLAG_OWN) {
  1200. copy = FALSE;
  1201. }
  1202. if (!copy) {
  1203. dest = (gchar *)t->start;
  1204. plen = &t->len;
  1205. lua_pushvalue (L, 1); /* Push text as a result */
  1206. }
  1207. else {
  1208. /* We need to copy read only text */
  1209. struct rspamd_lua_text *nt;
  1210. dest = g_malloc (t->len);
  1211. nt = lua_newuserdata (L, sizeof (*nt));
  1212. rspamd_lua_setclass (L, "rspamd{text}", -1);
  1213. nt->len = t->len;
  1214. nt->flags = RSPAMD_TEXT_FLAG_OWN;
  1215. memcpy (dest, t->start, t->len);
  1216. nt->start = dest;
  1217. plen = &nt->len;
  1218. }
  1219. /* Fill pattern bitset */
  1220. memset (byteset, 0, sizeof byteset);
  1221. while (patlen > 0) {
  1222. if (*pat == '%') {
  1223. pat ++;
  1224. patlen --;
  1225. if (patlen > 0) {
  1226. /*
  1227. * This stuff assumes little endian, but GSIZE_FROM_LE should
  1228. * deal with proper conversion
  1229. */
  1230. switch (*pat) {
  1231. case '%':
  1232. BITOP (byteset, *(guchar *) pat, |=);
  1233. break;
  1234. case 's':
  1235. /* "\r\n\t\f " */
  1236. byteset[0] |= GSIZE_FROM_LE (0x100003600);
  1237. break;
  1238. case 'n':
  1239. /* newlines: "\r\n" */
  1240. byteset[0] |= GSIZE_FROM_LE (0x2400);
  1241. break;
  1242. case '8':
  1243. /* 8 bit characters */
  1244. byteset[2] |= GSIZE_FROM_LE (0xffffffffffffffffLLU);
  1245. byteset[3] |= GSIZE_FROM_LE (0xffffffffffffffffLLU);
  1246. break;
  1247. case 'c':
  1248. /* Non printable (control) characters */
  1249. byteset[0] |= GSIZE_FROM_LE (0xffffffff);
  1250. /* Del character */
  1251. byteset[1] |= GSIZE_FROM_LE (0x8000000000000000);
  1252. break;
  1253. }
  1254. }
  1255. else {
  1256. /* Last '%' */
  1257. BITOP (byteset, (guchar)'%', |=);
  1258. }
  1259. }
  1260. else {
  1261. BITOP (byteset, *(guchar *)pat, |=);
  1262. }
  1263. pat ++;
  1264. patlen --;
  1265. }
  1266. for (; patlen > 0 && BITOP (byteset, *(guchar *)pat, |=); pat++, patlen --);
  1267. p = t->start;
  1268. end = t->start + t->len;
  1269. d = dest;
  1270. while (p < end) {
  1271. if (!BITOP (byteset, *(guchar *)p, &)) {
  1272. *d++ = *p;
  1273. }
  1274. p ++;
  1275. }
  1276. *(plen) = d - dest;
  1277. }
  1278. else {
  1279. return luaL_error (L, "invalid arguments");
  1280. }
  1281. return 1;
  1282. }
  1283. static gint
  1284. lua_text_oneline (lua_State *L)
  1285. {
  1286. LUA_TRACE_POINT;
  1287. struct rspamd_lua_text *t = lua_check_text (L, 1);
  1288. const gchar *p, *end;
  1289. gchar *dest, *d;
  1290. gsize byteset[32 / sizeof(gsize)]; /* Bitset for ascii */
  1291. gboolean copy = TRUE, seen_8bit = FALSE;
  1292. guint *plen;
  1293. if (t != NULL) {
  1294. if (lua_isboolean (L, 2)) {
  1295. copy = lua_toboolean (L, 2);
  1296. }
  1297. else if (t->flags & RSPAMD_TEXT_FLAG_OWN) {
  1298. copy = FALSE;
  1299. }
  1300. if (!copy) {
  1301. dest = (gchar *)t->start;
  1302. plen = &t->len;
  1303. lua_pushvalue (L, 1); /* Push text as a result */
  1304. }
  1305. else {
  1306. /* We need to copy read only text */
  1307. struct rspamd_lua_text *nt;
  1308. dest = g_malloc (t->len);
  1309. nt = lua_newuserdata (L, sizeof (*nt));
  1310. rspamd_lua_setclass (L, "rspamd{text}", -1);
  1311. nt->len = t->len;
  1312. nt->flags = RSPAMD_TEXT_FLAG_OWN;
  1313. memcpy (dest, t->start, t->len);
  1314. nt->start = dest;
  1315. plen = &nt->len;
  1316. }
  1317. /* Fill pattern bitset */
  1318. memset (byteset, 0, sizeof byteset);
  1319. /* All spaces */
  1320. byteset[0] |= GSIZE_FROM_LE (0x100003600);
  1321. /* Control characters */
  1322. byteset[0] |= GSIZE_FROM_LE (0xffffffff);
  1323. /* Del character */
  1324. byteset[1] |= GSIZE_FROM_LE (0x8000000000000000);
  1325. /* 8 bit characters */
  1326. byteset[2] |= GSIZE_FROM_LE (0xffffffffffffffffLLU);
  1327. byteset[3] |= GSIZE_FROM_LE (0xffffffffffffffffLLU);
  1328. p = t->start;
  1329. end = t->start + t->len;
  1330. d = dest;
  1331. while (p < end) {
  1332. if (!BITOP (byteset, *(guchar *)p, &)) {
  1333. *d++ = *p;
  1334. }
  1335. else {
  1336. if ((*(guchar *)p) & 0x80) {
  1337. seen_8bit = TRUE;
  1338. *d++ = *p;
  1339. }
  1340. else {
  1341. if (*p == ' ') {
  1342. if (d != dest) {
  1343. *d++ = *p++;
  1344. }
  1345. while (p < end && g_ascii_isspace (*p)) {
  1346. p ++;
  1347. }
  1348. continue; /* To avoid p++ */
  1349. }
  1350. else if (*p == '\r' || *p == '\n') {
  1351. if (d != dest) {
  1352. *d++ = ' ';
  1353. p ++;
  1354. }
  1355. while (p < end && g_ascii_isspace (*p)) {
  1356. p ++;
  1357. }
  1358. continue; /* To avoid p++ */
  1359. }
  1360. }
  1361. }
  1362. p ++;
  1363. }
  1364. while (d > dest && g_ascii_isspace (*(d - 1))) {
  1365. d --;
  1366. }
  1367. if (seen_8bit) {
  1368. if (rspamd_fast_utf8_validate (dest, d - dest) != 0) {
  1369. /* Need to make it valid :( */
  1370. UChar32 uc;
  1371. goffset err_offset;
  1372. gsize remain = d - dest;
  1373. gchar *nd = dest;
  1374. while (remain > 0 && (err_offset = rspamd_fast_utf8_validate (nd, remain)) > 0) {
  1375. gint i = 0;
  1376. err_offset --; /* As it returns it 1 indexed */
  1377. nd += err_offset;
  1378. remain -= err_offset;
  1379. /* Each invalid character of input requires 3 bytes of output (+2 bytes) */
  1380. while (i < remain) {
  1381. gint old_pos = i;
  1382. U8_NEXT (nd, i, remain, uc);
  1383. if (uc < 0) {
  1384. nd[old_pos] = '?';
  1385. }
  1386. else {
  1387. break;
  1388. }
  1389. }
  1390. nd += i;
  1391. remain -= i;
  1392. }
  1393. }
  1394. }
  1395. *(plen) = d - dest;
  1396. }
  1397. else {
  1398. return luaL_error (L, "invalid arguments");
  1399. }
  1400. return 1;
  1401. }
  1402. static gint
  1403. lua_text_lower (lua_State *L)
  1404. {
  1405. LUA_TRACE_POINT;
  1406. struct rspamd_lua_text *t = lua_check_text (L, 1), *nt;
  1407. gboolean is_utf8 = FALSE, is_inplace = FALSE;
  1408. if (t != NULL) {
  1409. if (lua_isboolean (L, 2)) {
  1410. is_utf8 = lua_toboolean (L, 2);
  1411. }
  1412. if (lua_isboolean (L, 3)) {
  1413. is_inplace = lua_toboolean (L, 3);
  1414. }
  1415. if (is_inplace) {
  1416. nt = t;
  1417. lua_pushvalue (L, 1);
  1418. }
  1419. else {
  1420. nt = lua_new_text (L, t->start, t->len, TRUE);
  1421. }
  1422. if (!is_utf8) {
  1423. rspamd_str_lc ((gchar *) nt->start, nt->len);
  1424. }
  1425. else {
  1426. rspamd_str_lc_utf8 ((gchar *) nt->start, nt->len);
  1427. }
  1428. }
  1429. else {
  1430. return luaL_error (L, "invalid arguments");
  1431. }
  1432. return 1;
  1433. }
  1434. static gint
  1435. lua_text_strtoul (lua_State *L)
  1436. {
  1437. LUA_TRACE_POINT;
  1438. struct rspamd_lua_text *t = lua_check_text (L, 1);
  1439. if (t) {
  1440. unsigned long ll;
  1441. if (rspamd_strtoul (t->start, t->len, &ll)) {
  1442. lua_pushinteger (L, ll);
  1443. }
  1444. else {
  1445. lua_pushnil (L);
  1446. }
  1447. }
  1448. else {
  1449. return luaL_error (L, "invalid arguments");
  1450. }
  1451. return 1;
  1452. }
  1453. /* Used to distinguish lua text metatable */
  1454. static const guint rspamd_lua_text_cookie = 0x2b21ef6fU;
  1455. static gint
  1456. lua_load_text (lua_State * L)
  1457. {
  1458. lua_newtable (L);
  1459. lua_pushstring (L, "cookie");
  1460. lua_pushnumber (L, rspamd_lua_text_cookie);
  1461. lua_settable (L, -3);
  1462. luaL_register (L, NULL, textlib_f);
  1463. return 1;
  1464. }
  1465. void
  1466. luaopen_text (lua_State *L)
  1467. {
  1468. rspamd_lua_new_class (L, "rspamd{text}", textlib_m);
  1469. lua_pushstring (L, "cookie");
  1470. lua_pushnumber (L, rspamd_lua_text_cookie);
  1471. lua_settable (L, -3);
  1472. lua_pop (L, 1);
  1473. rspamd_lua_add_preload (L, "rspamd_text", lua_load_text);
  1474. }