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 #define DEBUGFILE "debug.txt"
69 #define DEFAULT_SERVER_PORT 30000
71 typedef std::map<std::string, ValueSpec> OptionList;
73 /**********************************************************************
75 **********************************************************************/
77 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
78 static void set_allowed_options(OptionList *allowed_options);
80 static void print_help(const OptionList &allowed_options);
81 static void print_allowed_options(const OptionList &allowed_options);
82 static void print_version();
83 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
84 std::ostream &os, bool print_name = true, bool print_path = true);
85 static void print_modified_quicktune_values();
87 static void list_game_ids();
88 static void list_worlds(bool print_name, bool print_path);
89 static bool setup_log_params(const Settings &cmd_args);
90 static bool create_userdata_path();
91 static bool init_common(const Settings &cmd_args, int argc, char *argv[]);
92 static void uninit_common();
93 static void startup_message();
94 static bool read_config_file(const Settings &cmd_args);
95 static void init_log_streams(const Settings &cmd_args);
97 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
98 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
100 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
101 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
102 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
103 static bool auto_select_world(GameParams *game_params);
104 static std::string get_clean_world_path(const std::string &path);
106 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
107 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
108 static bool determine_subgame(GameParams *game_params);
110 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
111 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args);
112 static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr);
114 /**********************************************************************/
117 FileLogOutput file_log_output;
119 static OptionList allowed_options;
121 int main(int argc, char *argv[])
124 debug_set_exception_handler();
126 g_logger.registerThread("Main");
127 g_logger.addOutputMaxLevel(&stderr_output, LL_ACTION);
130 bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
132 || cmd_args.getFlag("help")
133 || cmd_args.exists("nonopt1")) {
134 porting::attachOrCreateConsole();
135 print_help(allowed_options);
136 return cmd_args_ok ? 0 : 1;
138 if (cmd_args.getFlag("console"))
139 porting::attachOrCreateConsole();
141 if (cmd_args.getFlag("version")) {
142 porting::attachOrCreateConsole();
147 if (!setup_log_params(cmd_args))
150 porting::signal_handler_init();
153 porting::initAndroid();
154 porting::initializePathsAndroid();
156 porting::initializePaths();
159 if (!create_userdata_path()) {
160 errorstream << "Cannot create user data directory" << std::endl;
165 BEGIN_DEBUG_EXCEPTION_HANDLER
167 // List gameids if requested
168 if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
173 // List worlds, world names, and world paths if requested
174 if (cmd_args.exists("worldlist")) {
175 if (cmd_args.get("worldlist") == "name") {
176 list_worlds(true, false);
177 } else if (cmd_args.get("worldlist") == "path") {
178 list_worlds(false, true);
179 } else if (cmd_args.get("worldlist") == "both") {
180 list_worlds(true, true);
182 errorstream << "Invalid --worldlist value: "
183 << cmd_args.get("worldlist") << std::endl;
189 if (!init_common(cmd_args, argc, argv))
192 if (g_settings->getBool("enable_console"))
193 porting::attachOrCreateConsole();
197 if (cmd_args.getFlag("run-unittests")) {
201 errorstream << "Unittest support is not enabled in this binary. "
202 << "If you want to enable it, compile project with BUILD_UNITTESTS=1 flag."
209 GameStartData game_params;
211 porting::attachOrCreateConsole();
212 game_params.is_dedicated_server = true;
214 const bool isServer = cmd_args.getFlag("server");
216 porting::attachOrCreateConsole();
217 game_params.is_dedicated_server = isServer;
220 if (!game_configure(&game_params, cmd_args))
223 sanity_check(!game_params.world_path.empty());
225 if (game_params.is_dedicated_server)
226 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
229 retval = ClientLauncher().run(game_params, cmd_args) ? 0 : 1;
234 // Update configuration file
235 if (!g_settings_path.empty())
236 g_settings->updateConfigFile(g_settings_path.c_str());
238 print_modified_quicktune_values();
240 END_DEBUG_EXCEPTION_HANDLER
246 /*****************************************************************************
248 *****************************************************************************/
251 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
253 set_allowed_options(&allowed_options);
255 return cmd_args->parseCommandLine(argc, argv, allowed_options);
258 static void set_allowed_options(OptionList *allowed_options)
260 allowed_options->clear();
262 allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
263 _("Show allowed options"))));
264 allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
265 _("Show version information"))));
266 allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
267 _("Load configuration from specified file"))));
268 allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
269 _("Set network port (UDP)"))));
270 allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
271 _("Run the unit tests and exit"))));
272 allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
273 _("Same as --world (deprecated)"))));
274 allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
275 _("Set world path (implies local game if used with option --go)"))));
276 allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
277 _("Set world by name (implies local game if used with option --go)"))));
278 allowed_options->insert(std::make_pair("worldlist", ValueSpec(VALUETYPE_STRING,
279 _("Get list of worlds ('path' lists paths, "
280 "'name' lists names, 'both' lists both)"))));
281 allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
282 _("Print to console errors only"))));
283 allowed_options->insert(std::make_pair("color", ValueSpec(VALUETYPE_STRING,
284 _("Coloured logs ('always', 'never' or 'auto'), defaults to 'auto'"
286 allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
287 _("Print more information to console"))));
288 allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
289 _("Print even more information to console"))));
290 allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
291 _("Print enormous amounts of information to log and console"))));
292 allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
293 _("Set logfile path ('' = no logging)"))));
294 allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
295 _("Set gameid (\"--gameid list\" prints available ones)"))));
296 allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
297 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
298 allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING,
299 _("Migrate from current players backend to another (Only works when using minetestserver or with --server)"))));
300 allowed_options->insert(std::make_pair("migrate-auth", ValueSpec(VALUETYPE_STRING,
301 _("Migrate from current auth backend to another (Only works when using minetestserver or with --server)"))));
302 allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
303 _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
304 allowed_options->insert(std::make_pair("recompress", ValueSpec(VALUETYPE_FLAG,
305 _("Recompress the blocks of the given map database."))));
307 allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
308 _("Run speed tests"))));
309 allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
310 _("Address to connect to. ('' = local game)"))));
311 allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
312 _("Enable random user input, for testing"))));
313 allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
314 _("Run dedicated server"))));
315 allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
316 _("Set player name"))));
317 allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
318 _("Set password"))));
319 allowed_options->insert(std::make_pair("password-file", ValueSpec(VALUETYPE_STRING,
320 _("Set password from contents of file"))));
321 allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
322 _("Disable main menu"))));
323 allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
324 _("Starts with the console (Windows only)"))));
329 static void print_help(const OptionList &allowed_options)
331 std::cout << _("Allowed options:") << std::endl;
332 print_allowed_options(allowed_options);
335 static void print_allowed_options(const OptionList &allowed_options)
337 for (const auto &allowed_option : allowed_options) {
338 std::ostringstream os1(std::ios::binary);
339 os1 << " --" << allowed_option.first;
340 if (allowed_option.second.type != VALUETYPE_FLAG)
341 os1 << _(" <value>");
343 std::cout << padStringRight(os1.str(), 30);
345 if (allowed_option.second.help)
346 std::cout << allowed_option.second.help;
348 std::cout << std::endl;
352 static void print_version()
354 std::cout << PROJECT_NAME_C " " << g_version_hash
355 << " (" << porting::getPlatformName() << ")" << std::endl;
357 std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl;
360 std::cout << "Using " << LUAJIT_VERSION << std::endl;
362 std::cout << "Using " << LUA_RELEASE << std::endl;
364 std::cout << g_build_info << std::endl;
367 static void list_game_ids()
369 std::set<std::string> gameids = getAvailableGameIds();
370 for (const std::string &gameid : gameids)
371 std::cout << gameid <<std::endl;
374 static void list_worlds(bool print_name, bool print_path)
376 std::cout << _("Available worlds:") << std::endl;
377 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
378 print_worldspecs(worldspecs, std::cout, print_name, print_path);
381 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
382 std::ostream &os, bool print_name, bool print_path)
384 for (const WorldSpec &worldspec : worldspecs) {
385 std::string name = worldspec.name;
386 std::string path = worldspec.path;
387 if (print_name && print_path) {
388 os << "\t" << name << "\t\t" << path << std::endl;
389 } else if (print_name) {
390 os << "\t" << name << std::endl;
391 } else if (print_path) {
392 os << "\t" << path << std::endl;
397 static void print_modified_quicktune_values()
399 bool header_printed = false;
400 std::vector<std::string> names = getQuicktuneNames();
402 for (const std::string &name : names) {
403 QuicktuneValue val = getQuicktuneValue(name);
406 if (!header_printed) {
407 dstream << "Modified quicktune values:" << std::endl;
408 header_printed = true;
410 dstream << name << " = " << val.getString() << std::endl;
414 static bool setup_log_params(const Settings &cmd_args)
416 // Quiet mode, print errors only
417 if (cmd_args.getFlag("quiet")) {
418 g_logger.removeOutput(&stderr_output);
419 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
422 // Coloured log messages (see log.h)
423 std::string color_mode;
424 if (cmd_args.exists("color")) {
425 color_mode = cmd_args.get("color");
428 char *color_mode_env = getenv("MT_LOGCOLOR");
430 color_mode = color_mode_env;
433 if (color_mode != "") {
434 if (color_mode == "auto") {
435 Logger::color_mode = LOG_COLOR_AUTO;
436 } else if (color_mode == "always") {
437 Logger::color_mode = LOG_COLOR_ALWAYS;
438 } else if (color_mode == "never") {
439 Logger::color_mode = LOG_COLOR_NEVER;
441 errorstream << "Invalid color mode: " << color_mode << std::endl;
446 // If trace is enabled, enable logging of certain things
447 if (cmd_args.getFlag("trace")) {
448 dstream << _("Enabling trace level debug output") << std::endl;
449 g_logger.setTraceEnabled(true);
450 dout_con_ptr = &verbosestream; // This is somewhat old
451 socket_enable_debug_output = true; // Sockets doesn't use log.h
454 // In certain cases, output info level on stderr
455 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
456 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
457 g_logger.addOutput(&stderr_output, LL_INFO);
459 // In certain cases, output verbose level on stderr
460 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
461 g_logger.addOutput(&stderr_output, LL_VERBOSE);
466 static bool create_userdata_path()
471 if (!fs::PathExists(porting::path_user)) {
472 success = fs::CreateDir(porting::path_user);
477 // Create user data directory
478 success = fs::CreateDir(porting::path_user);
484 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
487 set_default_settings();
491 // Initialize g_settings
492 Settings::createLayer(SL_GLOBAL);
494 // Set cleanup callback(s) to run at process exit
495 atexit(uninit_common);
497 if (!read_config_file(cmd_args))
500 init_log_streams(cmd_args);
502 // Initialize random seed
506 // Initialize HTTP fetcher
507 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
509 init_gettext(porting::path_locale.c_str(),
510 g_settings->get("language"), argc, argv);
515 static void uninit_common()
521 // It'd actually be okay to leak these but we want to please valgrind...
522 for (int i = 0; i < (int)SL_TOTAL_COUNT; i++)
523 delete Settings::getLayer((SettingsLayer)i);
526 static void startup_message()
528 infostream << PROJECT_NAME << " " << _("with")
529 << " SER_FMT_VER_HIGHEST_READ="
530 << (int)SER_FMT_VER_HIGHEST_READ << ", "
531 << g_build_info << std::endl;
534 static bool read_config_file(const Settings &cmd_args)
536 // Path of configuration file in use
537 sanity_check(g_settings_path == ""); // Sanity check
539 if (cmd_args.exists("config")) {
540 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
542 errorstream << "Could not read configuration from \""
543 << cmd_args.get("config") << "\"" << std::endl;
546 g_settings_path = cmd_args.get("config");
548 std::vector<std::string> filenames;
549 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
550 // Legacy configuration file location
551 filenames.push_back(porting::path_user +
552 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
555 // Try also from a lower level (to aid having the same configuration
556 // for many RUN_IN_PLACE installs)
557 filenames.push_back(porting::path_user +
558 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
561 for (const std::string &filename : filenames) {
562 bool r = g_settings->readConfigFile(filename.c_str());
564 g_settings_path = filename;
569 // If no path found, use the first one (menu creates the file)
570 if (g_settings_path.empty())
571 g_settings_path = filenames[0];
577 static void init_log_streams(const Settings &cmd_args)
579 std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
581 if (cmd_args.exists("logfile"))
582 log_filename = cmd_args.get("logfile");
584 g_logger.removeOutput(&file_log_output);
585 std::string conf_loglev = g_settings->get("debug_log_level");
587 // Old integer format
588 if (std::isdigit(conf_loglev[0])) {
589 warningstream << "Deprecated use of debug_log_level with an "
590 "integer value; please update your configuration." << std::endl;
591 static const char *lev_name[] =
592 {"", "error", "action", "info", "verbose"};
593 int lev_i = atoi(conf_loglev.c_str());
594 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
595 warningstream << "Supplied invalid debug_log_level!"
596 " Assuming action level." << std::endl;
599 conf_loglev = lev_name[lev_i];
602 if (log_filename.empty() || conf_loglev.empty()) // No logging
605 LogLevel log_level = Logger::stringToLevel(conf_loglev);
606 if (log_level == LL_MAX) {
607 warningstream << "Supplied unrecognized debug_log_level; "
608 "using maximum." << std::endl;
611 file_log_output.setFile(log_filename,
612 g_settings->getU64("debug_log_size_max") * 1000000);
613 g_logger.addOutputMaxLevel(&file_log_output, log_level);
616 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
618 game_configure_port(game_params, cmd_args);
620 if (!game_configure_world(game_params, cmd_args)) {
621 errorstream << "No world path specified or found." << std::endl;
625 game_configure_subgame(game_params, cmd_args);
630 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
632 if (cmd_args.exists("port")) {
633 game_params->socket_port = cmd_args.getU16("port");
635 if (game_params->is_dedicated_server)
636 game_params->socket_port = g_settings->getU16("port");
638 game_params->socket_port = g_settings->getU16("remote_port");
641 if (game_params->socket_port == 0)
642 game_params->socket_port = DEFAULT_SERVER_PORT;
645 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
647 if (get_world_from_cmdline(game_params, cmd_args))
650 if (get_world_from_config(game_params, cmd_args))
653 return auto_select_world(game_params);
656 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
658 std::string commanded_world;
661 std::string commanded_worldname;
662 if (cmd_args.exists("worldname"))
663 commanded_worldname = cmd_args.get("worldname");
665 // If a world name was specified, convert it to a path
666 if (!commanded_worldname.empty()) {
667 // Get information about available worlds
668 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
670 for (const WorldSpec &worldspec : worldspecs) {
671 std::string name = worldspec.name;
672 if (name == commanded_worldname) {
673 dstream << _("Using world specified by --worldname on the "
674 "command line") << std::endl;
675 commanded_world = worldspec.path;
681 dstream << _("World") << " '" << commanded_worldname
682 << _("' not available. Available worlds:") << std::endl;
683 print_worldspecs(worldspecs, dstream);
687 game_params->world_path = get_clean_world_path(commanded_world);
688 return !commanded_world.empty();
691 if (cmd_args.exists("world"))
692 commanded_world = cmd_args.get("world");
693 else if (cmd_args.exists("map-dir"))
694 commanded_world = cmd_args.get("map-dir");
695 else if (cmd_args.exists("nonopt0")) // First nameless argument
696 commanded_world = cmd_args.get("nonopt0");
698 game_params->world_path = get_clean_world_path(commanded_world);
699 return !commanded_world.empty();
702 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
705 std::string commanded_world;
707 if (g_settings->exists("map-dir"))
708 commanded_world = g_settings->get("map-dir");
710 game_params->world_path = get_clean_world_path(commanded_world);
712 return !commanded_world.empty();
715 static bool auto_select_world(GameParams *game_params)
717 // No world was specified; try to select it automatically
718 // Get information about available worlds
720 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
721 std::string world_path;
723 // If there is only a single world, use it
724 if (worldspecs.size() == 1) {
725 world_path = worldspecs[0].path;
726 dstream <<_("Automatically selecting world at") << " ["
727 << world_path << "]" << std::endl;
728 // If there are multiple worlds, list them
729 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
730 std::cerr << _("Multiple worlds are available.") << std::endl;
731 std::cerr << _("Please select one using --worldname <name>"
732 " or --world <path>") << std::endl;
733 print_worldspecs(worldspecs, std::cerr);
735 // If there are no worlds, automatically create a new one
737 // This is the ultimate default world path
738 world_path = porting::path_user + DIR_DELIM + "worlds" +
740 infostream << "Using default world at ["
741 << world_path << "]" << std::endl;
744 assert(world_path != ""); // Post-condition
745 game_params->world_path = world_path;
749 static std::string get_clean_world_path(const std::string &path)
751 const std::string worldmt = "world.mt";
752 std::string clean_path;
754 if (path.size() > worldmt.size()
755 && path.substr(path.size() - worldmt.size()) == worldmt) {
756 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
757 clean_path = path.substr(0, path.size() - worldmt.size());
765 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
769 success = get_game_from_cmdline(game_params, cmd_args);
771 success = determine_subgame(game_params);
776 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
778 SubgameSpec commanded_gamespec;
780 if (cmd_args.exists("gameid")) {
781 std::string gameid = cmd_args.get("gameid");
782 commanded_gamespec = findSubgame(gameid);
783 if (!commanded_gamespec.isValid()) {
784 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
787 dstream << _("Using game specified by --gameid on the command line")
789 game_params->game_spec = commanded_gamespec;
796 static bool determine_subgame(GameParams *game_params)
798 SubgameSpec gamespec;
800 assert(game_params->world_path != ""); // Pre-condition
802 // If world doesn't exist
803 if (!game_params->world_path.empty()
804 && !getWorldExists(game_params->world_path)) {
805 // Try to take gamespec from command line
806 if (game_params->game_spec.isValid()) {
807 gamespec = game_params->game_spec;
808 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
809 } else { // Otherwise we will be using "minetest"
810 gamespec = findSubgame(g_settings->get("default_game"));
811 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
812 if (!gamespec.isValid()) {
813 errorstream << "Game specified in default_game ["
814 << g_settings->get("default_game")
815 << "] is invalid." << std::endl;
819 } else { // World exists
820 std::string world_gameid = getWorldGameId(game_params->world_path, false);
821 // If commanded to use a gameid, do so
822 if (game_params->game_spec.isValid()) {
823 gamespec = game_params->game_spec;
824 if (game_params->game_spec.id != world_gameid) {
825 warningstream << "Using commanded gameid ["
826 << gamespec.id << "]" << " instead of world gameid ["
827 << world_gameid << "]" << std::endl;
830 // If world contains an embedded game, use it;
831 // Otherwise find world from local system.
832 gamespec = findWorldSubgame(game_params->world_path);
833 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
837 if (!gamespec.isValid()) {
838 errorstream << "Game [" << gamespec.id << "] could not be found."
843 game_params->game_spec = gamespec;
848 /*****************************************************************************
850 *****************************************************************************/
851 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
853 verbosestream << _("Using world path") << " ["
854 << game_params.world_path << "]" << std::endl;
855 verbosestream << _("Using gameid") << " ["
856 << game_params.game_spec.id << "]" << std::endl;
859 std::string bind_str = g_settings->get("bind_address");
860 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
862 if (g_settings->getBool("ipv6_server")) {
863 bind_addr.setAddress((IPv6AddressBytes*) NULL);
866 bind_addr.Resolve(bind_str.c_str());
867 } catch (ResolveError &e) {
868 infostream << "Resolving bind address \"" << bind_str
869 << "\" failed: " << e.what()
870 << " -- Listening on all addresses." << std::endl;
872 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
873 errorstream << "Unable to listen on "
874 << bind_addr.serializeString()
875 << L" because IPv6 is disabled" << std::endl;
879 // Database migration/compression
880 if (cmd_args.exists("migrate"))
881 return migrate_map_database(game_params, cmd_args);
883 if (cmd_args.exists("migrate-players"))
884 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
886 if (cmd_args.exists("migrate-auth"))
887 return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);
889 if (cmd_args.getFlag("recompress"))
890 return recompress_map_database(game_params, cmd_args, bind_addr);
892 if (cmd_args.exists("terminal")) {
895 std::string admin_nick = g_settings->get("name");
897 name_ok = name_ok && !admin_nick.empty();
898 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
901 if (admin_nick.empty()) {
902 errorstream << "No name given for admin. "
903 << "Please check your minetest.conf that it "
904 << "contains a 'name = ' to your main admin account."
907 errorstream << "Name for admin '"
908 << admin_nick << "' is not valid. "
909 << "Please check that it only contains allowed characters. "
910 << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
916 bool &kill = *porting::signal_handler_killstatus();
920 Server server(game_params.world_path, game_params.game_spec,
921 false, bind_addr, true, &iface);
923 g_term_console.setup(&iface, &kill, admin_nick);
925 g_term_console.start();
929 dedicated_server_loop(server, kill);
930 } catch (const ModError &e) {
931 g_term_console.stopAndWaitforThread();
932 errorstream << "ModError: " << e.what() << std::endl;
934 } catch (const ServerError &e) {
935 g_term_console.stopAndWaitforThread();
936 errorstream << "ServerError: " << e.what() << std::endl;
940 // Tell the console to stop, and wait for it to finish,
941 // only then leave context and free iface
942 g_term_console.stop();
943 g_term_console.wait();
945 g_term_console.clearKillStatus();
948 errorstream << "Cmd arg --terminal passed, but "
949 << "compiled without ncurses. Ignoring." << std::endl;
954 Server server(game_params.world_path, game_params.game_spec, false,
959 bool &kill = *porting::signal_handler_killstatus();
960 dedicated_server_loop(server, kill);
962 } catch (const ModError &e) {
963 errorstream << "ModError: " << e.what() << std::endl;
965 } catch (const ServerError &e) {
966 errorstream << "ServerError: " << e.what() << std::endl;
974 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
976 std::string migrate_to = cmd_args.get("migrate");
978 std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
979 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
980 errorstream << "Cannot read world.mt!" << std::endl;
984 if (!world_mt.exists("backend")) {
985 errorstream << "Please specify your current backend in world.mt:"
987 << " backend = {sqlite3|leveldb|redis|dummy|postgresql}"
992 std::string backend = world_mt.get("backend");
993 if (backend == migrate_to) {
994 errorstream << "Cannot migrate: new backend is same"
995 << " as the old one" << std::endl;
999 MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
1000 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
1003 time_t last_update_time = 0;
1004 bool &kill = *porting::signal_handler_killstatus();
1006 std::vector<v3s16> blocks;
1007 old_db->listAllLoadableBlocks(blocks);
1008 new_db->beginSave();
1009 for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
1010 if (kill) return false;
1013 old_db->loadBlock(*it, &data);
1014 if (!data.empty()) {
1015 new_db->saveBlock(*it, data);
1017 errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
1019 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
1020 std::cerr << " Migrated " << count << " blocks, "
1021 << (100.0 * count / blocks.size()) << "% completed.\r";
1023 new_db->beginSave();
1024 last_update_time = time(NULL);
1027 std::cerr << std::endl;
1032 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1033 world_mt.set("backend", migrate_to);
1034 if (!world_mt.updateConfigFile(world_mt_path.c_str()))
1035 errorstream << "Failed to update world.mt!" << std::endl;
1037 actionstream << "world.mt updated" << std::endl;
1042 static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr)
1045 const std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
1047 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
1048 errorstream << "Cannot read world.mt at " << world_mt_path << std::endl;
1051 const std::string &backend = world_mt.get("backend");
1052 Server server(game_params.world_path, game_params.game_spec, false, addr, false);
1053 MapDatabase *db = ServerMap::createDatabase(backend, game_params.world_path, world_mt);
1056 u64 last_update_time = 0;
1057 bool &kill = *porting::signal_handler_killstatus();
1058 const u8 serialize_as_ver = SER_FMT_VER_HIGHEST_WRITE;
1060 // This is ok because the server doesn't actually run
1061 std::vector<v3s16> blocks;
1062 db->listAllLoadableBlocks(blocks);
1064 std::istringstream iss(std::ios_base::binary);
1065 std::ostringstream oss(std::ios_base::binary);
1066 for (auto it = blocks.begin(); it != blocks.end(); ++it) {
1067 if (kill) return false;
1070 db->loadBlock(*it, &data);
1072 errorstream << "Failed to load block " << PP(*it) << std::endl;
1079 MapBlock mb(nullptr, v3s16(0,0,0), &server);
1080 u8 ver = readU8(iss);
1081 mb.deSerialize(iss, ver, true);
1085 writeU8(oss, serialize_as_ver);
1086 mb.serialize(oss, serialize_as_ver, true, -1);
1088 db->saveBlock(*it, oss.str());
1091 if (count % 0xFF == 0 && porting::getTimeS() - last_update_time >= 1) {
1092 std::cerr << " Recompressed " << count << " blocks, "
1093 << (100.0f * count / blocks.size()) << "% completed.\r";
1096 last_update_time = porting::getTimeS();
1099 std::cerr << std::endl;
1102 actionstream << "Done, " << count << " blocks were recompressed." << std::endl;