File: internet_gaming.cc

package info (click to toggle)
widelands 1%3A19%2Brepack-6
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 371,172 kB
  • sloc: cpp: 108,458; ansic: 18,695; python: 5,155; sh: 487; xml: 460; makefile: 229
file content (839 lines) | stat: -rw-r--r-- 25,640 bytes parent folder | download | duplicates (2)
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
/*
 * Copyright (C) 2004-2016 by the Widelands Development Team
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 */

#include "network/internet_gaming.h"

#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>

#include "base/i18n.h"
#include "base/log.h"
#include "base/macros.h"
#include "base/warning.h"
#include "io/fileread.h"
#include "io/filesystem/layered_filesystem.h"
#include "network/internet_gaming_messages.h"

/// Private constructor by purpose: NEVER call directly. Always call InternetGaming::ref(), this
/// will ensure
/// that only one instance is running at time.
InternetGaming::InternetGaming()
   : sock_(nullptr),
     sockset_(nullptr),
     state_(OFFLINE),
     reg_(false),
     port_(INTERNET_GAMING_PORT),
     clientrights_(INTERNET_CLIENT_UNREGISTERED),
     gameip_(""),
     clientupdateonmetaserver_(true),
     gameupdateonmetaserver_(true),
     clientupdate_(false),
     gameupdate_(false),
     time_offset_(0),
     waittimeout_(std::numeric_limits<int32_t>::max()),
     lastping_(time(nullptr)) {
	// Fill the list of possible messages from the server
	InternetGamingMessages::fill_map();

	// Set connection tracking variables to 0
	lastbrokensocket_[0] = 0;
	lastbrokensocket_[1] = 0;
}

/// resets all stored variables without the chat messages for a clean new login (not relogin)
void InternetGaming::reset() {
	sock_ = nullptr;
	sockset_ = nullptr;
	state_ = OFFLINE;
	pwd_ = "";
	reg_ = false;
	meta_ = INTERNET_GAMING_METASERVER;
	port_ = INTERNET_GAMING_PORT;
	clientname_ = "";
	clientrights_ = INTERNET_CLIENT_UNREGISTERED;
	gamename_ = "";
	gameip_ = "";
	clientupdateonmetaserver_ = true;
	gameupdateonmetaserver_ = true;
	clientupdate_ = false;
	gameupdate_ = false;
	time_offset_ = 0;
	waitcmd_ = "";
	waittimeout_ = std::numeric_limits<int32_t>::max();
	lastbrokensocket_[0] = 0;
	lastbrokensocket_[1] = 0;
	lastping_ = time(nullptr);

	clientlist_.clear();
	gamelist_.clear();
}

/// the one and only InternetGaming instance.
static InternetGaming* ig = nullptr;

/// \returns the one and only InternetGaming instance.
InternetGaming& InternetGaming::ref() {
	if (!ig)
		ig = new InternetGaming();
	return *ig;
}

void InternetGaming::initialize_connection() {
	// First of all try to connect to the metaserver
	log("InternetGaming: Connecting to the metaserver.\n");
	IPaddress peer;
	if (hostent* const he = gethostbyname(meta_.c_str())) {
		peer.host = (reinterpret_cast<in_addr*>(he->h_addr_list[0]))->s_addr;
		DIAG_OFF("-Wold-style-cast")
		peer.port = htons(port_);
		DIAG_ON("-Wold-style-cast")
	} else
		throw WLWarning(
		   _("Connection problem"), "%s", _("Widelands could not connect to the metaserver."));

	SDLNet_ResolveHost(&peer, meta_.c_str(), port_);
	sock_ = SDLNet_TCP_Open(&peer);
	if (sock_ == nullptr)
		throw WLWarning(_("Could not establish connection to host"),
		                _("Widelands could not establish a connection to the given address.\n"
		                  "Either there was no metaserver running at the supposed port or\n"
		                  "your network setup is broken."));

	sockset_ = SDLNet_AllocSocketSet(1);
	SDLNet_TCP_AddSocket(sockset_, sock_);

	// Of course not 100% true, but we just care about an answer at all, so we reset this tracker
	lastping_ = time(nullptr);
}

