regex_match.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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/module_common.h>
  76. #include <generated/blog_channel_ncd_regex_match.h>
  77. #define MAX_MATCHES 64
  78. struct instance {
  79. NCDModuleInst *i;
  80. MemRef input;
  81. int succeeded;
  82. int num_matches;
  83. regmatch_t matches[MAX_MATCHES];
  84. };
  85. struct replace_instance {
  86. NCDModuleInst *i;
  87. MemRef output;
  88. };
  89. static void func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  90. {
  91. struct instance *o = vo;
  92. o->i = i;
  93. // read arguments
  94. NCDValRef input_arg;
  95. NCDValRef regex_arg;
  96. if (!NCDVal_ListRead(params->args, 2, &input_arg, &regex_arg)) {
  97. ModuleLog(o->i, BLOG_ERROR, "wrong arity");
  98. goto fail0;
  99. }
  100. if (!NCDVal_IsString(input_arg) || !NCDVal_IsStringNoNulls(regex_arg)) {
  101. ModuleLog(o->i, BLOG_ERROR, "wrong type");
  102. goto fail0;
  103. }
  104. o->input = NCDVal_StringMemRef(input_arg);
  105. // make sure we don't overflow regoff_t
  106. if (o->input.len > INT_MAX) {
  107. ModuleLog(o->i, BLOG_ERROR, "input string too long");
  108. goto fail0;
  109. }
  110. // null terminate regex
  111. NCDValNullTermString regex_nts;
  112. if (!NCDVal_StringNullTerminate(regex_arg, &regex_nts)) {
  113. ModuleLog(i, BLOG_ERROR, "NCDVal_StringNullTerminate failed");
  114. goto fail0;
  115. }
  116. // compile regex
  117. regex_t preg;
  118. int ret = regcomp(&preg, regex_nts.data, REG_EXTENDED);
  119. NCDValNullTermString_Free(&regex_nts);
  120. if (ret != 0) {
  121. ModuleLog(o->i, BLOG_ERROR, "regcomp failed (error=%d)", ret);
  122. goto fail0;
  123. }
  124. // execute match
  125. o->matches[0].rm_so = 0;
  126. o->matches[0].rm_eo = o->input.len;
  127. o->succeeded = (regexec(&preg, o->input.ptr, MAX_MATCHES, o->matches, REG_STARTEND) == 0);
  128. // free regex
  129. regfree(&preg);
  130. // signal up
  131. NCDModuleInst_Backend_Up(o->i);
  132. return;
  133. fail0:
  134. NCDModuleInst_Backend_DeadError(i);
  135. }
  136. static int func_getvar (void *vo, const char *name, NCDValMem *mem, NCDValRef *out)
  137. {
  138. struct instance *o = vo;
  139. if (!strcmp(name, "succeeded")) {
  140. *out = ncd_make_boolean(mem, o->succeeded, o->i->params->iparams->string_index);
  141. return 1;
  142. }
  143. size_t pos;
  144. uintmax_t n;
  145. if ((pos = string_begins_with(name, "match")) && parse_unsigned_integer(name + pos, &n)) {
  146. if (o->succeeded && n < MAX_MATCHES && o->matches[n].rm_so >= 0) {
  147. regmatch_t *m = &o->matches[n];
  148. ASSERT(m->rm_so <= o->input.len)
  149. ASSERT(m->rm_eo >= m->rm_so)
  150. ASSERT(m->rm_eo <= o->input.len)
  151. size_t len = m->rm_eo - m->rm_so;
  152. *out = NCDVal_NewStringBinMr(mem, MemRef_Sub(o->input, m->rm_so, len));
  153. return 1;
  154. }
  155. }
  156. return 0;
  157. }
  158. static void replace_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  159. {
  160. struct replace_instance *o = vo;
  161. o->i = i;
  162. // read arguments
  163. NCDValRef input_arg;
  164. NCDValRef regex_arg;
  165. NCDValRef replace_arg;
  166. if (!NCDVal_ListRead(params->args, 3, &input_arg, &regex_arg, &replace_arg)) {
  167. ModuleLog(i, BLOG_ERROR, "wrong arity");
  168. goto fail1;
  169. }
  170. if (!NCDVal_IsString(input_arg) || !NCDVal_IsList(regex_arg) || !NCDVal_IsList(replace_arg)) {
  171. ModuleLog(i, BLOG_ERROR, "wrong type");
  172. goto fail1;
  173. }
  174. // check number of regex/replace
  175. if (NCDVal_ListCount(regex_arg) != NCDVal_ListCount(replace_arg)) {
  176. ModuleLog(i, BLOG_ERROR, "number of regex's is not the same as number of replacements");
  177. goto fail1;
  178. }
  179. size_t num_regex = NCDVal_ListCount(regex_arg);
  180. // allocate array for compiled regex's
  181. regex_t *regs = BAllocArray(num_regex, sizeof(regs[0]));
  182. if (!regs) {
  183. ModuleLog(i, BLOG_ERROR, "BAllocArray failed");
  184. goto fail1;
  185. }
  186. size_t num_done_regex = 0;
  187. // compile regex's, check arguments
  188. while (num_done_regex < num_regex) {
  189. NCDValRef regex = NCDVal_ListGet(regex_arg, num_done_regex);
  190. NCDValRef replace = NCDVal_ListGet(replace_arg, num_done_regex);
  191. if (!NCDVal_IsStringNoNulls(regex) || !NCDVal_IsString(replace)) {
  192. ModuleLog(i, BLOG_ERROR, "wrong regex/replace type for pair %zu", num_done_regex);
  193. goto fail2;
  194. }
  195. // null terminate regex
  196. NCDValNullTermString regex_nts;
  197. if (!NCDVal_StringNullTerminate(regex, &regex_nts)) {
  198. ModuleLog(i, BLOG_ERROR, "NCDVal_StringNullTerminate failed");
  199. goto fail2;
  200. }
  201. int res = regcomp(&regs[num_done_regex], regex_nts.data, REG_EXTENDED);
  202. NCDValNullTermString_Free(&regex_nts);
  203. if (res != 0) {
  204. ModuleLog(i, BLOG_ERROR, "regcomp failed for pair %zu (error=%d)", num_done_regex, res);
  205. goto fail2;
  206. }
  207. num_done_regex++;
  208. }
  209. // init output string
  210. ExpString out;
  211. if (!ExpString_Init(&out)) {
  212. ModuleLog(i, BLOG_ERROR, "ExpString_Init failed");
  213. goto fail2;
  214. }
  215. // input state
  216. const char *in = NCDVal_StringData(input_arg);
  217. size_t in_pos = 0;
  218. size_t in_len = NCDVal_StringLength(input_arg);
  219. // process input
  220. while (in_pos < in_len) {
  221. // find first match
  222. int have_match = 0;
  223. size_t match_regex = 0; // to remove warning
  224. regmatch_t match = {0, 0}; // to remove warning
  225. for (size_t j = 0; j < num_regex; j++) {
  226. regmatch_t this_match;
  227. this_match.rm_so = 0;
  228. this_match.rm_eo = in_len - in_pos;
  229. if (regexec(&regs[j], in + in_pos, 1, &this_match, REG_STARTEND) == 0 && (!have_match || this_match.rm_so < match.rm_so)) {
  230. have_match = 1;
  231. match_regex = j;
  232. match = this_match;
  233. }
  234. }
  235. // if no match, append remaining data and finish
  236. if (!have_match) {
  237. if (!ExpString_AppendBinary(&out, (const uint8_t *)in + in_pos, in_len - in_pos)) {
  238. ModuleLog(i, BLOG_ERROR, "ExpString_AppendBinary failed");
  239. goto fail3;
  240. }
  241. break;
  242. }
  243. // append data before match
  244. if (!ExpString_AppendBinary(&out, (const uint8_t *)in + in_pos, match.rm_so)) {
  245. ModuleLog(i, BLOG_ERROR, "ExpString_AppendBinary failed");
  246. goto fail3;
  247. }
  248. // append replacement data
  249. NCDValRef replace = NCDVal_ListGet(replace_arg, match_regex);
  250. if (!ExpString_AppendBinaryMr(&out, NCDVal_StringMemRef(replace))) {
  251. ModuleLog(i, BLOG_ERROR, "ExpString_AppendBinaryMr failed");
  252. goto fail3;
  253. }
  254. in_pos += match.rm_eo;
  255. }
  256. // set output
  257. o->output = ExpString_GetMr(&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_DeadError(i);
  276. }
  277. static void replace_func_die (void *vo)
  278. {
  279. struct replace_instance *o = vo;
  280. // free output
  281. BFree((char *)o->output.ptr);
  282. NCDModuleInst_Backend_Dead(o->i);
  283. }
  284. static int replace_func_getvar (void *vo, const char *name, NCDValMem *mem, NCDValRef *out)
  285. {
  286. struct replace_instance *o = vo;
  287. if (!strcmp(name, "")) {
  288. *out = NCDVal_NewStringBinMr(mem, o->output);
  289. return 1;
  290. }
  291. return 0;
  292. }
  293. static struct NCDModule modules[] = {
  294. {
  295. .type = "regex_match",
  296. .func_new2 = func_new,
  297. .func_getvar = func_getvar,
  298. .alloc_size = sizeof(struct instance)
  299. }, {
  300. .type = "regex_replace",
  301. .func_new2 = replace_func_new,
  302. .func_die = replace_func_die,
  303. .func_getvar = replace_func_getvar,
  304. .alloc_size = sizeof(struct replace_instance)
  305. }, {
  306. .type = NULL
  307. }
  308. };
  309. const struct NCDModuleGroup ncdmodule_regex_match = {
  310. .modules = modules
  311. };