regex_match.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /**
  2. * @file regex_match.c
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of the author nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *
  29. * @section DESCRIPTION
  30. *
  31. * Regular expression matching module.
  32. *
  33. * Synopsis:
  34. * regex_match(string input, string regex)
  35. *
  36. * Variables:
  37. * succeeded - "true" or "false", indicating whether input matched regex
  38. * matchN - for N=0,1,2,..., the matching data for the N-th subexpression
  39. * (match0 = whole match)
  40. *
  41. * Description:
  42. * Matches 'input' with the POSIX extended regular expression 'regex'.
  43. * 'regex' must be a string without null bytes, but 'input' can contain null bytes.
  44. * However, it's difficult, if not impossible, to actually match nulls with the regular
  45. * expression.
  46. * The input and regex strings are interpreted according to the POSIX regex functions
  47. * (regcomp(), regexec()); in particular, the current locale setting affects the
  48. * interpretation.
  49. *
  50. * Synopsis:
  51. * regex_replace(string input, list(string) regex, list(string) replace)
  52. *
  53. * Variables:
  54. * string (empty) - transformed input
  55. *
  56. * Description:
  57. * Replaces matching parts of a string. Replacement is performed by repetedly matching
  58. * the remaining part of the string with all regular expressions. On each step, out of
  59. * all regular expressions that match the remainder of the string, the one whose match
  60. * starts at the least position wins, and the matching part is replaced with the
  61. * replacement string corresponding to this regular expression. The process continues
  62. * from the end of the just-replaced portion until no more regular expressions match.
  63. * If multiple regular expressions match at the least position, the one that appears
  64. * first in the 'regex' argument wins.
  65. */
  66. #include <stdlib.h>
  67. #include <string.h>
  68. #include <limits.h>
  69. #include <regex.h>
  70. #include <misc/string_begins_with.h>
  71. #include <misc/parse_number.h>
  72. #include <misc/expstring.h>
  73. #include <misc/debug.h>
  74. #include <misc/balloc.h>
  75. #include <ncd/NCDModule.h>
  76. #include <generated/blog_channel_ncd_regex_match.h>
  77. #define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__)
  78. #define MAX_MATCHES 64
  79. struct instance {
  80. NCDModuleInst *i;
  81. const char *input;
  82. size_t input_len;
  83. int succeeded;
  84. int num_matches;
  85. regmatch_t matches[MAX_MATCHES];
  86. };
  87. struct replace_instance {
  88. NCDModuleInst *i;
  89. char *output;
  90. size_t output_len;
  91. };
  92. static void func_new (void *vo, NCDModuleInst *i)
  93. {
  94. struct instance *o = vo;
  95. o->i = i;
  96. // read arguments
  97. NCDValRef input_arg;
  98. NCDValRef regex_arg;
  99. if (!NCDVal_ListRead(o->i->args, 2, &input_arg, &regex_arg)) {
  100. ModuleLog(o->i, BLOG_ERROR, "wrong arity");
  101. goto fail0;
  102. }
  103. if (!NCDVal_IsString(input_arg) || !NCDVal_IsStringNoNulls(regex_arg)) {
  104. ModuleLog(o->i, BLOG_ERROR, "wrong type");
  105. goto fail0;
  106. }
  107. o->input = NCDVal_StringValue(input_arg);
  108. o->input_len = NCDVal_StringLength(input_arg);
  109. const char *regex = NCDVal_StringValue(regex_arg);
  110. // make sure we don't overflow regoff_t
  111. if (o->input_len > INT_MAX) {
  112. ModuleLog(o->i, BLOG_ERROR, "input string too long");
  113. goto fail0;
  114. }
  115. // compile regex
  116. regex_t preg;
  117. int ret;
  118. if ((ret = regcomp(&preg, regex, REG_EXTENDED)) != 0) {
  119. ModuleLog(o->i, BLOG_ERROR, "regcomp failed (error=%d)", ret);
  120. goto fail0;
  121. }
  122. // execute match
  123. o->matches[0].rm_so = 0;
  124. o->matches[0].rm_eo = o->input_len;
  125. o->succeeded = (regexec(&preg, o->input, MAX_MATCHES, o->matches, REG_STARTEND) == 0);
  126. // free regex
  127. regfree(&preg);
  128. // signal up
  129. NCDModuleInst_Backend_Up(o->i);
  130. return;
  131. fail0:
  132. NCDModuleInst_Backend_SetError(i);
  133. NCDModuleInst_Backend_Dead(i);
  134. }
  135. static int func_getvar (void *vo, const char *name, NCDValMem *mem, NCDValRef *out)
  136. {
  137. struct instance *o = vo;
  138. if (!strcmp(name, "succeeded")) {
  139. const char *str = o->succeeded ? "true" : "false";
  140. *out = NCDVal_NewString(mem, str);
  141. if (NCDVal_IsInvalid(*out)) {
  142. ModuleLog(o->i, BLOG_ERROR, "NCDVal_NewString failed");
  143. }
  144. return 1;
  145. }
  146. size_t pos;
  147. uintmax_t n;
  148. if ((pos = string_begins_with(name, "match")) && parse_unsigned_integer(name + pos, &n)) {
  149. if (o->succeeded && n < MAX_MATCHES && o->matches[n].rm_so >= 0) {
  150. regmatch_t *m = &o->matches[n];
  151. ASSERT(m->rm_so <= o->input_len)
  152. ASSERT(m->rm_eo >= m->rm_so)
  153. ASSERT(m->rm_eo <= o->input_len)
  154. size_t len = m->rm_eo - m->rm_so;
  155. *out = NCDVal_NewStringBin(mem, (uint8_t *)o->input + m->rm_so, len);
  156. if (NCDVal_IsInvalid(*out)) {
  157. ModuleLog(o->i, BLOG_ERROR, "NCDVal_NewStringBin failed");
  158. }
  159. return 1;
  160. }
  161. }
  162. return 0;
  163. }
  164. static void replace_func_new (void *vo, NCDModuleInst *i)
  165. {
  166. struct replace_instance *o = vo;
  167. o->i = i;
  168. // read arguments
  169. NCDValRef input_arg;
  170. NCDValRef regex_arg;
  171. NCDValRef replace_arg;
  172. if (!NCDVal_ListRead(i->args, 3, &input_arg, &regex_arg, &replace_arg)) {
  173. ModuleLog(i, BLOG_ERROR, "wrong arity");
  174. goto fail1;
  175. }
  176. if (!NCDVal_IsString(input_arg) || !NCDVal_IsList(regex_arg) || !NCDVal_IsList(replace_arg)) {
  177. ModuleLog(i, BLOG_ERROR, "wrong type");
  178. goto fail1;
  179. }
  180. // check number of regex/replace
  181. if (NCDVal_ListCount(regex_arg) != NCDVal_ListCount(replace_arg)) {
  182. ModuleLog(i, BLOG_ERROR, "number of regex's is not the same as number of replacements");
  183. goto fail1;
  184. }
  185. size_t num_regex = NCDVal_ListCount(regex_arg);
  186. // allocate array for compiled regex's
  187. regex_t *regs = BAllocArray(num_regex, sizeof(regs[0]));
  188. if (!regs) {
  189. ModuleLog(i, BLOG_ERROR, "BAllocArray failed");
  190. goto fail1;
  191. }
  192. size_t num_done_regex = 0;
  193. // compile regex's, check arguments
  194. while (num_done_regex < num_regex) {
  195. NCDValRef regex = NCDVal_ListGet(regex_arg, num_done_regex);
  196. NCDValRef replace = NCDVal_ListGet(replace_arg, num_done_regex);
  197. if (!NCDVal_IsStringNoNulls(regex) || !NCDVal_IsString(replace)) {
  198. ModuleLog(i, BLOG_ERROR, "wrong regex/replace type for pair %zu", num_done_regex);
  199. goto fail2;
  200. }
  201. int res = regcomp(&regs[num_done_regex], NCDVal_StringValue(regex), REG_EXTENDED);
  202. if (res != 0) {
  203. ModuleLog(i, BLOG_ERROR, "regcomp failed for pair %zu (error=%d)", num_done_regex, res);
  204. goto fail2;
  205. }
  206. num_done_regex++;
  207. }
  208. // init output string
  209. ExpString out;
  210. if (!ExpString_Init(&out)) {
  211. ModuleLog(i, BLOG_ERROR, "ExpString_Init failed");
  212. goto fail2;
  213. }
  214. // input state
  215. const char *in = NCDVal_StringValue(input_arg);
  216. size_t in_pos = 0;
  217. size_t in_len = NCDVal_StringLength(input_arg);
  218. // process input
  219. while (in_pos < in_len) {
  220. // find first match
  221. int have_match = 0;
  222. size_t match_regex;
  223. regmatch_t match;
  224. for (size_t j = 0; j < num_regex; j++) {
  225. regmatch_t this_match;
  226. this_match.rm_so = 0;
  227. this_match.rm_eo = in_len - in_pos;
  228. if (regexec(&regs[j], in + in_pos, 1, &this_match, REG_STARTEND) == 0 && (!have_match || this_match.rm_so < match.rm_so)) {
  229. have_match = 1;
  230. match_regex = j;
  231. match = this_match;
  232. }
  233. }
  234. // if no match, append remaining data and finish
  235. if (!have_match) {
  236. if (!ExpString_AppendBinary(&out, (const uint8_t *)in + in_pos, in_len - in_pos)) {
  237. ModuleLog(i, BLOG_ERROR, "ExpString_AppendBinary failed");
  238. goto fail3;
  239. }
  240. break;
  241. }
  242. // append data before match
  243. if (!ExpString_AppendBinary(&out, (const uint8_t *)in + in_pos, match.rm_so)) {
  244. ModuleLog(i, BLOG_ERROR, "ExpString_AppendBinary failed");
  245. goto fail3;
  246. }
  247. // append replacement data
  248. NCDValRef replace = NCDVal_ListGet(replace_arg, match_regex);
  249. if (!ExpString_AppendBinary(&out, (const uint8_t *)NCDVal_StringValue(replace), NCDVal_StringLength(replace))) {
  250. ModuleLog(i, BLOG_ERROR, "ExpString_AppendBinary failed");
  251. goto fail3;
  252. }
  253. in_pos += match.rm_eo;
  254. }
  255. // set output
  256. o->output = ExpString_Get(&out);
  257. o->output_len = ExpString_Length(&out);
  258. // free compiled regex's
  259. while (num_done_regex-- > 0) {
  260. regfree(&regs[num_done_regex]);
  261. }
  262. // free array
  263. BFree(regs);
  264. // signal up
  265. NCDModuleInst_Backend_Up(i);
  266. return;
  267. fail3:
  268. ExpString_Free(&out);
  269. fail2:
  270. while (num_done_regex-- > 0) {
  271. regfree(&regs[num_done_regex]);
  272. }
  273. BFree(regs);
  274. fail1:
  275. NCDModuleInst_Backend_SetError(i);
  276. NCDModuleInst_Backend_Dead(i);
  277. }
  278. static void replace_func_die (void *vo)
  279. {
  280. struct replace_instance *o = vo;
  281. // free output
  282. BFree(o->output);
  283. NCDModuleInst_Backend_Dead(o->i);
  284. }
  285. static int replace_func_getvar (void *vo, const char *name, NCDValMem *mem, NCDValRef *out)
  286. {
  287. struct replace_instance *o = vo;
  288. if (!strcmp(name, "")) {
  289. *out = NCDVal_NewStringBin(mem, (uint8_t *)o->output, o->output_len);
  290. if (NCDVal_IsInvalid(*out)) {
  291. ModuleLog(o->i, BLOG_ERROR, "NCDVal_NewStringBin failed");
  292. }
  293. return 1;
  294. }
  295. return 0;
  296. }
  297. static const struct NCDModule modules[] = {
  298. {
  299. .type = "regex_match",
  300. .func_new2 = func_new,
  301. .func_getvar = func_getvar,
  302. .alloc_size = sizeof(struct instance)
  303. }, {
  304. .type = "regex_replace",
  305. .func_new2 = replace_func_new,
  306. .func_die = replace_func_die,
  307. .func_getvar = replace_func_getvar,
  308. .alloc_size = sizeof(struct replace_instance)
  309. }, {
  310. .type = NULL
  311. }
  312. };
  313. const struct NCDModuleGroup ncdmodule_regex_match = {
  314. .modules = modules
  315. };