/
server.cpp
2874 lines (2547 loc) · 97.7 KB
/
server.cpp
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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* $Id$ */
/*
Copyright (C) 2003 - 2013 by David White <dave@whitevine.net>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
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.
See the COPYING file for more details.
*/
/**
* @file
* Wesnoth-Server, for multiplayer-games.
*/
#include "server.hpp"
#include "../global.hpp"
#include "../config.hpp"
#include "../game_config.hpp"
#include "../log.hpp"
#include "../map.hpp" // gamemap::MAX_PLAYERS
#include "../network.hpp"
#include "../filesystem.hpp"
#include "../multiplayer_error_codes.hpp"
#include "../serialization/parser.hpp"
#include "../serialization/preprocessor.hpp"
#include "../serialization/string_utils.hpp"
#include "../util.hpp"
#include "game.hpp"
#include "input_stream.hpp"
#include "metrics.hpp"
#include "player.hpp"
#include "proxy.hpp"
#include "simple_wml.hpp"
#include "ban.hpp"
#include "user_handler.hpp"
#include "sample_user_handler.hpp"
#ifdef HAVE_MYSQLPP
#include "forum_user_handler.hpp"
#endif
#include <boost/bind.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/scoped_array.hpp>
#include <boost/foreach.hpp>
#include <boost/utility.hpp>
#include <algorithm>
#include <cassert>
#include <cerrno>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <vector>
#include <queue>
#include <csignal>
#ifndef _WIN32
#include <sys/times.h>
namespace {
clock_t get_cpu_time(bool active) {
if(!active) {
return 0;
}
struct tms buf;
times(&buf);
return buf.tms_utime + buf.tms_stime;
}
}
#else
// on Windows we don't calculate CPU time
clock_t get_cpu_time(bool /*active*/) {
return 0;
}
#endif
namespace {
bool match_user(std::pair<network::connection, wesnothd::player> pl, const std::string& username, const std::string& ip) {
return pl.second.name() == username && network::ip_address(pl.first) == ip;
}
}
static lg::log_domain log_server("server");
/**
* fatal and directly server related errors/warnings,
* ie not caused by erroneous client data
*/
#define ERR_SERVER LOG_STREAM(err, log_server)
/** clients send wrong/unexpected data */
#define WRN_SERVER LOG_STREAM(warn, log_server)
/** normal events */
#define LOG_SERVER LOG_STREAM(info, log_server)
#define DBG_SERVER LOG_STREAM(debug, log_server)
static lg::log_domain log_config("config");
#define ERR_CONFIG LOG_STREAM(err, log_config)
#define WRN_CONFIG LOG_STREAM(warn, log_config)
//compatibility code for MS compilers
#ifndef SIGHUP
#define SIGHUP 20
#endif
/** @todo FIXME: should define SIGINT here too, but to what? */
sig_atomic_t config_reload = 0;
#ifndef _MSC_VER
static void reload_config(int signal) {
assert(signal == SIGHUP);
config_reload = 1;
}
#endif
static void exit_sigint(int signal) {
assert(signal == SIGINT);
LOG_SERVER << "SIGINT caught, exiting without cleanup immediately.\n";
exit(128 + SIGINT);
}
static void exit_sigterm(int signal) {
assert(signal == SIGTERM);
LOG_SERVER << "SIGTERM caught, exiting without cleanup immediately.\n";
exit(128 + SIGTERM);
}
namespace {
// we take profiling info on every n requests
int request_sample_frequency = 1;
void send_doc(simple_wml::document& doc, network::connection connection, std::string type = "")
{
if (type.empty())
type = doc.root().first_child().to_string();
try {
simple_wml::string_span s = doc.output_compressed();
network::send_raw_data(s.begin(), s.size(), connection, type);
} catch (simple_wml::error& e) {
WRN_CONFIG << __func__ << ": simple_wml error: " << e.message << std::endl;
}
}
void make_add_diff(const simple_wml::node& src, const char* gamelist,
const char* type,
simple_wml::document& out, int index=-1)
{
if (!out.child("gamelist_diff")) {
out.root().add_child("gamelist_diff");
}
simple_wml::node* top = out.child("gamelist_diff");
if(gamelist) {
top = &top->add_child("change_child");
top->set_attr_int("index", 0);
top = &top->add_child("gamelist");
}
simple_wml::node& insert = top->add_child("insert_child");
const simple_wml::node::child_list& children = src.children(type);
assert(!children.empty());
if(index < 0) {
index = children.size() - 1;
}
assert(index < static_cast<int>(children.size()));
insert.set_attr_int("index", index);
children[index]->copy_into(insert.add_child(type));
}
bool make_delete_diff(const simple_wml::node& src,
const char* gamelist,
const char* type,
const simple_wml::node* remove,
simple_wml::document& out)
{
if (!out.child("gamelist_diff")) {
out.root().add_child("gamelist_diff");
}
simple_wml::node* top = out.child("gamelist_diff");
if(gamelist) {
top = &top->add_child("change_child");
top->set_attr_int("index", 0);
top = &top->add_child("gamelist");
}
const simple_wml::node::child_list& children = src.children(type);
const simple_wml::node::child_list::const_iterator itor =
std::find(children.begin(), children.end(), remove);
if(itor == children.end()) {
return false;
}
const int index = itor - children.begin();
simple_wml::node& del = top->add_child("delete_child");
del.set_attr_int("index", index);
del.add_child(type);
return true;
}
bool make_change_diff(const simple_wml::node& src,
const char* gamelist,
const char* type,
const simple_wml::node* item,
simple_wml::document& out)
{
if (!out.child("gamelist_diff")) {
out.root().add_child("gamelist_diff");
}
simple_wml::node* top = out.child("gamelist_diff");
if(gamelist) {
top = &top->add_child("change_child");
top->set_attr_int("index", 0);
top = &top->add_child("gamelist");
}
const simple_wml::node::child_list& children = src.children(type);
const simple_wml::node::child_list::const_iterator itor =
std::find(children.begin(), children.end(), item);
if(itor == children.end()) {
return false;
}
simple_wml::node& diff = *top;
simple_wml::node& del = diff.add_child("delete_child");
const int index = itor - children.begin();
del.set_attr_int("index", index);
del.add_child(type);
//inserts will be processed first by the client, so insert at index+1,
//and then when the delete is processed we'll slide into the right position
simple_wml::node& insert = diff.add_child("insert_child");
insert.set_attr_int("index", index + 1);
children[index]->copy_into(insert.add_child(type));
return true;
}
std::string player_status(wesnothd::player_map::const_iterator pl) {
std::ostringstream out;
const network::connection_stats& stats = network::get_connection_stats(pl->first);
const int time_connected = stats.time_connected / 1000;
const int seconds = time_connected % 60;
const int minutes = (time_connected / 60) % 60;
const int hours = time_connected / (60 * 60);
out << "'" << pl->second.name() << "' @ " << network::ip_address(pl->first)
<< " connected for " << std::setw(2) << hours << ":" << std::setw(2) << minutes << ":" << std::setw(2) << seconds
<< " sent " << stats.bytes_sent << " bytes, received "
<< stats.bytes_received << " bytes";
return out.str();
}
} // namespace
class fps_limiter {
size_t start_ticks_;
size_t ms_per_frame_;
public:
fps_limiter(size_t ms_per_frame = 20) : start_ticks_(0), ms_per_frame_(ms_per_frame)
{}
void limit() {
size_t current_ticks = SDL_GetTicks();
if (current_ticks - start_ticks_ < ms_per_frame_) {
SDL_Delay(ms_per_frame_ - (current_ticks - start_ticks_));
start_ticks_ += ms_per_frame_;
} else {
start_ticks_ = current_ticks;
}
}
void set_ms_per_frame(size_t ms_per_frame)
{
ms_per_frame_ = ms_per_frame;
}
void set_fps(size_t fps)
{
ms_per_frame_ = 1000 / fps;
}
};
static fps_limiter fps_limit_;
namespace {
const std::string denied_msg = "You're not allowed to execute this command.";
const std::string help_msg = "Available commands are: adminmsg <msg>,"
" ban <mask> <time> <reason>, bans [deleted] [<ipmask>], clones,"
" dul|deny_unregistered_login [yes|no], kick <mask> [<reason>],"
" k[ick]ban <mask> <time> <reason>, help, games, metrics,"
" netstats [all], [lobby]msg <message>, motd [<message>],"
" pm|privatemsg <nickname> <message>, requests, sample, searchlog <mask>,"
" signout, stats, status [<mask>], unban <ipmask>\n"
"Specific strings (those not inbetween <> like the command names)"
" are case insensitive.";
}
server::server(int port, const std::string& config_file, size_t min_threads,
size_t max_threads) :
net_manager_(min_threads, max_threads),
server_(port),
ban_manager_(),
ip_log_(),
failed_logins_(),
user_handler_(NULL),
seeds_(),
players_(),
ghost_players_(),
games_(),
not_logged_in_(),
rooms_(players_),
input_(),
input_path_(),
config_file_(config_file),
cfg_(read_config()),
accepted_versions_(),
redirected_versions_(),
proxy_versions_(),
disallowed_names_(),
admin_passwd_(),
admins_(),
motd_(),
default_max_messages_(0),
default_time_period_(0),
concurrent_connections_(0),
graceful_restart(false),
lan_server_(time(NULL)),
last_user_seen_time_(time(NULL)),
restart_command(),
max_ip_log_size_(0),
uh_name_(),
deny_unregistered_login_(false),
save_replays_(false),
replay_save_path_(),
allow_remote_shutdown_(false),
tor_ip_list_(),
failed_login_limit_(),
failed_login_ban_(),
failed_login_buffer_size_(),
version_query_response_("[version]\n[/version]\n", simple_wml::INIT_COMPRESSED),
login_response_("[mustlogin]\n[/mustlogin]\n", simple_wml::INIT_COMPRESSED),
join_lobby_response_("[join_lobby]\n[/join_lobby]\n", simple_wml::INIT_COMPRESSED),
games_and_users_list_("[gamelist]\n[/gamelist]\n", simple_wml::INIT_STATIC),
metrics_(),
last_ping_(time(NULL)),
last_stats_(last_ping_),
last_uh_clean_(last_ping_),
cmd_handlers_()
{
setup_handlers();
load_config();
ban_manager_.read();
rooms_.read_rooms();
#ifndef _MSC_VER
signal(SIGHUP, reload_config);
#endif
signal(SIGINT, exit_sigint);
signal(SIGTERM, exit_sigterm);
}
void server::setup_handlers()
{
cmd_handlers_["shut_down"] = &server::shut_down_handler;
cmd_handlers_["restart"] = &server::restart_handler;
cmd_handlers_["sample"] = &server::sample_handler;
cmd_handlers_["help"] = &server::help_handler;
cmd_handlers_["stats"] = &server::stats_handler;
cmd_handlers_["metrics"] = &server::metrics_handler;
cmd_handlers_["requests"] = &server::requests_handler;
cmd_handlers_["games"] = &server::games_handler;
cmd_handlers_["wml"] = &server::wml_handler;
cmd_handlers_["netstats"] = &server::netstats_handler;
cmd_handlers_["report"] = &server::adminmsg_handler;
cmd_handlers_["adminmsg"] = &server::adminmsg_handler;
cmd_handlers_["pm"] = &server::pm_handler;
cmd_handlers_["privatemsg"] = &server::pm_handler;
cmd_handlers_["msg"] = &server::msg_handler;
cmd_handlers_["lobbymsg"] = &server::msg_handler;
cmd_handlers_["status"] = &server::status_handler;
cmd_handlers_["clones"] = &server::clones_handler;
cmd_handlers_["bans"] = &server::bans_handler;
cmd_handlers_["ban"] = &server::ban_handler;
cmd_handlers_["unban"] = &server::unban_handler;
cmd_handlers_["ungban"] = &server::ungban_handler;
cmd_handlers_["kick"] = &server::kick_handler;
cmd_handlers_["kickban"] = &server::kickban_handler;
cmd_handlers_["kban"] = &server::kickban_handler;
cmd_handlers_["gban"] = &server::gban_handler;
cmd_handlers_["motd"] = &server::motd_handler;
cmd_handlers_["searchlog"] = &server::searchlog_handler;
cmd_handlers_["sl"] = &server::searchlog_handler;
cmd_handlers_["dul"] = &server::dul_handler;
cmd_handlers_["deny_unregistered_login"] = &server::dul_handler;
}
void server::send_error(network::connection sock, const char* msg, const char* error_code) const
{
simple_wml::document doc;
doc.root().add_child("error").set_attr("message", msg);
if(*error_code != '\0') {
doc.child("error")->set_attr("error_code", error_code);
}
send_doc(doc, sock, "error");
}
void server::send_warning(network::connection sock, const char* msg, const char* warning_code) const
{
simple_wml::document doc;
doc.root().add_child("warning").set_attr("message", msg);
if(*warning_code != '\0') {
doc.child("warning")->set_attr("warning_code", warning_code);
}
send_doc(doc, sock, "warning");
}
void server::send_password_request(network::connection sock, const std::string& msg,
const std::string& user, const char* error_code, bool force_confirmation)
{
std::string salt = user_handler_->create_salt();
std::string pepper = user_handler_->create_pepper(user);
std::string spices = pepper + salt;
if(user_handler_->use_phpbb_encryption() && pepper.empty()) {
send_error(sock, "Even though your nickname is registered on this server you "
"cannot log in due to an error in the hashing algorithm. "
"Logging into your forum account on http://forum.wesnoth.org "
"may fix this problem.");
return;
}
seeds_.insert(std::pair<network::connection, std::string>(sock, salt));
simple_wml::document doc;
simple_wml::node& e = doc.root().add_child("error");
e.set_attr("message", msg.c_str());
e.set_attr("password_request", "yes");
e.set_attr("phpbb_encryption", user_handler_->use_phpbb_encryption() ? "yes" : "no");
e.set_attr("salt", spices.c_str());
e.set_attr("force_confirmation", force_confirmation ? "yes" : "no");
if(*error_code != '\0') {
e.set_attr("error_code", error_code);
}
send_doc(doc, sock, "error");
}
config server::read_config() const {
config configuration;
if (config_file_ == "") return configuration;
try {
scoped_istream stream = preprocess_file(config_file_);
read(configuration, *stream);
LOG_SERVER << "Server configuration from file: '" << config_file_
<< "' read.\n";
} catch(config::error& e) {
ERR_CONFIG << "ERROR: Could not read configuration file: '"
<< config_file_ << "': '" << e.message << "'.\n";
}
return configuration;
}
void server::load_config() {
#ifndef FIFODIR
# ifdef _MSC_VER
# pragma message ("No FIFODIR set")
# define FIFODIR "d:/"
# else
# warning "No FIFODIR set"
# ifdef _WIN32
# define FIFODIR "d:/"
# else
# define FIFODIR "/var/run/wesnothd"
# endif
# endif
#endif
const std::string fifo_path = (cfg_["fifo_path"].empty() ? std::string(FIFODIR) + "/socket" : std::string(cfg_["fifo_path"]));
// Reset (replace) the input stream only if the FIFO path changed.
if(fifo_path != input_path_) {
input_.reset(new input_stream(fifo_path));
}
input_path_ = fifo_path;
save_replays_ = cfg_["save_replays"].to_bool();
replay_save_path_ = cfg_["replay_save_path"].str();
tor_ip_list_ = utils::split(cfg_["tor_ip_list_path"].empty() ? "" : read_file(cfg_["tor_ip_list_path"]), '\n');
admin_passwd_ = cfg_["passwd"].str();
motd_ = cfg_["motd"].str();
lan_server_ = lexical_cast_default<time_t>(cfg_["lan_server"], 0);
uh_name_ = cfg_["user_handler"].str();
deny_unregistered_login_ = cfg_["deny_unregistered_login"].to_bool();
allow_remote_shutdown_ = cfg_["allow_remote_shutdown"].to_bool();
disallowed_names_.clear();
if (cfg_["disallow_names"] == "") {
disallowed_names_.push_back("*admin*");
disallowed_names_.push_back("*admln*");
disallowed_names_.push_back("*server*");
disallowed_names_.push_back("player");
disallowed_names_.push_back("network");
disallowed_names_.push_back("human");
disallowed_names_.push_back("computer");
disallowed_names_.push_back("ai");
disallowed_names_.push_back("ai?");
} else {
disallowed_names_ = utils::split(cfg_["disallow_names"]);
}
default_max_messages_ = cfg_["max_messages"].to_int(4);
default_time_period_ = cfg_["messages_time_period"].to_int(10);
concurrent_connections_ = cfg_["connections_allowed"].to_int(5);
max_ip_log_size_ = cfg_["max_ip_log_size"].to_int(500);
failed_login_limit_ = cfg_["failed_logins_limit"].to_int(10);
failed_login_ban_ = cfg_["failed_logins_ban"].to_int(3600);
failed_login_buffer_size_ = cfg_["failed_logins_buffer_size"].to_int(500);
// Example config line:
// restart_command="./wesnothd-debug -d -c ~/.wesnoth1.5/server.cfg"
// remember to make new one as a daemon or it will block old one
restart_command = cfg_["restart_command"].str();
fps_limit_.set_ms_per_frame(cfg_["ms_per_frame"].to_int(20));
accepted_versions_.clear();
const std::string& versions = cfg_["versions_accepted"];
if (versions.empty()) {
accepted_versions_.push_back("1.10*");
accepted_versions_.push_back("test");
} else {
accepted_versions_ = utils::split(versions);
}
redirected_versions_.clear();
BOOST_FOREACH(const config &redirect, cfg_.child_range("redirect")) {
BOOST_FOREACH(const std::string &version, utils::split(redirect["version"])) {
redirected_versions_[version] = redirect;
}
}
proxy_versions_.clear();
BOOST_FOREACH(const config &proxy, cfg_.child_range("proxy")) {
BOOST_FOREACH(const std::string &version, utils::split(proxy["version"])) {
proxy_versions_[version] = proxy;
}
}
ban_manager_.load_config(cfg_);
rooms_.load_config(cfg_);
// If there is a [user_handler] tag in the config file
// allow nick registration, otherwise we set user_handler_
// to NULL. Thus we must check user_handler_ for not being
// NULL everytime we want to use it.
user_handler_.reset();
if (const config &user_handler = cfg_.child("user_handler")) {
if(uh_name_ == "sample") {
user_handler_.reset(new suh(user_handler));
}
#ifdef HAVE_MYSQLPP
else if(uh_name_ == "forum" || uh_name_.empty()) {
user_handler_.reset(new fuh(user_handler));
}
#endif
// Initiate the mailer class with the [mail] tag
// from the config file
if (user_handler_) user_handler_->init_mailer(cfg_.child("mail"));
}
}
bool server::ip_exceeds_connection_limit(const std::string& ip) const {
if (concurrent_connections_ == 0) return false;
size_t connections = 0;
for (wesnothd::player_map::const_iterator i = players_.begin(); i != players_.end(); ++i) {
if (network::ip_address(i->first) == ip) {
++connections;
}
}
return connections >= concurrent_connections_;
}
std::string server::is_ip_banned(const std::string& ip) const {
if (!tor_ip_list_.empty()) {
if (find(tor_ip_list_.begin(), tor_ip_list_.end(), ip) != tor_ip_list_.end()) return "TOR IP";
}
return ban_manager_.is_ip_banned(ip);
}
void server::dump_stats(const time_t& now) {
last_stats_ = now;
LOG_SERVER << "Statistics:"
<< "\tnumber_of_games = " << games_.size()
<< "\tnumber_of_users = " << players_.size()
<< "\tlobby_users = " << rooms_.lobby().size() << "\n";
}
void server::clean_user_handler(const time_t& now) {
if(!user_handler_) {
return;
}
last_uh_clean_ = now;
user_handler_->clean_up();
}
void server::run() {
int graceful_counter = 0;
for (int loop = 0;; ++loop) {
// Try to run with 50 FPS all the time
// Server will respond a bit faster under heavy load
fps_limit_.limit();
try {
// We are going to waith 10 seconds before shutting down so users can get out of game.
if (graceful_restart && games_.empty() && ++graceful_counter > 500 )
{
// TODO: We should implement client side autoreconnect.
// Idea:
// server should send [reconnect]host=host,port=number[/reconnect]
// Then client would reconnect to new server automatically.
// This would also allow server to move to new port or address if there is need
process_command("msg All games ended. Shutting down now. Reconnect to the new server instance.", "system");
throw network::error("shut down");
}
if (config_reload == 1) {
cfg_ = read_config();
load_config();
config_reload = 0;
}
// Process commands from the server socket/fifo
std::string admin_cmd;
if (input_ && input_->read_line(admin_cmd)) {
LOG_SERVER << "Admin Command: type: " << admin_cmd << "\n";
const std::string res = process_command(admin_cmd, "*socket*");
// Only mark the response if we fake the issuer (i.e. command comes from IRC or so)
if (admin_cmd.at(0) == '+') {
LOG_SERVER << "[admin_command_response]\n" << res << "\n" << "[/admin_command_response]\n";
} else {
LOG_SERVER << res << "\n";
}
}
time_t now = time(NULL);
if (last_ping_ + network::ping_interval <= now) {
if (lan_server_ && players_.empty() && last_user_seen_time_ + lan_server_ < now)
{
LOG_SERVER << "Lan server has been empty for " << (now - last_user_seen_time_) << " seconds. Shutting down!\n";
// We have to shutdown
graceful_restart = true;
}
// and check if bans have expired
ban_manager_.check_ban_times(now);
// Make sure we log stats every 5 minutes
if (last_stats_ + 5 * 60 <= now) {
dump_stats(now);
if (rooms_.dirty()) rooms_.write_rooms();
}
// Cleaning the user_handler once a day should be more than enough
if (last_uh_clean_ + 60 * 60 * 24 <= now) {
clean_user_handler(now);
}
// Send network stats every hour
static int prev_hour = localtime(&now)->tm_hour;
if (prev_hour != localtime(&now)->tm_hour)
{
prev_hour = localtime(&now)->tm_hour;
LOG_SERVER << network::get_bandwidth_stats();
}
// send a 'ping' to all players to detect ghosts
DBG_SERVER << "Pinging inactive players.\n" ;
std::ostringstream strstr ;
strstr << "ping=\"" << now << "\"" ;
simple_wml::document ping( strstr.str().c_str(),
simple_wml::INIT_COMPRESSED );
simple_wml::string_span s = ping.output_compressed();
BOOST_FOREACH(network::connection sock, ghost_players_) {
if (!lg::debug.dont_log(log_server)) {
wesnothd::player_map::const_iterator i = players_.find(sock);
if (i != players_.end()) {
DBG_SERVER << "Pinging " << i->second.name() << "(" << i->first << ").\n";
} else {
ERR_SERVER << "Player " << sock << " is in ghost_players_ but not in players_.\n";
}
}
network::send_raw_data(s.begin(), s.size(), sock, "ping") ;
}
// Copy new player list on top of ghost_players_ list.
// Only a single thread should be accessing this
// Erase before we copy - speeds inserts
ghost_players_.clear();
BOOST_FOREACH(const wesnothd::player_map::value_type v, players_) {
ghost_players_.insert(v.first);
}
last_ping_ = now;
}
network::process_send_queue();
network::connection sock = network::accept_connection();
if (sock) {
const std::string ip = network::ip_address(sock);
const std::string reason = is_ip_banned(ip);
if (!reason.empty()) {
LOG_SERVER << ip << "\trejected banned user. Reason: " << reason << "\n";
send_error(sock, "You are banned. Reason: " + reason);
network::disconnect(sock);
} else if (ip_exceeds_connection_limit(ip)) {
LOG_SERVER << ip << "\trejected ip due to excessive connections\n";
send_error(sock, "Too many connections from your IP.");
network::disconnect(sock);
} else {
DBG_SERVER << ip << "\tnew connection accepted. (socket: "
<< sock << ")\n";
send_doc(version_query_response_, sock);
not_logged_in_.insert(sock);
}
}
static int sample_counter = 0;
std::vector<char> buf;
network::bandwidth_in_ptr bandwidth_type;
while ((sock = network::receive_data(buf, &bandwidth_type)) != network::null_connection) {
metrics_.service_request();
if(buf.empty()) {
WRN_SERVER << "received empty packet\n";
continue;
}
const bool sample = request_sample_frequency >= 1 && (sample_counter++ % request_sample_frequency) == 0;
const clock_t before_parsing = get_cpu_time(sample);
char* buf_ptr = new char [buf.size()];
memcpy(buf_ptr, &buf[0], buf.size());
simple_wml::string_span compressed_buf(buf_ptr, buf.size());
boost::scoped_ptr<simple_wml::document> data_ptr;
try {
data_ptr.reset(new simple_wml::document(compressed_buf)); // might throw a simple_wml::error
data_ptr->take_ownership_of_buffer(buf_ptr);
} catch (simple_wml::error& e) {
WRN_CONFIG << "simple_wml error in received data: " << e.message << std::endl;
send_error(sock, "Invalid WML received: " + e.message);
delete [] buf_ptr;
continue;
} catch(...) {
delete [] buf_ptr;
throw;
}
simple_wml::document& data = *data_ptr;
std::vector<char>().swap(buf);
const clock_t after_parsing = get_cpu_time(sample);
process_data(sock, data);
bandwidth_type->set_type(data.root().first_child().to_string());
if(sample) {
const clock_t after_processing = get_cpu_time(sample);
metrics_.record_sample(data.root().first_child(),
after_parsing - before_parsing,
after_processing - after_parsing);
}
}
metrics_.no_requests();
} catch(simple_wml::error& e) {
WRN_CONFIG << "Warning: error in received data: " << e.message << "\n";
} catch(network::error& e) {
if (e.message == "shut down") {
LOG_SERVER << "Try to disconnect all users...\n";
for (wesnothd::player_map::const_iterator pl = players_.begin();
pl != players_.end(); ++pl)
{
network::disconnect(pl->first);
}
LOG_SERVER << "Shutting server down.\n";
break;
}
if (!e.socket) {
ERR_SERVER << "network error: " << e.message << "\n";
e.disconnect();
continue;
}
DBG_SERVER << "socket closed: " << e.message << "\n";
const std::string ip = network::ip_address(e.socket);
if (proxy::is_proxy(e.socket)) {
LOG_SERVER << ip << "\tProxy user disconnected.\n";
proxy::disconnect(e.socket);
e.disconnect();
DBG_SERVER << "done closing socket...\n";
continue;
}
// Was the user already logged in?
const wesnothd::player_map::iterator pl_it = players_.find(e.socket);
if (pl_it == players_.end()) {
std::set<network::connection>::iterator i = not_logged_in_.find(e.socket);
if (i != not_logged_in_.end()) {
DBG_SERVER << ip << "\tNot logged in user disconnected.\n";
not_logged_in_.erase(i);
} else {
WRN_SERVER << ip << "\tWarning: User disconnected right after the connection was accepted.\n";
}
e.disconnect();
DBG_SERVER << "done closing socket...\n";
continue;
}
const simple_wml::node::child_list& users = games_and_users_list_.root().children("user");
const size_t index = std::find(users.begin(), users.end(), pl_it->second.config_address()) - users.begin();
if (index < users.size()) {
simple_wml::document diff;
if(make_delete_diff(games_and_users_list_.root(), NULL, "user",
pl_it->second.config_address(), diff)) {
rooms_.lobby().send_data(diff, e.socket);
}
games_and_users_list_.root().remove_child("user", index);
} else {
ERR_SERVER << ip << "ERROR: Could not find user to remove: "
<< pl_it->second.name() << " in games_and_users_list_.\n";
}
// Was the player in the lobby or a game?
if (rooms_.in_lobby(e.socket)) {
rooms_.remove_player(e.socket);
LOG_SERVER << ip << "\t" << pl_it->second.name()
<< "\thas logged off. (socket: " << e.socket << ")\n";
} else {
for (std::vector<wesnothd::game*>::iterator g = games_.begin();
g != games_.end(); ++g)
{
if (!(*g)->is_member(e.socket)) {
continue;
}
// Did the last player leave?
if ((*g)->remove_player(e.socket, true)) {
delete_game(g);
break;
} else {
(*g)->describe_slots();
update_game_in_lobby(*g, e.socket);
}
break;
}
}
// Find the matching nick-ip pair in the log and update the sign off time
connection_log ip_name = connection_log(pl_it->second.name(), ip, 0);
std::deque<connection_log>::iterator i = std::find(ip_log_.begin(), ip_log_.end(), ip_name);
if(i != ip_log_.end()) {
i->log_off = time(NULL);
}
players_.erase(pl_it);
ghost_players_.erase(e.socket);
if (lan_server_)
{
last_user_seen_time_ = time(0);
}
e.disconnect();
DBG_SERVER << "done closing socket...\n";
// Catch user_handler exceptions here, to prevent the
// server from going down completely. Once we are sure
// all user_handler exceptions are caught correctly
// this can removed.
} catch (user_handler::error& e) {
ERR_SERVER << "Uncaught user_handler exception: " << e.message << "\n";
}
}
}
void server::process_data(const network::connection sock,
simple_wml::document& data) {
if (proxy::is_proxy(sock)) {
proxy::received_data(sock, data);
return;
}
// We know the client is alive for this interval
// Remove player from ghost_players map if selective_ping
// is enabled for the player.
if (ghost_players_.find(sock) != ghost_players_.end()) {
const wesnothd::player_map::const_iterator pl = players_.find(sock);
if (pl != players_.end()) {
if (pl->second.selective_ping() ) {
ghost_players_.erase(sock);
}
}
}
// Process the message
simple_wml::node& root = data.root();
if(root.has_attr("ping")) {
// Ignore client side pings for now.
return;
} else if(not_logged_in_.find(sock) != not_logged_in_.end()) {
// Someone who is not yet logged in is sending login details.
process_login(sock, data);
} else if (simple_wml::node* query = root.child("query")) {
process_query(sock, *query);
} else if (simple_wml::node* nickserv = root.child("nickserv")) {
process_nickserv(sock, *nickserv);
} else if (simple_wml::node* whisper = root.child("whisper")) {
process_whisper(sock, *whisper);
} else if (rooms_.in_lobby(sock)) {
process_data_lobby(sock, data);
} else {
process_data_game(sock, data);
}
}
void server::process_login(const network::connection sock,
simple_wml::document& data) {
// See if the client is sending their version number.
if (const simple_wml::node* const version = data.child("version")) {
const simple_wml::string_span& version_str_span = (*version)["version"];
const std::string version_str(version_str_span.begin(),
version_str_span.end());
std::vector<std::string>::const_iterator accepted_it;
// Check if it is an accepted version.
for (accepted_it = accepted_versions_.begin();
accepted_it != accepted_versions_.end(); ++accepted_it) {
if (utils::wildcard_string_match(version_str, *accepted_it)) break;
}
if (accepted_it != accepted_versions_.end()) {
LOG_SERVER << network::ip_address(sock)
<< "\tplayer joined using accepted version " << version_str
<< ":\ttelling them to log in.\n";
send_doc(login_response_, sock);
return;
}
std::map<std::string, config>::const_iterator config_it;
// Check if it is a redirected version
for (config_it = redirected_versions_.begin();
config_it != redirected_versions_.end(); ++config_it)
{
if (utils::wildcard_string_match(version_str, config_it->first))
break;
}
if (config_it != redirected_versions_.end()) {
LOG_SERVER << network::ip_address(sock)
<< "\tplayer joined using version " << version_str
<< ":\tredirecting them to " << config_it->second["host"]
<< ":" << config_it->second["port"] << "\n";
config response;
response.add_child("redirect", config_it->second);
network::send_data(response, sock, "redirect");
return;
}
// Check if it's a version we should start a proxy for.
for (config_it = proxy_versions_.begin();
config_it != proxy_versions_.end(); ++config_it)
{