main.cpp 40 KB

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