regex_match.c 12 KB

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