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 "benchmark/benchmark.h"
24 #include "chat_interface.h"
26 #include "unittest/test.h"
30 #include "client/game.h"
31 #include "defaultsettings.h"
34 #include "util/quicktune.h"
35 #include "httpfetch.h"
36 #include "gameparams.h"
37 #include "database/database.h"
41 #include "network/socket.h"
44 #include "terminal_chat_console.h"
47 #include "gui/guiMainMenu.h"
48 #include "client/clientlauncher.h"
49 #include "gui/guiEngine.h"
50 #include "gui/mainmenumanager.h"
52 #ifdef HAVE_TOUCHSCREENGUI
53 #include "gui/touchscreengui.h"
56 // for version information only
65 #if !defined(__cpp_rtti) || !defined(__cpp_exceptions)
66 #error Minetest cannot be built without exceptions or RTTI
69 #if defined(__MINGW32__) && !defined(__MINGW64__) && !defined(__clang__) && \
70 (__GNUC__ < 11 || (__GNUC__ == 11 && __GNUC_MINOR__ < 1))
71 // see e.g. https://github.com/minetest/minetest/issues/10137
72 #warning ==================================
73 #warning 32-bit MinGW gcc before 11.1 has known issues with crashes on thread exit, you should upgrade.
74 #warning ==================================
77 #define DEBUGFILE "debug.txt"
78 #define DEFAULT_SERVER_PORT 30000
80 typedef std::map<std::string, ValueSpec> OptionList;
82 /**********************************************************************
84 **********************************************************************/
86 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
87 static void set_allowed_options(OptionList *allowed_options);
89 static void print_help(const OptionList &allowed_options);
90 static void print_allowed_options(const OptionList &allowed_options);
91 static void print_version();
92 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
93 std::ostream &os, bool print_name = true, bool print_path = true);
94 static void print_modified_quicktune_values();
96 static void list_game_ids();
97 static void list_worlds(bool print_name, bool print_path);
98 static bool setup_log_params(const Settings &cmd_args);
99 static bool create_userdata_path();
100 static bool init_common(const Settings &cmd_args, int argc, char *argv[]);
101 static void uninit_common();
102 static void startup_message();
103 static bool read_config_file(const Settings &cmd_args);
104 static void init_log_streams(const Settings &cmd_args);
106 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
107 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
109 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
110 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
111 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
112 static bool auto_select_world(GameParams *game_params);
113 static std::string get_clean_world_path(const std::string &path);
115 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
116 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
117 static bool determine_subgame(GameParams *game_params);
119 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
120 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args);
121 static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr);
123 /**********************************************************************/
126 FileLogOutput file_log_output;
128 static OptionList allowed_options;
130 int main(int argc, char *argv[])
133 debug_set_exception_handler();
135 g_logger.registerThread("Main");
136 g_logger.addOutputMaxLevel(&stderr_output, LL_ACTION);
139 bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
141 || cmd_args.getFlag("help")
142 || cmd_args.exists("nonopt1")) {
143 porting::attachOrCreateConsole();
144 print_help(allowed_options);
145 return cmd_args_ok ? 0 : 1;
147 if (cmd_args.getFlag("console"))
148 porting::attachOrCreateConsole();
150 if (cmd_args.getFlag("version")) {
151 porting::attachOrCreateConsole();
156 if (!setup_log_params(cmd_args))
159 porting::signal_handler_init();
162 porting::initAndroid();
163 porting::initializePathsAndroid();
165 porting::initializePaths();
168 if (!create_userdata_path()) {
169 errorstream << "Cannot create user data directory" << std::endl;
174 BEGIN_DEBUG_EXCEPTION_HANDLER
176 // List gameids if requested
177 if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
182 // List worlds, world names, and world paths if requested
183 if (cmd_args.exists("worldlist")) {
184 if (cmd_args.get("worldlist") == "name") {
185 list_worlds(true, false);
186 } else if (cmd_args.get("worldlist") == "path") {
187 list_worlds(false, true);
188 } else if (cmd_args.get("worldlist") == "both") {
189 list_worlds(true, true);
191 errorstream << "Invalid --worldlist value: "
192 << cmd_args.get("worldlist") << std::endl;
198 if (!init_common(cmd_args, argc, argv))
201 if (g_settings->getBool("enable_console"))
202 porting::attachOrCreateConsole();
206 if (cmd_args.getFlag("run-unittests")) {
210 errorstream << "Unittest support is not enabled in this binary. "
211 << "If you want to enable it, compile project with BUILD_UNITTESTS=1 flag."
218 if (cmd_args.getFlag("run-benchmarks")) {
220 return run_benchmarks();
222 errorstream << "Benchmark support is not enabled in this binary. "
223 << "If you want to enable it, compile project with BUILD_BENCHMARKS=1 flag."
228 #endif // __ANDROID__
230 GameStartData game_params;
232 porting::attachOrCreateConsole();
233 game_params.is_dedicated_server = true;
235 const bool isServer = cmd_args.getFlag("server");
237 porting::attachOrCreateConsole();
238 game_params.is_dedicated_server = isServer;
241 if (!game_configure(&game_params, cmd_args))
244 sanity_check(!game_params.world_path.empty());
246 if (game_params.is_dedicated_server)
247 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
250 retval = ClientLauncher().run(game_params, cmd_args) ? 0 : 1;
255 // Update configuration file
256 if (!g_settings_path.empty())
257 g_settings->updateConfigFile(g_settings_path.c_str());
259 print_modified_quicktune_values();
261 END_DEBUG_EXCEPTION_HANDLER
267 /*****************************************************************************
269 *****************************************************************************/
272 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
274 set_allowed_options(&allowed_options);
276 return cmd_args->parseCommandLine(argc, argv, allowed_options);
279 static void set_allowed_options(OptionList *allowed_options)
281 allowed_options->clear();
283 allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
284 _("Show allowed options"))));
285 allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
286 _("Show version information"))));
287 allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
288 _("Load configuration from specified file"))));
289 allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
290 _("Set network port (UDP)"))));
291 allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
292 _("Run the unit tests and exit"))));
293 allowed_options->insert(std::make_pair("run-benchmarks", ValueSpec(VALUETYPE_FLAG,
294 _("Run the benchmarks and exit"))));
295 allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
296 _("Same as --world (deprecated)"))));
297 allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
298 _("Set world path (implies local game if used with option --go)"))));
299 allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
300 _("Set world by name (implies local game if used with option --go)"))));
301 allowed_options->insert(std::make_pair("worldlist", ValueSpec(VALUETYPE_STRING,
302 _("Get list of worlds ('path' lists paths, "
303 "'name' lists names, 'both' lists both)"))));
304 allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
305 _("Print to console errors only"))));
306 allowed_options->insert(std::make_pair("color", ValueSpec(VALUETYPE_STRING,
307 _("Coloured logs ('always', 'never' or 'auto'), defaults to 'auto'"
309 allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
310 _("Print more information to console"))));
311 allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
312 _("Print even more information to console"))));
313 allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
314 _("Print enormous amounts of information to log and console"))));
315 allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
316 _("Set logfile path ('' = no logging)"))));
317 allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
318 _("Set gameid (\"--gameid list\" prints available ones)"))));
319 allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
320 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
321 allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING,
322 _("Migrate from current players backend to another (Only works when using minetestserver or with --server)"))));
323 allowed_options->insert(std::make_pair("migrate-auth", ValueSpec(VALUETYPE_STRING,
324 _("Migrate from current auth backend to another (Only works when using minetestserver or with --server)"))));
325 allowed_options->insert(std::make_pair("migrate-mod-storage", ValueSpec(VALUETYPE_STRING,
326 _("Migrate from current mod storage backend to another (Only works when using minetestserver or with --server)"))));
327 allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
328 _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
329 allowed_options->insert(std::make_pair("recompress", ValueSpec(VALUETYPE_FLAG,
330 _("Recompress the blocks of the given map database."))));
332 allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
333 _("Run speed tests"))));
334 allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
335 _("Address to connect to. ('' = local game)"))));
336 allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
337 _("Enable random user input, for testing"))));
338 allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
339 _("Run dedicated server"))));
340 allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
341 _("Set player name"))));
342 allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
343 _("Set password"))));
344 allowed_options->insert(std::make_pair("password-file", ValueSpec(VALUETYPE_STRING,
345 _("Set password from contents of file"))));
346 allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
347 _("Disable main menu"))));
348 allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
349 _("Starts with the console (Windows only)"))));
354 static void print_help(const OptionList &allowed_options)
356 std::cout << _("Allowed options:") << std::endl;
357 print_allowed_options(allowed_options);
360 static void print_allowed_options(const OptionList &allowed_options)
362 for (const auto &allowed_option : allowed_options) {
363 std::ostringstream os1(std::ios::binary);
364 os1 << " --" << allowed_option.first;
365 if (allowed_option.second.type != VALUETYPE_FLAG)
366 os1 << _(" <value>");
368 std::cout << padStringRight(os1.str(), 30);
370 if (allowed_option.second.help)
371 std::cout << allowed_option.second.help;
373 std::cout << std::endl;
377 static void print_version()
379 std::cout << PROJECT_NAME_C " " << g_version_hash
380 << " (" << porting::getPlatformName() << ")" << std::endl;
382 std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl;
385 std::cout << "Using " << LUAJIT_VERSION << std::endl;
387 std::cout << "Using " << LUA_RELEASE << std::endl;
389 std::cout << g_build_info << std::endl;
392 static void list_game_ids()
394 std::set<std::string> gameids = getAvailableGameIds();
395 for (const std::string &gameid : gameids)
396 std::cout << gameid <<std::endl;
399 static void list_worlds(bool print_name, bool print_path)
401 std::cout << _("Available worlds:") << std::endl;
402 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
403 print_worldspecs(worldspecs, std::cout, print_name, print_path);
406 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
407 std::ostream &os, bool print_name, bool print_path)
409 for (const WorldSpec &worldspec : worldspecs) {
410 std::string name = worldspec.name;
411 std::string path = worldspec.path;
412 if (print_name && print_path) {
413 os << "\t" << name << "\t\t" << path << std::endl;
414 } else if (print_name) {
415 os << "\t" << name << std::endl;
416 } else if (print_path) {
417 os << "\t" << path << std::endl;
422 static void print_modified_quicktune_values()
424 bool header_printed = false;
425 std::vector<std::string> names = getQuicktuneNames();
427 for (const std::string &name : names) {
428 QuicktuneValue val = getQuicktuneValue(name);
431 if (!header_printed) {
432 dstream << "Modified quicktune values:" << std::endl;
433 header_printed = true;
435 dstream << name << " = " << val.getString() << std::endl;
439 static bool setup_log_params(const Settings &cmd_args)
441 // Quiet mode, print errors only
442 if (cmd_args.getFlag("quiet")) {
443 g_logger.removeOutput(&stderr_output);
444 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
447 // Coloured log messages (see log.h)
448 std::string color_mode;
449 if (cmd_args.exists("color")) {
450 color_mode = cmd_args.get("color");
453 char *color_mode_env = getenv("MT_LOGCOLOR");
455 color_mode = color_mode_env;
458 if (color_mode != "") {
459 if (color_mode == "auto") {
460 Logger::color_mode = LOG_COLOR_AUTO;
461 } else if (color_mode == "always") {
462 Logger::color_mode = LOG_COLOR_ALWAYS;
463 } else if (color_mode == "never") {
464 Logger::color_mode = LOG_COLOR_NEVER;
466 errorstream << "Invalid color mode: " << color_mode << std::endl;
471 // In certain cases, output info level on stderr
472 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
473 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
474 g_logger.addOutput(&stderr_output, LL_INFO);
476 // In certain cases, output verbose level on stderr
477 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
478 g_logger.addOutput(&stderr_output, LL_VERBOSE);
480 if (cmd_args.getFlag("trace")) {
481 dstream << _("Enabling trace level debug output") << std::endl;
482 g_logger.addOutput(&stderr_output, LL_TRACE);
483 socket_enable_debug_output = true;
489 static bool create_userdata_path()
494 if (!fs::PathExists(porting::path_user)) {
495 success = fs::CreateDir(porting::path_user);
500 // Create user data directory
501 success = fs::CreateDir(porting::path_user);
507 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
510 set_default_settings();
514 // Initialize g_settings
515 Settings::createLayer(SL_GLOBAL);
517 // Set cleanup callback(s) to run at process exit
518 atexit(uninit_common);
520 if (!read_config_file(cmd_args))
523 init_log_streams(cmd_args);
525 // Initialize random seed
529 // Initialize HTTP fetcher
530 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
532 init_gettext(porting::path_locale.c_str(),
533 g_settings->get("language"), argc, argv);
538 static void uninit_common()
544 // It'd actually be okay to leak these but we want to please valgrind...
545 for (int i = 0; i < (int)SL_TOTAL_COUNT; i++)
546 delete Settings::getLayer((SettingsLayer)i);
549 static void startup_message()
551 infostream << PROJECT_NAME << " " << _("with")
552 << " SER_FMT_VER_HIGHEST_READ="
553 << (int)SER_FMT_VER_HIGHEST_READ << ", "
554 << g_build_info << std::endl;
557 static bool read_config_file(const Settings &cmd_args)
559 // Path of configuration file in use
560 sanity_check(g_settings_path == ""); // Sanity check
562 if (cmd_args.exists("config")) {
563 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
565 errorstream << "Could not read configuration from \""
566 << cmd_args.get("config") << "\"" << std::endl;
569 g_settings_path = cmd_args.get("config");
571 std::vector<std::string> filenames;
572 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
573 // Legacy configuration file location
574 filenames.push_back(porting::path_user +
575 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
578 // Try also from a lower level (to aid having the same configuration
579 // for many RUN_IN_PLACE installs)
580 filenames.push_back(porting::path_user +
581 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
584 for (const std::string &filename : filenames) {
585 bool r = g_settings->readConfigFile(filename.c_str());
587 g_settings_path = filename;
592 // If no path found, use the first one (menu creates the file)
593 if (g_settings_path.empty())
594 g_settings_path = filenames[0];
600 static void init_log_streams(const Settings &cmd_args)
602 std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
604 if (cmd_args.exists("logfile"))
605 log_filename = cmd_args.get("logfile");
607 g_logger.removeOutput(&file_log_output);
608 std::string conf_loglev = g_settings->get("debug_log_level");
610 // Old integer format
611 if (std::isdigit(conf_loglev[0])) {
612 warningstream << "Deprecated use of debug_log_level with an "
613 "integer value; please update your configuration." << std::endl;
614 static const char *lev_name[] =
615 {"", "error", "action", "info", "verbose", "trace"};
616 int lev_i = atoi(conf_loglev.c_str());
617 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
618 warningstream << "Supplied invalid debug_log_level!"
619 " Assuming action level." << std::endl;
622 conf_loglev = lev_name[lev_i];
625 if (log_filename.empty() || conf_loglev.empty()) // No logging
628 LogLevel log_level = Logger::stringToLevel(conf_loglev);
629 if (log_level == LL_MAX) {
630 warningstream << "Supplied unrecognized debug_log_level; "
631 "using maximum." << std::endl;
634 file_log_output.setFile(log_filename,
635 g_settings->getU64("debug_log_size_max") * 1000000);
636 g_logger.addOutputMaxLevel(&file_log_output, log_level);
639 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
641 game_configure_port(game_params, cmd_args);
643 if (!game_configure_world(game_params, cmd_args)) {
644 errorstream << "No world path specified or found." << std::endl;
648 game_configure_subgame(game_params, cmd_args);
653 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
655 if (cmd_args.exists("port")) {
656 game_params->socket_port = cmd_args.getU16("port");
658 if (game_params->is_dedicated_server)
659 game_params->socket_port = g_settings->getU16("port");
661 game_params->socket_port = g_settings->getU16("remote_port");
664 if (game_params->socket_port == 0)
665 game_params->socket_port = DEFAULT_SERVER_PORT;
668 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
670 if (get_world_from_cmdline(game_params, cmd_args))
673 if (get_world_from_config(game_params, cmd_args))
676 return auto_select_world(game_params);
679 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
681 std::string commanded_world;
684 std::string commanded_worldname;
685 if (cmd_args.exists("worldname"))
686 commanded_worldname = cmd_args.get("worldname");
688 // If a world name was specified, convert it to a path
689 if (!commanded_worldname.empty()) {
690 // Get information about available worlds
691 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
693 for (const WorldSpec &worldspec : worldspecs) {
694 std::string name = worldspec.name;
695 if (name == commanded_worldname) {
696 dstream << _("Using world specified by --worldname on the "
697 "command line") << std::endl;
698 commanded_world = worldspec.path;
704 dstream << _("World") << " '" << commanded_worldname
705 << _("' not available. Available worlds:") << std::endl;
706 print_worldspecs(worldspecs, dstream);
710 game_params->world_path = get_clean_world_path(commanded_world);
711 return !commanded_world.empty();
714 if (cmd_args.exists("world"))
715 commanded_world = cmd_args.get("world");
716 else if (cmd_args.exists("map-dir"))
717 commanded_world = cmd_args.get("map-dir");
718 else if (cmd_args.exists("nonopt0")) // First nameless argument
719 commanded_world = cmd_args.get("nonopt0");
721 game_params->world_path = get_clean_world_path(commanded_world);
722 return !commanded_world.empty();
725 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
728 std::string commanded_world;
730 if (g_settings->exists("map-dir"))
731 commanded_world = g_settings->get("map-dir");
733 game_params->world_path = get_clean_world_path(commanded_world);
735 return !commanded_world.empty();
738 static bool auto_select_world(GameParams *game_params)
740 // No world was specified; try to select it automatically
741 // Get information about available worlds
743 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
744 std::string world_path;
746 // If there is only a single world, use it
747 if (worldspecs.size() == 1) {
748 world_path = worldspecs[0].path;
749 dstream <<_("Automatically selecting world at") << " ["
750 << world_path << "]" << std::endl;
751 // If there are multiple worlds, list them
752 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
753 std::cerr << _("Multiple worlds are available.") << std::endl;
754 std::cerr << _("Please select one using --worldname <name>"
755 " or --world <path>") << std::endl;
756 print_worldspecs(worldspecs, std::cerr);
758 // If there are no worlds, automatically create a new one
760 // This is the ultimate default world path
761 world_path = porting::path_user + DIR_DELIM + "worlds" +
763 infostream << "Using default world at ["
764 << world_path << "]" << std::endl;
767 assert(world_path != ""); // Post-condition
768 game_params->world_path = world_path;
772 static std::string get_clean_world_path(const std::string &path)
774 const std::string worldmt = "world.mt";
775 std::string clean_path;
777 if (path.size() > worldmt.size()
778 && path.substr(path.size() - worldmt.size()) == worldmt) {
779 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
780 clean_path = path.substr(0, path.size() - worldmt.size());
788 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
792 success = get_game_from_cmdline(game_params, cmd_args);
794 success = determine_subgame(game_params);
799 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
801 SubgameSpec commanded_gamespec;
803 if (cmd_args.exists("gameid")) {
804 std::string gameid = cmd_args.get("gameid");
805 commanded_gamespec = findSubgame(gameid);
806 if (!commanded_gamespec.isValid()) {
807 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
810 dstream << _("Using game specified by --gameid on the command line")
812 game_params->game_spec = commanded_gamespec;
819 static bool determine_subgame(GameParams *game_params)
821 SubgameSpec gamespec;
823 assert(game_params->world_path != ""); // Pre-condition
825 // If world doesn't exist
826 if (!game_params->world_path.empty()
827 && !getWorldExists(game_params->world_path)) {
828 // Try to take gamespec from command line
829 if (game_params->game_spec.isValid()) {
830 gamespec = game_params->game_spec;
831 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
832 } else { // Otherwise we will be using "minetest"
833 gamespec = findSubgame(g_settings->get("default_game"));
834 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
835 if (!gamespec.isValid()) {
836 errorstream << "Game specified in default_game ["
837 << g_settings->get("default_game")
838 << "] is invalid." << std::endl;
842 } else { // World exists
843 std::string world_gameid = getWorldGameId(game_params->world_path, false);
844 // If commanded to use a gameid, do so
845 if (game_params->game_spec.isValid()) {
846 gamespec = game_params->game_spec;
847 if (game_params->game_spec.id != world_gameid) {
848 warningstream << "Using commanded gameid ["
849 << gamespec.id << "]" << " instead of world gameid ["
850 << world_gameid << "]" << std::endl;
853 // If world contains an embedded game, use it;
854 // Otherwise find world from local system.
855 gamespec = findWorldSubgame(game_params->world_path);
856 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
860 if (!gamespec.isValid()) {
861 errorstream << "Game [" << gamespec.id << "] could not be found."
866 game_params->game_spec = gamespec;
871 /*****************************************************************************
873 *****************************************************************************/
874 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
876 verbosestream << _("Using world path") << " ["
877 << game_params.world_path << "]" << std::endl;
878 verbosestream << _("Using gameid") << " ["
879 << game_params.game_spec.id << "]" << std::endl;
882 std::string bind_str = g_settings->get("bind_address");
883 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
885 if (g_settings->getBool("ipv6_server")) {
886 bind_addr.setAddress((IPv6AddressBytes*) NULL);
889 bind_addr.Resolve(bind_str.c_str());
890 } catch (ResolveError &e) {
891 infostream << "Resolving bind address \"" << bind_str
892 << "\" failed: " << e.what()
893 << " -- Listening on all addresses." << std::endl;
895 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
896 errorstream << "Unable to listen on "
897 << bind_addr.serializeString()
898 << L" because IPv6 is disabled" << std::endl;
902 // Database migration/compression
903 if (cmd_args.exists("migrate"))
904 return migrate_map_database(game_params, cmd_args);
906 if (cmd_args.exists("migrate-players"))
907 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
909 if (cmd_args.exists("migrate-auth"))
910 return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);
912 if (cmd_args.exists("migrate-mod-storage"))
913 return Server::migrateModStorageDatabase(game_params, cmd_args);
915 if (cmd_args.getFlag("recompress"))
916 return recompress_map_database(game_params, cmd_args, bind_addr);
918 if (cmd_args.exists("terminal")) {
921 std::string admin_nick = g_settings->get("name");
923 name_ok = name_ok && !admin_nick.empty();
924 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
927 if (admin_nick.empty()) {
928 errorstream << "No name given for admin. "
929 << "Please check your minetest.conf that it "
930 << "contains a 'name = ' to your main admin account."
933 errorstream << "Name for admin '"
934 << admin_nick << "' is not valid. "
935 << "Please check that it only contains allowed characters. "
936 << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
942 bool &kill = *porting::signal_handler_killstatus();
946 Server server(game_params.world_path, game_params.game_spec,
947 false, bind_addr, true, &iface);
949 g_term_console.setup(&iface, &kill, admin_nick);
951 g_term_console.start();
955 dedicated_server_loop(server, kill);
956 } catch (const ModError &e) {
957 g_term_console.stopAndWaitforThread();
958 errorstream << "ModError: " << e.what() << std::endl;
960 } catch (const ServerError &e) {
961 g_term_console.stopAndWaitforThread();
962 errorstream << "ServerError: " << e.what() << std::endl;
966 // Tell the console to stop, and wait for it to finish,
967 // only then leave context and free iface
968 g_term_console.stop();
969 g_term_console.wait();
971 g_term_console.clearKillStatus();
974 errorstream << "Cmd arg --terminal passed, but "
975 << "compiled without ncurses. Ignoring." << std::endl;
980 Server server(game_params.world_path, game_params.game_spec, false,
985 bool &kill = *porting::signal_handler_killstatus();
986 dedicated_server_loop(server, kill);
988 } catch (const ModError &e) {
989 errorstream << "ModError: " << e.what() << std::endl;
991 } catch (const ServerError &e) {
992 errorstream << "ServerError: " << e.what() << std::endl;
1000 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
1002 std::string migrate_to = cmd_args.get("migrate");
1004 std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
1005 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
1006 errorstream << "Cannot read world.mt!" << std::endl;
1010 if (!world_mt.exists("backend")) {
1011 errorstream << "Please specify your current backend in world.mt:"
1013 << " backend = {sqlite3|leveldb|redis|dummy|postgresql}"
1018 std::string backend = world_mt.get("backend");
1019 if (backend == migrate_to) {
1020 errorstream << "Cannot migrate: new backend is same"
1021 << " as the old one" << std::endl;
1025 MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
1026 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
1029 time_t last_update_time = 0;
1030 bool &kill = *porting::signal_handler_killstatus();
1032 std::vector<v3s16> blocks;
1033 old_db->listAllLoadableBlocks(blocks);
1034 new_db->beginSave();
1035 for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
1036 if (kill) return false;
1039 old_db->loadBlock(*it, &data);
1040 if (!data.empty()) {
1041 new_db->saveBlock(*it, data);
1043 errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
1045 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
1046 std::cerr << " Migrated " << count << " blocks, "
1047 << (100.0 * count / blocks.size()) << "% completed.\r";
1049 new_db->beginSave();
1050 last_update_time = time(NULL);
1053 std::cerr << std::endl;
1058 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1059 world_mt.set("backend", migrate_to);
1060 if (!world_mt.updateConfigFile(world_mt_path.c_str()))
1061 errorstream << "Failed to update world.mt!" << std::endl;
1063 actionstream << "world.mt updated" << std::endl;
1068 static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr)
1071 const std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
1073 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
1074 errorstream << "Cannot read world.mt at " << world_mt_path << std::endl;
1077 const std::string &backend = world_mt.get("backend");
1078 Server server(game_params.world_path, game_params.game_spec, false, addr, false);
1079 MapDatabase *db = ServerMap::createDatabase(backend, game_params.world_path, world_mt);
1082 u64 last_update_time = 0;
1083 bool &kill = *porting::signal_handler_killstatus();
1084 const u8 serialize_as_ver = SER_FMT_VER_HIGHEST_WRITE;
1086 // This is ok because the server doesn't actually run
1087 std::vector<v3s16> blocks;
1088 db->listAllLoadableBlocks(blocks);
1090 std::istringstream iss(std::ios_base::binary);
1091 std::ostringstream oss(std::ios_base::binary);
1092 for (auto it = blocks.begin(); it != blocks.end(); ++it) {
1093 if (kill) return false;
1096 db->loadBlock(*it, &data);
1098 errorstream << "Failed to load block " << PP(*it) << std::endl;
1105 MapBlock mb(nullptr, v3s16(0,0,0), &server);
1106 u8 ver = readU8(iss);
1107 mb.deSerialize(iss, ver, true);
1111 writeU8(oss, serialize_as_ver);
1112 mb.serialize(oss, serialize_as_ver, true, -1);
1114 db->saveBlock(*it, oss.str());
1117 if (count % 0xFF == 0 && porting::getTimeS() - last_update_time >= 1) {
1118 std::cerr << " Recompressed " << count << " blocks, "
1119 << (100.0f * count / blocks.size()) << "% completed.\r";
1122 last_update_time = porting::getTimeS();
1125 std::cerr << std::endl;
1128 actionstream << "Done, " << count << " blocks were recompressed." << std::endl;