summaryrefslogtreecommitdiffstats
path: root/src/collectors/log2journal/log2journal-rewrite.c
blob: 112391bf035191e74f500d8c44653236f71cf040 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// SPDX-License-Identifier: GPL-3.0-or-later

#include "log2journal.h"

void rewrite_cleanup(REWRITE *rw) {
    hashed_key_cleanup(&rw->key);

    if(rw->flags & RW_MATCH_PCRE2)
        search_pattern_cleanup(&rw->match_pcre2);
    else if(rw->flags & RW_MATCH_NON_EMPTY)
        replace_pattern_cleanup(&rw->match_non_empty);

    replace_pattern_cleanup(&rw->value);
    rw->flags = RW_NONE;
}

bool log_job_rewrite_add(LOG_JOB *jb, const char *key, RW_FLAGS flags, const char *search_pattern, const char *replace_pattern) {
    if(jb->rewrites.used >= MAX_REWRITES) {
        log2stderr("Error: too many rewrites. You can add up to %d rewrite rules.", MAX_REWRITES);
        return false;
    }

    if((flags & (RW_MATCH_PCRE2|RW_MATCH_NON_EMPTY)) && (!search_pattern || !*search_pattern)) {
        log2stderr("Error: rewrite for key '%s' does not specify a search pattern.", key);
        return false;
    }

    REWRITE *rw = &jb->rewrites.array[jb->rewrites.used++];
    rw->flags = flags;

    hashed_key_set(&rw->key, key);

    if((flags & RW_MATCH_PCRE2) && !search_pattern_set(&rw->match_pcre2, search_pattern, strlen(search_pattern))) {
        rewrite_cleanup(rw);
        jb->rewrites.used--;
        return false;
    }
    else if((flags & RW_MATCH_NON_EMPTY) && !replace_pattern_set(&rw->match_non_empty, search_pattern)) {
        rewrite_cleanup(rw);
        jb->rewrites.used--;
        return false;
    }

    if(replace_pattern && *replace_pattern && !replace_pattern_set(&rw->value, replace_pattern)) {
        rewrite_cleanup(rw);
        jb->rewrites.used--;
        return false;
    }

    return true;
}