/* Socks Server 5
* Copyright (C) 2002 - 2006 by Matteo Ricchetti - <matteo.ricchetti@libero.it>

* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

#ifndef SS5MAIN_H
#define SS5MAIN_H 1

#include <pthread.h>
#include <pwd.h>
#define _XOPEN_SOURCE
#include <time.h>
#include <ctype.h>
#include <netdb.h>
#include <fcntl.h>
#include <stdio.h>
#include <signal.h>
#include <syslog.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <sched.h>
#include <unistd.h>
#include <errno.h>
#include <dlfcn.h>

#include "config.h"

#ifdef LINUX
#include <linux/if.h>
#include <linux/if_ether.h>
#endif

#ifdef SOLARIS
#include <net/if.h>
#include <sys/sockio.h>
#endif

#ifdef FREEBSD
#include <sys/syslog.h>
#include <sys/param.h>
#include <net/if.h>
#include <net/if_dl.h>
#endif

/*
* MACRO for epoll:
*/
#ifdef EPOLL_IO
#include <sys/epoll.h>
#define IFEPOLL(x)	x
#define IFSELECT(x)
#else
#define IFSELECT(x)	x
#define IFEPOLL(x)
#endif

/*
* MACRO for OS:
*/
#ifdef LINUX
#define IFLINUX(x)	x
#define IFSOLARIS(x)
#else
#define IFSOLARIS(x)	x
#define IFLINUX(x)
#endif

#ifdef LINUX
#define SS5_SEND_OPT           MSG_NOSIGNAL   
#else
#define SS5_SEND_OPT           0     
#endif

/*
* MACRO for options:
*/
#define THREADED()	( SS5SocksOpt.IsThreaded )
#define NOTTHREADED()	( !SS5SocksOpt.IsThreaded )

#define SYSLOG()	( SS5SocksOpt.Syslog )
#define VERBOSE()	( SS5SocksOpt.Verbose )
#define DEBUG()		( SS5SocksOpt.Debug )
#define BALANCE()	( SS5SocksOpt.IsBalance )
#define CONSOLE()	( SS5SocksOpt.IsConsole )
#define DUMP()		( SS5SocksOpt.IsDump )
#define FILTER()	( SS5Facilities.Fixup[0] != '-' )
#define DISFILTER()	SS5Facilities.Fixup[0] = '-';
#define ROUTE()		( SS5SocksOpt.IsRoute )
#define UPSTREAM()	( SS5SocksOpt.IsUpstream )
#define BANDWIDTH()	( SS5Facilities.Bandwidth )

#define AUTHENFILE()      ( SS5SocksOpt.Authentication == FILE_AUTHENTICATION )
#define AUTHENEAP()       ( SS5SocksOpt.Authentication == EAP_AUTHENTICATION )
#define AUTHENPAM()       ( SS5SocksOpt.Authentication == PAM_AUTHENTICATION )
#define LDAPBASE() 	  ( SS5SocksOpt.LdapCriteria   == LDAP_BASE )
#define LDAPFILTER() 	  ( SS5SocksOpt.LdapCriteria   == LDAP_FILTER )
#define AUTHORFILE()      ( SS5SocksOpt.Profiling == FILE_PROFILING )
#define AUTHORDIRECTORY() ( SS5SocksOpt.Profiling == LDAP_PROFILING )
#define ISSOCKS4()	  ( SS5MethodInfo.Ver     == SOCKS4_VERSION )
#define ISSOCKS5()	  ( SS5MethodInfo.Ver     == SOCKS5_VERSION )
#define NOTMUTE()	  ( SS5SocksOpt.Mute      == ERR )

#define STREQ(x,y,z)	  !strncmp(x,y,z)
#define STRCASEEQ(x,y,z)  !strncasecmp(x,y,z)

/*
* MACRO for modules:
*/
#define MODBALANCING()  ( SS5Modules.mod_balancing_loaded  )
#define MODSTATISTICS() ( SS5Modules.mod_statistics_loaded )
#define MODBANDWIDTH()  ( SS5Modules.mod_bandwidth_loaded  )
#define MODDUMP()       ( SS5Modules.mod_dump_loaded       )
#define MODFILTER()     ( SS5Modules.mod_filter_loaded     )
#define MODSOCKS4()     ( SS5Modules.mod_socks4_loaded     )
#define NOTMODSOCKS4()  ( !SS5Modules.mod_socks4_loaded    )

#define LOGUPDATE()	SS5Modules.mod_logging.Logging(logString);
#define UPDATESTAT()	SS5Modules.mod_statistics.Summary(autheErr,authoErr,cmdErr);

