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 #define ENV_NO_COLOR "NO_COLOR"
81 #define ENV_CLICOLOR "CLICOLOR"
82 #define ENV_CLICOLOR_FORCE "CLICOLOR_FORCE"
84 typedef std::map<std::string, ValueSpec> OptionList;
86 /**********************************************************************
88 **********************************************************************/
90 static void get_env_opts(Settings &args);
91 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
92 static void set_allowed_options(OptionList *allowed_options);
94 static void print_help(const OptionList &allowed_options);
95 static void print_allowed_options(const OptionList &allowed_options);
96 static void print_version();
97 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
98 std::ostream &os, bool print_name = true, bool print_path = true);
99 static void print_modified_quicktune_values();
101 static void list_game_ids();
102 static void list_worlds(bool print_name, bool print_path);
103 static bool setup_log_params(const Settings &cmd_args);
104 static bool create_userdata_path();
105 static bool init_common(const Settings &cmd_args, int argc, char *argv[]);
106 static void uninit_common();
107 static void startup_message();
108 static bool read_config_file(const Settings &cmd_args);
109 static void init_log_streams(const Settings &cmd_args);
111 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
112 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
114 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
115 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
116 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
117 static bool auto_select_world(GameParams *game_params);
118 static std::string get_clean_world_path(const std::string &path);
120 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
121 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
122 static bool determine_subgame(GameParams *game_params);
124 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
125 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args);
126 static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr);
128 /**********************************************************************/
131 FileLogOutput file_log_output;
133 static OptionList allowed_options;
135 int main(int argc, char *argv[])
138 debug_set_exception_handler();
140 g_logger.registerThread("Main");
141 g_logger.addOutputMaxLevel(&stderr_output, LL_ACTION);
144 get_env_opts(cmd_args);
145 bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
147 || cmd_args.getFlag("help")
148 || cmd_args.exists("nonopt1")) {
149 porting::attachOrCreateConsole();
150 print_help(allowed_options);
151 return cmd_args_ok ? 0 : 1;
153 if (cmd_args.getFlag("console"))
154 porting::attachOrCreateConsole();
156 if (cmd_args.getFlag("version")) {
157 porting::attachOrCreateConsole();
162 if (!setup_log_params(cmd_args))
165 porting::signal_handler_init();
168 porting::initAndroid();
169 porting::initializePathsAndroid();
171 porting::initializePaths();
174 if (!create_userdata_path()) {
175 errorstream << "Cannot create user data directory" << std::endl;
180 BEGIN_DEBUG_EXCEPTION_HANDLER
182 // List gameids if requested
183 if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
188 // List worlds, world names, and world paths if requested
189 if (cmd_args.exists("worldlist")) {
190 if (cmd_args.get("worldlist") == "name") {
191 list_worlds(true, false);
192 } else if (cmd_args.get("worldlist") == "path") {
193 list_worlds(false, true);
194 } else if (cmd_args.get("worldlist") == "both") {
195 list_worlds(true, true);
197 errorstream << "Invalid --worldlist value: "
198 << cmd_args.get("worldlist") << std::endl;
204 if (!init_common(cmd_args, argc, argv))
207 if (g_settings->getBool("enable_console"))
208 porting::attachOrCreateConsole();
212 if (cmd_args.getFlag("run-unittests")) {
216 errorstream << "Unittest support is not enabled in this binary. "
217 << "If you want to enable it, compile project with BUILD_UNITTESTS=1 flag."
224 if (cmd_args.getFlag("run-benchmarks")) {
226 return run_benchmarks();
228 errorstream << "Benchmark support is not enabled in this binary. "
229 << "If you want to enable it, compile project with BUILD_BENCHMARKS=1 flag."
234 #endif // __ANDROID__
236 GameStartData game_params;
238 porting::attachOrCreateConsole();
239 game_params.is_dedicated_server = true;
241 const bool isServer = cmd_args.getFlag("server");
243 porting::attachOrCreateConsole();
244 game_params.is_dedicated_server = isServer;
247 if (!game_configure(&game_params, cmd_args))
250 sanity_check(!game_params.world_path.empty());
252 if (game_params.is_dedicated_server)
253 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
256 retval = ClientLauncher().run(game_params, cmd_args) ? 0 : 1;
261 // Update configuration file
262 if (!g_settings_path.empty())
263 g_settings->updateConfigFile(g_settings_path.c_str());
265 print_modified_quicktune_values();
267 END_DEBUG_EXCEPTION_HANDLER
273 /*****************************************************************************
275 *****************************************************************************/
278 static void get_env_opts(Settings &args)
280 // CLICOLOR is a de-facto standard option for colors <https://bixense.com/clicolors/>
281 // CLICOLOR != 0: ANSI colors are supported (auto-detection, this is the default)
282 // CLICOLOR == 0: ANSI colors are NOT supported
283 const char *clicolor = std::getenv(ENV_CLICOLOR);
284 if (clicolor && std::string(clicolor) == "0") {
285 args.set("color", "never");
287 // NO_COLOR only specifies that no color is allowed.
288 // Implemented according to <http://no-color.org/>
289 const char *no_color = std::getenv(ENV_NO_COLOR);
290 if (no_color && no_color[0]) {
291 args.set("color", "never");
293 // CLICOLOR_FORCE is another option, which should turn on colors "no matter what".
294 const char *clicolor_force = std::getenv(ENV_CLICOLOR_FORCE);
295 if (clicolor_force && std::string(clicolor_force) != "0") {
296 // should ALWAYS have colors, so we ignore tty (no "auto")
297 args.set("color", "always");
301 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
303 set_allowed_options(&allowed_options);
305 return cmd_args->parseCommandLine(argc, argv, allowed_options);
308 static void set_allowed_options(OptionList *allowed_options)
310 allowed_options->clear();
312 allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
313 _("Show allowed options"))));
314 allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
315 _("Show version information"))));
316 allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
317 _("Load configuration from specified file"))));
318 allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
319 _("Set network port (UDP)"))));
320 allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
321 _("Run the unit tests and exit"))));
322 allowed_options->insert(std::make_pair("run-benchmarks", ValueSpec(VALUETYPE_FLAG,
323 _("Run the benchmarks and exit"))));
324 allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
325 _("Same as --world (deprecated)"))));
326 allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
327 _("Set world path (implies local game if used with option --go)"))));
328 allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
329 _("Set world by name (implies local game if used with option --go)"))));
330 allowed_options->insert(std::make_pair("worldlist", ValueSpec(VALUETYPE_STRING,
331 _("Get list of worlds ('path' lists paths, "
332 "'name' lists names, 'both' lists both)"))));
333 allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
334 _("Print to console errors only"))));
335 allowed_options->insert(std::make_pair("color", ValueSpec(VALUETYPE_STRING,
336 _("Coloured logs ('always', 'never' or 'auto'), defaults to 'auto'"
338 allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
339 _("Print more information to console"))));
340 allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
341 _("Print even more information to console"))));
342 allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
343 _("Print enormous amounts of information to log and console"))));
344 allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
345 _("Set logfile path ('' = no logging)"))));
346 allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
347 _("Set gameid (\"--gameid list\" prints available ones)"))));
348 allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
349 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
350 allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING,
351 _("Migrate from current players backend to another (Only works when using minetestserver or with --server)"))));
352 allowed_options->insert(std::make_pair("migrate-auth", ValueSpec(VALUETYPE_STRING,
353 _("Migrate from current auth backend to another (Only works when using minetestserver or with --server)"))));
354 allowed_options->insert(std::make_pair("migrate-mod-storage", ValueSpec(VALUETYPE_STRING,
355 _("Migrate from current mod storage backend to another (Only works when using minetestserver or with --server)"))));
356 allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
357 _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
358 allowed_options->insert(std::make_pair("recompress", ValueSpec(VALUETYPE_FLAG,
359 _("Recompress the blocks of the given map database."))));
361 allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
362 _("Run speed tests"))));
363 allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
364 _("Address to connect to. ('' = local game)"))));
365 allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
366 _("Enable random user input, for testing"))));
367 allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
368 _("Run dedicated server"))));
369 allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
370 _("Set player name"))));
371 allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
372 _("Set password"))));
373 allowed_options->insert(std::make_pair("password-file", ValueSpec(VALUETYPE_STRING,
374 _("Set password from contents of file"))));
375 allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
376 _("Disable main menu"))));
377 allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
378 _("Starts with the console (Windows only)"))));
383 static void print_help(const OptionList &allowed_options)
385 std::cout << _("Allowed options:") << std::endl;
386 print_allowed_options(allowed_options);
389 static void print_allowed_options(const OptionList &allowed_options)
391 for (const auto &allowed_option : allowed_options) {
392 std::ostringstream os1(std::ios::binary);
393 os1 << " --" << allowed_option.first;
394 if (allowed_option.second.type != VALUETYPE_FLAG)
395 os1 << _(" <value>");
397 std::cout << padStringRight(os1.str(), 30);
399 if (allowed_option.second.help)
400 std::cout << allowed_option.second.help;
402 std::cout << std::endl;
406 static void print_version()
408 std::cout << PROJECT_NAME_C " " << g_version_hash
409 << " (" << porting::getPlatformName() << ")" << std::endl;
411 std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl;
414 std::cout << "Using " << LUAJIT_VERSION << std::endl;
416 std::cout << "Using " << LUA_RELEASE << std::endl;
418 std::cout << g_build_info << std::endl;
421 static void list_game_ids()
423 std::set<std::string> gameids = getAvailableGameIds();
424 for (const std::string &gameid : gameids)
425 std::cout << gameid <<std::endl;
428 static void list_worlds(bool print_name, bool print_path)
430 std::cout << _("Available worlds:") << std::endl;
431 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
432 print_worldspecs(worldspecs, std::cout, print_name, print_path);
435 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
436 std::ostream &os, bool print_name, bool print_path)
438 for (const WorldSpec &worldspec : worldspecs) {
439 std::string name = worldspec.name;
440 std::string path = worldspec.path;
441 if (print_name && print_path) {
442 os << "\t" << name << "\t\t" << path << std::endl;
443 } else if (print_name) {
444 os << "\t" << name << std::endl;
445 } else if (print_path) {
446 os << "\t" << path << std::endl;
451 static void print_modified_quicktune_values()
453 bool header_printed = false;
454 std::vector<std::string> names = getQuicktuneNames();
456 for (const std::string &name : names) {
457 QuicktuneValue val = getQuicktuneValue(name);
460 if (!header_printed) {
461 dstream << "Modified quicktune values:" << std::endl;
462 header_printed = true;
464 dstream << name << " = " << val.getString() << std::endl;
468 static bool setup_log_params(const Settings &cmd_args)
470 // Quiet mode, print errors only
471 if (cmd_args.getFlag("quiet")) {
472 g_logger.removeOutput(&stderr_output);
473 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
476 // Coloured log messages (see log.h)
477 std::string color_mode;
478 if (cmd_args.exists("color")) {
479 color_mode = cmd_args.get("color");
482 char *color_mode_env = getenv("MT_LOGCOLOR");
484 color_mode = color_mode_env;
487 if (!color_mode.empty()) {
488 if (color_mode == "auto") {
489 Logger::color_mode = LOG_COLOR_AUTO;
490 } else if (color_mode == "always") {
491 Logger::color_mode = LOG_COLOR_ALWAYS;
492 } else if (color_mode == "never") {
493 Logger::color_mode = LOG_COLOR_NEVER;
495 errorstream << "Invalid color mode: " << color_mode << std::endl;
500 // In certain cases, output info level on stderr
501 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
502 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
503 g_logger.addOutput(&stderr_output, LL_INFO);
505 // In certain cases, output verbose level on stderr
506 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
507 g_logger.addOutput(&stderr_output, LL_VERBOSE);
509 if (cmd_args.getFlag("trace")) {
510 dstream << _("Enabling trace level debug output") << std::endl;
511 g_logger.addOutput(&stderr_output, LL_TRACE);
512 socket_enable_debug_output = true;
518 static bool create_userdata_path()
523 if (!fs::PathExists(porting::path_user)) {
524 success = fs::CreateDir(porting::path_user);
529 // Create user data directory
530 success = fs::CreateAllDirs(porting::path_user);
536 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
539 set_default_settings();
543 // Initialize g_settings
544 Settings::createLayer(SL_GLOBAL);
546 // Set cleanup callback(s) to run at process exit
547 atexit(uninit_common);
549 if (!read_config_file(cmd_args))
552 init_log_streams(cmd_args);
554 // Initialize random seed
558 // Initialize HTTP fetcher
559 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
561 init_gettext(porting::path_locale.c_str(),
562 g_settings->get("language"), argc, argv);
567 static void uninit_common()
573 // It'd actually be okay to leak these but we want to please valgrind...
574 for (int i = 0; i < (int)SL_TOTAL_COUNT; i++)
575 delete Settings::getLayer((SettingsLayer)i);
578 static void startup_message()
580 infostream << PROJECT_NAME << " " << _("with")
581 << " SER_FMT_VER_HIGHEST_READ="
582 << (int)SER_FMT_VER_HIGHEST_READ << ", "
583 << g_build_info << std::endl;
586 static bool read_config_file(const Settings &cmd_args)
588 // Path of configuration file in use
589 sanity_check(g_settings_path.empty()); // Sanity check
591 if (cmd_args.exists("config")) {
592 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
594 errorstream << "Could not read configuration from \""
595 << cmd_args.get("config") << "\"" << std::endl;
598 g_settings_path = cmd_args.get("config");
600 std::vector<std::string> filenames;
601 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
602 // Legacy configuration file location
603 filenames.push_back(porting::path_user +
604 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
607 // Try also from a lower level (to aid having the same configuration
608 // for many RUN_IN_PLACE installs)
609 filenames.push_back(porting::path_user +
610 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
613 for (const std::string &filename : filenames) {
614 bool r = g_settings->readConfigFile(filename.c_str());
616 g_settings_path = filename;
621 // If no path found, use the first one (menu creates the file)
622 if (g_settings_path.empty())
623 g_settings_path = filenames[0];
629 static void init_log_streams(const Settings &cmd_args)
631 std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
633 if (cmd_args.exists("logfile"))
634 log_filename = cmd_args.get("logfile");
636 g_logger.removeOutput(&file_log_output);
637 std::string conf_loglev = g_settings->get("debug_log_level");
639 // Old integer format
640 if (std::isdigit(conf_loglev[0])) {
641 warningstream << "Deprecated use of debug_log_level with an "
642 "integer value; please update your configuration." << std::endl;
643 static const char *lev_name[] =
644 {"", "error", "action", "info", "verbose", "trace"};
645 int lev_i = atoi(conf_loglev.c_str());
646 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
647 warningstream << "Supplied invalid debug_log_level!"
648 " Assuming action level." << std::endl;
651 conf_loglev = lev_name[lev_i];
654 if (log_filename.empty() || conf_loglev.empty()) // No logging
657 LogLevel log_level = Logger::stringToLevel(conf_loglev);
658 if (log_level == LL_MAX) {
659 warningstream << "Supplied unrecognized debug_log_level; "
660 "using maximum." << std::endl;
663 file_log_output.setFile(log_filename,
664 g_settings->getU64("debug_log_size_max") * 1000000);
665 g_logger.addOutputMaxLevel(&file_log_output, log_level);
668 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
670 game_configure_port(game_params, cmd_args);
672 if (!game_configure_world(game_params, cmd_args)) {
673 errorstream << "No world path specified or found." << std::endl;
677 game_configure_subgame(game_params, cmd_args);
682 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
684 if (cmd_args.exists("port")) {
685 game_params->socket_port = cmd_args.getU16("port");
687 if (game_params->is_dedicated_server)
688 game_params->socket_port = g_settings->getU16("port");
690 game_params->socket_port = g_settings->getU16("remote_port");
693 if (game_params->socket_port == 0)
694 game_params->socket_port = DEFAULT_SERVER_PORT;
697 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
699 if (get_world_from_cmdline(game_params, cmd_args))
702 if (get_world_from_config(game_params, cmd_args))
705 return auto_select_world(game_params);
708 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
710 std::string commanded_world;
713 std::string commanded_worldname;
714 if (cmd_args.exists("worldname"))
715 commanded_worldname = cmd_args.get("worldname");
717 // If a world name was specified, convert it to a path
718 if (!commanded_worldname.empty()) {
719 // Get information about available worlds
720 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
722 for (const WorldSpec &worldspec : worldspecs) {
723 std::string name = worldspec.name;
724 if (name == commanded_worldname) {
725 dstream << _("Using world specified by --worldname on the "
726 "command line") << std::endl;
727 commanded_world = worldspec.path;
733 dstream << _("World") << " '" << commanded_worldname
734 << _("' not available. Available worlds:") << std::endl;
735 print_worldspecs(worldspecs, dstream);
739 game_params->world_path = get_clean_world_path(commanded_world);
740 return !commanded_world.empty();
743 if (cmd_args.exists("world"))
744 commanded_world = cmd_args.get("world");
745 else if (cmd_args.exists("map-dir"))
746 commanded_world = cmd_args.get("map-dir");
747 else if (cmd_args.exists("nonopt0")) // First nameless argument
748 commanded_world = cmd_args.get("nonopt0");
750 game_params->world_path = get_clean_world_path(commanded_world);
751 return !commanded_world.empty();
754 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
757 std::string commanded_world;
759 if (g_settings->exists("map-dir"))
760 commanded_world = g_settings->get("map-dir");
762 game_params->world_path = get_clean_world_path(commanded_world);
764 return !commanded_world.empty();
767 static bool auto_select_world(GameParams *game_params)
769 // No world was specified; try to select it automatically
770 // Get information about available worlds
772 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
773 std::string world_path;
775 // If there is only a single world, use it
776 if (worldspecs.size() == 1) {
777 world_path = worldspecs[0].path;
778 dstream <<_("Automatically selecting world at") << " ["
779 << world_path << "]" << std::endl;
780 // If there are multiple worlds, list them
781 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
782 std::cerr << _("Multiple worlds are available.") << std::endl;
783 std::cerr << _("Please select one using --worldname <name>"
784 " or --world <path>") << std::endl;
785 print_worldspecs(worldspecs, std::cerr);
787 // If there are no worlds, automatically create a new one
789 // This is the ultimate default world path
790 world_path = porting::path_user + DIR_DELIM + "worlds" +
792 infostream << "Using default world at ["
793 << world_path << "]" << std::endl;
796 assert(!world_path.empty()); // Post-condition
797 game_params->world_path = world_path;
801 static std::string get_clean_world_path(const std::string &path)
803 const std::string worldmt = "world.mt";
804 std::string clean_path;
806 if (path.size() > worldmt.size()
807 && path.substr(path.size() - worldmt.size()) == worldmt) {
808 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
809 clean_path = path.substr(0, path.size() - worldmt.size());
817 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
821 success = get_game_from_cmdline(game_params, cmd_args);
823 success = determine_subgame(game_params);
828 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
830 SubgameSpec commanded_gamespec;
832 if (cmd_args.exists("gameid")) {
833 std::string gameid = cmd_args.get("gameid");
834 commanded_gamespec = findSubgame(gameid);
835 if (!commanded_gamespec.isValid()) {
836 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
839 dstream << _("Using game specified by --gameid on the command line")
841 game_params->game_spec = commanded_gamespec;
848 static bool determine_subgame(GameParams *game_params)
850 SubgameSpec gamespec;
852 assert(!game_params->world_path.empty()); // Pre-condition
854 // If world doesn't exist
855 if (!game_params->world_path.empty()
856 && !getWorldExists(game_params->world_path)) {
857 // Try to take gamespec from command line
858 if (game_params->game_spec.isValid()) {
859 gamespec = game_params->game_spec;
860 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
861 } else { // Otherwise we will be using "minetest"
862 gamespec = findSubgame(g_settings->get("default_game"));
863 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
864 if (!gamespec.isValid()) {
865 errorstream << "Game specified in default_game ["
866 << g_settings->get("default_game")
867 << "] is invalid." << std::endl;
871 } else { // World exists
872 std::string world_gameid = getWorldGameId(game_params->world_path, false);
873 // If commanded to use a gameid, do so
874 if (game_params->game_spec.isValid()) {
875 gamespec = game_params->game_spec;
876 if (game_params->game_spec.id != world_gameid) {
877 warningstream << "Using commanded gameid ["
878 << gamespec.id << "]" << " instead of world gameid ["
879 << world_gameid << "]" << std::endl;
882 // If world contains an embedded game, use it;
883 // Otherwise find world from local system.
884 gamespec = findWorldSubgame(game_params->world_path);
885 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
889 if (!gamespec.isValid()) {
890 errorstream << "Game [" << gamespec.id << "] could not be found."
895 game_params->game_spec = gamespec;
900 /*****************************************************************************
902 *****************************************************************************/
903 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
905 verbosestream << _("Using world path") << " ["
906 << game_params.world_path << "]" << std::endl;
907 verbosestream << _("Using gameid") << " ["
908 << game_params.game_spec.id << "]" << std::endl;
911 std::string bind_str = g_settings->get("bind_address");
912 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
914 if (g_settings->getBool("ipv6_server")) {
915 bind_addr.setAddress((IPv6AddressBytes*) NULL);
918 bind_addr.Resolve(bind_str.c_str());
919 } catch (ResolveError &e) {
920 infostream << "Resolving bind address \"" << bind_str
921 << "\" failed: " << e.what()
922 << " -- Listening on all addresses." << std::endl;
924 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
925 errorstream << "Unable to listen on "
926 << bind_addr.serializeString()
927 << L" because IPv6 is disabled" << std::endl;
931 // Database migration/compression
932 if (cmd_args.exists("migrate"))
933 return migrate_map_database(game_params, cmd_args);
935 if (cmd_args.exists("migrate-players"))
936 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
938 if (cmd_args.exists("migrate-auth"))
939 return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);
941 if (cmd_args.exists("migrate-mod-storage"))
942 return Server::migrateModStorageDatabase(game_params, cmd_args);
944 if (cmd_args.getFlag("recompress"))
945 return recompress_map_database(game_params, cmd_args, bind_addr);
947 if (cmd_args.exists("terminal")) {
950 std::string admin_nick = g_settings->get("name");
952 name_ok = name_ok && !admin_nick.empty();
953 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
956 if (admin_nick.empty()) {
957 errorstream << "No name given for admin. "
958 << "Please check your minetest.conf that it "
959 << "contains a 'name = ' to your main admin account."
962 errorstream << "Name for admin '"
963 << admin_nick << "' is not valid. "
964 << "Please check that it only contains allowed characters. "
965 << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
971 bool &kill = *porting::signal_handler_killstatus();
975 Server server(game_params.world_path, game_params.game_spec,
976 false, bind_addr, true, &iface);
978 g_term_console.setup(&iface, &kill, admin_nick);
980 g_term_console.start();
984 dedicated_server_loop(server, kill);
985 } catch (const ModError &e) {
986 g_term_console.stopAndWaitforThread();
987 errorstream << "ModError: " << e.what() << std::endl;
989 } catch (const ServerError &e) {
990 g_term_console.stopAndWaitforThread();
991 errorstream << "ServerError: " << e.what() << std::endl;
995 // Tell the console to stop, and wait for it to finish,
996 // only then leave context and free iface
997 g_term_console.stop();
998 g_term_console.wait();
1000 g_term_console.clearKillStatus();
1003 errorstream << "Cmd arg --terminal passed, but "
1004 << "compiled without ncurses. Ignoring." << std::endl;
1009 Server server(game_params.world_path, game_params.game_spec, false,
1014 bool &kill = *porting::signal_handler_killstatus();
1015 dedicated_server_loop(server, kill);
1017 } catch (const ModError &e) {
1018 errorstream << "ModError: " << e.what() << std::endl;
1020 } catch (const ServerError &e) {
1021 errorstream << "ServerError: " << e.what() << std::endl;
1029 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
1031 std::string migrate_to = cmd_args.get("migrate");
1033 std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
1034 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
1035 errorstream << "Cannot read world.mt!" << std::endl;
1039 if (!world_mt.exists("backend")) {
1040 errorstream << "Please specify your current backend in world.mt:"
1042 << " backend = {sqlite3|leveldb|redis|dummy|postgresql}"
1047 std::string backend = world_mt.get("backend");
1048 if (backend == migrate_to) {
1049 errorstream << "Cannot migrate: new backend is same"
1050 << " as the old one" << std::endl;
1054 MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
1055 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
1058 time_t last_update_time = 0;
1059 bool &kill = *porting::signal_handler_killstatus();
1061 std::vector<v3s16> blocks;
1062 old_db->listAllLoadableBlocks(blocks);
1063 new_db->beginSave();
1064 for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
1065 if (kill) return false;
1068 old_db->loadBlock(*it, &data);
1069 if (!data.empty()) {
1070 new_db->saveBlock(*it, data);
1072 errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
1074 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
1075 std::cerr << " Migrated " << count << " blocks, "
1076 << (100.0 * count / blocks.size()) << "% completed.\r";
1078 new_db->beginSave();
1079 last_update_time = time(NULL);
1082 std::cerr << std::endl;
1087 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1088 world_mt.set("backend", migrate_to);
1089 if (!world_mt.updateConfigFile(world_mt_path.c_str()))
1090 errorstream << "Failed to update world.mt!" << std::endl;
1092 actionstream << "world.mt updated" << std::endl;
1097 static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr)
1100 const std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
1102 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
1103 errorstream << "Cannot read world.mt at " << world_mt_path << std::endl;
1106 const std::string &backend = world_mt.get("backend");
1107 Server server(game_params.world_path, game_params.game_spec, false, addr, false);
1108 MapDatabase *db = ServerMap::createDatabase(backend, game_params.world_path, world_mt);
1111 u64 last_update_time = 0;
1112 bool &kill = *porting::signal_handler_killstatus();
1113 const u8 serialize_as_ver = SER_FMT_VER_HIGHEST_WRITE;
1115 // This is ok because the server doesn't actually run
1116 std::vector<v3s16> blocks;
1117 db->listAllLoadableBlocks(blocks);
1119 std::istringstream iss(std::ios_base::binary);
1120 std::ostringstream oss(std::ios_base::binary);
1121 for (auto it = blocks.begin(); it != blocks.end(); ++it) {
1122 if (kill) return false;
1125 db->loadBlock(*it, &data);
1127 errorstream << "Failed to load block " << PP(*it) << std::endl;
1135 MapBlock mb(nullptr, v3s16(0,0,0), &server);
1136 u8 ver = readU8(iss);
1137 mb.deSerialize(iss, ver, true);
1141 writeU8(oss, serialize_as_ver);
1142 mb.serialize(oss, serialize_as_ver, true, -1);
1145 db->saveBlock(*it, oss.str());
1148 if (count % 0xFF == 0 && porting::getTimeS() - last_update_time >= 1) {
1149 std::cerr << " Recompressed " << count << " blocks, "
1150 << (100.0f * count / blocks.size()) << "% completed.\r";
1153 last_update_time = porting::getTimeS();
1156 std::cerr << std::endl;
1159 actionstream << "Done, " << count << " blocks were recompressed." << std::endl;