/// Login to metaserver
bool InternetGaming::login(const std::string& nick,
                           const std::string& pwd,
                           bool reg,
                           const std::string& meta,
                           uint32_t port) {
	assert(state_ == OFFLINE);

	pwd_ = pwd;
	reg_ = reg;
	meta_ = meta;
	port_ = port;

	initialize_connection();

	// If we are here, a connection was established and we can send our login package through the
	// socket.
	log("InternetGaming: Sending login request.\n");
	SendPacket s;
	s.string(IGPCMD_LOGIN);
	s.string(boost::lexical_cast<std::string>(INTERNET_GAMING_PROTOCOL_VERSION));
	s.string(nick);
	s.string(build_id());
	s.string(bool2str(reg));
	if (reg)
		s.string(pwd);
	s.send(sock_);

	// Now let's see, whether the metaserver is answering
	uint32_t const secs = time(nullptr);
	state_ = CONNECTING;
	while (INTERNET_GAMING_TIMEOUT > time(nullptr) - secs) {
		handle_metaserver_communication();
		// Check if we are a step further... if yes handle_packet has taken care about all the
		// paperwork, so we put our feet up and just return. ;)
		if (state_ != CONNECTING) {
			if (state_ == LOBBY) {
				format_and_add_chat(
				   "", "", true, _("For hosting a game, please take a look at the notes at:"));
				format_and_add_chat("", "", true, "http://wl.widelands.org/wiki/InternetGaming");
				return true;
			} else if (error())
				return false;
		}
	}
	log("InternetGaming: No answer from metaserver!\n");
	logout("NO_ANSWER");
	return false;
}

/// Relogin to metaserver after loosing connection
bool InternetGaming::relogin() {
	if (!error()) {
		throw wexception("InternetGaming::relogin: This only makes sense if there was an error.");
	}

	initialize_connection();

	// If we are here, a connection was established and we can send our login package through the
	// socket.
	log("InternetGaming: Sending relogin request.\n");
	SendPacket s;
	s.string(IGPCMD_RELOGIN);
	s.string(boost::lexical_cast<std::string>(INTERNET_GAMING_PROTOCOL_VERSION));
	s.string(clientname_);
	s.string(build_id());
	s.string(bool2str(reg_));
	if (reg_)
		s.string(pwd_);
	s.send(sock_);

	// Now let's see, whether the metaserver is answering
	uint32_t const secs = time(nullptr);
	state_ = CONNECTING;
	while (INTERNET_GAMING_TIMEOUT > time(nullptr) - secs) {
		handle_metaserver_communication();
		// Check if we are a step further... if yes handle_packet has taken care about all the
		// paperwork, so we put our feet up and just return. ;)
		if (state_ != CONNECTING) {
			if (state_ == LOBBY) {
				break;
			} else if (error())
				return false;
		}
	}

	if (INTERNET_GAMING_TIMEOUT <= time(nullptr) - secs) {
		log("InternetGaming: No answer from metaserver!\n");
		return false;
	}

	// Client is reconnected, so let's try resend the timeouted command.
	if (waitcmd_ == IGPCMD_GAME_CONNECT)
		join_game(gamename_);
	else if (waitcmd_ == IGPCMD_GAME_OPEN) {
		state_ = IN_GAME;
		open_game();
	} else if (waitcmd_ == IGPCMD_GAME_START) {
		state_ = IN_GAME;
		set_game_playing();
	}

	return true;
}

