forked from ethereum/aleth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetConnection.cpp
More file actions
369 lines (313 loc) · 9.56 KB
/
NetConnection.cpp
File metadata and controls
369 lines (313 loc) · 9.56 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
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file NetConnection.cpp
* @author Alex Leverington <nessence@gmail.com>
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include <memory>
#include "NetConnection.h"
#include "NetMsg.h"
using namespace std;
using namespace dev;
NetConnection::NetConnection(boost::asio::io_service& _io_service):
m_socket(_io_service),
m_stopped(true),
m_originateConnection(false),
m_socketError()
{
m_stopped = true;
m_started = false;
}
NetConnection::NetConnection(boost::asio::io_service& _io_service, boost::asio::ip::tcp::endpoint _ep):
m_socket(_io_service),
m_endpoint(_ep),
m_stopped(true),
m_originateConnection(true),
m_socketError()
{
m_stopped = true;
m_started = false;
}
NetConnection::~NetConnection()
{
shutdown(true);
}
void NetConnection::setServiceMessageHandler(NetMsgServiceType _svc, messageHandler _h)
{
m_serviceMsgHandlers.insert(std::make_pair(_svc, _h));
}
void NetConnection::setDataMessageHandler(NetMsgServiceType _svc, messageHandler _h)
{
m_dataMsgHandlers.insert(std::make_pair(_svc, _h));
}
boost::asio::ip::tcp::socket* NetConnection::socket() {
return &m_socket;
}
void NetConnection::start()
{
assert(m_started.load() == false);
bool no = false;
if (!m_started.compare_exchange_strong(no, true))
return;
clog(RPCConnect) << (void*)this << (m_originateConnection ? "[egress]" : "[ingress]") << "start()";
if (!m_originateConnection)
handshake();
else
{
auto self(shared_from_this());
m_socket.async_connect(m_endpoint, [self, this](boost::system::error_code const& _ec)
{
if (_ec)
// todo: retry times 3 w/250ms sleep
shutdownWithError(_ec); // Connection failed
else
handshake();
});
}
}
void NetConnection::send(NetMsg const& _msg)
{
if (!m_started)
return;
lock_guard<mutex> l(x_writeQueue);
m_writeQueue.push_back(_msg.payload());
if (m_writeQueue.size() == 1 && !m_stopped)
doWrite();
}
void NetConnection::doWrite()
{
const bytes& bytes = m_writeQueue[0];
auto self(shared_from_this());
boost::asio::async_write(m_socket, boost::asio::buffer(bytes), [this, self](boost::system::error_code _ec, std::size_t /*length*/)
{
if (_ec)
return shutdownWithError(_ec);
else
{
lock_guard<mutex> l(x_writeQueue);
m_writeQueue.pop_front();
if (m_writeQueue.empty())
return;
}
doWrite();
});
}
void NetConnection::handshake(size_t _rlpLen)
{
// read header
if (m_recvdBytes == 0)
{
clog(RPCConnect) << (void*)this << (m_originateConnection ? "[egress]" : "[ingress]") << "handshake() started";
// write version packet
RLPStream s;
s.appendList(1);
s << "version";
shared_ptr<NetMsg> version(new NetMsg((NetMsgServiceType)0, 0, (NetMsgType)0, RLP(s.out())));
// as a special case, message is manually written as
// read/write isn't setup until connection is verified
auto self(shared_from_this());
boost::asio::async_write(m_socket, boost::asio::buffer(version->payload()), [this, self, version](boost::system::error_code _ec, size_t _len)
{
if (_ec)
return shutdownWithError(_ec); // handshake write failed
assert(_len);
// read length header
m_recvBuffer.resize(4);
boost::asio::async_read(m_socket, boost::asio::buffer(m_recvBuffer), [this, self](boost::system::error_code _ec, size_t _len)
{
if (_ec)
return shutdownWithError(_ec); // handshake read-header failed
if (_len == 0)
return shutdownWithError(boost::asio::error::connection_reset); // todo: reread
assert(_len == 4);
m_recvdBytes += _len;
size_t rlpLen = fromBigEndian<uint32_t>(bytesConstRef(m_recvBuffer.data(), 4));
if (rlpLen > 1024*64)
return shutdownWithError(boost::asio::error::connection_reset); // throw MessageTooLarge();
if (rlpLen < 3)
return shutdownWithError(boost::asio::error::connection_reset); // throw MessageTooSmall();
m_recvBuffer.resize(2 * (rlpLen + 4));
assert(rlpLen > 0);
assert(rlpLen < 14);
handshake(rlpLen);
});
});
return;
}
assert(_rlpLen > 0);
auto self(shared_from_this());
m_socket.async_read_some(boost::asio::buffer(boost::asio::buffer(m_recvBuffer) + m_recvdBytes), [this, self, _rlpLen](boost::system::error_code _ec, size_t _len)
{
if (_ec)
return shutdownWithError(_ec); // handshake read-data failed
m_recvdBytes += _len;
if (m_recvdBytes >= _rlpLen + 4)
{
try
{
NetMsg msg(bytesConstRef(m_recvBuffer.data(), _rlpLen + 4));
if (RLP(msg.rlp())[0].toString() == "version")
{
// It's possible for handshake to finish following shutdown
lock_guard<mutex> l(x_socketError);
if (m_started)
{
// start writes if pending messages were created during handshake
lock_guard<mutex> l(x_writeQueue);
if (m_writeQueue.size() > 0)
doWrite();
m_stopped = false;
}
else
return;
clog(RPCNote) << (m_originateConnection ? "[egress]" : "[ingress]") << "Version verified!";
}
else
clog(RPCNote) << (m_originateConnection ? "[egress]" : "[ingress]") << "Version Failed! ";
}
catch (std::exception const& _e)
{
shutdownWithError(boost::asio::error::connection_reset); // handshake failed negotiation
return;
}
m_recvdBytes = m_recvdBytes - _rlpLen - 4;
if (m_recvdBytes)
memmove(m_recvBuffer.data(), m_recvBuffer.data() + _rlpLen + 4, m_recvdBytes);
doRead();
return;
}
assert(_rlpLen > 0);
assert(_rlpLen < 14);
handshake(_rlpLen);
});
}
void NetConnection::doRead(size_t _rlpLen)
{
// Previously, shutdown wouldn't occur if _rlpLen was > 0, however with streaming protocols it's possible remote closes connection before writing a full response. Instead shutdown will defer until writes are complete (see send()).
if (m_stopped)
// if m_stopped is true it is certain shutdown already occurred
return closeSocket();
if (!_rlpLen && m_recvdBytes > 3)
{
// Read buffer if there's enough data for header
clog(RPCNote) << "NetConnection::doRead length header";
_rlpLen = fromBigEndian<uint32_t>(bytesConstRef(m_recvBuffer.data(), 4));
if (_rlpLen > 1024*1024*128)
// todo: managed via service messages and flow-control, requiring message-chunking
return shutdownWithError(boost::asio::error::connection_reset);
if (_rlpLen < 3)
return shutdownWithError(boost::asio::error::connection_reset);
if (4+2*_rlpLen > m_recvBuffer.size())
m_recvBuffer.resize(4+2*_rlpLen);
}
if (_rlpLen && m_recvdBytes >= _rlpLen + 4)
{
try
{
clog(RPCNote) << "NetConnection::doRead message";
NetMsg msg(bytesConstRef(m_recvBuffer.data(), _rlpLen + 4));
if (msg.service())
{
messageHandlers &hs = msg.type() ? m_dataMsgHandlers : m_serviceMsgHandlers;
// If handler is found, get pointer and call
auto hit = hs.find(msg.service());
if (hit!=hs.end())
hit->second(msg);
else
throw MessageServiceInvalid();
}
// else, control messages (ignored right now)
}
catch (std::exception const& _e)
{
// bad message
shutdownWithError(boost::asio::error::connection_reset); // MessageInvalid
return;
}
m_recvdBytes = m_recvdBytes - _rlpLen - 4;
if (m_recvdBytes)
memmove(m_recvBuffer.data(), m_recvBuffer.data() + _rlpLen + 4, m_recvdBytes);
doRead();
}
else
{
// otherwise read more data
auto self(shared_from_this());
m_socket.async_read_some(boost::asio::buffer(boost::asio::buffer(m_recvBuffer) + m_recvdBytes), [this, self, _rlpLen](boost::system::error_code _ec, size_t _len)
{
if (_ec)
return shutdownWithError(_ec);
assert(_len);
m_recvdBytes += _len;
doRead(_rlpLen);
});
}
}
bool NetConnection::connectionError() const
{
// Note: use of mutex here has issues
return m_socketError!=0;
}
bool NetConnection::connectionOpen() const
{
return m_stopped ? false : m_socket.is_open();
}
void NetConnection::shutdownWithError(boost::system::error_code _ec)
{
// If !started and already stopped, shutdown has already occured. (EOF or Operation canceled)
if (!m_started && m_stopped)
return;
assert(_ec);
{
lock_guard<mutex> l(x_socketError);
if (m_socketError != boost::system::error_code())
return;
m_socketError = _ec;
}
clog(RPCWarn) << (void*)this << "Socket shutdown due to error: " << _ec.message();
closeSocket();
shutdown(false);
}
void NetConnection::shutdown(bool _wait)
{
{
lock_guard<mutex> l(x_socketError);
bool yes = true;
if (!m_started.compare_exchange_strong(yes, false))
return;
// if socket never left stopped-state (pre-handshake)
if (m_stopped)
return closeSocket();
else
m_stopped = true;
// immediately close reads
// TODO: (if no error) wait for pending writes
closeSocket();
}
// when m_stopped is true, doRead will close socket
if (_wait)
while (m_socket.is_open() && !connectionError())
usleep(200);
m_recvBuffer.resize(0);
}
void NetConnection::closeSocket()
{
if (m_socket.is_open())
{
boost::system::error_code ec;
m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
m_socket.close();
}
}