regex_match.c 12 KB

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