/// logout of the metaserver
/// \note \arg msgcode should be a message from the list of InternetGamingMessages
void InternetGaming::logout(const std::string& msgcode) {

	// Just in case the metaserver is listening on the socket - tell him we break up with him ;)
	SendPacket s;
	s.string(IGPCMD_DISCONNECT);
	s.string(msgcode);
	s.send(sock_);

	const std::string& msg = InternetGamingMessages::get_message(msgcode);
	log("InternetGaming: logout(%s)\n", msg.c_str());
	format_and_add_chat("", "", true, msg);

	reset();
}

/**
 * Handle situation when reading from socket failed.
 */
void InternetGaming::handle_failed_read() {
	set_error();
	const std::string& msg = InternetGamingMessages::get_message("CONNECTION_LOST");
	log("InternetGaming: Error: %s\n", msg.c_str());
	format_and_add_chat("", "", true, msg);

	// Check how much time passed since the socket broke the last time
	// Maybe something is completely wrong at the moment?
	// At least it seems to be, if the socket broke three times in the last 10 seconds...
	time_t now = time(nullptr);
	if ((now - lastbrokensocket_[1] < 10) && (now - lastbrokensocket_[0] < 10)) {
		reset();
		set_error();
		return;
	}
	lastbrokensocket_[1] = lastbrokensocket_[0];
	lastbrokensocket_[0] = now;

	// Try to relogin
	if (!relogin()) {
		// Do not try to relogin again automatically.
		reset();
		set_error();
	}
}

/// handles all communication between the metaserver and the client
void InternetGaming::handle_metaserver_communication() {
	if (error())
		return;
	try {
		while (sock_ != nullptr && SDLNet_CheckSockets(sockset_, 0) > 0) {
			// Perform only one read operation, then process all packets
			// from this read. This ensures that we process DISCONNECT
			// packets that are followed immediately by connection close.
			if (!deserializer_.read(sock_)) {
				handle_failed_read();
				return;
			}

			// Process all the packets from the last read
			while (sock_ && deserializer_.avail()) {
				RecvPacket packet(deserializer_);
				handle_packet(packet);
			}
		}
	} catch (const std::exception& e) {
		std::string reason = _("Something went wrong: ");
		reason += e.what();
		logout(reason);
		set_error();
	}

	if (state_ == LOBBY) {
		// client is in the lobby and therefore we want realtime information updates
		if (clientupdateonmetaserver_) {
			SendPacket s;
			s.string(IGPCMD_CLIENTS);
			s.send(sock_);

			clientupdateonmetaserver_ = false;
		}

		if (gameupdateonmetaserver_) {
			SendPacket s;
			s.string(IGPCMD_GAMES);
			s.send(sock_);

			gameupdateonmetaserver_ = false;
		}
	}

	if (!waitcmd_.empty()) {
		// Check if timeout is reached
		time_t now = time(nullptr);
		if (now > waittimeout_) {
			set_error();
			waittimeout_ = std::numeric_limits<int32_t>::max();
			log("InternetGaming: reached a timeout for an awaited answer of the metaserver!\n");
			if (!relogin()) {
				// Do not try to relogin again automatically.
				reset();
				set_error();
			}
		}
	}

	// Check connection to the metaserver
	// Was a ping received in the last 4 minutes?
	if (time(nullptr) - lastping_ > 240) {
		// Try to relogin
		set_error();
		if (!relogin()) {
			// Do not try to relogin again automatically.
			reset();
			set_error();
		}
	}
}

