main.cpp 40 KB

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