-
Notifications
You must be signed in to change notification settings - Fork 1
/
Csocket.cpp
3525 lines (3056 loc) · 87.4 KB
/
Csocket.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** @file
*
* Copyright (c) 1999-2011 Jim Hull <[email protected]>
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* Redistributions in any form must be accompanied by information on how to obtain
* complete source code for this software and any accompanying software that uses this software.
* The source code must either be included in the distribution or be available for no more than
* the cost of distribution plus a nominal fee, and must be freely redistributable
* under reasonable conditions. For an executable file, complete source code means the source
* code for all modules it contains. It does not include source code for modules or files
* that typically accompany the major components of the operating system on which the executable file runs.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
* OR NON-INFRINGEMENT, ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THIS SOFTWARE BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
*/
#include "Csocket.h"
#ifdef __NetBSD__
#include <sys/param.h>
#endif /* __NetBSD__ */
#ifdef HAVE_LIBSSL
#include <stdio.h>
#include <openssl/conf.h>
#include <openssl/engine.h>
#endif /* HAVE_LIBSSL */
#include <list>
#define CS_SRANDBUFFER 128
using namespace std;
#define CREATE_ARES_VER( a, b, c ) ((a<<16)|(b<<8)|c)
#ifndef _NO_CSOCKET_NS // some people may not want to use a namespace
namespace Csocket
{
#endif /* _NO_CSOCKET_NS */
static int g_iCsockSSLIdx = 0; //!< this get setup once in InitSSL
int GetCsockClassIdx()
{
return( g_iCsockSSLIdx );
}
#ifdef _WIN32
static const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt)
{
if( af == AF_INET )
{
struct sockaddr_in in;
memset(&in, 0, sizeof(in));
in.sin_family = AF_INET;
memcpy( &in.sin_addr, src, sizeof(struct in_addr) );
getnameinfo( (struct sockaddr *)&in, sizeof(struct sockaddr_in), dst, cnt, NULL, 0, NI_NUMERICHOST );
return dst;
}
else if( af == AF_INET6 )
{
struct sockaddr_in6 in;
memset( &in, 0, sizeof(in) );
in.sin6_family = AF_INET6;
memcpy( &in.sin6_addr, src, sizeof(struct in_addr6) );
getnameinfo( (struct sockaddr *)&in, sizeof(struct sockaddr_in6), dst, cnt, NULL, 0, NI_NUMERICHOST );
return dst;
}
return( NULL );
}
#if defined(_WIN32) && (!defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0600))
//! thanks to KiNgMaR @ #znc for this wrapper
static int inet_pton( int af, const char *src, void *dst )
{
sockaddr_storage aAddress;
int iAddrLen = sizeof( sockaddr_storage );
memset( &aAddress, 0, iAddrLen );
char *pTmp = strdup( src );
aAddress.ss_family = af; // this is important:
// The function fails if the sin_family member of the SOCKADDR_IN structure is not set to AF_INET or AF_INET6.
int iRet = WSAStringToAddressA( pTmp, af, NULL, (sockaddr *)&aAddress, &iAddrLen );
free( pTmp );
if( iRet == 0 )
{
if( af == AF_INET6 )
memcpy(dst, &((sockaddr_in6 *)&aAddress)->sin6_addr, sizeof(in6_addr));
else
memcpy(dst, &((sockaddr_in *)&aAddress)->sin_addr, sizeof(in_addr));
return( 1 );
}
return( -1 );
}
#endif
static inline void set_non_blocking(cs_sock_t fd)
{
u_long iOpts = 1;
ioctlsocket( fd, FIONBIO, &iOpts );
}
static inline void set_blocking(cs_sock_t fd)
{
u_long iOpts = 0;
ioctlsocket( fd, FIONBIO, &iOpts );
}
static inline void set_close_on_exec(cs_sock_t fd)
{
// TODO add this for windows
// see http://gcc.gnu.org/ml/java-patches/2002-q1/msg00696.html
// for infos on how to do this
}
#else
static inline void set_non_blocking(cs_sock_t fd)
{
int fdflags = fcntl(fd, F_GETFL, 0);
if ( fdflags < 0 )
return; // Ignore errors
fcntl( fd, F_SETFL, fdflags|O_NONBLOCK );
}
static inline void set_blocking(cs_sock_t fd)
{
int fdflags = fcntl(fd, F_GETFL, 0);
if ( fdflags < 0 )
return; // Ignore errors
fdflags &= ~O_NONBLOCK;
fcntl( fd, F_SETFL, fdflags );
}
static inline void set_close_on_exec(cs_sock_t fd)
{
int fdflags = fcntl(fd, F_GETFD, 0);
if ( fdflags < 0 )
return; // Ignore errors
fcntl( fd, F_SETFD, fdflags|FD_CLOEXEC);
}
#endif /* _WIN32 */
#ifdef HAVE_LIBSSL
Csock *GetCsockFromCTX( X509_STORE_CTX *pCTX )
{
Csock *pSock = NULL;
SSL *pSSL = (SSL *)X509_STORE_CTX_get_ex_data( pCTX, SSL_get_ex_data_X509_STORE_CTX_idx() );
if( pSSL )
pSock = (Csock *)SSL_get_ex_data( pSSL, GetCsockClassIdx() );
return( pSock );
}
#endif /* HAVE_LIBSSL */
#ifndef HAVE_IPV6
// this issue here is getaddrinfo has a significant behavior difference when dealing with round robin dns on an
// ipv4 network. This is not desirable IMHO. so when this is compiled without ipv6 support backwards compatibility
// is maintained.
static int __GetHostByName( const CS_STRING & sHostName, struct in_addr *paddr, u_int iNumRetries )
{
int iReturn = HOST_NOT_FOUND;
struct hostent *hent = NULL;
#ifdef __linux__
char hbuff[2048];
struct hostent hentbuff;
int err;
for( u_int a = 0; a < iNumRetries; a++ )
{
memset( (char *)hbuff, '\0', 2048 );
iReturn = gethostbyname_r( sHostName.c_str(), &hentbuff, hbuff, 2048, &hent, &err );
if ( iReturn == 0 )
break;
if ( iReturn != TRY_AGAIN )
{
CS_DEBUG( "gethostyname_r: " << hstrerror( h_errno ) );
break;
}
}
if ( ( !hent ) && ( iReturn == 0 ) )
iReturn = HOST_NOT_FOUND;
#else
for( u_int a = 0; a < iNumRetries; a++ )
{
iReturn = HOST_NOT_FOUND;
hent = gethostbyname( sHostName.c_str() );
if ( hent )
{
iReturn = 0;
break;
}
if( h_errno != TRY_AGAIN )
{
#ifndef _WIN32
CS_DEBUG( "gethostyname: " << hstrerror( h_errno ) );
#endif /* _WIN32 */
break;
}
}
#endif /* __linux__ */
if ( iReturn == 0 )
memcpy( &paddr->s_addr, hent->h_addr_list[0], sizeof( paddr->s_addr ) );
return( iReturn == TRY_AGAIN ? EAGAIN : iReturn );
}
#endif /* !HAVE_IPV6 */
#ifdef HAVE_C_ARES
void Csock::FreeAres()
{
if( m_pARESChannel )
{
ares_destroy( m_pARESChannel );
m_pARESChannel = NULL;
}
}
#endif /* HAVE_C_ARES */
#ifdef HAVE_C_ARES
static void AresHostCallback( void *pArg, int status, int timeouts, struct hostent *hent )
{
Csock *pSock = (Csock *)pArg;
if( status == ARES_SUCCESS && hent && hent->h_addr_list[0] != NULL )
{
CSSockAddr *pSockAddr = pSock->GetCurrentAddr();
if( hent->h_addrtype == AF_INET )
{
pSock->SetIPv6( false );
memcpy( pSockAddr->GetAddr(), hent->h_addr_list[0], sizeof( *(pSockAddr->GetAddr()) ) );
}
#ifdef HAVE_IPV6
else if( hent->h_addrtype == AF_INET6 )
{
pSock->SetIPv6( true );
memcpy( pSockAddr->GetAddr6(), hent->h_addr_list[0], sizeof( *(pSockAddr->GetAddr6()) ) );
}
#endif /* HAVE_IPV6 */
else
{
status = ARES_ENOTFOUND;
}
}
else
{
CS_DEBUG( ares_strerror( status ) );
if( status == ARES_SUCCESS )
{
CS_DEBUG("Received ARES_SUCCESS without any useful reply, using NODATA instead");
status = ARES_ENODATA;
}
}
pSock->SetAresFinished( status );
}
#endif /* HAVE_C_ARES */
int GetAddrInfo( const CS_STRING & sHostname, Csock *pSock, CSSockAddr & csSockAddr )
{
#ifndef HAVE_IPV6
// if ipv6 is not enabled, then simply use gethostbyname, nothing special outside of this is done
if( pSock )
pSock->SetIPv6( false );
csSockAddr.SetIPv6( false );
if( __GetHostByName( sHostname, csSockAddr.GetAddr(), 3 ) == 0 )
return( 0 );
#else /* HAVE_IPV6 */
struct addrinfo *res = NULL;
struct addrinfo hints;
memset( (struct addrinfo *)&hints, '\0', sizeof( hints ) );
hints.ai_family = csSockAddr.GetAFRequire();
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
#ifdef AI_ADDRCONFIG
// this is suppose to eliminate host from appearing that this system can not support
hints.ai_flags = AI_ADDRCONFIG;
#endif /* AI_ADDRCONFIG */
if( pSock && ( pSock->GetType() == Csock::LISTENER || pSock->GetConState() == Csock::CST_BINDVHOST ) )
{ // when doing a dns for bind only, set the AI_PASSIVE flag as suggested by the man page
hints.ai_flags |= AI_PASSIVE;
}
int iRet = getaddrinfo( sHostname.c_str(), NULL, &hints, &res );
if( iRet == EAI_AGAIN )
return( EAGAIN ); // need to return telling the user to try again
else if( ( iRet == 0 ) && ( res ) )
{
std::list<struct addrinfo *> lpTryAddrs;
bool bFound = false;
for( struct addrinfo *pRes = res; pRes; pRes = pRes->ai_next )
{ // pass through the list building out a lean list of candidates to try. AI_CONFIGADDR doesn't always seem to work
#ifdef __sun
if( ( pRes->ai_socktype != SOCK_STREAM ) || ( pRes->ai_protocol != IPPROTO_TCP && pRes->ai_protocol != IPPROTO_IP ) )
#else
if( ( pRes->ai_socktype != SOCK_STREAM ) || ( pRes->ai_protocol != IPPROTO_TCP ) )
#endif /* __sun work around broken impl of getaddrinfo */
continue;
if( ( csSockAddr.GetAFRequire() != CSSockAddr::RAF_ANY ) && ( pRes->ai_family != csSockAddr.GetAFRequire() ) )
continue; // they requested a special type, so be certain we woop past anything unwanted
lpTryAddrs.push_back( pRes );
}
for( std::list<struct addrinfo *>::iterator it = lpTryAddrs.begin(); it != lpTryAddrs.end(); )
{ // cycle through these, leaving the last iterator for the outside caller to call, so if there is an error it can call the events
struct addrinfo * pRes = *it;
bool bTryConnect = false;
if( pRes->ai_family == AF_INET )
{
if( pSock )
pSock->SetIPv6( false );
csSockAddr.SetIPv6( false );
struct sockaddr_in *pTmp = (struct sockaddr_in *)pRes->ai_addr;
memcpy( csSockAddr.GetAddr(), &(pTmp->sin_addr), sizeof( *(csSockAddr.GetAddr()) ) );
if( pSock && pSock->GetConState() == Csock::CST_DESTDNS && pSock->GetType() == Csock::OUTBOUND )
{
bTryConnect = true;
}
else
{
bFound = true;
break;
}
}
else if( pRes->ai_family == AF_INET6 )
{
if( pSock )
pSock->SetIPv6( true );
csSockAddr.SetIPv6( true );
struct sockaddr_in6 *pTmp = (struct sockaddr_in6 *)pRes->ai_addr;
memcpy( csSockAddr.GetAddr6(), &(pTmp->sin6_addr), sizeof( *(csSockAddr.GetAddr6()) ) );
if( pSock && pSock->GetConState() == Csock::CST_DESTDNS && pSock->GetType() == Csock::OUTBOUND )
{
bTryConnect = true;
}
else
{
bFound = true;
break;
}
}
it++; // increment the iterator her so we know if its the last element or not
if( bTryConnect && it != lpTryAddrs.end() )
{ // save the last attempt for the outer loop, the issue then becomes that the error is thrown on the last failure
if( pSock->CreateSocksFD() && pSock->Connect( pSock->GetBindHost(), true ) )
{
pSock->SetSkipConnect( true ); // this tells the socket that the connection state has been started
bFound = true;
break;
}
pSock->CloseSocksFD();
}
else if( bTryConnect )
{
bFound = true;
}
}
freeaddrinfo( res );
if( bFound ) // the data pointed to here is invalid now, but the pointer itself is a good test
{
return( 0 );
}
}
#endif /* ! HAVE_IPV6 */
return( ETIMEDOUT );
}
bool InitCsocket()
{
#ifdef _WIN32
WSADATA wsaData;
int iResult = WSAStartup( MAKEWORD( 2, 2 ), &wsaData );
if( iResult != NO_ERROR )
return( false );
#endif /* _WIN32 */
#ifdef HAVE_C_ARES
#if ARES_VERSION >= CREATE_ARES_VER( 1, 6, 1 )
if( ares_library_init( ARES_LIB_INIT_ALL ) != 0 )
return( false );
#endif /* ARES_VERSION >= CREATE_ARES_VER( 1, 6, 1 ) */
#endif /* HAVE_C_ARES */
#ifdef HAVE_LIBSSL
if( !InitSSL() )
return( false );
#endif /* HAVE_LIBSSL */
return( true );
}
void ShutdownCsocket()
{
#ifdef HAVE_LIBSSL
ERR_remove_state(0);
ENGINE_cleanup();
CONF_modules_unload(1);
ERR_free_strings();
EVP_cleanup();
CRYPTO_cleanup_all_ex_data();
#endif /* HAVE_LIBSSL */
#ifdef HAVE_C_ARES
#if ARES_VERSION >= CREATE_ARES_VER( 1, 6, 1 )
ares_library_cleanup();
#endif /* ARES_VERSION >= CREATE_ARES_VER( 1, 6, 1 ) */
#endif /* HAVE_C_ARES */
#ifdef _WIN32
WSACleanup();
#endif /* _WIN32 */
}
#ifdef HAVE_LIBSSL
bool InitSSL( ECompType eCompressionType )
{
SSL_load_error_strings();
if ( SSL_library_init() != 1 )
{
CS_DEBUG( "SSL_library_init() failed!" );
return( false );
}
#ifndef _WIN32
if ( access( "/dev/urandom", R_OK ) == 0 )
RAND_load_file( "/dev/urandom", 1024 );
else if( access( "/dev/random", R_OK ) == 0 )
RAND_load_file( "/dev/random", 1024 );
else
{
CS_DEBUG( "Unable to locate entropy location! Tried /dev/urandom and /dev/random" );
return( false );
}
#endif /* _WIN32 */
COMP_METHOD *cm = NULL;
if ( CT_ZLIB & eCompressionType )
{
cm = COMP_zlib();
if ( cm )
SSL_COMP_add_compression_method( CT_ZLIB, cm );
}
if ( CT_RLE & eCompressionType )
{
cm = COMP_rle();
if ( cm )
SSL_COMP_add_compression_method( CT_RLE, cm );
}
// setting this up once in the begining
g_iCsockSSLIdx = SSL_get_ex_new_index( 0, (void *)"CsockGlobalIndex", NULL, NULL, NULL);
return( true );
}
void CSAdjustTVTimeout( struct timeval & tv, long iTimeoutMS )
{
if( iTimeoutMS >= 0 )
{
long iCurTimeout = tv.tv_usec / 1000;
iCurTimeout += tv.tv_sec * 1000;
if( iCurTimeout > iTimeoutMS )
{
tv.tv_sec = iTimeoutMS / 1000;
tv.tv_usec = iTimeoutMS % 1000;
}
}
}
void SSLErrors( const char *filename, u_int iLineNum )
{
unsigned long iSSLError = 0;
while( ( iSSLError = ERR_get_error() ) != 0 )
{
CS_DEBUG( "at " << filename << ":" << iLineNum );
char szError[512];
memset( (char *) szError, '\0', 512 );
ERR_error_string_n( iSSLError, szError, 511 );
if ( *szError )
CS_DEBUG( szError );
}
}
#endif /* HAVE_LIBSSL */
void __Perror( const CS_STRING & s, const char *pszFile, unsigned int iLineNo )
{
#if defined( sgi ) || defined(__sun) || defined(_WIN32) || (defined(__NetBSD_Version__) && __NetBSD_Version__ < 4000000000)
std::cerr << s << "(" << pszFile << ":" << iLineNo << "): " << strerror( GetSockError() ) << endl;
#else
char buff[512];
memset( (char *)buff, '\0', 512 );
if ( strerror_r( GetSockError(), buff, 511 ) == 0 )
std::cerr << s << "(" << pszFile << ":" << iLineNo << "): " << buff << endl;
else
std::cerr << s << "(" << pszFile << ":" << iLineNo << "): Unknown Error Occured " << endl;
#endif /* __sun */
}
unsigned long long millitime()
{
unsigned long long iTime = 0;
#ifdef _WIN32
struct timeb tm;
ftime( &tm );
iTime = tm.time * 1000;
iTime += tm.millitm;
#else
struct timeval tv;
gettimeofday( &tv, NULL );
iTime = (unsigned long long )tv.tv_sec * 1000;
iTime += ( (unsigned long long)tv.tv_usec / 1000 );
#endif /* _WIN32 */
return( iTime );
}
#ifndef _NO_CSOCKET_NS // some people may not want to use a namespace
}
using namespace Csocket;
#endif /* _NO_CSOCKET_NS */
CCron::CCron()
{
m_iCycles = 0;
m_iMaxCycles = 0;
m_bActive = true;
m_iTime = 0;
m_iTimeSequence = 60;
m_bPause = false;
m_bRunOnNextCall = false;
}
void CCron::run( time_t & iNow )
{
if ( m_bPause )
return;
if( iNow == 0 )
iNow = time( NULL );
if ( ( m_bActive ) && ( iNow >= m_iTime || m_bRunOnNextCall ) )
{
m_bRunOnNextCall = false; // Setting this here because RunJob() could set it back to true
RunJob();
if ( ( m_iMaxCycles > 0 ) && ( ++m_iCycles >= m_iMaxCycles ) )
m_bActive = false;
else
m_iTime = iNow + m_iTimeSequence;
}
}
void CCron::StartMaxCycles( int TimeSequence, u_int iMaxCycles )
{
m_iTimeSequence = TimeSequence;
m_iTime = time( NULL ) + m_iTimeSequence;
m_iMaxCycles = iMaxCycles;
}
void CCron::Start( int TimeSequence )
{
m_iTimeSequence = TimeSequence;
m_iTime = time( NULL ) + m_iTimeSequence;
m_iMaxCycles = 0;
}
void CCron::Stop()
{
m_bActive = false;
}
void CCron::Pause()
{
m_bPause = true;
}
void CCron::UnPause()
{
m_bPause = false;
}
int CCron::GetInterval() const { return( m_iTimeSequence ); }
u_int CCron::GetMaxCycles() const { return( m_iMaxCycles ); }
u_int CCron::GetCyclesLeft() const { return( ( m_iMaxCycles > m_iCycles ? ( m_iMaxCycles - m_iCycles ) : 0 ) ); }
bool CCron::isValid() { return( m_bActive ); }
const CS_STRING & CCron::GetName() const { return( m_sName ); }
void CCron::SetName( const CS_STRING & sName ) { m_sName = sName; }
void CCron::RunJob() { CS_DEBUG( "This should be overridden" ); }
bool CSMonitorFD::GatherFDsForSelect( std::map< int, short > & miiReadyFds, long & iTimeoutMS )
{
iTimeoutMS = -1; // don't bother changing anything in the default implementation
for( std::map< int, short >::iterator it = m_miiMonitorFDs.begin(); it != m_miiMonitorFDs.end(); ++it )
{
miiReadyFds[it->first] = it->second;
}
return( m_bEnabled );
}
bool CSMonitorFD::CheckFDs( const std::map< int, short > & miiReadyFds )
{
std::map< int, short > miiTriggerdFds;
for( std::map< int, short >::iterator it = m_miiMonitorFDs.begin(); it != m_miiMonitorFDs.end(); ++it )
{
std::map< int, short >::const_iterator itFD = miiReadyFds.find( it->first );
if( itFD != miiReadyFds.end() )
miiTriggerdFds[itFD->first] = itFD->second;
}
if( miiTriggerdFds.size() )
return( FDsThatTriggered( miiTriggerdFds ) );
return( m_bEnabled );
}
CSockCommon::~CSockCommon()
{
// delete any left over crons
CleanupCrons();
CleanupFDMonitors();
}
void CSockCommon::CleanupCrons()
{
for( size_t a = 0; a < m_vcCrons.size(); a++ )
CS_Delete( m_vcCrons[a] );
m_vcCrons.clear();
}
void CSockCommon::CleanupFDMonitors()
{
for( size_t a = 0; a < m_vcMonitorFD.size(); a++ )
CS_Delete( m_vcMonitorFD[a] );
m_vcMonitorFD.clear();
}
void CSockCommon::CheckFDs( const std::map< int, short > & miiReadyFds )
{
for( size_t uMon = 0; uMon < m_vcMonitorFD.size(); ++uMon )
{
if( !m_vcMonitorFD[uMon]->IsEnabled() || !m_vcMonitorFD[uMon]->CheckFDs( miiReadyFds ) )
m_vcMonitorFD.erase( m_vcMonitorFD.begin() + uMon-- );
}
}
void CSockCommon::AssignFDs( std::map< int, short > & miiReadyFds, struct timeval * tvtimeout )
{
for( size_t uMon = 0; uMon < m_vcMonitorFD.size(); ++uMon )
{
long iTimeoutMS = -1;
if( m_vcMonitorFD[uMon]->IsEnabled() && m_vcMonitorFD[uMon]->GatherFDsForSelect( miiReadyFds, iTimeoutMS ) )
{
CSAdjustTVTimeout( *tvtimeout, iTimeoutMS );
}
else
{
CS_Delete( m_vcMonitorFD[uMon] );
m_vcMonitorFD.erase( m_vcMonitorFD.begin() + uMon-- );
}
}
}
void CSockCommon::Cron()
{
time_t iNow = 0;
for( vector<CCron *>::size_type a = 0; a < m_vcCrons.size(); a++ )
{
CCron *pcCron = m_vcCrons[a];
if ( !pcCron->isValid() )
{
CS_Delete( pcCron );
m_vcCrons.erase( m_vcCrons.begin() + a-- );
} else
pcCron->run( iNow );
}
}
void CSockCommon::AddCron( CCron * pcCron )
{
m_vcCrons.push_back( pcCron );
}
void CSockCommon::DelCron( const CS_STRING & sName, bool bDeleteAll, bool bCaseSensitive )
{
for( u_int a = 0; a < m_vcCrons.size(); a++ )
{
int (*Cmp)(const char *, const char *) = ( bCaseSensitive ? strcmp : strcasecmp );
if ( Cmp( m_vcCrons[a]->GetName().c_str(), sName.c_str() ) == 0 )
{
m_vcCrons[a]->Stop();
CS_Delete( m_vcCrons[a] );
m_vcCrons.erase( m_vcCrons.begin() + a-- );
if( !bDeleteAll )
break;
}
}
}
void CSockCommon::DelCron( u_int iPos )
{
if ( iPos < m_vcCrons.size() )
{
m_vcCrons[iPos]->Stop();
CS_Delete( m_vcCrons[iPos] );
m_vcCrons.erase( m_vcCrons.begin() + iPos );
}
}
void CSockCommon::DelCronByAddr( CCron *pcCron )
{
for( u_int a = 0; a < m_vcCrons.size(); a++ )
{
if ( m_vcCrons[a] == pcCron )
{
m_vcCrons[a]->Stop();
CS_Delete( m_vcCrons[a] );
m_vcCrons.erase( m_vcCrons.begin() + a );
return;
}
}
}
Csock::Csock( int itimeout ) : CSockCommon()
{
#ifdef HAVE_LIBSSL
m_pCerVerifyCB = NULL;
#endif /* HAVE_LIBSSL */
Init( "", 0, itimeout );
}
Csock::Csock( const CS_STRING & sHostname, u_short iport, int itimeout ) : CSockCommon()
{
#ifdef HAVE_LIBSSL
m_pCerVerifyCB = NULL;
#endif /* HAVE_LIBSSL */
Init( sHostname, iport, itimeout );
}
// override this for accept sockets
Csock *Csock::GetSockObj( const CS_STRING & sHostname, u_short iPort )
{
return( NULL );
}
#ifdef _WIN32
#define CS_CLOSE closesocket
#else
#define CS_CLOSE close
#endif /* _WIN32 */
Csock::~Csock()
{
#ifdef HAVE_C_ARES
if( m_pARESChannel )
ares_cancel( m_pARESChannel );
FreeAres();
#endif /* HAVE_C_ARES */
#ifdef HAVE_LIBSSL
FREE_SSL();
FREE_CTX();
#endif /* HAVE_LIBSSL */
CloseSocksFD();
}
void Csock::CloseSocksFD()
{
if ( m_iReadSock != m_iWriteSock )
{
if( m_iReadSock != CS_INVALID_SOCK )
CS_CLOSE( m_iReadSock );
if( m_iWriteSock != CS_INVALID_SOCK )
CS_CLOSE( m_iWriteSock );
} else if( m_iReadSock != CS_INVALID_SOCK )
CS_CLOSE( m_iReadSock );
m_iReadSock = CS_INVALID_SOCK;
m_iWriteSock = CS_INVALID_SOCK;
}
void Csock::Dereference()
{
m_iWriteSock = m_iReadSock = CS_INVALID_SOCK;
#ifdef HAVE_LIBSSL
m_ssl = NULL;
m_ssl_ctx = NULL;
#endif /* HAVE_LIBSSL */
// don't delete and erase, just erase since they were moved to the copied sock
m_vcCrons.clear();
m_vcMonitorFD.clear();
Close( CLT_DEREFERENCE );
}
void Csock::Copy( const Csock & cCopy )
{
m_iTcount = cCopy.m_iTcount;
m_iLastCheckTimeoutTime = cCopy.m_iLastCheckTimeoutTime;
m_uPort = cCopy.m_uPort;
m_iRemotePort = cCopy.m_iRemotePort;
m_iLocalPort = cCopy.m_iLocalPort;
m_iReadSock = cCopy.m_iReadSock;
m_iWriteSock = cCopy.m_iWriteSock;
m_itimeout = cCopy.m_itimeout;
m_iConnType = cCopy.m_iConnType;
m_iMethod = cCopy.m_iMethod;
m_bssl = cCopy.m_bssl;
m_bIsConnected = cCopy.m_bIsConnected;
m_bBLOCK = cCopy.m_bBLOCK;
m_bsslEstablished = cCopy.m_bsslEstablished;
m_bEnableReadLine = cCopy.m_bEnableReadLine;
m_bPauseRead = cCopy.m_bPauseRead;
m_shostname = cCopy.m_shostname;
m_sbuffer = cCopy.m_sbuffer;
m_sSockName = cCopy.m_sSockName;
m_sPemFile = cCopy.m_sPemFile;
m_sCipherType = cCopy.m_sCipherType;
m_sParentName = cCopy.m_sParentName;
m_sSend = cCopy.m_sSend;
m_sPemPass = cCopy.m_sPemPass;
m_sLocalIP = cCopy.m_sLocalIP;
m_sRemoteIP = cCopy.m_sRemoteIP;
m_eCloseType = cCopy.m_eCloseType;
m_iMaxMilliSeconds = cCopy.m_iMaxMilliSeconds;
m_iLastSendTime = cCopy.m_iLastSendTime;
m_iBytesRead = cCopy.m_iBytesRead;
m_iBytesWritten = cCopy.m_iBytesWritten;
m_iStartTime = cCopy.m_iStartTime;
m_iMaxBytes = cCopy.m_iMaxBytes;
m_iLastSend = cCopy.m_iLastSend;
m_iMaxStoredBufferLength = cCopy.m_iMaxStoredBufferLength;
m_iTimeoutType = cCopy.m_iTimeoutType;
m_address = cCopy.m_address;
m_bindhost = cCopy.m_bindhost;
m_bIsIPv6 = cCopy.m_bIsIPv6;
m_bSkipConnect = cCopy.m_bSkipConnect;
#ifdef HAVE_C_ARES
FreeAres(); // Not copying this state, but making sure its nulled out
m_iARESStatus = -1; // set it to unitialized
m_pCurrAddr = NULL;
#endif /* HAVE_C_ARES */
#ifdef HAVE_LIBSSL
m_iRequireClientCertFlags = cCopy.m_iRequireClientCertFlags;
m_sSSLBuffer = cCopy.m_sSSLBuffer;
FREE_SSL();
FREE_CTX(); // be sure to remove anything that was already here
m_ssl = cCopy.m_ssl;
m_ssl_ctx = cCopy.m_ssl_ctx;
m_pCerVerifyCB = cCopy.m_pCerVerifyCB;
#endif /* HAVE_LIBSSL */
CleanupCrons();
CleanupFDMonitors();
m_vcCrons = cCopy.m_vcCrons;
m_vcMonitorFD = cCopy.m_vcMonitorFD;
m_eConState = cCopy.m_eConState;
m_sBindHost = cCopy.m_sBindHost;
m_iCurBindCount = cCopy.m_iCurBindCount;
m_iDNSTryCount = cCopy.m_iDNSTryCount;
}
Csock & Csock::operator<<( const CS_STRING & s )
{
Write( s );
return( *this );
}
Csock & Csock::operator<<( ostream & ( *io )( ostream & ) )
{
Write( "\r\n" );
return( *this );
}
Csock & Csock::operator<<( int i )
{
stringstream s;
s << i;
Write( s.str() );
return( *this );
}
Csock & Csock::operator<<( unsigned int i )
{
stringstream s;
s << i;
Write( s.str() );
return( *this );
}
Csock & Csock::operator<<( long i )
{
stringstream s;
s << i;
Write( s.str() );
return( *this );
}
Csock & Csock::operator<<( unsigned long i )
{
stringstream s;
s << i;
Write( s.str() );
return( *this );
}
Csock & Csock::operator<<( unsigned long long i )
{
stringstream s;
s << i;
Write( s.str() );
return( *this );
}
Csock & Csock::operator<<( float i )
{
stringstream s;
s << i;
Write( s.str() );
return( *this );
}
Csock & Csock::operator<<( double i )
{
stringstream s;
s << i;
Write( s.str() );
return( *this );
}
bool Csock::Connect( const CS_STRING & sBindHost, bool bSkipSetup )
{
if( m_bSkipConnect )
{ // this was already called, so skipping now. this is to allow easy pass through
if ( m_eConState != CST_OK )
{
m_eConState = ( GetSSL() ? CST_CONNECTSSL : CST_OK );
}
return( true );
}
// bind to a hostname if requested
m_sBindHost = sBindHost;
if ( !bSkipSetup )
{
if ( !sBindHost.empty() )
{
// try to bind 3 times, otherwise exit failure
bool bBound = false;
for( int a = 0; a < 3 && !bBound; a++ )
{
if ( SetupVHost() )
bBound = true;
#ifdef _WIN32
Sleep( 5000 );
#else
usleep( 5000 ); // quick pause, common lets BIND!)(!*!
#endif /* _WIN32 */
}
if ( !bBound )
{
CS_DEBUG( "Failure to bind to " << sBindHost );
return( false );
}
}
int iDNSRet = ETIMEDOUT;
while( true )
{
iDNSRet = DNSLookup( DNS_VHOST );
if ( iDNSRet == EAGAIN )
continue;