Repository navigation
Expand file tree
/
Copy pathnetwork.cpp
More file actions
418 lines (384 loc) · 13 KB
/
Copy pathnetwork.cpp
File metadata and controls
418 lines (384 loc) · 13 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
#include "addrseed.h"
#include "network.h"
#include "message.h"
#include "reporter.h"
#include <bitcoin/serialize.h>
#include <bitcoin/stream.h>
#include <bitcoin/protocol.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/resource.h>
#include <netinet/tcp.h>
#include <errno.h>
#include <fcntl.h>
#include <vector>
#include <iostream>
extern ReporterInterface *gReporter;
static const int DRAIN_SEED_SIZE_PER_LOOP = 128;
bool Connection::sendBuffer(bool &moreWrite)
{
while (!sendingBuffer.empty()) {
std::vector<unsigned char> &buffer = sendingBuffer.front();
int bytesToSend = buffer.size() - sendPos;
if (bytesToSend <= 0) {
sendPos = 0;
sendingBuffer.pop_front();
continue;
}
int wsize = write(sock, &buffer[0] + sendPos, bytesToSend);
if (wsize < 0) {
if (errno != EWOULDBLOCK || errno != EINPROGRESS || errno != EINTR) {
printf("send buffer error: %s\n", strerror(errno));
return false;
}
break;
} else {
sendPos += wsize;
if (wsize != bytesToSend) {
// partial write
break;
} else {
sendPos = 0;
sendingBuffer.pop_front();
}
}
}
moreWrite = !sendingBuffer.empty();
return true;
}
void Connection::processMessage(uint32_t version, CMessageHeader &header, const std::vector<unsigned char> &buffer, size_t offset)
{
std::string command(header.command);
CVectorReader tmpVreader(false, SER_NETWORK, 0, buffer, offset+MESSAGE_HEADER_SIZE);
if (command == "version") {
tmpVreader >> youVersion >> youServices;
CVectorReader vreader(false, SER_NETWORK, youVersion, buffer, offset+MESSAGE_HEADER_SIZE);
CVersionPayload payload;
vreader >> payload;
if (gReporter != nullptr) {
gReporter->reportVersionedAddr(addrYou.ToStringIP(), addrYou.GetPort(), payload.user_agent, payload.version, payload.services);
}
printf("version command: addrme=%s, addryou=%s, agent=%s, version=%d, services=%lu\n",
payload.addrMe.ToString().c_str(), addrYou.ToString().c_str(), payload.user_agent.c_str(),
payload.version, payload.services);
pushVerackCommand();
} else if (command == "ping") {
uint64_t nonce;
tmpVreader >> nonce;
pushPongCommand(nonce);
} else if (command == "addr") {
CVectorReader vreader(true, SER_NETWORK, version, buffer, offset+MESSAGE_HEADER_SIZE);
uint32_t count = ReadVarInt<CVectorReader, VarIntMode::DEFAULT, uint32_t>(vreader);
CAddress addr;
for (auto i = 0; i < count; ++i) {
// assume valid
vreader >> addr;
printf("got new address from %s: %s\n", addrYou.ToString().c_str(), addr.ToString().c_str());
CAddrSeed::getInstance().addNewAddr(addr);
}
}
}
bool Connection::readBuffer(uint32_t version)
{
unsigned char tmpBuffer[16 * 1024];
int nread = read(sock, tmpBuffer, sizeof(tmpBuffer));
if (nread == 0) {
// peer close
printf("peer %s closed connection\n", addrYou.ToString().c_str());
return false;
} else if (nread < 0) {
if (errno != EWOULDBLOCK || errno != EINPROGRESS || errno != EINTR) {
printf("read error %d:%s\n", errno, strerror(errno));
return false;
}
return true;
}
vReadBuffer.insert(vReadBuffer.end(), tmpBuffer, tmpBuffer + nread);
size_t offset = 0;
CVectorReader vreader(false, SER_NETWORK, version, vReadBuffer, 0);
while (vReadBuffer.size() >= offset + MESSAGE_HEADER_SIZE) {
if (!headerValid) {
headerValid = true;
vreader >> header;
if (header.magic != MAIN_MAGIC) {
// printf("Invalid magic in header from %s: %#x\n", addrYou.ToString().c_str(), header.magic);
return false;
}
} else {
vreader.skip(MESSAGE_HEADER_SIZE);
}
if (vReadBuffer.size() < header.payloadLength + MESSAGE_HEADER_SIZE + offset) {
break;
}
processMessage(version, header, vReadBuffer, offset);
headerValid = false;
offset += header.payloadLength + MESSAGE_HEADER_SIZE;
vreader.skip(header.payloadLength);
}
if (offset > 0) {
size_t leftSize = vReadBuffer.size() - offset;
memcpy(&vReadBuffer[0], &vReadBuffer[offset], leftSize);
vReadBuffer.resize(leftSize);
}
return true;
}
bool Connection::pushCommand()
{
sendingBuffer.push_back(std::move(vSendBuffer));
return true;
}
bool Connection::pushVersionCommand(uint32_t version)
{
vSendBuffer.clear();
vSendBuffer.resize(MESSAGE_HEADER_SIZE);
CVersionPayload versionPayload;
versionPayload.version = version;
versionPayload.services = static_cast<uint64_t>(NODE_NETWORK);
versionPayload.timestamp = time(nullptr);
versionPayload.addrMe = CAddress(addrMe, version, versionPayload.timestamp);
versionPayload.addrYou = CAddress(addrYou, version, versionPayload.timestamp);
versionPayload.nonce = versionPayload.timestamp;
versionPayload.user_agent = "/Satoshi:0.14.2/";
versionPayload.start_height = 0;
versionPayload.relay = false;
CVectorWriter{false, SER_NETWORK, version, vSendBuffer, MESSAGE_HEADER_SIZE, versionPayload};
unsigned char hash[32];
dsha256(&vSendBuffer[MESSAGE_HEADER_SIZE], vSendBuffer.size() - MESSAGE_HEADER_SIZE, hash);
CMessageHeader hdr(MAIN_MAGIC, "version", vSendBuffer.size() - MESSAGE_HEADER_SIZE, hash);
CVectorWriter{false, SER_NETWORK, version, vSendBuffer, 0, hdr};
return pushCommand();
}
bool Connection::pushPongCommand(uint64_t nonce)
{
vSendBuffer.resize(0);
CVectorWriter{false, SER_NETWORK, 0, vSendBuffer, MESSAGE_HEADER_SIZE, nonce};
unsigned char hash[32];
dsha256(&vSendBuffer[MESSAGE_HEADER_SIZE], vSendBuffer.size() - MESSAGE_HEADER_SIZE, hash);
CMessageHeader hdr(MAIN_MAGIC, "pong", vSendBuffer.size() - MESSAGE_HEADER_SIZE, hash);
CVectorWriter{false, SER_NETWORK, 0, vSendBuffer, 0, hdr};
return pushCommand();
}
bool Connection::initializeAddress()
{
assert(sock > 0);
struct sockaddr sa;
memset(&sa, 0, sizeof(sa));
socklen_t slen = sizeof(sa);
// ignore error
getsockname(sock, &sa, &slen);
addrMe = CService(&sa);
memset(&sa, 0, sizeof(sa));
getpeername(sock, &sa, &slen);
addrYou = CService(&sa);
return true;
}
bool Connection::pushVerackCommand()
{
vSendBuffer.clear();
unsigned char hash[32];
const unsigned char p[] = "";
dsha256(p, 0, hash);
CMessageHeader hdr(MAIN_MAGIC, "verack", 0, hash);
CVectorWriter{false, SER_NETWORK, 0, vSendBuffer, 0, hdr};
return pushCommand();
}
NetworkCallback *ConnectionManager::initiateConnection(const CService &saddr, int &sock)
{
struct sockaddr addr;
socklen_t addrlen = sizeof(addr);
printf("initiate connection to %s\n", saddr.ToString().c_str());
saddr.GetSockAddr(&addr, &addrlen);
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
return nullptr;
}
Connection &con = *addConnection(saddr, sock);
int flag = fcntl(sock, F_GETFL, 0);
if ( -1 == flag ) {
close(sock);
sock = -1;
return nullptr;
}
fcntl(sock, F_SETFL, flag | O_NONBLOCK);
int on = 1;
int ret = setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
if (-1 == ret) {
close(sock);
sock = -1;
return nullptr;
}
ret = connect(sock, &addr, sizeof(addr));
if (ret == -1) {
int err = errno;
if (err == EINPROGRESS || err == EWOULDBLOCK) {
// connecting
con.status = CONNECTING;
} else {
close(sock);
sock = -1;
return nullptr;
}
} else {
con.initializeAddress();
con.status = CONNECTED;
}
auto cb = std::bind(&ConnectionManager::networkCallback, this, sock,
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
callbacks[sock] = cb;
qSocks.push_back(sock);
return &callbacks[sock];
}
Connection *ConnectionManager::addConnection(const CService &addr, int sock)
{
if (sock < 0) {
return nullptr;
}
Connection con(sock, addr);
connections[sock] = con;
return &connections[sock];
}
int ConnectionManager::evictSock()
{
if (!qSocks.empty()) {
int sock = qSocks.front();
qSocks.pop_front();
return sock;
}
return -1;
}
void ConnectionManager::closeConnection(int sock)
{
if (connections.count(sock) <= 0) {
return;
}
connections.erase(sock);
callbacks.erase(sock);
close(sock);
}
bool ConnectionManager::networkCallback(int sock, const struct event &event, int &rsock, bool &moreWrite)
{
Connection &conn = connections[sock];
rsock = sock;
if (event.write) {
if (conn.status < CONNECTED) {
printf("connection to %s success\n", conn.addrYou.ToString().c_str());
conn.initializeAddress();
conn.status = VERSION_SENT;
conn.pushVersionCommand(mVersion);
} else {
if (conn.status == CONNECTED) {
conn.pushVersionCommand(mVersion);
conn.status = VERSION_SENT;
}
}
return conn.sendBuffer(moreWrite);
} else if (event.read) {
int ret = conn.readBuffer(conn.youVersion);
moreWrite = !conn.sendingBuffer.empty();
return ret;
} else if (event.error) {
return false;
}
return false;
}
bool NetworkEngine::initEngine()
{
sp = sp_create(1024);
if (sp == -1) {
return false;
}
int flag = fcntl(sp, F_GETFL, 0);
if ( -1 == flag ) {
close(sp);
sp = -1;
return false;
}
fcntl(sp, F_SETFL, flag | O_NONBLOCK);
struct rlimit limit;
if (getrlimit(RLIMIT_NOFILE, &limit) < 0) {
printf("getrlimit error");
return false;
}
maxConnections = limit.rlim_cur - 10;
return true;
}
void NetworkEngine::startEngine()
{
std::vector<CService *> addrs;
addrs.reserve(DRAIN_SEED_SIZE_PER_LOOP);
size_t newSize;
while (true) {
newSize = DRAIN_SEED_SIZE_PER_LOOP;
addrs.resize(0);
CAddrSeed::getInstance().getNewAddrs(addrs, newSize, false);
for (auto paddr: addrs) {
int sock = -1;
if (connMan.connectionCount() >= maxConnections) {
int esock = connMan.evictSock();
if (esock > 0) {
sp_del(sp, esock);
nPendingEvents--;
connMan.closeConnection(esock);
}
}
auto pCallback = connMan.initiateConnection(*paddr, sock);
if (sock < 0) {
printf("initiate connection to %s failed: %s\n", paddr->ToString().c_str(), strerror(errno));
continue;
}
int ret = sp_add(sp, sock, reinterpret_cast<void *>(pCallback));
if (ret < 0) {
printf("sp_add_write error: %s\n", strerror(errno));
sp_del(sp, sock);
nPendingEvents--;
connMan.closeConnection(sock);
continue;
}
writeEnabled[sock] = true;
}
nPendingEvents += newSize;
if (nPendingEvents > events.size()) {
events.resize(nPendingEvents); }
int nActiveEvents = sp_wait(sp, &events[0], nPendingEvents, nullptr);
dispatchNetworkEvents(nActiveEvents);
}
}
void NetworkEngine::dispatchNetworkEvents(int nActiveEvents)
{
std::vector<int> closeSocks;
for (auto i = 0; i < nActiveEvents; ++i) {
const struct event &event = events[i];
NetworkCallback *callback = reinterpret_cast<NetworkCallback *>(event.ud);
int sock;
bool moreWrite;
if(!(*callback)(event, sock, moreWrite)) {
sp_del(sp, sock);
closeSocks.push_back(sock);
continue;
}
if (moreWrite) {
if (!writeEnabled[sock]) {
int ret = sp_enable_write(sp, sock, reinterpret_cast<void *>(connMan.getNetworkCallback(sock)));
if (ret == -1) {
printf("sp_enable_write sock=%d failed: %s\n", sock, strerror(errno));
}
writeEnabled[sock] = true;
}
} else {
if (writeEnabled[sock]) {
int ret = sp_disable_write(sp, sock, reinterpret_cast<void *>(connMan.getNetworkCallback(sock)));
if (ret == -1) {
printf("sp_disable_write sock=%d failed\n", sock);
}
writeEnabled[sock] = false;
}
}
}
for (auto sock: closeSocks) {
connMan.closeConnection(sock);
}
}