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 "irrlichttypes.h" // must be included before anything irrlicht, see comment in the file
21 #include "irrlicht.h" // createDevice
22 #include "irrlichttypes_extrabloated.h"
23 #include "chat_interface.h"
25 #include "unittest/test.h"
29 #include "client/game.h"
30 #include "defaultsettings.h"
33 #include "util/quicktune.h"
34 #include "httpfetch.h"
35 #include "gameparams.h"
36 #include "database/database.h"
40 #include "network/socket.h"
43 #include "terminal_chat_console.h"
46 #include "gui/guiMainMenu.h"
47 #include "client/clientlauncher.h"
48 #include "gui/guiEngine.h"
49 #include "gui/mainmenumanager.h"
51 #ifdef HAVE_TOUCHSCREENGUI
52 #include "gui/touchscreengui.h"
55 // for version information only
64 #if !defined(__cpp_rtti) || !defined(__cpp_exceptions)
65 #error Minetest cannot be built without exceptions or RTTI
68 #if defined(__MINGW32__) && !defined(__MINGW64__) && !defined(__clang__) && \
69 (__GNUC__ < 11 || (__GNUC__ == 11 && __GNUC_MINOR__ < 1))
70 // see e.g. https://github.com/minetest/minetest/issues/10137
71 #warning ==================================
72 #warning 32-bit MinGW gcc before 11.1 has known issues with crashes on thread exit, you should upgrade.
73 #warning ==================================
76 #define DEBUGFILE "debug.txt"
77 #define DEFAULT_SERVER_PORT 30000
79 typedef std::map<std::string, ValueSpec> OptionList;
81 /**********************************************************************
83 **********************************************************************/
85 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
86 static void set_allowed_options(OptionList *allowed_options);
88 static void print_help(const OptionList &allowed_options);
89 static void print_allowed_options(const OptionList &allowed_options);
90 static void print_version();
91 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
92 std::ostream &os, bool print_name = true, bool print_path = true);
93 static void print_modified_quicktune_values();
95 static void list_game_ids();
96 static void list_worlds(bool print_name, bool print_path);
97 static bool setup_log_params(const Settings &cmd_args);
98 static bool create_userdata_path();
99 static bool init_common(const Settings &cmd_args, int argc, char *argv[]);
100 static void uninit_common();
101 static void startup_message();
102 static bool read_config_file(const Settings &cmd_args);
103 static void init_log_streams(const Settings &cmd_args);
105 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
106 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
108 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
109 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
110 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
111 static bool auto_select_world(GameParams *game_params);
112 static std::string get_clean_world_path(const std::string &path);
114 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
115 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
116 static bool determine_subgame(GameParams *game_params);
118 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
119 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args);
120 static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr);
122 /**********************************************************************/
125 FileLogOutput file_log_output;
127 static OptionList allowed_options;
129 int main(int argc, char *argv[])
132 debug_set_exception_handler();
134 g_logger.registerThread("Main");
135 g_logger.addOutputMaxLevel(&stderr_output, LL_ACTION);
138 bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
140 || cmd_args.getFlag("help")
141 || cmd_args.exists("nonopt1")) {
142 porting::attachOrCreateConsole();
143 print_help(allowed_options);
144 return cmd_args_ok ? 0 : 1;
146 if (cmd_args.getFlag("console"))
147 porting::attachOrCreateConsole();
149 if (cmd_args.getFlag("version")) {
150 porting::attachOrCreateConsole();
155 if (!setup_log_params(cmd_args))
158 porting::signal_handler_init();
161 porting::initAndroid();
162 porting::initializePathsAndroid();
164 porting::initializePaths();
167 if (!create_userdata_path()) {
168 errorstream << "Cannot create user data directory" << std::endl;
173 BEGIN_DEBUG_EXCEPTION_HANDLER
175 // List gameids if requested
176 if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
181 // List worlds, world names, and world paths if requested
182 if (cmd_args.exists("worldlist")) {
183 if (cmd_args.get("worldlist") == "name") {
184 list_worlds(true, false);
185 } else if (cmd_args.get("worldlist") == "path") {
186 list_worlds(false, true);
187 } else if (cmd_args.get("worldlist") == "both") {
188 list_worlds(true, true);
190 errorstream << "Invalid --worldlist value: "
191 << cmd_args.get("worldlist") << std::endl;
197 if (!init_common(cmd_args, argc, argv))
200 if (g_settings->getBool("enable_console"))
201 porting::attachOrCreateConsole();
205 if (cmd_args.getFlag("run-unittests")) {
209 errorstream << "Unittest support is not enabled in this binary. "
210 << "If you want to enable it, compile project with BUILD_UNITTESTS=1 flag."
217 GameStartData game_params;
219 porting::attachOrCreateConsole();
220 game_params.is_dedicated_server = true;
222 const bool isServer = cmd_args.getFlag("server");
224 porting::attachOrCreateConsole();
225 game_params.is_dedicated_server = isServer;
228 if (!game_configure(&game_params, cmd_args))
231 sanity_check(!game_params.world_path.empty());
233 if (game_params.is_dedicated_server)
234 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
237 retval = ClientLauncher().run(game_params, cmd_args) ? 0 : 1;
242 // Update configuration file
243 if (!g_settings_path.empty())
244 g_settings->updateConfigFile(g_settings_path.c_str());
246 print_modified_quicktune_values();
248 END_DEBUG_EXCEPTION_HANDLER
254 /*****************************************************************************
256 *****************************************************************************/
259 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
261 set_allowed_options(&allowed_options);
263 return cmd_args->parseCommandLine(argc, argv, allowed_options);
266 static void set_allowed_options(OptionList *allowed_options)
268 allowed_options->clear();
270 allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
271 _("Show allowed options"))));
272 allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
273 _("Show version information"))));
274 allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
275 _("Load configuration from specified file"))));
276 allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
277 _("Set network port (UDP)"))));
278 allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
279 _("Run the unit tests and exit"))));
280 allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
281 _("Same as --world (deprecated)"))));
282 allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
283 _("Set world path (implies local game if used with option --go)"))));
284 allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
285 _("Set world by name (implies local game if used with option --go)"))));
286 allowed_options->insert(std::make_pair("worldlist", ValueSpec(VALUETYPE_STRING,
287 _("Get list of worlds ('path' lists paths, "
288 "'name' lists names, 'both' lists both)"))));
289 allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
290 _("Print to console errors only"))));
291 allowed_options->insert(std::make_pair("color", ValueSpec(VALUETYPE_STRING,
292 _("Coloured logs ('always', 'never' or 'auto'), defaults to 'auto'"
294 allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
295 _("Print more information to console"))));
296 allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
297 _("Print even more information to console"))));
298 allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
299 _("Print enormous amounts of information to log and console"))));
300 allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
301 _("Set logfile path ('' = no logging)"))));
302 allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
303 _("Set gameid (\"--gameid list\" prints available ones)"))));
304 allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
305 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
306 allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING,
307 _("Migrate from current players backend to another (Only works when using minetestserver or with --server)"))));
308 allowed_options->insert(std::make_pair("migrate-auth", ValueSpec(VALUETYPE_STRING,
309 _("Migrate from current auth backend to another (Only works when using minetestserver or with --server)"))));
310 allowed_options->insert(std::make_pair("migrate-mod-storage", ValueSpec(VALUETYPE_STRING,
311 _("Migrate from current mod storage backend to another (Only works when using minetestserver or with --server)"))));
312 allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
313 _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
314 allowed_options->insert(std::make_pair("recompress", ValueSpec(VALUETYPE_FLAG,
315 _("Recompress the blocks of the given map database."))));
317 allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
318 _("Run speed tests"))));
319 allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
320 _("Address to connect to. ('' = local game)"))));
321 allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
322 _("Enable random user input, for testing"))));
323 allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
324 _("Run dedicated server"))));
325 allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
326 _("Set player name"))));
327 allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
328 _("Set password"))));
329 allowed_options->insert(std::make_pair("password-file", ValueSpec(VALUETYPE_STRING,
330 _("Set password from contents of file"))));
331 allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
332 _("Disable main menu"))));
333 allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
334 _("Starts with the console (Windows only)"))));
339 static void print_help(const OptionList &allowed_options)
341 std::cout << _("Allowed options:") << std::endl;
342 print_allowed_options(allowed_options);
345 static void print_allowed_options(const OptionList &allowed_options)
347 for (const auto &allowed_option : allowed_options) {
348 std::ostringstream os1(std::ios::binary);
349 os1 << " --" << allowed_option.first;
350 if (allowed_option.second.type != VALUETYPE_FLAG)
351 os1 << _(" <value>");
353 std::cout << padStringRight(os1.str(), 30);
355 if (allowed_option.second.help)
356 std::cout << allowed_option.second.help;
358 std::cout << std::endl;
362 static void print_version()
364 std::cout << PROJECT_NAME_C " " << g_version_hash
365 << " (" << porting::getPlatformName() << ")" << std::endl;
367 std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl;
370 std::cout << "Using " << LUAJIT_VERSION << std::endl;
372 std::cout << "Using " << LUA_RELEASE << std::endl;
374 std::cout << g_build_info << std::endl;
377 static void list_game_ids()
379 std::set<std::string> gameids = getAvailableGameIds();
380 for (const std::string &gameid : gameids)
381 std::cout << gameid <<std::endl;
384 static void list_worlds(bool print_name, bool print_path)
386 std::cout << _("Available worlds:") << std::endl;
387 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
388 print_worldspecs(worldspecs, std::cout, print_name, print_path);
391 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
392 std::ostream &os, bool print_name, bool print_path)
394 for (const WorldSpec &worldspec : worldspecs) {
395 std::string name = worldspec.name;
396 std::string path = worldspec.path;
397 if (print_name && print_path) {
398 os << "\t" << name << "\t\t" << path << std::endl;
399 } else if (print_name) {
400 os << "\t" << name << std::endl;
401 } else if (print_path) {
402 os << "\t" << path << std::endl;
407 static void print_modified_quicktune_values()
409 bool header_printed = false;
410 std::vector<std::string> names = getQuicktuneNames();
412 for (const std::string &name : names) {
413 QuicktuneValue val = getQuicktuneValue(name);
416 if (!header_printed) {
417 dstream << "Modified quicktune values:" << std::endl;
418 header_printed = true;
420 dstream << name << " = " << val.getString() << std::endl;
424 static bool setup_log_params(const Settings &cmd_args)
426 // Quiet mode, print errors only
427 if (cmd_args.getFlag("quiet")) {
428 g_logger.removeOutput(&stderr_output);
429 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
432 // Coloured log messages (see log.h)
433 std::string color_mode;
434 if (cmd_args.exists("color")) {
435 color_mode = cmd_args.get("color");
438 char *color_mode_env = getenv("MT_LOGCOLOR");
440 color_mode = color_mode_env;
443 if (color_mode != "") {
444 if (color_mode == "auto") {
445 Logger::color_mode = LOG_COLOR_AUTO;
446 } else if (color_mode == "always") {
447 Logger::color_mode = LOG_COLOR_ALWAYS;
448 } else if (color_mode == "never") {
449 Logger::color_mode = LOG_COLOR_NEVER;
451 errorstream << "Invalid color mode: " << color_mode << std::endl;
456 // In certain cases, output info level on stderr
457 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
458 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
459 g_logger.addOutput(&stderr_output, LL_INFO);
461 // In certain cases, output verbose level on stderr
462 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
463 g_logger.addOutput(&stderr_output, LL_VERBOSE);
465 if (cmd_args.getFlag("trace")) {
466 dstream << _("Enabling trace level debug output") << std::endl;
467 g_logger.addOutput(&stderr_output, LL_TRACE);
468 socket_enable_debug_output = true;
474 static bool create_userdata_path()
479 if (!fs::PathExists(porting::path_user)) {
480 success = fs::CreateDir(porting::path_user);
485 // Create user data directory
486 success = fs::CreateDir(porting::path_user);
492 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
495 set_default_settings();
499 // Initialize g_settings
500 Settings::createLayer(SL_GLOBAL);
502 // Set cleanup callback(s) to run at process exit
503 atexit(uninit_common);
505 if (!read_config_file(cmd_args))
508 init_log_streams(cmd_args);
510 // Initialize random seed
514 // Initialize HTTP fetcher
515 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
517 init_gettext(porting::path_locale.c_str(),
518 g_settings->get("language"), argc, argv);
523 static void uninit_common()
529 // It'd actually be okay to leak these but we want to please valgrind...
530 for (int i = 0; i < (int)SL_TOTAL_COUNT; i++)
531 delete Settings::getLayer((SettingsLayer)i);
534 static void startup_message()
536 infostream << PROJECT_NAME << " " << _("with")
537 << " SER_FMT_VER_HIGHEST_READ="
538 << (int)SER_FMT_VER_HIGHEST_READ << ", "
539 << g_build_info << std::endl;
542 static bool read_config_file(const Settings &cmd_args)
544 // Path of configuration file in use
545 sanity_check(g_settings_path == ""); // Sanity check
547 if (cmd_args.exists("config")) {
548 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
550 errorstream << "Could not read configuration from \""
551 << cmd_args.get("config") << "\"" << std::endl;
554 g_settings_path = cmd_args.get("config");
556 std::vector<std::string> filenames;
557 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
558 // Legacy configuration file location
559 filenames.push_back(porting::path_user +
560 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
563 // Try also from a lower level (to aid having the same configuration
564 // for many RUN_IN_PLACE installs)
565 filenames.push_back(porting::path_user +
566 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
569 for (const std::string &filename : filenames) {
570 bool r = g_settings->readConfigFile(filename.c_str());
572 g_settings_path = filename;
577 // If no path found, use the first one (menu creates the file)
578 if (g_settings_path.empty())
579 g_settings_path = filenames[0];
585 static void init_log_streams(const Settings &cmd_args)
587 std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
589 if (cmd_args.exists("logfile"))
590 log_filename = cmd_args.get("logfile");
592 g_logger.removeOutput(&file_log_output);
593 std::string conf_loglev = g_settings->get("debug_log_level");
595 // Old integer format
596 if (std::isdigit(conf_loglev[0])) {
597 warningstream << "Deprecated use of debug_log_level with an "
598 "integer value; please update your configuration." << std::endl;
599 static const char *lev_name[] =
600 {"", "error", "action", "info", "verbose", "trace"};
601 int lev_i = atoi(conf_loglev.c_str());
602 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
603 warningstream << "Supplied invalid debug_log_level!"
604 " Assuming action level." << std::endl;
607 conf_loglev = lev_name[lev_i];
610 if (log_filename.empty() || conf_loglev.empty()) // No logging
613 LogLevel log_level = Logger::stringToLevel(conf_loglev);
614 if (log_level == LL_MAX) {
615 warningstream << "Supplied unrecognized debug_log_level; "
616 "using maximum." << std::endl;
619 file_log_output.setFile(log_filename,
620 g_settings->getU64("debug_log_size_max") * 1000000);
621 g_logger.addOutputMaxLevel(&file_log_output, log_level);
624 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
626 game_configure_port(game_params, cmd_args);
628 if (!game_configure_world(game_params, cmd_args)) {
629 errorstream << "No world path specified or found." << std::endl;
633 game_configure_subgame(game_params, cmd_args);
638 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
640 if (cmd_args.exists("port")) {
641 game_params->socket_port = cmd_args.getU16("port");
643 if (game_params->is_dedicated_server)
644 game_params->socket_port = g_settings->getU16("port");
646 game_params->socket_port = g_settings->getU16("remote_port");
649 if (game_params->socket_port == 0)
650 game_params->socket_port = DEFAULT_SERVER_PORT;
653 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
655 if (get_world_from_cmdline(game_params, cmd_args))
658 if (get_world_from_config(game_params, cmd_args))
661 return auto_select_world(game_params);
664 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
666 std::string commanded_world;
669 std::string commanded_worldname;
670 if (cmd_args.exists("worldname"))
671 commanded_worldname = cmd_args.get("worldname");
673 // If a world name was specified, convert it to a path
674 if (!commanded_worldname.empty()) {
675 // Get information about available worlds
676 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
678 for (const WorldSpec &worldspec : worldspecs) {
679 std::string name = worldspec.name;
680 if (name == commanded_worldname) {
681 dstream << _("Using world specified by --worldname on the "
682 "command line") << std::endl;
683 commanded_world = worldspec.path;
689 dstream << _("World") << " '" << commanded_worldname
690 << _("' not available. Available worlds:") << std::endl;
691 print_worldspecs(worldspecs, dstream);
695 game_params->world_path = get_clean_world_path(commanded_world);
696 return !commanded_world.empty();
699 if (cmd_args.exists("world"))
700 commanded_world = cmd_args.get("world");
701 else if (cmd_args.exists("map-dir"))
702 commanded_world = cmd_args.get("map-dir");
703 else if (cmd_args.exists("nonopt0")) // First nameless argument
704 commanded_world = cmd_args.get("nonopt0");
706 game_params->world_path = get_clean_world_path(commanded_world);
707 return !commanded_world.empty();
710 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
713 std::string commanded_world;
715 if (g_settings->exists("map-dir"))
716 commanded_world = g_settings->get("map-dir");
718 game_params->world_path = get_clean_world_path(commanded_world);
720 return !commanded_world.empty();
723 static bool auto_select_world(GameParams *game_params)
725 // No world was specified; try to select it automatically
726 // Get information about available worlds
728 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
729 std::string world_path;
731 // If there is only a single world, use it
732 if (worldspecs.size() == 1) {
733 world_path = worldspecs[0].path;
734 dstream <<_("Automatically selecting world at") << " ["
735 << world_path << "]" << std::endl;
736 // If there are multiple worlds, list them
737 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
738 std::cerr << _("Multiple worlds are available.") << std::endl;
739 std::cerr << _("Please select one using --worldname <name>"
740 " or --world <path>") << std::endl;
741 print_worldspecs(worldspecs, std::cerr);
743 // If there are no worlds, automatically create a new one
745 // This is the ultimate default world path
746 world_path = porting::path_user + DIR_DELIM + "worlds" +
748 infostream << "Using default world at ["
749 << world_path << "]" << std::endl;
752 assert(world_path != ""); // Post-condition
753 game_params->world_path = world_path;
757 static std::string get_clean_world_path(const std::string &path)
759 const std::string worldmt = "world.mt";
760 std::string clean_path;
762 if (path.size() > worldmt.size()
763 && path.substr(path.size() - worldmt.size()) == worldmt) {
764 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
765 clean_path = path.substr(0, path.size() - worldmt.size());
773 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
777 success = get_game_from_cmdline(game_params, cmd_args);
779 success = determine_subgame(game_params);
784 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
786 SubgameSpec commanded_gamespec;
788 if (cmd_args.exists("gameid")) {
789 std::string gameid = cmd_args.get("gameid");
790 commanded_gamespec = findSubgame(gameid);
791 if (!commanded_gamespec.isValid()) {
792 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
795 dstream << _("Using game specified by --gameid on the command line")
797 game_params->game_spec = commanded_gamespec;
804 static bool determine_subgame(GameParams *game_params)
806 SubgameSpec gamespec;
808 assert(game_params->world_path != ""); // Pre-condition
810 // If world doesn't exist
811 if (!game_params->world_path.empty()
812 && !getWorldExists(game_params->world_path)) {
813 // Try to take gamespec from command line
814 if (game_params->game_spec.isValid()) {
815 gamespec = game_params->game_spec;
816 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
817 } else { // Otherwise we will be using "minetest"
818 gamespec = findSubgame(g_settings->get("default_game"));
819 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
820 if (!gamespec.isValid()) {
821 errorstream << "Game specified in default_game ["
822 << g_settings->get("default_game")
823 << "] is invalid." << std::endl;
827 } else { // World exists
828 std::string world_gameid = getWorldGameId(game_params->world_path, false);
829 // If commanded to use a gameid, do so
830 if (game_params->game_spec.isValid()) {
831 gamespec = game_params->game_spec;
832 if (game_params->game_spec.id != world_gameid) {
833 warningstream << "Using commanded gameid ["
834 << gamespec.id << "]" << " instead of world gameid ["
835 << world_gameid << "]" << std::endl;
838 // If world contains an embedded game, use it;
839 // Otherwise find world from local system.
840 gamespec = findWorldSubgame(game_params->world_path);
841 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
845 if (!gamespec.isValid()) {
846 errorstream << "Game [" << gamespec.id << "] could not be found."
851 game_params->game_spec = gamespec;
856 /*****************************************************************************
858 *****************************************************************************/
859 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
861 verbosestream << _("Using world path") << " ["
862 << game_params.world_path << "]" << std::endl;
863 verbosestream << _("Using gameid") << " ["
864 << game_params.game_spec.id << "]" << std::endl;
867 std::string bind_str = g_settings->get("bind_address");
868 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
870 if (g_settings->getBool("ipv6_server")) {
871 bind_addr.setAddress((IPv6AddressBytes*) NULL);
874 bind_addr.Resolve(bind_str.c_str());
875 } catch (ResolveError &e) {
876 infostream << "Resolving bind address \"" << bind_str
877 << "\" failed: " << e.what()
878 << " -- Listening on all addresses." << std::endl;
880 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
881 errorstream << "Unable to listen on "
882 << bind_addr.serializeString()
883 << L" because IPv6 is disabled" << std::endl;
887 // Database migration/compression
888 if (cmd_args.exists("migrate"))
889 return migrate_map_database(game_params, cmd_args);
891 if (cmd_args.exists("migrate-players"))
892 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
894 if (cmd_args.exists("migrate-auth"))
895 return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);
897 if (cmd_args.exists("migrate-mod-storage"))
898 return Server::migrateModStorageDatabase(game_params, cmd_args);
900 if (cmd_args.getFlag("recompress"))
901 return recompress_map_database(game_params, cmd_args, bind_addr);
903 if (cmd_args.exists("terminal")) {
906 std::string admin_nick = g_settings->get("name");
908 name_ok = name_ok && !admin_nick.empty();
909 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
912 if (admin_nick.empty()) {
913 errorstream << "No name given for admin. "
914 << "Please check your minetest.conf that it "
915 << "contains a 'name = ' to your main admin account."
918 errorstream << "Name for admin '"
919 << admin_nick << "' is not valid. "
920 << "Please check that it only contains allowed characters. "
921 << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
927 bool &kill = *porting::signal_handler_killstatus();
931 Server server(game_params.world_path, game_params.game_spec,
932 false, bind_addr, true, &iface);
934 g_term_console.setup(&iface, &kill, admin_nick);
936 g_term_console.start();
940 dedicated_server_loop(server, kill);
941 } catch (const ModError &e) {
942 g_term_console.stopAndWaitforThread();
943 errorstream << "ModError: " << e.what() << std::endl;
945 } catch (const ServerError &e) {
946 g_term_console.stopAndWaitforThread();
947 errorstream << "ServerError: " << e.what() << std::endl;
951 // Tell the console to stop, and wait for it to finish,
952 // only then leave context and free iface
953 g_term_console.stop();
954 g_term_console.wait();
956 g_term_console.clearKillStatus();
959 errorstream << "Cmd arg --terminal passed, but "
960 << "compiled without ncurses. Ignoring." << std::endl;
965 Server server(game_params.world_path, game_params.game_spec, false,
970 bool &kill = *porting::signal_handler_killstatus();
971 dedicated_server_loop(server, kill);
973 } catch (const ModError &e) {
974 errorstream << "ModError: " << e.what() << std::endl;
976 } catch (const ServerError &e) {
977 errorstream << "ServerError: " << e.what() << std::endl;
985 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
987 std::string migrate_to = cmd_args.get("migrate");
989 std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
990 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
991 errorstream << "Cannot read world.mt!" << std::endl;
995 if (!world_mt.exists("backend")) {
996 errorstream << "Please specify your current backend in world.mt:"
998 << " backend = {sqlite3|leveldb|redis|dummy|postgresql}"
1003 std::string backend = world_mt.get("backend");
1004 if (backend == migrate_to) {
1005 errorstream << "Cannot migrate: new backend is same"
1006 << " as the old one" << std::endl;
1010 MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
1011 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
1014 time_t last_update_time = 0;
1015 bool &kill = *porting::signal_handler_killstatus();
1017 std::vector<v3s16> blocks;
1018 old_db->listAllLoadableBlocks(blocks);
1019 new_db->beginSave();
1020 for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
1021 if (kill) return false;
1024 old_db->loadBlock(*it, &data);
1025 if (!data.empty()) {
1026 new_db->saveBlock(*it, data);
1028 errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
1030 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
1031 std::cerr << " Migrated " << count << " blocks, "
1032 << (100.0 * count / blocks.size()) << "% completed.\r";
1034 new_db->beginSave();
1035 last_update_time = time(NULL);
1038 std::cerr << std::endl;
1043 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1044 world_mt.set("backend", migrate_to);
1045 if (!world_mt.updateConfigFile(world_mt_path.c_str()))
1046 errorstream << "Failed to update world.mt!" << std::endl;
1048 actionstream << "world.mt updated" << std::endl;
1053 static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr)
1056 const std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
1058 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
1059 errorstream << "Cannot read world.mt at " << world_mt_path << std::endl;
1062 const std::string &backend = world_mt.get("backend");
1063 Server server(game_params.world_path, game_params.game_spec, false, addr, false);
1064 MapDatabase *db = ServerMap::createDatabase(backend, game_params.world_path, world_mt);
1067 u64 last_update_time = 0;
1068 bool &kill = *porting::signal_handler_killstatus();
1069 const u8 serialize_as_ver = SER_FMT_VER_HIGHEST_WRITE;
1071 // This is ok because the server doesn't actually run
1072 std::vector<v3s16> blocks;
1073 db->listAllLoadableBlocks(blocks);
1075 std::istringstream iss(std::ios_base::binary);
1076 std::ostringstream oss(std::ios_base::binary);
1077 for (auto it = blocks.begin(); it != blocks.end(); ++it) {
1078 if (kill) return false;
1081 db->loadBlock(*it, &data);
1083 errorstream << "Failed to load block " << PP(*it) << std::endl;
1090 MapBlock mb(nullptr, v3s16(0,0,0), &server);
1091 u8 ver = readU8(iss);
1092 mb.deSerialize(iss, ver, true);
1096 writeU8(oss, serialize_as_ver);
1097 mb.serialize(oss, serialize_as_ver, true, -1);
1099 db->saveBlock(*it, oss.str());
1102 if (count % 0xFF == 0 && porting::getTimeS() - last_update_time >= 1) {
1103 std::cerr << " Recompressed " << count << " blocks, "
1104 << (100.0f * count / blocks.size()) << "% completed.\r";
1107 last_update_time = porting::getTimeS();
1110 std::cerr << std::endl;
1113 actionstream << "Done, " << count << " blocks were recompressed." << std::endl;