The Battle for Wesnoth  1.15.0-dev
server.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
15 /**
16  * @file
17  * Wesnoth-Server, for multiplayer-games.
18  */
19 
20 #include "server/server.hpp"
21 
22 #include "config.hpp"
23 #include "filesystem.hpp"
24 #include "game_config.hpp"
25 #include "lexical_cast.hpp"
26 #include "log.hpp"
28 #include "serialization/parser.hpp"
32 #include "utils/functional.hpp"
33 #include "utils/iterable_pair.hpp"
34 #include "game_version.hpp"
35 
36 #include "server/ban.hpp"
37 #include "server/game.hpp"
38 #include "server/metrics.hpp"
39 #include "server/player.hpp"
42 #include "server/simple_wml.hpp"
43 #include "server/user_handler.hpp"
44 
45 #ifdef HAVE_MYSQLPP
47 #endif
48 
49 #include <boost/algorithm/string.hpp>
50 
51 #include <algorithm>
52 #include <cassert>
53 #include <cerrno>
54 #include <csignal>
55 #include <cstdlib>
56 #include <iomanip>
57 #include <iostream>
58 #include <map>
59 #include <queue>
60 #include <set>
61 #include <sstream>
62 #include <vector>
63 
64 static lg::log_domain log_server("server");
65 /**
66  * fatal and directly server related errors/warnings,
67  * ie not caused by erroneous client data
68  */
69 #define ERR_SERVER LOG_STREAM(err, log_server)
70 
71 /** clients send wrong/unexpected data */
72 #define WRN_SERVER LOG_STREAM(warn, log_server)
73 
74 /** normal events */
75 #define LOG_SERVER LOG_STREAM(info, log_server)
76 #define DBG_SERVER LOG_STREAM(debug, log_server)
77 
78 static lg::log_domain log_config("config");
79 #define ERR_CONFIG LOG_STREAM(err, log_config)
80 #define WRN_CONFIG LOG_STREAM(warn, log_config)
81 
83 
84 namespace wesnothd
85 {
86 // we take profiling info on every n requests
89 
90 static void make_add_diff(
91  const simple_wml::node& src, const char* gamelist, const char* type, simple_wml::document& out, int index = -1)
92 {
93  if(!out.child("gamelist_diff")) {
94  out.root().add_child("gamelist_diff");
95  }
96 
97  simple_wml::node* top = out.child("gamelist_diff");
98  if(gamelist) {
99  top = &top->add_child("change_child");
100  top->set_attr_int("index", 0);
101  top = &top->add_child("gamelist");
102  }
103 
104  simple_wml::node& insert = top->add_child("insert_child");
105  const simple_wml::node::child_list& children = src.children(type);
106  assert(!children.empty());
107 
108  if(index < 0) {
109  index = children.size() - 1;
110  }
111 
112  assert(index < static_cast<int>(children.size()));
113  insert.set_attr_int("index", index);
114 
115  children[index]->copy_into(insert.add_child(type));
116 }
117 
118 static bool make_delete_diff(const simple_wml::node& src,
119  const char* gamelist,
120  const char* type,
121  const simple_wml::node* remove,
123 {
124  if(!out.child("gamelist_diff")) {
125  out.root().add_child("gamelist_diff");
126  }
127 
128  simple_wml::node* top = out.child("gamelist_diff");
129  if(gamelist) {
130  top = &top->add_child("change_child");
131  top->set_attr_int("index", 0);
132  top = &top->add_child("gamelist");
133  }
134 
135  const simple_wml::node::child_list& children = src.children(type);
136  const auto itor = std::find(children.begin(), children.end(), remove);
137 
138  if(itor == children.end()) {
139  return false;
140  }
141 
142  const int index = std::distance(children.begin(), itor);
143 
144  simple_wml::node& del = top->add_child("delete_child");
145  del.set_attr_int("index", index);
146  del.add_child(type);
147 
148  return true;
149 }
150 
151 static bool make_change_diff(const simple_wml::node& src,
152  const char* gamelist,
153  const char* type,
154  const simple_wml::node* item,
156 {
157  if(!out.child("gamelist_diff")) {
158  out.root().add_child("gamelist_diff");
159  }
160 
161  simple_wml::node* top = out.child("gamelist_diff");
162  if(gamelist) {
163  top = &top->add_child("change_child");
164  top->set_attr_int("index", 0);
165  top = &top->add_child("gamelist");
166  }
167 
168  const simple_wml::node::child_list& children = src.children(type);
169  const auto itor = std::find(children.begin(), children.end(), item);
170 
171  if(itor == children.end()) {
172  return false;
173  }
174 
175  simple_wml::node& diff = *top;
176  simple_wml::node& del = diff.add_child("delete_child");
177 
178  const int index = std::distance(children.begin(), itor);
179 
180  del.set_attr_int("index", index);
181  del.add_child(type);
182 
183  // inserts will be processed first by the client, so insert at index+1,
184  // and then when the delete is processed we'll slide into the right position
185  simple_wml::node& insert = diff.add_child("insert_child");
186  insert.set_attr_int("index", index + 1);
187 
188  children[index]->copy_into(insert.add_child(type));
189  return true;
190 }
191 
192 static std::string player_status(const wesnothd::player_record& player)
193 {
194  std::ostringstream out;
195  // const network::connection_stats& stats = network::get_connection_stats(pl->first);
196  // const int time_connected = stats.time_connected / 1000;
197  // const int seconds = time_connected % 60;
198  // const int minutes = (time_connected / 60) % 60;
199  // const int hours = time_connected / (60 * 60);
200  out << "'" << player.name() << "' @ " << client_address(player.socket());
201  // << " connected for " << std::setw(2) << hours << ":" << std::setw(2) << minutes << ":" << std::setw(2) <<
202  //seconds
203  // << " sent " << stats.bytes_sent << " bytes, received "
204  // << stats.bytes_received << " bytes";
205  return out.str();
206 }
207 
208 const std::string denied_msg = "You're not allowed to execute this command.";
209 const std::string help_msg =
210  "Available commands are: adminmsg <msg>,"
211  " ban <mask> <time> <reason>, bans [deleted] [<ipmask>], clones,"
212  " dul|deny_unregistered_login [yes|no], kick <mask> [<reason>],"
213  " k[ick]ban <mask> <time> <reason>, help, games, metrics,"
214  " netstats [all], [lobby]msg <message>, motd [<message>],"
215  " pm|privatemsg <nickname> <message>, requests, sample, searchlog <mask>,"
216  " signout, stats, status [<mask>], unban <ipmask>\n"
217  "Specific strings (those not in between <> like the command names)"
218  " are case insensitive.";
219 
220 server::server(int port,
221  bool keep_alive,
222  const std::string& config_file,
223  std::size_t /*min_threads*/,
224  std::size_t /*max_threads*/)
225  : server_base(port, keep_alive)
226  , ban_manager_()
227  , ip_log_()
228  , failed_logins_()
229  , user_handler_(nullptr)
230 #ifndef _WIN32
231  , input_path_()
232 #endif
233  , config_file_(config_file)
234  , cfg_(read_config())
235  , accepted_versions_()
236  , redirected_versions_()
237  , proxy_versions_()
238  , disallowed_names_()
239  , admin_passwd_()
240  , motd_()
241  , default_max_messages_(0)
242  , default_time_period_(0)
243  , concurrent_connections_(0)
244  , graceful_restart(false)
245  , lan_server_(std::time(nullptr))
246  , last_user_seen_time_(std::time(nullptr))
247  , restart_command()
248  , max_ip_log_size_(0)
249  , uh_name_()
250  , deny_unregistered_login_(false)
251  , save_replays_(false)
252  , replay_save_path_()
253  , allow_remote_shutdown_(false)
254  , tor_ip_list_()
255  , failed_login_limit_()
256  , failed_login_ban_()
257  , failed_login_buffer_size_()
258  , version_query_response_("[version]\n[/version]\n", simple_wml::INIT_COMPRESSED)
259  , login_response_("[mustlogin]\n[/mustlogin]\n", simple_wml::INIT_COMPRESSED)
260  , join_lobby_response_("[join_lobby]\n[/join_lobby]\n", simple_wml::INIT_COMPRESSED)
261  , games_and_users_list_("[gamelist]\n[/gamelist]\n", simple_wml::INIT_STATIC)
262  , metrics_()
263  , last_ping_(std::time(nullptr))
264  , dump_stats_timer_(io_service_)
265  , last_uh_clean_(last_ping_)
266  , cmd_handlers_()
267  , timer_(io_service_)
268  , lan_server_timer_(io_service_)
269 {
270  setup_handlers();
271  load_config();
272  ban_manager_.read();
273 
274  start_server();
275 
277 }
278 
279 #ifndef _WIN32
280 void server::handle_sighup(const boost::system::error_code& error, int)
281 {
282  assert(!error);
283 
284  WRN_SERVER << "SIGHUP caught, reloading config\n";
285 
286  cfg_ = read_config();
287  load_config();
288 
289  sighup_.async_wait(std::bind(&server::handle_sighup, this, _1, _2));
290 }
291 #endif
292 
293 void server::handle_graceful_timeout(const boost::system::error_code& error)
294 {
295  assert(!error);
296 
297  if(games().empty()) {
298  process_command("msg All games ended. Shutting down now. Reconnect to the new server instance.", "system");
299  throw server_shutdown("graceful shutdown timeout");
300  } else {
301  timer_.expires_from_now(boost::posix_time::seconds(1));
302  timer_.async_wait(std::bind(&server::handle_graceful_timeout, this, _1));
303  }
304 }
305 
307 {
308  lan_server_timer_.expires_from_now(std::chrono::seconds(lan_server_));
309  lan_server_timer_.async_wait([this](const boost::system::error_code& ec) { handle_lan_server_shutdown(ec); });
310 }
311 
313 {
314  lan_server_timer_.cancel();
315 }
316 
317 void server::handle_lan_server_shutdown(const boost::system::error_code& error)
318 {
319  if(error)
320  return;
321 
322  throw server_shutdown("lan server shutdown");
323 }
324 
326 {
327 #ifndef _WIN32
328  const int res = mkfifo(input_path_.c_str(), 0660);
329  if(res != 0 && errno != EEXIST) {
330  ERR_SERVER << "could not make fifo at '" << input_path_ << "' (" << strerror(errno) << ")\n";
331  return;
332  }
333  int fifo = open(input_path_.c_str(), O_RDWR | O_NONBLOCK);
334  input_.assign(fifo);
335  LOG_SERVER << "opened fifo at '" << input_path_ << "'. Server commands may be written to this file.\n";
336  read_from_fifo();
337 #endif
338 }
339 
340 #ifndef _WIN32
341 
342 void server::handle_read_from_fifo(const boost::system::error_code& error, std::size_t)
343 {
344  if(error) {
345  std::cout << error.message() << std::endl;
346  return;
347  }
348 
349  std::istream is(&admin_cmd_);
350  std::string cmd;
351  std::getline(is, cmd);
352 
353  LOG_SERVER << "Admin Command: type: " << cmd << "\n";
354 
355  const std::string res = process_command(cmd, "*socket*");
356 
357  // Only mark the response if we fake the issuer (i.e. command comes from IRC or so)
358  if(cmd.at(0) == '+') {
359  LOG_SERVER << "[admin_command_response]\n"
360  << res << "\n"
361  << "[/admin_command_response]\n";
362  } else {
363  LOG_SERVER << res << "\n";
364  }
365 
366  read_from_fifo();
367 }
368 
369 #endif
370 
372 {
373 #define SETUP_HANDLER(name, function) \
374  cmd_handlers_[name] = std::bind(function, this, \
375  std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4);
376 
391  SETUP_HANDLER("privatemsg", &server::pm_handler);
393  SETUP_HANDLER("lobbymsg", &server::msg_handler);
408  SETUP_HANDLER("deny_unregistered_login", &server::dul_handler);
409 
410 #undef SETUP_HANDLER
411 }
412 
414 {
415  config configuration;
416 
417  if(config_file_.empty()) {
418  return configuration;
419  }
420 
421  try {
423  read(configuration, *stream);
424  LOG_SERVER << "Server configuration from file: '" << config_file_ << "' read.\n";
425  } catch(const config::error& e) {
426  ERR_CONFIG << "ERROR: Could not read configuration file: '" << config_file_ << "': '" << e.message << "'.\n";
427  }
428 
429  return configuration;
430 }
431 
433 {
434 #ifndef _WIN32
435 #ifndef FIFODIR
436 #warning No FIFODIR set
437 #define FIFODIR "/var/run/wesnothd"
438 #endif
439  const std::string fifo_path
440  = (cfg_["fifo_path"].empty() ? std::string(FIFODIR) + "/socket" : std::string(cfg_["fifo_path"]));
441  // Reset (replace) the input stream only if the FIFO path changed.
442  if(fifo_path != input_path_) {
443  input_.close();
444  input_path_ = fifo_path;
445  setup_fifo();
446  }
447 #endif
448 
449  save_replays_ = cfg_["save_replays"].to_bool();
450  replay_save_path_ = cfg_["replay_save_path"].str();
451 
452  tor_ip_list_ = utils::split(cfg_["tor_ip_list_path"].empty()
453  ? ""
454  : filesystem::read_file(cfg_["tor_ip_list_path"]), '\n');
455 
456  admin_passwd_ = cfg_["passwd"].str();
457  motd_ = cfg_["motd"].str();
458  lan_server_ = cfg_["lan_server"].to_time_t(0);
459  uh_name_ = cfg_["user_handler"].str();
460 
461  deny_unregistered_login_ = cfg_["deny_unregistered_login"].to_bool();
462 
463  allow_remote_shutdown_ = cfg_["allow_remote_shutdown"].to_bool();
464 
465  disallowed_names_.clear();
466  if(cfg_["disallow_names"].empty()) {
467  disallowed_names_.push_back("*admin*");
468  disallowed_names_.push_back("*admln*");
469  disallowed_names_.push_back("*server*");
470  disallowed_names_.push_back("player");
471  disallowed_names_.push_back("network");
472  disallowed_names_.push_back("human");
473  disallowed_names_.push_back("computer");
474  disallowed_names_.push_back("ai");
475  disallowed_names_.push_back("ai?");
476  } else {
477  disallowed_names_ = utils::split(cfg_["disallow_names"]);
478  }
479 
480  default_max_messages_ = cfg_["max_messages"].to_int(4);
481  default_time_period_ = cfg_["messages_time_period"].to_int(10);
482  concurrent_connections_ = cfg_["connections_allowed"].to_int(5);
483  max_ip_log_size_ = cfg_["max_ip_log_size"].to_int(500);
484 
485  failed_login_limit_ = cfg_["failed_logins_limit"].to_int(10);
486  failed_login_ban_ = cfg_["failed_logins_ban"].to_int(3600);
487  failed_login_buffer_size_ = cfg_["failed_logins_buffer_size"].to_int(500);
488 
489  // Example config line:
490  // restart_command="./wesnothd-debug -d -c ~/.wesnoth1.5/server.cfg"
491  // remember to make new one as a daemon or it will block old one
492  restart_command = cfg_["restart_command"].str();
493 
494  recommended_version_ = cfg_["recommended_version"].str();
495  accepted_versions_.clear();
496  const std::string& versions = cfg_["versions_accepted"];
497  if(versions.empty() == false) {
498  accepted_versions_ = utils::split(versions);
499  } else {
501  accepted_versions_.push_back("test");
502  }
503 
504  redirected_versions_.clear();
505  for(const config& redirect : cfg_.child_range("redirect")) {
506  for(const std::string& version : utils::split(redirect["version"])) {
507  redirected_versions_[version] = redirect;
508  }
509  }
510 
511  proxy_versions_.clear();
512  for(const config& proxy : cfg_.child_range("proxy")) {
513  for(const std::string& version : utils::split(proxy["version"])) {
514  proxy_versions_[version] = proxy;
515  }
516  }
517 
519 
520  // If there is a [user_handler] tag in the config file
521  // allow nick registration, otherwise we set user_handler_
522  // to nullptr. Thus we must check user_handler_ for not being
523  // nullptr every time we want to use it.
524  user_handler_.reset();
525 
526  if(const config& user_handler = cfg_.child("user_handler")) {
527  if(uh_name_ == "sample") {
528  user_handler_.reset(new suh(user_handler));
529  }
530 #ifdef HAVE_MYSQLPP
531  else if(uh_name_ == "forum" || uh_name_.empty()) {
532  user_handler_.reset(new fuh(user_handler));
533  }
534 #endif
535  // Initiate the mailer class with the [mail] tag
536  // from the config file
537  if(user_handler_) {
538  user_handler_->init_mailer(cfg_.child("mail"));
539  }
540  }
541 }
542 
543 bool server::ip_exceeds_connection_limit(const std::string& ip) const
544 {
545  if(concurrent_connections_ == 0) {
546  return false;
547  }
548 
549  std::size_t connections = 0;
550  for(const auto& player : player_connections_) {
551  if(client_address(player.socket()) == ip) {
552  ++connections;
553  }
554  }
555 
556  return connections >= concurrent_connections_;
557 }
558 
559 std::string server::is_ip_banned(const std::string& ip)
560 {
561  if(!tor_ip_list_.empty()) {
562  if(find(tor_ip_list_.begin(), tor_ip_list_.end(), ip) != tor_ip_list_.end()) {
563  return "TOR IP";
564  }
565  }
566 
567  return ban_manager_.is_ip_banned(ip);
568 }
569 
571 {
572  dump_stats_timer_.expires_from_now(std::chrono::minutes(5));
573  dump_stats_timer_.async_wait([this](const boost::system::error_code& ec) { dump_stats(ec); });
574 }
575 
576 void server::dump_stats(const boost::system::error_code& ec)
577 {
578  if(ec) {
579  ERR_SERVER << "Error waiting for timer: " << ec.message() << "\n";
580  return;
581  }
582  LOG_SERVER << "Statistics:"
583  << "\tnumber_of_games = " << games().size() << "\tnumber_of_users = " << player_connections_.size()
584  << "\n";
586 }
587 
588 void server::clean_user_handler(const std::time_t& now)
589 {
590  if(!user_handler_) {
591  return;
592  }
593 
594  last_uh_clean_ = now;
595  user_handler_->clean_up();
596 }
597 
599 {
600  async_send_doc(socket, version_query_response_, std::bind(&server::handle_version, this, _1));
601 }
602 
604 {
605  async_receive_doc(socket, std::bind(&server::read_version, this, _1, _2));
606 }
607 
608 void server::read_version(socket_ptr socket, std::shared_ptr<simple_wml::document> doc)
609 {
610  if(const simple_wml::node* const version = doc->child("version")) {
611  const simple_wml::string_span& version_str_span = (*version)["version"];
612  const std::string version_str(version_str_span.begin(), version_str_span.end());
613 
614  // Check if it is an accepted version.
615  auto accepted_it = std::find_if(accepted_versions_.begin(), accepted_versions_.end(),
616  std::bind(&utils::wildcard_string_match, version_str, _1));
617 
618  if(accepted_it != accepted_versions_.end()) {
619  LOG_SERVER << client_address(socket) << "\tplayer joined using accepted version " << version_str
620  << ":\ttelling them to log in.\n";
621  async_send_doc(socket, login_response_, std::bind(&server::login, this, _1, version_str));
622  return;
623  }
624 
625  simple_wml::document response;
626 
627  // Check if it is a redirected version
628  for(const auto& redirect_version : redirected_versions_) {
629  if(utils::wildcard_string_match(version_str, redirect_version.first)) {
630  LOG_SERVER << client_address(socket) << "\tplayer joined using version " << version_str
631  << ":\tredirecting them to " << redirect_version.second["host"] << ":"
632  << redirect_version.second["port"] << "\n";
633 
634  simple_wml::node& redirect = response.root().add_child("redirect");
635  for(const auto& attr : redirect_version.second.attribute_range()) {
636  redirect.set_attr_dup(attr.first.c_str(), attr.second.str().c_str());
637  }
638 
639  send_to_player(socket, response);
640  return;
641  }
642  }
643 
644  LOG_SERVER << client_address(socket) << "\tplayer joined using unknown version " << version_str
645  << ":\trejecting them\n";
646 
647  // For compatibility with older clients
648  response.set_attr("version", accepted_versions_.begin()->c_str());
649 
650  simple_wml::node& reject = response.root().add_child("reject");
651  reject.set_attr_dup("accepted_versions", utils::join(accepted_versions_).c_str());
652  send_to_player(socket, response);
653  } else {
654  LOG_SERVER << client_address(socket) << "\tclient didn't send its version: rejecting\n";
655  }
656 }
657 
658 void server::login(socket_ptr socket, std::string version)
659 {
660  async_receive_doc(socket, std::bind(&server::handle_login, this, _1, _2, version));
661 }
662 
663 void server::handle_login(socket_ptr socket, std::shared_ptr<simple_wml::document> doc, std::string version)
664 {
665  if(const simple_wml::node* const login = doc->child("login")) {
666  if(!is_login_allowed(socket, login, version)) {
667  server::login(socket, version); // keep reading logins from client until we get a successful one
668  }
669  } else {
670  async_send_error(socket, "You must login first.", MP_MUST_LOGIN);
671  }
672 }
673 
674 bool server::is_login_allowed(socket_ptr socket, const simple_wml::node* const login, const std::string& version)
675 {
676  // Check if the username is valid (all alpha-numeric plus underscore and hyphen)
677  std::string username = (*login)["username"].to_string();
678 
679  if(!utils::isvalid_username(username)) {
680  async_send_error(socket,
681  "The nickname '" + username + "' contains invalid "
682  "characters. Only alpha-numeric characters, underscores and hyphens are allowed.",
684  );
685 
686  return false;
687  }
688 
689  if(username.size() > 20) {
690  async_send_error(socket, "The nickname '" + username + "' is too long. Nicks must be 20 characters or less.",
692  return false;
693  }
694 
695  // Check if the username is allowed.
696  for(const std::string d : disallowed_names_) {
698  async_send_error(socket, "The nickname '" + username + "' is reserved and cannot be used by players",
700  return false;
701  }
702  }
703 
704  // Check the username isn't already taken
705  auto p = player_connections_.get<name_t>().find(username);
706  bool name_taken = p != player_connections_.get<name_t>().end();
707 
708  // Check for password
709 
710  bool registered;
711  if(!authenticate(socket, username, (*login)["password"].to_string(), version, name_taken, registered))
712  return true; // it's a failed login but we don't want to call server::login again
713  // because send_password_request() will handle the next network write and read instead
714 
715  // If we disallow unregistered users and this user is not registered send an error
716  if(user_handler_ && !registered && deny_unregistered_login_) {
717  async_send_error(socket,
718  "The nickname '" + username + "' is not registered. This server disallows unregistered nicknames.",
720  );
721 
722  return false;
723  }
724 
725  const bool is_moderator = user_handler_ && user_handler_->user_is_moderator(username);
726  const user_handler::BAN_TYPE auth_ban = user_handler_
727  ? user_handler_->user_is_banned(username, client_address(socket))
729 
730  if(auth_ban) {
731  std::string ban_type_desc;
732  std::string ban_reason;
733  const char* msg_numeric;
734 
735  switch(auth_ban) {
737  ban_type_desc = "account";
738  msg_numeric = MP_NAME_AUTH_BAN_USER_ERROR;
739  ban_reason = "a ban has been issued on your user account.";
740  break;
742  ban_type_desc = "IP address";
743  msg_numeric = MP_NAME_AUTH_BAN_IP_ERROR;
744  ban_reason = "a ban has been issued on your IP address.";
745  break;
747  ban_type_desc = "email address";
748  msg_numeric = MP_NAME_AUTH_BAN_EMAIL_ERROR;
749  ban_reason = "a ban has been issued on your email address.";
750  break;
751  default:
752  ban_type_desc = "<unknown ban type>";
753  msg_numeric = "";
754  ban_reason = ban_type_desc;
755  }
756 
757  if(!is_moderator) {
758  LOG_SERVER << client_address(socket) << "\t" << username << "\tis banned by user_handler (" << ban_type_desc
759  << ")\n";
760  async_send_error(socket, "You are banned from this server: " + ban_reason, msg_numeric);
761  return false;
762  } else {
763  LOG_SERVER << client_address(socket) << "\t" << username << "\tis banned by user_handler (" << ban_type_desc
764  << "), " << "ignoring due to moderator flag\n";
765  }
766  }
767 
768  if(name_taken) {
769  if(registered) {
770  // If there is already a client using this username kick it
771  process_command("kick " + p->info().name() + " autokick by registered user", username);
772  } else {
773  async_send_error(socket, "The nickname '" + username + "' is already taken.", MP_NAME_TAKEN_ERROR);
774  return false;
775  }
776  }
777 
778  async_send_doc(socket, join_lobby_response_, [this, username, registered, version](socket_ptr socket) {
779  simple_wml::node& player_cfg = games_and_users_list_.root().add_child("user");
781  username,
782  player_cfg,
783  registered,
784  version,
787  user_handler_ && user_handler_->user_is_moderator(username)
788  )
789  );
790  });
791 
792  LOG_SERVER << client_address(socket) << "\t" << username << "\thas logged on"
793  << (registered ? " to a registered account" : "") << "\n";
794 
795  if(is_moderator) {
796  LOG_SERVER << "Admin automatically recognized: IP: " << client_address(socket) << "\tnick: " << username
797  << std::endl;
798 
799  // This string is parsed by the client!
800  send_server_message(socket,
801  "You are now recognized as an administrator. "
802  "If you no longer want to be automatically authenticated use '/query signout'.");
803  }
804 
805  if(auth_ban) {
806  send_server_message(socket, "You are currently banned by the forum administration.");
807  }
808 
809  // Log the IP
810  connection_log ip_name = connection_log(username, client_address(socket), 0);
811 
812  if(std::find(ip_log_.begin(), ip_log_.end(), ip_name) == ip_log_.end()) {
813  ip_log_.push_back(ip_name);
814 
815  // Remove the oldest entry if the size of the IP log exceeds the maximum size
816  if(ip_log_.size() > max_ip_log_size_) {
817  ip_log_.pop_front();
818  }
819  }
820 
821  return true;
822 }
823 
825  socket_ptr socket, const std::string& username, const std::string& password, const std::string& version, bool name_taken, bool& registered)
826 {
827  // Current login procedure for registered nicks is:
828  // - Client asks to log in with a particular nick
829  // - Server sends client random nonce plus some info
830  // generated from the original hash that is required to
831  // regenerate the hash
832  // - Client generates hash for the user provided password
833  // and mixes it with the received random nonce
834  // - Server received password hash hashed with the nonce,
835  // applies the nonce to the valid hash and compares the results
836 
837  registered = false;
838 
839  if(user_handler_) {
840  const bool exists = user_handler_->user_exists(username);
841 
842  // This name is registered but the account is not active
843  if(exists && !user_handler_->user_is_active(username)) {
844  async_send_warning(socket,
845  "The nickname '" + username + "' is inactive. You cannot claim ownership of this "
846  "nickname until you activate your account via email or ask an administrator to do it for you.",
848  );
849  // registered = false;
850  } else if(exists) {
851  // This name is registered and no password provided
852  if(password.empty()) {
853  if(!name_taken) {
854  send_password_request(socket, "The nickname '" + username + "' is registered on this server.",
855  username, version, MP_PASSWORD_REQUEST);
856  } else {
857  send_password_request(socket,
858  "The nickname '" + username + "' is registered on this server."
859  "\n\nWARNING: There is already a client using this username, "
860  "logging in will cause that client to be kicked!",
861  username, version, MP_PASSWORD_REQUEST_FOR_LOGGED_IN_NAME, true
862  );
863  }
864 
865  return false;
866  }
867 
868  // A password (or hashed password) was provided, however
869  // there is no seed
870  if(seeds_[socket.get()].empty()) {
871  send_password_request(socket, "Please try again.", username, version, MP_NO_SEED_ERROR);
872  return false;
873  }
874 
875  // This name is registered and an incorrect password provided
876  else if(!(user_handler_->login(username, password, seeds_[socket.get()]))) {
877  const std::time_t now = std::time(nullptr);
878 
879  // Reset the random seed
880  seeds_.erase(socket.get());
881 
882  login_log login_ip = login_log(client_address(socket), 0, now);
883  auto i = std::find(failed_logins_.begin(), failed_logins_.end(), login_ip);
884 
885  if(i == failed_logins_.end()) {
886  failed_logins_.push_back(login_ip);
887  i = --failed_logins_.end();
888 
889  // Remove oldest entry if maximum size is exceeded
891  failed_logins_.pop_front();
892  }
893  }
894 
895  if(i->first_attempt + failed_login_ban_ < now) {
896  // Clear and move to the beginning
897  failed_logins_.erase(i);
898  failed_logins_.push_back(login_ip);
899  i = --failed_logins_.end();
900  }
901 
902  i->attempts++;
903 
904  if(i->attempts > failed_login_limit_) {
905  LOG_SERVER << ban_manager_.ban(login_ip.ip, now + failed_login_ban_,
906  "Maximum login attempts exceeded", "automatic", "", username);
907 
908  async_send_error(socket,
909  "You have made too many failed login attempts.", MP_TOO_MANY_ATTEMPTS_ERROR);
910  } else {
911  send_password_request(socket,
912  "The password you provided for the nickname '" + username + "' was incorrect.", username,version,
914  }
915 
916  // Log the failure
917  LOG_SERVER << client_address(socket) << "\t"
918  << "Login attempt with incorrect password for nickname '" << username << "'.\n";
919  return false;
920  }
921 
922  // This name exists and the password was neither empty nor incorrect
923  registered = true;
924 
925  // Reset the random seed
926  seeds_.erase(socket.get());
927  user_handler_->user_logged_in(username);
928  }
929  }
930 
931  return true;
932 }
933 
935  const std::string& msg,
936  const std::string& user,
937  const std::string& version,
938  const char* error_code,
939  bool force_confirmation)
940 {
941  std::string salt = user_handler_->extract_salt(user);
942 
943  // If using crypt_blowfish, use 32 random Base64 characters, cryptographic-strength, 192 bits entropy
944  // else (phppass, MD5, $H$), use 8 random integer digits, not secure, do not use, this is crap, 29.8 bits entropy
945  std::string nonce{(salt[1] == '2')
946  ? user_handler_->create_secure_nonce()
947  : user_handler_->create_unsecure_nonce()};
948 
949  std::string password_challenge = salt + nonce;
950  if(user_handler_->use_phpbb_encryption() && salt.empty()) {
951  async_send_error(socket,
952  "Even though your nickname is registered on this server you "
953  "cannot log in due to an error in the hashing algorithm. "
954  "Logging into your forum account on https://forums.wesnoth.org "
955  "may fix this problem.");
956  login(socket, version);
957  return;
958  }
959 
960  seeds_[socket.get()] = nonce;
961 
963  simple_wml::node& e = doc.root().add_child("error");
964  e.set_attr_dup("message", msg.c_str());
965  e.set_attr("password_request", "yes");
966  e.set_attr("phpbb_encryption", user_handler_->use_phpbb_encryption() ? "yes" : "no");
967  e.set_attr_dup("salt", password_challenge.c_str());
968  e.set_attr("force_confirmation", force_confirmation ? "yes" : "no");
969 
970  if(*error_code != '\0') {
971  e.set_attr("error_code", error_code);
972  }
973 
974  async_send_doc(socket, doc, std::bind(&server::login, this, _1, version));
975 }
976 
978 {
979  if(lan_server_)
981 
982  bool inserted;
983  std::tie(std::ignore, inserted) = player_connections_.insert(player_connections::value_type(socket, player));
984  assert(inserted);
985 
987 
988  if(!motd_.empty()) {
989  send_server_message(socket, motd_);
990  }
991  if(version_info(player.version()) < secure_version ){
992  send_server_message(socket, "You are using version " + player.version() + " which has known security issues that can be used to compromise your computer. We strongly recommend updating to a Wesnoth version " + secure_version.str() + " or newer!");
993  }
995  send_server_message(socket, "A newer Wesnoth version, " + recommended_version_ + ", is out!");
996  }
997 
998  read_from_player(socket);
999 
1000  // Send other players in the lobby the update that the player has joined
1001  simple_wml::document diff;
1002  make_add_diff(games_and_users_list_.root(), nullptr, "user", diff);
1003  send_to_lobby(diff, socket);
1004 }
1005 
1007 {
1008  async_receive_doc(socket,
1009  std::bind(&server::handle_read_from_player, this, _1, _2),
1010  std::bind(&server::remove_player, this, _1)
1011  );
1012 }
1013 
1014 void server::handle_read_from_player(socket_ptr socket, std::shared_ptr<simple_wml::document> doc)
1015 {
1016  read_from_player(socket);
1017 
1018  // DBG_SERVER << client_address(socket) << "\tWML received:\n" << doc->output() << std::endl;
1019  if(doc->child("refresh_lobby")) {
1021  return;
1022  }
1023 
1024  if(simple_wml::node* whisper = doc->child("whisper")) {
1025  handle_whisper(socket, *whisper);
1026  return;
1027  }
1028 
1029  if(simple_wml::node* query = doc->child("query")) {
1030  handle_query(socket, *query);
1031  return;
1032  }
1033 
1034  if(simple_wml::node* nickserv = doc->child("nickserv")) {
1035  handle_nickserv(socket, *nickserv);
1036  return;
1037  }
1038 
1039  if(!player_is_in_game(socket)) {
1040  handle_player_in_lobby(socket, doc);
1041  } else {
1042  handle_player_in_game(socket, doc);
1043  }
1044 }
1045 
1046 void server::handle_player_in_lobby(socket_ptr socket, std::shared_ptr<simple_wml::document> doc)
1047 {
1048  if(simple_wml::node* message = doc->child("message")) {
1049  handle_message(socket, *message);
1050  return;
1051  }
1052 
1053  if(simple_wml::node* create_game = doc->child("create_game")) {
1054  handle_create_game(socket, *create_game);
1055  return;
1056  }
1057 
1058  if(simple_wml::node* join = doc->child("join")) {
1059  handle_join_game(socket, *join);
1060  return;
1061  }
1062 }
1063 
1065 {
1066  if((whisper["receiver"].empty()) || (whisper["message"].empty())) {
1067  static simple_wml::document data(
1068  "[message]\n"
1069  "message=\"Invalid number of arguments\"\n"
1070  "sender=\"server\"\n"
1071  "[/message]\n",
1073  );
1074 
1075  send_to_player(socket, data);
1076  return;
1077  }
1078 
1079  whisper.set_attr_dup("sender", player_connections_.find(socket)->name().c_str());
1080 
1081  auto receiver_iter = player_connections_.get<name_t>().find(whisper["receiver"].to_string());
1082  if(receiver_iter == player_connections_.get<name_t>().end()) {
1083  send_server_message(socket, "Can't find '" + whisper["receiver"].to_string() + "'.");
1084  return;
1085  }
1086 
1087  auto g = player_connections_.find(socket)->get_game();
1088  if(g && g->started() && g->is_player(receiver_iter->socket()) && g->is_member(socket)) {
1089  send_server_message(socket, "You cannot send private messages to players in a running game you observe.");
1090  return;
1091  }
1092 
1093  simple_wml::document cwhisper;
1094 
1095  simple_wml::node& trunc_whisper = cwhisper.root().add_child("whisper");
1096  whisper.copy_into(trunc_whisper);
1097 
1098  const simple_wml::string_span& msg = trunc_whisper["message"];
1099  chat_message::truncate_message(msg, trunc_whisper);
1100 
1101  send_to_player(receiver_iter->socket(), cwhisper);
1102 }
1103 
1105 {
1106  auto iter = player_connections_.find(socket);
1107  if(iter == player_connections_.end()) {
1108  return;
1109  }
1110 
1111  wesnothd::player& player = iter->info();
1112 
1113  const std::string command(query["type"].to_string());
1114  std::ostringstream response;
1115 
1116  const std::string& query_help_msg =
1117  "Available commands are: adminmsg <msg>, help, games, metrics,"
1118  " motd, netstats [all], requests, sample, stats, status, version, wml.";
1119 
1120  // Commands a player may issue.
1121  if(command == "status") {
1122  response << process_command(command + " " + player.name(), player.name());
1123  } else if(
1124  command.compare(0, 8, "adminmsg") == 0 ||
1125  command.compare(0, 6, "report") == 0 ||
1126  command == "games" ||
1127  command == "metrics" ||
1128  command == "motd" ||
1129  command == "netstats" ||
1130  command == "netstats all" ||
1131  command.compare(0, 7, "version") == 0 ||
1132  command == "requests" ||
1133  command == "sample" ||
1134  command == "stats" ||
1135  command == "status " + player.name() ||
1136  command == "wml"
1137  ) {
1138  response << process_command(command, player.name());
1139  } else if(player.is_moderator()) {
1140  if(command == "signout") {
1141  LOG_SERVER << "Admin signed out: IP: " << client_address(socket) << "\tnick: " << player.name()
1142  << std::endl;
1143  player.set_moderator(false);
1144  // This string is parsed by the client!
1145  response << "You are no longer recognized as an administrator.";
1146  if(user_handler_) {
1147  user_handler_->set_is_moderator(player.name(), false);
1148  }
1149  } else {
1150  LOG_SERVER << "Admin Command: type: " << command << "\tIP: " << client_address(socket)
1151  << "\tnick: " << player.name() << std::endl;
1152  response << process_command(command, player.name());
1153  LOG_SERVER << response.str() << std::endl;
1154  }
1155  } else if(command == "help" || command.empty()) {
1156  response << query_help_msg;
1157  } else if(command == "admin" || command.compare(0, 6, "admin ") == 0) {
1158  if(admin_passwd_.empty()) {
1159  send_server_message(socket, "No password set.");
1160  return;
1161  }
1162 
1163  std::string passwd;
1164  if(command.size() >= 6) {
1165  passwd = command.substr(6);
1166  }
1167 
1168  if(passwd == admin_passwd_) {
1169  LOG_SERVER << "New Admin recognized: IP: " << client_address(socket) << "\tnick: " << player.name()
1170  << std::endl;
1171  player.set_moderator(true);
1172  // This string is parsed by the client!
1173  response << "You are now recognized as an administrator.";
1174 
1175  if(user_handler_) {
1176  user_handler_->set_is_moderator(player.name(), true);
1177  }
1178  } else {
1179  WRN_SERVER << "FAILED Admin attempt with password: '" << passwd << "'\tIP: " << client_address(socket)
1180  << "\tnick: " << player.name() << std::endl;
1181  response << "Error: wrong password";
1182  }
1183  } else {
1184  response << "Error: unrecognized query: '" << command << "'\n" << query_help_msg;
1185  }
1186 
1187  send_server_message(socket, response.str());
1188 }
1189 
1191 {
1192  // Check if this server allows nick registration at all
1193  if(!user_handler_) {
1194  send_server_message(socket, "This server does not allow username registration.");
1195  return;
1196  }
1197 
1198  if(nickserv.child("register")) {
1199  try {
1200  (user_handler_->add_user(player_connections_.find(socket)->name(),
1201  (*nickserv.child("register"))["mail"].to_string(),
1202  (*nickserv.child("register"))["password"].to_string()));
1203 
1204  std::stringstream msg;
1205  msg << "Your username has been registered." <<
1206  // Warn that providing an email address might be a good idea
1207  ((*nickserv.child("register"))["mail"].empty()
1208  ? " It is recommended that you provide an email address for password recovery."
1209  : "");
1210 
1211  send_server_message(socket, msg.str());
1212 
1213  // Mark the player as registered and send the other clients
1214  // an update to display this change
1215  player_connections_.find(socket)->info().mark_registered();
1216 
1217  simple_wml::document diff;
1218  make_change_diff(games_and_users_list_.root(), nullptr, "user",
1219  player_connections_.find(socket)->info().config_address(), diff);
1220  send_to_lobby(diff);
1221 
1222  } catch(const user_handler::error& e) {
1223  send_server_message(socket,
1224  "There was an error registering your username. The error message was: " + e.message);
1225  }
1226 
1227  return;
1228  }
1229 
1230  // A user requested to update his password or mail
1231  if(nickserv.child("set")) {
1232  if(!(user_handler_->user_exists(player_connections_.find(socket)->name()))) {
1233  send_server_message(socket, "You are not registered. Please register first.");
1234  return;
1235  }
1236 
1237  const simple_wml::node& set = *(nickserv.child("set"));
1238 
1239  try {
1240  user_handler_->set_user_detail(
1241  player_connections_.find(socket)->name(), set["detail"].to_string(), set["value"].to_string());
1242 
1243  send_server_message(socket, "Your details have been updated.");
1244 
1245  } catch(const user_handler::error& e) {
1246  send_server_message(socket,
1247  "There was an error updating your details. The error message was: " + e.message);
1248  }
1249 
1250  return;
1251  }
1252 
1253  // A user requested information about another user
1254  if(nickserv.child("details")) {
1255  send_server_message(socket, "Valid details for this server are: " + user_handler_->get_valid_details());
1256  return;
1257  }
1258 
1259  // A user requested a list of which details can be set
1260  if(nickserv.child("info")) {
1261  try {
1262  std::string res = user_handler_->user_info((*nickserv.child("info"))["name"].to_string());
1263  send_server_message(socket, res);
1264  } catch(const user_handler::error& e) {
1265  send_server_message(socket,
1266  "There was an error looking up the details of the user '"
1267  + (*nickserv.child("info"))["name"].to_string() + "'. "
1268  + " The error message was: " + e.message
1269  );
1270  }
1271 
1272  return;
1273  }
1274 
1275  // A user requested to delete his nick
1276  if(nickserv.child("drop")) {
1277  if(!(user_handler_->user_exists(player_connections_.find(socket)->name()))) {
1278  send_server_message(socket, "You are not registered.");
1279  return;
1280  }
1281 
1282  // With the current policy of dissallowing to log in with a
1283  // registered username without the password we should never get
1284  // to call this
1285  if(!(player_connections_.find(socket)->info().registered())) {
1286  send_server_message(socket, "You are not logged in.");
1287  return;
1288  }
1289 
1290  try {
1291  user_handler_->remove_user(player_connections_.find(socket)->name());
1292  send_server_message(socket, "Your username has been dropped.");
1293 
1294  // Mark the player as not registered and send the other clients
1295  // an update to display this change.
1296  player_connections_.find(socket)->info().mark_registered(false);
1297 
1298  simple_wml::document diff;
1299  make_change_diff(games_and_users_list_.root(), nullptr, "user",
1300  player_connections_.find(socket)->info().config_address(), diff);
1301 
1302  send_to_lobby(diff);
1303  } catch(const user_handler::error& e) {
1304  send_server_message(socket,
1305  "There was an error dropping your username. The error message was: " + e.message);
1306  }
1307  return;
1308  }
1309 }
1310 
1312 {
1313  auto user = player_connections_.find(socket);
1314  if(user->info().is_message_flooding()) {
1315  send_server_message(socket,
1316  "Warning: you are sending too many messages too fast. Your message has not been relayed.");
1317  return;
1318  }
1319 
1320  simple_wml::document relay_message;
1321  message.set_attr_dup("sender", user->name().c_str());
1322 
1323  simple_wml::node& trunc_message = relay_message.root().add_child("message");
1324  message.copy_into(trunc_message);
1325 
1326  const simple_wml::string_span& msg = trunc_message["message"];
1327  chat_message::truncate_message(msg, trunc_message);
1328 
1329  if(msg.size() >= 3 && simple_wml::string_span(msg.begin(), 4) == "/me ") {
1330  LOG_SERVER << client_address(socket) << "\t<" << user->name()
1331  << simple_wml::string_span(msg.begin() + 3, msg.size() - 3) << ">\n";
1332  } else {
1333  LOG_SERVER << client_address(socket) << "\t<" << user->name() << "> " << msg << "\n";
1334  }
1335 
1336  send_to_lobby(relay_message, socket);
1337 }
1338 
1340 {
1341  if(graceful_restart) {
1342  static simple_wml::document leave_game_doc("[leave_game]\n[/leave_game]\n", simple_wml::INIT_COMPRESSED);
1343  send_to_player(socket, leave_game_doc);
1344 
1345  send_server_message(socket,
1346  "This server is shutting down. You aren't allowed to make new games. Please "
1347  "reconnect to the new server.");
1348 
1350  return;
1351  }
1352 
1353  player_connections_.modify(
1354  player_connections_.find(socket), std::bind(&server::create_game, this, _1, std::ref(create_game)));
1355 
1356  return;
1357 }
1358 
1360 {
1361  const std::string game_name = create_game["name"].to_string();
1362  const std::string game_password = create_game["password"].to_string();
1363 
1364  DBG_SERVER << client_address(host_record.socket()) << "\t" << host_record.info().name()
1365  << "\tcreates a new game: \"" << game_name << "\".\n";
1366 
1367  // Create the new game, remove the player from the lobby
1368  // and set the player as the host/owner.
1369  host_record.get_game().reset(
1370  new wesnothd::game(player_connections_, host_record.socket(), game_name, save_replays_, replay_save_path_),
1371  std::bind(&server::cleanup_game, this, _1)
1372  );
1373 
1374  wesnothd::game& g = *host_record.get_game();
1375 
1376  if(game_password.empty() == false) {
1377  g.set_password(game_password);
1378  }
1379 
1380  create_game.copy_into(g.level().root());
1381 }
1382 
1384 {
1386 
1387  simple_wml::node* const gamelist = games_and_users_list_.child("gamelist");
1388  assert(gamelist != nullptr);
1389 
1390  // Send a diff of the gamelist with the game deleted to players in the lobby
1391  simple_wml::document diff;
1392  if(make_delete_diff(*gamelist, "gamelist", "game", game_ptr->description(), diff)) {
1393  send_to_lobby(diff);
1394  }
1395 
1396  // Delete the game from the games_and_users_list_.
1397  const simple_wml::node::child_list& games = gamelist->children("game");
1398  const auto g = std::find(games.begin(), games.end(), game_ptr->description());
1399 
1400  if(g != games.end()) {
1401  const std::size_t index = std::distance(games.begin(), g);
1402  gamelist->remove_child("game", index);
1403  } else {
1404  // Can happen when the game ends before the scenario was transferred.
1405  LOG_SERVER << "Could not find game (" << game_ptr->id() << ") to delete in games_and_users_list_.\n";
1406  }
1407 
1408  delete game_ptr;
1409 }
1410 
1412 {
1413  const bool observer = join.attr("observe").to_bool();
1414  const std::string& password = join["password"].to_string();
1415  int game_id = join["id"].to_int();
1416 
1417  auto g_iter = player_connections_.get<game_t>().find(game_id);
1418 
1419  std::shared_ptr<game> g;
1420  if(g_iter != player_connections_.get<game_t>().end()) {
1421  g = g_iter->get_game();
1422  }
1423 
1424  static simple_wml::document leave_game_doc("[leave_game]\n[/leave_game]\n", simple_wml::INIT_COMPRESSED);
1425  if(!g) {
1426  WRN_SERVER << client_address(socket) << "\t" << player_connections_.find(socket)->info().name()
1427  << "\tattempted to join unknown game:\t" << game_id << ".\n";
1428  async_send_doc(socket, leave_game_doc);
1429  send_server_message(socket, "Attempt to join unknown game.");
1431  return;
1432  } else if(!g->level_init()) {
1433  WRN_SERVER << client_address(socket) << "\t" << player_connections_.find(socket)->info().name()
1434  << "\tattempted to join uninitialized game:\t\"" << g->name() << "\" (" << game_id << ").\n";
1435  async_send_doc(socket, leave_game_doc);
1436  send_server_message(socket, "Attempt to join an uninitialized game.");
1438  return;
1439  } else if(player_connections_.find(socket)->info().is_moderator()) {
1440  // Admins are always allowed to join.
1441  } else if(g->registered_users_only() && !player_connections_.find(socket)->info().registered()) {
1442  async_send_doc(socket, leave_game_doc);
1443  send_server_message(socket, "Only registered users are allowed to join this game.");
1445  return;
1446  } else if(g->player_is_banned(socket)) {
1447  DBG_SERVER << client_address(socket)
1448  << "\tReject banned player: " << player_connections_.find(socket)->info().name()
1449  << "\tfrom game:\t\"" << g->name() << "\" (" << game_id << ").\n";
1450  async_send_doc(socket, leave_game_doc);
1451  send_server_message(socket, "You are banned from this game.");
1453  return;
1454  } else if(!observer && !g->password_matches(password)) {
1455  WRN_SERVER << client_address(socket) << "\t" << player_connections_.find(socket)->info().name()
1456  << "\tattempted to join game:\t\"" << g->name() << "\" (" << game_id << ") with bad password\n";
1457  async_send_doc(socket, leave_game_doc);
1458  send_server_message(socket, "Incorrect password.");
1460  return;
1461  }
1462 
1463  bool joined = g->add_player(socket, observer);
1464  if(!joined) {
1465  WRN_SERVER << client_address(socket) << "\t" << player_connections_.find(socket)->info().name()
1466  << "\tattempted to observe game:\t\"" << g->name() << "\" (" << game_id
1467  << ") which doesn't allow observers.\n";
1468  async_send_doc(socket, leave_game_doc);
1469 
1470  send_server_message(socket,
1471  "Attempt to observe a game that doesn't allow observers. (You probably joined the "
1472  "game shortly after it filled up.)");
1473 
1475  return;
1476  }
1477 
1478  player_connections_.modify(player_connections_.find(socket),
1479  std::bind(&player_record::set_game, _1, player_connections_.get<game_t>().find(game_id)->get_game()));
1480 
1481  g->describe_slots();
1482 
1483  // send notification of changes to the game and user
1484  simple_wml::document diff;
1485  bool diff1 = make_change_diff(*games_and_users_list_.child("gamelist"), "gamelist", "game", g->description(), diff);
1486  bool diff2 = make_change_diff(games_and_users_list_.root(), nullptr, "user",
1487  player_connections_.find(socket)->info().config_address(), diff);
1488 
1489  if(diff1 || diff2) {
1490  send_to_lobby(diff);
1491  }
1492 }
1493 
1494 void server::handle_player_in_game(socket_ptr socket, std::shared_ptr<simple_wml::document> doc)
1495 {
1496  DBG_SERVER << "in process_data_game...\n";
1497 
1498  auto p = player_connections_.find(socket);
1499  wesnothd::player& player = p->info();
1500 
1501  game& g = *(p->get_game());
1502  std::weak_ptr<game> g_ptr{p->get_game()};
1503 
1504  simple_wml::document& data = *doc;
1505 
1506  // If this is data describing the level for a game.
1507  if(doc->child("snapshot") || doc->child("scenario")) {
1508  if(!g.is_owner(socket)) {
1509  return;
1510  }
1511 
1512  // If this game is having its level data initialized
1513  // for the first time, and is ready for players to join.
1514  // We should currently have a summary of the game in g.level().
1515  // We want to move this summary to the games_and_users_list_, and
1516  // place a pointer to that summary in the game's description.
1517  // g.level() should then receive the full data for the game.
1518  if(!g.level_init()) {
1519  LOG_SERVER << client_address(socket) << "\t" << player.name() << "\tcreated game:\t\"" << g.name() << "\" ("
1520  << g.id() << ").\n";
1521  // Update our config object which describes the open games,
1522  // and save a pointer to the description in the new game.
1523  simple_wml::node* const gamelist = games_and_users_list_.child("gamelist");
1524  assert(gamelist != nullptr);
1525 
1526  simple_wml::node& desc = gamelist->add_child("game");
1527  g.level().root().copy_into(desc);
1528 
1529  if(const simple_wml::node* m = doc->child("multiplayer")) {
1530  m->copy_into(desc);
1531  } else {
1532  WRN_SERVER << client_address(socket) << "\t" << player.name() << "\tsent scenario data in game:\t\""
1533  << g.name() << "\" (" << g.id() << ") without a 'multiplayer' child.\n";
1534  // Set the description so it can be removed in delete_game().
1535  g.set_description(&desc);
1536  delete_game(g.id());
1537 
1538  send_server_message(socket,
1539  "The scenario data is missing the [multiplayer] tag which contains the "
1540  "game settings. Game aborted.");
1541  return;
1542  }
1543 
1544  g.set_description(&desc);
1545  desc.set_attr_dup("id", lexical_cast<std::string>(g.id()).c_str());
1546  } else {
1547  WRN_SERVER << client_address(socket) << "\t" << player.name() << "\tsent scenario data in game:\t\""
1548  << g.name() << "\" (" << g.id() << ") although it's already initialized.\n";
1549  return;
1550  }
1551 
1552  assert(games_and_users_list_.child("gamelist")->children("game").empty() == false);
1553 
1554  simple_wml::node& desc = *g.description();
1555 
1556  // Update the game's description.
1557  // If there is no shroud, then tell players in the lobby
1558  // what the map looks like
1560  // fixme: the hanlder of [store_next_scenario] below searches for 'mp_shroud' in [scenario]
1561  // at least of the these cosed is likely wrong.
1562  if(!data["mp_shroud"].to_bool()) {
1563  desc.set_attr_dup("map_data", s["map_data"]);
1564  }
1565 
1566  if(const simple_wml::node* e = data.child("era")) {
1567  if(!e->attr("require_era").to_bool(true)) {
1568  desc.set_attr("require_era", "no");
1569  }
1570  }
1571 
1572  if(s["require_scenario"].to_bool(false)) {
1573  desc.set_attr("require_scenario", "yes");
1574  }
1575 
1576  const simple_wml::node::child_list& mlist = data.children("modification");
1577  for(const simple_wml::node* m : mlist) {
1578  desc.add_child_at("modification", 0);
1579  desc.child("modification")->set_attr_dup("id", m->attr("id"));
1580  desc.child("modification")->set_attr_dup("name", m->attr("name"));
1581  desc.child("modification")->set_attr_dup("addon_id", m->attr("addon_id"));
1582 
1583  if(m->attr("require_modification").to_bool(false)) {
1584  desc.child("modification")->set_attr("require_modification", "yes");
1585  }
1586  }
1587 
1588  // Record the full scenario in g.level()
1589  g.level().swap(data);
1590 
1591  // The host already put himself in the scenario so we just need
1592  // to update_side_data().
1593  // g.take_side(sock);
1594  g.update_side_data();
1595  g.describe_slots();
1596 
1597  // Send the update of the game description to the lobby.
1598  simple_wml::document diff;
1599  make_add_diff(*games_and_users_list_.child("gamelist"), "gamelist", "game", diff);
1600  make_change_diff(games_and_users_list_.root(), nullptr, "user", player_connections_.find(socket)->info().config_address(), diff);
1601 
1602  send_to_lobby(diff);
1603 
1604  /** @todo FIXME: Why not save the level data in the history_? */
1605  return;
1606  // Everything below should only be processed if the game is already initialized.
1607  } else if(!g.level_init()) {
1608  WRN_SERVER << client_address(socket) << "\tReceived unknown data from: " << player.name()
1609  << " (socket:" << socket << ") while the scenario wasn't yet initialized.\n"
1610  << data.output();
1611  return;
1612  // If the host is sending the next scenario data.
1613  } else if(const simple_wml::node* scenario = data.child("store_next_scenario")) {
1614  if(!g.is_owner(socket)) {
1615  return;
1616  }
1617 
1618  if(!g.level_init()) {
1619  WRN_SERVER << client_address(socket) << "\tWarning: " << player.name()
1620  << "\tsent [store_next_scenario] in game:\t\"" << g.name() << "\" (" << g.id()
1621  << ") while the scenario is not yet initialized.";
1622  return;
1623  }
1624 
1625  g.new_scenario(socket);
1626  g.save_replay();
1628 
1629  // Record the full scenario in g.level()
1630  g.level().clear();
1631  scenario->copy_into(g.level().root());
1632 
1633  if(g.description() == nullptr) {
1634  ERR_SERVER << client_address(socket) << "\tERROR: \"" << g.name() << "\" (" << g.id()
1635  << ") is initialized but has no description_.\n";
1636  return;
1637  }
1638 
1639  simple_wml::node& desc = *g.description();
1640 
1641  // Update the game's description.
1642  if(const simple_wml::node* m = scenario->child("multiplayer")) {
1643  m->copy_into(desc);
1644  } else {
1645  WRN_SERVER << client_address(socket) << "\t" << player.name() << "\tsent scenario data in game:\t\""
1646  << g.name() << "\" (" << g.id() << ") without a 'multiplayer' child.\n";
1647 
1648  delete_game(g.id());
1649 
1650  send_server_message(socket,
1651  "The scenario data is missing the [multiplayer] tag which contains the game "
1652  "settings. Game aborted.");
1653  return;
1654  }
1655 
1656  // If there is no shroud, then tell players in the lobby
1657  // what the map looks like.
1659  desc.set_attr_dup("map_data", s["mp_shroud"].to_bool() ? "" : s["map_data"]);
1660 
1661  if(const simple_wml::node* e = data.child("era")) {
1662  if(!e->attr("require_era").to_bool(true)) {
1663  desc.set_attr("require_era", "no");
1664  }
1665  }
1666 
1667  if(s["require_scenario"].to_bool(false)) {
1668  desc.set_attr("require_scenario", "yes");
1669  }
1670 
1671  // Tell everyone that the next scenario data is available.
1672  static simple_wml::document notify_next_scenario(
1673  "[notify_next_scenario]\n[/notify_next_scenario]\n", simple_wml::INIT_COMPRESSED);
1674  g.send_data(notify_next_scenario, socket);
1675 
1676  // Send the update of the game description to the lobby.
1678  return;
1679  // A mp client sends a request for the next scenario of a mp campaign.
1680  } else if(data.child("load_next_scenario")) {
1681  g.load_next_scenario(socket);
1682  return;
1683  } else if(data.child("start_game")) {
1684  if(!g.is_owner(socket)) {
1685  return;
1686  }
1687 
1688  // perform controller tweaks, assigning sides as human for their owners etc.
1690 
1691  // Send notification of the game starting immediately.
1692  // g.start_game() will send data that assumes
1693  // the [start_game] message has been sent
1694  g.send_data(data, socket);
1695  g.start_game(socket);
1696 
1697  // update the game having changed in the lobby
1699  return;
1700  } else if(data.child("update_game")) {
1701  g.update_game();
1703  return;
1704  } else if(data.child("leave_game")) {
1705  // May be better to just let remove_player() figure out when a game ends.
1706  if((g.is_player(socket) && g.nplayers() == 1) || (g.is_owner(socket) && (!g.started() || g.nplayers() == 0))) {
1707  // Remove the player in delete_game() with all other remaining
1708  // ones so he gets the updated gamelist.
1709  delete_game(g.id());
1710  } else {
1711  auto description = g.description();
1712  g.remove_player(socket);
1713 
1715  if(!g_ptr.expired()) {
1716  g.describe_slots();
1717  }
1718 
1719  // Send all other players in the lobby the update to the gamelist.
1720  simple_wml::document diff;
1721  bool diff1 = make_change_diff(*games_and_users_list_.child("gamelist"), "gamelist", "game", description, diff);
1722  bool diff2 = make_change_diff(games_and_users_list_.root(), nullptr, "user", player.config_address(), diff);
1723 
1724  if(diff1 || diff2) {
1725  send_to_lobby(diff, socket);
1726  }
1727 
1728  // Send the player who has quit the gamelist.
1730  }
1731 
1732  return;
1733  // If this is data describing side changes by the host.
1734  } else if(const simple_wml::node* scenario_diff = data.child("scenario_diff")) {
1735  if(!g.is_owner(socket)) {
1736  return;
1737  }
1738 
1739  g.level().root().apply_diff(*scenario_diff);
1740  const simple_wml::node* cfg_change = scenario_diff->child("change_child");
1741 
1742  // it is very likeley that the diff changes a side so this check isn't that important.
1743  // Note that [side] is not at toplevel but inside [scenario] or [snapshot]
1744  if(cfg_change /** && cfg_change->child("side") */) {
1745  g.update_side_data();
1746  }
1747 
1748  if(g.describe_slots()) {
1750  }
1751 
1752  g.send_data(data, socket);
1753  return;
1754  // If a player changes his faction.
1755  } else if(data.child("change_faction")) {
1756  g.send_data(data, socket);
1757  return;
1758  // If the owner of a side is changing the controller.
1759  } else if(const simple_wml::node* change = data.child("change_controller")) {
1760  g.transfer_side_control(socket, *change);
1761  if(g.describe_slots()) {
1763  }
1764 
1765  return;
1766  // If all observers should be muted. (toggles)
1767  } else if(data.child("muteall")) {
1768  if(!g.is_owner(socket)) {
1769  g.send_server_message("You cannot mute: not the game host.", socket);
1770  return;
1771  }
1772 
1773  g.mute_all_observers();
1774  return;
1775  // If an observer should be muted.
1776  } else if(const simple_wml::node* mute = data.child("mute")) {
1777  g.mute_observer(*mute, socket);
1778  return;
1779  // If an observer should be unmuted.
1780  } else if(const simple_wml::node* unmute = data.child("unmute")) {
1781  g.unmute_observer(*unmute, socket);
1782  return;
1783  // The owner is kicking/banning someone from the game.
1784  } else if(data.child("kick") || data.child("ban")) {
1785  bool ban = (data.child("ban") != nullptr);
1786  const socket_ptr user = (ban
1787  ? g.ban_user(*data.child("ban"), socket)
1788  : g.kick_member(*data.child("kick"), socket));
1789 
1790  if(user) {
1792  if(g.describe_slots()) {
1793  update_game_in_lobby(g, user);
1794  }
1795 
1796  // Send all other players in the lobby the update to the gamelist.
1797  simple_wml::document gamelist_diff;
1798  make_change_diff(*games_and_users_list_.child("gamelist"), "gamelist", "game", g.description(), gamelist_diff);
1799  make_change_diff(games_and_users_list_.root(), nullptr, "user", player_connections_.find(user)->info().config_address(), gamelist_diff);
1800 
1801  send_to_lobby(gamelist_diff, socket);
1802 
1803  // Send the removed user the lobby game list.
1805  }
1806 
1807  return;
1808  } else if(const simple_wml::node* unban = data.child("unban")) {
1809  g.unban_user(*unban, socket);
1810  return;
1811  // If info is being provided about the game state.
1812  } else if(const simple_wml::node* info = data.child("info")) {
1813  if(!g.is_player(socket)) {
1814  return;
1815  }
1816 
1817  if((*info)["type"] == "termination") {
1818  g.set_termination_reason((*info)["condition"].to_string());
1819  if((*info)["condition"].to_string() == "out of sync") {
1820  g.send_server_message_to_all(player.name() + " reports out of sync errors.");
1821  }
1822  }
1823 
1824  return;
1825  } else if(data.child("turn")) {
1826  // Notify the game of the commands, and if it changes
1827  // the description, then sync the new description
1828  // to players in the lobby.
1829  if(g.process_turn(data, socket)) {
1831  }
1832 
1833  return;
1834  } else if(data.child("whiteboard")) {
1835  g.process_whiteboard(data, socket);
1836  return;
1837  } else if(data.child("change_turns_wml")) {
1838  g.process_change_turns_wml(data, socket);
1840  return;
1841  } else if(simple_wml::node* sch = data.child("request_choice")) {
1842  g.handle_choice(*sch, socket);
1843  return;
1844  } else if(data.child("message")) {
1845  g.process_message(data, socket);
1846  return;
1847  } else if(data.child("stop_updates")) {
1848  g.send_data(data, socket);
1849  return;
1850  // Data to ignore.
1851  } else if(
1852  data.child("error") ||
1853  data.child("side_secured") ||
1854  data.root().has_attr("failed") ||
1855  data.root().has_attr("side")
1856  ) {
1857  return;
1858  }
1859 
1860  WRN_SERVER << client_address(socket) << "\tReceived unknown data from: " << player.name() << " (socket:" << socket
1861  << ") in game: \"" << g.name() << "\" (" << g.id() << ")\n"
1862  << data.output();
1863 }
1864 
1865 using SendQueue = std::map<socket_ptr, std::deque<std::shared_ptr<simple_wml::document>>>;
1867 
1869 {
1870  if(send_queue[socket].empty()) {
1871  send_queue.erase(socket);
1872  } else {
1873  async_send_doc(socket, *(send_queue[socket].front()), handle_send_to_player, handle_send_to_player);
1874  send_queue[socket].pop_front();
1875  }
1876 }
1877 
1879 {
1880  auto iter = send_queue.find(socket);
1881  if(iter == send_queue.end()) {
1882  send_queue[socket];
1884  } else {
1885  send_queue[socket].push_back(std::shared_ptr<simple_wml::document>(doc.clone()));
1886  }
1887 }
1888 
1889 void send_server_message(socket_ptr socket, const std::string& message)
1890 {
1892  simple_wml::node& msg = server_message.root().add_child("message");
1893  msg.set_attr("sender", "server");
1894  msg.set_attr_dup("message", message.c_str());
1895 
1896  send_to_player(socket, server_message);
1897 }
1898 
1900 {
1901  std::string ip;
1902 
1903  auto iter = player_connections_.find(socket);
1904  if(iter == player_connections_.end()) {
1905  return;
1906  } else {
1907  // client_address() is very likely to return <unknown address> at this point
1908  // so we remember ip in player_connections_
1909  ip = iter->saved_client_ip();
1910  }
1911 
1912  const std::shared_ptr<game> g = iter->get_game();
1913  if(g) {
1914  g->remove_player(socket, true, false);
1915  }
1916 
1918  const std::size_t index =
1919  std::distance(users.begin(), std::find(users.begin(), users.end(), iter->info().config_address()));
1920 
1921  // Notify other players in lobby
1922  simple_wml::document diff;
1923  if(make_delete_diff(games_and_users_list_.root(), nullptr, "user", iter->info().config_address(), diff)) {
1924  send_to_lobby(diff, socket);
1925  }
1926 
1927  games_and_users_list_.root().remove_child("user", index);
1928 
1929  LOG_SERVER << ip << "\t" << iter->info().name() << "\twas logged off"
1930  << "\n";
1931 
1932  // Find the matching nick-ip pair in the log and update the sign off time
1933  connection_log ip_name = connection_log(iter->info().name(), ip, 0);
1934 
1935  auto i = std::find(ip_log_.begin(), ip_log_.end(), ip_name);
1936  if(i != ip_log_.end()) {
1937  i->log_off = std::time(nullptr);
1938  }
1939 
1940  player_connections_.erase(iter);
1941 
1942  if(socket->is_open()) {
1943  socket->close();
1944  }
1945 
1946  if(lan_server_ && player_connections_.size() == 0)
1948 }
1949 
1951 {
1952  for(const auto& player : player_connections_.get<game_t>().equal_range(0)) {
1953  if(player.socket() != exclude) {
1954  send_to_player(player.socket(), data);
1955  }
1956  }
1957 }
1958 
1959 void server::send_server_message_to_lobby(const std::string& message, socket_ptr exclude) const
1960 {
1961  for(const auto& player : player_connections_.get<game_t>().equal_range(0)) {
1962  if(player.socket() != exclude) {
1963  send_server_message(player.socket(), message);
1964  }
1965  }
1966 }
1967 
1968 void server::send_server_message_to_all(const std::string& message, socket_ptr exclude) const
1969 {
1970  for(const auto& player : player_connections_) {
1971  if(player.socket() != exclude) {
1972  send_server_message(player.socket(), message);
1973  }
1974  }
1975 }
1976 
1978 {
1979  if(restart_command.empty()) {
1980  return;
1981  }
1982 
1983  // Example config line:
1984  // restart_command="./wesnothd-debug -d -c ~/.wesnoth1.5/server.cfg"
1985  // remember to make new one as a daemon or it will block old one
1986  if(std::system(restart_command.c_str())) {
1987  ERR_SERVER << "Failed to start new server with command: " << restart_command << std::endl;
1988  } else {
1989  LOG_SERVER << "New server started with command: " << restart_command << "\n";
1990  }
1991 }
1992 
1993 std::string server::process_command(std::string query, std::string issuer_name)
1994 {
1995  boost::trim(query);
1996 
1997  if(issuer_name == "*socket*" && query.at(0) == '+') {
1998  // The first argument might be "+<issuer>: ".
1999  // In that case we use +<issuer>+ as the issuer_name.
2000  // (Mostly used for communication with IRC.)
2001  auto issuer_end = std::find(query.begin(), query.end(), ':');
2002 
2003  std::string issuer(query.begin() + 1, issuer_end);
2004  if(!issuer.empty()) {
2005  issuer_name = "+" + issuer + "+";
2006  query = std::string(issuer_end + 1, query.end());
2007  boost::trim(query);
2008  }
2009  }
2010 
2011  const auto i = std::find(query.begin(), query.end(), ' ');
2012 
2013  try {
2014  const std::string command = utf8::lowercase(std::string(query.begin(), i));
2015 
2016  std::string parameters = (i == query.end() ? "" : std::string(i + 1, query.end()));
2017  boost::trim(parameters);
2018 
2019  std::ostringstream out;
2020  auto handler_itor = cmd_handlers_.find(command);
2021 
2022  if(handler_itor == cmd_handlers_.end()) {
2023  out << "Command '" << command << "' is not recognized.\n" << help_msg;
2024  } else {
2025  const cmd_handler& handler = handler_itor->second;
2026  try {
2027  handler(issuer_name, query, parameters, &out);
2028  } catch(const std::bad_function_call& ex) {
2029  ERR_SERVER << "While handling a command '" << command
2030  << "', caught a std::bad_function_call exception.\n";
2031  ERR_SERVER << ex.what() << std::endl;
2032  out << "An internal server error occurred (std::bad_function_call) while executing '" << command
2033  << "'\n";
2034  }
2035  }
2036 
2037  return out.str();
2038 
2039  } catch(const utf8::invalid_utf8_exception& e) {
2040  std::string msg = "While handling a command, caught an invalid utf8 exception: ";
2041  msg += e.what();
2042  ERR_SERVER << msg << std::endl;
2043  return (msg + '\n');
2044  }
2045 }
2046 
2047 // Shutdown, restart and sample commands can only be issued via the socket.
2049  const std::string& issuer_name, const std::string& /*query*/, std::string& parameters, std::ostringstream* out)
2050 {
2051  assert(out != nullptr);
2052 
2053  if(issuer_name != "*socket*" && !allow_remote_shutdown_) {
2054  *out << denied_msg;
2055  return;
2056  }
2057 
2058  if(parameters == "now") {
2059  throw server_shutdown("shut down by admin command");
2060  } else {
2061  // Graceful shut down.
2062  graceful_restart = true;
2063  acceptor_v6_.close();
2064  acceptor_v4_.close();
2065 
2066  timer_.expires_from_now(boost::posix_time::seconds(10));
2067  timer_.async_wait(std::bind(&server::handle_graceful_timeout, this, _1));
2068 
2070  "msg The server is shutting down. You may finish your games but can't start new ones. Once all "
2071  "games have ended the server will exit.",
2072  issuer_name
2073  );
2074 
2075  *out << "Server is doing graceful shut down.";
2076  }
2077 }
2078 
2079 void server::restart_handler(const std::string& issuer_name,
2080  const std::string& /*query*/,
2081  std::string& /*parameters*/,
2082  std::ostringstream* out)
2083 {
2084  assert(out != nullptr);
2085 
2086  if(issuer_name != "*socket*" && !allow_remote_shutdown_) {
2087  *out << denied_msg;
2088  return;
2089  }
2090 
2091  if(restart_command.empty()) {
2092  *out << "No restart_command configured! Not restarting.";
2093  } else {
2094  graceful_restart = true;
2095  acceptor_v6_.close();
2096  acceptor_v4_.close();
2097  timer_.expires_from_now(boost::posix_time::seconds(10));
2098  timer_.async_wait(std::bind(&server::handle_graceful_timeout, this, _1));
2099 
2100  start_new_server();
2101 
2103  "msg The server has been restarted. You may finish current games but can't start new ones and "
2104  "new players can't join this (old) server instance. (So if a player of your game disconnects "
2105  "you have to save, reconnect and reload the game on the new server instance. It is actually "
2106  "recommended to do that right away.)",
2107  issuer_name
2108  );
2109 
2110  *out << "New server started.";
2111  }
2112 }
2113 
2115  const std::string& issuer_name, const std::string& /*query*/, std::string& parameters, std::ostringstream* out)
2116 {
2117  assert(out != nullptr);
2118 
2119  if(parameters.empty()) {
2120  *out << "Current sample frequency: " << request_sample_frequency;
2121  return;
2122  } else if(issuer_name != "*socket*") {
2123  *out << denied_msg;
2124  return;
2125  }
2126 
2127  request_sample_frequency = atoi(parameters.c_str());
2128  if(request_sample_frequency <= 0) {
2129  *out << "Sampling turned off.";
2130  } else {
2131  *out << "Sampling every " << request_sample_frequency << " requests.";
2132  }
2133 }
2134 
2135 void server::help_handler(const std::string& /*issuer_name*/,
2136  const std::string& /*query*/,
2137  std::string& /*parameters*/,
2138  std::ostringstream* out)
2139 {
2140  assert(out != nullptr);
2141  *out << help_msg;
2142 }
2143 
2144 void server::stats_handler(const std::string& /*issuer_name*/,
2145  const std::string& /*query*/,
2146  std::string& /*parameters*/,
2147  std::ostringstream* out)
2148 {
2149  assert(out != nullptr);
2150 
2151  *out << "Number of games = " << games().size() << "\nTotal number of users = " << player_connections_.size()
2152  << "\n";
2153 }
2154 
2155 void server::metrics_handler(const std::string& /*issuer_name*/,
2156  const std::string& /*query*/,
2157  std::string& /*parameters*/,
2158  std::ostringstream* out)
2159 {
2160  assert(out != nullptr);
2161  *out << metrics_;
2162 }
2163 
2164 void server::requests_handler(const std::string& /*issuer_name*/,
2165  const std::string& /*query*/,
2166  std::string& /*parameters*/,
2167  std::ostringstream* out)
2168 {
2169  assert(out != nullptr);
2170  metrics_.requests(*out);
2171 }
2172 
2173 void server::games_handler(const std::string& /*issuer_name*/,
2174  const std::string& /*query*/,
2175  std::string& /*parameters*/,
2176  std::ostringstream* out)
2177 {
2178  assert(out != nullptr);
2179  metrics_.games(*out);
2180 }
2181 
2182 void server::wml_handler(const std::string& /*issuer_name*/,
2183  const std::string& /*query*/,
2184  std::string& /*parameters*/,
2185  std::ostringstream* out)
2186 {
2187  assert(out != nullptr);
2188  *out << simple_wml::document::stats();
2189 }
2190 
2191 void server::netstats_handler(const std::string& /*issuer_name*/,
2192  const std::string& /*query*/,
2193  std::string& /*parameters*/,
2194  std::ostringstream* /*out*/)
2195 {
2196  /*
2197  assert(out != nullptr);
2198 
2199  network::pending_statistics stats = network::get_pending_stats();
2200  *out << "Network stats:\nPending send buffers: "
2201  << stats.npending_sends << "\nBytes in buffers: "
2202  << stats.nbytes_pending_sends << "\n";
2203 
2204  try {
2205 
2206  if (utf8::lowercase(parameters) == "all") {
2207  *out << network::get_bandwidth_stats_all();
2208  } else {
2209  *out << network::get_bandwidth_stats(); // stats from previuos hour
2210  }
2211 
2212  } catch ( utf8::invalid_utf8_exception & e ) {
2213  ERR_SERVER << "While handling a netstats command, caught an invalid utf8 exception: " << e.what() << std::endl;
2214  }
2215  */
2216 }
2217 
2219  const std::string& issuer_name, const std::string& /*query*/, std::string& parameters, std::ostringstream* out)
2220 {
2221  assert(out != nullptr);
2222 
2223  if(parameters.empty()) {
2224  *out << "You must type a message.";
2225  return;
2226  }
2227 
2228  const std::string& sender = issuer_name;
2229  const std::string& message = parameters;
2230  LOG_SERVER << "Admin message: <" << sender
2231  << (message.find("/me ") == 0 ? std::string(message.begin() + 3, message.end()) + ">" : "> " + message)
2232  << "\n";
2233 
2234  simple_wml::document data;
2235  simple_wml::node& msg = data.root().add_child("whisper");
2236  msg.set_attr_dup("sender", ("admin message from " + sender).c_str());
2237  msg.set_attr_dup("message", message.c_str());
2238 
2239  int n = 0;
2240  for(const auto& player : player_connections_) {
2241  if(player.info().is_moderator()) {
2242  ++n;
2243  send_to_player(player.socket(), data);
2244  }
2245  }
2246 
2247  bool is_admin = false;
2248 
2249  for(const auto& player : player_connections_) {
2250  if(issuer_name == player.info().name() && player.info().is_moderator()) {
2251  is_admin = true;
2252  break;
2253  }
2254  }
2255 
2256  if(!is_admin) {
2257  *out << "Your report has been logged and sent to the server administrators. Thanks!";
2258  return;
2259  }
2260 
2261  *out << "Your report has been logged and sent to " << n << " online administrators. Thanks!";
2262 }
2263 
2265  const std::string& issuer_name, const std::string& /*query*/, std::string& parameters, std::ostringstream* out)
2266 {
2267  assert(out != nullptr);
2268 
2269  auto first_space = std::find(parameters.begin(), parameters.end(), ' ');
2270  if(first_space == parameters.end()) {
2271  *out << "You must name a receiver.";
2272  return;
2273  }
2274 
2275  const std::string& sender = issuer_name;
2276  const std::string receiver(parameters.begin(), first_space);
2277 
2278  std::string message(first_space + 1, parameters.end());
2279  boost::trim(message);
2280 
2281  if(message.empty()) {
2282  *out << "You must type a message.";
2283  return;
2284  }
2285 
2286  simple_wml::document data;
2287  simple_wml::node& msg = data.root().add_child("whisper");
2288 
2289  // This string is parsed by the client!
2290  msg.set_attr_dup("sender", ("server message from " + sender).c_str());
2291  msg.set_attr_dup("message", message.c_str());
2292 
2293  for(const auto& player : player_connections_) {
2294  if(receiver != player.info().name().c_str()) {
2295  continue;
2296  }
2297 
2298  send_to_player(player.socket(), data);
2299  *out << "Message to " << receiver << " successfully sent.";
2300  return;
2301  }
2302 
2303  *out << "No such nick: " << receiver;
2304 }
2305 
2306 void server::msg_handler(const std::string& /*issuer_name*/,
2307  const std::string& /*query*/,
2308  std::string& parameters,
2309  std::ostringstream* out)
2310 {
2311  assert(out != nullptr);
2312 
2313  if(parameters.empty()) {
2314  *out << "You must type a message.";
2315  return;
2316  }
2317 
2318  send_server_message_to_all(parameters);
2319 
2320  LOG_SERVER << "<server"
2321  << (parameters.find("/me ") == 0
2322  ? std::string(parameters.begin() + 3, parameters.end()) + ">"
2323  : "> " + parameters)
2324  << "\n";
2325 
2326  *out << "message '" << parameters << "' relayed to players";
2327 }
2328 
2329 void server::lobbymsg_handler(const std::string& /*issuer_name*/,
2330  const std::string& /*query*/,
2331  std::string& parameters,
2332  std::ostringstream* out)
2333 {
2334  assert(out != nullptr);
2335 
2336  if(parameters.empty()) {
2337  *out << "You must type a message.";
2338  return;
2339  }
2340 
2341  send_server_message_to_lobby(parameters);
2342  LOG_SERVER << "<server"
2343  << (parameters.find("/me ") == 0
2344  ? std::string(parameters.begin() + 3, parameters.end()) + ">"
2345  : "> " + parameters)
2346  << "\n";
2347 
2348  *out << "message '" << parameters << "' relayed to players";
2349 }
2350 
2352  const std::string& /*issuer_name*/, const std::string& /*query*/, std::string& parameters, std::ostringstream* out)
2353 {
2354  assert(out != nullptr);
2355 
2356  if(parameters.empty()) {
2357  *out << "Server version is " << game_config::wesnoth_version.str();
2358  return;
2359  }
2360 
2361  for(const auto& player : player_connections_) {
2362  if(parameters == player.info().name()) {
2363  *out << "Player " << parameters << " is using wesnoth " << player.info().version();
2364  return;
2365  }
2366  }
2367 
2368  *out << "Player '" << parameters << "' not found.";
2369 }
2370 
2372  const std::string& issuer_name, const std::string& /*query*/, std::string& parameters, std::ostringstream* out)
2373 {
2374  assert(out != nullptr);
2375 
2376  *out << "STATUS REPORT for '" << parameters << "'";
2377  bool found_something = false;
2378 
2379  // If a simple username is given we'll check for its IP instead.
2380  if(utils::isvalid_username(parameters)) {
2381  for(const auto& player : player_connections_) {
2382  if(utf8::lowercase(parameters) == utf8::lowercase(player.info().name())) {
2383  parameters = client_address(player.socket());
2384  found_something = true;
2385  break;
2386  }
2387  }
2388 
2389  if(!found_something) {
2390  // out << "\nNo match found. You may want to check with 'searchlog'.";
2391  // return out.str();
2392  *out << process_command("searchlog " + parameters, issuer_name);
2393  return;
2394  }
2395  }
2396 
2397  const bool match_ip = (std::count(parameters.begin(), parameters.end(), '.') >= 1);
2398  for(const auto& player : player_connections_) {
2399  if(parameters.empty() || parameters == "*" ||
2400  (match_ip && utils::wildcard_string_match(client_address(player.socket()), parameters)) ||
2401  (!match_ip && utils::wildcard_string_match(utf8::lowercase(player.info().name()), utf8::lowercase(parameters)))
2402  ) {
2403  found_something = true;
2404  *out << std::endl << player_status(player);
2405  }
2406  }
2407 
2408  if(!found_something) {
2409  *out << "\nNo match found. You may want to check with 'searchlog'.";
2410  }
2411 }
2412 
2413 void server::clones_handler(const std::string& /*issuer_name*/,
2414  const std::string& /*query*/,
2415  std::string& /*parameters*/,
2416  std::ostringstream* out)
2417 {
2418  assert(out != nullptr);
2419  *out << "CLONES STATUS REPORT";
2420 
2421  std::set<std::string> clones;
2422 
2423  for(auto it = player_connections_.begin(); it != player_connections_.end(); ++it) {
2424  if(clones.find(client_address(it->socket())) != clones.end()) {
2425  continue;
2426  }
2427 
2428  bool found = false;
2429  for(auto clone = std::next(it); clone != player_connections_.end(); ++clone) {
2430  if(client_address(it->socket()) == client_address(clone->socket())) {
2431  if(!found) {
2432  found = true;
2433  clones.insert(client_address(it->socket()));
2434  *out << std::endl << player_status(*it);
2435  }
2436 
2437  *out << std::endl << player_status(*clone);
2438  }
2439  }
2440  }
2441 
2442  if(clones.empty()) {
2443  *out << std::endl << "No clones found.";
2444  }
2445 }
2446 
2447 void server::bans_handler(const std::string& /*issuer_name*/,
2448  const std::string& /*query*/,
2449  std::string& parameters,
2450  std::ostringstream* out)
2451 {
2452  assert(out != nullptr);
2453 
2454  try {
2455  if(parameters.empty()) {
2456  ban_manager_.list_bans(*out);
2457  } else if(utf8::lowercase(parameters) == "deleted") {
2459  } else if(utf8::lowercase(parameters).find("deleted") == 0) {
2460  std::string mask = parameters.substr(7);
2461  ban_manager_.list_deleted_bans(*out, boost::trim_copy(mask));
2462  } else {
2463  boost::trim(parameters);
2464  ban_manager_.list_bans(*out, parameters);
2465  }
2466 
2467  } catch(const utf8::invalid_utf8_exception& e) {
2468  ERR_SERVER << "While handling bans, caught an invalid utf8 exception: " << e.what() << std::endl;
2469  }
2470 }
2471 
2473  const std::string& issuer_name, const std::string& /*query*/, std::string& parameters, std::ostringstream* out)
2474 {
2475  assert(out != nullptr);
2476 
2477  bool banned = false;
2478  auto first_space = std::find(parameters.begin(), parameters.end(), ' ');
2479 
2480  if(first_space == parameters.end()) {
2481  *out << ban_manager_.get_ban_help();
2482  return;
2483  }
2484 
2485  auto second_space = std::find(first_space + 1, parameters.end(), ' ');
2486  const std::string target(parameters.begin(), first_space);
2487  const std::string duration(first_space + 1, second_space);
2488  std::time_t parsed_time = std::time(nullptr);
2489 
2490  if(ban_manager_.parse_time(duration, &parsed_time) == false) {
2491  *out << "Failed to parse the ban duration: '" << duration << "'\n" << ban_manager_.get_ban_help();
2492  return;
2493  }
2494 
2495  if(second_space == parameters.end()) {
2496  --second_space;
2497  }
2498 
2499  std::string reason(second_space + 1, parameters.end());
2500  boost::trim(reason);
2501 
2502  if(reason.empty()) {
2503  *out << "You need to give a reason for the ban.";
2504  return;
2505  }
2506 
2507  std::string dummy_group;
2508 
2509  // if we find a '.' consider it an ip mask
2510  /** @todo FIXME: make a proper check for valid IPs. */
2511  if(std::count(target.begin(), target.end(), '.') >= 1) {
2512  banned = true;
2513 
2514  *out << ban_manager_.ban(target, parsed_time, reason, issuer_name, dummy_group);
2515  } else {
2516  for(const auto& player : player_connections_) {
2517  if(utils::wildcard_string_match(player.info().name(), target)) {
2518  if(banned) {
2519  *out << "\n";
2520  } else {
2521  banned = true;
2522  }
2523 
2524  const std::string ip = client_address(player.socket());
2525  *out << ban_manager_.ban(ip, parsed_time, reason, issuer_name, dummy_group, target);
2526  }
2527  }
2528 
2529  if(!banned) {
2530  // If nobody was banned yet check the ip_log but only if a
2531  // simple username was used to prevent accidental bans.
2532  // @todo FIXME: since we can have several entries now we should only ban the latest or so
2533  /*if (utils::isvalid_username(target)) {
2534  for (std::deque<connection_log>::const_iterator i = ip_log_.begin();
2535  i != ip_log_.end(); ++i) {
2536  if (i->nick == target) {
2537  if (banned) out << "\n";
2538  else banned = true;
2539  out << ban_manager_.ban(i->ip, parsed_time, reason, issuer_name, group, target);
2540  }
2541  }
2542  }*/
2543 
2544  if(!banned) {
2545  *out << "Nickname mask '" << target << "' did not match, no bans set.";
2546  }
2547  }
2548  }
2549 }
2550 
2552  const std::string& issuer_name, const std::string& /*query*/, std::string& parameters, std::ostringstream* out)
2553 {
2554  assert(out != nullptr);
2555 
2556  bool banned = false;
2557  auto first_space = std::find(parameters.begin(), parameters.end(), ' ');
2558  if(first_space == parameters.end()) {
2559  *out << ban_manager_.get_ban_help();
2560  return;
2561  }
2562 
2563  auto second_space = std::find(first_space + 1, parameters.end(), ' ');
2564  const std::string target(parameters.begin(), first_space);
2565  const std::string duration(first_space + 1, second_space);
2566  std::time_t parsed_time = std::time(nullptr);
2567 
2568  if(ban_manager_.parse_time(duration, &parsed_time) == false) {
2569  *out << "Failed to parse the ban duration: '" << duration << "'\n" << ban_manager_.get_ban_help();
2570  return;
2571  }
2572 
2573  if(second_space == parameters.end()) {
2574  --second_space;
2575  }
2576 
2577  std::string reason(second_space + 1, parameters.end());
2578  boost::trim(reason);
2579 
2580  if(reason.empty()) {
2581  *out << "You need to give a reason for the ban.";
2582  return;
2583  }
2584 
2585  std::string dummy_group;
2586  std::vector<socket_ptr> users_to_kick;
2587 
2588  // if we find a '.' consider it an ip mask
2589  /** @todo FIXME: make a proper check for valid IPs. */
2590  if(std::count(target.begin(), target.end(), '.') >= 1) {
2591  banned = true;
2592 
2593  *out << ban_manager_.ban(target, parsed_time, reason, issuer_name, dummy_group);
2594 
2595  for(const auto& player : player_connections_) {
2596  if(utils::wildcard_string_match(client_address(player.socket()), target)) {
2597  users_to_kick.push_back(player.socket());
2598  }
2599  }
2600  } else {
2601  for(const auto& player : player_connections_) {
2602  if(utils::wildcard_string_match(player.info().name(), target)) {
2603  if(banned) {
2604  *out << "\n";
2605  } else {
2606  banned = true;
2607  }
2608 
2609  const std::string ip = client_address(player.socket());
2610  *out << ban_manager_.ban(ip, parsed_time, reason, issuer_name, dummy_group, target);
2611  users_to_kick.push_back(player.socket());
2612  }
2613  }
2614 
2615  if(!banned) {
2616  // If nobody was banned yet check the ip_log but only if a
2617  // simple username was used to prevent accidental bans.
2618  // @todo FIXME: since we can have several entries now we should only ban the latest or so
2619  /*if (utils::isvalid_username(target)) {
2620  for (std::deque<connection_log>::const_iterator i = ip_log_.begin();
2621  i != ip_log_.end(); ++i) {
2622  if (i->nick == target) {
2623  if (banned) out << "\n";
2624  else banned = true;
2625  out << ban_manager_.ban(i->ip, parsed_time, reason, issuer_name, group, target);
2626  }
2627  }
2628  }*/
2629  if(!banned) {
2630  *out << "Nickname mask '" << target << "' did not match, no bans set.";
2631  }
2632  }
2633  }
2634 
2635  for(const auto& user : users_to_kick) {
2636  *out << "\nKicked " << player_connections_.find(user)->info().name() << " (" << client_address(user) << ").";
2637  async_send_error(user, "You have been banned. Reason: " + reason);
2638  remove_player(user);
2639  }
2640 }
2641 
2643  const std::string& issuer_name, const std::string& /*query*/, std::string& parameters, std::ostringstream* out)
2644 {
2645  assert(out != nullptr);
2646 
2647  bool banned = false;
2648  auto first_space = std::find(parameters.begin(), parameters.end(), ' ');
2649  if(first_space == parameters.end()) {
2650  *out << ban_manager_.get_ban_help();
2651  return;
2652  }
2653 
2654  auto second_space = std::find(first_space + 1, parameters.end(), ' ');
2655  const std::string target(parameters.begin(), first_space);
2656 
2657  std::string group = std::string(first_space + 1, second_space);
2658  first_space = second_space;
2659  second_space = std::find(first_space + 1, parameters.end(), ' ');
2660 
2661  const std::string duration(first_space + 1, second_space);
2662  std::time_t parsed_time = std::time(nullptr);
2663 
2664  if(ban_manager_.parse_time(duration, &parsed_time) == false) {
2665  *out << "Failed to parse the ban duration: '" << duration << "'\n" << ban_manager_.get_ban_help();
2666  return;
2667  }
2668 
2669  if(second_space == parameters.end()) {
2670  --second_space;
2671  }
2672 
2673  std::string reason(second_space + 1, parameters.end());
2674  boost::trim(reason);
2675 
2676  if(reason.empty()) {
2677  *out << "You need to give a reason for the ban.";
2678  return;
2679  }
2680 
2681  // if we find a '.' consider it an ip mask
2682  /** @todo FIXME: make a proper check for valid IPs. */
2683  if(std::count(target.begin(), target.end(), '.') >= 1) {
2684  banned = true;
2685 
2686  *out << ban_manager_.ban(target, parsed_time, reason, issuer_name, group);
2687  } else {
2688  for(const auto& player : player_connections_) {
2689  if(utils::wildcard_string_match(player.info().name(), target)) {
2690  if(banned) {
2691  *out << "\n";
2692  } else {
2693  banned = true;
2694  }
2695 
2696  const std::string ip = client_address(player.socket());
2697  *out << ban_manager_.ban(ip, parsed_time, reason, issuer_name, group, target);
2698  }
2699  }
2700 
2701  if(!banned) {
2702  // If nobody was banned yet check the ip_log but only if a
2703  // simple username was used to prevent accidental bans.
2704  // @todo FIXME: since we can have several entries now we should only ban the latest or so
2705  /*if (utils::isvalid_username(target)) {
2706  for (std::deque<connection_log>::const_iterator i = ip_log_.begin();
2707  i != ip_log_.end(); ++i) {
2708  if (i->nick == target) {
2709  if (banned) out << "\n";
2710  else banned = true;
2711  out << ban_manager_.ban(i->ip, parsed_time, reason, issuer_name, group, target);
2712  }
2713  }
2714  }*/
2715  if(!banned) {
2716  *out << "Nickname mask '" << target << "' did not match, no bans set.";
2717  }
2718  }
2719  }
2720 }
2721 
2722 void server::unban_handler(const std::string& /*issuer_name*/,
2723  const std::string& /*query*/,
2724  std::string& parameters,
2725  std::ostringstream* out)
2726 {
2727  assert(out != nullptr);
2728 
2729  if(parameters.empty()) {
2730  *out << "You must enter an ipmask to unban.";
2731  return;
2732  }
2733 
2734  ban_manager_.unban(*out, parameters);
2735 }
2736 
2737 void server::ungban_handler(const std::string& /*issuer_name*/,
2738  const std::string& /*query*/,
2739  std::string& parameters,
2740  std::ostringstream* out)
2741 {
2742  assert(out != nullptr);
2743 
2744  if(parameters.empty()) {
2745  *out << "You must enter an ipmask to ungban.";
2746  return;
2747  }
2748 
2749  ban_manager_.unban_group(*out, parameters);
2750 }
2751 
2752 void server::kick_handler(const std::string& /*issuer_name*/,
2753  const std::string& /*query*/,
2754  std::string& parameters,
2755  std::ostringstream* out)
2756 {
2757  assert(out != nullptr);
2758 
2759  if(parameters.empty()) {
2760  *out << "You must enter a mask to kick.";
2761  return;
2762  }
2763 
2764  auto i = std::find(parameters.begin(), parameters.end(), ' ');
2765  const std::string kick_mask = std::string(parameters.begin(), i);
2766  const std::string kick_message = (i == parameters.end()
2767  ? "You have been kicked."
2768  : "You have been kicked. Reason: " + std::string(i + 1, parameters.end()));
2769 
2770  bool kicked = false;
2771 
2772  // if we find a '.' consider it an ip mask
2773  const bool match_ip = (std::count(kick_mask.begin(), kick_mask.end(), '.') >= 1);
2774 
2775  std::vector<socket_ptr> users_to_kick;
2776  for(const auto& player : player_connections_) {
2777  if((match_ip && utils::wildcard_string_match(client_address(player.socket()), kick_mask)) ||
2778  (!match_ip && utils::wildcard_string_match(player.info().name(), kick_mask))
2779  ) {
2780  users_to_kick.push_back(player.socket());
2781  }
2782  }
2783 
2784  for(const auto& socket : users_to_kick) {
2785  if(kicked) {
2786  *out << "\n";
2787  } else {
2788  kicked = true;
2789  }
2790 
2791  *out << "Kicked " << player_connections_.find(socket)->name() << " (" << client_address(socket) << "). '"
2792  << kick_message << "'";
2793 
2794  async_send_error(socket, kick_message);
2795  remove_player(socket);
2796  }
2797 
2798  if(!kicked) {
2799  *out << "No user matched '" << kick_mask << "'.";
2800  }
2801 }
2802 
2803 void server::motd_handler(const std::string& /*issuer_name*/,
2804  const std::string& /*query*/,
2805  std::string& parameters,
2806  std::ostringstream* out)
2807 {
2808  assert(out != nullptr);
2809 
2810  if(parameters.empty()) {
2811  if(!motd_.empty()) {
2812  *out << "Message of the day:\n" << motd_;
2813  return;
2814  } else {
2815  *out << "No message of the day set.";
2816  return;
2817  }
2818  }
2819 
2820  motd_ = parameters;
2821  *out << "Message of the day set to: " << motd_;
2822 }
2823 
2824 void server::searchlog_handler(const std::string& /*issuer_name*/,
2825  const std::string& /*query*/,
2826  std::string& parameters,
2827  std::ostringstream* out)
2828 {
2829  assert(out != nullptr);
2830 
2831  if(parameters.empty()) {
2832  *out << "You must enter a mask to search for.";
2833  return;
2834  }
2835 
2836  *out << "IP/NICK LOG for '" << parameters << "'";
2837 
2838  bool found_something = false;
2839 
2840  // If this looks like an IP look up which nicks have been connected from it
2841  // Otherwise look for the last IP the nick used to connect
2842  const bool match_ip = (std::count(parameters.begin(), parameters.end(), '.') >= 1);
2843 
2844  for(const auto& i : ip_log_) {
2845  const std::string& username = i.nick;
2846  const std::string& ip = i.ip;
2847 
2848  if((match_ip && utils::wildcard_string_match(ip, parameters)) ||
2849  (!match_ip && utils::wildcard_string_match(utf8::lowercase(username), utf8::lowercase(parameters)))
2850  ) {
2851  found_something = true;
2852  auto player = player_connections_.get<name_t>().find(username);
2853 
2854  if(player != player_connections_.get<name_t>().end() && client_address(player->socket()) == ip) {
2855  *out << std::endl << player_status(*player);
2856  } else {
2857  *out << "\n'" << username << "' @ " << ip
2858  << " last seen: " << lg::get_timestamp(i.log_off, "%H:%M:%S %d.%m.%Y");
2859  }
2860  }
2861  }
2862 
2863  if(!found_something) {
2864  *out << "\nNo match found.";
2865  }
2866 }
2867 
2868 void server::dul_handler(const std::string& /*issuer_name*/,
2869  const std::string& /*query*/,
2870  std::string& parameters,
2871  std::ostringstream* out)
2872 {
2873  assert(out != nullptr);
2874 
2875  try {
2876  if(parameters.empty()) {
2877  *out << "Unregistered login is " << (deny_unregistered_login_ ? "disallowed" : "allowed") << ".";
2878  } else {
2879  deny_unregistered_login_ = (utf8::lowercase(parameters) == "yes");
2880  *out << "Unregistered login is now " << (deny_unregistered_login_ ? "disallowed" : "allowed") << ".";
2881  }
2882 
2883  } catch(const utf8::invalid_utf8_exception& e) {
2884  ERR_SERVER << "While handling dul (deny unregistered logins), caught an invalid utf8 exception: " << e.what()
2885  << std::endl;
2886  }
2887 }
2888 
2889 void server::delete_game(int gameid)
2890 {
2891  // Set the availability status for all quitting users.
2892  auto range_pair = player_connections_.get<game_t>().equal_range(gameid);
2893 
2894  // Make a copy of the iterators so that we can change them while iterating over them.
2895  // We can use pair::first_type since equal_range returns a pair of iterators.
2896  std::vector<decltype(range_pair)::first_type> range_vctor;
2897 
2898  for(auto it = range_pair.first; it != range_pair.second; ++it) {
2899  range_vctor.push_back(it);
2900  it->info().mark_available();
2901 
2902  simple_wml::document udiff;
2903  if(make_change_diff(games_and_users_list_.root(), nullptr, "user", it->info().config_address(), udiff)) {
2904  send_to_lobby(udiff);
2905  } else {
2906  ERR_SERVER << "ERROR: delete_game(): Could not find user in players_. (socket: " << it->socket() << ")\n";
2907  }
2908  }
2909 
2910  // Put the remaining users back in the lobby.
2911  // This will call cleanup_game() deleter since there won't
2912  // be any references to that game from player_connections_ anymore
2913  for(const auto& it : range_vctor) {
2915  }
2916 
2917  // send users in the game a notification to leave the game since it has ended
2918  static simple_wml::document leave_game_doc("[leave_game]\n[/leave_game]\n", simple_wml::INIT_COMPRESSED);
2919 
2920  for(const auto& it : range_vctor) {
2921  send_to_player(it->socket(), leave_game_doc);
2922  send_to_player(it->socket(), games_and_users_list_);
2923  }
2924 }
2925 
2927 {
2928  simple_wml::document diff;
2929  if(make_change_diff(*games_and_users_list_.child("gamelist"), "gamelist", "game", g.description(), diff)) {
2930  send_to_lobby(diff, exclude);
2931  }
2932 }
2933 
2934 } // namespace wesnothd
2935 
2936 int main(int argc, char** argv)
2937 {
2938  int port = 15000;
2939  bool keep_alive = false;
2940  std::size_t min_threads = 5;
2941  std::size_t max_threads = 0;
2942 
2943  srand(static_cast<unsigned>(std::time(nullptr)));
2944 
2945  std::string config_file;
2946 
2947  // setting path to currentworking directory
2949 
2950  // show 'info' by default
2952  lg::timestamps(true);
2953 
2954  for(int arg = 1; arg != argc; ++arg) {
2955  const std::string val(argv[arg]);
2956  if(val.empty()) {
2957  continue;
2958  }
2959 
2960  if((val == "--config" || val == "-c") && arg + 1 != argc) {
2961  config_file = argv[++arg];
2962  } else if(val == "--verbose" || val == "-v") {
2964  } else if(val.substr(0, 6) == "--log-") {
2965  std::size_t p = val.find('=');
2966  if(p == std::string::npos) {
2967  std::cerr << "unknown option: " << val << '\n';
2968  return 2;
2969  }
2970 
2971  std::string s = val.substr(6, p - 6);
2972  int severity;
2973 
2974  if(s == "error") {
2975  severity = lg::err().get_severity();
2976  } else if(s == "warning") {
2977  severity = lg::warn().get_severity();
2978  } else if(s == "info") {
2979  severity = lg::info().get_severity();
2980  } else if(s == "debug") {
2981  severity = lg::debug().get_severity();
2982  } else {
2983  std::cerr << "unknown debug level: " << s << '\n';
2984  return 2;
2985  }
2986 
2987  while(p != std::string::npos) {
2988  std::size_t q = val.find(',', p + 1);
2989  s = val.substr(p + 1, q == std::string::npos ? q : q - (p + 1));
2990 
2991  if(!lg::set_log_domain_severity(s, severity)) {
2992  std::cerr << "unknown debug domain: " << s << '\n';
2993  return 2;
2994  }
2995 
2996  p = q;
2997  }
2998  } else if((val == "--port" || val == "-p") && arg + 1 != argc) {
2999  port = atoi(argv[++arg]);
3000  } else if(val == "--keepalive") {
3001  keep_alive = true;
3002  } else if(val == "--help" || val == "-h") {
3003  std::cout << "usage: " << argv[0]
3004  << " [-dvV] [-c path] [-m n] [-p port] [-t n]\n"
3005  << " -c, --config <path> Tells wesnothd where to find the config file to use.\n"
3006  << " -d, --daemon Runs wesnothd as a daemon.\n"
3007  << " -h, --help Shows this usage message.\n"
3008  << " --log-<level>=<domain1>,<domain2>,...\n"
3009  << " sets the severity level of the debug domains.\n"
3010  << " 'all' can be used to match any debug domain.\n"
3011  << " Available levels: error, warning, info, debug.\n"
3012  << " -p, --port <port> Binds the server to the specified port.\n"
3013  << " --keepalive Enable TCP keepalive.\n"
3014  << " -t, --threads <n> Uses n worker threads for network I/O (default: 5).\n"
3015  << " -v --verbose Turns on more verbose logging.\n"
3016  << " -V, --version Returns the server version.\n";
3017  return 0;
3018  } else if(val == "--version" || val == "-V") {
3019  std::cout << "Battle for Wesnoth server " << game_config::wesnoth_version.str() << "\n";
3020  return 0;
3021  } else if(val == "--daemon" || val == "-d") {
3022 #ifdef _WIN32
3023  ERR_SERVER << "Running as a daemon is not supported on this platform" << std::endl;
3024  return -1;
3025 #else
3026  const pid_t pid = fork();
3027  if(pid < 0) {
3028  ERR_SERVER << "Could not fork and run as a daemon" << std::endl;
3029  return -1;
3030  } else if(pid > 0) {
3031  std::cout << "Started wesnothd as a daemon with process id " << pid << "\n";
3032  return 0;
3033  }
3034 
3035  setsid();
3036 #endif
3037  } else if((val == "--threads" || val == "-t") && arg + 1 != argc) {
3038  min_threads = atoi(argv[++arg]);
3039  if(min_threads > 30) {
3040  min_threads = 30;
3041  }
3042  } else if((val == "--max-threads" || val == "-T") && arg + 1 != argc) {
3043  max_threads = atoi(argv[++arg]);
3044  } else if(val == "--request_sample_frequency" && arg + 1 != argc) {
3045  wesnothd::request_sample_frequency = atoi(argv[++arg]);
3046  } else {
3047  ERR_SERVER << "unknown option: " << val << std::endl;
3048  return 2;
3049  }
3050  }
3051 
3052  try {
3053  wesnothd::server(port, keep_alive, config_file, min_threads, max_threads).run();
3054  } catch(const std::exception& e) {
3055  ERR_SERVER << "terminated by C++ exception: " << e.what() << std::endl;
3056  return 1;
3057  }
3058 
3059  return 0;
3060 }
boost::asio::ip::tcp::acceptor acceptor_v4_
Definition: server_base.hpp:47
std::string motd_
Definition: server.hpp:140
static void set_game(player_record &, std::shared_ptr< game >)
node & add_child(const char *name)
Definition: simple_wml.cpp:464
bool remove_player(const socket_ptr &player, const bool disconnect=false, const bool destruct=false)
Removes a user from the game.
Definition: game.cpp:1461
void send_data(simple_wml::document &data, const socket_ptr &exclude=socket_ptr(), std::string packet_type="") const
Definition: game.cpp:1666
static void enter_lobby(player_record &)
bool started() const
Definition: game.hpp:115
const string_span & attr(const char *key) const
Definition: simple_wml.hpp:127
std::string get_timestamp(const std::time_t &t, const std::string &format)
Definition: log.cpp:175
config & child(config_key_type key, int n=0)
Returns the nth child with the given key, or a reference to an invalid config if there is none...
Definition: config.cpp:420
void update_game()
Definition: game.cpp:371
void handle_nickserv(socket_ptr socket, simple_wml::node &nickserv)
Definition: server.cpp:1190
SendQueue send_queue
Definition: server.cpp:1866
node & set_attr(const char *key, const char *value)
Definition: simple_wml.hpp:272
void login(socket_ptr socket, std::string version)
Definition: server.cpp:658
void handle_whisper(socket_ptr socket, simple_wml::node &whisper)
Definition: server.cpp:1064
const simple_wml::node * config_address() const
Definition: player.hpp:51
bool isvalid_username(const std::string &username)
Check if the username contains only valid characters.
void shut_down_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2048
simple_wml::document games_and_users_list_
Definition: server.hpp:168
void new_scenario(const socket_ptr &player)
when the host sends the new scenario of a mp campaign
Definition: game.cpp:1603
std::deque< login_log >::size_type failed_login_buffer_size_
Definition: server.hpp:157
void apply_diff(const node &diff)
Definition: simple_wml.cpp:826
#define FIFODIR
Interfaces for manipulating version numbers of engine, add-ons, etc.
void load_config(const config &)
Definition: ban.cpp:703
void save_replay()
Definition: game.cpp:1819
#define MP_NAME_AUTH_BAN_USER_ERROR
const std::string denied_msg
Definition: server.cpp:208
void handle_version(socket_ptr socket)
Definition: server.cpp:603
void status_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2371
std::string join(const T &v, const std::string &s=",")
Generates a new string joining container items in a list.
bool has_attr(const char *key) const
Definition: simple_wml.cpp:403
void games_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2173
std::ostream & games(std::ostream &out) const
Definition: metrics.cpp:109
int failed_login_limit_
Definition: server.hpp:155
const std::string & version() const
Definition: player.hpp:50
static std::string player_status(const wesnothd::player_record &player)
Definition: server.cpp:192
boost::asio::signal_set sighup_
Definition: server_base.hpp:73
static l_noret error(LoadState *S, const char *why)
Definition: lundump.cpp:39
#define MP_TOO_MANY_ATTEMPTS_ERROR
New lexcical_cast header.
logger & info()
Definition: log.cpp:90
void update_side_data()
Resets the side configuration according to the scenario data.
Definition: game.cpp:452
std::string is_ip_banned(const std::string &ip)
Definition: ban.cpp:661
bool save_replays_
Definition: server.hpp:151
std::function< void(const std::string &, const std::string &, std::string &, std::ostringstream *)> cmd_handler
Definition: server.hpp:195
const char * end() const
Definition: simple_wml.hpp:90
int main(int argc, char **argv)
Definition: server.cpp:2936
void kickban_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2551
const std::string & name() const
Definition: player.hpp:49
void start_dump_stats()
Definition: server.cpp:570
child_itors child_range(config_key_type key)
Definition: config.cpp:362
static void handle_send_to_player(socket_ptr socket)
Definition: server.cpp:1868
void handle_query(socket_ptr socket, simple_wml::node &query)
Definition: server.cpp:1104
void start_lan_server_timer()
Definition: server.cpp:306
void timestamps(bool t)
Definition: log.cpp:75
std::unique_ptr< user_handler > user_handler_
Definition: server.hpp:108
node & set_attr_int(const char *key, int value)
Definition: simple_wml.cpp:439
void process_whiteboard(simple_wml::document &data, const socket_ptr &user)
Handles incoming [whiteboard] data.
Definition: game.cpp:1271
#define MP_NO_SEED_ERROR
void help_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2135
#define WRN_SERVER
clients send wrong/unexpected data
Definition: server.cpp:72
bool level_init() const
Definition: game.hpp:83
node & set_attr(const char *key, const char *value)
Definition: simple_wml.cpp:411
bool wildcard_string_match(const std::string &str, const std::string &match)
Match using &#39;*&#39; as any number of characters (including none), &#39;+&#39; as one or more characters, and &#39;?&#39; as any one character.
void wml_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2182
bool to_bool(bool default_value=false) const
Definition: simple_wml.cpp:157
#define ERR_CONFIG
Definition: server.cpp:79
void stats_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2144
void send_server_message(const char *message, const socket_ptr &sock=socket_ptr(), simple_wml::document *doc=nullptr) const
Definition: game.cpp:2011
#define MP_NAME_TOO_LONG_ERROR
std::deque< std::shared_ptr< game > > games()
Definition: server.hpp:112
STL namespace.
void handle_read_from_fifo(const boost::system::error_code &error, std::size_t bytes_transferred)
Definition: server.cpp:342
void update_game_in_lobby(const wesnothd::game &g, const socket_ptr &exclude=socket_ptr())
Definition: server.cpp:2926
static void msg(const char *act, debug_info &i, const char *to="", const char *result="")
Definition: debugger.cpp:109
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)
Definition: server.cpp:118
std::size_t default_time_period_
Definition: server.hpp:142
void requests_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2164
#define d
Define the errors the server may send during the login procedure.
std::vector< std::string > accepted_versions_
Definition: server.hpp:134
std::size_t default_max_messages_
Definition: server.hpp:141
bool is_moderator() const
Definition: player.hpp:69
void send_server_message_to_lobby(const std::string &message, socket_ptr exclude=socket_ptr()) const
Definition: server.cpp:1959
const child_list & children(const char *name) const
Definition: simple_wml.cpp:633
void delete_game(int)
Definition: server.cpp:2889
void ban_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2472
Definitions for the interface to Wesnoth Markup Language (WML).
void handle_sighup(const boost::system::error_code &error, int signal_number)
Definition: server.cpp:280
std::vector< std::string > split(const std::string &val, const char c, const int flags)
Splits a (comma-)separated string into a vector of pieces.
void handle_read_from_player(socket_ptr socket, std::shared_ptr< simple_wml::document > doc)
Definition: server.cpp:1014
void send_server_message_to_all(const char *message, const socket_ptr &exclude=socket_ptr()) const
Definition: game.cpp:2004
std::string uh_name_
Definition: server.hpp:149
void handle_create_game(socket_ptr socket, simple_wml::node &create_game)
Definition: server.cpp:1339
An example of how to implement user_handler.
std::time_t last_uh_clean_
Definition: server.hpp:177
const socket_ptr socket() const
bool deny_unregistered_login_
Definition: server.hpp:150
void handle_graceful_timeout(const boost::system::error_code &error)
Definition: server.cpp:293
void async_send_warning(socket_ptr socket, const std::string &msg, const char *warning_code)
#define MP_INCORRECT_PASSWORD_ERROR
void gban_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2642
std::string get_cwd()
Definition: filesystem.cpp:771
void start_server()
Definition: server_base.cpp:58
node * child(const char *name)
Definition: simple_wml.hpp:260
const char * output()
bool exists(const image::locator &i_locator)
returns true if the given image actually exists, without loading it.
Definition: picture.cpp:1217
node * child(const char *name)
Definition: simple_wml.cpp:606
std::string recommended_version_
Definition: server.hpp:135
bool process_turn(simple_wml::document &data, const socket_ptr &user)
Handles [end_turn], repackages [commands] with private [speak]s in them and sends the data...
Definition: game.cpp:995
bool player_is_in_game(socket_ptr socket) const
Definition: server.hpp:71
void process_message(simple_wml::document &data, const socket_ptr &user)
Definition: game.cpp:914
const char * begin() const
Definition: simple_wml.hpp:89
const socket_ptr const std::string & name
Definition: game.hpp:46
#define MP_MUST_LOGIN
simple_wml::document login_response_
Definition: server.hpp:166
#define MP_NAME_UNREGISTERED_ERROR
void process_change_turns_wml(simple_wml::document &data, const socket_ptr &user)
Handles incoming [change_turns_wml] data.
Definition: game.cpp:1298
void handle_login(socket_ptr socket, std::shared_ptr< simple_wml::document > doc, std::string version)
Definition: server.cpp:663
A user_handler implementation to link the server with a phpbb3 forum.
boost::asio::streambuf admin_cmd_
Definition: server_base.hpp:71
void truncate_message(const simple_wml::string_span &str, simple_wml::node &message)
Function to ensure a text message is within the allowed length.
bool is_login_allowed(socket_ptr socket, const simple_wml::node *const login, const std::string &version)
Definition: server.cpp:674
bool allow_remote_shutdown_
Definition: server.hpp:153
std::map< std::string, config > proxy_versions_
Definition: server.hpp:137
void start_game(const socket_ptr &starter)
Definition: game.cpp:294
void unban_group(std::ostringstream &os, const std::string &group)
Definition: ban.cpp:553
void msg_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2306
void clean_user_handler(const std::time_t &now)
Definition: server.cpp:588
bool authenticate(socket_ptr socket, const std::string &username, const std::string &password, const std::string &version, bool name_taken, bool &registered)
Definition: server.cpp:824
void add_player(socket_ptr socket, const wesnothd::player &)
Definition: server.cpp:977
std::map< socket_ptr::element_type *, std::string > seeds_
Definition: server.hpp:109
void remove_player(socket_ptr socket)
Definition: server.cpp:1899
void handle_lan_server_shutdown(const boost::system::error_code &error)
Definition: server.cpp:317
void read(config &cfg, std::istream &in, abstract_validator *validator)
Definition: parser.cpp:625
void list_deleted_bans(std::ostringstream &out, const std::string &mask="*") const
Definition: ban.cpp:589
std::string ban(const std::string &, const std::time_t &, const std::string &, const std::string &, const std::string &, const std::string &="")
Definition: ban.cpp:491
#define SETUP_HANDLER(name, function)
std::string restart_command
Definition: server.hpp:147
bool describe_slots()
Set the description to the number of available slots.
Definition: game.cpp:673
void handle_player_in_lobby(socket_ptr socket, std::shared_ptr< simple_wml::document > doc)
Definition: server.cpp:1046
void clones_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2413
bool ip_exceeds_connection_limit(const std::string &ip) const
Definition: server.cpp:543
std::string input_path_
server socket/fifo.
Definition: server.hpp:124
An interface class to handle nick registration To activate it put a [user_handler] section into the s...
std::unique_ptr< std::istream > scoped_istream
Definition: filesystem.hpp:39
boost::asio::deadline_timer timer_
Definition: server.hpp:230
void motd_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2803
std::vector< std::string > tor_ip_list_
Definition: server.hpp:154
std::string path
Definition: game_config.cpp:39
boost::asio::ip::tcp::acceptor acceptor_v6_
Definition: server_base.hpp:46
void load_next_scenario(const socket_ptr &user)
A user (player only?) asks for the next scenario to advance to.
Definition: game.cpp:1614
void bans_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2447
std::ostream & requests(std::ostream &out) const
Definition: metrics.cpp:124
void searchlog_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2824
logger & debug()
Definition: log.cpp:96
simple_wml::document version_query_response_
Definition: server.hpp:165
void perform_controller_tweaks()
Definition: game.cpp:229
bool is_player(const socket_ptr &player) const
Definition: game.cpp:193
std::string read_file(const std::string &fname)
Basic disk I/O - read file.
Definition: filesystem.cpp:874
std::string replay_save_path_
Definition: server.hpp:152
void kick_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2752
void send_to_lobby(simple_wml::document &data, socket_ptr exclude=socket_ptr()) const
Definition: server.cpp:1950
static void make_add_diff(const simple_wml::node &src, const char *gamelist, const char *type, simple_wml::document &out, int index=-1)
Definition: server.cpp:90
void send_to_player(socket_ptr socket, simple_wml::document &doc)
Definition: server.cpp:1878
void netstats_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2191
boost::asio::steady_timer dump_stats_timer_
Definition: server.hpp:173
void swap(document &o)
const std::string & name() const
const std::string help_msg
Definition: server.cpp:209
void cleanup_game(game *)
Definition: server.cpp:1383
void 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=false)
Definition: server.cpp:934
socket_ptr kick_member(const simple_wml::node &kick, const socket_ptr &kicker)
Kick a member by name.
Definition: game.cpp:812
std::string server_message
static simple_wml::node * starting_pos(simple_wml::node &data)
Definition: game.hpp:88
void set_moderator(bool moderator)
Definition: player.hpp:68
static std::string stats()
bool graceful_restart
Definition: server.hpp:144
void game_terminated(const std::string &reason)
Definition: metrics.cpp:104
void sample_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2114
std::size_t i
Definition: function.cpp:933
logger & err()
Definition: log.cpp:78
Thrown by operations encountering invalid UTF-8 data.
node & set_attr_dup(const char *key, const char *value)
Definition: simple_wml.cpp:427
void start_new_server()
Definition: server.cpp:1977
boost::asio::steady_timer lan_server_timer_
Definition: server.hpp:233
void send_server_message_to_all(const std::string &message, socket_ptr exclude=socket_ptr()) const
Definition: server.cpp:1968
void read_from_player(socket_ptr socket)
Definition: server.cpp:1006
const node::child_list & children(const char *name) const
Definition: simple_wml.hpp:268
std::size_t concurrent_connections_
Definition: server.hpp:143
mock_party p
void unban_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2722
const std::string config_file_
Definition: server.hpp:127
static map_location::DIRECTION s
double g
Definition: astarsearch.cpp:64
void remove_child(const char *name, std::size_t index)
Definition: simple_wml.cpp:601
std::time_t failed_login_ban_
Definition: server.hpp:156
std::string password(const std::string &server, const std::string &login)
std::vector< node * > child_list
Definition: simple_wml.hpp:124
void unban_user(const simple_wml::node &unban, const socket_ptr &unbanner)
Definition: game.cpp:885
std::string client_address(const socket_ptr socket)
std::string admin_passwd_
Definition: server.hpp:139
void reset_last_synced_context_id()
Definition: game.hpp:306
wesnothd::ban_manager ban_manager_
Definition: server.hpp:75
std::deque< login_log > failed_logins_
Definition: server.hpp:106
void adminmsg_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2218
#define ERR_SERVER
fatal and directly server related errors/warnings, ie not caused by erroneous client data ...
Definition: server.cpp:69
metrics metrics_
Definition: server.hpp:170
void handle_player_in_game(socket_ptr socket, std::shared_ptr< simple_wml::document > doc)
Definition: server.cpp:1494
std::string & insert(std::string &str, const std::size_t pos, const std::string &insert)
Insert a UTF-8 string at the specified position.
Definition: unicode.cpp:99
Declarations for File-IO.
void mute_observer(const simple_wml::node &mute, const socket_ptr &muter)
Mute an observer or give a message of all currently muted observers if no name is given...
Definition: game.cpp:732
std::map< socket_ptr, std::deque< std::shared_ptr< simple_wml::document > >> SendQueue
Definition: server.cpp:1865
void read_from_fifo()
std::size_t index(const std::string &str, const std::size_t index)
Codepoint index corresponding to the nth character in a UTF-8 string.
Definition: unicode.cpp:71
#define MP_PASSWORD_REQUEST
void handle_choice(const simple_wml::node &data, const socket_ptr &user)
Definition: game.cpp:1229
std::string lowercase(const std::string &s)
Returns a lowercased version of the string.
Definition: unicode.cpp:51
void set_description(simple_wml::node *desc)
Functions to set/get the address of the game&#39;s summary description as sent to players in the lobby...
Definition: game.cpp:1895
boost::asio::posix::stream_descriptor input_
Definition: server_base.hpp:67
#define MP_NAME_INACTIVE_WARNING
std::map< std::string, config > redirected_versions_
Definition: server.hpp:136
const version_info wesnoth_version(VERSION)
void set_password(const std::string &passwd)
Definition: game.hpp:280
std::string observer
bool set_log_domain_severity(const std::string &name, int severity)
Definition: log.cpp:118
Represents version numbers.
const std::shared_ptr< game > get_game() const
void dump_stats(const boost::system::error_code &ec)
Definition: server.cpp:576
std::size_t nplayers() const
Definition: game.hpp:120
void handle_message(socket_ptr socket, simple_wml::node &message)
Definition: server.cpp:1311
int request_sample_frequency
Definition: server.cpp:87
void restart_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2079
#define MP_PASSWORD_REQUEST_FOR_LOGGED_IN_NAME
#define next(ls)
Definition: llex.cpp:32
void version_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2351
#define MP_NAME_TAKEN_ERROR
std::string is_ip_banned(const std::string &ip)
Definition: server.cpp:559
void list_bans(std::ostringstream &out, const std::string &mask="*")
Definition: ban.cpp:617
std::time_t lan_server_
Definition: server.hpp:145
void async_send_doc(socket_ptr socket, simple_wml::document &doc, Handler handler, ErrorHandler error_handler)
logger & warn()
Definition: log.cpp:84
void async_receive_doc(socket_ptr socket, Handler handler, ErrorHandler error_handler)
server(int port, bool keep_alive, const std::string &config_file, std::size_t, std::size_t)
Definition: server.cpp:220
bool is_owner(const socket_ptr &player) const
Definition: game.hpp:62
void unmute_observer(const simple_wml::node &unmute, const socket_ptr &unmuter)
Definition: game.cpp:774
bool find(E event, F functor)
Tests whether an event handler is available.
void handle_join_game(socket_ptr socket, simple_wml::node &join)
Definition: server.cpp:1411
void async_send_error(socket_ptr socket, const std::string &msg, const char *error_code)
void unban(std::ostringstream &os, const std::string &ip, bool immediate_write=true)
Definition: ban.cpp:526
void setup_handlers()
Definition: server.cpp:371
Definition: ban.cpp:28
bool parse_time(const std::string &duration, std::time_t *time) const
Parses the given duration and adds it to *time except if the duration is &#39;0&#39; or &#39;permanent&#39; in which ...
Definition: ban.cpp:327
std::map< std::string, cmd_handler > cmd_handlers_
Definition: server.hpp:196
#define LOG_SERVER
normal events
Definition: server.cpp:75
const std::string & termination_reason() const
Definition: game.hpp:290
void setup_fifo()
Definition: server.cpp:325
Standard logging facilities (interface).
void dul_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2868
static lg::log_domain log_config("config")
std::string str() const
Serializes the version number into string form.
void transfer_side_control(const socket_ptr &sock, const simple_wml::node &cfg)
Let&#39;s a player owning a side give it to another player or observer.
Definition: game.cpp:524
std::string message
Definition: exceptions.hpp:31
std::shared_ptr< boost::asio::ip::tcp::socket > socket_ptr
Definition: server_base.hpp:28
player_connections player_connections_
Definition: server.hpp:111
void load_config()
Parse the server config into local variables.
Definition: server.cpp:432
simple_wml::document join_lobby_response_
Definition: server.hpp:167
void read_version(socket_ptr socket, std::shared_ptr< simple_wml::document > doc)
Definition: server.cpp:608
std::deque< connection_log > ip_log_
Definition: server.hpp:90
#define e
void handle_new_client(socket_ptr socket)
Definition: server.cpp:598
#define MP_NAME_RESERVED_ERROR
void ungban_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2737
static lg::log_domain log_server("server")
std::string process_command(std::string cmd, std::string issuer_name)
Process commands from admins and users.
Definition: server.cpp:1993
config read_config() const
Read the server config from file &#39;config_file_&#39;.
Definition: server.cpp:413
void copy_into(node &n) const
Definition: simple_wml.cpp:805
void metrics_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2155
static bool read_config(config &src, config &dst)
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:92
void lobbymsg_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2329
#define MP_NAME_AUTH_BAN_EMAIL_ERROR
void pm_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2264
filesystem::scoped_istream preprocess_file(const std::string &fname, preproc_map *defines)
void create_game(player_record &host, simple_wml::node &create_game)
Definition: server.cpp:1359
int get_severity() const
Definition: log.hpp:128
const std::string & get_ban_help() const
Definition: ban.hpp:167
static map_location::DIRECTION n
void abort_lan_server_timer()
Definition: server.cpp:312
std::size_t max_ip_log_size_
Definition: server.hpp:148
void mute_all_observers()
Definition: game.cpp:710
bool empty() const
Definition: config.cpp:884
version_info secure_version
Definition: server.cpp:88
void send_server_message(socket_ptr socket, const std::string &message)
Definition: server.cpp:1889
void set_termination_reason(const std::string &reason)
Definition: game.cpp:1903
socket_ptr ban_user(const simple_wml::node &ban, const socket_ptr &banner)
Ban and kick a user by name.
Definition: game.cpp:844
std::vector< std::string > disallowed_names_
Definition: server.hpp:138
#define DBG_SERVER
Definition: server.cpp:76
#define MP_NAME_AUTH_BAN_IP_ERROR
#define MP_INVALID_CHARS_IN_NAME_ERROR
simple_wml::document & level()
The full scenario data.
Definition: game.hpp:264
simple_wml::node * description() const
Definition: game.hpp:275
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)
Definition: server.cpp:151
int id() const
Definition: game.hpp:52