forked from jimloco/Csocket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Csocket.h
1670 lines (1418 loc) · 55.6 KB
/
Csocket.h
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.h
* @author Jim Hull <[email protected]>
*
* Copyright (c) 1999-2012 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.
*/
/*
* NOTES ...
* - You should always compile with -Woverloaded-virtual to detect callbacks that may have been redefined since your last update
* - If you want to use gethostbyname instead of getaddrinfo, the use -DUSE_GETHOSTBYNAME when compiling
* - To compile with win32 need to link to winsock2, using gcc its -lws2_32
* - Code is formated with 'astyle --style=ansi -t4 --unpad-paren --pad-paren-in --keep-one-line-blocks'
*/
#ifndef _HAS_CSOCKET_
#define _HAS_CSOCKET_
#include "defines.h" // require this as a general rule, most projects have a defines.h or the like
#include <stdio.h>
#include <fcntl.h>
#ifndef _WIN32
#include <unistd.h>
#include <sys/time.h>
#include <sys/file.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netdb.h>
#include <sys/select.h>
#else
#include <io.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <time.h>
#include <sys/timeb.h>
#ifdef _MSC_VER
#define strcasecmp _stricmp
#define suseconds_t long
#endif
#ifndef ECONNREFUSED
// these aliases might or might not be defined in errno.h
// already, depending on the WinSDK version.
#define ECONNREFUSED WSAECONNREFUSED
#define EINPROGRESS WSAEINPROGRESS
#define ETIMEDOUT WSAETIMEDOUT
#define EADDRNOTAVAIL WSAEADDRNOTAVAIL
#define ECONNABORTED WSAECONNABORTED
#define ENETUNREACH WSAENETUNREACH
#endif /* ECONNREFUSED */
#endif /* _WIN32 */
#ifdef HAVE_C_ARES
#include <ares.h>
#endif /* HAVE_C_ARES */
#ifdef HAVE_ICU
# include <unicode/ucnv.h>
#endif
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#ifdef HAVE_LIBSSL
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#endif /* HAVE_LIBSSL */
#ifdef __sun
#include <strings.h>
#include <fcntl.h>
#endif /* __sun */
#include <vector>
#include <list>
#include <iostream>
#include <sstream>
#include <string>
#include <set>
#include <map>
#ifndef CS_STRING
# ifdef _HAS_CSTRING_
# define CS_STRING Cstring
# else
# define CS_STRING std::string
# endif /* _HAS_CSTRING_ */
#endif /* CS_STRING */
#ifndef CS_DEBUG
#ifdef __DEBUG__
# define CS_DEBUG( f ) std::cerr << __FILE__ << ":" << __LINE__ << " " << f << std::endl
#else
# define CS_DEBUG(f) (void)0
#endif /* __DEBUG__ */
#endif /* CS_DEBUG */
#ifndef CS_EXPORT
#define CS_EXPORT
#endif /* CS_EXPORT */
#ifndef PERROR
#ifdef __DEBUG__
# define PERROR( f ) __Perror( f, __FILE__, __LINE__ )
#else
# define PERROR( f ) (void)0
#endif /* __DEBUG__ */
#endif /* PERROR */
#ifdef _WIN32
typedef SOCKET cs_sock_t;
#ifdef _WIN64
typedef signed __int64 cs_ssize_t;
#else
typedef signed int cs_ssize_t;
#endif /* _WIN64 */
#define CS_INVALID_SOCK INVALID_SOCKET
#else
typedef int cs_sock_t;
typedef ssize_t cs_ssize_t;
#define CS_INVALID_SOCK -1
#endif /* _WIN32 */
/* Assume that everything but windows has Unix sockets */
#ifndef _WIN32
#define HAVE_UNIX_SOCKET
#endif
#ifdef CSOCK_USE_POLL
#include <poll.h>
#endif /* CSOCK_USE_POLL */
#ifdef HAVE_UNIX_SOCKET
#include <sys/un.h>
#endif
#ifndef _NO_CSOCKET_NS // some people may not want to use a namespace
namespace Csocket
{
#endif /* _NO_CSOCKET_NS */
/**
* @class CSCharBuffer
* @brief Ease of use self deleting char * class.
*/
class CS_EXPORT CSCharBuffer
{
public:
CSCharBuffer( size_t iSize )
{
m_pBuffer = ( char * )malloc( iSize );
}
~CSCharBuffer()
{
free( m_pBuffer );
}
char * operator()() { return( m_pBuffer ); }
private:
char * m_pBuffer;
};
/**
* @class CSSockAddr
* @brief sockaddr wrapper.
*/
class CS_EXPORT CSSockAddr
{
public:
CSSockAddr()
{
m_bIsIPv6 = false;
memset( ( struct sockaddr_in * ) &m_saddr, '\0', sizeof( m_saddr ) );
#ifdef HAVE_IPV6
memset( ( struct sockaddr_in6 * ) &m_saddr6, '\0', sizeof( m_saddr6 ) );
#endif /* HAVE_IPV6 */
m_iAFRequire = RAF_ANY;
}
virtual ~CSSockAddr() {}
enum EAFRequire
{
RAF_ANY = PF_UNSPEC,
#ifdef HAVE_IPV6
RAF_INET6 = AF_INET6,
#endif /* HAVE_IPV6 */
RAF_INET = AF_INET
};
void SinFamily();
void SinPort( uint16_t iPort );
void SetIPv6( bool b );
bool GetIPv6() const { return( m_bIsIPv6 ); }
socklen_t GetSockAddrLen() { return( sizeof( m_saddr ) ); }
sockaddr_in * GetSockAddr() { return( &m_saddr ); }
in_addr * GetAddr() { return( &( m_saddr.sin_addr ) ); }
#ifdef HAVE_IPV6
socklen_t GetSockAddrLen6() { return( sizeof( m_saddr6 ) ); }
sockaddr_in6 * GetSockAddr6() { return( &m_saddr6 ); }
in6_addr * GetAddr6() { return( &( m_saddr6.sin6_addr ) ); }
#endif /* HAVE_IPV6 */
void SetAFRequire( EAFRequire iWhich ) { m_iAFRequire = iWhich; }
EAFRequire GetAFRequire() const { return( m_iAFRequire ); }
private:
bool m_bIsIPv6;
sockaddr_in m_saddr;
#ifdef HAVE_IPV6
sockaddr_in6 m_saddr6;
#endif /* HAVE_IPV6 */
EAFRequire m_iAFRequire;
};
class Csock;
/**
* @class CGetAddrInfo
* @brief this function is a wrapper around getaddrinfo (for ipv6)
*
* in the event this code is using ipv6, it calls getaddrinfo, and it tries to start the connection on each iteration
* in the linked list returned by getaddrinfo. if pSock is not NULL the following behavior happens.
* - if pSock is a listener, or if the connect state is in a bind vhost state (to be used with bind) AI_PASSIVE is sent to getaddrinfo
* - if pSock is an outbound connection, AI_ADDRCONFIG and the connection is started from within this function.
* getaddrinfo might return multiple (possibly invalid depending on system configuration) ip addresses, so connect needs to try them all.
* A classic example of this is a hostname that resolves to both ipv4 and ipv6 ip's. You still need to call Connect (and ConnectSSL) to finish
* up the connection state
*
* Process can be called in a thread, but Init and Finish must only be called from the parent once the thread is complete
*/
class CS_EXPORT CGetAddrInfo
{
public:
/**
* @brief ctor
* @param sHostname the host to resolve
* @param pSock the sock being setup, this option can be NULL, if it is null csSockAddr is only setup
* @param csSockAddr the struct that sockaddr data is being copied to
*/
CGetAddrInfo( const CS_STRING & sHostname, Csock * pSock, CSSockAddr & csSockAddr );
~CGetAddrInfo();
//! simply sets up m_cHints for use in process
void Init();
//! the simplest part of the function, only calls getaddrinfo and uses only m_sHostname, m_pAddrRes, and m_cHints.
int Process();
//! finalizes and sets up csSockAddr (and pSock if not NULL), only needs to be called if Process returns 0, but can be called anyways if flow demands it
int Finish();
private:
CS_STRING m_sHostname;
Csock * m_pSock;
CSSockAddr & m_csSockAddr;
struct addrinfo * m_pAddrRes;
struct addrinfo m_cHints;
int m_iRet;
};
//! backwards compatible wrapper around CGetAddrInfo and gethostbyname
int CS_GetAddrInfo( const CS_STRING & sHostname, Csock * pSock, CSSockAddr & csSockAddr );
/**
* This returns the [ex_]data index position for SSL objects only. If you want to tie more data
* to the SSL object, you should generate your own at application start so as to avoid collision
* with Csocket SSL_set_ex_data()
*/
int GetCsockSSLIdx();
#ifdef HAVE_LIBSSL
//! returns the sock object associated to the particular context. returns NULL on failure or if not available
Csock * GetCsockFromCTX( X509_STORE_CTX * pCTX );
#endif /* HAVE_LIBSSL */
const uint32_t CS_BLOCKSIZE = 4096;
template <class T> inline void CS_Delete( T * & p ) { if( p ) { delete p; p = NULL; } }
#ifdef HAVE_LIBSSL
enum ECompType
{
CT_NONE = 0,
CT_ZLIB = 1
};
//! adjusts tv with a new timeout if iTimeoutMS is smaller
void CSAdjustTVTimeout( struct timeval & tv, long iTimeoutMS );
void SSLErrors( const char *filename, uint32_t iLineNum );
/**
* @brief You HAVE to call this in order to use the SSL library, calling InitCsocket() also calls this
* so unless you need to call InitSSL for a specific reason call InitCsocket()
* @return true on success
*/
bool InitSSL( ECompType eCompressionType = CT_NONE );
#endif /* HAVE_LIBSSL */
/**
* This does all the csocket initialized inclusing InitSSL() and win32 specific initializations, only needs to be called once
*/
bool InitCsocket();
/**
* Shutdown and release global allocated memory
*/
void ShutdownCsocket();
//! @todo need to make this sock specific via getsockopt
inline int GetSockError()
{
#ifdef _WIN32
return( WSAGetLastError() );
#else
return( errno );
#endif /* _WIN32 */
}
//! wrappers for FD_SET and such to work in templates.
inline void TFD_ZERO( fd_set *set )
{
FD_ZERO( set );
}
inline void TFD_SET( cs_sock_t iSock, fd_set *set )
{
FD_SET( iSock, set );
}
inline bool TFD_ISSET( cs_sock_t iSock, fd_set *set )
{
return( FD_ISSET( iSock, set ) != 0 );
}
inline void TFD_CLR( cs_sock_t iSock, fd_set *set )
{
FD_CLR( iSock, set );
}
void __Perror( const CS_STRING & s, const char * pszFile, uint32_t iLineNo );
/**
* @class CCron
* @brief this is the main cron job class
*
* You should derive from this class, and override RunJob() with your code
* @author Jim Hull <[email protected]>
*/
class CS_EXPORT CCron
{
public:
CCron();
virtual ~CCron() {}
//! This is used by the Job Manager, and not you directly
void run( timeval & tNow );
/**
* @param TimeSequence how often to run in seconds
* @param iMaxCycles how many times to run, 0 makes it run forever
*/
void StartMaxCycles( double dTimeSequence, uint32_t iMaxCycles );
void StartMaxCycles( const timeval& tTimeSequence, uint32_t iMaxCycles );
//! starts and runs infinity amount of times
void Start( double dTimeSequence );
void Start( const timeval& TimeSequence );
//! call this to turn off your cron, it will be removed
void Stop();
//! pauses excution of your code in RunJob
void Pause();
//! removes the pause on RunJon
void UnPause();
//! reset the timer
void Reset();
timeval GetInterval() const;
uint32_t GetMaxCycles() const;
uint32_t GetCyclesLeft() const;
//! returns true if cron is active
bool isValid() const;
const CS_STRING & GetName() const;
void SetName( const CS_STRING & sName );
//! returns the timestamp of the next estimated run time. Note that it may not run at this EXACT time, but it will run at least at this time or after
timeval GetNextRun() const { return( m_tTime ); }
public:
//! this is the method you should override
virtual void RunJob();
protected:
bool m_bRunOnNextCall; //!< if set to true, RunJob() gets called on next invocation of run() despite the timeout
private:
timeval m_tTime;
bool m_bActive, m_bPause;
timeval m_tTimeSequence;
uint32_t m_iMaxCycles, m_iCycles;
CS_STRING m_sName;
};
/**
* @class CSMonitorFD
* @brief Class to tie sockets to for monitoring by Csocket at either the Csock or TSockManager.
*/
class CS_EXPORT CSMonitorFD
{
public:
CSMonitorFD() { m_bEnabled = true; }
virtual ~CSMonitorFD() {}
/**
* @brief called before select, typically you don't need to reimplement this just add sockets via Add and let the default implementation have its way
* @param miiReadyFds fill with fd's to monitor and the associated bit to check them for (@see CSockManager::ECheckType)
* @param iTimeoutMS the timeout to change to, setting this to -1 (the default)
* @return returning false will remove this from monitoring. The same effect can be had by setting m_bEnabled to false as it is returned from this
*/
virtual bool GatherFDsForSelect( std::map< cs_sock_t, short > & miiReadyFds, long & iTimeoutMS );
/**
* @brief called when there are fd's belonging to this class that have triggered
* @param miiReadyFds the map of fd's with the bits that triggered them (@see CSockManager::ECheckType)
* @return returning false will remove this from monitoring
*/
virtual bool FDsThatTriggered( const std::map< cs_sock_t, short > & miiReadyFds ) { return( true ); }
/**
* @brief gets called to diff miiReadyFds with m_miiMonitorFDs, and calls FDsThatTriggered when appropriate. Typically you don't need to reimplement this.
* @param miiReadyFds the map of all triggered fd's, not just the fd's from this class
* @return returning false will remove this from monitoring
*/
virtual bool CheckFDs( const std::map< cs_sock_t, short > & miiReadyFds );
/**
* @brief adds a file descriptor to be monitored
* @param iFD the file descriptor
* @param iMonitorEvents bitset of events to monitor for (@see CSockManager::ECheckType)
*/
void Add( cs_sock_t iFD, short iMonitorEvents ) { m_miiMonitorFDs[iFD] = iMonitorEvents; }
//! removes this fd from monitoring
void Remove( cs_sock_t iFD ) { m_miiMonitorFDs.erase( iFD ); }
//! causes this monitor to be removed
void DisableMonitor() { m_bEnabled = false; }
bool IsEnabled() const { return( m_bEnabled ); }
protected:
std::map< cs_sock_t, short > m_miiMonitorFDs;
bool m_bEnabled;
};
/**
* @class CSockCommon
* @brief simple class to share common code to both TSockManager and Csock
*/
class CS_EXPORT CSockCommon
{
public:
CSockCommon() {}
virtual ~CSockCommon();
void CleanupCrons();
void CleanupFDMonitors();
//! returns a const reference to the crons associated to this socket
const std::vector<CCron *> & GetCrons() const { return( m_vcCrons ); }
//! This has a garbage collecter, and is used internall to call the jobs
virtual void Cron();
//! insert a newly created cron
virtual void AddCron( CCron * pcCron );
/**
* @brief deletes a cron by name
* @param sName the name of the cron
* @param bDeleteAll delete all crons that match sName
* @param bCaseSensitive use strcmp or strcasecmp
*/
virtual void DelCron( const CS_STRING & sName, bool bDeleteAll = true, bool bCaseSensitive = true );
//! delete cron by idx
virtual void DelCron( uint32_t iPos );
//! delete cron by address
virtual void DelCronByAddr( CCron * pcCron );
void CheckFDs( const std::map< cs_sock_t, short > & miiReadyFds );
void AssignFDs( std::map< cs_sock_t, short > & miiReadyFds, struct timeval * tvtimeout );
//! add an FD set to monitor
void MonitorFD( CSMonitorFD * pMonitorFD ) { m_vcMonitorFD.push_back( pMonitorFD ); }
protected:
std::vector<CCron *> m_vcCrons;
std::vector<CSMonitorFD *> m_vcMonitorFD;
};
#ifdef HAVE_LIBSSL
typedef int ( *FPCertVerifyCB )( int, X509_STORE_CTX * );
#endif /* HAVE_LIBSSL */
/**
* @class Csock
* @brief Basic socket class.
*
* The most basic level socket class.
* You can use this class directly for quick things
* or use the socket manager.
* @see TSocketManager
* @author Jim Hull <[email protected]>
*/
class CS_EXPORT Csock : public CSockCommon
{
public:
//! default constructor, sets a timeout of 60 seconds
Csock( int iTimeout = 60 );
/**
* @brief Advanced constructor, for creating a simple connection
* @param sHostname the hostname your are connecting to
* @param uPort the port you are connecting to
* @param itimeout how long to wait before ditching the connection, default is 60 seconds
*/
Csock( const CS_STRING & sHostname, uint16_t uPort, int itimeout = 60 );
//! override this for accept sockets
virtual Csock *GetSockObj( const CS_STRING & sHostname, uint16_t iPort );
virtual ~Csock();
/**
* @brief in the event you pass this class to Copy(), you MUST call this function or
* on the original Csock other wise bad side effects will happen (double deletes, weird sock closures, etc)
* if you call this function and have not handled the internal pointers, other bad things can happend (memory leaks, fd leaks, etc)
* the whole point of this function is to allow this class to go away without shutting down
*/
virtual void Dereference();
//! use this to copy a sock from one to the other, override it if you have special needs in the event of a copy
virtual void Copy( const Csock & cCopy );
enum ETConn
{
OUTBOUND = 0, //!< outbound connection
LISTENER = 1, //!< a socket accepting connections
INBOUND = 2 //!< an inbound connection, passed from LISTENER
};
enum EFRead
{
READ_EOF = 0, //!< End Of File, done reading
READ_ERR = -1, //!< Error on the socket, socket closed, done reading
READ_EAGAIN = -2, //!< Try to get data again
READ_CONNREFUSED = -3, //!< Connection Refused
READ_TIMEDOUT = -4 //!< Connection timed out
};
enum EFSelect
{
SEL_OK = 0, //!< Select passed ok
SEL_TIMEOUT = -1, //!< Select timed out
SEL_EAGAIN = -2, //!< Select wants you to try again
SEL_ERR = -3 //!< Select recieved an error
};
enum ESSLMethod
{
TLS = 0,
SSL23 = TLS,
SSL2 = 2,
SSL3 = 3,
TLS1 = 4,
TLS11 = 5,
TLS12 = 6
};
enum EDisableProtocol
{
EDP_None = 0, //!< disable nothing
EDP_SSLv2 = 1, //!< disable SSL version 2
EDP_SSLv3 = 2, //!< disable SSL version 3
EDP_TLSv1 = 4, //!< disable TLS version 1
EDP_TLSv1_1 = 8, //!< disable TLS version 1.1
EDP_TLSv1_2 = 16, //!< disable TLS version 1.2
EDP_SSL = (EDP_SSLv2|EDP_SSLv3)
};
enum ECONState
{
CST_START = 0,
CST_DNS = CST_START,
CST_BINDVHOST = 1,
CST_DESTDNS = 2,
CST_CONNECT = 3,
CST_CONNECTSSL = 4,
CST_OK = 5
};
enum ECloseType
{
CLT_DONT = 0, //!< don't close DER
CLT_NOW = 1, //!< close immediatly
CLT_AFTERWRITE = 2, //!< close after finishing writing the buffer
CLT_DEREFERENCE = 3 //!< used after copy in Csock::Dereference() to cleanup a sock thats being shutdown
};
Csock & operator<<( const CS_STRING & s );
Csock & operator<<( std::ostream & ( *io )( std::ostream & ) );
Csock & operator<<( int32_t i );
Csock & operator<<( uint32_t i );
Csock & operator<<( int64_t i );
Csock & operator<<( uint64_t i );
Csock & operator<<( float i );
Csock & operator<<( double i );
/**
* @brief Create the connection, this is used by the socket manager, and shouldn't be called directly by the user
* @return true on success
*/
virtual bool Connect();
#ifdef HAVE_UNIX_SOCKET
/**
* @brief Connect to a UNIX socket.
* @param sPath the path to the UNIX socket.
*/
virtual bool ConnectUnix( const CS_STRING & sPath );
/**
* @brief Listens for connections on an UNIX socket
* @param sBindFile the socket on which to listen
* @param iMaxConns the maximum amount of pending connections to allow
* @param iTimeout if no connections come in by this timeout, the listener is closed
*/
virtual bool ListenUnix( const CS_STRING & sBindFile, int iMaxConns = SOMAXCONN, uint32_t iTimeout = 0 );
#endif
/**
* @brief Listens for connections
* @param iPort the port to listen on
* @param iMaxConns the maximum amount of pending connections to allow
* @param sBindHost the vhost on which to listen
* @param iTimeout if no connections come in by this timeout, the listener is closed
* @param bDetach don't block waiting for port to come up, instead detach and return immediately
*/
virtual bool Listen( uint16_t iPort, int iMaxConns = SOMAXCONN, const CS_STRING & sBindHost = "", uint32_t iTimeout = 0, bool bDetach = false );
//! Accept an inbound connection, this is used internally
virtual cs_sock_t Accept( CS_STRING & sHost, uint16_t & iRPort );
//! Accept an inbound SSL connection, this is used internally and called after Accept
virtual bool AcceptSSL();
//! This sets up the SSL Client, this is used internally
virtual bool SSLClientSetup();
//! This sets up the SSL Server, this is used internally
virtual bool SSLServerSetup();
/**
* @brief Create the SSL connection
* @return true on success
*
* This is used by the socket manager, and shouldn't be called directly by the user.
*/
virtual bool ConnectSSL();
//! start a TLS connection on an existing plain connection
bool StartTLS();
/**
* @brief Write data to the socket
*
* If not all of the data is sent, it will be stored on
* an internal buffer, and tried again with next call to Write
* if the socket is blocking, it will send everything, its ok to check ernno after this (nothing else is processed)
*
* @param data the data to send
* @param len the length of data
*/
virtual bool Write( const char *data, size_t len );
/**
* @brief Write a text string to the socket
*
* Encoding is used, if set
*
* @param sData the string to send; if encoding is provided, sData should be UTF-8 and will be encoded
* @see Write( const char *, int )
*/
virtual bool Write( const CS_STRING & sData );
/**
* Read from the socket
* Just pass in a pointer, big enough to hold len bytes
*
* @param data the buffer to read into
* @param len the size of the buffer
*
* @return
* Returns READ_EOF for EOF
* Returns READ_ERR for ERROR
* Returns READ_EAGAIN for Try Again ( EAGAIN )
* Returns READ_CONNREFUSED for connection refused
* Returns READ_TIMEDOUT for a connection that timed out at the TCP level
* Otherwise returns the bytes read into data
*/
virtual cs_ssize_t Read( char *data, size_t len );
CS_STRING GetLocalIP() const;
CS_STRING GetRemoteIP() const;
//! Tells you if the socket is connected
virtual bool IsConnected() const;
//! Sets the sock, telling it its connected (internal use only)
virtual void SetIsConnected( bool b );
//! returns a reference to the sock
cs_sock_t & GetRSock();
const cs_sock_t & GetRSock() const;
void SetRSock( cs_sock_t iSock );
cs_sock_t & GetWSock();
const cs_sock_t & GetWSock() const;
void SetWSock( cs_sock_t iSock );
void SetSock( cs_sock_t iSock );
cs_sock_t & GetSock();
const cs_sock_t & GetSock() const;
/**
* @brief calls SockError, if sDescription is not set, then strerror is used to pull out a default description
* @param iErrno the errno to send
* @param sDescription the description of the error that occurred
*/
void CallSockError( int iErrno, const CS_STRING & sDescription = "" );
//! resets the time counter, this is virtual in the event you need an event on the timer being Reset
virtual void ResetTimer();
//! will pause/unpause reading on this socket
void PauseRead();
void UnPauseRead();
bool IsReadPaused() const;
/**
* this timeout isn't just connection timeout, but also timeout on
* NOT recieving data, to disable this set it to 0
* then the normal TCP timeout will apply (basically TCP will kill a dead connection)
* Set the timeout, set to 0 to never timeout
*/
enum
{
TMO_READ = 1,
TMO_WRITE = 2,
TMO_ACCEPT = 4,
TMO_ALL = TMO_READ|TMO_WRITE|TMO_ACCEPT
};
//! Currently this uses the same value for all timeouts, and iTimeoutType merely states which event will be checked
//! for timeouts
void SetTimeout( int iTimeout, uint32_t iTimeoutType = TMO_ALL );
void SetTimeoutType( uint32_t iTimeoutType );
int GetTimeout() const;
uint32_t GetTimeoutType() const;
//! returns true if the socket has timed out
virtual bool CheckTimeout( time_t iNow );
/**
* pushes data up on the buffer, if a line is ready
* it calls the ReadLine event
*/
virtual void PushBuff( const char *data, size_t len, bool bStartAtZero = false );
//! This gives access to the internal read buffer, if your
//! not going to use ReadLine(), then you may want to clear this out
//! (if its binary data and not many '\\n')
CS_STRING & GetInternalReadBuffer();
//! This gives access to the internal write buffer.
//! If you want to check if the send queue fills up, check here.
CS_STRING & GetInternalWriteBuffer();
//! sets the max buffered threshold when EnableReadLine() is enabled
void SetMaxBufferThreshold( uint32_t iThreshold );
uint32_t GetMaxBufferThreshold() const;
//! Returns the connection type from enum eConnType
int GetType() const;
void SetType( int iType );
//! Returns a reference to the socket name
const CS_STRING & GetSockName() const;
void SetSockName( const CS_STRING & sName );
//! Returns a reference to the host name
const CS_STRING & GetHostName() const;
void SetHostName( const CS_STRING & sHostname );
//! Gets the starting time of this socket
uint64_t GetStartTime() const;
//! Resets the start time
void ResetStartTime();
//! Gets the amount of data read during the existence of the socket
uint64_t GetBytesRead() const;
void ResetBytesRead();
//! Gets the amount of data written during the existence of the socket
uint64_t GetBytesWritten() const;
void ResetBytesWritten();
//! Get Avg Read Speed in sample milliseconds (default is 1000 milliseconds or 1 second)
double GetAvgRead( uint64_t iSample = 1000 ) const;
//! Get Avg Write Speed in sample milliseconds (default is 1000 milliseconds or 1 second)
double GetAvgWrite( uint64_t iSample = 1000 ) const;
//! Returns the remote port
uint16_t GetRemotePort() const;
//! Returns the local port
uint16_t GetLocalPort() const;
//! Returns the port
uint16_t GetPort() const;
void SetPort( uint16_t iPort );
//! just mark us as closed, the parent can pick it up
void Close( ECloseType eCloseType = CLT_NOW );
//! returns int of type to close @see ECloseType
ECloseType GetCloseType() const { return( m_eCloseType ); }
bool IsClosed() const { return( GetCloseType() != CLT_DONT ); }
//! Use this to change your fd's to blocking or none blocking
void NonBlockingIO();
//! Return true if this socket is using ssl. Note this does not mean the SSL state is finished, but simply that its configured to use ssl
bool GetSSL() const;
void SetSSL( bool b );
#ifdef HAVE_LIBSSL
//! bitwise setter, @see EDisableProtocol
void DisableSSLProtocols( u_int uDisableOpts ) { m_uDisableProtocols = uDisableOpts; }
//! allow disabling compression
void DisableSSLCompression() { m_bNoSSLCompression = true; }
//! select the ciphers in server-preferred order
void FollowSSLCipherServerPreference() { m_bSSLCipherServerPreference = true; }
//! Set the cipher type ( openssl cipher [to see ciphers available] )
void SetCipher( const CS_STRING & sCipher );
const CS_STRING & GetCipher() const;
//! Set the pem file location
void SetDHParamLocation( const CS_STRING & sDHParamFile );
const CS_STRING & GetDHParamLocation() const;
void SetKeyLocation( const CS_STRING & sKeyFile );
const CS_STRING & GetKeyLocation() const;
void SetPemLocation( const CS_STRING & sPemFile );
const CS_STRING & GetPemLocation() const;
void SetPemPass( const CS_STRING & sPassword );
const CS_STRING & GetPemPass() const;
//! Set the SSL method type
void SetSSLMethod( int iMethod );
int GetSSLMethod() const;
void SetSSLObject( SSL *ssl, bool bDeleteExisting = false );
SSL * GetSSLObject() const;
void SetCTXObject( SSL_CTX *sslCtx, bool bDeleteExisting = false );
SSL_SESSION * GetSSLSession() const;
//! setting this to NULL will allow the default openssl verification process kick in
void SetCertVerifyCB( FPCertVerifyCB pFP ) { m_pCerVerifyCB = pFP; }
#endif /* HAVE_LIBSSL */
//! Get the send buffer
bool HasWriteBuffer() const;
void ClearWriteBuffer();
//! is SSL_accept finished ?
//! is the ssl properly finished (from write no error)
bool SslIsEstablished() const;
//! Use this to bind this socket to inetd
bool ConnectInetd( bool bIsSSL = false, const CS_STRING & sHostname = "" );
//! Tie this guy to an existing real file descriptor
bool ConnectFD( int iReadFD, int iWriteFD, const CS_STRING & sName, bool bIsSSL = false, ETConn eDirection = INBOUND );
//! Get the peer's X509 cert
#ifdef HAVE_LIBSSL
//! it is up to you, the caller to call X509_free() on this object
X509 *GetX509() const;
//! Returns the peer's public key
CS_STRING GetPeerPubKey() const;
//! Returns the peer's certificate finger print
long GetPeerFingerprint( CS_STRING & sFP ) const;
uint32_t GetRequireClientCertFlags() const;
//! legacy, deprecated @see SetRequireClientCertFlags
void SetRequiresClientCert( bool bRequiresCert );
//! bitwise flags, 0 means don't require cert, SSL_VERIFY_PEER verifies peers, SSL_VERIFY_FAIL_IF_NO_PEER_CERT will cause the connection to fail if no cert
void SetRequireClientCertFlags( uint32_t iRequireClientCertFlags ) { m_iRequireClientCertFlags = iRequireClientCertFlags; }
#endif /* HAVE_LIBSSL */
//! Set The INBOUND Parent sockname
virtual void SetParentSockName( const CS_STRING & sParentName );
const CS_STRING & GetParentSockName() const;
/**
* sets the rate at which we can send data
* @param iBytes the amount of bytes we can write
* @param iMilliseconds the amount of time we have to rate to iBytes
*/
virtual void SetRate( uint32_t iBytes, uint64_t iMilliseconds );
uint32_t GetRateBytes() const;
uint64_t GetRateTime() const;
/**
* Connected event
*/
virtual void Connected() {}
/**
* Disconnected event
*/
virtual void Disconnected() {}
/**
* Sock Timed out event
*/
virtual void Timeout() {}
/**
* Ready to read data event
*/
virtual void ReadData( const char *data, size_t len ) {}
/**
*
* Ready to Read a full line event. If encoding is provided, this is guaranteed to be UTF-8
*/
virtual void ReadLine( const CS_STRING & sLine ) {}
//! set the value of m_bEnableReadLine to true, we don't want to store a buffer for ReadLine, unless we want it
void EnableReadLine();
void DisableReadLine();
//! returns the value of m_bEnableReadLine, if ReadLine is enabled
bool HasReadLine() const { return( m_bEnableReadLine ); }
/**
* This WARNING event is called when your buffer for readline exceeds the warning threshold
* and triggers this event. Either Override it and do nothing, or SetMaxBufferThreshold()
* This event will only get called if m_bEnableReadLine is enabled
*/
virtual void ReachedMaxBuffer();