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"
51 #ifdef HAVE_TOUCHSCREENGUI
52 #include "gui/touchscreengui.h"
55 #if !defined(SERVER) && \
56 (IRRLICHT_VERSION_MAJOR == 1) && \
57 (IRRLICHT_VERSION_MINOR == 8) && \
58 (IRRLICHT_VERSION_REVISION == 2)
59 #error "Irrlicht 1.8.2 is known to be broken - please update Irrlicht to version >= 1.8.3"
62 #define DEBUGFILE "debug.txt"
63 #define DEFAULT_SERVER_PORT 30000
65 typedef std::map<std::string, ValueSpec> OptionList;
67 /**********************************************************************
69 **********************************************************************/
71 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
72 static void set_allowed_options(OptionList *allowed_options);
74 static void print_help(const OptionList &allowed_options);
75 static void print_allowed_options(const OptionList &allowed_options);
76 static void print_version();
77 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
78 std::ostream &os, bool print_name = true, bool print_path = true);
79 static void print_modified_quicktune_values();
81 static void list_game_ids();
82 static void list_worlds(bool print_name, bool print_path);
83 static bool setup_log_params(const Settings &cmd_args);
84 static bool create_userdata_path();
85 static bool init_common(const Settings &cmd_args, int argc, char *argv[]);
86 static void startup_message();
87 static bool read_config_file(const Settings &cmd_args);
88 static void init_log_streams(const Settings &cmd_args);
90 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
91 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
93 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
94 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
95 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
96 static bool auto_select_world(GameParams *game_params);
97 static std::string get_clean_world_path(const std::string &path);
99 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
100 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
101 static bool determine_subgame(GameParams *game_params);
103 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
104 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args);
106 /**********************************************************************/
109 FileLogOutput file_log_output;
111 static OptionList allowed_options;
113 int main(int argc, char *argv[])
116 debug_set_exception_handler();
118 g_logger.registerThread("Main");
119 g_logger.addOutputMaxLevel(&stderr_output, LL_ACTION);
122 bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
124 || cmd_args.getFlag("help")
125 || cmd_args.exists("nonopt1")) {
126 porting::attachOrCreateConsole();
127 print_help(allowed_options);
128 return cmd_args_ok ? 0 : 1;
130 if (cmd_args.getFlag("console"))
131 porting::attachOrCreateConsole();
133 if (cmd_args.getFlag("version")) {
134 porting::attachOrCreateConsole();
139 if (!setup_log_params(cmd_args))
142 porting::signal_handler_init();
145 porting::initAndroid();
146 porting::initializePathsAndroid();
148 porting::initializePaths();
151 if (!create_userdata_path()) {
152 errorstream << "Cannot create user data directory" << std::endl;
157 BEGIN_DEBUG_EXCEPTION_HANDLER
159 // List gameids if requested
160 if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
165 // List worlds, world names, and world paths if requested
166 if (cmd_args.exists("worldlist")) {
167 if (cmd_args.get("worldlist") == "name") {
168 list_worlds(true, false);
169 } else if (cmd_args.get("worldlist") == "path") {
170 list_worlds(false, true);
171 } else if (cmd_args.get("worldlist") == "both") {
172 list_worlds(true, true);
174 errorstream << "Invalid --worldlist value: "
175 << cmd_args.get("worldlist") << std::endl;
181 if (!init_common(cmd_args, argc, argv))
184 if (g_settings->getBool("enable_console"))
185 porting::attachOrCreateConsole();
189 if (cmd_args.getFlag("run-unittests")) {
193 errorstream << "Unittest support is not enabled in this binary. "
194 << "If you want to enable it, compile project with BUILD_UNITTESTS=1 flag."
200 GameParams game_params;
202 porting::attachOrCreateConsole();
203 game_params.is_dedicated_server = true;
205 const bool isServer = cmd_args.getFlag("server");
207 porting::attachOrCreateConsole();
208 game_params.is_dedicated_server = isServer;
211 if (!game_configure(&game_params, cmd_args))
214 sanity_check(!game_params.world_path.empty());
216 if (game_params.is_dedicated_server)
217 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
220 ClientLauncher launcher;
221 retval = launcher.run(game_params, cmd_args) ? 0 : 1;
226 // Update configuration file
227 if (!g_settings_path.empty())
228 g_settings->updateConfigFile(g_settings_path.c_str());
230 print_modified_quicktune_values();
232 // Stop httpfetch thread (if started)
235 END_DEBUG_EXCEPTION_HANDLER
241 /*****************************************************************************
243 *****************************************************************************/
246 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
248 set_allowed_options(&allowed_options);
250 return cmd_args->parseCommandLine(argc, argv, allowed_options);
253 static void set_allowed_options(OptionList *allowed_options)
255 allowed_options->clear();
257 allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
258 _("Show allowed options"))));
259 allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
260 _("Show version information"))));
261 allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
262 _("Load configuration from specified file"))));
263 allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
264 _("Set network port (UDP)"))));
265 allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
266 _("Run the unit tests and exit"))));
267 allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
268 _("Same as --world (deprecated)"))));
269 allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
270 _("Set world path (implies local game if used with option --go)"))));
271 allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
272 _("Set world by name (implies local game if used with option --go)"))));
273 allowed_options->insert(std::make_pair("worldlist", ValueSpec(VALUETYPE_STRING,
274 _("Get list of worlds ('path' lists paths, "
275 "'name' lists names, 'both' lists both)"))));
276 allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
277 _("Print to console errors only"))));
278 allowed_options->insert(std::make_pair("color", ValueSpec(VALUETYPE_STRING,
279 _("Coloured logs ('always', 'never' or 'auto'), defaults to 'auto'"
281 allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
282 _("Print more information to console"))));
283 allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
284 _("Print even more information to console"))));
285 allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
286 _("Print enormous amounts of information to log and console"))));
287 allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
288 _("Set logfile path ('' = no logging)"))));
289 allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
290 _("Set gameid (\"--gameid list\" prints available ones)"))));
291 allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
292 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
293 allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING,
294 _("Migrate from current players backend to another (Only works when using minetestserver or with --server)"))));
295 allowed_options->insert(std::make_pair("migrate-auth", ValueSpec(VALUETYPE_STRING,
296 _("Migrate from current auth backend to another (Only works when using minetestserver or with --server)"))));
297 allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
298 _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
300 allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
301 _("Show available video modes"))));
302 allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
303 _("Run speed tests"))));
304 allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
305 _("Address to connect to. ('' = local game)"))));
306 allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
307 _("Enable random user input, for testing"))));
308 allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
309 _("Run dedicated server"))));
310 allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
311 _("Set player name"))));
312 allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
313 _("Set password"))));
314 allowed_options->insert(std::make_pair("password-file", ValueSpec(VALUETYPE_STRING,
315 _("Set password from contents of file"))));
316 allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
317 _("Disable main menu"))));
318 allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
319 _("Starts with the console (Windows only)"))));
324 static void print_help(const OptionList &allowed_options)
326 std::cout << _("Allowed options:") << std::endl;
327 print_allowed_options(allowed_options);
330 static void print_allowed_options(const OptionList &allowed_options)
332 for (const auto &allowed_option : allowed_options) {
333 std::ostringstream os1(std::ios::binary);
334 os1 << " --" << allowed_option.first;
335 if (allowed_option.second.type != VALUETYPE_FLAG)
336 os1 << _(" <value>");
338 std::cout << padStringRight(os1.str(), 30);
340 if (allowed_option.second.help)
341 std::cout << allowed_option.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 << g_build_info << std::endl;
357 static void list_game_ids()
359 std::set<std::string> gameids = getAvailableGameIds();
360 for (const std::string &gameid : gameids)
361 std::cout << gameid <<std::endl;
364 static void list_worlds(bool print_name, bool print_path)
366 std::cout << _("Available worlds:") << std::endl;
367 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
368 print_worldspecs(worldspecs, std::cout, print_name, print_path);
371 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
372 std::ostream &os, bool print_name, bool print_path)
374 for (const WorldSpec &worldspec : worldspecs) {
375 std::string name = worldspec.name;
376 std::string path = worldspec.path;
377 if (print_name && print_path) {
378 os << "\t" << name << "\t\t" << path << std::endl;
379 } else if (print_name) {
380 os << "\t" << name << std::endl;
381 } else if (print_path) {
382 os << "\t" << path << std::endl;
387 static void print_modified_quicktune_values()
389 bool header_printed = false;
390 std::vector<std::string> names = getQuicktuneNames();
392 for (const std::string &name : names) {
393 QuicktuneValue val = getQuicktuneValue(name);
396 if (!header_printed) {
397 dstream << "Modified quicktune values:" << std::endl;
398 header_printed = true;
400 dstream << name << " = " << val.getString() << std::endl;
404 static bool setup_log_params(const Settings &cmd_args)
406 // Quiet mode, print errors only
407 if (cmd_args.getFlag("quiet")) {
408 g_logger.removeOutput(&stderr_output);
409 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
412 // Coloured log messages (see log.h)
413 std::string color_mode;
414 if (cmd_args.exists("color")) {
415 color_mode = cmd_args.get("color");
418 char *color_mode_env = getenv("MT_LOGCOLOR");
420 color_mode = color_mode_env;
423 if (color_mode != "") {
424 if (color_mode == "auto") {
425 Logger::color_mode = LOG_COLOR_AUTO;
426 } else if (color_mode == "always") {
427 Logger::color_mode = LOG_COLOR_ALWAYS;
428 } else if (color_mode == "never") {
429 Logger::color_mode = LOG_COLOR_NEVER;
431 errorstream << "Invalid color mode: " << color_mode << std::endl;
436 // If trace is enabled, enable logging of certain things
437 if (cmd_args.getFlag("trace")) {
438 dstream << _("Enabling trace level debug output") << std::endl;
439 g_logger.setTraceEnabled(true);
440 dout_con_ptr = &verbosestream; // This is somewhat old
441 socket_enable_debug_output = true; // Sockets doesn't use log.h
444 // In certain cases, output info level on stderr
445 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
446 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
447 g_logger.addOutput(&stderr_output, LL_INFO);
449 // In certain cases, output verbose level on stderr
450 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
451 g_logger.addOutput(&stderr_output, LL_VERBOSE);
456 static bool create_userdata_path()
461 if (!fs::PathExists(porting::path_user)) {
462 success = fs::CreateDir(porting::path_user);
467 // Create user data directory
468 success = fs::CreateDir(porting::path_user);
474 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
477 set_default_settings(g_settings);
479 // Initialize sockets
481 atexit(sockets_cleanup);
483 if (!read_config_file(cmd_args))
486 init_log_streams(cmd_args);
488 // Initialize random seed
492 // Initialize HTTP fetcher
493 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
495 init_gettext(porting::path_locale.c_str(),
496 g_settings->get("language"), argc, argv);
501 static void startup_message()
503 infostream << PROJECT_NAME << " " << _("with")
504 << " SER_FMT_VER_HIGHEST_READ="
505 << (int)SER_FMT_VER_HIGHEST_READ << ", "
506 << g_build_info << std::endl;
509 static bool read_config_file(const Settings &cmd_args)
511 // Path of configuration file in use
512 sanity_check(g_settings_path == ""); // Sanity check
514 if (cmd_args.exists("config")) {
515 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
517 errorstream << "Could not read configuration from \""
518 << cmd_args.get("config") << "\"" << std::endl;
521 g_settings_path = cmd_args.get("config");
523 std::vector<std::string> filenames;
524 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
525 // Legacy configuration file location
526 filenames.push_back(porting::path_user +
527 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
530 // Try also from a lower level (to aid having the same configuration
531 // for many RUN_IN_PLACE installs)
532 filenames.push_back(porting::path_user +
533 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
536 for (const std::string &filename : filenames) {
537 bool r = g_settings->readConfigFile(filename.c_str());
539 g_settings_path = filename;
544 // If no path found, use the first one (menu creates the file)
545 if (g_settings_path.empty())
546 g_settings_path = filenames[0];
552 static void init_log_streams(const Settings &cmd_args)
554 std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
556 if (cmd_args.exists("logfile"))
557 log_filename = cmd_args.get("logfile");
559 g_logger.removeOutput(&file_log_output);
560 std::string conf_loglev = g_settings->get("debug_log_level");
562 // Old integer format
563 if (std::isdigit(conf_loglev[0])) {
564 warningstream << "Deprecated use of debug_log_level with an "
565 "integer value; please update your configuration." << std::endl;
566 static const char *lev_name[] =
567 {"", "error", "action", "info", "verbose"};
568 int lev_i = atoi(conf_loglev.c_str());
569 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
570 warningstream << "Supplied invalid debug_log_level!"
571 " Assuming action level." << std::endl;
574 conf_loglev = lev_name[lev_i];
577 if (log_filename.empty() || conf_loglev.empty()) // No logging
580 LogLevel log_level = Logger::stringToLevel(conf_loglev);
581 if (log_level == LL_MAX) {
582 warningstream << "Supplied unrecognized debug_log_level; "
583 "using maximum." << std::endl;
586 file_log_output.setFile(log_filename,
587 g_settings->getU64("debug_log_size_max") * 1000000);
588 g_logger.addOutputMaxLevel(&file_log_output, log_level);
591 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
593 game_configure_port(game_params, cmd_args);
595 if (!game_configure_world(game_params, cmd_args)) {
596 errorstream << "No world path specified or found." << std::endl;
600 game_configure_subgame(game_params, cmd_args);
605 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
607 if (cmd_args.exists("port"))
608 game_params->socket_port = cmd_args.getU16("port");
610 game_params->socket_port = g_settings->getU16("port");
612 if (game_params->socket_port == 0)
613 game_params->socket_port = DEFAULT_SERVER_PORT;
616 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
618 if (get_world_from_cmdline(game_params, cmd_args))
621 if (get_world_from_config(game_params, cmd_args))
624 return auto_select_world(game_params);
627 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
629 std::string commanded_world;
632 std::string commanded_worldname;
633 if (cmd_args.exists("worldname"))
634 commanded_worldname = cmd_args.get("worldname");
636 // If a world name was specified, convert it to a path
637 if (!commanded_worldname.empty()) {
638 // Get information about available worlds
639 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
641 for (const WorldSpec &worldspec : worldspecs) {
642 std::string name = worldspec.name;
643 if (name == commanded_worldname) {
644 dstream << _("Using world specified by --worldname on the "
645 "command line") << std::endl;
646 commanded_world = worldspec.path;
652 dstream << _("World") << " '" << commanded_worldname
653 << _("' not available. Available worlds:") << std::endl;
654 print_worldspecs(worldspecs, dstream);
658 game_params->world_path = get_clean_world_path(commanded_world);
659 return !commanded_world.empty();
662 if (cmd_args.exists("world"))
663 commanded_world = cmd_args.get("world");
664 else if (cmd_args.exists("map-dir"))
665 commanded_world = cmd_args.get("map-dir");
666 else if (cmd_args.exists("nonopt0")) // First nameless argument
667 commanded_world = cmd_args.get("nonopt0");
669 game_params->world_path = get_clean_world_path(commanded_world);
670 return !commanded_world.empty();
673 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
676 std::string commanded_world;
678 if (g_settings->exists("map-dir"))
679 commanded_world = g_settings->get("map-dir");
681 game_params->world_path = get_clean_world_path(commanded_world);
683 return !commanded_world.empty();
686 static bool auto_select_world(GameParams *game_params)
688 // No world was specified; try to select it automatically
689 // Get information about available worlds
691 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
692 std::string world_path;
694 // If there is only a single world, use it
695 if (worldspecs.size() == 1) {
696 world_path = worldspecs[0].path;
697 dstream <<_("Automatically selecting world at") << " ["
698 << world_path << "]" << std::endl;
699 // If there are multiple worlds, list them
700 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
701 std::cerr << _("Multiple worlds are available.") << std::endl;
702 std::cerr << _("Please select one using --worldname <name>"
703 " or --world <path>") << std::endl;
704 print_worldspecs(worldspecs, std::cerr);
706 // If there are no worlds, automatically create a new one
708 // This is the ultimate default world path
709 world_path = porting::path_user + DIR_DELIM + "worlds" +
711 infostream << "Using default world at ["
712 << world_path << "]" << std::endl;
715 assert(world_path != ""); // Post-condition
716 game_params->world_path = world_path;
720 static std::string get_clean_world_path(const std::string &path)
722 const std::string worldmt = "world.mt";
723 std::string clean_path;
725 if (path.size() > worldmt.size()
726 && path.substr(path.size() - worldmt.size()) == worldmt) {
727 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
728 clean_path = path.substr(0, path.size() - worldmt.size());
736 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
740 success = get_game_from_cmdline(game_params, cmd_args);
742 success = determine_subgame(game_params);
747 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
749 SubgameSpec commanded_gamespec;
751 if (cmd_args.exists("gameid")) {
752 std::string gameid = cmd_args.get("gameid");
753 commanded_gamespec = findSubgame(gameid);
754 if (!commanded_gamespec.isValid()) {
755 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
758 dstream << _("Using game specified by --gameid on the command line")
760 game_params->game_spec = commanded_gamespec;
767 static bool determine_subgame(GameParams *game_params)
769 SubgameSpec gamespec;
771 assert(game_params->world_path != ""); // Pre-condition
773 // If world doesn't exist
774 if (!game_params->world_path.empty()
775 && !getWorldExists(game_params->world_path)) {
776 // Try to take gamespec from command line
777 if (game_params->game_spec.isValid()) {
778 gamespec = game_params->game_spec;
779 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
780 } else { // Otherwise we will be using "minetest"
781 gamespec = findSubgame(g_settings->get("default_game"));
782 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
783 if (!gamespec.isValid()) {
784 errorstream << "Game specified in default_game ["
785 << g_settings->get("default_game")
786 << "] is invalid." << std::endl;
790 } else { // World exists
791 std::string world_gameid = getWorldGameId(game_params->world_path, false);
792 // If commanded to use a gameid, do so
793 if (game_params->game_spec.isValid()) {
794 gamespec = game_params->game_spec;
795 if (game_params->game_spec.id != world_gameid) {
796 warningstream << "Using commanded gameid ["
797 << gamespec.id << "]" << " instead of world gameid ["
798 << world_gameid << "]" << std::endl;
801 // If world contains an embedded game, use it;
802 // Otherwise find world from local system.
803 gamespec = findWorldSubgame(game_params->world_path);
804 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
808 if (!gamespec.isValid()) {
809 errorstream << "Game [" << gamespec.id << "] could not be found."
814 game_params->game_spec = gamespec;
819 /*****************************************************************************
821 *****************************************************************************/
822 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
824 verbosestream << _("Using world path") << " ["
825 << game_params.world_path << "]" << std::endl;
826 verbosestream << _("Using gameid") << " ["
827 << game_params.game_spec.id << "]" << std::endl;
830 std::string bind_str = g_settings->get("bind_address");
831 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
833 if (g_settings->getBool("ipv6_server")) {
834 bind_addr.setAddress((IPv6AddressBytes*) NULL);
837 bind_addr.Resolve(bind_str.c_str());
838 } catch (ResolveError &e) {
839 infostream << "Resolving bind address \"" << bind_str
840 << "\" failed: " << e.what()
841 << " -- Listening on all addresses." << std::endl;
843 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
844 errorstream << "Unable to listen on "
845 << bind_addr.serializeString()
846 << L" because IPv6 is disabled" << std::endl;
850 // Database migration
851 if (cmd_args.exists("migrate"))
852 return migrate_map_database(game_params, cmd_args);
854 if (cmd_args.exists("migrate-players"))
855 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
857 if (cmd_args.exists("migrate-auth"))
858 return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);
860 if (cmd_args.exists("terminal")) {
863 std::string admin_nick = g_settings->get("name");
865 name_ok = name_ok && !admin_nick.empty();
866 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
869 if (admin_nick.empty()) {
870 errorstream << "No name given for admin. "
871 << "Please check your minetest.conf that it "
872 << "contains a 'name = ' to your main admin account."
875 errorstream << "Name for admin '"
876 << admin_nick << "' is not valid. "
877 << "Please check that it only contains allowed characters. "
878 << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
884 bool &kill = *porting::signal_handler_killstatus();
888 Server server(game_params.world_path, game_params.game_spec,
889 false, bind_addr, true, &iface);
891 g_term_console.setup(&iface, &kill, admin_nick);
893 g_term_console.start();
897 dedicated_server_loop(server, kill);
898 } catch (const ModError &e) {
899 g_term_console.stopAndWaitforThread();
900 errorstream << "ModError: " << e.what() << std::endl;
902 } catch (const ServerError &e) {
903 g_term_console.stopAndWaitforThread();
904 errorstream << "ServerError: " << e.what() << std::endl;
908 // Tell the console to stop, and wait for it to finish,
909 // only then leave context and free iface
910 g_term_console.stop();
911 g_term_console.wait();
913 g_term_console.clearKillStatus();
916 errorstream << "Cmd arg --terminal passed, but "
917 << "compiled without ncurses. Ignoring." << std::endl;
922 Server server(game_params.world_path, game_params.game_spec, false,
927 bool &kill = *porting::signal_handler_killstatus();
928 dedicated_server_loop(server, kill);
930 } catch (const ModError &e) {
931 errorstream << "ModError: " << e.what() << std::endl;
933 } catch (const ServerError &e) {
934 errorstream << "ServerError: " << e.what() << std::endl;
942 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
944 std::string migrate_to = cmd_args.get("migrate");
946 std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
947 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
948 errorstream << "Cannot read world.mt!" << std::endl;
952 if (!world_mt.exists("backend")) {
953 errorstream << "Please specify your current backend in world.mt:"
955 << " backend = {sqlite3|leveldb|redis|dummy|postgresql}"
960 std::string backend = world_mt.get("backend");
961 if (backend == migrate_to) {
962 errorstream << "Cannot migrate: new backend is same"
963 << " as the old one" << std::endl;
967 MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
968 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
971 time_t last_update_time = 0;
972 bool &kill = *porting::signal_handler_killstatus();
974 std::vector<v3s16> blocks;
975 old_db->listAllLoadableBlocks(blocks);
977 for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
978 if (kill) return false;
981 old_db->loadBlock(*it, &data);
983 new_db->saveBlock(*it, data);
985 errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
987 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
988 std::cerr << " Migrated " << count << " blocks, "
989 << (100.0 * count / blocks.size()) << "% completed.\r";
992 last_update_time = time(NULL);
995 std::cerr << std::endl;
1000 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1001 world_mt.set("backend", migrate_to);
1002 if (!world_mt.updateConfigFile(world_mt_path.c_str()))
1003 errorstream << "Failed to update world.mt!" << std::endl;
1005 actionstream << "world.mt updated" << std::endl;