summaryrefslogtreecommitdiff
path: root/modules/extra/regex_posix.cpp
blob: cef4486f99bfd19902eb7a5c52f54c77ced0dbaa (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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
 *
 * (C) 2012-2024 Anope Team
 * Contact us at team@anope.org
 *
 * Please read COPYING and README for further details.
 */

#include "module.h"
#include <sys/types.h>
#include <regex.h>

class POSIXRegex final
	: public Regex
{
	regex_t regbuf;

public:
	POSIXRegex(const Anope::string &expr) : Regex(expr)
	{
		int err = regcomp(&this->regbuf, expr.c_str(), REG_EXTENDED | REG_NOSUB | REG_ICASE);
		if (err)
		{
			char buf[BUFSIZE];
			regerror(err, &this->regbuf, buf, sizeof(buf));
			regfree(&this->regbuf);
			throw RegexException("Error in regex " + expr + ": " + buf);
		}
	}

	~POSIXRegex()
	{
		regfree(&this->regbuf);
	}

	bool Matches(const Anope::string &str)
	{
		return regexec(&this->regbuf, str.c_str(), 0, NULL, 0) == 0;
	}
};

class POSIXRegexProvider final
	: public RegexProvider
{
public:
	POSIXRegexProvider(Module *creator) : RegexProvider(creator, "regex/posix") { }

	Regex *Compile(const Anope::string &expression) override
	{
		return new POSIXRegex(expression);
	}
};

class ModuleRegexPOSIX final
	: public Module
{
	POSIXRegexProvider posix_regex_provider;

public:
	ModuleRegexPOSIX(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, EXTRA | VENDOR),
		posix_regex_provider(this)
	{
		this->SetPermanent(true);
	}

	~ModuleRegexPOSIX()
	{
		for (auto *xlm : XLineManager::XLineManagers)
		{
			for (auto *x : xlm->GetList())
			{
				if (x->regex && dynamic_cast<POSIXRegex *>(x->regex))
				{
					delete x->regex;
					x->regex = NULL;
				}
			}
		}
	}
};

MODULE_INIT(ModuleRegexPOSIX)