-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathConnectionManager.cpp
More file actions
267 lines (220 loc) · 9.87 KB
/
ConnectionManager.cpp
File metadata and controls
267 lines (220 loc) · 9.87 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
//
// Created by Aleksey Timin on 11/18/19.
//
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <random>
#include "ConnectionManager.h"
#include "eip/CommonPacket.h"
#include "cip/connectionManager/ForwardOpenRequest.h"
#include "cip/connectionManager/ForwardCloseRequest.h"
#include "cip/connectionManager/LargeForwardOpenRequest.h"
#include "cip/connectionManager/ForwardOpenResponse.h"
#include "cip/connectionManager/NetworkConnectionParams.h"
#include "cip/connectionManager/NetworkConnectionParametersBuilder.h"
#include "utils/Logger.h"
#include "utils/Buffer.h"
namespace eipScanner {
using namespace cip::connectionManager;
using namespace utils;
using cip::MessageRouterResponse;
using cip::EPath;
using cip::GeneralStatusCodes;
using eip::CommonPacket;
using sockets::UDPSocket;
using sockets::UDPBoundSocket;
using sockets::BaseSocket;
enum class ConnectionManagerServiceCodes : cip::CipUsint {
FORWARD_OPEN = 0x54,
LARGE_FORWARD_OPEN = 0x5B,
FORWARD_CLOSE = 0x4E
};
ConnectionManager::ConnectionManager()
: ConnectionManager(std::make_shared<MessageRouter>()){
}
ConnectionManager::ConnectionManager(const MessageRouter::SPtr& messageRouter)
: _messageRouter(messageRouter)
, _connectionMap(){
std::random_device rd;
std::uniform_int_distribution<cip::CipUint> dist(0, std::numeric_limits<cip::CipUint>::max());
_incarnationId = dist(rd);
}
ConnectionManager::~ConnectionManager() = default;
IOConnection::WPtr
ConnectionManager::forwardOpen(const SessionInfoIf::SPtr& si, ConnectionParameters connectionParameters, bool isLarge) {
static int serialNumberCount = 0;
connectionParameters.connectionSerialNumber = ++serialNumberCount;
NetworkConnectionParametersBuilder o2tNCP(connectionParameters.o2tNetworkConnectionParams, isLarge);
NetworkConnectionParametersBuilder t2oNCP(connectionParameters.t2oNetworkConnectionParams, isLarge);
if (o2tNCP.getConnectionType() == NetworkConnectionParametersBuilder::MULTICAST) {
static cip::CipUint idCount = _incarnationId << 16;
connectionParameters.o2tNetworkConnectionId = ++idCount;
}
if (t2oNCP.getConnectionType() == NetworkConnectionParametersBuilder::P2P) {
static cip::CipUdint idCount = _incarnationId << 16;
connectionParameters.t2oNetworkConnectionId = ++idCount;
}
auto o2tSize = o2tNCP.getConnectionSize();
auto t2oSize = t2oNCP.getConnectionSize();
connectionParameters.connectionPathSize = (connectionParameters.connectionPath .size() / 2)
+ (connectionParameters.connectionPath.size() % 2);
if ((connectionParameters.transportTypeTrigger & NetworkConnectionParams::CLASS1) > 0
|| (connectionParameters.transportTypeTrigger & NetworkConnectionParams::CLASS3) > 0) {
connectionParameters.o2tNetworkConnectionParams += 2;
connectionParameters.t2oNetworkConnectionParams += 2;
}
if (connectionParameters.o2tRealTimeFormat) {
connectionParameters.o2tNetworkConnectionParams += 4;
}
if (connectionParameters.t2oRealTimeFormat) {
connectionParameters.t2oNetworkConnectionParams += 4;
}
MessageRouterResponse messageRouterResponse;
if (isLarge) {
LargeForwardOpenRequest request(connectionParameters);
messageRouterResponse = _messageRouter->sendRequest(si,
static_cast<cip::CipUsint>(ConnectionManagerServiceCodes::LARGE_FORWARD_OPEN),
EPath(6, 1), request.pack(), {});
} else {
ForwardOpenRequest request(connectionParameters);
messageRouterResponse = _messageRouter->sendRequest(si,
static_cast<cip::CipUsint>(ConnectionManagerServiceCodes::FORWARD_OPEN),
EPath(6, 1), request.pack(), {});
}
IOConnection::SPtr ioConnection;
if (messageRouterResponse.getGeneralStatusCode() == GeneralStatusCodes::SUCCESS) {
ForwardOpenResponse response;
response.expand(messageRouterResponse.getData());
Logger(LogLevel::INFO) << "Open IO connection O2T_ID=" << response.getO2TNetworkConnectionId()
<< " T2O_ID=" << response.getT2ONetworkConnectionId()
<< " SerialNumber " << response.getConnectionSerialNumber();
ioConnection.reset(new IOConnection());
ioConnection->_o2tNetworkConnectionId = response.getO2TNetworkConnectionId();
ioConnection->_t2oNetworkConnectionId = response.getT2ONetworkConnectionId();
ioConnection->_o2tAPI = response.getO2TApi();
ioConnection->_t2oAPI = response.getT2OApi();
ioConnection->_connectionTimeoutMultiplier = 4 << connectionParameters.connectionTimeoutMultiplier;
ioConnection->_serialNumber = response.getConnectionSerialNumber();
ioConnection->_transportTypeTrigger = connectionParameters.transportTypeTrigger;
ioConnection->_o2tRealTimeFormat = connectionParameters.o2tRealTimeFormat;
ioConnection->_t2oRealTimeFormat = connectionParameters.t2oRealTimeFormat;
ioConnection->_connectionPath = connectionParameters.connectionPath;
ioConnection->_originatorVendorId = connectionParameters.originatorVendorId;
ioConnection->_originatorSerialNumber = connectionParameters.originatorSerialNumber;
ioConnection->_o2tDataSize = o2tSize;
ioConnection->_t2oDataSize = t2oSize;
ioConnection->_o2tFixedSize = (o2tNCP.getType() == NetworkConnectionParametersBuilder::FIXED);
ioConnection->_t2oFixedSize = (t2oNCP.getType() == NetworkConnectionParametersBuilder::FIXED);
const eip::CommonPacketItem::Vec &additionalItems = messageRouterResponse.getAdditionalPacketItems();
auto o2tSockAddrInfo = std::find_if(additionalItems.begin(), additionalItems.end(),
[](auto item) { return item.getTypeId() == eip::CommonPacketItemIds::O2T_SOCKADDR_INFO; });
if (o2tSockAddrInfo != additionalItems.end()) {
Buffer sockAddrBuffer(o2tSockAddrInfo->getData());
sockets::EndPoint endPoint("",0);
sockAddrBuffer >> endPoint;
if (endPoint.getHost() == "0.0.0.0") {
ioConnection->_socket = std::make_unique<UDPBoundSocket>(
si->getRemoteEndPoint().getHost(), endPoint.getPort());
} else {
ioConnection->_socket = std::make_unique<UDPBoundSocket>(endPoint);
}
} else {
ioConnection->_socket = std::make_unique<UDPBoundSocket>(si->getRemoteEndPoint().getHost(), EIP_DEFAULT_IMPLICIT_PORT);
}
Logger(LogLevel::INFO) << "Open UDP socket to send data to "
<< ioConnection->_socket->getRemoteEndPoint().toString();
findOrCreateSocket(sockets::EndPoint(si->getRemoteEndPoint().getHost(), EIP_DEFAULT_IMPLICIT_PORT));
auto result = _connectionMap
.insert(std::make_pair(response.getT2ONetworkConnectionId(), ioConnection));
if (!result.second) {
Logger(LogLevel::ERROR)
<< "Connection with T2O_ID=" << response.getT2ONetworkConnectionId()
<< " already exists.";
}
} else {
logGeneralAndAdditionalStatus(messageRouterResponse);
}
return ioConnection;
}
IOConnection::WPtr
ConnectionManager::largeForwardOpen(const SessionInfoIf::SPtr& si, ConnectionParameters connectionParameters) {
return forwardOpen(si, connectionParameters, true);
}
void ConnectionManager::forwardClose(const SessionInfoIf::SPtr& si, const IOConnection::WPtr& ioConnection) {
if (auto ptr = ioConnection.lock()) {
ForwardCloseRequest request;
request.setConnectionPath(ptr->_connectionPath);
request.setConnectionSerialNumber(ptr->_serialNumber);
request.setOriginatorVendorId(ptr->_originatorVendorId);
request.setOriginatorSerialNumber(ptr->_originatorSerialNumber);
Logger(LogLevel::INFO) << "Close connection connection T2O_ID="
<< ptr->_t2oNetworkConnectionId;
auto messageRouterResponse = _messageRouter->sendRequest(si,
static_cast<cip::CipUsint>(ConnectionManagerServiceCodes::FORWARD_CLOSE),
EPath(6, 1), request.pack());
if (messageRouterResponse.getGeneralStatusCode() != GeneralStatusCodes::SUCCESS) {
Logger(LogLevel::WARNING)
<< "Failed to close the connection in target with error=0x"
<< std::hex
<< messageRouterResponse.getGeneralStatusCode()
<< ". But the connection is removed from ConnectionManager anyway";
}
auto rc = _connectionMap.erase(ptr->_t2oNetworkConnectionId);
(void) rc;
assert(rc);
} else {
Logger(LogLevel::WARNING) << "Attempt to close an already closed connection";
}
}
void ConnectionManager::handleConnections(std::chrono::milliseconds timeout) {
std::vector<BaseSocket::SPtr > sockets;
std::transform(_socketMap.begin(), _socketMap.end(), std::back_inserter(sockets), [](auto entry) {
auto fd = entry.second->getSocketFd();
(void) fd;
return entry.second;
});
BaseSocket::select(sockets, timeout);
std::vector<cip::CipUdint> connectionsToClose;
for (auto& entry : _connectionMap) {
if (!entry.second->notifyTick()) {
connectionsToClose.push_back(entry.first);
}
}
for (auto& id : connectionsToClose) {
_connectionMap.erase(id);
}
}
UDPBoundSocket::SPtr ConnectionManager::findOrCreateSocket(const sockets::EndPoint& endPoint) {
auto socket = _socketMap.find(endPoint);
if (socket == _socketMap.end()) {
auto newSocket = std::make_shared<UDPBoundSocket>(endPoint);
_socketMap[endPoint] = newSocket;
newSocket->setBeginReceiveHandler([](sockets::BaseSocket& sock) {
(void) sock;
Logger(LogLevel::DEBUG) << "Received something";
});
newSocket->setBeginReceiveHandler([this](BaseSocket& sock) {
auto recvData = sock.Receive(8192);
CommonPacket commonPacket;
commonPacket.expand(recvData);
// TODO: Check TypeIDs and sequence of the packages
Buffer buffer(commonPacket.getItems().at(0).getData());
cip::CipUdint connectionId;
buffer >> connectionId;
Logger(LogLevel::DEBUG) << "Received data from connection T2O_ID=" << connectionId;
auto io = _connectionMap.find(connectionId);
if (io != _connectionMap.end()) {
io->second->notifyReceiveData(commonPacket.getItems().at(1).getData());
} else {
Logger(LogLevel::ERROR) << "Received data from unknown connection T2O_ID=" << connectionId;
}
});
return newSocket;
}
return socket->second;
}
bool ConnectionManager::hasOpenConnections() const {
return !_connectionMap.empty();
}
}