/*
* MACRO for general purpose:
*/
#define THREADEXIT()	 { S5ChildClose(CONTINUE,SS5ClientInfo.Socket); pthread_exit(THREAD_EXIT); }
#define PROCESSCLOSE()	 { S5ChildClose(CONTINUE,SS5ClientInfo.Socket); return ERR; }
#define PROCESSEXIT()    S5ChildClose(EXIT,SS5ClientInfo.Socket);
#define LOCKMUTEXCS()	 pthread_mutex_lock  ( &CSMutex );
#define UNLOCKMUTEXCS()	 pthread_mutex_unlock( &CSMutex );
#define LOCKMUTEXCA()	 pthread_mutex_lock  ( &CAMutex );
#define UNLOCKMUTEXCA()	 pthread_mutex_unlock( &CAMutex );
#define LOCKMUTEXCT()	 pthread_mutex_lock  ( &CTMutex );
#define UNLOCKMUTEXCT()	 pthread_mutex_unlock( &CTMutex );
#define LOCKMUTEXCO()	 pthread_mutex_lock  ( &COMutex );
#define UNLOCKMUTEXCO()	 pthread_mutex_unlock( &COMutex );
#define LOCKMUTEXPAM()	 pthread_mutex_lock  ( &PAMMutex );
#define UNLOCKMUTEXPAM() pthread_mutex_unlock( &PAMMutex );

#ifdef LINUX
#define ERRNO(p)        { snprintf(logString,sizeof(logString) - 1,"[%u] [ERRO] $%s$: (%s).",p,__func__,(char *)strerror_r(errno,logString,sizeof(logString) - 1)); \
		          LOGUPDATE() }
#else
#define ERRNO(p)        { snprintf(logString,sizeof(logString) - 1,"[%u] [ERRO] $%s$: (%s).",p,__func__,strerror(errno)); \
		          LOGUPDATE() }
#endif

#define ERRNOPAM(p,h,e) { snprintf(logString,sizeof(logString) - 1,"[%u] [ERRO] $%s$: (%s).",p,__func__,pam_strerror( h, e)); \
		          LOGUPDATE() }

#define ERRNOLDAP(p,r)  { snprintf(logString,sizeof(logString) - 1,"[%u] [ERRO] $%s$: (%s).",p,__func__,ldap_err2string(r)); \
		          LOGUPDATE() }

#define SS5_VERSION        "SS5 Version 3.6.2 - Release 1"

/*
* Socks Server 5:
* ------------------------------------------------------------------------------------
* SECTION 1: socks protocol RFC definitions:
*
* a) Version
* b) Method
* c) Request
*
*/

enum VER_SS5       { SOCKS4_VERSION = 4,
	     SOCKS5_VERSION = 5 };

enum METHOD_SS5    { NOAUTH = 0,
	     GSSAPI = 1,
	     USRPWD = 2,
	     FAKEPWD = 254,
	     NOMETHOD = 255 };

enum COMMAND_SS5   { CONNECT = 1,
	     BIND = 2,
	     UDP_ASSOCIATE = 3 };

enum ADDRTYPE_SS5  { IPV4 = 1,
	     DOMAIN = 3,
	     IPV6 = 4 };

/*
* Socks Server 5:
* ------------------------------------------------------------------------------------
* SECTION 2: socks protocol CUSTOM definitions:
*
*/


#define CONTINUE                0
#define EXIT                    1
#define THREAD_EXIT             0

#define LOAD_CONFIG             2
#define RELOAD_CONFIG           1
#define PARSE_CONFIG            0

#define MASTER			0
#define SLAVE			1
#define ALONE			2

#define SOCKS5_PORT             1080    /* Default socks port */
#define DATABUF                 1460    /* MTU - (header IP + header TCP) */
#define MAXIF                   2048    /* Max number of network interfaces */
#define MAXPREFORKPROCS         5000    /* Max number of preforked processes */
#define MAXPREFORKPROCLIFE      2048    /* Max number of requests a preforked process can servs */
#define MAXPEERS                  12    /* Max number of network interfaces */

enum ERR_SS5 { ERR = 0,
       OK = 1 };

/*
* SS5: Custom data types
*/
typedef int S5RetCode;
typedef unsigned int S5Limit;

S5Limit NInterF;

pthread_mutex_t COMutex;
pthread_mutex_t PAMMutex;

S5Limit NPeers;

/*
* Socks Server 5:
* ------------------------------------------------------------------------------------
* SECTION 3: socks protocol CUSTOM structures
*
* a) Network interfaces
* b) Tcp client info
* c) Udp client info
* d) Method info
* e) Authenticaiotn info
* f) Tcp request info
* g) Udp request info
* h) Upstream info
* i) V4 socks protocol data
* l) V5 socks protocol data
* m) Options
* n) Modules
* o) Modules pointer funciotns
*
*/

