Project::OSiRiON - Git repositories
Project::OSiRiON
News . About . Screenshots . Downloads . Forum . Wiki . Tracker . Git
summaryrefslogtreecommitdiff
blob: 55480d266b6df5ee8a08b31fd5622ec44c62200a (plain)
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
/*
   net/netconnection.cc
   This file is part of the Osirion project and is distributed under
   the terms of the GNU General Public License version 2
*/

#include <sstream>

#include "sys/sys.h"
#include "core/application.h"
#include "core/gameconnection.h"
#include "core/netconnection.h"
#include "core/player.h"
#include "core/stats.h"

namespace core 
{

NetConnection::NetConnection()
{
	connection_timeout = core::application()->time();
	connection_state = Connecting;
}

NetConnection::~NetConnection()
{
	disconnect();
}

void NetConnection::abort()
{
	connection_error= true;
}

void NetConnection::connect(std::string const &to_host, int to_port)
{
	connection_error = false;
	connection_fd = -1;
	connection_state = Connecting;

	if (valid())
		return;
		
	// resolve serverhostname
	struct hostent *serverhostent;
	serverhostent = gethostbyname(to_host.c_str());
	if (!serverhostent) {
		con_warn << "Could not resolve '" << to_host.c_str() << "'" << std::endl;
		abort();
		return;
	}
	
	// Get a socket file descriptor
	connection_fd = socket(PF_INET, SOCK_DGRAM, 0);
	if (connection_fd == -1) {
		//con_error << "Network socket() failed!" << std::endl;
		abort();
		return;
	}
	
	// make the connection
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(to_port);
	// FIXME inet_addr can still fail
	server_addr.sin_addr.s_addr = inet_addr(inet_ntoa(*((struct in_addr *)serverhostent->h_addr)));
	memset(server_addr.sin_zero, '\0', sizeof server_addr.sin_zero);
	if (server_addr.sin_addr.s_addr == INADDR_NONE) {
		con_error << "Network invalid address " << to_host << "!" << std::endl;
		abort();
		return;
	}
	
	connection_host = to_host;
	connection_port = to_port;
	connection_error = false;

	FD_ZERO(&clientset);
#ifdef _WIN32
	FD_SET((unsigned int) fd(), &clientset);
#else
	FD_SET(fd(), &clientset);
#endif

	connection_timeout = application()->time();
	connection_keepalive = application()->time();

	game()->localplayer()->player_dirty = true;

	con_print << "Connecting to " << inet_ntoa(*((struct in_addr *)serverhostent->h_addr))  << ":" << to_port << "..." << std::endl;
}

void NetConnection::disconnect()
{
	if (connection_fd != -1) {
		sendq.clear();
		sendq.assign("disconnect\n");
		transmit();

		FD_ZERO(&clientset);
#ifdef _WIN32
		closesocket(connection_fd);
#else
		close(connection_fd);
#endif
	}
	
	connection_fd = -1;
	connection_error = false;
	connection_host.clear();
	connection_port = 0;
	connection_state = Connecting;
}

bool NetConnection::has_messages() const
{
	return (recvq.size() > 0);
}

void NetConnection::retreive(std::string & message)
{
	if (recvq.size() > 0) {
		message.assign(recvq.front());
		recvq.pop_front();
	} else {
		message.clear();
	}
}

// receive data and decode it into lines
void NetConnection::receive()
{
	// TODO: binary mode data transfer
	if (error() || invalid())
		return;

	ssize_t		bytes_received;
	
	memset(recvbuf, '\0', BLOCKSIZE);
	bytes_received = ::recv(connection_fd, recvbuf, BLOCKSIZE-1, 0);
	Stats::network_bytes_received += bytes_received;
	connection_timeout = core::application()->time();

	if (bytes_received == 0) {
		con_print << "Disconnected.";
		abort();
		return;
	} else if (bytes_received < 0) {
		con_error << "Network receive() error!" << std::endl;
		//perror("recv");
		abort();
		return;
	}

	std::string datablock;
	datablock.assign(recvbuf);

	while (datablock.size()) {
		// scan the datablock for enters
		if (datablock[0] == '\n' || datablock[0] == '\r') {
			if (messageblock.size() >= FRAMESIZE) {
				con_warn << "Incoming message exceeds " << FRAMESIZE << " bytes!\n";
				messageblock.clear();
			} else if (messageblock.size()) {
				recvq.push_back(messageblock);
				//con_debug << "Incoming message '" << messageblock << "'" << std::endl;
				messageblock.clear();
			}
		} else {
			messageblock.append(datablock.substr(0,1));
		}
		datablock.erase(0,1);
	}
	datablock.clear();
}

void NetConnection::frame(float seconds)
{
	timeval timeout;
	timeout.tv_sec = 0;
	timeout.tv_usec = 0;
	fd_set readset = clientset;

	int nb = select(fd()+1, &readset, NULL, NULL, &timeout);
	if (nb == 0) {
		if (connection_timeout + NETTIMEOUT < core::application()->time()) {
			con_error << "Connection timeout!\n";
			abort();
		}
		return;
	}
	if (nb == -1) {
		con_error << "Network error on select()" << std::endl;
		//perror("select");
		abort();
	}

	while (FD_ISSET(this->fd(), &readset) && !error()) {
		receive();

		while (has_messages()) {
			std::string message;
			retreive(message);
			parse_incoming_message(message);
		}

		nb = select(fd()+1, &readset, NULL, NULL, &timeout);
		if (nb == 0) {
			return;
		}
		if (nb == -1) {
			con_error << "Network error on select()" << std::endl;
			//perror("select");
			abort();
		}
	}
}

void NetConnection::send(std::string const &msg)
{
	sendq.append(msg);
}

void NetConnection::transmit()
{

	if (error() || invalid())
		return;
	
	if (!sendq.size()) {
		if (connection_keepalive + NETTIMEOUT /2 < application()->time()) {
			sendq.assign("ping\n");
		} else {
			return;
		}
	} else if (sendq.size() > FRAMESIZE) {
		con_warn << "Outgoing message exceeds " << FRAMESIZE << " bytes!\n";
		//sendq.clear();
		//return;
	}
	
	ssize_t 	bytes_sent = 0;
	
	while (sendq.size()) {
		bytes_sent = ::sendto(connection_fd, sendq.c_str(), sendq.size(), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
		if (bytes_sent <= 0) {
			con_error << "Network send() error!" << std::endl;
			//perror("send");
			abort();
			return;
		}
		
		// assert (bytes_sent <= sendbuf.size());
		sendq.erase(0, bytes_sent);
		Stats::network_bytes_sent += bytes_sent;
	}

	connection_keepalive = application()->time();
}

// parse incoming client messages
/**
 * The following incoming messages are parsed;
 *
 * connect
 * disconnect
 * msg info <text>
 * msg public <name> <text>
 * die
 * ent
 * frame
 * sup
 * pif
 */
void NetConnection::parse_incoming_message(const std::string & message)
{
	std::istringstream msgstream(message);
	
	std::string command;
	msgstream >> command;
	
	if (command == "msg") {
		std::string level;
		if (msgstream >> level) {
			if (level =="info") {
				if (message.size() > 9) {
					con_print << message.substr(9) << std::endl;
				}
			} else if (level == "public") {
				// FIXME - separate sender nickname
				if (message.size() > 11) {
					con_print << message.substr(11) << std::endl;
				}
				
			}
		}
	} else if (command == "connect") {

		connection_state = Connected;
		con_print << "Connected." << std::endl;
		return;

	} else if (command == "disconnect") {

		con_error << "Server disconnected!" << std::endl;
		abort();

	} else if (command == "ping") {

	} else if (command == "frame") {
		float timestamp;
		if (msgstream >> timestamp) {
			game()->reset_clientstate(timestamp);
		}

	} else if (command == "die") {
		unsigned int id;
		if (msgstream >> id) {
			//con_debug << "Received die entity id " << id << std::endl;
			Entity *e = Entity::find(id);
			if (localcontrol() == e) 
				localplayer()->player_control = 0;
			if (e)
				Entity::remove(id);
		}
	} else if (command == "ent") {
		unsigned int type;
		if (msgstream >> type) {
			//con_debug << "Received create entity type " << type << std::endl;
			switch (type) 
			{
			case Entity::Default:
				new Entity(msgstream);
				break;
			case Entity::Dynamic:
				new EntityDynamic(msgstream);
				break;
			case Entity::Controlable:
				new EntityControlable(msgstream);
				break;
			case Entity::Globe:
				new EntityGlobe(msgstream);
				break;
			default:
				con_warn << "Create for unknown entity type " << type << std::endl;
				break;
			}
		}
	} else if (command == "sup") {
		if (connection_state == Connected) 
		{
			unsigned int id;
			if (msgstream >> id) {
				//con_debug << "Received update entity id " << id << std::endl;
				Entity *entity = Entity::find(id);
				if (!entity) {
					con_warn << "Update for unknown entity " << id << std::endl;
				} else 
					entity->recieve_server_update(msgstream);
			}
		}

	} else if (command == "pif") {
		//con_debug << "Received update player info" << std::endl;
		connection()->localplayer()->recieve_server_update(msgstream);
	}
	
}

}