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 // If trace is enabled, enable logging of certain things
457 if (cmd_args.getFlag("trace")) {
458 dstream << _("Enabling trace level debug output") << std::endl;
459 g_logger.setTraceEnabled(true);
460 dout_con_ptr = &verbosestream; // This is somewhat old
461 socket_enable_debug_output = true; // Sockets doesn't use log.h
464 // In certain cases, output info level on stderr
465 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
466 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
467 g_logger.addOutput(&stderr_output, LL_INFO);
469 // In certain cases, output verbose level on stderr
470 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
471 g_logger.addOutput(&stderr_output, LL_VERBOSE);
476 static bool create_userdata_path()
481 if (!fs::PathExists(porting::path_user)) {
482 success = fs::CreateDir(porting::path_user);
487 // Create user data directory
488 success = fs::CreateDir(porting::path_user);
494 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
497 set_default_settings();
501 // Initialize g_settings
502 Settings::createLayer(SL_GLOBAL);
504 // Set cleanup callback(s) to run at process exit
505 atexit(uninit_common);
507 if (!read_config_file(cmd_args))
510 init_log_streams(cmd_args);
512 // Initialize random seed
516 // Initialize HTTP fetcher
517 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
519 init_gettext(porting::path_locale.c_str(),
520 g_settings->get("language"), argc, argv);
525 static void uninit_common()
531 // It'd actually be okay to leak these but we want to please valgrind...
532 for (int i = 0; i < (int)SL_TOTAL_COUNT; i++)
533 delete Settings::getLayer((SettingsLayer)i);
536 static void startup_message()
538 infostream << PROJECT_NAME << " " << _("with")
539 << " SER_FMT_VER_HIGHEST_READ="
540 << (int)SER_FMT_VER_HIGHEST_READ << ", "
541 << g_build_info << std::endl;
544 static bool read_config_file(const Settings &cmd_args)
546 // Path of configuration file in use
547 sanity_check(g_settings_path == ""); // Sanity check
549 if (cmd_args.exists("config")) {
550 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
552 errorstream << "Could not read configuration from \""
553 << cmd_args.get("config") << "\"" << std::endl;
556 g_settings_path = cmd_args.get("config");
558 std::vector<std::string> filenames;
559 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
560 // Legacy configuration file location
561 filenames.push_back(porting::path_user +
562 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
565 // Try also from a lower level (to aid having the same configuration
566 // for many RUN_IN_PLACE installs)
567 filenames.push_back(porting::path_user +
568 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
571 for (const std::string &filename : filenames) {
572 bool r = g_settings->readConfigFile(filename.c_str());
574 g_settings_path = filename;
579 // If no path found, use the first one (menu creates the file)
580 if (g_settings_path.empty())
581 g_settings_path = filenames[0];
587 static void init_log_streams(const Settings &cmd_args)
589 std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
591 if (cmd_args.exists("logfile"))
592 log_filename = cmd_args.get("logfile");
594 g_logger.removeOutput(&file_log_output);
595 std::string conf_loglev = g_settings->get("debug_log_level");
597 // Old integer format
598 if (std::isdigit(conf_loglev[0])) {
599 warningstream << "Deprecated use of debug_log_level with an "
600 "integer value; please update your configuration." << std::endl;
601 static const char *lev_name[] =
602 {"", "error", "action", "info", "verbose"};
603 int lev_i = atoi(conf_loglev.c_str());
604 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
605 warningstream << "Supplied invalid debug_log_level!"
606 " Assuming action level." << std::endl;
609 conf_loglev = lev_name[lev_i];
612 if (log_filename.empty() || conf_loglev.empty()) // No logging
615 LogLevel log_level = Logger::stringToLevel(conf_loglev);
616 if (log_level == LL_MAX) {
617 warningstream << "Supplied unrecognized debug_log_level; "
618 "using maximum." << std::endl;
621 file_log_output.setFile(log_filename,
622 g_settings->getU64("debug_log_size_max") * 1000000);
623 g_logger.addOutputMaxLevel(&file_log_output, log_level);
626 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
628 game_configure_port(game_params, cmd_args);
630 if (!game_configure_world(game_params, cmd_args)) {
631 errorstream << "No world path specified or found." << std::endl;
635 game_configure_subgame(game_params, cmd_args);
640 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
642 if (cmd_args.exists("port")) {
643 game_params->socket_port = cmd_args.getU16("port");
645 if (game_params->is_dedicated_server)
646 game_params->socket_port = g_settings->getU16("port");
648 game_params->socket_port = g_settings->getU16("remote_port");
651 if (game_params->socket_port == 0)
652 game_params->socket_port = DEFAULT_SERVER_PORT;
655 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
657 if (get_world_from_cmdline(game_params, cmd_args))
660 if (get_world_from_config(game_params, cmd_args))
663 return auto_select_world(game_params);
666 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
668 std::string commanded_world;
671 std::string commanded_worldname;
672 if (cmd_args.exists("worldname"))
673 commanded_worldname = cmd_args.get("worldname");
675 // If a world name was specified, convert it to a path
676 if (!commanded_worldname.empty()) {
677 // Get information about available worlds
678 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
680 for (const WorldSpec &worldspec : worldspecs) {
681 std::string name = worldspec.name;
682 if (name == commanded_worldname) {
683 dstream << _("Using world specified by --worldname on the "
684 "command line") << std::endl;
685 commanded_world = worldspec.path;
691 dstream << _("World") << " '" << commanded_worldname
692 << _("' not available. Available worlds:") << std::endl;
693 print_worldspecs(worldspecs, dstream);
697 game_params->world_path = get_clean_world_path(commanded_world);
698 return !commanded_world.empty();
701 if (cmd_args.exists("world"))
702 commanded_world = cmd_args.get("world");
703 else if (cmd_args.exists("map-dir"))
704 commanded_world = cmd_args.get("map-dir");
705 else if (cmd_args.exists("nonopt0")) // First nameless argument
706 commanded_world = cmd_args.get("nonopt0");
708 game_params->world_path = get_clean_world_path(commanded_world);
709 return !commanded_world.empty();
712 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
715 std::string commanded_world;
717 if (g_settings->exists("map-dir"))
718 commanded_world = g_settings->get("map-dir");
720 game_params->world_path = get_clean_world_path(commanded_world);
722 return !commanded_world.empty();
725 static bool auto_select_world(GameParams *game_params)
727 // No world was specified; try to select it automatically
728 // Get information about available worlds
730 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
731 std::string world_path;
733 // If there is only a single world, use it
734 if (worldspecs.size() == 1) {
735 world_path = worldspecs[0].path;
736 dstream <<_("Automatically selecting world at") << " ["
737 << world_path << "]" << std::endl;
738 // If there are multiple worlds, list them
739 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
740 std::cerr << _("Multiple worlds are available.") << std::endl;
741 std::cerr << _("Please select one using --worldname <name>"
742 " or --world <path>") << std::endl;
743 print_worldspecs(worldspecs, std::cerr);
745 // If there are no worlds, automatically create a new one
747 // This is the ultimate default world path
748 world_path = porting::path_user + DIR_DELIM + "worlds" +
750 infostream << "Using default world at ["
751 << world_path << "]" << std::endl;
754 assert(world_path != ""); // Post-condition
755 game_params->world_path = world_path;
759 static std::string get_clean_world_path(const std::string &path)
761 const std::string worldmt = "world.mt";
762 std::string clean_path;
764 if (path.size() > worldmt.size()
765 && path.substr(path.size() - worldmt.size()) == worldmt) {
766 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
767 clean_path = path.substr(0, path.size() - worldmt.size());
775 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
779 success = get_game_from_cmdline(game_params, cmd_args);
781 success = determine_subgame(game_params);
786 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
788 SubgameSpec commanded_gamespec;
790 if (cmd_args.exists("gameid")) {
791 std::string gameid = cmd_args.get("gameid");
792 commanded_gamespec = findSubgame(gameid);
793 if (!commanded_gamespec.isValid()) {
794 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
797 dstream << _("Using game specified by --gameid on the command line")
799 game_params->game_spec = commanded_gamespec;
806 static bool determine_subgame(GameParams *game_params)
808 SubgameSpec gamespec;
810 assert(game_params->world_path != ""); // Pre-condition
812 // If world doesn't exist
813 if (!game_params->world_path.empty()
814 && !getWorldExists(game_params->world_path)) {
815 // Try to take gamespec from command line
816 if (game_params->game_spec.isValid()) {
817 gamespec = game_params->game_spec;
818 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
819 } else { // Otherwise we will be using "minetest"
820 gamespec = findSubgame(g_settings->get("default_game"));
821 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
822 if (!gamespec.isValid()) {
823 errorstream << "Game specified in default_game ["
824 << g_settings->get("default_game")
825 << "] is invalid." << std::endl;
829 } else { // World exists
830 std::string world_gameid = getWorldGameId(game_params->world_path, false);
831 // If commanded to use a gameid, do so
832 if (game_params->game_spec.isValid()) {
833 gamespec = game_params->game_spec;
834 if (game_params->game_spec.id != world_gameid) {
835 warningstream << "Using commanded gameid ["
836 << gamespec.id << "]" << " instead of world gameid ["
837 << world_gameid << "]" << std::endl;
840 // If world contains an embedded game, use it;
841 // Otherwise find world from local system.
842 gamespec = findWorldSubgame(game_params->world_path);
843 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
847 if (!gamespec.isValid()) {
848 errorstream << "Game [" << gamespec.id << "] could not be found."
853 game_params->game_spec = gamespec;
858 /*****************************************************************************
860 *****************************************************************************/
861 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
863 verbosestream << _("Using world path") << " ["
864 << game_params.world_path << "]" << std::endl;
865 verbosestream << _("Using gameid") << " ["
866 << game_params.game_spec.id << "]" << std::endl;
869 std::string bind_str = g_settings->get("bind_address");
870 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
872 if (g_settings->getBool("ipv6_server")) {
873 bind_addr.setAddress((IPv6AddressBytes*) NULL);
876 bind_addr.Resolve(bind_str.c_str());
877 } catch (ResolveError &e) {
878 infostream << "Resolving bind address \"" << bind_str
879 << "\" failed: " << e.what()
880 << " -- Listening on all addresses." << std::endl;
882 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
883 errorstream << "Unable to listen on "
884 << bind_addr.serializeString()
885 << L" because IPv6 is disabled" << std::endl;
889 // Database migration/compression
890 if (cmd_args.exists("migrate"))
891 return migrate_map_database(game_params, cmd_args);
893 if (cmd_args.exists("migrate-players"))
894 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
896 if (cmd_args.exists("migrate-auth"))
897 return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);
899 if (cmd_args.exists("migrate-mod-storage"))
900 return Server::migrateModStorageDatabase(game_params, cmd_args);
902 if (cmd_args.getFlag("recompress"))
903 return recompress_map_database(game_params, cmd_args, bind_addr);
905 if (cmd_args.exists("terminal")) {
908 std::string admin_nick = g_settings->get("name");
910 name_ok = name_ok && !admin_nick.empty();
911 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
914 if (admin_nick.empty()) {
915 errorstream << "No name given for admin. "
916 << "Please check your minetest.conf that it "
917 << "contains a 'name = ' to your main admin account."
920 errorstream << "Name for admin '"
921 << admin_nick << "' is not valid. "
922 << "Please check that it only contains allowed characters. "
923 << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
929 bool &kill = *porting::signal_handler_killstatus();
933 Server server(game_params.world_path, game_params.game_spec,
934 false, bind_addr, true, &iface);
936 g_term_console.setup(&iface, &kill, admin_nick);
938 g_term_console.start();
942 dedicated_server_loop(server, kill);
943 } catch (const ModError &e) {
944 g_term_console.stopAndWaitforThread();
945 errorstream << "ModError: " << e.what() << std::endl;
947 } catch (const ServerError &e) {
948 g_term_console.stopAndWaitforThread();
949 errorstream << "ServerError: " << e.what() << std::endl;
953 // Tell the console to stop, and wait for it to finish,
954 // only then leave context and free iface
955 g_term_console.stop();
956 g_term_console.wait();
958 g_term_console.clearKillStatus();
961 errorstream << "Cmd arg --terminal passed, but "
962 << "compiled without ncurses. Ignoring." << std::endl;
967 Server server(game_params.world_path, game_params.game_spec, false,
972 bool &kill = *porting::signal_handler_killstatus();
973 dedicated_server_loop(server, kill);
975 } catch (const ModError &e) {
976 errorstream << "ModError: " << e.what() << std::endl;
978 } catch (const ServerError &e) {
979 errorstream << "ServerError: " << e.what() << std::endl;
987 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
989 std::string migrate_to = cmd_args.get("migrate");
991 std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
992 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
993 errorstream << "Cannot read world.mt!" << std::endl;
997 if (!world_mt.exists("backend")) {
998 errorstream << "Please specify your current backend in world.mt:"
1000 << " backend = {sqlite3|leveldb|redis|dummy|postgresql}"
1005 std::string backend = world_mt.get("backend");
1006 if (backend == migrate_to) {
1007 errorstream << "Cannot migrate: new backend is same"
1008 << " as the old one" << std::endl;
1012 MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
1013 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
1016 time_t last_update_time = 0;
1017 bool &kill = *porting::signal_handler_killstatus();
1019 std::vector<v3s16> blocks;
1020 old_db->listAllLoadableBlocks(blocks);
1021 new_db->beginSave();
1022 for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
1023 if (kill) return false;
1026 old_db->loadBlock(*it, &data);
1027 if (!data.empty()) {
1028 new_db->saveBlock(*it, data);
1030 errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
1032 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
1033 std::cerr << " Migrated " << count << " blocks, "
1034 << (100.0 * count / blocks.size()) << "% completed.\r";
1036 new_db->beginSave();
1037 last_update_time = time(NULL);
1040 std::cerr << std::endl;
1045 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1046 world_mt.set("backend", migrate_to);
1047 if (!world_mt.updateConfigFile(world_mt_path.c_str()))
1048 errorstream << "Failed to update world.mt!" << std::endl;
1050 actionstream << "world.mt updated" << std::endl;
1055 static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr)
1058 const std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
1060 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
1061 errorstream << "Cannot read world.mt at " << world_mt_path << std::endl;
1064 const std::string &backend = world_mt.get("backend");
1065 Server server(game_params.world_path, game_params.game_spec, false, addr, false);
1066 MapDatabase *db = ServerMap::createDatabase(backend, game_params.world_path, world_mt);
1069 u64 last_update_time = 0;
1070 bool &kill = *porting::signal_handler_killstatus();
1071 const u8 serialize_as_ver = SER_FMT_VER_HIGHEST_WRITE;
1073 // This is ok because the server doesn't actually run
1074 std::vector<v3s16> blocks;
1075 db->listAllLoadableBlocks(blocks);
1077 std::istringstream iss(std::ios_base::binary);
1078 std::ostringstream oss(std::ios_base::binary);
1079 for (auto it = blocks.begin(); it != blocks.end(); ++it) {
1080 if (kill) return false;
1083 db->loadBlock(*it, &data);
1085 errorstream << "Failed to load block " << PP(*it) << std::endl;
1092 MapBlock mb(nullptr, v3s16(0,0,0), &server);
1093 u8 ver = readU8(iss);
1094 mb.deSerialize(iss, ver, true);
1098 writeU8(oss, serialize_as_ver);
1099 mb.serialize(oss, serialize_as_ver, true, -1);
1101 db->saveBlock(*it, oss.str());
1104 if (count % 0xFF == 0 && porting::getTimeS() - last_update_time >= 1) {
1105 std::cerr << " Recompressed " << count << " blocks, "
1106 << (100.0f * count / blocks.size()) << "% completed.\r";
1109 last_update_time = porting::getTimeS();
1112 std::cerr << std::endl;
1115 actionstream << "Done, " << count << " blocks were recompressed." << std::endl;