initial import to git

This commit is contained in:
z3APA3A committed 2014-04-08 13:03:21 +04:00
commit a060376f1e
217 files changed
+64253

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
D/WindowsAuthentication////
D/TrafficPlugin////
D/PCREPlugin////
D/FilePlugin////
D/TransparentPlugin////
D/utf8tocp1251////
D/SSLPlugin////
+1
View File
@@ -0,0 +1 @@
3proxy-0.5a/src/plugins
+1
View File
@@ -0,0 +1 @@
/cygdrive/m/MEDIA/H/CVS
+4
View File
@@ -0,0 +1,4 @@
/Makefile.inc/1.1/Sun Sep 20 17:13:29 2009//
/FilePlugin.h/1.4/Fri Oct 9 11:36:00 2009//
/FilePlugin.c/1.8/Wed Apr 11 23:01:22 2012//
D
+1
View File
@@ -0,0 +1 @@
3proxy-0.5a/src/plugins/FilePlugin
+1
View File
@@ -0,0 +1 @@
/cygdrive/m/MEDIA/H/CVS
+895
View File
@@ -0,0 +1,895 @@
/*
3APA3A simpliest proxy server
(c) 2007-2008 by ZARAZA <3APA3A@security.nnov.ru>
please read License Agreement
$Id: FilePlugin.c,v 1.8 2012-04-11 23:01:22 vlad Exp $
*/
#include "../../structures.h"
#include "FilePlugin.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/timeb.h>
#include <fcntl.h>
#include <time.h>
#ifdef _WIN32
#ifndef _WINCE
#include <io.h>
#else
#include <sys/unistd.h>
#endif
#else
#include <unistd.h>
#ifndef O_BINARY
#define O_BINARY (0)
#endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifndef _WIN32
#define WINAPI
#define fp_size_t size_t
#else
#define fp_size_t int
#endif
static struct pluginlink * pl;
static pthread_mutex_t file_mutex;
unsigned long preview = 0;
char path[256];
static int counter = 0;
static int timeo = 0;
static char * fp_stringtable[] = {
/* 0 */ "HTTP/1.0 503 Service Unavailable\r\n"
"Proxy-Connection: close\r\n"
"Content-type: text/html; charset=us-ascii\r\n"
"\r\n"
"<html><head><title>503 Service Unavailable</title></head>\r\n"
"<body><h2>503 Service Unavailable</h2><h3>HTTP policy violation: you have no permission to perform this action. Please conatct helpdesk or Administrator.</h3></body></html>\r\n",
/* 1 */ "421 SMTP policy violation: you have no permission to perform this action. Please conatct helpdesk or Administrator.\r\n",
/* 2 */ "421 FTP policy violation: you have no permission to perform this action. Please conatct helpdesk or Administrator.\r\n",
NULL
};
enum states {
STATE_INITIAL = 0,
GOT_HTTP_REQUEST,
GOT_HTTP_CLI_HDR,
GOT_HTTP_SRV_HDR,
GOT_HTTP_CLI_HDR2,
GOT_HTTP_SRV_HDR2,
GOT_HTTP_CLIDATA,
GOT_HTTP_SRVDATA,
GOT_SMTP_REQ,
GOT_SMTP_DATA,
GOT_FTP_REQ,
GOT_FTP_CLIDATA,
GOT_FTP_SRVDATA,
FLUSH_DATA
};
struct fp_callback {
struct fp_callback *next;
FP_CALLBACK callback;
void * data;
int what;
int preview_size;
int max_size;
};
struct fp_stream {
struct fp_stream *next;
char * buf;
int state;
int what;
int needsrvconnect;
int preview_size;
long bufsize;
unsigned long clihdrwritten, clientwritten, clientsent, srvhdrwritten, serverwritten, serversent;
struct fp_callback *callbacks;
struct fp_filedata fpd;
} *fp_streams = NULL;
struct sockfuncs sso;
static void genpaths(struct fp_stream *fps){
if(fps->what & (FP_CLIDATA|FP_CLIHEADER)){
if(fps->fpd.path_cli) free(fps->fpd.path_cli);
fps->fpd.path_cli = malloc(strlen(path) + 10);
sprintf(fps->fpd.path_cli, path, counter++);
}
if(fps->what & (FP_SRVDATA|FP_SRVHEADER)){
if(fps->fpd.path_srv) free(fps->fpd.path_srv);
fps->fpd.path_srv = malloc(strlen(path) + 10);
sprintf(fps->fpd.path_srv, path, counter++);
}
}
static
#ifdef _WIN32
HANDLE
#else
int
#endif
initclientfile(struct fp_stream *fps){
fps->clientwritten = fps->clientsent = 0;
#ifdef _WIN32
if(fps->fpd.h_cli != INVALID_HANDLE_VALUE){
CloseHandle(fps->fpd.h_cli);
}
fps->fpd.h_cli = CreateFile(fps->fpd.path_cli, GENERIC_READ | GENERIC_WRITE, (fps->what & FP_SHAREFILE)? FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE:0, NULL, CREATE_ALWAYS, (fps->what & (FP_KEEPFILE|FP_SHAREFILE))? FILE_ATTRIBUTE_TEMPORARY : FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, NULL);
return fps->fpd.h_cli;
#else
if(fps->fpd.fd_cli != -1) close(fps->fpd.fd_cli);
fps->fpd.fd_cli = open(fps->fpd.path_cli, O_BINARY|O_RDWR|O_CREAT|O_TRUNC, 0600);
return fps->fpd.fd_cli;
#endif
}
static
#ifdef _WIN32
HANDLE
#else
int
#endif
initserverfile(struct fp_stream *fps){
fps->serverwritten = fps->serversent = 0;
#ifdef _WIN32
if(fps->fpd.h_srv != INVALID_HANDLE_VALUE){
CloseHandle(fps->fpd.h_srv);
}
fps->fpd.h_srv = CreateFile(fps->fpd.path_srv, GENERIC_READ | GENERIC_WRITE, (fps->what & FP_SHAREFILE)? FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE:0, NULL, CREATE_ALWAYS, (fps->what & (FP_KEEPFILE|FP_SHAREFILE))? FILE_ATTRIBUTE_TEMPORARY : FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, NULL);
return fps->fpd.h_srv;
#else
if(fps->fpd.fd_srv != -1) close(fps->fpd.fd_srv);
fps->fpd.fd_srv = open(fps->fpd.path_srv, O_BINARY|O_RDWR|O_CREAT|O_TRUNC, 0600);
return fps->fpd.fd_srv;
#endif
}
static void closefiles(struct fp_stream *fps){
#ifdef _WIN32
if(fps->fpd.h_cli != INVALID_HANDLE_VALUE) {
CloseHandle(fps->fpd.h_cli);
fps->fpd.h_cli = INVALID_HANDLE_VALUE;
if((fps->what & FP_SHAREFILE) && !(fps->what & FP_KEEPFILE)) DeleteFile(fps->fpd.path_cli);
}
if(fps->fpd.h_srv != INVALID_HANDLE_VALUE) {
CloseHandle(fps->fpd.h_srv);
fps->fpd.h_srv = INVALID_HANDLE_VALUE;
if((fps->what & FP_SHAREFILE) && !(fps->what & FP_KEEPFILE)) DeleteFile(fps->fpd.path_cli);
}
#else
if(fps->fpd.fd_cli != -1) {
close(fps->fpd.fd_cli);
fps->fpd.fd_cli = -1;
if(!(fps->what & FP_KEEPFILE)) unlink(fps->fpd.path_cli);
}
if(fps->fpd.fd_srv != -1) {
close(fps->fpd.fd_srv);
fps->fpd.fd_srv = -1;
if(!(fps->what & FP_KEEPFILE)) unlink(fps->fpd.path_srv);
}
#endif
if(fps->fpd.path_cli) {
free(fps->fpd.path_cli);
fps->fpd.path_cli = NULL;
}
if(fps->fpd.path_srv) {
free(fps->fpd.path_srv);
fps->fpd.path_srv = NULL;
}
fps->clihdrwritten = fps->clientwritten = fps->clientsent = fps->srvhdrwritten = fps->serverwritten = fps->serversent = 0;
}
static int searchsocket(SOCKET s, struct fp_stream **pfps){
struct fp_stream *fps = NULL;
int ret = 0;
pthread_mutex_lock(&file_mutex);
for(fps = fp_streams; fps; fps = fps->next){
if(fps->fpd.cp->clisock == s) {
ret = 1;
break;
}
if(fps->fpd.cp->remsock == s) {
ret = 2;
break;
}
if(fps->fpd.cp->ctrlsock == s) {
ret = 3;
break;
}
}
pthread_mutex_unlock(&file_mutex);
*pfps = fps;
return ret;
}
static void freecallback(struct fp_stream * fps, struct fp_callback * fpc){
if(fpc->next) freecallback(fps, fpc->next);
if(fpc->what & FP_CALLONREMOVE) (*fpc->callback)(FP_CALLONREMOVE, fpc->data, &fps->fpd, NULL, 0);
free(fpc);
}
static void removefps(struct fp_stream * fps){
if(!fp_streams) return;
pthread_mutex_lock(&file_mutex);
if(fp_streams == fps)fp_streams = fps->next;
else {
struct fp_stream *fps2;
for(fps2 = fp_streams; fps2->next; fps2 = fps2->next){
if(fps2->next == fps){
fps2->next = fps->next;
break;
}
}
}
pthread_mutex_unlock(&file_mutex);
if(fps->callbacks){
freecallback(fps, fps->callbacks);
fps->callbacks = 0;
}
closefiles(fps);
if(fps->buf) {
free(fps->buf);
fps->buf = NULL;
}
fps->state = 0;
}
static int WINAPI fp_connect(SOCKET s, const struct sockaddr *name, fp_size_t namelen){
return sso._connect(s, name, namelen);
}
void processcallbacks(struct fp_stream *fps, int what, char *msg, int size){
struct fp_callback *cb;
int state;
state = fps->state;
if(fps->what & what) {
fps->what = 0;
for(cb = fps->callbacks; cb; cb=cb->next){
if(cb->what & what){
cb->what = (*cb->callback)(what, cb->data, &(fps->fpd), msg, size);
}
fps->what |= cb->what;
}
}
if(fps->what & FP_REJECT){
switch(state){
/*
Fixme: handle different states
*/
case GOT_SMTP_REQ:
case GOT_SMTP_DATA:
fps->state = FLUSH_DATA;
pl->socksend(fps->fpd.cp->clisock, fp_stringtable[1], (int)strlen(fp_stringtable[1]), pl->conf->timeouts[STRING_S]);
fps->state = state;
break;
case GOT_HTTP_REQUEST:
case GOT_HTTP_CLI_HDR:
case GOT_HTTP_SRV_HDR:
case GOT_HTTP_CLI_HDR2:
case GOT_HTTP_SRV_HDR2:
case GOT_HTTP_CLIDATA:
case GOT_HTTP_SRVDATA:
if(!fps->serversent){
fps->state = FLUSH_DATA;
pl->socksend(fps->fpd.cp->clisock, fp_stringtable[0], (int)strlen(fp_stringtable[0]), pl->conf->timeouts[STRING_S]);
fps->state = state;
}
break;
case GOT_FTP_CLIDATA:
case GOT_FTP_REQ:
case GOT_FTP_SRVDATA:
fps->state = FLUSH_DATA;
pl->socksend(fps->fpd.cp->ctrlsock, fp_stringtable[1], (int)strlen(fp_stringtable[1]), pl->conf->timeouts[STRING_S]);
fps->state = state;
break;
default:
break;
}
if(fps->fpd.cp->remsock != INVALID_SOCKET)sso._closesocket(fps->fpd.cp->remsock);
fps->fpd.cp->remsock = INVALID_SOCKET;
if(fps->fpd.cp->clisock != INVALID_SOCKET)sso._closesocket(fps->fpd.cp->clisock);
fps->fpd.cp->clisock = INVALID_SOCKET;
}
}
static int copyfdtosock(struct fp_stream * fps, DIRECTION which, long len){
int res;
long toread;
int state;
#ifdef _WIN32
HANDLE h;
#else
int fd;
#endif
SOCKET sock;
long offset;
int sendchunk = 0;
state = fps->state;
fps->state = FLUSH_DATA;
if(!fps->buf){
fps->buf = malloc(2048);
if(!fps->buf) return -2;
fps->bufsize = 2048;
}
if(which == SERVER){
offset = fps->clientsent;
fps->clientsent += len;
#ifdef _WIN32
h = fps->fpd.h_cli;
#else
fd = fps->fpd.fd_cli;
#endif
sock = fps->fpd.cp->remsock;
}
else {
if(fps->fpd.cp->chunked){
if(fps->serversent < fps->srvhdrwritten && (fps->serversent + len) > fps->srvhdrwritten){
len -= fps->srvhdrwritten - fps->serversent;
if ((res = copyfdtosock(fps, which, fps->srvhdrwritten - fps->serversent))) return res;
}
if(fps->serversent >= fps->srvhdrwritten){
sprintf(fps->buf, "%lx\r\n", len);
sendchunk = (int)strlen(fps->buf);
if(pl->socksend(fps->fpd.cp->clisock, fps->buf, sendchunk, pl->conf->timeouts[STRING_S]) != sendchunk){
return -4;
}
}
}
offset = fps->serversent;
fps->serversent += len;
#ifdef _WIN32
h = fps->fpd.h_srv;
#else
fd = fps->fpd.fd_srv;
#endif
sock = fps->fpd.cp->clisock;
}
#ifdef _WIN32
if(SetFilePointer(h,offset,0,FILE_BEGIN)!=offset){
return -1;
}
#else
if(lseek(fd, offset, SEEK_SET) < 0) {
return -1;
}
#endif
while(len > 0){
/*
Fixme: prevent client/server timeouts
*/
toread = (len > fps->bufsize)? fps->bufsize:len;
#ifdef _WIN32
if(!ReadFile(h, fps->buf, (DWORD)toread,(DWORD *)&res,NULL)) {
#else
if((res = read(fd, fps->buf, toread)) <= 0) {
#endif
return -3;
}
if(pl->socksend(sock, fps->buf, res, pl->conf->timeouts[STRING_S]) != res) {
return -4;
}
len -= res;
}
if(sendchunk){
if(pl->socksend(sock, "\r\n", 2, pl->conf->timeouts[STRING_S]) != 2)
return -4;
}
fps->state = state;
return 0;
}
static int WINAPI fp_poll(struct pollfd *fds, unsigned int nfds, int timeout){
struct fp_stream *fps = NULL;
int res;
unsigned i;
int to;
for(i = 0; i<nfds; i++){
res = searchsocket(fds[i].fd, &fps);
if(res == 2 && fps->state == GOT_SMTP_DATA){
if(fds[i].events & POLLOUT){
fds[i].revents = POLLOUT;
return 1;
}
}
else if(res == 2 && (((fps->what & FP_CLIHEADER) && (fps->state == GOT_HTTP_REQUEST || fps->state == GOT_HTTP_CLI_HDR2)) || ((fps->what & FP_CLIDATA) && fps->state == GOT_HTTP_CLIDATA))){
if(fds[i].events & POLLIN){
processcallbacks(fps, (fps->state == GOT_HTTP_CLIDATA)?FP_CLIDATA:FP_CALLAFTERCLIHEADERS, NULL, 0);
if(fps->clihdrwritten + fps->clientwritten > fps->clientsent) {
if(copyfdtosock(fps, SERVER, (fps->clihdrwritten + fps->clientwritten) - fps->clientsent))
return -2;
}
if(fps->state) {
if(fps->what & FP_SRVHEADER) initserverfile(fps);
fps->state = GOT_HTTP_SRV_HDR;
}
}
else if(fds[i].events & POLLOUT){
fds[i].revents = POLLOUT;
return 1;
}
}
else if(res == 1 && (fps->state == GOT_HTTP_SRVDATA || fps->state == GOT_HTTP_SRV_HDR || fps->state == GOT_HTTP_SRV_HDR2)&& (fds[i].events & POLLIN)){
processcallbacks(fps, (fps->state == GOT_HTTP_SRVDATA)? FP_SRVDATA:FP_CALLAFTERSRVHEADERS, NULL, 0);
if(fps->srvhdrwritten + fps->serverwritten > fps->serversent) {
if(copyfdtosock(fps, CLIENT, (fps->srvhdrwritten + fps->serverwritten) - fps->serversent))
return -2;
}
closefiles(fps);
fps->state = 0;
}
}
return sso._poll(fds, nfds, timeout);
}
static int WINAPI fp_send(SOCKET s, const char *msg, fp_size_t len, int flags){
struct fp_stream *fps = NULL;
int res;
res = searchsocket(s, &fps);
if(res == 2){
if(fps->state == GOT_SMTP_DATA) {
if(fps->clihdrwritten + fps->clientwritten > fps->clientsent) {
processcallbacks(fps, FP_CLIDATA, NULL, 0);
if(copyfdtosock(fps, SERVER, (fps->clihdrwritten + fps->clientwritten) - fps->clientsent)) {
return -1;
}
fps->state = 0;
}
closefiles(fps);
fps->state = 0;
return sso._send(s, msg, len, flags);
}
if((((fps->what & FP_CLIHEADER) && (fps->state == GOT_HTTP_REQUEST || fps->state == GOT_HTTP_CLI_HDR2)) || ((fps->what & FP_CLIDATA) && fps->state == GOT_HTTP_CLIDATA))){
#ifdef _WIN32
if(SetFilePointer(fps->fpd.h_cli, fps->clientwritten + fps->clihdrwritten, 0, FILE_BEGIN) != (fps->clientwritten + fps->clihdrwritten)){
return -1;
}
if(!WriteFile(fps->fpd.h_cli, msg, (DWORD)len,(DWORD *)&res,NULL) || res != len){
return -1;
}
#else
if(lseek(fps->fpd.fd_cli, fps->clientwritten + fps->clihdrwritten, SEEK_SET) < 0) {
return -1;
}
if((res = write(fps->fpd.fd_cli, msg, len) != len)) return -1;
#endif
if(fps->state == GOT_HTTP_CLIDATA)fps->clientwritten += res;
else fps->clihdrwritten += res;
return res;
}
}
if(res == 1){
if(((fps->what & FP_SRVDATA) && (fps->state == GOT_HTTP_SRVDATA || fps->state == GOT_HTTP_SRV_HDR) && fps->fpd.cp->chunked && len < 16 )){
int hasnonzero = 0, i;
for(i=0; i < len; i++){
char c = msg[i];
if(c == '\r' || c == '\n') continue;
if((c<'0'|| c>'9') && (c<'A' || c>'F') && (c<'a' || c>'f')) {
return sso._send(s, msg, len, flags);
}
if(c != '0') hasnonzero = 1;
}
if(i>2 && !hasnonzero){
if(fps->srvhdrwritten + fps->serverwritten > fps->serversent) {
processcallbacks(fps, FP_SRVDATA, NULL, 0);
if(copyfdtosock(fps, CLIENT, (fps->srvhdrwritten + fps->serverwritten) - fps->serversent)) {
return -1;
}
fps->state = 0;
}
closefiles(fps);
fps->state = 0;
return sso._send(s, msg, len, flags);
}
return len;
}
if(((fps->what & FP_SRVHEADER) && (fps->state == GOT_HTTP_SRV_HDR || fps->state == GOT_HTTP_SRV_HDR2))){
#ifdef _WIN32
if(SetFilePointer(fps->fpd.h_srv, fps->serverwritten + fps->srvhdrwritten, 0, FILE_BEGIN) != (fps->serverwritten + fps->srvhdrwritten)){
return -1;
}
if(!WriteFile(fps->fpd.h_srv, msg, (DWORD)len,(DWORD *)&res,NULL) || res !=len){
return -1;
}
#else
if(lseek(fps->fpd.fd_srv, fps->serverwritten + fps->srvhdrwritten, SEEK_SET) < 0) {
return -1;
}
if((res = write(fps->fpd.fd_srv, msg, len) != len)) return -1;
#endif
fps->srvhdrwritten += res;
return res;
}
}
return sso._send(s, msg, len, flags);
}
static int WINAPI fp_sendto(SOCKET s, const void *msg, int len, int flags, const struct sockaddr *to, fp_size_t tolen){
struct fp_stream *fps = NULL;
int res;
res = searchsocket(s, &fps);
if(res == 2) {
switch(fps->state){
case GOT_SMTP_REQ:
if(!(fps->what & FP_CLIDATA)) break;
fps->state = GOT_SMTP_DATA;
initclientfile(fps);
case GOT_FTP_REQ:
if(fps->state == GOT_FTP_REQ){
if(!(fps->what & FP_CLIDATA)) break;
fps->state = GOT_FTP_CLIDATA;
initclientfile(fps);
}
case GOT_HTTP_CLI_HDR2:
if(fps->state == GOT_HTTP_CLI_HDR2){
processcallbacks(fps, FP_CALLAFTERCLIHEADERS, NULL, 0);
if ((fps->what & FP_REJECT)) return -1;
if((fps->what & FP_CLIDATA) && !(fps->what & FP_CLIHEADER)) initclientfile(fps);
else if(!(fps->what & FP_CLIDATA) && (fps->what & FP_CLIHEADER)){
if(fps->clihdrwritten + fps->clientwritten > fps->clientsent) {
if(copyfdtosock(fps, SERVER, (fps->clihdrwritten + fps->clientwritten) - fps->clientsent))
return -2;
}
}
fps->state = GOT_HTTP_CLIDATA;
}
case GOT_HTTP_REQUEST:
if(fps->state == GOT_HTTP_REQUEST && !(fps->what & FP_CLIHEADER)) break;
case GOT_SMTP_DATA:
case GOT_FTP_CLIDATA:
case GOT_FTP_SRVDATA:
case GOT_HTTP_CLIDATA:
if((!fps->what & FP_CLIDATA)) break;
#ifdef _WIN32
if(SetFilePointer(fps->fpd.h_cli, fps->clientwritten + fps->clihdrwritten, 0, FILE_BEGIN) != (fps->clientwritten + fps->clihdrwritten)){
return -1;
}
if(!WriteFile(fps->fpd.h_cli, msg, (DWORD)len,(DWORD *)&res,NULL) || res != len) {
return -1;
}
#else
if(lseek(fps->fpd.fd_cli, fps->clientwritten + fps->clihdrwritten, SEEK_SET) < 0) {
return -1;
}
if((res = write(fps->fpd.fd_cli, msg, len) != len)) return -1;
#endif
if(fps->state == GOT_HTTP_REQUEST)fps->clihdrwritten += res;
else fps->clientwritten += res;
if(fps->preview_size && ((fps->clihdrwritten + fps->clientwritten) > (fps->clientsent + fps->preview_size))){
if(!fps->clientsent){
processcallbacks(fps, FP_PREVIEWCLI, NULL, 0);
if ((fps->what & FP_REJECT)) return -1;
}
if(copyfdtosock(fps, SERVER, (fps->clihdrwritten + fps->clientwritten) - (fps->clientsent + fps->preview_size)))
return -1;
}
return res;
}
}
else if(res == 1){
switch(fps->state){
case GOT_HTTP_SRV_HDR2:
processcallbacks(fps, FP_CALLAFTERSRVHEADERS, NULL, 0);
if ((fps->what & FP_REJECT)) return REJECT;
if((fps->what & FP_SRVDATA) && !(fps->what & FP_SRVHEADER)) initserverfile(fps);
else if(!(fps->what & FP_SRVDATA) && (fps->what & FP_SRVHEADER)){
if(fps->srvhdrwritten + fps->serverwritten > fps->serversent) {
if(copyfdtosock(fps, CLIENT, (fps->srvhdrwritten + fps->serverwritten) - fps->serversent))
return -2;
}
}
fps->state = GOT_HTTP_SRVDATA;
case GOT_FTP_REQ:
if(fps->state == GOT_FTP_REQ){
if(!(fps->what & FP_SRVDATA)) break;
fps->state = GOT_FTP_SRVDATA;
initserverfile(fps);
}
case GOT_HTTP_SRV_HDR:
if(fps->state == GOT_HTTP_SRV_HDR && !(fps->what & FP_SRVHEADER)) break;
case GOT_HTTP_SRVDATA:
case GOT_FTP_SRVDATA:
case GOT_FTP_CLIDATA:
if(!(fps->what & FP_SRVDATA)) break;
#ifdef _WIN32
if(SetFilePointer(fps->fpd.h_srv, fps->serverwritten + fps->srvhdrwritten, 0, FILE_BEGIN) != (fps->serverwritten + fps->srvhdrwritten)){
return -1;
}
if(!WriteFile(fps->fpd.h_srv, msg, (DWORD)len,(DWORD *)&res,NULL) || res != len){
return -1;
}
#else
if(lseek(fps->fpd.fd_srv, fps->serverwritten + fps->srvhdrwritten, SEEK_SET) < 0) {
return -1;
}
if((res = write(fps->fpd.fd_srv, msg, len) != len)) return -1;
#endif
if(fps->state == GOT_HTTP_SRV_HDR)fps->srvhdrwritten += res;
else fps->serverwritten += res;
if(fps->preview_size && ((fps->srvhdrwritten + fps->serverwritten) > (fps->serversent + fps->preview_size))){
if(!fps->serversent){
processcallbacks(fps, FP_PREVIEWSRV, NULL, 0);
if ((fps->what & FP_REJECT)) return -1;
}
if(copyfdtosock(fps, CLIENT, (fps->srvhdrwritten + fps->serverwritten) - (fps->serversent + fps->preview_size)))
return -1;
}
return res;
}
}
return sso._sendto(s, msg, len, flags, to, tolen);
}
static int WINAPI fp_recv(SOCKET s, void *buf, fp_size_t len, int flags){
return sso._recv(s, buf, len, flags);
}
static int WINAPI fp_recvfrom(SOCKET s, void * buf, fp_size_t len, int flags, struct sockaddr * from, fp_size_t * fromlen){
return sso._recvfrom(s, buf, len, flags, from, fromlen);
}
static int WINAPI fp_shutdown(SOCKET s, int how){
struct fp_stream *fps = NULL;
int res;
res = searchsocket(s, &fps);
if(res){
if(fps->state == GOT_HTTP_SRV_HDR || fps->state == GOT_HTTP_SRVDATA || fps->state == GOT_FTP_SRVDATA){
if(fps->srvhdrwritten + fps->serverwritten > fps->serversent) {
processcallbacks(fps, FP_SRVDATA, NULL, 0);
copyfdtosock(fps, CLIENT, (fps->srvhdrwritten + fps->serverwritten) - fps->serversent);
}
closefiles(fps);
fps->state = 0;
}
else if(fps->state == GOT_FTP_CLIDATA){
if(fps->clihdrwritten + fps->clientwritten > fps->clientsent) {
processcallbacks(fps, FP_CLIDATA, NULL, 0);
copyfdtosock(fps, SERVER, (fps->clihdrwritten + fps->clientwritten) - fps->clientsent);
}
closefiles(fps);
fps->state = 0;
}
}
return sso._shutdown(s, how);
}
static int WINAPI fp_closesocket(SOCKET s){
return sso._closesocket(s);
}
struct fp_stream * addfps(struct clientparam *cp){
struct fp_stream *fps;
for(fps = fp_streams; fps && fps->fpd.cp != cp; fps = fps->next);
if(!fps) {
fps = malloc(sizeof(struct fp_stream));
if(!fps){
return NULL;
}
memset(fps, 0, sizeof(struct fp_stream));
fps->fpd.cp = cp;
fps->next = fp_streams;
fp_streams = fps;
#ifdef _WIN32
fps->fpd.h_cli = fps->fpd.h_srv = INVALID_HANDLE_VALUE;
#else
fps->fpd.fd_cli = fps->fpd.fd_srv = -1;
#endif
}
return fps;
}
static int fp_registercallback (int what, int max_size, int preview_size, struct clientparam *cp, FP_CALLBACK cb, void *data){
struct fp_callback * fpc;
struct fp_stream *fps;
fpc = malloc(sizeof(struct fp_callback));
if(!fpc) return 0;
fpc->what = what;
fpc->preview_size = preview_size;
fpc->max_size = max_size;
fpc->data = data;
fpc->callback = cb;
pthread_mutex_lock(&file_mutex);
fps = addfps(cp);
if(fps){
fpc->next = fps->callbacks;
fps->callbacks = fpc;
fps->what |= fpc->what;
if(preview_size > fps->preview_size) fps->preview_size = preview_size;
}
else free(fpc);
pthread_mutex_unlock(&file_mutex);
return fps?1:0;
}
static void * fp_open(void * idata, struct srvparam * param){
return idata;
}
#define FC ((struct fp_stream *)fc)
static FILTER_ACTION fp_client(void *fo, struct clientparam * param, void** fc){
pthread_mutex_lock(&file_mutex);
(*fc) = (void *)addfps(param);
pthread_mutex_unlock(&file_mutex);
return CONTINUE;
}
static FILTER_ACTION fp_request(void *fc, struct clientparam * param, unsigned char ** buf_p, int * bufsize_p, int offset, int * length_p){
if(fc && (param->service == S_PROXY)){
if(FC->state) {
closefiles(FC);
FC->state = 0;
}
processcallbacks(FC, FP_CALLONREQUEST, *buf_p + offset, *length_p - offset);
if(FC->what &FP_REJECT) return REJECT;
FC->state = GOT_HTTP_REQUEST;
genpaths(FC);
if(FC->what & FP_CLIHEADER) initclientfile(FC);
}
return CONTINUE;
}
static FILTER_ACTION fp_hcli(void *fc, struct clientparam * param, unsigned char ** buf_p, int * bufsize_p, int offset, int * length_p){
if(fc && param->service == S_SMTPP) {
processcallbacks(FC, FP_CALLONREQUEST, *buf_p + offset, *length_p - offset);
if(FC->what & FP_REJECT) return REJECT;
if(!FC->state)genpaths(FC);
FC->state = GOT_SMTP_REQ;
}
if(fc && param->service == S_FTPPR) {
processcallbacks(FC, FP_CALLONREQUEST, *buf_p + offset, *length_p - offset);
if(FC->what & FP_REJECT) return REJECT;
genpaths(FC);
FC->state = GOT_FTP_REQ;
}
return CONTINUE;
}
static FILTER_ACTION fp_hsrv(void *fc, struct clientparam * param, unsigned char ** buf_p, int * bufsize_p, int offset, int * length_p){
if(fc && param->service == S_PROXY && (FC->state == GOT_HTTP_REQUEST || FC->state == GOT_HTTP_CLI_HDR || FC->state == GOT_HTTP_CLIDATA)){
if(FC->what & FP_SRVHEADER) initserverfile(FC);
FC->state = GOT_HTTP_SRV_HDR;
}
return CONTINUE;
}
static FILTER_ACTION fp_dcli(void *fc, struct clientparam * param, unsigned char ** buf_p, int * bufsize_p, int offset, int * length_p){
if(fc && FC->state == GOT_HTTP_REQUEST){
FC->state = GOT_HTTP_CLI_HDR2;
}
return CONTINUE;
}
static FILTER_ACTION fp_dsrv(void *fc, struct clientparam * param, unsigned char ** buf_p, int * bufsize_p, int offset, int * length_p){
if(fc && (FC->state == GOT_HTTP_REQUEST || FC->state == GOT_HTTP_CLI_HDR || FC->state == GOT_HTTP_CLIDATA || FC->state == GOT_HTTP_CLIDATA || FC->state == GOT_HTTP_SRV_HDR)){
FC->state = GOT_HTTP_SRV_HDR2;
}
return CONTINUE;
}
static void fp_clear(void *fc){
removefps(FC);
free(fc);
}
static void fp_close(void *fo){
}
static struct filter fp_filter = {
NULL,
"filefilter",
"filefilter",
fp_open,
fp_client,
fp_request,
fp_hcli,
fp_hsrv,
NULL,
fp_dcli,
fp_dsrv,
fp_clear,
fp_close,
};
static struct symbol fp_symbols[] = {
{fp_symbols + 1, "fp_registercallback", (void*) fp_registercallback},
{NULL, "fp_stringtable", (void*) fp_stringtable}
};
static int file_loaded=0;
#ifdef _WIN32
__declspec(dllexport)
#endif
int file_plugin (struct pluginlink * pluginlink,
int argc, char** argv){
char * dirp;
if(!file_loaded){
pthread_mutex_init(&file_mutex, NULL);
file_loaded = 1;
pl = pluginlink;
memcpy(&sso, pl->so, sizeof(struct sockfuncs));
pl->so->_poll = fp_poll;
pl->so->_send = fp_send;
pl->so->_sendto = fp_sendto;
pl->so->_recv = fp_recv;
pl->so->_recvfrom = fp_recvfrom;
pl->so->_shutdown = fp_shutdown;
pl->so->_closesocket = fp_closesocket;
fp_filter.next = pl->conf->filters;
pl->conf->filters = &fp_filter;
fp_symbols[1].next = pl->symbols.next;
pl->symbols.next = fp_symbols;
}
if(path) free(path);
dirp = (argc > 1)? argv[1] : getenv("TEMP");
if(strlen(dirp) > 200 || strchr(dirp, '%')) return (13001);
#ifdef _WIN32
sprintf(path, "%s\\%%d.tmp", dirp);
#else
sprintf(path, "%s/%%d.tmp", dirp);
#endif
if(argc > 2) preview = atoi(argv[2]);
if(!preview) preview = 32768;
return 0;
}
#ifdef __cplusplus
}
#endif
+41
View File
@@ -0,0 +1,41 @@
#ifdef __cplusplus
extern "C" {
#endif
#define FP_OK 0
#define FP_REJECT 65536
#define FP_CLIDATA 1
#define FP_SRVDATA 2
#define FP_CLIHEADER 4
#define FP_SRVHEADER 8
#define FP_KEEPFILE 16
#define FP_SHAREFILE 32
#define FP_PREVIEWCLI 64
#define FP_PREVIEWSRV 128
#define FP_CALLONREQUEST 256
#define FP_CALLAFTERCLIHEADERS 512
#define FP_CALLAFTERSRVHEADERS 1024
#define FP_CALLONREMOVE 2048
struct fp_filedata {
struct clientparam *cp;
#ifdef _WIN32
HANDLE h_cli, h_srv;
#else
int fd_cli, fd_srv;
#endif
char *path_cli;
char *path_srv;
};
typedef int (*FP_CALLBACK)(int what, void *data, struct fp_filedata *fpd, char *buf, int size);
typedef int (*FP_REGISTERCALBACK) (int what, int max_size, int preview_size, struct clientparam *cp, FP_CALLBACK cb, void *data);
#ifdef __cplusplus
}
#endif
+1
View File
@@ -0,0 +1 @@
include Makefile.var
+7
View File
@@ -0,0 +1,7 @@
all: $(BUILDDIR)FilePlugin$(DLSUFFICS)
FilePlugin$(OBJSUFFICS): FilePlugin.c
$(CC) $(DCFLAGS) $(CFLAGS) FilePlugin.c
$(BUILDDIR)FilePlugin$(DLSUFFICS): FilePlugin$(OBJSUFFICS)
$(LN) $(LNOUT)../../$(BUILDDIR)FilePlugin$(DLSUFFICS) $(LDFLAGS) $(DLFLAGS) FilePlugin$(OBJSUFFICS)
+37
View File
@@ -0,0 +1,37 @@
VERFILE = version.obj ../3proxy.RES
#$Id: Makefile.msvc,v 1.17 2010-11-11 14:44:11 v.dubrovin Exp $
#
# 3 proxy Makefile for Microsoft Visual C compiler (for both make and nmake)
#
# You can try to remove -DWITH_STD_MALLOC to CFLAGS to use optimized malloc
# libraries
#
# Add /DSAFESQL to CFLAGS if you are using poorely written/tested ODBC driver
BUILDDIR = ../bin/
CC = cl
CFLAGS = /nologo /MT /W3 /Ox /GS /EHs- /GA /GF /D "MSVC" /D "WITH_STD_MALLOC" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "_WIN32" /Fp"proxy.pch" /FD /c
COUT = /Fo
LN = link
LDFLAGS = /nologo /subsystem:console /incremental:no /machine:I386
DLFLAGS = /DLL
DLSUFFICS = .dll
LIBS = ws2_32.lib advapi32.lib odbc32.lib user32.lib kernel32.lib Gdi32.lib libeay32MT.lib ssleay32MT.lib
LIBEXT = .lib
LNOUT = /out:
EXESUFFICS = .exe
OBJSUFFICS = .obj
DEFINEOPTION = /D
COMPFILES = *.pch *.idb
REMOVECOMMAND = del 2>NUL >NUL
TYPECOMMAND = type
COMPATLIBS =
MAKEFILE = Makefile.msvc
PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin lastFripper FilePlugin
include Makefile.inc
allplugins:
for /D %%i in ($(PLUGINS)) do (copy Makefile plugins\%%i && copy Makefile.var plugins\%%i && cd plugins\%%i && nmake && del *.obj *.idb &&cd ..\..)
+1
View File
@@ -0,0 +1 @@
include Makefile.var
+7
View File
@@ -0,0 +1,7 @@
all: $(BUILDDIR)lastFripper$(DLSUFFICS)
lastFripper$(OBJSUFFICS): lastFripper.c
$(CC) $(DCFLAGS) $(CFLAGS) lastFripper.c
$(BUILDDIR)lastFripper$(DLSUFFICS): lastFripper$(OBJSUFFICS)
$(LN) $(LNOUT)../../$(BUILDDIR)lastFripper$(DLSUFFICS) $(LDFLAGS) $(DLFLAGS) lastFripper$(OBJSUFFICS)
+37
View File
@@ -0,0 +1,37 @@
VERFILE = version.obj ../3proxy.RES
#$Id: Makefile.msvc,v 1.17 2010-11-11 14:44:11 v.dubrovin Exp $
#
# 3 proxy Makefile for Microsoft Visual C compiler (for both make and nmake)
#
# You can try to remove -DWITH_STD_MALLOC to CFLAGS to use optimized malloc
# libraries
#
# Add /DSAFESQL to CFLAGS if you are using poorely written/tested ODBC driver
BUILDDIR = ../bin/
CC = cl
CFLAGS = /nologo /MT /W3 /Ox /GS /EHs- /GA /GF /D "MSVC" /D "WITH_STD_MALLOC" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "_WIN32" /Fp"proxy.pch" /FD /c
COUT = /Fo
LN = link
LDFLAGS = /nologo /subsystem:console /incremental:no /machine:I386
DLFLAGS = /DLL
DLSUFFICS = .dll
LIBS = ws2_32.lib advapi32.lib odbc32.lib user32.lib kernel32.lib Gdi32.lib libeay32MT.lib ssleay32MT.lib
LIBEXT = .lib
LNOUT = /out:
EXESUFFICS = .exe
OBJSUFFICS = .obj
DEFINEOPTION = /D
COMPFILES = *.pch *.idb
REMOVECOMMAND = del 2>NUL >NUL
TYPECOMMAND = type
COMPATLIBS =
MAKEFILE = Makefile.msvc
PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin lastFripper FilePlugin
include Makefile.inc
allplugins:
for /D %%i in ($(PLUGINS)) do (copy Makefile plugins\%%i && copy Makefile.var plugins\%%i && cd plugins\%%i && nmake && del *.obj *.idb &&cd ..\..)
+704
View File
@@ -0,0 +1,704 @@
/*
released as a public domain
std.denis, 2009
*/
#include "../../structures.h"
#include "lastFripper.h"
#define strdup _strdup
#define strnicmp _strnicmp
#define ltoa _ltoa
#define mkdir _mkdir
#define PART_SUFFIX "_partial"
void my_mkdir( char* name )
{
char* pdir = name;
while( 1 ) {
char ch;
char* pnext = pdir;
while( *pnext && *pnext != '\\' && *pnext != '/' )
pnext++;
if( *pnext == 0 )
break;
ch = *pnext;
*pnext = 0;
mkdir( name );
*pnext = ch;
pdir = pnext + 1;
}
mkdir( name );
}
__inline void myOutputDebugStringA1( char* str )
{
/* char fname[128];
ltoa( GetCurrentThreadId(), fname, 10 );
FILE* fp = fopen( fname, "ab" );
fputs( str, fp );
fputs( "\r\n", fp );
fflush( fp );
fclose( fp );
*/
}
__inline void myOutputDebugStringA( void* buf, int len )
{
/* char fname[128];
ltoa( GetCurrentThreadId(), fname, 10 );
FILE* fp = fopen( fname, "ab" );
fwrite( buf, len, 1, fp );
fputs( "\r\n", fp );
fflush( fp );
fclose( fp ); */
}
#ifndef isnumber
#define isnumber(i_n_arg) ((i_n_arg>='0')&&(i_n_arg<='9'))
#endif
#define sizearr(x) (sizeof(x)/sizeof(x[0]))
#define xmalloc( type, len ) ((type*)malloc( (len) * sizeof(type) ) )
#define xcalloc( type, len ) ((type*)calloc( (len), sizeof(type) ) )
int clean_filename( char* filename )
{
int i;
for( i = 0; filename[i]; i++ )
switch( filename[i] ) {
case '*':
case '?':
case '<':
case '>':
case '\\':
case '/':
case ':':
case '"':
filename[i] = '_';
break;
}
return i;
}
static struct pluginlink * pl;
static int lfm_loaded = 0;
static char* g_folder = 0;
static char* g_format = 0;
static int lfm_format_filename( struct playlist_item* p_item, char* p_filename, int n_filename )
{
int i = 0, j;
char ch;
char* fmt;
char *ff = NULL;
if( g_folder && *g_folder ) {
strncpy( p_filename, g_folder, n_filename );
i = strlen( p_filename );
if( i < n_filename-1 && p_filename[i-1] != '\\' )
p_filename[i++] = '\\';
}
fmt = g_format;
if( fmt == NULL ) fmt = "%a\\%t.mp3";
while( ( ch = *fmt++ ) != 0 ) {
if( ch == '%' ) {
char* p_sz = NULL;
char a_sz[32];
ch = *fmt++;
switch( ch ) {
case 0:
fmt--; break;
case '%':
p_sz = "%";
break;
case 'n': {
static unsigned ndx = 0;
ltoa( ndx++, a_sz, 10 );
p_sz = a_sz;
break;
}
case 'a':
p_sz = p_item->artist;
break;
case 't':
p_sz = p_item->title;
break;
case 'l':
p_sz = p_item->album;
break;
}
if( p_sz ) {
strncpy( p_filename+i, p_sz, n_filename-i );
p_filename[n_filename-1] = 0;
i += clean_filename( p_filename+i );
}
} else
if( i < n_filename ) p_filename[i++] = ch;
}
for( j = i-1; j >= 0; j-- )
if( p_filename[j] == '\\' || p_filename[j] == '/' ) {
ff = p_filename + j;
break;
}
if( ff ) {
char ch = *ff;
*ff = 0;
my_mkdir( p_filename );
*ff = ch;
}
return i;
}
static void lfm_close_request( struct lfm_client_data* p_client )
{
struct lfm_filter_data* p_data;
if( p_client == NULL ) return;
p_data = p_client->p_data;
if( p_data == NULL ) return;
if( p_client->req_type == LFM_PLAYLIST ) {
free( p_client->pl_xml );
} else if( p_client->req_type == LFM_GET && p_client->fp ) {
struct playlist_item* p_item = p_client->pl_item;
if( p_item ) {
char id3v1[128];
memset( id3v1, 0, 128 );
strcpy( id3v1, "TAG" );
strncpy( id3v1+3, p_item->title, 30 );
strncpy( id3v1+33, p_item->artist, 30 );
strncpy( id3v1+63, p_item->album, 30 );
id3v1[127] = -1;
fwrite( id3v1, 128, 1, p_client->fp );
}
fclose( p_client->fp );
/*
if( p_item ) {
char filename_part[512], filename[512];
int i = lfm_format_filename( p_item, filename_part, sizearr(filename_part) );
memcpy( filename, filename_part, sizeof(filename) );
strncpy( filename_part+i, PART_SUFFIX, sizearr(filename_part)-i );
rename( filename_part, filename );
}
*/
pthread_mutex_lock( &p_data->mutex );
if( p_data->playlist != NULL && p_item != NULL ) {
if( p_data->playlist == p_item )
p_data->playlist = p_item->next;
else {
struct playlist_item *p_last = p_data->playlist;
while( p_last->next != NULL && p_last->next != p_item )
p_last = p_last->next;
if( p_last->next )
p_last->next = p_item->next;
}
if( p_item->artist ) free( p_item->artist );
if( p_item->title ) free( p_item->title );
if( p_item->album ) free( p_item->album );
if( p_item->url ) free( p_item->url );
free( p_item );
}
pthread_mutex_unlock( &p_data->mutex );
}
p_client->req_type = LFM_NONE;
}
static void* lfm_filter_open( void * idata, struct srvparam * param ){
struct lfm_filter_data* pdata = (struct lfm_filter_data*)idata;
if( pdata ){
pthread_mutex_lock( &pdata->mutex );
pdata->refs++;
pthread_mutex_unlock( &pdata->mutex );
} else {
if( ( pdata = xcalloc( struct lfm_filter_data, 1 ) ) != NULL ) {
pthread_mutex_init( &pdata->mutex, NULL );
pdata->playlist = NULL;
pdata->refs++;
}
}
return pdata;
}
static FILTER_ACTION lfm_filter_client( void *fo, struct clientparam* param, void** fc )
{
struct lfm_filter_data* p_data;
struct lfm_client_data* p_client;
*fc = NULL;
if( fo == NULL ) return PASS;
p_data = (struct lfm_filter_data*)fo;
p_client = xcalloc( struct lfm_client_data, 1 );
if( p_client == NULL ) return PASS;
p_client->p_data = p_data;
p_client->req_type = LFM_NONE;
*fc = p_client;
return CONTINUE;
}
static void lfm_filter_clear( void *fc )
{
struct lfm_client_data* p_client;
p_client = (struct lfm_client_data*)fc;
if( p_client == NULL ) return;
lfm_close_request( p_client );
free( p_client );
}
static void lfm_filter_close(void *fo){
struct lfm_filter_data* p_data;
struct playlist_item* p_item;
p_data = (struct lfm_filter_data*)fo;
if( p_data == NULL ) return;
if( --p_data->refs > 0 ) return;
pthread_mutex_destroy( &p_data->mutex );
p_item = p_data->playlist;
while( p_item ) {
struct playlist_item* p_old = p_item;
p_item = p_item->next;
if( p_old->artist ) free( p_old->artist );
if( p_old->title ) free( p_old->title );
if( p_old->album ) free( p_old->album );
if( p_old->url ) free( p_old->url );
free( p_old );
}
free( p_data );
}
static FILTER_ACTION lfm_filter_request( void *fc, struct clientparam *param, unsigned char** buf_p, int* bufsize_p, int offset, int* length_p )
{
char* p_buf = (char*)( *buf_p + offset );
int n_buf = *length_p - offset;
struct lfm_client_data* p_client;
struct lfm_filter_data* p_data;
if( p_buf == NULL || n_buf < 5 ) return CONTINUE;
p_client = (struct lfm_client_data*)fc;
if( p_client == NULL ) return CONTINUE;
p_data = p_client->p_data;
if( p_data == NULL ) return CONTINUE;
pl->conf->filtermaxsize = 0;
lfm_close_request( p_client );
p_client->req_type = LFM_NONE;
p_client->fp = NULL;
if( strncasecmp( p_buf, "GET ", 4 ) != 0 ) return CONTINUE;
p_buf += 4;
if( strncasecmp( p_buf, "http://ws.audioscrobbler.com/radio/xspf.php?", 44 ) == 0 ) {
myOutputDebugStringA1( "getting a playlist" );
p_client->req_type = LFM_PLAYLIST;
} else {
char zzz[256];
int i;
struct playlist_item* p_item;
for( i = 0; i < n_buf && i < 256; i++ ) {
if( p_buf[i] == '\r' ) break;
zzz[i] = p_buf[i];
}
zzz[i] = 0;
myOutputDebugStringA1( zzz );
pthread_mutex_lock( &p_data->mutex );
p_item = p_data->playlist;
while( p_item ) {
if( strncasecmp( p_buf, p_item->url, p_item->url_len ) == 0 )
break;
p_item = p_item->next;
}
pthread_mutex_unlock( &p_data->mutex );
if( p_item ) {
myOutputDebugStringA1( "getting a known url: " );
myOutputDebugStringA1( p_item->title );
p_client->req_type = LFM_GET;
p_client->pl_item = p_item;
}
}
return CONTINUE;
}
static FILTER_ACTION lfm_filter_header_srv( void *fc, struct clientparam *param, unsigned char** buf_p, int* bufsize_p, int offset, int* length_p )
{
char* p_buf = (char*)( *buf_p + offset );
struct lfm_client_data* p_client;
int n_buf = *length_p - offset;
struct lfm_filter_data* p_data;
char zzz[100];
int code;
if( p_buf == NULL || n_buf < 9 ) return CONTINUE;
p_client = (struct lfm_client_data*)fc;
if( p_client == NULL ) return CONTINUE;
p_data = p_client->p_data;
if( p_data == NULL ) return CONTINUE;
code = atoi( p_buf + 9 );
sprintf( zzz, "http code: %d", code );
myOutputDebugStringA1( zzz );
myOutputDebugStringA( p_buf, n_buf );
if( p_client->req_type == LFM_GET && ( code > 300 && code < 304 || code == 307 ) ) {
p_client->req_type = LFM_REDIR;
do {
char* p_line = p_buf;
int n_line;
for(; n_buf > 0 && *p_buf != '\r'; p_buf++, n_buf-- ) {};
n_line = p_buf - p_line;
if( n_line <= 0 ) break;
if( n_line > 10 && strncasecmp( p_line, "location: ", 10 ) == 0 ) {
myOutputDebugStringA1( "redir/location: " );
myOutputDebugStringA( p_line + 10, n_line - 10 );
if( p_client->pl_item ) {
char* p_url = p_line + 10;
int n_url = n_line - 10;
pthread_mutex_lock( &p_data->mutex );
if( p_client->pl_item->url ) free( p_client->pl_item->url );
p_client->pl_item->url = xmalloc( char, n_url + 1 + 1 );
memcpy( p_client->pl_item->url, p_url, n_url );
p_client->pl_item->url[n_url] = ' ';
p_client->pl_item->url[n_url+1] = 0;
p_client->pl_item->url_len = n_url + 1;
myOutputDebugStringA1( "got a url: " );
myOutputDebugStringA1( p_client->pl_item->url );
pthread_mutex_unlock( &p_data->mutex );
}
p_client->req_type = LFM_NONE;
}
for(; n_buf > 0 && ( *p_buf == '\n' || *p_buf == '\r' ); p_buf++, n_buf-- ) {};
} while( n_buf > 0 );
}
if( code == 200 && p_client->req_type == LFM_GET ) {
struct playlist_item* p_item = p_client->pl_item;
char filename[512];
int i = lfm_format_filename( p_item, filename, sizearr(filename) );
/*
strncpy( filename + i, PART_SUFFIX, sizearr(filename)-i );
*/
p_client->fp = fopen( filename, "wb" );
}
else if( code == 200 && p_client->req_type == LFM_PLAYLIST ) {
p_client->pl_xml = xcalloc( struct xml_state, 1 );
}
return CONTINUE;
}
void playlist_analyze( struct lfm_client_data* p_client, const char* p_buf, int len );
static FILTER_ACTION lfm_filter_data_srv( void *fc, struct clientparam *param, unsigned char** buf_p, int* bufsize_p, int offset, int* length_p )
{
char* p_buf = (char*)( *buf_p + offset );
int n_buf = *length_p - offset;
struct lfm_client_data* p_client;
struct lfm_filter_data* p_data;
myOutputDebugStringA1( "filter_data_srv" );
myOutputDebugStringA( p_buf, n_buf );
if( p_buf == NULL || n_buf < 1 ) return CONTINUE;
p_client = (struct lfm_client_data*)fc;
if( p_client == NULL ) return CONTINUE;
p_data = p_client->p_data;
if( p_data == NULL ) return CONTINUE;
if( p_client->req_type == LFM_PLAYLIST )
myOutputDebugStringA1( "filter_data_srv: playlist" );
else if( p_client->req_type == LFM_GET ) {
myOutputDebugStringA1( "filter_data_srv: retrieving" );
if( p_client->fp == NULL )
myOutputDebugStringA1( "but no file allocated" );
}
if( p_client->req_type == LFM_PLAYLIST )
playlist_analyze( p_client, p_buf, n_buf );
if( p_client->fp )
fwrite( p_buf, n_buf, 1, p_client->fp );
return CONTINUE;
}
enum XmlState
{
XML_TEXT,
XML_TAGNAME,
XML_ATTRNAME_W,
XML_ATTRNAME,
XML_ATTRVALUE_W,
XML_ATTRVALUE,
XML_TAGCLOSE,
XML_TAGOPENCLOSE,
};
int xml_get_token_id( char** table, char* token )
{
int i;
char* psz;
for( psz = token; *psz; psz++ )
*psz = tolower( *psz );
for( i = 0; *table; i++, table++ )
if( strcmp( *table, token ) == 0 ) return i;
return -1;
}
enum {
XT_PLAYLIST,
XT_TRACK_LIST,
XT_TRACK,
XT_LOCATION,
XT_CREATOR,
XT_ALBUM,
XT_TITLE
};
char* xt_list[] = {
"playlist",
"tracklist",
"track",
"location",
"creator",
"album",
"title",
NULL
};
void playlist_analyze( struct lfm_client_data* p_client, const char* p_buf, int len )
{
struct xml_state* xs = p_client->pl_xml;
int n_buf = len;
if( xs == NULL ) return;
while( n_buf > 0 ) {
enum {
XMS_NONE,
XMS_TAG,
XMS_ATTR_NAME,
XMS_ATTR_VALUE,
XMS_TEXT
} gotta = XMS_NONE;
char ch = *p_buf++;
n_buf--;
lbl_retry:
switch( xs->state ) {
case XML_TAGNAME:
if( ch == '>' ) {
xs->state = XML_TEXT;
gotta = XMS_TAG;
break;
} else if( ch == '/' ) {
if( xs->n_token == 0 )
xs->closing = 1;
else {
xs->state = XML_ATTRNAME_W;
gotta = XMS_TAG;
xs->n_token--;
}
break;
} else if( isspace( ch ) ) {
xs->state = XML_ATTRNAME_W;
gotta = XMS_TAG;
break;
}
if( xs->n_token < TOKEN_MAXLEN ) xs->p_token[xs->n_token++] = ch;
break;
case XML_ATTRNAME_W:
if( ch == '>' ) {
xs->state = XML_TEXT;
break;
} else if( ch == '/' ) {
xs->closing = 1;
xs->state = XML_TEXT;
gotta = XMS_TAG;
break;
} else if( !isspace( ch ) ) {
xs->state = XML_ATTRNAME;
goto lbl_retry;
}
break;
case XML_ATTRNAME:
if( ch == '=' ) {
xs->state = XML_ATTRVALUE_W;
gotta = XMS_ATTR_NAME;
break;
}
if( xs->n_token < TOKEN_MAXLEN ) xs->p_token[xs->n_token++] = ch;
break;
case XML_ATTRVALUE_W:
if( ch == '"' || ch == '\'' ) {
xs->sep = ch;
xs->state = XML_ATTRVALUE;
break;
}
break;
case XML_ATTRVALUE:
if( ch == xs->sep ) {
xs->state = XML_ATTRNAME_W;
gotta = XMS_ATTR_VALUE;
break;
}
if( xs->n_token < TOKEN_MAXLEN ) xs->p_token[xs->n_token++] = ch;
break;
case XML_TEXT:
if( ch == '<' ) {
xs->state = XML_TAGNAME;
gotta = XMS_TEXT;
break;
}
if( xs->n_token < TOKEN_MAXLEN ) xs->p_token[xs->n_token++] = ch;
break;
}
if( gotta != XMS_NONE ) {
xs->p_token[xs->n_token] = 0;
switch( gotta ) {
case XMS_TAG: {
int id = xml_get_token_id( xt_list, xs->p_token );
if( !xs->closing ) {
if( xs->level < sizeof(xs->tree) ) xs->tree[xs->level] = id;
xs->level++;
if( id == XT_TRACK && xs->level == 3 && xs->tree[1] == XT_TRACK_LIST )
xs->p_item = xcalloc( struct playlist_item, 1 );
} else {
if( xs->level > 0 ) xs->level--;
if( id == XT_TRACK && xs->level == 2 && xs->tree[1] == XT_TRACK_LIST ) {
char zzz[1024];
_snprintf( zzz, 1024, "artist: <%s>, title: <%s>, url: <%s>",
xs->p_item->artist, xs->p_item->title, xs->p_item->url );
myOutputDebugStringA1( zzz );
pthread_mutex_lock( &p_client->p_data->mutex );
xs->p_item->next = p_client->p_data->playlist;
p_client->p_data->playlist = xs->p_item;
pthread_mutex_unlock( &p_client->p_data->mutex );
}
xs->closing = 0;
}
break;
}
case XMS_ATTR_NAME:
break;
case XMS_ATTR_VALUE:
break;
case XMS_TEXT:
if( xs->level == 4 && xs->tree[1] == XT_TRACK_LIST && xs->tree[2] == XT_TRACK ) {
struct playlist_item* item = xs->p_item;
if( item )
switch( xs->tree[3] ) {
case XT_LOCATION:
item->url_len = xs->n_token;
item->url = xmalloc( char, item->url_len + 1 + 1);
memcpy( item->url, xs->p_token, item->url_len );
item->url[item->url_len++] = ' ';
item->url[item->url_len] = 0;
break;
case XT_CREATOR:
item->artist = strdup( xs->p_token );
break;
case XT_ALBUM:
item->album = strdup( xs->p_token );
break;
case XT_TITLE:
item->title = strdup( xs->p_token );
break;
}
}
break;
}
xs->n_token = 0;
}
}
}
static struct filter lfm_filter = {
NULL,
"last.fm spy",
NULL,
lfm_filter_open,
lfm_filter_client,
lfm_filter_request,
NULL,
lfm_filter_header_srv,
NULL,
NULL,
lfm_filter_data_srv,
lfm_filter_clear,
lfm_filter_close
};
static int h_lfm_folder( int argc, unsigned char **argv )
{
if( g_folder ) free( g_folder );
g_folder = strdup( (char*)argv[1] );
return 0;
}
static int h_lfm_format( int argc, unsigned char **argv )
{
if( g_format ) free( g_format );
g_format = strdup( (char*)argv[1] );
return 0;
}
static struct commands lfm_commandhandlers[] = {
{lfm_commandhandlers+1, "lfm_folder", h_lfm_folder, 2, 2},
{NULL, "lfm_format", h_lfm_format, 2, 2}
};
#ifdef __cplusplus
extern "C" {
#endif
#ifdef _WIN32
__declspec(dllexport)
#endif
int lfm_plugin( struct pluginlink * pluginlink, int argc, char** argv )
{
pl = pluginlink;
myOutputDebugStringA1( "lfm_plugin" );
if( !lfm_loaded ) {
lfm_loaded = 1;
lfm_filter.next = pl->conf->filters;
pl->conf->filters = &lfm_filter;
lfm_commandhandlers[1].next = pl->commandhandlers->next;
pl->commandhandlers->next = lfm_commandhandlers;
}
return 0;
}
#ifdef __cplusplus
}
#endif
+66
View File
@@ -0,0 +1,66 @@
//
// released as a public domain
// std.denis, 2009
//
/*
#include "direct.h"
*/
#ifdef _WIN32
#define strcasecmp stricmp
#define strncasecmp strnicmp
#else
#define closesocket close
extern pthread_attr_t pa;
#endif
#ifndef SOCKET_ERROR
#define SOCKET_ERROR -1
#endif
typedef enum {
LFM_NONE,
LFM_PLAYLIST, // GET http://ws.audioscrobbler.com/radio/adjust.php(...)
LFM_REDIR, // GET http://play.last.fm/user/(...)
LFM_GET
} LFM_CLASS;
struct playlist_item {
struct playlist_item* next;
char* artist;
char* title;
char* album;
char* url;
int url_len;
};
#define TOKEN_MAXLEN 1024
struct xml_state {
int state;
int closing;
char sep;
int level;
char tree[128]; // 128 levels nesting
int n_token;
char p_token[TOKEN_MAXLEN];
struct playlist_item* p_item;
};
struct lfm_filter_data {
pthread_mutex_t mutex;
struct playlist_item* playlist;
int refs;
};
struct lfm_client_data {
struct lfm_filter_data* p_data;
int req_type;
struct xml_state* pl_xml;
struct playlist_item* pl_item;
FILE* fp;
};
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
gcc -shared -o libldapauth.so ldapauth_new.c -DNOODBC -I/usr/include -L/usr/lib -lldap
+4
View File
@@ -0,0 +1,4 @@
del ldapauth.dll
gcc -o getldapuser getldapuser.c -DWIN32 -I"./ldapwindev" -L"./ldapwindev" -lldap
gcc -shared -o ldapauth.dll ldapauth.c -DWIN32 -I"./ldapwindev" -L"./ldapwindev" -lldap
+105
View File
@@ -0,0 +1,105 @@
/* Create list user for 3proxy ACL from LDAP server
(c) Kirill Lopuchov lopuchov@mail.ru
*/
#include <stdio.h>
#include <ldap.h>
/*Create list user for 3proxy ACL from LDAP server*/
/* argv[1] = server
argv[2] = basedn
argv[3] = user_attribute
argv[4] = filter
argv[5] = user
argv[6] = password
*/
main(int argc, char *argv[])
{
LDAP *ld = NULL;
LDAPMessage *res = NULL;
LDAPMessage *msg = NULL;
BerElement *ber;
char *getattr,**vals;
char *attrs[] = { NULL, NULL };
int i, rc = -1;
int lderrno;
unsigned char tmpbuf[1000];
if ( argc < 6 )
{
printf ("Create 3proxy ACL userlist from ldap server.\ngetldapuser < ldapserver sbasedn user_attribute filter user password > \n");
printf ("Example: getldapuser 192.168.0.1 dc=domain,dc=com cn (memberOf=cn=internet,cn=Users,dc=domain,dc=com) cn=admin,cn=users,dc=domain,dc=com password \n");
}
else
{
attrs[0]=strdup(argv[3]);
/* init ldap ------------------------ */
ld = ldap_init( argv[1] , 389 );
if ( ld == NULL )
{
/*perror( "ldap_init" );*/
printf("Error init ldap") ;
exit(1);
}
/* connect ------------------------ */
rc = ldap_bind_s( ld, argv[5], argv[6], LDAP_AUTH_SIMPLE );
if ( rc != LDAP_SUCCESS )
{
ldap_perror( ld, "Error ldap_bind" );
}
/* search ------------------------ */
rc = ldap_search_s( ld,argv[2], LDAP_SCOPE_SUBTREE,
argv[4], attrs, 0, &res );
/* get val ------------------------*/
rc=ldap_count_entries(ld,res);
if (rc > 0)
{
msg=ldap_first_entry(ld, res);
getattr=ldap_first_attribute(ld, msg, &ber);
while (rc > 0)
{
vals=ldap_get_values(ld, msg, getattr);
if (vals != NULL && vals[0] != NULL )
{
i=ldap_count_values(vals);
while(i>0)
{
printf("%s",vals[0]);
i--;
if (rc > 1) { printf(",",vals[0]); }
}
ldap_value_free(vals);
}
msg=ldap_next_entry(ld, msg);
rc--;
}
} //end if (rc>0)
ldap_memfree(res);
ldap_unbind(ld);
}/*end else*/
}
+575
View File
@@ -0,0 +1,575 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ldap.h>
#ifndef _WIN32
#include <ctype.h>
#endif
#include "../../proxy.h"
#include "../../structures.h"
struct counter_record
{
unsigned long traf;
unsigned long trafgb;
time_t cleared;
time_t updated;
};
int already_loaded = 0;
static struct auth myalwaysauth;
static struct commands ldap_serv_auth_handler;
static struct commands ldap_access_handler;
static struct commands ldap_sbase_handler;
static struct commands ldap_userenv_handler;
static struct commands ldap_trafgroup_handler;
static struct commands ldap_attrsgroup_handler;
static struct commands ldap_dircount_handler;
static char *attrs[] = { NULL, NULL};
static char *ldap_group_attr;
static char *ldap_access;
static char *ldap_sbase;
static char *ldap_serv;
static char *ldap_user;
static char *ldap_pass;
static char *ldap_userenv;
int ldap_userenv_size;
static char *ldap_trafgroup;
static char *ldap_dircount;
static int usercaselow = 0;
struct pluginlink * mypluginlink;
struct schedule myschedule;
#ifndef _WIN32
void lower (char *string)
{
int length, i;
length = strlen(string);
for (i=0; i<length; i++)
{
string[i] = tolower(string[i]);
}
}
#endif
/* -------------------------------------------------------------------------- */
int savecouters(void)
{
struct trafcount *tc=mypluginlink->conf->trafcounter;
struct trafcount *tcd;
struct counter_record wcounter;
FILE *f;
unsigned char *tmpbuf,pat_file[]="%s%s.lc";
/* timetoexit !=0 - áóäåì çàâåðøàòüñÿ.*/
while (tc != NULL)
{
tcd = tc;
tc = tc->next;
f=NULL;
if(strcmp(tcd->comment,"ldapcounters")==0) {
tmpbuf=mypluginlink->myalloc(strlen(pat_file)+strlen(ldap_dircount)+strlen(tcd->ace->users->user));
sprintf(tmpbuf,pat_file,ldap_dircount,tcd->ace->users->user);
f=fopen(tmpbuf,"w+b");
fseek(f,0,SEEK_SET);
fprintf(f,"%10lu %10lu %lu %lu\n",tcd->trafgb,tcd->traf,
tcd->cleared,tcd->updated);
fclose(f);
mypluginlink->myfree(tmpbuf);
}
}
/*return 1 delete job , return 0 no delete job*/
if (mypluginlink->conf->needreload !=0 )
{
return (0);
}
return (0);
}
/*--------------------------------------------------------------------------*/
#ifdef _WIN32
__declspec(dllexport) int start(struct pluginlink * pluginlink,
int argc, char** argv);
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
#else
int start(struct pluginlink * pluginlink,
int argc, char** argv);
#endif
/* --------------------------------------------------------------------------*/
static int ldapfunc(struct clientparam *param)
{
LDAP *ld = NULL;
LDAPMessage *res = NULL;
int rc = -1;
char tmpbuf[1024];
/* init ldap ---------------------- */
ld = ldap_init( ldap_serv, 389 );
if ( ld == NULL )
{
param->srv->logfunc(param,"Error ldap_init: No init lib ldap");
/*ldap_perror( ld, "Error ldap_init" ); */
return 7;
}
/* test proxy user auth ------------------------*/
if(!param->username || !param->password) return 4;
if(strlen(param->password)==0) return 4;
/* this code for Active Directory LDAP catalog :(
detail see documentation for plugin */
if (usercaselow > 0)
#ifdef _WIN32
{ CharLower(param->username); }
#else
{ lower(param->username); }
#endif
/* create user for test auth */
sprintf(tmpbuf,"%.200s=%.200s,%.200s",attrs[0],param->username,ldap_userenv);
rc = ldap_bind_s( ld, tmpbuf, param->password, LDAP_AUTH_SIMPLE );
if ( rc != LDAP_SUCCESS )
{
param->srv->logfunc(param,"Error ldap_bind: No connect ldap catalog");
ldap_unbind_s(ld);
return 7;
}
ldap_unbind_s(ld);
ld = ldap_init( ldap_serv, 389 );
rc = ldap_bind_s( ld, ldap_user, ldap_pass, LDAP_AUTH_SIMPLE );
if ( rc != LDAP_SUCCESS )
{
param->srv->logfunc(param, "Error ldap_bind: Not authorize in ldap\
catalog, checked option \'ldapconnect\' ");
ldap_unbind_s(ld);
return 7;
}
/* test enter user in filter ------------------------------
create filter for search*/
sprintf(tmpbuf,"(&(%.200s=%.200s)(%.200s=%.200s))",attrs[0],param->username,
ldap_group_attr,ldap_access);
/* search */
rc = ldap_search_s( ld, ldap_sbase, LDAP_SCOPE_SUBTREE,
tmpbuf, attrs, 0, &res );
rc=ldap_count_entries(ld,res);
ldap_msgfree(res);
ldap_unbind_s(ld);
/* user not found */
if (rc == 0)
{ return 5; }
return 0;
}
/* --------------------------------------------------------------------------
handle command ldapserv */
int h_ldapconnect(int argc, unsigned char ** argv)
{
LDAP *ld = NULL;
if (argc < 2)
{
fprintf(stderr, "Error in ldapconnect: See documentation of ldapauth plugin.\n");
return 1;
}
ldap_serv=mypluginlink->mystrdup(argv[1]);
ldap_user=mypluginlink->mystrdup(argv[2]);
ld = ldap_init( ldap_serv, 389 );
ldap_unbind_s(ld);
if (argc == 4)
{
ldap_pass= mypluginlink->mystrdup(argv[3]);
}
else
{
ldap_pass=NULL;
}
return 0;
}
/* --------------------------------------------------------------------------
handle command ldapaccess */
int h_access(int argc, unsigned char ** argv)
{
if (argc < 1)
{
fprintf(stderr, "Error in ldapaccess: See documentation of ldapauth plugin.\n");
return 1;
}
ldap_access=mypluginlink->mystrdup(argv[1]);
return 0;
}
/* --------------------------------------------------------------------------
handle command ldapsbase
searching base */
int h_sbase(int argc, unsigned char ** argv)
{
if (argc < 1)
{
fprintf(stderr, "Error in ldapsbase: See documentation of ldapauth plugin.\n");
return 1;
}
ldap_sbase=mypluginlink->mystrdup(argv[1]);
return 0;
}
/* --------------------------------------------------------------------------
handle command ldapuserenv */
int h_userenv(int argc, unsigned char ** argv)
{
if (argc < 1)
{
fprintf(stderr, "Error in ldapsbase: See documentation of ldapauth plugin.\n");
return 1;
}
ldap_userenv=mypluginlink->mystrdup(argv[1]);
return 0;
}
/* --------------------------------------------------------------------------
handle command ldaptrafgroup */
int h_trafgroup(int argc, unsigned char ** argv)
{
struct trafcount *newtrafcount;
struct bandlim *newbandlim;
static struct ace *newace;
static struct userlist *newuserlist;
struct counter_record rcounter;
LDAP *ld = NULL;
LDAPMessage *res = NULL;
LDAPMessage *msg = NULL;
BerElement *ber = NULL;
int rc = -1;
char *tmpbuf,pat_file[]="%s%s.lc",pat_group[]="(%s=%s)";
char *getattr,**vals,buf[256];
ROTATION rtype;
unsigned long traflimit;
int bandwidth ;
FILE *f;
if (argc < 3)
{
fprintf(stderr, "Error in ldaptrafgroup: See documentation of ldapauth plugin.\n");
return 1;
}
ld = ldap_init( ldap_serv, 389 );
if ( ld == NULL )
{
fprintf(stderr,"Error in ldaptrafgroup: ldap_init: No init lib ldap");
return 7;
}
rc = ldap_bind_s( ld, ldap_user, ldap_pass, LDAP_AUTH_SIMPLE );
if ( rc != LDAP_SUCCESS )
{
fprintf(stderr, "Error in ldaptrafgroup: ldap_bind: Not authorize in ldap\
catalog, checked option \'ldapconnect\' ");
ldap_unbind_s(ld);
return 7;
}
/* type traf limit */
if(strcmp(argv[2],"MONTHLY")==0||strcmp(argv[2],"monthly")==0)
{rtype=MONTHLY;}
if(strcmp(argv[2],"DAILY")==0||strcmp(argv[2],"daily")==0)
{rtype=DAILY;}
if(strcmp(argv[2],"WEEKLY")==0||strcmp(argv[2],"weekly")==0)
{rtype=WEEKLY;}
traflimit = atol((char *)argv[3]);
bandwidth = atoi((char *)argv[4]);
/* name ldap group */
tmpbuf=mypluginlink->myalloc(strlen(pat_group)+strlen(ldap_group_attr)+strlen(argv[1]));
sprintf(tmpbuf,pat_group,ldap_group_attr,argv[1]);
rc = ldap_search_s( ld, ldap_sbase, LDAP_SCOPE_SUBTREE,
tmpbuf, attrs, 0, &res );
mypluginlink->myfree(tmpbuf);
rc=ldap_count_entries(ld,res);
/* users found */
if (rc > 0)
{
msg=ldap_first_entry(ld, res);
getattr=ldap_first_attribute(ld, msg, &ber);
while (rc > 0)
{
vals=ldap_get_values(ld, msg, getattr);
if (vals != NULL && vals[0] != NULL )
{
/* -------------bandlim----------
create user list */
newuserlist = (*mypluginlink->myalloc)(sizeof (struct userlist));
if (usercaselow > 0)
#ifdef _WIN32
{ CharLower(vals[0]); }
#else
{ lower(vals[0]); }
#endif
newuserlist->user = (*mypluginlink->mystrdup)(vals[0]);
newuserlist->next = NULL;
/*create user rule */
newace = (*mypluginlink->myalloc)(sizeof (struct ace));
memset(newace, 0, sizeof(struct ace));
newace->users = newuserlist;
newace->action = BANDLIM;
/*create user bandlim */
newbandlim =(*mypluginlink->myalloc)(sizeof (struct bandlim));
memset(newbandlim, 0, sizeof(struct bandlim));
newbandlim->rate = bandwidth;
newbandlim->ace = newace;
newbandlim->next = mypluginlink->conf->bandlimiter;
mypluginlink->conf->bandlimiter = newbandlim;
/* -------------counters----------
create user list */
newuserlist = (*mypluginlink->myalloc)(sizeof (struct userlist));
if (usercaselow > 0)
#ifdef _WIN32
{ CharLower(vals[0]); }
#else
{ lower(vals[0]); }
#endif
newuserlist->user = (*mypluginlink->mystrdup)(vals[0]);
newuserlist->next = NULL;
/*create user rule */
newace = (*mypluginlink->myalloc)(sizeof (struct ace));
memset(newace, 0, sizeof(struct ace));
newace->users = newuserlist;
newace->action = COUNTIN;
/*create user counter */
newtrafcount =(*mypluginlink->myalloc)(sizeof (struct trafcount));
memset(newtrafcount, 0, sizeof(struct trafcount));
newtrafcount->ace = newace;
newtrafcount->type=rtype;
newtrafcount->traflimgb =(traflimit/(1024*4));
newtrafcount->traflim = ((traflimit - (newtrafcount->traflimgb*(1024*4)))*(1024*1024));
newtrafcount->comment=(*mypluginlink->mystrdup)("ldapcounters");
newtrafcount->number=0;
tmpbuf=(*mypluginlink->myalloc)(strlen(pat_file)+strlen(ldap_dircount)+strlen(vals[0]));
sprintf(tmpbuf,pat_file,ldap_dircount,vals[0]);
f=NULL;
f=fopen(tmpbuf,"rb");
if(f!=NULL)
{
fseek(f,0,SEEK_SET);
fgets(buf, 256, f);
sscanf(buf,"%10lu %10lu %lu %lu\n",&rcounter.trafgb, &rcounter.traf,
&rcounter.cleared, &rcounter.updated);
newtrafcount->trafgb=rcounter.trafgb;
newtrafcount->traf=rcounter.traf;
newtrafcount->cleared=rcounter.cleared;
newtrafcount->updated=rcounter.updated;
fclose(f);
}
mypluginlink->myfree(tmpbuf);
newtrafcount->next = mypluginlink->conf->trafcounter;
mypluginlink->conf->trafcounter = newtrafcount;
ldap_value_free(vals);
}
msg=ldap_next_entry(ld, msg);
rc--;
}
}/* end if (rc > 0) */
ldap_unbind_s(ld);
return 0;
}
/* --------------------------------------------------------------------------
handle command ldapattrsgroup */
int h_attrsgroup(int argc, unsigned char ** argv)
{
if (argc < 1)
{
fprintf(stderr, "Error in ldapattr: See documentation of ldapauth plugin.\n");
return 1;
}
attrs[0]=mypluginlink->mystrdup(argv[1]);
ldap_group_attr=mypluginlink->mystrdup(argv[2]);
if(argc == 4)
{ usercaselow=atoi(argv[3]); }
return 0;
}
/* --------------------------------------------------------------------------
handle command ldapdircount */
int h_dircount(int argc, unsigned char ** argv)
{
if (argc < 1)
{
fprintf(stderr, "Error in ldapdircount: See documentation of ldapauth plugin.\n");
return 1;
}
ldap_dircount=mypluginlink->mystrdup(argv[1]);
return 0;
}
/*------------------------------- MAIN --------------------------------------
start plugin init */
int start(struct pluginlink * pluginlink, int argc, char** argv)
{
if (already_loaded != 0)
{
pluginlink->myfree(ldap_access);
pluginlink->myfree(ldap_sbase);
pluginlink->myfree(ldap_serv);
pluginlink->myfree(ldap_user);
pluginlink->myfree(ldap_pass);
pluginlink->myfree(ldap_userenv);
pluginlink->myfree(ldap_dircount);
pluginlink->myfree(ldap_group_attr);
pluginlink->myfree(attrs[0]);
return (0);
}
already_loaded = 1;
mypluginlink=pluginlink;
ldap_access=NULL;
ldap_sbase=NULL;
ldap_serv=NULL;
ldap_user=NULL;
ldap_pass=NULL;
ldap_userenv=NULL;
ldap_trafgroup=NULL;
ldap_dircount=NULL;
ldap_group_attr=NULL;
myalwaysauth.authenticate = ldapfunc;
myalwaysauth.authorize = pluginlink->checkACL;
myalwaysauth.desc = "ldap";
myalwaysauth.next = pluginlink->authfuncs->next;
pluginlink->authfuncs->next = &myalwaysauth;
/* add command: ldapconnect ipserv user_serv pass_serv */
ldap_serv_auth_handler.minargs = 3;
ldap_serv_auth_handler.maxargs = 4;
ldap_serv_auth_handler.command = "ldapconnect";
ldap_serv_auth_handler.handler = h_ldapconnect;
ldap_serv_auth_handler.next = pluginlink->commandhandlers->next;
pluginlink->commandhandlers->next = &ldap_serv_auth_handler;
/* add command: ldapaccess cn=internet,cn=users,dc=domain,dc=ru */
ldap_access_handler.minargs = 2;
ldap_access_handler.maxargs = 2;
ldap_access_handler.command = "ldapaccess";
ldap_access_handler.handler = h_access;
ldap_access_handler.next = pluginlink->commandhandlers->next;
pluginlink->commandhandlers->next = &ldap_access_handler;
/* add command: ldapsbase cn=users,dc=domain,dc=ru */
ldap_sbase_handler.minargs = 2;
ldap_sbase_handler.maxargs = 2;
ldap_sbase_handler.command = "ldapsbase";
ldap_sbase_handler.handler = h_sbase;
ldap_sbase_handler.next = pluginlink->commandhandlers->next;
pluginlink->commandhandlers->next = &ldap_sbase_handler;
/* add command: ldapuserenv (cn=users,dc=domain,dc=ru) */
ldap_userenv_handler.minargs = 2;
ldap_userenv_handler.maxargs = 2;
ldap_userenv_handler.command = "ldapuserenv";
ldap_userenv_handler.handler = h_userenv;
ldap_userenv_handler.next = pluginlink->commandhandlers->next;
pluginlink->commandhandlers->next = &ldap_userenv_handler;
/* add command: ldaptrafgroup cn=traf500,cn=users,dc=domain,dc=ru M 500 333 */
ldap_trafgroup_handler.minargs = 5;
ldap_trafgroup_handler.maxargs = 5;
ldap_trafgroup_handler.command = "ldaptrafgroup";
ldap_trafgroup_handler.handler = h_trafgroup;
ldap_trafgroup_handler.next = pluginlink->commandhandlers->next;
pluginlink->commandhandlers->next = &ldap_trafgroup_handler;
/* add command: ldapattr cn memberOf usercaselow=1 */
ldap_attrsgroup_handler.minargs = 3;
ldap_attrsgroup_handler.maxargs = 4;
ldap_attrsgroup_handler.command = "ldapattr";
ldap_attrsgroup_handler.handler = h_attrsgroup;
ldap_attrsgroup_handler.next = pluginlink->commandhandlers->next;
pluginlink->commandhandlers->next = &ldap_attrsgroup_handler;
/* add command: ldapdircount c:\3proxy\ */
ldap_dircount_handler.minargs = 2;
ldap_dircount_handler.maxargs = 2;
ldap_dircount_handler.command = "ldapdircount";
ldap_dircount_handler.handler = h_dircount;
ldap_dircount_handler.next = pluginlink->commandhandlers->next;
pluginlink->commandhandlers->next = &ldap_dircount_handler;
/*create job shedule for processing reload, save counters to file */
memset(&myschedule,0,sizeof(struct schedule));
myschedule.type=MINUTELY;
myschedule.function=savecouters;
myschedule.next = *pluginlink->schedule;
*pluginlink->schedule=&myschedule;
return 0;
}
+602
View File
@@ -0,0 +1,602 @@
----------------------------win1251------------------------------
Плагин аутентификации в LDAP для сервера 3proxу (ОС windows,unix)
(c) Lopuchov Kirill lopuchov@mail.ru
1. Краткое описание
* Поддерживается только аутентификация открытым текстом (basic)
* Поддерживается создание лимитов по трафику для групп пользователей
(в день,месяц,неделю)
* Поддерживается создание лимитов по скорости для групп пользователей
(пока лимиты только на входящий трафик)
* Отсутcтвует кеширование имен пользователей.
В качестве интерфейса доступа к ldap используется библиотека openldap,
поэтому плагин может компилироваться и работать как на Windows 98/2000/XP
так и на различных unix подобных системах например Linux,FreeBSD.
Все тесты работоспособности проводились на сервере с Active Directory в
ее реализации ldap но в принципе должно работать и на других ldap системах.
Для компиляции и тестирования под ОС Windows использовался пакет Dev-C++
http://www.bloodshed.net/dev/ и часть библиотек OpenLDAP for Windows
http://lucas.bergmans.us/hacks/openldap/
версия openldap-2.2.29-db-4.3.29-openssl-0.9.8a-win32_Setup.exe,
версия этой же библиотеки идет в комплекте к плагину.
под unix подобной ОС (Freebsd) использовался стандартный gcc.
и библиотеки openldap-client.
!!!! Внимание при работе плагина возможна утечка памяти !!!!
У меня на Win 2000 Serv и окола 600 пользователях при канале 500 кбит/сек .
процесс 3proxy за сутки выростает до 40 мб . Лечится рестартом сервиса.
Если кто то знает хорошо Open Ldap api и может указать на ошибку в плагине
с радостью выслушаю :) .
2. Настройка плагина.
2.1 Для подключения к LDAP серверу используется комманда ldapconnect .
Первый параметр определят ip адрес или host имя LDAP сервера ,
второй параметр имя пользователя от имени корого будут совершиться
вся дальнейшая работа с ldap каталогом такая как поиск пользователей
и проверка их принадлежности к той или иной группе, третий параметр это
пароль для этого пользователя.
У такого пользовате в контекстет Active Directory могут отсутсвовать
права администратора для нормальной работы плагина. В классических Open Ldap
серверах под xNIX таким пользователем может выступать anonymous.
Пример:
ldapconnect 192.160.0.1 cn=ldap,cn=users,dc=domain,dc=ru ldap
2.2 Для определения в каком контексте искать пользователей и группы
служит комманда ldapsbase
Пример:
ldapsbase cn=users,dc=domain,dc=ru
2.3 Комманда ldapattr служит для определния различных параметров плагина.
a)первый параметр определяет атрибут "пользователь" в контексте ldap каталога
в Active Directory это как правило "cn" , в других ldap серверах "uid".
b)второй параметр опеределяет атрибут "группа" в контексте ldap каталога
в Active Directory это как правило "memberof" , в других ldap серверах "ou".
c)третий параметр может не обязательный и может содержать 0 или 1
1 - означает, что при авторизации пользователя или создании для него
орграничения по трафику его имя будет приводится к нижнему регистру
(примечание: только для имен пользователей на английском) .
Этот параметр создан для исключения случаев когда LDAP каталог при
авторизации не отличает имен пользователей в регистрах.
Пример:
ldapattr cn memberof 1
2.4 Комманда ldapaccess служит для определения "признака" доступности
пользователю вообще пройти авторизацию на proxy сервере. В контексте
ldap каталога это ЗНАЧЕНИЕ атрибута "группы" описанной в комманде ldapattr.
Пример:
ldapaccess CN=internet,CN=Users,DC=domain,DC=ru
Например: для Active Directory это будет пользователь входящий в группу
internet. Тоесть при проверке можно ли пользователю работать с proxy
формируется фильтр он должен попасть в следующий фильтр:
(&(cn=имяпользователя)(memberof=CN=internet,CN=Users,DC=domain,DC=ru))
2.5 Комманда ldapuserenv служит для формирования строки имени пользователя
который пытается пройти авторизацию в ldap. Тоесть фактически это base DN
для пользователя.
Пример:
ldapuserenv cn=users,dc=domain,dc=ru
2.7 Комманда ldaptrafgroup служит для создания лимитов
ОНИ ОБЯЗАТЕЛЬНО ДОЛЖНА ИДТИ ПОСЛЕ ВСЕХ остальных комманд плагина.
a) первый параметр это название группы (значение ldap атрибута ) в которую
входит пользователь.
b) второй параметр на какой период накладывается ограничение по объему
трафика . Может иметь одно из следующих значений "MONTHLY","DAILY","WEEKLY".
с) третий параметр это размер лимита в мегабайтах .
в) четвертый параметр это ограничение по скорости в бит/сек.
Лимиты накладываются персонально на пользователя входящего в группу,
а не НА группу в целом.
В данном примере в Active Directory создана группа с именем traf200m
куда ключенны все пользователи кторым необходим данный лимит 200 Мбайт,
в месяц с входящей полосой 60000 бит/сек НА КАЖДОГО ПОЛЬЗОВАТЕЛЯ.
Пример:
ldaptrafgroup CN=traf200m,CN=Users,DC=domain,DC=ru MONTHLY 200 60000
Счетчики храняться для каждого пользователя в отдельном файле,имя которых
формируется, как имя пользователя и расширение lc. Сохранение счетчиков
происходит раз в минуту.
2.6 Комманда ldapdircount служит для указания директории куда будут
сохраняться файлы с пользовательскими счетчиками. Путь к директории
надо заканчивать слэшем, прямой или обратный в зависимости от ОС.
Пример:
ldapdircount c:\3proxy\counter\
ldapdircount /usr/3proxy/counter/
Настройка 3proxy
---------------------
# ВНИМАНИЕ ! Не забывайте что daemon или service должен идти первой строкой
# конфигурационного файла,то есть до загрузки любых плагинов
daemon
# для win32
plugin "с:\3proxy\ldapauth.dll" start
# для unix
plugin "/3proxy/libldapauth.so" start
ldapconnect 192.160.0.1 cn=ldap,cn=users,dc=domain,dc=ru ldap
ldapsbase cn=users,dc=domain,dc=ru
ldapaccess CN=internet,CN=Users,DC=domain,DC=ru
ldapuserenv cn=users,dc=domain,dc=ru
ldapdircount /3proxy/counter/
ldapattr cn memberof 1
ldaptrafgroup CN=traf200m,CN=Users,DC=domain,DC=ru MONTHLY 200 60000
ldaptrafgroup CN=traf60d,CN=Users,DC=domain,DC=ru DAILY 60 80000
ldaptrafgroup CN=traf100w,CN=Users,DC=domain,DC=ru WEEKLY 100 80000
auth ldap
allow * * * *
proxy -p3128 -n
--------------------
Так же возможна следующая конфигурация без учета трафика и ограничений
по скорости.
---------------------
service
plugin "с:\3proxy\ldapauth.dll" start
ldapconnect 192.160.0.1 cn=ldap,cn=users,dc=domain,dc=ru ldap
ldapsbase cn=users,dc=domain,dc=ru
ldapaccess CN=internet,CN=Users,DC=domain,DC=ru
ldapuserenv cn=users,dc=domain,dc=ru
ldapattr cn memberof 1
auth ldap
allow * * * *
proxy -p3128 -n
---------------------
Создание списков доступа
Чтобы можно было создавать ACL на основе списков пользователей входящих
в различные группы каталога ldap существует утилита getldapuser
Данной утилите могут переданы 5 параметров :
getldapuser < ldapserver basedn user_attribute filter user password >
ldapserver - имя или ip адрес LDAP сервера
basedn - контекст подключения к LDAP (например: cn=users,dc=domain,dc=com)
user_attribute - название пользовательского атрибута (например:
в Active Directory это cn в других LDAP каталогах он может
быт ou)
filter - фильтр по какому пользователи будут отбираться из LDAP (например:
для Active Directory вывести всех пользователей входящих в группу
internet будет следующая строка
(memberOf=cn=internet,cn=Users,dc=domain,dc=com) )
user - имя пользователя для подключения к серверу
password - пароль (если есть)
Пример использования getldapuser в 3proxy.
Необходимо дать доступ к icq только определенным пользоватлям . Cоздаем
в AD группу icquser заносим туда нужных пользователей.
Создаем bat файл следующего содержания который будет формировать файл
c:\3proxy\icquser со списком пользователей:
-------------------------------------------
getldapuser 192.168.0.1 dc=domain,dc=com cn (memberOf=cn=icquser,cn=Users,dc=domain,dc=com)
cn=admin,cn=users,dc=domain,dc=com password > c:\3proxy\icquser
-------------------------------------------
Вставляем данный bat файл на периодическое выполнение.
Далее прописываем 3proxy.cfg след строки
-------------------------------------------------
monitor "c:\3proxy\icquser"
auth ldap
allow $"c:\3proxy\icquser" * *icq.com
deny * * *icq.com
allow *
proxy -n
-------------------------------------------------
Компиляция плагина на различных ОС
1) Win32 (windows 98/NT/XP/2000/2003)
Для сборки и работы плагина в архиве с ним уже идут в каталоге ldapwindev
следующие библиотеки (версия 2.2.29).
libcrypto.dll
liblber.dll
libldap.dll
libssl.dll
и заголовочные файлы
lber.h
lber_types.h
ldap.h
ldap_cdefs.h
ldap_features.h
ldap_schema.h
ldap_utf8.h
Далее вам необходимо скачать и установить компилятор Dev-Cpp с сайта
http://www.bloodshed.net/dev/
Далее скачать исходные тексты 3proxy отсюда:
http://3proxy.ru/current/3proxy-0.6-devel.tgz и распаковать.
В каталог \src\plugins скопировать каталог с исходными текстами
плагина. Скорректировать com-win32.bat файл с учетом того где у Вас установлен
компилятор gcc , например:
-------------com-win32.bat----------------
c:\Dev-Cpp\bin\gcc -shared -o ldapauth.dll ldapauth.c -DWIN32 -I"./ldapwindev" -L"./ldapwindev" -lldap
------------------------------------------
И запустить на выполнение com-win32.bat после этого у Вас должна появится
библиотека ldapauth.dll и исполняемый файл getldapuser.exe .
Для дальнейшей работы получившиеся файлы и все библиотеки dll из каталога
ldapwindev скопировать в каталог с 3proxy.
2) xNIX (linux,freebsd и т.п. )
Перед компиляцией нужно проверить чтобы в системе был уcтановлен
OpenLDAP client. В системе должны присутвовать следующие
библиотеки:
liblber.a
libldap.a
liblber.so
libldap.so
и заголовочные файлы
lber.h
lber_types.h
ldap.h
ldap_cdefs.h
ldap_features.h
ldap_schema.h
ldap_utf8.h
Установка клиента под разными ОС это делается либо инсталяцией готового пакета
либо самостоятельная сборка данного клиента из исходных текстов которые
расположенны тут ftp://ftp.openldap.org/pub/OpenLDAP/openldap-release/
Чтобы собрать пакет, необходимо скачать архив
wget ftp://ftp.openldap.org/pub/OpenLDAP/openldap-release/openldap-2.3.9.tgz
распаковываем архив
tar xvzf openldap-2.3.9.tgz
и запускаем скрипт автоконфигурации со следующими
параметрами:
./configure --enable-backends=no --enable-slapd=no
далее
make
make install
Далее скачать исходные тексты 3proxy отсюда:
http://3proxy.ru/current/3proxy-0.6-devel.tgz и распаковать.
В каталог \src\plugins скопировать каталог с исходными текстами
плагина. Изменить пути в файле com-unix.sh параметрах компиляции -I и -L
к заголовочным и библиотечным файлам ldap для Вашей системы.
Выполнить следующие комманды:
chmod +x com-unix.sh
com-unix.sh
И запустить на выполнение com-unix.sh после этого у Вас должна появится
библиотека ldapauth.so и исполняемый файл getldapuser.
Получившиеся файлы скопировать в каталог с 3proxy.
----------------------------win1251------------------------------
----------------------------KOI8-R------------------------------
рМБЗЙО БХФЕОФЙЖЙЛБГЙЙ Ч LDAP ДМС УЕТЧЕТБ 3proxХ (пу windows,unix)
(c) Lopuchov Kirill lopuchov@mail.ru
1. лТБФЛПЕ ПРЙУБОЙЕ
* рПДДЕТЦЙЧБЕФУС ФПМШЛП БХФЕОФЙЖЙЛБГЙС ПФЛТЩФЩН ФЕЛУФПН (basic)
* рПДДЕТЦЙЧБЕФУС УПЪДБОЙЕ МЙНЙФПЧ РП ФТБЖЙЛХ ДМС ЗТХРР РПМШЪПЧБФЕМЕК
(Ч ДЕОШ,НЕУСГ,ОЕДЕМА)
* рПДДЕТЦЙЧБЕФУС УПЪДБОЙЕ МЙНЙФПЧ РП УЛПТПУФЙ ДМС ЗТХРР РПМШЪПЧБФЕМЕК
(РПЛБ МЙНЙФЩ ФПМШЛП ОБ ЧИПДСЭЙК ФТБЖЙЛ)
* пФУХФcФЧХЕФ ЛЕЫЙТПЧБОЙЕ ЙНЕО РПМШЪПЧБФЕМЕК.
ч ЛБЮЕУФЧЕ ЙОФЕТЖЕКУБ ДПУФХРБ Л ldap ЙУРПМШЪХЕФУС ВЙВМЙПФЕЛБ openldap,
РПЬФПНХ РМБЗЙО НПЦЕФ ЛПНРЙМЙТПЧБФШУС Й ТБВПФБФШ ЛБЛ ОБ Windows 98/2000/XP
ФБЛ Й ОБ ТБЪМЙЮОЩИ unix РПДПВОЩИ УЙУФЕНБИ ОБРТЙНЕТ Linux,FreeBSD.
чУЕ ФЕУФЩ ТБВПФПУРПУПВОПУФЙ РТПЧПДЙМЙУШ ОБ УЕТЧЕТЕ У Active Directory Ч
ЕЕ ТЕБМЙЪБГЙЙ ldap ОП Ч РТЙОГЙРЕ ДПМЦОП ТБВПФБФШ Й ОБ ДТХЗЙИ ldap УЙУФЕНБИ.
дМС ЛПНРЙМСГЙЙ Й ФЕУФЙТПЧБОЙС РПД пу Windows ЙУРПМШЪПЧБМУС РБЛЕФ Dev-C++
http://www.bloodshed.net/dev/ Й ЮБУФШ ВЙВМЙПФЕЛ OpenLDAP for Windows
http://lucas.bergmans.us/hacks/openldap/
ЧЕТУЙС openldap-2.2.29-db-4.3.29-openssl-0.9.8a-win32_Setup.exe,
ЧЕТУЙС ЬФПК ЦЕ ВЙВМЙПФЕЛЙ ЙДЕФ Ч ЛПНРМЕЛФЕ Л РМБЗЙОХ.
РПД unix РПДПВОПК пу (Freebsd) ЙУРПМШЪПЧБМУС УФБОДБТФОЩК gcc.
Й ВЙВМЙПФЕЛЙ openldap-client.
!!!! чОЙНБОЙЕ РТЙ ТБВПФЕ РМБЗЙОБ ЧПЪНПЦОБ ХФЕЮЛБ РБНСФЙ !!!!
х НЕОС ОБ Win 2000 Serv Й ПЛПМБ 600 РПМШЪПЧБФЕМСИ РТЙ ЛБОБМЕ 500 ЛВЙФ/УЕЛ .
РТПГЕУУ 3proxy ЪБ УХФЛЙ ЧЩТПУФБЕФ ДП 40 НВ . мЕЮЙФУС ТЕУФБТФПН УЕТЧЙУБ.
еУМЙ ЛФП ФП ЪОБЕФ ИПТПЫП Open Ldap api Й НПЦЕФ ХЛБЪБФШ ОБ ПЫЙВЛХ Ч РМБЗЙОЕ
У ТБДПУФША ЧЩУМХЫБА :) .
2. оБУФТПКЛБ РМБЗЙОБ.
2.1 дМС РПДЛМАЮЕОЙС Л LDAP УЕТЧЕТХ ЙУРПМШЪХЕФУС ЛПННБОДБ ldapconnect .
рЕТЧЩК РБТБНЕФТ ПРТЕДЕМСФ ip БДТЕУ ЙМЙ host ЙНС LDAP УЕТЧЕТБ ,
ЧФПТПК РБТБНЕФТ ЙНС РПМШЪПЧБФЕМС ПФ ЙНЕОЙ ЛПТПЗП ВХДХФ УПЧЕТЫЙФШУС
ЧУС ДБМШОЕКЫБС ТБВПФБ У ldap ЛБФБМПЗПН ФБЛБС ЛБЛ РПЙУЛ РПМШЪПЧБФЕМЕК
Й РТПЧЕТЛБ ЙИ РТЙОБДМЕЦОПУФЙ Л ФПК ЙМЙ ЙОПК ЗТХРРЕ, ФТЕФЙК РБТБНЕФТ ЬФП
РБТПМШ ДМС ЬФПЗП РПМШЪПЧБФЕМС.
х ФБЛПЗП РПМШЪПЧБФЕ Ч ЛПОФЕЛУФЕФ Active Directory НПЗХФ ПФУХФУЧПЧБФШ
РТБЧБ БДНЙОЙУФТБФПТБ ДМС ОПТНБМШОПК ТБВПФЩ РМБЗЙОБ. ч ЛМБУУЙЮЕУЛЙИ Open Ldap
УЕТЧЕТБИ РПД xNIX ФБЛЙН РПМШЪПЧБФЕМЕН НПЦЕФ ЧЩУФХРБФШ anonymous.
рТЙНЕТ:
ldapconnect 192.160.0.1 cn=ldap,cn=users,dc=domain,dc=ru ldap
2.2 дМС ПРТЕДЕМЕОЙС Ч ЛБЛПН ЛПОФЕЛУФЕ ЙУЛБФШ РПМШЪПЧБФЕМЕК Й ЗТХРРЩ
УМХЦЙФ ЛПННБОДБ ldapsbase
рТЙНЕТ:
ldapsbase cn=users,dc=domain,dc=ru
2.3 лПННБОДБ ldapattr УМХЦЙФ ДМС ПРТЕДЕМОЙС ТБЪМЙЮОЩИ РБТБНЕФТПЧ РМБЗЙОБ.
a)РЕТЧЩК РБТБНЕФТ ПРТЕДЕМСЕФ БФТЙВХФ "РПМШЪПЧБФЕМШ" Ч ЛПОФЕЛУФЕ ldap ЛБФБМПЗБ
Ч Active Directory ЬФП ЛБЛ РТБЧЙМП "cn" , Ч ДТХЗЙИ ldap УЕТЧЕТБИ "uid".
b)ЧФПТПК РБТБНЕФТ ПРЕТЕДЕМСЕФ БФТЙВХФ "ЗТХРРБ" Ч ЛПОФЕЛУФЕ ldap ЛБФБМПЗБ
Ч Active Directory ЬФП ЛБЛ РТБЧЙМП "memberof" , Ч ДТХЗЙИ ldap УЕТЧЕТБИ "ou".
c)ФТЕФЙК РБТБНЕФТ НПЦЕФ ОЕ ПВСЪБФЕМШОЩК Й НПЦЕФ УПДЕТЦБФШ 0 ЙМЙ 1
1 - ПЪОБЮБЕФ, ЮФП РТЙ БЧФПТЙЪБГЙЙ РПМШЪПЧБФЕМС ЙМЙ УПЪДБОЙЙ ДМС ОЕЗП
ПТЗТБОЙЮЕОЙС РП ФТБЖЙЛХ ЕЗП ЙНС ВХДЕФ РТЙЧПДЙФУС Л ОЙЦОЕНХ ТЕЗЙУФТХ
(РТЙНЕЮБОЙЕ: ФПМШЛП ДМС ЙНЕО РПМШЪПЧБФЕМЕК ОБ БОЗМЙКУЛПН) .
ьФПФ РБТБНЕФТ УПЪДБО ДМС ЙУЛМАЮЕОЙС УМХЮБЕЧ ЛПЗДБ LDAP ЛБФБМПЗ РТЙ
БЧФПТЙЪБГЙЙ ОЕ ПФМЙЮБЕФ ЙНЕО РПМШЪПЧБФЕМЕК Ч ТЕЗЙУФТБИ.
рТЙНЕТ:
ldapattr cn memberof 1
2.4 лПННБОДБ ldapaccess УМХЦЙФ ДМС ПРТЕДЕМЕОЙС "РТЙЪОБЛБ" ДПУФХРОПУФЙ
РПМШЪПЧБФЕМА ЧППВЭЕ РТПКФЙ БЧФПТЙЪБГЙА ОБ proxy УЕТЧЕТЕ. ч ЛПОФЕЛУФЕ
ldap ЛБФБМПЗБ ЬФП ъобюеойе БФТЙВХФБ "ЗТХРРЩ" ПРЙУБООПК Ч ЛПННБОДЕ ldapattr.
рТЙНЕТ:
ldapaccess CN=internet,CN=Users,DC=domain,DC=ru
оБРТЙНЕТ: ДМС Active Directory ЬФП ВХДЕФ РПМШЪПЧБФЕМШ ЧИПДСЭЙК Ч ЗТХРРХ
internet. фПЕУФШ РТЙ РТПЧЕТЛЕ НПЦОП МЙ РПМШЪПЧБФЕМА ТБВПФБФШ У proxy
ЖПТНЙТХЕФУС ЖЙМШФТ ПО ДПМЦЕО РПРБУФШ Ч УМЕДХАЭЙК ЖЙМШФТ:
(&(cn=ЙНСРПМШЪПЧБФЕМС)(memberof=CN=internet,CN=Users,DC=domain,DC=ru))
2.5 лПННБОДБ ldapuserenv УМХЦЙФ ДМС ЖПТНЙТПЧБОЙС УФТПЛЙ ЙНЕОЙ РПМШЪПЧБФЕМС
ЛПФПТЩК РЩФБЕФУС РТПКФЙ БЧФПТЙЪБГЙА Ч ldap. фПЕУФШ ЖБЛФЙЮЕУЛЙ ЬФП base DN
ДМС РПМШЪПЧБФЕМС.
рТЙНЕТ:
ldapuserenv cn=users,dc=domain,dc=ru
2.7 лПННБОДБ ldaptrafgroup УМХЦЙФ ДМС УПЪДБОЙС МЙНЙФПЧ
пой пвсъбфемшоп дпмцоб йдфй рпуме чуеи ПУФБМШОЩИ ЛПННБОД РМБЗЙОБ.
a) РЕТЧЩК РБТБНЕФТ ЬФП ОБЪЧБОЙЕ ЗТХРРЩ (ЪОБЮЕОЙЕ ldap БФТЙВХФБ ) Ч ЛПФПТХА
ЧИПДЙФ РПМШЪПЧБФЕМШ.
b) ЧФПТПК РБТБНЕФТ ОБ ЛБЛПК РЕТЙПД ОБЛМБДЩЧБЕФУС ПЗТБОЙЮЕОЙЕ РП ПВЯЕНХ
ФТБЖЙЛБ . нПЦЕФ ЙНЕФШ ПДОП ЙЪ УМЕДХАЭЙИ ЪОБЮЕОЙК "MONTHLY","DAILY","WEEKLY".
У) ФТЕФЙК РБТБНЕФТ ЬФП ТБЪНЕТ МЙНЙФБ Ч НЕЗБВБКФБИ .
Ч) ЮЕФЧЕТФЩК РБТБНЕФТ ЬФП ПЗТБОЙЮЕОЙЕ РП УЛПТПУФЙ Ч ВЙФ/УЕЛ.
мЙНЙФЩ ОБЛМБДЩЧБАФУС РЕТУПОБМШОП ОБ РПМШЪПЧБФЕМС ЧИПДСЭЕЗП Ч ЗТХРРХ,
Б ОЕ об ЗТХРРХ Ч ГЕМПН.
ч ДБООПН РТЙНЕТЕ Ч Active Directory УПЪДБОБ ЗТХРРБ У ЙНЕОЕН traf200m
ЛХДБ ЛМАЮЕООЩ ЧУЕ РПМШЪПЧБФЕМЙ ЛФПТЩН ОЕПВИПДЙН ДБООЩК МЙНЙФ 200 нВБКФ,
Ч НЕУСГ У ЧИПДСЭЕК РПМПУПК 60000 ВЙФ/УЕЛ об лбцдпзп рпмшъпчбфемс.
рТЙНЕТ:
ldaptrafgroup CN=traf200m,CN=Users,DC=domain,DC=ru MONTHLY 200 60000
уЮЕФЮЙЛЙ ИТБОСФШУС ДМС ЛБЦДПЗП РПМШЪПЧБФЕМС Ч ПФДЕМШОПН ЖБКМЕ,ЙНС ЛПФПТЩИ
ЖПТНЙТХЕФУС, ЛБЛ ЙНС РПМШЪПЧБФЕМС Й ТБУЫЙТЕОЙЕ lc. уПИТБОЕОЙЕ УЮЕФЮЙЛПЧ
РТПЙУИПДЙФ ТБЪ Ч НЙОХФХ.
2.6 лПННБОДБ ldapdircount УМХЦЙФ ДМС ХЛБЪБОЙС ДЙТЕЛФПТЙЙ ЛХДБ ВХДХФ
УПИТБОСФШУС ЖБКМЩ У РПМШЪПЧБФЕМШУЛЙНЙ УЮЕФЮЙЛБНЙ. рХФШ Л ДЙТЕЛФПТЙЙ
ОБДП ЪБЛБОЮЙЧБФШ УМЬЫЕН, РТСНПК ЙМЙ ПВТБФОЩК Ч ЪБЧЙУЙНПУФЙ ПФ пу.
рТЙНЕТ:
ldapdircount c:\3proxy\counter\
ldapdircount /usr/3proxy/counter/
оБУФТПКЛБ 3proxy
---------------------
# чойнбойе ! оЕ ЪБВЩЧБКФЕ ЮФП daemon ЙМЙ service ДПМЦЕО ЙДФЙ РЕТЧПК УФТПЛПК
# ЛПОЖЙЗХТБГЙПООПЗП ЖБКМБ,ФП ЕУФШ ДП ЪБЗТХЪЛЙ МАВЩИ РМБЗЙОПЧ
daemon
# ДМС win32
plugin "У:\3proxy\ldapauth.dll" start
# ДМС unix
plugin "/3proxy/libldapauth.so" start
ldapconnect 192.160.0.1 cn=ldap,cn=users,dc=domain,dc=ru ldap
ldapsbase cn=users,dc=domain,dc=ru
ldapaccess CN=internet,CN=Users,DC=domain,DC=ru
ldapuserenv cn=users,dc=domain,dc=ru
ldapdircount /3proxy/counter/
ldapattr cn memberof 1
ldaptrafgroup CN=traf200m,CN=Users,DC=domain,DC=ru MONTHLY 200 60000
ldaptrafgroup CN=traf60d,CN=Users,DC=domain,DC=ru DAILY 60 80000
ldaptrafgroup CN=traf100w,CN=Users,DC=domain,DC=ru WEEKLY 100 80000
auth ldap
allow * * * *
proxy -p3128 -n
--------------------
фБЛ ЦЕ ЧПЪНПЦОБ УМЕДХАЭБС ЛПОЖЙЗХТБГЙС ВЕЪ ХЮЕФБ ФТБЖЙЛБ Й ПЗТБОЙЮЕОЙК
РП УЛПТПУФЙ.
---------------------
service
plugin "У:\3proxy\ldapauth.dll" start
ldapconnect 192.160.0.1 cn=ldap,cn=users,dc=domain,dc=ru ldap
ldapsbase cn=users,dc=domain,dc=ru
ldapaccess CN=internet,CN=Users,DC=domain,DC=ru
ldapuserenv cn=users,dc=domain,dc=ru
ldapattr cn memberof 1
auth ldap
allow * * * *
proxy -p3128 -n
---------------------
уПЪДБОЙЕ УРЙУЛПЧ ДПУФХРБ
юФПВЩ НПЦОП ВЩМП УПЪДБЧБФШ ACL ОБ ПУОПЧЕ УРЙУЛПЧ РПМШЪПЧБФЕМЕК ЧИПДСЭЙИ
Ч ТБЪМЙЮОЩЕ ЗТХРРЩ ЛБФБМПЗБ ldap УХЭЕУФЧХЕФ ХФЙМЙФБ getldapuser
дБООПК ХФЙМЙФЕ НПЗХФ РЕТЕДБОЩ 5 РБТБНЕФТПЧ :
getldapuser < ldapserver basedn user_attribute filter user password >
ldapserver - ЙНС ЙМЙ ip БДТЕУ LDAP УЕТЧЕТБ
basedn - ЛПОФЕЛУФ РПДЛМАЮЕОЙС Л LDAP (ОБРТЙНЕТ: cn=users,dc=domain,dc=com)
user_attribute - ОБЪЧБОЙЕ РПМШЪПЧБФЕМШУЛПЗП БФТЙВХФБ (ОБРТЙНЕТ:
Ч Active Directory ЬФП cn Ч ДТХЗЙИ LDAP ЛБФБМПЗБИ ПО НПЦЕФ
ВЩФ ou)
filter - ЖЙМШФТ РП ЛБЛПНХ РПМШЪПЧБФЕМЙ ВХДХФ ПФВЙТБФШУС ЙЪ LDAP (ОБРТЙНЕТ:
ДМС Active Directory ЧЩЧЕУФЙ ЧУЕИ РПМШЪПЧБФЕМЕК ЧИПДСЭЙИ Ч ЗТХРРХ
internet ВХДЕФ УМЕДХАЭБС УФТПЛБ
(memberOf=cn=internet,cn=Users,dc=domain,dc=com) )
user - ЙНС РПМШЪПЧБФЕМС ДМС РПДЛМАЮЕОЙС Л УЕТЧЕТХ
password - РБТПМШ (ЕУМЙ ЕУФШ)
рТЙНЕТ ЙУРПМШЪПЧБОЙС getldapuser Ч 3proxy.
оЕПВИПДЙНП ДБФШ ДПУФХР Л icq ФПМШЛП ПРТЕДЕМЕООЩН РПМШЪПЧБФМСН . CПЪДБЕН
Ч AD ЗТХРРХ icquser ЪБОПУЙН ФХДБ ОХЦОЩИ РПМШЪПЧБФЕМЕК.
уПЪДБЕН bat ЖБКМ УМЕДХАЭЕЗП УПДЕТЦБОЙС ЛПФПТЩК ВХДЕФ ЖПТНЙТПЧБФШ ЖБКМ
c:\3proxy\icquser УП УРЙУЛПН РПМШЪПЧБФЕМЕК:
-------------------------------------------
getldapuser 192.168.0.1 dc=domain,dc=com cn (memberOf=cn=icquser,cn=Users,dc=domain,dc=com)
cn=admin,cn=users,dc=domain,dc=com password > c:\3proxy\icquser
-------------------------------------------
чУФБЧМСЕН ДБООЩК bat ЖБКМ ОБ РЕТЙПДЙЮЕУЛПЕ ЧЩРПМОЕОЙЕ.
дБМЕЕ РТПРЙУЩЧБЕН 3proxy.cfg УМЕД УФТПЛЙ
-------------------------------------------------
monitor "c:\3proxy\icquser"
auth ldap
allow $"c:\3proxy\icquser" * *icq.com
deny * * *icq.com
allow *
proxy -n
-------------------------------------------------
лПНРЙМСГЙС РМБЗЙОБ ОБ ТБЪМЙЮОЩИ пу
1) Win32 (windows 98/NT/XP/2000/2003)
дМС УВПТЛЙ Й ТБВПФЩ РМБЗЙОБ Ч БТИЙЧЕ У ОЙН ХЦЕ ЙДХФ Ч ЛБФБМПЗЕ ldapwindev
УМЕДХАЭЙЕ ВЙВМЙПФЕЛЙ (ЧЕТУЙС 2.2.29).
libcrypto.dll
liblber.dll
libldap.dll
libssl.dll
Й ЪБЗПМПЧПЮОЩЕ ЖБКМЩ
lber.h
lber_types.h
ldap.h
ldap_cdefs.h
ldap_features.h
ldap_schema.h
ldap_utf8.h
дБМЕЕ ЧБН ОЕПВИПДЙНП УЛБЮБФШ Й ХУФБОПЧЙФШ ЛПНРЙМСФПТ Dev-Cpp У УБКФБ
http://www.bloodshed.net/dev/
дБМЕЕ УЛБЮБФШ ЙУИПДОЩЕ ФЕЛУФЩ 3proxy ПФУАДБ:
http://3proxy.ru/current/3proxy-0.6-devel.tgz Й ТБУРБЛПЧБФШ.
ч ЛБФБМПЗ \src\plugins УЛПРЙТПЧБФШ ЛБФБМПЗ У ЙУИПДОЩНЙ ФЕЛУФБНЙ
РМБЗЙОБ. уЛПТТЕЛФЙТПЧБФШ com-win32.bat ЖБКМ У ХЮЕФПН ФПЗП ЗДЕ Х чБУ ХУФБОПЧМЕО
ЛПНРЙМСФПТ gcc , ОБРТЙНЕТ:
-------------com-win32.bat----------------
c:\Dev-Cpp\bin\gcc -shared -o ldapauth.dll ldapauth.c -DWIN32 -I"./ldapwindev" -L"./ldapwindev" -lldap
------------------------------------------
й ЪБРХУФЙФШ ОБ ЧЩРПМОЕОЙЕ com-win32.bat РПУМЕ ЬФПЗП Х чБУ ДПМЦОБ РПСЧЙФУС
ВЙВМЙПФЕЛБ ldapauth.dll Й ЙУРПМОСЕНЩК ЖБКМ getldapuser.exe .
дМС ДБМШОЕКЫЕК ТБВПФЩ РПМХЮЙЧЫЙЕУС ЖБКМЩ Й ЧУЕ ВЙВМЙПФЕЛЙ dll ЙЪ ЛБФБМПЗБ
ldapwindev УЛПРЙТПЧБФШ Ч ЛБФБМПЗ У 3proxy.
2) xNIX (linux,freebsd Й Ф.Р. )
рЕТЕД ЛПНРЙМСГЙЕК ОХЦОП РТПЧЕТЙФШ ЮФПВЩ Ч УЙУФЕНЕ ВЩМ ХcФБОПЧМЕО
OpenLDAP client. ч УЙУФЕНЕ ДПМЦОЩ РТЙУХФЧПЧБФШ УМЕДХАЭЙЕ
ВЙВМЙПФЕЛЙ:
liblber.a
libldap.a
liblber.so
libldap.so
Й ЪБЗПМПЧПЮОЩЕ ЖБКМЩ
lber.h
lber_types.h
ldap.h
ldap_cdefs.h
ldap_features.h
ldap_schema.h
ldap_utf8.h
хУФБОПЧЛБ ЛМЙЕОФБ РПД ТБЪОЩНЙ пу ЬФП ДЕМБЕФУС МЙВП ЙОУФБМСГЙЕК ЗПФПЧПЗП РБЛЕФБ
МЙВП УБНПУФПСФЕМШОБС УВПТЛБ ДБООПЗП ЛМЙЕОФБ ЙЪ ЙУИПДОЩИ ФЕЛУФПЧ ЛПФПТЩЕ
ТБУРПМПЦЕООЩ ФХФ ftp://ftp.openldap.org/pub/OpenLDAP/openldap-release/
юФПВЩ УПВТБФШ РБЛЕФ, ОЕПВИПДЙНП УЛБЮБФШ БТИЙЧ
wget ftp://ftp.openldap.org/pub/OpenLDAP/openldap-release/openldap-2.3.9.tgz
ТБУРБЛПЧЩЧБЕН БТИЙЧ
tar xvzf openldap-2.3.9.tgz
Й ЪБРХУЛБЕН УЛТЙРФ БЧФПЛПОЖЙЗХТБГЙЙ УП УМЕДХАЭЙНЙ
РБТБНЕФТБНЙ:
./configure --enable-backends=no --enable-slapd=no
ДБМЕЕ
make
make install
дБМЕЕ УЛБЮБФШ ЙУИПДОЩЕ ФЕЛУФЩ 3proxy ПФУАДБ:
http://3proxy.ru/current/3proxy-0.6-devel.tgz Й ТБУРБЛПЧБФШ.
ч ЛБФБМПЗ \src\plugins УЛПРЙТПЧБФШ ЛБФБМПЗ У ЙУИПДОЩНЙ ФЕЛУФБНЙ
РМБЗЙОБ. йЪНЕОЙФШ РХФЙ Ч ЖБКМЕ com-unix.sh РБТБНЕФТБИ ЛПНРЙМСГЙЙ -I Й -L
Л ЪБЗПМПЧПЮОЩН Й ВЙВМЙПФЕЮОЩН ЖБКМБН ldap ДМС чБЫЕК УЙУФЕНЩ.
чЩРПМОЙФШ УМЕДХАЭЙЕ ЛПННБОДЩ:
chmod +x com-unix.sh
com-unix.sh
й ЪБРХУФЙФШ ОБ ЧЩРПМОЕОЙЕ com-unix.sh РПУМЕ ЬФПЗП Х чБУ ДПМЦОБ РПСЧЙФУС
ВЙВМЙПФЕЛБ ldapauth.so Й ЙУРПМОСЕНЩК ЖБКМ getldapuser.
рПМХЮЙЧЫЙЕУС ЖБКМЩ УЛПРЙТПЧБФШ Ч ЛБФБМПЗ У 3proxy.
----------------------------KOI8-R------------------------------
+2
View File
@@ -0,0 +1,2 @@
/pcre_plugin.c/1.11/Wed Apr 25 18:17:22 2012//
D
+1
View File
@@ -0,0 +1 @@
3proxy-0.5a/src/plugins/PCREPlugin
+1
View File
@@ -0,0 +1 @@
/cygdrive/m/MEDIA/H/CVS
+1
View File
@@ -0,0 +1 @@
include Makefile.var
+71
View File
@@ -0,0 +1,71 @@
all: $(BUILDDIR)PCREPlugin$(DLSUFFICS)
pcre_compile$(OBJSUFFICS): pcre_compile.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_compile.c
pcre_config$(OBJSUFFICS): pcre_config.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_config.c
pcre_dfa_exec$(OBJSUFFICS): pcre_dfa_exec.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_dfa_exec.c
pcre_exec$(OBJSUFFICS): pcre_exec.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_exec.c
pcre_fullinfo$(OBJSUFFICS): pcre_fullinfo.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_fullinfo.c
pcre_get$(OBJSUFFICS): pcre_get.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_get.c
pcre_globals$(OBJSUFFICS): pcre_globals.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_globals.c
pcre_info$(OBJSUFFICS): pcre_info.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_info.c
pcre_maketables$(OBJSUFFICS): pcre_maketables.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_maketables.c
pcre_newline$(OBJSUFFICS): pcre_newline.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_newline.c
pcre_ord2utf8$(OBJSUFFICS): pcre_ord2utf8.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_ord2utf8.c
pcre_refcount$(OBJSUFFICS): pcre_refcount.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_refcount.c
pcre_study$(OBJSUFFICS): pcre_study.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_study.c
pcre_tables$(OBJSUFFICS): pcre_tables.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_tables.c
pcre_try_flipped$(OBJSUFFICS): pcre_try_flipped.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_try_flipped.c
pcre_ucp_searchfuncs$(OBJSUFFICS): pcre_ucp_searchfuncs.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_ucp_searchfuncs.c
pcre_valid_utf8$(OBJSUFFICS): pcre_valid_utf8.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_valid_utf8.c
pcre_version$(OBJSUFFICS): pcre_version.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_version.c
pcre_xclass$(OBJSUFFICS): pcre_xclass.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_xclass.c
pcre_dftables$(OBJSUFFICS): pcre_dftables.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_dftables.c
pcre_plugin$(OBJSUFFICS): pcre_plugin.c
$(CC) $(DCFLAGS) $(CFLAGS) pcre_plugin.c
pcreposix$(OBJSUFFICS): pcreposix.c
$(CC) $(DCFLAGS) $(CFLAGS) pcreposix.c
$(BUILDDIR)PCREPlugin$(DLSUFFICS): pcre_compile$(OBJSUFFICS) pcre_config$(OBJSUFFICS) pcre_dfa_exec$(OBJSUFFICS) pcre_exec$(OBJSUFFICS) pcre_fullinfo$(OBJSUFFICS) pcre_get$(OBJSUFFICS) pcre_globals$(OBJSUFFICS) pcre_info$(OBJSUFFICS) pcre_maketables$(OBJSUFFICS) pcre_newline$(OBJSUFFICS) pcre_ord2utf8$(OBJSUFFICS) pcre_refcount$(OBJSUFFICS) pcre_study$(OBJSUFFICS) pcre_tables$(OBJSUFFICS) pcre_try_flipped$(OBJSUFFICS) pcre_ucp_searchfuncs$(OBJSUFFICS) pcre_valid_utf8$(OBJSUFFICS) pcre_version$(OBJSUFFICS) pcre_xclass$(OBJSUFFICS) pcre_dftables$(OBJSUFFICS) pcre_plugin$(OBJSUFFICS) pcreposix$(OBJSUFFICS)
$(LN) $(LNOUT)../../$(BUILDDIR)PCREPlugin$(DLSUFFICS) $(LDFLAGS) $(DLFLAGS) pcre_compile$(OBJSUFFICS) pcre_config$(OBJSUFFICS) pcre_dfa_exec$(OBJSUFFICS) pcre_exec$(OBJSUFFICS) pcre_fullinfo$(OBJSUFFICS) pcre_get$(OBJSUFFICS) pcre_globals$(OBJSUFFICS) pcre_info$(OBJSUFFICS) pcre_maketables$(OBJSUFFICS) pcre_newline$(OBJSUFFICS) pcre_ord2utf8$(OBJSUFFICS) pcre_refcount$(OBJSUFFICS) pcre_study$(OBJSUFFICS) pcre_tables$(OBJSUFFICS) pcre_try_flipped$(OBJSUFFICS) pcre_ucp_searchfuncs$(OBJSUFFICS) pcre_valid_utf8$(OBJSUFFICS) pcre_version$(OBJSUFFICS) pcre_xclass$(OBJSUFFICS) pcre_dftables$(OBJSUFFICS) pcre_plugin$(OBJSUFFICS) pcreposix$(OBJSUFFICS)
+37
View File
@@ -0,0 +1,37 @@
VERFILE = version.obj ../3proxy.RES
#$Id: Makefile.msvc,v 1.17 2010-11-11 14:44:11 v.dubrovin Exp $
#
# 3 proxy Makefile for Microsoft Visual C compiler (for both make and nmake)
#
# You can try to remove -DWITH_STD_MALLOC to CFLAGS to use optimized malloc
# libraries
#
# Add /DSAFESQL to CFLAGS if you are using poorely written/tested ODBC driver
BUILDDIR = ../bin/
CC = cl
CFLAGS = /nologo /MT /W3 /Ox /GS /EHs- /GA /GF /D "MSVC" /D "WITH_STD_MALLOC" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "_WIN32" /Fp"proxy.pch" /FD /c
COUT = /Fo
LN = link
LDFLAGS = /nologo /subsystem:console /incremental:no /machine:I386
DLFLAGS = /DLL
DLSUFFICS = .dll
LIBS = ws2_32.lib advapi32.lib odbc32.lib user32.lib kernel32.lib Gdi32.lib libeay32MT.lib ssleay32MT.lib
LIBEXT = .lib
LNOUT = /out:
EXESUFFICS = .exe
OBJSUFFICS = .obj
DEFINEOPTION = /D
COMPFILES = *.pch *.idb
REMOVECOMMAND = del 2>NUL >NUL
TYPECOMMAND = type
COMPATLIBS =
MAKEFILE = Makefile.msvc
PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin lastFripper FilePlugin
include Makefile.inc
allplugins:
for /D %%i in ($(PLUGINS)) do (copy Makefile plugins\%%i && copy Makefile.var plugins\%%i && cd plugins\%%i && nmake && del *.obj *.idb &&cd ..\..)
+145
View File
@@ -0,0 +1,145 @@
/* On Unix-like systems config.in is converted by "configure" into config.h.
Some other environments also support the use of "configure". PCRE is written in
Standard C, but there are a few non-standard things it can cope with, allowing
it to run on SunOS4 and other "close to standard" systems.
On a non-Unix-like system you should just copy this file into config.h, and set
up the macros the way you need them. You should normally change the definitions
of HAVE_STRERROR and HAVE_MEMMOVE to 1. Unfortunately, because of the way
autoconf works, these cannot be made the defaults. If your system has bcopy()
and not memmove(), change the definition of HAVE_BCOPY instead of HAVE_MEMMOVE.
If your system has neither bcopy() nor memmove(), leave them both as 0; an
emulation function will be used. */
/* If you are compiling for a system that uses EBCDIC instead of ASCII
character codes, define this macro as 1. On systems that can use "configure",
this can be done via --enable-ebcdic. */
#ifndef EBCDIC
#define EBCDIC 0
#endif
#define PCRE_STATIC
/* If you are compiling for a system other than a Unix-like system or Win32,
and it needs some magic to be inserted before the definition of a function that
is exported by the library, define this macro to contain the relevant magic. If
you do not define this macro, it defaults to "extern" for a C compiler and
"extern C" for a C++ compiler on non-Win32 systems. This macro apears at the
start of every exported function that is part of the external API. It does not
appear on functions that are "external" in the C sense, but which are internal
to the library. */
/* #define PCRE_DATA_SCOPE */
/* Define the following macro to empty if the "const" keyword does not work. */
#undef const
/* Define the following macro to "unsigned" if <stddef.h> does not define
size_t. */
#undef size_t
/* The following two definitions are mainly for the benefit of SunOS4, which
does not have the strerror() or memmove() functions that should be present in
all Standard C libraries. The macros HAVE_STRERROR and HAVE_MEMMOVE should
normally be defined with the value 1 for other systems, but unfortunately we
cannot make this the default because "configure" files generated by autoconf
will only change 0 to 1; they won't change 1 to 0 if the functions are not
found. */
#define HAVE_STRERROR 0
#define HAVE_MEMMOVE 0
/* There are some non-Unix-like systems that don't even have bcopy(). If this
macro is false, an emulation is used. If HAVE_MEMMOVE is set to 1, the value of
HAVE_BCOPY is not relevant. */
#define HAVE_BCOPY 0
/* The value of NEWLINE determines the newline character. The default is to
leave it up to the compiler, but some sites want to force a particular value.
On Unix-like systems, "configure" can be used to override this default. */
#ifndef NEWLINE
#define NEWLINE '\n'
#endif
/* The value of LINK_SIZE determines the number of bytes used to store links as
offsets within the compiled regex. The default is 2, which allows for compiled
patterns up to 64K long. This covers the vast majority of cases. However, PCRE
can also be compiled to use 3 or 4 bytes instead. This allows for longer
patterns in extreme cases. On systems that support it, "configure" can be used
to override this default. */
#ifndef LINK_SIZE
#define LINK_SIZE 2
#endif
/* When calling PCRE via the POSIX interface, additional working storage is
required for holding the pointers to capturing substrings because PCRE requires
three integers per substring, whereas the POSIX interface provides only two. If
the number of expected substrings is small, the wrapper function uses space on
the stack, because this is faster than using malloc() for each call. The
threshold above which the stack is no longer used is defined by POSIX_MALLOC_
THRESHOLD. On systems that support it, "configure" can be used to override this
default. */
#ifndef POSIX_MALLOC_THRESHOLD
#define POSIX_MALLOC_THRESHOLD 10
#endif
/* PCRE uses recursive function calls to handle backtracking while matching.
This can sometimes be a problem on systems that have stacks of limited size.
Define NO_RECURSE to get a version that doesn't use recursion in the match()
function; instead it creates its own stack by steam using pcre_recurse_malloc()
to obtain memory from the heap. For more detail, see the comments and other
stuff just above the match() function. On systems that support it, "configure"
can be used to set this in the Makefile (use --disable-stack-for-recursion). */
/* #define NO_RECURSE */
/* The value of MATCH_LIMIT determines the default number of times the internal
match() function can be called during a single execution of pcre_exec(). There
is a runtime interface for setting a different limit. The limit exists in order
to catch runaway regular expressions that take for ever to determine that they
do not match. The default is set very large so that it does not accidentally
catch legitimate cases. On systems that support it, "configure" can be used to
override this default default. */
#ifndef MATCH_LIMIT
#define MATCH_LIMIT 10000000
#endif
/* The above limit applies to all calls of match(), whether or not they
increase the recursion depth. In some environments it is desirable to limit the
depth of recursive calls of match() more strictly, in order to restrict the
maximum amount of stack (or heap, if NO_RECURSE is defined) that is used. The
value of MATCH_LIMIT_RECURSION applies only to recursive calls of match(). To
have any useful effect, it must be less than the value of MATCH_LIMIT. There is
a runtime method for setting a different limit. On systems that support it,
"configure" can be used to override this default default. */
#ifndef MATCH_LIMIT_RECURSION
#define MATCH_LIMIT_RECURSION MATCH_LIMIT
#endif
/* These three limits are parameterized just in case anybody ever wants to
change them. Care must be taken if they are increased, because they guard
against integer overflow caused by enormously large patterns. */
#ifndef MAX_NAME_SIZE
#define MAX_NAME_SIZE 32
#endif
#ifndef MAX_NAME_COUNT
#define MAX_NAME_COUNT 10000
#endif
#ifndef MAX_DUPLENGTH
#define MAX_DUPLENGTH 30000
#endif
/* End */
+304
View File
@@ -0,0 +1,304 @@
#include "config.h"
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* This is the public header file for the PCRE library, to be #included by
applications that call the PCRE functions.
Copyright (c) 1997-2007 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
#ifndef _PCRE_H
#define _PCRE_H
/* The current PCRE version information. */
#define PCRE_MAJOR 7
#define PCRE_MINOR 4
#define PCRE_PRERELEASE
#define PCRE_DATE 2007-09-21
/* When an application links to a PCRE DLL in Windows, the symbols that are
imported have to be identified as such. When building PCRE, the appropriate
export setting is defined in pcre_internal.h, which includes this file. So we
don't change existing definitions of PCRE_EXP_DECL and PCRECPP_EXP_DECL. */
#if defined(_WIN32) && !defined(PCRE_STATIC)
# ifndef PCRE_EXP_DECL
# define PCRE_EXP_DECL extern __declspec(dllimport)
# endif
# ifdef __cplusplus
# ifndef PCRECPP_EXP_DECL
# define PCRECPP_EXP_DECL extern __declspec(dllimport)
# endif
# ifndef PCRECPP_EXP_DEFN
# define PCRECPP_EXP_DEFN __declspec(dllimport)
# endif
# endif
#endif
/* By default, we use the standard "extern" declarations. */
#ifndef PCRE_EXP_DECL
# ifdef __cplusplus
# define PCRE_EXP_DECL extern "C"
# else
# define PCRE_EXP_DECL extern
# endif
#endif
#ifdef __cplusplus
# ifndef PCRECPP_EXP_DECL
# define PCRECPP_EXP_DECL extern
# endif
# ifndef PCRECPP_EXP_DEFN
# define PCRECPP_EXP_DEFN
# endif
#endif
/* Have to include stdlib.h in order to ensure that size_t is defined;
it is needed here for malloc. */
#include <stdlib.h>
/* Allow for C++ users */
#ifdef __cplusplus
extern "C" {
#endif
/* Options */
#define PCRE_CASELESS 0x00000001
#define PCRE_MULTILINE 0x00000002
#define PCRE_DOTALL 0x00000004
#define PCRE_EXTENDED 0x00000008
#define PCRE_ANCHORED 0x00000010
#define PCRE_DOLLAR_ENDONLY 0x00000020
#define PCRE_EXTRA 0x00000040
#define PCRE_NOTBOL 0x00000080
#define PCRE_NOTEOL 0x00000100
#define PCRE_UNGREEDY 0x00000200
#define PCRE_NOTEMPTY 0x00000400
#define PCRE_UTF8 0x00000800
#define PCRE_NO_AUTO_CAPTURE 0x00001000
#define PCRE_NO_UTF8_CHECK 0x00002000
#define PCRE_AUTO_CALLOUT 0x00004000
#define PCRE_PARTIAL 0x00008000
#define PCRE_DFA_SHORTEST 0x00010000
#define PCRE_DFA_RESTART 0x00020000
#define PCRE_FIRSTLINE 0x00040000
#define PCRE_DUPNAMES 0x00080000
#define PCRE_NEWLINE_CR 0x00100000
#define PCRE_NEWLINE_LF 0x00200000
#define PCRE_NEWLINE_CRLF 0x00300000
#define PCRE_NEWLINE_ANY 0x00400000
#define PCRE_NEWLINE_ANYCRLF 0x00500000
#define PCRE_BSR_ANYCRLF 0x00800000
#define PCRE_BSR_UNICODE 0x01000000
/* Exec-time and get/set-time error codes */
#define PCRE_ERROR_NOMATCH (-1)
#define PCRE_ERROR_NULL (-2)
#define PCRE_ERROR_BADOPTION (-3)
#define PCRE_ERROR_BADMAGIC (-4)
#define PCRE_ERROR_UNKNOWN_OPCODE (-5)
#define PCRE_ERROR_UNKNOWN_NODE (-5) /* For backward compatibility */
#define PCRE_ERROR_NOMEMORY (-6)
#define PCRE_ERROR_NOSUBSTRING (-7)
#define PCRE_ERROR_MATCHLIMIT (-8)
#define PCRE_ERROR_CALLOUT (-9) /* Never used by PCRE itself */
#define PCRE_ERROR_BADUTF8 (-10)
#define PCRE_ERROR_BADUTF8_OFFSET (-11)
#define PCRE_ERROR_PARTIAL (-12)
#define PCRE_ERROR_BADPARTIAL (-13)
#define PCRE_ERROR_INTERNAL (-14)
#define PCRE_ERROR_BADCOUNT (-15)
#define PCRE_ERROR_DFA_UITEM (-16)
#define PCRE_ERROR_DFA_UCOND (-17)
#define PCRE_ERROR_DFA_UMLIMIT (-18)
#define PCRE_ERROR_DFA_WSSIZE (-19)
#define PCRE_ERROR_DFA_RECURSE (-20)
#define PCRE_ERROR_RECURSIONLIMIT (-21)
#define PCRE_ERROR_NULLWSLIMIT (-22) /* No longer actually used */
#define PCRE_ERROR_BADNEWLINE (-23)
/* Request types for pcre_fullinfo() */
#define PCRE_INFO_OPTIONS 0
#define PCRE_INFO_SIZE 1
#define PCRE_INFO_CAPTURECOUNT 2
#define PCRE_INFO_BACKREFMAX 3
#define PCRE_INFO_FIRSTBYTE 4
#define PCRE_INFO_FIRSTCHAR 4 /* For backwards compatibility */
#define PCRE_INFO_FIRSTTABLE 5
#define PCRE_INFO_LASTLITERAL 6
#define PCRE_INFO_NAMEENTRYSIZE 7
#define PCRE_INFO_NAMECOUNT 8
#define PCRE_INFO_NAMETABLE 9
#define PCRE_INFO_STUDYSIZE 10
#define PCRE_INFO_DEFAULT_TABLES 11
#define PCRE_INFO_OKPARTIAL 12
#define PCRE_INFO_JCHANGED 13
#define PCRE_INFO_HASCRORLF 14
/* Request types for pcre_config(). Do not re-arrange, in order to remain
compatible. */
#define PCRE_CONFIG_UTF8 0
#define PCRE_CONFIG_NEWLINE 1
#define PCRE_CONFIG_LINK_SIZE 2
#define PCRE_CONFIG_POSIX_MALLOC_THRESHOLD 3
#define PCRE_CONFIG_MATCH_LIMIT 4
#define PCRE_CONFIG_STACKRECURSE 5
#define PCRE_CONFIG_UNICODE_PROPERTIES 6
#define PCRE_CONFIG_MATCH_LIMIT_RECURSION 7
#define PCRE_CONFIG_BSR 8
/* Bit flags for the pcre_extra structure. Do not re-arrange or redefine
these bits, just add new ones on the end, in order to remain compatible. */
#define PCRE_EXTRA_STUDY_DATA 0x0001
#define PCRE_EXTRA_MATCH_LIMIT 0x0002
#define PCRE_EXTRA_CALLOUT_DATA 0x0004
#define PCRE_EXTRA_TABLES 0x0008
#define PCRE_EXTRA_MATCH_LIMIT_RECURSION 0x0010
/* Types */
struct real_pcre; /* declaration; the definition is private */
typedef struct real_pcre pcre;
/* When PCRE is compiled as a C++ library, the subject pointer type can be
replaced with a custom type. For conventional use, the public interface is a
const char *. */
#ifndef PCRE_SPTR
#define PCRE_SPTR const char *
#endif
/* The structure for passing additional data to pcre_exec(). This is defined in
such as way as to be extensible. Always add new fields at the end, in order to
remain compatible. */
typedef struct pcre_extra {
unsigned long int flags; /* Bits for which fields are set */
void *study_data; /* Opaque data from pcre_study() */
unsigned long int match_limit; /* Maximum number of calls to match() */
void *callout_data; /* Data passed back in callouts */
const unsigned char *tables; /* Pointer to character tables */
unsigned long int match_limit_recursion; /* Max recursive calls to match() */
} pcre_extra;
/* The structure for passing out data via the pcre_callout_function. We use a
structure so that new fields can be added on the end in future versions,
without changing the API of the function, thereby allowing old clients to work
without modification. */
typedef struct pcre_callout_block {
int version; /* Identifies version of block */
/* ------------------------ Version 0 ------------------------------- */
int callout_number; /* Number compiled into pattern */
int *offset_vector; /* The offset vector */
PCRE_SPTR subject; /* The subject being matched */
int subject_length; /* The length of the subject */
int start_match; /* Offset to start of this match attempt */
int current_position; /* Where we currently are in the subject */
int capture_top; /* Max current capture */
int capture_last; /* Most recently closed capture */
void *callout_data; /* Data passed in with the call */
/* ------------------- Added for Version 1 -------------------------- */
int pattern_position; /* Offset to next item in the pattern */
int next_item_length; /* Length of next item in the pattern */
/* ------------------------------------------------------------------ */
} pcre_callout_block;
/* Indirection for store get and free functions. These can be set to
alternative malloc/free functions if required. Special ones are used in the
non-recursive case for "frames". There is also an optional callout function
that is triggered by the (?) regex item. For Virtual Pascal, these definitions
have to take another form. */
#ifndef VPCOMPAT
PCRE_EXP_DECL void *(*pcre_malloc)(size_t);
PCRE_EXP_DECL void (*pcre_free)(void *);
PCRE_EXP_DECL void *(*pcre_stack_malloc)(size_t);
PCRE_EXP_DECL void (*pcre_stack_free)(void *);
PCRE_EXP_DECL int (*pcre_callout)(pcre_callout_block *);
#else /* VPCOMPAT */
PCRE_EXP_DECL void *pcre_malloc(size_t);
PCRE_EXP_DECL void pcre_free(void *);
PCRE_EXP_DECL void *pcre_stack_malloc(size_t);
PCRE_EXP_DECL void pcre_stack_free(void *);
PCRE_EXP_DECL int pcre_callout(pcre_callout_block *);
#endif /* VPCOMPAT */
/* Exported PCRE functions */
PCRE_EXP_DECL pcre *pcre_compile(const char *, int, const char **, int *,
const unsigned char *);
PCRE_EXP_DECL pcre *pcre_compile2(const char *, int, int *, const char **,
int *, const unsigned char *);
PCRE_EXP_DECL int pcre_config(int, void *);
PCRE_EXP_DECL int pcre_copy_named_substring(const pcre *, const char *,
int *, int, const char *, char *, int);
PCRE_EXP_DECL int pcre_copy_substring(const char *, int *, int, int, char *,
int);
PCRE_EXP_DECL int pcre_dfa_exec(const pcre *, const pcre_extra *,
const char *, int, int, int, int *, int , int *, int);
PCRE_EXP_DECL int pcre_exec(const pcre *, const pcre_extra *, PCRE_SPTR,
int, int, int, int *, int);
PCRE_EXP_DECL void pcre_free_substring(const char *);
PCRE_EXP_DECL void pcre_free_substring_list(const char **);
PCRE_EXP_DECL int pcre_fullinfo(const pcre *, const pcre_extra *, int,
void *);
PCRE_EXP_DECL int pcre_get_named_substring(const pcre *, const char *,
int *, int, const char *, const char **);
PCRE_EXP_DECL int pcre_get_stringnumber(const pcre *, const char *);
PCRE_EXP_DECL int pcre_get_stringtable_entries(const pcre *, const char *,
char **, char **);
PCRE_EXP_DECL int pcre_get_substring(const char *, int *, int, int,
const char **);
PCRE_EXP_DECL int pcre_get_substring_list(const char *, int *, int,
const char ***);
PCRE_EXP_DECL int pcre_info(const pcre *, int *, int *);
PCRE_EXP_DECL const unsigned char *pcre_maketables(void);
PCRE_EXP_DECL int pcre_refcount(pcre *, int);
PCRE_EXP_DECL pcre_extra *pcre_study(const pcre *, int, const char **);
PCRE_EXP_DECL const char *pcre_version(void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* End of pcre.h */
File diff suppressed because it is too large. Load diff
+128
View File
@@ -0,0 +1,128 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2007 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains the external function pcre_config(). */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/*************************************************
* Return info about what features are configured *
*************************************************/
/* This function has an extensible interface so that additional items can be
added compatibly.
Arguments:
what what information is required
where where to put the information
Returns: 0 if data returned, negative on error
*/
PCRE_EXP_DEFN int
pcre_config(int what, void *where)
{
switch (what)
{
case PCRE_CONFIG_UTF8:
#ifdef SUPPORT_UTF8
*((int *)where) = 1;
#else
*((int *)where) = 0;
#endif
break;
case PCRE_CONFIG_UNICODE_PROPERTIES:
#ifdef SUPPORT_UCP
*((int *)where) = 1;
#else
*((int *)where) = 0;
#endif
break;
case PCRE_CONFIG_NEWLINE:
*((int *)where) = NEWLINE;
break;
case PCRE_CONFIG_BSR:
#ifdef BSR_ANYCRLF
*((int *)where) = 1;
#else
*((int *)where) = 0;
#endif
break;
case PCRE_CONFIG_LINK_SIZE:
*((int *)where) = LINK_SIZE;
break;
case PCRE_CONFIG_POSIX_MALLOC_THRESHOLD:
*((int *)where) = POSIX_MALLOC_THRESHOLD;
break;
case PCRE_CONFIG_MATCH_LIMIT:
*((unsigned int *)where) = MATCH_LIMIT;
break;
case PCRE_CONFIG_MATCH_LIMIT_RECURSION:
*((unsigned int *)where) = MATCH_LIMIT_RECURSION;
break;
case PCRE_CONFIG_STACKRECURSE:
#ifdef NO_RECURSE
*((int *)where) = 0;
#else
*((int *)where) = 1;
#endif
break;
default: return PCRE_ERROR_BADOPTION;
}
return 0;
}
/* End of pcre_config.c */
File diff suppressed because it is too large. Load diff
+192
View File
@@ -0,0 +1,192 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* This file is automatically written by the dftables auxiliary
program. If you edit it by hand, you might like to edit the Makefile to
prevent its ever being regenerated.
This file contains the default tables for characters with codes less than
128 (ASCII characters). These tables are used when no external tables are
passed to PCRE.
The following #include is present because without it gcc 4.x may remove
the array definition from the final binary if PCRE is built into a static
library and dead code stripping is activated. This leads to link errors.
Pulling in the header ensures that the array gets flagged as "someone
outside this compilation unit might reference this" and so it will always
be supplied to the linker. */
#include "pcre_internal.h"
const unsigned char _pcre_default_tables[] = {
/* This table is a lower casing table. */
0, 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, 97, 98, 99,100,101,102,103,
104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,
120,121,122, 91, 92, 93, 94, 95,
96, 97, 98, 99,100,101,102,103,
104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,
120,121,122,123,124,125,126,127,
128,129,130,131,132,133,134,135,
136,137,138,139,140,141,142,143,
144,145,146,147,148,149,150,151,
152,153,154,155,156,157,158,159,
160,161,162,163,164,165,166,167,
168,169,170,171,172,173,174,175,
176,177,178,179,180,181,182,183,
184,185,186,187,188,189,190,191,
192,193,194,195,196,197,198,199,
200,201,202,203,204,205,206,207,
208,209,210,211,212,213,214,215,
216,217,218,219,220,221,222,223,
224,225,226,227,228,229,230,231,
232,233,234,235,236,237,238,239,
240,241,242,243,244,245,246,247,
248,249,250,251,252,253,254,255,
/* This table is a case flipping table. */
0, 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, 97, 98, 99,100,101,102,103,
104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,
120,121,122, 91, 92, 93, 94, 95,
96, 65, 66, 67, 68, 69, 70, 71,
72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87,
88, 89, 90,123,124,125,126,127,
128,129,130,131,132,133,134,135,
136,137,138,139,140,141,142,143,
144,145,146,147,148,149,150,151,
152,153,154,155,156,157,158,159,
160,161,162,163,164,165,166,167,
168,169,170,171,172,173,174,175,
176,177,178,179,180,181,182,183,
184,185,186,187,188,189,190,191,
192,193,194,195,196,197,198,199,
200,201,202,203,204,205,206,207,
208,209,210,211,212,213,214,215,
216,217,218,219,220,221,222,223,
224,225,226,227,228,229,230,231,
232,233,234,235,236,237,238,239,
240,241,242,243,244,245,246,247,
248,249,250,251,252,253,254,255,
/* This table contains bit maps for various character classes.
Each map is 32 bytes long and the bits run from the least
significant end of each byte. The classes that have their own
maps are: space, xdigit, digit, upper, lower, word, graph
print, punct, and cntrl. Other classes are built from combinations. */
0x00,0x3e,0x00,0x00,0x01,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03,
0x7e,0x00,0x00,0x00,0x7e,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xfe,0xff,0xff,0x07,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xfe,0xff,0xff,0x07,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03,
0xfe,0xff,0xff,0x87,0xfe,0xff,0xff,0x07,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xfe,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x7f,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x7f,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xfe,0xff,0x00,0xfc,
0x01,0x00,0x00,0xf8,0x01,0x00,0x00,0x78,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
/* This table identifies various classes of character by individual bits:
0x01 white space character
0x02 letter
0x04 decimal digit
0x08 hexadecimal digit
0x10 alphanumeric or '_'
0x80 regular expression metacharacter or binary zero
*/
0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 */
0x00,0x01,0x01,0x00,0x01,0x01,0x00,0x00, /* 8- 15 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */
0x01,0x00,0x00,0x00,0x80,0x00,0x00,0x00, /* - ' */
0x80,0x80,0x80,0x80,0x00,0x00,0x80,0x00, /* ( - / */
0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c, /* 0 - 7 */
0x1c,0x1c,0x00,0x00,0x00,0x00,0x00,0x80, /* 8 - ? */
0x00,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* @ - G */
0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* H - O */
0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* P - W */
0x12,0x12,0x12,0x80,0x80,0x00,0x80,0x10, /* X - _ */
0x00,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* ` - g */
0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* h - o */
0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* p - w */
0x12,0x12,0x12,0x80,0x80,0x00,0x00,0x00, /* x -127 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 128-135 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 136-143 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144-151 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 152-159 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160-167 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 168-175 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 176-183 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 192-199 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 200-207 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 208-215 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 216-223 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 224-231 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 232-239 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 240-247 */
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/* 248-255 */
/* End of chartables.c */
File diff suppressed because it is too large. Load diff
+165
View File
@@ -0,0 +1,165 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/*PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2007 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains the external function pcre_fullinfo(), which returns
information about a compiled pattern. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/*************************************************
* Return info about compiled pattern *
*************************************************/
/* This is a newer "info" function which has an extensible interface so
that additional items can be added compatibly.
Arguments:
argument_re points to compiled code
extra_data points extra data, or NULL
what what information is required
where where to put the information
Returns: 0 if data returned, negative on error
*/
PCRE_EXP_DEFN int
pcre_fullinfo(const pcre *argument_re, const pcre_extra *extra_data, int what,
void *where)
{
real_pcre internal_re;
pcre_study_data internal_study;
const real_pcre *re = (const real_pcre *)argument_re;
const pcre_study_data *study = NULL;
if (re == NULL || where == NULL) return PCRE_ERROR_NULL;
if (extra_data != NULL && (extra_data->flags & PCRE_EXTRA_STUDY_DATA) != 0)
study = (const pcre_study_data *)extra_data->study_data;
if (re->magic_number != MAGIC_NUMBER)
{
re = _pcre_try_flipped(re, &internal_re, study, &internal_study);
if (re == NULL) return PCRE_ERROR_BADMAGIC;
if (study != NULL) study = &internal_study;
}
switch (what)
{
case PCRE_INFO_OPTIONS:
*((unsigned long int *)where) = re->options & PUBLIC_OPTIONS;
break;
case PCRE_INFO_SIZE:
*((size_t *)where) = re->size;
break;
case PCRE_INFO_STUDYSIZE:
*((size_t *)where) = (study == NULL)? 0 : study->size;
break;
case PCRE_INFO_CAPTURECOUNT:
*((int *)where) = re->top_bracket;
break;
case PCRE_INFO_BACKREFMAX:
*((int *)where) = re->top_backref;
break;
case PCRE_INFO_FIRSTBYTE:
*((int *)where) =
((re->flags & PCRE_FIRSTSET) != 0)? re->first_byte :
((re->flags & PCRE_STARTLINE) != 0)? -1 : -2;
break;
/* Make sure we pass back the pointer to the bit vector in the external
block, not the internal copy (with flipped integer fields). */
case PCRE_INFO_FIRSTTABLE:
*((const uschar **)where) =
(study != NULL && (study->options & PCRE_STUDY_MAPPED) != 0)?
((const pcre_study_data *)extra_data->study_data)->start_bits : NULL;
break;
case PCRE_INFO_LASTLITERAL:
*((int *)where) =
((re->flags & PCRE_REQCHSET) != 0)? re->req_byte : -1;
break;
case PCRE_INFO_NAMEENTRYSIZE:
*((int *)where) = re->name_entry_size;
break;
case PCRE_INFO_NAMECOUNT:
*((int *)where) = re->name_count;
break;
case PCRE_INFO_NAMETABLE:
*((const uschar **)where) = (const uschar *)re + re->name_table_offset;
break;
case PCRE_INFO_DEFAULT_TABLES:
*((const uschar **)where) = (const uschar *)(_pcre_default_tables);
break;
case PCRE_INFO_OKPARTIAL:
*((int *)where) = (re->flags & PCRE_NOPARTIAL) == 0;
break;
case PCRE_INFO_JCHANGED:
*((int *)where) = (re->flags & PCRE_JCHANGED) != 0;
break;
case PCRE_INFO_HASCRORLF:
*((int *)where) = (re->flags & PCRE_HASCRORLF) != 0;
break;
default: return PCRE_ERROR_BADOPTION;
}
return 0;
}
/* End of pcre_fullinfo.c */
+465
View File
@@ -0,0 +1,465 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2007 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains some convenience functions for extracting substrings
from the subject string after a regex match has succeeded. The original idea
for these functions came from Scott Wimer. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/*************************************************
* Find number for named string *
*************************************************/
/* This function is used by the get_first_set() function below, as well
as being generally available. It assumes that names are unique.
Arguments:
code the compiled regex
stringname the name whose number is required
Returns: the number of the named parentheses, or a negative number
(PCRE_ERROR_NOSUBSTRING) if not found
*/
int
pcre_get_stringnumber(const pcre *code, const char *stringname)
{
int rc;
int entrysize;
int top, bot;
uschar *nametable;
if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0)
return rc;
if (top <= 0) return PCRE_ERROR_NOSUBSTRING;
if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0)
return rc;
if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0)
return rc;
bot = 0;
while (top > bot)
{
int mid = (top + bot) / 2;
uschar *entry = nametable + entrysize*mid;
int c = strcmp(stringname, (char *)(entry + 2));
if (c == 0) return (entry[0] << 8) + entry[1];
if (c > 0) bot = mid + 1; else top = mid;
}
return PCRE_ERROR_NOSUBSTRING;
}
/*************************************************
* Find (multiple) entries for named string *
*************************************************/
/* This is used by the get_first_set() function below, as well as being
generally available. It is used when duplicated names are permitted.
Arguments:
code the compiled regex
stringname the name whose entries required
firstptr where to put the pointer to the first entry
lastptr where to put the pointer to the last entry
Returns: the length of each entry, or a negative number
(PCRE_ERROR_NOSUBSTRING) if not found
*/
int
pcre_get_stringtable_entries(const pcre *code, const char *stringname,
char **firstptr, char **lastptr)
{
int rc;
int entrysize;
int top, bot;
uschar *nametable, *lastentry;
if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0)
return rc;
if (top <= 0) return PCRE_ERROR_NOSUBSTRING;
if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0)
return rc;
if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0)
return rc;
lastentry = nametable + entrysize * (top - 1);
bot = 0;
while (top > bot)
{
int mid = (top + bot) / 2;
uschar *entry = nametable + entrysize*mid;
int c = strcmp(stringname, (char *)(entry + 2));
if (c == 0)
{
uschar *first = entry;
uschar *last = entry;
while (first > nametable)
{
if (strcmp(stringname, (char *)(first - entrysize + 2)) != 0) break;
first -= entrysize;
}
while (last < lastentry)
{
if (strcmp(stringname, (char *)(last + entrysize + 2)) != 0) break;
last += entrysize;
}
*firstptr = (char *)first;
*lastptr = (char *)last;
return entrysize;
}
if (c > 0) bot = mid + 1; else top = mid;
}
return PCRE_ERROR_NOSUBSTRING;
}
/*************************************************
* Find first set of multiple named strings *
*************************************************/
/* This function allows for duplicate names in the table of named substrings.
It returns the number of the first one that was set in a pattern match.
Arguments:
code the compiled regex
stringname the name of the capturing substring
ovector the vector of matched substrings
Returns: the number of the first that is set,
or the number of the last one if none are set,
or a negative number on error
*/
static int
get_first_set(const pcre *code, const char *stringname, int *ovector)
{
const real_pcre *re = (const real_pcre *)code;
int entrysize;
char *first, *last;
uschar *entry;
if ((re->options & PCRE_DUPNAMES) == 0 && (re->flags & PCRE_JCHANGED) == 0)
return pcre_get_stringnumber(code, stringname);
entrysize = pcre_get_stringtable_entries(code, stringname, &first, &last);
if (entrysize <= 0) return entrysize;
for (entry = (uschar *)first; entry <= (uschar *)last; entry += entrysize)
{
int n = (entry[0] << 8) + entry[1];
if (ovector[n*2] >= 0) return n;
}
return (first[0] << 8) + first[1];
}
/*************************************************
* Copy captured string to given buffer *
*************************************************/
/* This function copies a single captured substring into a given buffer.
Note that we use memcpy() rather than strncpy() in case there are binary zeros
in the string.
Arguments:
subject the subject string that was matched
ovector pointer to the offsets table
stringcount the number of substrings that were captured
(i.e. the yield of the pcre_exec call, unless
that was zero, in which case it should be 1/3
of the offset table size)
stringnumber the number of the required substring
buffer where to put the substring
size the size of the buffer
Returns: if successful:
the length of the copied string, not including the zero
that is put on the end; can be zero
if not successful:
PCRE_ERROR_NOMEMORY (-6) buffer too small
PCRE_ERROR_NOSUBSTRING (-7) no such captured substring
*/
int
pcre_copy_substring(const char *subject, int *ovector, int stringcount,
int stringnumber, char *buffer, int size)
{
int yield;
if (stringnumber < 0 || stringnumber >= stringcount)
return PCRE_ERROR_NOSUBSTRING;
stringnumber *= 2;
yield = ovector[stringnumber+1] - ovector[stringnumber];
if (size < yield + 1) return PCRE_ERROR_NOMEMORY;
memcpy(buffer, subject + ovector[stringnumber], yield);
buffer[yield] = 0;
return yield;
}
/*************************************************
* Copy named captured string to given buffer *
*************************************************/
/* This function copies a single captured substring into a given buffer,
identifying it by name. If the regex permits duplicate names, the first
substring that is set is chosen.
Arguments:
code the compiled regex
subject the subject string that was matched
ovector pointer to the offsets table
stringcount the number of substrings that were captured
(i.e. the yield of the pcre_exec call, unless
that was zero, in which case it should be 1/3
of the offset table size)
stringname the name of the required substring
buffer where to put the substring
size the size of the buffer
Returns: if successful:
the length of the copied string, not including the zero
that is put on the end; can be zero
if not successful:
PCRE_ERROR_NOMEMORY (-6) buffer too small
PCRE_ERROR_NOSUBSTRING (-7) no such captured substring
*/
int
pcre_copy_named_substring(const pcre *code, const char *subject, int *ovector,
int stringcount, const char *stringname, char *buffer, int size)
{
int n = get_first_set(code, stringname, ovector);
if (n <= 0) return n;
return pcre_copy_substring(subject, ovector, stringcount, n, buffer, size);
}
/*************************************************
* Copy all captured strings to new store *
*************************************************/
/* This function gets one chunk of store and builds a list of pointers and all
of the captured substrings in it. A NULL pointer is put on the end of the list.
Arguments:
subject the subject string that was matched
ovector pointer to the offsets table
stringcount the number of substrings that were captured
(i.e. the yield of the pcre_exec call, unless
that was zero, in which case it should be 1/3
of the offset table size)
listptr set to point to the list of pointers
Returns: if successful: 0
if not successful:
PCRE_ERROR_NOMEMORY (-6) failed to get store
*/
int
pcre_get_substring_list(const char *subject, int *ovector, int stringcount,
const char ***listptr)
{
int i;
int size = sizeof(char *);
int double_count = stringcount * 2;
char **stringlist;
char *p;
for (i = 0; i < double_count; i += 2)
size += sizeof(char *) + ovector[i+1] - ovector[i] + 1;
stringlist = (char **)(pcre_malloc)(size);
if (stringlist == NULL) return PCRE_ERROR_NOMEMORY;
*listptr = (const char **)stringlist;
p = (char *)(stringlist + stringcount + 1);
for (i = 0; i < double_count; i += 2)
{
int len = ovector[i+1] - ovector[i];
memcpy(p, subject + ovector[i], len);
*stringlist++ = p;
p += len;
*p++ = 0;
}
*stringlist = NULL;
return 0;
}
/*************************************************
* Free store obtained by get_substring_list *
*************************************************/
/* This function exists for the benefit of people calling PCRE from non-C
programs that can call its functions, but not free() or (pcre_free)() directly.
Argument: the result of a previous pcre_get_substring_list()
Returns: nothing
*/
void
pcre_free_substring_list(const char **pointer)
{
(pcre_free)((void *)pointer);
}
/*************************************************
* Copy captured string to new store *
*************************************************/
/* This function copies a single captured substring into a piece of new
store
Arguments:
subject the subject string that was matched
ovector pointer to the offsets table
stringcount the number of substrings that were captured
(i.e. the yield of the pcre_exec call, unless
that was zero, in which case it should be 1/3
of the offset table size)
stringnumber the number of the required substring
stringptr where to put a pointer to the substring
Returns: if successful:
the length of the string, not including the zero that
is put on the end; can be zero
if not successful:
PCRE_ERROR_NOMEMORY (-6) failed to get store
PCRE_ERROR_NOSUBSTRING (-7) substring not present
*/
int
pcre_get_substring(const char *subject, int *ovector, int stringcount,
int stringnumber, const char **stringptr)
{
int yield;
char *substring;
if (stringnumber < 0 || stringnumber >= stringcount)
return PCRE_ERROR_NOSUBSTRING;
stringnumber *= 2;
yield = ovector[stringnumber+1] - ovector[stringnumber];
substring = (char *)(pcre_malloc)(yield + 1);
if (substring == NULL) return PCRE_ERROR_NOMEMORY;
memcpy(substring, subject + ovector[stringnumber], yield);
substring[yield] = 0;
*stringptr = substring;
return yield;
}
/*************************************************
* Copy named captured string to new store *
*************************************************/
/* This function copies a single captured substring, identified by name, into
new store. If the regex permits duplicate names, the first substring that is
set is chosen.
Arguments:
code the compiled regex
subject the subject string that was matched
ovector pointer to the offsets table
stringcount the number of substrings that were captured
(i.e. the yield of the pcre_exec call, unless
that was zero, in which case it should be 1/3
of the offset table size)
stringname the name of the required substring
stringptr where to put the pointer
Returns: if successful:
the length of the copied string, not including the zero
that is put on the end; can be zero
if not successful:
PCRE_ERROR_NOMEMORY (-6) couldn't get memory
PCRE_ERROR_NOSUBSTRING (-7) no such captured substring
*/
int
pcre_get_named_substring(const pcre *code, const char *subject, int *ovector,
int stringcount, const char *stringname, const char **stringptr)
{
int n = get_first_set(code, stringname, ovector);
if (n <= 0) return n;
return pcre_get_substring(subject, ovector, stringcount, n, stringptr);
}
/*************************************************
* Free store obtained by get_substring *
*************************************************/
/* This function exists for the benefit of people calling PCRE from non-C
programs that can call its functions, but not free() or (pcre_free)() directly.
Argument: the result of a previous pcre_get_substring()
Returns: nothing
*/
void
pcre_free_substring(const char *pointer)
{
(pcre_free)((void *)pointer);
}
/* End of pcre_get.c */
+63
View File
@@ -0,0 +1,63 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2007 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains global variables that are exported by the PCRE library.
PCRE is thread-clean and doesn't use any global variables in the normal sense.
However, it calls memory allocation and freeing functions via the four
indirections below, and it can optionally do callouts, using the fifth
indirection. These values can be changed by the caller, but are shared between
all threads. However, when compiling for Virtual Pascal, things are done
differently, and global variables are not used (see pcre.in). */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
#ifndef VPCOMPAT
PCRE_EXP_DATA_DEFN void *(*pcre_malloc)(size_t) = malloc;
PCRE_EXP_DATA_DEFN void (*pcre_free)(void *) = free;
PCRE_EXP_DATA_DEFN void *(*pcre_stack_malloc)(size_t) = malloc;
PCRE_EXP_DATA_DEFN void (*pcre_stack_free)(void *) = free;
PCRE_EXP_DATA_DEFN int (*pcre_callout)(pcre_callout_block *) = NULL;
#endif
/* End of pcre_globals.c */
+93
View File
@@ -0,0 +1,93 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2007 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains the external function pcre_info(), which gives some
information about a compiled pattern. However, use of this function is now
deprecated, as it has been superseded by pcre_fullinfo(). */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/*************************************************
* (Obsolete) Return info about compiled pattern *
*************************************************/
/* This is the original "info" function. It picks potentially useful data out
of the private structure, but its interface was too rigid. It remains for
backwards compatibility. The public options are passed back in an int - though
the re->options field has been expanded to a long int, all the public options
at the low end of it, and so even on 16-bit systems this will still be OK.
Therefore, I haven't changed the API for pcre_info().
Arguments:
argument_re points to compiled code
optptr where to pass back the options
first_byte where to pass back the first character,
or -1 if multiline and all branches start ^,
or -2 otherwise
Returns: number of capturing subpatterns
or negative values on error
*/
PCRE_EXP_DEFN int
pcre_info(const pcre *argument_re, int *optptr, int *first_byte)
{
real_pcre internal_re;
const real_pcre *re = (const real_pcre *)argument_re;
if (re == NULL) return PCRE_ERROR_NULL;
if (re->magic_number != MAGIC_NUMBER)
{
re = _pcre_try_flipped(re, &internal_re, NULL, NULL);
if (re == NULL) return PCRE_ERROR_BADMAGIC;
}
if (optptr != NULL) *optptr = (int)(re->options & PUBLIC_OPTIONS);
if (first_byte != NULL)
*first_byte = ((re->flags & PCRE_FIRSTSET) != 0)? re->first_byte :
((re->flags & PCRE_STARTLINE) != 0)? -1 : -2;
return re->top_bracket;
}
/* End of pcre_info.c */
File diff suppressed because it is too large. Load diff
+143
View File
@@ -0,0 +1,143 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2007 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains the external function pcre_maketables(), which builds
character tables for PCRE in the current locale. The file is compiled on its
own as part of the PCRE library. However, it is also included in the
compilation of dftables.c, in which case the macro DFTABLES is defined. */
#ifndef DFTABLES
# ifdef HAVE_CONFIG_H
# include "config.h"
# endif
# include "pcre_internal.h"
#endif
/*************************************************
* Create PCRE character tables *
*************************************************/
/* This function builds a set of character tables for use by PCRE and returns
a pointer to them. They are build using the ctype functions, and consequently
their contents will depend upon the current locale setting. When compiled as
part of the library, the store is obtained via pcre_malloc(), but when compiled
inside dftables, use malloc().
Arguments: none
Returns: pointer to the contiguous block of data
*/
const unsigned char *
pcre_maketables(void)
{
unsigned char *yield, *p;
int i;
#ifndef DFTABLES
yield = (unsigned char*)(pcre_malloc)(tables_length);
#else
yield = (unsigned char*)malloc(tables_length);
#endif
if (yield == NULL) return NULL;
p = yield;
/* First comes the lower casing table */
for (i = 0; i < 256; i++) *p++ = tolower(i);
/* Next the case-flipping table */
for (i = 0; i < 256; i++) *p++ = islower(i)? toupper(i) : tolower(i);
/* Then the character class tables. Don't try to be clever and save effort on
exclusive ones - in some locales things may be different. Note that the table
for "space" includes everything "isspace" gives, including VT in the default
locale. This makes it work for the POSIX class [:space:]. Note also that it is
possible for a character to be alnum or alpha without being lower or upper,
such as "male and female ordinals" (\xAA and \xBA) in the fr_FR locale (at
least under Debian Linux's locales as of 12/2005). So we must test for alnum
specially. */
memset(p, 0, cbit_length);
for (i = 0; i < 256; i++)
{
if (isdigit(i)) p[cbit_digit + i/8] |= 1 << (i&7);
if (isupper(i)) p[cbit_upper + i/8] |= 1 << (i&7);
if (islower(i)) p[cbit_lower + i/8] |= 1 << (i&7);
if (isalnum(i)) p[cbit_word + i/8] |= 1 << (i&7);
if (i == '_') p[cbit_word + i/8] |= 1 << (i&7);
if (isspace(i)) p[cbit_space + i/8] |= 1 << (i&7);
if (isxdigit(i))p[cbit_xdigit + i/8] |= 1 << (i&7);
if (isgraph(i)) p[cbit_graph + i/8] |= 1 << (i&7);
if (isprint(i)) p[cbit_print + i/8] |= 1 << (i&7);
if (ispunct(i)) p[cbit_punct + i/8] |= 1 << (i&7);
if (iscntrl(i)) p[cbit_cntrl + i/8] |= 1 << (i&7);
}
p += cbit_length;
/* Finally, the character type table. In this, we exclude VT from the white
space chars, because Perl doesn't recognize it as such for \s and for comments
within regexes. */
for (i = 0; i < 256; i++)
{
int x = 0;
if (i != 0x0b && isspace(i)) x += ctype_space;
if (isalpha(i)) x += ctype_letter;
if (isdigit(i)) x += ctype_digit;
if (isxdigit(i)) x += ctype_xdigit;
if (isalnum(i) || i == '_') x += ctype_word;
/* Note: strchr includes the terminating zero in the characters it considers.
In this instance, that is ok because we want binary zero to be flagged as a
meta-character, which in this sense is any character that terminates a run
of data characters. */
if (strchr("\\*+?{^.$|()[", i) != 0) x += ctype_meta;
*p++ = x;
}
return yield;
}
/* End of pcre_maketables.c */
+164
View File
@@ -0,0 +1,164 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2007 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains internal functions for testing newlines when more than
one kind of newline is to be recognized. When a newline is found, its length is
returned. In principle, we could implement several newline "types", each
referring to a different set of newline characters. At present, PCRE supports
only NLTYPE_FIXED, which gets handled without these functions, NLTYPE_ANYCRLF,
and NLTYPE_ANY. The full list of Unicode newline characters is taken from
http://unicode.org/unicode/reports/tr18/. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/*************************************************
* Check for newline at given position *
*************************************************/
/* It is guaranteed that the initial value of ptr is less than the end of the
string that is being processed.
Arguments:
ptr pointer to possible newline
type the newline type
endptr pointer to the end of the string
lenptr where to return the length
utf8 TRUE if in utf8 mode
Returns: TRUE or FALSE
*/
BOOL
_pcre_is_newline(const uschar *ptr, int type, const uschar *endptr,
int *lenptr, BOOL utf8)
{
int c;
if (utf8) { GETCHAR(c, ptr); } else c = *ptr;
if (type == NLTYPE_ANYCRLF) switch(c)
{
case 0x000a: *lenptr = 1; return TRUE; /* LF */
case 0x000d: *lenptr = (ptr < endptr - 1 && ptr[1] == 0x0a)? 2 : 1;
return TRUE; /* CR */
default: return FALSE;
}
/* NLTYPE_ANY */
else switch(c)
{
case 0x000a: /* LF */
case 0x000b: /* VT */
case 0x000c: *lenptr = 1; return TRUE; /* FF */
case 0x000d: *lenptr = (ptr < endptr - 1 && ptr[1] == 0x0a)? 2 : 1;
return TRUE; /* CR */
case 0x0085: *lenptr = utf8? 2 : 1; return TRUE; /* NEL */
case 0x2028: /* LS */
case 0x2029: *lenptr = 3; return TRUE; /* PS */
default: return FALSE;
}
}
/*************************************************
* Check for newline at previous position *
*************************************************/
/* It is guaranteed that the initial value of ptr is greater than the start of
the string that is being processed.
Arguments:
ptr pointer to possible newline
type the newline type
startptr pointer to the start of the string
lenptr where to return the length
utf8 TRUE if in utf8 mode
Returns: TRUE or FALSE
*/
BOOL
_pcre_was_newline(const uschar *ptr, int type, const uschar *startptr,
int *lenptr, BOOL utf8)
{
int c;
ptr--;
#ifdef SUPPORT_UTF8
if (utf8)
{
BACKCHAR(ptr);
GETCHAR(c, ptr);
}
else c = *ptr;
#else /* no UTF-8 support */
c = *ptr;
#endif /* SUPPORT_UTF8 */
if (type == NLTYPE_ANYCRLF) switch(c)
{
case 0x000a: *lenptr = (ptr > startptr && ptr[-1] == 0x0d)? 2 : 1;
return TRUE; /* LF */
case 0x000d: *lenptr = 1; return TRUE; /* CR */
default: return FALSE;
}
else switch(c)
{
case 0x000a: *lenptr = (ptr > startptr && ptr[-1] == 0x0d)? 2 : 1;
return TRUE; /* LF */
case 0x000b: /* VT */
case 0x000c: /* FF */
case 0x000d: *lenptr = 1; return TRUE; /* CR */
case 0x0085: *lenptr = utf8? 2 : 1; return TRUE; /* NEL */
case 0x2028: /* LS */
case 0x2029: *lenptr = 3; return TRUE; /* PS */
default: return FALSE;
}
}
/* End of pcre_newline.c */
+85
View File
@@ -0,0 +1,85 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2007 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This file contains a private PCRE function that converts an ordinal
character value into a UTF8 string. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/*************************************************
* Convert character value to UTF-8 *
*************************************************/
/* This function takes an integer value in the range 0 - 0x7fffffff
and encodes it as a UTF-8 character in 0 to 6 bytes.
Arguments:
cvalue the character value
buffer pointer to buffer for result - at least 6 bytes long
Returns: number of characters placed in the buffer
*/
int
_pcre_ord2utf8(int cvalue, uschar *buffer)
{
#ifdef SUPPORT_UTF8
register int i, j;
for (i = 0; i < _pcre_utf8_table1_size; i++)
if (cvalue <= _pcre_utf8_table1[i]) break;
buffer += i;
for (j = i; j > 0; j--)
{
*buffer-- = 0x80 | (cvalue & 0x3f);
cvalue >>= 6;
}
*buffer = _pcre_utf8_table2[i] | cvalue;
return i + 1;
#else
return 0; /* Keep compiler happy; this function won't ever be */
#endif /* called when SUPPORT_UTF8 is not defined. */
}
/* End of pcre_ord2utf8.c */
+400
View File
@@ -0,0 +1,400 @@
/*
3APA3A simpliest proxy server
(c) 2007-2008 by ZARAZA <3APA3A@security.nnov.ru>
please read License Agreement
$Id: pcre_plugin.c,v 1.11 2012-04-25 18:17:22 vlad Exp $
*/
#include "../../structures.h"
#include <string.h>
#include "pcre.h"
#include "pcreposix.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifndef isnumber
#define isnumber(i_n_arg) ((i_n_arg>='0')&&(i_n_arg<='9'))
#endif
static struct pluginlink * pl;
static pthread_mutex_t pcre_mutex;
static struct filter pcre_first_filter = {
NULL,
"Fake filter",
NULL, NULL,
NULL, NULL,
NULL, NULL, NULL,
NULL, NULL
};
static struct filter *pcre_last_filter;
static int pcre_loaded = 0;
static int pcre_options = 0;
static struct pcreopt {
char * name;
int value;
} pcreopts[]= {
{"PCRE_CASELESS", 0x00000001},
{"PCRE_MULTILINE", 0x00000002},
{"PCRE_DOTALL", 0x00000004},
{"PCRE_EXTENDED", 0x00000008},
{"PCRE_ANCHORED", 0x00000010},
{"PCRE_DOLLAR_ENDONLY", 0x00000020},
{"PCRE_EXTRA", 0x00000040},
{"PCRE_NOTBOL", 0x00000080},
{"PCRE_NOTEOL", 0x00000100},
{"PCRE_UNGREEDY", 0x00000200},
{"PCRE_NOTEMPTY", 0x00000400},
{"PCRE_UTF8", 0x00000800},
{"PCRE_NO_AUTO_CAPTURE", 0x00001000},
{"PCRE_NO_UTF8_CHECK", 0x00002000},
{"PCRE_AUTO_CALLOUT", 0x00004000},
{"PCRE_PARTIAL", 0x00008000},
{"PCRE_DFA_SHORTEST", 0x00010000},
{"PCRE_DFA_RESTART", 0x00020000},
{"PCRE_FIRSTLINE", 0x00040000},
{"PCRE_DUPNAMES", 0x00080000},
{"PCRE_NEWLINE_CR", 0x00100000},
{"PCRE_NEWLINE_LF", 0x00200000},
{"PCRE_NEWLINE_CRLF", 0x00300000},
{"PCRE_NEWLINE_ANY", 0x00400000},
{"PCRE_NEWLINE_ANYCRLF", 0x00500000},
{"PCRE_BSR_ANYCRLF", 0x00800000},
{"PCRE_BSR_UNICODE", 0x01000000},
{NULL, 0}
};
struct pcre_filter_data {
int users;
pcre * re;
int action;
char * replace;
struct ace *acl;
};
static void pcre_data_free(struct pcre_filter_data *pcrefd){
pthread_mutex_lock(&pcre_mutex);
pcrefd->users--;
if(!pcrefd->users){
if(pcrefd->re) pl->myfree(pcrefd->re);
if(pcrefd->acl) pl->freeacl(pcrefd->acl);
if(pcrefd->replace) pl->myfree(pcrefd->replace);
pl->myfree(pcrefd);
}
pthread_mutex_unlock(&pcre_mutex);
}
static void* pcre_filter_open(void * idata, struct srvparam * param){
#define pcrefd ((struct pcre_filter_data *)idata)
if(idata){
pthread_mutex_lock(&pcre_mutex);
pcrefd->users++;
pthread_mutex_unlock(&pcre_mutex);
}
#undef pcrefd
return idata;
}
static FILTER_ACTION pcre_filter_client(void *fo, struct clientparam * param, void** fc){
int res;
struct ace tmpace;
*fc = fo;
if(!fo) return PASS;
#define pcrefd ((struct pcre_filter_data *)fo)
if(!pcrefd->acl) return CONTINUE;
memset (&tmpace, 0, sizeof(struct ace));
tmpace.src = pcrefd->acl->src;
res = pl->ACLMatches(&tmpace, param);
#undef pcrefd
return (res)? CONTINUE:PASS;
}
static FILTER_ACTION pcre_filter_buffer(void *fc, struct clientparam *param, unsigned char ** buf_p, int * bufsize_p, int offset, int * length_p){
int ovector[48];
int count = 0;
struct ace *acl;
int match = 0;
int replen, num;
char * replace;
char * tmpbuf, *target, *newbuf;
int nreplaces=0;
#define pcrefd ((struct pcre_filter_data *)fc)
for(acl = pcrefd->acl; acl; acl=acl->next){
if(pl->ACLMatches(pcrefd->acl, param)){
match = 1;
break;
}
}
if(!match) return CONTINUE;
if(!pcrefd->re) return pcrefd->action;
for(; offset < *length_p; nreplaces++){
count = pcre_exec(pcrefd->re, NULL, *buf_p, *length_p, offset, 0, ovector, 48);
if(count <= 0) break;
if(!(replace = pcrefd->replace) || param->nooverwritefilter) return pcrefd->action;
replen = *length_p - ovector[1];
while(*replace){
if(*replace == '\\' && *(replace +1)){
replace+=2;
++replen;
}
else if(*replace == '$' && isnumber(*(replace+1))){
replace ++;
num = atoi(replace);
while(isnumber(*replace)) replace++;
if(num > (count - 1)) continue;
replen += (ovector[(num<<1) + 1] - ovector[(num<<1)]);
}
else {
replace++;
replen++;
}
}
tmpbuf = (*pl->myalloc)(replen);
if(!tmpbuf) return CONTINUE;
for(target = tmpbuf, replace = pcrefd->replace; *replace; ){
if(*replace == '\\' && *(replace +1)){
*target++ = replace[1];
replace+=2;
}
else if(*replace == '$' && isnumber(*(replace+1))){
replace ++;
num = atoi(replace);
if(num > (count - 1)) continue;
memcpy(target, *buf_p + ovector[(num<<1)], ovector[(num<<1) + 1] - ovector[(num<<1)]);
target += (ovector[(num<<1) + 1] - ovector[(num<<1)]);
while(isnumber(*replace)) replace++;
}
else {
*target++ = *replace++;
}
}
memcpy(target, *buf_p + ovector[1], *length_p - ovector[1]);
if((ovector[0] + replen + 1) > *bufsize_p){
newbuf = (*pl->myalloc)(ovector[0] + replen + 1);
if(!newbuf){
(*pl->myfree)(tmpbuf);
return CONTINUE;
}
memcpy(newbuf, *buf_p, ovector[0]);
(*pl->myfree)(*buf_p);
*buf_p = newbuf;
*bufsize_p = ovector[0] + replen + 1;
}
memcpy(*buf_p + ovector[0], tmpbuf, replen);
(*pl->myfree)(tmpbuf);
(*buf_p)[ovector[0] + replen] = 0;
*length_p = ovector[0] + replen;
if(ovector[0] + replen <= offset){
break;
}
offset = ovector[0] + (int)strlen(pcrefd->replace);
}
return nreplaces? pcrefd->action : CONTINUE;
#undef pcrefd
}
static void pcre_filter_clear(void *fo){
}
static void pcre_filter_close(void *fo){
if(!fo) return;
pcre_data_free((struct pcre_filter_data *)fo);
}
static int h_pcre(int argc, unsigned char **argv){
int action = 0;
pcre *re = NULL;
struct ace *acl;
int offset = 4;
const char * errptr;
struct pcre_filter_data *flt;
struct filter *newf;
char *replace = NULL;
if(!strcmp(argv[2], "allow")) action = PASS;
else if(!strcmp(argv[2], "deny")) action = REJECT;
else if(!strcmp(argv[2], "remove")) action = REMOVE;
else if(!strcmp(argv[2], "dunno")) action = CONTINUE;
else return 1;
if(!strcmp(argv[0], "pcre_rewrite")) {
int i,j;
offset = 5;
replace = pl->mystrdup(argv[4]);
if(!replace) return 9;
for(i=0, j=0; replace[i]; i++, j++){
if(replace[i] == '\\'){
switch(replace[i+1]){
case 'r':
i++;
replace[j] = '\r';
break;
case 'n':
i++;
replace[j] = '\n';
break;
case '0':
i++;
replace[j] = 0;
break;
case '\\':
i++;
default:
replace[j] = '\\';
break;
}
}
else replace[j] = replace[i];
}
replace[j] = 0;
}
if(!(acl = pl->make_ace(argc - offset, argv + offset))) return 2;
if(*argv[3] && !(*argv[3] == '*' && !argv[3][1]) ){
re = pcre_compile((char *)argv[3], pcre_options, &errptr, &offset, NULL);
if(!re) {
pl->myfree(acl);
if(replace) pl->myfree(replace);
return 3;
}
}
flt = pl->myalloc(sizeof(struct pcre_filter_data));
newf = pl->myalloc(sizeof(struct filter));
if(!flt || !newf) {
pl->myfree(acl);
pl->myfree(re);
if(replace) pl->myfree(replace);
if(flt) pl->myfree(flt);
return 4;
}
memset(flt, 0, sizeof(struct pcre_filter_data));
memset(newf, 0, sizeof(struct filter));
flt->action = action;
flt->re = re;
flt->acl = acl;
flt->replace = replace;
flt->users = 1;
newf->instance = "pcre";
newf->data = flt;
newf->filter_open = pcre_filter_open;
newf->filter_client = pcre_filter_client;
if(strstr(argv[1], "request"))newf->filter_request = pcre_filter_buffer;
if(strstr(argv[1], "cliheader"))newf->filter_header_cli = pcre_filter_buffer;
if(strstr(argv[1], "clidata"))newf->filter_data_cli = pcre_filter_buffer;
if(strstr(argv[1], "srvheader"))newf->filter_header_srv = pcre_filter_buffer;
if(strstr(argv[1], "srvdata"))newf->filter_data_srv = pcre_filter_buffer;
newf->filter_clear = pcre_filter_clear;
newf->filter_close = pcre_filter_close;
if(!pcre_last_filter){
newf->next = pcre_first_filter.next;
pcre_first_filter.next=newf;
}
else {
newf->next = pcre_last_filter->next;
pcre_last_filter->next = newf;
}
pcre_last_filter=newf;
return 0;
}
static int h_pcre_extend(int argc, unsigned char **argv){
struct ace *acl;
if(!pcre_last_filter || !pcre_last_filter->data) return 1;
acl = ((struct pcre_filter_data *)pcre_last_filter->data)->acl;
if(!acl) return 2;
for(; acl->next; acl=acl->next);
acl->next = (*pl->make_ace)(argc - 1, argv + 1);
if(!acl->next) return 3;
return 0;
}
static int h_pcre_options(int argc, unsigned char **argv){
int i,j;
pcre_options = 0;
for(j=1; j<argc; j++)
for(i=0; pcreopts[i].name; i++)
if(!strcmp(pcreopts[i].name, argv[j]))
pcre_options |= pcreopts[i].value;
return 0;
}
static struct commands pcre_commandhandlers[] = {
{pcre_commandhandlers+1, "pcre", h_pcre, 4, 0},
{pcre_commandhandlers+2, "pcre_rewrite", h_pcre, 5, 0},
{pcre_commandhandlers+3, "pcre_extend", h_pcre_extend, 2, 0},
{NULL, "pcre_options", h_pcre_options, 2, 0}
};
static struct symbol regexp_symbols[] = {
{regexp_symbols+1, "regcomp", (void*) regcomp},
{regexp_symbols+2, "regexec", (void*) regexec},
{regexp_symbols+3, "regerror", (void*) regerror},
{regexp_symbols+4, "regfree", (void*) regfree},
{regexp_symbols+5, "pcre_compile", (void*) pcre_compile},
{regexp_symbols+6, "pcre_exec", (void*) pcre_exec},
{NULL, "pcre_free", NULL},
};
#ifdef _WIN32
__declspec(dllexport)
#endif
int pcre_plugin (struct pluginlink * pluginlink,
int argc, char** argv){
struct filter *flt, *tmpflt;
pl = pluginlink;
pcre_options = 0;
if(!pcre_loaded){
pcre_malloc = pl->myalloc;
pcre_free = pl->myfree;
pcre_loaded = 1;
pthread_mutex_init(&pcre_mutex, NULL);
regexp_symbols[6].value = pl->myfree;
regexp_symbols[6].next = pl->symbols.next;
pl->symbols.next = regexp_symbols;
pcre_commandhandlers[3].next = pl->commandhandlers->next;
pl->commandhandlers->next = pcre_commandhandlers;
pcre_first_filter.next = pl->conf->filters;
pl->conf->filters = &pcre_first_filter;
}
else if(pcre_last_filter){
pcre_first_filter.next = pcre_last_filter->next;
flt = pcre_first_filter.next;
for(; flt; flt = tmpflt){
tmpflt = flt->next;
if(flt->data)
pcre_data_free((struct pcre_filter_data *)flt->data);
pl->myfree(flt);
if(flt == pcre_last_filter) break;
}
}
pcre_last_filter = NULL;
return 0;
}
#ifdef __cplusplus
}
#endif
+82
View File
@@ -0,0 +1,82 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2007 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains the external function pcre_refcount(), which is an
auxiliary function that can be used to maintain a reference count in a compiled
pattern data block. This might be helpful in applications where the block is
shared by different users. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/*************************************************
* Maintain reference count *
*************************************************/
/* The reference count is a 16-bit field, initialized to zero. It is not
possible to transfer a non-zero count from one host to a different host that
has a different byte order - though I can't see why anyone in their right mind
would ever want to do that!
Arguments:
argument_re points to compiled code
adjust value to add to the count
Returns: the (possibly updated) count value (a non-negative number), or
a negative error number
*/
PCRE_EXP_DEFN int
pcre_refcount(pcre *argument_re, int adjust)
{
real_pcre *re = (real_pcre *)argument_re;
if (re == NULL) return PCRE_ERROR_NULL;
re->ref_count = (-adjust > re->ref_count)? 0 :
(adjust + re->ref_count > 65535)? 65535 :
re->ref_count + adjust;
return re->ref_count;
}
/* End of pcre_refcount.c */
+579
View File
@@ -0,0 +1,579 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2007 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains the external function pcre_study(), along with local
supporting functions. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/* Returns from set_start_bits() */
enum { SSB_FAIL, SSB_DONE, SSB_CONTINUE };
/*************************************************
* Set a bit and maybe its alternate case *
*************************************************/
/* Given a character, set its bit in the table, and also the bit for the other
version of a letter if we are caseless.
Arguments:
start_bits points to the bit map
c is the character
caseless the caseless flag
cd the block with char table pointers
Returns: nothing
*/
static void
set_bit(uschar *start_bits, unsigned int c, BOOL caseless, compile_data *cd)
{
start_bits[c/8] |= (1 << (c&7));
if (caseless && (cd->ctypes[c] & ctype_letter) != 0)
start_bits[cd->fcc[c]/8] |= (1 << (cd->fcc[c]&7));
}
/*************************************************
* Create bitmap of starting bytes *
*************************************************/
/* This function scans a compiled unanchored expression recursively and
attempts to build a bitmap of the set of possible starting bytes. As time goes
by, we may be able to get more clever at doing this. The SSB_CONTINUE return is
useful for parenthesized groups in patterns such as (a*)b where the group
provides some optional starting bytes but scanning must continue at the outer
level to find at least one mandatory byte. At the outermost level, this
function fails unless the result is SSB_DONE.
Arguments:
code points to an expression
start_bits points to a 32-byte table, initialized to 0
caseless the current state of the caseless flag
utf8 TRUE if in UTF-8 mode
cd the block with char table pointers
Returns: SSB_FAIL => Failed to find any starting bytes
SSB_DONE => Found mandatory starting bytes
SSB_CONTINUE => Found optional starting bytes
*/
static int
set_start_bits(const uschar *code, uschar *start_bits, BOOL caseless,
BOOL utf8, compile_data *cd)
{
register int c;
int yield = SSB_DONE;
#if 0
/* ========================================================================= */
/* The following comment and code was inserted in January 1999. In May 2006,
when it was observed to cause compiler warnings about unused values, I took it
out again. If anybody is still using OS/2, they will have to put it back
manually. */
/* This next statement and the later reference to dummy are here in order to
trick the optimizer of the IBM C compiler for OS/2 into generating correct
code. Apparently IBM isn't going to fix the problem, and we would rather not
disable optimization (in this module it actually makes a big difference, and
the pcre module can use all the optimization it can get). */
volatile int dummy;
/* ========================================================================= */
#endif
do
{
const uschar *tcode = code + (((int)*code == OP_CBRA)? 3:1) + LINK_SIZE;
BOOL try_next = TRUE;
while (try_next) /* Loop for items in this branch */
{
int rc;
switch(*tcode)
{
/* Fail if we reach something we don't understand */
default:
return SSB_FAIL;
/* If we hit a bracket or a positive lookahead assertion, recurse to set
bits from within the subpattern. If it can't find anything, we have to
give up. If it finds some mandatory character(s), we are done for this
branch. Otherwise, carry on scanning after the subpattern. */
case OP_BRA:
case OP_SBRA:
case OP_CBRA:
case OP_SCBRA:
case OP_ONCE:
case OP_ASSERT:
rc = set_start_bits(tcode, start_bits, caseless, utf8, cd);
if (rc == SSB_FAIL) return SSB_FAIL;
if (rc == SSB_DONE) try_next = FALSE; else
{
do tcode += GET(tcode, 1); while (*tcode == OP_ALT);
tcode += 1 + LINK_SIZE;
}
break;
/* If we hit ALT or KET, it means we haven't found anything mandatory in
this branch, though we might have found something optional. For ALT, we
continue with the next alternative, but we have to arrange that the final
result from subpattern is SSB_CONTINUE rather than SSB_DONE. For KET,
return SSB_CONTINUE: if this is the top level, that indicates failure,
but after a nested subpattern, it causes scanning to continue. */
case OP_ALT:
yield = SSB_CONTINUE;
try_next = FALSE;
break;
case OP_KET:
case OP_KETRMAX:
case OP_KETRMIN:
return SSB_CONTINUE;
/* Skip over callout */
case OP_CALLOUT:
tcode += 2 + 2*LINK_SIZE;
break;
/* Skip over lookbehind and negative lookahead assertions */
case OP_ASSERT_NOT:
case OP_ASSERTBACK:
case OP_ASSERTBACK_NOT:
do tcode += GET(tcode, 1); while (*tcode == OP_ALT);
tcode += 1 + LINK_SIZE;
break;
/* Skip over an option setting, changing the caseless flag */
case OP_OPT:
caseless = (tcode[1] & PCRE_CASELESS) != 0;
tcode += 2;
break;
/* BRAZERO does the bracket, but carries on. */
case OP_BRAZERO:
case OP_BRAMINZERO:
if (set_start_bits(++tcode, start_bits, caseless, utf8, cd) == SSB_FAIL)
return SSB_FAIL;
/* =========================================================================
See the comment at the head of this function concerning the next line,
which was an old fudge for the benefit of OS/2.
dummy = 1;
========================================================================= */
do tcode += GET(tcode,1); while (*tcode == OP_ALT);
tcode += 1 + LINK_SIZE;
break;
/* Single-char * or ? sets the bit and tries the next item */
case OP_STAR:
case OP_MINSTAR:
case OP_POSSTAR:
case OP_QUERY:
case OP_MINQUERY:
case OP_POSQUERY:
set_bit(start_bits, tcode[1], caseless, cd);
tcode += 2;
#ifdef SUPPORT_UTF8
if (utf8 && tcode[-1] >= 0xc0)
tcode += _pcre_utf8_table4[tcode[-1] & 0x3f];
#endif
break;
/* Single-char upto sets the bit and tries the next */
case OP_UPTO:
case OP_MINUPTO:
case OP_POSUPTO:
set_bit(start_bits, tcode[3], caseless, cd);
tcode += 4;
#ifdef SUPPORT_UTF8
if (utf8 && tcode[-1] >= 0xc0)
tcode += _pcre_utf8_table4[tcode[-1] & 0x3f];
#endif
break;
/* At least one single char sets the bit and stops */
case OP_EXACT: /* Fall through */
tcode += 2;
case OP_CHAR:
case OP_CHARNC:
case OP_PLUS:
case OP_MINPLUS:
case OP_POSPLUS:
set_bit(start_bits, tcode[1], caseless, cd);
try_next = FALSE;
break;
/* Single character type sets the bits and stops */
case OP_NOT_DIGIT:
for (c = 0; c < 32; c++)
start_bits[c] |= ~cd->cbits[c+cbit_digit];
try_next = FALSE;
break;
case OP_DIGIT:
for (c = 0; c < 32; c++)
start_bits[c] |= cd->cbits[c+cbit_digit];
try_next = FALSE;
break;
/* The cbit_space table has vertical tab as whitespace; we have to
discard it. */
case OP_NOT_WHITESPACE:
for (c = 0; c < 32; c++)
{
int d = cd->cbits[c+cbit_space];
if (c == 1) d &= ~0x08;
start_bits[c] |= ~d;
}
try_next = FALSE;
break;
/* The cbit_space table has vertical tab as whitespace; we have to
discard it. */
case OP_WHITESPACE:
for (c = 0; c < 32; c++)
{
int d = cd->cbits[c+cbit_space];
if (c == 1) d &= ~0x08;
start_bits[c] |= d;
}
try_next = FALSE;
break;
case OP_NOT_WORDCHAR:
for (c = 0; c < 32; c++)
start_bits[c] |= ~cd->cbits[c+cbit_word];
try_next = FALSE;
break;
case OP_WORDCHAR:
for (c = 0; c < 32; c++)
start_bits[c] |= cd->cbits[c+cbit_word];
try_next = FALSE;
break;
/* One or more character type fudges the pointer and restarts, knowing
it will hit a single character type and stop there. */
case OP_TYPEPLUS:
case OP_TYPEMINPLUS:
tcode++;
break;
case OP_TYPEEXACT:
tcode += 3;
break;
/* Zero or more repeats of character types set the bits and then
try again. */
case OP_TYPEUPTO:
case OP_TYPEMINUPTO:
case OP_TYPEPOSUPTO:
tcode += 2; /* Fall through */
case OP_TYPESTAR:
case OP_TYPEMINSTAR:
case OP_TYPEPOSSTAR:
case OP_TYPEQUERY:
case OP_TYPEMINQUERY:
case OP_TYPEPOSQUERY:
switch(tcode[1])
{
case OP_ANY:
return SSB_FAIL;
case OP_NOT_DIGIT:
for (c = 0; c < 32; c++)
start_bits[c] |= ~cd->cbits[c+cbit_digit];
break;
case OP_DIGIT:
for (c = 0; c < 32; c++)
start_bits[c] |= cd->cbits[c+cbit_digit];
break;
/* The cbit_space table has vertical tab as whitespace; we have to
discard it. */
case OP_NOT_WHITESPACE:
for (c = 0; c < 32; c++)
{
int d = cd->cbits[c+cbit_space];
if (c == 1) d &= ~0x08;
start_bits[c] |= ~d;
}
break;
/* The cbit_space table has vertical tab as whitespace; we have to
discard it. */
case OP_WHITESPACE:
for (c = 0; c < 32; c++)
{
int d = cd->cbits[c+cbit_space];
if (c == 1) d &= ~0x08;
start_bits[c] |= d;
}
break;
case OP_NOT_WORDCHAR:
for (c = 0; c < 32; c++)
start_bits[c] |= ~cd->cbits[c+cbit_word];
break;
case OP_WORDCHAR:
for (c = 0; c < 32; c++)
start_bits[c] |= cd->cbits[c+cbit_word];
break;
}
tcode += 2;
break;
/* Character class where all the information is in a bit map: set the
bits and either carry on or not, according to the repeat count. If it was
a negative class, and we are operating with UTF-8 characters, any byte
with a value >= 0xc4 is a potentially valid starter because it starts a
character with a value > 255. */
case OP_NCLASS:
#ifdef SUPPORT_UTF8
if (utf8)
{
start_bits[24] |= 0xf0; /* Bits for 0xc4 - 0xc8 */
memset(start_bits+25, 0xff, 7); /* Bits for 0xc9 - 0xff */
}
#endif
/* Fall through */
case OP_CLASS:
{
tcode++;
/* In UTF-8 mode, the bits in a bit map correspond to character
values, not to byte values. However, the bit map we are constructing is
for byte values. So we have to do a conversion for characters whose
value is > 127. In fact, there are only two possible starting bytes for
characters in the range 128 - 255. */
#ifdef SUPPORT_UTF8
if (utf8)
{
for (c = 0; c < 16; c++) start_bits[c] |= tcode[c];
for (c = 128; c < 256; c++)
{
if ((tcode[c/8] && (1 << (c&7))) != 0)
{
int d = (c >> 6) | 0xc0; /* Set bit for this starter */
start_bits[d/8] |= (1 << (d&7)); /* and then skip on to the */
c = (c & 0xc0) + 0x40 - 1; /* next relevant character. */
}
}
}
/* In non-UTF-8 mode, the two bit maps are completely compatible. */
else
#endif
{
for (c = 0; c < 32; c++) start_bits[c] |= tcode[c];
}
/* Advance past the bit map, and act on what follows */
tcode += 32;
switch (*tcode)
{
case OP_CRSTAR:
case OP_CRMINSTAR:
case OP_CRQUERY:
case OP_CRMINQUERY:
tcode++;
break;
case OP_CRRANGE:
case OP_CRMINRANGE:
if (((tcode[1] << 8) + tcode[2]) == 0) tcode += 5;
else try_next = FALSE;
break;
default:
try_next = FALSE;
break;
}
}
break; /* End of bitmap class handling */
} /* End of switch */
} /* End of try_next loop */
code += GET(code, 1); /* Advance to next branch */
}
while (*code == OP_ALT);
return yield;
}
/*************************************************
* Study a compiled expression *
*************************************************/
/* This function is handed a compiled expression that it must study to produce
information that will speed up the matching. It returns a pcre_extra block
which then gets handed back to pcre_exec().
Arguments:
re points to the compiled expression
options contains option bits
errorptr points to where to place error messages;
set NULL unless error
Returns: pointer to a pcre_extra block, with study_data filled in and the
appropriate flag set;
NULL on error or if no optimization possible
*/
PCRE_EXP_DEFN pcre_extra *
pcre_study(const pcre *external_re, int options, const char **errorptr)
{
uschar start_bits[32];
pcre_extra *extra;
pcre_study_data *study;
const uschar *tables;
uschar *code;
compile_data compile_block;
const real_pcre *re = (const real_pcre *)external_re;
*errorptr = NULL;
if (re == NULL || re->magic_number != MAGIC_NUMBER)
{
*errorptr = "argument is not a compiled regular expression";
return NULL;
}
if ((options & ~PUBLIC_STUDY_OPTIONS) != 0)
{
*errorptr = "unknown or incorrect option bit(s) set";
return NULL;
}
code = (uschar *)re + re->name_table_offset +
(re->name_count * re->name_entry_size);
/* For an anchored pattern, or an unanchored pattern that has a first char, or
a multiline pattern that matches only at "line starts", no further processing
at present. */
if ((re->options & PCRE_ANCHORED) != 0 ||
(re->flags & (PCRE_FIRSTSET|PCRE_STARTLINE)) != 0)
return NULL;
/* Set the character tables in the block that is passed around */
tables = re->tables;
if (tables == NULL)
(void)pcre_fullinfo(external_re, NULL, PCRE_INFO_DEFAULT_TABLES,
(void *)(&tables));
compile_block.lcc = tables + lcc_offset;
compile_block.fcc = tables + fcc_offset;
compile_block.cbits = tables + cbits_offset;
compile_block.ctypes = tables + ctypes_offset;
/* See if we can find a fixed set of initial characters for the pattern. */
memset(start_bits, 0, 32 * sizeof(uschar));
if (set_start_bits(code, start_bits, (re->options & PCRE_CASELESS) != 0,
(re->options & PCRE_UTF8) != 0, &compile_block) != SSB_DONE) return NULL;
/* Get a pcre_extra block and a pcre_study_data block. The study data is put in
the latter, which is pointed to by the former, which may also get additional
data set later by the calling program. At the moment, the size of
pcre_study_data is fixed. We nevertheless save it in a field for returning via
the pcre_fullinfo() function so that if it becomes variable in the future, we
don't have to change that code. */
extra = (pcre_extra *)(pcre_malloc)
(sizeof(pcre_extra) + sizeof(pcre_study_data));
if (extra == NULL)
{
*errorptr = "failed to get memory";
return NULL;
}
study = (pcre_study_data *)((char *)extra + sizeof(pcre_extra));
extra->flags = PCRE_EXTRA_STUDY_DATA;
extra->study_data = study;
study->size = sizeof(pcre_study_data);
study->options = PCRE_STUDY_MAPPED;
memcpy(study->start_bits, start_bits, sizeof(start_bits));
return extra;
}
/* End of pcre_study.c */
+318
View File
@@ -0,0 +1,318 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2007 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains some fixed tables that are used by more than one of the
PCRE code modules. The tables are also #included by the pcretest program, which
uses macros to change their names from _pcre_xxx to xxxx, thereby avoiding name
clashes with the library. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/* Table of sizes for the fixed-length opcodes. It's defined in a macro so that
the definition is next to the definition of the opcodes in pcre_internal.h. */
const uschar _pcre_OP_lengths[] = { OP_LENGTHS };
/*************************************************
* Tables for UTF-8 support *
*************************************************/
/* These are the breakpoints for different numbers of bytes in a UTF-8
character. */
#ifdef SUPPORT_UTF8
const int _pcre_utf8_table1[] =
{ 0x7f, 0x7ff, 0xffff, 0x1fffff, 0x3ffffff, 0x7fffffff};
const int _pcre_utf8_table1_size = sizeof(_pcre_utf8_table1)/sizeof(int);
/* These are the indicator bits and the mask for the data bits to set in the
first byte of a character, indexed by the number of additional bytes. */
const int _pcre_utf8_table2[] = { 0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc};
const int _pcre_utf8_table3[] = { 0xff, 0x1f, 0x0f, 0x07, 0x03, 0x01};
/* Table of the number of extra bytes, indexed by the first byte masked with
0x3f. The highest number for a valid UTF-8 first byte is in fact 0x3d. */
const uschar _pcre_utf8_table4[] = {
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 };
/* The pcre_utt[] table below translates Unicode property names into type and
code values. It is searched by binary chop, so must be in collating sequence of
name. Originally, the table contained pointers to the name strings in the first
field of each entry. However, that leads to a large number of relocations when
a shared library is dynamically loaded. A significant reduction is made by
putting all the names into a single, large string and then using offsets in the
table itself. Maintenance is more error-prone, but frequent changes to this
data is unlikely. */
const char _pcre_utt_names[] =
"Any\0"
"Arabic\0"
"Armenian\0"
"Balinese\0"
"Bengali\0"
"Bopomofo\0"
"Braille\0"
"Buginese\0"
"Buhid\0"
"C\0"
"Canadian_Aboriginal\0"
"Cc\0"
"Cf\0"
"Cherokee\0"
"Cn\0"
"Co\0"
"Common\0"
"Coptic\0"
"Cs\0"
"Cuneiform\0"
"Cypriot\0"
"Cyrillic\0"
"Deseret\0"
"Devanagari\0"
"Ethiopic\0"
"Georgian\0"
"Glagolitic\0"
"Gothic\0"
"Greek\0"
"Gujarati\0"
"Gurmukhi\0"
"Han\0"
"Hangul\0"
"Hanunoo\0"
"Hebrew\0"
"Hiragana\0"
"Inherited\0"
"Kannada\0"
"Katakana\0"
"Kharoshthi\0"
"Khmer\0"
"L\0"
"L&\0"
"Lao\0"
"Latin\0"
"Limbu\0"
"Linear_B\0"
"Ll\0"
"Lm\0"
"Lo\0"
"Lt\0"
"Lu\0"
"M\0"
"Malayalam\0"
"Mc\0"
"Me\0"
"Mn\0"
"Mongolian\0"
"Myanmar\0"
"N\0"
"Nd\0"
"New_Tai_Lue\0"
"Nko\0"
"Nl\0"
"No\0"
"Ogham\0"
"Old_Italic\0"
"Old_Persian\0"
"Oriya\0"
"Osmanya\0"
"P\0"
"Pc\0"
"Pd\0"
"Pe\0"
"Pf\0"
"Phags_Pa\0"
"Phoenician\0"
"Pi\0"
"Po\0"
"Ps\0"
"Runic\0"
"S\0"
"Sc\0"
"Shavian\0"
"Sinhala\0"
"Sk\0"
"Sm\0"
"So\0"
"Syloti_Nagri\0"
"Syriac\0"
"Tagalog\0"
"Tagbanwa\0"
"Tai_Le\0"
"Tamil\0"
"Telugu\0"
"Thaana\0"
"Thai\0"
"Tibetan\0"
"Tifinagh\0"
"Ugaritic\0"
"Yi\0"
"Z\0"
"Zl\0"
"Zp\0"
"Zs\0";
const ucp_type_table _pcre_utt[] = {
{ 0, PT_ANY, 0 },
{ 4, PT_SC, ucp_Arabic },
{ 11, PT_SC, ucp_Armenian },
{ 20, PT_SC, ucp_Balinese },
{ 29, PT_SC, ucp_Bengali },
{ 37, PT_SC, ucp_Bopomofo },
{ 46, PT_SC, ucp_Braille },
{ 54, PT_SC, ucp_Buginese },
{ 63, PT_SC, ucp_Buhid },
{ 69, PT_GC, ucp_C },
{ 71, PT_SC, ucp_Canadian_Aboriginal },
{ 91, PT_PC, ucp_Cc },
{ 94, PT_PC, ucp_Cf },
{ 97, PT_SC, ucp_Cherokee },
{ 106, PT_PC, ucp_Cn },
{ 109, PT_PC, ucp_Co },
{ 112, PT_SC, ucp_Common },
{ 119, PT_SC, ucp_Coptic },
{ 126, PT_PC, ucp_Cs },
{ 129, PT_SC, ucp_Cuneiform },
{ 139, PT_SC, ucp_Cypriot },
{ 147, PT_SC, ucp_Cyrillic },
{ 156, PT_SC, ucp_Deseret },
{ 164, PT_SC, ucp_Devanagari },
{ 175, PT_SC, ucp_Ethiopic },
{ 184, PT_SC, ucp_Georgian },
{ 193, PT_SC, ucp_Glagolitic },
{ 204, PT_SC, ucp_Gothic },
{ 211, PT_SC, ucp_Greek },
{ 217, PT_SC, ucp_Gujarati },
{ 226, PT_SC, ucp_Gurmukhi },
{ 235, PT_SC, ucp_Han },
{ 239, PT_SC, ucp_Hangul },
{ 246, PT_SC, ucp_Hanunoo },
{ 254, PT_SC, ucp_Hebrew },
{ 261, PT_SC, ucp_Hiragana },
{ 270, PT_SC, ucp_Inherited },
{ 280, PT_SC, ucp_Kannada },
{ 288, PT_SC, ucp_Katakana },
{ 297, PT_SC, ucp_Kharoshthi },
{ 308, PT_SC, ucp_Khmer },
{ 314, PT_GC, ucp_L },
{ 316, PT_LAMP, 0 },
{ 319, PT_SC, ucp_Lao },
{ 323, PT_SC, ucp_Latin },
{ 329, PT_SC, ucp_Limbu },
{ 335, PT_SC, ucp_Linear_B },
{ 344, PT_PC, ucp_Ll },
{ 347, PT_PC, ucp_Lm },
{ 350, PT_PC, ucp_Lo },
{ 353, PT_PC, ucp_Lt },
{ 356, PT_PC, ucp_Lu },
{ 359, PT_GC, ucp_M },
{ 361, PT_SC, ucp_Malayalam },
{ 371, PT_PC, ucp_Mc },
{ 374, PT_PC, ucp_Me },
{ 377, PT_PC, ucp_Mn },
{ 380, PT_SC, ucp_Mongolian },
{ 390, PT_SC, ucp_Myanmar },
{ 398, PT_GC, ucp_N },
{ 400, PT_PC, ucp_Nd },
{ 403, PT_SC, ucp_New_Tai_Lue },
{ 415, PT_SC, ucp_Nko },
{ 419, PT_PC, ucp_Nl },
{ 422, PT_PC, ucp_No },
{ 425, PT_SC, ucp_Ogham },
{ 431, PT_SC, ucp_Old_Italic },
{ 442, PT_SC, ucp_Old_Persian },
{ 454, PT_SC, ucp_Oriya },
{ 460, PT_SC, ucp_Osmanya },
{ 468, PT_GC, ucp_P },
{ 470, PT_PC, ucp_Pc },
{ 473, PT_PC, ucp_Pd },
{ 476, PT_PC, ucp_Pe },
{ 479, PT_PC, ucp_Pf },
{ 482, PT_SC, ucp_Phags_Pa },
{ 491, PT_SC, ucp_Phoenician },
{ 502, PT_PC, ucp_Pi },
{ 505, PT_PC, ucp_Po },
{ 508, PT_PC, ucp_Ps },
{ 511, PT_SC, ucp_Runic },
{ 517, PT_GC, ucp_S },
{ 519, PT_PC, ucp_Sc },
{ 522, PT_SC, ucp_Shavian },
{ 530, PT_SC, ucp_Sinhala },
{ 538, PT_PC, ucp_Sk },
{ 541, PT_PC, ucp_Sm },
{ 544, PT_PC, ucp_So },
{ 547, PT_SC, ucp_Syloti_Nagri },
{ 560, PT_SC, ucp_Syriac },
{ 567, PT_SC, ucp_Tagalog },
{ 575, PT_SC, ucp_Tagbanwa },
{ 584, PT_SC, ucp_Tai_Le },
{ 591, PT_SC, ucp_Tamil },
{ 597, PT_SC, ucp_Telugu },
{ 604, PT_SC, ucp_Thaana },
{ 611, PT_SC, ucp_Thai },
{ 616, PT_SC, ucp_Tibetan },
{ 624, PT_SC, ucp_Tifinagh },
{ 633, PT_SC, ucp_Ugaritic },
{ 642, PT_SC, ucp_Yi },
{ 645, PT_GC, ucp_Z },
{ 647, PT_PC, ucp_Zl },
{ 650, PT_PC, ucp_Zp },
{ 653, PT_PC, ucp_Zs }
};
const int _pcre_utt_size = sizeof(_pcre_utt)/sizeof(ucp_type_table);
#endif /* SUPPORT_UTF8 */
/* End of pcre_tables.c */
+137
View File
@@ -0,0 +1,137 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2007 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains an internal function that tests a compiled pattern to
see if it was compiled with the opposite endianness. If so, it uses an
auxiliary local function to flip the appropriate bytes. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/*************************************************
* Flip bytes in an integer *
*************************************************/
/* This function is called when the magic number in a regex doesn't match, in
order to flip its bytes to see if we are dealing with a pattern that was
compiled on a host of different endianness. If so, this function is used to
flip other byte values.
Arguments:
value the number to flip
n the number of bytes to flip (assumed to be 2 or 4)
Returns: the flipped value
*/
static unsigned long int
byteflip(unsigned long int value, int n)
{
if (n == 2) return ((value & 0x00ff) << 8) | ((value & 0xff00) >> 8);
return ((value & 0x000000ff) << 24) |
((value & 0x0000ff00) << 8) |
((value & 0x00ff0000) >> 8) |
((value & 0xff000000) >> 24);
}
/*************************************************
* Test for a byte-flipped compiled regex *
*************************************************/
/* This function is called from pcre_exec(), pcre_dfa_exec(), and also from
pcre_fullinfo(). Its job is to test whether the regex is byte-flipped - that
is, it was compiled on a system of opposite endianness. The function is called
only when the native MAGIC_NUMBER test fails. If the regex is indeed flipped,
we flip all the relevant values into a different data block, and return it.
Arguments:
re points to the regex
study points to study data, or NULL
internal_re points to a new regex block
internal_study points to a new study block
Returns: the new block if is is indeed a byte-flipped regex
NULL if it is not
*/
real_pcre *
_pcre_try_flipped(const real_pcre *re, real_pcre *internal_re,
const pcre_study_data *study, pcre_study_data *internal_study)
{
if (byteflip(re->magic_number, sizeof(re->magic_number)) != MAGIC_NUMBER)
return NULL;
*internal_re = *re; /* To copy other fields */
internal_re->size = byteflip(re->size, sizeof(re->size));
internal_re->options = byteflip(re->options, sizeof(re->options));
internal_re->flags = (pcre_uint16)byteflip(re->flags, sizeof(re->flags));
internal_re->top_bracket =
(pcre_uint16)byteflip(re->top_bracket, sizeof(re->top_bracket));
internal_re->top_backref =
(pcre_uint16)byteflip(re->top_backref, sizeof(re->top_backref));
internal_re->first_byte =
(pcre_uint16)byteflip(re->first_byte, sizeof(re->first_byte));
internal_re->req_byte =
(pcre_uint16)byteflip(re->req_byte, sizeof(re->req_byte));
internal_re->name_table_offset =
(pcre_uint16)byteflip(re->name_table_offset, sizeof(re->name_table_offset));
internal_re->name_entry_size =
(pcre_uint16)byteflip(re->name_entry_size, sizeof(re->name_entry_size));
internal_re->name_count =
(pcre_uint16)byteflip(re->name_count, sizeof(re->name_count));
if (study != NULL)
{
*internal_study = *study; /* To copy other fields */
internal_study->size = byteflip(study->size, sizeof(study->size));
internal_study->options = byteflip(study->options, sizeof(study->options));
}
return internal_re;
}
/* End of pcre_tryflipped.c */
@@ -0,0 +1,179 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2007 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains code for searching the table of Unicode character
properties. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
#include "ucp.h" /* Category definitions */
#include "ucpinternal.h" /* Internal table details */
#include "ucptable.h" /* The table itself */
/* Table to translate from particular type value to the general value. */
static const int ucp_gentype[] = {
ucp_C, ucp_C, ucp_C, ucp_C, ucp_C, /* Cc, Cf, Cn, Co, Cs */
ucp_L, ucp_L, ucp_L, ucp_L, ucp_L, /* Ll, Lu, Lm, Lo, Lt */
ucp_M, ucp_M, ucp_M, /* Mc, Me, Mn */
ucp_N, ucp_N, ucp_N, /* Nd, Nl, No */
ucp_P, ucp_P, ucp_P, ucp_P, ucp_P, /* Pc, Pd, Pe, Pf, Pi */
ucp_P, ucp_P, /* Ps, Po */
ucp_S, ucp_S, ucp_S, ucp_S, /* Sc, Sk, Sm, So */
ucp_Z, ucp_Z, ucp_Z /* Zl, Zp, Zs */
};
/*************************************************
* Search table and return type *
*************************************************/
/* Three values are returned: the category is ucp_C, ucp_L, etc. The detailed
character type is ucp_Lu, ucp_Nd, etc. The script is ucp_Latin, etc.
Arguments:
c the character value
type_ptr the detailed character type is returned here
script_ptr the script is returned here
Returns: the character type category
*/
int
_pcre_ucp_findprop(const unsigned int c, int *type_ptr, int *script_ptr)
{
int bot = 0;
int top = sizeof(ucp_table)/sizeof(cnode);
int mid;
/* The table is searched using a binary chop. You might think that using
intermediate variables to hold some of the common expressions would speed
things up, but tests with gcc 3.4.4 on Linux showed that, on the contrary, it
makes things a lot slower. */
for (;;)
{
if (top <= bot)
{
*type_ptr = ucp_Cn;
*script_ptr = ucp_Common;
return ucp_C;
}
mid = (bot + top) >> 1;
if (c == (ucp_table[mid].f0 & f0_charmask)) break;
if (c < (ucp_table[mid].f0 & f0_charmask)) top = mid;
else
{
if ((ucp_table[mid].f0 & f0_rangeflag) != 0 &&
c <= (ucp_table[mid].f0 & f0_charmask) +
(ucp_table[mid].f1 & f1_rangemask)) break;
bot = mid + 1;
}
}
/* Found an entry in the table. Set the script and detailed type values, and
return the general type. */
*script_ptr = (ucp_table[mid].f0 & f0_scriptmask) >> f0_scriptshift;
*type_ptr = (ucp_table[mid].f1 & f1_typemask) >> f1_typeshift;
return ucp_gentype[*type_ptr];
}
/*************************************************
* Search table and return other case *
*************************************************/
/* If the given character is a letter, and there is another case for the
letter, return the other case. Otherwise, return -1.
Arguments:
c the character value
Returns: the other case or NOTACHAR if none
*/
unsigned int
_pcre_ucp_othercase(const unsigned int c)
{
int bot = 0;
int top = sizeof(ucp_table)/sizeof(cnode);
int mid, offset;
/* The table is searched using a binary chop. You might think that using
intermediate variables to hold some of the common expressions would speed
things up, but tests with gcc 3.4.4 on Linux showed that, on the contrary, it
makes things a lot slower. */
for (;;)
{
if (top <= bot) return -1;
mid = (bot + top) >> 1;
if (c == (ucp_table[mid].f0 & f0_charmask)) break;
if (c < (ucp_table[mid].f0 & f0_charmask)) top = mid;
else
{
if ((ucp_table[mid].f0 & f0_rangeflag) != 0 &&
c <= (ucp_table[mid].f0 & f0_charmask) +
(ucp_table[mid].f1 & f1_rangemask)) break;
bot = mid + 1;
}
}
/* Found an entry in the table. Return NOTACHAR for a range entry. Otherwise
return the other case if there is one, else NOTACHAR. */
if ((ucp_table[mid].f0 & f0_rangeflag) != 0) return NOTACHAR;
offset = ucp_table[mid].f1 & f1_casemask;
if ((offset & f1_caseneg) != 0) offset |= f1_caseneg;
return (offset == 0)? NOTACHAR : c + offset;
}
/* End of pcre_ucp_searchfuncs.c */
+162
View File
@@ -0,0 +1,162 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2007 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains an internal function for validating UTF-8 character
strings. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/*************************************************
* Validate a UTF-8 string *
*************************************************/
/* This function is called (optionally) at the start of compile or match, to
validate that a supposed UTF-8 string is actually valid. The early check means
that subsequent code can assume it is dealing with a valid string. The check
can be turned off for maximum performance, but the consequences of supplying
an invalid string are then undefined.
Originally, this function checked according to RFC 2279, allowing for values in
the range 0 to 0x7fffffff, up to 6 bytes long, but ensuring that they were in
the canonical format. Once somebody had pointed out RFC 3629 to me (it
obsoletes 2279), additional restrictions were applies. The values are now
limited to be between 0 and 0x0010ffff, no more than 4 bytes long, and the
subrange 0xd000 to 0xdfff is excluded.
Arguments:
string points to the string
length length of string, or -1 if the string is zero-terminated
Returns: < 0 if the string is a valid UTF-8 string
>= 0 otherwise; the value is the offset of the bad byte
*/
int
_pcre_valid_utf8(const uschar *string, int length)
{
#ifdef SUPPORT_UTF8
register const uschar *p;
if (length < 0)
{
for (p = string; *p != 0; p++);
length = p - string;
}
for (p = string; length-- > 0; p++)
{
register int ab;
register int c = *p;
if (c < 128) continue;
if (c < 0xc0) return p - string;
ab = _pcre_utf8_table4[c & 0x3f]; /* Number of additional bytes */
if (length < ab || ab > 3) return p - string;
length -= ab;
/* Check top bits in the second byte */
if ((*(++p) & 0xc0) != 0x80) return p - string;
/* Check for overlong sequences for each different length, and for the
excluded range 0xd000 to 0xdfff. */
switch (ab)
{
/* Check for xx00 000x (overlong sequence) */
case 1:
if ((c & 0x3e) == 0) return p - string;
continue; /* We know there aren't any more bytes to check */
/* Check for 1110 0000, xx0x xxxx (overlong sequence) or
1110 1101, 1010 xxxx (0xd000 - 0xdfff) */
case 2:
if ((c == 0xe0 && (*p & 0x20) == 0) ||
(c == 0xed && *p >= 0xa0))
return p - string;
break;
/* Check for 1111 0000, xx00 xxxx (overlong sequence) or
greater than 0x0010ffff (f4 8f bf bf) */
case 3:
if ((c == 0xf0 && (*p & 0x30) == 0) ||
(c > 0xf4 ) ||
(c == 0xf4 && *p > 0x8f))
return p - string;
break;
#if 0
/* These cases can no longer occur, as we restrict to a maximum of four
bytes nowadays. Leave the code here in case we ever want to add an option
for longer sequences. */
/* Check for 1111 1000, xx00 0xxx */
case 4:
if (c == 0xf8 && (*p & 0x38) == 0) return p - string;
break;
/* Check for leading 0xfe or 0xff, and then for 1111 1100, xx00 00xx */
case 5:
if (c == 0xfe || c == 0xff ||
(c == 0xfc && (*p & 0x3c) == 0)) return p - string;
break;
#endif
}
/* Check for valid bytes after the 2nd, if any; all must start 10 */
while (--ab > 0)
{
if ((*(++p) & 0xc0) != 0x80) return p - string;
}
}
#endif
return -1;
}
/* End of pcre_valid_utf8.c */
+90
View File
@@ -0,0 +1,90 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2007 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains the external function pcre_version(), which returns a
string that identifies the PCRE version that is in use. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/*************************************************
* Return version string *
*************************************************/
/* These macros are the standard way of turning unquoted text into C strings.
They allow macros like PCRE_MAJOR to be defined without quotes, which is
convenient for user programs that want to test its value. */
#define STRING(a) # a
#define XSTRING(s) STRING(s)
/* A problem turned up with PCRE_PRERELEASE, which is defined empty for
production releases. Originally, it was used naively in this code:
return XSTRING(PCRE_MAJOR)
"." XSTRING(PCRE_MINOR)
XSTRING(PCRE_PRERELEASE)
" " XSTRING(PCRE_DATE);
However, when PCRE_PRERELEASE is empty, this leads to an attempted expansion of
STRING(). The C standard states: "If (before argument substitution) any
argument consists of no preprocessing tokens, the behavior is undefined." It
turns out the gcc treats this case as a single empty string - which is what we
really want - but Visual C grumbles about the lack of an argument for the
macro. Unfortunately, both are within their rights. To cope with both ways of
handling this, I had resort to some messy hackery that does a test at run time.
I could find no way of detecting that a macro is defined as an empty string at
pre-processor time. This hack uses a standard trick for avoiding calling
the STRING macro with an empty argument when doing the test. */
PCRE_EXP_DEFN const char *
pcre_version(void)
{
return (XSTRING(Z PCRE_PRERELEASE)[1] == 0)?
XSTRING(PCRE_MAJOR.PCRE_MINOR PCRE_DATE) :
XSTRING(PCRE_MAJOR.PCRE_MINOR) XSTRING(PCRE_PRERELEASE PCRE_DATE);
}
/* End of pcre_version.c */
+148
View File
@@ -0,0 +1,148 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2007 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains an internal function that is used to match an extended
class (one that contains characters whose values are > 255). It is used by both
pcre_exec() and pcre_def_exec(). */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/*************************************************
* Match character against an XCLASS *
*************************************************/
/* This function is called to match a character against an extended class that
might contain values > 255.
Arguments:
c the character
data points to the flag byte of the XCLASS data
Returns: TRUE if character matches, else FALSE
*/
BOOL
_pcre_xclass(int c, const uschar *data)
{
int t;
BOOL negated = (*data & XCL_NOT) != 0;
/* Character values < 256 are matched against a bitmap, if one is present. If
not, we still carry on, because there may be ranges that start below 256 in the
additional data. */
if (c < 256)
{
if ((*data & XCL_MAP) != 0 && (data[1 + c/8] & (1 << (c&7))) != 0)
return !negated; /* char found */
}
/* First skip the bit map if present. Then match against the list of Unicode
properties or large chars or ranges that end with a large char. We won't ever
encounter XCL_PROP or XCL_NOTPROP when UCP support is not compiled. */
if ((*data++ & XCL_MAP) != 0) data += 32;
while ((t = *data++) != XCL_END)
{
int x, y;
if (t == XCL_SINGLE)
{
GETCHARINC(x, data);
if (c == x) return !negated;
}
else if (t == XCL_RANGE)
{
GETCHARINC(x, data);
GETCHARINC(y, data);
if (c >= x && c <= y) return !negated;
}
#ifdef SUPPORT_UCP
else /* XCL_PROP & XCL_NOTPROP */
{
int chartype, script;
int category = _pcre_ucp_findprop(c, &chartype, &script);
switch(*data)
{
case PT_ANY:
if (t == XCL_PROP) return !negated;
break;
case PT_LAMP:
if ((chartype == ucp_Lu || chartype == ucp_Ll || chartype == ucp_Lt) ==
(t == XCL_PROP)) return !negated;
break;
case PT_GC:
if ((data[1] == category) == (t == XCL_PROP)) return !negated;
break;
case PT_PC:
if ((data[1] == chartype) == (t == XCL_PROP)) return !negated;
break;
case PT_SC:
if ((data[1] == script) == (t == XCL_PROP)) return !negated;
break;
/* This should never occur, but compilers may mutter if there is no
default. */
default:
return FALSE;
}
data += 2;
}
#endif /* SUPPORT_UCP */
}
return negated; /* char did not match */
}
/* End of pcre_xclass.c */
+337
View File
@@ -0,0 +1,337 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2007 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module is a wrapper that provides a POSIX API to the underlying PCRE
functions. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* Ensure that the PCREPOSIX_EXP_xxx macros are set appropriately for
compiling these functions. This must come before including pcreposix.h, where
they are set for an application (using these functions) if they have not
previously been set. */
#if defined(_WIN32) && !defined(PCRE_STATIC)
# define PCREPOSIX_EXP_DECL extern __declspec(dllexport)
# define PCREPOSIX_EXP_DEFN __declspec(dllexport)
#endif
#include "pcre.h"
#include "pcre_internal.h"
#include "pcreposix.h"
/* Table to translate PCRE compile time error codes into POSIX error codes. */
static const int eint[] = {
0, /* no error */
REG_EESCAPE, /* \ at end of pattern */
REG_EESCAPE, /* \c at end of pattern */
REG_EESCAPE, /* unrecognized character follows \ */
REG_BADBR, /* numbers out of order in {} quantifier */
REG_BADBR, /* number too big in {} quantifier */
REG_EBRACK, /* missing terminating ] for character class */
REG_ECTYPE, /* invalid escape sequence in character class */
REG_ERANGE, /* range out of order in character class */
REG_BADRPT, /* nothing to repeat */
REG_BADRPT, /* operand of unlimited repeat could match the empty string */
REG_ASSERT, /* internal error: unexpected repeat */
REG_BADPAT, /* unrecognized character after (? */
REG_BADPAT, /* POSIX named classes are supported only within a class */
REG_EPAREN, /* missing ) */
REG_ESUBREG, /* reference to non-existent subpattern */
REG_INVARG, /* erroffset passed as NULL */
REG_INVARG, /* unknown option bit(s) set */
REG_EPAREN, /* missing ) after comment */
REG_ESIZE, /* parentheses nested too deeply */
REG_ESIZE, /* regular expression too large */
REG_ESPACE, /* failed to get memory */
REG_EPAREN, /* unmatched brackets */
REG_ASSERT, /* internal error: code overflow */
REG_BADPAT, /* unrecognized character after (?< */
REG_BADPAT, /* lookbehind assertion is not fixed length */
REG_BADPAT, /* malformed number or name after (?( */
REG_BADPAT, /* conditional group contains more than two branches */
REG_BADPAT, /* assertion expected after (?( */
REG_BADPAT, /* (?R or (?[+-]digits must be followed by ) */
REG_ECTYPE, /* unknown POSIX class name */
REG_BADPAT, /* POSIX collating elements are not supported */
REG_INVARG, /* this version of PCRE is not compiled with PCRE_UTF8 support */
REG_BADPAT, /* spare error */
REG_BADPAT, /* character value in \x{...} sequence is too large */
REG_BADPAT, /* invalid condition (?(0) */
REG_BADPAT, /* \C not allowed in lookbehind assertion */
REG_EESCAPE, /* PCRE does not support \L, \l, \N, \U, or \u */
REG_BADPAT, /* number after (?C is > 255 */
REG_BADPAT, /* closing ) for (?C expected */
REG_BADPAT, /* recursive call could loop indefinitely */
REG_BADPAT, /* unrecognized character after (?P */
REG_BADPAT, /* syntax error in subpattern name (missing terminator) */
REG_BADPAT, /* two named subpatterns have the same name */
REG_BADPAT, /* invalid UTF-8 string */
REG_BADPAT, /* support for \P, \p, and \X has not been compiled */
REG_BADPAT, /* malformed \P or \p sequence */
REG_BADPAT, /* unknown property name after \P or \p */
REG_BADPAT, /* subpattern name is too long (maximum 32 characters) */
REG_BADPAT, /* too many named subpatterns (maximum 10,000) */
REG_BADPAT, /* repeated subpattern is too long */
REG_BADPAT, /* octal value is greater than \377 (not in UTF-8 mode) */
REG_BADPAT, /* internal error: overran compiling workspace */
REG_BADPAT, /* internal error: previously-checked referenced subpattern not found */
REG_BADPAT, /* DEFINE group contains more than one branch */
REG_BADPAT, /* repeating a DEFINE group is not allowed */
REG_INVARG, /* inconsistent NEWLINE options */
REG_BADPAT, /* \g is not followed followed by an (optionally braced) non-zero number */
REG_BADPAT, /* (?+ or (?- must be followed by a non-zero number */
REG_BADPAT /* number is too big */
};
/* Table of texts corresponding to POSIX error codes */
static const char *const pstring[] = {
"", /* Dummy for value 0 */
"internal error", /* REG_ASSERT */
"invalid repeat counts in {}", /* BADBR */
"pattern error", /* BADPAT */
"? * + invalid", /* BADRPT */
"unbalanced {}", /* EBRACE */
"unbalanced []", /* EBRACK */
"collation error - not relevant", /* ECOLLATE */
"bad class", /* ECTYPE */
"bad escape sequence", /* EESCAPE */
"empty expression", /* EMPTY */
"unbalanced ()", /* EPAREN */
"bad range inside []", /* ERANGE */
"expression too big", /* ESIZE */
"failed to get memory", /* ESPACE */
"bad back reference", /* ESUBREG */
"bad argument", /* INVARG */
"match failed" /* NOMATCH */
};
/*************************************************
* Translate error code to string *
*************************************************/
PCREPOSIX_EXP_DEFN size_t
regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
{
const char *message, *addmessage;
size_t length, addlength;
message = (errcode >= (int)(sizeof(pstring)/sizeof(char *)))?
"unknown error code" : pstring[errcode];
length = strlen(message) + 1;
addmessage = " at offset ";
addlength = (preg != NULL && (int)preg->re_erroffset != -1)?
strlen(addmessage) + 6 : 0;
if (errbuf_size > 0)
{
if (addlength > 0 && errbuf_size >= length + addlength)
sprintf(errbuf, "%s%s%-6d", message, addmessage, (int)preg->re_erroffset);
else
{
strncpy(errbuf, message, errbuf_size - 1);
errbuf[errbuf_size-1] = 0;
}
}
return length + addlength;
}
/*************************************************
* Free store held by a regex *
*************************************************/
PCREPOSIX_EXP_DEFN void
regfree(regex_t *preg)
{
(pcre_free)(preg->re_pcre);
}
/*************************************************
* Compile a regular expression *
*************************************************/
/*
Arguments:
preg points to a structure for recording the compiled expression
pattern the pattern to compile
cflags compilation flags
Returns: 0 on success
various non-zero codes on failure
*/
PCREPOSIX_EXP_DEFN int
regcomp(regex_t *preg, const char *pattern, int cflags)
{
const char *errorptr;
int erroffset;
int errorcode;
int options = 0;
if ((cflags & REG_ICASE) != 0) options |= PCRE_CASELESS;
if ((cflags & REG_NEWLINE) != 0) options |= PCRE_MULTILINE;
if ((cflags & REG_DOTALL) != 0) options |= PCRE_DOTALL;
if ((cflags & REG_NOSUB) != 0) options |= PCRE_NO_AUTO_CAPTURE;
if ((cflags & REG_UTF8) != 0) options |= PCRE_UTF8;
preg->re_pcre = pcre_compile2(pattern, options, &errorcode, &errorptr,
&erroffset, NULL);
preg->re_erroffset = erroffset;
if (preg->re_pcre == NULL) return eint[errorcode];
preg->re_nsub = pcre_info((const pcre *)preg->re_pcre, NULL, NULL);
return 0;
}
/*************************************************
* Match a regular expression *
*************************************************/
/* Unfortunately, PCRE requires 3 ints of working space for each captured
substring, so we have to get and release working store instead of just using
the POSIX structures as was done in earlier releases when PCRE needed only 2
ints. However, if the number of possible capturing brackets is small, use a
block of store on the stack, to reduce the use of malloc/free. The threshold is
in a macro that can be changed at configure time.
If REG_NOSUB was specified at compile time, the PCRE_NO_AUTO_CAPTURE flag will
be set. When this is the case, the nmatch and pmatch arguments are ignored, and
the only result is yes/no/error. */
PCREPOSIX_EXP_DEFN int
regexec(const regex_t *preg, const char *string, size_t nmatch,
regmatch_t pmatch[], int eflags)
{
int rc;
int options = 0;
int *ovector = NULL;
int small_ovector[POSIX_MALLOC_THRESHOLD * 3];
BOOL allocated_ovector = FALSE;
BOOL nosub =
(((const pcre *)preg->re_pcre)->options & PCRE_NO_AUTO_CAPTURE) != 0;
if ((eflags & REG_NOTBOL) != 0) options |= PCRE_NOTBOL;
if ((eflags & REG_NOTEOL) != 0) options |= PCRE_NOTEOL;
((regex_t *)preg)->re_erroffset = (size_t)(-1); /* Only has meaning after compile */
/* When no string data is being returned, ensure that nmatch is zero.
Otherwise, ensure the vector for holding the return data is large enough. */
if (nosub) nmatch = 0;
else if (nmatch > 0)
{
if (nmatch <= POSIX_MALLOC_THRESHOLD)
{
ovector = &(small_ovector[0]);
}
else
{
if (nmatch > INT_MAX/(sizeof(int) * 3)) return REG_ESPACE;
ovector = (int *)malloc(sizeof(int) * nmatch * 3);
if (ovector == NULL) return REG_ESPACE;
allocated_ovector = TRUE;
}
}
rc = pcre_exec((const pcre *)preg->re_pcre, NULL, string, (int)strlen(string),
0, options, ovector, nmatch * 3);
if (rc == 0) rc = nmatch; /* All captured slots were filled in */
if (rc >= 0)
{
size_t i;
if (!nosub)
{
for (i = 0; i < (size_t)rc; i++)
{
pmatch[i].rm_so = ovector[i*2];
pmatch[i].rm_eo = ovector[i*2+1];
}
if (allocated_ovector) free(ovector);
for (; i < nmatch; i++) pmatch[i].rm_so = pmatch[i].rm_eo = -1;
}
return 0;
}
else
{
if (allocated_ovector) free(ovector);
switch(rc)
{
case PCRE_ERROR_NOMATCH: return REG_NOMATCH;
case PCRE_ERROR_NULL: return REG_INVARG;
case PCRE_ERROR_BADOPTION: return REG_INVARG;
case PCRE_ERROR_BADMAGIC: return REG_INVARG;
case PCRE_ERROR_UNKNOWN_NODE: return REG_ASSERT;
case PCRE_ERROR_NOMEMORY: return REG_ESPACE;
case PCRE_ERROR_MATCHLIMIT: return REG_ESPACE;
case PCRE_ERROR_BADUTF8: return REG_INVARG;
case PCRE_ERROR_BADUTF8_OFFSET: return REG_INVARG;
default: return REG_ASSERT;
}
}
}
/* End of pcreposix.c */
+142
View File
@@ -0,0 +1,142 @@
/*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
#ifndef _PCREPOSIX_H
#define _PCREPOSIX_H
/* This is the header for the POSIX wrapper interface to the PCRE Perl-
Compatible Regular Expression library. It defines the things POSIX says should
be there. I hope.
Copyright (c) 1997-2007 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* Have to include stdlib.h in order to ensure that size_t is defined. */
#include <stdlib.h>
/* Allow for C++ users */
#ifdef __cplusplus
extern "C" {
#endif
/* Options, mostly defined by POSIX, but with a couple of extras. */
#define REG_ICASE 0x0001
#define REG_NEWLINE 0x0002
#define REG_NOTBOL 0x0004
#define REG_NOTEOL 0x0008
#define REG_DOTALL 0x0010 /* NOT defined by POSIX. */
#define REG_NOSUB 0x0020
#define REG_UTF8 0x0040 /* NOT defined by POSIX. */
/* This is not used by PCRE, but by defining it we make it easier
to slot PCRE into existing programs that make POSIX calls. */
#define REG_EXTENDED 0
/* Error values. Not all these are relevant or used by the wrapper. */
enum {
REG_ASSERT = 1, /* internal error ? */
REG_BADBR, /* invalid repeat counts in {} */
REG_BADPAT, /* pattern error */
REG_BADRPT, /* ? * + invalid */
REG_EBRACE, /* unbalanced {} */
REG_EBRACK, /* unbalanced [] */
REG_ECOLLATE, /* collation error - not relevant */
REG_ECTYPE, /* bad class */
REG_EESCAPE, /* bad escape sequence */
REG_EMPTY, /* empty expression */
REG_EPAREN, /* unbalanced () */
REG_ERANGE, /* bad range inside [] */
REG_ESIZE, /* expression too big */
REG_ESPACE, /* failed to get memory */
REG_ESUBREG, /* bad back reference */
REG_INVARG, /* bad argument */
REG_NOMATCH /* match failed */
};
/* The structure representing a compiled regular expression. */
typedef struct {
void *re_pcre;
size_t re_nsub;
size_t re_erroffset;
} regex_t;
/* The structure in which a captured offset is returned. */
typedef int regoff_t;
typedef struct {
regoff_t rm_so;
regoff_t rm_eo;
} regmatch_t;
/* When an application links to a PCRE DLL in Windows, the symbols that are
imported have to be identified as such. When building PCRE, the appropriate
export settings are needed, and are set in pcreposix.c before including this
file. */
#if defined(_WIN32) && !defined(PCRE_STATIC) && !defined(PCREPOSIX_EXP_DECL)
# define PCREPOSIX_EXP_DECL extern __declspec(dllimport)
# define PCREPOSIX_EXP_DEFN __declspec(dllimport)
#endif
/* By default, we use the standard "extern" declarations. */
#ifndef PCREPOSIX_EXP_DECL
# ifdef __cplusplus
# define PCREPOSIX_EXP_DECL extern "C"
# define PCREPOSIX_EXP_DEFN extern "C"
# else
# define PCREPOSIX_EXP_DECL extern
# define PCREPOSIX_EXP_DEFN extern
# endif
#endif
/* The functions */
PCREPOSIX_EXP_DECL int regcomp(regex_t *, const char *, int);
PCREPOSIX_EXP_DECL int regexec(const regex_t *, const char *, size_t,
regmatch_t *, int);
PCREPOSIX_EXP_DECL size_t regerror(int, const regex_t *, char *, size_t);
PCREPOSIX_EXP_DECL void regfree(regex_t *);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* End of pcreposix.h */
+133
View File
@@ -0,0 +1,133 @@
/*************************************************
* Unicode Property Table handler *
*************************************************/
#ifndef _UCP_H
#define _UCP_H
/* This file contains definitions of the property values that are returned by
the function _pcre_ucp_findprop(). New values that are added for new releases
of Unicode should always be at the end of each enum, for backwards
compatibility. */
/* These are the general character categories. */
enum {
ucp_C, /* Other */
ucp_L, /* Letter */
ucp_M, /* Mark */
ucp_N, /* Number */
ucp_P, /* Punctuation */
ucp_S, /* Symbol */
ucp_Z /* Separator */
};
/* These are the particular character types. */
enum {
ucp_Cc, /* Control */
ucp_Cf, /* Format */
ucp_Cn, /* Unassigned */
ucp_Co, /* Private use */
ucp_Cs, /* Surrogate */
ucp_Ll, /* Lower case letter */
ucp_Lm, /* Modifier letter */
ucp_Lo, /* Other letter */
ucp_Lt, /* Title case letter */
ucp_Lu, /* Upper case letter */
ucp_Mc, /* Spacing mark */
ucp_Me, /* Enclosing mark */
ucp_Mn, /* Non-spacing mark */
ucp_Nd, /* Decimal number */
ucp_Nl, /* Letter number */
ucp_No, /* Other number */
ucp_Pc, /* Connector punctuation */
ucp_Pd, /* Dash punctuation */
ucp_Pe, /* Close punctuation */
ucp_Pf, /* Final punctuation */
ucp_Pi, /* Initial punctuation */
ucp_Po, /* Other punctuation */
ucp_Ps, /* Open punctuation */
ucp_Sc, /* Currency symbol */
ucp_Sk, /* Modifier symbol */
ucp_Sm, /* Mathematical symbol */
ucp_So, /* Other symbol */
ucp_Zl, /* Line separator */
ucp_Zp, /* Paragraph separator */
ucp_Zs /* Space separator */
};
/* These are the script identifications. */
enum {
ucp_Arabic,
ucp_Armenian,
ucp_Bengali,
ucp_Bopomofo,
ucp_Braille,
ucp_Buginese,
ucp_Buhid,
ucp_Canadian_Aboriginal,
ucp_Cherokee,
ucp_Common,
ucp_Coptic,
ucp_Cypriot,
ucp_Cyrillic,
ucp_Deseret,
ucp_Devanagari,
ucp_Ethiopic,
ucp_Georgian,
ucp_Glagolitic,
ucp_Gothic,
ucp_Greek,
ucp_Gujarati,
ucp_Gurmukhi,
ucp_Han,
ucp_Hangul,
ucp_Hanunoo,
ucp_Hebrew,
ucp_Hiragana,
ucp_Inherited,
ucp_Kannada,
ucp_Katakana,
ucp_Kharoshthi,
ucp_Khmer,
ucp_Lao,
ucp_Latin,
ucp_Limbu,
ucp_Linear_B,
ucp_Malayalam,
ucp_Mongolian,
ucp_Myanmar,
ucp_New_Tai_Lue,
ucp_Ogham,
ucp_Old_Italic,
ucp_Old_Persian,
ucp_Oriya,
ucp_Osmanya,
ucp_Runic,
ucp_Shavian,
ucp_Sinhala,
ucp_Syloti_Nagri,
ucp_Syriac,
ucp_Tagalog,
ucp_Tagbanwa,
ucp_Tai_Le,
ucp_Tamil,
ucp_Telugu,
ucp_Thaana,
ucp_Thai,
ucp_Tibetan,
ucp_Tifinagh,
ucp_Ugaritic,
ucp_Yi,
ucp_Balinese, /* New for Unicode 5.0.0 */
ucp_Cuneiform, /* New for Unicode 5.0.0 */
ucp_Nko, /* New for Unicode 5.0.0 */
ucp_Phags_Pa, /* New for Unicode 5.0.0 */
ucp_Phoenician /* New for Unicode 5.0.0 */
};
#endif
/* End of ucp.h */
+92
View File
@@ -0,0 +1,92 @@
/*************************************************
* Unicode Property Table handler *
*************************************************/
#ifndef _UCPINTERNAL_H
#define _UCPINTERNAL_H
/* Internal header file defining the layout of the bits in each pair of 32-bit
words that form a data item in the table. */
typedef struct cnode {
pcre_uint32 f0;
pcre_uint32 f1;
} cnode;
/* Things for the f0 field */
#define f0_scriptmask 0xff000000 /* Mask for script field */
#define f0_scriptshift 24 /* Shift for script value */
#define f0_rangeflag 0x00f00000 /* Flag for a range item */
#define f0_charmask 0x001fffff /* Mask for code point value */
/* Things for the f1 field */
#define f1_typemask 0xfc000000 /* Mask for char type field */
#define f1_typeshift 26 /* Shift for the type field */
#define f1_rangemask 0x0000ffff /* Mask for a range offset */
#define f1_casemask 0x0000ffff /* Mask for a case offset */
#define f1_caseneg 0xffff8000 /* Bits for negation */
/* The data consists of a vector of structures of type cnode. The two unsigned
32-bit integers are used as follows:
(f0) (1) The most significant byte holds the script number. The numbers are
defined by the enum in ucp.h.
(2) The 0x00800000 bit is set if this entry defines a range of characters.
It is not set if this entry defines a single character
(3) The 0x00600000 bits are spare.
(4) The 0x001fffff bits contain the code point. No Unicode code point will
ever be greater than 0x0010ffff, so this should be OK for ever.
(f1) (1) The 0xfc000000 bits contain the character type number. The numbers are
defined by an enum in ucp.h.
(2) The 0x03ff0000 bits are spare.
(3) The 0x0000ffff bits contain EITHER the unsigned offset to the top of
range if this entry defines a range, OR the *signed* offset to the
character's "other case" partner if this entry defines a single
character. There is no partner if the value is zero.
-------------------------------------------------------------------------------
| script (8) |.|.|.| codepoint (21) || type (6) |.|.| spare (8) | offset (16) |
-------------------------------------------------------------------------------
| | | | |
| | |-> spare | |-> spare
| | |
| |-> spare |-> spare
|
|-> range flag
The upper/lower casing information is set only for characters that come in
pairs. The non-one-to-one mappings in the Unicode data are ignored.
When searching the data, proceed as follows:
(1) Set up for a binary chop search.
(2) If the top is not greater than the bottom, the character is not in the
table. Its type must therefore be "Cn" ("Undefined").
(3) Find the middle vector element.
(4) Extract the code point and compare. If equal, we are done.
(5) If the test character is smaller, set the top to the current point, and
goto (2).
(6) If the current entry defines a range, compute the last character by adding
the offset, and see if the test character is within the range. If it is,
we are done.
(7) Otherwise, set the bottom to one element past the current point and goto
(2).
*/
#endif /* _UCPINTERNAL_H */
/* End of ucpinternal.h */
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
include Makefile.var
+7
View File
@@ -0,0 +1,7 @@
all: $(BUILDDIR)pamauth$(DLSUFFICS)
pamauth$(OBJSUFFICS): pamauth.c
$(CC) $(DCFLAGS) $(CFLAGS) pamauth.c
$(BUILDDIR)pamauth$(DLSUFFICS): pamauth$(OBJSUFFICS)
$(LN) $(LNOUT)../../$(BUILDDIR)pamauth$(DLSUFFICS) $(LDFLAGS) $(DLFLAGS) -lpam pamauth$(OBJSUFFICS)
+30
View File
@@ -0,0 +1,30 @@
Плагин PAM авторизации для 3proxy (ОС *NIX)
(c) Kirill Lopuchov lopuchov@mail.ru
Описание
Работает только на *NIX системах . Работоспособность проверялась на
freebsd 5.2 и Linux Debian 4.
Настройка PAM
Настраиваем PAM сервис для 3proxy на примере для Linux debian 4 , создаем файл
/etc/pam.d/3proxy. Прописываем в нем следующую строку
@include common-auth
Настройка плагина
----------------------------3proxy.cfg-------------------------------
# start - имя процедуры инициализации плагина
# 3proxy - имя сервиса PAM
plugin "pamauth.so" start 3proxy
# рекомендуется включать кеширование авторизации
authcache user,password 60
auth cache pam
allow *
proxy -p3128
----------------------------3proxy.cfg-------------------------------
+140
View File
@@ -0,0 +1,140 @@
/* plugin for 3proxy with PAM auth only for *NIX (linux,*bsd)
Kirill Lopuchov <lopuchov@mail.ru>
Compile with: gcc -shared -o pamauth.so pamauth.c -lpam -DNOODBC
*/
#include "../../structures.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <security/pam_appl.h>
static int already_loaded = 0;
static struct auth pamauth;
#ifdef USERCASE
static int usercaselow = 0;
#edif
static unsigned char *service=NULL;
static struct pluginlink * pl;
static char *password = NULL;
static int password_conversation ( int num_msg, const struct pam_message **msg,
struct pam_response **resp,
void *appdata_ptr)
{
if (num_msg != 1 || msg[0]->msg_style != PAM_PROMPT_ECHO_OFF)
{
return PAM_CONV_ERR;
}
if (!appdata_ptr) appdata_ptr = password;
if (!appdata_ptr)
{
return PAM_CONV_ERR;
}
*resp = calloc (num_msg, sizeof (struct pam_response));
if (!*resp)
{
return PAM_CONV_ERR;
}
(*resp)[0].resp = strdup ((char *) appdata_ptr);
(*resp)[0].resp_retcode = 0;
return ((*resp)[0].resp ? PAM_SUCCESS : PAM_CONV_ERR);
}
#ifdef USERCASE
static void lower (char *string)
{
int length, i;
length = strlen(string);
for (i=0; i<length; i++)
{
string[i] = tolower(string[i]);
}
}
#endif
/* --------------------------------------------------------------------------*/
static int pamfunc(struct clientparam *param)
{
pam_handle_t *pamh = NULL;
int retval;
int rc=0;
struct pam_conv conv = {
&password_conversation,
NULL };
/* test proxy user auth ------------------------*/
if(!param->username || !param->password) return 4;
/*if(strlen(param->password)==0) return 4;*/
#ifdef USERCASE
if (usercaselow > 0)
{ lower(param->username); }
#endif
/*start process auth */
conv.appdata_ptr = (char *) param->password;
if (!pamh)
{
retval = pam_start ((char *)service, "3proxy@" , &conv, &pamh);
}
if (retval == PAM_SUCCESS)
retval = pam_set_item (pamh, PAM_USER, param->username);
/*fprintf(stderr,"pam_set_item1 rc=%d\n",retval);*/
if (retval == PAM_SUCCESS)
retval = pam_set_item (pamh, PAM_CONV, &conv);
/*fprintf(stderr,"pam_set_item2 rc=%d\n",retval); */
if (retval == PAM_SUCCESS)
retval = pam_authenticate (pamh, 0);
/*fprintf(stderr,"pam_authenticate rc=%d\n",retval);*/
if (retval == PAM_SUCCESS) { /*auth OK*/ rc=0; }
else { /*auth ERR*/ rc=5; }
if (pamh)
retval = pam_end (pamh, retval);
if (retval != PAM_SUCCESS)
{ pamh = NULL; }
return rc;
}
/*------------------------------- MAIN --------------------------------------
start plugin init */
int start(struct pluginlink * pluginlink, int argc, unsigned char** argv)
{
if(argc < 2) return 1;
pl = pluginlink;
if(service) pl->myfree(service);
service=pl->mystrdup(argv[1]);
if (already_loaded) { return (0); }
already_loaded = 1;
pamauth.authenticate = pamfunc;
pamauth.authorize = pluginlink->checkACL;
pamauth.desc = "pam";
pamauth.next = pluginlink->authfuncs->next;
pluginlink->authfuncs->next = &pamauth;
return 0;
}
+1
View File
@@ -0,0 +1 @@
D
+1
View File
@@ -0,0 +1 @@
3proxy-0.5a/src/plugins/SSLPlugin
+1
View File
@@ -0,0 +1 @@
/cygdrive/m/MEDIA/H/CVS
+1
View File
@@ -0,0 +1 @@
include Makefile.var
+14
View File
@@ -0,0 +1,14 @@
all: $(BUILDDIR)SSLPlugin$(DLSUFFICS)
ssl_plugin$(OBJSUFFICS): ssl_plugin.c
$(CC) $(DCFLAGS) $(CFLAGS) ssl_plugin.c
my_ssl$(OBJSUFFICS): my_ssl.c
$(CC) $(DCFLAGS) $(CFLAGS) my_ssl.c
$(BUILDDIR)SSLPlugin$(DLSUFFICS): ssl_plugin$(OBJSUFFICS) my_ssl$(OBJSUFFICS)
$(LN) $(LNOUT)../../$(BUILDDIR)SSLPlugin$(DLSUFFICS) $(LDFLAGS) $(DLFLAGS) ssl_plugin$(OBJSUFFICS) my_ssl$(OBJSUFFICS) $(LIBS)
+37
View File
@@ -0,0 +1,37 @@
VERFILE = version.obj ../3proxy.RES
#$Id: Makefile.msvc,v 1.17 2010-11-11 14:44:11 v.dubrovin Exp $
#
# 3 proxy Makefile for Microsoft Visual C compiler (for both make and nmake)
#
# You can try to remove -DWITH_STD_MALLOC to CFLAGS to use optimized malloc
# libraries
#
# Add /DSAFESQL to CFLAGS if you are using poorely written/tested ODBC driver
BUILDDIR = ../bin/
CC = cl
CFLAGS = /nologo /MT /W3 /Ox /GS /EHs- /GA /GF /D "MSVC" /D "WITH_STD_MALLOC" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "_WIN32" /Fp"proxy.pch" /FD /c
COUT = /Fo
LN = link
LDFLAGS = /nologo /subsystem:console /incremental:no /machine:I386
DLFLAGS = /DLL
DLSUFFICS = .dll
LIBS = ws2_32.lib advapi32.lib odbc32.lib user32.lib kernel32.lib Gdi32.lib libeay32MT.lib ssleay32MT.lib
LIBEXT = .lib
LNOUT = /out:
EXESUFFICS = .exe
OBJSUFFICS = .obj
DEFINEOPTION = /D
COMPFILES = *.pch *.idb
REMOVECOMMAND = del 2>NUL >NUL
TYPECOMMAND = type
COMPATLIBS =
MAKEFILE = Makefile.msvc
PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin lastFripper FilePlugin SSLPlugin
include Makefile.inc
allplugins:
for /D %%i in ($(PLUGINS)) do (copy Makefile plugins\%%i && copy Makefile.var plugins\%%i && cd plugins\%%i && nmake && del *.obj *.idb &&cd ..\..)
+453
View File
@@ -0,0 +1,453 @@
#define _CRT_SECURE_NO_WARNINGS
#include "../../structures.h"
#include "../../proxy.h"
#include "my_ssl.h"
#include <memory.h>
#include <errno.h>
#include <fcntl.h>
#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
typedef struct _ssl_conn {
SSL_CTX *ctx;
SSL *ssl;
} ssl_conn;
static X509 *CA_cert = NULL;
static EVP_PKEY *CA_key = NULL;
static EVP_PKEY *server_key = NULL;
static X509_NAME *name = NULL;
pthread_mutex_t ssl_file_mutex;
static char errbuf[256];
static char hexMap[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
static BIO *bio_err=NULL;
static size_t bin2hex (const unsigned char* bin, size_t bin_length, char* str, size_t str_length)
{
char *p;
size_t i;
if ( str_length < ( bin_length+1) )
return 0;
p = str;
for ( i=0; i < bin_length; ++i )
{
*p++ = hexMap[*bin >> 4];
*p++ = hexMap[*bin & 0xf];
++bin;
}
*p = 0;
return p - str;
}
static int add_ext(X509 *cert, int nid, char *value)
{
X509_EXTENSION *ex;
X509V3_CTX ctx;
/* This sets the 'context' of the extensions. */
/* No configuration database */
X509V3_set_ctx_nodb(&ctx);
/* Issuer and subject certs: both the target since it is self signed,
* no request and no CRL
*/
X509V3_set_ctx(&ctx, cert, cert, NULL, NULL, 0);
ex = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
if (!ex)
return 0;
X509_add_ext(cert,ex,-1);
X509_EXTENSION_free(ex);
return 1;
}
extern char *cert_path;
void del_ext(X509 *dst_cert, int nid, int where){
int ex;
ex = X509_get_ext_by_NID(dst_cert, nid, where);
if(ex>=0){
X509_EXTENSION *ext;
if((ext = X509_delete_ext(dst_cert, ex))) X509_EXTENSION_free(ext);
}
}
SSL_CERT ssl_copy_cert(SSL_CERT cert)
{
int err = -1;
FILE *fcache;
X509 *src_cert = (X509 *) cert;
X509 *dst_cert = NULL;
EVP_PKEY *pk = NULL;
RSA *rsa = NULL;
unsigned char p1[] = "RU";
unsigned char p2[] = "3proxy";
unsigned char p3[] = "3proxy CA";
static char hash_name[sizeof(src_cert->sha1_hash)*2 + 1];
static char cache_name[200];
pthread_mutex_lock(&ssl_file_mutex);
bin2hex(src_cert->sha1_hash, sizeof(src_cert->sha1_hash), hash_name, sizeof(hash_name));
sprintf(cache_name, "%s%s.pem", cert_path, hash_name);
/* check if certificate is already cached */
fcache = fopen(cache_name, "rb");
if ( fcache != NULL ) {
dst_cert = PEM_read_X509(fcache, &dst_cert, NULL, NULL);
fclose(fcache);
if ( dst_cert != NULL ){
pthread_mutex_unlock(&ssl_file_mutex);
return dst_cert;
}
}
pthread_mutex_unlock(&ssl_file_mutex);
/* proceed if certificate is not cached */
dst_cert = X509_dup(src_cert);
if ( dst_cert == NULL ) {
return NULL;
}
del_ext(dst_cert, NID_crl_distribution_points, -1);
del_ext(dst_cert, NID_info_access, -1);
del_ext(dst_cert, NID_authority_key_identifier, -1);
del_ext(dst_cert, NID_certificate_policies, 0);
err = X509_set_pubkey(dst_cert, server_key);
if ( err == 0 ) {
X509_free(dst_cert);
return NULL;
}
/* Its self signed so set the issuer name to be the same as the
* subject.
*/
err = X509_set_issuer_name(dst_cert, name);
if(!err){
X509_free(dst_cert);
return NULL;
}
err = X509_digest(dst_cert, EVP_sha1(), dst_cert->sha1_hash, NULL);
if(!err){
X509_free(dst_cert);
return NULL;
}
err = X509_sign(dst_cert, CA_key, EVP_sha1());
if(!err){
X509_free(dst_cert);
return NULL;
}
/* write to cache */
pthread_mutex_lock(&ssl_file_mutex);
fcache = fopen(cache_name, "wb");
if ( fcache != NULL ) {
PEM_write_X509(fcache, dst_cert);
fclose(fcache);
}
pthread_mutex_unlock(&ssl_file_mutex);
return dst_cert;
}
SSL_CONN ssl_handshake_to_server(SOCKET s, SSL_CERT *server_cert, char **errSSL)
{
int err = 0;
X509 *cert;
ssl_conn *conn;
*errSSL = NULL;
conn = (ssl_conn *)malloc(sizeof(ssl_conn));
if ( conn == NULL ){
return NULL;
}
conn->ctx = SSL_CTX_new(SSLv23_client_method());
if ( conn->ctx == NULL ) {
free(conn);
return NULL;
}
conn->ssl = SSL_new(conn->ctx);
if ( conn->ssl == NULL ) {
SSL_CTX_free(conn->ctx);
free(conn);
return NULL;
}
if(!SSL_set_fd(conn->ssl, s)){
ssl_conn_free(conn);
return NULL;
}
err = SSL_connect(conn->ssl);
if ( err == -1 ) {
*errSSL = ERR_error_string(ERR_get_error(), errbuf);
ssl_conn_free(conn);
return NULL;
}
cert = SSL_get_peer_certificate(conn->ssl);
/* TODO: Verify certificate */
*server_cert = cert;
return conn;
}
SSL_CONN ssl_handshake_to_client(SOCKET s, SSL_CERT server_cert, char** errSSL)
{
int err = 0;
X509 *cert;
ssl_conn *conn;
*errSSL = NULL;
conn = (ssl_conn *)malloc(sizeof(ssl_conn));
if ( conn == NULL )
return NULL;
conn->ctx = SSL_CTX_new(SSLv23_server_method());
if ( conn->ctx == NULL ) {
free(conn);
return NULL;
}
err = SSL_CTX_use_certificate(conn->ctx, (X509 *) server_cert);
if ( err <= 0 ) {
SSL_CTX_free(conn->ctx);
free(conn);
return NULL;
}
err = SSL_CTX_use_PrivateKey(conn->ctx, server_key);
if ( err <= 0 ) {
SSL_CTX_free(conn->ctx);
free(conn);
return NULL;
}
/*
err = SSL_CTX_load_verify_locations(conn->ctx, "3proxy.pem",
NULL);
if ( err <= 0 ) {
SSL_CTX_free(conn->ctx);
free(conn);
return NULL;
}
*/
conn->ssl = SSL_new(conn->ctx);
if ( conn->ssl == NULL ) {
SSL_CTX_free(conn->ctx);
free(conn);
return NULL;
}
SSL_set_fd(conn->ssl, (int)s);
err = SSL_accept(conn->ssl);
if ( err <= 0 ) {
*errSSL = ERR_error_string(ERR_get_error(), errbuf);
ssl_conn_free(conn);
return NULL;
}
//
// client certificate
// TODO: is it required?
//
cert = SSL_get_peer_certificate(conn->ssl);
if ( cert != NULL )
X509_free(cert);
return conn;
}
int ssl_read(SSL_CONN connection, void * buf, int bufsize)
{
ssl_conn *conn = (ssl_conn *) connection;
return SSL_read(conn->ssl, buf, bufsize);
}
int ssl_write(SSL_CONN connection, void * buf, int bufsize)
{
ssl_conn *conn = (ssl_conn *) connection;
return SSL_write(conn->ssl, buf, bufsize);
}
int ssl_pending(SSL_CONN connection)
{
ssl_conn *conn = (ssl_conn *) connection;
return SSL_pending(conn->ssl);
}
void ssl_conn_free(SSL_CONN connection)
{
ssl_conn *conn = (ssl_conn *) connection;
SSL_shutdown(conn->ssl);
SSL_free(conn->ssl);
SSL_CTX_free(conn->ctx);
free(conn);
}
void _ssl_cert_free(SSL_CERT cert)
{
X509_free((X509 *)cert);
}
/* This array will store all of the mutexes available to OpenSSL. */
static pthread_mutex_t *mutex_buf= NULL;
static void locking_function(int mode, int n, const char * file, int line)
{
if (mode & CRYPTO_LOCK)
pthread_mutex_lock(mutex_buf + n);
else
pthread_mutex_unlock(mutex_buf + n);
}
static unsigned long id_function(void)
{
#ifdef _WIN32
return ((unsigned long)GetCurrentThreadId());
#else
return ((unsigned long)pthread_self());
#endif
}
int thread_setup(void)
{
int i;
mutex_buf = malloc(CRYPTO_num_locks( ) * sizeof(pthread_mutex_t));
if (!mutex_buf)
return 0;
for (i = 0; i < CRYPTO_num_locks( ); i++)
pthread_mutex_init(mutex_buf +i, NULL);
CRYPTO_set_id_callback(id_function);
CRYPTO_set_locking_callback(locking_function);
return 1;
}
int thread_cleanup(void)
{
int i;
if (!mutex_buf)
return 0;
CRYPTO_set_id_callback(NULL);
CRYPTO_set_locking_callback(NULL);
for (i = 0; i < CRYPTO_num_locks( ); i++)
pthread_mutex_destroy(mutex_buf +i);
free(mutex_buf);
mutex_buf = NULL;
return 1;
}
int ssl_file_init = 0;
void ssl_init(void)
{
FILE *f;
static char fname[200];
if(!ssl_file_init++)pthread_mutex_init(&ssl_file_mutex, NULL);
pthread_mutex_lock(&ssl_file_mutex);
thread_setup();
SSLeay_add_ssl_algorithms();
SSL_load_error_strings();
sprintf(fname, "%.128s3proxy.pem", cert_path);
f = fopen(fname, "r");
if ( f != NULL ) {
PEM_read_X509(f, &CA_cert, NULL, NULL);
fclose(f);
}
else {
fprintf(stderr, "failed to open: %s\n", fname);
}
name = X509_get_subject_name(CA_cert);
sprintf(fname, "%.128s3proxy.key", cert_path);
f = fopen(fname, "rb");
if ( f != NULL ) {
CA_key = PEM_read_PrivateKey(f, &CA_key, NULL, NULL);
fclose(f);
}
else {
fprintf(stderr, "failed to open: %s\n", fname);
}
sprintf(fname, "%.128sserver.key", cert_path);
f = fopen(fname, "rb");
if ( f != NULL ) {
server_key = PEM_read_PrivateKey(f, &server_key, NULL, NULL);
fclose(f);
}
else {
fprintf(stderr, "failed to open: %s\n", fname);
}
if(!CA_cert || !CA_key || !server_key){
fprintf(stderr, "failed to init SSL certificate / keys\n");
}
bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
pthread_mutex_unlock(&ssl_file_mutex);
}
void ssl_release(void)
{
pthread_mutex_lock(&ssl_file_mutex);
if ( CA_cert != NULL ) {
X509_free(CA_cert);
CA_cert = NULL;
}
if ( CA_key != NULL ) {
EVP_PKEY_free(CA_key);
CA_key = NULL;
}
if ( server_key != NULL ) {
EVP_PKEY_free(server_key);
server_key = NULL;
}
thread_cleanup();
pthread_mutex_unlock(&ssl_file_mutex);
}
+43
View File
@@ -0,0 +1,43 @@
#ifndef __my_ssl_h__
#define __my_ssl_h__
//
// opaque connection structure
//
typedef void *SSL_CONN;
//
// opaque certificate structure
//
typedef void *SSL_CERT;
//
// Create copy of certificate signed by "other" CA
//
SSL_CERT ssl_copy_cert(SSL_CERT cert);
//
// SSL/TLS handshakes
//
SSL_CONN ssl_handshake_to_server(SOCKET s, SSL_CERT *server_cert, char **errSSL);
SSL_CONN ssl_handshake_to_client(SOCKET s, SSL_CERT server_cert, char **errSSL);
//
// SSL/TLS Read/Write
//
int ssl_read(SSL_CONN connection, void * buf, int bufsize);
int ssl_write(SSL_CONN connection, void * buf, int bufsize);
int ssl_pending(SSL_CONN connection);
//
// Release of opaque structures
//
void ssl_conn_free(SSL_CONN connection);
void _ssl_cert_free(SSL_CERT cert);
//
// Global (de)initialization
//
void ssl_init(void);
void ssl_release(void);
#endif // __my_ssl_h__
+371
View File
@@ -0,0 +1,371 @@
/*
3APA3A simpliest proxy server
(c) 2007-2008 by ZARAZA <3APA3A@security.nnov.ru>
please read License Agreement
$Id: ssl_plugin.c,v 1.9 2010-11-11 11:32:33 v.dubrovin Exp $
*/
#include "../../structures.h"
#include "../../proxy.h"
#include <openssl/rsa.h> /* SSLeay stuff */
#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include "my_ssl.h"
#ifndef _WIN32
#define WINAPI
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifndef isnumber
#define isnumber(i_n_arg) ((i_n_arg>='0')&&(i_n_arg<='9'))
#endif
PROXYFUNC tcppmfunc, proxyfunc, smtppfunc, ftpprfunc;
static struct pluginlink * pl;
pthread_mutex_t ssl_mutex;
static int ssl_loaded = 0;
static int ssl_connect_timeout = 0;
char *cert_path = "";
typedef struct _ssl_conn {
struct SSL_CTX *ctx;
struct SSL *ssl;
} ssl_conn;
struct SSLqueue {
struct SSLqueue *next;
SOCKET s;
SSL_CERT cert;
SSL_CONN conn;
struct clientparam* param;
} *SSLq = NULL;
/*
Todo: use hashtable
*/
static struct SSLqueue *searchSSL(SOCKET s){
struct SSLqueue *sslq;
for(sslq = SSLq; sslq; sslq = sslq->next)
if(sslq->s == s) return sslq;
return NULL;
}
static void addSSL(SOCKET s, SSL_CERT cert, SSL_CONN conn, struct clientparam* param){
struct SSLqueue *sslq;
sslq = (struct SSLqueue *) malloc(sizeof(struct SSLqueue));
sslq->s = s;
sslq->cert = cert;
sslq->conn = conn;
pthread_mutex_lock(&ssl_mutex);
sslq->next = SSLq;
sslq->param = param;
SSLq = sslq;
pthread_mutex_unlock(&ssl_mutex);
}
int delSSL(SOCKET s){
struct SSLqueue *sqi, *sqt = NULL;
if(!SSLq) return 0;
pthread_mutex_lock(&ssl_mutex);
if(SSLq){
if(SSLq->s == s){
sqt = SSLq;
SSLq = SSLq->next;
}
else for(sqi = SSLq; sqi->next; sqi = sqi->next){
if (sqi->next->s == s){
sqt = sqi->next;
sqi->next = sqt->next;
break;
}
}
}
pthread_mutex_unlock(&ssl_mutex);
if(sqt) {
_ssl_cert_free(sqt->cert);
ssl_conn_free(sqt->conn);
free(sqt);
return 1;
}
return 0;
}
struct sockfuncs sso;
#ifdef _WIN32
static int WINAPI ssl_send(SOCKET s, const void *msg, int len, int flags){
#else
static int ssl_send(SOCKET s, const void *msg, size_t len, int flags){
#endif
struct SSLqueue *sslq;
if ((sslq = searchSSL(s))){
int i=0, res, err;
do {
if((res = ssl_write(sslq->conn, (void *)msg, len)) < 0) {
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
usleep(10*SLEEPTIME);
}
} while (res < 0 && (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) && ++i < 100);
return res;
}
return sso._send(s, msg, len, flags);
}
#ifdef _WIN32
static int WINAPI ssl_sendto(SOCKET s, const void *msg, int len, int flags, const struct sockaddr *to, int tolen){
#else
static int ssl_sendto(SOCKET s, const void *msg, size_t len, int flags, const struct sockaddr *to, SASIZETYPE tolen){
#endif
struct SSLqueue *sslq;
if ((sslq = searchSSL(s))){
int i=0, res, err;
do {
if((res = ssl_write(sslq->conn, (void *)msg, len)) < 0) {
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
usleep(10*SLEEPTIME);
}
} while (res < 0 && (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) && ++i < 100);
return res;
}
return sso._sendto(s, msg, len, flags, to, tolen);
}
#ifdef _WIN32
static int WINAPI ssl_recvfrom(SOCKET s, void *msg, int len, int flags, struct sockaddr *from, int *fromlen){
#else
static int ssl_recvfrom(SOCKET s, void *msg, size_t len, int flags, struct sockaddr *from, SASIZETYPE *fromlen){
#endif
struct SSLqueue *sslq;
if ((sslq = searchSSL(s))){
int i=0, res, err;
do {
if((res = ssl_read(sslq->conn, (void *)msg, len)) < 0) {
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
usleep(10*SLEEPTIME);
}
} while (res < 0 && (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) && ++i < 100);
return res;
}
return sso._recvfrom(s, msg, len, flags, from, fromlen);
}
#ifdef _WIN32
static int WINAPI ssl_recv(SOCKET s, void *msg, int len, int flags){
#else
static int WINAPI ssl_recv(SOCKET s, void *msg, size_t len, int flags){
#endif
struct SSLqueue *sslq;
if ((sslq = searchSSL(s))){
int i=0, res, err;
do {
if((res = ssl_read(sslq->conn, (void *)msg, len)) < 0) {
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
usleep(10*SLEEPTIME);
}
} while (res < 0 && (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) && ++i < 100);
return res;
}
return sso._recv(s, msg, len, flags);
}
static int WINAPI ssl_closesocket(SOCKET s){
delSSL(s);
return sso._closesocket(s);
}
static int WINAPI ssl_poll(struct pollfd *fds, unsigned int nfds, int timeout){
struct SSLqueue *sslq = NULL;
unsigned int i;
int ret = 0;
for(i = 0; i < nfds; i++){
if((fds[i].events & POLLIN) && (sslq = searchSSL(fds[i].fd)) && ssl_pending(sslq->conn)){
fds[i].revents = POLLIN;
ret++;
}
else fds[i].revents = 0;
}
if(ret) return ret;
ret = sso._poll(fds, nfds, timeout);
return ret;
}
int dossl(struct clientparam* param, SSL_CONN* ServerConnp, SSL_CONN* ClientConnp){
SSL_CERT ServerCert=NULL, FakeCert=NULL;
SSL_CONN ServerConn, ClientConn;
char *errSSL=NULL;
unsigned long ul;
#ifdef _WIN32
ul = 0;
ioctlsocket(param->remsock, FIONBIO, &ul);
ul = 0;
ioctlsocket(param->clisock, FIONBIO, &ul);
#else
fcntl(param->remsock,F_SETFL,0);
fcntl(param->clisock,F_SETFL,0);
#endif
if(ssl_connect_timeout){
ul = ((unsigned long)ssl_connect_timeout)*1000;
setsockopt(param->remsock, SOL_SOCKET, SO_RCVTIMEO, (char *)&ul, 4);
ul = ((unsigned long)ssl_connect_timeout)*1000;
setsockopt(param->remsock, SOL_SOCKET, SO_SNDTIMEO, (char *)&ul, 4);
}
ServerConn = ssl_handshake_to_server(param->remsock, &ServerCert, &errSSL);
if ( ServerConn == NULL || ServerCert == NULL ) {
param->res = 8011;
param->srv->logfunc(param, (unsigned char *)"SSL handshake to server failed");
if(ServerConn == NULL) param->srv->logfunc(param, (unsigned char *)"ServerConn is NULL");
if(ServerCert == NULL) param->srv->logfunc(param, (unsigned char *)"ServerCert is NULL");
if(errSSL)param->srv->logfunc(param, (unsigned char *)errSSL);
return 1;
}
FakeCert = ssl_copy_cert(ServerCert);
if ( FakeCert == NULL ) {
param->res = 8012;
_ssl_cert_free(ServerCert);
param->srv->logfunc(param, (unsigned char *)"Failed to create certificate copy");
ssl_conn_free(ServerConn);
return 2;
}
ClientConn = ssl_handshake_to_client(param->clisock, FakeCert, &errSSL);
if ( ClientConn == NULL ) {
param->res = 8012;
param->srv->logfunc(param, (unsigned char *)"Handshake to client failed");
if(errSSL)param->srv->logfunc(param, (unsigned char *)errSSL);
_ssl_cert_free(ServerCert);
_ssl_cert_free(FakeCert);
ssl_conn_free(ServerConn);
return 3;
}
#ifdef _WIN32
ul = 1;
ioctlsocket(param->remsock, FIONBIO, &ul);
ul = 1;
ioctlsocket(param->clisock, FIONBIO, &ul);
#else
fcntl(param->remsock,F_SETFL,O_NONBLOCK);
fcntl(param->clisock,F_SETFL,O_NONBLOCK);
#endif
SSL_set_mode((SSL *)((ssl_conn *)ServerConn)->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE|SSL_MODE_AUTO_RETRY);
SSL_set_mode((SSL *)((ssl_conn *)ClientConn)->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE|SSL_MODE_AUTO_RETRY);
SSL_set_read_ahead((SSL *)((ssl_conn *)ServerConn)->ssl, 0);
SSL_set_read_ahead((SSL *)((ssl_conn *)ClientConn)->ssl, 0);
addSSL(param->remsock, ServerCert, ServerConn, param);
addSSL(param->clisock, FakeCert, ClientConn, param);
if(ServerConnp)*ServerConnp = ServerConn;
if(ClientConnp)*ClientConnp = ClientConn;
return 0;
}
static void* ssl_filter_open(void * idata, struct srvparam * param){
return idata;
}
static FILTER_ACTION ssl_filter_client(void *fo, struct clientparam * param, void** fc){
return CONTINUE;
}
static FILTER_ACTION ssl_filter_predata(void *fo, struct clientparam * param){
if(param->operation != HTTP_CONNECT) return PASS;
if(dossl(param, NULL, NULL)) {
return REJECT;
}
param->redirectfunc = proxyfunc;
return HANDLED;
}
static void ssl_filter_clear(void *fo){
}
static void ssl_filter_close(void *fo){
}
static struct filter ssl_filter = {
NULL,
"ssl filter",
"ssl filter",
ssl_filter_open,
ssl_filter_client,
NULL, NULL, NULL, ssl_filter_predata, NULL, NULL,
ssl_filter_clear,
ssl_filter_close
};
#ifdef _WIN32
__declspec(dllexport)
#endif
int ssl_plugin (struct pluginlink * pluginlink,
int argc, char** argv){
pl = pluginlink;
if(argc > 1) {
if(cert_path && *cert_path) free(cert_path);
cert_path = strdup(argv[1]);
}
if(!ssl_loaded){
ssl_loaded = 1;
pthread_mutex_init(&ssl_mutex, NULL);
ssl_filter.next = pl->conf->filters;
pl->conf->filters = &ssl_filter;
memcpy(&sso, pl->so, sizeof(struct sockfuncs));
pl->so->_send = ssl_send;
pl->so->_recv = ssl_recv;
pl->so->_sendto = ssl_sendto;
pl->so->_recvfrom = ssl_recvfrom;
pl->so->_closesocket = ssl_closesocket;
pl->so->_poll = ssl_poll;
}
else{
ssl_release();
}
ssl_init();
tcppmfunc = (PROXYFUNC)pl->findbyname("tcppm");
if(!tcppmfunc){return 13;}
proxyfunc = (PROXYFUNC)pl->findbyname("proxy");
if(!proxyfunc)proxyfunc = tcppmfunc;
smtppfunc = (PROXYFUNC)pl->findbyname("smtpp");
if(!smtppfunc)smtppfunc = tcppmfunc;
ftpprfunc = (PROXYFUNC)pl->findbyname("ftppr");
if(!ftpprfunc)ftpprfunc = tcppmfunc;
return 0;
}
#ifdef __cplusplus
}
#endif
+2
View File
@@ -0,0 +1,2 @@
/TrafficPlugin.c/1.4/Mon Mar 19 10:24:40 2007//
D
+1
View File
@@ -0,0 +1 @@
3proxy-0.5a/src/plugins/TrafficPlugin
+1
View File
@@ -0,0 +1 @@
/cygdrive/m/MEDIA/H/CVS
+1
View File
@@ -0,0 +1 @@
include Makefile.var
+7
View File
@@ -0,0 +1,7 @@
all: $(BUILDDIR)StringsPlugin$(DLSUFFICS)
StringsPlugin$(OBJSUFFICS): StringsPlugin.c
$(CC) $(DCFLAGS) $(CFLAGS) StringsPlugin.c
$(BUILDDIR)StringsPlugin$(DLSUFFICS): StringsPlugin$(OBJSUFFICS)
$(LN) $(LNOUT)../../$(BUILDDIR)StringsPlugin$(DLSUFFICS) $(LDFLAGS) $(DLFLAGS) StringsPlugin$(OBJSUFFICS)
+37
View File
@@ -0,0 +1,37 @@
VERFILE = version.obj ../3proxy.RES
#$Id: Makefile.msvc,v 1.17 2010-11-11 14:44:11 v.dubrovin Exp $
#
# 3 proxy Makefile for Microsoft Visual C compiler (for both make and nmake)
#
# You can try to remove -DWITH_STD_MALLOC to CFLAGS to use optimized malloc
# libraries
#
# Add /DSAFESQL to CFLAGS if you are using poorely written/tested ODBC driver
BUILDDIR = ../bin/
CC = cl
CFLAGS = /nologo /MT /W3 /Ox /GS /EHs- /GA /GF /D "MSVC" /D "WITH_STD_MALLOC" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "_WIN32" /Fp"proxy.pch" /FD /c
COUT = /Fo
LN = link
LDFLAGS = /nologo /subsystem:console /incremental:no /machine:I386
DLFLAGS = /DLL
DLSUFFICS = .dll
LIBS = ws2_32.lib advapi32.lib odbc32.lib user32.lib kernel32.lib Gdi32.lib libeay32MT.lib ssleay32MT.lib
LIBEXT = .lib
LNOUT = /out:
EXESUFFICS = .exe
OBJSUFFICS = .obj
DEFINEOPTION = /D
COMPFILES = *.pch *.idb
REMOVECOMMAND = del 2>NUL >NUL
TYPECOMMAND = type
COMPATLIBS =
MAKEFILE = Makefile.msvc
PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin lastFripper FilePlugin
include Makefile.inc
allplugins:
for /D %%i in ($(PLUGINS)) do (copy Makefile plugins\%%i && copy Makefile.var plugins\%%i && cd plugins\%%i && nmake && del *.obj *.idb &&cd ..\..)
+63
View File
@@ -0,0 +1,63 @@
-------------------------windows-1251------------------------
Плагин подменяющий строки в сервере 3proxу (ОС windows,unix)
(c) Lopuchov Kirill lopuchov@mail.ru
1. Краткое описание описание
Используется для руссификации сообщений выдаваемых 3proxy.
Для корректной работы требуется последняя 0.6 версия 3proxy (в интерфейсе
plugin api которой появился job schedule ). Все сообщения были взяты из
дистрибутива 3proxy и вынесенны в отдельный файл. Пример файла rus-win1251.3ps.
Для каждого сервиса существуют свои блоки сообщений. Начало и конец блока
разделены , на пример для сервиса ADMIN начало "[--admin--]" конец [/--admin--].
Сами сообщения отделены между собой строкой "[end]", новая строка определяется
строкой "\n" .
От версии к версии количество сообщений в 3proxy может менятся.
В этом случае необходимо либо добавить самостоятельно новые строки в
соответсвеющие блоки rus-win1251.3ps, или ждать обновления :)
Для компиляции и тестирования под ОС Windows использовался пакет Dev-C++
http://www.bloodshed.net/dev/
Для компиляции и тестирования под unix подобными использовался gcc
Настройка 3proxy
---------------------
plugin "string.dll" start c:\3proxy\rus-win1251.3ps
-------------------------windows-1251------------------------
---------------------------KOI8-R---------------------------
рМБЗЙО РПДНЕОСАЭЙК УФТПЛЙ Ч УЕТЧЕТЕ 3proxХ (пу windows,unix)
(c) Lopuchov Kirill lopuchov@mail.ru
1. лТБФЛПЕ ПРЙУБОЙЕ ПРЙУБОЙЕ
йУРПМШЪХЕФУС ДМС ТХУУЙЖЙЛБГЙЙ УППВЭЕОЙК ЧЩДБЧБЕНЩИ 3proxy.
дМС ЛПТТЕЛФОПК ТБВПФЩ ФТЕВХЕФУС РПУМЕДОСС 0.6 ЧЕТУЙС 3proxy (Ч ЙОФЕТЖЕКУЕ
plugin api ЛПФПТПК РПСЧЙМУС job schedule ). чУЕ УППВЭЕОЙС ВЩМЙ ЧЪСФЩ ЙЪ
ДЙУФТЙВХФЙЧБ 3proxy Й ЧЩОЕУЕООЩ Ч ПФДЕМШОЩК ЖБКМ. рТЙНЕТ ЖБКМБ rus-win1251.3ps.
дМС ЛБЦДПЗП УЕТЧЙУБ УХЭЕУФЧХАФ УЧПЙ ВМПЛЙ УППВЭЕОЙК. оБЮБМП Й ЛПОЕГ ВМПЛБ
ТБЪДЕМЕОЩ , ОБ РТЙНЕТ ДМС УЕТЧЙУБ ADMIN ОБЮБМП "[--admin--]" ЛПОЕГ [/--admin--].
уБНЙ УППВЭЕОЙС ПФДЕМЕОЩ НЕЦДХ УПВПК УФТПЛПК "[end]", ОПЧБС УФТПЛБ ПРТЕДЕМСЕФУС
УФТПЛПК "\n" .
пФ ЧЕТУЙЙ Л ЧЕТУЙЙ ЛПМЙЮЕУФЧП УППВЭЕОЙК Ч 3proxy НПЦЕФ НЕОСФУС.
ч ЬФПН УМХЮБЕ ОЕПВИПДЙНП МЙВП ДПВБЧЙФШ УБНПУФПСФЕМШОП ОПЧЩЕ УФТПЛЙ Ч
УППФЧЕФУЧЕАЭЙЕ ВМПЛЙ rus-win1251.3ps, ЙМЙ ЦДБФШ ПВОПЧМЕОЙС :)
дМС ЛПНРЙМСГЙЙ Й ФЕУФЙТПЧБОЙС РПД пу Windows ЙУРПМШЪПЧБМУС РБЛЕФ Dev-C++
http://www.bloodshed.net/dev/
дМС ЛПНРЙМСГЙЙ Й ФЕУФЙТПЧБОЙС РПД unix РПДПВОЩНЙ ЙУРПМШЪПЧБМУС gcc
оБУФТПКЛБ 3proxy
---------------------
plugin "string.dll" start c:\3proxy\rus-win1251.3ps
---------------------------KOI8-R---------------------------
+254
View File
@@ -0,0 +1,254 @@
#include "../../structures.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifdef __cplusplus
extern "C" {
#endif
struct pluginlink * mypl;
int count_load_str_proxy_from_file=0,count_load_str_admin_from_file=0;
int count_str_proxy_in_3proxy=0,count_str_admin_in_3proxy=0;
char ** old_proxy_table=NULL;
char ** old_admin_table=NULL;
struct schedule myschedule;
char **load_string(FILE *f,int max_count_str, int *countloadstr,
char *start,char *stop,char **table_3proxy)
{
int cstr=0,i=0;
char tmpbuf1[1024],*rstr,*pt=NULL,*p=NULL;
char **old_table;
tmpbuf1[0]='\0';
fseek(f,0,SEEK_SET);
/*find start service section*/
while(!feof(f))
{
fgets(tmpbuf1, 1023,f);
if ((strstr(tmpbuf1,start))!=NULL) { i++; break; }
tmpbuf1[0]='\0';
}
if (i==0){
fprintf(stderr,"Error StringsPlugin: No start section %s strings! \n",start);
return NULL;
}
/*create table for old strings */
old_table=(char **)mypl->myalloc(max_count_str*sizeof(char *));
memset(old_table,0,max_count_str*sizeof(char *));
/*load from file new strings */
i=0;
while ( !feof(f) || i< max_count_str)
{
fgets(tmpbuf1, 1023,f);
if ((strstr(tmpbuf1,stop))!=NULL) { break; }
if (strstr(tmpbuf1,"[end]")==NULL)
{
/* find and replace \n \r*/
rstr = tmpbuf1;
while (*rstr!='\0')
{
if (*rstr=='\r' || *rstr=='\n' )
{ *rstr='\0'; rstr++; }
rstr++;
}
while ((rstr=strstr(tmpbuf1,"\\n")))
{
if (rstr!=NULL){ *rstr='\r'; rstr++; *rstr='\n'; }
}
/* add string */
if (pt!=NULL) { cstr=cstr+(int)strlen(pt); }
cstr=cstr+(int)strlen(tmpbuf1)+1;
p = (char *)mypl->myalloc(cstr);
if (pt!=NULL)
{
strcpy(p, pt);
strcat(p, tmpbuf1);
mypl->myfree(pt);
}
else
{ strcpy(p, tmpbuf1); }
pt=p; cstr=0;
}
else
{
/* save old string */
old_table[i]=table_3proxy[i];
/* replace string */
table_3proxy[i]=pt;
pt=NULL; i++;
}
}
if(pt)mypl->myfree(pt);
*countloadstr=i;
if (i==0) { mypl->myfree(old_table); old_table=NULL; }
return old_table;
}
/*-------------------------------------------------------------------*/
static int restore_old_table(void * v)
{
int i; char *p=NULL;
/* restore old proxy table */
if(old_proxy_table)
{
for(i=0; i < count_str_proxy_in_3proxy; i++){
p=mypl->proxy_table[i];
mypl->proxy_table[i]=old_proxy_table[i];
mypl->myfree(p);
}
mypl->myfree(old_proxy_table);
old_proxy_table = NULL;
}
p=NULL;
/* restore old admin table */
if(old_admin_table)
{
for(i=0; i < count_str_admin_in_3proxy; i++){
p=mypl->admin_table[i];
mypl->admin_table[i]=old_admin_table[i];
mypl->myfree(p);
}
mypl->myfree(old_admin_table);
old_admin_table = NULL;
}
/*return 1 delete job, 0 no delete!!! :)*/
return 1;
}
/*-------------------------------------------------------------------*/
#ifdef _WIN32
__declspec(dllexport) int start(struct pluginlink * pluginlink,
int argc, char** argv);
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
if (ul_reason_for_call == DLL_PROCESS_DETACH)
{
if(old_proxy_table) { restore_old_table(NULL); }
}
return TRUE;
}
#else
int start(struct pluginlink * pluginlink,
int argc, char** argv);
#endif
/*---------------------- start plugin init ------------------------------ */
int start(struct pluginlink * pluginlink, int argc, char** argv)
{
FILE *f=NULL;
mypl=pluginlink;
if(old_proxy_table||old_admin_table) restore_old_table(NULL);
if(!(f=fopen(argv[1],"r"))) return 1001;
/*count string service PROXY in 3proxy */
count_str_proxy_in_3proxy=0;
while( mypl->proxy_table[count_str_proxy_in_3proxy] != NULL )
{ count_str_proxy_in_3proxy++; }
/*count string service ADMIN in 3proxy */
count_str_admin_in_3proxy=0;
while( mypl->admin_table[count_str_admin_in_3proxy] != NULL )
{ count_str_admin_in_3proxy++; }
/*---- load string for PROXY service ----*/
old_proxy_table=load_string(f,count_str_proxy_in_3proxy,
&count_load_str_proxy_from_file,
"[--proxy--]","[/--proxy--]",
mypl->proxy_table);
if (old_proxy_table == NULL)
{
fprintf(stderr,"Error StringsPlugin: No load string from file %s \
for service PROXY !\n",argv[1]);
}
if(count_str_proxy_in_3proxy!= count_load_str_proxy_from_file)
{
fprintf(stderr,"Warning StringsPlugin: Count string for service PROXY in\
3proxy not equality count string in file %s \n",argv[1]);
}
/*---- load string for ADMIN service ----*/
old_admin_table=load_string(f,count_str_admin_in_3proxy,
&count_load_str_admin_from_file,
"[--admin--]","[/--admin--]",
mypl->admin_table);
if (old_admin_table == NULL)
{
fprintf(stderr,"Error StringsPlugin: No load string from file %s \
for service ADMIN !\n",argv[1]);
}
if(count_str_admin_in_3proxy!= count_load_str_admin_from_file)
{
fprintf(stderr,"Warning StringsPlugin: Count string for service ADMIN in\
3proxy not equality count string in file %s\n",argv[1]);
}
fclose(f);
/* create job shedule for processing reload */
if(*pluginlink->schedule!=&myschedule){
memset(&myschedule,0,sizeof(struct schedule));
myschedule.type=NONE;
myschedule.function=restore_old_table;
myschedule.next = *pluginlink->schedule;
*pluginlink->schedule=&myschedule;
}
return 0;
}
#ifdef __cplusplus
extern }
#endif
+2
View File
@@ -0,0 +1,2 @@
/TrafficPlugin.c/1.11/Fri Aug 14 10:20:01 2009//
D
+1
View File
@@ -0,0 +1 @@
3proxy-0.5a/src/plugins/TrafficPlugin
+1
View File
@@ -0,0 +1 @@
/cygdrive/m/MEDIA/H/CVS
+13
View File
@@ -0,0 +1,13 @@
========================================================================
3proxy traffic plugin Changelog
========================================================================
v0.1.2 (2 января 2007 года)
- Плугин обновлён в соответствии с обновлением 3proxy.
- Добавлена опция debug.
v0.1.1
- Теперь udp нельзя задавать proxy, tcppm, pop3p
- Исправлена ошибка с выбором типа соединения.
v0.1.0 beta (10 июля 2006)
Первый релиз.
+1
View File
@@ -0,0 +1 @@
include Makefile.var
+7
View File
@@ -0,0 +1,7 @@
all: $(BUILDDIR)TrafficPlugin$(DLSUFFICS)
TrafficPlugin$(OBJSUFFICS): TrafficPlugin.c
$(CC) $(DCFLAGS) $(CFLAGS) TrafficPlugin.c
$(BUILDDIR)TrafficPlugin$(DLSUFFICS): TrafficPlugin$(OBJSUFFICS)
$(LN) $(LNOUT)../../$(BUILDDIR)TrafficPlugin$(DLSUFFICS) $(LDFLAGS) $(DLFLAGS) TrafficPlugin$(OBJSUFFICS)
+37
View File
@@ -0,0 +1,37 @@
VERFILE = version.obj ../3proxy.RES
#$Id: Makefile.msvc,v 1.17 2010-11-11 14:44:11 v.dubrovin Exp $
#
# 3 proxy Makefile for Microsoft Visual C compiler (for both make and nmake)
#
# You can try to remove -DWITH_STD_MALLOC to CFLAGS to use optimized malloc
# libraries
#
# Add /DSAFESQL to CFLAGS if you are using poorely written/tested ODBC driver
BUILDDIR = ../bin/
CC = cl
CFLAGS = /nologo /MT /W3 /Ox /GS /EHs- /GA /GF /D "MSVC" /D "WITH_STD_MALLOC" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "_WIN32" /Fp"proxy.pch" /FD /c
COUT = /Fo
LN = link
LDFLAGS = /nologo /subsystem:console /incremental:no /machine:I386
DLFLAGS = /DLL
DLSUFFICS = .dll
LIBS = ws2_32.lib advapi32.lib odbc32.lib user32.lib kernel32.lib Gdi32.lib libeay32MT.lib ssleay32MT.lib
LIBEXT = .lib
LNOUT = /out:
EXESUFFICS = .exe
OBJSUFFICS = .obj
DEFINEOPTION = /D
COMPFILES = *.pch *.idb
REMOVECOMMAND = del 2>NUL >NUL
TYPECOMMAND = type
COMPATLIBS =
MAKEFILE = Makefile.msvc
PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin lastFripper FilePlugin
include Makefile.inc
allplugins:
for /D %%i in ($(PLUGINS)) do (copy Makefile plugins\%%i && copy Makefile.var plugins\%%i && cd plugins\%%i && nmake && del *.obj *.idb &&cd ..\..)
+67
View File
@@ -0,0 +1,67 @@
========================================================================
3proxy traffic plugin
========================================================================
Как известно 3proxy считает траффик не сетевой, а прикладной.
Обычно прикладной траффик немного меньше (примерно на 10%) чем сетевой,
однако в некоторых случаях, например когда пользователи сети играют в
игры, сетевой траффик может превысить прикладной в 4-5 раз. Это довольно неприятно,
так как получается, что они за это не платят.
Происходит это потому, что в каждом посланом пакете есть заголовок+данные. Заголовок
весит порядка 50-60 байт а колличество данных может меняться от 15-20 байт (что характерно для игр)
до 800-900 байт (у IE). Также колличество данных в пакете зависит от загрузки сети,
удалённости сервера и прочих причин.
Данный плагин может исправить такую ситуацию. Он может умножать счётчик траффика
при окончании соединения на некоторый коэффициент либо добавлять к данным размеры заголовков пакетов,
которые прошли по сети.
Как использовать плагин:
загрузка плагина:
plugin "TrafficPlugin.dll" start
Далее недоходимо добавить правила:
ДЛЯ РЕЖИМА ДОМНОЖЕНИЯ ТРАФФИКА НА ЧИСЛО:
trafcorrect m <сервис> <исходящий порт> <коэффициент>
где: <сервис> может быть proxy, socks4, socks45, socks5, tcppm, udppm, pop3p
если сервис указан неверно то считается, что это может быть любой сервис.
можно использовать *, тогда правило будет считаться для любого сервиса.
<исходящий порт> - порт, к которому подключается прокси сервер. * - любой
<коэффициент> - число на каоторое домнажается траффик. Обязательный параметр.
Должен быть от больше 0 и меньше 100
ДЛЯ РЕЖИМА С УЧЁТОМ РАЗМЕРА ЗАГОЛОВКОВ ПАКЕТОВ:
trafcorrect p <сервис> <tcp/udp> <исходящий порт> [размер пустого пакета]
<tcp/udp> - протокол, по которому осуществляется соединение.
[размер пакета] - средний размер пустого пакета. Можно определить захватив
данные при помощи такой утилиты как Ethernal. Параметр необязателен. Если отсутствует,
то размер пакета будет считаться равным 66 байт.
Режимы можно смешивать.
Следует учитывать, что плугин создаёт список всех правил изменения траффика.
Когда происходит окончание соединения выполняется первое подходящее правило.
Пример:
plugin "TrafficPlugin.dll" start
trafcorrect m socks5 6112 4.5
trafcorrect m socks5 * 1.1
следующее неверно:
plugin "TrafficPlugin.dll" start
trafcorrect m socks5 * 1.1
trafcorrect m socks5 6112 4.5
Вторая строчка выполнена никогда не будет. Так как 1 имеет более широкое назначение.
РЕЖИМ ОТЛАДКИ ПРАВИЛ:
1. Запускает прокси в оконном режиме (чтобы видеть stdout).
2. Загрузка плагина должна выглядеть сл. образом:
plugin "TrafficPlugin.dll" start debug
3. В окне прокси сервера будет написана информация о прохождении правил коррекции траффика.
Правила нумеруются с 1.
/////////////////////////////////////////////////////////////////////////////
Copyright:
(c) Maslov Michael aka Flexx(rus) All rights reserved.
Plugin was writen on Visual C++ 6.0 SP5
Using structures.h from 3proxy distr.
+282
View File
@@ -0,0 +1,282 @@
/*
3proxy Traffic correct plugin v0.1 beta
Íàïèñàë Maslov Michael aka Flexx(rus)
Ôîðìóëà ðàñ÷¸òà òðàôôèêà ïî ðàçìåðó ïàêåòà by 3APA3A
email: flexx_rus@mail.ru
ICQ: 299132764
http://3proxy.ru/
Êàê ðàáîòàåò íå çíàþ (ìíîãîå çàâèñèò îò âàøèõ íàñòðîåê). Íèêàêèõ ãàðàíòèé.
Ñ ïëóãèíîì ìîæåòå äåëàòü âñ¸, ÷òî çàõî÷åòñÿ.
Äîæåí ðàñïðîñòðîíÿòüñÿ òîëüêî ñ èñõîäíûìè êîäàìè èëè âìåñòå ñ 3proxy.
Óäàëÿòü äàííûé Copyright çàïðåùåíî.
*/
#include "../../structures.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
int DBGLEVEL = 0;
int already_loaded = 0;
typedef int (* handler)(int argc, unsigned char ** argv);
struct extparam * conf;
struct commands * commandhandlers;
struct pluginlink * pl;
typedef enum {
MULTIPLAY, /* ìåòîä êîððåêöèè óìíîæåíèåì íà êîôôèöèåíò */
IPCORRECT, /* ìåòîä êîððåêöèè ñ ó÷¸òîì ðàçìåðà ïàêåòà */
} TRAFCORRECT_TYPE;
typedef enum {
UDP,
TCP
} CONN_TYPE;
struct trafcorrect {
struct trafcorrect * next;
TRAFCORRECT_TYPE type;
int port;
PROXYSERVICE p_service;
double coeff;
CONN_TYPE con_type;
int psize;
};
struct trafcorrect * firsttrafcorrect = NULL;
static void addtrafcorrect(struct trafcorrect * tc) {
struct trafcorrect * starttrafcorrect;
if (!firsttrafcorrect) {
firsttrafcorrect = tc;
return;
}
starttrafcorrect = firsttrafcorrect;
for ( ; starttrafcorrect->next ; starttrafcorrect = starttrafcorrect->next);
starttrafcorrect->next = tc;
}
static void killtrafcorrect() {
struct trafcorrect * p = firsttrafcorrect;
struct trafcorrect * d;
if (!firsttrafcorrect) return;
firsttrafcorrect = NULL;
while (p) {
d = p;
p = p->next;
pl->myfree(d);
}
}
struct commands trafcorrect_handler;
int h_trafcorrect(int argc, unsigned char ** argv) {
if (argc < 2) {
if(DBGLEVEL == 1)fprintf(stdout, "See documentation of traffic correct plugin.\n");
return 1;
}
/* ðåæèì óìíîæåíèÿ òðàôôèêà íà êîýôôèöèåíò */
if (!strcmp((char *)argv[1], "m")) {
struct trafcorrect * newitem;
if (argc < 5) {
if(DBGLEVEL == 1){
fprintf(stdout, "USE: trafcorrect m <service> <port> <coefficient>\n");
fprintf(stdout, "See documentation of traffic correct plugin.\n");
}
return 1;
}
newitem = (struct trafcorrect *)pl->myalloc(sizeof(struct trafcorrect));
newitem->next = NULL;
newitem->type = MULTIPLAY;
newitem->p_service = S_NOSERVICE;
if (!strcmp((char *)argv[2], (char *)"proxy")) newitem->p_service = S_PROXY;
if (!strcmp((char *)argv[2], (char *)"socks4")) newitem->p_service = S_SOCKS4;
if (!strcmp((char *)argv[2], (char *)"socks45")) newitem->p_service = S_SOCKS45;
if (!strcmp((char *)argv[2], (char *)"socks5")) newitem->p_service = S_SOCKS5;
if (!strcmp((char *)argv[2],(char *) "tcppm")) newitem->p_service = S_TCPPM;
if (!strcmp((char *)argv[2],(char *) "udppm")) newitem->p_service = S_UDPPM;
if (!strcmp((char *)argv[2], (char *)"admin")) newitem->p_service = S_ADMIN;
if (!strcmp((char *)argv[2], (char *)"pop3p")) newitem->p_service = S_POP3P;
newitem->port = atoi((char *)argv[3]);
newitem->coeff = atof((char *)argv[4]);
/* ïðîâåðêà íà êîððåêòíîñòü ââîäà */
if ((newitem->port>65535) | (newitem->coeff<=0) | (newitem->coeff>100)) {
pl->myfree(newitem);
if(DBGLEVEL == 1)fprintf(stdout, "Port must be 0<p<65535 and coefficient must be 0<c<100.\n");
return 2;
}
addtrafcorrect(newitem);
return 0;
}
/* ðåæèì ó÷¸òà âõîäÿùèõ è èñõîäÿùèõ ïàêåòîâ */
if (!strcmp((char *)argv[1], "p")) {
struct trafcorrect * newitem;
if (argc < 5) {
if(DBGLEVEL == 1){
fprintf(stdout, "USE: trafcorrect p <service> <tcp/udp> <port> [packet size]\n");
fprintf(stdout, "See documentation of traffic correct plugin.\n");
}
return 1;
}
newitem = (struct trafcorrect *)pl->myalloc(sizeof(struct trafcorrect));
newitem->next = NULL;
newitem->type = IPCORRECT;
newitem->p_service = S_NOSERVICE;
if (!strstr((char *)argv[2], "proxy")) newitem->p_service = S_PROXY;
if (!strstr((char *)argv[2], "socks4")) newitem->p_service = S_SOCKS4;
if (!strstr((char *)argv[2], "socks45")) newitem->p_service = S_SOCKS45;
if (!strstr((char *)argv[2], "socks5")) newitem->p_service = S_SOCKS5;
if (!strstr((char *)argv[2], "tcppm")) newitem->p_service = S_TCPPM;
if (!strstr((char *)argv[2], "udppm")) newitem->p_service = S_UDPPM;
if (!strstr((char *)argv[2], "admin")) newitem->p_service = S_ADMIN;
if (!strstr((char *)argv[2], "pop3p")) newitem->p_service = S_POP3P;
newitem->con_type = TCP;
newitem->psize = 52;
if ((!strcmp((char *)argv[3], "udp")) & (newitem->p_service != S_PROXY) & (newitem->p_service != S_TCPPM) & (newitem->p_service != S_POP3P)) {
newitem->con_type = UDP;
newitem->psize = 48;
}
newitem->port = atoi((char *)argv[4]);
/* ïîñëåäíèé íåîáÿçàòåëüíûé ïàðàìåòð - ðàçìåð ïàêåòà */
if (argc >= 6) {
newitem->psize = atoi((char *)argv[5]);
}
if ((newitem->port>65535) | (newitem->psize<=0)) {
pl->myfree(newitem);
if(DBGLEVEL == 1)fprintf(stdout, "Port must be 0<p<65535.\n");
return 2;
}
addtrafcorrect(newitem);
return 0;
}
if(DBGLEVEL == 1)fprintf(stdout, "See documentation of traffic correct plugin.\n");
return 1;
}
static unsigned short myhtons(unsigned short port) {
return (port << 8) | (port >> 8);
}
LOGFUNC origlogfunc;
void mylogfunc(struct clientparam * param, const unsigned char * pz) {
PROXYSERVICE g_s = S_NOSERVICE;
int port;
int rule = 0;
struct trafcorrect * starttrafcorrect = firsttrafcorrect;
int statssrv_before, statscli_before;
int ok = 0;
for (;starttrafcorrect != NULL; starttrafcorrect = starttrafcorrect->next) {
port = starttrafcorrect->port;
g_s = starttrafcorrect->p_service;
if (starttrafcorrect->p_service == S_NOSERVICE) g_s = param->service;
if (starttrafcorrect->port <= 0) port = myhtons(param->sins.sin_port);
statssrv_before = param->statssrv;
statscli_before = param->statscli;
rule++;
if (((g_s == param->service) && (port == myhtons(param->sins.sin_port))) ||
( ((starttrafcorrect->type == UDP) &&
((param->operation == UDPASSOC)||
(param->operation == DNSRESOLVE)||
(param->operation == BIND)||
(param->operation == ICMPASSOC))
)||(starttrafcorrect->type == TCP))) /* TCP support */
{
/* ôèëüòð ïîäîø¸ë. ìîæíî èçìåíÿòü çíà÷åíèå òðàôôèêà
äîìíîæàåì íà ÷èñëî */
if (starttrafcorrect->type == MULTIPLAY) {
param->statssrv = (unsigned)((double)param->statssrv *starttrafcorrect->coeff);
param->statscli = (unsigned)((double)param->statscli * starttrafcorrect->coeff);
}
/* ñ ó÷¸òîì ïàêåòîâ */
if (starttrafcorrect->type == IPCORRECT) {
if (starttrafcorrect->con_type == TCP) {
param->statssrv+=(param->nreads + 3*param->nconnects)*starttrafcorrect->psize;
param->statscli+=(param->nwrites + 3*param->nconnects)*starttrafcorrect->psize;
} else {
param->statssrv+=param->nreads*starttrafcorrect->psize;
param->statscli+=param->nwrites*starttrafcorrect->psize;
}
}
if (DBGLEVEL == 1) {
fprintf(stdout, "Port=%hd; Before: srv=%d, cli=%d; After: srv=%ld, cli=%ld; nreads=%ld; nwrites=%ld; Rule=%d\n",myhtons(param->sins.sin_port), statssrv_before, statscli_before, param->statssrv, param->statscli,param->nreads,param->nwrites,rule);
}
ok = 1;
break;
}
}
if ((!ok) && (DBGLEVEL == 1)) {
fprintf(stdout, "No rules specifed: service=%d, port=%d, operation=%d", param->service, param->sins.sin_port,param->operation);
}
origlogfunc(param, pz);
}
#ifdef _WIN32
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
if (ul_reason_for_call == DLL_PROCESS_DETACH) killtrafcorrect();
return TRUE;
}
__declspec(dllexport)
#endif
int start(struct pluginlink * pluginlink, int argc, char** argv) {
struct commands * starthandler;
conf = pluginlink->conf;
commandhandlers = pluginlink->commandhandlers;
pl = pluginlink;
if (argc>1) {
/*for (int i = 0; i< argc; i++) fprintf(stdout,"%s ", argv[i]); */
if (!strcmp((char *)argv[1], "debug")) {
DBGLEVEL = 1;
fprintf(stdout, "Traffic correct plugin: debug mode enabled.\n");
}
}
if (already_loaded) {
killtrafcorrect();
return 0;
}
already_loaded = 1;
/* äîáàâëÿåì êîìàíäó "trafcorrect" */
starthandler = commandhandlers;
for ( ; starthandler->next; starthandler = starthandler->next);
trafcorrect_handler.next = NULL;
trafcorrect_handler.minargs = 1;
trafcorrect_handler.maxargs = 10;
trafcorrect_handler.command = "trafcorrect";
trafcorrect_handler.handler = h_trafcorrect;
starthandler->next = &trafcorrect_handler;
/* ïîäìåíÿåì conf->logfunc, ñ öåëüþ êîíòðîëèðîâàòü òðàôôèê */
origlogfunc = conf->logfunc;
conf->logfunc = mylogfunc;
return 0;
}
#ifdef __cplusplus
}
#endif
@@ -0,0 +1 @@
D
@@ -0,0 +1 @@
3proxy-0.5a/src/plugins/TransparentPlugin
+1
View File
@@ -0,0 +1 @@
/cygdrive/m/MEDIA/H/CVS
+1
View File
@@ -0,0 +1 @@
include Makefile.var
@@ -0,0 +1,10 @@
all: $(BUILDDIR)TransparentPlugin$(DLSUFFICS)
transparent_plugin$(OBJSUFFICS): transparent_plugin.c
$(CC) $(DCFLAGS) $(CFLAGS) transparent_plugin.c
$(BUILDDIR)TransparentPlugin$(DLSUFFICS): transparent_plugin$(OBJSUFFICS)
$(LN) $(LNOUT)../../$(BUILDDIR)TransparentPlugin$(DLSUFFICS) $(LDFLAGS) $(DLFLAGS) transparent_plugin$(OBJSUFFICS)
@@ -0,0 +1,35 @@
#$Id: Makefile.win,v 1.9 2007/08/20 15:26:27 vlad Exp $
#
# 3 proxy Makefile for GCC/windows
#
# You can try to remove -DWITH_STD_MALLOC to CFLAGS to use optimized malloc
# libraries
#
# remove -DNOODBC from CFLAGS and add -lodbc to LDFLAGS to compile with ODBC
# library support
BUILDDIR = ../bin/
CC = gcc
CFLAGS = -Wall -O2 -s -c -mno-cygwin -mthreads -DWITH_STD_MALLOC
COUT = -o
LN = gcc
LDFLAGS = -Wall -O2 -s -mno-cygwin -mthreads
DLFLAGS = -shared
DLSUFFICS = .dll
LIBS = -lws2_32 -lodbc32 -ladvapi32
LNOUT = -o
EXESUFFICS = .exe
OBJSUFFICS = .o
DEFINEOPTION = -D
COMPFILES = *.tmp
REMOVECOMMAND = rm -f
TYPECOMMAND = cat
COMPATLIBS =
MAKEFILE = Makefile.win
PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin
include Makefile.inc
allplugins:
@list='$(PLUGINS)'; for p in $$list; do cp Makefile Makefile.var plugins/$$p; cd plugins/$$p ; make ; rm *.o ; cd ../.. ; done
@@ -0,0 +1,114 @@
/*
3APA3A simpliest proxy server
(c) 2007-2008 by ZARAZA <3APA3A@security.nnov.ru>
please read License Agreement
$Id: transparent_plugin.c,v 1.9 2010-11-11 11:32:33 v.dubrovin Exp $
*/
#include <sys/utsname.h>
#include "../../structures.h"
#include "../../proxy.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <limits.h>
#include <linux/netfilter_ipv4.h>
#ifdef __cplusplus
extern "C" {
#endif
#ifndef isnumber
#define isnumber(i_n_arg) ((i_n_arg>='0')&&(i_n_arg<='9'))
#endif
static struct pluginlink * pl;
static pthread_mutex_t transparent_mutex;
static int transparent_loaded = 0;
static void* transparent_filter_open(void * idata, struct srvparam * param){
return idata;
}
static FILTER_ACTION transparent_filter_client(void *fo, struct clientparam * param, void** fc){
#ifdef SO_ORIGINAL_DST
struct sockaddr_in addr;
socklen_t len;
unsigned u;
unsigned short p;
char addrbuf[24];
len = sizeof(addr);
if(getsockopt(param->clisock, SOL_IP, SO_ORIGINAL_DST,(struct sockaddr *) &addr, &len) || !addr.sin_addr.s_addr){
perror("getsockopt()");
return PASS;
}
u = ntohl(addr.sin_addr.s_addr);
p = ntohs(addr.sin_port);
sprintf(addrbuf, "%u.%u.%u.%u:%hu",
((u&0xFF000000)>>24),
((u&0x00FF0000)>>16),
((u&0x0000FF00)>>8),
((u&0x000000FF)),
p);
param->srv->logfunc(param, (unsigned char *)"transparent_filter_client() Success");
param->srv->logfunc(param, (unsigned char *)addrbuf);
pl->parsehostname(addrbuf, param, 0);
return PASS;
#else
#error No SO_ORIGINAL_DST defined
param->srv->logfunc(param, (unsigned char *)"transparent_plugin: No SO_ORIGINAL_DST defined");
return REJECT;
#endif
return PASS;
}
static void transparent_filter_clear(void *fo){
}
static void transparent_filter_close(void *fo){
}
static struct filter transparent_filter = {
NULL,
"Transparent filter",
"Transparent filter",
transparent_filter_open,
transparent_filter_client,
NULL, NULL, NULL, NULL, NULL, NULL,
transparent_filter_clear,
transparent_filter_close
};
#ifdef _WIN32
__declspec(dllexport)
#endif
int transparent_plugin (struct pluginlink * pluginlink,
int argc, char** argv){
pl = pluginlink;
if(!transparent_loaded){
transparent_loaded = 1;
pthread_mutex_init(&transparent_mutex, NULL);
transparent_filter.next = pl->conf->filters;
pl->conf->filters = &transparent_filter;
}
return 0;
}
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,4 @@
/Makefile/1.3/Tue Jan 23 15:46:31 2007//
/Makefile.inc/1.5/Fri Apr 6 14:12:06 2007//
/WindowsAuthentication.c/1.12/Tue Apr 12 13:05:58 2011//
D
@@ -0,0 +1 @@
3proxy-0.5a/src/plugins/WindowsAuthentication
@@ -0,0 +1 @@
/cygdrive/m/MEDIA/H/CVS
@@ -0,0 +1 @@
include Makefile.var
@@ -0,0 +1,8 @@
all: $(BUILDDIR)WindowsAuthentication$(DLSUFFICS)
WindowsAuthentication$(OBJSUFFICS): WindowsAuthentication.c
$(CC) $(DCFLAGS) $(CFLAGS) WindowsAuthentication.c
$(BUILDDIR)WindowsAuthentication$(DLSUFFICS): WindowsAuthentication$(OBJSUFFICS)
$(LN) $(LNOUT)../../$(BUILDDIR)WindowsAuthentication$(DLSUFFICS) $(LDFLAGS) $(DLFLAGS) WindowsAuthentication$(OBJSUFFICS) $(LIBS)
@@ -0,0 +1,37 @@
VERFILE = version.obj ../3proxy.RES
#$Id: Makefile.msvc,v 1.17 2010-11-11 14:44:11 v.dubrovin Exp $
#
# 3 proxy Makefile for Microsoft Visual C compiler (for both make and nmake)
#
# You can try to remove -DWITH_STD_MALLOC to CFLAGS to use optimized malloc
# libraries
#
# Add /DSAFESQL to CFLAGS if you are using poorely written/tested ODBC driver
BUILDDIR = ../bin/
CC = cl
CFLAGS = /nologo /MT /W3 /Ox /GS /EHs- /GA /GF /D "MSVC" /D "WITH_STD_MALLOC" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "_WIN32" /Fp"proxy.pch" /FD /c
COUT = /Fo
LN = link
LDFLAGS = /nologo /subsystem:console /incremental:no /machine:I386
DLFLAGS = /DLL
DLSUFFICS = .dll
LIBS = ws2_32.lib advapi32.lib odbc32.lib user32.lib kernel32.lib Gdi32.lib libeay32MT.lib ssleay32MT.lib
LIBEXT = .lib
LNOUT = /out:
EXESUFFICS = .exe
OBJSUFFICS = .obj
DEFINEOPTION = /D
COMPFILES = *.pch *.idb
REMOVECOMMAND = del 2>NUL >NUL
TYPECOMMAND = type
COMPATLIBS =
MAKEFILE = Makefile.msvc
PLUGINS = utf8tocp1251 WindowsAuthentication TrafficPlugin StringsPlugin PCREPlugin lastFripper FilePlugin
include Makefile.inc
allplugins:
for /D %%i in ($(PLUGINS)) do (copy Makefile plugins\%%i && copy Makefile.var plugins\%%i && cd plugins\%%i && nmake && del *.obj *.idb &&cd ..\..)
Loaded 100 of 217 files, more files were not shown because too many files have changed in this diff. Show more