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"
31 #include "client/game.h"
33 #include "defaultsettings.h"
36 #include "util/quicktune.h"
37 #include "httpfetch.h"
38 #include "gameparams.h"
39 #include "database/database.h"
43 #include "network/socket.h"
46 #include "terminal_chat_console.h"
49 #include "gui/guiMainMenu.h"
50 #include "client/clientlauncher.h"
51 #include "gui/guiEngine.h"
52 #include "gui/mainmenumanager.h"
54 #ifdef HAVE_TOUCHSCREENGUI
55 #include "gui/touchscreengui.h"
58 // for version information only
67 #if !defined(__cpp_rtti) || !defined(__cpp_exceptions)
68 #error Minetest cannot be built without exceptions or RTTI
71 #if defined(__MINGW32__) && !defined(__MINGW64__) && !defined(__clang__) && \
72 (__GNUC__ < 11 || (__GNUC__ == 11 && __GNUC_MINOR__ < 1))
73 // see e.g. https://github.com/minetest/minetest/issues/10137
74 #warning ==================================
75 #warning 32-bit MinGW gcc before 11.1 has known issues with crashes on thread exit, you should upgrade.
76 #warning ==================================
79 #define DEBUGFILE "debug.txt"
80 #define DEFAULT_SERVER_PORT 30000
82 typedef std::map<std::string, ValueSpec> OptionList;
84 /**********************************************************************
86 **********************************************************************/
88 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
89 static void set_allowed_options(OptionList *allowed_options);
91 static void print_help(const OptionList &allowed_options);
92 static void print_allowed_options(const OptionList &allowed_options);
93 static void print_version();
94 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
95 std::ostream &os, bool print_name = true, bool print_path = true);
96 static void print_modified_quicktune_values();
98 static void list_game_ids();
99 static void list_worlds(bool print_name, bool print_path);
100 static bool setup_log_params(const Settings &cmd_args);
101 static bool create_userdata_path();
102 static bool init_common(const Settings &cmd_args, int argc, char *argv[]);
103 static void uninit_common();
104 static void startup_message();
105 static bool read_config_file(const Settings &cmd_args);
106 static void init_log_streams(const Settings &cmd_args);
108 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
109 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
111 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
112 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
113 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
114 static bool auto_select_world(GameParams *game_params);
115 static std::string get_clean_world_path(const std::string &path);
117 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
118 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
119 static bool determine_subgame(GameParams *game_params);
121 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
122 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args);
123 static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr);
125 /**********************************************************************/
128 FileLogOutput file_log_output;
130 static OptionList allowed_options;
132 int main(int argc, char *argv[])
135 debug_set_exception_handler();
137 g_logger.registerThread("Main");
138 g_logger.addOutputMaxLevel(&stderr_output, LL_ACTION);
141 bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
143 || cmd_args.getFlag("help")
144 || cmd_args.exists("nonopt1")) {
145 porting::attachOrCreateConsole();
146 print_help(allowed_options);
147 return cmd_args_ok ? 0 : 1;
149 if (cmd_args.getFlag("console"))
150 porting::attachOrCreateConsole();
152 if (cmd_args.getFlag("version")) {
153 porting::attachOrCreateConsole();
158 if (!setup_log_params(cmd_args))
161 porting::signal_handler_init();
164 porting::initAndroid();
165 porting::initializePathsAndroid();
167 porting::initializePaths();
170 if (!create_userdata_path()) {
171 errorstream << "Cannot create user data directory" << std::endl;
176 BEGIN_DEBUG_EXCEPTION_HANDLER
178 // List gameids if requested
179 if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
184 // List worlds, world names, and world paths if requested
185 if (cmd_args.exists("worldlist")) {
186 if (cmd_args.get("worldlist") == "name") {
187 list_worlds(true, false);
188 } else if (cmd_args.get("worldlist") == "path") {
189 list_worlds(false, true);
190 } else if (cmd_args.get("worldlist") == "both") {
191 list_worlds(true, true);
193 errorstream << "Invalid --worldlist value: "
194 << cmd_args.get("worldlist") << std::endl;
200 if (!init_common(cmd_args, argc, argv))
203 if (g_settings->getBool("enable_console"))
204 porting::attachOrCreateConsole();
208 if (cmd_args.getFlag("run-unittests")) {
212 errorstream << "Unittest support is not enabled in this binary. "
213 << "If you want to enable it, compile project with BUILD_UNITTESTS=1 flag."
220 if (cmd_args.getFlag("run-benchmarks")) {
222 return run_benchmarks();
224 errorstream << "Benchmark support is not enabled in this binary. "
225 << "If you want to enable it, compile project with BUILD_BENCHMARKS=1 flag."
230 #endif // __ANDROID__
232 GameStartData game_params;
234 porting::attachOrCreateConsole();
235 game_params.is_dedicated_server = true;
237 const bool isServer = cmd_args.getFlag("server");
239 porting::attachOrCreateConsole();
240 game_params.is_dedicated_server = isServer;
243 if (!game_configure(&game_params, cmd_args))
246 sanity_check(!game_params.world_path.empty());
248 if (game_params.is_dedicated_server)
249 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
252 retval = ClientLauncher().run(game_params, cmd_args) ? 0 : 1;
257 // Update configuration file
258 if (!g_settings_path.empty())
259 g_settings->updateConfigFile(g_settings_path.c_str());
261 print_modified_quicktune_values();
263 END_DEBUG_EXCEPTION_HANDLER
269 /*****************************************************************************
271 *****************************************************************************/
274 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
276 set_allowed_options(&allowed_options);
278 return cmd_args->parseCommandLine(argc, argv, allowed_options);
281 static void set_allowed_options(OptionList *allowed_options)
283 allowed_options->clear();
285 allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
286 _("Show allowed options"))));
287 allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
288 _("Show version information"))));
289 allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
290 _("Load configuration from specified file"))));
291 allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
292 _("Set network port (UDP)"))));
293 allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
294 _("Run the unit tests and exit"))));
295 allowed_options->insert(std::make_pair("run-benchmarks", ValueSpec(VALUETYPE_FLAG,
296 _("Run the benchmarks and exit"))));
297 allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
298 _("Same as --world (deprecated)"))));
299 allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
300 _("Set world path (implies local game if used with option --go)"))));
301 allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
302 _("Set world by name (implies local game if used with option --go)"))));
303 allowed_options->insert(std::make_pair("worldlist", ValueSpec(VALUETYPE_STRING,
304 _("Get list of worlds ('path' lists paths, "
305 "'name' lists names, 'both' lists both)"))));
306 allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
307 _("Print to console errors only"))));
308 allowed_options->insert(std::make_pair("color", ValueSpec(VALUETYPE_STRING,
309 _("Coloured logs ('always', 'never' or 'auto'), defaults to 'auto'"
311 allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
312 _("Print more information to console"))));
313 allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
314 _("Print even more information to console"))));
315 allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
316 _("Print enormous amounts of information to log and console"))));
317 allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
318 _("Set logfile path ('' = no logging)"))));
319 allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
320 _("Set gameid (\"--gameid list\" prints available ones)"))));
321 allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
322 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
323 allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING,
324 _("Migrate from current players backend to another (Only works when using minetestserver or with --server)"))));
325 allowed_options->insert(std::make_pair("migrate-auth", ValueSpec(VALUETYPE_STRING,
326 _("Migrate from current auth backend to another (Only works when using minetestserver or with --server)"))));
327 allowed_options->insert(std::make_pair("migrate-mod-storage", ValueSpec(VALUETYPE_STRING,
328 _("Migrate from current mod storage backend to another (Only works when using minetestserver or with --server)"))));
329 allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
330 _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
331 allowed_options->insert(std::make_pair("recompress", ValueSpec(VALUETYPE_FLAG,
332 _("Recompress the blocks of the given map database."))));
334 allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
335 _("Run speed tests"))));
336 allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
337 _("Address to connect to. ('' = local game)"))));
338 allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
339 _("Enable random user input, for testing"))));
340 allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
341 _("Run dedicated server"))));
342 allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
343 _("Set player name"))));
344 allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
345 _("Set password"))));
346 allowed_options->insert(std::make_pair("password-file", ValueSpec(VALUETYPE_STRING,
347 _("Set password from contents of file"))));
348 allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
349 _("Disable main menu"))));
350 allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
351 _("Starts with the console (Windows only)"))));
356 static void print_help(const OptionList &allowed_options)
358 std::cout << _("Allowed options:") << std::endl;
359 print_allowed_options(allowed_options);
362 static void print_allowed_options(const OptionList &allowed_options)
364 for (const auto &allowed_option : allowed_options) {
365 std::ostringstream os1(std::ios::binary);
366 os1 << " --" << allowed_option.first;
367 if (allowed_option.second.type != VALUETYPE_FLAG)
368 os1 << _(" <value>");
370 std::cout << padStringRight(os1.str(), 30);
372 if (allowed_option.second.help)
373 std::cout << allowed_option.second.help;
375 std::cout << std::endl;
379 static void print_version()
381 std::cout << PROJECT_NAME_C " " << g_version_hash
382 << " (" << porting::getPlatformName() << ")" << std::endl;
384 std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl;
387 std::cout << "Using " << LUAJIT_VERSION << std::endl;
389 std::cout << "Using " << LUA_RELEASE << std::endl;
391 std::cout << g_build_info << std::endl;
394 static void list_game_ids()
396 std::set<std::string> gameids = getAvailableGameIds();
397 for (const std::string &gameid : gameids)
398 std::cout << gameid <<std::endl;
401 static void list_worlds(bool print_name, bool print_path)
403 std::cout << _("Available worlds:") << std::endl;
404 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
405 print_worldspecs(worldspecs, std::cout, print_name, print_path);
408 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
409 std::ostream &os, bool print_name, bool print_path)
411 for (const WorldSpec &worldspec : worldspecs) {
412 std::string name = worldspec.name;
413 std::string path = worldspec.path;
414 if (print_name && print_path) {
415 os << "\t" << name << "\t\t" << path << std::endl;
416 } else if (print_name) {
417 os << "\t" << name << std::endl;
418 } else if (print_path) {
419 os << "\t" << path << std::endl;
424 static void print_modified_quicktune_values()
426 bool header_printed = false;
427 std::vector<std::string> names = getQuicktuneNames();
429 for (const std::string &name : names) {
430 QuicktuneValue val = getQuicktuneValue(name);
433 if (!header_printed) {
434 dstream << "Modified quicktune values:" << std::endl;
435 header_printed = true;
437 dstream << name << " = " << val.getString() << std::endl;
441 static bool setup_log_params(const Settings &cmd_args)
443 // Quiet mode, print errors only
444 if (cmd_args.getFlag("quiet")) {
445 g_logger.removeOutput(&stderr_output);
446 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
449 // Coloured log messages (see log.h)
450 std::string color_mode;
451 if (cmd_args.exists("color")) {
452 color_mode = cmd_args.get("color");
455 char *color_mode_env = getenv("MT_LOGCOLOR");
457 color_mode = color_mode_env;
460 if (color_mode != "") {
461 if (color_mode == "auto") {
462 Logger::color_mode = LOG_COLOR_AUTO;
463 } else if (color_mode == "always") {
464 Logger::color_mode = LOG_COLOR_ALWAYS;
465 } else if (color_mode == "never") {
466 Logger::color_mode = LOG_COLOR_NEVER;
468 errorstream << "Invalid color mode: " << color_mode << std::endl;
473 // In certain cases, output info level on stderr
474 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
475 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
476 g_logger.addOutput(&stderr_output, LL_INFO);
478 // In certain cases, output verbose level on stderr
479 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
480 g_logger.addOutput(&stderr_output, LL_VERBOSE);
482 if (cmd_args.getFlag("trace")) {
483 dstream << _("Enabling trace level debug output") << std::endl;
484 g_logger.addOutput(&stderr_output, LL_TRACE);
485 socket_enable_debug_output = true;
491 static bool create_userdata_path()
496 if (!fs::PathExists(porting::path_user)) {
497 success = fs::CreateDir(porting::path_user);
502 // Create user data directory
503 success = fs::CreateDir(porting::path_user);
509 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
512 set_default_settings();
516 // Initialize g_settings
517 Settings::createLayer(SL_GLOBAL);
519 // Set cleanup callback(s) to run at process exit
520 atexit(uninit_common);
522 if (!read_config_file(cmd_args))
525 init_log_streams(cmd_args);
527 // Initialize random seed
531 // Initialize HTTP fetcher
532 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
534 init_gettext(porting::path_locale.c_str(),
535 g_settings->get("language"), argc, argv);
540 static void uninit_common()
546 // It'd actually be okay to leak these but we want to please valgrind...
547 for (int i = 0; i < (int)SL_TOTAL_COUNT; i++)
548 delete Settings::getLayer((SettingsLayer)i);
551 static void startup_message()
553 infostream << PROJECT_NAME << " " << _("with")
554 << " SER_FMT_VER_HIGHEST_READ="
555 << (int)SER_FMT_VER_HIGHEST_READ << ", "
556 << g_build_info << std::endl;
559 static bool read_config_file(const Settings &cmd_args)
561 // Path of configuration file in use
562 sanity_check(g_settings_path == ""); // Sanity check
564 if (cmd_args.exists("config")) {
565 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
567 errorstream << "Could not read configuration from \""
568 << cmd_args.get("config") << "\"" << std::endl;
571 g_settings_path = cmd_args.get("config");
573 std::vector<std::string> filenames;
574 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
575 // Legacy configuration file location
576 filenames.push_back(porting::path_user +
577 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
580 // Try also from a lower level (to aid having the same configuration
581 // for many RUN_IN_PLACE installs)
582 filenames.push_back(porting::path_user +
583 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
586 for (const std::string &filename : filenames) {
587 bool r = g_settings->readConfigFile(filename.c_str());
589 g_settings_path = filename;
594 // If no path found, use the first one (menu creates the file)
595 if (g_settings_path.empty())
596 g_settings_path = filenames[0];
602 static void init_log_streams(const Settings &cmd_args)
604 std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
606 if (cmd_args.exists("logfile"))
607 log_filename = cmd_args.get("logfile");
609 g_logger.removeOutput(&file_log_output);
610 std::string conf_loglev = g_settings->get("debug_log_level");
612 // Old integer format
613 if (std::isdigit(conf_loglev[0])) {
614 warningstream << "Deprecated use of debug_log_level with an "
615 "integer value; please update your configuration." << std::endl;
616 static const char *lev_name[] =
617 {"", "error", "action", "info", "verbose", "trace"};
618 int lev_i = atoi(conf_loglev.c_str());
619 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
620 warningstream << "Supplied invalid debug_log_level!"
621 " Assuming action level." << std::endl;
624 conf_loglev = lev_name[lev_i];
627 if (log_filename.empty() || conf_loglev.empty()) // No logging
630 LogLevel log_level = Logger::stringToLevel(conf_loglev);
631 if (log_level == LL_MAX) {
632 warningstream << "Supplied unrecognized debug_log_level; "
633 "using maximum." << std::endl;
636 file_log_output.setFile(log_filename,
637 g_settings->getU64("debug_log_size_max") * 1000000);
638 g_logger.addOutputMaxLevel(&file_log_output, log_level);
641 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
643 game_configure_port(game_params, cmd_args);
645 if (!game_configure_world(game_params, cmd_args)) {
646 errorstream << "No world path specified or found." << std::endl;
650 game_configure_subgame(game_params, cmd_args);
655 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
657 if (cmd_args.exists("port")) {
658 game_params->socket_port = cmd_args.getU16("port");
660 if (game_params->is_dedicated_server)
661 game_params->socket_port = g_settings->getU16("port");
663 game_params->socket_port = g_settings->getU16("remote_port");
666 if (game_params->socket_port == 0)
667 game_params->socket_port = DEFAULT_SERVER_PORT;
670 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
672 if (get_world_from_cmdline(game_params, cmd_args))
675 if (get_world_from_config(game_params, cmd_args))
678 return auto_select_world(game_params);
681 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
683 std::string commanded_world;
686 std::string commanded_worldname;
687 if (cmd_args.exists("worldname"))
688 commanded_worldname = cmd_args.get("worldname");
690 // If a world name was specified, convert it to a path
691 if (!commanded_worldname.empty()) {
692 // Get information about available worlds
693 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
695 for (const WorldSpec &worldspec : worldspecs) {
696 std::string name = worldspec.name;
697 if (name == commanded_worldname) {
698 dstream << _("Using world specified by --worldname on the "
699 "command line") << std::endl;
700 commanded_world = worldspec.path;
706 dstream << _("World") << " '" << commanded_worldname
707 << _("' not available. Available worlds:") << std::endl;
708 print_worldspecs(worldspecs, dstream);
712 game_params->world_path = get_clean_world_path(commanded_world);
713 return !commanded_world.empty();
716 if (cmd_args.exists("world"))
717 commanded_world = cmd_args.get("world");
718 else if (cmd_args.exists("map-dir"))
719 commanded_world = cmd_args.get("map-dir");
720 else if (cmd_args.exists("nonopt0")) // First nameless argument
721 commanded_world = cmd_args.get("nonopt0");
723 game_params->world_path = get_clean_world_path(commanded_world);
724 return !commanded_world.empty();
727 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
730 std::string commanded_world;
732 if (g_settings->exists("map-dir"))
733 commanded_world = g_settings->get("map-dir");
735 game_params->world_path = get_clean_world_path(commanded_world);
737 return !commanded_world.empty();
740 static bool auto_select_world(GameParams *game_params)
742 // No world was specified; try to select it automatically
743 // Get information about available worlds
745 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
746 std::string world_path;
748 // If there is only a single world, use it
749 if (worldspecs.size() == 1) {
750 world_path = worldspecs[0].path;
751 dstream <<_("Automatically selecting world at") << " ["
752 << world_path << "]" << std::endl;
753 // If there are multiple worlds, list them
754 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
755 std::cerr << _("Multiple worlds are available.") << std::endl;
756 std::cerr << _("Please select one using --worldname <name>"
757 " or --world <path>") << std::endl;
758 print_worldspecs(worldspecs, std::cerr);
760 // If there are no worlds, automatically create a new one
762 // This is the ultimate default world path
763 world_path = porting::path_user + DIR_DELIM + "worlds" +
765 infostream << "Using default world at ["
766 << world_path << "]" << std::endl;
769 assert(world_path != ""); // Post-condition
770 game_params->world_path = world_path;
774 static std::string get_clean_world_path(const std::string &path)
776 const std::string worldmt = "world.mt";
777 std::string clean_path;
779 if (path.size() > worldmt.size()
780 && path.substr(path.size() - worldmt.size()) == worldmt) {
781 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
782 clean_path = path.substr(0, path.size() - worldmt.size());
790 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
794 success = get_game_from_cmdline(game_params, cmd_args);
796 success = determine_subgame(game_params);
801 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
803 SubgameSpec commanded_gamespec;
805 if (cmd_args.exists("gameid")) {
806 std::string gameid = cmd_args.get("gameid");
807 commanded_gamespec = findSubgame(gameid);
808 if (!commanded_gamespec.isValid()) {
809 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
812 dstream << _("Using game specified by --gameid on the command line")
814 game_params->game_spec = commanded_gamespec;
821 static bool determine_subgame(GameParams *game_params)
823 SubgameSpec gamespec;
825 assert(game_params->world_path != ""); // Pre-condition
827 // If world doesn't exist
828 if (!game_params->world_path.empty()
829 && !getWorldExists(game_params->world_path)) {
830 // Try to take gamespec from command line
831 if (game_params->game_spec.isValid()) {
832 gamespec = game_params->game_spec;
833 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
834 } else { // Otherwise we will be using "minetest"
835 gamespec = findSubgame(g_settings->get("default_game"));
836 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
837 if (!gamespec.isValid()) {
838 errorstream << "Game specified in default_game ["
839 << g_settings->get("default_game")
840 << "] is invalid." << std::endl;
844 } else { // World exists
845 std::string world_gameid = getWorldGameId(game_params->world_path, false);
846 // If commanded to use a gameid, do so
847 if (game_params->game_spec.isValid()) {
848 gamespec = game_params->game_spec;
849 if (game_params->game_spec.id != world_gameid) {
850 warningstream << "Using commanded gameid ["
851 << gamespec.id << "]" << " instead of world gameid ["
852 << world_gameid << "]" << std::endl;
855 // If world contains an embedded game, use it;
856 // Otherwise find world from local system.
857 gamespec = findWorldSubgame(game_params->world_path);
858 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
862 if (!gamespec.isValid()) {
863 errorstream << "Game [" << gamespec.id << "] could not be found."
868 game_params->game_spec = gamespec;
873 /*****************************************************************************
875 *****************************************************************************/
876 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
878 verbosestream << _("Using world path") << " ["
879 << game_params.world_path << "]" << std::endl;
880 verbosestream << _("Using gameid") << " ["
881 << game_params.game_spec.id << "]" << std::endl;
884 std::string bind_str = g_settings->get("bind_address");
885 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
887 if (g_settings->getBool("ipv6_server")) {
888 bind_addr.setAddress((IPv6AddressBytes*) NULL);
891 bind_addr.Resolve(bind_str.c_str());
892 } catch (ResolveError &e) {
893 infostream << "Resolving bind address \"" << bind_str
894 << "\" failed: " << e.what()
895 << " -- Listening on all addresses." << std::endl;
897 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
898 errorstream << "Unable to listen on "
899 << bind_addr.serializeString()
900 << L" because IPv6 is disabled" << std::endl;
904 // Database migration/compression
905 if (cmd_args.exists("migrate"))
906 return migrate_map_database(game_params, cmd_args);
908 if (cmd_args.exists("migrate-players"))
909 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
911 if (cmd_args.exists("migrate-auth"))
912 return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);
914 if (cmd_args.exists("migrate-mod-storage"))
915 return Server::migrateModStorageDatabase(game_params, cmd_args);
917 if (cmd_args.getFlag("recompress"))
918 return recompress_map_database(game_params, cmd_args, bind_addr);
920 if (cmd_args.exists("terminal")) {
923 std::string admin_nick = g_settings->get("name");
925 name_ok = name_ok && !admin_nick.empty();
926 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
929 if (admin_nick.empty()) {
930 errorstream << "No name given for admin. "
931 << "Please check your minetest.conf that it "
932 << "contains a 'name = ' to your main admin account."
935 errorstream << "Name for admin '"
936 << admin_nick << "' is not valid. "
937 << "Please check that it only contains allowed characters. "
938 << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
944 bool &kill = *porting::signal_handler_killstatus();
948 Server server(game_params.world_path, game_params.game_spec,
949 false, bind_addr, true, &iface);
951 g_term_console.setup(&iface, &kill, admin_nick);
953 g_term_console.start();
957 dedicated_server_loop(server, kill);
958 } catch (const ModError &e) {
959 g_term_console.stopAndWaitforThread();
960 errorstream << "ModError: " << e.what() << std::endl;
962 } catch (const ServerError &e) {
963 g_term_console.stopAndWaitforThread();
964 errorstream << "ServerError: " << e.what() << std::endl;
968 // Tell the console to stop, and wait for it to finish,
969 // only then leave context and free iface
970 g_term_console.stop();
971 g_term_console.wait();
973 g_term_console.clearKillStatus();
976 errorstream << "Cmd arg --terminal passed, but "
977 << "compiled without ncurses. Ignoring." << std::endl;
982 Server server(game_params.world_path, game_params.game_spec, false,
987 bool &kill = *porting::signal_handler_killstatus();
988 dedicated_server_loop(server, kill);
990 } catch (const ModError &e) {
991 errorstream << "ModError: " << e.what() << std::endl;
993 } catch (const ServerError &e) {
994 errorstream << "ServerError: " << e.what() << std::endl;
1002 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
1004 std::string migrate_to = cmd_args.get("migrate");
1006 std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
1007 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
1008 errorstream << "Cannot read world.mt!" << std::endl;
1012 if (!world_mt.exists("backend")) {
1013 errorstream << "Please specify your current backend in world.mt:"
1015 << " backend = {sqlite3|leveldb|redis|dummy|postgresql}"
1020 std::string backend = world_mt.get("backend");
1021 if (backend == migrate_to) {
1022 errorstream << "Cannot migrate: new backend is same"
1023 << " as the old one" << std::endl;
1027 MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
1028 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
1031 time_t last_update_time = 0;
1032 bool &kill = *porting::signal_handler_killstatus();
1034 std::vector<v3s16> blocks;
1035 old_db->listAllLoadableBlocks(blocks);
1036 new_db->beginSave();
1037 for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
1038 if (kill) return false;
1041 old_db->loadBlock(*it, &data);
1042 if (!data.empty()) {
1043 new_db->saveBlock(*it, data);
1045 errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
1047 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
1048 std::cerr << " Migrated " << count << " blocks, "
1049 << (100.0 * count / blocks.size()) << "% completed.\r";
1051 new_db->beginSave();
1052 last_update_time = time(NULL);
1055 std::cerr << std::endl;
1060 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1061 world_mt.set("backend", migrate_to);
1062 if (!world_mt.updateConfigFile(world_mt_path.c_str()))
1063 errorstream << "Failed to update world.mt!" << std::endl;
1065 actionstream << "world.mt updated" << std::endl;
1070 static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr)
1073 const std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
1075 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
1076 errorstream << "Cannot read world.mt at " << world_mt_path << std::endl;
1079 const std::string &backend = world_mt.get("backend");
1080 Server server(game_params.world_path, game_params.game_spec, false, addr, false);
1081 MapDatabase *db = ServerMap::createDatabase(backend, game_params.world_path, world_mt);
1084 u64 last_update_time = 0;
1085 bool &kill = *porting::signal_handler_killstatus();
1086 const u8 serialize_as_ver = SER_FMT_VER_HIGHEST_WRITE;
1088 // This is ok because the server doesn't actually run
1089 std::vector<v3s16> blocks;
1090 db->listAllLoadableBlocks(blocks);
1092 std::istringstream iss(std::ios_base::binary);
1093 std::ostringstream oss(std::ios_base::binary);
1094 for (auto it = blocks.begin(); it != blocks.end(); ++it) {
1095 if (kill) return false;
1098 db->loadBlock(*it, &data);
1100 errorstream << "Failed to load block " << PP(*it) << std::endl;
1107 MapBlock mb(nullptr, v3s16(0,0,0), &server);
1108 u8 ver = readU8(iss);
1109 mb.deSerialize(iss, ver, true);
1113 writeU8(oss, serialize_as_ver);
1114 mb.serialize(oss, serialize_as_ver, true, -1);
1116 db->saveBlock(*it, oss.str());
1119 if (count % 0xFF == 0 && porting::getTimeS() - last_update_time >= 1) {
1120 std::cerr << " Recompressed " << count << " blocks, "
1121 << (100.0f * count / blocks.size()) << "% completed.\r";
1124 last_update_time = porting::getTimeS();
1127 std::cerr << std::endl;
1130 actionstream << "Done, " << count << " blocks were recompressed." << std::endl;