/// Handle one packet received from the metaserver.
void InternetGaming::handle_packet(RecvPacket& packet) {
	std::string cmd = packet.string();

	// First check if everything is fine or whether the metaserver broke up with the client.
	if (cmd == IGPCMD_DISCONNECT) {
		std::string reason = packet.string();
		format_and_add_chat("", "", true, InternetGamingMessages::get_message(reason));
		if (reason == "CLIENT_TIMEOUT") {
			// Try to relogin
			set_error();
			if (!relogin()) {
				// Do not try to relogin again automatically.
				reset();
				set_error();
			}
		}
		return;
	}

	// Are we already online?
	if (state_ == CONNECTING) {
		if (cmd == IGPCMD_LOGIN) {
			// Clients request to login was granted
			clientname_ = packet.string();
			clientrights_ = packet.string();
			state_ = LOBBY;
			log("InternetGaming: Client %s logged in.\n", clientname_.c_str());
			return;

		} else if (cmd == IGPCMD_RELOGIN) {
			// Clients request to relogin was granted
			state_ = LOBBY;
			log("InternetGaming: Client %s relogged in.\n", clientname_.c_str());
			format_and_add_chat("", "", true, _("Successfully reconnected to the metaserver!"));
			return;

		} else if (cmd == IGPCMD_ERROR) {
			std::string errortype = packet.string();
			if (errortype != "LOGIN" && errortype != "RELOGIN") {
				log("InternetGaming: Strange ERROR in connecting state: %s\n", errortype.c_str());
				throw WLWarning(
				   _("Mixed up"), _("The metaserver sent a strange ERROR during connection"));
			}
			// Clients login request got rejected
			logout(packet.string());
			set_error();
			return;

		} else {
			logout();
			set_error();
			throw WLWarning(
			   _("Unexpected packet"),
			   _("Expected a LOGIN, RELOGIN or REJECTED packet from server, but received command "
			     "%s. Maybe the metaserver is using a different protocol version ?"),
			   cmd.c_str());
		}
	}

	try {
		if (cmd == IGPCMD_LOGIN || cmd == IGPCMD_RELOGIN) {
			// Login specific commands but not in CONNECTING state...
			log("InternetGaming: Received %s cmd although client is not in CONNECTING state.\n",
			    cmd.c_str());
			std::string temp =
			   (boost::format(
			       _("WARNING: Received a %s command although we are not in CONNECTING state.")) %
			    cmd)
			      .str();
			format_and_add_chat("", "", true, temp);
		}

		else if (cmd == IGPCMD_TIME) {
			// Client received the server time
			time_offset_ = boost::lexical_cast<int>(packet.string()) - time(nullptr);
			log(ngettext("InternetGaming: Server time offset is %u second.",
			             "InternetGaming: Server time offset is %u seconds.", time_offset_),
			    time_offset_);
			std::string temp =
			   (boost::format(ngettext("Server time offset is %u second.",
			                           "Server time offset is %u seconds.", time_offset_)) %
			    time_offset_)
			      .str();
			format_and_add_chat("", "", true, temp);
		}

		else if (cmd == IGPCMD_PING) {
			// Client received a PING and should immediately PONG as requested
			SendPacket s;
			s.string(IGPCMD_PONG);
			s.send(sock_);

			lastping_ = time(nullptr);
		}

		else if (cmd == IGPCMD_CHAT) {
			// Client received a chat message
			std::string sender = packet.string();
			std::string message = packet.string();
			std::string type = packet.string();

			if (type != "public" && type != "private" && type != "system")
				throw WLWarning(
				   _("Invalid message type"), _("Invalid chat message type \"%s\"."), type.c_str());

			bool personal = type == "private";
			bool system = type == "system";

			format_and_add_chat(sender, personal ? clientname_ : "", system, message);
		}

		else if (cmd == IGPCMD_GAMES_UPDATE) {
			// Client received a note, that the list of games was changed
			log("InternetGaming: Game update on metaserver.\n");
			gameupdateonmetaserver_ = true;
		}

		else if (cmd == IGPCMD_GAMES) {
			// Client received the new list of games
			uint8_t number = boost::lexical_cast<int>(packet.string()) & 0xff;
			std::vector<InternetGame> old = gamelist_;
			gamelist_.clear();
			log("InternetGaming: Received a game list update with %u items.\n", number);
			for (uint8_t i = 0; i < number; ++i) {
				InternetGame* ing = new InternetGame();
				ing->name = packet.string();
				ing->build_id = packet.string();
				ing->connectable = str2bool(packet.string());
				gamelist_.push_back(*ing);

				bool found = false;
				for (std::vector<InternetGame>::size_type j = 0; j < old.size(); ++j)
					if (old[j].name == ing->name) {
						found = true;
						old[j].name = "";
						break;
					}
				if (!found)
					format_and_add_chat(
					   "", "", true,
					   (boost::format(_("The game %s is now available")) % ing->name).str());

				delete ing;
				ing = nullptr;
			}

			for (std::vector<InternetGame>::size_type i = 0; i < old.size(); ++i)
				if (old[i].name.size())
					format_and_add_chat(
					   "", "", true,
					   (boost::format(_("The game %s has been closed")) % old[i].name).str());

			gameupdate_ = true;
		}

		else if (cmd == IGPCMD_CLIENTS_UPDATE) {
			// Client received a note, that the list of clients was changed
			log("InternetGaming: Client update on metaserver.\n");
			clientupdateonmetaserver_ = true;
		}

		else if (cmd == IGPCMD_CLIENTS) {
			// Client received the new list of clients
			uint8_t number = boost::lexical_cast<int>(packet.string()) & 0xff;
			std::vector<InternetClient> old = clientlist_;
			clientlist_.clear();
			log("InternetGaming: Received a client list update with %u items.\n", number);
			for (uint8_t i = 0; i < number; ++i) {
				InternetClient* inc = new InternetClient();
				inc->name = packet.string();
				inc->build_id = packet.string();
				inc->game = packet.string();
				inc->type = packet.string();
				inc->points = packet.string();
				clientlist_.push_back(*inc);

				bool found =
				   old.empty();  // do not show all clients, if this instance is the actual change
				for (std::vector<InternetClient>::size_type j = 0; j < old.size(); ++j)
					if (old[j].name == inc->name) {
						found = true;
						old[j].name = "";
						break;
					}
				if (!found)
					format_and_add_chat(
					   "", "", true, (boost::format(_("%s joined the lobby")) % inc->name).str());

				delete inc;
				inc = nullptr;
			}

			for (std::vector<InternetClient>::size_type i = 0; i < old.size(); ++i)
				if (old[i].name.size())
					format_and_add_chat(
					   "", "", true, (boost::format(_("%s left the lobby")) % old[i].name).str());

			clientupdate_ = true;
		}

		else if (cmd == IGPCMD_GAME_OPEN) {
			// Client received the acknowledgment, that the game was opened
			assert(waitcmd_ == IGPCMD_GAME_OPEN);
			waitcmd_ = "";
		}

		else if (cmd == IGPCMD_GAME_CONNECT) {
			// Client received the ip for the game it wants to join
			assert(waitcmd_ == IGPCMD_GAME_CONNECT);
			waitcmd_ = "";
			// save the received ip, so the client cann connect to the game
			gameip_ = packet.string();
			log("InternetGaming: Received ip of the game to join: %s.\n", gameip_.c_str());
		}

		else if (cmd == IGPCMD_GAME_START) {
			// Client received the acknowledgment, that the game was started
			assert(waitcmd_ == IGPCMD_GAME_START);
			waitcmd_ = "";
		}

		else if (cmd == IGPCMD_ERROR) {
			// Client received an ERROR message - seems something went wrong
			std::string subcmd(packet.string());
			std::string reason(packet.string());
			std::string message = "";

			if (subcmd == IGPCMD_CHAT) {
				// Something went wrong with the chat message the user sent.
				message += _("Chat message could not be sent.");
				if (reason == "NO_SUCH_USER")
					message = (boost::format("%s %s") % message %
					           (boost::format(InternetGamingMessages::get_message(reason)) %
					            packet.string().c_str()))
					             .str();
			}

			else if (subcmd == IGPCMD_GAME_OPEN) {
				// Something went wrong with the newly opened game
				message = InternetGamingMessages::get_message(reason);
				// we got our answer, so no need to wait anymore
				waitcmd_ = "";
			}
			message = (boost::format(_("ERROR: %s")) % message).str();

			// Finally send the error message as system chat to the client.
			format_and_add_chat("", "", true, message);
		}

		else
			// Inform the client about the unknown command
			format_and_add_chat(
			   "", "", true,
			   (boost::format(_("Received an unknown command from the metaserver: %s")) % cmd).str());

	} catch (WLWarning& e) {
		format_and_add_chat("", "", true, e.what());
	}
}

