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 "benchmark/benchmark.h"
24 #include "chat_interface.h"
26 #include "unittest/test.h"
30 #include "client/game.h"
31 #include "defaultsettings.h"
34 #include "util/quicktune.h"
35 #include "httpfetch.h"
36 #include "gameparams.h"
37 #include "database/database.h"
41 #include "network/socket.h"
44 #include "terminal_chat_console.h"
47 #include "gui/guiMainMenu.h"
48 #include "client/clientlauncher.h"
49 #include "gui/guiEngine.h"
50 #include "gui/mainmenumanager.h"
52 #ifdef HAVE_TOUCHSCREENGUI
53 #include "gui/touchscreengui.h"
56 // for version information only
65 #if !defined(__cpp_rtti) || !defined(__cpp_exceptions)
66 #error Minetest cannot be built without exceptions or RTTI
69 #if defined(__MINGW32__) && !defined(__MINGW64__) && !defined(__clang__) && \
70 (__GNUC__ < 11 || (__GNUC__ == 11 && __GNUC_MINOR__ < 1))
71 // see e.g. https://github.com/minetest/minetest/issues/10137
72 #warning ==================================
73 #warning 32-bit MinGW gcc before 11.1 has known issues with crashes on thread exit, you should upgrade.
74 #warning ==================================
77 #define DEBUGFILE "debug.txt"
78 #define DEFAULT_SERVER_PORT 30000
80 #define ENV_NO_COLOR "NO_COLOR"
81 #define ENV_CLICOLOR "CLICOLOR"
82 #define ENV_CLICOLOR_FORCE "CLICOLOR_FORCE"
84 typedef std::map<std::string, ValueSpec> OptionList;
86 /**********************************************************************
88 **********************************************************************/
90 static void get_env_opts(Settings &args);
91 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
92 static void set_allowed_options(OptionList *allowed_options);
94 static void print_help(const OptionList &allowed_options);
95 static void print_allowed_options(const OptionList &allowed_options);
96 static void print_version();
97 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
98 std::ostream &os, bool print_name = true, bool print_path = true);
99 static void print_modified_quicktune_values();
101 static void list_game_ids();
102 static void list_worlds(bool print_name, bool print_path);
103 static bool setup_log_params(const Settings &cmd_args);
104 static bool create_userdata_path();
105 static bool use_debugger(int argc, char *argv[]);
106 static bool init_common(const Settings &cmd_args, int argc, char *argv[]);
107 static void uninit_common();
108 static void startup_message();
109 static bool read_config_file(const Settings &cmd_args);
110 static void init_log_streams(const Settings &cmd_args);
112 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
113 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
115 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
116 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
117 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
118 static bool auto_select_world(GameParams *game_params);
119 static std::string get_clean_world_path(const std::string &path);
121 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
122 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
123 static bool determine_subgame(GameParams *game_params);
125 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
126 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args);
127 static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr);
129 /**********************************************************************/
132 FileLogOutput file_log_output;
134 static OptionList allowed_options;
136 int main(int argc, char *argv[])
139 debug_set_exception_handler();
141 g_logger.registerThread("Main");
142 g_logger.addOutputMaxLevel(&stderr_output, LL_ACTION);
145 get_env_opts(cmd_args);
146 bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
148 || cmd_args.getFlag("help")
149 || cmd_args.exists("nonopt1")) {
150 porting::attachOrCreateConsole();
151 print_help(allowed_options);
152 return cmd_args_ok ? 0 : 1;
154 if (cmd_args.getFlag("console"))
155 porting::attachOrCreateConsole();
157 if (cmd_args.getFlag("version")) {
158 porting::attachOrCreateConsole();
163 if (!setup_log_params(cmd_args))
166 if (cmd_args.getFlag("debugger")) {
167 if (!use_debugger(argc, argv))
168 warningstream << "Continuing without debugger" << std::endl;
171 porting::signal_handler_init();
174 porting::initAndroid();
175 porting::initializePathsAndroid();
177 porting::initializePaths();
180 if (!create_userdata_path()) {
181 errorstream << "Cannot create user data directory" << std::endl;
186 BEGIN_DEBUG_EXCEPTION_HANDLER
188 // List gameids if requested
189 if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
194 // List worlds, world names, and world paths if requested
195 if (cmd_args.exists("worldlist")) {
196 if (cmd_args.get("worldlist") == "name") {
197 list_worlds(true, false);
198 } else if (cmd_args.get("worldlist") == "path") {
199 list_worlds(false, true);
200 } else if (cmd_args.get("worldlist") == "both") {
201 list_worlds(true, true);
203 errorstream << "Invalid --worldlist value: "
204 << cmd_args.get("worldlist") << std::endl;
210 if (!init_common(cmd_args, argc, argv))
213 if (g_settings->getBool("enable_console"))
214 porting::attachOrCreateConsole();
218 if (cmd_args.getFlag("run-unittests")) {
222 errorstream << "Unittest support is not enabled in this binary. "
223 << "If you want to enable it, compile project with BUILD_UNITTESTS=1 flag."
230 if (cmd_args.getFlag("run-benchmarks")) {
232 return run_benchmarks();
234 errorstream << "Benchmark support is not enabled in this binary. "
235 << "If you want to enable it, compile project with BUILD_BENCHMARKS=1 flag."
240 #endif // __ANDROID__
242 GameStartData game_params;
244 porting::attachOrCreateConsole();
245 game_params.is_dedicated_server = true;
247 const bool isServer = cmd_args.getFlag("server");
249 porting::attachOrCreateConsole();
250 game_params.is_dedicated_server = isServer;
253 if (!game_configure(&game_params, cmd_args))
256 sanity_check(!game_params.world_path.empty());
258 if (game_params.is_dedicated_server)
259 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
262 retval = ClientLauncher().run(game_params, cmd_args) ? 0 : 1;
267 // Update configuration file
268 if (!g_settings_path.empty())
269 g_settings->updateConfigFile(g_settings_path.c_str());
271 print_modified_quicktune_values();
273 END_DEBUG_EXCEPTION_HANDLER
279 /*****************************************************************************
281 *****************************************************************************/
284 static void get_env_opts(Settings &args)
286 // CLICOLOR is a de-facto standard option for colors <https://bixense.com/clicolors/>
287 // CLICOLOR != 0: ANSI colors are supported (auto-detection, this is the default)
288 // CLICOLOR == 0: ANSI colors are NOT supported
289 const char *clicolor = std::getenv(ENV_CLICOLOR);
290 if (clicolor && std::string(clicolor) == "0") {
291 args.set("color", "never");
293 // NO_COLOR only specifies that no color is allowed.
294 // Implemented according to <http://no-color.org/>
295 const char *no_color = std::getenv(ENV_NO_COLOR);
296 if (no_color && no_color[0]) {
297 args.set("color", "never");
299 // CLICOLOR_FORCE is another option, which should turn on colors "no matter what".
300 const char *clicolor_force = std::getenv(ENV_CLICOLOR_FORCE);
301 if (clicolor_force && std::string(clicolor_force) != "0") {
302 // should ALWAYS have colors, so we ignore tty (no "auto")
303 args.set("color", "always");
307 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
309 set_allowed_options(&allowed_options);
311 return cmd_args->parseCommandLine(argc, argv, allowed_options);
314 static void set_allowed_options(OptionList *allowed_options)
316 allowed_options->clear();
318 allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
319 _("Show allowed options"))));
320 allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
321 _("Show version information"))));
322 allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
323 _("Load configuration from specified file"))));
324 allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
325 _("Set network port (UDP)"))));
326 allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
327 _("Run the unit tests and exit"))));
328 allowed_options->insert(std::make_pair("run-benchmarks", ValueSpec(VALUETYPE_FLAG,
329 _("Run the benchmarks and exit"))));
330 allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
331 _("Same as --world (deprecated)"))));
332 allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
333 _("Set world path (implies local game if used with option --go)"))));
334 allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
335 _("Set world by name (implies local game if used with option --go)"))));
336 allowed_options->insert(std::make_pair("worldlist", ValueSpec(VALUETYPE_STRING,
337 _("Get list of worlds ('path' lists paths, "
338 "'name' lists names, 'both' lists both)"))));
339 allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
340 _("Print to console errors only"))));
341 allowed_options->insert(std::make_pair("color", ValueSpec(VALUETYPE_STRING,
342 _("Coloured logs ('always', 'never' or 'auto'), defaults to 'auto'"
344 allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
345 _("Print more information to console"))));
346 allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
347 _("Print even more information to console"))));
348 allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
349 _("Print enormous amounts of information to log and console"))));
350 allowed_options->insert(std::make_pair("debugger", ValueSpec(VALUETYPE_FLAG,
351 _("Try to automatically attach a debugger before starting (convenience option)"))));
352 allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
353 _("Set logfile path ('' = no logging)"))));
354 allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
355 _("Set gameid (\"--gameid list\" prints available ones)"))));
356 allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
357 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
358 allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING,
359 _("Migrate from current players backend to another (Only works when using minetestserver or with --server)"))));
360 allowed_options->insert(std::make_pair("migrate-auth", ValueSpec(VALUETYPE_STRING,
361 _("Migrate from current auth backend to another (Only works when using minetestserver or with --server)"))));
362 allowed_options->insert(std::make_pair("migrate-mod-storage", ValueSpec(VALUETYPE_STRING,
363 _("Migrate from current mod storage backend to another (Only works when using minetestserver or with --server)"))));
364 allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
365 _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
366 allowed_options->insert(std::make_pair("recompress", ValueSpec(VALUETYPE_FLAG,
367 _("Recompress the blocks of the given map database."))));
369 allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
370 _("Run speed tests"))));
371 allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
372 _("Address to connect to. ('' = local game)"))));
373 allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
374 _("Enable random user input, for testing"))));
375 allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
376 _("Run dedicated server"))));
377 allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
378 _("Set player name"))));
379 allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
380 _("Set password"))));
381 allowed_options->insert(std::make_pair("password-file", ValueSpec(VALUETYPE_STRING,
382 _("Set password from contents of file"))));
383 allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
384 _("Disable main menu"))));
385 allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
386 _("Starts with the console (Windows only)"))));
391 static void print_help(const OptionList &allowed_options)
393 std::cout << _("Allowed options:") << std::endl;
394 print_allowed_options(allowed_options);
397 static void print_allowed_options(const OptionList &allowed_options)
399 for (const auto &allowed_option : allowed_options) {
400 std::string opt = " --" + allowed_option.first;
401 if (allowed_option.second.type != VALUETYPE_FLAG)
402 opt += _(" <value>");
404 std::string opt_padded = padStringRight(opt, 30);
405 std::cout << opt_padded;
406 if (opt == opt_padded) // Line is too long to pad
407 std::cout << std::endl << padStringRight("", 30);
409 if (allowed_option.second.help)
410 std::cout << allowed_option.second.help;
412 std::cout << std::endl;
416 static void print_version()
418 std::cout << PROJECT_NAME_C " " << g_version_hash
419 << " (" << porting::getPlatformName() << ")" << std::endl;
421 std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl;
424 std::cout << "Using " << LUAJIT_VERSION << std::endl;
426 std::cout << "Using " << LUA_RELEASE << std::endl;
428 std::cout << g_build_info << std::endl;
431 static void list_game_ids()
433 std::set<std::string> gameids = getAvailableGameIds();
434 for (const std::string &gameid : gameids)
435 std::cout << gameid <<std::endl;
438 static void list_worlds(bool print_name, bool print_path)
440 std::cout << _("Available worlds:") << std::endl;
441 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
442 print_worldspecs(worldspecs, std::cout, print_name, print_path);
445 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
446 std::ostream &os, bool print_name, bool print_path)
448 for (const WorldSpec &worldspec : worldspecs) {
449 std::string name = worldspec.name;
450 std::string path = worldspec.path;
451 if (print_name && print_path) {
452 os << "\t" << name << "\t\t" << path << std::endl;
453 } else if (print_name) {
454 os << "\t" << name << std::endl;
455 } else if (print_path) {
456 os << "\t" << path << std::endl;
461 static void print_modified_quicktune_values()
463 bool header_printed = false;
464 std::vector<std::string> names = getQuicktuneNames();
466 for (const std::string &name : names) {
467 QuicktuneValue val = getQuicktuneValue(name);
470 if (!header_printed) {
471 dstream << "Modified quicktune values:" << std::endl;
472 header_printed = true;
474 dstream << name << " = " << val.getString() << std::endl;
478 static bool setup_log_params(const Settings &cmd_args)
480 // Quiet mode, print errors only
481 if (cmd_args.getFlag("quiet")) {
482 g_logger.removeOutput(&stderr_output);
483 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
486 // Coloured log messages (see log.h)
487 std::string color_mode;
488 if (cmd_args.exists("color")) {
489 color_mode = cmd_args.get("color");
492 char *color_mode_env = getenv("MT_LOGCOLOR");
494 color_mode = color_mode_env;
497 if (!color_mode.empty()) {
498 if (color_mode == "auto") {
499 Logger::color_mode = LOG_COLOR_AUTO;
500 } else if (color_mode == "always") {
501 Logger::color_mode = LOG_COLOR_ALWAYS;
502 } else if (color_mode == "never") {
503 Logger::color_mode = LOG_COLOR_NEVER;
505 errorstream << "Invalid color mode: " << color_mode << std::endl;
510 // In certain cases, output info level on stderr
511 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
512 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
513 g_logger.addOutput(&stderr_output, LL_INFO);
515 // In certain cases, output verbose level on stderr
516 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
517 g_logger.addOutput(&stderr_output, LL_VERBOSE);
519 if (cmd_args.getFlag("trace")) {
520 dstream << _("Enabling trace level debug output") << std::endl;
521 g_logger.addOutput(&stderr_output, LL_TRACE);
522 socket_enable_debug_output = true;
528 static bool create_userdata_path()
533 if (!fs::PathExists(porting::path_user)) {
534 success = fs::CreateDir(porting::path_user);
539 // Create user data directory
540 success = fs::CreateAllDirs(porting::path_user);
547 std::string findProgram(const char *name)
549 char *path_c = getenv("PATH");
552 std::istringstream iss(path_c);
553 std::string checkpath;
555 std::getline(iss, checkpath, PATH_DELIM[0]);
556 if (!checkpath.empty() && checkpath.back() != DIR_DELIM_CHAR)
557 checkpath.push_back(DIR_DELIM_CHAR);
558 checkpath.append(name);
559 if (fs::IsExecutable(checkpath))
566 const char *debuggerNames[] = {"gdb.exe", "lldb.exe"};
568 const char *debuggerNames[] = {"gdb", "lldb"};
571 void getDebuggerArgs(T &out, int i) {
573 for (auto s : {"-q", "--batch", "-iex", "set confirm off",
574 "-ex", "run", "-ex", "bt", "--args"})
577 for (auto s : {"-Q", "-b", "-o", "run", "-k", "bt\nq", "--"})
583 static bool use_debugger(int argc, char *argv[])
585 #if defined(__ANDROID__)
589 if (IsDebuggerPresent()) {
590 warningstream << "Process is already being debugged." << std::endl;
595 char exec_path[1024];
596 if (!porting::getCurrentExecPath(exec_path, sizeof(exec_path)))
600 std::string debugger_path;
601 for (u32 i = 0; i < ARRLEN(debuggerNames); i++) {
602 debugger_path = findProgram(debuggerNames[i]);
603 if (!debugger_path.empty()) {
608 if (debugger == -1) {
609 warningstream << "Couldn't find a debugger to use. Try installing gdb or lldb." << std::endl;
615 if (strcmp(BUILD_TYPE, "RelWithDebInfo") != 0) {
616 warningstream << "It looks like your " PROJECT_NAME_C " executable was built without "
617 "debug symbols (BUILD_TYPE=" BUILD_TYPE "), so you won't get useful backtraces."
622 std::vector<const char*> new_args;
623 new_args.push_back(debugger_path.c_str());
624 getDebuggerArgs(new_args, debugger);
625 // Copy the existing arguments
626 new_args.push_back(exec_path);
627 for (int i = 1; i < argc; i++) {
628 if (!strcmp(argv[i], "--debugger"))
630 new_args.push_back(argv[i]);
632 new_args.push_back(nullptr);
635 // Special treatment for Windows
637 for (int i = 1; new_args[i]; i++) {
640 cmdline += porting::QuoteArgv(new_args[i]);
643 STARTUPINFO startup_info = {};
644 PROCESS_INFORMATION process_info = {};
645 bool ok = CreateProcess(new_args[0], cmdline.empty() ? nullptr : &cmdline[0],
646 nullptr, nullptr, false, CREATE_UNICODE_ENVIRONMENT,
647 nullptr, nullptr, &startup_info, &process_info);
649 warningstream << "CreateProcess: " << GetLastError() << std::endl;
653 WaitForSingleObject(process_info.hProcess, INFINITE);
654 GetExitCodeProcess(process_info.hProcess, &exitcode);
659 execv(new_args[0], const_cast<char**>(new_args.data()));
660 warningstream << "execv: " << strerror(errno) << std::endl;
666 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
669 set_default_settings();
673 // Initialize g_settings
674 Settings::createLayer(SL_GLOBAL);
676 // Set cleanup callback(s) to run at process exit
677 atexit(uninit_common);
679 if (!read_config_file(cmd_args))
682 init_log_streams(cmd_args);
684 // Initialize random seed
688 // Initialize HTTP fetcher
689 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
691 init_gettext(porting::path_locale.c_str(),
692 g_settings->get("language"), argc, argv);
697 static void uninit_common()
703 // It'd actually be okay to leak these but we want to please valgrind...
704 for (int i = 0; i < (int)SL_TOTAL_COUNT; i++)
705 delete Settings::getLayer((SettingsLayer)i);
708 static void startup_message()
710 infostream << PROJECT_NAME << " " << _("with")
711 << " SER_FMT_VER_HIGHEST_READ="
712 << (int)SER_FMT_VER_HIGHEST_READ << ", "
713 << g_build_info << std::endl;
716 static bool read_config_file(const Settings &cmd_args)
718 // Path of configuration file in use
719 sanity_check(g_settings_path.empty()); // Sanity check
721 if (cmd_args.exists("config")) {
722 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
724 errorstream << "Could not read configuration from \""
725 << cmd_args.get("config") << "\"" << std::endl;
728 g_settings_path = cmd_args.get("config");
730 std::vector<std::string> filenames;
731 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
732 // Legacy configuration file location
733 filenames.push_back(porting::path_user +
734 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
737 // Try also from a lower level (to aid having the same configuration
738 // for many RUN_IN_PLACE installs)
739 filenames.push_back(porting::path_user +
740 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
743 for (const std::string &filename : filenames) {
744 bool r = g_settings->readConfigFile(filename.c_str());
746 g_settings_path = filename;
751 // If no path found, use the first one (menu creates the file)
752 if (g_settings_path.empty())
753 g_settings_path = filenames[0];
759 static void init_log_streams(const Settings &cmd_args)
761 std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
763 if (cmd_args.exists("logfile"))
764 log_filename = cmd_args.get("logfile");
766 g_logger.removeOutput(&file_log_output);
767 std::string conf_loglev = g_settings->get("debug_log_level");
769 // Old integer format
770 if (std::isdigit(conf_loglev[0])) {
771 warningstream << "Deprecated use of debug_log_level with an "
772 "integer value; please update your configuration." << std::endl;
773 static const char *lev_name[] =
774 {"", "error", "action", "info", "verbose", "trace"};
775 int lev_i = atoi(conf_loglev.c_str());
776 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
777 warningstream << "Supplied invalid debug_log_level!"
778 " Assuming action level." << std::endl;
781 conf_loglev = lev_name[lev_i];
784 if (log_filename.empty() || conf_loglev.empty()) // No logging
787 LogLevel log_level = Logger::stringToLevel(conf_loglev);
788 if (log_level == LL_MAX) {
789 warningstream << "Supplied unrecognized debug_log_level; "
790 "using maximum." << std::endl;
793 file_log_output.setFile(log_filename,
794 g_settings->getU64("debug_log_size_max") * 1000000);
795 g_logger.addOutputMaxLevel(&file_log_output, log_level);
798 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
800 game_configure_port(game_params, cmd_args);
802 if (!game_configure_world(game_params, cmd_args)) {
803 errorstream << "No world path specified or found." << std::endl;
807 game_configure_subgame(game_params, cmd_args);
812 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
814 if (cmd_args.exists("port")) {
815 game_params->socket_port = cmd_args.getU16("port");
817 if (game_params->is_dedicated_server)
818 game_params->socket_port = g_settings->getU16("port");
820 game_params->socket_port = g_settings->getU16("remote_port");
823 if (game_params->socket_port == 0)
824 game_params->socket_port = DEFAULT_SERVER_PORT;
827 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
829 if (get_world_from_cmdline(game_params, cmd_args))
832 if (get_world_from_config(game_params, cmd_args))
835 return auto_select_world(game_params);
838 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
840 std::string commanded_world;
843 std::string commanded_worldname;
844 if (cmd_args.exists("worldname"))
845 commanded_worldname = cmd_args.get("worldname");
847 // If a world name was specified, convert it to a path
848 if (!commanded_worldname.empty()) {
849 // Get information about available worlds
850 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
852 for (const WorldSpec &worldspec : worldspecs) {
853 std::string name = worldspec.name;
854 if (name == commanded_worldname) {
855 dstream << _("Using world specified by --worldname on the "
856 "command line") << std::endl;
857 commanded_world = worldspec.path;
863 dstream << _("World") << " '" << commanded_worldname
864 << _("' not available. Available worlds:") << std::endl;
865 print_worldspecs(worldspecs, dstream);
869 game_params->world_path = get_clean_world_path(commanded_world);
870 return !commanded_world.empty();
873 if (cmd_args.exists("world"))
874 commanded_world = cmd_args.get("world");
875 else if (cmd_args.exists("map-dir"))
876 commanded_world = cmd_args.get("map-dir");
877 else if (cmd_args.exists("nonopt0")) // First nameless argument
878 commanded_world = cmd_args.get("nonopt0");
880 game_params->world_path = get_clean_world_path(commanded_world);
881 return !commanded_world.empty();
884 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
887 std::string commanded_world;
889 if (g_settings->exists("map-dir"))
890 commanded_world = g_settings->get("map-dir");
892 game_params->world_path = get_clean_world_path(commanded_world);
894 return !commanded_world.empty();
897 static bool auto_select_world(GameParams *game_params)
899 // No world was specified; try to select it automatically
900 // Get information about available worlds
902 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
903 std::string world_path;
905 // If there is only a single world, use it
906 if (worldspecs.size() == 1) {
907 world_path = worldspecs[0].path;
908 dstream <<_("Automatically selecting world at") << " ["
909 << world_path << "]" << std::endl;
910 // If there are multiple worlds, list them
911 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
912 std::cerr << _("Multiple worlds are available.") << std::endl;
913 std::cerr << _("Please select one using --worldname <name>"
914 " or --world <path>") << std::endl;
915 print_worldspecs(worldspecs, std::cerr);
917 // If there are no worlds, automatically create a new one
919 // This is the ultimate default world path
920 world_path = porting::path_user + DIR_DELIM + "worlds" +
922 infostream << "Using default world at ["
923 << world_path << "]" << std::endl;
926 assert(!world_path.empty()); // Post-condition
927 game_params->world_path = world_path;
931 static std::string get_clean_world_path(const std::string &path)
933 const std::string worldmt = "world.mt";
934 std::string clean_path;
936 if (path.size() > worldmt.size()
937 && path.substr(path.size() - worldmt.size()) == worldmt) {
938 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
939 clean_path = path.substr(0, path.size() - worldmt.size());
947 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
951 success = get_game_from_cmdline(game_params, cmd_args);
953 success = determine_subgame(game_params);
958 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
960 SubgameSpec commanded_gamespec;
962 if (cmd_args.exists("gameid")) {
963 std::string gameid = cmd_args.get("gameid");
964 commanded_gamespec = findSubgame(gameid);
965 if (!commanded_gamespec.isValid()) {
966 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
969 dstream << _("Using game specified by --gameid on the command line")
971 game_params->game_spec = commanded_gamespec;
978 static bool determine_subgame(GameParams *game_params)
980 SubgameSpec gamespec;
982 assert(!game_params->world_path.empty()); // Pre-condition
984 // If world doesn't exist
985 if (!game_params->world_path.empty()
986 && !getWorldExists(game_params->world_path)) {
987 // Try to take gamespec from command line
988 if (game_params->game_spec.isValid()) {
989 gamespec = game_params->game_spec;
990 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
991 } else { // Otherwise we will be using "minetest"
992 gamespec = findSubgame(g_settings->get("default_game"));
993 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
994 if (!gamespec.isValid()) {
995 errorstream << "Game specified in default_game ["
996 << g_settings->get("default_game")
997 << "] is invalid." << std::endl;
1001 } else { // World exists
1002 std::string world_gameid = getWorldGameId(game_params->world_path, false);
1003 // If commanded to use a gameid, do so
1004 if (game_params->game_spec.isValid()) {
1005 gamespec = game_params->game_spec;
1006 if (game_params->game_spec.id != world_gameid) {
1007 warningstream << "Using commanded gameid ["
1008 << gamespec.id << "]" << " instead of world gameid ["
1009 << world_gameid << "]" << std::endl;
1012 // If world contains an embedded game, use it;
1013 // Otherwise find world from local system.
1014 gamespec = findWorldSubgame(game_params->world_path);
1015 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
1019 if (!gamespec.isValid()) {
1020 errorstream << "Game [" << gamespec.id << "] could not be found."
1025 game_params->game_spec = gamespec;
1030 /*****************************************************************************
1032 *****************************************************************************/
1033 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
1035 verbosestream << _("Using world path") << " ["
1036 << game_params.world_path << "]" << std::endl;
1037 verbosestream << _("Using gameid") << " ["
1038 << game_params.game_spec.id << "]" << std::endl;
1041 std::string bind_str = g_settings->get("bind_address");
1042 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
1044 if (g_settings->getBool("ipv6_server")) {
1045 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1048 bind_addr.Resolve(bind_str.c_str());
1049 } catch (ResolveError &e) {
1050 infostream << "Resolving bind address \"" << bind_str
1051 << "\" failed: " << e.what()
1052 << " -- Listening on all addresses." << std::endl;
1054 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1055 errorstream << "Unable to listen on "
1056 << bind_addr.serializeString()
1057 << L" because IPv6 is disabled" << std::endl;
1061 // Database migration/compression
1062 if (cmd_args.exists("migrate"))
1063 return migrate_map_database(game_params, cmd_args);
1065 if (cmd_args.exists("migrate-players"))
1066 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
1068 if (cmd_args.exists("migrate-auth"))
1069 return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);
1071 if (cmd_args.exists("migrate-mod-storage"))
1072 return Server::migrateModStorageDatabase(game_params, cmd_args);
1074 if (cmd_args.getFlag("recompress"))
1075 return recompress_map_database(game_params, cmd_args, bind_addr);
1077 if (cmd_args.exists("terminal")) {
1079 bool name_ok = true;
1080 std::string admin_nick = g_settings->get("name");
1082 name_ok = name_ok && !admin_nick.empty();
1083 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
1086 if (admin_nick.empty()) {
1087 errorstream << "No name given for admin. "
1088 << "Please check your minetest.conf that it "
1089 << "contains a 'name = ' to your main admin account."
1092 errorstream << "Name for admin '"
1093 << admin_nick << "' is not valid. "
1094 << "Please check that it only contains allowed characters. "
1095 << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
1100 ChatInterface iface;
1101 bool &kill = *porting::signal_handler_killstatus();
1105 Server server(game_params.world_path, game_params.game_spec,
1106 false, bind_addr, true, &iface);
1108 g_term_console.setup(&iface, &kill, admin_nick);
1110 g_term_console.start();
1114 dedicated_server_loop(server, kill);
1115 } catch (const ModError &e) {
1116 g_term_console.stopAndWaitforThread();
1117 errorstream << "ModError: " << e.what() << std::endl;
1119 } catch (const ServerError &e) {
1120 g_term_console.stopAndWaitforThread();
1121 errorstream << "ServerError: " << e.what() << std::endl;
1125 // Tell the console to stop, and wait for it to finish,
1126 // only then leave context and free iface
1127 g_term_console.stop();
1128 g_term_console.wait();
1130 g_term_console.clearKillStatus();
1133 errorstream << "Cmd arg --terminal passed, but "
1134 << "compiled without ncurses. Ignoring." << std::endl;
1139 Server server(game_params.world_path, game_params.game_spec, false,
1144 bool &kill = *porting::signal_handler_killstatus();
1145 dedicated_server_loop(server, kill);
1147 } catch (const ModError &e) {
1148 errorstream << "ModError: " << e.what() << std::endl;
1150 } catch (const ServerError &e) {
1151 errorstream << "ServerError: " << e.what() << std::endl;
1159 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
1161 std::string migrate_to = cmd_args.get("migrate");
1163 std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
1164 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
1165 errorstream << "Cannot read world.mt!" << std::endl;
1169 if (!world_mt.exists("backend")) {
1170 errorstream << "Please specify your current backend in world.mt:"
1172 << " backend = {sqlite3|leveldb|redis|dummy|postgresql}"
1177 std::string backend = world_mt.get("backend");
1178 if (backend == migrate_to) {
1179 errorstream << "Cannot migrate: new backend is same"
1180 << " as the old one" << std::endl;
1184 MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
1185 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
1188 time_t last_update_time = 0;
1189 bool &kill = *porting::signal_handler_killstatus();
1191 std::vector<v3s16> blocks;
1192 old_db->listAllLoadableBlocks(blocks);
1193 new_db->beginSave();
1194 for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
1195 if (kill) return false;
1198 old_db->loadBlock(*it, &data);
1199 if (!data.empty()) {
1200 new_db->saveBlock(*it, data);
1202 errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
1204 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
1205 std::cerr << " Migrated " << count << " blocks, "
1206 << (100.0 * count / blocks.size()) << "% completed.\r";
1208 new_db->beginSave();
1209 last_update_time = time(NULL);
1212 std::cerr << std::endl;
1217 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1218 world_mt.set("backend", migrate_to);
1219 if (!world_mt.updateConfigFile(world_mt_path.c_str()))
1220 errorstream << "Failed to update world.mt!" << std::endl;
1222 actionstream << "world.mt updated" << std::endl;
1227 static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr)
1230 const std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
1232 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
1233 errorstream << "Cannot read world.mt at " << world_mt_path << std::endl;
1236 const std::string &backend = world_mt.get("backend");
1237 Server server(game_params.world_path, game_params.game_spec, false, addr, false);
1238 MapDatabase *db = ServerMap::createDatabase(backend, game_params.world_path, world_mt);
1241 u64 last_update_time = 0;
1242 bool &kill = *porting::signal_handler_killstatus();
1243 const u8 serialize_as_ver = SER_FMT_VER_HIGHEST_WRITE;
1245 // This is ok because the server doesn't actually run
1246 std::vector<v3s16> blocks;
1247 db->listAllLoadableBlocks(blocks);
1249 std::istringstream iss(std::ios_base::binary);
1250 std::ostringstream oss(std::ios_base::binary);
1251 for (auto it = blocks.begin(); it != blocks.end(); ++it) {
1252 if (kill) return false;
1255 db->loadBlock(*it, &data);
1257 errorstream << "Failed to load block " << PP(*it) << std::endl;
1265 MapBlock mb(nullptr, v3s16(0,0,0), &server);
1266 u8 ver = readU8(iss);
1267 mb.deSerialize(iss, ver, true);
1271 writeU8(oss, serialize_as_ver);
1272 mb.serialize(oss, serialize_as_ver, true, -1);
1275 db->saveBlock(*it, oss.str());
1278 if (count % 0xFF == 0 && porting::getTimeS() - last_update_time >= 1) {
1279 std::cerr << " Recompressed " << count << " blocks, "
1280 << (100.0f * count / blocks.size()) << "% completed.\r";
1283 last_update_time = porting::getTimeS();
1286 std::cerr << std::endl;
1289 actionstream << "Done, " << count << " blocks were recompressed." << std::endl;