main.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "irrlichttypes.h" // must be included before anything irrlicht, see comment in the file
  17. #include "irrlicht.h" // createDevice
  18. #include "irrlichttypes_extrabloated.h"
  19. #include "chat_interface.h"
  20. #include "debug.h"
  21. #include "unittest/test.h"
  22. #include "server.h"
  23. #include "filesys.h"
  24. #include "version.h"
  25. #include "client/game.h"
  26. #include "defaultsettings.h"
  27. #include "gettext.h"
  28. #include "log.h"
  29. #include "util/quicktune.h"
  30. #include "httpfetch.h"
  31. #include "gameparams.h"
  32. #include "database/database.h"
  33. #include "config.h"
  34. #include "player.h"
  35. #include "porting.h"
  36. #include "network/socket.h"
  37. #include "mapblock.h"
  38. #if USE_CURSES
  39. #include "terminal_chat_console.h"
  40. #endif
  41. #ifndef SERVER
  42. #include "gui/guiMainMenu.h"
  43. #include "client/clientlauncher.h"
  44. #include "gui/guiEngine.h"
  45. #include "gui/mainmenumanager.h"
  46. #endif
  47. #ifdef HAVE_TOUCHSCREENGUI
  48. #include "gui/touchscreengui.h"
  49. #endif
  50. // for version information only
  51. extern "C" {
  52. #if USE_LUAJIT
  53. #include <luajit.h>
  54. #else
  55. #include <lua.h>
  56. #endif
  57. }
  58. #if !defined(__cpp_rtti) || !defined(__cpp_exceptions)
  59. #error Minetest cannot be built without exceptions or RTTI
  60. #endif
  61. #if defined(__MINGW32__) && !defined(__MINGW64__) && !defined(__clang__) && \
  62. (__GNUC__ < 11 || (__GNUC__ == 11 && __GNUC_MINOR__ < 1))
  63. // see e.g. https://github.com/minetest/minetest/issues/10137
  64. #warning ==================================
  65. #warning 32-bit MinGW gcc before 11.1 has known issues with crashes on thread exit, you should upgrade.
  66. #warning ==================================
  67. #endif
  68. #define DEBUGFILE "debug.txt"
  69. #define DEFAULT_SERVER_PORT 30000
  70. typedef std::map<std::string, ValueSpec> OptionList;
  71. /**********************************************************************
  72. * Private functions
  73. **********************************************************************/
  74. static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
  75. static void set_allowed_options(OptionList *allowed_options);
  76. static void print_help(const OptionList &allowed_options);
  77. static void print_allowed_options(const OptionList &allowed_options);
  78. static void print_version();
  79. static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
  80. std::ostream &os, bool print_name = true, bool print_path = true);
  81. static void print_modified_quicktune_values();
  82. static void list_game_ids();
  83. static void list_worlds(bool print_name, bool print_path);
  84. static bool setup_log_params(const Settings &cmd_args);
  85. static bool create_userdata_path();
  86. static bool init_common(const Settings &cmd_args, int argc, char *argv[]);
  87. static void uninit_common();
  88. static void startup_message();
  89. static bool read_config_file(const Settings &cmd_args);
  90. static void init_log_streams(const Settings &cmd_args);
  91. static bool game_configure(GameParams *game_params, const Settings &cmd_args);
  92. 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);
  98. static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
  99. static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
  100. static bool determine_subgame(GameParams *game_params);
  101. static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
  102. static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args);
  103. static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr);
  104. /**********************************************************************/
  105. FileLogOutput file_log_output;
  106. static OptionList allowed_options;
  107. int main(int argc, char *argv[])
  108. {
  109. int retval;
  110. debug_set_exception_handler();
  111. g_logger.registerThread("Main");
  112. g_logger.addOutputMaxLevel(&stderr_output, LL_ACTION);
  113. Settings cmd_args;
  114. bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
  115. if (!cmd_args_ok
  116. || cmd_args.getFlag("help")
  117. || cmd_args.exists("nonopt1")) {
  118. porting::attachOrCreateConsole();
  119. print_help(allowed_options);
  120. return cmd_args_ok ? 0 : 1;
  121. }
  122. if (cmd_args.getFlag("console"))
  123. porting::attachOrCreateConsole();
  124. if (cmd_args.getFlag("version")) {
  125. porting::attachOrCreateConsole();
  126. print_version();
  127. return 0;
  128. }
  129. if (!setup_log_params(cmd_args))
  130. return 1;
  131. porting::signal_handler_init();
  132. #ifdef __ANDROID__
  133. porting::initAndroid();
  134. porting::initializePathsAndroid();
  135. #else
  136. porting::initializePaths();
  137. #endif
  138. if (!create_userdata_path()) {
  139. errorstream << "Cannot create user data directory" << std::endl;
  140. return 1;
  141. }
  142. // Debug handler
  143. BEGIN_DEBUG_EXCEPTION_HANDLER
  144. // List gameids if requested
  145. if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
  146. list_game_ids();
  147. return 0;
  148. }
  149. // List worlds, world names, and world paths if requested
  150. if (cmd_args.exists("worldlist")) {
  151. if (cmd_args.get("worldlist") == "name") {
  152. list_worlds(true, false);
  153. } else if (cmd_args.get("worldlist") == "path") {
  154. list_worlds(false, true);
  155. } else if (cmd_args.get("worldlist") == "both") {
  156. list_worlds(true, true);
  157. } else {
  158. errorstream << "Invalid --worldlist value: "
  159. << cmd_args.get("worldlist") << std::endl;
  160. return 1;
  161. }
  162. return 0;
  163. }
  164. if (!init_common(cmd_args, argc, argv))
  165. return 1;
  166. if (g_settings->getBool("enable_console"))
  167. porting::attachOrCreateConsole();
  168. #ifndef __ANDROID__
  169. // Run unit tests
  170. if (cmd_args.getFlag("run-unittests")) {
  171. #if BUILD_UNITTESTS
  172. return run_tests();
  173. #else
  174. errorstream << "Unittest support is not enabled in this binary. "
  175. << "If you want to enable it, compile project with BUILD_UNITTESTS=1 flag."
  176. << std::endl;
  177. return 1;
  178. #endif
  179. }
  180. #endif
  181. GameStartData game_params;
  182. #ifdef SERVER
  183. porting::attachOrCreateConsole();
  184. game_params.is_dedicated_server = true;
  185. #else
  186. const bool isServer = cmd_args.getFlag("server");
  187. if (isServer)
  188. porting::attachOrCreateConsole();
  189. game_params.is_dedicated_server = isServer;
  190. #endif
  191. if (!game_configure(&game_params, cmd_args))
  192. return 1;
  193. sanity_check(!game_params.world_path.empty());
  194. if (game_params.is_dedicated_server)
  195. return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
  196. #ifndef SERVER
  197. retval = ClientLauncher().run(game_params, cmd_args) ? 0 : 1;
  198. #else
  199. retval = 0;
  200. #endif
  201. // Update configuration file
  202. if (!g_settings_path.empty())
  203. g_settings->updateConfigFile(g_settings_path.c_str());
  204. print_modified_quicktune_values();
  205. END_DEBUG_EXCEPTION_HANDLER
  206. return retval;
  207. }
  208. /*****************************************************************************
  209. * Startup / Init
  210. *****************************************************************************/
  211. static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
  212. {
  213. set_allowed_options(&allowed_options);
  214. return cmd_args->parseCommandLine(argc, argv, allowed_options);
  215. }
  216. static void set_allowed_options(OptionList *allowed_options)
  217. {
  218. allowed_options->clear();
  219. allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
  220. _("Show allowed options"))));
  221. allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
  222. _("Show version information"))));
  223. allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
  224. _("Load configuration from specified file"))));
  225. allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
  226. _("Set network port (UDP)"))));
  227. allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
  228. _("Run the unit tests and exit"))));
  229. allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
  230. _("Same as --world (deprecated)"))));
  231. allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
  232. _("Set world path (implies local game if used with option --go)"))));
  233. allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
  234. _("Set world by name (implies local game if used with option --go)"))));
  235. allowed_options->insert(std::make_pair("worldlist", ValueSpec(VALUETYPE_STRING,
  236. _("Get list of worlds ('path' lists paths, "
  237. "'name' lists names, 'both' lists both)"))));
  238. allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
  239. _("Print to console errors only"))));
  240. allowed_options->insert(std::make_pair("color", ValueSpec(VALUETYPE_STRING,
  241. _("Coloured logs ('always', 'never' or 'auto'), defaults to 'auto'"
  242. ))));
  243. allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
  244. _("Print more information to console"))));
  245. allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
  246. _("Print even more information to console"))));
  247. allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
  248. _("Print enormous amounts of information to log and console"))));
  249. allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
  250. _("Set logfile path ('' = no logging)"))));
  251. allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
  252. _("Set gameid (\"--gameid list\" prints available ones)"))));
  253. allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
  254. _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
  255. allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING,
  256. _("Migrate from current players backend to another (Only works when using minetestserver or with --server)"))));
  257. allowed_options->insert(std::make_pair("migrate-auth", ValueSpec(VALUETYPE_STRING,
  258. _("Migrate from current auth backend to another (Only works when using minetestserver or with --server)"))));
  259. allowed_options->insert(std::make_pair("migrate-mod-storage", ValueSpec(VALUETYPE_STRING,
  260. _("Migrate from current mod storage backend to another (Only works when using minetestserver or with --server)"))));
  261. allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
  262. _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
  263. allowed_options->insert(std::make_pair("recompress", ValueSpec(VALUETYPE_FLAG,
  264. _("Recompress the blocks of the given map database."))));
  265. #ifndef SERVER
  266. allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
  267. _("Run speed tests"))));
  268. allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
  269. _("Address to connect to. ('' = local game)"))));
  270. allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
  271. _("Enable random user input, for testing"))));
  272. allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
  273. _("Run dedicated server"))));
  274. allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
  275. _("Set player name"))));
  276. allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
  277. _("Set password"))));
  278. allowed_options->insert(std::make_pair("password-file", ValueSpec(VALUETYPE_STRING,
  279. _("Set password from contents of file"))));
  280. allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
  281. _("Disable main menu"))));
  282. allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
  283. _("Starts with the console (Windows only)"))));
  284. #endif
  285. }
  286. static void print_help(const OptionList &allowed_options)
  287. {
  288. std::cout << _("Allowed options:") << std::endl;
  289. print_allowed_options(allowed_options);
  290. }
  291. static void print_allowed_options(const OptionList &allowed_options)
  292. {
  293. for (const auto &allowed_option : allowed_options) {
  294. std::ostringstream os1(std::ios::binary);
  295. os1 << " --" << allowed_option.first;
  296. if (allowed_option.second.type != VALUETYPE_FLAG)
  297. os1 << _(" <value>");
  298. std::cout << padStringRight(os1.str(), 30);
  299. if (allowed_option.second.help)
  300. std::cout << allowed_option.second.help;
  301. std::cout << std::endl;
  302. }
  303. }
  304. static void print_version()
  305. {
  306. std::cout << PROJECT_NAME_C " " << g_version_hash
  307. << " (" << porting::getPlatformName() << ")" << std::endl;
  308. #ifndef SERVER
  309. std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl;
  310. #endif
  311. #if USE_LUAJIT
  312. std::cout << "Using " << LUAJIT_VERSION << std::endl;
  313. #else
  314. std::cout << "Using " << LUA_RELEASE << std::endl;
  315. #endif
  316. std::cout << g_build_info << std::endl;
  317. }
  318. static void list_game_ids()
  319. {
  320. std::set<std::string> gameids = getAvailableGameIds();
  321. for (const std::string &gameid : gameids)
  322. std::cout << gameid <<std::endl;
  323. }
  324. static void list_worlds(bool print_name, bool print_path)
  325. {
  326. std::cout << _("Available worlds:") << std::endl;
  327. std::vector<WorldSpec> worldspecs = getAvailableWorlds();
  328. print_worldspecs(worldspecs, std::cout, print_name, print_path);
  329. }
  330. static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
  331. std::ostream &os, bool print_name, bool print_path)
  332. {
  333. for (const WorldSpec &worldspec : worldspecs) {
  334. std::string name = worldspec.name;
  335. std::string path = worldspec.path;
  336. if (print_name && print_path) {
  337. os << "\t" << name << "\t\t" << path << std::endl;
  338. } else if (print_name) {
  339. os << "\t" << name << std::endl;
  340. } else if (print_path) {
  341. os << "\t" << path << std::endl;
  342. }
  343. }
  344. }
  345. static void print_modified_quicktune_values()
  346. {
  347. bool header_printed = false;
  348. std::vector<std::string> names = getQuicktuneNames();
  349. for (const std::string &name : names) {
  350. QuicktuneValue val = getQuicktuneValue(name);
  351. if (!val.modified)
  352. continue;
  353. if (!header_printed) {
  354. dstream << "Modified quicktune values:" << std::endl;
  355. header_printed = true;
  356. }
  357. dstream << name << " = " << val.getString() << std::endl;
  358. }
  359. }
  360. static bool setup_log_params(const Settings &cmd_args)
  361. {
  362. // Quiet mode, print errors only
  363. if (cmd_args.getFlag("quiet")) {
  364. g_logger.removeOutput(&stderr_output);
  365. g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
  366. }
  367. // Coloured log messages (see log.h)
  368. std::string color_mode;
  369. if (cmd_args.exists("color")) {
  370. color_mode = cmd_args.get("color");
  371. #if !defined(_WIN32)
  372. } else {
  373. char *color_mode_env = getenv("MT_LOGCOLOR");
  374. if (color_mode_env)
  375. color_mode = color_mode_env;
  376. #endif
  377. }
  378. if (color_mode != "") {
  379. if (color_mode == "auto") {
  380. Logger::color_mode = LOG_COLOR_AUTO;
  381. } else if (color_mode == "always") {
  382. Logger::color_mode = LOG_COLOR_ALWAYS;
  383. } else if (color_mode == "never") {
  384. Logger::color_mode = LOG_COLOR_NEVER;
  385. } else {
  386. errorstream << "Invalid color mode: " << color_mode << std::endl;
  387. return false;
  388. }
  389. }
  390. // If trace is enabled, enable logging of certain things
  391. if (cmd_args.getFlag("trace")) {
  392. dstream << _("Enabling trace level debug output") << std::endl;
  393. g_logger.setTraceEnabled(true);
  394. dout_con_ptr = &verbosestream; // This is somewhat old
  395. socket_enable_debug_output = true; // Sockets doesn't use log.h
  396. }
  397. // In certain cases, output info level on stderr
  398. if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
  399. cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
  400. g_logger.addOutput(&stderr_output, LL_INFO);
  401. // In certain cases, output verbose level on stderr
  402. if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
  403. g_logger.addOutput(&stderr_output, LL_VERBOSE);
  404. return true;
  405. }
  406. static bool create_userdata_path()
  407. {
  408. bool success;
  409. #ifdef __ANDROID__
  410. if (!fs::PathExists(porting::path_user)) {
  411. success = fs::CreateDir(porting::path_user);
  412. } else {
  413. success = true;
  414. }
  415. #else
  416. // Create user data directory
  417. success = fs::CreateDir(porting::path_user);
  418. #endif
  419. return success;
  420. }
  421. static bool init_common(const Settings &cmd_args, int argc, char *argv[])
  422. {
  423. startup_message();
  424. set_default_settings();
  425. sockets_init();
  426. // Initialize g_settings
  427. Settings::createLayer(SL_GLOBAL);
  428. // Set cleanup callback(s) to run at process exit
  429. atexit(uninit_common);
  430. if (!read_config_file(cmd_args))
  431. return false;
  432. init_log_streams(cmd_args);
  433. // Initialize random seed
  434. srand(time(0));
  435. mysrand(time(0));
  436. // Initialize HTTP fetcher
  437. httpfetch_init(g_settings->getS32("curl_parallel_limit"));
  438. init_gettext(porting::path_locale.c_str(),
  439. g_settings->get("language"), argc, argv);
  440. return true;
  441. }
  442. static void uninit_common()
  443. {
  444. httpfetch_cleanup();
  445. sockets_cleanup();
  446. // It'd actually be okay to leak these but we want to please valgrind...
  447. for (int i = 0; i < (int)SL_TOTAL_COUNT; i++)
  448. delete Settings::getLayer((SettingsLayer)i);
  449. }
  450. static void startup_message()
  451. {
  452. infostream << PROJECT_NAME << " " << _("with")
  453. << " SER_FMT_VER_HIGHEST_READ="
  454. << (int)SER_FMT_VER_HIGHEST_READ << ", "
  455. << g_build_info << std::endl;
  456. }
  457. static bool read_config_file(const Settings &cmd_args)
  458. {
  459. // Path of configuration file in use
  460. sanity_check(g_settings_path == ""); // Sanity check
  461. if (cmd_args.exists("config")) {
  462. bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
  463. if (!r) {
  464. errorstream << "Could not read configuration from \""
  465. << cmd_args.get("config") << "\"" << std::endl;
  466. return false;
  467. }
  468. g_settings_path = cmd_args.get("config");
  469. } else {
  470. std::vector<std::string> filenames;
  471. filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
  472. // Legacy configuration file location
  473. filenames.push_back(porting::path_user +
  474. DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
  475. #if RUN_IN_PLACE
  476. // Try also from a lower level (to aid having the same configuration
  477. // for many RUN_IN_PLACE installs)
  478. filenames.push_back(porting::path_user +
  479. DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
  480. #endif
  481. for (const std::string &filename : filenames) {
  482. bool r = g_settings->readConfigFile(filename.c_str());
  483. if (r) {
  484. g_settings_path = filename;
  485. break;
  486. }
  487. }
  488. // If no path found, use the first one (menu creates the file)
  489. if (g_settings_path.empty())
  490. g_settings_path = filenames[0];
  491. }
  492. return true;
  493. }
  494. static void init_log_streams(const Settings &cmd_args)
  495. {
  496. std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
  497. if (cmd_args.exists("logfile"))
  498. log_filename = cmd_args.get("logfile");
  499. g_logger.removeOutput(&file_log_output);
  500. std::string conf_loglev = g_settings->get("debug_log_level");
  501. // Old integer format
  502. if (std::isdigit(conf_loglev[0])) {
  503. warningstream << "Deprecated use of debug_log_level with an "
  504. "integer value; please update your configuration." << std::endl;
  505. static const char *lev_name[] =
  506. {"", "error", "action", "info", "verbose"};
  507. int lev_i = atoi(conf_loglev.c_str());
  508. if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
  509. warningstream << "Supplied invalid debug_log_level!"
  510. " Assuming action level." << std::endl;
  511. lev_i = 2;
  512. }
  513. conf_loglev = lev_name[lev_i];
  514. }
  515. if (log_filename.empty() || conf_loglev.empty()) // No logging
  516. return;
  517. LogLevel log_level = Logger::stringToLevel(conf_loglev);
  518. if (log_level == LL_MAX) {
  519. warningstream << "Supplied unrecognized debug_log_level; "
  520. "using maximum." << std::endl;
  521. }
  522. file_log_output.setFile(log_filename,
  523. g_settings->getU64("debug_log_size_max") * 1000000);
  524. g_logger.addOutputMaxLevel(&file_log_output, log_level);
  525. }
  526. static bool game_configure(GameParams *game_params, const Settings &cmd_args)
  527. {
  528. game_configure_port(game_params, cmd_args);
  529. if (!game_configure_world(game_params, cmd_args)) {
  530. errorstream << "No world path specified or found." << std::endl;
  531. return false;
  532. }
  533. game_configure_subgame(game_params, cmd_args);
  534. return true;
  535. }
  536. static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
  537. {
  538. if (cmd_args.exists("port")) {
  539. game_params->socket_port = cmd_args.getU16("port");
  540. } else {
  541. if (game_params->is_dedicated_server)
  542. game_params->socket_port = g_settings->getU16("port");
  543. else
  544. game_params->socket_port = g_settings->getU16("remote_port");
  545. }
  546. if (game_params->socket_port == 0)
  547. game_params->socket_port = DEFAULT_SERVER_PORT;
  548. }
  549. static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
  550. {
  551. if (get_world_from_cmdline(game_params, cmd_args))
  552. return true;
  553. if (get_world_from_config(game_params, cmd_args))
  554. return true;
  555. return auto_select_world(game_params);
  556. }
  557. static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
  558. {
  559. std::string commanded_world;
  560. // World name
  561. std::string commanded_worldname;
  562. if (cmd_args.exists("worldname"))
  563. commanded_worldname = cmd_args.get("worldname");
  564. // If a world name was specified, convert it to a path
  565. if (!commanded_worldname.empty()) {
  566. // Get information about available worlds
  567. std::vector<WorldSpec> worldspecs = getAvailableWorlds();
  568. bool found = false;
  569. for (const WorldSpec &worldspec : worldspecs) {
  570. std::string name = worldspec.name;
  571. if (name == commanded_worldname) {
  572. dstream << _("Using world specified by --worldname on the "
  573. "command line") << std::endl;
  574. commanded_world = worldspec.path;
  575. found = true;
  576. break;
  577. }
  578. }
  579. if (!found) {
  580. dstream << _("World") << " '" << commanded_worldname
  581. << _("' not available. Available worlds:") << std::endl;
  582. print_worldspecs(worldspecs, dstream);
  583. return false;
  584. }
  585. game_params->world_path = get_clean_world_path(commanded_world);
  586. return !commanded_world.empty();
  587. }
  588. if (cmd_args.exists("world"))
  589. commanded_world = cmd_args.get("world");
  590. else if (cmd_args.exists("map-dir"))
  591. commanded_world = cmd_args.get("map-dir");
  592. else if (cmd_args.exists("nonopt0")) // First nameless argument
  593. commanded_world = cmd_args.get("nonopt0");
  594. game_params->world_path = get_clean_world_path(commanded_world);
  595. return !commanded_world.empty();
  596. }
  597. static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
  598. {
  599. // World directory
  600. std::string commanded_world;
  601. if (g_settings->exists("map-dir"))
  602. commanded_world = g_settings->get("map-dir");
  603. game_params->world_path = get_clean_world_path(commanded_world);
  604. return !commanded_world.empty();
  605. }
  606. static bool auto_select_world(GameParams *game_params)
  607. {
  608. // No world was specified; try to select it automatically
  609. // Get information about available worlds
  610. std::vector<WorldSpec> worldspecs = getAvailableWorlds();
  611. std::string world_path;
  612. // If there is only a single world, use it
  613. if (worldspecs.size() == 1) {
  614. world_path = worldspecs[0].path;
  615. dstream <<_("Automatically selecting world at") << " ["
  616. << world_path << "]" << std::endl;
  617. // If there are multiple worlds, list them
  618. } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
  619. std::cerr << _("Multiple worlds are available.") << std::endl;
  620. std::cerr << _("Please select one using --worldname <name>"
  621. " or --world <path>") << std::endl;
  622. print_worldspecs(worldspecs, std::cerr);
  623. return false;
  624. // If there are no worlds, automatically create a new one
  625. } else {
  626. // This is the ultimate default world path
  627. world_path = porting::path_user + DIR_DELIM + "worlds" +
  628. DIR_DELIM + "world";
  629. infostream << "Using default world at ["
  630. << world_path << "]" << std::endl;
  631. }
  632. assert(world_path != ""); // Post-condition
  633. game_params->world_path = world_path;
  634. return true;
  635. }
  636. static std::string get_clean_world_path(const std::string &path)
  637. {
  638. const std::string worldmt = "world.mt";
  639. std::string clean_path;
  640. if (path.size() > worldmt.size()
  641. && path.substr(path.size() - worldmt.size()) == worldmt) {
  642. dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
  643. clean_path = path.substr(0, path.size() - worldmt.size());
  644. } else {
  645. clean_path = path;
  646. }
  647. return path;
  648. }
  649. static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
  650. {
  651. bool success;
  652. success = get_game_from_cmdline(game_params, cmd_args);
  653. if (!success)
  654. success = determine_subgame(game_params);
  655. return success;
  656. }
  657. static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
  658. {
  659. SubgameSpec commanded_gamespec;
  660. if (cmd_args.exists("gameid")) {
  661. std::string gameid = cmd_args.get("gameid");
  662. commanded_gamespec = findSubgame(gameid);
  663. if (!commanded_gamespec.isValid()) {
  664. errorstream << "Game \"" << gameid << "\" not found" << std::endl;
  665. return false;
  666. }
  667. dstream << _("Using game specified by --gameid on the command line")
  668. << std::endl;
  669. game_params->game_spec = commanded_gamespec;
  670. return true;
  671. }
  672. return false;
  673. }
  674. static bool determine_subgame(GameParams *game_params)
  675. {
  676. SubgameSpec gamespec;
  677. assert(game_params->world_path != ""); // Pre-condition
  678. // If world doesn't exist
  679. if (!game_params->world_path.empty()
  680. && !getWorldExists(game_params->world_path)) {
  681. // Try to take gamespec from command line
  682. if (game_params->game_spec.isValid()) {
  683. gamespec = game_params->game_spec;
  684. infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
  685. } else { // Otherwise we will be using "minetest"
  686. gamespec = findSubgame(g_settings->get("default_game"));
  687. infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
  688. if (!gamespec.isValid()) {
  689. errorstream << "Game specified in default_game ["
  690. << g_settings->get("default_game")
  691. << "] is invalid." << std::endl;
  692. return false;
  693. }
  694. }
  695. } else { // World exists
  696. std::string world_gameid = getWorldGameId(game_params->world_path, false);
  697. // If commanded to use a gameid, do so
  698. if (game_params->game_spec.isValid()) {
  699. gamespec = game_params->game_spec;
  700. if (game_params->game_spec.id != world_gameid) {
  701. warningstream << "Using commanded gameid ["
  702. << gamespec.id << "]" << " instead of world gameid ["
  703. << world_gameid << "]" << std::endl;
  704. }
  705. } else {
  706. // If world contains an embedded game, use it;
  707. // Otherwise find world from local system.
  708. gamespec = findWorldSubgame(game_params->world_path);
  709. infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
  710. }
  711. }
  712. if (!gamespec.isValid()) {
  713. errorstream << "Game [" << gamespec.id << "] could not be found."
  714. << std::endl;
  715. return false;
  716. }
  717. game_params->game_spec = gamespec;
  718. return true;
  719. }
  720. /*****************************************************************************
  721. * Dedicated server
  722. *****************************************************************************/
  723. static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
  724. {
  725. verbosestream << _("Using world path") << " ["
  726. << game_params.world_path << "]" << std::endl;
  727. verbosestream << _("Using gameid") << " ["
  728. << game_params.game_spec.id << "]" << std::endl;
  729. // Bind address
  730. std::string bind_str = g_settings->get("bind_address");
  731. Address bind_addr(0, 0, 0, 0, game_params.socket_port);
  732. if (g_settings->getBool("ipv6_server")) {
  733. bind_addr.setAddress((IPv6AddressBytes*) NULL);
  734. }
  735. try {
  736. bind_addr.Resolve(bind_str.c_str());
  737. } catch (ResolveError &e) {
  738. infostream << "Resolving bind address \"" << bind_str
  739. << "\" failed: " << e.what()
  740. << " -- Listening on all addresses." << std::endl;
  741. }
  742. if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
  743. errorstream << "Unable to listen on "
  744. << bind_addr.serializeString()
  745. << L" because IPv6 is disabled" << std::endl;
  746. return false;
  747. }
  748. // Database migration/compression
  749. if (cmd_args.exists("migrate"))
  750. return migrate_map_database(game_params, cmd_args);
  751. if (cmd_args.exists("migrate-players"))
  752. return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
  753. if (cmd_args.exists("migrate-auth"))
  754. return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);
  755. if (cmd_args.exists("migrate-mod-storage"))
  756. return Server::migrateModStorageDatabase(game_params, cmd_args);
  757. if (cmd_args.getFlag("recompress"))
  758. return recompress_map_database(game_params, cmd_args, bind_addr);
  759. if (cmd_args.exists("terminal")) {
  760. #if USE_CURSES
  761. bool name_ok = true;
  762. std::string admin_nick = g_settings->get("name");
  763. name_ok = name_ok && !admin_nick.empty();
  764. name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
  765. if (!name_ok) {
  766. if (admin_nick.empty()) {
  767. errorstream << "No name given for admin. "
  768. << "Please check your minetest.conf that it "
  769. << "contains a 'name = ' to your main admin account."
  770. << std::endl;
  771. } else {
  772. errorstream << "Name for admin '"
  773. << admin_nick << "' is not valid. "
  774. << "Please check that it only contains allowed characters. "
  775. << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
  776. << std::endl;
  777. }
  778. return false;
  779. }
  780. ChatInterface iface;
  781. bool &kill = *porting::signal_handler_killstatus();
  782. try {
  783. // Create server
  784. Server server(game_params.world_path, game_params.game_spec,
  785. false, bind_addr, true, &iface);
  786. g_term_console.setup(&iface, &kill, admin_nick);
  787. g_term_console.start();
  788. server.start();
  789. // Run server
  790. dedicated_server_loop(server, kill);
  791. } catch (const ModError &e) {
  792. g_term_console.stopAndWaitforThread();
  793. errorstream << "ModError: " << e.what() << std::endl;
  794. return false;
  795. } catch (const ServerError &e) {
  796. g_term_console.stopAndWaitforThread();
  797. errorstream << "ServerError: " << e.what() << std::endl;
  798. return false;
  799. }
  800. // Tell the console to stop, and wait for it to finish,
  801. // only then leave context and free iface
  802. g_term_console.stop();
  803. g_term_console.wait();
  804. g_term_console.clearKillStatus();
  805. } else {
  806. #else
  807. errorstream << "Cmd arg --terminal passed, but "
  808. << "compiled without ncurses. Ignoring." << std::endl;
  809. } {
  810. #endif
  811. try {
  812. // Create server
  813. Server server(game_params.world_path, game_params.game_spec, false,
  814. bind_addr, true);
  815. server.start();
  816. // Run server
  817. bool &kill = *porting::signal_handler_killstatus();
  818. dedicated_server_loop(server, kill);
  819. } catch (const ModError &e) {
  820. errorstream << "ModError: " << e.what() << std::endl;
  821. return false;
  822. } catch (const ServerError &e) {
  823. errorstream << "ServerError: " << e.what() << std::endl;
  824. return false;
  825. }
  826. }
  827. return true;
  828. }
  829. static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
  830. {
  831. std::string migrate_to = cmd_args.get("migrate");
  832. Settings world_mt;
  833. std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
  834. if (!world_mt.readConfigFile(world_mt_path.c_str())) {
  835. errorstream << "Cannot read world.mt!" << std::endl;
  836. return false;
  837. }
  838. if (!world_mt.exists("backend")) {
  839. errorstream << "Please specify your current backend in world.mt:"
  840. << std::endl
  841. << " backend = {sqlite3|leveldb|redis|dummy|postgresql}"
  842. << std::endl;
  843. return false;
  844. }
  845. std::string backend = world_mt.get("backend");
  846. if (backend == migrate_to) {
  847. errorstream << "Cannot migrate: new backend is same"
  848. << " as the old one" << std::endl;
  849. return false;
  850. }
  851. MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
  852. *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
  853. u32 count = 0;
  854. time_t last_update_time = 0;
  855. bool &kill = *porting::signal_handler_killstatus();
  856. std::vector<v3s16> blocks;
  857. old_db->listAllLoadableBlocks(blocks);
  858. new_db->beginSave();
  859. for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
  860. if (kill) return false;
  861. std::string data;
  862. old_db->loadBlock(*it, &data);
  863. if (!data.empty()) {
  864. new_db->saveBlock(*it, data);
  865. } else {
  866. errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
  867. }
  868. if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
  869. std::cerr << " Migrated " << count << " blocks, "
  870. << (100.0 * count / blocks.size()) << "% completed.\r";
  871. new_db->endSave();
  872. new_db->beginSave();
  873. last_update_time = time(NULL);
  874. }
  875. }
  876. std::cerr << std::endl;
  877. new_db->endSave();
  878. delete old_db;
  879. delete new_db;
  880. actionstream << "Successfully migrated " << count << " blocks" << std::endl;
  881. world_mt.set("backend", migrate_to);
  882. if (!world_mt.updateConfigFile(world_mt_path.c_str()))
  883. errorstream << "Failed to update world.mt!" << std::endl;
  884. else
  885. actionstream << "world.mt updated" << std::endl;
  886. return true;
  887. }
  888. static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr)
  889. {
  890. Settings world_mt;
  891. const std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
  892. if (!world_mt.readConfigFile(world_mt_path.c_str())) {
  893. errorstream << "Cannot read world.mt at " << world_mt_path << std::endl;
  894. return false;
  895. }
  896. const std::string &backend = world_mt.get("backend");
  897. Server server(game_params.world_path, game_params.game_spec, false, addr, false);
  898. MapDatabase *db = ServerMap::createDatabase(backend, game_params.world_path, world_mt);
  899. u32 count = 0;
  900. u64 last_update_time = 0;
  901. bool &kill = *porting::signal_handler_killstatus();
  902. const u8 serialize_as_ver = SER_FMT_VER_HIGHEST_WRITE;
  903. // This is ok because the server doesn't actually run
  904. std::vector<v3s16> blocks;
  905. db->listAllLoadableBlocks(blocks);
  906. db->beginSave();
  907. std::istringstream iss(std::ios_base::binary);
  908. std::ostringstream oss(std::ios_base::binary);
  909. for (auto it = blocks.begin(); it != blocks.end(); ++it) {
  910. if (kill) return false;
  911. std::string data;
  912. db->loadBlock(*it, &data);
  913. if (data.empty()) {
  914. errorstream << "Failed to load block " << PP(*it) << std::endl;
  915. return false;
  916. }
  917. iss.str(data);
  918. iss.clear();
  919. MapBlock mb(nullptr, v3s16(0,0,0), &server);
  920. u8 ver = readU8(iss);
  921. mb.deSerialize(iss, ver, true);
  922. oss.str("");
  923. oss.clear();
  924. writeU8(oss, serialize_as_ver);
  925. mb.serialize(oss, serialize_as_ver, true, -1);
  926. db->saveBlock(*it, oss.str());
  927. count++;
  928. if (count % 0xFF == 0 && porting::getTimeS() - last_update_time >= 1) {
  929. std::cerr << " Recompressed " << count << " blocks, "
  930. << (100.0f * count / blocks.size()) << "% completed.\r";
  931. db->endSave();
  932. db->beginSave();
  933. last_update_time = porting::getTimeS();
  934. }
  935. }
  936. std::cerr << std::endl;
  937. db->endSave();
  938. actionstream << "Done, " << count << " blocks were recompressed." << std::endl;
  939. return true;
  940. }