#include "sab.h"
#include "../../util/util.h"
#include "../../util/pblock.h"
int rq_match(pblock *pb,
const pb_key *param, Request *rq,
const char *match,
const char *notmatch,
int *error) {
if(error) {
*error =
0;
}
if(!match && !notmatch) {
return 1;
}
char *str = pblock_findkeyval(param, rq->reqpb);
if(!str) {
str =
"";
}
int ret =
0;
if(match) {
regex_t regex;
if(regcomp(®ex, match,
REG_EXTENDED)) {
log_ereport(
LOG_MISCONFIG,
"sab: cannot compile regex pattern %s", match);
if(error) {
*error =
1;
}
return 0;
}
regmatch_t rm;
if(regexec(®ex, str,
1, &rm,
0) ==
0) {
ret =
1;
}
regfree(®ex);
}
else {
ret =
1;
}
if(notmatch) {
regex_t regex;
if(regcomp(®ex, notmatch,
REG_EXTENDED)) {
log_ereport(
LOG_MISCONFIG,
"sab: cannot compile regex pattern %s", match);
if(error) {
*error =
1;
}
return 0;
}
regmatch_t rm;
if(regexec(®ex, str,
1, &rm,
0) ==
0) {
ret =
0;
}
regfree(®ex);
}
return ret;
}
int sab_url_match(pblock *pb, Request *rq,
int *error) {
char *match = pblock_findval(
"match", pb);
char *notmatch = pblock_findval(
"notmatch", pb);
return rq_match(pb, pb_key_uri, rq, match, notmatch, error);
}
int sab_query_match(pblock *pb, Request *rq,
int *error) {
char *match = pblock_findval(
"query_match", pb);
char *notmatch = pblock_findval(
"query_notmatch", pb);
return rq_match(pb, pb_key_query, rq, match, notmatch, error);
}
int sab_has_cookie(pblock *pb, Session *sn, Request *rq) {
int error;
int match = sab_url_match(pb, rq, &error);
if(!match) {
return error ?
REQ_ABORTED :
REQ_NOACTION;
}
match = sab_query_match(pb, rq, &error);
if(!match) {
return error ?
REQ_ABORTED :
REQ_NOACTION;
}
char *cookie_name = pblock_findval(
"cookie", pb);
char *cookie_value = pblock_findval(
"value", pb);
if(!cookie_name) {
log_ereport(
LOG_MISCONFIG,
"sab-has-cookie: no cookie specified");
return REQ_ABORTED;
}
WSBool has_cookie =
FALSE;
char *cookie = pblock_findkeyval(pb_key_cookie, rq->headers);
if(cookie) {
char *value = util_cookie_find(cookie, cookie_name);
if(value) {
if(cookie_value) {
has_cookie = !strcmp(cookie_value, value);
}
else {
has_cookie =
TRUE;
}
}
}
if(!has_cookie) {
pblock_nvinsert(
"is-bot",
"1", rq->vars);
}
return REQ_NOACTION;
}