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"
42 #include "terminal_chat_console.h"
45 #include "gui/guiMainMenu.h"
46 #include "client/clientlauncher.h"
47 #include "gui/guiEngine.h"
48 #include "gui/mainmenumanager.h"
50 #ifdef HAVE_TOUCHSCREENGUI
51 #include "gui/touchscreengui.h"
54 // for version information only
63 #if !defined(SERVER) && \
64 (IRRLICHT_VERSION_MAJOR == 1) && \
65 (IRRLICHT_VERSION_MINOR == 8) && \
66 (IRRLICHT_VERSION_REVISION == 2)
67 #error "Irrlicht 1.8.2 is known to be broken - please update Irrlicht to version >= 1.8.3"
70 #define DEBUGFILE "debug.txt"
71 #define DEFAULT_SERVER_PORT 30000
73 typedef std::map<std::string, ValueSpec> OptionList;
75 /**********************************************************************
77 **********************************************************************/
79 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
80 static void set_allowed_options(OptionList *allowed_options);
82 static void print_help(const OptionList &allowed_options);
83 static void print_allowed_options(const OptionList &allowed_options);
84 static void print_version();
85 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
86 std::ostream &os, bool print_name = true, bool print_path = true);
87 static void print_modified_quicktune_values();
89 static void list_game_ids();
90 static void list_worlds(bool print_name, bool print_path);
91 static bool setup_log_params(const Settings &cmd_args);
92 static bool create_userdata_path();
93 static bool init_common(const Settings &cmd_args, int argc, char *argv[]);
94 static void startup_message();
95 static bool read_config_file(const Settings &cmd_args);
96 static void init_log_streams(const Settings &cmd_args);
98 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
99 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
101 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
102 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
103 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
104 static bool auto_select_world(GameParams *game_params);
105 static std::string get_clean_world_path(const std::string &path);
107 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
108 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
109 static bool determine_subgame(GameParams *game_params);
111 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
112 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args);
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."
208 GameStartData game_params;
210 porting::attachOrCreateConsole();
211 game_params.is_dedicated_server = true;
213 const bool isServer = cmd_args.getFlag("server");
215 porting::attachOrCreateConsole();
216 game_params.is_dedicated_server = isServer;
219 if (!game_configure(&game_params, cmd_args))
222 sanity_check(!game_params.world_path.empty());
224 if (game_params.is_dedicated_server)
225 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
228 ClientLauncher launcher;
229 retval = launcher.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 // Stop httpfetch thread (if started)
243 END_DEBUG_EXCEPTION_HANDLER
249 /*****************************************************************************
251 *****************************************************************************/
254 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
256 set_allowed_options(&allowed_options);
258 return cmd_args->parseCommandLine(argc, argv, allowed_options);
261 static void set_allowed_options(OptionList *allowed_options)
263 allowed_options->clear();
265 allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
266 _("Show allowed options"))));
267 allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
268 _("Show version information"))));
269 allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
270 _("Load configuration from specified file"))));
271 allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
272 _("Set network port (UDP)"))));
273 allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
274 _("Run the unit tests and exit"))));
275 allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
276 _("Same as --world (deprecated)"))));
277 allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
278 _("Set world path (implies local game if used with option --go)"))));
279 allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
280 _("Set world by name (implies local game if used with option --go)"))));
281 allowed_options->insert(std::make_pair("worldlist", ValueSpec(VALUETYPE_STRING,
282 _("Get list of worlds ('path' lists paths, "
283 "'name' lists names, 'both' lists both)"))));
284 allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
285 _("Print to console errors only"))));
286 allowed_options->insert(std::make_pair("color", ValueSpec(VALUETYPE_STRING,
287 _("Coloured logs ('always', 'never' or 'auto'), defaults to 'auto'"
289 allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
290 _("Print more information to console"))));
291 allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
292 _("Print even more information to console"))));
293 allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
294 _("Print enormous amounts of information to log and console"))));
295 allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
296 _("Set logfile path ('' = no logging)"))));
297 allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
298 _("Set gameid (\"--gameid list\" prints available ones)"))));
299 allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
300 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
301 allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING,
302 _("Migrate from current players backend to another (Only works when using minetestserver or with --server)"))));
303 allowed_options->insert(std::make_pair("migrate-auth", ValueSpec(VALUETYPE_STRING,
304 _("Migrate from current auth backend to another (Only works when using minetestserver or with --server)"))));
305 allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
306 _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
308 allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
309 _("Show available video modes"))));
310 allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
311 _("Run speed tests"))));
312 allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
313 _("Address to connect to. ('' = local game)"))));
314 allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
315 _("Enable random user input, for testing"))));
316 allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
317 _("Run dedicated server"))));
318 allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
319 _("Set player name"))));
320 allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
321 _("Set password"))));
322 allowed_options->insert(std::make_pair("password-file", ValueSpec(VALUETYPE_STRING,
323 _("Set password from contents of file"))));
324 allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
325 _("Disable main menu"))));
326 allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
327 _("Starts with the console (Windows only)"))));
332 static void print_help(const OptionList &allowed_options)
334 std::cout << _("Allowed options:") << std::endl;
335 print_allowed_options(allowed_options);
338 static void print_allowed_options(const OptionList &allowed_options)
340 for (const auto &allowed_option : allowed_options) {
341 std::ostringstream os1(std::ios::binary);
342 os1 << " --" << allowed_option.first;
343 if (allowed_option.second.type != VALUETYPE_FLAG)
344 os1 << _(" <value>");
346 std::cout << padStringRight(os1.str(), 30);
348 if (allowed_option.second.help)
349 std::cout << allowed_option.second.help;
351 std::cout << std::endl;
355 static void print_version()
357 std::cout << PROJECT_NAME_C " " << g_version_hash
358 << " (" << porting::getPlatformName() << ")" << std::endl;
360 std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl;
363 std::cout << "Using " << LUAJIT_VERSION << std::endl;
365 std::cout << "Using " << LUA_RELEASE << std::endl;
367 std::cout << g_build_info << std::endl;
370 static void list_game_ids()
372 std::set<std::string> gameids = getAvailableGameIds();
373 for (const std::string &gameid : gameids)
374 std::cout << gameid <<std::endl;
377 static void list_worlds(bool print_name, bool print_path)
379 std::cout << _("Available worlds:") << std::endl;
380 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
381 print_worldspecs(worldspecs, std::cout, print_name, print_path);
384 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
385 std::ostream &os, bool print_name, bool print_path)
387 for (const WorldSpec &worldspec : worldspecs) {
388 std::string name = worldspec.name;
389 std::string path = worldspec.path;
390 if (print_name && print_path) {
391 os << "\t" << name << "\t\t" << path << std::endl;
392 } else if (print_name) {
393 os << "\t" << name << std::endl;
394 } else if (print_path) {
395 os << "\t" << path << std::endl;
400 static void print_modified_quicktune_values()
402 bool header_printed = false;
403 std::vector<std::string> names = getQuicktuneNames();
405 for (const std::string &name : names) {
406 QuicktuneValue val = getQuicktuneValue(name);
409 if (!header_printed) {
410 dstream << "Modified quicktune values:" << std::endl;
411 header_printed = true;
413 dstream << name << " = " << val.getString() << std::endl;
417 static bool setup_log_params(const Settings &cmd_args)
419 // Quiet mode, print errors only
420 if (cmd_args.getFlag("quiet")) {
421 g_logger.removeOutput(&stderr_output);
422 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
425 // Coloured log messages (see log.h)
426 std::string color_mode;
427 if (cmd_args.exists("color")) {
428 color_mode = cmd_args.get("color");
431 char *color_mode_env = getenv("MT_LOGCOLOR");
433 color_mode = color_mode_env;
436 if (color_mode != "") {
437 if (color_mode == "auto") {
438 Logger::color_mode = LOG_COLOR_AUTO;
439 } else if (color_mode == "always") {
440 Logger::color_mode = LOG_COLOR_ALWAYS;
441 } else if (color_mode == "never") {
442 Logger::color_mode = LOG_COLOR_NEVER;
444 errorstream << "Invalid color mode: " << color_mode << std::endl;
449 // If trace is enabled, enable logging of certain things
450 if (cmd_args.getFlag("trace")) {
451 dstream << _("Enabling trace level debug output") << std::endl;
452 g_logger.setTraceEnabled(true);
453 dout_con_ptr = &verbosestream; // This is somewhat old
454 socket_enable_debug_output = true; // Sockets doesn't use log.h
457 // In certain cases, output info level on stderr
458 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
459 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
460 g_logger.addOutput(&stderr_output, LL_INFO);
462 // In certain cases, output verbose level on stderr
463 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
464 g_logger.addOutput(&stderr_output, LL_VERBOSE);
469 static bool create_userdata_path()
474 if (!fs::PathExists(porting::path_user)) {
475 success = fs::CreateDir(porting::path_user);
480 // Create user data directory
481 success = fs::CreateDir(porting::path_user);
487 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
490 set_default_settings(g_settings);
492 // Initialize sockets
494 atexit(sockets_cleanup);
496 if (!read_config_file(cmd_args))
499 init_log_streams(cmd_args);
501 // Initialize random seed
505 // Initialize HTTP fetcher
506 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
508 init_gettext(porting::path_locale.c_str(),
509 g_settings->get("language"), argc, argv);
514 static void startup_message()
516 infostream << PROJECT_NAME << " " << _("with")
517 << " SER_FMT_VER_HIGHEST_READ="
518 << (int)SER_FMT_VER_HIGHEST_READ << ", "
519 << g_build_info << std::endl;
522 static bool read_config_file(const Settings &cmd_args)
524 // Path of configuration file in use
525 sanity_check(g_settings_path == ""); // Sanity check
527 if (cmd_args.exists("config")) {
528 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
530 errorstream << "Could not read configuration from \""
531 << cmd_args.get("config") << "\"" << std::endl;
534 g_settings_path = cmd_args.get("config");
536 std::vector<std::string> filenames;
537 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
538 // Legacy configuration file location
539 filenames.push_back(porting::path_user +
540 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
543 // Try also from a lower level (to aid having the same configuration
544 // for many RUN_IN_PLACE installs)
545 filenames.push_back(porting::path_user +
546 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
549 for (const std::string &filename : filenames) {
550 bool r = g_settings->readConfigFile(filename.c_str());
552 g_settings_path = filename;
557 // If no path found, use the first one (menu creates the file)
558 if (g_settings_path.empty())
559 g_settings_path = filenames[0];
565 static void init_log_streams(const Settings &cmd_args)
567 std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
569 if (cmd_args.exists("logfile"))
570 log_filename = cmd_args.get("logfile");
572 g_logger.removeOutput(&file_log_output);
573 std::string conf_loglev = g_settings->get("debug_log_level");
575 // Old integer format
576 if (std::isdigit(conf_loglev[0])) {
577 warningstream << "Deprecated use of debug_log_level with an "
578 "integer value; please update your configuration." << std::endl;
579 static const char *lev_name[] =
580 {"", "error", "action", "info", "verbose"};
581 int lev_i = atoi(conf_loglev.c_str());
582 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
583 warningstream << "Supplied invalid debug_log_level!"
584 " Assuming action level." << std::endl;
587 conf_loglev = lev_name[lev_i];
590 if (log_filename.empty() || conf_loglev.empty()) // No logging
593 LogLevel log_level = Logger::stringToLevel(conf_loglev);
594 if (log_level == LL_MAX) {
595 warningstream << "Supplied unrecognized debug_log_level; "
596 "using maximum." << std::endl;
599 file_log_output.setFile(log_filename,
600 g_settings->getU64("debug_log_size_max") * 1000000);
601 g_logger.addOutputMaxLevel(&file_log_output, log_level);
604 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
606 game_configure_port(game_params, cmd_args);
608 if (!game_configure_world(game_params, cmd_args)) {
609 errorstream << "No world path specified or found." << std::endl;
613 game_configure_subgame(game_params, cmd_args);
618 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
620 if (cmd_args.exists("port")) {
621 game_params->socket_port = cmd_args.getU16("port");
623 if (game_params->is_dedicated_server)
624 game_params->socket_port = g_settings->getU16("port");
626 game_params->socket_port = g_settings->getU16("remote_port");
629 if (game_params->socket_port == 0)
630 game_params->socket_port = DEFAULT_SERVER_PORT;
633 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
635 if (get_world_from_cmdline(game_params, cmd_args))
638 if (get_world_from_config(game_params, cmd_args))
641 return auto_select_world(game_params);
644 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
646 std::string commanded_world;
649 std::string commanded_worldname;
650 if (cmd_args.exists("worldname"))
651 commanded_worldname = cmd_args.get("worldname");
653 // If a world name was specified, convert it to a path
654 if (!commanded_worldname.empty()) {
655 // Get information about available worlds
656 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
658 for (const WorldSpec &worldspec : worldspecs) {
659 std::string name = worldspec.name;
660 if (name == commanded_worldname) {
661 dstream << _("Using world specified by --worldname on the "
662 "command line") << std::endl;
663 commanded_world = worldspec.path;
669 dstream << _("World") << " '" << commanded_worldname
670 << _("' not available. Available worlds:") << std::endl;
671 print_worldspecs(worldspecs, dstream);
675 game_params->world_path = get_clean_world_path(commanded_world);
676 return !commanded_world.empty();
679 if (cmd_args.exists("world"))
680 commanded_world = cmd_args.get("world");
681 else if (cmd_args.exists("map-dir"))
682 commanded_world = cmd_args.get("map-dir");
683 else if (cmd_args.exists("nonopt0")) // First nameless argument
684 commanded_world = cmd_args.get("nonopt0");
686 game_params->world_path = get_clean_world_path(commanded_world);
687 return !commanded_world.empty();
690 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
693 std::string commanded_world;
695 if (g_settings->exists("map-dir"))
696 commanded_world = g_settings->get("map-dir");
698 game_params->world_path = get_clean_world_path(commanded_world);
700 return !commanded_world.empty();
703 static bool auto_select_world(GameParams *game_params)
705 // No world was specified; try to select it automatically
706 // Get information about available worlds
708 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
709 std::string world_path;
711 // If there is only a single world, use it
712 if (worldspecs.size() == 1) {
713 world_path = worldspecs[0].path;
714 dstream <<_("Automatically selecting world at") << " ["
715 << world_path << "]" << std::endl;
716 // If there are multiple worlds, list them
717 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
718 std::cerr << _("Multiple worlds are available.") << std::endl;
719 std::cerr << _("Please select one using --worldname <name>"
720 " or --world <path>") << std::endl;
721 print_worldspecs(worldspecs, std::cerr);
723 // If there are no worlds, automatically create a new one
725 // This is the ultimate default world path
726 world_path = porting::path_user + DIR_DELIM + "worlds" +
728 infostream << "Using default world at ["
729 << world_path << "]" << std::endl;
732 assert(world_path != ""); // Post-condition
733 game_params->world_path = world_path;
737 static std::string get_clean_world_path(const std::string &path)
739 const std::string worldmt = "world.mt";
740 std::string clean_path;
742 if (path.size() > worldmt.size()
743 && path.substr(path.size() - worldmt.size()) == worldmt) {
744 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
745 clean_path = path.substr(0, path.size() - worldmt.size());
753 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
757 success = get_game_from_cmdline(game_params, cmd_args);
759 success = determine_subgame(game_params);
764 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
766 SubgameSpec commanded_gamespec;
768 if (cmd_args.exists("gameid")) {
769 std::string gameid = cmd_args.get("gameid");
770 commanded_gamespec = findSubgame(gameid);
771 if (!commanded_gamespec.isValid()) {
772 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
775 dstream << _("Using game specified by --gameid on the command line")
777 game_params->game_spec = commanded_gamespec;
784 static bool determine_subgame(GameParams *game_params)
786 SubgameSpec gamespec;
788 assert(game_params->world_path != ""); // Pre-condition
790 // If world doesn't exist
791 if (!game_params->world_path.empty()
792 && !getWorldExists(game_params->world_path)) {
793 // Try to take gamespec from command line
794 if (game_params->game_spec.isValid()) {
795 gamespec = game_params->game_spec;
796 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
797 } else { // Otherwise we will be using "minetest"
798 gamespec = findSubgame(g_settings->get("default_game"));
799 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
800 if (!gamespec.isValid()) {
801 errorstream << "Game specified in default_game ["
802 << g_settings->get("default_game")
803 << "] is invalid." << std::endl;
807 } else { // World exists
808 std::string world_gameid = getWorldGameId(game_params->world_path, false);
809 // If commanded to use a gameid, do so
810 if (game_params->game_spec.isValid()) {
811 gamespec = game_params->game_spec;
812 if (game_params->game_spec.id != world_gameid) {
813 warningstream << "Using commanded gameid ["
814 << gamespec.id << "]" << " instead of world gameid ["
815 << world_gameid << "]" << std::endl;
818 // If world contains an embedded game, use it;
819 // Otherwise find world from local system.
820 gamespec = findWorldSubgame(game_params->world_path);
821 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
825 if (!gamespec.isValid()) {
826 errorstream << "Game [" << gamespec.id << "] could not be found."
831 game_params->game_spec = gamespec;
836 /*****************************************************************************
838 *****************************************************************************/
839 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
841 verbosestream << _("Using world path") << " ["
842 << game_params.world_path << "]" << std::endl;
843 verbosestream << _("Using gameid") << " ["
844 << game_params.game_spec.id << "]" << std::endl;
847 std::string bind_str = g_settings->get("bind_address");
848 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
850 if (g_settings->getBool("ipv6_server")) {
851 bind_addr.setAddress((IPv6AddressBytes*) NULL);
854 bind_addr.Resolve(bind_str.c_str());
855 } catch (ResolveError &e) {
856 infostream << "Resolving bind address \"" << bind_str
857 << "\" failed: " << e.what()
858 << " -- Listening on all addresses." << std::endl;
860 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
861 errorstream << "Unable to listen on "
862 << bind_addr.serializeString()
863 << L" because IPv6 is disabled" << std::endl;
867 // Database migration
868 if (cmd_args.exists("migrate"))
869 return migrate_map_database(game_params, cmd_args);
871 if (cmd_args.exists("migrate-players"))
872 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
874 if (cmd_args.exists("migrate-auth"))
875 return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);
877 if (cmd_args.exists("terminal")) {
880 std::string admin_nick = g_settings->get("name");
882 name_ok = name_ok && !admin_nick.empty();
883 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
886 if (admin_nick.empty()) {
887 errorstream << "No name given for admin. "
888 << "Please check your minetest.conf that it "
889 << "contains a 'name = ' to your main admin account."
892 errorstream << "Name for admin '"
893 << admin_nick << "' is not valid. "
894 << "Please check that it only contains allowed characters. "
895 << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
901 bool &kill = *porting::signal_handler_killstatus();
905 Server server(game_params.world_path, game_params.game_spec,
906 false, bind_addr, true, &iface);
908 g_term_console.setup(&iface, &kill, admin_nick);
910 g_term_console.start();
914 dedicated_server_loop(server, kill);
915 } catch (const ModError &e) {
916 g_term_console.stopAndWaitforThread();
917 errorstream << "ModError: " << e.what() << std::endl;
919 } catch (const ServerError &e) {
920 g_term_console.stopAndWaitforThread();
921 errorstream << "ServerError: " << e.what() << std::endl;
925 // Tell the console to stop, and wait for it to finish,
926 // only then leave context and free iface
927 g_term_console.stop();
928 g_term_console.wait();
930 g_term_console.clearKillStatus();
933 errorstream << "Cmd arg --terminal passed, but "
934 << "compiled without ncurses. Ignoring." << std::endl;
939 Server server(game_params.world_path, game_params.game_spec, false,
944 bool &kill = *porting::signal_handler_killstatus();
945 dedicated_server_loop(server, kill);
947 } catch (const ModError &e) {
948 errorstream << "ModError: " << e.what() << std::endl;
950 } catch (const ServerError &e) {
951 errorstream << "ServerError: " << e.what() << std::endl;
959 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
961 std::string migrate_to = cmd_args.get("migrate");
963 std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
964 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
965 errorstream << "Cannot read world.mt!" << std::endl;
969 if (!world_mt.exists("backend")) {
970 errorstream << "Please specify your current backend in world.mt:"
972 << " backend = {sqlite3|leveldb|redis|dummy|postgresql}"
977 std::string backend = world_mt.get("backend");
978 if (backend == migrate_to) {
979 errorstream << "Cannot migrate: new backend is same"
980 << " as the old one" << std::endl;
984 MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
985 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
988 time_t last_update_time = 0;
989 bool &kill = *porting::signal_handler_killstatus();
991 std::vector<v3s16> blocks;
992 old_db->listAllLoadableBlocks(blocks);
994 for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
995 if (kill) return false;
998 old_db->loadBlock(*it, &data);
1000 new_db->saveBlock(*it, data);
1002 errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
1004 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
1005 std::cerr << " Migrated " << count << " blocks, "
1006 << (100.0 * count / blocks.size()) << "% completed.\r";
1008 new_db->beginSave();
1009 last_update_time = time(NULL);
1012 std::cerr << std::endl;
1017 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1018 world_mt.set("backend", migrate_to);
1019 if (!world_mt.updateConfigFile(world_mt_path.c_str()))
1020 errorstream << "Failed to update world.mt!" << std::endl;
1022 actionstream << "world.mt updated" << std::endl;