ZNC  trunk
Csocket.h
Go to the documentation of this file.
1 
33 /*
34  * NOTES ...
35  * - You should always compile with -Woverloaded-virtual to detect callbacks that may have been redefined since your last update
36  * - If you want to use gethostbyname instead of getaddrinfo, the use -DUSE_GETHOSTBYNAME when compiling
37  * - To compile with win32 need to link to winsock2, using gcc its -lws2_32
38  * - Code is formated with 'astyle --style=ansi -t4 --unpad-paren --pad-paren-in --keep-one-line-blocks'
39  */
40 #ifndef _HAS_CSOCKET_
41 #define _HAS_CSOCKET_
42 
43 #include "defines.h" // require this as a general rule, most projects have a defines.h or the like
44 
45 #include <stdio.h>
46 #include <fcntl.h>
47 
48 #ifndef _WIN32
49 
50 #include <unistd.h>
51 #include <sys/time.h>
52 #include <sys/file.h>
53 #include <netinet/in.h>
54 #include <arpa/inet.h>
55 #include <sys/socket.h>
56 #include <sys/ioctl.h>
57 #include <netdb.h>
58 #include <sys/select.h>
59 
60 #else
61 
62 #include <io.h>
63 #include <winsock2.h>
64 #include <ws2tcpip.h>
65 #include <time.h>
66 #include <sys/timeb.h>
67 
68 #ifdef _MSC_VER
69 #define strcasecmp _stricmp
70 #define suseconds_t long
71 #endif
72 
73 #ifndef ECONNREFUSED
74 // these aliases might or might not be defined in errno.h
75 // already, depending on the WinSDK version.
76 #define ECONNREFUSED WSAECONNREFUSED
77 #define EINPROGRESS WSAEINPROGRESS
78 #define ETIMEDOUT WSAETIMEDOUT
79 #define EADDRNOTAVAIL WSAEADDRNOTAVAIL
80 #define ECONNABORTED WSAECONNABORTED
81 #define ENETUNREACH WSAENETUNREACH
82 #endif /* ECONNREFUSED */
83 
84 #endif /* _WIN32 */
85 
86 #ifdef HAVE_C_ARES
87 #include <ares.h>
88 #endif /* HAVE_C_ARES */
89 
90 #ifdef HAVE_ICU
91 # include <unicode/ucnv.h>
92 #endif
93 
94 #include <stdlib.h>
95 #include <errno.h>
96 #include <string.h>
97 #include <ctype.h>
98 #include <assert.h>
99 
100 #ifdef HAVE_LIBSSL
101 #include <openssl/ssl.h>
102 #include <openssl/err.h>
103 #include <openssl/rand.h>
104 #endif /* HAVE_LIBSSL */
105 
106 #ifdef __sun
107 #include <strings.h>
108 #include <fcntl.h>
109 #endif /* __sun */
110 
111 #include <vector>
112 #include <list>
113 #include <iostream>
114 #include <sstream>
115 #include <string>
116 #include <set>
117 #include <map>
118 
119 #ifndef CS_STRING
120 # ifdef _HAS_CSTRING_
121 # define CS_STRING Cstring
122 # else
123 # define CS_STRING std::string
124 # endif /* _HAS_CSTRING_ */
125 #endif /* CS_STRING */
126 
127 #ifndef CS_DEBUG
128 #ifdef __DEBUG__
129 # define CS_DEBUG( f ) std::cerr << __FILE__ << ":" << __LINE__ << " " << f << std::endl
130 #else
131 # define CS_DEBUG(f) (void)0
132 #endif /* __DEBUG__ */
133 #endif /* CS_DEBUG */
134 
135 #ifndef CS_EXPORT
136 #define CS_EXPORT
137 #endif /* CS_EXPORT */
138 
139 #ifndef PERROR
140 #ifdef __DEBUG__
141 # define PERROR( f ) __Perror( f, __FILE__, __LINE__ )
142 #else
143 # define PERROR( f ) (void)0
144 #endif /* __DEBUG__ */
145 #endif /* PERROR */
146 
147 #ifdef _WIN32
148 typedef SOCKET cs_sock_t;
149 #ifdef _WIN64
150 typedef signed __int64 cs_ssize_t;
151 #else
152 typedef signed int cs_ssize_t;
153 #endif /* _WIN64 */
154 #define CS_INVALID_SOCK INVALID_SOCKET
155 #else
156 typedef int cs_sock_t;
157 typedef ssize_t cs_ssize_t;
158 #define CS_INVALID_SOCK -1
159 #endif /* _WIN32 */
160 
161 /* Assume that everything but windows has Unix sockets */
162 #ifndef _WIN32
163 #define HAVE_UNIX_SOCKET
164 #endif
165 
166 #ifdef CSOCK_USE_POLL
167 #include <poll.h>
168 #endif /* CSOCK_USE_POLL */
169 
170 #ifdef HAVE_UNIX_SOCKET
171 #include <sys/un.h>
172 #endif
173 
174 #ifndef _NO_CSOCKET_NS // some people may not want to use a namespace
175 namespace Csocket
176 {
177 #endif /* _NO_CSOCKET_NS */
178 
179 
185 {
186 public:
187  CSCharBuffer( size_t iSize )
188  {
189  m_pBuffer = ( char * )malloc( iSize );
190  }
192  {
193  free( m_pBuffer );
194  }
195  char * operator()() { return( m_pBuffer ); }
196 
197 private:
198  char * m_pBuffer;
199 };
200 
201 
207 {
208 public:
210  {
211  m_bIsIPv6 = false;
212  memset( ( struct sockaddr_in * ) &m_saddr, '\0', sizeof( m_saddr ) );
213 #ifdef HAVE_IPV6
214  memset( ( struct sockaddr_in6 * ) &m_saddr6, '\0', sizeof( m_saddr6 ) );
215 #endif /* HAVE_IPV6 */
216  m_iAFRequire = RAF_ANY;
217  }
218  virtual ~CSSockAddr() {}
219 
220 
222  {
223  RAF_ANY = PF_UNSPEC,
224 #ifdef HAVE_IPV6
225  RAF_INET6 = AF_INET6,
226 #endif /* HAVE_IPV6 */
227  RAF_INET = AF_INET
228  };
229 
230  void SinFamily();
231  void SinPort( uint16_t iPort );
232  void SetIPv6( bool b );
233  bool GetIPv6() const { return( m_bIsIPv6 ); }
234 
235  socklen_t GetSockAddrLen() { return( sizeof( m_saddr ) ); }
236  sockaddr_in * GetSockAddr() { return( &m_saddr ); }
237  in_addr * GetAddr() { return( &( m_saddr.sin_addr ) ); }
238 #ifdef HAVE_IPV6
239  socklen_t GetSockAddrLen6() { return( sizeof( m_saddr6 ) ); }
240  sockaddr_in6 * GetSockAddr6() { return( &m_saddr6 ); }
241  in6_addr * GetAddr6() { return( &( m_saddr6.sin6_addr ) ); }
242 #endif /* HAVE_IPV6 */
243 
244  void SetAFRequire( EAFRequire iWhich ) { m_iAFRequire = iWhich; }
245  EAFRequire GetAFRequire() const { return( m_iAFRequire ); }
246 
247 private:
248  bool m_bIsIPv6;
249  sockaddr_in m_saddr;
250 #ifdef HAVE_IPV6
251  sockaddr_in6 m_saddr6;
252 #endif /* HAVE_IPV6 */
253  EAFRequire m_iAFRequire;
254 };
255 
256 
257 class Csock;
258 
259 
275 {
276 public:
283  CGetAddrInfo( const CS_STRING & sHostname, Csock * pSock, CSSockAddr & csSockAddr );
285 
287  void Init();
289  int Process();
291  int Finish();
292 
293 private:
294  CS_STRING m_sHostname;
295  Csock * m_pSock;
296  CSSockAddr & m_csSockAddr;
297  struct addrinfo * m_pAddrRes;
298  struct addrinfo m_cHints;
299  int m_iRet;
300 };
301 
303 int CS_GetAddrInfo( const CS_STRING & sHostname, Csock * pSock, CSSockAddr & csSockAddr );
304 
311 
312 #ifdef HAVE_LIBSSL
314 Csock * GetCsockFromCTX( X509_STORE_CTX * pCTX );
315 #endif /* HAVE_LIBSSL */
316 
317 
318 const uint32_t CS_BLOCKSIZE = 4096;
319 template <class T> inline void CS_Delete( T * & p ) { if( p ) { delete p; p = NULL; } }
320 
321 #ifdef HAVE_LIBSSL
323 {
324  CT_NONE = 0,
325  CT_ZLIB = 1
326 };
327 
329 void CSAdjustTVTimeout( struct timeval & tv, long iTimeoutMS );
330 
331 void SSLErrors( const char *filename, uint32_t iLineNum );
332 
338 bool InitSSL( ECompType eCompressionType = CT_NONE );
339 
340 #endif /* HAVE_LIBSSL */
341 
345 bool InitCsocket();
350 
352 inline int GetSockError()
353 {
354 #ifdef _WIN32
355  return( WSAGetLastError() );
356 #else
357  return( errno );
358 #endif /* _WIN32 */
359 }
360 
362 inline void TFD_ZERO( fd_set *set )
363 {
364  FD_ZERO( set );
365 }
366 
367 inline void TFD_SET( cs_sock_t iSock, fd_set *set )
368 {
369  FD_SET( iSock, set );
370 }
371 
372 inline bool TFD_ISSET( cs_sock_t iSock, fd_set *set )
373 {
374  return( FD_ISSET( iSock, set ) != 0 );
375 }
376 
377 inline void TFD_CLR( cs_sock_t iSock, fd_set *set )
378 {
379  FD_CLR( iSock, set );
380 }
381 
382 void __Perror( const CS_STRING & s, const char * pszFile, uint32_t iLineNo );
383 
384 
393 {
394 public:
395  CCron();
396  virtual ~CCron() {}
397 
399  void run( timeval & tNow );
400 
405  void StartMaxCycles( double dTimeSequence, uint32_t iMaxCycles );
406  void StartMaxCycles( const timeval& tTimeSequence, uint32_t iMaxCycles );
407 
409  void Start( double dTimeSequence );
410  void Start( const timeval& TimeSequence );
411 
413  void Stop();
414 
416  void Pause();
417 
419  void UnPause();
420 
422  void Reset();
423 
424  timeval GetInterval() const;
425  uint32_t GetMaxCycles() const;
426  uint32_t GetCyclesLeft() const;
427 
429  bool isValid() const;
430 
431  const CS_STRING & GetName() const;
432  void SetName( const CS_STRING & sName );
433 
435  timeval GetNextRun() const { return( m_tTime ); }
436 
437 public:
438 
440  virtual void RunJob();
441 
442 protected:
444 
445 private:
446  timeval m_tTime;
447  bool m_bActive, m_bPause;
448  timeval m_tTimeSequence;
449  uint32_t m_iMaxCycles, m_iCycles;
450  CS_STRING m_sName;
451 };
452 
458 {
459 public:
460  CSMonitorFD() { m_bEnabled = true; }
461  virtual ~CSMonitorFD() {}
462 
469  virtual bool GatherFDsForSelect( std::map< cs_sock_t, short > & miiReadyFds, long & iTimeoutMS );
470 
476  virtual bool FDsThatTriggered( const std::map< cs_sock_t, short > & miiReadyFds ) { return( true ); }
477 
483  virtual bool CheckFDs( const std::map< cs_sock_t, short > & miiReadyFds );
484 
490  void Add( cs_sock_t iFD, short iMonitorEvents ) { m_miiMonitorFDs[iFD] = iMonitorEvents; }
492  void Remove( cs_sock_t iFD ) { m_miiMonitorFDs.erase( iFD ); }
494  void DisableMonitor() { m_bEnabled = false; }
495 
496  bool IsEnabled() const { return( m_bEnabled ); }
497 
498 protected:
499  std::map< cs_sock_t, short > m_miiMonitorFDs;
501 };
502 
503 
509 {
510 public:
512  virtual ~CSockCommon();
513 
514  void CleanupCrons();
516 
518  const std::vector<CCron *> & GetCrons() const { return( m_vcCrons ); }
520  virtual void Cron();
521 
523  virtual void AddCron( CCron * pcCron );
530  virtual void DelCron( const CS_STRING & sName, bool bDeleteAll = true, bool bCaseSensitive = true );
532  virtual void DelCron( uint32_t iPos );
534  virtual void DelCronByAddr( CCron * pcCron );
535 
536  void CheckFDs( const std::map< cs_sock_t, short > & miiReadyFds );
537  void AssignFDs( std::map< cs_sock_t, short > & miiReadyFds, struct timeval * tvtimeout );
538 
540  void MonitorFD( CSMonitorFD * pMonitorFD ) { m_vcMonitorFD.push_back( pMonitorFD ); }
541 
542 protected:
543  std::vector<CCron *> m_vcCrons;
544  std::vector<CSMonitorFD *> m_vcMonitorFD;
545 };
546 
547 
548 #ifdef HAVE_LIBSSL
549 typedef int ( *FPCertVerifyCB )( int, X509_STORE_CTX * );
550 #endif /* HAVE_LIBSSL */
551 
552 
564 {
565 public:
567  Csock( int iTimeout = 60 );
574  Csock( const CS_STRING & sHostname, uint16_t uPort, int itimeout = 60 );
575 
577  virtual Csock *GetSockObj( const CS_STRING & sHostname, uint16_t iPort );
578 
579  virtual ~Csock();
580 
587  virtual void Dereference();
589  virtual void Copy( const Csock & cCopy );
590 
591  enum ETConn
592  {
593  OUTBOUND = 0,
594  LISTENER = 1,
595  INBOUND = 2
596  };
597 
598  enum EFRead
599  {
600  READ_EOF = 0,
601  READ_ERR = -1,
602  READ_EAGAIN = -2,
603  READ_CONNREFUSED = -3,
604  READ_TIMEDOUT = -4
605  };
606 
607  enum EFSelect
608  {
609  SEL_OK = 0,
610  SEL_TIMEOUT = -1,
611  SEL_EAGAIN = -2,
612  SEL_ERR = -3
613  };
614 
616  {
617  TLS = 0,
618  SSL23 = TLS,
619  SSL2 = 2,
620  SSL3 = 3,
621  TLS1 = 4,
622  TLS11 = 5,
623  TLS12 = 6
624  };
625 
627  {
628  EDP_None = 0,
629  EDP_SSLv2 = 1,
630  EDP_SSLv3 = 2,
631  EDP_TLSv1 = 4,
632  EDP_TLSv1_1 = 8,
633  EDP_TLSv1_2 = 16,
634  EDP_SSL = (EDP_SSLv2|EDP_SSLv3)
635  };
636 
638  {
639  CST_START = 0,
640  CST_DNS = CST_START,
641  CST_BINDVHOST = 1,
642  CST_DESTDNS = 2,
643  CST_CONNECT = 3,
644  CST_CONNECTSSL = 4,
645  CST_OK = 5
646  };
647 
649  {
650  CLT_DONT = 0,
651  CLT_NOW = 1,
652  CLT_AFTERWRITE = 2,
653  CLT_DEREFERENCE = 3
654  };
655 
656  Csock & operator<<( const CS_STRING & s );
657  Csock & operator<<( std::ostream & ( *io )( std::ostream & ) );
658  Csock & operator<<( int32_t i );
659  Csock & operator<<( uint32_t i );
660  Csock & operator<<( int64_t i );
661  Csock & operator<<( uint64_t i );
662  Csock & operator<<( float i );
663  Csock & operator<<( double i );
664 
669  virtual bool Connect();
670 
671 #ifdef HAVE_UNIX_SOCKET
676  virtual bool ConnectUnix( const CS_STRING & sPath );
677 
684  virtual bool ListenUnix( const CS_STRING & sBindFile, int iMaxConns = SOMAXCONN, uint32_t iTimeout = 0 );
685 #endif
686 
695  virtual bool Listen( uint16_t iPort, int iMaxConns = SOMAXCONN, const CS_STRING & sBindHost = "", uint32_t iTimeout = 0, bool bDetach = false );
696 
698  virtual cs_sock_t Accept( CS_STRING & sHost, uint16_t & iRPort );
699 
701  virtual bool AcceptSSL();
702 
704  virtual bool SSLClientSetup();
705 
707  virtual bool SSLServerSetup();
708 
715  virtual bool ConnectSSL();
716 
718  bool StartTLS();
719 
730  virtual bool Write( const char *data, size_t len );
731 
740  virtual bool Write( const CS_STRING & sData );
741 
757  virtual cs_ssize_t Read( char *data, size_t len );
760 
762  virtual bool IsConnected() const;
764  virtual void SetIsConnected( bool b );
765 
768  const cs_sock_t & GetRSock() const;
769  void SetRSock( cs_sock_t iSock );
771  const cs_sock_t & GetWSock() const;
772  void SetWSock( cs_sock_t iSock );
773 
774  void SetSock( cs_sock_t iSock );
776  const cs_sock_t & GetSock() const;
777 
783  void CallSockError( int iErrno, const CS_STRING & sDescription = "" );
785  virtual void ResetTimer();
786 
788  void PauseRead();
789  void UnPauseRead();
790  bool IsReadPaused() const;
797  enum
798  {
799  TMO_READ = 1,
800  TMO_WRITE = 2,
801  TMO_ACCEPT = 4,
802  TMO_ALL = TMO_READ|TMO_WRITE|TMO_ACCEPT
803  };
804 
807  void SetTimeout( int iTimeout, uint32_t iTimeoutType = TMO_ALL );
808  void SetTimeoutType( uint32_t iTimeoutType );
809  int GetTimeout() const;
810  uint32_t GetTimeoutType() const;
811 
813  virtual bool CheckTimeout( time_t iNow );
814 
819  virtual void PushBuff( const char *data, size_t len, bool bStartAtZero = false );
820 
825 
829 
831  void SetMaxBufferThreshold( uint32_t iThreshold );
832  uint32_t GetMaxBufferThreshold() const;
833 
835  int GetType() const;
836  void SetType( int iType );
837 
839  const CS_STRING & GetSockName() const;
840  void SetSockName( const CS_STRING & sName );
841 
843  const CS_STRING & GetHostName() const;
844  void SetHostName( const CS_STRING & sHostname );
845 
846 
848  uint64_t GetStartTime() const;
851 
853  uint64_t GetBytesRead() const;
855 
857  uint64_t GetBytesWritten() const;
859 
861  double GetAvgRead( uint64_t iSample = 1000 ) const;
862 
864  double GetAvgWrite( uint64_t iSample = 1000 ) const;
865 
867  uint16_t GetRemotePort() const;
868 
870  uint16_t GetLocalPort() const;
871 
873  uint16_t GetPort() const;
874  void SetPort( uint16_t iPort );
875 
877  void Close( ECloseType eCloseType = CLT_NOW );
879  ECloseType GetCloseType() const { return( m_eCloseType ); }
880  bool IsClosed() const { return( GetCloseType() != CLT_DONT ); }
881 
884 
886  bool GetSSL() const;
887  void SetSSL( bool b );
888 
889 #ifdef HAVE_LIBSSL
891  void DisableSSLProtocols( u_int uDisableOpts ) { m_uDisableProtocols = uDisableOpts; }
893  void DisableSSLCompression() { m_bNoSSLCompression = true; }
895  void FollowSSLCipherServerPreference() { m_bSSLCipherServerPreference = true; }
897  void SetCipher( const CS_STRING & sCipher );
898  const CS_STRING & GetCipher() const;
899 
901  void SetDHParamLocation( const CS_STRING & sDHParamFile );
902  const CS_STRING & GetDHParamLocation() const;
903  void SetKeyLocation( const CS_STRING & sKeyFile );
904  const CS_STRING & GetKeyLocation() const;
905  void SetPemLocation( const CS_STRING & sPemFile );
906  const CS_STRING & GetPemLocation() const;
907  void SetPemPass( const CS_STRING & sPassword );
908  const CS_STRING & GetPemPass() const;
909 
911  void SetSSLMethod( int iMethod );
912  int GetSSLMethod() const;
913 
914  void SetSSLObject( SSL *ssl, bool bDeleteExisting = false );
915  SSL * GetSSLObject() const;
916  void SetCTXObject( SSL_CTX *sslCtx, bool bDeleteExisting = false );
917  SSL_SESSION * GetSSLSession() const;
918 
920  void SetCertVerifyCB( FPCertVerifyCB pFP ) { m_pCerVerifyCB = pFP; }
921 #endif /* HAVE_LIBSSL */
922 
924  bool HasWriteBuffer() const;
926 
929  bool SslIsEstablished() const;
930 
932  bool ConnectInetd( bool bIsSSL = false, const CS_STRING & sHostname = "" );
933 
935  bool ConnectFD( int iReadFD, int iWriteFD, const CS_STRING & sName, bool bIsSSL = false, ETConn eDirection = INBOUND );
936 
938 #ifdef HAVE_LIBSSL
940  X509 *GetX509() const;
941 
945  long GetPeerFingerprint( CS_STRING & sFP ) const;
946 
947  uint32_t GetRequireClientCertFlags() const;
949  void SetRequiresClientCert( bool bRequiresCert );
951  void SetRequireClientCertFlags( uint32_t iRequireClientCertFlags ) { m_iRequireClientCertFlags = iRequireClientCertFlags; }
952 #endif /* HAVE_LIBSSL */
953 
955  virtual void SetParentSockName( const CS_STRING & sParentName );
956  const CS_STRING & GetParentSockName() const;
957 
963  virtual void SetRate( uint32_t iBytes, uint64_t iMilliseconds );
964 
965  uint32_t GetRateBytes() const;
966  uint64_t GetRateTime() const;
967 
971  virtual void Connected() {}
975  virtual void Disconnected() {}
979  virtual void Timeout() {}
983  virtual void ReadData( const char *data, size_t len ) {}
988  virtual void ReadLine( const CS_STRING & sLine ) {}
993  bool HasReadLine() const { return( m_bEnableReadLine ); }
994 
1000  virtual void ReachedMaxBuffer();
1004  virtual void SockError( int iErrno, const CS_STRING & sDescription ) {}
1010  virtual bool ConnectionFrom( const CS_STRING & sHost, uint16_t iPort ) { return( true ); }
1011 
1017  virtual void Listening( const CS_STRING & sBindIP, uint16_t uPort ) {}
1018 
1023  virtual void ConnectionRefused() {}
1027  virtual void ReadPaused() {}
1028 
1029 #ifdef HAVE_LIBSSL
1034  virtual void SSLFinishSetup( SSL * pSSL ) {}
1042  virtual bool SNIConfigureServer( const CS_STRING & sHostname, CS_STRING & sPemFile, CS_STRING & sPemPass ) { return( false ); }
1048  virtual bool SNIConfigureClient( CS_STRING & sHostname );
1050  SSL_CTX * SetupServerCTX();
1051 
1065  virtual void SSLHandShakeFinished() {}
1077  virtual int VerifyPeerCertificate( int iPreVerify, X509_STORE_CTX * pStoreCTX ) { return( 1 ); }
1078 #endif /* HAVE_LIBSSL */
1079 
1080 
1082  time_t GetTimeSinceLastDataTransaction( time_t iNow = 0 ) const;
1083 
1084  time_t GetLastCheckTimeout() const { return( m_iLastCheckTimeoutTime ); }
1085 
1087  time_t GetNextCheckTimeout( time_t iNow = 0 ) const;
1088 
1090  virtual int GetPending() const;
1091 
1093  // Connection State Stuff
1095  ECONState GetConState() const { return( m_eConState ); }
1097  void SetConState( ECONState eState ) { m_eConState = eState; }
1098 
1101 
1104 
1105  const CS_STRING & GetBindHost() const { return( m_sBindHost ); }
1106  void SetBindHost( const CS_STRING & sBindHost ) { m_sBindHost = sBindHost; }
1107 
1109  {
1111  DNS_DEST
1112  };
1113 
1118  int DNSLookup( EDNSLType eDNSLType );
1119 
1121  bool SetupVHost();
1122 
1123  bool GetIPv6() const { return( m_bIsIPv6 ); }
1124  void SetIPv6( bool b )
1125  {
1126  m_bIsIPv6 = b;
1127  m_address.SetIPv6( b );
1128  m_bindhost.SetIPv6( b );
1129  }
1130 
1132  {
1133  m_address.SetAFRequire( iAFRequire );
1134  m_bindhost.SetAFRequire( iAFRequire );
1135  }
1136 
1138  bool AllowWrite( uint64_t & iNOW ) const;
1139 
1140 
1141  void SetSkipConnect( bool b ) { m_bSkipConnect = b; }
1142 
1149  virtual int GetAddrInfo( const CS_STRING & sHostname, CSSockAddr & csSockAddr );
1150 
1163  virtual int ConvertAddress( const struct sockaddr_storage * pAddr, socklen_t iAddrLen, CS_STRING & sIP, uint16_t * piPort ) const;
1164 
1165 #ifdef HAVE_C_ARES
1166  CSSockAddr * GetCurrentAddr() const { return( m_pCurrAddr ); }
1167  void SetAresFinished( int status ) { m_pCurrAddr = NULL; m_iARESStatus = status; }
1168  ares_channel GetAresChannel() const { return( m_pARESChannel ); }
1169 #endif /* HAVE_C_ARES */
1170 
1172  int GetMaxConns() const { return( m_iMaxConns ); }
1173 
1174 #ifdef HAVE_ICU
1175  void SetEncoding( const CS_STRING & sEncoding );
1176  CS_STRING GetEncoding() const { return m_sEncoding; }
1177  virtual void IcuExtToUCallback(
1178  UConverterToUnicodeArgs* toArgs,
1179  const char* codeUnits,
1180  int32_t length,
1181  UConverterCallbackReason reason,
1182  UErrorCode* err );
1183  virtual void IcuExtFromUCallback(
1184  UConverterFromUnicodeArgs* fromArgs,
1185  const UChar* codeUnits,
1186  int32_t length,
1187  UChar32 codePoint,
1188  UConverterCallbackReason reason,
1189  UErrorCode* err );
1190 #endif /* HAVE_ICU */
1191 
1192 private:
1194  Csock( const Csock & cCopy ) : CSockCommon() {}
1196  void ShrinkSendBuff();
1197  void IncBuffPos( size_t uBytes );
1199 
1200  // NOTE! if you add any new members, be sure to add them to Copy()
1201  uint16_t m_uPort;
1202  cs_sock_t m_iReadSock, m_iWriteSock;
1203  int m_iTimeout, m_iConnType, m_iMethod, m_iTcount, m_iMaxConns;
1204  bool m_bUseSSL, m_bIsConnected;
1205  bool m_bsslEstablished, m_bEnableReadLine, m_bPauseRead;
1206  CS_STRING m_shostname, m_sbuffer, m_sSockName, m_sDHParamFile, m_sKeyFile, m_sPemFile, m_sCipherType, m_sParentName;
1207  CS_STRING m_sSend, m_sPemPass;
1208  ECloseType m_eCloseType;
1209 
1210  // initialized lazily
1211  mutable uint16_t m_iRemotePort, m_iLocalPort;
1212  mutable CS_STRING m_sLocalIP, m_sRemoteIP;
1213 
1214  uint64_t m_iMaxMilliSeconds, m_iLastSendTime, m_iBytesRead, m_iBytesWritten, m_iStartTime;
1215  uint32_t m_iMaxBytes, m_iMaxStoredBufferLength, m_iTimeoutType;
1216  size_t m_iLastSend, m_uSendBufferPos;
1217 
1218  CSSockAddr m_address, m_bindhost;
1219  bool m_bIsIPv6, m_bSkipConnect;
1220  time_t m_iLastCheckTimeoutTime;
1221 
1222 #ifdef HAVE_LIBSSL
1223  CS_STRING m_sSSLBuffer;
1224  SSL * m_ssl;
1225  SSL_CTX * m_ssl_ctx;
1226  uint32_t m_iRequireClientCertFlags;
1227  u_int m_uDisableProtocols;
1228  bool m_bNoSSLCompression;
1229  bool m_bSSLCipherServerPreference;
1230 
1231  FPCertVerifyCB m_pCerVerifyCB;
1232 
1233  void FREE_SSL();
1234  void FREE_CTX();
1235  bool ConfigureCTXOptions( SSL_CTX * pCTX );
1236 
1237 #endif /* HAVE_LIBSSL */
1238 
1240  cs_sock_t CreateSocket( bool bListen = false, bool bUnix = false );
1241  void Init( const CS_STRING & sHostname, uint16_t uPort, int iTimeout = 60 );
1242 
1243  // Connection State Info
1244  ECONState m_eConState;
1245  CS_STRING m_sBindHost;
1246  uint32_t m_iCurBindCount, m_iDNSTryCount;
1247 #ifdef HAVE_C_ARES
1248  void FreeAres();
1249  ares_channel m_pARESChannel;
1250  CSSockAddr * m_pCurrAddr;
1251  int m_iARESStatus;
1252 #endif /* HAVE_C_ARES */
1253 
1254 #ifdef HAVE_ICU
1255  UConverter* m_cnvInt;
1256  UConverter* m_cnvExt;
1257  bool m_cnvTryUTF8;
1258  bool m_cnvSendUTF8;
1259  CS_STRING m_sEncoding;
1260 #endif
1261 };
1262 
1268 {
1269 public:
1275  CSConnection( const CS_STRING & sHostname, uint16_t iPort, int iTimeout = 60 )
1276  {
1277  m_sHostname = sHostname;
1278  m_iPort = iPort;
1279  m_iTimeout = iTimeout;
1280  m_bIsSSL = false;
1281 #ifdef HAVE_LIBSSL
1282  m_sCipher = "HIGH";
1283 #endif /* HAVE_LIBSSL */
1284  m_iAFrequire = CSSockAddr::RAF_ANY;
1285  }
1286  virtual ~CSConnection() {}
1287 
1288  const CS_STRING & GetHostname() const { return( m_sHostname ); }
1289  const CS_STRING & GetSockName() const { return( m_sSockName ); }
1290  const CS_STRING & GetBindHost() const { return( m_sBindHost ); }
1291  uint16_t GetPort() const { return( m_iPort ); }
1292  int GetTimeout() const { return( m_iTimeout ); }
1293  bool GetIsSSL() const { return( m_bIsSSL ); }
1294  CSSockAddr::EAFRequire GetAFRequire() const { return( m_iAFrequire ); }
1295 
1296 #ifdef HAVE_LIBSSL
1297  const CS_STRING & GetCipher() const { return( m_sCipher ); }
1298  const CS_STRING & GetPemLocation() const { return( m_sPemLocation ); }
1299  const CS_STRING & GetKeyLocation() const { return( m_sKeyLocation ); }
1300  const CS_STRING & GetDHParamLocation() const { return( m_sDHParamLocation ); }
1301  const CS_STRING & GetPemPass() const { return( m_sPemPass ); }
1302 #endif /* HAVE_LIBSSL */
1303 
1305  void SetHostname( const CS_STRING & s ) { m_sHostname = s; }
1307  void SetSockName( const CS_STRING & s ) { m_sSockName = s; }
1309  void SetBindHost( const CS_STRING & s ) { m_sBindHost = s; }
1311  void SetPort( uint16_t i ) { m_iPort = i; }
1313  void SetTimeout( int i ) { m_iTimeout = i; }
1315  void SetIsSSL( bool b ) { m_bIsSSL = b; }
1317  void SetAFRequire( CSSockAddr::EAFRequire iAFRequire ) { m_iAFrequire = iAFRequire; }
1318 
1319 #ifdef HAVE_LIBSSL
1321  void SetCipher( const CS_STRING & s ) { m_sCipher = s; }
1323  void SetPemLocation( const CS_STRING & s ) { m_sPemLocation = s; }
1325  void SetPemPass( const CS_STRING & s ) { m_sPemPass = s; }
1326 #endif /* HAVE_LIBSSL */
1327 
1328 protected:
1329  CS_STRING m_sHostname, m_sSockName, m_sBindHost;
1330  uint16_t m_iPort;
1332  bool m_bIsSSL;
1334 #ifdef HAVE_LIBSSL
1335  CS_STRING m_sDHParamLocation, m_sKeyLocation, m_sPemLocation, m_sPemPass, m_sCipher;
1336 #endif /* HAVE_LIBSSL */
1337 };
1338 
1340 {
1341 public:
1342  CSSSLConnection( const CS_STRING & sHostname, uint16_t iPort, int iTimeout = 60 ) :
1343  CSConnection( sHostname, iPort, iTimeout )
1344  {
1345  SetIsSSL( true );
1346  }
1347 };
1348 
1349 
1355 {
1356 public:
1362  CSListener( uint16_t iPort, const CS_STRING & sBindHost = "", bool bDetach = false )
1363  {
1364  m_iPort = iPort;
1365  m_sBindHost = sBindHost;
1366  m_bIsSSL = false;
1367  m_iMaxConns = SOMAXCONN;
1368  m_iTimeout = 0;
1369  m_iAFrequire = CSSockAddr::RAF_ANY;
1370  m_bDetach = bDetach;
1371 #ifdef HAVE_LIBSSL
1372  m_sCipher = "HIGH";
1373  m_iRequireCertFlags = 0;
1374 #endif /* HAVE_LIBSSL */
1375  }
1376  virtual ~CSListener() {}
1377 
1378  void SetDetach( bool b ) { m_bDetach = b; }
1379  bool GetDetach() const { return( m_bDetach ); }
1380  uint16_t GetPort() const { return( m_iPort ); }
1381  const CS_STRING & GetSockName() const { return( m_sSockName ); }
1382  const CS_STRING & GetBindHost() const { return( m_sBindHost ); }
1383  bool GetIsSSL() const { return( m_bIsSSL ); }
1384  int GetMaxConns() const { return( m_iMaxConns ); }
1385  uint32_t GetTimeout() const { return( m_iTimeout ); }
1386  CSSockAddr::EAFRequire GetAFRequire() const { return( m_iAFrequire ); }
1387 #ifdef HAVE_LIBSSL
1388  const CS_STRING & GetCipher() const { return( m_sCipher ); }
1389  const CS_STRING & GetDHParamLocation() const { return( m_sDHParamLocation ); }
1390  const CS_STRING & GetKeyLocation() const { return( m_sKeyLocation ); }
1391  const CS_STRING & GetPemLocation() const { return( m_sPemLocation ); }
1392  const CS_STRING & GetPemPass() const { return( m_sPemPass ); }
1393  uint32_t GetRequireClientCertFlags() const { return( m_iRequireCertFlags ); }
1394 #endif /* HAVE_LIBSSL */
1395 
1397  void SetPort( uint16_t iPort ) { m_iPort = iPort; }
1399  void SetSockName( const CS_STRING & sSockName ) { m_sSockName = sSockName; }
1401  void SetBindHost( const CS_STRING & sBindHost ) { m_sBindHost = sBindHost; }
1403  void SetIsSSL( bool b ) { m_bIsSSL = b; }
1405  void SetMaxConns( int i ) { m_iMaxConns = i; }
1407  void SetTimeout( uint32_t i ) { m_iTimeout = i; }
1409  void SetAFRequire( CSSockAddr::EAFRequire iAFRequire ) { m_iAFrequire = iAFRequire; }
1410 
1411 #ifdef HAVE_LIBSSL
1413  void SetCipher( const CS_STRING & s ) { m_sCipher = s; }
1415  void SetPemLocation( const CS_STRING & s ) { m_sPemLocation = s; }
1417  void SetKeyLocation( const CS_STRING & s ) { m_sKeyLocation = s; }
1419  void SetDHParamLocation( const CS_STRING & s ) { m_sDHParamLocation = s; }
1421  void SetPemPass( const CS_STRING & s ) { m_sPemPass = s; }
1423  void SetRequiresClientCert( bool b ) { m_iRequireCertFlags = ( b ? SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT : 0 ); }
1425  void SetRequireClientCertFlags( unsigned int iRequireCertFlags ) { m_iRequireCertFlags = iRequireCertFlags; }
1426 #endif /* HAVE_LIBSSL */
1427 private:
1428  uint16_t m_iPort;
1429  CS_STRING m_sSockName, m_sBindHost;
1430  bool m_bIsSSL;
1431  bool m_bDetach;
1432  int m_iMaxConns;
1433  uint32_t m_iTimeout;
1434  CSSockAddr::EAFRequire m_iAFrequire;
1435 
1436 #ifdef HAVE_LIBSSL
1437  CS_STRING m_sDHParamLocation, m_sKeyLocation, m_sPemLocation, m_sPemPass, m_sCipher;
1438  uint32_t m_iRequireCertFlags;
1439 #endif /* HAVE_LIBSSL */
1440 };
1441 
1442 #ifdef HAVE_LIBSSL
1443 class CSSSListener : public CSListener
1444 {
1445 public:
1446  CSSSListener( uint16_t iPort, const CS_STRING & sBindHost = "" ) :
1447  CSListener( iPort, sBindHost )
1448  {
1449  SetIsSSL( true );
1450  }
1451 };
1452 #endif /* HAVE_LIBSSL */
1453 
1475 class CS_EXPORT CSocketManager : public std::vector<Csock *>, public CSockCommon
1476 {
1477 public:
1479  virtual ~CSocketManager();
1480  virtual void clear();
1481  virtual void Cleanup();
1482 
1483  virtual Csock * GetSockObj( const CS_STRING & sHostname, uint16_t uPort, int iTimeout = 60 );
1484 
1486  {
1487  SUCCESS = 0,
1488  SELECT_ERROR = -1,
1489  SELECT_TIMEOUT = -2,
1490  SELECT_TRYAGAIN = -3
1491  };
1492 
1498  void Connect( const CSConnection & cCon, Csock * pcSock = NULL );
1499 
1509  virtual bool Listen( const CSListener & cListen, Csock * pcSock = NULL, uint16_t * piRandPort = NULL );
1510 
1511 
1513  bool HasFDs() const;
1514 
1520  virtual void Loop();
1521 
1537  void DynamicSelectLoop( uint64_t iLowerBounds, uint64_t iUpperBounds, time_t iMaxResolution = 3600 );
1538 
1543  virtual void AddSock( Csock * pcSock, const CS_STRING & sSockName );
1544 
1546  virtual Csock * FindSockByRemotePort( uint16_t iPort );
1547 
1549  virtual Csock * FindSockByLocalPort( uint16_t iPort );
1550 
1552  virtual Csock * FindSockByName( const CS_STRING & sName );
1553 
1555  virtual Csock * FindSockByFD( cs_sock_t iFD );
1556 
1557  virtual std::vector<Csock *> FindSocksByName( const CS_STRING & sName );
1558 
1560  virtual std::vector<Csock *> FindSocksByRemoteHost( const CS_STRING & sHostname );
1561 
1563  int GetErrno() const { return( m_errno ); }
1564 
1566  uint64_t GetSelectTimeout() const { return( m_iSelectWait ); }
1569  void SetSelectTimeout( uint64_t iTimeout ) { m_iSelectWait = iTimeout; }
1570 
1575  virtual void DelSockByAddr( Csock * pcSock );
1576 
1582  virtual void DelSock( size_t iPos );
1583 
1590  virtual bool SwapSockByIdx( Csock * pNewSock, size_t iOrginalSockIdx );
1591 
1598  virtual bool SwapSockByAddr( Csock * pNewSock, Csock * pOrigSock );
1599 
1601  uint64_t GetBytesRead() const;
1602 
1604  uint64_t GetBytesWritten() const;
1605 
1608  {
1609  ECT_Read = 1,
1610  ECT_Write = 2
1611  };
1612 
1613  void FDSetCheck( cs_sock_t iFd, std::map< cs_sock_t, short > & miiReadyFds, ECheckType eType );
1614  bool FDHasCheck( cs_sock_t iFd, std::map< cs_sock_t, short > & miiReadyFds, ECheckType eType );
1615 
1616 protected:
1617 
1618  virtual int Select( std::map< cs_sock_t, short > & miiReadyFds, struct timeval *tvtimeout );
1619 
1620 private:
1627  void Select( std::map<Csock *, EMessages> & mpeSocks );
1628 
1629  timeval GetDynamicSleepTime( const timeval& tNow, const timeval& tMaxResolution ) const;
1630 
1632  virtual void SelectSock( std::map<Csock *, EMessages> & mpeSocks, EMessages eErrno, Csock * pcSock );
1633 
1635  // Connection State Functions
1636 
1638  // members
1639  EMessages m_errno;
1640  uint64_t m_iCallTimeouts;
1641  uint64_t m_iBytesRead;
1642  uint64_t m_iBytesWritten;
1643  uint64_t m_iSelectWait;
1644 };
1645 
1646 
1653 template<class T>
1655 {
1656 public:
1658  virtual ~TSocketManager() {}
1659  virtual T * GetSockObj( const CS_STRING & sHostname, uint16_t uPort, int iTimeout = 60 )
1660  {
1661  return( new T( sHostname, uPort, iTimeout ) );
1662  }
1663 };
1664 
1665 #ifndef _NO_CSOCKET_NS
1666 }
1667 #endif /* _NO_CSOCKET_NS */
1668 
1669 #endif /* _HAS_CSOCKET_ */
1670 
void TFD_ZERO(fd_set *set)
wrappers for FD_SET and such to work in templates.
Definition: Csocket.h:362
void SSLErrors(const char *filename, uint32_t iLineNum)
bool InitCsocket()
This does all the csocket initialized inclusing InitSSL() and win32 specific initializations,...
void __Perror(const CS_STRING &s, const char *pszFile, uint32_t iLineNo)
bool InitSSL(ECompType eCompressionType=CT_NONE)
You HAVE to call this in order to use the SSL library, calling InitCsocket() also calls this so unles...
ECompType
Definition: Csocket.h:323
@ CT_NONE
Definition: Csocket.h:324
@ CT_ZLIB
Definition: Csocket.h:325
void CS_Delete(T *&p)
Definition: Csocket.h:319
#define CS_STRING
Definition: Csocket.h:123
int GetCsockSSLIdx()
This returns the [ex_]data index position for SSL objects only.
int CS_GetAddrInfo(const CS_STRING &sHostname, Csock *pSock, CSSockAddr &csSockAddr)
backwards compatible wrapper around CGetAddrInfo and gethostbyname
ssize_t cs_ssize_t
Definition: Csocket.h:157
void ShutdownCsocket()
Shutdown and release global allocated memory.
#define CS_EXPORT
Definition: Csocket.h:136
int GetSockError()
Definition: Csocket.h:352
void TFD_CLR(cs_sock_t iSock, fd_set *set)
Definition: Csocket.h:377
const uint32_t CS_BLOCKSIZE
Definition: Csocket.h:318
void CSAdjustTVTimeout(struct timeval &tv, long iTimeoutMS)
adjusts tv with a new timeout if iTimeoutMS is smaller
int(* FPCertVerifyCB)(int, X509_STORE_CTX *)
Definition: Csocket.h:549
Csock * GetCsockFromCTX(X509_STORE_CTX *pCTX)
returns the sock object associated to the particular context. returns NULL on failure or if not avail...
int cs_sock_t
Definition: Csocket.h:156
void TFD_SET(cs_sock_t iSock, fd_set *set)
Definition: Csocket.h:367
bool TFD_ISSET(cs_sock_t iSock, fd_set *set)
Definition: Csocket.h:372
this is the main cron job class
Definition: Csocket.h:393
void SetName(const CS_STRING &sName)
virtual ~CCron()
Definition: Csocket.h:396
void Start(double dTimeSequence)
starts and runs infinity amount of times
timeval GetInterval() const
void Pause()
pauses excution of your code in RunJob
void run(timeval &tNow)
This is used by the Job Manager, and not you directly.
void StartMaxCycles(const timeval &tTimeSequence, uint32_t iMaxCycles)
void Reset()
reset the timer
timeval GetNextRun() const
returns the timestamp of the next estimated run time. Note that it may not run at this EXACT time,...
Definition: Csocket.h:435
bool m_bRunOnNextCall
if set to true, RunJob() gets called on next invocation of run() despite the timeout
Definition: Csocket.h:443
uint32_t GetMaxCycles() const
const CS_STRING & GetName() const
void Stop()
call this to turn off your cron, it will be removed
void Start(const timeval &TimeSequence)
void StartMaxCycles(double dTimeSequence, uint32_t iMaxCycles)
uint32_t GetCyclesLeft() const
virtual void RunJob()
this is the method you should override
bool isValid() const
returns true if cron is active
void UnPause()
removes the pause on RunJon
this function is a wrapper around getaddrinfo (for ipv6)
Definition: Csocket.h:275
int Process()
the simplest part of the function, only calls getaddrinfo and uses only m_sHostname,...
CGetAddrInfo(const CS_STRING &sHostname, Csock *pSock, CSSockAddr &csSockAddr)
ctor
int Finish()
finalizes and sets up csSockAddr (and pSock if not NULL), only needs to be called if Process returns ...
void Init()
simply sets up m_cHints for use in process
Ease of use self deleting char * class.
Definition: Csocket.h:185
~CSCharBuffer()
Definition: Csocket.h:191
char * operator()()
Definition: Csocket.h:195
CSCharBuffer(size_t iSize)
Definition: Csocket.h:187
options for creating a connection
Definition: Csocket.h:1268
const CS_STRING & GetPemPass() const
Definition: Csocket.h:1301
void SetBindHost(const CS_STRING &s)
sets the hostname to bind to (vhost support)
Definition: Csocket.h:1309
CSConnection(const CS_STRING &sHostname, uint16_t iPort, int iTimeout=60)
Definition: Csocket.h:1275
void SetHostname(const CS_STRING &s)
sets the hostname to connect to
Definition: Csocket.h:1305
uint16_t m_iPort
Definition: Csocket.h:1330
void SetIsSSL(bool b)
set to true to enable SSL
Definition: Csocket.h:1315
const CS_STRING & GetCipher() const
Definition: Csocket.h:1297
const CS_STRING & GetHostname() const
Definition: Csocket.h:1288
const CS_STRING & GetBindHost() const
Definition: Csocket.h:1290
int GetTimeout() const
Definition: Csocket.h:1292
void SetPemLocation(const CS_STRING &s)
set the location of the pemfile
Definition: Csocket.h:1323
CS_STRING m_sBindHost
Definition: Csocket.h:1329
bool m_bIsSSL
Definition: Csocket.h:1332
CS_STRING m_sCipher
Definition: Csocket.h:1335
void SetPemPass(const CS_STRING &s)
set the pemfile pass
Definition: Csocket.h:1325
const CS_STRING & GetDHParamLocation() const
Definition: Csocket.h:1300
const CS_STRING & GetPemLocation() const
Definition: Csocket.h:1298
virtual ~CSConnection()
Definition: Csocket.h:1286
CSSockAddr::EAFRequire GetAFRequire() const
Definition: Csocket.h:1294
int m_iTimeout
Definition: Csocket.h:1331
void SetSockName(const CS_STRING &s)
sets the name of the socket, used for reference, ie in FindSockByName()
Definition: Csocket.h:1307
const CS_STRING & GetKeyLocation() const
Definition: Csocket.h:1299
bool GetIsSSL() const
Definition: Csocket.h:1293
const CS_STRING & GetSockName() const
Definition: Csocket.h:1289
void SetTimeout(int i)
sets the connection timeout
Definition: Csocket.h:1313
void SetCipher(const CS_STRING &s)
set the cipher strength to use, default is HIGH
Definition: Csocket.h:1321
void SetPort(uint16_t i)
sets the port to connect to
Definition: Csocket.h:1311
CSSockAddr::EAFRequire m_iAFrequire
Definition: Csocket.h:1333
void SetAFRequire(CSSockAddr::EAFRequire iAFRequire)
sets the AF family type required
Definition: Csocket.h:1317
uint16_t GetPort() const
Definition: Csocket.h:1291
options container to create a listener
Definition: Csocket.h:1355
uint16_t GetPort() const
Definition: Csocket.h:1380
void SetAFRequire(CSSockAddr::EAFRequire iAFRequire)
sets the AF family type required
Definition: Csocket.h:1409
const CS_STRING & GetPemLocation() const
Definition: Csocket.h:1391
void SetRequiresClientCert(bool b)
set to true if require a client certificate (deprecated
Definition: Csocket.h:1423
uint32_t GetRequireClientCertFlags() const
Definition: Csocket.h:1393
const CS_STRING & GetPemPass() const
Definition: Csocket.h:1392
void SetPemPass(const CS_STRING &s)
set the pemfile pass
Definition: Csocket.h:1421
uint32_t GetTimeout() const
Definition: Csocket.h:1385
void SetDHParamLocation(const CS_STRING &s)
set the location of the dhparamfile
Definition: Csocket.h:1419
void SetSockName(const CS_STRING &sSockName)
sets the sock name for later reference (ie FindSockByName)
Definition: Csocket.h:1399
void SetTimeout(uint32_t i)
sets the listen timeout. The listener class will close after timeout has been reached if not 0
Definition: Csocket.h:1407
const CS_STRING & GetSockName() const
Definition: Csocket.h:1381
virtual ~CSListener()
Definition: Csocket.h:1376
void SetBindHost(const CS_STRING &sBindHost)
sets the host to bind to
Definition: Csocket.h:1401
const CS_STRING & GetKeyLocation() const
Definition: Csocket.h:1390
const CS_STRING & GetBindHost() const
Definition: Csocket.h:1382
void SetCipher(const CS_STRING &s)
set the cipher strength to use, default is HIGH
Definition: Csocket.h:1413
void SetDetach(bool b)
Definition: Csocket.h:1378
const CS_STRING & GetCipher() const
Definition: Csocket.h:1388
int GetMaxConns() const
Definition: Csocket.h:1384
void SetPemLocation(const CS_STRING &s)
set the location of the pemfile
Definition: Csocket.h:1415
CSListener(uint16_t iPort, const CS_STRING &sBindHost="", bool bDetach=false)
Definition: Csocket.h:1362
void SetIsSSL(bool b)
set to true to enable SSL
Definition: Csocket.h:1403
bool GetDetach() const
Definition: Csocket.h:1379
const CS_STRING & GetDHParamLocation() const
Definition: Csocket.h:1389
void SetMaxConns(int i)
set max connections as called by accept()
Definition: Csocket.h:1405
void SetRequireClientCertFlags(unsigned int iRequireCertFlags)
bitwise flags, 0 means don't require cert, SSL_VERIFY_PEER verifies peers, SSL_VERIFY_FAIL_IF_NO_PEER...
Definition: Csocket.h:1425
CSSockAddr::EAFRequire GetAFRequire() const
Definition: Csocket.h:1386
void SetPort(uint16_t iPort)
sets the port to listen on. Set to 0 to listen on a random port
Definition: Csocket.h:1397
void SetKeyLocation(const CS_STRING &s)
set the location of the keyfile
Definition: Csocket.h:1417
bool GetIsSSL() const
Definition: Csocket.h:1383
Class to tie sockets to for monitoring by Csocket at either the Csock or TSockManager.
Definition: Csocket.h:458
bool m_bEnabled
Definition: Csocket.h:500
std::map< cs_sock_t, short > m_miiMonitorFDs
Definition: Csocket.h:499
CSMonitorFD()
Definition: Csocket.h:460
virtual bool GatherFDsForSelect(std::map< cs_sock_t, short > &miiReadyFds, long &iTimeoutMS)
called before select, typically you don't need to reimplement this just add sockets via Add and let t...
void DisableMonitor()
causes this monitor to be removed
Definition: Csocket.h:494
virtual bool FDsThatTriggered(const std::map< cs_sock_t, short > &miiReadyFds)
called when there are fd's belonging to this class that have triggered
Definition: Csocket.h:476
virtual ~CSMonitorFD()
Definition: Csocket.h:461
virtual bool CheckFDs(const std::map< cs_sock_t, short > &miiReadyFds)
gets called to diff miiReadyFds with m_miiMonitorFDs, and calls FDsThatTriggered when appropriate.
void Remove(cs_sock_t iFD)
removes this fd from monitoring
Definition: Csocket.h:492
void Add(cs_sock_t iFD, short iMonitorEvents)
adds a file descriptor to be monitored
Definition: Csocket.h:490
bool IsEnabled() const
Definition: Csocket.h:496
Definition: Csocket.h:1340
CSSSLConnection(const CS_STRING &sHostname, uint16_t iPort, int iTimeout=60)
Definition: Csocket.h:1342
Definition: Csocket.h:1444
CSSSListener(uint16_t iPort, const CS_STRING &sBindHost="")
Definition: Csocket.h:1446
sockaddr wrapper.
Definition: Csocket.h:207
sockaddr_in6 * GetSockAddr6()
Definition: Csocket.h:240
in6_addr * GetAddr6()
Definition: Csocket.h:241
EAFRequire GetAFRequire() const
Definition: Csocket.h:245
void SetIPv6(bool b)
EAFRequire
Definition: Csocket.h:222
@ RAF_ANY
Definition: Csocket.h:223
in_addr * GetAddr()
Definition: Csocket.h:237
void SetAFRequire(EAFRequire iWhich)
Definition: Csocket.h:244
bool GetIPv6() const
Definition: Csocket.h:233
sockaddr_in * GetSockAddr()
Definition: Csocket.h:236
void SinPort(uint16_t iPort)
socklen_t GetSockAddrLen6()
Definition: Csocket.h:239
socklen_t GetSockAddrLen()
Definition: Csocket.h:235
void SinFamily()
virtual ~CSSockAddr()
Definition: Csocket.h:218
CSSockAddr()
Definition: Csocket.h:209
simple class to share common code to both TSockManager and Csock
Definition: Csocket.h:509
virtual void AddCron(CCron *pcCron)
insert a newly created cron
void AssignFDs(std::map< cs_sock_t, short > &miiReadyFds, struct timeval *tvtimeout)
virtual void DelCron(uint32_t iPos)
delete cron by idx
void CheckFDs(const std::map< cs_sock_t, short > &miiReadyFds)
void MonitorFD(CSMonitorFD *pMonitorFD)
add an FD set to monitor
Definition: Csocket.h:540
CSockCommon()
Definition: Csocket.h:511
virtual void Cron()
This has a garbage collecter, and is used internall to call the jobs.
std::vector< CCron * > m_vcCrons
Definition: Csocket.h:543
void CleanupCrons()
const std::vector< CCron * > & GetCrons() const
returns a const reference to the crons associated to this socket
Definition: Csocket.h:518
virtual ~CSockCommon()
std::vector< CSMonitorFD * > m_vcMonitorFD
Definition: Csocket.h:544
virtual void DelCronByAddr(CCron *pcCron)
delete cron by address
void CleanupFDMonitors()
virtual void DelCron(const CS_STRING &sName, bool bDeleteAll=true, bool bCaseSensitive=true)
deletes a cron by name
Best class to use to interact with the sockets.
Definition: Csocket.h:1476
virtual bool Listen(const CSListener &cListen, Csock *pcSock=NULL, uint16_t *piRandPort=NULL)
Sets up a listening socket.
void Connect(const CSConnection &cCon, Csock *pcSock=NULL)
Create a connection.
virtual void clear()
virtual bool SwapSockByAddr(Csock *pNewSock, Csock *pOrigSock)
swaps out a sock with a copy of the original sock
virtual void DelSockByAddr(Csock *pcSock)
Delete a sock by addr its position is looked up the socket is deleted, the appropriate call backs are...
virtual Csock * FindSockByName(const CS_STRING &sName)
returns a pointer to the FIRST sock found by name or NULL on no match
virtual void Loop()
Best place to call this class for running, all the call backs are called.
ECheckType
this is a strict wrapper around C-api select(). Added in the event you need to do special work here
Definition: Csocket.h:1608
bool HasFDs() const
simple method to see if there are file descriptors being processed, useful to know if all the work is...
virtual Csock * FindSockByRemotePort(uint16_t iPort)
returns a pointer to the FIRST sock found by port or NULL on no match
bool FDHasCheck(cs_sock_t iFd, std::map< cs_sock_t, short > &miiReadyFds, ECheckType eType)
uint64_t GetSelectTimeout() const
Get the Select Timeout in MICROSECONDS ( 1000 == 1 millisecond )
Definition: Csocket.h:1566
virtual ~CSocketManager()
void FDSetCheck(cs_sock_t iFd, std::map< cs_sock_t, short > &miiReadyFds, ECheckType eType)
virtual Csock * FindSockByLocalPort(uint16_t iPort)
returns a pointer to the FIRST sock found by port or NULL on no match
uint64_t GetBytesRead() const
Get the bytes read from all sockets current and past.
uint64_t GetBytesWritten() const
Get the bytes written to all sockets current and past.
virtual Csock * FindSockByFD(cs_sock_t iFD)
returns a pointer to the FIRST sock found by filedescriptor or NULL on no match
virtual std::vector< Csock * > FindSocksByName(const CS_STRING &sName)
void SetSelectTimeout(uint64_t iTimeout)
Set the Select Timeout in MICROSECONDS ( 1000 == 1 millisecond ) Setting this to 0 will cause no time...
Definition: Csocket.h:1569
void DynamicSelectLoop(uint64_t iLowerBounds, uint64_t iUpperBounds, time_t iMaxResolution=3600)
this is similar to loop, except that it dynamically adjusts the select time based on jobs and timeout...
virtual bool SwapSockByIdx(Csock *pNewSock, size_t iOrginalSockIdx)
swaps out a sock with a copy of the original sock
virtual Csock * GetSockObj(const CS_STRING &sHostname, uint16_t uPort, int iTimeout=60)
virtual void AddSock(Csock *pcSock, const CS_STRING &sSockName)
Make this method virtual, so you can override it when a socket is added.
virtual int Select(std::map< cs_sock_t, short > &miiReadyFds, struct timeval *tvtimeout)
virtual std::vector< Csock * > FindSocksByRemoteHost(const CS_STRING &sHostname)
returns a vector of pointers to socks with sHostname as being connected
virtual void DelSock(size_t iPos)
Delete a sock by position in the vector the socket is deleted, the appropriate call backs are peforme...
EMessages
Definition: Csocket.h:1486
int GetErrno() const
return the last known error as set by this class
Definition: Csocket.h:1563
virtual void Cleanup()
Basic socket class.
Definition: Csocket.h:564
void DisableSSLProtocols(u_int uDisableOpts)
bitwise setter,
Definition: Csocket.h:891
virtual bool Write(const CS_STRING &sData)
Write a text string to the socket.
void SetMaxBufferThreshold(uint32_t iThreshold)
sets the max buffered threshold when EnableReadLine() is enabled
uint16_t GetRemotePort() const
Returns the remote port.
virtual void ReadData(const char *data, size_t len)
Ready to read data event.
Definition: Csocket.h:983
int GetType() const
Returns the connection type from enum eConnType.
const CS_STRING & GetSockName() const
Returns a reference to the socket name.
bool HasWriteBuffer() const
Get the send buffer.
virtual void Dereference()
in the event you pass this class to Copy(), you MUST call this function or on the original Csock othe...
virtual bool ConnectUnix(const CS_STRING &sPath)
Connect to a UNIX socket.
ETConn
Definition: Csocket.h:592
CS_STRING GetLocalIP() const
virtual void SetParentSockName(const CS_STRING &sParentName)
Set The INBOUND Parent sockname.
time_t GetLastCheckTimeout() const
Definition: Csocket.h:1084
CS_STRING & GetInternalReadBuffer()
This gives access to the internal read buffer, if your not going to use ReadLine(),...
ECONState
Definition: Csocket.h:638
uint64_t GetStartTime() const
Gets the starting time of this socket.
virtual void SockError(int iErrno, const CS_STRING &sDescription)
A sock error occured event.
Definition: Csocket.h:1004
Csock & operator<<(uint64_t i)
void SetAFRequire(CSSockAddr::EAFRequire iAFRequire)
Definition: Csocket.h:1131
bool ConnectInetd(bool bIsSSL=false, const CS_STRING &sHostname="")
Use this to bind this socket to inetd.
void CloseSocksFD()
puts the socks back to the state they were prior to calling CreateSocksFD
void SetType(int iType)
uint32_t GetRequireClientCertFlags() const
double GetAvgWrite(uint64_t iSample=1000) const
Get Avg Write Speed in sample milliseconds (default is 1000 milliseconds or 1 second)
Csock & operator<<(float i)
const CS_STRING & GetParentSockName() const
virtual void IcuExtFromUCallback(UConverterFromUnicodeArgs *fromArgs, const UChar *codeUnits, int32_t length, UChar32 codePoint, UConverterCallbackReason reason, UErrorCode *err)
virtual bool Listen(uint16_t iPort, int iMaxConns=SOMAXCONN, const CS_STRING &sBindHost="", uint32_t iTimeout=0, bool bDetach=false)
Listens for connections.
void SetEncoding(const CS_STRING &sEncoding)
const CS_STRING & GetDHParamLocation() const
void SetHostName(const CS_STRING &sHostname)
const CS_STRING & GetPemLocation() const
virtual int VerifyPeerCertificate(int iPreVerify, X509_STORE_CTX *pStoreCTX)
this is hooked in via SSL_set_verify, and be default it just returns 1 meaning success
Definition: Csocket.h:1077
const CS_STRING & GetCipher() const
void PauseRead()
will pause/unpause reading on this socket
void SetSkipConnect(bool b)
Definition: Csocket.h:1141
virtual bool CheckTimeout(time_t iNow)
returns true if the socket has timed out
const cs_sock_t & GetWSock() const
virtual bool ConnectionFrom(const CS_STRING &sHost, uint16_t iPort)
Incoming Connection Event return false and the connection will fail default returns true.
Definition: Csocket.h:1010
virtual bool SNIConfigureServer(const CS_STRING &sHostname, CS_STRING &sPemFile, CS_STRING &sPemPass)
gets called when a SNI request is sent, and used to configure a SNI session
Definition: Csocket.h:1042
void SetKeyLocation(const CS_STRING &sKeyFile)
virtual void ResetTimer()
resets the time counter, this is virtual in the event you need an event on the timer being Reset
Csock & operator<<(uint32_t i)
EDisableProtocol
Definition: Csocket.h:627
double GetAvgRead(uint64_t iSample=1000) const
Get Avg Read Speed in sample milliseconds (default is 1000 milliseconds or 1 second)
bool StartTLS()
start a TLS connection on an existing plain connection
cs_sock_t & GetWSock()
bool IsClosed() const
Definition: Csocket.h:880
void SetConState(ECONState eState)
sets the connection state to eState
Definition: Csocket.h:1097
void SetIPv6(bool b)
Definition: Csocket.h:1124
Csock & operator<<(int64_t i)
void SetCTXObject(SSL_CTX *sslCtx, bool bDeleteExisting=false)
void SetSockName(const CS_STRING &sName)
virtual void ReachedMaxBuffer()
This WARNING event is called when your buffer for readline exceeds the warning threshold and triggers...
Csock & operator<<(std::ostream &(*io)(std::ostream &))
void ResetStartTime()
Resets the start time.
time_t GetTimeSinceLastDataTransaction(time_t iNow=0) const
return how long it has been (in seconds) since the last read or successful write
Csock & operator<<(double i)
uint16_t GetPort() const
Returns the port.
void SetWSock(cs_sock_t iSock)
SSL_SESSION * GetSSLSession() const
uint16_t GetLocalPort() const
Returns the local port.
void SetSSLObject(SSL *ssl, bool bDeleteExisting=false)
virtual void Copy(const Csock &cCopy)
use this to copy a sock from one to the other, override it if you have special needs in the event of ...
virtual int ConvertAddress(const struct sockaddr_storage *pAddr, socklen_t iAddrLen, CS_STRING &sIP, uint16_t *piPort) const
retrieve name info (numeric only) for a given sockaddr_storage
bool GetSSL() const
Return true if this socket is using ssl. Note this does not mean the SSL state is finished,...
uint32_t GetRateBytes() const
virtual cs_ssize_t Read(char *data, size_t len)
Read from the socket Just pass in a pointer, big enough to hold len bytes.
virtual bool IsConnected() const
Tells you if the socket is connected.
void SetSSL(bool b)
uint64_t GetBytesWritten() const
Gets the amount of data written during the existence of the socket.
void FollowSSLCipherServerPreference()
select the ciphers in server-preferred order
Definition: Csocket.h:895
CS_STRING GetPeerPubKey() const
Returns the peer's public key.
int DNSLookup(EDNSLType eDNSLType)
dns lookup
Csock & operator<<(int32_t i)
void DisableSSLCompression()
allow disabling compression
Definition: Csocket.h:893
const CS_STRING & GetPemPass() const
void UnPauseRead()
X509 * GetX509() const
Get the peer's X509 cert.
virtual void IcuExtToUCallback(UConverterToUnicodeArgs *toArgs, const char *codeUnits, int32_t length, UConverterCallbackReason reason, UErrorCode *err)
virtual void ReadLine(const CS_STRING &sLine)
Ready to Read a full line event.
Definition: Csocket.h:988
virtual bool AcceptSSL()
Accept an inbound SSL connection, this is used internally and called after Accept.
void CallSockError(int iErrno, const CS_STRING &sDescription="")
calls SockError, if sDescription is not set, then strerror is used to pull out a default description
virtual bool ConnectSSL()
Create the SSL connection.
bool IsReadPaused() const
bool SetupVHost()
this is only used on outbound connections, listeners bind in a different spot
void SetBindHost(const CS_STRING &sBindHost)
Definition: Csocket.h:1106
void SetSSLMethod(int iMethod)
Set the SSL method type.
ECloseType
Definition: Csocket.h:649
void SetRSock(cs_sock_t iSock)
void ResetBytesRead()
void SetTimeout(int iTimeout, uint32_t iTimeoutType=TMO_ALL)
Currently this uses the same value for all timeouts, and iTimeoutType merely states which event will ...
uint32_t GetMaxBufferThreshold() const
long GetPeerFingerprint(CS_STRING &sFP) const
Returns the peer's certificate finger print.
virtual void SSLHandShakeFinished()
called once the SSL handshake is complete, this is triggered via SSL_CB_HANDSHAKE_DONE in SSL_set_inf...
Definition: Csocket.h:1065
CS_STRING GetEncoding() const
Definition: Csocket.h:1176
EDNSLType
Definition: Csocket.h:1109
@ DNS_VHOST
this lookup is for the vhost bind
Definition: Csocket.h:1110
CS_STRING & GetInternalWriteBuffer()
This gives access to the internal write buffer.
SSL * GetSSLObject() const
const cs_sock_t & GetSock() const
bool AllowWrite(uint64_t &iNOW) const
returns true if this socket can write its data, primarily used with rate shaping, initialize iNOW to ...
virtual Csock * GetSockObj(const CS_STRING &sHostname, uint16_t iPort)
override this for accept sockets
EFSelect
Definition: Csocket.h:608
bool GetIPv6() const
Definition: Csocket.h:1123
int GetSSLMethod() const
void SetCipher(const CS_STRING &sCipher)
Set the cipher type ( openssl cipher [to see ciphers available] )
ESSLMethod
Definition: Csocket.h:616
virtual cs_sock_t Accept(CS_STRING &sHost, uint16_t &iRPort)
Accept an inbound connection, this is used internally.
virtual void Listening(const CS_STRING &sBindIP, uint16_t uPort)
called when type is LISTENER and the listening port is up and running
Definition: Csocket.h:1017
ECloseType GetCloseType() const
returns int of type to close
Definition: Csocket.h:879
time_t GetNextCheckTimeout(time_t iNow=0) const
Returns the time when CheckTimeout() should be called next.
virtual void SSLFinishSetup(SSL *pSSL)
Gets called immediatly after the m_ssl member is setup and initialized, useful if you need to assign ...
Definition: Csocket.h:1034
Csock(int iTimeout=60)
default constructor, sets a timeout of 60 seconds
uint64_t GetBytesRead() const
Gets the amount of data read during the existence of the socket.
virtual void ReadPaused()
This gets called every iteration of CSocketManager::Select() if the socket is ReadPaused.
Definition: Csocket.h:1027
bool HasReadLine() const
returns the value of m_bEnableReadLine, if ReadLine is enabled
Definition: Csocket.h:993
virtual bool SNIConfigureClient(CS_STRING &sHostname)
called to configure the SNI client
virtual ~Csock()
Csock(const CS_STRING &sHostname, uint16_t uPort, int itimeout=60)
Advanced constructor, for creating a simple connection.
void NonBlockingIO()
Use this to change your fd's to blocking or none blocking.
cs_sock_t & GetSock()
void SetPort(uint16_t iPort)
const CS_STRING & GetKeyLocation() const
virtual void Timeout()
Sock Timed out event.
Definition: Csocket.h:979
uint32_t GetTimeoutType() const
void ResetBytesWritten()
virtual bool Connect()
Create the connection, this is used by the socket manager, and shouldn't be called directly by the us...
void SetSock(cs_sock_t iSock)
virtual void ConnectionRefused()
Connection Refused Event.
Definition: Csocket.h:1023
void Close(ECloseType eCloseType=CLT_NOW)
just mark us as closed, the parent can pick it up
int GetTimeout() const
void SetTimeoutType(uint32_t iTimeoutType)
const cs_sock_t & GetRSock() const
Csock & operator<<(const CS_STRING &s)
void SetRequireClientCertFlags(uint32_t iRequireClientCertFlags)
bitwise flags, 0 means don't require cert, SSL_VERIFY_PEER verifies peers, SSL_VERIFY_FAIL_IF_NO_PEER...
Definition: Csocket.h:951
virtual void SetRate(uint32_t iBytes, uint64_t iMilliseconds)
sets the rate at which we can send data
void SetPemLocation(const CS_STRING &sPemFile)
const CS_STRING & GetHostName() const
Returns a reference to the host name.
virtual void Connected()
Connected event.
Definition: Csocket.h:971
const CS_STRING & GetBindHost() const
Definition: Csocket.h:1105
virtual void SetIsConnected(bool b)
Sets the sock, telling it its connected (internal use only)
void ClearWriteBuffer()
void DisableReadLine()
EFRead
Definition: Csocket.h:599
virtual int GetAddrInfo(const CS_STRING &sHostname, CSSockAddr &csSockAddr)
override this call with your own DNS lookup method if you have one.
cs_sock_t & GetRSock()
returns a reference to the sock
void SetDHParamLocation(const CS_STRING &sDHParamFile)
Set the pem file location.
SSL_CTX * SetupServerCTX()
creates a new SSL_CTX based on the setup of this sock
virtual int GetPending() const
return the data imediatly ready for read
bool SslIsEstablished() const
is SSL_accept finished ? is the ssl properly finished (from write no error)
virtual void Disconnected()
Disconnected event.
Definition: Csocket.h:975
virtual bool Write(const char *data, size_t len)
Write data to the socket.
virtual bool SSLClientSetup()
This sets up the SSL Client, this is used internally.
bool CreateSocksFD()
grabs fd's for the sockets
bool ConnectFD(int iReadFD, int iWriteFD, const CS_STRING &sName, bool bIsSSL=false, ETConn eDirection=INBOUND)
Tie this guy to an existing real file descriptor.
CS_STRING GetRemoteIP() const
uint64_t GetRateTime() const
ECONState GetConState() const
returns the current connection state
Definition: Csocket.h:1095
virtual bool SSLServerSetup()
This sets up the SSL Server, this is used internally.
virtual void PushBuff(const char *data, size_t len, bool bStartAtZero=false)
pushes data up on the buffer, if a line is ready it calls the ReadLine event
void EnableReadLine()
set the value of m_bEnableReadLine to true, we don't want to store a buffer for ReadLine,...
int GetMaxConns() const
returns the number of max pending connections when type is LISTENER
Definition: Csocket.h:1172
void SetRequiresClientCert(bool bRequiresCert)
legacy, deprecated
void SetPemPass(const CS_STRING &sPassword)
void SetCertVerifyCB(FPCertVerifyCB pFP)
setting this to NULL will allow the default openssl verification process kick in
Definition: Csocket.h:920
virtual bool ListenUnix(const CS_STRING &sBindFile, int iMaxConns=SOMAXCONN, uint32_t iTimeout=0)
Listens for connections on an UNIX socket.
Ease of use templated socket manager.
Definition: Csocket.h:1655
TSocketManager()
Definition: Csocket.h:1657
virtual T * GetSockObj(const CS_STRING &sHostname, uint16_t uPort, int iTimeout=60)
Definition: Csocket.h:1659
virtual ~TSocketManager()
Definition: Csocket.h:1658