-
Notifications
You must be signed in to change notification settings - Fork 93
/
ut_clnt.cpp
2558 lines (2159 loc) · 77.2 KB
/
ut_clnt.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
//=================================================================
// class: CUT_WSClient
// File: Ut_clnt.cpp
//
// Purpose:
//
// Implementation of the main Client Winsock class
// (the Main engine, and the building block) of the
// Ultimate TCP/IP Library.
//
// This class encapsulates the functionality of winsock.dll in order to give
// the user a friendly, and object oriented framework for Winsock programming
//
// ===================================================================
// Ultimate TCP/IP v4.2
// This software along with its related components, documentation and files ("The Libraries")
// is © 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is
// governed by a software license agreement ("Agreement"). Copies of the Agreement are
// available at The Code Project (www.codeproject.com), as part of the package you downloaded
// to obtain this file, or directly from our office. For a copy of the license governing
// this software, you may contact us at legalaffairs@codeproject.com, or by calling 416-849-8900.
// ===================================================================
/*
NppFTP:
Modification made April 2010:
-Replaced existing secure functionality with OpenSSL functionality
*/
#ifdef _WINSOCK_2_0_
#define _WINSOCKAPI_ /* Prevent inclusion of winsock.h in windows.h */
/* Remove this line if you are using WINSOCK 1.1 */
#endif
#include "stdafx.h"
#include <stdio.h>
#include "ut_clnt.h"
#include "ut_strop.h"
#ifdef __BORLANDC__
#include "mem.h"
#else
#include "memory.h"
#endif
/***********************************************
Constructor
************************************************/
CUT_WSClient::CUT_WSClient() :
m_nRemotePort(0), // Initialize the remote port
m_nLocalPort(0), // Initialize the local port
m_nAcceptPort(0), // Initialize the accept port
m_nProtocol(0), // Initialize protocol
m_nFamily(2), // Initialize socket family
m_nSockType(1), // Initialize socket type
m_socket(INVALID_SOCKET), // Initialize socket
m_serverSocket(INVALID_SOCKET), // Initialize server socket
m_nBlockingMode(CUT_BLOCKING), // Default mode - BLOCKING
m_nSuccessful(TRUE), // Set Windows Socket DLL initialization flag to TRUE
m_hAsyncWnd(NULL), // Initialize window handle with NULL
m_lSendTimeOut(30000), // Set default Send Time Out value
m_lRecvTimeOut(30000), // Set default Receive Time Out value
m_isSSL(false),
m_SSLconnected(false),
m_sslMode(NONE),
m_meth(NULL),
m_ctx(NULL),
m_ssl(NULL),
m_reuseSession(NULL)
{
static bool isSSLInit = false;
if (!isSSLInit) {
SSL_library_init();
SSL_load_error_strings();
//ERR_load_BIO_strings();
OpenSSL_add_all_algorithms();
isSSLInit = true;
}
// Initialize address array
m_szAddress[0] = 0;
//initialize the Windows Socket DLL
if( WSAStartup(WINSOCKVER, &m_data) != 0 )
m_nSuccessful = FALSE;
//set up the default send are receive time-outs
SetReceiveTimeOut(m_lRecvTimeOut);
SetSendTimeOut(m_lSendTimeOut);
}
/***********************************************
Destructor
************************************************/
CUT_WSClient::~CUT_WSClient(){
CloseConnection(); // Close any open connection
WSACleanup(); // Shut down the winsock DLL
if(m_hAsyncWnd != NULL) // Destory the async window
DestroyWindow(m_hAsyncWnd);
}
/***********************************************
Connect
Connects to a specified port
Params
port - port to connect to
address - address to connect to (ex."204.64.75.73")
[timeout] - time to wait for connection
[family] - protocol family: AF_INET, AF_AF_IPX, etc. Default AF_INET
[sockType] - SOCK_STREAM (TCP) or SOCK_DGRAM (UDP) Default is SOCK_STREAM
Return
UTE_SOCK_ALREADY_OPEN - socket already open or in use
UTE_SOCK_CREATE_FAILED - socket creation failed
UTE_SOCK_CONNECT_FAILED - socket connection failed
UTE_INVALID_ADDRESS - invalid address
UTE_SUCCESS - success
UTE_CONNECT_TIMEOUT - connect time out
************************************************/
#if defined _UNICODE
int CUT_WSClient::Connect(unsigned int port, LPCWSTR address, long timeout, int family, int sockType){
return Connect(port, AC(address), timeout, family, sockType);}
#endif
int CUT_WSClient::Connect(unsigned int port, LPCSTR address, long timeout, int family, int sockType)
{
int nError = UTE_SUCCESS;
if(m_socket != INVALID_SOCKET)
return OnError(UTE_SOCK_ALREADY_OPEN);
//copy the params
//check to see if the domain is a name or address
if(IsIPAddress(address) != TRUE) {
if(GetAddressFromName(address, m_szAddress, sizeof(m_szAddress)) != UTE_SUCCESS)
return OnError(UTE_INVALID_ADDRESS);
}
else
strncpy(m_szAddress, address, sizeof(m_szAddress)-1);
m_nFamily = family;
m_nSockType = sockType;
//Set up the SockAddr structure
memset(&m_sockAddr, 0, sizeof(m_sockAddr)); //clear all
m_sockAddr.sin_port = (unsigned short) htons((u_short )port); //port
m_sockAddr.sin_family = (short) family; //family
m_sockAddr.sin_addr.s_addr = inet_addr(m_szAddress); //address
//create a socket
if(CreateSocket(m_socket, family,sockType) == UTE_ERROR)
return OnError(UTE_SOCK_CREATE_FAILED); // ERROR: socket unsuccessful
// switch to nonblocking mode to support timeout
if(timeout >= 0)
SetBlockingMode(CUT_NONBLOCKING);
if( connect(m_socket,(LPSOCKADDR)&m_sockAddr,sizeof(m_sockAddr))==SOCKET_ERROR){
if(WSAGetLastError() == WSAEWOULDBLOCK ) {
if(timeout >= 0) {
if(WaitForSend(timeout, 0) != CUT_SUCCESS) {
SocketClose(m_socket);
m_socket = INVALID_SOCKET;
return OnError(UTE_CONNECT_TIMEOUT);
}
SetBlockingMode(CUT_BLOCKING);
}
//set up the default send are receive time-outs
SetReceiveTimeOut(m_lRecvTimeOut);
SetSendTimeOut(m_lSendTimeOut);
// save the remote port
m_nRemotePort = ntohs(m_sockAddr.sin_port);
// save the local port
SOCKADDR_IN sa{};
int len = sizeof(SOCKADDR_IN);
getsockname(m_socket, (SOCKADDR*) &sa, &len);
m_nLocalPort = ntohs(sa.sin_port);
// Call socket connection notification
if((nError = SocketOnConnected(m_socket, address)) != UTE_SUCCESS)
{
SocketClose(m_socket);
m_socket = INVALID_SOCKET;
}
return OnError(nError);
}
else {
// did not have these two lines prior to Feb 11 1999
SocketClose(m_socket);
m_socket = INVALID_SOCKET;
}
return OnError(UTE_SOCK_CONNECT_FAILED); // ERROR: connect unsuccessful
}
// set up the default send are receive time-outs
SetReceiveTimeOut(m_lRecvTimeOut);
SetSendTimeOut(m_lSendTimeOut);
// Call socket connection notification
if((nError = SocketOnConnected(m_socket, address)) != UTE_SUCCESS)
{
SocketClose(m_socket);
m_socket = INVALID_SOCKET;
}
return OnError(nError);
}
/***********************************************
ConnectBound
Connects to a specified port from a specified port
Params
localPort - local port to connect the socket to
remotePort - remote port to connect the socket to
localAddress - local address to connect to
remoteAddress - remote address to connect to
family - protocol family: AF_INET, AF_AF_IPX, etc.
sockType - SOCK_STREAM (TCP) or SOCK_DGRAM (UDP)
Return
UTE_SOCK_ALREADY_OPEN - socket already open or in use
UTE_SOCK_CREATE_FAILED - socket creation failed
UTE_SOCK_BIND_FAILED - socket binding to local port failed
UTE_SOCK_CONNECT_FAILED - socket connection failed
UTE_SUCCESS - success
************************************************/
#if defined _UNICODE
int CUT_WSClient::ConnectBound(unsigned int localPort, unsigned int remotePort,
LPWSTR localAddress, LPWSTR remoteAddress, int family, int sockType) {
return ConnectBound(localPort, remotePort, AC(localAddress),
AC(remoteAddress), family, sockType);
}
#endif
int CUT_WSClient::ConnectBound(unsigned int localPort,unsigned int remotePort,
LPSTR localAddress,LPSTR remoteAddress,int family,int sockType){
if(m_socket != INVALID_SOCKET)
return OnError(UTE_SOCK_ALREADY_OPEN);
//copy the params
strncpy(m_szAddress, remoteAddress, sizeof(m_szAddress)-1);
m_nFamily = family;
m_nSockType = sockType;
//create a socket
if((CreateSocket(m_socket, family, sockType)) == UTE_ERROR){
return OnError(UTE_SOCK_CREATE_FAILED); // ERROR: socket unsuccessful
}
//associate the socket with the address
SOCKADDR_IN addr;
memset(&addr,0,sizeof(addr)); //clear all
addr.sin_port = (unsigned short)htons((u_short )localPort); //port
addr.sin_family = (short)family; //family
addr.sin_addr.s_addr= inet_addr(localAddress); //address
if(bind(m_socket,(LPSOCKADDR)&addr,sizeof(addr)) == SOCKET_ERROR){
return OnError(UTE_SOCK_BIND_FAILED); // ERROR: bind unsuccessful
}
//Set up the SockAddr structure
memset(&m_sockAddr, 0, sizeof(m_sockAddr)); //clear all
m_sockAddr.sin_port = (unsigned short) htons((u_short )remotePort); //port
m_sockAddr.sin_family = (short) family; //family
m_sockAddr.sin_addr.s_addr = inet_addr(remoteAddress); //address
if( connect(m_socket,(LPSOCKADDR)&m_sockAddr,sizeof(m_sockAddr))==SOCKET_ERROR){
return OnError(UTE_SOCK_CONNECT_FAILED); // ERROR: connect unsuccessful
}
// save the remote port
m_nRemotePort = ntohs(m_sockAddr.sin_port);
// save the local port
SOCKADDR_IN sa{};
int len = sizeof(SOCKADDR_IN);
getsockname(m_socket, (SOCKADDR*) &sa, &len);
m_nLocalPort = ntohs(sa.sin_port);
//set up the default send are receive time-outs
SetReceiveTimeOut(m_lRecvTimeOut);
SetSendTimeOut(m_lSendTimeOut);
return OnError(UTE_SUCCESS);
}
/***********************************************
CreateUDPSocket
Creates a socket for UDP use. The socket is
setup and bound to the given ports, but
no connection is made
Params
localPort - local port to bind socket to
remotePort - port to use when SendTo and
ReceiveFrom are used
remoteAddress - addresess to use when using
SendTo and ReceiveFrom
[localAddress] - local address to bind the socket to
Return
UTE_SOCK_ALREADY_OPEN - socket already open or in use
UTE_SOCK_CREATE_FAILED - socket creation failed
UTE_SOCK_BIND_FAILED - socket binding to local port failed
UTE_SUCCESS - success
************************************************/
#ifdef CUT_UDP_SOCKET
#if defined _UNICODE
int CUT_WSClient::CreateUDPSocket(unsigned int localPort, unsigned int remotePort,
LPWSTR remoteAddress, LPWSTR localAddress) {
return CreateUDPSocket(localPort, remotePort, AC(remoteAddress), AC(localAddress));
}
#endif
int CUT_WSClient::CreateUDPSocket(unsigned int localPort,unsigned int remotePort,
LPSTR remoteAddress,LPSTR localAddress){
if(m_socket != INVALID_SOCKET)
return OnError(UTE_SOCK_ALREADY_OPEN);
//copy the params
strncpy(m_szAddress, remoteAddress, sizeof(m_szAddress));
m_nFamily = AF_INET;
m_nSockType = SOCK_DGRAM;
//create a socket
if(CreateSocket(m_socket, m_nFamily, m_nSockType) == UTE_ERROR){
return OnError(UTE_SOCK_CREATE_FAILED); // ERROR: socket unsuccessful
}
//associate the socket with the address
SOCKADDR_IN addr;
memset(&addr,0,sizeof(addr)); //clear all
addr.sin_port = (unsigned short) htons((u_short )localPort); //port
addr.sin_family = (short) m_nFamily; //family
if(localAddress == NULL)
addr.sin_addr.s_addr= htonl(INADDR_ANY); //address
else
addr.sin_addr.s_addr= inet_addr(localAddress); //address
if(bind(m_socket,(LPSOCKADDR)&addr,sizeof(addr)) == SOCKET_ERROR){
SocketClose(m_socket);
m_socket = INVALID_SOCKET;
return OnError(UTE_SOCK_BIND_FAILED); // ERROR: bind unsuccessful
}
// save the local port number for GetLocalPort...
SOCKADDR_IN sa;
int len = sizeof(SOCKADDR_IN);
getsockname(m_socket, (SOCKADDR*) &sa, &len);
m_nLocalPort = ntohs(sa.sin_port);
// and the remote port for sendto and GetRemotePort
m_nRemotePort = remotePort;
//set up the default send are receive time-outs
SetReceiveTimeOut(m_lRecvTimeOut);
SetSendTimeOut(m_lSendTimeOut);
return OnError(UTE_SUCCESS);
}
#endif //CUT_UDP_SOCKET
/***********************************************
WaitForConnect
Creates a socket and binds it to the given port
and address. Then puts the socket in a listening state
Params
port - port to listen on. If 0, winsock
will assign chose a port between
1024 and 5000. Call GetAcceptPort
to retrieve this port number.
[queSize] - que size for incomming connections
[family] - protocol family: AF_INET, AF_AF_IPX, etc.
[address] - address to listen on
Return
UTE_SOCK_ALREADY_OPEN - socket already open or in use
UTE_SOCK_CREATE_FAILED - socket creation failed
UTE_SOCK_BIND_FAILED - socket binding to local port failed
UTE_SOCK_LISTEN_ERROR - listen failed
UTE_SUCCESS - success
************************************************/
int CUT_WSClient::WaitForConnect(unsigned short port,int queSize,short family,
unsigned long address) {
if(m_serverSocket != INVALID_SOCKET)
return OnError(UTE_SOCK_ALREADY_OPEN);
//Set up the serverSockAddr structure
memset(&m_serverSockAddr, 0, sizeof(m_serverSockAddr)); //clear all
m_serverSockAddr.sin_port = htons(port); //port
m_serverSockAddr.sin_family = family; //Internet family
m_serverSockAddr.sin_addr.s_addr = address; //address (any)
//create a socket
if(CreateSocket(m_serverSocket, family, SOCK_STREAM, m_nProtocol) == UTE_ERROR){
return OnError(UTE_SOCK_CREATE_FAILED); // ERROR: socket unsuccessful
}
//associate the socket with the address and port
if(bind(m_serverSocket,(LPSOCKADDR)&m_serverSockAddr,sizeof(m_serverSockAddr))
== SOCKET_ERROR){
return OnError(UTE_SOCK_BIND_FAILED); // ERROR: bind unsuccessful
}
//allow the socket to take connections
if( listen(m_serverSocket, queSize ) == SOCKET_ERROR){
return OnError(UTE_SOCK_LISTEN_ERROR); // ERROR: listen unsuccessful
}
//set up the default send are receive time-outs
SetReceiveTimeOut(m_lRecvTimeOut);
SetSendTimeOut(m_lSendTimeOut);
// save the port number for GetAcceptPort
SOCKADDR_IN sa{};
int len = sizeof(SOCKADDR_IN);
getsockname(m_serverSocket, (SOCKADDR*) &sa, &len);
m_nAcceptPort = ntohs(sa.sin_port);
return OnError(UTE_SUCCESS);
}
/***********************************************
AcceptConnection
This function is used to accept a connection
once a socket is set up for listening see:
WaitForConnect
To see if a connection is waiting call:
WaitForAccept
Params
none
Return
UTE_ERROR - error
UTE_SUCCESS - success
************************************************/
int CUT_WSClient::AcceptConnection(){
int addrLen = sizeof(SOCKADDR_IN);
// close the socket if open - may be blocking though
if(m_socket != INVALID_SOCKET){
if(m_nSockType == SOCK_STREAM){
if(SocketShutDown(m_socket, 2) == SOCKET_ERROR){
return OnError(UTE_ERROR);
}
}
if(SocketClose(m_socket) == SOCKET_ERROR){
return OnError(UTE_ERROR);
}
}
// accept the connection request when one is received
m_socket = accept(m_serverSocket,(LPSOCKADDR)&m_sockAddr,&addrLen);
if(m_socket == INVALID_SOCKET)
return OnError(UTE_ERROR);
strcpy(m_szAddress, inet_ntoa(m_sockAddr.sin_addr));
// save the remote port
m_nRemotePort = ntohs(m_sockAddr.sin_port);
// save the local port
SOCKADDR_IN sa{};
int len = sizeof(SOCKADDR_IN);
getsockname(m_socket, (SOCKADDR*) &sa, &len);
m_nLocalPort = ntohs(sa.sin_port);
return SocketOnConnected(m_socket, m_szAddress);
// now close the server socket so we can reuse it - return no errors
// SocketShutDown(m_serverSocket, 2);
// SocketClose(m_serverSocket);
// m_serverSocket = INVALID_SOCKET;
// m_nAcceptPort = 0;
// return OnError(UTE_SUCCESS);
}
/***************************************************
WaitForAccept
Waits up til the specified time to see if there
is an incomming connection waiting with a read set. If this
function returns UTE_SUCCESS then call
AcceptConnection to connect.
Params
secs - the max. number of seconds to wait
Return
UTE_ERROR - error
UTE_SUCCESS - success
****************************************************/
int CUT_WSClient::WaitForAccept(long secs){
fd_set readSet{};
struct timeval tv{};
tv.tv_sec = secs;
tv.tv_usec = 0;
FD_ZERO(&readSet);
FD_SET(m_serverSocket,&readSet);
//wait up to the specified time to see if data is avail
if( select(-1,&readSet,NULL,NULL,&tv)!= 1){
return OnError(UTE_ERROR);
}
return OnError(UTE_SUCCESS);
}
/***********************************************
CloseConnection
Call this function to close any used and/or
open port.
Params
none
Return (bitwise)
UTE_SUCCESS - success
UTE_ERROR - failed
1 - client socket shutdown failed
2 - client socket close failed
3 - server socket shutdown failed
4 - server socket close failed
************************************************/
int CUT_WSClient::CloseConnection(){
int rt = UTE_SUCCESS;
//if the socket is not open then just return
if(m_socket != INVALID_SOCKET){
if (m_SSLconnected) {
DisconnectSSL();
}
if(m_nSockType == SOCK_STREAM){
if(SocketShutDown(m_socket, 2) == SOCKET_ERROR){
rt = UTE_ERROR; //1
}
}
if(SocketClose(m_socket) == SOCKET_ERROR){
rt = UTE_ERROR; //2
}
}
if(m_serverSocket != INVALID_SOCKET){
if(SocketShutDown(m_serverSocket, 2) == SOCKET_ERROR){
rt = UTE_ERROR; //3
}
if(SocketClose(m_serverSocket) == SOCKET_ERROR){
rt = UTE_ERROR; //4
}
}
//clear the socket variables
m_socket = INVALID_SOCKET;
m_serverSocket = INVALID_SOCKET;
m_nRemotePort = 0;
m_nLocalPort = 0;
m_nAcceptPort = 0;
strcpy(m_szAddress, "");
return OnError(rt);
}
/****
SSL related
****/
int CUT_WSClient::EnableSSL(bool enable) {
if (enable == m_isSSL)
return UTE_SUCCESS;
if (!enable) {
DisconnectSSL();
m_isSSL = false;
if (m_ssl)
SSL_free(m_ssl);
if (m_ctx)
SSL_CTX_free(m_ctx);
m_ssl = NULL;
m_ctx = NULL;
return UTE_SUCCESS;
}
if (enable) {
if (!m_meth)
return UTE_ERROR;
while (ERR_get_error() != 0);
m_ctx = SSL_CTX_new(m_meth);
if (!m_ctx) {
int errval = ERR_get_error();
printf("*** %s\n", ERR_error_string(errval, NULL));
}
SSL_CTX_set_mode(m_ctx, SSL_MODE_AUTO_RETRY);
int certRet = OnLoadCertificates(m_ctx);
if (certRet != UTE_SUCCESS) {
SSL_CTX_free(m_ctx);
m_ctx = NULL;
return UTE_ERROR;
}
m_ssl = SSL_new(m_ctx);
m_isSSL = true;
return UTE_SUCCESS;
}
return UTE_SUCCESS;
}
int CUT_WSClient::SetSecurityMode(SSLMode mode){
if (m_SSLconnected)
return UTE_ERROR; //cannot change mode when SSL is connected
if (m_sslMode == mode)
return OnError(UTE_SUCCESS);
m_sslMode = mode;
switch(mode) {
case TLS:
default:
//all version specific methods are deprecated since openssl 1.1.0
m_meth = TLS_client_method();
break;
}
if (m_meth == NULL) //possible?
return OnError(UTE_ERROR);
else
return ResetSSL();
return UTE_SUCCESS;
}
int CUT_WSClient::ConnectSSL() {
if (m_SSLconnected)
return UTE_SUCCESS;
SSL_set_fd(m_ssl, m_socket);
//Session reuse mod: If m_reuseSession is set, set it as the current SSL session
//m_reuseSession should be set just prior to a Connect() call.
if (m_reuseSession != NULL) {
SSL_set_session(m_ssl, m_reuseSession);
}
int rc = SSL_connect(m_ssl);
if (rc < 1) {
char buf[256];
u_long err;
while ((err = ERR_get_error()) != 0) {
ERR_error_string_n(err, buf, sizeof(buf));
printf("*** %s\n", buf);
}
return UTE_ERROR;
}
X509* cert = SSL_get_peer_certificate(m_ssl);
int code = SSL_get_verify_result(m_ssl);
int res = OnSSLCertificate(m_ssl, cert, code);
if (cert)
X509_free(cert);
if (res == UTE_ERROR) {
return UTE_ERROR;
}
m_SSLconnected = true;
return UTE_SUCCESS;
}
int CUT_WSClient::DisconnectSSL() {
if (!m_SSLconnected)
return UTE_SUCCESS;
//assuming shutdown fully blocks on blocking sockets
int rc = SSL_shutdown(m_ssl);
//wait for peer to disconnect
if (rc == 0) {
char buf[256]{};
int read = SSL_read(m_ssl, &buf[0], 256);
while (read > 0) {
read = SSL_read(m_ssl, &buf[0], 256);
}
rc = SSL_shutdown(m_ssl);
}
m_SSLconnected = false;
//all done
if (rc == 1) {
return UTE_SUCCESS;
}
//error
if (rc < 0) {
//this is risky, is it closed or not? Up to client to detect that
char buf[256];
u_long err;
while ((err = ERR_get_error()) != 0) {
ERR_error_string_n(err, buf, sizeof(buf));
printf("*** %s\n", buf);
}
return UTE_ERROR;
}
return UTE_SUCCESS;
}
int CUT_WSClient::ResetSSL() {
if (m_SSLconnected)
DisconnectSSL();
if (m_ssl)
SSL_free(m_ssl);
if (m_ctx)
SSL_CTX_free(m_ctx);
m_ssl = NULL;
m_ctx = NULL;
m_ctx = SSL_CTX_new(m_meth);
if (!m_ctx) {
EnableSSL(false);
return UTE_ERROR;
}
int certRet = OnLoadCertificates(m_ctx);
if (certRet != UTE_SUCCESS) {
EnableSSL(false);
return UTE_ERROR;
}
m_ssl = SSL_new(m_ctx);
if (!m_ssl) {
EnableSSL(false);
return UTE_ERROR;
}
return UTE_SUCCESS;
}
int CUT_WSClient::OnLoadCertificates(SSL_CTX * ctx) {
return UTE_SUCCESS;
}
int CUT_WSClient::OnSSLCertificate(const SSL * ssl, const X509* certificate, int verifyResult) {
if (certificate == NULL) {
return UTE_ERROR;
} else {
if (verifyResult == X509_V_OK) {
return UTE_SUCCESS;
} else {
return UTE_ERROR; //This should be properly handled by a subclass
}
}
return UTE_SUCCESS;
}
int CUT_WSClient::SSLSend(LPCSTR data, int len) {
if (m_isSSL && m_SSLconnected) {
return SSL_write(m_ssl, (char *)data, len);
} else {
return SocketSend(m_socket, (char *)data, len, 0);
}
}
int CUT_WSClient::SSLReceive(LPSTR buffer, int maxSize, bool peek) {
if (m_isSSL && m_SSLconnected) {
if (!peek) {
int size = SSL_read(m_ssl, (char *)buffer, maxSize);
return size;
}
else {
//return SSL_peek(m_ssl, (char *)buffer, maxSize);
int size = SSL_peek(m_ssl, (char *)buffer, maxSize);
return size;
}
} else {
return SocketRecv(m_socket, (char *)buffer, maxSize, peek?MSG_PEEK:0);
}
}
SSL_SESSION * CUT_WSClient::SSLGetCurrentSession() {
if (m_ssl)
return SSL_get_session(m_ssl);
else
return NULL;
}
int CUT_WSClient::SSLSetReuseSession(SSL_SESSION * reuseSession) {
m_reuseSession = reuseSession;
return UTE_SUCCESS;
}
/***************************************************
Send
Sends the given data to the client.
if 'len' is 0 or less then the given data is
assumed to be a NULL terminated string
Params
data - pointer to the data to send
[len] - length of the data to send
Note that the widechar version translates to
ANSI before sending.
Return
number of bytes sent
0 - on fail
****************************************************/
#if defined _UNICODE
int CUT_WSClient::Send(LPCWSTR data, int len) {
return Send(AC(data), len);}
#endif
int CUT_WSClient::Send(LPCSTR data, int len)
{
if(len <=0)
len = (int)strlen((char *)data);
int rt = SSLSend(data,len);
//TODO: onerror socket io
if(SOCKET_ERROR == rt)
return 0;
return rt;
}
/***************************************************
SendBlob
Sends information to the currently connected
client. The receive function can block until the
specified timeout. Unlike Receive, this method
waits until all the data is sent or until an
error occurs.
Params
data - pointer to data to send
dataLen - buffer length
timeOut - timeout in seconds ( 0- for no time-out)
Return
number of bytes send
0 if the connection was closed or timed-out
any other error returns SOCKET_ERROR
****************************************************/
int CUT_WSClient::SendBlob(LPBYTE data,int dataLen){
LPBYTE position = data;
int dataRemain = dataLen;
// Try to send all data
while(dataRemain > 0){
// Send as much data as we can
int dataSent = Send((LPCSTR)position, dataRemain);
if(dataSent == 0)
break;
// Move past the data sent
position += dataSent;
dataRemain -= dataSent;
}
return (int)(position - data);
}
/***************************************************
SendAsLine
Sends the given data and breaks the data up into
lines of the specified line lengths by adding
'\r\n' to the data
Params
data - data to send
len - length of the data to send
linelen - max length to send as a line
Note that the widechar version translates to
ANSI before sending.
Return
number of bytes sent
UTE_ERROR - on fail
****************************************************/
#if defined _UNICODE
int CUT_WSClient::SendAsLine(LPCWSTR data, int len,int lineLen){
return SendAsLine(AC(data), len, lineLen);}
#endif
int CUT_WSClient::SendAsLine(LPCSTR data, int len,int lineLen){
int pos,sendLen;
int rt;
int bytesSent =0;
//if the length value is less than zero then find the length
if(len < 0)
len = (int)strlen(data);
sendLen =lineLen;
for(pos =0; pos < len && !IsAborted(); pos+= lineLen){
if(sendLen > (len-pos))
sendLen = (len-pos);
rt = Send(&data[pos],sendLen);
if(rt > 0)
bytesSent += rt;
else
break;
if(Send("\r\n") <=0)
break;
}
return bytesSent;
}
/***************************************************
Send
Sends data from the datasource across the connection
Params
source - data source
Return
UTE_SUCCESS - success
UTE_ABORTED - send aborted
UTE_SOCK_NOT_OPEN - socket is not set up
UTE_DS_OPEN_FAILED - unable to open specified data source
UTE_SOCK_SEND_ERROR - remote connection terminated
****************************************************/
int CUT_WSClient::Send(CUT_DataSource & source)
{
//check to see if the socket is open
if(m_socket == INVALID_SOCKET)
return OnError(UTE_SOCK_NOT_OPEN);
int len = 0;
char buf[WSC_BUFFER_SIZE];
long bytesSent = 0;
// Open data source for reading
if(source.Open(UTM_OM_READING) == -1)
return OnError(UTE_DS_OPEN_FAILED);
int error = UTE_SUCCESS;
// Send the file
do{
if((len = source.Read(buf, sizeof(buf)-1)) <= 0)
break;
if( Send(buf, len) == 0){
error = UTE_SOCK_SEND_ERROR;
break;
}
bytesSent += len;
//send notify
if(SendFileStatus(bytesSent) == FALSE || IsAborted()) {
error = UTE_ABORTED;
break;
}
}while (len > 0);
// Close data source
source.Close();
//return success
return OnError(error);
}