File: UDPListener.cpp

package info (click to toggle)
spring 88.0%2Bdfsg1-1.1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 41,524 kB
  • sloc: cpp: 343,114; ansic: 38,414; python: 12,257; java: 12,203; awk: 5,748; sh: 1,204; xml: 997; perl: 405; objc: 192; makefile: 181; php: 134; sed: 2
file content (228 lines) | stat: -rwxr-xr-x 5,898 bytes parent folder | download
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
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */

#include "UDPListener.h"

#ifdef _MSC_VER
#	include "System/Platform/Win/win32.h"
#elif defined(_WIN32)
#	include <windows.h>
#endif

#include <boost/weak_ptr.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
#include <list>
#include <queue>

#include "System/mmgr.h"

#include "ProtocolDef.h"
#include "UDPConnection.h"
#include "Socket.h"
#include "System/Log/ILog.h"
#include "System/Platform/errorhandler.h"
#include "System/Util.h" // for IntToString (header only)

namespace netcode
{
using namespace boost::asio;

UDPListener::UDPListener(int port, const std::string& ip)
	: acceptNewConnections(false)
{
	SocketPtr socket;

	if (UDPListener::TryBindSocket(port, &socket, ip)) {
		boost::asio::socket_base::non_blocking_io socketCommand(true);
		socket->io_control(socketCommand);

		mySocket = socket;
		SetAcceptingConnections(true);
	}

	if (IsAcceptingConnections()) {
		LOG("[UDPListener] successfully bound socket on port %i", port);
	} else {
		handleerror(NULL, "[UDPListener] error: unable to bind UDP port, see log for details.", "Network error", MBF_OK | MBF_EXCL);
	}
}

bool UDPListener::TryBindSocket(int port, SocketPtr* socket, const std::string& ip) {

	std::string errorMsg = "";

	try {
		ip::address addr;
		boost::system::error_code err;

		socket->reset(new ip::udp::socket(netservice));
		(*socket)->open(ip::udp::v6(), err); // test IP v6 support

		const bool supportsIPv6 = !err;

		addr = WrapIP(ip, &err);
		if (ip.empty()) {
			// use the "any" address
			if (supportsIPv6) {
				addr = ip::address_v6::any();
			} else {
				addr = ip::address_v4::any();
			}
		} else if (err) {
			throw std::runtime_error("Failed to parse address " + ip + ": " + err.message());
		}

		if (!supportsIPv6 && addr.is_v6()) {
			throw std::runtime_error("IP v6 not supported, can not use address " + addr.to_string());
		}

		if (netcode::IsLoopbackAddress(addr)) {
			LOG_L(L_WARNING, "Opening socket on loopback address. Other users will not be able to connect!");
		}

		if (!addr.is_v6()) {
			if (supportsIPv6) {
				(*socket)->close();
			}
			(*socket)->open(ip::udp::v4(), err);
			if (err) {
				throw std::runtime_error("Failed to open IP V4 socket: " + err.message());
			}
		}

		if ((port < 0) || (port > 65535)) {
			throw std::range_error("Port is out of range [0, 65535]: " + IntToString(port));
		}

		LOG("Binding UDP socket to IP %s %s port %i",
				(addr.is_v6() ? "(v6)" : "(v4)"), addr.to_string().c_str(),
				port);
		(*socket)->bind(ip::udp::endpoint(addr, port));
	} catch (const std::runtime_error& ex) { // includes boost::system::system_error and std::range_error
		socket->reset();
		errorMsg = ex.what();
		if (errorMsg.empty()) {
			errorMsg = "Unknown problem";
		}
	}
	const bool isBound = errorMsg.empty();

	if (!isBound) {
		LOG_L(L_ERROR, "Failed to bind UDP socket on IP %s, port %i: %s",
				ip.c_str(), port, errorMsg.c_str());
	}

	return isBound;
}

void UDPListener::Update() {
	netservice.poll();

	size_t bytes_avail = 0;

	while ((bytes_avail = mySocket->available()) > 0) {
		std::vector<uint8_t> buffer(bytes_avail);
		ip::udp::endpoint sender_endpoint;
		boost::asio::ip::udp::socket::message_flags flags = 0;
		boost::system::error_code err;
		size_t bytesReceived = mySocket->receive_from(boost::asio::buffer(buffer), sender_endpoint, flags, err);

		ConnMap::iterator ci = conn.find(sender_endpoint);
		bool knownConnection = (ci != conn.end());

		if (knownConnection && ci->second.expired())
			continue;

		if (CheckErrorCode(err))
			break;

		if (bytesReceived < Packet::headerSize)
			continue;

		Packet data(&buffer[0], bytesReceived);

		if (knownConnection) {
			ci->second.lock()->ProcessRawPacket(data);
		}
		else { // still have the packet (means no connection with the sender's address found)
			if (acceptNewConnections && data.lastContinuous == -1 && data.nakType == 0)	{
				if (!data.chunks.empty() && (*data.chunks.begin())->chunkNumber == 0) {
					// new client wants to connect
					boost::shared_ptr<UDPConnection> incoming(new UDPConnection(mySocket, sender_endpoint));
					waiting.push(incoming);
					conn[sender_endpoint] = incoming;
					incoming->ProcessRawPacket(data);
				}
			}
			else {
				LOG_L(L_WARNING, "Dropping packet from unknown IP: [%s]:%i",
						sender_endpoint.address().to_string().c_str(),
						sender_endpoint.port());
			}
		}
	}

	for (ConnMap::iterator i = conn.begin(); i != conn.end(); ) {
		if (i->second.expired()) {
			i = set_erase(conn, i);
			continue;
		}
		i->second.lock()->Update();
		++i;
	}
}

boost::shared_ptr<UDPConnection> UDPListener::SpawnConnection(const std::string& ip, const unsigned port)
{
	boost::shared_ptr<UDPConnection> newConn(new UDPConnection(mySocket, ip::udp::endpoint(WrapIP(ip), port)));
	conn[newConn->GetEndpoint()] = newConn;
	return newConn;
}

void UDPListener::SetAcceptingConnections(const bool enable)
{
	acceptNewConnections = enable;
}

bool UDPListener::IsAcceptingConnections() const
{
	return acceptNewConnections;
}

bool UDPListener::HasIncomingConnections() const
{
	return !waiting.empty();
}

boost::weak_ptr<UDPConnection> UDPListener::PreviewConnection()
{
	return waiting.front();
}

boost::shared_ptr<UDPConnection> UDPListener::AcceptConnection()
{
	boost::shared_ptr<UDPConnection> newConn = waiting.front();
	waiting.pop();
	conn[newConn->GetEndpoint()] = newConn;
	return newConn;
}

void UDPListener::RejectConnection()
{
	waiting.pop();
}

void UDPListener::UpdateConnections() {
	for (ConnMap::iterator i = conn.begin(); i != conn.end(); ) {
		boost::shared_ptr<UDPConnection> uc = i->second.lock();
		if (uc && i->first != uc->GetEndpoint()) {
			conn[uc->GetEndpoint()] = uc; // inserting does not invalidate iterators
			i = set_erase(conn, i);
		}
		else
			++i;
	}
}

}