main.cpp 40 KB

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