The Battle for Wesnoth  1.15.1+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"
41 #include "server/simple_wml.hpp"
42 #include "server/user_handler.hpp"
43 
44 #ifdef HAVE_MYSQLPP
46 #endif
47 
48 #include <boost/algorithm/string.hpp>
49 
50 #include <algorithm>
51 #include <cassert>
52 #include <cerrno>
53 #include <csignal>
54 #include <cstdlib>
55 #include <iomanip>
56 #include <iostream>
57 #include <map>
58 #include <queue>
59 #include <set>
60 #include <sstream>
61 #include <vector>
62 
63 static lg::log_domain log_server("server");
64 /**
65  * fatal and directly server related errors/warnings,
66  * ie not caused by erroneous client data
67  */
68 #define ERR_SERVER LOG_STREAM(err, log_server)
69 
70 /** clients send wrong/unexpected data */
71 #define WRN_SERVER LOG_STREAM(warn, log_server)
72 
73 /** normal events */
74 #define LOG_SERVER LOG_STREAM(info, log_server)
75 #define DBG_SERVER LOG_STREAM(debug, log_server)
76 
77 static lg::log_domain log_config("config");
78 #define ERR_CONFIG LOG_STREAM(err, log_config)
79 #define WRN_CONFIG LOG_STREAM(warn, log_config)
80 
82 
83 namespace wesnothd
84 {
85 // we take profiling info on every n requests
88 
89 static void make_add_diff(
90  const simple_wml::node& src, const char* gamelist, const char* type, simple_wml::document& out, int index = -1)
91 {
92  if(!out.child("gamelist_diff")) {
93  out.root().add_child("gamelist_diff");
94  }
95 
96  simple_wml::node* top = out.child("gamelist_diff");
97  if(gamelist) {
98  top = &top->add_child("change_child");
99  top->set_attr_int("index", 0);
100  top = &top->add_child("gamelist");
101  }
102 
103  simple_wml::node& insert = top->add_child("insert_child");
104  const simple_wml::node::child_list& children = src.children(type);
105  assert(!children.empty());
106 
107  if(index < 0) {
108  index = children.size() - 1;
109  }
110 
111  assert(index < static_cast<int>(children.size()));
112  insert.set_attr_int("index", index);
113 
114  children[index]->copy_into(insert.add_child(type));
115 }
116 
117 static bool make_delete_diff(const simple_wml::node& src,
118  const char* gamelist,
119  const char* type,
120  const simple_wml::node* remove,
122 {
123  if(!out.child("gamelist_diff")) {
124  out.root().add_child("gamelist_diff");
125  }
126 
127  simple_wml::node* top = out.child("gamelist_diff");
128  if(gamelist) {
129  top = &top->add_child("change_child");
130  top->set_attr_int("index", 0);
131  top = &top->add_child("gamelist");
132  }
133 
134  const simple_wml::node::child_list& children = src.children(type);
135  const auto itor = std::find(children.begin(), children.end(), remove);
136 
137  if(itor == children.end()) {
138  return false;
139  }
140 
141  const int index = std::distance(children.begin(), itor);
142 
143  simple_wml::node& del = top->add_child("delete_child");
144  del.set_attr_int("index", index);
145  del.add_child(type);
146 
147  return true;
148 }
149 
150 static bool make_change_diff(const simple_wml::node& src,
151  const char* gamelist,
152  const char* type,
153  const simple_wml::node* item,
155 {
156  if(!out.child("gamelist_diff")) {
157  out.root().add_child("gamelist_diff");
158  }
159 
160  simple_wml::node* top = out.child("gamelist_diff");
161  if(gamelist) {
162  top = &top->add_child("change_child");
163  top->set_attr_int("index", 0);
164  top = &top->add_child("gamelist");
165  }
166 
167  const simple_wml::node::child_list& children = src.children(type);
168  const auto itor = std::find(children.begin(), children.end(), item);
169 
170  if(itor == children.end()) {
171  return false;
172  }
173 
174  simple_wml::node& diff = *top;
175  simple_wml::node& del = diff.add_child("delete_child");
176 
177  const int index = std::distance(children.begin(), itor);
178 
179  del.set_attr_int("index", index);
180  del.add_child(type);
181 
182  // inserts will be processed first by the client, so insert at index+1,
183  // and then when the delete is processed we'll slide into the right position
184  simple_wml::node& insert = diff.add_child("insert_child");
185  insert.set_attr_int("index", index + 1);
186 
187  children[index]->copy_into(insert.add_child(type));
188  return true;
189 }
190 
191 static std::string player_status(const wesnothd::player_record& player)
192 {
193  std::ostringstream out;
194  // const network::connection_stats& stats = network::get_connection_stats(pl->first);
195  // const int time_connected = stats.time_connected / 1000;
196  // const int seconds = time_connected % 60;
197  // const int minutes = (time_connected / 60) % 60;
198  // const int hours = time_connected / (60 * 60);
199  out << "'" << player.name() << "' @ " << client_address(player.socket());
200  // << " connected for " << std::setw(2) << hours << ":" << std::setw(2) << minutes << ":" << std::setw(2) <<
201  //seconds
202  // << " sent " << stats.bytes_sent << " bytes, received "
203  // << stats.bytes_received << " bytes";
204  return out.str();
205 }
206 
207 const std::string denied_msg = "You're not allowed to execute this command.";
208 const std::string help_msg =
209  "Available commands are: adminmsg <msg>,"
210  " ban <mask> <time> <reason>, bans [deleted] [<ipmask>], clones,"
211  " dul|deny_unregistered_login [yes|no], kick <mask> [<reason>],"
212  " k[ick]ban <mask> <time> <reason>, help, games, metrics,"
213  " netstats [all], [lobby]msg <message>, motd [<message>],"
214  " pm|privatemsg <nickname> <message>, requests, sample, searchlog <mask>,"
215  " signout, stats, status [<mask>], stopgame <nick> [<reason>], unban <ipmask>\n"
216  "Specific strings (those not in between <> like the command names)"
217  " are case insensitive.";
218 
219 server::server(int port,
220  bool keep_alive,
221  const std::string& config_file,
222  std::size_t /*min_threads*/,
223  std::size_t /*max_threads*/)
224  : server_base(port, keep_alive)
225  , ban_manager_()
226  , ip_log_()
227  , failed_logins_()
228  , user_handler_(nullptr)
229 #ifndef _WIN32
230  , input_path_()
231 #endif
232  , uuid_("")
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  , deny_unregistered_login_(false)
250  , save_replays_(false)
251  , replay_save_path_()
252  , allow_remote_shutdown_(false)
253  , tor_ip_list_()
254  , failed_login_limit_()
255  , failed_login_ban_()
256  , failed_login_buffer_size_()
257  , version_query_response_("[version]\n[/version]\n", simple_wml::INIT_COMPRESSED)
258  , login_response_("[mustlogin]\n[/mustlogin]\n", simple_wml::INIT_COMPRESSED)
259  , join_lobby_response_("[join_lobby]\n[/join_lobby]\n", simple_wml::INIT_COMPRESSED)
260  , games_and_users_list_("[gamelist]\n[/gamelist]\n", simple_wml::INIT_STATIC)
261  , metrics_()
262  , dump_stats_timer_(io_service_)
263  , cmd_handlers_()
264  , timer_(io_service_)
265  , lan_server_timer_(io_service_)
266 {
267  setup_handlers();
268  load_config();
269  ban_manager_.read();
270 
271  start_server();
272 
274 }
275 
276 #ifndef _WIN32
277 void server::handle_sighup(const boost::system::error_code& error, int)
278 {
279  assert(!error);
280 
281  WRN_SERVER << "SIGHUP caught, reloading config\n";
282 
283  cfg_ = read_config();
284  load_config();
285 
286  sighup_.async_wait(std::bind(&server::handle_sighup, this, _1, _2));
287 }
288 #endif
289 
290 void server::handle_graceful_timeout(const boost::system::error_code& error)
291 {
292  assert(!error);
293 
294  if(games().empty()) {
295  process_command("msg All games ended. Shutting down now. Reconnect to the new server instance.", "system");
296  throw server_shutdown("graceful shutdown timeout");
297  } else {
298  timer_.expires_from_now(boost::posix_time::seconds(1));
299  timer_.async_wait(std::bind(&server::handle_graceful_timeout, this, _1));
300  }
301 }
302 
304 {
305  lan_server_timer_.expires_from_now(std::chrono::seconds(lan_server_));
306  lan_server_timer_.async_wait([this](const boost::system::error_code& ec) { handle_lan_server_shutdown(ec); });
307 }
308 
310 {
311  lan_server_timer_.cancel();
312 }
313 
314 void server::handle_lan_server_shutdown(const boost::system::error_code& error)
315 {
316  if(error)
317  return;
318 
319  throw server_shutdown("lan server shutdown");
320 }
321 
323 {
324 #ifndef _WIN32
325  const int res = mkfifo(input_path_.c_str(), 0660);
326  if(res != 0 && errno != EEXIST) {
327  ERR_SERVER << "could not make fifo at '" << input_path_ << "' (" << strerror(errno) << ")\n";
328  return;
329  }
330  int fifo = open(input_path_.c_str(), O_RDWR | O_NONBLOCK);
331  input_.assign(fifo);
332  LOG_SERVER << "opened fifo at '" << input_path_ << "'. Server commands may be written to this file.\n";
333  read_from_fifo();
334 #endif
335 }
336 
337 #ifndef _WIN32
338 
339 void server::handle_read_from_fifo(const boost::system::error_code& error, std::size_t)
340 {
341  if(error) {
342  std::cout << error.message() << std::endl;
343  return;
344  }
345 
346  std::istream is(&admin_cmd_);
347  std::string cmd;
348  std::getline(is, cmd);
349 
350  LOG_SERVER << "Admin Command: type: " << cmd << "\n";
351 
352  const std::string res = process_command(cmd, "*socket*");
353 
354  // Only mark the response if we fake the issuer (i.e. command comes from IRC or so)
355  if(cmd.at(0) == '+') {
356  LOG_SERVER << "[admin_command_response]\n"
357  << res << "\n"
358  << "[/admin_command_response]\n";
359  } else {
360  LOG_SERVER << res << "\n";
361  }
362 
363  read_from_fifo();
364 }
365 
366 #endif
367 
369 {
370 #define SETUP_HANDLER(name, function) \
371  cmd_handlers_[name] = std::bind(function, this, \
372  std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4);
373 
388  SETUP_HANDLER("privatemsg", &server::pm_handler);
390  SETUP_HANDLER("lobbymsg", &server::msg_handler);
405  SETUP_HANDLER("deny_unregistered_login", &server::dul_handler);
406  SETUP_HANDLER("stopgame", &server::stopgame);
407 
408 #undef SETUP_HANDLER
409 }
410 
412 {
413  config configuration;
414 
415  if(config_file_.empty()) {
416  return configuration;
417  }
418 
419  try {
421  read(configuration, *stream);
422  LOG_SERVER << "Server configuration from file: '" << config_file_ << "' read.\n";
423  } catch(const config::error& e) {
424  ERR_CONFIG << "ERROR: Could not read configuration file: '" << config_file_ << "': '" << e.message << "'.\n";
425  }
426 
427  return configuration;
428 }
429 
431 {
432 #ifndef _WIN32
433 #ifndef FIFODIR
434 #warning No FIFODIR set
435 #define FIFODIR "/var/run/wesnothd"
436 #endif
437  const std::string fifo_path
438  = (cfg_["fifo_path"].empty() ? std::string(FIFODIR) + "/socket" : std::string(cfg_["fifo_path"]));
439  // Reset (replace) the input stream only if the FIFO path changed.
440  if(fifo_path != input_path_) {
441  input_.close();
442  input_path_ = fifo_path;
443  setup_fifo();
444  }
445 #endif
446 
447  save_replays_ = cfg_["save_replays"].to_bool();
448  replay_save_path_ = cfg_["replay_save_path"].str();
449 
450  tor_ip_list_ = utils::split(cfg_["tor_ip_list_path"].empty()
451  ? ""
452  : filesystem::read_file(cfg_["tor_ip_list_path"]), '\n');
453 
454  admin_passwd_ = cfg_["passwd"].str();
455  motd_ = cfg_["motd"].str();
456  lan_server_ = cfg_["lan_server"].to_time_t(0);
457 
458  deny_unregistered_login_ = cfg_["deny_unregistered_login"].to_bool();
459 
460  allow_remote_shutdown_ = cfg_["allow_remote_shutdown"].to_bool();
461 
462  disallowed_names_.clear();
463  if(cfg_["disallow_names"].empty()) {
464  disallowed_names_.push_back("*admin*");
465  disallowed_names_.push_back("*admln*");
466  disallowed_names_.push_back("*server*");
467  disallowed_names_.push_back("player");
468  disallowed_names_.push_back("network");
469  disallowed_names_.push_back("human");
470  disallowed_names_.push_back("computer");
471  disallowed_names_.push_back("ai");
472  disallowed_names_.push_back("ai?");
473  disallowed_names_.push_back("*moderator*");
474  } else {
475  disallowed_names_ = utils::split(cfg_["disallow_names"]);
476  }
477 
478  default_max_messages_ = cfg_["max_messages"].to_int(4);
479  default_time_period_ = cfg_["messages_time_period"].to_int(10);
480  concurrent_connections_ = cfg_["connections_allowed"].to_int(5);
481  max_ip_log_size_ = cfg_["max_ip_log_size"].to_int(500);
482 
483  failed_login_limit_ = cfg_["failed_logins_limit"].to_int(10);
484  failed_login_ban_ = cfg_["failed_logins_ban"].to_int(3600);
485  failed_login_buffer_size_ = cfg_["failed_logins_buffer_size"].to_int(500);
486 
487  // Example config line:
488  // restart_command="./wesnothd-debug -d -c ~/.wesnoth1.5/server.cfg"
489  // remember to make new one as a daemon or it will block old one
490  restart_command = cfg_["restart_command"].str();
491 
492  recommended_version_ = cfg_["recommended_version"].str();
493  accepted_versions_.clear();
494  const std::string& versions = cfg_["versions_accepted"];
495  if(versions.empty() == false) {
496  accepted_versions_ = utils::split(versions);
497  } else {
499  accepted_versions_.push_back("test");
500  }
501 
502  redirected_versions_.clear();
503  for(const config& redirect : cfg_.child_range("redirect")) {
504  for(const std::string& version : utils::split(redirect["version"])) {
505  redirected_versions_[version] = redirect;
506  }
507  }
508 
509  proxy_versions_.clear();
510  for(const config& proxy : cfg_.child_range("proxy")) {
511  for(const std::string& version : utils::split(proxy["version"])) {
512  proxy_versions_[version] = proxy;
513  }
514  }
515 
517 
518  // If there is a [user_handler] tag in the config file
519  // allow nick registration, otherwise we set user_handler_
520  // to nullptr. Thus we must check user_handler_ for not being
521  // nullptr every time we want to use it.
522  user_handler_.reset();
523 
524 #ifdef HAVE_MYSQLPP
525  if(const config& user_handler = cfg_.child("user_handler")) {
526  user_handler_.reset(new fuh(user_handler));
527  uuid_ = user_handler_->get_uuid();
528  }
529 #endif
530 }
531 
532 bool server::ip_exceeds_connection_limit(const std::string& ip) const
533 {
534  if(concurrent_connections_ == 0) {
535  return false;
536  }
537 
538  std::size_t connections = 0;
539  for(const auto& player : player_connections_) {
540  if(client_address(player.socket()) == ip) {
541  ++connections;
542  }
543  }
544 
545  return connections >= concurrent_connections_;
546 }
547 
548 std::string server::is_ip_banned(const std::string& ip)
549 {
550  if(!tor_ip_list_.empty()) {
551  if(find(tor_ip_list_.begin(), tor_ip_list_.end(), ip) != tor_ip_list_.end()) {
552  return "TOR IP";
553  }
554  }
555 
556  return ban_manager_.is_ip_banned(ip);
557 }
558 
560 {
561  dump_stats_timer_.expires_from_now(std::chrono::minutes(5));
562  dump_stats_timer_.async_wait([this](const boost::system::error_code& ec) { dump_stats(ec); });
563 }
564 
565 void server::dump_stats(const boost::system::error_code& ec)
566 {
567  if(ec) {
568  ERR_SERVER << "Error waiting for timer: " << ec.message() << "\n";
569  return;
570  }
571  LOG_SERVER << "Statistics:"
572  << "\tnumber_of_games = " << games().size() << "\tnumber_of_users = " << player_connections_.size()
573  << "\n";
575 }
576 
578 {
579  async_send_doc(socket, version_query_response_, std::bind(&server::handle_version, this, _1));
580 }
581 
583 {
584  async_receive_doc(socket, std::bind(&server::read_version, this, _1, _2));
585 }
586 
587 void server::read_version(socket_ptr socket, std::shared_ptr<simple_wml::document> doc)
588 {
589  if(const simple_wml::node* const version = doc->child("version")) {
590  const simple_wml::string_span& version_str_span = (*version)["version"];
591  const std::string version_str(version_str_span.begin(), version_str_span.end());
592 
593  // Check if it is an accepted version.
594  auto accepted_it = std::find_if(accepted_versions_.begin(), accepted_versions_.end(),
595  std::bind(&utils::wildcard_string_match, version_str, _1));
596 
597  if(accepted_it != accepted_versions_.end()) {
598  LOG_SERVER << client_address(socket) << "\tplayer joined using accepted version " << version_str
599  << ":\ttelling them to log in.\n";
600  async_send_doc(socket, login_response_, std::bind(&server::login, this, _1, version_str));
601  return;
602  }
603 
604  simple_wml::document response;
605 
606  // Check if it is a redirected version
607  for(const auto& redirect_version : redirected_versions_) {
608  if(utils::wildcard_string_match(version_str, redirect_version.first)) {
609  LOG_SERVER << client_address(socket) << "\tplayer joined using version " << version_str
610  << ":\tredirecting them to " << redirect_version.second["host"] << ":"
611  << redirect_version.second["port"] << "\n";
612 
613  simple_wml::node& redirect = response.root().add_child("redirect");
614  for(const auto& attr : redirect_version.second.attribute_range()) {
615  redirect.set_attr_dup(attr.first.c_str(), attr.second.str().c_str());
616  }
617 
618  send_to_player(socket, response);
619  return;
620  }
621  }
622 
623  LOG_SERVER << client_address(socket) << "\tplayer joined using unknown version " << version_str
624  << ":\trejecting them\n";
625 
626  // For compatibility with older clients
627  response.set_attr("version", accepted_versions_.begin()->c_str());
628 
629  simple_wml::node& reject = response.root().add_child("reject");
630  reject.set_attr_dup("accepted_versions", utils::join(accepted_versions_).c_str());
631  send_to_player(socket, response);
632  } else {
633  LOG_SERVER << client_address(socket) << "\tclient didn't send its version: rejecting\n";
634  }
635 }
636 
637 void server::login(socket_ptr socket, std::string version)
638 {
639  async_receive_doc(socket, std::bind(&server::handle_login, this, _1, _2, version));
640 }
641 
642 void server::handle_login(socket_ptr socket, std::shared_ptr<simple_wml::document> doc, std::string version)
643 {
644  if(const simple_wml::node* const login = doc->child("login")) {
645  if(!is_login_allowed(socket, login, version)) {
646  server::login(socket, version); // keep reading logins from client until we get a successful one
647  }
648  } else {
649  async_send_error(socket, "You must login first.", MP_MUST_LOGIN);
650  }
651 }
652 
653 bool server::is_login_allowed(socket_ptr socket, const simple_wml::node* const login, const std::string& version)
654 {
655  // Check if the username is valid (all alpha-numeric plus underscore and hyphen)
656  std::string username = (*login)["username"].to_string();
657 
658  if(!utils::isvalid_username(username)) {
659  async_send_error(socket,
660  "The nickname '" + username + "' contains invalid "
661  "characters. Only alpha-numeric characters, underscores and hyphens are allowed.",
663  );
664 
665  return false;
666  }
667 
668  if(username.size() > 20) {
669  async_send_error(socket, "The nickname '" + username + "' is too long. Nicks must be 20 characters or less.",
671  return false;
672  }
673 
674  // Check if the username is allowed.
675  for(const std::string d : disallowed_names_) {
677  async_send_error(socket, "The nickname '" + username + "' is reserved and cannot be used by players",
679  return false;
680  }
681  }
682 
683  // Check the username isn't already taken
684  auto p = player_connections_.get<name_t>().find(username);
685  bool name_taken = p != player_connections_.get<name_t>().end();
686 
687  // Check for password
688 
689  bool registered;
690  if(!authenticate(socket, username, (*login)["password"].to_string(), version, name_taken, registered))
691  return true; // it's a failed login but we don't want to call server::login again
692  // because send_password_request() will handle the next network write and read instead
693 
694  // If we disallow unregistered users and this user is not registered send an error
695  if(user_handler_ && !registered && deny_unregistered_login_) {
696  async_send_error(socket,
697  "The nickname '" + username + "' is not registered. This server disallows unregistered nicknames.",
699  );
700 
701  return false;
702  }
703 
704  const bool is_moderator = user_handler_ && user_handler_->user_is_moderator(username);
705  user_handler::ban_info auth_ban;
706 
707  if(user_handler_) {
708  auth_ban = user_handler_->user_is_banned(username, client_address(socket));
709  }
710 
711  if(auth_ban.type) {
712  std::string ban_type_desc;
713  std::string ban_reason;
714  const char* msg_numeric;
715  std::string ban_duration = std::to_string(auth_ban.duration);
716 
717  switch(auth_ban.type) {
719  ban_type_desc = "account";
720  msg_numeric = MP_NAME_AUTH_BAN_USER_ERROR;
721  ban_reason = "a ban has been issued on your user account.";
722  break;
724  ban_type_desc = "IP address";
725  msg_numeric = MP_NAME_AUTH_BAN_IP_ERROR;
726  ban_reason = "a ban has been issued on your IP address.";
727  break;
729  ban_type_desc = "email address";
730  msg_numeric = MP_NAME_AUTH_BAN_EMAIL_ERROR;
731  ban_reason = "a ban has been issued on your email address.";
732  break;
733  default:
734  ban_type_desc = "<unknown ban type>";
735  msg_numeric = "";
736  ban_reason = ban_type_desc;
737  }
738 
739  ban_reason += " (" + ban_duration + ")";
740 
741  if(!is_moderator) {
742  LOG_SERVER << client_address(socket) << "\t" << username << "\tis banned by user_handler (" << ban_type_desc
743  << ")\n";
744  if(auth_ban.duration) {
745  // Temporary ban
746  async_send_error(socket, "You are banned from this server: " + ban_reason, msg_numeric, {{"duration", ban_duration}});
747  } else {
748  // Permanent ban
749  async_send_error(socket, "You are banned from this server: " + ban_reason, msg_numeric);
750  }
751  return false;
752  } else {
753  LOG_SERVER << client_address(socket) << "\t" << username << "\tis banned by user_handler (" << ban_type_desc
754  << "), " << "ignoring due to moderator flag\n";
755  }
756  }
757 
758  if(name_taken) {
759  if(registered) {
760  // If there is already a client using this username kick it
761  process_command("kick " + p->info().name() + " autokick by registered user", username);
762  } else {
763  async_send_error(socket, "The nickname '" + username + "' is already taken.", MP_NAME_TAKEN_ERROR);
764  return false;
765  }
766  }
767 
768  async_send_doc(socket, join_lobby_response_, [this, username, registered, version](socket_ptr socket) {
769  simple_wml::node& player_cfg = games_and_users_list_.root().add_child("user");
771  username,
772  player_cfg,
773  registered,
774  version,
777  user_handler_ && user_handler_->user_is_moderator(username)
778  )
779  );
780  });
781 
782  LOG_SERVER << client_address(socket) << "\t" << username << "\thas logged on"
783  << (registered ? " to a registered account" : "") << "\n";
784 
785  std::shared_ptr<game> last_sent;
786  for(const auto& record : player_connections_.get<game_t>()) {
787  auto g_ptr { record.get_game() };
788  if(g_ptr != last_sent) {
789  // Note: This string is parsed by the client to identify lobby join messages!
790  g_ptr->send_server_message_to_all(username + " has logged into the lobby");
791  last_sent = g_ptr;
792  }
793  }
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.type) {
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  // A user requested a list of which details can be set
1199  if(nickserv.child("info")) {
1200  try {
1201  std::string res = user_handler_->user_info((*nickserv.child("info"))["name"].to_string());
1202  send_server_message(socket, res);
1203  } catch(const user_handler::error& e) {
1204  send_server_message(socket,
1205  "There was an error looking up the details of the user '"
1206  + (*nickserv.child("info"))["name"].to_string() + "'. "
1207  + " The error message was: " + e.message
1208  );
1209  }
1210 
1211  return;
1212  }
1213 }
1214 
1216 {
1217  auto user = player_connections_.find(socket);
1218  if(user->info().is_message_flooding()) {
1219  send_server_message(socket,
1220  "Warning: you are sending too many messages too fast. Your message has not been relayed.");
1221  return;
1222  }
1223 
1224  simple_wml::document relay_message;
1225  message.set_attr_dup("sender", user->name().c_str());
1226 
1227  simple_wml::node& trunc_message = relay_message.root().add_child("message");
1228  message.copy_into(trunc_message);
1229 
1230  const simple_wml::string_span& msg = trunc_message["message"];
1231  chat_message::truncate_message(msg, trunc_message);
1232 
1233  if(msg.size() >= 3 && simple_wml::string_span(msg.begin(), 4) == "/me ") {
1234  LOG_SERVER << client_address(socket) << "\t<" << user->name()
1235  << simple_wml::string_span(msg.begin() + 3, msg.size() - 3) << ">\n";
1236  } else {
1237  LOG_SERVER << client_address(socket) << "\t<" << user->name() << "> " << msg << "\n";
1238  }
1239 
1240  send_to_lobby(relay_message, socket);
1241 }
1242 
1244 {
1245  if(graceful_restart) {
1246  static simple_wml::document leave_game_doc("[leave_game]\n[/leave_game]\n", simple_wml::INIT_COMPRESSED);
1247  send_to_player(socket, leave_game_doc);
1248 
1249  send_server_message(socket,
1250  "This server is shutting down. You aren't allowed to make new games. Please "
1251  "reconnect to the new server.");
1252 
1254  return;
1255  }
1256 
1257  player_connections_.modify(
1258  player_connections_.find(socket), std::bind(&server::create_game, this, _1, std::ref(create_game)));
1259 
1260  return;
1261 }
1262 
1264 {
1265  const std::string game_name = create_game["name"].to_string();
1266  const std::string game_password = create_game["password"].to_string();
1267  const std::string initial_bans = create_game["ignored"].to_string();
1268 
1269  DBG_SERVER << client_address(host_record.socket()) << "\t" << host_record.info().name()
1270  << "\tcreates a new game: \"" << game_name << "\".\n";
1271 
1272  // Create the new game, remove the player from the lobby
1273  // and set the player as the host/owner.
1274  host_record.get_game().reset(
1275  new wesnothd::game(player_connections_, host_record.socket(), game_name, save_replays_, replay_save_path_),
1276  std::bind(&server::cleanup_game, this, _1)
1277  );
1278 
1279  wesnothd::game& g = *host_record.get_game();
1280 
1281  DBG_SERVER << "initial bans: " << initial_bans << "\n";
1282  if(initial_bans != "") {
1283  g.set_name_bans(utils::split(initial_bans,','));
1284  }
1285 
1286  if(game_password.empty() == false) {
1287  g.set_password(game_password);
1288  }
1289 
1290  create_game.copy_into(g.level().root());
1291 
1292  if(user_handler_) {
1293  user_handler_->db_insert_game_info(uuid_, g.id(), game_config::wesnoth_version.str(), g.name());
1294  }
1295 }
1296 
1298 {
1300 
1301  if(user_handler_){
1302  user_handler_->db_update_game_end(uuid_, game_ptr->id(), game_ptr->get_replay_filename());
1303  }
1304 
1305  simple_wml::node* const gamelist = games_and_users_list_.child("gamelist");
1306  assert(gamelist != nullptr);
1307 
1308  // Send a diff of the gamelist with the game deleted to players in the lobby
1309  simple_wml::document diff;
1310  if(make_delete_diff(*gamelist, "gamelist", "game", game_ptr->description(), diff)) {
1311  send_to_lobby(diff);
1312  }
1313 
1314  // Delete the game from the games_and_users_list_.
1315  const simple_wml::node::child_list& games = gamelist->children("game");
1316  const auto g = std::find(games.begin(), games.end(), game_ptr->description());
1317 
1318  if(g != games.end()) {
1319  const std::size_t index = std::distance(games.begin(), g);
1320  gamelist->remove_child("game", index);
1321  } else {
1322  // Can happen when the game ends before the scenario was transferred.
1323  LOG_SERVER << "Could not find game (" << game_ptr->id() << ") to delete in games_and_users_list_.\n";
1324  }
1325 
1326  delete game_ptr;
1327 }
1328 
1330 {
1331  const bool observer = join.attr("observe").to_bool();
1332  const std::string& password = join["password"].to_string();
1333  int game_id = join["id"].to_int();
1334 
1335  auto g_iter = player_connections_.get<game_t>().find(game_id);
1336 
1337  std::shared_ptr<game> g;
1338  if(g_iter != player_connections_.get<game_t>().end()) {
1339  g = g_iter->get_game();
1340  }
1341 
1342  static simple_wml::document leave_game_doc("[leave_game]\n[/leave_game]\n", simple_wml::INIT_COMPRESSED);
1343  if(!g) {
1344  WRN_SERVER << client_address(socket) << "\t" << player_connections_.find(socket)->info().name()
1345  << "\tattempted to join unknown game:\t" << game_id << ".\n";
1346  async_send_doc(socket, leave_game_doc);
1347  send_server_message(socket, "Attempt to join unknown game.");
1349  return;
1350  } else if(!g->level_init()) {
1351  WRN_SERVER << client_address(socket) << "\t" << player_connections_.find(socket)->info().name()
1352  << "\tattempted to join uninitialized game:\t\"" << g->name() << "\" (" << game_id << ").\n";
1353  async_send_doc(socket, leave_game_doc);
1354  send_server_message(socket, "Attempt to join an uninitialized game.");
1356  return;
1357  } else if(player_connections_.find(socket)->info().is_moderator()) {
1358  // Admins are always allowed to join.
1359  } else if(g->registered_users_only() && !player_connections_.find(socket)->info().registered()) {
1360  async_send_doc(socket, leave_game_doc);
1361  send_server_message(socket, "Only registered users are allowed to join this game.");
1363  return;
1364  } else if(g->player_is_banned(socket, player_connections_.find(socket)->info().name())) {
1365  DBG_SERVER << client_address(socket)
1366  << "\tReject banned player: " << player_connections_.find(socket)->info().name()
1367  << "\tfrom game:\t\"" << g->name() << "\" (" << game_id << ").\n";
1368  async_send_doc(socket, leave_game_doc);
1369  send_server_message(socket, "You are banned from this game.");
1371  return;
1372  } else if(!g->password_matches(password)) {
1373  WRN_SERVER << client_address(socket) << "\t" << player_connections_.find(socket)->info().name()
1374  << "\tattempted to join game:\t\"" << g->name() << "\" (" << game_id << ") with bad password\n";
1375  async_send_doc(socket, leave_game_doc);
1376  send_server_message(socket, "Incorrect password.");
1378  return;
1379  }
1380 
1381  bool joined = g->add_player(socket, observer);
1382  if(!joined) {
1383  WRN_SERVER << client_address(socket) << "\t" << player_connections_.find(socket)->info().name()
1384  << "\tattempted to observe game:\t\"" << g->name() << "\" (" << game_id
1385  << ") which doesn't allow observers.\n";
1386  async_send_doc(socket, leave_game_doc);
1387 
1388  send_server_message(socket,
1389  "Attempt to observe a game that doesn't allow observers. (You probably joined the "
1390  "game shortly after it filled up.)");
1391 
1393  return;
1394  }
1395 
1396  player_connections_.modify(player_connections_.find(socket),
1397  std::bind(&player_record::set_game, _1, player_connections_.get<game_t>().find(game_id)->get_game()));
1398 
1399  g->describe_slots();
1400 
1401  // send notification of changes to the game and user
1402  simple_wml::document diff;
1403  bool diff1 = make_change_diff(*games_and_users_list_.child("gamelist"), "gamelist", "game", g->description(), diff);
1404  bool diff2 = make_change_diff(games_and_users_list_.root(), nullptr, "user",
1405  player_connections_.find(socket)->info().config_address(), diff);
1406 
1407  if(diff1 || diff2) {
1408  send_to_lobby(diff);
1409  }
1410 }
1411 
1412 void server::handle_player_in_game(socket_ptr socket, std::shared_ptr<simple_wml::document> doc)
1413 {
1414  DBG_SERVER << "in process_data_game...\n";
1415 
1416  auto p = player_connections_.find(socket);
1417  wesnothd::player& player = p->info();
1418 
1419  game& g = *(p->get_game());
1420  std::weak_ptr<game> g_ptr{p->get_game()};
1421 
1422  simple_wml::document& data = *doc;
1423 
1424  // If this is data describing the level for a game.
1425  if(doc->child("snapshot") || doc->child("scenario")) {
1426  if(!g.is_owner(socket)) {
1427  return;
1428  }
1429 
1430  // If this game is having its level data initialized
1431  // for the first time, and is ready for players to join.
1432  // We should currently have a summary of the game in g.level().
1433  // We want to move this summary to the games_and_users_list_, and
1434  // place a pointer to that summary in the game's description.
1435  // g.level() should then receive the full data for the game.
1436  if(!g.level_init()) {
1437  LOG_SERVER << client_address(socket) << "\t" << player.name() << "\tcreated game:\t\"" << g.name() << "\" ("
1438  << g.id() << ").\n";
1439  // Update our config object which describes the open games,
1440  // and save a pointer to the description in the new game.
1441  simple_wml::node* const gamelist = games_and_users_list_.child("gamelist");
1442  assert(gamelist != nullptr);
1443 
1444  simple_wml::node& desc = gamelist->add_child("game");
1445  g.level().root().copy_into(desc);
1446 
1447  if(const simple_wml::node* m = doc->child("multiplayer")) {
1448  m->copy_into(desc);
1449  } else {
1450  WRN_SERVER << client_address(socket) << "\t" << player.name() << "\tsent scenario data in game:\t\""
1451  << g.name() << "\" (" << g.id() << ") without a 'multiplayer' child.\n";
1452  // Set the description so it can be removed in delete_game().
1453  g.set_description(&desc);
1454  delete_game(g.id());
1455 
1456  send_server_message(socket,
1457  "The scenario data is missing the [multiplayer] tag which contains the "
1458  "game settings. Game aborted.");
1459  return;
1460  }
1461 
1462  g.set_description(&desc);
1463  desc.set_attr_dup("id", lexical_cast<std::string>(g.id()).c_str());
1464  } else {
1465  WRN_SERVER << client_address(socket) << "\t" << player.name() << "\tsent scenario data in game:\t\""
1466  << g.name() << "\" (" << g.id() << ") although it's already initialized.\n";
1467  return;
1468  }
1469 
1470  assert(games_and_users_list_.child("gamelist")->children("game").empty() == false);
1471 
1472  simple_wml::node& desc = *g.description();
1473 
1474  // Update the game's description.
1475  // If there is no shroud, then tell players in the lobby
1476  // what the map looks like
1478  // fixme: the hanlder of [store_next_scenario] below searches for 'mp_shroud' in [scenario]
1479  // at least of the these cosed is likely wrong.
1480  if(!data["mp_shroud"].to_bool()) {
1481  desc.set_attr_dup("map_data", s["map_data"]);
1482  }
1483 
1484  if(const simple_wml::node* e = data.child("era")) {
1485  if(!e->attr("require_era").to_bool(true)) {
1486  desc.set_attr("require_era", "no");
1487  }
1488  }
1489 
1490  if(s["require_scenario"].to_bool(false)) {
1491  desc.set_attr("require_scenario", "yes");
1492  }
1493 
1494  const simple_wml::node::child_list& mlist = data.children("modification");
1495  for(const simple_wml::node* m : mlist) {
1496  desc.add_child_at("modification", 0);
1497  desc.child("modification")->set_attr_dup("id", m->attr("id"));
1498  desc.child("modification")->set_attr_dup("name", m->attr("name"));
1499  desc.child("modification")->set_attr_dup("addon_id", m->attr("addon_id"));
1500 
1501  if(m->attr("require_modification").to_bool(false)) {
1502  desc.child("modification")->set_attr("require_modification", "yes");
1503  }
1504  }
1505 
1506  // Record the full scenario in g.level()
1507  g.level().swap(data);
1508 
1509  // The host already put himself in the scenario so we just need
1510  // to update_side_data().
1511  // g.take_side(sock);
1512  g.update_side_data();
1513  g.describe_slots();
1514 
1515  // Send the update of the game description to the lobby.
1516  simple_wml::document diff;
1517  make_add_diff(*games_and_users_list_.child("gamelist"), "gamelist", "game", diff);
1518  make_change_diff(games_and_users_list_.root(), nullptr, "user", player_connections_.find(socket)->info().config_address(), diff);
1519 
1520  send_to_lobby(diff);
1521 
1522  /** @todo FIXME: Why not save the level data in the history_? */
1523  return;
1524  // Everything below should only be processed if the game is already initialized.
1525  } else if(!g.level_init()) {
1526  WRN_SERVER << client_address(socket) << "\tReceived unknown data from: " << player.name()
1527  << " (socket:" << socket << ") while the scenario wasn't yet initialized.\n"
1528  << data.output();
1529  return;
1530  // If the host is sending the next scenario data.
1531  } else if(const simple_wml::node* scenario = data.child("store_next_scenario")) {
1532  if(!g.is_owner(socket)) {
1533  return;
1534  }
1535 
1536  if(!g.level_init()) {
1537  WRN_SERVER << client_address(socket) << "\tWarning: " << player.name()
1538  << "\tsent [store_next_scenario] in game:\t\"" << g.name() << "\" (" << g.id()
1539  << ") while the scenario is not yet initialized.";
1540  return;
1541  }
1542 
1543  g.save_replay();
1544 
1545  g.new_scenario(socket);
1547 
1548  // Record the full scenario in g.level()
1549  g.level().clear();
1550  scenario->copy_into(g.level().root());
1551 
1552  if(g.description() == nullptr) {
1553  ERR_SERVER << client_address(socket) << "\tERROR: \"" << g.name() << "\" (" << g.id()
1554  << ") is initialized but has no description_.\n";
1555  return;
1556  }
1557 
1558  simple_wml::node& desc = *g.description();
1559 
1560  // Update the game's description.
1561  if(const simple_wml::node* m = scenario->child("multiplayer")) {
1562  m->copy_into(desc);
1563  } else {
1564  WRN_SERVER << client_address(socket) << "\t" << player.name() << "\tsent scenario data in game:\t\""
1565  << g.name() << "\" (" << g.id() << ") without a 'multiplayer' child.\n";
1566 
1567  delete_game(g.id());
1568 
1569  send_server_message(socket,
1570  "The scenario data is missing the [multiplayer] tag which contains the game "
1571  "settings. Game aborted.");
1572  return;
1573  }
1574 
1575  // If there is no shroud, then tell players in the lobby
1576  // what the map looks like.
1578  desc.set_attr_dup("map_data", s["mp_shroud"].to_bool() ? "" : s["map_data"]);
1579 
1580  if(const simple_wml::node* e = data.child("era")) {
1581  if(!e->attr("require_era").to_bool(true)) {
1582  desc.set_attr("require_era", "no");
1583  }
1584  }
1585 
1586  if(s["require_scenario"].to_bool(false)) {
1587  desc.set_attr("require_scenario", "yes");
1588  }
1589 
1590  // Tell everyone that the next scenario data is available.
1591  static simple_wml::document notify_next_scenario(
1592  "[notify_next_scenario]\n[/notify_next_scenario]\n", simple_wml::INIT_COMPRESSED);
1593  g.send_data(notify_next_scenario, socket);
1594 
1595  // Send the update of the game description to the lobby.
1597  return;
1598  // A mp client sends a request for the next scenario of a mp campaign.
1599  } else if(data.child("load_next_scenario")) {
1600  g.load_next_scenario(socket);
1601  return;
1602  } else if(data.child("start_game")) {
1603  if(!g.is_owner(socket)) {
1604  return;
1605  }
1606 
1607  // perform controller tweaks, assigning sides as human for their owners etc.
1609 
1610  // Send notification of the game starting immediately.
1611  // g.start_game() will send data that assumes
1612  // the [start_game] message has been sent
1613  g.send_data(data, socket);
1614  g.start_game(socket);
1615 
1616  if(user_handler_) {
1617  const simple_wml::node& multiplayer = *g.level().root().child("multiplayer");
1618  user_handler_->db_update_game_start(uuid_, g.id(), multiplayer["mp_scenario"].to_string(), multiplayer["mp_era"].to_string(), g.is_reload());
1619 
1620  const simple_wml::node::child_list& sides = g.get_sides_list();
1621  for(unsigned side_index = 0; side_index < sides.size(); ++side_index) {
1622  const simple_wml::node& side = *sides[side_index];
1623  user_handler_->db_insert_game_player_info(uuid_, g.id(), side["player_id"].to_string(), side["side"].to_int(), side["is_host"].to_bool(), side["faction"].to_string());
1624  }
1625 
1626  const std::string mods = multiplayer["active_mods"].to_string();
1627  if(mods != "") {
1628  for(const std::string mod : utils::split(mods, ',')){
1629  user_handler_->db_insert_modification_info(uuid_, g.id(), mod);
1630  }
1631  }
1632  }
1633 
1634  // update the game having changed in the lobby
1636  return;
1637  } else if(data.child("leave_game")) {
1638  if(g.remove_player(socket)) {
1639  delete_game(g.id());
1640  } else {
1641  auto description = g.description();
1642 
1643  player_connections_.modify(player_connections_.find(socket), std::bind(&player_record::enter_lobby, _1));
1644  if(!g_ptr.expired()) {
1645  g.describe_slots();
1646  }
1647 
1648  // Send all other players in the lobby the update to the gamelist.
1649  simple_wml::document diff;
1650  bool diff1 = make_change_diff(*games_and_users_list_.child("gamelist"), "gamelist", "game", description, diff);
1651  bool diff2 = make_change_diff(games_and_users_list_.root(), nullptr, "user", player.config_address(), diff);
1652 
1653  if(diff1 || diff2) {
1654  send_to_lobby(diff, socket);
1655  }
1656 
1657  // Send the player who has quit the gamelist.
1659  }
1660 
1661  return;
1662  // If this is data describing side changes by the host.
1663  } else if(const simple_wml::node* scenario_diff = data.child("scenario_diff")) {
1664  if(!g.is_owner(socket)) {
1665  return;
1666  }
1667 
1668  g.level().root().apply_diff(*scenario_diff);
1669  const simple_wml::node* cfg_change = scenario_diff->child("change_child");
1670 
1671  // it is very likeley that the diff changes a side so this check isn't that important.
1672  // Note that [side] is not at toplevel but inside [scenario] or [snapshot]
1673  if(cfg_change /** && cfg_change->child("side") */) {
1674  g.update_side_data();
1675  }
1676 
1677  if(g.describe_slots()) {
1679  }
1680 
1681  g.send_data(data, socket);
1682  return;
1683  // If a player changes his faction.
1684  } else if(data.child("change_faction")) {
1685  g.send_data(data, socket);
1686  return;
1687  // If the owner of a side is changing the controller.
1688  } else if(const simple_wml::node* change = data.child("change_controller")) {
1689  g.transfer_side_control(socket, *change);
1690  if(g.describe_slots()) {
1692  }
1693 
1694  return;
1695  // If all observers should be muted. (toggles)
1696  } else if(data.child("muteall")) {
1697  if(!g.is_owner(socket)) {
1698  g.send_server_message("You cannot mute: not the game host.", socket);
1699  return;
1700  }
1701 
1702  g.mute_all_observers();
1703  return;
1704  // If an observer should be muted.
1705  } else if(const simple_wml::node* mute = data.child("mute")) {
1706  g.mute_observer(*mute, socket);
1707  return;
1708  // If an observer should be unmuted.
1709  } else if(const simple_wml::node* unmute = data.child("unmute")) {
1710  g.unmute_observer(*unmute, socket);
1711  return;
1712  // The owner is kicking/banning someone from the game.
1713  } else if(data.child("kick") || data.child("ban")) {
1714  bool ban = (data.child("ban") != nullptr);
1715  const socket_ptr user = (ban
1716  ? g.ban_user(*data.child("ban"), socket)
1717  : g.kick_member(*data.child("kick"), socket));
1718 
1719  if(user) {
1720  player_connections_.modify(player_connections_.find(user), std::bind(&player_record::enter_lobby, _1));
1721  if(g.describe_slots()) {
1722  update_game_in_lobby(g, user);
1723  }
1724 
1725  // Send all other players in the lobby the update to the gamelist.
1726  simple_wml::document gamelist_diff;
1727  make_change_diff(*games_and_users_list_.child("gamelist"), "gamelist", "game", g.description(), gamelist_diff);
1728  make_change_diff(games_and_users_list_.root(), nullptr, "user", player_connections_.find(user)->info().config_address(), gamelist_diff);
1729 
1730  send_to_lobby(gamelist_diff, socket);
1731 
1732  // Send the removed user the lobby game list.
1734  }
1735 
1736  return;
1737  } else if(const simple_wml::node* unban = data.child("unban")) {
1738  g.unban_user(*unban, socket);
1739  return;
1740  // If info is being provided about the game state.
1741  } else if(const simple_wml::node* info = data.child("info")) {
1742  if(!g.is_player(socket)) {
1743  return;
1744  }
1745 
1746  if((*info)["type"] == "termination") {
1747  g.set_termination_reason((*info)["condition"].to_string());
1748  if((*info)["condition"].to_string() == "out of sync") {
1749  g.send_server_message_to_all(player.name() + " reports out of sync errors.");
1750  if(user_handler_){
1751  user_handler_->db_set_oos_flag(uuid_, g.id());
1752  }
1753  }
1754  }
1755 
1756  return;
1757  } else if(data.child("turn")) {
1758  // Notify the game of the commands, and if it changes
1759  // the description, then sync the new description
1760  // to players in the lobby.
1761  if(g.process_turn(data, socket)) {
1763  }
1764 
1765  return;
1766  } else if(data.child("whiteboard")) {
1767  g.process_whiteboard(data, socket);
1768  return;
1769  } else if(data.child("change_turns_wml")) {
1770  g.process_change_turns_wml(data, socket);
1772  return;
1773  } else if(simple_wml::node* sch = data.child("request_choice")) {
1774  g.handle_choice(*sch, socket);
1775  return;
1776  } else if(data.child("message")) {
1777  g.process_message(data, socket);
1778  return;
1779  } else if(data.child("stop_updates")) {
1780  g.send_data(data, socket);
1781  return;
1782  // Data to ignore.
1783  } else if(
1784  data.child("error") ||
1785  data.child("side_secured") ||
1786  data.root().has_attr("failed") ||
1787  data.root().has_attr("side")
1788  ) {
1789  return;
1790  }
1791 
1792  WRN_SERVER << client_address(socket) << "\tReceived unknown data from: " << player.name() << " (socket:" << socket
1793  << ") in game: \"" << g.name() << "\" (" << g.id() << ")\n"
1794  << data.output();
1795 }
1796 
1797 using SendQueue = std::map<socket_ptr, std::queue<std::shared_ptr<simple_wml::document>>>;
1799 
1801 {
1802  if(send_queue[socket].empty()) {
1803  send_queue.erase(socket);
1804  } else {
1805  async_send_doc(socket, *(send_queue[socket].front()), handle_send_to_player, handle_send_to_player);
1806  send_queue[socket].pop();
1807  }
1808 }
1809 
1811 {
1812  auto iter = send_queue.find(socket);
1813  if(iter == send_queue.end()) {
1814  send_queue[socket];
1816  } else {
1817  send_queue[socket].emplace(doc.clone());
1818  }
1819 }
1820 
1821 void send_server_message(socket_ptr socket, const std::string& message)
1822 {
1824  simple_wml::node& msg = server_message.root().add_child("message");
1825  msg.set_attr("sender", "server");
1826  msg.set_attr_dup("message", message.c_str());
1827 
1828  send_to_player(socket, server_message);
1829 }
1830 
1832 {
1833  std::string ip;
1834 
1835  auto iter = player_connections_.find(socket);
1836  if(iter == player_connections_.end()) {
1837  return;
1838  } else {
1839  // client_address() is very likely to return <unknown address> at this point
1840  // so we remember ip in player_connections_
1841  ip = iter->saved_client_ip();
1842  }
1843 
1844  const std::shared_ptr<game> g = iter->get_game();
1845  bool game_ended = false;
1846  if(g) {
1847  game_ended = g->remove_player(socket, true, false);
1848  }
1849 
1851  const std::size_t index =
1852  std::distance(users.begin(), std::find(users.begin(), users.end(), iter->info().config_address()));
1853 
1854  // Notify other players in lobby
1855  simple_wml::document diff;
1856  if(make_delete_diff(games_and_users_list_.root(), nullptr, "user", iter->info().config_address(), diff)) {
1857  send_to_lobby(diff, socket);
1858  }
1859 
1860  games_and_users_list_.root().remove_child("user", index);
1861 
1862  LOG_SERVER << ip << "\t" << iter->info().name() << "\twas logged off"
1863  << "\n";
1864 
1865  // Find the matching nick-ip pair in the log and update the sign off time
1866  connection_log ip_name = connection_log(iter->info().name(), ip, 0);
1867 
1868  auto i = std::find(ip_log_.begin(), ip_log_.end(), ip_name);
1869  if(i != ip_log_.end()) {
1870  i->log_off = std::time(nullptr);
1871  }
1872 
1873  player_connections_.erase(iter);
1874 
1875  if(socket->is_open()) {
1876  socket->close();
1877  }
1878 
1879  if(lan_server_ && player_connections_.size() == 0)
1881 
1882  if(game_ended) delete_game(g->id());
1883 }
1884 
1886 {
1887  for(const auto& player : player_connections_.get<game_t>().equal_range(0)) {
1888  if(player.socket() != exclude) {
1889  send_to_player(player.socket(), data);
1890  }
1891  }
1892 }
1893 
1894 void server::send_server_message_to_lobby(const std::string& message, socket_ptr exclude) const
1895 {
1896  for(const auto& player : player_connections_.get<game_t>().equal_range(0)) {
1897  if(player.socket() != exclude) {
1898  send_server_message(player.socket(), message);
1899  }
1900  }
1901 }
1902 
1903 void server::send_server_message_to_all(const std::string& message, socket_ptr exclude) const
1904 {
1905  for(const auto& player : player_connections_) {
1906  if(player.socket() != exclude) {
1907  send_server_message(player.socket(), message);
1908  }
1909  }
1910 }
1911 
1913 {
1914  if(restart_command.empty()) {
1915  return;
1916  }
1917 
1918  // Example config line:
1919  // restart_command="./wesnothd-debug -d -c ~/.wesnoth1.5/server.cfg"
1920  // remember to make new one as a daemon or it will block old one
1921  if(std::system(restart_command.c_str())) {
1922  ERR_SERVER << "Failed to start new server with command: " << restart_command << std::endl;
1923  } else {
1924  LOG_SERVER << "New server started with command: " << restart_command << "\n";
1925  }
1926 }
1927 
1928 std::string server::process_command(std::string query, std::string issuer_name)
1929 {
1930  boost::trim(query);
1931 
1932  if(issuer_name == "*socket*" && query.at(0) == '+') {
1933  // The first argument might be "+<issuer>: ".
1934  // In that case we use +<issuer>+ as the issuer_name.
1935  // (Mostly used for communication with IRC.)
1936  auto issuer_end = std::find(query.begin(), query.end(), ':');
1937 
1938  std::string issuer(query.begin() + 1, issuer_end);
1939  if(!issuer.empty()) {
1940  issuer_name = "+" + issuer + "+";
1941  query = std::string(issuer_end + 1, query.end());
1942  boost::trim(query);
1943  }
1944  }
1945 
1946  const auto i = std::find(query.begin(), query.end(), ' ');
1947 
1948  try {
1949  const std::string command = utf8::lowercase(std::string(query.begin(), i));
1950 
1951  std::string parameters = (i == query.end() ? "" : std::string(i + 1, query.end()));
1952  boost::trim(parameters);
1953 
1954  std::ostringstream out;
1955  auto handler_itor = cmd_handlers_.find(command);
1956 
1957  if(handler_itor == cmd_handlers_.end()) {
1958  out << "Command '" << command << "' is not recognized.\n" << help_msg;
1959  } else {
1960  const cmd_handler& handler = handler_itor->second;
1961  try {
1962  handler(issuer_name, query, parameters, &out);
1963  } catch(const std::bad_function_call& ex) {
1964  ERR_SERVER << "While handling a command '" << command
1965  << "', caught a std::bad_function_call exception.\n";
1966  ERR_SERVER << ex.what() << std::endl;
1967  out << "An internal server error occurred (std::bad_function_call) while executing '" << command
1968  << "'\n";
1969  }
1970  }
1971 
1972  return out.str();
1973 
1974  } catch(const utf8::invalid_utf8_exception& e) {
1975  std::string msg = "While handling a command, caught an invalid utf8 exception: ";
1976  msg += e.what();
1977  ERR_SERVER << msg << std::endl;
1978  return (msg + '\n');
1979  }
1980 }
1981 
1982 // Shutdown, restart and sample commands can only be issued via the socket.
1984  const std::string& issuer_name, const std::string& /*query*/, std::string& parameters, std::ostringstream* out)
1985 {
1986  assert(out != nullptr);
1987 
1988  if(issuer_name != "*socket*" && !allow_remote_shutdown_) {
1989  *out << denied_msg;
1990  return;
1991  }
1992 
1993  if(parameters == "now") {
1994  throw server_shutdown("shut down by admin command");
1995  } else {
1996  // Graceful shut down.
1997  graceful_restart = true;
1998  acceptor_v6_.close();
1999  acceptor_v4_.close();
2000 
2001  timer_.expires_from_now(boost::posix_time::seconds(10));
2002  timer_.async_wait(std::bind(&server::handle_graceful_timeout, this, _1));
2003 
2005  "msg The server is shutting down. You may finish your games but can't start new ones. Once all "
2006  "games have ended the server will exit.",
2007  issuer_name
2008  );
2009 
2010  *out << "Server is doing graceful shut down.";
2011  }
2012 }
2013 
2014 void server::restart_handler(const std::string& issuer_name,
2015  const std::string& /*query*/,
2016  std::string& /*parameters*/,
2017  std::ostringstream* out)
2018 {
2019  assert(out != nullptr);
2020 
2021  if(issuer_name != "*socket*" && !allow_remote_shutdown_) {
2022  *out << denied_msg;
2023  return;
2024  }
2025 
2026  if(restart_command.empty()) {
2027  *out << "No restart_command configured! Not restarting.";
2028  } else {
2029  graceful_restart = true;
2030  acceptor_v6_.close();
2031  acceptor_v4_.close();
2032  timer_.expires_from_now(boost::posix_time::seconds(10));
2033  timer_.async_wait(std::bind(&server::handle_graceful_timeout, this, _1));
2034 
2035  start_new_server();
2036 
2038  "msg The server has been restarted. You may finish current games but can't start new ones and "
2039  "new players can't join this (old) server instance. (So if a player of your game disconnects "
2040  "you have to save, reconnect and reload the game on the new server instance. It is actually "
2041  "recommended to do that right away.)",
2042  issuer_name
2043  );
2044 
2045  *out << "New server started.";
2046  }
2047 }
2048 
2050  const std::string& issuer_name, const std::string& /*query*/, std::string& parameters, std::ostringstream* out)
2051 {
2052  assert(out != nullptr);
2053 
2054  if(parameters.empty()) {
2055  *out << "Current sample frequency: " << request_sample_frequency;
2056  return;
2057  } else if(issuer_name != "*socket*") {
2058  *out << denied_msg;
2059  return;
2060  }
2061 
2062  request_sample_frequency = atoi(parameters.c_str());
2063  if(request_sample_frequency <= 0) {
2064  *out << "Sampling turned off.";
2065  } else {
2066  *out << "Sampling every " << request_sample_frequency << " requests.";
2067  }
2068 }
2069 
2070 void server::help_handler(const std::string& /*issuer_name*/,
2071  const std::string& /*query*/,
2072  std::string& /*parameters*/,
2073  std::ostringstream* out)
2074 {
2075  assert(out != nullptr);
2076  *out << help_msg;
2077 }
2078 
2079 void server::stats_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  *out << "Number of games = " << games().size() << "\nTotal number of users = " << player_connections_.size()
2087  << "\n";
2088 }
2089 
2090 void server::metrics_handler(const std::string& /*issuer_name*/,
2091  const std::string& /*query*/,
2092  std::string& /*parameters*/,
2093  std::ostringstream* out)
2094 {
2095  assert(out != nullptr);
2096  *out << metrics_;
2097 }
2098 
2099 void server::requests_handler(const std::string& /*issuer_name*/,
2100  const std::string& /*query*/,
2101  std::string& /*parameters*/,
2102  std::ostringstream* out)
2103 {
2104  assert(out != nullptr);
2105  metrics_.requests(*out);
2106 }
2107 
2108 void server::games_handler(const std::string& /*issuer_name*/,
2109  const std::string& /*query*/,
2110  std::string& /*parameters*/,
2111  std::ostringstream* out)
2112 {
2113  assert(out != nullptr);
2114  metrics_.games(*out);
2115 }
2116 
2117 void server::wml_handler(const std::string& /*issuer_name*/,
2118  const std::string& /*query*/,
2119  std::string& /*parameters*/,
2120  std::ostringstream* out)
2121 {
2122  assert(out != nullptr);
2123  *out << simple_wml::document::stats();
2124 }
2125 
2126 void server::netstats_handler(const std::string& /*issuer_name*/,
2127  const std::string& /*query*/,
2128  std::string& /*parameters*/,
2129  std::ostringstream* /*out*/)
2130 {
2131  /*
2132  assert(out != nullptr);
2133 
2134  network::pending_statistics stats = network::get_pending_stats();
2135  *out << "Network stats:\nPending send buffers: "
2136  << stats.npending_sends << "\nBytes in buffers: "
2137  << stats.nbytes_pending_sends << "\n";
2138 
2139  try {
2140 
2141  if (utf8::lowercase(parameters) == "all") {
2142  *out << network::get_bandwidth_stats_all();
2143  } else {
2144  *out << network::get_bandwidth_stats(); // stats from previuos hour
2145  }
2146 
2147  } catch ( utf8::invalid_utf8_exception & e ) {
2148  ERR_SERVER << "While handling a netstats command, caught an invalid utf8 exception: " << e.what() << std::endl;
2149  }
2150  */
2151 }
2152 
2154  const std::string& issuer_name, const std::string& /*query*/, std::string& parameters, std::ostringstream* out)
2155 {
2156  assert(out != nullptr);
2157 
2158  if(parameters.empty()) {
2159  *out << "You must type a message.";
2160  return;
2161  }
2162 
2163  const std::string& sender = issuer_name;
2164  const std::string& message = parameters;
2165  LOG_SERVER << "Admin message: <" << sender
2166  << (message.find("/me ") == 0 ? std::string(message.begin() + 3, message.end()) + ">" : "> " + message)
2167  << "\n";
2168 
2169  simple_wml::document data;
2170  simple_wml::node& msg = data.root().add_child("whisper");
2171  msg.set_attr_dup("sender", ("admin message from " + sender).c_str());
2172  msg.set_attr_dup("message", message.c_str());
2173 
2174  int n = 0;
2175  for(const auto& player : player_connections_) {
2176  if(player.info().is_moderator()) {
2177  ++n;
2178  send_to_player(player.socket(), data);
2179  }
2180  }
2181 
2182  bool is_admin = false;
2183 
2184  for(const auto& player : player_connections_) {
2185  if(issuer_name == player.info().name() && player.info().is_moderator()) {
2186  is_admin = true;
2187  break;
2188  }
2189  }
2190 
2191  if(!is_admin) {
2192  *out << "Your report has been logged and sent to the server administrators. Thanks!";
2193  return;
2194  }
2195 
2196  *out << "Your report has been logged and sent to " << n << " online administrators. Thanks!";
2197 }
2198 
2200  const std::string& issuer_name, const std::string& /*query*/, std::string& parameters, std::ostringstream* out)
2201 {
2202  assert(out != nullptr);
2203 
2204  auto first_space = std::find(parameters.begin(), parameters.end(), ' ');
2205  if(first_space == parameters.end()) {
2206  *out << "You must name a receiver.";
2207  return;
2208  }
2209 
2210  const std::string& sender = issuer_name;
2211  const std::string receiver(parameters.begin(), first_space);
2212 
2213  std::string message(first_space + 1, parameters.end());
2214  boost::trim(message);
2215 
2216  if(message.empty()) {
2217  *out << "You must type a message.";
2218  return;
2219  }
2220 
2221  simple_wml::document data;
2222  simple_wml::node& msg = data.root().add_child("whisper");
2223 
2224  // This string is parsed by the client!
2225  msg.set_attr_dup("sender", ("server message from " + sender).c_str());
2226  msg.set_attr_dup("message", message.c_str());
2227 
2228  for(const auto& player : player_connections_) {
2229  if(receiver != player.info().name().c_str()) {
2230  continue;
2231  }
2232 
2233  send_to_player(player.socket(), data);
2234  *out << "Message to " << receiver << " successfully sent.";
2235  return;
2236  }
2237 
2238  *out << "No such nick: " << receiver;
2239 }
2240 
2241 void server::msg_handler(const std::string& /*issuer_name*/,
2242  const std::string& /*query*/,
2243  std::string& parameters,
2244  std::ostringstream* out)
2245 {
2246  assert(out != nullptr);
2247 
2248  if(parameters.empty()) {
2249  *out << "You must type a message.";
2250  return;
2251  }
2252 
2253  send_server_message_to_all(parameters);
2254 
2255  LOG_SERVER << "<server"
2256  << (parameters.find("/me ") == 0
2257  ? std::string(parameters.begin() + 3, parameters.end()) + ">"
2258  : "> " + parameters)
2259  << "\n";
2260 
2261  *out << "message '" << parameters << "' relayed to players";
2262 }
2263 
2264 void server::lobbymsg_handler(const std::string& /*issuer_name*/,
2265  const std::string& /*query*/,
2266  std::string& parameters,
2267  std::ostringstream* out)
2268 {
2269  assert(out != nullptr);
2270 
2271  if(parameters.empty()) {
2272  *out << "You must type a message.";
2273  return;
2274  }
2275 
2276  send_server_message_to_lobby(parameters);
2277  LOG_SERVER << "<server"
2278  << (parameters.find("/me ") == 0
2279  ? std::string(parameters.begin() + 3, parameters.end()) + ">"
2280  : "> " + parameters)
2281  << "\n";
2282 
2283  *out << "message '" << parameters << "' relayed to players";
2284 }
2285 
2287  const std::string& /*issuer_name*/, const std::string& /*query*/, std::string& parameters, std::ostringstream* out)
2288 {
2289  assert(out != nullptr);
2290 
2291  if(parameters.empty()) {
2292  *out << "Server version is " << game_config::wesnoth_version.str();
2293  return;
2294  }
2295 
2296  for(const auto& player : player_connections_) {
2297  if(parameters == player.info().name()) {
2298  *out << "Player " << parameters << " is using wesnoth " << player.info().version();
2299  return;
2300  }
2301  }
2302 
2303  *out << "Player '" << parameters << "' not found.";
2304 }
2305 
2307  const std::string& issuer_name, const std::string& /*query*/, std::string& parameters, std::ostringstream* out)
2308 {
2309  assert(out != nullptr);
2310 
2311  *out << "STATUS REPORT for '" << parameters << "'";
2312  bool found_something = false;
2313 
2314  // If a simple username is given we'll check for its IP instead.
2315  if(utils::isvalid_username(parameters)) {
2316  for(const auto& player : player_connections_) {
2317  if(utf8::lowercase(parameters) == utf8::lowercase(player.info().name())) {
2318  parameters = client_address(player.socket());
2319  found_something = true;
2320  break;
2321  }
2322  }
2323 
2324  if(!found_something) {
2325  // out << "\nNo match found. You may want to check with 'searchlog'.";
2326  // return out.str();
2327  *out << process_command("searchlog " + parameters, issuer_name);
2328  return;
2329  }
2330  }
2331 
2332  const bool match_ip = (std::count(parameters.begin(), parameters.end(), '.') >= 1);
2333  for(const auto& player : player_connections_) {
2334  if(parameters.empty() || parameters == "*" ||
2335  (match_ip && utils::wildcard_string_match(client_address(player.socket()), parameters)) ||
2336  (!match_ip && utils::wildcard_string_match(utf8::lowercase(player.info().name()), utf8::lowercase(parameters)))
2337  ) {
2338  found_something = true;
2339  *out << std::endl << player_status(player);
2340  }
2341  }
2342 
2343  if(!found_something) {
2344  *out << "\nNo match found. You may want to check with 'searchlog'.";
2345  }
2346 }
2347 
2348 void server::clones_handler(const std::string& /*issuer_name*/,
2349  const std::string& /*query*/,
2350  std::string& /*parameters*/,
2351  std::ostringstream* out)
2352 {
2353  assert(out != nullptr);
2354  *out << "CLONES STATUS REPORT";
2355 
2356  std::set<std::string> clones;
2357 
2358  for(auto it = player_connections_.begin(); it != player_connections_.end(); ++it) {
2359  if(clones.find(client_address(it->socket())) != clones.end()) {
2360  continue;
2361  }
2362 
2363  bool found = false;
2364  for(auto clone = std::next(it); clone != player_connections_.end(); ++clone) {
2365  if(client_address(it->socket()) == client_address(clone->socket())) {
2366  if(!found) {
2367  found = true;
2368  clones.insert(client_address(it->socket()));
2369  *out << std::endl << player_status(*it);
2370  }
2371 
2372  *out << std::endl << player_status(*clone);
2373  }
2374  }
2375  }
2376 
2377  if(clones.empty()) {
2378  *out << std::endl << "No clones found.";
2379  }
2380 }
2381 
2382 void server::bans_handler(const std::string& /*issuer_name*/,
2383  const std::string& /*query*/,
2384  std::string& parameters,
2385  std::ostringstream* out)
2386 {
2387  assert(out != nullptr);
2388 
2389  try {
2390  if(parameters.empty()) {
2391  ban_manager_.list_bans(*out);
2392  } else if(utf8::lowercase(parameters) == "deleted") {
2394  } else if(utf8::lowercase(parameters).find("deleted") == 0) {
2395  std::string mask = parameters.substr(7);
2396  ban_manager_.list_deleted_bans(*out, boost::trim_copy(mask));
2397  } else {
2398  boost::trim(parameters);
2399  ban_manager_.list_bans(*out, parameters);
2400  }
2401 
2402  } catch(const utf8::invalid_utf8_exception& e) {
2403  ERR_SERVER << "While handling bans, caught an invalid utf8 exception: " << e.what() << std::endl;
2404  }
2405 }
2406 
2408  const std::string& issuer_name, const std::string& /*query*/, std::string& parameters, std::ostringstream* out)
2409 {
2410  assert(out != nullptr);
2411 
2412  bool banned = false;
2413  auto first_space = std::find(parameters.begin(), parameters.end(), ' ');
2414 
2415  if(first_space == parameters.end()) {
2416  *out << ban_manager_.get_ban_help();
2417  return;
2418  }
2419 
2420  auto second_space = std::find(first_space + 1, parameters.end(), ' ');
2421  const std::string target(parameters.begin(), first_space);
2422  const std::string duration(first_space + 1, second_space);
2423  std::time_t parsed_time = std::time(nullptr);
2424 
2425  if(ban_manager_.parse_time(duration, &parsed_time) == false) {
2426  *out << "Failed to parse the ban duration: '" << duration << "'\n" << ban_manager_.get_ban_help();
2427  return;
2428  }
2429 
2430  if(second_space == parameters.end()) {
2431  --second_space;
2432  }
2433 
2434  std::string reason(second_space + 1, parameters.end());
2435  boost::trim(reason);
2436 
2437  if(reason.empty()) {
2438  *out << "You need to give a reason for the ban.";
2439  return;
2440  }
2441 
2442  std::string dummy_group;
2443 
2444  // if we find a '.' consider it an ip mask
2445  /** @todo FIXME: make a proper check for valid IPs. */
2446  if(std::count(target.begin(), target.end(), '.') >= 1) {
2447  banned = true;
2448 
2449  *out << ban_manager_.ban(target, parsed_time, reason, issuer_name, dummy_group);
2450  } else {
2451  for(const auto& player : player_connections_) {
2452  if(utils::wildcard_string_match(player.info().name(), target)) {
2453  if(banned) {
2454  *out << "\n";
2455  } else {
2456  banned = true;
2457  }
2458 
2459  const std::string ip = client_address(player.socket());
2460  *out << ban_manager_.ban(ip, parsed_time, reason, issuer_name, dummy_group, target);
2461  }
2462  }
2463 
2464  if(!banned) {
2465  // If nobody was banned yet check the ip_log but only if a
2466  // simple username was used to prevent accidental bans.
2467  // @todo FIXME: since we can have several entries now we should only ban the latest or so
2468  /*if (utils::isvalid_username(target)) {
2469  for (std::deque<connection_log>::const_iterator i = ip_log_.begin();
2470  i != ip_log_.end(); ++i) {
2471  if (i->nick == target) {
2472  if (banned) out << "\n";
2473  else banned = true;
2474  out << ban_manager_.ban(i->ip, parsed_time, reason, issuer_name, group, target);
2475  }
2476  }
2477  }*/
2478 
2479  if(!banned) {
2480  *out << "Nickname mask '" << target << "' did not match, no bans set.";
2481  }
2482  }
2483  }
2484 }
2485 
2487  const std::string& issuer_name, const std::string& /*query*/, std::string& parameters, std::ostringstream* out)
2488 {
2489  assert(out != nullptr);
2490 
2491  bool banned = false;
2492  auto first_space = std::find(parameters.begin(), parameters.end(), ' ');
2493  if(first_space == parameters.end()) {
2494  *out << ban_manager_.get_ban_help();
2495  return;
2496  }
2497 
2498  auto second_space = std::find(first_space + 1, parameters.end(), ' ');
2499  const std::string target(parameters.begin(), first_space);
2500  const std::string duration(first_space + 1, second_space);
2501  std::time_t parsed_time = std::time(nullptr);
2502 
2503  if(ban_manager_.parse_time(duration, &parsed_time) == false) {
2504  *out << "Failed to parse the ban duration: '" << duration << "'\n" << ban_manager_.get_ban_help();
2505  return;
2506  }
2507 
2508  if(second_space == parameters.end()) {
2509  --second_space;
2510  }
2511 
2512  std::string reason(second_space + 1, parameters.end());
2513  boost::trim(reason);
2514 
2515  if(reason.empty()) {
2516  *out << "You need to give a reason for the ban.";
2517  return;
2518  }
2519 
2520  std::string dummy_group;
2521  std::vector<socket_ptr> users_to_kick;
2522 
2523  // if we find a '.' consider it an ip mask
2524  /** @todo FIXME: make a proper check for valid IPs. */
2525  if(std::count(target.begin(), target.end(), '.') >= 1) {
2526  banned = true;
2527 
2528  *out << ban_manager_.ban(target, parsed_time, reason, issuer_name, dummy_group);
2529 
2530  for(const auto& player : player_connections_) {
2531  if(utils::wildcard_string_match(client_address(player.socket()), target)) {
2532  users_to_kick.push_back(player.socket());
2533  }
2534  }
2535  } else {
2536  for(const auto& player : player_connections_) {
2537  if(utils::wildcard_string_match(player.info().name(), target)) {
2538  if(banned) {
2539  *out << "\n";
2540  } else {
2541  banned = true;
2542  }
2543 
2544  const std::string ip = client_address(player.socket());
2545  *out << ban_manager_.ban(ip, parsed_time, reason, issuer_name, dummy_group, target);
2546  users_to_kick.push_back(player.socket());
2547  }
2548  }
2549 
2550  if(!banned) {
2551  // If nobody was banned yet check the ip_log but only if a
2552  // simple username was used to prevent accidental bans.
2553  // @todo FIXME: since we can have several entries now we should only ban the latest or so
2554  /*if (utils::isvalid_username(target)) {
2555  for (std::deque<connection_log>::const_iterator i = ip_log_.begin();
2556  i != ip_log_.end(); ++i) {
2557  if (i->nick == target) {
2558  if (banned) out << "\n";
2559  else banned = true;
2560  out << ban_manager_.ban(i->ip, parsed_time, reason, issuer_name, group, target);
2561  }
2562  }
2563  }*/
2564  if(!banned) {
2565  *out << "Nickname mask '" << target << "' did not match, no bans set.";
2566  }
2567  }
2568  }
2569 
2570  for(const auto& user : users_to_kick) {
2571  *out << "\nKicked " << player_connections_.find(user)->info().name() << " (" << client_address(user) << ").";
2572  async_send_error(user, "You have been banned. Reason: " + reason);
2573  remove_player(user);
2574  }
2575 }
2576 
2578  const std::string& issuer_name, const std::string& /*query*/, std::string& parameters, std::ostringstream* out)
2579 {
2580  assert(out != nullptr);
2581 
2582  bool banned = false;
2583  auto first_space = std::find(parameters.begin(), parameters.end(), ' ');
2584  if(first_space == parameters.end()) {
2585  *out << ban_manager_.get_ban_help();
2586  return;
2587  }
2588 
2589  auto second_space = std::find(first_space + 1, parameters.end(), ' ');
2590  const std::string target(parameters.begin(), first_space);
2591 
2592  std::string group = std::string(first_space + 1, second_space);
2593  first_space = second_space;
2594  second_space = std::find(first_space + 1, parameters.end(), ' ');
2595 
2596  const std::string duration(first_space + 1, second_space);
2597  std::time_t parsed_time = std::time(nullptr);
2598 
2599  if(ban_manager_.parse_time(duration, &parsed_time) == false) {
2600  *out << "Failed to parse the ban duration: '" << duration << "'\n" << ban_manager_.get_ban_help();
2601  return;
2602  }
2603 
2604  if(second_space == parameters.end()) {
2605  --second_space;
2606  }
2607 
2608  std::string reason(second_space + 1, parameters.end());
2609  boost::trim(reason);
2610 
2611  if(reason.empty()) {
2612  *out << "You need to give a reason for the ban.";
2613  return;
2614  }
2615 
2616  // if we find a '.' consider it an ip mask
2617  /** @todo FIXME: make a proper check for valid IPs. */
2618  if(std::count(target.begin(), target.end(), '.') >= 1) {
2619  banned = true;
2620 
2621  *out << ban_manager_.ban(target, parsed_time, reason, issuer_name, group);
2622  } else {
2623  for(const auto& player : player_connections_) {
2624  if(utils::wildcard_string_match(player.info().name(), target)) {
2625  if(banned) {
2626  *out << "\n";
2627  } else {
2628  banned = true;
2629  }
2630 
2631  const std::string ip = client_address(player.socket());
2632  *out << ban_manager_.ban(ip, parsed_time, reason, issuer_name, group, target);
2633  }
2634  }
2635 
2636  if(!banned) {
2637  // If nobody was banned yet check the ip_log but only if a
2638  // simple username was used to prevent accidental bans.
2639  // @todo FIXME: since we can have several entries now we should only ban the latest or so
2640  /*if (utils::isvalid_username(target)) {
2641  for (std::deque<connection_log>::const_iterator i = ip_log_.begin();
2642  i != ip_log_.end(); ++i) {
2643  if (i->nick == target) {
2644  if (banned) out << "\n";
2645  else banned = true;
2646  out << ban_manager_.ban(i->ip, parsed_time, reason, issuer_name, group, target);
2647  }
2648  }
2649  }*/
2650  if(!banned) {
2651  *out << "Nickname mask '" << target << "' did not match, no bans set.";
2652  }
2653  }
2654  }
2655 }
2656 
2657 void server::unban_handler(const std::string& /*issuer_name*/,
2658  const std::string& /*query*/,
2659  std::string& parameters,
2660  std::ostringstream* out)
2661 {
2662  assert(out != nullptr);
2663 
2664  if(parameters.empty()) {
2665  *out << "You must enter an ipmask to unban.";
2666  return;
2667  }
2668 
2669  ban_manager_.unban(*out, parameters);
2670 }
2671 
2672 void server::ungban_handler(const std::string& /*issuer_name*/,
2673  const std::string& /*query*/,
2674  std::string& parameters,
2675  std::ostringstream* out)
2676 {
2677  assert(out != nullptr);
2678 
2679  if(parameters.empty()) {
2680  *out << "You must enter an ipmask to ungban.";
2681  return;
2682  }
2683 
2684  ban_manager_.unban_group(*out, parameters);
2685 }
2686 
2687 void server::kick_handler(const std::string& /*issuer_name*/,
2688  const std::string& /*query*/,
2689  std::string& parameters,
2690  std::ostringstream* out)
2691 {
2692  assert(out != nullptr);
2693 
2694  if(parameters.empty()) {
2695  *out << "You must enter a mask to kick.";
2696  return;
2697  }
2698 
2699  auto i = std::find(parameters.begin(), parameters.end(), ' ');
2700  const std::string kick_mask = std::string(parameters.begin(), i);
2701  const std::string kick_message = (i == parameters.end()
2702  ? "You have been kicked."
2703  : "You have been kicked. Reason: " + std::string(i + 1, parameters.end()));
2704 
2705  bool kicked = false;
2706 
2707  // if we find a '.' consider it an ip mask
2708  const bool match_ip = (std::count(kick_mask.begin(), kick_mask.end(), '.') >= 1);
2709 
2710  std::vector<socket_ptr> users_to_kick;
2711  for(const auto& player : player_connections_) {
2712  if((match_ip && utils::wildcard_string_match(client_address(player.socket()), kick_mask)) ||
2713  (!match_ip && utils::wildcard_string_match(player.info().name(), kick_mask))
2714  ) {
2715  users_to_kick.push_back(player.socket());
2716  }
2717  }
2718 
2719  for(const auto& socket : users_to_kick) {
2720  if(kicked) {
2721  *out << "\n";
2722  } else {
2723  kicked = true;
2724  }
2725 
2726  *out << "Kicked " << player_connections_.find(socket)->name() << " (" << client_address(socket) << "). '"
2727  << kick_message << "'";
2728 
2729  async_send_error(socket, kick_message);
2730  remove_player(socket);
2731  }
2732 
2733  if(!kicked) {
2734  *out << "No user matched '" << kick_mask << "'.";
2735  }
2736 }
2737 
2738 void server::motd_handler(const std::string& /*issuer_name*/,
2739  const std::string& /*query*/,
2740  std::string& parameters,
2741  std::ostringstream* out)
2742 {
2743  assert(out != nullptr);
2744 
2745  if(parameters.empty()) {
2746  if(!motd_.empty()) {
2747  *out << "Message of the day:\n" << motd_;
2748  return;
2749  } else {
2750  *out << "No message of the day set.";
2751  return;
2752  }
2753  }
2754 
2755  motd_ = parameters;
2756  *out << "Message of the day set to: " << motd_;
2757 }
2758 
2759 void server::searchlog_handler(const std::string& /*issuer_name*/,
2760  const std::string& /*query*/,
2761  std::string& parameters,
2762  std::ostringstream* out)
2763 {
2764  assert(out != nullptr);
2765 
2766  if(parameters.empty()) {
2767  *out << "You must enter a mask to search for.";
2768  return;
2769  }
2770 
2771  *out << "IP/NICK LOG for '" << parameters << "'";
2772 
2773  bool found_something = false;
2774 
2775  // If this looks like an IP look up which nicks have been connected from it
2776  // Otherwise look for the last IP the nick used to connect
2777  const bool match_ip = (std::count(parameters.begin(), parameters.end(), '.') >= 1);
2778 
2779  for(const auto& i : ip_log_) {
2780  const std::string& username = i.nick;
2781  const std::string& ip = i.ip;
2782 
2783  if((match_ip && utils::wildcard_string_match(ip, parameters)) ||
2784  (!match_ip && utils::wildcard_string_match(utf8::lowercase(username), utf8::lowercase(parameters)))
2785  ) {
2786  found_something = true;
2787  auto player = player_connections_.get<name_t>().find(username);
2788 
2789  if(player != player_connections_.get<name_t>().end() && client_address(player->socket()) == ip) {
2790  *out << std::endl << player_status(*player);
2791  } else {
2792  *out << "\n'" << username << "' @ " << ip
2793  << " last seen: " << lg::get_timestamp(i.log_off, "%H:%M:%S %d.%m.%Y");
2794  }
2795  }
2796  }
2797 
2798  if(!found_something) {
2799  *out << "\nNo match found.";
2800  }
2801 }
2802 
2803 void server::dul_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  try {
2811  if(parameters.empty()) {
2812  *out << "Unregistered login is " << (deny_unregistered_login_ ? "disallowed" : "allowed") << ".";
2813  } else {
2814  deny_unregistered_login_ = (utf8::lowercase(parameters) == "yes");
2815  *out << "Unregistered login is now " << (deny_unregistered_login_ ? "disallowed" : "allowed") << ".";
2816  }
2817 
2818  } catch(const utf8::invalid_utf8_exception& e) {
2819  ERR_SERVER << "While handling dul (deny unregistered logins), caught an invalid utf8 exception: " << e.what()
2820  << std::endl;
2821  }
2822 }
2823 
2824 void server::stopgame(const std::string& /*issuer_name*/,
2825  const std::string& /*query*/,
2826  std::string& parameters,
2827  std::ostringstream* out)
2828 {
2829  const std::string nick = parameters.substr(0, parameters.find(' '));
2830  const std::string reason = parameters.length() > nick.length()+1 ? parameters.substr(nick.length()+1) : "";
2831  auto player = player_connections_.get<name_t>().find(nick);
2832 
2833  if(player != player_connections_.get<name_t>().end()){
2834  std::shared_ptr<game> g = player->get_game();
2835  if(g){
2836  *out << "Player '" << nick << "' is in game with id '" << g->id() << "' named '" << g->name() << "'. Ending game for reason: '" << reason << "'...";
2837  delete_game(g->id(), reason);
2838  } else {
2839  *out << "Player '" << nick << "' is not currently in a game.";
2840  }
2841  } else {
2842  *out << "Player '" << nick << "' is not currently logged in.";
2843  }
2844 }
2845 
2846 void server::delete_game(int gameid, const std::string& reason)
2847 {
2848  // Set the availability status for all quitting users.
2849  auto range_pair = player_connections_.get<game_t>().equal_range(gameid);
2850 
2851  // Make a copy of the iterators so that we can change them while iterating over them.
2852  // We can use pair::first_type since equal_range returns a pair of iterators.
2853  std::vector<decltype(range_pair)::first_type> range_vctor;
2854 
2855  for(auto it = range_pair.first; it != range_pair.second; ++it) {
2856  range_vctor.push_back(it);
2857  it->info().mark_available();
2858 
2859  simple_wml::document udiff;
2860  if(make_change_diff(games_and_users_list_.root(), nullptr, "user", it->info().config_address(), udiff)) {
2861  send_to_lobby(udiff);
2862  } else {
2863  ERR_SERVER << "ERROR: delete_game(): Could not find user in players_. (socket: " << it->socket() << ")\n";
2864  }
2865  }
2866 
2867  // Put the remaining users back in the lobby.
2868  // This will call cleanup_game() deleter since there won't
2869  // be any references to that game from player_connections_ anymore
2870  for(const auto& it : range_vctor) {
2871  player_connections_.get<game_t>().modify(it, std::bind(&player_record::enter_lobby, _1));
2872  }
2873 
2874  // send users in the game a notification to leave the game since it has ended
2875  static simple_wml::document leave_game_doc("[leave_game]\n[/leave_game]\n", simple_wml::INIT_COMPRESSED);
2876 
2877  for(const auto& it : range_vctor) {
2878  if(reason != "") {
2879  simple_wml::document leave_game_doc_reason("[leave_game]\n[/leave_game]\n", simple_wml::INIT_STATIC);
2880  leave_game_doc_reason.child("leave_game")->set_attr_dup("reason", reason.c_str());
2881  send_to_player(it->socket(), leave_game_doc_reason);
2882  } else {
2883  send_to_player(it->socket(), leave_game_doc);
2884  }
2885  send_to_player(it->socket(), games_and_users_list_);
2886  }
2887 }
2888 
2890 {
2891  simple_wml::document diff;
2892  if(make_change_diff(*games_and_users_list_.child("gamelist"), "gamelist", "game", g.description(), diff)) {
2893  send_to_lobby(diff, exclude);
2894  }
2895 }
2896 
2897 } // namespace wesnothd
2898 
2899 int main(int argc, char** argv)
2900 {
2901  int port = 15000;
2902  bool keep_alive = false;
2903  std::size_t min_threads = 5;
2904  std::size_t max_threads = 0;
2905 
2906  srand(static_cast<unsigned>(std::time(nullptr)));
2907 
2908  std::string config_file;
2909 
2910  // setting path to currentworking directory
2912 
2913  // show 'info' by default
2915  lg::timestamps(true);
2916 
2917  for(int arg = 1; arg != argc; ++arg) {
2918  const std::string val(argv[arg]);
2919  if(val.empty()) {
2920  continue;
2921  }
2922 
2923  if((val == "--config" || val == "-c") && arg + 1 != argc) {
2924  config_file = argv[++arg];
2925  } else if(val == "--verbose" || val == "-v") {
2927  } else if(val.substr(0, 6) == "--log-") {
2928  std::size_t p = val.find('=');
2929  if(p == std::string::npos) {
2930  std::cerr << "unknown option: " << val << '\n';
2931  return 2;
2932  }
2933 
2934  std::string s = val.substr(6, p - 6);
2935  int severity;
2936 
2937  if(s == "error") {
2938  severity = lg::err().get_severity();
2939  } else if(s == "warning") {
2940  severity = lg::warn().get_severity();
2941  } else if(s == "info") {
2942  severity = lg::info().get_severity();
2943  } else if(s == "debug") {
2944  severity = lg::debug().get_severity();
2945  } else {
2946  std::cerr << "unknown debug level: " << s << '\n';
2947  return 2;
2948  }
2949 
2950  while(p != std::string::npos) {
2951  std::size_t q = val.find(',', p + 1);
2952  s = val.substr(p + 1, q == std::string::npos ? q : q - (p + 1));
2953 
2954  if(!lg::set_log_domain_severity(s, severity)) {
2955  std::cerr << "unknown debug domain: " << s << '\n';
2956  return 2;
2957  }
2958 
2959  p = q;
2960  }
2961  } else if((val == "--port" || val == "-p") && arg + 1 != argc) {
2962  port = atoi(argv[++arg]);
2963  } else if(val == "--keepalive") {
2964  keep_alive = true;
2965  } else if(val == "--help" || val == "-h") {
2966  std::cout << "usage: " << argv[0]
2967  << " [-dvV] [-c path] [-m n] [-p port] [-t n]\n"
2968  << " -c, --config <path> Tells wesnothd where to find the config file to use.\n"
2969  << " -d, --daemon Runs wesnothd as a daemon.\n"
2970  << " -h, --help Shows this usage message.\n"
2971  << " --log-<level>=<domain1>,<domain2>,...\n"
2972  << " sets the severity level of the debug domains.\n"
2973  << " 'all' can be used to match any debug domain.\n"
2974  << " Available levels: error, warning, info, debug.\n"
2975  << " -p, --port <port> Binds the server to the specified port.\n"
2976  << " --keepalive Enable TCP keepalive.\n"
2977  << " -t, --threads <n> Uses n worker threads for network I/O (default: 5).\n"
2978  << " -v --verbose Turns on more verbose logging.\n"
2979  << " -V, --version Returns the server version.\n";
2980  return 0;
2981  } else if(val == "--version" || val == "-V") {
2982  std::cout << "Battle for Wesnoth server " << game_config::wesnoth_version.str() << "\n";
2983  return 0;
2984  } else if(val == "--daemon" || val == "-d") {
2985 #ifdef _WIN32
2986  ERR_SERVER << "Running as a daemon is not supported on this platform" << std::endl;
2987  return -1;
2988 #else
2989  const pid_t pid = fork();
2990  if(pid < 0) {
2991  ERR_SERVER << "Could not fork and run as a daemon" << std::endl;
2992  return -1;
2993  } else if(pid > 0) {
2994  std::cout << "Started wesnothd as a daemon with process id " << pid << "\n";
2995  return 0;
2996  }
2997 
2998  setsid();
2999 #endif
3000  } else if((val == "--threads" || val == "-t") && arg + 1 != argc) {
3001  min_threads = atoi(argv[++arg]);
3002  if(min_threads > 30) {
3003  min_threads = 30;
3004  }
3005  } else if((val == "--max-threads" || val == "-T") && arg + 1 != argc) {
3006  max_threads = atoi(argv[++arg]);
3007  } else if(val == "--request_sample_frequency" && arg + 1 != argc) {
3008  wesnothd::request_sample_frequency = atoi(argv[++arg]);
3009  } else {
3010  ERR_SERVER << "unknown option: " << val << std::endl;
3011  return 2;
3012  }
3013  }
3014 
3015  try {
3016  wesnothd::server(port, keep_alive, config_file, min_threads, max_threads).run();
3017  } catch(const std::exception& e) {
3018  ERR_SERVER << "terminated by C++ exception: " << e.what() << std::endl;
3019  return 1;
3020  }
3021 
3022  return 0;
3023 }
boost::asio::ip::tcp::acceptor acceptor_v4_
Definition: server_base.hpp:49
std::string motd_
Definition: server.hpp:142
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:1468
void send_data(simple_wml::document &data, const socket_ptr &exclude=socket_ptr(), std::string packet_type="") const
Definition: game.cpp:1674
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
std::time_t duration
Ban duration (0 if permanent)
void handle_nickserv(socket_ptr socket, simple_wml::node &nickserv)
Definition: server.cpp:1190
SendQueue send_queue
Definition: server.cpp:1798
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:637
void handle_whisper(socket_ptr socket, simple_wml::node &whisper)
Definition: server.cpp:1064
const simple_wml::node * config_address() const
Definition: player.hpp:49
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:1983
simple_wml::document games_and_users_list_
Definition: server.hpp:169
void new_scenario(const socket_ptr &player)
when the host sends the new scenario of a mp campaign
Definition: game.cpp:1610
std::deque< login_log >::size_type failed_login_buffer_size_
Definition: server.hpp:158
void apply_diff(const node &diff)
Definition: simple_wml.cpp:826
std::string uuid_
Definition: server.hpp:127
#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:1837
void async_send_error(socket_ptr socket, const std::string &msg, const char *error_code, const info_table &info)
#define MP_NAME_AUTH_BAN_USER_ERROR
const std::string denied_msg
Definition: server.cpp:207
void handle_version(socket_ptr socket)
Definition: server.cpp:582
void status_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2306
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:2108
std::ostream & games(std::ostream &out) const
Definition: metrics.cpp:109
int failed_login_limit_
Definition: server.hpp:156
const std::string & version() const
Definition: player.hpp:48
static std::string player_status(const wesnothd::player_record &player)
Definition: server.cpp:191
const simple_wml::node::child_list & get_sides_list() const
Definition: game.hpp:110
boost::asio::signal_set sighup_
Definition: server_base.hpp:75
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:455
std::string is_ip_banned(const std::string &ip)
Definition: ban.cpp:661
bool save_replays_
Definition: server.hpp:152
std::function< void(const std::string &, const std::string &, std::string &, std::ostringstream *)> cmd_handler
Definition: server.hpp:192
const char * end() const
Definition: simple_wml.hpp:90
int main(int argc, char **argv)
Definition: server.cpp:2899
void kickban_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2486
const std::string & name() const
Definition: player.hpp:47
void start_dump_stats()
Definition: server.cpp:559
child_itors child_range(config_key_type key)
Definition: config.cpp:362
static void handle_send_to_player(socket_ptr socket)
Definition: server.cpp:1800
void handle_query(socket_ptr socket, simple_wml::node &query)
Definition: server.cpp:1104
void start_lan_server_timer()
Definition: server.cpp:303
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:1278
#define MP_NO_SEED_ERROR
void help_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2070
#define WRN_SERVER
clients send wrong/unexpected data
Definition: server.cpp:71
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:2117
bool to_bool(bool default_value=false) const
Definition: simple_wml.cpp:157
#define ERR_CONFIG
Definition: server.cpp:78
void stats_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2079
void send_server_message(const char *message, const socket_ptr &sock=socket_ptr(), simple_wml::document *doc=nullptr) const
Definition: game.cpp:2020
#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:339
void update_game_in_lobby(const wesnothd::game &g, const socket_ptr &exclude=socket_ptr())
Definition: server.cpp:2889
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:117
std::size_t default_time_period_
Definition: server.hpp:144
void requests_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2099
#define d
Define the errors the server may send during the login procedure.
std::vector< std::string > accepted_versions_
Definition: server.hpp:136
std::size_t default_max_messages_
Definition: server.hpp:143
bool is_moderator() const
Definition: player.hpp:54
void send_server_message_to_lobby(const std::string &message, socket_ptr exclude=socket_ptr()) const
Definition: server.cpp:1894
const child_list & children(const char *name) const
Definition: simple_wml.cpp:633
void ban_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2407
Definitions for the interface to Wesnoth Markup Language (WML).
void handle_sighup(const boost::system::error_code &error, int signal_number)
Definition: server.cpp:277
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:2013
void handle_create_game(socket_ptr socket, simple_wml::node &create_game)
Definition: server.cpp:1243
const socket_ptr socket() const
bool deny_unregistered_login_
Definition: server.hpp:151
void handle_graceful_timeout(const boost::system::error_code &error)
Definition: server.cpp:290
User account/name ban.
#define MP_INCORRECT_PASSWORD_ERROR
void gban_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2577
std::string get_cwd()
Definition: filesystem.cpp:814
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:1070
node * child(const char *name)
Definition: simple_wml.cpp:606
std::string recommended_version_
Definition: server.hpp:137
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:1002
bool player_is_in_game(socket_ptr socket) const
Definition: server.hpp:71
std::map< socket_ptr, std::queue< std::shared_ptr< simple_wml::document > >> SendQueue
Definition: server.cpp:1797
void process_message(simple_wml::document &data, const socket_ptr &user)
Definition: game.cpp:921
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:167
#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:1305
void handle_login(socket_ptr socket, std::shared_ptr< simple_wml::document > doc, std::string version)
Definition: server.cpp:642
A user_handler implementation to link the server with a phpbb3 forum.
boost::asio::streambuf admin_cmd_
Definition: server_base.hpp:73
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:653
bool allow_remote_shutdown_
Definition: server.hpp:154
std::map< std::string, config > proxy_versions_
Definition: server.hpp:139
void start_game(const socket_ptr &starter)
Definition: game.cpp:295
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:2241
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:1831
void handle_lan_server_shutdown(const boost::system::error_code &error)
Definition: server.cpp:314
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:149
bool describe_slots()
Set the description to the number of available slots.
Definition: game.cpp:676
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:2348
bool ip_exceeds_connection_limit(const std::string &ip) const
Definition: server.cpp:532
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:228
void motd_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2738
std::vector< std::string > tor_ip_list_
Definition: server.hpp:155
std::string path
Definition: game_config.cpp:39
boost::asio::ip::tcp::acceptor acceptor_v6_
Definition: server_base.hpp:48
void load_next_scenario(const socket_ptr &user)
A user (player only?) asks for the next scenario to advance to.
Definition: game.cpp:1622
void bans_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2382
std::string get_replay_filename()
Definition: game.cpp:1827
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:2759
logger & debug()
Definition: log.cpp:96
simple_wml::document version_query_response_
Definition: server.hpp:166
void perform_controller_tweaks()
Definition: game.cpp:230
bool is_player(const socket_ptr &player) const
Definition: game.cpp:194
std::string read_file(const std::string &fname)
Basic disk I/O - read file.
Definition: filesystem.cpp:917
std::string replay_save_path_
Definition: server.hpp:153
void kick_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2687
void send_to_lobby(simple_wml::document &data, socket_ptr exclude=socket_ptr()) const
Definition: server.cpp:1885
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:89
void send_to_player(socket_ptr socket, simple_wml::document &doc)
Definition: server.cpp:1810
void netstats_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2126
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:208
void cleanup_game(game *)
Definition: server.cpp:1297
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:817
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:53
static std::string stats()
bool graceful_restart
Definition: server.hpp:146
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:2049
std::size_t i
Definition: function.cpp:933
logger & err()
Definition: log.cpp:78
Thrown by operations encountering invalid UTF-8 data.
IP address ban.
node & set_attr_dup(const char *key, const char *value)
Definition: simple_wml.cpp:427
void start_new_server()
Definition: server.cpp:1912
boost::asio::steady_timer lan_server_timer_
Definition: server.hpp:231
void send_server_message_to_all(const std::string &message, socket_ptr exclude=socket_ptr()) const
Definition: server.cpp:1903
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:145
mock_party p
void unban_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2657
const std::string config_file_
Definition: server.hpp:129
static map_location::DIRECTION s
void delete_game(int, const std::string &reason="")
Definition: server.cpp:2846
Ban status description.
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:157
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:891
std::string client_address(const socket_ptr socket)
std::string admin_passwd_
Definition: server.hpp:141
void reset_last_synced_context_id()
Definition: game.hpp:313
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:2153
void stopgame(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2824
#define ERR_SERVER
fatal and directly server related errors/warnings, ie not caused by erroneous client data ...
Definition: server.cpp:68
metrics metrics_
Definition: server.hpp:171
void handle_player_in_game(socket_ptr socket, std::shared_ptr< simple_wml::document > doc)
Definition: server.cpp:1412
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:737
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:1236
std::string lowercase(const std::string &s)
Returns a lowercased version of the string.
Definition: unicode.cpp:51
BAN_TYPE type
Ban type.
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:1904
boost::asio::posix::stream_descriptor input_
Definition: server_base.hpp:69
#define MP_NAME_INACTIVE_WARNING
std::map< std::string, config > redirected_versions_
Definition: server.hpp:138
const version_info wesnoth_version(VERSION)
void set_password(const std::string &passwd)
Definition: game.hpp:282
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:565
void set_game(std::shared_ptr< game > new_game)
void handle_message(socket_ptr socket, simple_wml::node &message)
Definition: server.cpp:1215
int request_sample_frequency
Definition: server.cpp:86
void restart_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2014
#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:2286
#define MP_NAME_TAKEN_ERROR
std::string is_ip_banned(const std::string &ip)
Definition: server.cpp:548
void list_bans(std::ostringstream &out, const std::string &mask="*")
Definition: ban.cpp:617
std::time_t lan_server_
Definition: server.hpp:147
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:219
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:779
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:1329
bool is_reload() const
Definition: game.cpp:2049
void unban(std::ostringstream &os, const std::string &ip, bool immediate_write=true)
Definition: ban.cpp:526
void setup_handlers()
Definition: server.cpp:368
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:193
#define LOG_SERVER
normal events
Definition: server.cpp:74
const std::string & termination_reason() const
Definition: game.hpp:297
void setup_fifo()
Definition: server.cpp:322
Standard logging facilities (interface).
void dul_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2803
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:527
std::string message
Definition: exceptions.hpp:31
std::shared_ptr< boost::asio::ip::tcp::socket > socket_ptr
Definition: server_base.hpp:30
player_connections player_connections_
Definition: server.hpp:111
void load_config()
Parse the server config into local variables.
Definition: server.cpp:430
simple_wml::document join_lobby_response_
Definition: server.hpp:168
void read_version(socket_ptr socket, std::shared_ptr< simple_wml::document > doc)
Definition: server.cpp:587
void async_send_warning(socket_ptr socket, const std::string &msg, const char *warning_code, const info_table &info)
std::deque< connection_log > ip_log_
Definition: server.hpp:90
#define e
void handle_new_client(socket_ptr socket)
Definition: server.cpp:577
#define MP_NAME_RESERVED_ERROR
Account email address ban.
void ungban_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2672
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:1928
config read_config() const
Read the server config from file &#39;config_file_&#39;.
Definition: server.cpp:411
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:2090
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:2264
#define MP_NAME_AUTH_BAN_EMAIL_ERROR
void pm_handler(const std::string &, const std::string &, std::string &, std::ostringstream *)
Definition: server.cpp:2199
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:1263
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 set_name_bans(const std::vector< std::string > name_bans)
Definition: game.hpp:287
void abort_lan_server_timer()
Definition: server.cpp:309
std::size_t max_ip_log_size_
Definition: server.hpp:150
void mute_all_observers()
Definition: game.cpp:715
bool empty() const
Definition: config.cpp:884
version_info secure_version
Definition: server.cpp:87
void send_server_message(socket_ptr socket, const std::string &message)
Definition: server.cpp:1821
void set_termination_reason(const std::string &reason)
Definition: game.cpp:1912
socket_ptr ban_user(const simple_wml::node &ban, const socket_ptr &banner)
Ban and kick a user by name.
Definition: game.cpp:849
std::vector< std::string > disallowed_names_
Definition: server.hpp:140
#define DBG_SERVER
Definition: server.cpp:75
std::pair< std::string, unsigned > item
Definition: help_impl.hpp:371
#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:266
simple_wml::node * description() const
Definition: game.hpp:277
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:150
int id() const
Definition: game.hpp:52