/
server.cpp
3000 lines (2502 loc) · 92.2 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
/*
Copyright (C) 2003 - 2018 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/server.hpp"
#include "config.hpp"
#include "filesystem.hpp"
#include "game_config.hpp"
#include "lexical_cast.hpp"
#include "log.hpp"
#include "multiplayer_error_codes.hpp"
#include "serialization/parser.hpp"
#include "serialization/preprocessor.hpp"
#include "serialization/string_utils.hpp"
#include "serialization/unicode.hpp"
#include "utils/functional.hpp"
#include "utils/iterable_pair.hpp"
#include "server/ban.hpp"
#include "server/game.hpp"
#include "server/metrics.hpp"
#include "server/player.hpp"
#include "server/player_network.hpp"
#include "server/sample_user_handler.hpp"
#include "server/simple_wml.hpp"
#include "server/user_handler.hpp"
#ifdef HAVE_MYSQLPP
#include "server/forum_user_handler.hpp"
#endif
#include <boost/algorithm/string.hpp>
#include <algorithm>
#include <cassert>
#include <cerrno>
#include <csignal>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <vector>
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)
#include "server/send_receive_wml_helpers.ipp"
namespace wesnothd
{
// we take profiling info on every n requests
int request_sample_frequency = 1;
static 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));
}
static 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 auto itor = std::find(children.begin(), children.end(), remove);
if(itor == children.end()) {
return false;
}
const int index = std::distance(children.begin(), itor);
simple_wml::node& del = top->add_child("delete_child");
del.set_attr_int("index", index);
del.add_child(type);
return true;
}
static 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 auto 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 = std::distance(children.begin(), itor);
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;
}
static std::string player_status(const wesnothd::player_record& player)
{
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 << "'" << player.name() << "' @ " << client_address(player.socket());
// << " 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();
}
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 in between <> like the command names)"
" are case insensitive.";
server::server(int port,
bool keep_alive,
const std::string& config_file,
std::size_t /*min_threads*/,
std::size_t /*max_threads*/)
: server_base(port, keep_alive)
, ban_manager_()
, ip_log_()
, failed_logins_()
, user_handler_(nullptr)
#ifndef _WIN32
, input_path_()
#endif
, config_file_(config_file)
, cfg_(read_config())
, accepted_versions_()
, redirected_versions_()
, proxy_versions_()
, disallowed_names_()
, admin_passwd_()
, motd_()
, default_max_messages_(0)
, default_time_period_(0)
, concurrent_connections_(0)
, graceful_restart(false)
, lan_server_(std::time(nullptr))
, last_user_seen_time_(std::time(nullptr))
, 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_(std::time(nullptr))
, last_stats_(last_ping_)
, last_uh_clean_(last_ping_)
, cmd_handlers_()
, timer_(io_service_)
{
setup_handlers();
load_config();
ban_manager_.read();
start_server();
}
#ifndef _WIN32
void server::handle_sighup(const boost::system::error_code& error, int)
{
assert(!error);
WRN_SERVER << "SIGHUP caught, reloading config\n";
cfg_ = read_config();
load_config();
sighup_.async_wait(std::bind(&server::handle_sighup, this, _1, _2));
}
#endif
void server::handle_graceful_timeout(const boost::system::error_code& error)
{
assert(!error);
if(games().empty()) {
process_command("msg All games ended. Shutting down now. Reconnect to the new server instance.", "system");
throw server_shutdown("graceful shutdown timeout");
} else {
timer_.expires_from_now(boost::posix_time::seconds(1));
timer_.async_wait(std::bind(&server::handle_graceful_timeout, this, _1));
}
}
void server::setup_fifo()
{
#ifndef _WIN32
const int res = mkfifo(input_path_.c_str(), 0660);
if(res != 0 && errno != EEXIST) {
ERR_SERVER << "could not make fifo at '" << input_path_ << "' (" << strerror(errno) << ")\n";
return;
}
int fifo = open(input_path_.c_str(), O_RDWR | O_NONBLOCK);
input_.assign(fifo);
LOG_SERVER << "opened fifo at '" << input_path_ << "'. Server commands may be written to this file.\n";
read_from_fifo();
#endif
}
#ifndef _WIN32
void server::handle_read_from_fifo(const boost::system::error_code& error, std::size_t)
{
if(error) {
std::cout << error.message() << std::endl;
return;
}
std::istream is(&admin_cmd_);
std::string cmd;
std::getline(is, cmd);
LOG_SERVER << "Admin Command: type: " << cmd << "\n";
const std::string res = process_command(cmd, "*socket*");
// Only mark the response if we fake the issuer (i.e. command comes from IRC or so)
if(cmd.at(0) == '+') {
LOG_SERVER << "[admin_command_response]\n"
<< res << "\n"
<< "[/admin_command_response]\n";
} else {
LOG_SERVER << res << "\n";
}
read_from_fifo();
}
#endif
void server::setup_handlers()
{
#define SETUP_HANDLER(name, function) \
cmd_handlers_[name] = std::bind(function, this, \
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4);
SETUP_HANDLER("shut_down", &server::shut_down_handler);
SETUP_HANDLER("restart", &server::restart_handler);
SETUP_HANDLER("sample", &server::sample_handler);
SETUP_HANDLER("help", &server::help_handler);
SETUP_HANDLER("stats", &server::stats_handler);
SETUP_HANDLER("version", &server::version_handler);
SETUP_HANDLER("metrics", &server::metrics_handler);
SETUP_HANDLER("requests", &server::requests_handler);
SETUP_HANDLER("games", &server::games_handler);
SETUP_HANDLER("wml", &server::wml_handler);
SETUP_HANDLER("netstats", &server::netstats_handler);
SETUP_HANDLER("report", &server::adminmsg_handler);
SETUP_HANDLER("adminmsg", &server::adminmsg_handler);
SETUP_HANDLER("pm", &server::pm_handler);
SETUP_HANDLER("privatemsg", &server::pm_handler);
SETUP_HANDLER("msg", &server::msg_handler);
SETUP_HANDLER("lobbymsg", &server::msg_handler);
SETUP_HANDLER("status", &server::status_handler);
SETUP_HANDLER("clones", &server::clones_handler);
SETUP_HANDLER("bans", &server::bans_handler);
SETUP_HANDLER("ban", &server::ban_handler);
SETUP_HANDLER("unban", &server::unban_handler);
SETUP_HANDLER("ungban", &server::ungban_handler);
SETUP_HANDLER("kick", &server::kick_handler);
SETUP_HANDLER("kickban", &server::kickban_handler);
SETUP_HANDLER("kban", &server::kickban_handler);
SETUP_HANDLER("gban", &server::gban_handler);
SETUP_HANDLER("motd", &server::motd_handler);
SETUP_HANDLER("searchlog", &server::searchlog_handler);
SETUP_HANDLER("sl", &server::searchlog_handler);
SETUP_HANDLER("dul", &server::dul_handler);
SETUP_HANDLER("deny_unregistered_login", &server::dul_handler);
#undef SETUP_HANDLER
}
config server::read_config() const
{
config configuration;
if(config_file_.empty()) {
return configuration;
}
try {
filesystem::scoped_istream stream = preprocess_file(config_file_);
read(configuration, *stream);
LOG_SERVER << "Server configuration from file: '" << config_file_ << "' read.\n";
} catch(const config::error& e) {
ERR_CONFIG << "ERROR: Could not read configuration file: '" << config_file_ << "': '" << e.message << "'.\n";
}
return configuration;
}
void server::load_config()
{
#ifndef _WIN32
#ifndef FIFODIR
#warning No FIFODIR set
#define FIFODIR "/var/run/wesnothd"
#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_.close();
input_path_ = fifo_path;
setup_fifo();
}
#endif
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()
? ""
: filesystem::read_file(cfg_["tor_ip_list_path"]), '\n');
admin_passwd_ = cfg_["passwd"].str();
motd_ = cfg_["motd"].str();
lan_server_ = cfg_["lan_server"].to_time_t(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"].empty()) {
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();
accepted_versions_.clear();
const std::string& versions = cfg_["versions_accepted"];
if(versions.empty() == false) {
accepted_versions_ = utils::split(versions);
} else {
accepted_versions_.push_back(game_config::wesnoth_version.str());
accepted_versions_.push_back("test");
}
redirected_versions_.clear();
for(const config& redirect : cfg_.child_range("redirect")) {
for(const std::string& version : utils::split(redirect["version"])) {
redirected_versions_[version] = redirect;
}
}
proxy_versions_.clear();
for(const config& proxy : cfg_.child_range("proxy")) {
for(const std::string& version : utils::split(proxy["version"])) {
proxy_versions_[version] = proxy;
}
}
ban_manager_.load_config(cfg_);
// If there is a [user_handler] tag in the config file
// allow nick registration, otherwise we set user_handler_
// to nullptr. Thus we must check user_handler_ for not being
// nullptr every time 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;
}
std::size_t connections = 0;
for(const auto& player : player_connections_) {
if(client_address(player.socket()) == ip) {
++connections;
}
}
return connections >= concurrent_connections_;
}
std::string server::is_ip_banned(const std::string& ip)
{
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 std::time_t& now)
{
last_stats_ = now;
LOG_SERVER << "Statistics:"
<< "\tnumber_of_games = " << games().size() << "\tnumber_of_users = " << player_connections_.size()
<< "\n";
}
void server::clean_user_handler(const std::time_t& now)
{
if(!user_handler_) {
return;
}
last_uh_clean_ = now;
user_handler_->clean_up();
}
void server::handle_new_client(socket_ptr socket)
{
async_send_doc(socket, version_query_response_, std::bind(&server::handle_version, this, _1));
}
void server::handle_version(socket_ptr socket)
{
async_receive_doc(socket, std::bind(&server::read_version, this, _1, _2));
}
void server::read_version(socket_ptr socket, std::shared_ptr<simple_wml::document> doc)
{
if(const simple_wml::node* const version = doc->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());
// Check if it is an accepted version.
auto accepted_it = std::find_if(accepted_versions_.begin(), accepted_versions_.end(),
std::bind(&utils::wildcard_string_match, version_str, _1));
if(accepted_it != accepted_versions_.end()) {
LOG_SERVER << client_address(socket) << "\tplayer joined using accepted version " << version_str
<< ":\ttelling them to log in.\n";
async_send_doc(socket, login_response_, std::bind(&server::login, this, _1, version_str));
return;
}
simple_wml::document response;
// Check if it is a redirected version
for(const auto& redirect_version : redirected_versions_) {
if(utils::wildcard_string_match(version_str, redirect_version.first)) {
LOG_SERVER << client_address(socket) << "\tplayer joined using version " << version_str
<< ":\tredirecting them to " << redirect_version.second["host"] << ":"
<< redirect_version.second["port"] << "\n";
simple_wml::node& redirect = response.root().add_child("redirect");
for(const auto& attr : redirect_version.second.attribute_range()) {
redirect.set_attr_dup(attr.first.c_str(), attr.second.str().c_str());
}
send_to_player(socket, response);
return;
}
}
LOG_SERVER << client_address(socket) << "\tplayer joined using unknown version " << version_str
<< ":\trejecting them\n";
// For compatibility with older clients
response.set_attr("version", accepted_versions_.begin()->c_str());
simple_wml::node& reject = response.root().add_child("reject");
reject.set_attr_dup("accepted_versions", utils::join(accepted_versions_).c_str());
send_to_player(socket, response);
} else {
LOG_SERVER << client_address(socket) << "\tclient didn't send its version: rejecting\n";
}
}
void server::login(socket_ptr socket, std::string version)
{
async_receive_doc(socket, std::bind(&server::handle_login, this, _1, _2, version));
}
void server::handle_login(socket_ptr socket, std::shared_ptr<simple_wml::document> doc, std::string version)
{
if(const simple_wml::node* const login = doc->child("login")) {
if(!is_login_allowed(socket, login, version)) {
server::login(socket, version); // keep reading logins from client until we get a successful one
}
} else {
async_send_error(socket, "You must login first.", MP_MUST_LOGIN);
}
}
bool server::is_login_allowed(socket_ptr socket, const simple_wml::node* const login, const std::string& version)
{
// Check if the username is valid (all alpha-numeric plus underscore and hyphen)
std::string username = (*login)["username"].to_string();
if(!utils::isvalid_username(username)) {
async_send_error(socket,
"The nickname '" + username + "' contains invalid "
"characters. Only alpha-numeric characters, underscores and hyphens are allowed.",
MP_INVALID_CHARS_IN_NAME_ERROR
);
return false;
}
if(username.size() > 20) {
async_send_error(socket, "The nickname '" + username + "' is too long. Nicks must be 20 characters or less.",
MP_NAME_TOO_LONG_ERROR);
return false;
}
// Check if the username is allowed.
for(const std::string d : disallowed_names_) {
if(utils::wildcard_string_match(utf8::lowercase(username), utf8::lowercase(d))) {
async_send_error(socket, "The nickname '" + username + "' is reserved and cannot be used by players",
MP_NAME_RESERVED_ERROR);
return false;
}
}
// Check the username isn't already taken
auto p = player_connections_.get<name_t>().find(username);
bool name_taken = p != player_connections_.get<name_t>().end();
// Check for password
bool registered;
if(!authenticate(socket, username, (*login)["password"].to_string(), version, name_taken, registered))
return true; // it's a failed login but we don't want to call server::login again
// because send_password_request() will handle the next network write and read instead
// If we disallow unregistered users and this user is not registered send an error
if(user_handler_ && !registered && deny_unregistered_login_) {
async_send_error(socket,
"The nickname '" + username + "' is not registered. This server disallows unregistered nicknames.",
MP_NAME_UNREGISTERED_ERROR
);
return false;
}
const bool is_moderator = user_handler_ && user_handler_->user_is_moderator(username);
const user_handler::BAN_TYPE auth_ban = user_handler_
? user_handler_->user_is_banned(username, client_address(socket))
: user_handler::BAN_NONE;
if(auth_ban) {
std::string ban_type_desc;
std::string ban_reason;
const char* msg_numeric;
switch(auth_ban) {
case user_handler::BAN_USER:
ban_type_desc = "account";
msg_numeric = MP_NAME_AUTH_BAN_USER_ERROR;
ban_reason = "a ban has been issued on your user account.";
break;
case user_handler::BAN_IP:
ban_type_desc = "IP address";
msg_numeric = MP_NAME_AUTH_BAN_IP_ERROR;
ban_reason = "a ban has been issued on your IP address.";
break;
case user_handler::BAN_EMAIL:
ban_type_desc = "email address";
msg_numeric = MP_NAME_AUTH_BAN_EMAIL_ERROR;
ban_reason = "a ban has been issued on your email address.";
break;
default:
ban_type_desc = "<unknown ban type>";
msg_numeric = "";
ban_reason = ban_type_desc;
}
if(!is_moderator) {
LOG_SERVER << client_address(socket) << "\t" << username << "\tis banned by user_handler (" << ban_type_desc
<< ")\n";
async_send_error(socket, "You are banned from this server: " + ban_reason, msg_numeric);
return false;
} else {
LOG_SERVER << client_address(socket) << "\t" << username << "\tis banned by user_handler (" << ban_type_desc
<< "), " << "ignoring due to moderator flag\n";
}
}
if(name_taken) {
if(registered) {
// If there is already a client using this username kick it
process_command("kick " + p->info().name() + " autokick by registered user", username);
} else {
async_send_error(socket, "The nickname '" + username + "' is already taken.", MP_NAME_TAKEN_ERROR);
return false;
}
}
simple_wml::node& player_cfg = games_and_users_list_.root().add_child("user");
async_send_doc(socket, join_lobby_response_,
std::bind(&server::add_player, this, _1,
wesnothd::player(
username,
player_cfg,
registered,
version,
default_max_messages_,
default_time_period_,
user_handler_ && user_handler_->user_is_moderator(username)
)
)
);
LOG_SERVER << client_address(socket) << "\t" << username << "\thas logged on"
<< (registered ? " to a registered account" : "") << "\n";
if(is_moderator) {
LOG_SERVER << "Admin automatically recognized: IP: " << client_address(socket) << "\tnick: " << username
<< std::endl;
// This string is parsed by the client!
send_server_message(socket,
"You are now recognized as an administrator. "
"If you no longer want to be automatically authenticated use '/query signout'.");
}
if(auth_ban) {
send_server_message(socket, "You are currently banned by the forum administration.");
}
// Log the IP
connection_log ip_name = connection_log(username, client_address(socket), 0);
if(std::find(ip_log_.begin(), ip_log_.end(), ip_name) == ip_log_.end()) {
ip_log_.push_back(ip_name);
// Remove the oldest entry if the size of the IP log exceeds the maximum size
if(ip_log_.size() > max_ip_log_size_) {
ip_log_.pop_front();
}
}
return true;
}
bool server::authenticate(
socket_ptr socket, const std::string& username, const std::string& password, const std::string& version, bool name_taken, bool& registered)
{
// Current login procedure for registered nicks is:
// - Client asks to log in with a particular nick
// - Server sends client random nonce plus some info
// generated from the original hash that is required to
// regenerate the hash
// - Client generates hash for the user provided password
// and mixes it with the received random nonce
// - Server received password hash hashed with the nonce,
// applies the nonce to the valid hash and compares the results
registered = false;
if(user_handler_) {
const bool exists = user_handler_->user_exists(username);
// This name is registered but the account is not active
if(exists && !user_handler_->user_is_active(username)) {
async_send_warning(socket,
"The nickname '" + username + "' is inactive. You cannot claim ownership of this "
"nickname until you activate your account via email or ask an administrator to do it for you.",
MP_NAME_INACTIVE_WARNING
);
// registered = false;
} else if(exists) {
// This name is registered and no password provided
if(password.empty()) {
if(!name_taken) {
send_password_request(socket, "The nickname '" + username + "' is registered on this server.",
username, version, MP_PASSWORD_REQUEST);
} else {
send_password_request(socket,
"The nickname '" + username + "' is registered on this server."
"\n\nWARNING: There is already a client using this username, "
"logging in will cause that client to be kicked!",
username, version, MP_PASSWORD_REQUEST_FOR_LOGGED_IN_NAME, true
);
}
return false;
}
// A password (or hashed password) was provided, however
// there is no seed
if(seeds_[reinterpret_cast<long int>(socket.get())].empty()) {
send_password_request(socket, "Please try again.", username, version, MP_NO_SEED_ERROR);
return false;
}
// This name is registered and an incorrect password provided
else if(!(user_handler_->login(username, password, seeds_[reinterpret_cast<unsigned long>(socket.get())]))) {
const std::time_t now = std::time(nullptr);
// Reset the random seed
seeds_.erase(reinterpret_cast<unsigned long>(socket.get()));
login_log login_ip = login_log(client_address(socket), 0, now);
auto i = std::find(failed_logins_.begin(), failed_logins_.end(), login_ip);
if(i == failed_logins_.end()) {
failed_logins_.push_back(login_ip);
i = --failed_logins_.end();
// Remove oldest entry if maximum size is exceeded
if(failed_logins_.size() > failed_login_buffer_size_) {
failed_logins_.pop_front();
}
}
if(i->first_attempt + failed_login_ban_ < now) {
// Clear and move to the beginning
failed_logins_.erase(i);
failed_logins_.push_back(login_ip);
i = --failed_logins_.end();
}
i->attempts++;
if(i->attempts > failed_login_limit_) {
LOG_SERVER << ban_manager_.ban(login_ip.ip, now + failed_login_ban_,
"Maximum login attempts exceeded", "automatic", "", username);
async_send_error(socket,
"You have made too many failed login attempts.", MP_TOO_MANY_ATTEMPTS_ERROR);
} else {
send_password_request(socket,
"The password you provided for the nickname '" + username + "' was incorrect.", username,version,
MP_INCORRECT_PASSWORD_ERROR);
}
// Log the failure
LOG_SERVER << client_address(socket) << "\t"
<< "Login attempt with incorrect password for nickname '" << username << "'.\n";
return false;
}
// This name exists and the password was neither empty nor incorrect
registered = true;
// Reset the random seed
seeds_.erase(reinterpret_cast<long int>(socket.get()));
user_handler_->user_logged_in(username);
}
}
return true;
}
void server::send_password_request(socket_ptr socket,
const std::string& msg,
const std::string& user,
const std::string& version,
const char* error_code,
bool force_confirmation)
{
std::string salt = user_handler_->extract_salt(user);
// If using crypt_blowfish, use 32 random Base64 characters, cryptographic-strength, 192 bits entropy
// else (phppass, MD5, $H$), use 8 random integer digits, not secure, do not use, this is crap, 29.8 bits entropy
std::string nonce{(salt[1] == '2')
? user_handler_->create_secure_nonce()
: user_handler_->create_unsecure_nonce()};
std::string password_challenge = salt + nonce;
if(user_handler_->use_phpbb_encryption() && salt.empty()) {
async_send_error(socket,
"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 https://forums.wesnoth.org "
"may fix this problem.");
login(socket, version);
return;
}
seeds_[reinterpret_cast<long int>(socket.get())] = nonce;
simple_wml::document doc;
simple_wml::node& e = doc.root().add_child("error");
e.set_attr_dup("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_dup("salt", password_challenge.c_str());
e.set_attr("force_confirmation", force_confirmation ? "yes" : "no");
if(*error_code != '\0') {
e.set_attr("error_code", error_code);
}
async_send_doc(socket, doc, std::bind(&server::login, this, _1, version));
}
void server::add_player(socket_ptr socket, const wesnothd::player& player)
{
bool inserted;
std::tie(std::ignore, inserted) = player_connections_.insert(player_connections::value_type(socket, player));
assert(inserted);
send_to_player(socket, games_and_users_list_);
if(!motd_.empty()) {
send_server_message(socket, motd_);
}
read_from_player(socket);
// Send other players in the lobby the update that the player has joined
simple_wml::document diff;
make_add_diff(games_and_users_list_.root(), nullptr, "user", diff);
send_to_lobby(diff, socket);
}
void server::read_from_player(socket_ptr socket)
{
async_receive_doc(socket,
std::bind(&server::handle_read_from_player, this, _1, _2),
std::bind(&server::remove_player, this, _1)
);
}
void server::handle_read_from_player(socket_ptr socket, std::shared_ptr<simple_wml::document> doc)
{
read_from_player(socket);
// DBG_SERVER << client_address(socket) << "\tWML received:\n" << doc->output() << std::endl;
if(doc->child("refresh_lobby")) {
send_to_player(socket, games_and_users_list_);
return;
}
if(simple_wml::node* whisper = doc->child("whisper")) {
handle_whisper(socket, *whisper);
return;
}
if(simple_wml::node* query = doc->child("query")) {
handle_query(socket, *query);
return;
}
if(simple_wml::node* nickserv = doc->child("nickserv")) {
handle_nickserv(socket, *nickserv);
return;
}
if(!player_is_in_game(socket)) {
handle_player_in_lobby(socket, doc);
} else {
handle_player_in_game(socket, doc);