int S5SocksSocket;

struct sockaddr_in S5SocksSsin;

FILE *S5ConfFile;

FILE *S5PeerFile;

char S5ConfigFile[128];
char S5PeersFile[128];
char S5PasswordFile[128];
char S5LibPath[128];
char S5TracePath[128];
char S5ProfilePath[128];
char S5LoggingFile[128];
char S5RepKey[16];

struct _SS5Peer {
  char IP[16];
} SS5Peer[MAXPEERS];

struct _S5Interface {
char IP[16];
char NetMask[16];
} *S5Interface[MAXIF];

struct _SS5ClientInfo{
unsigned int Socket;
struct sockaddr_in SockAddr;
char SrcAddr[16];
unsigned int SrcPort;
};

struct _SS5UdpClientInfo{
int Socket;
struct sockaddr_in SockAddr;
char SrcAddr[16];
unsigned int SrcPort;
};

struct _SS5MethodInfo {
unsigned int Ver;
unsigned int NMeth;
unsigned int NoAuth;
unsigned int BasicAuth;
unsigned int Method;
};

struct _SS5AuthInfo {
char Username[64];
char Password[64];
};

struct _SS5RequestInfo {
unsigned int Ver;
unsigned int Cmd;
unsigned int Rsv;
unsigned int ATyp;
char DstAddr[64];
unsigned int DstPort;
};

struct _SS5UdpRequestInfo {
unsigned int Rsv;
unsigned int Frag;
unsigned int ATyp;
char DstAddr[64];
unsigned int DstPort;
};

struct _SS5UpstreamInfo{
unsigned long int DstAddr;
unsigned int DstPort;
};

struct _SS5DumpInfo{
unsigned int DumpMode;
};

struct _SS5Facilities {
char Fixup[16];               /* Fixup */
char Group[64];               /* User groups */
unsigned long int Bandwidth;  /* Bandwidth */
char ExpDate[10];             /* Acl expiration date */
};

struct _SS5SocksOpt {
unsigned int DnsOrder;           /* Dns ordering */
unsigned int Verbose;            /* verbose mode */
unsigned int Debug;              /* Debug mode */
unsigned int Syslog;             /* Log to syslog */
unsigned int Mute;               /* No logging */
long unsigned int SessionTimeout;/* Session idle timeout */
unsigned int Profiling;          /* Set profiling type */
unsigned int LdapCriteria;       /* Set Ldap criteria */
unsigned int LdapTimeout;        /* Ldap search operation timeout */
unsigned int LdapNetbiosDomain;  /* Ldap netbios compatibility */
unsigned int AuthCacheAge;       /* Authentication cache age */
unsigned int AuthoCacheAge;      /* Authorization cache age */
unsigned int StickyAge;          /* Affinity age */
unsigned int Sticky;             /* Affinity feature */
unsigned int Authentication;     /* Set authentication type */
unsigned int AcceptTimeout;      /* Accept idle timeout */
unsigned int IsThreaded;         /* Threaded mode */
unsigned int IsBalance;          /* At least a balance line */
unsigned int IsUpstream;         /* At least an upstream line */
unsigned int IsRoute;            /* At least a route line */
unsigned int IsDump;             /* At least a dump line */
unsigned int IsConsole;          /* Web console enable */
unsigned int Role;               /* Role of ss5 istance  */
long unsigned int PropagateKey;  /* Key for config propagation  */
unsigned int PreforkProcesses;
unsigned int PreforkProcessLife;
} SS5SocksOpt;


/*
* Socks Server 5:
* ------------------------------------------------------------------------------------
* SECTION 4: modules protocol CUSTOM structures
*
* SOCKS5 module
*
*/

#define BIND_TIMEOUT	120     /* Seconds */
#define UDP_TIMEOUT	5       /* Seconds */
#define MAXMETHODLIST	997     /* Max auth loadable */
#define MAXROUTELIST	997     /* Max route acl loadable */
#define MAXPROXYLIST	997     /* Max proxy list loadable */
#define MAXDNS_RESOLV	30      /* Max hosts resolved */

enum ERR_PROXY {
ERR_NOPROXY = 0
};

S5Limit      NMethodList,
     _tmp_NMethodList,
     NRouteList,
     _tmp_NRouteList,
     NProxyList,
     _tmp_NProxyList;

