main.cpp 36 KB

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