log2journal-pattern.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "log2journal.h"
  3. void search_pattern_cleanup(SEARCH_PATTERN *sp) {
  4. if(sp->pattern) {
  5. freez((void *)sp->pattern);
  6. sp->pattern = NULL;
  7. }
  8. if(sp->re) {
  9. pcre2_code_free(sp->re);
  10. sp->re = NULL;
  11. }
  12. if(sp->match_data) {
  13. pcre2_match_data_free(sp->match_data);
  14. sp->match_data = NULL;
  15. }
  16. txt_cleanup(&sp->error);
  17. }
  18. static void pcre2_error_message(SEARCH_PATTERN *sp, int rc, int pos) {
  19. char msg[1024];
  20. pcre2_get_error_in_buffer(msg, sizeof(msg), rc, pos);
  21. txt_replace(&sp->error, msg, strlen(msg));
  22. }
  23. static inline bool compile_pcre2(SEARCH_PATTERN *sp) {
  24. int error_number;
  25. PCRE2_SIZE error_offset;
  26. PCRE2_SPTR pattern_ptr = (PCRE2_SPTR)sp->pattern;
  27. sp->re = pcre2_compile(pattern_ptr, PCRE2_ZERO_TERMINATED, 0, &error_number, &error_offset, NULL);
  28. if (!sp->re) {
  29. pcre2_error_message(sp, error_number, (int) error_offset);
  30. return false;
  31. }
  32. return true;
  33. }
  34. bool search_pattern_set(SEARCH_PATTERN *sp, const char *search_pattern, size_t search_pattern_len) {
  35. search_pattern_cleanup(sp);
  36. sp->pattern = strndupz(search_pattern, search_pattern_len);
  37. if (!compile_pcre2(sp))
  38. return false;
  39. sp->match_data = pcre2_match_data_create_from_pattern(sp->re, NULL);
  40. return true;
  41. }