struct _SS5Socks5Data {
/* Socks server V5 - Method - */
char MethodRequest[256];
char MethodResponse[2];
int  MethodBytesSent;
int  MethodBytesReceived;
/* Socks server V5 - Tcp request - */
char TcpRequest[256];
int  TcpRBytesSent;
int  TcpRBytesReceived;
/* Socks server V5 - Udp request - */
char UdpRequest[DATABUF];
int  UdpRBytesSent;
int  UdpRBytesReceived;
/* Socks server V5 - Response - */
char Response[32];
};

/*
* SS5: Auth line parameters
*/
struct _S5MethodNode {
unsigned int Mask;
unsigned long int SrcAddr;      /* Source ip */
unsigned long int  SrcPort;     /* Source port */
unsigned int SrcRangeMin;
unsigned int SrcRangeMax;
unsigned int Method; 		 /* Authentication type */
struct _S5MethodNode *next;
};

struct  _S5MethodNode **S5MethodList,
	      **_tmp_S5MethodList,
	      **_old_S5MethodList;

/*
* SS5: Route line parameters
*/
struct _S5RouteNode {
unsigned int Mask;
unsigned long int SrcAddr;     /* Source address    */
unsigned long int SrcIf;       /* Source interface  */
char Group[64];                /* Source user group */
struct _S5RouteNode *next;
};

struct _S5RouteNode **S5RouteList,
	    **_tmp_S5RouteList,
	    **_old_S5RouteList;

/*
* SS5: Upstream socks line parameters
*/
struct _S5ProxyNode {
unsigned int Mask;
unsigned int Type;
unsigned long int DstAddr;    /* Destination ip */
unsigned long int DstPort;    /* Destination port */
unsigned int DstRangeMax;     /* Destination port */
unsigned int DstRangeMin;     /* Destination port */
unsigned long int ProxyAddr;  /* Proxy IP */
unsigned int ProxyPort;	/* Proxy port */
struct _S5ProxyNode *next;
};

struct  _S5ProxyNode **S5ProxyList,
	     **_tmp_S5ProxyList,
	     **_old_S5ProxyList;

/*
* SS5: Dns response buffer
*/
struct _S5HostList {
char NextHost[16];
};


/*
* Socks Server 5:
* ------------------------------------------------------------------------------------
* SECTION 5: modules protocol CUSTOM structures
*
* SOCKS4 module
*
*/

struct _SS5Socks4Data {
char Requ[32];
char Resp[8];
};


/*
* Socks Server 5:
* ------------------------------------------------------------------------------------
* SECTION 6: modules protocol CUSTOM structures
*
* AUTHENTICATION module
*
*/

#define FILE_AUTHENTICATION     0
#define PAM_AUTHENTICATION      2
#define EAP_AUTHENTICATION      3
#define MAXAUTHCACHELIST        9997    /* Max authentication cache entries */


enum ERR_AUTHENTICATION {
ERR_EXPIRED=	-1,
ERR_NOAUTH=	2
};


/*
* SS5: PAM buffers
*/
struct _S5PamData {
const char *user;
const char *password;
};

/*
* SS5: Authetication program buffer
*/
struct _S5AuthCmd {
char ProgName[128];
} *S5AuthCmd;

/*
* SS5: Authentication Cache line parameters
*/
struct _S5AuthCacheNode {
char Usr[64];
char Pwd[64];
time_t ttl;
struct _S5AuthCacheNode *next;
};

struct  _S5AuthCacheNode *S5AuthCacheList[MAXAUTHCACHELIST];



struct _SS5BasicData {
char Request[64];               /* Basic request packet */
char Response[2];               /* Basic response packet */
};

FILE *S5PwdFile;        /* Password file pointer  /var/log/ss5.passwd */


/*
* Socks Server 5:
* ------------------------------------------------------------------------------------
* SECTION 7: modules protocol CUSTOM structures
*
* AUTHORIZATION module
*
*/

#define LDAP_BASE	0
#define LDAP_FILTER	1

#define PERMIT  	0
#define DENY    	1

#define PROXY	  	0
#define NOPROXY    	1

#define FILE_PROFILING  0
#define LDAP_PROFILING  1

#define MAXLDAPSTORE   20

#define MAXACLLIST              9997    /* Max acl loadable */
#define MAXAUTHOCACHELIST       9997    /* Max authorization cache entries */

enum ERR_AUTHORIZATION {
ERR_DENY=-2,
ERR_NOACLFOUND=-1};

S5Limit      NAclList,
     _tmp_NAclList;

S5Limit      NLdapStore;

