forked from SQream/cpp-connector
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.cpp
More file actions
772 lines (560 loc) · 20.9 KB
/
socket.cpp
File metadata and controls
772 lines (560 loc) · 20.9 KB
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
#include <stdio.h>
#include <string>
#include <tuple>
#include <memory>
#ifndef __linux__
#include <winsock.h>
#endif
#include "socket.hpp"
#include <errno.h>
#include <openssl/ssl.h>
//#include <openssl/err.h>
//#include <openssl/ossl_typ.h>
ssize_t TSocketClient::sock_recv (char *__buf, sock_buf_size __n)
{
if (is_ssl)
return SSL_read (ssl, __buf, __n);
else
return recv (vSocket, __buf, __n, 0);
}
ssize_t TSocketClient::sock_send(const char *__buf, sock_buf_size __n)
{
if (is_ssl)
return SSL_write (ssl, __buf, __n);
else
return send (vSocket, __buf, __n, 0);
}
// ----------------- static data members initialization ------------------
bool TSocketClient::g_flgLibReady = 0;
// --------------------------------------------------------------------
// does the work of the constructor, initializes addr struct with IP and port
// --------------------------------------------------------------------
#ifndef __linux__
typedef unsigned int in_addr_t;
#endif
bool TSocketClient::Initialize ( const char* pServer, int pPort )
{
int x;
PHOSTENT phostent = NULL;
// precaution
if ( pServer == NULL || pPort <= 0 )
return false;
// try converting from dotted decimal form
x = inet_addr ( pServer );
if ( x != (in_addr_t)INADDR_NONE ) { // success
// put the addr in SOCKADDR struct
vSockAddr.sin_addr.s_addr = x;
}
// check if local
else if ( strcmp( pServer, "(local)" ) == 0 ) {
x = inet_addr ( "127.0.0.1" );
if ( x != (in_addr_t)INADDR_NONE ) { // success
// put the addr in SOCKADDR struct
vSockAddr.sin_addr.s_addr = x;
}
else
return false;
}
// try name resolution
else {
// use gethosbyname function and try resolving
phostent = gethostbyname(pServer);
if ( phostent == NULL )
return false; // resolution failed
// put the addr in SOCKADDR struct
memcpy ( &(vSockAddr.sin_addr), phostent->h_addr, phostent->h_length );
}
// prepare the remaining sock addr struct
vSockAddr.sin_family = AF_INET; // address family
vSockAddr.sin_port = htons ( (uint16_t)pPort ); // port number
#ifdef __linux__
g_flgLibReady = true;
#endif
if (is_ssl)
{
SSL_library_init();
SSL_load_error_strings();
OpenSSL_add_all_algorithms();
}
return true;
}
// --------------------------------------------------------------------
// default constructor, does nothing besides a rest
// --------------------------------------------------------------------
TSocketClient::TSocketClient ( bool is_ssl_ ) : is_ssl(is_ssl_)
{
vSocket = INVALID_SOCKET; // handle
memset ( &vSockAddr, 0, sizeof(vSockAddr)); // address struct
memset ( vszErrMsg, 0, sizeof(vszErrMsg)); // internal error message store
}
// --------------------------------------------------------------------
// constructor, which parepares sock_addr for connection
// --------------------------------------------------------------------
TSocketClient::TSocketClient ( const char* pServer, int pPort, bool is_ssl_ ) : is_ssl(is_ssl_)
{
vSocket = INVALID_SOCKET; // handle
memset ( &vSockAddr, 0, sizeof(vSockAddr)); // address struct
memset ( vszErrMsg, 0, sizeof(vszErrMsg)); // internal error message store
Initialize ( pServer, pPort ); // initialize with specified values
}
// --------------------------------------------------------------------
// destructor
// --------------------------------------------------------------------
TSocketClient::~TSocketClient ()
{
// will close socket if open and reset corres. member variables
SockClose();
}
#ifdef __linux__
// --------------------------------------------------------------------
// STATIC, to initialize the windows socket library ( requirement for winsock )
// --------------------------------------------------------------------
int TSocketClient::SockInitLib ( short pMajorVersion, short pMinorVersion )
{
// check if already initialized
if ( TSocketClient::g_flgLibReady == 1 )
return 1; // successs
int status;
struct addrinfo host_info;
struct addrinfo *host_info_list;
int socketfd ;
memset(&host_info, 0, sizeof host_info);
status = getaddrinfo("192.168.0.50", "2013", &host_info, &host_info_list);
if(status!=0){
return 1;
}
socketfd = socket(host_info_list->ai_family, host_info_list->ai_socktype,
host_info_list->ai_protocol);
if (socketfd == -1) {
return 2;
}
// set the static memeber indicator
TSocketClient::g_flgLibReady = 1;
return 0; // success
}
// --------------------------------------------------------------------
// to finalize the windows socket library
// --------------------------------------------------------------------
bool TSocketClient::SockFinalizeLib ( void )
{
// note
// applications must make sure that all sockets are closed
// since this is a static member function and does not
// know about class instances
// lib cleanup for winsock
// set the static memeber indicator
TSocketClient::g_flgLibReady = 0;
return true;
}
#else
// --------------------------------------------------------------------
// STATIC, to initialize the windows socket library ( requirement for winsock )
// --------------------------------------------------------------------
int TSocketClient::SockInitLib ( short pMajorVersion, short pMinorVersion )
{
short v;
int iStatus;
WSADATA wd;
// check if already initialized
if ( TSocketClient::g_flgLibReady == 1 )
return 1; // successs
// set the version required lo,hi
v = MAKEWORD( pMinorVersion, pMajorVersion );
// call the Winsock initialization function
iStatus = WSAStartup ( v, &wd );
if ( iStatus != 0 ) {
// SetErrMsg ( true, "WSAStartup failed" ); // cannot call a non-static member function
return -1; // so failure indicated by return code
}
// check if the required version is available
if ( LOBYTE( wd.wVersion ) != pMinorVersion ||
HIBYTE( wd.wVersion ) != pMajorVersion ) {
WSACleanup (); // perform the cleanup
// SetErrMsg ( false, "Version mismatch. Required: %d.%d, Available: %d.%d", pMajorVersion, pMinorVersion, HIBYTE( wd.wVersion ), LOBYTE( wd.wVersion ));
return -2;
}
// set the static memeber indicator
TSocketClient::g_flgLibReady = 1;
return 0; // success
}
// --------------------------------------------------------------------
// to finalize the windows socket library
// --------------------------------------------------------------------
bool TSocketClient::SockFinalizeLib ( void )
{
// note
// applications must make sure that all sockets are closed
// since this is a static member function and does not
// know about class instances
// lib cleanup for winsock
WSACleanup ();
// set the static memeber indicator
TSocketClient::g_flgLibReady = 0;
return true;
}
#endif
// --------------------------------------------------------------------
// to create a socket and connect to the server using specified sockaddr
// --------------------------------------------------------------------
bool TSocketClient::SockCreateAndConnect ( void )
{
int iStatus;
SOCKET s;
// note
// create and connect r merged due to nature of client application
// PRECAUTION
if ( TSocketClient::g_flgLibReady == 0 || vSockAddr.sin_addr.s_addr == 0 ) {
SetErrMsg ( false, "Winsock/SockAddr not initialized" );
return false;
}
// CREATE
// create a new stream socket
s = socket (AF_INET, SOCK_STREAM, 0 );
if ( s == INVALID_SOCKET ) {
SetErrMsg ( true, "WSASocket failed" );
return false;
}
// CONNECT
// connect using the already prepared address
iStatus = connect ( s, ( struct sockaddr* )&vSockAddr, sizeof(vSockAddr));
if ( iStatus != 0 ) {
#ifdef __linux__
close(s);// windows clean-up
#else
closesocket( s );
#endif
SetErrMsg ( true, "WSAConnect failed - %d\n ",errno );
return false;
}
// SUCCESS
vSocket = s;
if (is_ssl)
{
SSL_CTX * sslctx = SSL_CTX_new( SSLv23_client_method());
SSL_CTX_set_options (sslctx, SSL_OP_SINGLE_DH_USE | SSL_OP_NO_SSLv2);
//int use_cert = SSL_CTX_use_certificate_file(sslctx, "/serverCertificate.pem" , SSL_FILETYPE_PEM);
//int use_prv = SSL_CTX_use_PrivateKey_file(sslctx, "/serverCertificate.pem", SSL_FILETYPE_PEM);
ssl = SSL_new(sslctx);
SSL_set_fd(ssl, (int)vSocket );
if ( SSL_connect(ssl) == -1 )
{
is_ssl = false;
//Error occurred, log and close down ssl
ShutdownSSL();
SetErrMsg ( true, "server doesn't work in ssl mode\n ");
return false;
}
}
return true;
}
// --------------------------------------------------------------------
// to create a socket and connect to the server using specified sockaddr
// --------------------------------------------------------------------
// send ip + port
std::tuple<int ,std::string,bool> TSocketClient::GetParamsFromPicker(void)
{
int iStatus;
SOCKET s;
// note
// create and connect r merged due to nature of client application
// PRECAUTION
if (TSocketClient::g_flgLibReady == 0 || vSockAddr.sin_addr.s_addr == 0) {
SetErrMsg(false, "Winsock/SockAddr not initialized");
return std::make_tuple(0, std::string(""), false);
}
// CREATE
// create a new stream socket
s = socket(AF_INET, SOCK_STREAM, 0);
if (s == INVALID_SOCKET) {
SetErrMsg(true, "WSASocket failed");
return std::make_tuple(0, std::string(" "), false);
}
// CONNECT
// connect using the already prepared address
std::unique_ptr <char[]> s_ip;
char message_size[4] = { 0 };
char s_port[4] = { 0 };
int port;
int m_size = 0;
iStatus = connect(s, (struct sockaddr*)&vSockAddr, sizeof(vSockAddr));
if (iStatus >= 0)
{
//get bffer size;
recv(s, message_size, 4, 0);
//m_size = atoi(message_size);
m_size = *((int*)message_size) + 1;
s_ip = std::unique_ptr<char[]>(new char[m_size]);
memset(s_ip.get(), 0, m_size);
recv(s, s_ip.get(), m_size - 1, 0);
recv(s, s_port, 4, 0);
port = *((int*)s_port);
}
#ifdef __linux__
close(s);// windows clean-up
#else
closesocket(s);
#endif
vSocket = s;
if (iStatus == -1)
{
SetErrMsg(true, "WSAConnect failed - %d\n ", errno);
return std::make_tuple(0, std::string(""), false);
}
return std::make_tuple(port, std::string(s_ip.get()), true);
// SUCCESS
}
// --------------------------------------------------------------------
// to write a chunk to the socket
// --------------------------------------------------------------------
bool TSocketClient::SockWriteChunk (const void* pBuffer, size_t pChunkSize, int& pBytesWritten )
{
int iStatus;
// caller safe
pBytesWritten = 0;
// precaution -------- class level
if ( !IsReady()) {
SetErrMsg ( false, "Winsock/Class not initialized" );
return false;
}
// precaution --------- function level
if ( pBuffer == NULL || pChunkSize < 0 ) {
SetErrMsg ( false, "SockWriteChunk, bad params" ); // zero bytes write is NOT an error
return false;
}
// send
iStatus = (int)sock_send ( (char*)pBuffer, pChunkSize);
if ( iStatus == SOCKET_ERROR ) {
int ret = is_ssl ? SSL_get_error(ssl, iStatus) : errno;
SetErrMsg ( true, "WSASend failed: %d\n ", ret);
return false;
}
// bytes sent
pBytesWritten = iStatus;
return true;
}
// --------------------------------------------------------------------
// to read a chunk from the socket
// --------------------------------------------------------------------
bool TSocketClient::SockReadChunk ( char* pBuffer, int& pBytesRead, int pChunkSize )
{
int iStatus;
int iTotal_read=0;
// caller safe
pBytesRead = 0;
// precaution --------- class level
if ( !IsReady()) {
SetErrMsg ( false, "Winsock/Class not initialized" );
return false;
}
// precaution --------- function level
if ( pBuffer == NULL || pChunkSize < 0 ) {
SetErrMsg ( false, "SockReadChunk, bad params" ); // zero bytes read is NOT an error
return false;
}
// other initializations
// recv
//char* buf= new char[100];
while(true ){
iStatus = (int)sock_recv ( &pBuffer[iTotal_read], pChunkSize-iTotal_read);
if ( iStatus == SOCKET_ERROR ) {
SetErrMsg ( true, "WSARecv failed\n " );
return false;
}
iTotal_read=iTotal_read+iStatus;
if(iTotal_read == pChunkSize)
break;
if(iStatus==0){
if(iTotal_read != pChunkSize){
return false;
}
else{
break;
}
}
}
// bytes recd
pBytesRead = iTotal_read;
return true;
}
// --------------------------------------------------------------------
// to read a complete signed message from a socket
// --------------------------------------------------------------------
bool TSocketClient::SockReadFullMsg ( char*& pBuffer, int& pMsgSize, int pDefChunkSize )
{
bool flgComplete;
bool flgError;
bool flgSignedMsg; // message is a signed one
bool flgSignChecked; // message start has been checked for a sign
bool iStatus;
int iChunkSize;
int iCurrBytesRead, iTotalBytesRead;
int nBytesAvailable;
char* tmp;
char* buf; // final buf, to be returned to caller
// note
// the function receives msgs in 2 modes. 1. Signed message, 2. Raw msg
// Case signed message: it will read till it receives signature again
// Case Raw msg: it will read till it can peek
// The signature is not a part of the block returned to caller
// the raw message feature is not very reliable
// initialization for caller parameters
pBuffer = NULL;
pMsgSize = 0;
// local initializations
tmp = NULL;
buf = NULL;
iTotalBytesRead = 0;
nBytesAvailable = 0;
flgComplete = false;
flgError = false;
flgSignedMsg = false;
flgSignChecked = false;
// determine the chunk size
iChunkSize = ( pDefChunkSize <= 0 ) ? DEF_CHUNK_SIZE : pDefChunkSize;
// loop to read from socket in chunks
while( !flgComplete && !flgError ) {
// increase buffer size to read next chunk
tmp = buf; // save existing buffer
buf = new char[iTotalBytesRead+iChunkSize];
// preserve the existing data and release the old buffer
if( tmp ) {
memcpy( buf, tmp, iTotalBytesRead );
delete[] tmp;
tmp = NULL;
}
// read the chunk
iStatus = SockReadChunk ( buf+iTotalBytesRead, iCurrBytesRead, iChunkSize );
// check if IO failed
if( iStatus != true ) {
flgError = true;
continue;
}
else {
// printbuffer( "Read chunk", buf+iTotalBytesRead, iCurrBytesRead ); // ????? debug
// printf ( "Read chunk: %d, Total: %d\n", iCurrBytesRead, iTotalBytesRead ); // ????? debug
iTotalBytesRead += iCurrBytesRead; // increase the total number of bytes read
}
// IO succeeded
// 1. check for start signature if enough data
// 2. check for end signature if enough data
// 3. check for end thru peek if an un-signed message with enough data
// check START signature only if sufficient data & not checked
if( !flgSignChecked &&
iTotalBytesRead >= MSG_SOCK_SIGN_SIZE ) {
// first mark the message as checked for signature
flgSignChecked = true;
// check if start of msg is valid signature
if( memcmp( buf, MSG_SOCK_SIGN, MSG_SOCK_SIGN_SIZE ) == 0 )
flgSignedMsg = true; // mark the message as signed
// if( flgSignedMsg ) printf( "\nMessage is signed\n\n" );
// else printbuffer( "Chunk", buf, iTotalBytesRead );
}
// check END with signature only if sufficient data & msg is signed
if( flgSignedMsg == true &&
iTotalBytesRead >= (MSG_SOCK_SIGN_SIZE*2)) {
// check from the end of buffer
if( memcmp ( buf + iTotalBytesRead - MSG_SOCK_SIGN_SIZE, MSG_SOCK_SIGN, MSG_SOCK_SIGN_SIZE ) == 0 )
flgComplete = true; // full message has been recd.
}
// check END thru peek only if msg is known to be un-signed
if( flgSignChecked == true &&
flgSignedMsg == false ) {
#ifndef __linux__
// check if something more is available on pipe
flgError = ( ioctlsocket ( vSocket, FIONREAD, ( unsigned long* )&nBytesAvailable ) == SOCKET_ERROR ) ? true : false;
if( flgError ) {
SetErrMsg ( true, "Ioctlsocket failed for peek" );
continue;
}
#endif
// check if read operation is complete
// 1. read bytes were less than chunk size
// 2. no more data is available in pipe
flgComplete = ( iCurrBytesRead < iChunkSize || nBytesAvailable == 0 ) ? true : false;
}
}
// check if there has been error
if( flgError ) {
// release any allocated buffers
if( buf ) {
delete[] buf;
buf = NULL;
}
return false;
}
// read completed successfully so adjust msg if signed
if( flgSignedMsg == true ) {
// remove start signature
memmove( buf, buf + MSG_SOCK_SIGN_SIZE, iTotalBytesRead - MSG_SOCK_SIGN_SIZE );
// reduce the number of bytes read by START & END signatures
iTotalBytesRead -= ( MSG_SOCK_SIGN_SIZE*2 );
// since we have extra bytes bcoz of end signature, why not zero terminate the buffer
buf[iTotalBytesRead] = 0;
}
// transfer to caller, both buffer & number of bytes
pBuffer = buf;
pMsgSize = iTotalBytesRead;
return true;
}
// --------------------------------------------------------------------
// to close the current socket
// --------------------------------------------------------------------
void TSocketClient::ShutdownSSL()
{
SSL_shutdown(ssl);
SSL_free(ssl);
}
void TSocketClient::SockClose ( void )
{
int iStatus;
// check if socket handle is valid
if( vSocket != INVALID_SOCKET ) {
// start a graceful shutdown
shutdown ( vSocket, 0x02 ); // SD_BOTH is equal to 0x02
// use closesocket call
#ifdef __linux__
iStatus = close( vSocket );
#else
iStatus = closesocket( vSocket );
if(WSAGetLastError () != WSANOTINITIALISED ){
SetErrMsg ( true, "closesocket failed." );
}else{
vSocket = INVALID_SOCKET;
}
#endif
if( iStatus == SOCKET_ERROR) // considered failed only if previously initialized
SetErrMsg ( true, "closesocket failed." );
else
vSocket = INVALID_SOCKET;
if (is_ssl)
ShutdownSSL();
}
}
// --------------------------------------------------------------------
// to set error message for the server class
// --------------------------------------------------------------------
bool TSocketClient::SetErrMsg ( bool flgIncludeWin32Error, const char* pszErrMsg, ... )
{
// check if error message specified or clean-up required
if( pszErrMsg ) {
va_list args;
va_start (args, pszErrMsg);
vsprintf( vszErrMsg,pszErrMsg, args );
va_end (args);
#ifndef __linux__
if( flgIncludeWin32Error )
sprintf_s(vszErrMsg + strlen(vszErrMsg), 256 - strlen(vszErrMsg), " WSA-Win32 status: %d", WSAGetLastError());
#endif
}
else
vszErrMsg[0] = 0;
return false;
}
// --------------------------------------------------------------------
// to write the signature to socket to indicate start or end of msg
// --------------------------------------------------------------------
bool TSocketClient::WriteSignature ( void )
{
int x;
return SockWriteChunk (MSG_SOCK_SIGN, MSG_SOCK_SIGN_SIZE, x );
}