Project::OSiRiON - Git repositories
Project::OSiRiON
News . About . Screenshots . Downloads . Forum . Wiki . Tracker . Git
summaryrefslogtreecommitdiff
blob: 065d69577def98828e6445337da12c63d3844c82 (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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
/*
   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 << "^BInitializing 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 << "^BShutting 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
	}
}

void NetServer::abort() {
	netserver_error = true;
}

// 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("^B");
			message.append(client->player()->name());
			message.append(" ^Btimed 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 = 2500;
	fd_set readset = serverset;

	int nb = select(fd()+1, &readset, NULL, NULL, &timeout);
	if (nb == -1) {
#ifndef _WIN32
		// ncurses needs SIGWINCH catched
		if (errno == EINTR) {
			return;
		}
#endif
		con_error << "Network error on select()" << std::endl;
		this->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;
			this->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
	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 ^B" << Cvar::sv_name->str() << "\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());
	}

	//  send connect completed
	netmsg.str("connect\n");
	client->send(netmsg.str());
	client->transmit(fd());

	// set client state to pending
	client->client_state = NetClient::Pending;
}

// 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;
}

// send outgoing messages to clients

/**
 * The followig messages can be send to a client
 *
 * frame <timestamp> <previous timestamp>
 * ent <id> <entity create data>
 * die <id> <entity data>
 * sup <entity update data>

 * msg <channel> <text>
 * 	supported message channels are "info" "public" "rcon" and "snd"
 * 	"snd" is a special channel to transmit sound events
 */

// broadcast a "msg <channel>" message to all clients
void NetServer::broadcast_message(const char *channel, std::string const & message, Player *ignore_player)
{
	if (!channel)
		return;

	std::string msg("msg ");
	msg.append(channel);
	msg += ' ';
	msg.append(message);
	msg += '\n';

	for (std::list<NetClient *>::iterator it = clients.begin(); it != clients.end(); it++) {
		if (((*it)->player() && (*it)->player() != ignore_player) && ((*it)->state() == NetClient::Connected)) {
			(*it)->send(msg);
		}
	}
}

// send a "msg <channel>" message to one client
void NetServer::send_message(NetClient *client, const char *channel, std::string const & message)
{
	if (!channel)
		return;

	std::string msg("msg ");
	msg.append(channel);
	msg += ' ';
	msg.append(message);
	msg += '\n';

	client->send(msg);
}

// broadcast a "frame" message to all clients
void NetServer::broadcast_frame(float timestamp, float previoustimestamp)
{
	std::ostringstream msg("");
	msg << "frame " << timestamp << " " << previoustimestamp << "\n";

	for (std::list<NetClient *>::iterator it = clients.begin(); it != clients.end(); it++) {
		if ((*it)->state() == NetClient::Connected) {
			(*it)->send(msg.str());
		}
	}
}

// broadcast a "die" delete entity message to all clients
void NetServer::broadcast_entity_delete(Entity *entity)
{
	std::ostringstream msg("");
	msg << "die " << entity->id() <<  '\n';

	for (std::list<NetClient *>::iterator it = clients.begin(); it != clients.end(); it++) {
		if ((*it)->state() == NetClient::Connected) {
			(*it)->send(msg.str());
		}
	}
}

// broadcast a "ent" create entity message to all clients
void NetServer::broadcast_entity_create(Entity *entity)
{
	std::ostringstream msg;
	msg << "ent ";
	entity->serialize(msg);
	msg << '\n';

	for (std::list<NetClient *>::iterator it = clients.begin(); it != clients.end(); it++) {
		if ((*it)->state() == NetClient::Connected) {
			(*it)->send(msg.str());
		}
	}
}

// broadcast a "sup" server update entity message to all clients
void NetServer::broadcast_entity_update(Entity *entity)
{
	std::ostringstream msg;
	msg << "sup " << entity->id() << " ";
	entity->serialize_server_update(msg);
	msg << '\n';

	for (std::list<NetClient *>::iterator it = clients.begin(); it != clients.end(); it++) {
		if ((*it)->state() == NetClient::Connected) {
			(*it)->send(msg.str());
		}
	}
}

// broadcast a "pif" update player information if necessary
void NetServer::broadcast_player_update()
{
	for (std::list<NetClient *>::iterator it = clients.begin(); it != clients.end(); it++) {
		NetClient *client = *it;

		if (client->player()->dirty()) {
			// send player data
			std::ostringstream msg;
			msg << "pif ";
			client->player()->serialize_server_update(msg);
			msg << '\n';
			client->send(msg.str());

			client->player()->player_dirty = false;
		}
	}
}

// send a "pif" update player information to a single player
void NetServer::send_player_update(NetClient *client)
{
	std::ostringstream msg;
	msg << "pif ";
	client->player()->serialize_server_update(msg);	
	msg << '\n';
	client->send(msg.str());
}

// 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;
	}

	// connection request
	// connect is the first command expected from the client
	if (command == "connect") {
		if (client->state() != NetClient::Connecting)
			return;

		unsigned int protover;
		if (msgstream >> protover) {
			if (protover != PROTOCOLVERSION) {
				std::stringstream netmsgstream("");
				netmsgstream << "Protocol version mismatch: ";
				netmsgstream << "client " << protover << " server " << PROTOCOLVERSION << "!\n";

				con_print << client->host() << ":" << client->port() << " " << netmsgstream.str() << std::endl;
				server()->send(client->player(), netmsgstream.str());
			} else {
				client_initialize(client);
			}
		} else {
			std::string message("Unknown client protocol version!");
			con_print << client->host() << ":" << client->port() << " " << message << std::endl;
			server()->send(client->player(), message);
			client->abort();
		}
		return;
	}

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

		if (client->state() == NetClient::Pending) {

			client->client_state = NetClient::Connected;
			server()->player_connect(client->player());

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

			std::string netmsg("^B");
			netmsg.append(oldname);
			netmsg.append(" ^Brenamed 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";
				return;
			} 

			if (entity->type() == Entity::Controlable) {
				con_warn << client->host() << ":" << client->port() << " update for non-controlable entity " << id << "\n";
				return;
			}
	
			EntityControlable *entitycontrolable = (EntityControlable *)entity;

			if (entitycontrolable->owner() != client->player()) {
				con_warn << client->host() << ":" << client->port() << " update for not-owned entity " << id << "\n";
				return;
			}

			entitycontrolable->entity_dirty = true;
			entitycontrolable->recieve_client_update(msgstream);	
		}
		return;
	}

	// say
	if (command == "say") {		
		if (message.size() > command.size()+1) {
			server()->say(client->player(), message.substr(command.size()+1));
		}
		return;
	}
	
}

}