/// \returns the ip of the game the client is on or wants to join (or the client is hosting)
///          or 0, if no ip available.
const std::string& InternetGaming::ip() {
	return gameip_;
}

/// called by a client to join the game \arg gamename
void InternetGaming::join_game(const std::string& gamename) {
	if (!logged_in())
		return;

	SendPacket s;
	s.string(IGPCMD_GAME_CONNECT);
	s.string(gamename);
	s.send(sock_);
	gamename_ = gamename;
	log("InternetGaming: Client tries to join a game with the name %s\n", gamename_.c_str());
	state_ = IN_GAME;

	// From now on we wait for a reply from the metaserver
	waitcmd_ = IGPCMD_GAME_CONNECT;
	waittimeout_ = time(nullptr) + INTERNET_GAMING_TIMEOUT;
}

/// called by a client to open a new game with name gamename_
void InternetGaming::open_game() {
	if (!logged_in())
		return;

	SendPacket s;
	s.string(IGPCMD_GAME_OPEN);
	s.string(gamename_);
	s.string("1024");  // Used to be maxclients, no longer used.
	s.send(sock_);
	log("InternetGaming: Client opened a game with the name %s.\n", gamename_.c_str());
	state_ = IN_GAME;

	// From now on we wait for a reply from the metaserver
	waitcmd_ = IGPCMD_GAME_OPEN;
	waittimeout_ = time(nullptr) + INTERNET_GAMING_TIMEOUT;
}