/*
* SS5: Directory configuration parameters
*/
struct _S5Ldap {
char IP[16];        /* Directory ip */
char Port[6];       /* Directory port */
char Base[64];      /* Directory base */
char Filter[128];   /* Directory filter */
char Attribute[32]; /* Directory attribute for FILTER mode */
char Dn[64];        /* Directory dn */
char Pass[16];      /* Directory password */
char NtbDomain[16]; /* Windows netbios domain associated to directory */
} S5Ldap[MAXLDAPSTORE];


/*
* SS5: Permit line parameters
*/
struct _S5AclNode {
unsigned int Method;
unsigned int Type;
unsigned long int SrcAddr;
unsigned int SrcMask;
unsigned long int SrcPort;
unsigned int SrcRangeMin;
unsigned int SrcRangeMax;
unsigned long int DstAddr;
unsigned int DstMask;
unsigned long int DstPort;
unsigned int DstRangeMin;
unsigned int DstRangeMax;
char Fixup[16];
char Group[64];
unsigned long int Bandwidth;
char ExpDate[10];		
struct _S5AclNode *next;
};

struct  _S5AclNode **S5AclList,
	   **_tmp_S5AclList,
	   **_old_S5AclList;

/*
* SS5: Authorization Cache line parameters
*/
struct _S5AuthoCacheNode {
char Sa[64];
unsigned int  Sp;
char Da[64];
unsigned int  Dp;
char Us[64];
struct _SS5Facilities Fa;
time_t ttl;
struct _S5AuthoCacheNode *next;
};

struct  _S5AuthoCacheNode *S5AuthoCacheList[MAXAUTHOCACHELIST];

/*
* Socks Server 5:
* ------------------------------------------------------------------------------------
* SECTION 8: modules protocol CUSTOM structures
*
* PROXY  module
*
*/

#define RECVERR                        -1
#define SENDERR                        -1

struct _SS5ProxyData {
char Recv[DATABUF];
char Send[DATABUF];
int TcpRBufLen;
int TcpSBufLen;
char UdpRecv[DATABUF];
char UdpSend[DATABUF];
int UdpRBufLen;
int UdpSBufLen;
unsigned int Fd;
};


/*
* Socks Server 5:
* ------------------------------------------------------------------------------------
* SECTION 9: modules protocol CUSTOM structures
*
* BALANCE  module
*
*/


#define TCB_REQUEST	1
#define STAT_REQUEST	2
#define STICKY_REQUEST	3
#define STICKY_AGE	3600    /* TTL in seconds for sticky feature */
#define MAX_ENTRY_REAL	256     /* Max number of real servers */
#define MAXSTICKYLIST	997

struct _S5ConnectionEntry {
char Real[16];
unsigned int Vid;
unsigned int Connection;
};

struct _S5ConnectionTable {
struct _S5ConnectionEntry **S5ConnectionEntry,
		    **_tmp_S5ConnectionEntry,
		    **_old_S5ConnectionEntry;
} S5ConnectionTable;

S5Limit NReal,
_tmp_NReal;


struct _S5StickyNode {
unsigned long int srcip;
unsigned long int dstip;
unsigned int vid;
time_t ttl;
struct _S5StickyNode *next;
};

struct _S5StickyNode *S5StickyList[MAXSTICKYLIST];

pthread_mutex_t CTMutex;
pthread_mutex_t CAMutex;

/*
* Socks Server 5:
* ------------------------------------------------------------------------------------
* SECTION 10: modules protocol CUSTOM structures
*
* FILTER  module
*
*/

enum ERR_FILTER {
ERR_HTTP=	-5,
ERR_HTTPS=	-4,
ERR_SMTP=	-3,
ERR_POP3=	-2,
ERR_IMAP4=	-1
};


/*
* SS5: Fixup flags
*/
struct _S5Fixup {
unsigned int Status;
unsigned int Http;
unsigned int Https;
unsigned int Smtp;
unsigned int Pop3;
unsigned int Imap;
};


/*
* Socks Server 5:
* ------------------------------------------------------------------------------------
* SECTION 11: modules protocol CUSTOM structures
*
* STATISTICS  module
*
*/

#define STAT_REQUEST	2

enum STATCODE {
AFN=	1,
AFF=	101,
AEN=	2,
AEF=	102,
APN=	3,
APF=	103,
HFN=	4,
HFF=	104,
HLN=	5,
HLF=	105,
V4CN=	6,
V4CF=	106,
V4BN=	7,
V4BF=	107,
V5CN=	8,
V5CF=	108,
V5BN=	9,
V5BF=	109,
V5UN=	10,
V5UF=	110,
NONE=	0
};

