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
22 #include "mainmenumanager.h"
23 #include "irrlichttypes_extrabloated.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"
39 #include "mapsector.h"
40 #include "fontengine.h"
41 #include "gameparams.h"
46 #include "terminal_chat_console.h"
49 #include "client/clientlauncher.h"
53 #ifdef HAVE_TOUCHSCREENGUI
54 #include "touchscreengui.h"
57 #if !defined(SERVER) && \
58 (IRRLICHT_VERSION_MAJOR == 1) && \
59 (IRRLICHT_VERSION_MINOR == 8) && \
60 (IRRLICHT_VERSION_REVISION == 2)
61 #error "Irrlicht 1.8.2 is known to be broken - please update Irrlicht to version >= 1.8.3"
64 #define DEBUGFILE "debug.txt"
65 #define DEFAULT_SERVER_PORT 30000
67 typedef std::map<std::string, ValueSpec> OptionList;
69 /**********************************************************************
71 **********************************************************************/
73 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
74 static void set_allowed_options(OptionList *allowed_options);
76 static void print_help(const OptionList &allowed_options);
77 static void print_allowed_options(const OptionList &allowed_options);
78 static void print_version();
79 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
81 static void print_modified_quicktune_values();
83 static void list_game_ids();
84 static void list_worlds();
85 static void setup_log_params(const Settings &cmd_args);
86 static bool create_userdata_path();
87 static bool init_common(const Settings &cmd_args, int argc, char *argv[]);
88 static void startup_message();
89 static bool read_config_file(const Settings &cmd_args);
90 static void init_log_streams(const Settings &cmd_args);
92 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
93 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
95 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
96 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
97 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
98 static bool auto_select_world(GameParams *game_params);
99 static std::string get_clean_world_path(const std::string &path);
101 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
102 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
103 static bool determine_subgame(GameParams *game_params);
105 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
106 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args);
108 /**********************************************************************/
111 gettime.h implementation
118 /* Use imprecise system calls directly (from porting.h) */
119 return porting::getTime(PRECISION_MILLI);
122 u32 getTime(TimePrecision prec)
124 return porting::getTime(prec);
129 FileLogOutput file_log_output;
131 static OptionList allowed_options;
133 int main(int argc, char *argv[])
136 debug_set_exception_handler();
138 g_logger.registerThread("Main");
139 g_logger.addOutputMaxLevel(&stderr_output, LL_ACTION);
142 bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
144 || cmd_args.getFlag("help")
145 || cmd_args.exists("nonopt1")) {
146 porting::attachOrCreateConsole();
147 print_help(allowed_options);
148 return cmd_args_ok ? 0 : 1;
150 if (cmd_args.getFlag("console"))
151 porting::attachOrCreateConsole();
153 if (cmd_args.getFlag("version")) {
154 porting::attachOrCreateConsole();
159 setup_log_params(cmd_args);
161 porting::signal_handler_init();
164 porting::initAndroid();
165 porting::initializePathsAndroid();
167 porting::initializePaths();
170 if (!create_userdata_path()) {
171 errorstream << "Cannot create user data directory" << std::endl;
175 // Initialize debug stacks
176 DSTACK(FUNCTION_NAME);
179 BEGIN_DEBUG_EXCEPTION_HANDLER
181 // List gameids if requested
182 if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
187 // List worlds if requested
188 if (cmd_args.exists("world") && cmd_args.get("world") == "list") {
193 if (!init_common(cmd_args, argc, argv))
196 if (g_settings->getBool("enable_console"))
197 porting::attachOrCreateConsole();
201 if (cmd_args.getFlag("run-unittests")) {
206 GameParams game_params;
208 porting::attachOrCreateConsole();
209 game_params.is_dedicated_server = true;
211 const bool isServer = cmd_args.getFlag("server");
213 porting::attachOrCreateConsole();
214 game_params.is_dedicated_server = isServer;
217 if (!game_configure(&game_params, cmd_args))
220 sanity_check(!game_params.world_path.empty());
222 infostream << "Using commanded world path ["
223 << game_params.world_path << "]" << std::endl;
225 if (game_params.is_dedicated_server)
226 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
229 ClientLauncher launcher;
230 retval = launcher.run(game_params, cmd_args) ? 0 : 1;
235 // Update configuration file
236 if (g_settings_path != "")
237 g_settings->updateConfigFile(g_settings_path.c_str());
239 print_modified_quicktune_values();
241 // Stop httpfetch thread (if started)
244 END_DEBUG_EXCEPTION_HANDLER
250 /*****************************************************************************
252 *****************************************************************************/
255 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
257 set_allowed_options(&allowed_options);
259 return cmd_args->parseCommandLine(argc, argv, allowed_options);
262 static void set_allowed_options(OptionList *allowed_options)
264 allowed_options->clear();
266 allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
267 _("Show allowed options"))));
268 allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
269 _("Show version information"))));
270 allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
271 _("Load configuration from specified file"))));
272 allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
273 _("Set network port (UDP)"))));
274 allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
275 _("Run the unit tests and exit"))));
276 allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
277 _("Same as --world (deprecated)"))));
278 allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
279 _("Set world path (implies local game) ('list' lists all)"))));
280 allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
281 _("Set world by name (implies local game)"))));
282 allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
283 _("Print to console errors only"))));
284 allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
285 _("Print more information to console"))));
286 allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
287 _("Print even more information to console"))));
288 allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
289 _("Print enormous amounts of information to log and console"))));
290 allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
291 _("Set logfile path ('' = no logging)"))));
292 allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
293 _("Set gameid (\"--gameid list\" prints available ones)"))));
294 allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
295 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
296 allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING,
297 _("Migrate from current players backend to another (Only works when using minetestserver or with --server)"))));
298 allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
299 _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
301 allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
302 _("Show available video modes"))));
303 allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
304 _("Run speed tests"))));
305 allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
306 _("Address to connect to. ('' = local game)"))));
307 allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
308 _("Enable random user input, for testing"))));
309 allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
310 _("Run dedicated server"))));
311 allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
312 _("Set player name"))));
313 allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
314 _("Set password"))));
315 allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
316 _("Disable main menu"))));
317 allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
318 _("Starts with the console (Windows only)"))));
323 static void print_help(const OptionList &allowed_options)
325 std::cout << _("Allowed options:") << std::endl;
326 print_allowed_options(allowed_options);
329 static void print_allowed_options(const OptionList &allowed_options)
331 for (OptionList::const_iterator i = allowed_options.begin();
332 i != allowed_options.end(); ++i) {
333 std::ostringstream os1(std::ios::binary);
334 os1 << " --" << i->first;
335 if (i->second.type != VALUETYPE_FLAG)
336 os1 << _(" <value>");
338 std::cout << padStringRight(os1.str(), 30);
340 if (i->second.help != NULL)
341 std::cout << i->second.help;
343 std::cout << std::endl;
347 static void print_version()
349 std::cout << PROJECT_NAME_C " " << g_version_hash
350 << " (" << porting::getPlatformName() << ")" << std::endl;
352 std::cout << "Using Irrlicht " << IRRLICHT_SDK_VERSION << std::endl;
354 std::cout << "Build info: " << g_build_info << std::endl;
357 static void list_game_ids()
359 std::set<std::string> gameids = getAvailableGameIds();
360 for (std::set<std::string>::const_iterator i = gameids.begin();
361 i != gameids.end(); ++i)
362 std::cout << (*i) <<std::endl;
365 static void list_worlds()
367 std::cout << _("Available worlds:") << std::endl;
368 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
369 print_worldspecs(worldspecs, std::cout);
372 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
375 for (size_t i = 0; i < worldspecs.size(); i++) {
376 std::string name = worldspecs[i].name;
377 std::string path = worldspecs[i].path;
378 if (name.find(" ") != std::string::npos)
379 name = std::string("'") + name + "'";
380 path = std::string("'") + path + "'";
381 name = padStringRight(name, 14);
382 os << " " << name << " " << path << std::endl;
386 static void print_modified_quicktune_values()
388 bool header_printed = false;
389 std::vector<std::string> names = getQuicktuneNames();
391 for (u32 i = 0; i < names.size(); i++) {
392 QuicktuneValue val = getQuicktuneValue(names[i]);
395 if (!header_printed) {
396 dstream << "Modified quicktune values:" << std::endl;
397 header_printed = true;
399 dstream << names[i] << " = " << val.getString() << std::endl;
403 static void setup_log_params(const Settings &cmd_args)
405 // Quiet mode, print errors only
406 if (cmd_args.getFlag("quiet")) {
407 g_logger.removeOutput(&stderr_output);
408 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
411 // If trace is enabled, enable logging of certain things
412 if (cmd_args.getFlag("trace")) {
413 dstream << _("Enabling trace level debug output") << std::endl;
414 g_logger.setTraceEnabled(true);
415 dout_con_ptr = &verbosestream; // This is somewhat old
416 socket_enable_debug_output = true; // Sockets doesn't use log.h
419 // In certain cases, output info level on stderr
420 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
421 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
422 g_logger.addOutput(&stderr_output, LL_INFO);
424 // In certain cases, output verbose level on stderr
425 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
426 g_logger.addOutput(&stderr_output, LL_VERBOSE);
429 static bool create_userdata_path()
434 if (!fs::PathExists(porting::path_user)) {
435 success = fs::CreateDir(porting::path_user);
439 porting::copyAssets();
441 // Create user data directory
442 success = fs::CreateDir(porting::path_user);
448 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
451 set_default_settings(g_settings);
453 // Initialize sockets
455 atexit(sockets_cleanup);
457 if (!read_config_file(cmd_args))
460 init_log_streams(cmd_args);
462 // Initialize random seed
466 // Initialize HTTP fetcher
467 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
469 init_gettext(porting::path_locale.c_str(),
470 g_settings->get("language"), argc, argv);
475 static void startup_message()
477 infostream << PROJECT_NAME << " " << _("with")
478 << " SER_FMT_VER_HIGHEST_READ="
479 << (int)SER_FMT_VER_HIGHEST_READ << ", "
480 << g_build_info << std::endl;
483 static bool read_config_file(const Settings &cmd_args)
485 // Path of configuration file in use
486 sanity_check(g_settings_path == ""); // Sanity check
488 if (cmd_args.exists("config")) {
489 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
491 errorstream << "Could not read configuration from \""
492 << cmd_args.get("config") << "\"" << std::endl;
495 g_settings_path = cmd_args.get("config");
497 std::vector<std::string> filenames;
498 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
499 // Legacy configuration file location
500 filenames.push_back(porting::path_user +
501 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
504 // Try also from a lower level (to aid having the same configuration
505 // for many RUN_IN_PLACE installs)
506 filenames.push_back(porting::path_user +
507 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
510 for (size_t i = 0; i < filenames.size(); i++) {
511 bool r = g_settings->readConfigFile(filenames[i].c_str());
513 g_settings_path = filenames[i];
518 // If no path found, use the first one (menu creates the file)
519 if (g_settings_path == "")
520 g_settings_path = filenames[0];
526 static void init_log_streams(const Settings &cmd_args)
529 std::string log_filename = DEBUGFILE;
531 std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
533 if (cmd_args.exists("logfile"))
534 log_filename = cmd_args.get("logfile");
536 g_logger.removeOutput(&file_log_output);
537 std::string conf_loglev = g_settings->get("debug_log_level");
539 // Old integer format
540 if (std::isdigit(conf_loglev[0])) {
541 warningstream << "Deprecated use of debug_log_level with an "
542 "integer value; please update your configuration." << std::endl;
543 static const char *lev_name[] =
544 {"", "error", "action", "info", "verbose"};
545 int lev_i = atoi(conf_loglev.c_str());
546 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
547 warningstream << "Supplied invalid debug_log_level!"
548 " Assuming action level." << std::endl;
551 conf_loglev = lev_name[lev_i];
554 if (log_filename.empty() || conf_loglev.empty()) // No logging
557 LogLevel log_level = Logger::stringToLevel(conf_loglev);
558 if (log_level == LL_MAX) {
559 warningstream << "Supplied unrecognized debug_log_level; "
560 "using maximum." << std::endl;
563 verbosestream << "log_filename = " << log_filename << std::endl;
565 file_log_output.open(log_filename.c_str());
566 g_logger.addOutputMaxLevel(&file_log_output, log_level);
569 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
571 game_configure_port(game_params, cmd_args);
573 if (!game_configure_world(game_params, cmd_args)) {
574 errorstream << "No world path specified or found." << std::endl;
578 game_configure_subgame(game_params, cmd_args);
583 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
585 if (cmd_args.exists("port"))
586 game_params->socket_port = cmd_args.getU16("port");
588 game_params->socket_port = g_settings->getU16("port");
590 if (game_params->socket_port == 0)
591 game_params->socket_port = DEFAULT_SERVER_PORT;
594 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
596 if (get_world_from_cmdline(game_params, cmd_args))
598 if (get_world_from_config(game_params, cmd_args))
601 return auto_select_world(game_params);
604 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
606 std::string commanded_world = "";
609 std::string commanded_worldname = "";
610 if (cmd_args.exists("worldname"))
611 commanded_worldname = cmd_args.get("worldname");
613 // If a world name was specified, convert it to a path
614 if (commanded_worldname != "") {
615 // Get information about available worlds
616 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
618 for (u32 i = 0; i < worldspecs.size(); i++) {
619 std::string name = worldspecs[i].name;
620 if (name == commanded_worldname) {
621 dstream << _("Using world specified by --worldname on the "
622 "command line") << std::endl;
623 commanded_world = worldspecs[i].path;
629 dstream << _("World") << " '" << commanded_worldname
630 << _("' not available. Available worlds:") << std::endl;
631 print_worldspecs(worldspecs, dstream);
635 game_params->world_path = get_clean_world_path(commanded_world);
636 return commanded_world != "";
639 if (cmd_args.exists("world"))
640 commanded_world = cmd_args.get("world");
641 else if (cmd_args.exists("map-dir"))
642 commanded_world = cmd_args.get("map-dir");
643 else if (cmd_args.exists("nonopt0")) // First nameless argument
644 commanded_world = cmd_args.get("nonopt0");
646 game_params->world_path = get_clean_world_path(commanded_world);
647 return commanded_world != "";
650 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
653 std::string commanded_world = "";
655 if (g_settings->exists("map-dir"))
656 commanded_world = g_settings->get("map-dir");
658 game_params->world_path = get_clean_world_path(commanded_world);
660 return commanded_world != "";
663 static bool auto_select_world(GameParams *game_params)
665 // No world was specified; try to select it automatically
666 // Get information about available worlds
668 verbosestream << _("Determining world path") << std::endl;
670 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
671 std::string world_path;
673 // If there is only a single world, use it
674 if (worldspecs.size() == 1) {
675 world_path = worldspecs[0].path;
676 dstream <<_("Automatically selecting world at") << " ["
677 << world_path << "]" << std::endl;
678 // If there are multiple worlds, list them
679 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
680 std::cerr << _("Multiple worlds are available.") << std::endl;
681 std::cerr << _("Please select one using --worldname <name>"
682 " or --world <path>") << std::endl;
683 print_worldspecs(worldspecs, std::cerr);
685 // If there are no worlds, automatically create a new one
687 // This is the ultimate default world path
688 world_path = porting::path_user + DIR_DELIM + "worlds" +
690 infostream << "Creating default world at ["
691 << world_path << "]" << std::endl;
694 assert(world_path != ""); // Post-condition
695 game_params->world_path = world_path;
699 static std::string get_clean_world_path(const std::string &path)
701 const std::string worldmt = "world.mt";
702 std::string clean_path;
704 if (path.size() > worldmt.size()
705 && path.substr(path.size() - worldmt.size()) == worldmt) {
706 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
707 clean_path = path.substr(0, path.size() - worldmt.size());
715 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
719 success = get_game_from_cmdline(game_params, cmd_args);
721 success = determine_subgame(game_params);
726 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
728 SubgameSpec commanded_gamespec;
730 if (cmd_args.exists("gameid")) {
731 std::string gameid = cmd_args.get("gameid");
732 commanded_gamespec = findSubgame(gameid);
733 if (!commanded_gamespec.isValid()) {
734 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
737 dstream << _("Using game specified by --gameid on the command line")
739 game_params->game_spec = commanded_gamespec;
746 static bool determine_subgame(GameParams *game_params)
748 SubgameSpec gamespec;
750 assert(game_params->world_path != ""); // Pre-condition
752 verbosestream << _("Determining gameid/gamespec") << std::endl;
753 // If world doesn't exist
754 if (game_params->world_path != ""
755 && !getWorldExists(game_params->world_path)) {
756 // Try to take gamespec from command line
757 if (game_params->game_spec.isValid()) {
758 gamespec = game_params->game_spec;
759 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
760 } else { // Otherwise we will be using "minetest"
761 gamespec = findSubgame(g_settings->get("default_game"));
762 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
763 if (!gamespec.isValid()) {
764 errorstream << "Subgame specified in default_game ["
765 << g_settings->get("default_game")
766 << "] is invalid." << std::endl;
770 } else { // World exists
771 std::string world_gameid = getWorldGameId(game_params->world_path, false);
772 // If commanded to use a gameid, do so
773 if (game_params->game_spec.isValid()) {
774 gamespec = game_params->game_spec;
775 if (game_params->game_spec.id != world_gameid) {
776 warningstream << "Using commanded gameid ["
777 << gamespec.id << "]" << " instead of world gameid ["
778 << world_gameid << "]" << std::endl;
781 // If world contains an embedded game, use it;
782 // Otherwise find world from local system.
783 gamespec = findWorldSubgame(game_params->world_path);
784 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
788 if (!gamespec.isValid()) {
789 errorstream << "Subgame [" << gamespec.id << "] could not be found."
794 game_params->game_spec = gamespec;
799 /*****************************************************************************
801 *****************************************************************************/
802 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
804 DSTACK("Dedicated server branch");
806 verbosestream << _("Using world path") << " ["
807 << game_params.world_path << "]" << std::endl;
808 verbosestream << _("Using gameid") << " ["
809 << game_params.game_spec.id << "]" << std::endl;
812 std::string bind_str = g_settings->get("bind_address");
813 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
815 if (g_settings->getBool("ipv6_server")) {
816 bind_addr.setAddress((IPv6AddressBytes*) NULL);
819 bind_addr.Resolve(bind_str.c_str());
820 } catch (ResolveError &e) {
821 infostream << "Resolving bind address \"" << bind_str
822 << "\" failed: " << e.what()
823 << " -- Listening on all addresses." << std::endl;
825 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
826 errorstream << "Unable to listen on "
827 << bind_addr.serializeString()
828 << L" because IPv6 is disabled" << std::endl;
832 // Database migration
833 if (cmd_args.exists("migrate"))
834 return migrate_map_database(game_params, cmd_args);
835 else if (cmd_args.exists("migrate-players"))
836 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
838 if (cmd_args.exists("terminal")) {
841 std::string admin_nick = g_settings->get("name");
843 name_ok = name_ok && !admin_nick.empty();
844 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
847 if (admin_nick.empty()) {
848 errorstream << "No name given for admin. "
849 << "Please check your minetest.conf that it "
850 << "contains a 'name = ' to your main admin account."
853 errorstream << "Name for admin '"
854 << admin_nick << "' is not valid. "
855 << "Please check that it only contains allowed characters. "
856 << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
862 bool &kill = *porting::signal_handler_killstatus();
866 Server server(game_params.world_path, game_params.game_spec,
867 false, bind_addr.isIPv6(), true, &iface);
869 g_term_console.setup(&iface, &kill, admin_nick);
871 g_term_console.start();
873 server.start(bind_addr);
875 dedicated_server_loop(server, kill);
876 } catch (const ModError &e) {
877 g_term_console.stopAndWaitforThread();
878 errorstream << "ModError: " << e.what() << std::endl;
880 } catch (const ServerError &e) {
881 g_term_console.stopAndWaitforThread();
882 errorstream << "ServerError: " << e.what() << std::endl;
886 // Tell the console to stop, and wait for it to finish,
887 // only then leave context and free iface
888 g_term_console.stop();
889 g_term_console.wait();
891 g_term_console.clearKillStatus();
894 errorstream << "Cmd arg --terminal passed, but "
895 << "compiled without ncurses. Ignoring." << std::endl;
900 Server server(game_params.world_path, game_params.game_spec, false,
901 bind_addr.isIPv6(), true);
902 server.start(bind_addr);
905 bool &kill = *porting::signal_handler_killstatus();
906 dedicated_server_loop(server, kill);
908 } catch (const ModError &e) {
909 errorstream << "ModError: " << e.what() << std::endl;
911 } catch (const ServerError &e) {
912 errorstream << "ServerError: " << e.what() << std::endl;
920 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
922 std::string migrate_to = cmd_args.get("migrate");
924 std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
925 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
926 errorstream << "Cannot read world.mt!" << std::endl;
930 if (!world_mt.exists("backend")) {
931 errorstream << "Please specify your current backend in world.mt:"
933 << " backend = {sqlite3|leveldb|redis|dummy|postgresql}"
938 std::string backend = world_mt.get("backend");
939 if (backend == migrate_to) {
940 errorstream << "Cannot migrate: new backend is same"
941 << " as the old one" << std::endl;
945 MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
946 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
949 time_t last_update_time = 0;
950 bool &kill = *porting::signal_handler_killstatus();
952 std::vector<v3s16> blocks;
953 old_db->listAllLoadableBlocks(blocks);
955 for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
956 if (kill) return false;
959 old_db->loadBlock(*it, &data);
961 new_db->saveBlock(*it, data);
963 errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
965 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
966 std::cerr << " Migrated " << count << " blocks, "
967 << (100.0 * count / blocks.size()) << "% completed.\r";
970 last_update_time = time(NULL);
973 std::cerr << std::endl;
978 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
979 world_mt.set("backend", migrate_to);
980 if (!world_mt.updateConfigFile(world_mt_path.c_str()))
981 errorstream << "Failed to update world.mt!" << std::endl;
983 actionstream << "world.mt updated" << std::endl;