1   /* Socks Server 5
2 * Copyright (C) 2002 - 2011 by Matteo Ricchetti - <matteo.ricchetti@libero.it>
3 
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17 */
18 
19 #ifndef SS5MAIN_H
20 #define SS5MAIN_H 1
21 
22 #include <pthread.h>
23 #include <pwd.h>
24 
25 #ifndef SOLARIS
26 #define _XOPEN_SOURCE
27 #endif
28 
29 #include <time.h>
30 #include <ctype.h>
31 #include <netdb.h>
32 #include <fcntl.h>
33 #include <stdio.h>
34 #include <signal.h>
35 #include <syslog.h>
36 #include <string.h>
37 #include <netinet/in.h>
38 
39 #undef __FD_SETSIZE
40 #define __FD_SETSIZE 8192
41 
42 #include <sys/select.h>
43 
44 #include <sys/socket.h>
45 #include <sys/time.h>
46 #include <sys/types.h>
47 #include <sys/wait.h>
48 #include <sys/stat.h>
49 #include <sys/ioctl.h>
50 #include <arpa/inet.h>
51 #include <stdlib.h>
52 #include <sched.h>
53 #include <unistd.h>
54 #include <errno.h>
55 #include <dlfcn.h>
56 #include <grp.h>
57 #include <stdarg.h>
58 
59 #ifdef SS5_USE_GSSAPI
60 #include <gssapi/gssapi.h>
61 
62 #ifdef SOLARIS
63 #include <gssapi/gssapi_ext.h>
64 #else
65 #include <gssapi/gssapi_generic.h>
66 #endif
67 
68 #endif
69 
70 
71 #include "config.h"
72 
73 #ifdef LINUX
74 #include <linux/if.h>
75 #include <linux/if_ether.h>
76 #endif
77 
78 #ifdef SOLARIS
79 #include <net/if.h>
80 #include <sys/sockio.h>
81 #endif
82 
83 #ifdef FREEBSD
84 #include <sys/syslog.h>
85 #include <sys/param.h>
86 #include <net/if.h>
87 #include <net/if_dl.h>
88 #endif
89 
90 /*
91  * SS5 Title
92  */
93 #define SS5_VERSION        "SS5 Version 3.8.9 - Release 8"
94 #define SS5_COPYRIGHT      "Copyright (C) 2002-2013 by Matteo Ricchetti - <matteo.ricchetti@libero.it>"
95 
96 /*
97 * MACRO for epoll:
98 */
99 #ifdef EPOLL_IO
100 #include <sys/epoll.h>
101 #define IFEPOLL(x)	x
102 #define IFSELECT(x)
103 #else
104 #define IFSELECT(x)	x
105 #define IFEPOLL(x)
106 #endif
107 
108 /*
109 * MACRO for OS:
110 */
111 #ifdef LINUX
112 #define IFLINUX(x)	x
113 #define IFSOLARIS(x)
114 #else
115 #define IFSOLARIS(x)	x
116 #define IFLINUX(x)
117 #endif
118 
119 #ifdef LINUX
120 #define SS5_SEND_OPT           MSG_NOSIGNAL
121 #else
122 #define SS5_SEND_OPT           0
123 #endif
124 
125 /*
126 * MACRO for options:
127 */
128 #define THREADED()	 ( SS5SocksOpt.IsThreaded )
129 #define NOTTHREADED()	 ( !SS5SocksOpt.IsThreaded )
130 
131 #define SYSLOG()	 ( SS5SocksOpt.Syslog )
132 #define VERBOSE()	 ( SS5SocksOpt.Verbose )
133 #define GSSAPI()	 ( ci->GssEnc != GSS_NO_ENC )
134 #define GSSINTEGRITY()	 ( ci->GssEnc != GSS_ENC_NOINT )
135 #define DEBUG()		 ( SS5SocksOpt.Debug )
136 #define BALANCE()	 ( SS5SocksOpt.IsBalance )
137 #define CONSOLE()	 ( SS5SocksOpt.IsConsole )
138 #define SS5SRV()	 ( SS5SocksOpt.IsSrvmgr )
139 #define DUMP()		 ( SS5SocksOpt.IsDump )
140 #define FILTER()	 ( SS5Facilities.Fixup[0] != '-' )
141 #define DISFILTER()	   SS5Facilities.Fixup[0] = '-';
142 #define ROUTE()		 ( SS5SocksOpt.IsRoute )
143 #define UPSTREAM()	 ( SS5SocksOpt.IsUpstream )
144 #define BANDWIDTH()	 ( SS5Facilities.Bandwidth )
145 #define BANDWIDTHXUSER() ( SS5Facilities.BandwidthXUser )
146 #define STIMEXUSER()     ( SS5Facilities.STimeXUser )
147 
148 #define AUTHENFILE()      ( SS5SocksOpt.Authentication == FILE_AUTHENTICATION )
149 #define AUTHENEAP()       ( SS5SocksOpt.Authentication == EAP_AUTHENTICATION )
150 #define AUTHENPAM()       ( SS5SocksOpt.Authentication == PAM_AUTHENTICATION )
151 #define AUTHENRADIUS()    ( SS5SocksOpt.Authentication == RADIUS_AUTHENTICATION )
152 #define LDAPBASE() 	  ( SS5SocksOpt.LdapCriteria   == LDAP_BASE )
153 #define LDAPFILTER() 	  ( SS5SocksOpt.LdapCriteria   == LDAP_FILTER )
154 #define AUTHORFILE()      ( SS5SocksOpt.Profiling      == FILE_PROFILING )
155 #define AUTHORDIRECTORY() ( SS5SocksOpt.Profiling      == LDAP_PROFILING )
156 #define ISSOCKS4()	  ( SS5ClientInfo.Ver          == SOCKS4_VERSION )
157 #define ISSOCKS5()	  ( SS5ClientInfo.Ver          == SOCKS5_VERSION )
158 #define NOTMUTE()	  ( SS5SocksOpt.Mute           == ERR )
159 
160 #define STREQ(x,y,z)	  !strncmp(x,y,z)
161 #define STRCASEEQ(x,y,z)  !strncasecmp(x,y,z)
162 
163 /*
164 * MACRO for modules:
165 */
166 #define MODBALANCING()  ( SS5Modules.mod_balancing_loaded  )
167 #define MODSTATISTICS() ( SS5Modules.mod_statistics_loaded )
168 #define MODBANDWIDTH()  ( SS5Modules.mod_bandwidth_loaded  )
169 #define MODDUMP()       ( SS5Modules.mod_dump_loaded       )
170 #define MODFILTER()     ( SS5Modules.mod_filter_loaded     )
171 #define MODSOCKS4()     ( SS5Modules.mod_socks4_loaded     )
172 #define NOTMODSOCKS4()  ( !SS5Modules.mod_socks4_loaded    )
173 
174 #define LOGUPDATE()	SS5Modules.mod_logging.Logging(logString);
175 
176 /*
177 * MACRO for general purpose:
178 */
179 #define LOCKMUTEXCS()    pthread_mutex_lock  ( &CSMutex  );
180 #define UNLOCKMUTEXCS()  pthread_mutex_unlock( &CSMutex  );
181 #define LOCKMUTEXCA()    pthread_mutex_lock  ( &CAMutex  );
182 #define UNLOCKMUTEXCA()  pthread_mutex_unlock( &CAMutex  );
183 #define LOCKMUTEXCT()    pthread_mutex_lock  ( &CTMutex  );
184 #define UNLOCKMUTEXCT()  pthread_mutex_unlock( &CTMutex  );
185 #define LOCKMUTEXCO()    pthread_mutex_lock  ( &COMutex  );
186 #define UNLOCKMUTEXCO()  pthread_mutex_unlock( &COMutex  );
187 #define LOCKMUTEXPAM()   pthread_mutex_lock  ( &PAMMutex );
188 #define UNLOCKMUTEXPAM() pthread_mutex_unlock( &PAMMutex );
189 #define LOCKMUTEXBT()    pthread_mutex_lock  ( &BTMutex  );
190 #define UNLOCKMUTEXBT()  pthread_mutex_unlock( &BTMutex  );
191 #define LOCKMUTEXAC()    pthread_mutex_lock  ( &ACMutex  );
192 #define UNLOCKMUTEXAC()  pthread_mutex_unlock( &ACMutex  );
193 #define LOCKMUTEXAEC()    pthread_mutex_lock  ( &AECMutex  );
194 #define UNLOCKMUTEXAEC()  pthread_mutex_unlock( &AECMutex  );
195 
196 #define STRSCAT(d,s)   d[sizeof(d)-1]='\0';l=strlen(d);for( i=0; i< (sizeof(d)-l-1) && s[i] != '\0'; i++){ d[l+i] = s[i];}; d[l+i] = '\0';
197 
198 #define GETADDR(x,y,z)   y=0; for(i=0;i<4;i++) { y += ((ULINT)x[3-i+z] << (i*8)); };
199 #define GETPORT(x,y,z)   y=0; for(i=0;i<2;i++) { y += ((ULINT)x[2-i+z] << (i*8)); };
200 
201 #define SETPORT(x,y,z)   for(i=0;i<2;i++) { x[i+z]=  (y & (0x00FF << (i*8))) >> (i*8); };
202 #define SETADDR(x,y,z)   for(i=0;i<4;i++) { x[i+z]=  (y & (0x000000FF << (i*8))) >> (i*8); };
203 #define SETADDR_R(x,y,z) for(i=0;i<4;i++) { x[3-i+z]=(y & (0x000000FF << (i*8))) >> (i*8); };
204 #define SETPORT_R(x,y,z) for(i=0;i<2;i++) { x[1-i+z]=(y & (0x00FF << (i*8))) >> (i*8); };
205 
206 #ifdef LINUX
207 #define ERRNO(p)        { char s[128]; strerror_r(errno,s,sizeof(s)); snprintf(logString,        \
208                           sizeof(logString) - 1,"[%u] [ERRO] $%s$: (%s).",p,__func__,s); LOGUPDATE() }
209 #else
210 #define ERRNO(p)        { snprintf(logString,sizeof(logString) - 1,"[%u] [ERRO] $%s$: (%s)."     \
211                           ,p,__func__,strerror(errno)); LOGUPDATE() }
212 #endif
213 
214 #define ERRNOPAM(p,h,e) { snprintf(logString,sizeof(logString) - 1,"[%u] [ERRO] $%s$: (%s).",    \
215                           p,__func__,pam_strerror( h, e)); LOGUPDATE() }
216 
217 #define ERRNOLDAP(p,r)  { snprintf(logString,sizeof(logString) - 1,"[%u] [ERRO] $%s$: (%s).",    \
218                           p,__func__,ldap_err2string(r)); LOGUPDATE() }
219 
220 /*
221 * Socks RFC definitions:
222 * ------------------------------------------------------------------------------------
223 *
224 */
225 
226 enum VER_SS5       { SOCKS4_VERSION = 4,
227 	             SOCKS5_VERSION = 5 };
228 
229 enum METHOD_SS5    { NOAUTH     = 0,
230 	     	     GSSAPI     = 1,
231 	     	     USRPWD     = 2,
232 	     	     S_USER_PWD = 0x21,          /* RFC by Raffaele De Lorenzo (raffaele.delorenzo@libero.it) */
233 	     	     FAKEPWD    = 254,
234 	     	     NOMETHOD   = 255 };
235 
236 enum COMMAND_SS5   { CONNECT       = 1,
237 	             BIND          = 2,
238 	             UDP_ASSOCIATE = 3 };
239 
240 enum ADDRTYPE_SS5  { IPV4   = 1,
241 	             DOMAIN = 3,
242 	             IPV6   = 4 };
243 
244 /*
245 * SS5 DEFININITION
246 * ------------------------------------------------------------------------------------
247 *
248 */
249 
250 #define DISPLAY			0
251 #define CFGFILE			1
252 
253 #define ONLINE                  0
254 #define OFFLINE                 1
255 
256 #define CONTINUE                0
257 #define EXIT                    1
258 #define THREAD_EXIT             0
259 
260 #define LOAD_CONFIG             2
261 #define RELOAD_CONFIG           1
262 #define PARSE_CONFIG            0
263 
264 #define MASTER			1
265 #define SLAVE			2
266 #define ALONE			3
267 
268 #define SRC_ROUTE		0
269 #define DST_ROUTE		1
270 
271 #define SRC_DUMP		0
272 #define DST_DUMP		1
273 
274 #define SOCKS5_PORT             1080    /* Default socks port */
275 #define DATABUF                 1460    /* MTU - (header IP + header TCP) */
276 #define MAXIF                   2048    /* Max number of network interfaces */
277 #define MAXPREFORKPROCS         5000    /* Max number of preforked processes */
278 #define MAXPREFORKPROCLIFE      2048    /* Max number of requests a preforked process can servs */
279 #define MAXPEERS                  12    /* Max number of network interfaces */
280 #define MAXPPATHLEN      4096
281 
282 enum ERR_SS5 {
283   ERR_SRV_REQUEST = -1,
284   ERR = 0,
285   OK  = 1
286 };
287 
288 typedef short int SINT;
289 typedef int INT;
290 typedef unsigned int UINT;
291 typedef unsigned long int ULINT;
292 
293 struct _SS5ClientInfo{
294   UINT Ver;
295   UINT NMeth;
296   UINT NoAuth;
297   UINT BasicAuth;
298   UINT GssApiAuth;
299   UINT SecureBasicAuth;
300   UINT Method;
301 
302   int  Socket;
303   int  appSocket;
304   char SrcAddr[16];
305   UINT SrcPort;
306   UINT GssEnc;
307 
308   int udpSocket;
309   char udpSrcAddr[16];
310   UINT udpSrcPort;
311   UINT Stream;
312 
313   char Username[64];
314   char Password[64];
315 
316   char Request[1024];             /* Basic request packet  */
317   char Response[2];               /* Basic response packet */
318 
319 
320 #ifdef SS5_USE_GSSAPI
321   gss_ctx_id_t GssContext;
322 #endif
323 
324   /* Radius info */
325   struct sockaddr_in framedRoute;
326   unsigned char radiusTmp[16];
327   UINT sid;
328   ULINT sessionTime;
329   ULINT oPacket,iPacket;
330 };
331 
332 struct _SS5RequestInfo {
333   UINT Ver;
334   UINT Cmd;
335   UINT Rsv;
336   UINT ATyp;
337   char DstAddr[128];
338   UINT DstPort;
339 
340   UINT udpRsv;
341   UINT udpFrag;
342   UINT udpATyp;
343   char udpDstAddr[128];
344   UINT udpDstPort;
345 
346   ULINT upDstAddr;
347   UINT upDstPort;
348   UINT upSocksVer;
349 };
350 
351 struct _SS5DumpInfo {
352   UINT DumpDir;
353   UINT DumpMode;
354 };
355 
356 struct _SS5ParseConfFile {
357   char srcAddr[64];      /* Source address buffer         */
358   char srcPort[16];      /* Source port buffer            */
359   char dstAddr[128];      /* Destination address buffer    */
360   char dstPort[16];      /* Destination port buffer       */
361   char socksMeth[4];     /* Socks method buffer           */
362   char fixup[16];        /* Fixup buffer                  */
363   char user[256];        /* User name buffer              */
364   char group[256];       /* Group name buffer             */
365   char groupPath[256];   /* Grouppath name buffer         */
366   char bandwidth[16];    /* Bandwidth buffer              */
367   char lCon[6];          /* N connections buffer          */
368   char expDate[10];      /* Expiration date buffer        */
369   char pxyAddr[16];      /* Upstream proxy address buffer */
370   char pxyPort[6];       /* Upstream proxy port buffer    */
371   char upSocksV[1];      /* Upstream socks version buffer */
372   char dumpDir[3];       /*                               */
373   char dumpDct[1];       /*                               */
374   char real[16];         /* Real server address buffer    */
375   char vid[6];           /* Virtual identifier buffer     */
376   char srcIf[16];        /* Source interface buffer       */
377   char routeDir[1];      /* Route direction buffer        */
378   char slogFacil[32];    /* Syslog facility and level     */
379   char sessTimeout[16];  /* Per user session timeout      */
380 };
381 
382 struct _SS5Facilities {
383   char Fixup[16];                    /* Fixup               */
384   char Group[256];                   /* User groups         */
385   ULINT Bandwidth;       /* Bandwidth           */
386   ULINT BandwidthXUser;  /* Bandwidth per user  */
387   ULINT STimeXUser;      /* Bandwidth per user  */
388   char ExpDate[10];                  /* Acl expiration date */
389 };
390 
391 
392 /*
393  * SS5GLOBAL variables
394  * ------------------------------------------------------------------------------------
395  *
396  */
397 
398 int S5SocksSocket;
399 
400 struct sockaddr_in S5SocksSsin;
401 
402 FILE *S5ConfFile;
403 
404 FILE *S5PeerFile;
405 
406 FILE *S5PidFile;                  /* Pid file handle */
407 
408 char S5PidFileName[MAXPPATHLEN]; /* Path to pid file */
409 char S5ConfigFile[128];
410 char S5PeersFile[128];
411 char S5PasswordFile[128];
412 char S5LibPath[128];
413 char S5TracePath[128];
414 char S5ProfilePath[128];
415 char S5LoggingFile[128];
416 char S5RepKey[16];
417 
418 pthread_mutex_t COMutex;
419 
420 struct _SS5Peer {
421   char IP[16];
422 } SS5Peer[MAXPEERS];
423 
424 UINT NPeers;
425 
426 struct _S5Interface {
427   char IP[16];
428   char NetMask[16];
429 } *S5Interface[MAXIF];
430 
431 UINT NInterF;
432 
433 struct _SS5SocksOpt {
434   char GssPrincipal[64];                 /* Gss principal name */
435   unsigned char SupaKey[32];             /* SUPA Secret Key */
436   unsigned char ICacheServer[32];        /* Internet cache server for ICP feature */
437   int SyslogFa;                          /* Syslog facility */
438   int SyslogLe;                          /* Syslog level */
439   UINT DnsOrder;                 /* Dns ordering */
440   UINT Verbose;                  /* verbose mode */
441   UINT Debug;                    /* Debug mode */
442   UINT Syslog;                   /* Log to syslog */
443   UINT Mute;                     /* No logging */
444   UINT Profiling;                /* Set profiling type */
445   UINT LdapCriteria;             /* Set Ldap criteria */
446   UINT LdapTimeout;              /* Ldap search operation timeout */
447   UINT LdapNetbiosDomain;        /* Ldap netbios compatibility */
448   UINT AuthCacheAge;             /* Authentication cache age */
449   UINT AuthoCacheAge;            /* Authorization cache age */
450   UINT StickyAge;                /* Affinity age */
451   UINT Sticky;                   /* Affinity feature */
452   UINT Authentication;           /* Set authentication type */
453   UINT AcceptTimeout;            /* Accept idle timeout */
454   UINT IsThreaded;               /* Threaded mode */
455   UINT IsBalance;                /* At least a balance line */
456   UINT IsUpstream;               /* At least an upstream line */
457   UINT IsRoute;                  /* At least a route line */
458   UINT IsDump;                   /* At least a dump line */
459   UINT IsBandwidth;              /* At least a bandwidth line */
460   UINT IsGlobalBandwidth;        /* At least a bandwidth line with a dash as group name */
461   UINT IsConsole;                /* Web console enable */
462   UINT IsSrvmgr;                 /* Server manager enable */
463   UINT Role;                     /* Role of ss5 istance  */
464   UINT PreforkProcesses;
465   UINT PreforkProcessLife;
466   UINT RadInterimTimeout;        /* */
467   ULINT PropagateKey;        /* Key for config propagation  */
468   ULINT SessionIdleTimeout;  /* Session idle timeout */
469   ULINT RadIntUpdInterval;   /* Radius Interim update interval */
470   ULINT RadSessionTimeout;
471   ULINT RadSessionIdleTimeout;
472 } SS5SocksOpt;
473 
474 
475 
476 /*
477  * SOCKS5 module
478  * ------------------------------------------------------------------------------------
479  *
480  */
481 
482 #define MAXMETHODLIST	997     /* Max auth loadable */
483 #define MAXROUTELIST	997     /* Max route acl loadable */
484 #define MAXPROXYLIST	997     /* Max proxy list loadable */
485 #define MAXBANDLIST	9997    /* Max band list loadable */
486 #define MAXDNS_RESOLV	30      /* Max hosts resolved */
487 
488 struct _SS5Socks5Data {
489   /* Socks server V5 - Method - */
490   char MethodRequest[512];
491   char MethodResponse[2];
492   int  MethodBytesSent;
493   int  MethodBytesReceived;
494   /* Socks server V5 - Tcp request - */
495   char TcpRequest[256];
496   int  TcpRBytesSent;
497   int  TcpRBytesReceived;
498   /* Socks server V5 - Udp request - */
499   char UdpRequest[DATABUF];
500   int  UdpRBytesSent;
501   int  UdpRBytesReceived;
502   /* Socks server V5 - Response - */
503   char Response[256];
504 };
505 
506 /*
507  * SS5: Auth line parameters
508  */
509 struct _S5MethodNode {
510   UINT Mask;
511   ULINT SrcAddr;
512   ULINT  SrcPort;
513   UINT SrcRangeMin;
514   UINT SrcRangeMax;
515   UINT Method;
516   UINT Method2;
517 struct _S5MethodNode *next;
518 };
519 
520 struct  _S5MethodNode **S5MethodList,
521 	              **_tmp_S5MethodList,
522 	              **_old_S5MethodList;
523 
524 /*
525  * SS5: Route line parameters
526  */
527 struct _S5RouteNode {
528   UINT Mask;
529   ULINT SrcAddr;     /* Source address               */
530   ULINT SrcIf;       /* Source interface             */
531   char Group[64];                /* Source user group            */
532   UINT sd;               /* Source or destination route? */
533   struct _S5RouteNode *next;
534 };
535 
536 struct _S5RouteNode **S5RouteList,
537 	            **_tmp_S5RouteList,
538 	            **_old_S5RouteList;
539 
540 /*
541  * SS5: Upstream socks line parameters
542  */
543 struct _S5ProxyNode {
544   UINT Mask;
545   UINT Type;
546   ULINT DstAddr;    /* Destination ip */
547   ULINT DstPort;    /* Destination port */
548   UINT DstRangeMax;     /* Destination port */
549   UINT DstRangeMin;     /* Destination port */
550   ULINT ProxyAddr;  /* Proxy IP */
551   UINT ProxyPort;	      /* Proxy port */
552   UINT SocksVer;	      /* Socks Ver */
553 struct _S5ProxyNode *next;
554 };
555 
556 struct  _S5ProxyNode **S5ProxyList,
557                      **_tmp_S5ProxyList,
558                      **_old_S5ProxyList;
559 
560 /*
561  * SS5: Dns response buffer
562  */
563 struct _S5HostList {
564   char NextHost[16];
565 };
566 
567 
568 /*
569  * AUTHENTICATION module
570  * ------------------------------------------------------------------------------------
571  *
572  */
573 
574 #define MAXAUTHCACHELIST        9997    /* Max authentication cache entries */
575 
576 /*
577  * SS5: Authentication Cache line parameters
578  */
579 struct _S5AuthCacheNode {
580   char Usr[64];
581   char Pwd[64];
582   time_t ttl;
583   struct _S5AuthCacheNode *next;
584 };
585 
586 struct  _S5AuthCacheNode *S5AuthCacheList[MAXAUTHCACHELIST];
587 
588 struct _SS5SupaData {
589   char NegReq[256];              /* Initial negotiation packet */
590   char NegResp[256];
591   char KeyExReq[4096];           /* Key Exchange               */
592   char KeyExResp[1024];
593   char AuthReq[1024];            /* Authentication request     */
594 };
595 
596 
597 /*
598  * AUTHORIZATION module
599  * ------------------------------------------------------------------------------------
600  *
601  */
602 
603 #define MAXLDAPSTORE              20
604 #define MAXMYSQLSTORE             20
605 #define MAXACLLIST              9997    /* Max acl loadable */
606 #define MAXAUTHOCACHELIST       9997    /* Max authorization cache entries */
607 
608 /*
609  * SS5: Permit line parameters
610  */
611 struct _S5AclNode {
612   UINT Method;
613   UINT Method2;
614   UINT Type;
615   ULINT SrcAddr;
616   char SrcAddrFqdn[128];
617   UINT SrcMask;
618   ULINT SrcPort;
619   UINT SrcRangeMin;
620   UINT SrcRangeMax;
621   ULINT DstAddr;
622   char DstAddrFqdn[128];
623   UINT DstMask;
624   ULINT DstPort;
625   UINT DstRangeMin;
626   UINT DstRangeMax;
627   char Fixup[16];
628   char Group[256];
629   ULINT Bandwidth;
630   char ExpDate[10];
631   struct _S5AclNode *next;
632   };
633 
634 struct  _S5AclNode **S5AclList,
635 	           **_tmp_S5AclList,
636 	           **_old_S5AclList;
637 
638 /*
639  * SS5: Authorization Cache line parameters
640  */
641 struct _S5AuthoCacheNode {
642   char Sa[64];
643   UINT  Sp;
644   char Da[64];
645   UINT  Dp;
646   char Us[64];
647   struct _SS5Facilities Fa;
648   time_t ttl;
649   UINT Flg;
650   struct _S5AuthoCacheNode *next;
651 };
652 
653 struct  _S5AuthoCacheNode *S5AuthoCacheList[MAXAUTHOCACHELIST];
654 
655 /*
656  * PROXY  module
657  * ------------------------------------------------------------------------------------
658  *
659  */
660 
661 #define RECVERR                        -1
662 #define SENDERR                        -1
663 
664 struct _SS5ProxyData {
665   char *Recv;
666   char *Send;
667   int BufSize;
668   int TcpRBufLen;
669   int TcpSBufLen;
670   char *UdpRecv;
671   char *UdpSend;
672   int UdpBufSize;
673   int UdpRBufLen;
674   int UdpSBufLen;
675   UINT Fd;
676 };
677 
678 
679 /*
680  * BALANCE  module
681  * ------------------------------------------------------------------------------------
682  *
683  */
684 
685 #define TCB_REQUEST	1
686 #define STAT_REQUEST	2
687 #define STICKY_REQUEST	3
688 #define STICKY_AGE	3600    /* TTL in seconds for sticky feature */
689 #define MAX_ENTRY_REAL	256     /* Max number of real servers */
690 #define MAXSTICKYLIST	997
691 
692 struct _S5ConnectionEntry {
693   char Real[16];
694   UINT Vid;
695   UINT Connection;
696 };
697 
698 struct _S5ConnectionTable {
699   struct _S5ConnectionEntry **S5ConnectionEntry,
700                             **_tmp_S5ConnectionEntry,
701                             **_old_S5ConnectionEntry;
702 } S5ConnectionTable;
703 
704 UINT NReal,
705        _tmp_NReal;
706 
707 
708 struct _S5StickyNode {
709   ULINT srcip;
710   ULINT dstip;
711   UINT vid;
712   time_t ttl;
713   struct _S5StickyNode *next;
714 };
715 
716 struct _S5StickyNode *S5StickyList[MAXSTICKYLIST];
717 
718 pthread_mutex_t CTMutex;
719 pthread_mutex_t CAMutex;
720 
721 
722 /*
723  * STATISTICS  module
724  * ------------------------------------------------------------------------------------
725  *
726  */
727 
728 #define STAT_REQUEST	2
729 
730 enum STATCODE {
731   AFN=	1,
732   AFF=	101,
733   AEN=	2,
734   AEF=	102,
735   APN=	3,
736   APF=	103,
737   HFN=	4,
738   HFF=	104,
739   HLN=	5,
740   HLF=	105,
741   V4CN=	6,
742   V4CF=	106,
743   V4BN=	7,
744   V4BF=	107,
745   V5CN=	8,
746   V5CF=	108,
747   V5BN=	9,
748   V5BF=	109,
749   V5UN=	10,
750   V5UF=	110,
751   NONE=	0
752 };
753 
754 struct _SS5Statistics {
755   ULINT V5Total_Connect,V4Total_Connect;
756   ULINT V5Normal_Connect,V4Normal_Connect;
757   ULINT V5Failed_Connect,V4Failed_Connect;
758 
759   ULINT V5Current_Connect,V4Current_Connect;
760 
761   ULINT V5Total_Bind,V4Total_Bind;
762   ULINT V5Normal_Bind,V4Normal_Bind;
763   ULINT V5Failed_Bind,V4Failed_Bind;
764 
765   ULINT V5Current_Bind,V4Current_Bind;
766 
767   ULINT V5Total_Udp;
768   ULINT V5Normal_Udp;
769   ULINT V5Failed_Udp;
770 
771   ULINT V5Current_Udp;
772 
773   ULINT Total_Auth_File;
774   ULINT Total_Auth_EAP;
775   ULINT Total_Auth_PAM;
776   ULINT Normal_Auth_File;
777   ULINT Normal_Auth_EAP;
778   ULINT Normal_Auth_PAM;
779   ULINT Failed_Auth_File;
780   ULINT Failed_Auth_EAP;
781   ULINT Failed_Auth_PAM;
782 
783   ULINT Current_Auth_File;
784   ULINT Current_Auth_EAP;
785   ULINT Current_Auth_PAM;
786 
787   ULINT Total_Author_File;
788   ULINT Total_Author_Ldap;
789   ULINT Normal_Author_File;
790   ULINT Normal_Author_Ldap;
791   ULINT Failed_Author_File;
792   ULINT Failed_Author_Ldap;
793 
794   ULINT Current_Author_File;
795   ULINT Current_Author_Ldap;
796 
797 } SS5Statistics;
798 
799 pthread_mutex_t CSMutex;
800 
801 /*
802  * LOGS  module
803  * ------------------------------------------------------------------------------------
804  *
805  */
806 
807 FILE *S5LogFile;        /* Log file pointer */
808 
809 /*
810  * BANDWIDTH  module
811  * ------------------------------------------------------------------------------------
812  *
813  */
814 
815 #define MIN_BANDWIDTH           256     /* Bytes per second */
816 
817 enum ERR_BANDWIDTH {
818      ERR_LIMITFOUND= -1
819 };
820 
821 struct _S5BandTableNode {
822   char Usr[64];
823   int  NCon;
824   int  LNCon;
825   ULINT LBand;
826   ULINT STime;
827   struct _S5BandTableNode *next;
828 };
829 
830 struct _S5GlobalBandwidth {
831   ULINT BandW;
832   UINT LCon;
833 } S5GlobalBandwidth;
834 
835 struct  _S5BandTableNode **S5BandTableList,
836                          **_tmp_S5BandTableList,
837                          **_old_S5BandTableList;
838 
839 UINT     NBandwidthList,
840             _tmp_NBandwidthList;
841 
842 pthread_mutex_t BTMutex;
843 
844 
845 /*
846  * DUMP  module
847  * ------------------------------------------------------------------------------------
848  *
849  */
850 
851 /*
852  * SS5: dump line parameters
853  */
854 struct _S5DumpNode {
855   UINT Mask;
856   ULINT DstAddr;
857   ULINT DstPort;
858   UINT DstRangeMax;
859   UINT DstRangeMin;
860   UINT DumpDir;
861   UINT DumpMode;
862   struct _S5DumpNode *next;
863 };
864 
865 struct  _S5DumpNode **S5DumpList,
866                     **_tmp_S5DumpList,
867                     **_old_S5DumpList;
868 
869 
870 /*
871  * MODULE FUNCTION POINTERS
872  * ------------------------------------------------------------------------------------
873  *
874  */
875 struct _module {
876 
877 
878   /* Module Authentication VISIBLE functions */
879   UINT (*Authentication)(    struct _SS5ClientInfo *ci );
880 
881   INT (*SrvAuthentication)( struct _SS5ClientInfo *ci, struct _SS5Socks5Data *sd );
882 
883   /* HIDDEN */
884   UINT (*FreeAuthCache)( struct _S5AuthCacheNode **node );
885 
886 
887   /* Module Socks5 VISIBLE functions */
888   UINT (*MethodParsing)( struct _SS5ClientInfo *ci, struct _SS5Socks5Data *sd );
889 
890   UINT (*RequestParsing)( struct _SS5ClientInfo *ci, struct _SS5Socks5Data *sd,  struct _SS5RequestInfo *ri );
891 
892   UINT (*UpstreamServing)( struct _SS5ClientInfo *ci, struct _SS5RequestInfo *ri, struct _SS5Socks5Data *sd);
893 
894   UINT (*ConnectServing)( struct _SS5ClientInfo *ci, struct _SS5RequestInfo *ri, struct _SS5Socks5Data *sd);
895 
896   UINT (*BindServing)( struct _SS5ClientInfo *ci, struct _SS5RequestInfo *ri, struct _SS5Socks5Data *sd);
897 
898   UINT (*UdpAssociateServing)( struct _SS5ClientInfo *ci, struct _SS5RequestInfo *ri, struct _SS5Socks5Data *sd, struct _SS5ProxyData *pd);
899 
900   UINT (*UdpAssociateResponse)( struct _SS5ClientInfo *ci,struct _SS5RequestInfo *ri, struct _SS5Socks5Data *sd, struct _SS5ProxyData *pd);
901 
902   INT (*SrvSocks5)( struct _SS5ClientInfo *ci,struct _SS5Socks5Data *sd );
903 
904   /* HIDDEN */
905   UINT (*AddMethod)(UINT ctx, ULINT sa, ULINT sp, UINT me, UINT me2,UINT mask);
906 
907   UINT (*FreeMethod)( struct _S5MethodNode **node );
908 
909   unsigned char (*GetMethod)( struct _SS5ClientInfo *ci);
910 
911   UINT (*AddRoute)(UINT ctx, ULINT sa, ULINT si, char group[64], UINT mask, UINT sd );
912 
913   UINT (*FreeRoute)(	struct _S5RouteNode **node );
914 
915   ULINT (*GetRoute)( ULINT sa, ULINT da, char uname[64] );
916 
917   UINT (*AddProxy)(UINT ctx, UINT type, ULINT da, ULINT dp, ULINT pa,
918                                   UINT pp, UINT mask, UINT socksver );
919 
920   UINT (*FreeProxy)(	struct _S5ProxyNode **node );
921 
922   UINT (*GetProxy)( ULINT da, UINT dp, struct _SS5RequestInfo *ri);
923 
924 
925   /* Module Socks4 VISIBLE functions */
926   UINT (*V4RequestParsing)( struct _SS5ClientInfo *ci, struct _SS5Socks5Data *sd, struct _SS5RequestInfo *ri );
927 
928   UINT (*V4UpstreamServing)(	struct _SS5ClientInfo *ci, struct _SS5RequestInfo *ri, struct _SS5Socks5Data *sd);
929 
930   UINT (*V4ConnectServing)( struct _SS5ClientInfo *ci, struct _SS5RequestInfo *ri, struct _SS5Socks5Data *sd);
931 
932   UINT (*V4BindServing)( struct _SS5ClientInfo *ci, struct _SS5RequestInfo *ri, struct _SS5Socks5Data *sd);
933 
934   /* HIDDEN */
935   UINT (*V4AddRoute)( ULINT sa, ULINT si, char *group, UINT mask, UINT sd );
936 
937   UINT (*V4FreeRoute)( struct _S5RouteNode **node );
938 
939   ULINT (*V4GetRoute)( ULINT sa, ULINT da, char uname[64]);
940 
941 
942   /* Module Authorization VISIBLE functions */
943   UINT (*PreAuthorization)( struct _SS5ClientInfo *ci, struct _SS5RequestInfo *ri, struct _SS5Facilities *fa);
944 
945   UINT (*PostAuthorization)(	struct _SS5ClientInfo *ci, struct _SS5RequestInfo *ri, struct _SS5Facilities *fa);
946 
947   INT (*SrvAuthorization) ( struct _SS5ClientInfo *ci, struct _SS5Socks5Data *sd );
948 
949   UINT (*UpdateAuthoCache) ( char *sa, char *da, UINT dp, char *u, UINT f );
950 
951   /* HIDDEN */
952   UINT (*AddAcl)( UINT ctx, UINT type, ULINT sa, char sfqdn[64], ULINT sp, ULINT da, char dfqdn[64],
953                        ULINT dp, UINT srcmask, UINT dstmask, UINT method, UINT method2, struct _SS5Facilities *fa);
954 
955   INT (*GetAcl)( ULINT sa, UINT sp, ULINT da, UINT dp, struct _SS5Facilities *fa, UINT *me,  UINT *me2);
956 
957   UINT (*FreeAcl)( struct _S5AclNode **node );
958 
959   UINT (*FreeAuthoCache)( struct _S5AuthoCacheNode **node );
960 
961 
962   /* Module Balancing  VISIBLE functions */
963   UINT (*LoadBalancing)( struct _SS5ClientInfo *ci, struct _SS5RequestInfo *ri );
964   UINT (*Balancing)( struct _SS5ClientInfo *ci, struct _SS5Socks5Data *sd );
965   INT (*SrvBalancing)( struct _SS5ClientInfo *ci, struct _SS5Socks5Data *sd );
966 
967   /* HIDDEN */
968   UINT (*AddConn)( char *real );
969 
970   UINT (*RemoveConn)( char *real );
971 
972   UINT (*AddVip)( char *real, UINT vid, UINT index );
973 
974   UINT (*FreeConnectionTable)( struct _S5ConnectionEntry *ce );
975 
976   UINT (*FreeAffinity)( struct _S5StickyNode **node );
977 
978 
979   /* Module Proxy  VISIBLE functions */
980   INT (*ReceivingData)( struct _SS5ClientInfo *ci, struct _SS5ProxyData *pd,
981                                         #ifdef EPOLL_IO
982   					struct epoll_event *events );
983                                         #else
984   					fd_set *s5array );
985                                         #endif
986 
987   INT (*UdpReceivingData)( int t, int rSocket, struct _SS5RequestInfo *ri, struct _SS5ProxyData *pd, struct _SS5ClientInfo *ci );
988 
989   INT (*SendingData)( struct _SS5ClientInfo *ci, struct _SS5ProxyData *pd );
990 
991   INT (*UdpSendingData)( int t, int rSocket, struct _SS5RequestInfo *ri, struct _SS5ProxyData *pd, struct _SS5ClientInfo *ci );
992 
993 
994   /* Module Dump  VISIBLE functions */
995   UINT (*WritingDump)( FILE *df, struct _SS5ProxyData *pd, UINT dm );
996 
997   UINT (*OpenDump)( FILE **df, struct _SS5ClientInfo *ci );
998 
999   UINT (*CloseDump)(	FILE *df );
1000 
1001   UINT (*GetDump)( ULINT sa, UINT sp, ULINT da, UINT dp, struct _SS5DumpInfo *di );
1002 
1003   UINT (*AddDump)( UINT ctx, ULINT da, ULINT dp, UINT dc, UINT dm, UINT mask );
1004 
1005   UINT (*FreeDump)( struct _S5DumpNode **node );
1006 
1007   UINT (*ListDump)( UINT s);
1008 
1009   INT (*SrvDump)( struct _SS5ClientInfo *ci, struct _SS5Socks5Data *sd );
1010 
1011 
1012   /* Module Filter  VISIBLE functions */
1013   UINT (*Filtering)(	struct _SS5ClientInfo *ci, char *s, struct _SS5ProxyData *pd );
1014 
1015 
1016   /* Module Bandwidth  VISIBLE functions */
1017   UINT (*Bandwidth)( struct timeval tv, struct _SS5ProxyData *pd, struct _SS5Facilities *fa  );
1018 
1019   /* HIDDEN */
1020   UINT (*GetBandTableC)( char *u );
1021 
1022   UINT (*CheckBandTableC)( char *u );
1023 
1024   ULINT (*GetBandTableB)( char *u );
1025 
1026   ULINT (*GetBandTableS)( char *u );
1027 
1028   UINT (*UpdateBandTable)( char *u, int  n );
1029 
1030   UINT (*AddBandTable)( UINT ctx, char *u, int ln, ULINT lb, ULINT st );
1031 
1032   UINT (*TransfBandTable)( struct _S5BandTableNode *node );
1033 
1034   UINT (*FreeBandTable)( struct _S5BandTableNode **node );
1035 
1036   INT (*SrvBandwidth)( struct _SS5ClientInfo *ci, struct _SS5Socks5Data *sd );
1037 
1038 
1039   /* Module Log  VISIBLE functions */
1040   UINT (*Logging) ( char *s5logstring );
1041 
1042   /* HIDDEN */
1043   UINT (*Statistics)( struct _SS5ClientInfo *ci, struct _SS5Socks5Data *sd );
1044 
1045   UINT (*Summary)( UINT autheerr, UINT authoerr, UINT cmderr );
1046 
1047 };
1048 
1049 
1050 struct _SS5Modules {
1051 
1052   void *mod_socks5_handle;
1053   struct _module mod_socks5;
1054   UINT mod_socks5_loaded;
1055 
1056   void *mod_socks4_handle;
1057   struct _module mod_socks4;
1058   UINT  mod_socks4_loaded;
1059 
1060   void *mod_authentication_handle;
1061   struct _module mod_authentication;
1062   UINT mod_authentication_loaded;
1063 
1064   void *mod_authorization_handle;
1065   struct _module mod_authorization;
1066   UINT mod_authorization_loaded;
1067 
1068   void *mod_balancing_handle;
1069   struct _module mod_balancing;
1070   UINT mod_balancing_loaded;
1071 
1072   void *mod_proxy_handle;
1073   struct _module mod_proxy;
1074   UINT mod_proxy_loaded;
1075 
1076   void *mod_filter_handle;
1077   struct _module mod_filter;
1078   UINT mod_filter_loaded;
1079 
1080   void *mod_bandwidth_handle;
1081   struct _module mod_bandwidth;
1082   UINT mod_bandwidth_loaded;
1083 
1084   void *mod_logging_handle;
1085   struct _module mod_logging;
1086   UINT mod_logging_loaded;
1087 
1088   void *mod_statistics_handle;
1089   struct _module mod_statistics;
1090   UINT mod_statistics_loaded;
1091 
1092   void *mod_dump_handle;
1093   struct _module mod_dump;
1094   UINT mod_dump_loaded;
1095 
1096 } SS5Modules;
1097 
1098 #endif
1099