struct _SS5Statistics {
unsigned long int V5Total_Connect,V4Total_Connect;
unsigned long int V5Normal_Connect,V4Normal_Connect;
unsigned long int V5Failed_Connect,V4Failed_Connect;

unsigned long int V5Current_Connect,V4Current_Connect;

unsigned long int V5Total_Bind,V4Total_Bind;
unsigned long int V5Normal_Bind,V4Normal_Bind;
unsigned long int V5Failed_Bind,V4Failed_Bind;

unsigned long int V5Current_Bind,V4Current_Bind;

unsigned long int V5Total_Udp;
unsigned long int V5Normal_Udp;
unsigned long int V5Failed_Udp;

unsigned long int V5Current_Udp;

unsigned long int Total_Auth_File;
unsigned long int Total_Auth_EAP;
unsigned long int Total_Auth_PAM;
unsigned long int Normal_Auth_File;
unsigned long int Normal_Auth_EAP;
unsigned long int Normal_Auth_PAM;
unsigned long int Failed_Auth_File;
unsigned long int Failed_Auth_EAP;
unsigned long int Failed_Auth_PAM;

unsigned long int Current_Auth_File;
unsigned long int Current_Auth_EAP;
unsigned long int Current_Auth_PAM;

unsigned long int Total_Author_File;
unsigned long int Total_Author_Ldap;
unsigned long int Normal_Author_File;
unsigned long int Normal_Author_Ldap;
unsigned long int Failed_Author_File;
unsigned long int Failed_Author_Ldap;

unsigned long int Current_Author_File;
unsigned long int Current_Author_Ldap;

} SS5Statistics;

pthread_mutex_t CSMutex;

/*
* Socks Server 5:
* ------------------------------------------------------------------------------------
* SECTION 12: modules protocol CUSTOM structures
*
* LOGS  module
*
*/

FILE *S5LogFile;        /* Log file pointer /var/log/ss5.log */

/*
* Socks Server 5:
* ------------------------------------------------------------------------------------
* SECTION 13: modules protocol CUSTOM structures
*
* BANDWIDTH  module
*
*/

#define MIN_BANDWIDTH           256     /* Bytes per second */

/*
* Socks Server 5:
* ------------------------------------------------------------------------------------
* SECTION 14: modules protocol CUSTOM structures
*
* DUMP  module
*
*/

#define RX		0
#define TX		1
#define RTX		2

#define MAXDUMPLIST	997     /* Max dump list loadable */

/*
* SS5: dump line parameters
*/
struct _S5DumpNode {
unsigned int Mask;
unsigned long int DstAddr;
unsigned long int DstPort;
unsigned int DstRangeMax;
unsigned int DstRangeMin;
unsigned int DumpMode;
struct _S5DumpNode *next;
};

struct  _S5DumpNode **S5DumpList,
	    **_tmp_S5DumpList,
	    **_old_S5DumpList;



enum ERR_DUMP {
ERR_NODUMPFOUND=-1};

S5Limit      NDumpList,
     _tmp_NDumpList;


/*
* Socks Server 5:
* ------------------------------------------------------------------------------------
* SECTION 15: modules function pointers
*
*
*
*/

