Project::OSiRiON - Git repositories
Project::OSiRiON
News . About . Screenshots . Downloads . Forum . Wiki . Tracker . Git
summaryrefslogtreecommitdiff
blob: 300592246467f659e97c274f612c83457fb0f73c (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
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
419
420
421
422
/*
   net/netserver.h
   This file is part of the Osirion project and is distributed under
   the terms of the GNU General Public License version 2
*/

#include <unistd.h>
#include <errno.h>

#ifndef _WIN32
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>

#include <netinet/in.h>
#include <arpa/inet.h>
#else
#include <windows.h>
#endif

#include <iostream>
#include <sstream>

#include "sys/sys.h"
#include "core/gameserver.h"
#include "core/netclient.h"
#include "core/netserver.h"
#include "core/cvar.h"
#include "core/func.h"
#include "core/core.h"
#include "core/stats.h"

#ifdef _WIN32
	typedef int socklen_t;
#endif

namespace core
{

NetServer::NetServer(std::string const host, unsigned int const port)
{
	con_print << "Initializing network server..." << std::endl;

	// initialize variables
	netserver_fd = -1;
	netserver_error = true;

	// initialize socket
	netserver_fd = ::socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (netserver_fd == -1) {
		con_error << "Network can't create socket!" << std::endl;
		//perror("socket");
		return;
	}

	/*
	// set socket options
	socklen_t yes = 1;
	if (::setsockopt(netserver_fd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(socklen_t)) == -1) {
		con_error << "Network can't set socket options!" << std::endl;
		//perror("setsockopt");
		return;
	}
	*/
	
	// Get the local adress to bind to
	netserver_addr.sin_family = AF_INET;
	netserver_addr.sin_port = htons(port);
	if (host.size()) {
		netserver_addr.sin_addr.s_addr = inet_addr(host.c_str());
		if ( netserver_addr.sin_addr.s_addr == INADDR_NONE) {
			con_error << "Network invalid address " << host << "!" << std::endl;
			return;
		}
	} else {
		netserver_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	}
	memset(netserver_addr.sin_zero, '\0', sizeof(netserver_addr.sin_zero));
	
	// bind the local address to the socket ( note the typecast)
	if (::bind(netserver_fd, (struct sockaddr *) &netserver_addr, sizeof(struct sockaddr)) == -1) {
		con_error << "Network can't bind to local address!" << std::endl;
		//perror("bind");
		return;
	}
	
	con_print << "  Listening on " << inet_ntoa(netserver_addr.sin_addr) <<	":" << ntohs(netserver_addr.sin_port) << std::endl;

	// add the listening socket to the file descriptor set
	FD_ZERO(&serverset);
#ifdef _WIN32
	FD_SET((unsigned int) netserver_fd, &serverset);
#else
	FD_SET(netserver_fd, &serverset);
#endif
	netserver_error = false;
}

NetServer::~NetServer()
{
	con_print << "Shutting down network server..." << std::endl;

	std::string netmsg("disconnect\n");

	// delete all clients
	std::list<NetClient *>:: iterator it;
	for (it = clients.begin(); it != clients.end(); it++) {

		// notify the game server
		if ((*it)->state() == NetClient::Connected)	
			server()->player_disconnect((*it)->player());

		(*it)->send(netmsg);
		(*it)->transmit(fd());
		
		delete (*it);
	}
	clients.clear();

	if (valid()) {
#ifdef _WIN32
		closesocket(fd());
#else
		close(fd());
#endif
	}
}

// remove disconnected clients
void NetServer::reap()
{
        for (std::list<NetClient *>:: iterator it = clients.begin(); it != clients.end(); it++) {
                NetClient *client = *it;

		if (client->client_timeout + NETTIMEOUT < application()->time()) {
			// client timed out, send a disconnect
			std::string netmsg("disconnect\n");
			(*it)->send(netmsg);
			(*it)->transmit(fd());
			(*it)->abort();

			// print a message
			std::string message(client->player()->name());
			message.append(" timed out.");

			if (client->state() == NetClient::Connected) {
				server()->broadcast(message, client->player());
			} else {
				con_print << message << std::endl;
			}
		}

                if (client->error()) {
			
			// notify the game server
			if (client->state() == NetClient::Connected)	
				server()->player_disconnect((*it)->player());

			// remove the client
                        clients.erase(it);
                        delete client;
                        it=clients.begin();
                }
        }
}


void NetServer::transmit()
{
	for (std::list<NetClient *>::iterator it = clients.begin(); it != clients.end(); it++) {
		(*it)->transmit(fd());
	}
}

void NetServer::receive()
{
	if (error())
		return;

	timeval timeout;
	timeout.tv_sec = 0;
	timeout.tv_usec = 5000;
	fd_set readset = serverset;

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

	if (nb && FD_ISSET(fd(), &readset)) { 

		// receive incoming data
		struct sockaddr_in 	client_addr;
		socklen_t		client_addr_len = sizeof(client_addr);
		memset(recbuf, '\0', sizeof(recbuf));
		ssize_t bytes_received  = ::recvfrom(fd(), recbuf, FRAMESIZE-1, 0, (struct sockaddr *)&client_addr, &client_addr_len);
		if (bytes_received == -1) {
			con_error << "Network error on recvfrom()!" << std::endl;
			abort();
			return;
		} else {
			//con_debug << "Incoming data '" << recbuf <<  "'"<< bytes_received << " bytes" << std::endl;
		}
		Stats::network_bytes_received += bytes_received;

		// originator
		std::string client_host (inet_ntoa(client_addr.sin_addr));
		unsigned int client_port = ntohs(client_addr.sin_port);
	
		// get messages from clients
		bool msg_received = false;

		for (std::list<NetClient *>::iterator it = clients.begin(); it != clients.end() && !msg_received; it++) {
			NetClient *client = *it;
			
			if ((client->host() == client_host) && (client->port() == (int) client_port)) {
				// receive data
				client->receive(recbuf);
				
				// process parsed messages
				while (client->has_messages()) {
					std::string message;
					client->retreive(message);
					parse_incoming_message(client, message);
				}

				msg_received = true;
			}
		}

		if (!msg_received) {
			// new connection
			// FIXME maxclients
			NetClient *client = client_connect(client_host , client_port);

			if (client) {
				// receive data
				client->receive(recbuf);
				
				// process parsed messages
				while (client->has_messages()) {
					std::string message;
					client->retreive(message);
					parse_incoming_message(client, message);
				}
			}
		}

	}
	
	// remove dead connections
	// FIXME timeout
	reap();
}


NetClient * NetServer::client_connect(std::string const host, int const port)
{
	con_debug << "client_connect " << host << ":" << port << "\n";

	NetClient *client = new NetClient(host, port);
	if (client->error()) {
		con_warn << client->host() << ":" << client->port() << " connection failed!\n";
		delete(client);
		return 0;
	}

	clients.push_back(client);
	client->player()->player_dirty = false;
	return client;
}

void NetServer::client_initialize(NetClient *client) {

	// send welcome message
	std::ostringstream netmsg;
	netmsg.str("");
	netmsg << "msg info Receiving data from remote server...\n";
	client->send(netmsg.str());
	client->transmit(fd());

	// send entities
	std::map<unsigned int, Entity *>::iterator it;
	for (it=Entity::registry.begin(); it != Entity::registry.end(); it++) {
		netmsg.str("");
		netmsg << "ent ";
		(*it).second->serialize(netmsg);
		netmsg << "\n";
		client->send(netmsg.str());
	}
	netmsg.str("connect\n");
	client->send(netmsg.str());

	client->transmit(fd());
}

void NetServer::send(NetClient * client, std::string const & message)
{
	client->send(message);
}

// send a message to all clients
void NetServer::broadcast(std::string const & message, Player *ignore_player)
{
	//std::cout << "NetServer: " << osstream.str();
	for (std::list<NetClient *>::iterator it = clients.begin(); it != clients.end(); it++) {
		NetClient *client = *it;
		if (!client->error() && (client->state() == NetClient::Connected) && client->player() != ignore_player)
			client->send(message);
	}
}

// find the client corresponding to a player
NetClient *NetServer::find_client(Player const *player)
{
	for (std::list<NetClient *>::iterator it = clients.begin(); it != clients.end(); it++) {
		if ((*it)->player() == player) {
			return (*it);
		}
	}
	return 0;
}

// parse incoming client messages
/**
 * The following incoming protocol messages are parsed;
 *
 * disconnect
 * cmd <game command>
 * cup
 * pif
 * ping
 * say <text>
 * 
 */
void NetServer::parse_incoming_message(NetClient *client, const std::string & message) 
{
	if (!message.size())
		return;

	std::stringstream msgstream(message);
	
	std::string command;
	msgstream >> command;
	
	// disconnect
	if (command == "disconnect") {
		client->abort();
		return;
	}

	// pif - update player information
	// pif is the first command expected from the client
	if (command == "pif") {
		std::string oldname(client->player()->name());
		client->player()->recieve_client_update(msgstream);

		if (client->state() == NetClient::Connecting) {
			client->client_state = NetClient::Connected;
			client_initialize(client);
			server()->player_connect(client->player());

		} else if ((client->state() == NetClient::Connected) && (client->player()->name() != oldname)) {

			std::string netmsg(oldname);
			netmsg.append(" renamed to ");
			netmsg.append(client->player()->name());
			server()->broadcast(netmsg);
		}
	}

	if (command == "ping") {
		return;
	}

	if (client->state() != NetClient::Connected)
		return;

	// cmd
	if (command == "cmd") {
		if (message.size() > command.size()+1) {
			std::string cmdline(message.substr(command.size()+1));
			server()->exec(client->player(), cmdline);
		}
		return;
	}

	// cup - client update entity
	if (command == "cup") {
		//con_debug << message << "\n";
		unsigned int id;
		if (msgstream >> id) {
			Entity *entity = Entity::find(id);
			if (!entity) {
				con_warn << client->host() << ":" << client->port() << " update for unknown entity " << id << "\n";
				
			} else {
				entity->entity_dirty = true;
				entity->recieve_client_update(msgstream);
			}
			
		}
		return;
	}

	// say
	if (command == "say") {		
		if (message.size() > command.size()+1) {
			std::ostringstream osstream;
			osstream << "msg public " << client->player()->name() << " " << message.substr(command.size()+1) << "\n";
			broadcast(osstream.str());
			con_print << client->player()->name() << " " << message.substr(command.size()+1) << std::endl;
		}
		return;
	}
	
}

}