/// called by a client that is host of a game to inform the metaserver, that the game started
void InternetGaming::set_game_playing() {
	if (!logged_in())
		return;

	SendPacket s;
	s.string(IGPCMD_GAME_START);
	s.send(sock_);
	log("InternetGaming: Client announced the start of the game %s.\n", gamename_.c_str());

	// From now on we wait for a reply from the metaserver
	waitcmd_ = IGPCMD_GAME_START;
	waittimeout_ = time(nullptr) + INTERNET_GAMING_TIMEOUT;
}

/// called by a client to inform the metaserver, that it left the game and is back in the lobby.
/// If this is called by the hosting client, this further informs the metaserver, that the game was
/// closed.
void InternetGaming::set_game_done() {
	if (!logged_in())
		return;

	SendPacket s;
	s.string(IGPCMD_GAME_DISCONNECT);
	s.send(sock_);

	gameip_ = "";
	state_ = LOBBY;

	log("InternetGaming: Client announced the disconnect from the game %s.\n", gamename_.c_str());
}

/// \returns whether the local gamelist was updated
/// \note this function resets gameupdate_. So if you call it, please really handle the output.
bool InternetGaming::update_for_games() {
	bool temp = gameupdate_;
	gameupdate_ = false;
	return temp;
}

/// \returns the tables in the room, if no error occured, or nullptr in case of error
const std::vector<InternetGame>* InternetGaming::games() {
	return error() ? nullptr : &gamelist_;
}

/// \returns whether the local clientlist_ was updated
/// \note this function resets clientupdate_. So if you call it, please really handle the output.
bool InternetGaming::update_for_clients() {
	bool temp = clientupdate_;
	clientupdate_ = false;
	return temp;
}

/// \returns the players in the room, if no error occured, or nullptr in case of error
const std::vector<InternetClient>* InternetGaming::clients() {
	return error() ? nullptr : &clientlist_;
}

