-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStartTls-Example.cpp
More file actions
233 lines (187 loc) · 7.9 KB
/
StartTls-Example.cpp
File metadata and controls
233 lines (187 loc) · 7.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
/* Copyright (C) 2016-2019 Thomas Hauck - All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
The author would be happy if changes and
improvements were reported back to him.
Author: Thomas Hauck
Email: Thomas@fam-hauck.de
*/
#include <thread>
#include <sstream>
#include <iomanip>
#include <iostream>
#include "SocketLib/SocketLib.h"
using namespace std;
#if defined (_WIN32) || defined (_WIN64)
#include <conio.h>
#else // Linux
#include <termios.h>
void _getch()
{
struct termios t;
tcgetattr(fileno(stdin), &t);
t.c_lflag &= ~ICANON;
tcsetattr(fileno(stdin), TCSANOW, &t);
getchar();
t.c_lflag |= ICANON;
tcsetattr(fileno(stdin), TCSANOW, &t);
}
#endif
void ServerThread(const bool* bStop)
{
TcpServer sock;
bool bClientConnected = false;
// 3 callback function to handle the server socket events
sock.BindErrorFunction([&](BaseSocket* pSock) { cout << "Server: socket error" << endl << flush; pSock->Close(); }); // Must call Close function
sock.BindCloseFunction([&](BaseSocket*) { cout << "Server: socket closing" << endl << flush; });
sock.BindNewConnection([&](const vector<TcpSocket*>& lstSockets)
{
// a list with sockets new connected
for (auto& pSocket : lstSockets)
{
if (pSocket != nullptr)
{
bClientConnected = true;
// 3 callback functions to handle the sockets events
pSocket->BindFuncBytesReceived([&](TcpSocket* pSock)
{
const size_t nAvalible = pSock->GetBytesAvailable();
if (nAvalible == 0) // Socket closed on remote
{
pSock->Close();
return;
}
auto spBuffer = make_unique<uint8_t[]>(nAvalible + 1);
const size_t nRead = pSock->Read(spBuffer.get(), nAvalible);
if (nRead > 0)
{
string strRec(nRead, 0);
copy(&spBuffer[0], &spBuffer[nRead], &strRec[0]);
if (strRec == "STARTTLS")
{
SslTcpSocket* pSslTcpSocket = SslTcpSocket::SwitchToSll(pSock);
pSock->SelfDestroy();
if (pSslTcpSocket->AddServerCertificate("certs/ca-root.crt", "certs/127-0-0-1.crt", "certs/127-0-0-1-key.pem", nullptr) == false)
{
cout << "Server: can't load certificate" << endl;
pSslTcpSocket->Close();
return;
}
pSslTcpSocket->SetAcceptState();
pSslTcpSocket->StartReceiving();
pSslTcpSocket->Write("Server Hello Message with TLS", 29);
return;
}
stringstream strOutput;
strOutput << pSock->GetClientAddr() << " - Server received: " << nRead << " Bytes, \"" << strRec << "\"" << endl;
cout << strOutput.str() << flush;
strRec = "Server echo: " + strRec;
pSock->Write(&strRec[0], strRec.size());
//pSock->Close(); // Optional, if you don't close the socket, the connection stays open
}
});
pSocket->BindErrorFunction([&](BaseSocket* pSock)
{
// there was an error, we close the socket
pSock->Close();
cout << "Server: accept socket error" << endl << flush;
});
pSocket->BindCloseFunction([&](BaseSocket* pSock)
{
// We let the socket destroy it self, use this on sockets received by the server
bClientConnected = false;
cout << "Server: accept socket closing" << endl << flush;
});
pSocket->StartReceiving(); // start to receive data
pSocket->Write("Server Hello Message none TLS", 29);
}
}
});
// start der server socket
const bool bCreated = sock.Start("0.0.0.0", 3461); // IPv6 use "::1" as address
while (*bStop == false || bClientConnected == true)
{
this_thread::sleep_for(chrono::milliseconds(10));
}
// Closing the server socket will not call the close callback
sock.Close();
}
void ClientThread(const bool* bStop)
{
auto sock = make_unique<TcpSocket>();
bool bIsClosed = false;
bool bFirstConnect = false;
// client socket has 4 callback function
sock->BindErrorFunction([&](BaseSocket* pSock) { cout << "Client: socket error" << endl << flush; pSock->Close(); }); // Must call Close function
sock->BindCloseFunction([&](BaseSocket*) { cout << "Client: socket closing" << endl << flush; bIsClosed = true; });
sock->BindFuncBytesReceived([&](TcpSocket* pTcpSocket)
{
const size_t nAvalible = pTcpSocket->GetBytesAvailable();
if (nAvalible == 0) // Socket closed on remote
{
pTcpSocket->Close();
return;
}
auto spBuffer = make_unique<unsigned char[]>(nAvalible + 1);
const size_t nRead = pTcpSocket->Read(spBuffer.get(), nAvalible);
if (nRead > 0)
{
string strRec(nRead, 0);
copy(&spBuffer[0], &spBuffer[nRead], &strRec[0]);
stringstream strOutput;
strOutput << pTcpSocket->GetClientAddr() << " - Client received: " << nRead << " Bytes, \"" << strRec << "\"" << endl;
cout << strOutput.str() << flush;
}
});
sock->BindFuncConEstablished([&](TcpSocket* pTcpSocket)
{
if (bFirstConnect == false)
{
bFirstConnect = true; // The Function will be called twice, after the TLS is established
pTcpSocket->Write("STARTTLS", 8);
// we wait until the STARTTLS message is send
while (pTcpSocket->GetOutBytesInQue() > 0)
this_thread::sleep_for(chrono::milliseconds(10));
auto pSslTcpSocket = make_unique<SslTcpSocket>(pTcpSocket); // Make a new SslSocket
pTcpSocket->SelfDestroy(); // The current TcpSocket should delete it self, after the Callback return
// https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt
pSslTcpSocket->SetTrustedRootCertificates("certs/ca-root.crt");
pSslTcpSocket->SetConnectState();
pSslTcpSocket->StartReceiving();
sock = move(pSslTcpSocket); // We use the new TlsSocket from here on
return;
}
pTcpSocket->Write("Message in TLS connection", 25);
});
const bool bConnected = sock->Connect("127.0.0.1", 3461);
if (bConnected == false)
cout << "error creating client socket" << endl << flush;
while (*bStop == false)
{
this_thread::sleep_for(chrono::milliseconds(10));
}
if (bIsClosed == false)
{
sock->Close();
// We wait until the callback above was called
while (bIsClosed == false)
this_thread::sleep_for(chrono::milliseconds(10));
}
}
int main(int argc, const char* argv[])
{
#if defined(_WIN32) || defined(_WIN64)
// Detect Memory Leaks
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG));
#endif
bool bStop = false;
thread thServer = thread(bind(ServerThread, &bStop));
// we wait a second that the server is ready
this_thread::sleep_for(chrono::milliseconds(1000));
thread thClient = thread(bind(ClientThread, &bStop));
_getch();
bStop = true;
thServer.join();
thClient.join();
return 0;
}