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::string opt = " --" + allowed_option.first;
393 if (allowed_option.second.type != VALUETYPE_FLAG)
394 opt += _(" <value>");
396 std::string opt_padded = padStringRight(opt, 30);
397 std::cout << opt_padded;
398 if (opt == opt_padded) // Line is too long to pad
399 std::cout << std::endl << padStringRight("", 30);
401 if (allowed_option.second.help)
402 std::cout << allowed_option.second.help;
404 std::cout << std::endl;
408 static void print_version()
410 std::cout << PROJECT_NAME_C " " << g_version_hash
411 << " (" << porting::getPlatformName() << ")" << std::endl;
413 std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl;
416 std::cout << "Using " << LUAJIT_VERSION << std::endl;
418 std::cout << "Using " << LUA_RELEASE << std::endl;
420 std::cout << g_build_info << std::endl;
423 static void list_game_ids()
425 std::set<std::string> gameids = getAvailableGameIds();
426 for (const std::string &gameid : gameids)
427 std::cout << gameid <<std::endl;
430 static void list_worlds(bool print_name, bool print_path)
432 std::cout << _("Available worlds:") << std::endl;
433 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
434 print_worldspecs(worldspecs, std::cout, print_name, print_path);
437 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
438 std::ostream &os, bool print_name, bool print_path)
440 for (const WorldSpec &worldspec : worldspecs) {
441 std::string name = worldspec.name;
442 std::string path = worldspec.path;
443 if (print_name && print_path) {
444 os << "\t" << name << "\t\t" << path << std::endl;
445 } else if (print_name) {
446 os << "\t" << name << std::endl;
447 } else if (print_path) {
448 os << "\t" << path << std::endl;
453 static void print_modified_quicktune_values()
455 bool header_printed = false;
456 std::vector<std::string> names = getQuicktuneNames();
458 for (const std::string &name : names) {
459 QuicktuneValue val = getQuicktuneValue(name);
462 if (!header_printed) {
463 dstream << "Modified quicktune values:" << std::endl;
464 header_printed = true;
466 dstream << name << " = " << val.getString() << std::endl;
470 static bool setup_log_params(const Settings &cmd_args)
472 // Quiet mode, print errors only
473 if (cmd_args.getFlag("quiet")) {
474 g_logger.removeOutput(&stderr_output);
475 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
478 // Coloured log messages (see log.h)
479 std::string color_mode;
480 if (cmd_args.exists("color")) {
481 color_mode = cmd_args.get("color");
484 char *color_mode_env = getenv("MT_LOGCOLOR");
486 color_mode = color_mode_env;
489 if (!color_mode.empty()) {
490 if (color_mode == "auto") {
491 Logger::color_mode = LOG_COLOR_AUTO;
492 } else if (color_mode == "always") {
493 Logger::color_mode = LOG_COLOR_ALWAYS;
494 } else if (color_mode == "never") {
495 Logger::color_mode = LOG_COLOR_NEVER;
497 errorstream << "Invalid color mode: " << color_mode << std::endl;
502 // In certain cases, output info level on stderr
503 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
504 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
505 g_logger.addOutput(&stderr_output, LL_INFO);
507 // In certain cases, output verbose level on stderr
508 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
509 g_logger.addOutput(&stderr_output, LL_VERBOSE);
511 if (cmd_args.getFlag("trace")) {
512 dstream << _("Enabling trace level debug output") << std::endl;
513 g_logger.addOutput(&stderr_output, LL_TRACE);
514 socket_enable_debug_output = true;
520 static bool create_userdata_path()
525 if (!fs::PathExists(porting::path_user)) {
526 success = fs::CreateDir(porting::path_user);
531 // Create user data directory
532 success = fs::CreateAllDirs(porting::path_user);
538 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
541 set_default_settings();
545 // Initialize g_settings
546 Settings::createLayer(SL_GLOBAL);
548 // Set cleanup callback(s) to run at process exit
549 atexit(uninit_common);
551 if (!read_config_file(cmd_args))
554 init_log_streams(cmd_args);
556 // Initialize random seed
560 // Initialize HTTP fetcher
561 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
563 init_gettext(porting::path_locale.c_str(),
564 g_settings->get("language"), argc, argv);
569 static void uninit_common()
575 // It'd actually be okay to leak these but we want to please valgrind...
576 for (int i = 0; i < (int)SL_TOTAL_COUNT; i++)
577 delete Settings::getLayer((SettingsLayer)i);
580 static void startup_message()
582 infostream << PROJECT_NAME << " " << _("with")
583 << " SER_FMT_VER_HIGHEST_READ="
584 << (int)SER_FMT_VER_HIGHEST_READ << ", "
585 << g_build_info << std::endl;
588 static bool read_config_file(const Settings &cmd_args)
590 // Path of configuration file in use
591 sanity_check(g_settings_path.empty()); // Sanity check
593 if (cmd_args.exists("config")) {
594 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
596 errorstream << "Could not read configuration from \""
597 << cmd_args.get("config") << "\"" << std::endl;
600 g_settings_path = cmd_args.get("config");
602 std::vector<std::string> filenames;
603 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
604 // Legacy configuration file location
605 filenames.push_back(porting::path_user +
606 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
609 // Try also from a lower level (to aid having the same configuration
610 // for many RUN_IN_PLACE installs)
611 filenames.push_back(porting::path_user +
612 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
615 for (const std::string &filename : filenames) {
616 bool r = g_settings->readConfigFile(filename.c_str());
618 g_settings_path = filename;
623 // If no path found, use the first one (menu creates the file)
624 if (g_settings_path.empty())
625 g_settings_path = filenames[0];
631 static void init_log_streams(const Settings &cmd_args)
633 std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
635 if (cmd_args.exists("logfile"))
636 log_filename = cmd_args.get("logfile");
638 g_logger.removeOutput(&file_log_output);
639 std::string conf_loglev = g_settings->get("debug_log_level");
641 // Old integer format
642 if (std::isdigit(conf_loglev[0])) {
643 warningstream << "Deprecated use of debug_log_level with an "
644 "integer value; please update your configuration." << std::endl;
645 static const char *lev_name[] =
646 {"", "error", "action", "info", "verbose", "trace"};
647 int lev_i = atoi(conf_loglev.c_str());
648 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
649 warningstream << "Supplied invalid debug_log_level!"
650 " Assuming action level." << std::endl;
653 conf_loglev = lev_name[lev_i];
656 if (log_filename.empty() || conf_loglev.empty()) // No logging
659 LogLevel log_level = Logger::stringToLevel(conf_loglev);
660 if (log_level == LL_MAX) {
661 warningstream << "Supplied unrecognized debug_log_level; "
662 "using maximum." << std::endl;
665 file_log_output.setFile(log_filename,
666 g_settings->getU64("debug_log_size_max") * 1000000);
667 g_logger.addOutputMaxLevel(&file_log_output, log_level);
670 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
672 game_configure_port(game_params, cmd_args);
674 if (!game_configure_world(game_params, cmd_args)) {
675 errorstream << "No world path specified or found." << std::endl;
679 game_configure_subgame(game_params, cmd_args);
684 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
686 if (cmd_args.exists("port")) {
687 game_params->socket_port = cmd_args.getU16("port");
689 if (game_params->is_dedicated_server)
690 game_params->socket_port = g_settings->getU16("port");
692 game_params->socket_port = g_settings->getU16("remote_port");
695 if (game_params->socket_port == 0)
696 game_params->socket_port = DEFAULT_SERVER_PORT;
699 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
701 if (get_world_from_cmdline(game_params, cmd_args))
704 if (get_world_from_config(game_params, cmd_args))
707 return auto_select_world(game_params);
710 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
712 std::string commanded_world;
715 std::string commanded_worldname;
716 if (cmd_args.exists("worldname"))
717 commanded_worldname = cmd_args.get("worldname");
719 // If a world name was specified, convert it to a path
720 if (!commanded_worldname.empty()) {
721 // Get information about available worlds
722 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
724 for (const WorldSpec &worldspec : worldspecs) {
725 std::string name = worldspec.name;
726 if (name == commanded_worldname) {
727 dstream << _("Using world specified by --worldname on the "
728 "command line") << std::endl;
729 commanded_world = worldspec.path;
735 dstream << _("World") << " '" << commanded_worldname
736 << _("' not available. Available worlds:") << std::endl;
737 print_worldspecs(worldspecs, dstream);
741 game_params->world_path = get_clean_world_path(commanded_world);
742 return !commanded_world.empty();
745 if (cmd_args.exists("world"))
746 commanded_world = cmd_args.get("world");
747 else if (cmd_args.exists("map-dir"))
748 commanded_world = cmd_args.get("map-dir");
749 else if (cmd_args.exists("nonopt0")) // First nameless argument
750 commanded_world = cmd_args.get("nonopt0");
752 game_params->world_path = get_clean_world_path(commanded_world);
753 return !commanded_world.empty();
756 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
759 std::string commanded_world;
761 if (g_settings->exists("map-dir"))
762 commanded_world = g_settings->get("map-dir");
764 game_params->world_path = get_clean_world_path(commanded_world);
766 return !commanded_world.empty();
769 static bool auto_select_world(GameParams *game_params)
771 // No world was specified; try to select it automatically
772 // Get information about available worlds
774 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
775 std::string world_path;
777 // If there is only a single world, use it
778 if (worldspecs.size() == 1) {
779 world_path = worldspecs[0].path;
780 dstream <<_("Automatically selecting world at") << " ["
781 << world_path << "]" << std::endl;
782 // If there are multiple worlds, list them
783 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
784 std::cerr << _("Multiple worlds are available.") << std::endl;
785 std::cerr << _("Please select one using --worldname <name>"
786 " or --world <path>") << std::endl;
787 print_worldspecs(worldspecs, std::cerr);
789 // If there are no worlds, automatically create a new one
791 // This is the ultimate default world path
792 world_path = porting::path_user + DIR_DELIM + "worlds" +
794 infostream << "Using default world at ["
795 << world_path << "]" << std::endl;
798 assert(!world_path.empty()); // Post-condition
799 game_params->world_path = world_path;
803 static std::string get_clean_world_path(const std::string &path)
805 const std::string worldmt = "world.mt";
806 std::string clean_path;
808 if (path.size() > worldmt.size()
809 && path.substr(path.size() - worldmt.size()) == worldmt) {
810 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
811 clean_path = path.substr(0, path.size() - worldmt.size());
819 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
823 success = get_game_from_cmdline(game_params, cmd_args);
825 success = determine_subgame(game_params);
830 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
832 SubgameSpec commanded_gamespec;
834 if (cmd_args.exists("gameid")) {
835 std::string gameid = cmd_args.get("gameid");
836 commanded_gamespec = findSubgame(gameid);
837 if (!commanded_gamespec.isValid()) {
838 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
841 dstream << _("Using game specified by --gameid on the command line")
843 game_params->game_spec = commanded_gamespec;
850 static bool determine_subgame(GameParams *game_params)
852 SubgameSpec gamespec;
854 assert(!game_params->world_path.empty()); // Pre-condition
856 // If world doesn't exist
857 if (!game_params->world_path.empty()
858 && !getWorldExists(game_params->world_path)) {
859 // Try to take gamespec from command line
860 if (game_params->game_spec.isValid()) {
861 gamespec = game_params->game_spec;
862 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
863 } else { // Otherwise we will be using "minetest"
864 gamespec = findSubgame(g_settings->get("default_game"));
865 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
866 if (!gamespec.isValid()) {
867 errorstream << "Game specified in default_game ["
868 << g_settings->get("default_game")
869 << "] is invalid." << std::endl;
873 } else { // World exists
874 std::string world_gameid = getWorldGameId(game_params->world_path, false);
875 // If commanded to use a gameid, do so
876 if (game_params->game_spec.isValid()) {
877 gamespec = game_params->game_spec;
878 if (game_params->game_spec.id != world_gameid) {
879 warningstream << "Using commanded gameid ["
880 << gamespec.id << "]" << " instead of world gameid ["
881 << world_gameid << "]" << std::endl;
884 // If world contains an embedded game, use it;
885 // Otherwise find world from local system.
886 gamespec = findWorldSubgame(game_params->world_path);
887 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
891 if (!gamespec.isValid()) {
892 errorstream << "Game [" << gamespec.id << "] could not be found."
897 game_params->game_spec = gamespec;
902 /*****************************************************************************
904 *****************************************************************************/
905 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
907 verbosestream << _("Using world path") << " ["
908 << game_params.world_path << "]" << std::endl;
909 verbosestream << _("Using gameid") << " ["
910 << game_params.game_spec.id << "]" << std::endl;
913 std::string bind_str = g_settings->get("bind_address");
914 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
916 if (g_settings->getBool("ipv6_server")) {
917 bind_addr.setAddress((IPv6AddressBytes*) NULL);
920 bind_addr.Resolve(bind_str.c_str());
921 } catch (ResolveError &e) {
922 infostream << "Resolving bind address \"" << bind_str
923 << "\" failed: " << e.what()
924 << " -- Listening on all addresses." << std::endl;
926 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
927 errorstream << "Unable to listen on "
928 << bind_addr.serializeString()
929 << L" because IPv6 is disabled" << std::endl;
933 // Database migration/compression
934 if (cmd_args.exists("migrate"))
935 return migrate_map_database(game_params, cmd_args);
937 if (cmd_args.exists("migrate-players"))
938 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
940 if (cmd_args.exists("migrate-auth"))
941 return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);
943 if (cmd_args.exists("migrate-mod-storage"))
944 return Server::migrateModStorageDatabase(game_params, cmd_args);
946 if (cmd_args.getFlag("recompress"))
947 return recompress_map_database(game_params, cmd_args, bind_addr);
949 if (cmd_args.exists("terminal")) {
952 std::string admin_nick = g_settings->get("name");
954 name_ok = name_ok && !admin_nick.empty();
955 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
958 if (admin_nick.empty()) {
959 errorstream << "No name given for admin. "
960 << "Please check your minetest.conf that it "
961 << "contains a 'name = ' to your main admin account."
964 errorstream << "Name for admin '"
965 << admin_nick << "' is not valid. "
966 << "Please check that it only contains allowed characters. "
967 << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
973 bool &kill = *porting::signal_handler_killstatus();
977 Server server(game_params.world_path, game_params.game_spec,
978 false, bind_addr, true, &iface);
980 g_term_console.setup(&iface, &kill, admin_nick);
982 g_term_console.start();
986 dedicated_server_loop(server, kill);
987 } catch (const ModError &e) {
988 g_term_console.stopAndWaitforThread();
989 errorstream << "ModError: " << e.what() << std::endl;
991 } catch (const ServerError &e) {
992 g_term_console.stopAndWaitforThread();
993 errorstream << "ServerError: " << e.what() << std::endl;
997 // Tell the console to stop, and wait for it to finish,
998 // only then leave context and free iface
999 g_term_console.stop();
1000 g_term_console.wait();
1002 g_term_console.clearKillStatus();
1005 errorstream << "Cmd arg --terminal passed, but "
1006 << "compiled without ncurses. Ignoring." << std::endl;
1011 Server server(game_params.world_path, game_params.game_spec, false,
1016 bool &kill = *porting::signal_handler_killstatus();
1017 dedicated_server_loop(server, kill);
1019 } catch (const ModError &e) {
1020 errorstream << "ModError: " << e.what() << std::endl;
1022 } catch (const ServerError &e) {
1023 errorstream << "ServerError: " << e.what() << std::endl;
1031 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
1033 std::string migrate_to = cmd_args.get("migrate");
1035 std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
1036 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
1037 errorstream << "Cannot read world.mt!" << std::endl;
1041 if (!world_mt.exists("backend")) {
1042 errorstream << "Please specify your current backend in world.mt:"
1044 << " backend = {sqlite3|leveldb|redis|dummy|postgresql}"
1049 std::string backend = world_mt.get("backend");
1050 if (backend == migrate_to) {
1051 errorstream << "Cannot migrate: new backend is same"
1052 << " as the old one" << std::endl;
1056 MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
1057 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
1060 time_t last_update_time = 0;
1061 bool &kill = *porting::signal_handler_killstatus();
1063 std::vector<v3s16> blocks;
1064 old_db->listAllLoadableBlocks(blocks);
1065 new_db->beginSave();
1066 for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
1067 if (kill) return false;
1070 old_db->loadBlock(*it, &data);
1071 if (!data.empty()) {
1072 new_db->saveBlock(*it, data);
1074 errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
1076 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
1077 std::cerr << " Migrated " << count << " blocks, "
1078 << (100.0 * count / blocks.size()) << "% completed.\r";
1080 new_db->beginSave();
1081 last_update_time = time(NULL);
1084 std::cerr << std::endl;
1089 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1090 world_mt.set("backend", migrate_to);
1091 if (!world_mt.updateConfigFile(world_mt_path.c_str()))
1092 errorstream << "Failed to update world.mt!" << std::endl;
1094 actionstream << "world.mt updated" << std::endl;
1099 static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr)
1102 const std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
1104 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
1105 errorstream << "Cannot read world.mt at " << world_mt_path << std::endl;
1108 const std::string &backend = world_mt.get("backend");
1109 Server server(game_params.world_path, game_params.game_spec, false, addr, false);
1110 MapDatabase *db = ServerMap::createDatabase(backend, game_params.world_path, world_mt);
1113 u64 last_update_time = 0;
1114 bool &kill = *porting::signal_handler_killstatus();
1115 const u8 serialize_as_ver = SER_FMT_VER_HIGHEST_WRITE;
1117 // This is ok because the server doesn't actually run
1118 std::vector<v3s16> blocks;
1119 db->listAllLoadableBlocks(blocks);
1121 std::istringstream iss(std::ios_base::binary);
1122 std::ostringstream oss(std::ios_base::binary);
1123 for (auto it = blocks.begin(); it != blocks.end(); ++it) {
1124 if (kill) return false;
1127 db->loadBlock(*it, &data);
1129 errorstream << "Failed to load block " << PP(*it) << std::endl;
1137 MapBlock mb(nullptr, v3s16(0,0,0), &server);
1138 u8 ver = readU8(iss);
1139 mb.deSerialize(iss, ver, true);
1143 writeU8(oss, serialize_as_ver);
1144 mb.serialize(oss, serialize_as_ver, true, -1);
1147 db->saveBlock(*it, oss.str());
1150 if (count % 0xFF == 0 && porting::getTimeS() - last_update_time >= 1) {
1151 std::cerr << " Recompressed " << count << " blocks, "
1152 << (100.0f * count / blocks.size()) << "% completed.\r";
1155 last_update_time = porting::getTimeS();
1158 std::cerr << std::endl;
1161 actionstream << "Done, " << count << " blocks were recompressed." << std::endl;