/// ChatProvider: sends a message via the metaserver.
void InternetGaming::send(const std::string& msg) {
	if (!logged_in()) {
		format_and_add_chat(
		   "", "", true, _("Message could not be sent: You are not connected to the metaserver!"));
		return;
	}

	SendPacket s;
	s.string(IGPCMD_CHAT);

	if (msg.size() && *msg.begin() == '@') {
		// Format a personal message
		std::string::size_type const space = msg.find(' ');
		if (space >= msg.size() - 1) {
			format_and_add_chat(
			   "", "", true,
			   _("Message could not be sent: Was this supposed to be a private message?"));
			return;
		}
		s.string(msg.substr(space + 1));     // message
		s.string(msg.substr(1, space - 1));  // recipient

		format_and_add_chat(clientname_, msg.substr(1, space - 1), false, msg.substr(space + 1));

	} else if (clientrights_ == INTERNET_CLIENT_SUPERUSER && msg.size() && *msg.begin() == '/') {
		// This is either a /me command, a super user command, or well... just a chat message
		// beginning
		// with a "/" - let's see...

		// Split up in "cmd" "arg"
		std::string cmd, arg;
		std::string temp = msg.substr(1);  // cut off '/'
		std::string::size_type const space = temp.find(' ');
		if (space > temp.size())
			// no argument
			goto normal;

		// get the cmd and the arg
		cmd = temp.substr(0, space);
		arg = temp.substr(space + 1);

		if (cmd == "motd") {
			SendPacket m;
			m.string(IGPCMD_MOTD);
			// Check whether motd is attached or should be loaded from a file
			if (arg.size() > 1 && arg.at(0) == '%') {
				// Seems we should load the motd from a file
				temp = arg.substr(1);  // cut of the "%"
				if (g_fs->file_exists(temp) && !g_fs->is_directory(temp)) {
					// Read in the file
					FileRead fr;
					fr.open(*g_fs, temp);
					if (!fr.end_of_file()) {
						arg = fr.read_line();
						while (!fr.end_of_file()) {
							arg += fr.read_line();
						}
					}
				}
			}
			// send the request to change the motd
			m.string(arg);
			m.send(sock_);
			return;
		} else if (cmd == "announcement") {
			// send the request to change the motd
			SendPacket m;
			m.string(IGPCMD_ANNOUNCEMENT);
			m.string(arg);
			m.send(sock_);
			return;
		} else
			// let everything else pass
			goto normal;

	} else {
	normal:
		s.string(msg);
		s.string("");
	}

	s.send(sock_);
}

/**
 * \returns the boolean value of a string received from the metaserver.
 * If conversion fails, it throws a \ref warning
 */
bool InternetGaming::str2bool(std::string str) {
	if ((str != "true") && (str != "false"))
		throw WLWarning(_("Conversion error"),
		                /** TRANSLATORS: Geeky message from the metaserver */
		                /** TRANSLATORS: This message is shown if %s isn't "true" or "false" */
		                _("Unable to determine truth value for \"%s\""), str.c_str());

	return str == "true";
}

/// \returns a string containing the boolean value \arg b to be send to metaserver
std::string InternetGaming::bool2str(bool b) {
	return b ? "true" : "false";
}

/// formates a chat message and adds it to the list of chat messages
void InternetGaming::format_and_add_chat(std::string from,
                                         std::string to,
                                         bool system,
                                         std::string msg) {
	ChatMessage c;
	if (!system && from.empty()) {
		std::string unkown_string = (boost::format("<%s>") % _("unknown")).str();
		c.sender = unkown_string;
	} else {
		c.sender = from;
	}
	c.time = time(nullptr);
	c.playern = system ? -1 : to.size() ? 3 : 7;
	c.msg = msg;
	c.recipient = to;

	receive(c);
	if (system && (state_ == IN_GAME)) {
		// Save system chat messages seperately as well, so the nethost can import and show them in
		// game;
		c.msg = "METASERVER: " + msg;
		ingame_system_chat_.push_back(c);
	}
}