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 FileLogOutput file_log_output;
113 static OptionList allowed_options;
115 int main(int argc, char *argv[])
118 debug_set_exception_handler();
120 g_logger.registerThread("Main");
121 g_logger.addOutputMaxLevel(&stderr_output, LL_ACTION);
124 bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
126 || cmd_args.getFlag("help")
127 || cmd_args.exists("nonopt1")) {
128 porting::attachOrCreateConsole();
129 print_help(allowed_options);
130 return cmd_args_ok ? 0 : 1;
132 if (cmd_args.getFlag("console"))
133 porting::attachOrCreateConsole();
135 if (cmd_args.getFlag("version")) {
136 porting::attachOrCreateConsole();
141 setup_log_params(cmd_args);
143 porting::signal_handler_init();
146 porting::initAndroid();
147 porting::initializePathsAndroid();
149 porting::initializePaths();
152 if (!create_userdata_path()) {
153 errorstream << "Cannot create user data directory" << std::endl;
157 // Initialize debug stacks
158 DSTACK(FUNCTION_NAME);
161 BEGIN_DEBUG_EXCEPTION_HANDLER
163 // List gameids if requested
164 if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
169 // List worlds if requested
170 if (cmd_args.exists("world") && cmd_args.get("world") == "list") {
175 if (!init_common(cmd_args, argc, argv))
178 if (g_settings->getBool("enable_console"))
179 porting::attachOrCreateConsole();
183 if (cmd_args.getFlag("run-unittests")) {
188 GameParams game_params;
190 porting::attachOrCreateConsole();
191 game_params.is_dedicated_server = true;
193 const bool isServer = cmd_args.getFlag("server");
195 porting::attachOrCreateConsole();
196 game_params.is_dedicated_server = isServer;
199 if (!game_configure(&game_params, cmd_args))
202 sanity_check(!game_params.world_path.empty());
204 infostream << "Using commanded world path ["
205 << game_params.world_path << "]" << std::endl;
207 if (game_params.is_dedicated_server)
208 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
211 ClientLauncher launcher;
212 retval = launcher.run(game_params, cmd_args) ? 0 : 1;
217 // Update configuration file
218 if (g_settings_path != "")
219 g_settings->updateConfigFile(g_settings_path.c_str());
221 print_modified_quicktune_values();
223 // Stop httpfetch thread (if started)
226 END_DEBUG_EXCEPTION_HANDLER
232 /*****************************************************************************
234 *****************************************************************************/
237 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
239 set_allowed_options(&allowed_options);
241 return cmd_args->parseCommandLine(argc, argv, allowed_options);
244 static void set_allowed_options(OptionList *allowed_options)
246 allowed_options->clear();
248 allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
249 _("Show allowed options"))));
250 allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
251 _("Show version information"))));
252 allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
253 _("Load configuration from specified file"))));
254 allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
255 _("Set network port (UDP)"))));
256 allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
257 _("Run the unit tests and exit"))));
258 allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
259 _("Same as --world (deprecated)"))));
260 allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
261 _("Set world path (implies local game) ('list' lists all)"))));
262 allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
263 _("Set world by name (implies local game)"))));
264 allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
265 _("Print to console errors only"))));
266 allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
267 _("Print more information to console"))));
268 allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
269 _("Print even more information to console"))));
270 allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
271 _("Print enormous amounts of information to log and console"))));
272 allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
273 _("Set logfile path ('' = no logging)"))));
274 allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
275 _("Set gameid (\"--gameid list\" prints available ones)"))));
276 allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
277 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
278 allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING,
279 _("Migrate from current players backend to another (Only works when using minetestserver or with --server)"))));
280 allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
281 _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
283 allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
284 _("Show available video modes"))));
285 allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
286 _("Run speed tests"))));
287 allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
288 _("Address to connect to. ('' = local game)"))));
289 allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
290 _("Enable random user input, for testing"))));
291 allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
292 _("Run dedicated server"))));
293 allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
294 _("Set player name"))));
295 allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
296 _("Set password"))));
297 allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
298 _("Disable main menu"))));
299 allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
300 _("Starts with the console (Windows only)"))));
305 static void print_help(const OptionList &allowed_options)
307 std::cout << _("Allowed options:") << std::endl;
308 print_allowed_options(allowed_options);
311 static void print_allowed_options(const OptionList &allowed_options)
313 for (OptionList::const_iterator i = allowed_options.begin();
314 i != allowed_options.end(); ++i) {
315 std::ostringstream os1(std::ios::binary);
316 os1 << " --" << i->first;
317 if (i->second.type != VALUETYPE_FLAG)
318 os1 << _(" <value>");
320 std::cout << padStringRight(os1.str(), 30);
322 if (i->second.help != NULL)
323 std::cout << i->second.help;
325 std::cout << std::endl;
329 static void print_version()
331 std::cout << PROJECT_NAME_C " " << g_version_hash
332 << " (" << porting::getPlatformName() << ")" << std::endl;
334 std::cout << "Using Irrlicht " << IRRLICHT_SDK_VERSION << std::endl;
336 std::cout << "Build info: " << g_build_info << std::endl;
339 static void list_game_ids()
341 std::set<std::string> gameids = getAvailableGameIds();
342 for (std::set<std::string>::const_iterator i = gameids.begin();
343 i != gameids.end(); ++i)
344 std::cout << (*i) <<std::endl;
347 static void list_worlds()
349 std::cout << _("Available worlds:") << std::endl;
350 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
351 print_worldspecs(worldspecs, std::cout);
354 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
357 for (size_t i = 0; i < worldspecs.size(); i++) {
358 std::string name = worldspecs[i].name;
359 std::string path = worldspecs[i].path;
360 if (name.find(" ") != std::string::npos)
361 name = std::string("'") + name + "'";
362 path = std::string("'") + path + "'";
363 name = padStringRight(name, 14);
364 os << " " << name << " " << path << std::endl;
368 static void print_modified_quicktune_values()
370 bool header_printed = false;
371 std::vector<std::string> names = getQuicktuneNames();
373 for (u32 i = 0; i < names.size(); i++) {
374 QuicktuneValue val = getQuicktuneValue(names[i]);
377 if (!header_printed) {
378 dstream << "Modified quicktune values:" << std::endl;
379 header_printed = true;
381 dstream << names[i] << " = " << val.getString() << std::endl;
385 static void setup_log_params(const Settings &cmd_args)
387 // Quiet mode, print errors only
388 if (cmd_args.getFlag("quiet")) {
389 g_logger.removeOutput(&stderr_output);
390 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
393 // If trace is enabled, enable logging of certain things
394 if (cmd_args.getFlag("trace")) {
395 dstream << _("Enabling trace level debug output") << std::endl;
396 g_logger.setTraceEnabled(true);
397 dout_con_ptr = &verbosestream; // This is somewhat old
398 socket_enable_debug_output = true; // Sockets doesn't use log.h
401 // In certain cases, output info level on stderr
402 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
403 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
404 g_logger.addOutput(&stderr_output, LL_INFO);
406 // In certain cases, output verbose level on stderr
407 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
408 g_logger.addOutput(&stderr_output, LL_VERBOSE);
411 static bool create_userdata_path()
416 if (!fs::PathExists(porting::path_user)) {
417 success = fs::CreateDir(porting::path_user);
421 porting::copyAssets();
423 // Create user data directory
424 success = fs::CreateDir(porting::path_user);
430 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
433 set_default_settings(g_settings);
435 // Initialize sockets
437 atexit(sockets_cleanup);
439 if (!read_config_file(cmd_args))
442 init_log_streams(cmd_args);
444 // Initialize random seed
448 // Initialize HTTP fetcher
449 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
451 init_gettext(porting::path_locale.c_str(),
452 g_settings->get("language"), argc, argv);
457 static void startup_message()
459 infostream << PROJECT_NAME << " " << _("with")
460 << " SER_FMT_VER_HIGHEST_READ="
461 << (int)SER_FMT_VER_HIGHEST_READ << ", "
462 << g_build_info << std::endl;
465 static bool read_config_file(const Settings &cmd_args)
467 // Path of configuration file in use
468 sanity_check(g_settings_path == ""); // Sanity check
470 if (cmd_args.exists("config")) {
471 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
473 errorstream << "Could not read configuration from \""
474 << cmd_args.get("config") << "\"" << std::endl;
477 g_settings_path = cmd_args.get("config");
479 std::vector<std::string> filenames;
480 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
481 // Legacy configuration file location
482 filenames.push_back(porting::path_user +
483 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
486 // Try also from a lower level (to aid having the same configuration
487 // for many RUN_IN_PLACE installs)
488 filenames.push_back(porting::path_user +
489 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
492 for (size_t i = 0; i < filenames.size(); i++) {
493 bool r = g_settings->readConfigFile(filenames[i].c_str());
495 g_settings_path = filenames[i];
500 // If no path found, use the first one (menu creates the file)
501 if (g_settings_path == "")
502 g_settings_path = filenames[0];
508 static void init_log_streams(const Settings &cmd_args)
511 std::string log_filename = DEBUGFILE;
513 std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
515 if (cmd_args.exists("logfile"))
516 log_filename = cmd_args.get("logfile");
518 g_logger.removeOutput(&file_log_output);
519 std::string conf_loglev = g_settings->get("debug_log_level");
521 // Old integer format
522 if (std::isdigit(conf_loglev[0])) {
523 warningstream << "Deprecated use of debug_log_level with an "
524 "integer value; please update your configuration." << std::endl;
525 static const char *lev_name[] =
526 {"", "error", "action", "info", "verbose"};
527 int lev_i = atoi(conf_loglev.c_str());
528 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
529 warningstream << "Supplied invalid debug_log_level!"
530 " Assuming action level." << std::endl;
533 conf_loglev = lev_name[lev_i];
536 if (log_filename.empty() || conf_loglev.empty()) // No logging
539 LogLevel log_level = Logger::stringToLevel(conf_loglev);
540 if (log_level == LL_MAX) {
541 warningstream << "Supplied unrecognized debug_log_level; "
542 "using maximum." << std::endl;
545 verbosestream << "log_filename = " << log_filename << std::endl;
547 file_log_output.open(log_filename.c_str());
548 g_logger.addOutputMaxLevel(&file_log_output, log_level);
551 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
553 game_configure_port(game_params, cmd_args);
555 if (!game_configure_world(game_params, cmd_args)) {
556 errorstream << "No world path specified or found." << std::endl;
560 game_configure_subgame(game_params, cmd_args);
565 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
567 if (cmd_args.exists("port"))
568 game_params->socket_port = cmd_args.getU16("port");
570 game_params->socket_port = g_settings->getU16("port");
572 if (game_params->socket_port == 0)
573 game_params->socket_port = DEFAULT_SERVER_PORT;
576 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
578 if (get_world_from_cmdline(game_params, cmd_args))
580 if (get_world_from_config(game_params, cmd_args))
583 return auto_select_world(game_params);
586 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
588 std::string commanded_world = "";
591 std::string commanded_worldname = "";
592 if (cmd_args.exists("worldname"))
593 commanded_worldname = cmd_args.get("worldname");
595 // If a world name was specified, convert it to a path
596 if (commanded_worldname != "") {
597 // Get information about available worlds
598 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
600 for (u32 i = 0; i < worldspecs.size(); i++) {
601 std::string name = worldspecs[i].name;
602 if (name == commanded_worldname) {
603 dstream << _("Using world specified by --worldname on the "
604 "command line") << std::endl;
605 commanded_world = worldspecs[i].path;
611 dstream << _("World") << " '" << commanded_worldname
612 << _("' not available. Available worlds:") << std::endl;
613 print_worldspecs(worldspecs, dstream);
617 game_params->world_path = get_clean_world_path(commanded_world);
618 return commanded_world != "";
621 if (cmd_args.exists("world"))
622 commanded_world = cmd_args.get("world");
623 else if (cmd_args.exists("map-dir"))
624 commanded_world = cmd_args.get("map-dir");
625 else if (cmd_args.exists("nonopt0")) // First nameless argument
626 commanded_world = cmd_args.get("nonopt0");
628 game_params->world_path = get_clean_world_path(commanded_world);
629 return commanded_world != "";
632 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
635 std::string commanded_world = "";
637 if (g_settings->exists("map-dir"))
638 commanded_world = g_settings->get("map-dir");
640 game_params->world_path = get_clean_world_path(commanded_world);
642 return commanded_world != "";
645 static bool auto_select_world(GameParams *game_params)
647 // No world was specified; try to select it automatically
648 // Get information about available worlds
650 verbosestream << _("Determining world path") << std::endl;
652 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
653 std::string world_path;
655 // If there is only a single world, use it
656 if (worldspecs.size() == 1) {
657 world_path = worldspecs[0].path;
658 dstream <<_("Automatically selecting world at") << " ["
659 << world_path << "]" << std::endl;
660 // If there are multiple worlds, list them
661 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
662 std::cerr << _("Multiple worlds are available.") << std::endl;
663 std::cerr << _("Please select one using --worldname <name>"
664 " or --world <path>") << std::endl;
665 print_worldspecs(worldspecs, std::cerr);
667 // If there are no worlds, automatically create a new one
669 // This is the ultimate default world path
670 world_path = porting::path_user + DIR_DELIM + "worlds" +
672 infostream << "Creating default world at ["
673 << world_path << "]" << std::endl;
676 assert(world_path != ""); // Post-condition
677 game_params->world_path = world_path;
681 static std::string get_clean_world_path(const std::string &path)
683 const std::string worldmt = "world.mt";
684 std::string clean_path;
686 if (path.size() > worldmt.size()
687 && path.substr(path.size() - worldmt.size()) == worldmt) {
688 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
689 clean_path = path.substr(0, path.size() - worldmt.size());
697 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
701 success = get_game_from_cmdline(game_params, cmd_args);
703 success = determine_subgame(game_params);
708 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
710 SubgameSpec commanded_gamespec;
712 if (cmd_args.exists("gameid")) {
713 std::string gameid = cmd_args.get("gameid");
714 commanded_gamespec = findSubgame(gameid);
715 if (!commanded_gamespec.isValid()) {
716 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
719 dstream << _("Using game specified by --gameid on the command line")
721 game_params->game_spec = commanded_gamespec;
728 static bool determine_subgame(GameParams *game_params)
730 SubgameSpec gamespec;
732 assert(game_params->world_path != ""); // Pre-condition
734 verbosestream << _("Determining gameid/gamespec") << std::endl;
735 // If world doesn't exist
736 if (game_params->world_path != ""
737 && !getWorldExists(game_params->world_path)) {
738 // Try to take gamespec from command line
739 if (game_params->game_spec.isValid()) {
740 gamespec = game_params->game_spec;
741 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
742 } else { // Otherwise we will be using "minetest"
743 gamespec = findSubgame(g_settings->get("default_game"));
744 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
745 if (!gamespec.isValid()) {
746 errorstream << "Subgame specified in default_game ["
747 << g_settings->get("default_game")
748 << "] is invalid." << std::endl;
752 } else { // World exists
753 std::string world_gameid = getWorldGameId(game_params->world_path, false);
754 // If commanded to use a gameid, do so
755 if (game_params->game_spec.isValid()) {
756 gamespec = game_params->game_spec;
757 if (game_params->game_spec.id != world_gameid) {
758 warningstream << "Using commanded gameid ["
759 << gamespec.id << "]" << " instead of world gameid ["
760 << world_gameid << "]" << std::endl;
763 // If world contains an embedded game, use it;
764 // Otherwise find world from local system.
765 gamespec = findWorldSubgame(game_params->world_path);
766 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
770 if (!gamespec.isValid()) {
771 errorstream << "Subgame [" << gamespec.id << "] could not be found."
776 game_params->game_spec = gamespec;
781 /*****************************************************************************
783 *****************************************************************************/
784 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
786 DSTACK("Dedicated server branch");
788 verbosestream << _("Using world path") << " ["
789 << game_params.world_path << "]" << std::endl;
790 verbosestream << _("Using gameid") << " ["
791 << game_params.game_spec.id << "]" << std::endl;
794 std::string bind_str = g_settings->get("bind_address");
795 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
797 if (g_settings->getBool("ipv6_server")) {
798 bind_addr.setAddress((IPv6AddressBytes*) NULL);
801 bind_addr.Resolve(bind_str.c_str());
802 } catch (ResolveError &e) {
803 infostream << "Resolving bind address \"" << bind_str
804 << "\" failed: " << e.what()
805 << " -- Listening on all addresses." << std::endl;
807 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
808 errorstream << "Unable to listen on "
809 << bind_addr.serializeString()
810 << L" because IPv6 is disabled" << std::endl;
814 // Database migration
815 if (cmd_args.exists("migrate"))
816 return migrate_map_database(game_params, cmd_args);
817 else if (cmd_args.exists("migrate-players"))
818 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
820 if (cmd_args.exists("terminal")) {
823 std::string admin_nick = g_settings->get("name");
825 name_ok = name_ok && !admin_nick.empty();
826 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
829 if (admin_nick.empty()) {
830 errorstream << "No name given for admin. "
831 << "Please check your minetest.conf that it "
832 << "contains a 'name = ' to your main admin account."
835 errorstream << "Name for admin '"
836 << admin_nick << "' is not valid. "
837 << "Please check that it only contains allowed characters. "
838 << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
844 bool &kill = *porting::signal_handler_killstatus();
848 Server server(game_params.world_path, game_params.game_spec,
849 false, bind_addr.isIPv6(), true, &iface);
851 g_term_console.setup(&iface, &kill, admin_nick);
853 g_term_console.start();
855 server.start(bind_addr);
857 dedicated_server_loop(server, kill);
858 } catch (const ModError &e) {
859 g_term_console.stopAndWaitforThread();
860 errorstream << "ModError: " << e.what() << std::endl;
862 } catch (const ServerError &e) {
863 g_term_console.stopAndWaitforThread();
864 errorstream << "ServerError: " << e.what() << std::endl;
868 // Tell the console to stop, and wait for it to finish,
869 // only then leave context and free iface
870 g_term_console.stop();
871 g_term_console.wait();
873 g_term_console.clearKillStatus();
876 errorstream << "Cmd arg --terminal passed, but "
877 << "compiled without ncurses. Ignoring." << std::endl;
882 Server server(game_params.world_path, game_params.game_spec, false,
883 bind_addr.isIPv6(), true);
884 server.start(bind_addr);
887 bool &kill = *porting::signal_handler_killstatus();
888 dedicated_server_loop(server, kill);
890 } catch (const ModError &e) {
891 errorstream << "ModError: " << e.what() << std::endl;
893 } catch (const ServerError &e) {
894 errorstream << "ServerError: " << e.what() << std::endl;
902 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
904 std::string migrate_to = cmd_args.get("migrate");
906 std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
907 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
908 errorstream << "Cannot read world.mt!" << std::endl;
912 if (!world_mt.exists("backend")) {
913 errorstream << "Please specify your current backend in world.mt:"
915 << " backend = {sqlite3|leveldb|redis|dummy|postgresql}"
920 std::string backend = world_mt.get("backend");
921 if (backend == migrate_to) {
922 errorstream << "Cannot migrate: new backend is same"
923 << " as the old one" << std::endl;
927 MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
928 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
931 time_t last_update_time = 0;
932 bool &kill = *porting::signal_handler_killstatus();
934 std::vector<v3s16> blocks;
935 old_db->listAllLoadableBlocks(blocks);
937 for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
938 if (kill) return false;
941 old_db->loadBlock(*it, &data);
943 new_db->saveBlock(*it, data);
945 errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
947 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
948 std::cerr << " Migrated " << count << " blocks, "
949 << (100.0 * count / blocks.size()) << "% completed.\r";
952 last_update_time = time(NULL);
955 std::cerr << std::endl;
960 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
961 world_mt.set("backend", migrate_to);
962 if (!world_mt.updateConfigFile(world_mt_path.c_str()))
963 errorstream << "Failed to update world.mt!" << std::endl;
965 actionstream << "world.mt updated" << std::endl;