struct _module {
/*
* Module Authentication
* Main function pointer
* *******************************************************************************************************************************************
*/
S5RetCode (*Authentication)( 	struct _SS5MethodInfo *mi,
			struct _SS5ClientInfo *ci,
			struct _SS5BasicData *bd,
			struct _SS5AuthInfo *ai );
/*
* Slave function pointer
*/
S5RetCode (*FreeAuthCache)( struct _S5AuthCacheNode **node );

/*
* Module Socks5
* Main function pointer
* *******************************************************************************************************************************************
*/
S5RetCode (*MethodParsing)(	struct _SS5MethodInfo *mi,
			struct _SS5ClientInfo *ci,
			struct _SS5Socks5Data *sd );

S5RetCode (*RequestParsing)( struct _SS5ClientInfo *ci,
			struct _SS5Socks5Data *sd,
			struct _SS5RequestInfo *ri );

S5RetCode (*UpstreamServing)(	struct _SS5UpstreamInfo *ui,
			struct _SS5ClientInfo *ci,
			struct _SS5RequestInfo *ri,
			int *applicationSocket,
			struct _SS5Socks5Data *sd,
			struct _SS5AuthInfo *ai);

S5RetCode (*ConnectServing)( 	struct _SS5ClientInfo *ci,
			struct _SS5RequestInfo *ri,
			struct _SS5AuthInfo *ai,
			int *applicationSocket,
			struct _SS5Socks5Data *sd);

S5RetCode (*BindServing)(	struct _SS5ClientInfo *ci,
			struct _SS5RequestInfo *ri,
			struct _SS5AuthInfo *ai,
			int *applicationSocket,
			struct _SS5Socks5Data *sd);

S5RetCode (*UdpAssociateServing)(	struct _SS5ClientInfo *ci,
				struct _SS5RequestInfo *ri,
				struct _SS5UdpRequestInfo *uri,
				struct _SS5UdpClientInfo *uci,
				int *applicationSocket,
				struct _SS5Socks5Data *sd,
				struct _SS5ProxyData *pd);

S5RetCode (*UdpAssociateResponse)( struct _SS5UdpRequestInfo *uri,
				struct _SS5UdpClientInfo *uci,
				struct _SS5Socks5Data *sd,
				struct _SS5ProxyData *pd);
/*
* Slave function pointer
*/
S5RetCode (*AddMethod)(		unsigned long int sa,
				unsigned long int sp,
				unsigned int me,
				unsigned int mask);

S5RetCode (*FreeMethod)(		struct _S5MethodNode **node );

unsigned char (*GetMethod)(	unsigned long int sa,
				unsigned int sp);

S5RetCode (*AddRoute)(		unsigned long int sa,
				unsigned long int si,
                                char group[64],
				unsigned int mask );

S5RetCode (*FreeRoute)(		struct _S5RouteNode **node );

unsigned long int (*GetRoute)(	unsigned long int sa, char uname[64] );

S5RetCode (*AddProxy)(		unsigned int type,
				unsigned long int da,
				unsigned long int dp,
				unsigned long int pa,
				unsigned int pp,
				unsigned int mask );

S5RetCode (*FreeProxy)(		struct _S5ProxyNode **node );

S5RetCode (*GetProxy)(		unsigned long int da,
				unsigned int dp,
				struct _SS5UpstreamInfo *ui);

/*
* Module Socks4
* Main function pointer
* *******************************************************************************************************************************************
*/
S5RetCode (*V4RequestParsing)(	struct _SS5AuthInfo *ai,
				struct _SS5MethodInfo *mi,
				struct _SS5Socks5Data *sd,
				struct _SS5RequestInfo *ri );

S5RetCode (*V4UpstreamServing)(	struct _SS5UpstreamInfo *ui,
				struct _SS5ClientInfo *ci,
				struct _SS5RequestInfo *ri,
				int *applicationSocket,
				struct _SS5Socks5Data *sd,
				struct _SS5AuthInfo *ai);

S5RetCode (*V4ConnectServing)(	struct _SS5ClientInfo *ci,
				struct _SS5RequestInfo *ri,
				struct _SS5AuthInfo *ai,
				int *applicationSocket,
				struct _SS5Socks5Data *sd);

S5RetCode (*V4BindServing)(		struct _SS5ClientInfo *ci,
				struct _SS5RequestInfo *ri,
				struct _SS5AuthInfo *ai,
				int *applicationSocket,
				struct _SS5Socks5Data *sd);
/*
* Slave function pointer
*/
S5RetCode (*V4AddRoute)(		unsigned long int sa,
				unsigned long int si,
				unsigned int mask );

S5RetCode (*V4FreeRoute)( 		struct _S5RouteNode **node );

unsigned long int (*V4GetRoute)(	unsigned long int sa,
					char uname[64]);

/*
* Module Authorization
* Main function pointer
* *******************************************************************************************************************************************
*/
S5RetCode (*PreAuthorization)(	struct _SS5MethodInfo *mi,
				struct _SS5ClientInfo *ci,
				struct _SS5RequestInfo *ri,
				struct _SS5AuthInfo *ai,
				struct _SS5Facilities *fa);

S5RetCode (*PostAuthorization)(	struct _SS5MethodInfo *mi,
				struct _SS5UdpClientInfo *uci,
				struct _SS5UdpRequestInfo *uri,
				struct _SS5RequestInfo *ri,
				struct _SS5AuthInfo *ai,
				struct _SS5Facilities *fa);
/*
* Slave function pointer
*/
S5RetCode (*AddAcl)(	unsigned int type,
			unsigned long int sa,
			unsigned int sp,
			unsigned long int da,
			unsigned long int dp,
			unsigned int srcmask,
				unsigned int dstmask,
				unsigned int method,
				struct _SS5Facilities *fa);

    S5RetCode (*GetAcl)(	unsigned long int sa,
				unsigned int sp,
				unsigned long int da,
				unsigned int dp,
				struct _SS5Facilities *fa,
				unsigned int *acl);

    S5RetCode (*FreeAcl)(	struct _S5AclNode **node );

    S5RetCode (*FreeAuthoCache)( struct _S5AuthoCacheNode **node );

