main.cpp 39 KB

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