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 "irrlicht.h" // createDevice
21 #include "mainmenumanager.h"
22 #include "irrlichttypes_extrabloated.h"
23 #include "chat_interface.h"
25 #include "unittest/test.h"
29 #include "guiMainMenu.h"
31 #include "defaultsettings.h"
34 #include "quicktune.h"
35 #include "httpfetch.h"
36 #include "guiEngine.h"
37 #include "gameparams.h"
43 #include "terminal_chat_console.h"
46 #include "client/clientlauncher.h"
49 #ifdef HAVE_TOUCHSCREENGUI
50 #include "touchscreengui.h"
53 #if !defined(SERVER) && \
54 (IRRLICHT_VERSION_MAJOR == 1) && \
55 (IRRLICHT_VERSION_MINOR == 8) && \
56 (IRRLICHT_VERSION_REVISION == 2)
57 #error "Irrlicht 1.8.2 is known to be broken - please update Irrlicht to version >= 1.8.3"
60 #define DEBUGFILE "debug.txt"
61 #define DEFAULT_SERVER_PORT 30000
63 typedef std::map<std::string, ValueSpec> OptionList;
65 /**********************************************************************
67 **********************************************************************/
69 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
70 static void set_allowed_options(OptionList *allowed_options);
72 static void print_help(const OptionList &allowed_options);
73 static void print_allowed_options(const OptionList &allowed_options);
74 static void print_version();
75 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
77 static void print_modified_quicktune_values();
79 static void list_game_ids();
80 static void list_worlds();
81 static void setup_log_params(const Settings &cmd_args);
82 static bool create_userdata_path();
83 static bool init_common(const Settings &cmd_args, int argc, char *argv[]);
84 static void startup_message();
85 static bool read_config_file(const Settings &cmd_args);
86 static void init_log_streams(const Settings &cmd_args);
88 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
89 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
91 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
92 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
93 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
94 static bool auto_select_world(GameParams *game_params);
95 static std::string get_clean_world_path(const std::string &path);
97 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
98 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
99 static bool determine_subgame(GameParams *game_params);
101 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
102 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args);
104 /**********************************************************************/
107 FileLogOutput file_log_output;
109 static OptionList allowed_options;
111 int main(int argc, char *argv[])
114 debug_set_exception_handler();
116 g_logger.registerThread("Main");
117 g_logger.addOutputMaxLevel(&stderr_output, LL_ACTION);
120 bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
122 || cmd_args.getFlag("help")
123 || cmd_args.exists("nonopt1")) {
124 porting::attachOrCreateConsole();
125 print_help(allowed_options);
126 return cmd_args_ok ? 0 : 1;
128 if (cmd_args.getFlag("console"))
129 porting::attachOrCreateConsole();
131 if (cmd_args.getFlag("version")) {
132 porting::attachOrCreateConsole();
137 setup_log_params(cmd_args);
139 porting::signal_handler_init();
142 porting::initAndroid();
143 porting::initializePathsAndroid();
145 porting::initializePaths();
148 if (!create_userdata_path()) {
149 errorstream << "Cannot create user data directory" << std::endl;
153 // Initialize debug stacks
154 DSTACK(FUNCTION_NAME);
157 BEGIN_DEBUG_EXCEPTION_HANDLER
159 // List gameids if requested
160 if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
165 // List worlds if requested
166 if (cmd_args.exists("world") && cmd_args.get("world") == "list") {
171 if (!init_common(cmd_args, argc, argv))
174 if (g_settings->getBool("enable_console"))
175 porting::attachOrCreateConsole();
179 if (cmd_args.getFlag("run-unittests")) {
184 GameParams game_params;
186 porting::attachOrCreateConsole();
187 game_params.is_dedicated_server = true;
189 const bool isServer = cmd_args.getFlag("server");
191 porting::attachOrCreateConsole();
192 game_params.is_dedicated_server = isServer;
195 if (!game_configure(&game_params, cmd_args))
198 sanity_check(!game_params.world_path.empty());
200 infostream << "Using commanded world path ["
201 << game_params.world_path << "]" << std::endl;
203 if (game_params.is_dedicated_server)
204 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
207 ClientLauncher launcher;
208 retval = launcher.run(game_params, cmd_args) ? 0 : 1;
213 // Update configuration file
214 if (!g_settings_path.empty())
215 g_settings->updateConfigFile(g_settings_path.c_str());
217 print_modified_quicktune_values();
219 // Stop httpfetch thread (if started)
222 END_DEBUG_EXCEPTION_HANDLER
228 /*****************************************************************************
230 *****************************************************************************/
233 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
235 set_allowed_options(&allowed_options);
237 return cmd_args->parseCommandLine(argc, argv, allowed_options);
240 static void set_allowed_options(OptionList *allowed_options)
242 allowed_options->clear();
244 allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
245 _("Show allowed options"))));
246 allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
247 _("Show version information"))));
248 allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
249 _("Load configuration from specified file"))));
250 allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
251 _("Set network port (UDP)"))));
252 allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
253 _("Run the unit tests and exit"))));
254 allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
255 _("Same as --world (deprecated)"))));
256 allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
257 _("Set world path (implies local game) ('list' lists all)"))));
258 allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
259 _("Set world by name (implies local game)"))));
260 allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
261 _("Print to console errors only"))));
262 allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
263 _("Print more information to console"))));
264 allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
265 _("Print even more information to console"))));
266 allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
267 _("Print enormous amounts of information to log and console"))));
268 allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
269 _("Set logfile path ('' = no logging)"))));
270 allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
271 _("Set gameid (\"--gameid list\" prints available ones)"))));
272 allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
273 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
274 allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING,
275 _("Migrate from current players backend to another (Only works when using minetestserver or with --server)"))));
276 allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
277 _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
279 allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
280 _("Show available video modes"))));
281 allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
282 _("Run speed tests"))));
283 allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
284 _("Address to connect to. ('' = local game)"))));
285 allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
286 _("Enable random user input, for testing"))));
287 allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
288 _("Run dedicated server"))));
289 allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
290 _("Set player name"))));
291 allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
292 _("Set password"))));
293 allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
294 _("Disable main menu"))));
295 allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
296 _("Starts with the console (Windows only)"))));
301 static void print_help(const OptionList &allowed_options)
303 std::cout << _("Allowed options:") << std::endl;
304 print_allowed_options(allowed_options);
307 static void print_allowed_options(const OptionList &allowed_options)
309 for (const auto &allowed_option : allowed_options) {
310 std::ostringstream os1(std::ios::binary);
311 os1 << " --" << allowed_option.first;
312 if (allowed_option.second.type != VALUETYPE_FLAG)
313 os1 << _(" <value>");
315 std::cout << padStringRight(os1.str(), 30);
317 if (allowed_option.second.help)
318 std::cout << allowed_option.second.help;
320 std::cout << std::endl;
324 static void print_version()
326 std::cout << PROJECT_NAME_C " " << g_version_hash
327 << " (" << porting::getPlatformName() << ")" << std::endl;
329 std::cout << "Using Irrlicht " << IRRLICHT_SDK_VERSION << std::endl;
331 std::cout << "Build info: " << g_build_info << std::endl;
334 static void list_game_ids()
336 std::set<std::string> gameids = getAvailableGameIds();
337 for (const std::string &gameid : gameids)
338 std::cout << gameid <<std::endl;
341 static void list_worlds()
343 std::cout << _("Available worlds:") << std::endl;
344 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
345 print_worldspecs(worldspecs, std::cout);
348 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
351 for (const WorldSpec &worldspec : worldspecs) {
352 std::string name = worldspec.name;
353 std::string path = worldspec.path;
354 if (name.find(' ') != std::string::npos)
355 name = std::string("'") + name + "'";
356 path = std::string("'") + path + "'";
357 name = padStringRight(name, 14);
358 os << " " << name << " " << path << std::endl;
362 static void print_modified_quicktune_values()
364 bool header_printed = false;
365 std::vector<std::string> names = getQuicktuneNames();
367 for (const std::string &name : names) {
368 QuicktuneValue val = getQuicktuneValue(name);
371 if (!header_printed) {
372 dstream << "Modified quicktune values:" << std::endl;
373 header_printed = true;
375 dstream << name << " = " << val.getString() << std::endl;
379 static void setup_log_params(const Settings &cmd_args)
381 // Quiet mode, print errors only
382 if (cmd_args.getFlag("quiet")) {
383 g_logger.removeOutput(&stderr_output);
384 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
387 // If trace is enabled, enable logging of certain things
388 if (cmd_args.getFlag("trace")) {
389 dstream << _("Enabling trace level debug output") << std::endl;
390 g_logger.setTraceEnabled(true);
391 dout_con_ptr = &verbosestream; // This is somewhat old
392 socket_enable_debug_output = true; // Sockets doesn't use log.h
395 // In certain cases, output info level on stderr
396 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
397 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
398 g_logger.addOutput(&stderr_output, LL_INFO);
400 // In certain cases, output verbose level on stderr
401 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
402 g_logger.addOutput(&stderr_output, LL_VERBOSE);
405 static bool create_userdata_path()
410 if (!fs::PathExists(porting::path_user)) {
411 success = fs::CreateDir(porting::path_user);
415 porting::copyAssets();
417 // Create user data directory
418 success = fs::CreateDir(porting::path_user);
424 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
427 set_default_settings(g_settings);
429 // Initialize sockets
431 atexit(sockets_cleanup);
433 if (!read_config_file(cmd_args))
436 init_log_streams(cmd_args);
438 // Initialize random seed
442 // Initialize HTTP fetcher
443 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
445 init_gettext(porting::path_locale.c_str(),
446 g_settings->get("language"), argc, argv);
451 static void startup_message()
453 infostream << PROJECT_NAME << " " << _("with")
454 << " SER_FMT_VER_HIGHEST_READ="
455 << (int)SER_FMT_VER_HIGHEST_READ << ", "
456 << g_build_info << std::endl;
459 static bool read_config_file(const Settings &cmd_args)
461 // Path of configuration file in use
462 sanity_check(g_settings_path == ""); // Sanity check
464 if (cmd_args.exists("config")) {
465 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
467 errorstream << "Could not read configuration from \""
468 << cmd_args.get("config") << "\"" << std::endl;
471 g_settings_path = cmd_args.get("config");
473 std::vector<std::string> filenames;
474 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
475 // Legacy configuration file location
476 filenames.push_back(porting::path_user +
477 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
480 // Try also from a lower level (to aid having the same configuration
481 // for many RUN_IN_PLACE installs)
482 filenames.push_back(porting::path_user +
483 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
486 for (const std::string &filename : filenames) {
487 bool r = g_settings->readConfigFile(filename.c_str());
489 g_settings_path = filename;
494 // If no path found, use the first one (menu creates the file)
495 if (g_settings_path.empty())
496 g_settings_path = filenames[0];
502 static void init_log_streams(const Settings &cmd_args)
505 std::string log_filename = DEBUGFILE;
507 std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
509 if (cmd_args.exists("logfile"))
510 log_filename = cmd_args.get("logfile");
512 g_logger.removeOutput(&file_log_output);
513 std::string conf_loglev = g_settings->get("debug_log_level");
515 // Old integer format
516 if (std::isdigit(conf_loglev[0])) {
517 warningstream << "Deprecated use of debug_log_level with an "
518 "integer value; please update your configuration." << std::endl;
519 static const char *lev_name[] =
520 {"", "error", "action", "info", "verbose"};
521 int lev_i = atoi(conf_loglev.c_str());
522 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
523 warningstream << "Supplied invalid debug_log_level!"
524 " Assuming action level." << std::endl;
527 conf_loglev = lev_name[lev_i];
530 if (log_filename.empty() || conf_loglev.empty()) // No logging
533 LogLevel log_level = Logger::stringToLevel(conf_loglev);
534 if (log_level == LL_MAX) {
535 warningstream << "Supplied unrecognized debug_log_level; "
536 "using maximum." << std::endl;
539 verbosestream << "log_filename = " << log_filename << std::endl;
541 file_log_output.open(log_filename);
542 g_logger.addOutputMaxLevel(&file_log_output, log_level);
545 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
547 game_configure_port(game_params, cmd_args);
549 if (!game_configure_world(game_params, cmd_args)) {
550 errorstream << "No world path specified or found." << std::endl;
554 game_configure_subgame(game_params, cmd_args);
559 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
561 if (cmd_args.exists("port"))
562 game_params->socket_port = cmd_args.getU16("port");
564 game_params->socket_port = g_settings->getU16("port");
566 if (game_params->socket_port == 0)
567 game_params->socket_port = DEFAULT_SERVER_PORT;
570 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
572 if (get_world_from_cmdline(game_params, cmd_args))
575 if (get_world_from_config(game_params, cmd_args))
578 return auto_select_world(game_params);
581 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
583 std::string commanded_world;
586 std::string commanded_worldname;
587 if (cmd_args.exists("worldname"))
588 commanded_worldname = cmd_args.get("worldname");
590 // If a world name was specified, convert it to a path
591 if (!commanded_worldname.empty()) {
592 // Get information about available worlds
593 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
595 for (const WorldSpec &worldspec : worldspecs) {
596 std::string name = worldspec.name;
597 if (name == commanded_worldname) {
598 dstream << _("Using world specified by --worldname on the "
599 "command line") << std::endl;
600 commanded_world = worldspec.path;
606 dstream << _("World") << " '" << commanded_worldname
607 << _("' not available. Available worlds:") << std::endl;
608 print_worldspecs(worldspecs, dstream);
612 game_params->world_path = get_clean_world_path(commanded_world);
613 return !commanded_world.empty();
616 if (cmd_args.exists("world"))
617 commanded_world = cmd_args.get("world");
618 else if (cmd_args.exists("map-dir"))
619 commanded_world = cmd_args.get("map-dir");
620 else if (cmd_args.exists("nonopt0")) // First nameless argument
621 commanded_world = cmd_args.get("nonopt0");
623 game_params->world_path = get_clean_world_path(commanded_world);
624 return !commanded_world.empty();
627 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
630 std::string commanded_world;
632 if (g_settings->exists("map-dir"))
633 commanded_world = g_settings->get("map-dir");
635 game_params->world_path = get_clean_world_path(commanded_world);
637 return !commanded_world.empty();
640 static bool auto_select_world(GameParams *game_params)
642 // No world was specified; try to select it automatically
643 // Get information about available worlds
645 verbosestream << _("Determining world path") << std::endl;
647 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
648 std::string world_path;
650 // If there is only a single world, use it
651 if (worldspecs.size() == 1) {
652 world_path = worldspecs[0].path;
653 dstream <<_("Automatically selecting world at") << " ["
654 << world_path << "]" << std::endl;
655 // If there are multiple worlds, list them
656 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
657 std::cerr << _("Multiple worlds are available.") << std::endl;
658 std::cerr << _("Please select one using --worldname <name>"
659 " or --world <path>") << std::endl;
660 print_worldspecs(worldspecs, std::cerr);
662 // If there are no worlds, automatically create a new one
664 // This is the ultimate default world path
665 world_path = porting::path_user + DIR_DELIM + "worlds" +
667 infostream << "Creating default world at ["
668 << world_path << "]" << std::endl;
671 assert(world_path != ""); // Post-condition
672 game_params->world_path = world_path;
676 static std::string get_clean_world_path(const std::string &path)
678 const std::string worldmt = "world.mt";
679 std::string clean_path;
681 if (path.size() > worldmt.size()
682 && path.substr(path.size() - worldmt.size()) == worldmt) {
683 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
684 clean_path = path.substr(0, path.size() - worldmt.size());
692 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
696 success = get_game_from_cmdline(game_params, cmd_args);
698 success = determine_subgame(game_params);
703 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
705 SubgameSpec commanded_gamespec;
707 if (cmd_args.exists("gameid")) {
708 std::string gameid = cmd_args.get("gameid");
709 commanded_gamespec = findSubgame(gameid);
710 if (!commanded_gamespec.isValid()) {
711 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
714 dstream << _("Using game specified by --gameid on the command line")
716 game_params->game_spec = commanded_gamespec;
723 static bool determine_subgame(GameParams *game_params)
725 SubgameSpec gamespec;
727 assert(game_params->world_path != ""); // Pre-condition
729 verbosestream << _("Determining gameid/gamespec") << std::endl;
730 // If world doesn't exist
731 if (!game_params->world_path.empty()
732 && !getWorldExists(game_params->world_path)) {
733 // Try to take gamespec from command line
734 if (game_params->game_spec.isValid()) {
735 gamespec = game_params->game_spec;
736 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
737 } else { // Otherwise we will be using "minetest"
738 gamespec = findSubgame(g_settings->get("default_game"));
739 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
740 if (!gamespec.isValid()) {
741 errorstream << "Subgame specified in default_game ["
742 << g_settings->get("default_game")
743 << "] is invalid." << std::endl;
747 } else { // World exists
748 std::string world_gameid = getWorldGameId(game_params->world_path, false);
749 // If commanded to use a gameid, do so
750 if (game_params->game_spec.isValid()) {
751 gamespec = game_params->game_spec;
752 if (game_params->game_spec.id != world_gameid) {
753 warningstream << "Using commanded gameid ["
754 << gamespec.id << "]" << " instead of world gameid ["
755 << world_gameid << "]" << std::endl;
758 // If world contains an embedded game, use it;
759 // Otherwise find world from local system.
760 gamespec = findWorldSubgame(game_params->world_path);
761 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
765 if (!gamespec.isValid()) {
766 errorstream << "Subgame [" << gamespec.id << "] could not be found."
771 game_params->game_spec = gamespec;
776 /*****************************************************************************
778 *****************************************************************************/
779 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
781 DSTACK("Dedicated server branch");
783 verbosestream << _("Using world path") << " ["
784 << game_params.world_path << "]" << std::endl;
785 verbosestream << _("Using gameid") << " ["
786 << game_params.game_spec.id << "]" << std::endl;
789 std::string bind_str = g_settings->get("bind_address");
790 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
792 if (g_settings->getBool("ipv6_server")) {
793 bind_addr.setAddress((IPv6AddressBytes*) NULL);
796 bind_addr.Resolve(bind_str.c_str());
797 } catch (ResolveError &e) {
798 infostream << "Resolving bind address \"" << bind_str
799 << "\" failed: " << e.what()
800 << " -- Listening on all addresses." << std::endl;
802 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
803 errorstream << "Unable to listen on "
804 << bind_addr.serializeString()
805 << L" because IPv6 is disabled" << std::endl;
809 // Database migration
810 if (cmd_args.exists("migrate"))
811 return migrate_map_database(game_params, cmd_args);
813 if (cmd_args.exists("migrate-players"))
814 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
816 if (cmd_args.exists("terminal")) {
819 std::string admin_nick = g_settings->get("name");
821 name_ok = name_ok && !admin_nick.empty();
822 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
825 if (admin_nick.empty()) {
826 errorstream << "No name given for admin. "
827 << "Please check your minetest.conf that it "
828 << "contains a 'name = ' to your main admin account."
831 errorstream << "Name for admin '"
832 << admin_nick << "' is not valid. "
833 << "Please check that it only contains allowed characters. "
834 << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
840 bool &kill = *porting::signal_handler_killstatus();
844 Server server(game_params.world_path, game_params.game_spec,
845 false, bind_addr.isIPv6(), true, &iface);
847 g_term_console.setup(&iface, &kill, admin_nick);
849 g_term_console.start();
851 server.start(bind_addr);
853 dedicated_server_loop(server, kill);
854 } catch (const ModError &e) {
855 g_term_console.stopAndWaitforThread();
856 errorstream << "ModError: " << e.what() << std::endl;
858 } catch (const ServerError &e) {
859 g_term_console.stopAndWaitforThread();
860 errorstream << "ServerError: " << e.what() << std::endl;
864 // Tell the console to stop, and wait for it to finish,
865 // only then leave context and free iface
866 g_term_console.stop();
867 g_term_console.wait();
869 g_term_console.clearKillStatus();
872 errorstream << "Cmd arg --terminal passed, but "
873 << "compiled without ncurses. Ignoring." << std::endl;
878 Server server(game_params.world_path, game_params.game_spec, false,
879 bind_addr.isIPv6(), true);
880 server.start(bind_addr);
883 bool &kill = *porting::signal_handler_killstatus();
884 dedicated_server_loop(server, kill);
886 } catch (const ModError &e) {
887 errorstream << "ModError: " << e.what() << std::endl;
889 } catch (const ServerError &e) {
890 errorstream << "ServerError: " << e.what() << std::endl;
898 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
900 std::string migrate_to = cmd_args.get("migrate");
902 std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
903 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
904 errorstream << "Cannot read world.mt!" << std::endl;
908 if (!world_mt.exists("backend")) {
909 errorstream << "Please specify your current backend in world.mt:"
911 << " backend = {sqlite3|leveldb|redis|dummy|postgresql}"
916 std::string backend = world_mt.get("backend");
917 if (backend == migrate_to) {
918 errorstream << "Cannot migrate: new backend is same"
919 << " as the old one" << std::endl;
923 MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
924 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
927 time_t last_update_time = 0;
928 bool &kill = *porting::signal_handler_killstatus();
930 std::vector<v3s16> blocks;
931 old_db->listAllLoadableBlocks(blocks);
933 for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
934 if (kill) return false;
937 old_db->loadBlock(*it, &data);
939 new_db->saveBlock(*it, data);
941 errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
943 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
944 std::cerr << " Migrated " << count << " blocks, "
945 << (100.0 * count / blocks.size()) << "% completed.\r";
948 last_update_time = time(NULL);
951 std::cerr << std::endl;
956 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
957 world_mt.set("backend", migrate_to);
958 if (!world_mt.updateConfigFile(world_mt_path.c_str()))
959 errorstream << "Failed to update world.mt!" << std::endl;
961 actionstream << "world.mt updated" << std::endl;