  /*
   * Module Balancing
   * Main function pointer
   * *******************************************************************************************************************************************
   */
  S5RetCode (*LoadBalancing)(	struct _SS5ClientInfo *ci,
				struct _SS5RequestInfo *ri );
  S5RetCode (*Balancing)( 	struct _SS5ClientInfo *ci,
				struct _SS5Socks5Data *sd );
  /*
   * Slave function pointer
   */
    S5RetCode (*AddConn)( 		char *real );

    S5RetCode (*RemoveConn)( 		char *real );

    S5RetCode (*AddVip)( 		char *real,
					unsigned int vid,
					unsigned int index );

    S5RetCode (*FreeConnectionTable)(	struct _S5ConnectionEntry *ce);

    S5RetCode (*FreeAffinity)( 		struct _S5StickyNode **node );

  /*
   * Module Proxy
   * Main function pointer
   * *******************************************************************************************************************************************
   */
  S5RetCode (*ReceivingData)( 		struct _SS5ClientInfo *ci,
					int applicationSocket,
					struct _SS5ProxyData *pd,
                                      #ifdef EPOLL_IO
					struct epoll_event *events );
                                      #else
					fd_set *s5array );
                                      #endif

  S5RetCode (*UdpReceivingData)( 	int applicationSocket,
					struct _SS5ProxyData *pd );

  S5RetCode (*SendingData)( 		struct _SS5ClientInfo *ci,
					int applicationSocket,
					struct _SS5ProxyData *pd );

  S5RetCode (*UdpSendingData)( 		int applicationSocket,
					struct _SS5UdpRequestInfo *uri,
					struct _SS5ProxyData *pd );

  /*
   * Module Dump
   * Main function pointer
   * *******************************************************************************************************************************************
   */
  S5RetCode (*WritingDump)(         	FILE *df,
                        		struct _SS5ProxyData *pd,
                        		unsigned int dm );

  S5RetCode (*OpenDump)( 		FILE **df,
                                        struct _SS5AuthInfo *ai );

  S5RetCode (*CloseDump)(		FILE *df );

  S5RetCode (*GetDump)(			unsigned long int da,
                        		unsigned int dp,
                        		struct _SS5DumpInfo *di );

  S5RetCode (*AddDump)(			unsigned long int da,
                        		unsigned long int dp,
                        		unsigned int dm,
                        		unsigned int mask );

  S5RetCode (*FreeDump)(		struct _S5DumpNode **node );

  /*
   * Module Filter
   * Main function pointer
   * *******************************************************************************************************************************************
   */
  S5RetCode (*Filtering)(	char *s,
				struct _SS5ProxyData *pd );

  /*
   * Module Bandwidth
   * Main function pointer
   * *******************************************************************************************************************************************
   */
  S5RetCode (*Bandwidth)( 	struct timeval tv,
				struct _SS5ProxyData *pd,
				struct _SS5Facilities *fa  );

  /*
   * Module Log
   * Main function pointer
   * *******************************************************************************************************************************************
   */
  S5RetCode (*Logging)		( 	char *s5logstring );

  /*
   * Module Statistics
   * Main function pointer
   * *******************************************************************************************************************************************
   */
  S5RetCode (*Statistics)( 	struct _SS5ClientInfo *ci,
				struct _SS5Socks5Data *sd );

  S5RetCode (*Summary)(  	unsigned int autheerr,
				unsigned int authoerr,
				unsigned int cmderr );
};


struct _SS5Modules {

  void *mod_socks5_handle;
  struct _module mod_socks5;
  unsigned int mod_socks5_loaded;

  void *mod_socks4_handle;
  struct _module mod_socks4;
  unsigned int  mod_socks4_loaded;

  void *mod_authentication_handle;
  struct _module mod_authentication;
  unsigned int mod_authentication_loaded;

  void *mod_authorization_handle;
  struct _module mod_authorization;
  unsigned int mod_authorization_loaded;

  void *mod_balancing_handle;
  struct _module mod_balancing;
  unsigned int mod_balancing_loaded;

  void *mod_proxy_handle;
  struct _module mod_proxy;
  unsigned int mod_proxy_loaded;

  void *mod_filter_handle;
  struct _module mod_filter;
  unsigned int mod_filter_loaded;

  void *mod_bandwidth_handle;
  struct _module mod_bandwidth;
  unsigned int mod_bandwidth_loaded;

  void *mod_logging_handle;
  struct _module mod_logging;
  unsigned int mod_logging_loaded;

  void *mod_statistics_handle;
  struct _module mod_statistics;
  unsigned int mod_statistics_loaded;

  void *mod_dump_handle;
  struct _module mod_dump;
  unsigned int mod_dump_loaded;

} SS5Modules;

#endif


syntax highlighted by Code2HTML, v. 0.9.1