3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "irrlicht.h" // createDevice
21 #include "irrlichttypes_extrabloated.h"
22 #include "chat_interface.h"
24 #include "unittest/test.h"
28 #include "client/game.h"
29 #include "defaultsettings.h"
32 #include "quicktune.h"
33 #include "httpfetch.h"
34 #include "gameparams.h"
35 #include "database/database.h"
39 #include "network/socket.h"
41 #include "terminal_chat_console.h"
44 #include "gui/guiMainMenu.h"
45 #include "client/clientlauncher.h"
46 #include "gui/guiEngine.h"
47 #include "gui/mainmenumanager.h"
50 #ifdef HAVE_TOUCHSCREENGUI
51 #include "gui/touchscreengui.h"
54 #if !defined(SERVER) && \
55 (IRRLICHT_VERSION_MAJOR == 1) && \
56 (IRRLICHT_VERSION_MINOR == 8) && \
57 (IRRLICHT_VERSION_REVISION == 2)
58 #error "Irrlicht 1.8.2 is known to be broken - please update Irrlicht to version >= 1.8.3"
61 #define DEBUGFILE "debug.txt"
62 #define DEFAULT_SERVER_PORT 30000
64 typedef std::map<std::string, ValueSpec> OptionList;
66 /**********************************************************************
68 **********************************************************************/
70 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
71 static void set_allowed_options(OptionList *allowed_options);
73 static void print_help(const OptionList &allowed_options);
74 static void print_allowed_options(const OptionList &allowed_options);
75 static void print_version();
76 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
77 std::ostream &os, bool print_name = true, bool print_path = true);
78 static void print_modified_quicktune_values();
80 static void list_game_ids();
81 static void list_worlds(bool print_name, bool print_path);
82 static bool setup_log_params(const Settings &cmd_args);
83 static bool create_userdata_path();
84 static bool init_common(const Settings &cmd_args, int argc, char *argv[]);
85 static void startup_message();
86 static bool read_config_file(const Settings &cmd_args);
87 static void init_log_streams(const Settings &cmd_args);
89 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
90 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
92 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
93 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
94 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
95 static bool auto_select_world(GameParams *game_params);
96 static std::string get_clean_world_path(const std::string &path);
98 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
99 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
100 static bool determine_subgame(GameParams *game_params);
102 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
103 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args);
105 /**********************************************************************/
108 FileLogOutput file_log_output;
110 static OptionList allowed_options;
112 int main(int argc, char *argv[])
115 debug_set_exception_handler();
117 g_logger.registerThread("Main");
118 g_logger.addOutputMaxLevel(&stderr_output, LL_ACTION);
121 bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
123 || cmd_args.getFlag("help")
124 || cmd_args.exists("nonopt1")) {
125 porting::attachOrCreateConsole();
126 print_help(allowed_options);
127 return cmd_args_ok ? 0 : 1;
129 if (cmd_args.getFlag("console"))
130 porting::attachOrCreateConsole();
132 if (cmd_args.getFlag("version")) {
133 porting::attachOrCreateConsole();
138 if (!setup_log_params(cmd_args))
141 porting::signal_handler_init();
144 porting::initAndroid();
145 porting::initializePathsAndroid();
147 porting::initializePaths();
150 if (!create_userdata_path()) {
151 errorstream << "Cannot create user data directory" << std::endl;
156 BEGIN_DEBUG_EXCEPTION_HANDLER
158 // List gameids if requested
159 if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
164 // List worlds, world names, and world paths if requested
165 if (cmd_args.exists("worldlist")) {
166 if (cmd_args.get("worldlist") == "name") {
167 list_worlds(true, false);
168 } else if (cmd_args.get("worldlist") == "path") {
169 list_worlds(false, true);
170 } else if (cmd_args.get("worldlist") == "both") {
171 list_worlds(true, true);
173 errorstream << "Invalid --worldlist value: "
174 << cmd_args.get("worldlist") << std::endl;
180 if (!init_common(cmd_args, argc, argv))
183 if (g_settings->getBool("enable_console"))
184 porting::attachOrCreateConsole();
188 if (cmd_args.getFlag("run-unittests")) {
193 GameParams game_params;
195 porting::attachOrCreateConsole();
196 game_params.is_dedicated_server = true;
198 const bool isServer = cmd_args.getFlag("server");
200 porting::attachOrCreateConsole();
201 game_params.is_dedicated_server = isServer;
204 if (!game_configure(&game_params, cmd_args))
207 sanity_check(!game_params.world_path.empty());
209 infostream << "Using commanded world path ["
210 << game_params.world_path << "]" << std::endl;
212 if (game_params.is_dedicated_server)
213 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
216 ClientLauncher launcher;
217 retval = launcher.run(game_params, cmd_args) ? 0 : 1;
222 // Update configuration file
223 if (!g_settings_path.empty())
224 g_settings->updateConfigFile(g_settings_path.c_str());
226 print_modified_quicktune_values();
228 // Stop httpfetch thread (if started)
231 END_DEBUG_EXCEPTION_HANDLER
237 /*****************************************************************************
239 *****************************************************************************/
242 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
244 set_allowed_options(&allowed_options);
246 return cmd_args->parseCommandLine(argc, argv, allowed_options);
249 static void set_allowed_options(OptionList *allowed_options)
251 allowed_options->clear();
253 allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
254 _("Show allowed options"))));
255 allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
256 _("Show version information"))));
257 allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
258 _("Load configuration from specified file"))));
259 allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
260 _("Set network port (UDP)"))));
261 allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
262 _("Run the unit tests and exit"))));
263 allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
264 _("Same as --world (deprecated)"))));
265 allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
266 _("Set world path (implies local game if used with option --go)"))));
267 allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
268 _("Set world by name (implies local game if used with option --go)"))));
269 allowed_options->insert(std::make_pair("worldlist", ValueSpec(VALUETYPE_STRING,
270 _("Get list of worlds ('path' lists paths, "
271 "'name' lists names, 'both' lists both)"))));
272 allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
273 _("Print to console errors only"))));
274 allowed_options->insert(std::make_pair("color", ValueSpec(VALUETYPE_STRING,
275 _("Coloured logs ('always', 'never' or 'auto'), defaults to 'auto'"
277 allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
278 _("Print more information to console"))));
279 allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
280 _("Print even more information to console"))));
281 allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
282 _("Print enormous amounts of information to log and console"))));
283 allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
284 _("Set logfile path ('' = no logging)"))));
285 allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
286 _("Set gameid (\"--gameid list\" prints available ones)"))));
287 allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
288 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
289 allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING,
290 _("Migrate from current players backend to another (Only works when using minetestserver or with --server)"))));
291 allowed_options->insert(std::make_pair("migrate-auth", ValueSpec(VALUETYPE_STRING,
292 _("Migrate from current auth backend to another (Only works when using minetestserver or with --server)"))));
293 allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
294 _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
296 allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
297 _("Show available video modes"))));
298 allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
299 _("Run speed tests"))));
300 allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
301 _("Address to connect to. ('' = local game)"))));
302 allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
303 _("Enable random user input, for testing"))));
304 allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
305 _("Run dedicated server"))));
306 allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
307 _("Set player name"))));
308 allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
309 _("Set password"))));
310 allowed_options->insert(std::make_pair("password-file", ValueSpec(VALUETYPE_STRING,
311 _("Set password from contents of file"))));
312 allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
313 _("Disable main menu"))));
314 allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
315 _("Starts with the console (Windows only)"))));
320 static void print_help(const OptionList &allowed_options)
322 std::cout << _("Allowed options:") << std::endl;
323 print_allowed_options(allowed_options);
326 static void print_allowed_options(const OptionList &allowed_options)
328 for (const auto &allowed_option : allowed_options) {
329 std::ostringstream os1(std::ios::binary);
330 os1 << " --" << allowed_option.first;
331 if (allowed_option.second.type != VALUETYPE_FLAG)
332 os1 << _(" <value>");
334 std::cout << padStringRight(os1.str(), 30);
336 if (allowed_option.second.help)
337 std::cout << allowed_option.second.help;
339 std::cout << std::endl;
343 static void print_version()
345 std::cout << PROJECT_NAME_C " " << g_version_hash
346 << " (" << porting::getPlatformName() << ")" << std::endl;
348 std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl;
350 std::cout << g_build_info << std::endl;
353 static void list_game_ids()
355 std::set<std::string> gameids = getAvailableGameIds();
356 for (const std::string &gameid : gameids)
357 std::cout << gameid <<std::endl;
360 static void list_worlds(bool print_name, bool print_path)
362 std::cout << _("Available worlds:") << std::endl;
363 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
364 print_worldspecs(worldspecs, std::cout, print_name, print_path);
367 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
368 std::ostream &os, bool print_name, bool print_path)
370 for (const WorldSpec &worldspec : worldspecs) {
371 std::string name = worldspec.name;
372 std::string path = worldspec.path;
373 if (print_name && print_path) {
374 os << "\t" << name << "\t\t" << path << std::endl;
375 } else if (print_name) {
376 os << "\t" << name << std::endl;
377 } else if (print_path) {
378 os << "\t" << path << std::endl;
383 static void print_modified_quicktune_values()
385 bool header_printed = false;
386 std::vector<std::string> names = getQuicktuneNames();
388 for (const std::string &name : names) {
389 QuicktuneValue val = getQuicktuneValue(name);
392 if (!header_printed) {
393 dstream << "Modified quicktune values:" << std::endl;
394 header_printed = true;
396 dstream << name << " = " << val.getString() << std::endl;
400 static bool setup_log_params(const Settings &cmd_args)
402 // Quiet mode, print errors only
403 if (cmd_args.getFlag("quiet")) {
404 g_logger.removeOutput(&stderr_output);
405 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
408 // Coloured log messages (see log.h)
409 std::string color_mode;
410 if (cmd_args.exists("color")) {
411 color_mode = cmd_args.get("color");
414 char *color_mode_env = getenv("MT_LOGCOLOR");
416 color_mode = color_mode_env;
419 if (color_mode != "") {
420 if (color_mode == "auto") {
421 Logger::color_mode = LOG_COLOR_AUTO;
422 } else if (color_mode == "always") {
423 Logger::color_mode = LOG_COLOR_ALWAYS;
424 } else if (color_mode == "never") {
425 Logger::color_mode = LOG_COLOR_NEVER;
427 errorstream << "Invalid color mode: " << color_mode << std::endl;
432 // If trace is enabled, enable logging of certain things
433 if (cmd_args.getFlag("trace")) {
434 dstream << _("Enabling trace level debug output") << std::endl;
435 g_logger.setTraceEnabled(true);
436 dout_con_ptr = &verbosestream; // This is somewhat old
437 socket_enable_debug_output = true; // Sockets doesn't use log.h
440 // In certain cases, output info level on stderr
441 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
442 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
443 g_logger.addOutput(&stderr_output, LL_INFO);
445 // In certain cases, output verbose level on stderr
446 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
447 g_logger.addOutput(&stderr_output, LL_VERBOSE);
452 static bool create_userdata_path()
457 if (!fs::PathExists(porting::path_user)) {
458 success = fs::CreateDir(porting::path_user);
462 porting::copyAssets();
464 // Create user data directory
465 success = fs::CreateDir(porting::path_user);
471 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
474 set_default_settings(g_settings);
476 // Initialize sockets
478 atexit(sockets_cleanup);
480 if (!read_config_file(cmd_args))
483 init_log_streams(cmd_args);
485 // Initialize random seed
489 // Initialize HTTP fetcher
490 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
492 init_gettext(porting::path_locale.c_str(),
493 g_settings->get("language"), argc, argv);
498 static void startup_message()
500 infostream << PROJECT_NAME << " " << _("with")
501 << " SER_FMT_VER_HIGHEST_READ="
502 << (int)SER_FMT_VER_HIGHEST_READ << ", "
503 << g_build_info << std::endl;
506 static bool read_config_file(const Settings &cmd_args)
508 // Path of configuration file in use
509 sanity_check(g_settings_path == ""); // Sanity check
511 if (cmd_args.exists("config")) {
512 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
514 errorstream << "Could not read configuration from \""
515 << cmd_args.get("config") << "\"" << std::endl;
518 g_settings_path = cmd_args.get("config");
520 std::vector<std::string> filenames;
521 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
522 // Legacy configuration file location
523 filenames.push_back(porting::path_user +
524 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
527 // Try also from a lower level (to aid having the same configuration
528 // for many RUN_IN_PLACE installs)
529 filenames.push_back(porting::path_user +
530 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
533 for (const std::string &filename : filenames) {
534 bool r = g_settings->readConfigFile(filename.c_str());
536 g_settings_path = filename;
541 // If no path found, use the first one (menu creates the file)
542 if (g_settings_path.empty())
543 g_settings_path = filenames[0];
549 static void init_log_streams(const Settings &cmd_args)
551 std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
553 if (cmd_args.exists("logfile"))
554 log_filename = cmd_args.get("logfile");
556 g_logger.removeOutput(&file_log_output);
557 std::string conf_loglev = g_settings->get("debug_log_level");
559 // Old integer format
560 if (std::isdigit(conf_loglev[0])) {
561 warningstream << "Deprecated use of debug_log_level with an "
562 "integer value; please update your configuration." << std::endl;
563 static const char *lev_name[] =
564 {"", "error", "action", "info", "verbose"};
565 int lev_i = atoi(conf_loglev.c_str());
566 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
567 warningstream << "Supplied invalid debug_log_level!"
568 " Assuming action level." << std::endl;
571 conf_loglev = lev_name[lev_i];
574 if (log_filename.empty() || conf_loglev.empty()) // No logging
577 LogLevel log_level = Logger::stringToLevel(conf_loglev);
578 if (log_level == LL_MAX) {
579 warningstream << "Supplied unrecognized debug_log_level; "
580 "using maximum." << std::endl;
583 verbosestream << "log_filename = " << log_filename << std::endl;
585 file_log_output.open(log_filename);
586 g_logger.addOutputMaxLevel(&file_log_output, log_level);
589 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
591 game_configure_port(game_params, cmd_args);
593 if (!game_configure_world(game_params, cmd_args)) {
594 errorstream << "No world path specified or found." << std::endl;
598 game_configure_subgame(game_params, cmd_args);
603 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
605 if (cmd_args.exists("port"))
606 game_params->socket_port = cmd_args.getU16("port");
608 game_params->socket_port = g_settings->getU16("port");
610 if (game_params->socket_port == 0)
611 game_params->socket_port = DEFAULT_SERVER_PORT;
614 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
616 if (get_world_from_cmdline(game_params, cmd_args))
619 if (get_world_from_config(game_params, cmd_args))
622 return auto_select_world(game_params);
625 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
627 std::string commanded_world;
630 std::string commanded_worldname;
631 if (cmd_args.exists("worldname"))
632 commanded_worldname = cmd_args.get("worldname");
634 // If a world name was specified, convert it to a path
635 if (!commanded_worldname.empty()) {
636 // Get information about available worlds
637 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
639 for (const WorldSpec &worldspec : worldspecs) {
640 std::string name = worldspec.name;
641 if (name == commanded_worldname) {
642 dstream << _("Using world specified by --worldname on the "
643 "command line") << std::endl;
644 commanded_world = worldspec.path;
650 dstream << _("World") << " '" << commanded_worldname
651 << _("' not available. Available worlds:") << std::endl;
652 print_worldspecs(worldspecs, dstream);
656 game_params->world_path = get_clean_world_path(commanded_world);
657 return !commanded_world.empty();
660 if (cmd_args.exists("world"))
661 commanded_world = cmd_args.get("world");
662 else if (cmd_args.exists("map-dir"))
663 commanded_world = cmd_args.get("map-dir");
664 else if (cmd_args.exists("nonopt0")) // First nameless argument
665 commanded_world = cmd_args.get("nonopt0");
667 game_params->world_path = get_clean_world_path(commanded_world);
668 return !commanded_world.empty();
671 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
674 std::string commanded_world;
676 if (g_settings->exists("map-dir"))
677 commanded_world = g_settings->get("map-dir");
679 game_params->world_path = get_clean_world_path(commanded_world);
681 return !commanded_world.empty();
684 static bool auto_select_world(GameParams *game_params)
686 // No world was specified; try to select it automatically
687 // Get information about available worlds
689 verbosestream << _("Determining world path") << std::endl;
691 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
692 std::string world_path;
694 // If there is only a single world, use it
695 if (worldspecs.size() == 1) {
696 world_path = worldspecs[0].path;
697 dstream <<_("Automatically selecting world at") << " ["
698 << world_path << "]" << std::endl;
699 // If there are multiple worlds, list them
700 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
701 std::cerr << _("Multiple worlds are available.") << std::endl;
702 std::cerr << _("Please select one using --worldname <name>"
703 " or --world <path>") << std::endl;
704 print_worldspecs(worldspecs, std::cerr);
706 // If there are no worlds, automatically create a new one
708 // This is the ultimate default world path
709 world_path = porting::path_user + DIR_DELIM + "worlds" +
711 infostream << "Creating default world at ["
712 << world_path << "]" << std::endl;
715 assert(world_path != ""); // Post-condition
716 game_params->world_path = world_path;
720 static std::string get_clean_world_path(const std::string &path)
722 const std::string worldmt = "world.mt";
723 std::string clean_path;
725 if (path.size() > worldmt.size()
726 && path.substr(path.size() - worldmt.size()) == worldmt) {
727 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
728 clean_path = path.substr(0, path.size() - worldmt.size());
736 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
740 success = get_game_from_cmdline(game_params, cmd_args);
742 success = determine_subgame(game_params);
747 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
749 SubgameSpec commanded_gamespec;
751 if (cmd_args.exists("gameid")) {
752 std::string gameid = cmd_args.get("gameid");
753 commanded_gamespec = findSubgame(gameid);
754 if (!commanded_gamespec.isValid()) {
755 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
758 dstream << _("Using game specified by --gameid on the command line")
760 game_params->game_spec = commanded_gamespec;
767 static bool determine_subgame(GameParams *game_params)
769 SubgameSpec gamespec;
771 assert(game_params->world_path != ""); // Pre-condition
773 verbosestream << _("Determining gameid/gamespec") << std::endl;
774 // If world doesn't exist
775 if (!game_params->world_path.empty()
776 && !getWorldExists(game_params->world_path)) {
777 // Try to take gamespec from command line
778 if (game_params->game_spec.isValid()) {
779 gamespec = game_params->game_spec;
780 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
781 } else { // Otherwise we will be using "minetest"
782 gamespec = findSubgame(g_settings->get("default_game"));
783 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
784 if (!gamespec.isValid()) {
785 errorstream << "Subgame specified in default_game ["
786 << g_settings->get("default_game")
787 << "] is invalid." << std::endl;
791 } else { // World exists
792 std::string world_gameid = getWorldGameId(game_params->world_path, false);
793 // If commanded to use a gameid, do so
794 if (game_params->game_spec.isValid()) {
795 gamespec = game_params->game_spec;
796 if (game_params->game_spec.id != world_gameid) {
797 warningstream << "Using commanded gameid ["
798 << gamespec.id << "]" << " instead of world gameid ["
799 << world_gameid << "]" << std::endl;
802 // If world contains an embedded game, use it;
803 // Otherwise find world from local system.
804 gamespec = findWorldSubgame(game_params->world_path);
805 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
809 if (!gamespec.isValid()) {
810 errorstream << "Subgame [" << gamespec.id << "] could not be found."
815 game_params->game_spec = gamespec;
820 /*****************************************************************************
822 *****************************************************************************/
823 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
825 verbosestream << _("Using world path") << " ["
826 << game_params.world_path << "]" << std::endl;
827 verbosestream << _("Using gameid") << " ["
828 << game_params.game_spec.id << "]" << std::endl;
831 std::string bind_str = g_settings->get("bind_address");
832 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
834 if (g_settings->getBool("ipv6_server")) {
835 bind_addr.setAddress((IPv6AddressBytes*) NULL);
838 bind_addr.Resolve(bind_str.c_str());
839 } catch (ResolveError &e) {
840 infostream << "Resolving bind address \"" << bind_str
841 << "\" failed: " << e.what()
842 << " -- Listening on all addresses." << std::endl;
844 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
845 errorstream << "Unable to listen on "
846 << bind_addr.serializeString()
847 << L" because IPv6 is disabled" << std::endl;
851 // Database migration
852 if (cmd_args.exists("migrate"))
853 return migrate_map_database(game_params, cmd_args);
855 if (cmd_args.exists("migrate-players"))
856 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
858 if (cmd_args.exists("migrate-auth"))
859 return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);
861 if (cmd_args.exists("terminal")) {
864 std::string admin_nick = g_settings->get("name");
866 name_ok = name_ok && !admin_nick.empty();
867 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
870 if (admin_nick.empty()) {
871 errorstream << "No name given for admin. "
872 << "Please check your minetest.conf that it "
873 << "contains a 'name = ' to your main admin account."
876 errorstream << "Name for admin '"
877 << admin_nick << "' is not valid. "
878 << "Please check that it only contains allowed characters. "
879 << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
885 bool &kill = *porting::signal_handler_killstatus();
889 Server server(game_params.world_path, game_params.game_spec,
890 false, bind_addr, true, &iface);
893 g_term_console.setup(&iface, &kill, admin_nick);
895 g_term_console.start();
899 dedicated_server_loop(server, kill);
900 } catch (const ModError &e) {
901 g_term_console.stopAndWaitforThread();
902 errorstream << "ModError: " << e.what() << std::endl;
904 } catch (const ServerError &e) {
905 g_term_console.stopAndWaitforThread();
906 errorstream << "ServerError: " << e.what() << std::endl;
910 // Tell the console to stop, and wait for it to finish,
911 // only then leave context and free iface
912 g_term_console.stop();
913 g_term_console.wait();
915 g_term_console.clearKillStatus();
918 errorstream << "Cmd arg --terminal passed, but "
919 << "compiled without ncurses. Ignoring." << std::endl;
924 Server server(game_params.world_path, game_params.game_spec, false,
930 bool &kill = *porting::signal_handler_killstatus();
931 dedicated_server_loop(server, kill);
933 } catch (const ModError &e) {
934 errorstream << "ModError: " << e.what() << std::endl;
936 } catch (const ServerError &e) {
937 errorstream << "ServerError: " << e.what() << std::endl;
945 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
947 std::string migrate_to = cmd_args.get("migrate");
949 std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
950 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
951 errorstream << "Cannot read world.mt!" << std::endl;
955 if (!world_mt.exists("backend")) {
956 errorstream << "Please specify your current backend in world.mt:"
958 << " backend = {sqlite3|leveldb|redis|dummy|postgresql}"
963 std::string backend = world_mt.get("backend");
964 if (backend == migrate_to) {
965 errorstream << "Cannot migrate: new backend is same"
966 << " as the old one" << std::endl;
970 MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
971 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
974 time_t last_update_time = 0;
975 bool &kill = *porting::signal_handler_killstatus();
977 std::vector<v3s16> blocks;
978 old_db->listAllLoadableBlocks(blocks);
980 for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
981 if (kill) return false;
984 old_db->loadBlock(*it, &data);
986 new_db->saveBlock(*it, data);
988 errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
990 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
991 std::cerr << " Migrated " << count << " blocks, "
992 << (100.0 * count / blocks.size()) << "% completed.\r";
995 last_update_time = time(NULL);
998 std::cerr << std::endl;
1003 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1004 world_mt.set("backend", migrate_to);
1005 if (!world_mt.updateConfigFile(world_mt_path.c_str()))
1006 errorstream << "Failed to update world.mt!" << std::endl;
1008 actionstream << "world.mt updated" << std::endl;