-
Notifications
You must be signed in to change notification settings - Fork 22
/
Csocket.cc
4353 lines (3831 loc) · 109 KB
/
Csocket.cc
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 Csocket.cc
* @author Jim Hull <csocket@jimloco.com>
*
* Copyright (c) 1999-2012 Jim Hull <csocket@jimloco.com>
* 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.
*/
/***
* doing this because there seems to be a bug that is losing the "short" on htons when in optimize mode turns into a macro
* gcc 4.3.4
*/
#if defined(__OPTIMIZE__) && __GNUC__ == 4 && __GNUC_MINOR__ >= 3
#pragma GCC diagnostic warning "-Wconversion"
#endif /* defined(__OPTIMIZE__) && __GNUC__ == 4 && __GNUC_MINOR__ >= 3 */
#include "Csocket.h"
#ifdef __NetBSD__
#include <sys/param.h>
#endif /* __NetBSD__ */
#ifdef HAVE_LIBSSL
#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/conf.h>
#include <openssl/engine.h>
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
#include <openssl/core_names.h>
#endif /* OPENSSL_VERSION_NUMBER >= 0x30000000L */
#ifndef OPENSSL_NO_COMP
#include <openssl/comp.h>
#endif
#define HAVE_ERR_REMOVE_STATE
#ifdef OPENSSL_VERSION_NUMBER
# if OPENSSL_VERSION_NUMBER >= 0x10000000
# undef HAVE_ERR_REMOVE_STATE
# define HAVE_ERR_REMOVE_THREAD_STATE
# endif
# if OPENSSL_VERSION_NUMBER < 0x10001000
# define OPENSSL_NO_TLS1_1 /* 1.0.1-pre~: openssl/openssl@637f374ad49d5f6d4f81d87d7cdd226428aa470c */
# define OPENSSL_NO_TLS1_2 /* 1.0.1-pre~: openssl/openssl@7409d7ad517650db332ae528915a570e4e0ab88b */
# endif
# ifndef LIBRESSL_VERSION_NUMBER /* forked from OpenSSL 1.0.1g, sets high version "with the idea of discouraging software from relying on magic numbers for detecting features"(!) */
# if OPENSSL_VERSION_NUMBER >= 0x10100000
# undef HAVE_ERR_REMOVE_THREAD_STATE /* 1.1.0-pre4: openssl/openssl@8509dcc9f319190c565ab6baad7c88d37a951d1c */
# undef OPENSSL_NO_SSL2 /* 1.1.0-pre4: openssl/openssl@e80381e1a3309f5d4a783bcaa508a90187a48882 */
# define OPENSSL_NO_SSL2 /* 1.1.0-pre1: openssl/openssl@45f55f6a5bdcec411ef08a6f8aae41d5d3d234ad */
# define HAVE_FLEXIBLE_TLS_METHOD /* 1.1.0-pre1: openssl/openssl@32ec41539b5b23bc42503589fcc5be65d648d1f5 */
# define HAVE_OPAQUE_SSL
# endif
# endif /* LIBRESSL_VERSION_NUMBER */
#endif /* OPENSSL_VERSION_NUMBER */
#endif /* HAVE_LIBSSL */
#ifdef HAVE_ICU
#include <unicode/ustring.h>
#include <unicode/errorcode.h>
#include <unicode/ucnv_cb.h>
#endif /* HAVE_ICU */
#include <list>
#include <algorithm>
#define CS_SRANDBUFFER 128
/*
* timeradd/timersub is missing on solaris' sys/time.h, provide
* some fallback macros
*/
#ifndef timeradd
#define timeradd(a, b, result) \
do { \
(result)->tv_sec = (a)->tv_sec + (b)->tv_sec; \
(result)->tv_usec = (a)->tv_usec + (b)->tv_usec; \
if ((result)->tv_usec >= 1000000) { \
++(result)->tv_sec; \
(result)->tv_usec -= 1000000; \
} \
} while (0)
#endif
#ifndef timersub
#define timersub(a, b, result) \
do { \
(result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
(result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
if ((result)->tv_usec < 0) { \
--(result)->tv_sec; \
(result)->tv_usec += 1000000; \
} \
} while (0)
#endif
using std::stringstream;
using std::ostream;
using std::endl;
using std::min;
using std::vector;
#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 s_iCsockSSLIdx = 0; //!< this gets setup once in InitSSL
int GetCsockSSLIdx()
{
return( s_iCsockSSLIdx );
}
#ifdef _WIN32
#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 );
}
/*
* not used by anything anymore
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 // _WIN32
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 );
}
/*
* not used by anything anymore
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 */
void CSSockAddr::SinFamily()
{
#ifdef HAVE_IPV6
m_saddr6.sin6_family = PF_INET6;
#endif /* HAVE_IPV6 */
m_saddr.sin_family = PF_INET;
}
void CSSockAddr::SinPort( uint16_t iPort )
{
#ifdef HAVE_IPV6
m_saddr6.sin6_port = htons( iPort );
#endif /* HAVE_IPV6 */
m_saddr.sin_port = htons( iPort );
}
void CSSockAddr::SetIPv6( bool b )
{
#ifndef HAVE_IPV6
if( b )
{
CS_DEBUG( "-DHAVE_IPV6 must be set during compile time to enable this feature" );
m_bIsIPv6 = false;
return;
}
#endif /* HAVE_IPV6 */
m_bIsIPv6 = b;
SinFamily();
}
#ifdef HAVE_LIBSSL
static int _PemPassCB( char *pBuff, int iBuffLen, int rwflag, void * pcSocket )
{
Csock * pSock = static_cast<Csock *>( pcSocket );
const CS_STRING & sPassword = pSock->GetPemPass();
if( iBuffLen <= 0 )
return( 0 );
memset( pBuff, '\0', iBuffLen );
if( sPassword.empty() )
return( 0 );
int iUseBytes = min( iBuffLen - 1, ( int )sPassword.length() );
memcpy( pBuff, sPassword.data(), iUseBytes );
return( iUseBytes );
}
static int _CertVerifyCB( int preverify_ok, X509_STORE_CTX *x509_ctx )
{
Csock * pSock = GetCsockFromCTX( x509_ctx );
if( pSock )
return( pSock->VerifyPeerCertificate( preverify_ok, x509_ctx ) );
return( preverify_ok );
}
static void _InfoCallback( const SSL * pSSL, int where, int ret )
{
if( ( where & SSL_CB_HANDSHAKE_DONE ) && ret != 0 )
{
Csock * pSock = static_cast<Csock *>( SSL_get_ex_data( pSSL, GetCsockSSLIdx() ) );
if( pSock )
pSock->SSLHandShakeFinished();
}
}
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, GetCsockSSLIdx() );
return( pSock );
}
#endif /* HAVE_LIBSSL */
#ifdef USE_GETHOSTBYNAME
// 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 /* !USE_GETHOSTBYNAME */
#ifdef HAVE_C_ARES
void Csock::FreeAres()
{
if( m_pARESChannel )
{
ares_destroy( m_pARESChannel );
m_pARESChannel = NULL;
}
}
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 */
CGetAddrInfo::CGetAddrInfo( const CS_STRING & sHostname, Csock * pSock, CSSockAddr & csSockAddr )
: m_pSock( pSock ), m_csSockAddr( csSockAddr )
{
m_sHostname = sHostname;
m_pAddrRes = NULL;
m_iRet = ETIMEDOUT;
}
CGetAddrInfo::~CGetAddrInfo()
{
if( m_pAddrRes )
freeaddrinfo( m_pAddrRes );
m_pAddrRes = NULL;
}
void CGetAddrInfo::Init()
{
memset( ( struct addrinfo * )&m_cHints, '\0', sizeof( m_cHints ) );
m_cHints.ai_family = m_csSockAddr.GetAFRequire();
m_cHints.ai_socktype = SOCK_STREAM;
m_cHints.ai_protocol = IPPROTO_TCP;
#ifdef AI_ADDRCONFIG
// this is suppose to eliminate host from appearing that this system can not support
m_cHints.ai_flags = AI_ADDRCONFIG;
#endif /* AI_ADDRCONFIG */
if( m_pSock && ( m_pSock->GetType() == Csock::LISTENER || m_pSock->GetConState() == Csock::CST_BINDVHOST ) )
{
// when doing a dns for bind only, set the AI_PASSIVE flag as suggested by the man page
m_cHints.ai_flags |= AI_PASSIVE;
}
}
int CGetAddrInfo::Process()
{
m_iRet = getaddrinfo( m_sHostname.c_str(), NULL, &m_cHints, &m_pAddrRes );
if( m_iRet == EAI_AGAIN )
return( EAGAIN );
else if( m_iRet == 0 )
return( 0 );
return( ETIMEDOUT );
}
int CGetAddrInfo::Finish()
{
if( m_iRet == 0 && m_pAddrRes )
{
std::list<struct addrinfo *> lpTryAddrs;
bool bFound = false;
for( struct addrinfo * pRes = m_pAddrRes; 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( ( m_csSockAddr.GetAFRequire() != CSSockAddr::RAF_ANY ) && ( pRes->ai_family != m_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( m_pSock )
m_pSock->SetIPv6( false );
m_csSockAddr.SetIPv6( false );
struct sockaddr_in * pTmp = ( struct sockaddr_in * )pRes->ai_addr;
memcpy( m_csSockAddr.GetAddr(), &( pTmp->sin_addr ), sizeof( *( m_csSockAddr.GetAddr() ) ) );
if( m_pSock && m_pSock->GetConState() == Csock::CST_DESTDNS && m_pSock->GetType() == Csock::OUTBOUND )
{
bTryConnect = true;
}
else
{
bFound = true;
break;
}
}
#ifdef HAVE_IPV6
else if( pRes->ai_family == AF_INET6 )
{
if( m_pSock )
m_pSock->SetIPv6( true );
m_csSockAddr.SetIPv6( true );
struct sockaddr_in6 * pTmp = ( struct sockaddr_in6 * )pRes->ai_addr;
memcpy( m_csSockAddr.GetAddr6(), &( pTmp->sin6_addr ), sizeof( *( m_csSockAddr.GetAddr6() ) ) );
if( m_pSock && m_pSock->GetConState() == Csock::CST_DESTDNS && m_pSock->GetType() == Csock::OUTBOUND )
{
bTryConnect = true;
}
else
{
bFound = true;
break;
}
}
#endif /* HAVE_IPV6 */
++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( m_pSock->CreateSocksFD() && m_pSock->Connect() )
{
m_pSock->SetSkipConnect( true ); // this tells the socket that the connection state has been started
bFound = true;
break;
}
m_pSock->CloseSocksFD();
}
else if( bTryConnect )
{
bFound = true;
}
}
if( bFound ) // the data pointed to here is invalid now, but the pointer itself is a good test
{
return( 0 );
}
}
return( ETIMEDOUT );
}
int CS_GetAddrInfo( const CS_STRING & sHostname, Csock * pSock, CSSockAddr & csSockAddr )
{
#ifdef USE_GETHOSTBYNAME
if( pSock )
pSock->SetIPv6( false );
csSockAddr.SetIPv6( false );
int iRet = __GetHostByName( sHostname, csSockAddr.GetAddr(), 3 );
return( iRet );
#else
CGetAddrInfo cInfo( sHostname, pSock, csSockAddr );
cInfo.Init();
int iRet = cInfo.Process();
if( iRet != 0 )
return( iRet );
return( cInfo.Finish() );
#endif /* USE_GETHOSTBYNAME */
}
int Csock::ConvertAddress( const struct sockaddr_storage * pAddr, socklen_t iAddrLen, CS_STRING & sIP, uint16_t * piPort ) const
{
char szHostname[NI_MAXHOST];
char szServ[NI_MAXSERV];
int iRet = getnameinfo( ( const struct sockaddr * )pAddr, iAddrLen, szHostname, NI_MAXHOST, szServ, NI_MAXSERV, NI_NUMERICHOST|NI_NUMERICSERV );
if( iRet == 0 )
{
sIP = szHostname;
if( piPort )
*piPort = ( uint16_t )atoi( szServ );
}
return( iRet );
}
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
#if defined( HAVE_ERR_REMOVE_THREAD_STATE )
ERR_remove_thread_state( NULL );
#elif defined( HAVE_ERR_REMOVE_STATE )
ERR_remove_state( 0 );
#endif
#ifndef OPENSSL_NO_ENGINE
ENGINE_cleanup();
#endif
#ifndef OPENSSL_IS_BORINGSSL
CONF_modules_unload( 1 );
#endif
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 */
#ifndef OPENSSL_NO_COMP
COMP_METHOD *cm = NULL;
if( CT_ZLIB & eCompressionType )
{
cm = COMP_zlib();
if( cm )
SSL_COMP_add_compression_method( CT_ZLIB, cm );
}
#endif
// setting this up once in the begining
s_iCsockSSLIdx = SSL_get_ex_new_index( 0, NULL, NULL, NULL, NULL );
return( true );
}
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 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;
}
}
}
#define CS_UNKNOWN_ERROR "Unknown Error"
static const char * CS_StrError( int iErrno, char * pszBuff, size_t uBuffLen )
{
#if defined( sgi ) || defined(__sun) || (defined(__NetBSD_Version__) && __NetBSD_Version__ < 4000000000)
return( strerror( iErrno ) );
#else
memset( pszBuff, '\0', uBuffLen );
#if defined( _WIN32 )
if ( strerror_s( pszBuff, uBuffLen, iErrno ) == 0 )
return( pszBuff );
#elif !defined( _GNU_SOURCE ) || !defined(__GLIBC__) || defined( __FreeBSD__ )
if( strerror_r( iErrno, pszBuff, uBuffLen ) == 0 )
return( pszBuff );
#else
return( strerror_r( iErrno, pszBuff, uBuffLen ) );
#endif /* (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !defined( _GNU_SOURCE ) */
#endif /* defined( sgi ) || defined(__sun) || defined(_WIN32) || (defined(__NetBSD_Version__) && __NetBSD_Version__ < 4000000000) */
return( CS_UNKNOWN_ERROR );
}
void __Perror( const CS_STRING & s, const char * pszFile, u_int iLineNo )
{
char szBuff[0xff];
std::cerr << s << "(" << pszFile << ":" << iLineNo << "): " << CS_StrError( GetSockError(), szBuff, 0xff ) << endl;
}
uint64_t millitime()
{
uint64_t iTime = 0;
#ifdef _WIN32
struct timeb tm;
ftime( &tm );
iTime = tm.time * 1000;
iTime += tm.millitm;
#else
struct timeval tv;
gettimeofday( &tv, NULL );
iTime = ( uint64_t )tv.tv_sec * 1000;
iTime += ( ( uint64_t )tv.tv_usec / 1000 );
#endif /* _WIN32 */
return( iTime );
}
#ifndef _MSC_VER
#define CS_GETTIMEOFDAY gettimeofday
#else
#define CS_GETTIMEOFDAY win32_gettimeofday
// timezone-agnostic implementation of gettimeofday
static int
win32_gettimeofday( struct timeval* now, void* )
{
static const ULONGLONG epoch = 116444736000000000ULL; // Jan 1st 1970
ULARGE_INTEGER file_time;
SYSTEMTIME system_time;
GetSystemTime( &system_time );
if ( !SystemTimeToFileTime( &system_time, ( LPFILETIME )&file_time) )
return( 1 );
now->tv_sec = ( long )( ( file_time.QuadPart - epoch ) / 10000000L );
now->tv_usec = ( long )( system_time.wMilliseconds * 1000 );
return 0;
}
#endif
#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;
timerclear( &m_tTime );
m_tTimeSequence.tv_sec = 60;
m_tTimeSequence.tv_usec = 0;
m_bPause = false;
m_bRunOnNextCall = false;
}
void CCron::run( timeval & tNow )
{
if( m_bPause )
return;
if( !timerisset( &tNow ) )
CS_GETTIMEOFDAY( &tNow, NULL );
if( m_bActive && ( !timercmp( &tNow, &m_tTime, < ) || 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
timeradd( &tNow, &m_tTimeSequence, &m_tTime );
}
}
void CCron::StartMaxCycles( double dTimeSequence, u_int iMaxCycles )
{
timeval tNow;
m_tTimeSequence.tv_sec = ( time_t ) dTimeSequence;
// this could be done with modf(), but we're avoiding bringing in libm just for the one function.
m_tTimeSequence.tv_usec = ( suseconds_t )( ( dTimeSequence - ( double )( ( time_t ) dTimeSequence ) ) * 1000000 );
CS_GETTIMEOFDAY( &tNow, NULL );
timeradd( &tNow, &m_tTimeSequence, &m_tTime );
m_iMaxCycles = iMaxCycles;
m_bActive = true;
}
void CCron::StartMaxCycles( const timeval& tTimeSequence, u_int iMaxCycles )
{
timeval tNow;
m_tTimeSequence = tTimeSequence;
CS_GETTIMEOFDAY( &tNow, NULL );
timeradd( &tNow, &m_tTimeSequence, &m_tTime );
m_iMaxCycles = iMaxCycles;
m_bActive = true;
}
void CCron::Start( double dTimeSequence )
{
StartMaxCycles( dTimeSequence, 0 );
}
void CCron::Start( const timeval& tTimeSequence )
{
StartMaxCycles( tTimeSequence, 0 );
}
void CCron::Stop()
{
m_bActive = false;
}
void CCron::Pause()
{
m_bPause = true;
}
void CCron::UnPause()
{
m_bPause = false;
}
void CCron::Reset()
{
Stop();
Start(m_tTimeSequence);
}
timeval CCron::GetInterval() const { return( m_tTimeSequence ); }
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() const { 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< cs_sock_t, short > & miiReadyFds, long & iTimeoutMS )
{
iTimeoutMS = -1; // don't bother changing anything in the default implementation
for( std::map< cs_sock_t, 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< cs_sock_t, short > & miiReadyFds )
{
std::map< cs_sock_t, short > miiTriggerdFds;
for( std::map< cs_sock_t, short >::iterator it = m_miiMonitorFDs.begin(); it != m_miiMonitorFDs.end(); ++it )
{
std::map< cs_sock_t, short >::const_iterator itFD = miiReadyFds.find( it->first );
if( itFD != miiReadyFds.end() )
miiTriggerdFds[itFD->first] = itFD->second;
}
if( !miiTriggerdFds.empty() )
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< cs_sock_t, 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< cs_sock_t, 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()
{
timeval tNow;
timerclear( &tNow );
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( tNow );
}
}
}
void CSockCommon::AddCron( CCron * pcCron )
{
m_vcCrons.push_back( pcCron );
}
void CSockCommon::DelCron( const CS_STRING & sName, bool bDeleteAll, bool bCaseSensitive )
{
for( size_t 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( size_t 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 = _CertVerifyCB;
#endif /* HAVE_LIBSSL */
Init( "", 0, iTimeout );
}
Csock::Csock( const CS_STRING & sHostname, uint16_t iport, int iTimeout ) : CSockCommon()
{