main.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  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 "chat_interface.h"
  20. #include "debug.h"
  21. #include "unittest/test.h"
  22. #include "server.h"
  23. #include "filesys.h"
  24. #include "version.h"
  25. #include "client/game.h"
  26. #include "defaultsettings.h"
  27. #include "gettext.h"
  28. #include "log.h"
  29. #include "util/quicktune.h"
  30. #include "httpfetch.h"
  31. #include "gameparams.h"
  32. #include "database/database.h"
  33. #include "config.h"
  34. #include "player.h"
  35. #include "porting.h"
  36. #include "network/socket.h"
  37. #if USE_CURSES
  38. #include "terminal_chat_console.h"
  39. #endif
  40. #ifndef SERVER
  41. #include "gui/guiMainMenu.h"
  42. #include "client/clientlauncher.h"
  43. #include "gui/guiEngine.h"
  44. #include "gui/mainmenumanager.h"
  45. #endif
  46. #ifdef HAVE_TOUCHSCREENGUI
  47. #include "gui/touchscreengui.h"
  48. #endif
  49. #if !defined(SERVER) && \
  50. (IRRLICHT_VERSION_MAJOR == 1) && \
  51. (IRRLICHT_VERSION_MINOR == 8) && \
  52. (IRRLICHT_VERSION_REVISION == 2)
  53. #error "Irrlicht 1.8.2 is known to be broken - please update Irrlicht to version >= 1.8.3"
  54. #endif
  55. #define DEBUGFILE "debug.txt"
  56. #define DEFAULT_SERVER_PORT 30000
  57. typedef std::map<std::string, ValueSpec> OptionList;
  58. /**********************************************************************
  59. * Private functions
  60. **********************************************************************/
  61. static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
  62. static void set_allowed_options(OptionList *allowed_options);
  63. static void print_help(const OptionList &allowed_options);
  64. static void print_allowed_options(const OptionList &allowed_options);
  65. static void print_version();
  66. static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
  67. std::ostream &os, bool print_name = true, bool print_path = true);
  68. static void print_modified_quicktune_values();
  69. static void list_game_ids();
  70. static void list_worlds(bool print_name, bool print_path);
  71. static bool setup_log_params(const Settings &cmd_args);
  72. static bool create_userdata_path();
  73. static bool init_common(const Settings &cmd_args, int argc, char *argv[]);
  74. static void startup_message();
  75. static bool read_config_file(const Settings &cmd_args);
  76. static void init_log_streams(const Settings &cmd_args);
  77. static bool game_configure(GameParams *game_params, const Settings &cmd_args);
  78. static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
  79. static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
  80. static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
  81. static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
  82. static bool auto_select_world(GameParams *game_params);
  83. static std::string get_clean_world_path(const std::string &path);
  84. static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
  85. static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
  86. static bool determine_subgame(GameParams *game_params);
  87. static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
  88. static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args);
  89. /**********************************************************************/
  90. FileLogOutput file_log_output;
  91. static OptionList allowed_options;
  92. int main(int argc, char *argv[])
  93. {
  94. int retval;
  95. debug_set_exception_handler();
  96. g_logger.registerThread("Main");
  97. g_logger.addOutputMaxLevel(&stderr_output, LL_ACTION);
  98. Settings cmd_args;
  99. bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
  100. if (!cmd_args_ok
  101. || cmd_args.getFlag("help")
  102. || cmd_args.exists("nonopt1")) {
  103. porting::attachOrCreateConsole();
  104. print_help(allowed_options);
  105. return cmd_args_ok ? 0 : 1;
  106. }
  107. if (cmd_args.getFlag("console"))
  108. porting::attachOrCreateConsole();
  109. if (cmd_args.getFlag("version")) {
  110. porting::attachOrCreateConsole();
  111. print_version();
  112. return 0;
  113. }
  114. if (!setup_log_params(cmd_args))
  115. return 1;
  116. porting::signal_handler_init();
  117. #ifdef __ANDROID__
  118. porting::initAndroid();
  119. porting::initializePathsAndroid();
  120. #else
  121. porting::initializePaths();
  122. #endif
  123. if (!create_userdata_path()) {
  124. errorstream << "Cannot create user data directory" << std::endl;
  125. return 1;
  126. }
  127. // Debug handler
  128. BEGIN_DEBUG_EXCEPTION_HANDLER
  129. // List gameids if requested
  130. if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
  131. list_game_ids();
  132. return 0;
  133. }
  134. // List worlds, world names, and world paths if requested
  135. if (cmd_args.exists("worldlist")) {
  136. if (cmd_args.get("worldlist") == "name") {
  137. list_worlds(true, false);
  138. } else if (cmd_args.get("worldlist") == "path") {
  139. list_worlds(false, true);
  140. } else if (cmd_args.get("worldlist") == "both") {
  141. list_worlds(true, true);
  142. } else {
  143. errorstream << "Invalid --worldlist value: "
  144. << cmd_args.get("worldlist") << std::endl;
  145. return 1;
  146. }
  147. return 0;
  148. }
  149. if (!init_common(cmd_args, argc, argv))
  150. return 1;
  151. if (g_settings->getBool("enable_console"))
  152. porting::attachOrCreateConsole();
  153. #ifndef __ANDROID__
  154. // Run unit tests
  155. if (cmd_args.getFlag("run-unittests")) {
  156. return run_tests();
  157. }
  158. #endif
  159. GameParams game_params;
  160. #ifdef SERVER
  161. porting::attachOrCreateConsole();
  162. game_params.is_dedicated_server = true;
  163. #else
  164. const bool isServer = cmd_args.getFlag("server");
  165. if (isServer)
  166. porting::attachOrCreateConsole();
  167. game_params.is_dedicated_server = isServer;
  168. #endif
  169. if (!game_configure(&game_params, cmd_args))
  170. return 1;
  171. sanity_check(!game_params.world_path.empty());
  172. infostream << "Using commanded world path ["
  173. << game_params.world_path << "]" << std::endl;
  174. if (game_params.is_dedicated_server)
  175. return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
  176. #ifndef SERVER
  177. ClientLauncher launcher;
  178. retval = launcher.run(game_params, cmd_args) ? 0 : 1;
  179. #else
  180. retval = 0;
  181. #endif
  182. // Update configuration file
  183. if (!g_settings_path.empty())
  184. g_settings->updateConfigFile(g_settings_path.c_str());
  185. print_modified_quicktune_values();
  186. // Stop httpfetch thread (if started)
  187. httpfetch_cleanup();
  188. END_DEBUG_EXCEPTION_HANDLER
  189. return retval;
  190. }
  191. /*****************************************************************************
  192. * Startup / Init
  193. *****************************************************************************/
  194. static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
  195. {
  196. set_allowed_options(&allowed_options);
  197. return cmd_args->parseCommandLine(argc, argv, allowed_options);
  198. }
  199. static void set_allowed_options(OptionList *allowed_options)
  200. {
  201. allowed_options->clear();
  202. allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
  203. _("Show allowed options"))));
  204. allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
  205. _("Show version information"))));
  206. allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
  207. _("Load configuration from specified file"))));
  208. allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
  209. _("Set network port (UDP)"))));
  210. allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
  211. _("Run the unit tests and exit"))));
  212. allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
  213. _("Same as --world (deprecated)"))));
  214. allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
  215. _("Set world path (implies local game if used with option --go)"))));
  216. allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
  217. _("Set world by name (implies local game if used with option --go)"))));
  218. allowed_options->insert(std::make_pair("worldlist", ValueSpec(VALUETYPE_STRING,
  219. _("Get list of worlds ('path' lists paths, "
  220. "'name' lists names, 'both' lists both)"))));
  221. allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
  222. _("Print to console errors only"))));
  223. allowed_options->insert(std::make_pair("color", ValueSpec(VALUETYPE_STRING,
  224. _("Coloured logs ('always', 'never' or 'auto'), defaults to 'auto'"
  225. ))));
  226. allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
  227. _("Print more information to console"))));
  228. allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
  229. _("Print even more information to console"))));
  230. allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
  231. _("Print enormous amounts of information to log and console"))));
  232. allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
  233. _("Set logfile path ('' = no logging)"))));
  234. allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
  235. _("Set gameid (\"--gameid list\" prints available ones)"))));
  236. allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
  237. _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
  238. allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING,
  239. _("Migrate from current players backend to another (Only works when using minetestserver or with --server)"))));
  240. allowed_options->insert(std::make_pair("migrate-auth", ValueSpec(VALUETYPE_STRING,
  241. _("Migrate from current auth backend to another (Only works when using minetestserver or with --server)"))));
  242. allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
  243. _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
  244. #ifndef SERVER
  245. allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
  246. _("Show available video modes"))));
  247. allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
  248. _("Run speed tests"))));
  249. allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
  250. _("Address to connect to. ('' = local game)"))));
  251. allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
  252. _("Enable random user input, for testing"))));
  253. allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
  254. _("Run dedicated server"))));
  255. allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
  256. _("Set player name"))));
  257. allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
  258. _("Set password"))));
  259. allowed_options->insert(std::make_pair("password-file", ValueSpec(VALUETYPE_STRING,
  260. _("Set password from contents of file"))));
  261. allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
  262. _("Disable main menu"))));
  263. allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
  264. _("Starts with the console (Windows only)"))));
  265. #endif
  266. }
  267. static void print_help(const OptionList &allowed_options)
  268. {
  269. std::cout << _("Allowed options:") << std::endl;
  270. print_allowed_options(allowed_options);
  271. }
  272. static void print_allowed_options(const OptionList &allowed_options)
  273. {
  274. for (const auto &allowed_option : allowed_options) {
  275. std::ostringstream os1(std::ios::binary);
  276. os1 << " --" << allowed_option.first;
  277. if (allowed_option.second.type != VALUETYPE_FLAG)
  278. os1 << _(" <value>");
  279. std::cout << padStringRight(os1.str(), 30);
  280. if (allowed_option.second.help)
  281. std::cout << allowed_option.second.help;
  282. std::cout << std::endl;
  283. }
  284. }
  285. static void print_version()
  286. {
  287. std::cout << PROJECT_NAME_C " " << g_version_hash
  288. << " (" << porting::getPlatformName() << ")" << std::endl;
  289. #ifndef SERVER
  290. std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl;
  291. #endif
  292. std::cout << g_build_info << std::endl;
  293. }
  294. static void list_game_ids()
  295. {
  296. std::set<std::string> gameids = getAvailableGameIds();
  297. for (const std::string &gameid : gameids)
  298. std::cout << gameid <<std::endl;
  299. }
  300. static void list_worlds(bool print_name, bool print_path)
  301. {
  302. std::cout << _("Available worlds:") << std::endl;
  303. std::vector<WorldSpec> worldspecs = getAvailableWorlds();
  304. print_worldspecs(worldspecs, std::cout, print_name, print_path);
  305. }
  306. static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
  307. std::ostream &os, bool print_name, bool print_path)
  308. {
  309. for (const WorldSpec &worldspec : worldspecs) {
  310. std::string name = worldspec.name;
  311. std::string path = worldspec.path;
  312. if (print_name && print_path) {
  313. os << "\t" << name << "\t\t" << path << std::endl;
  314. } else if (print_name) {
  315. os << "\t" << name << std::endl;
  316. } else if (print_path) {
  317. os << "\t" << path << std::endl;
  318. }
  319. }
  320. }
  321. static void print_modified_quicktune_values()
  322. {
  323. bool header_printed = false;
  324. std::vector<std::string> names = getQuicktuneNames();
  325. for (const std::string &name : names) {
  326. QuicktuneValue val = getQuicktuneValue(name);
  327. if (!val.modified)
  328. continue;
  329. if (!header_printed) {
  330. dstream << "Modified quicktune values:" << std::endl;
  331. header_printed = true;
  332. }
  333. dstream << name << " = " << val.getString() << std::endl;
  334. }
  335. }
  336. static bool setup_log_params(const Settings &cmd_args)
  337. {
  338. // Quiet mode, print errors only
  339. if (cmd_args.getFlag("quiet")) {
  340. g_logger.removeOutput(&stderr_output);
  341. g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
  342. }
  343. // Coloured log messages (see log.h)
  344. std::string color_mode;
  345. if (cmd_args.exists("color")) {
  346. color_mode = cmd_args.get("color");
  347. #if !defined(_WIN32)
  348. } else {
  349. char *color_mode_env = getenv("MT_LOGCOLOR");
  350. if (color_mode_env)
  351. color_mode = color_mode_env;
  352. #endif
  353. }
  354. if (color_mode != "") {
  355. if (color_mode == "auto") {
  356. Logger::color_mode = LOG_COLOR_AUTO;
  357. } else if (color_mode == "always") {
  358. Logger::color_mode = LOG_COLOR_ALWAYS;
  359. } else if (color_mode == "never") {
  360. Logger::color_mode = LOG_COLOR_NEVER;
  361. } else {
  362. errorstream << "Invalid color mode: " << color_mode << std::endl;
  363. return false;
  364. }
  365. }
  366. // If trace is enabled, enable logging of certain things
  367. if (cmd_args.getFlag("trace")) {
  368. dstream << _("Enabling trace level debug output") << std::endl;
  369. g_logger.setTraceEnabled(true);
  370. dout_con_ptr = &verbosestream; // This is somewhat old
  371. socket_enable_debug_output = true; // Sockets doesn't use log.h
  372. }
  373. // In certain cases, output info level on stderr
  374. if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
  375. cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
  376. g_logger.addOutput(&stderr_output, LL_INFO);
  377. // In certain cases, output verbose level on stderr
  378. if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
  379. g_logger.addOutput(&stderr_output, LL_VERBOSE);
  380. return true;
  381. }
  382. static bool create_userdata_path()
  383. {
  384. bool success;
  385. #ifdef __ANDROID__
  386. if (!fs::PathExists(porting::path_user)) {
  387. success = fs::CreateDir(porting::path_user);
  388. } else {
  389. success = true;
  390. }
  391. porting::copyAssets();
  392. #else
  393. // Create user data directory
  394. success = fs::CreateDir(porting::path_user);
  395. #endif
  396. return success;
  397. }
  398. static bool init_common(const Settings &cmd_args, int argc, char *argv[])
  399. {
  400. startup_message();
  401. set_default_settings(g_settings);
  402. // Initialize sockets
  403. sockets_init();
  404. atexit(sockets_cleanup);
  405. if (!read_config_file(cmd_args))
  406. return false;
  407. init_log_streams(cmd_args);
  408. // Initialize random seed
  409. srand(time(0));
  410. mysrand(time(0));
  411. // Initialize HTTP fetcher
  412. httpfetch_init(g_settings->getS32("curl_parallel_limit"));
  413. init_gettext(porting::path_locale.c_str(),
  414. g_settings->get("language"), argc, argv);
  415. return true;
  416. }
  417. static void startup_message()
  418. {
  419. infostream << PROJECT_NAME << " " << _("with")
  420. << " SER_FMT_VER_HIGHEST_READ="
  421. << (int)SER_FMT_VER_HIGHEST_READ << ", "
  422. << g_build_info << std::endl;
  423. }
  424. static bool read_config_file(const Settings &cmd_args)
  425. {
  426. // Path of configuration file in use
  427. sanity_check(g_settings_path == ""); // Sanity check
  428. if (cmd_args.exists("config")) {
  429. bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
  430. if (!r) {
  431. errorstream << "Could not read configuration from \""
  432. << cmd_args.get("config") << "\"" << std::endl;
  433. return false;
  434. }
  435. g_settings_path = cmd_args.get("config");
  436. } else {
  437. std::vector<std::string> filenames;
  438. filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
  439. // Legacy configuration file location
  440. filenames.push_back(porting::path_user +
  441. DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
  442. #if RUN_IN_PLACE
  443. // Try also from a lower level (to aid having the same configuration
  444. // for many RUN_IN_PLACE installs)
  445. filenames.push_back(porting::path_user +
  446. DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
  447. #endif
  448. for (const std::string &filename : filenames) {
  449. bool r = g_settings->readConfigFile(filename.c_str());
  450. if (r) {
  451. g_settings_path = filename;
  452. break;
  453. }
  454. }
  455. // If no path found, use the first one (menu creates the file)
  456. if (g_settings_path.empty())
  457. g_settings_path = filenames[0];
  458. }
  459. return true;
  460. }
  461. static void init_log_streams(const Settings &cmd_args)
  462. {
  463. std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
  464. if (cmd_args.exists("logfile"))
  465. log_filename = cmd_args.get("logfile");
  466. g_logger.removeOutput(&file_log_output);
  467. std::string conf_loglev = g_settings->get("debug_log_level");
  468. // Old integer format
  469. if (std::isdigit(conf_loglev[0])) {
  470. warningstream << "Deprecated use of debug_log_level with an "
  471. "integer value; please update your configuration." << std::endl;
  472. static const char *lev_name[] =
  473. {"", "error", "action", "info", "verbose"};
  474. int lev_i = atoi(conf_loglev.c_str());
  475. if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
  476. warningstream << "Supplied invalid debug_log_level!"
  477. " Assuming action level." << std::endl;
  478. lev_i = 2;
  479. }
  480. conf_loglev = lev_name[lev_i];
  481. }
  482. if (log_filename.empty() || conf_loglev.empty()) // No logging
  483. return;
  484. LogLevel log_level = Logger::stringToLevel(conf_loglev);
  485. if (log_level == LL_MAX) {
  486. warningstream << "Supplied unrecognized debug_log_level; "
  487. "using maximum." << std::endl;
  488. }
  489. file_log_output.setFile(log_filename,
  490. g_settings->getU64("debug_log_size_max") * 1000000);
  491. g_logger.addOutputMaxLevel(&file_log_output, log_level);
  492. }
  493. static bool game_configure(GameParams *game_params, const Settings &cmd_args)
  494. {
  495. game_configure_port(game_params, cmd_args);
  496. if (!game_configure_world(game_params, cmd_args)) {
  497. errorstream << "No world path specified or found." << std::endl;
  498. return false;
  499. }
  500. game_configure_subgame(game_params, cmd_args);
  501. return true;
  502. }
  503. static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
  504. {
  505. if (cmd_args.exists("port"))
  506. game_params->socket_port = cmd_args.getU16("port");
  507. else
  508. game_params->socket_port = g_settings->getU16("port");
  509. if (game_params->socket_port == 0)
  510. game_params->socket_port = DEFAULT_SERVER_PORT;
  511. }
  512. static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
  513. {
  514. if (get_world_from_cmdline(game_params, cmd_args))
  515. return true;
  516. if (get_world_from_config(game_params, cmd_args))
  517. return true;
  518. return auto_select_world(game_params);
  519. }
  520. static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
  521. {
  522. std::string commanded_world;
  523. // World name
  524. std::string commanded_worldname;
  525. if (cmd_args.exists("worldname"))
  526. commanded_worldname = cmd_args.get("worldname");
  527. // If a world name was specified, convert it to a path
  528. if (!commanded_worldname.empty()) {
  529. // Get information about available worlds
  530. std::vector<WorldSpec> worldspecs = getAvailableWorlds();
  531. bool found = false;
  532. for (const WorldSpec &worldspec : worldspecs) {
  533. std::string name = worldspec.name;
  534. if (name == commanded_worldname) {
  535. dstream << _("Using world specified by --worldname on the "
  536. "command line") << std::endl;
  537. commanded_world = worldspec.path;
  538. found = true;
  539. break;
  540. }
  541. }
  542. if (!found) {
  543. dstream << _("World") << " '" << commanded_worldname
  544. << _("' not available. Available worlds:") << std::endl;
  545. print_worldspecs(worldspecs, dstream);
  546. return false;
  547. }
  548. game_params->world_path = get_clean_world_path(commanded_world);
  549. return !commanded_world.empty();
  550. }
  551. if (cmd_args.exists("world"))
  552. commanded_world = cmd_args.get("world");
  553. else if (cmd_args.exists("map-dir"))
  554. commanded_world = cmd_args.get("map-dir");
  555. else if (cmd_args.exists("nonopt0")) // First nameless argument
  556. commanded_world = cmd_args.get("nonopt0");
  557. game_params->world_path = get_clean_world_path(commanded_world);
  558. return !commanded_world.empty();
  559. }
  560. static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
  561. {
  562. // World directory
  563. std::string commanded_world;
  564. if (g_settings->exists("map-dir"))
  565. commanded_world = g_settings->get("map-dir");
  566. game_params->world_path = get_clean_world_path(commanded_world);
  567. return !commanded_world.empty();
  568. }
  569. static bool auto_select_world(GameParams *game_params)
  570. {
  571. // No world was specified; try to select it automatically
  572. // Get information about available worlds
  573. verbosestream << _("Determining world path") << std::endl;
  574. std::vector<WorldSpec> worldspecs = getAvailableWorlds();
  575. std::string world_path;
  576. // If there is only a single world, use it
  577. if (worldspecs.size() == 1) {
  578. world_path = worldspecs[0].path;
  579. dstream <<_("Automatically selecting world at") << " ["
  580. << world_path << "]" << std::endl;
  581. // If there are multiple worlds, list them
  582. } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
  583. std::cerr << _("Multiple worlds are available.") << std::endl;
  584. std::cerr << _("Please select one using --worldname <name>"
  585. " or --world <path>") << std::endl;
  586. print_worldspecs(worldspecs, std::cerr);
  587. return false;
  588. // If there are no worlds, automatically create a new one
  589. } else {
  590. // This is the ultimate default world path
  591. world_path = porting::path_user + DIR_DELIM + "worlds" +
  592. DIR_DELIM + "world";
  593. infostream << "Creating default world at ["
  594. << world_path << "]" << std::endl;
  595. }
  596. assert(world_path != ""); // Post-condition
  597. game_params->world_path = world_path;
  598. return true;
  599. }
  600. static std::string get_clean_world_path(const std::string &path)
  601. {
  602. const std::string worldmt = "world.mt";
  603. std::string clean_path;
  604. if (path.size() > worldmt.size()
  605. && path.substr(path.size() - worldmt.size()) == worldmt) {
  606. dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
  607. clean_path = path.substr(0, path.size() - worldmt.size());
  608. } else {
  609. clean_path = path;
  610. }
  611. return path;
  612. }
  613. static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
  614. {
  615. bool success;
  616. success = get_game_from_cmdline(game_params, cmd_args);
  617. if (!success)
  618. success = determine_subgame(game_params);
  619. return success;
  620. }
  621. static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
  622. {
  623. SubgameSpec commanded_gamespec;
  624. if (cmd_args.exists("gameid")) {
  625. std::string gameid = cmd_args.get("gameid");
  626. commanded_gamespec = findSubgame(gameid);
  627. if (!commanded_gamespec.isValid()) {
  628. errorstream << "Game \"" << gameid << "\" not found" << std::endl;
  629. return false;
  630. }
  631. dstream << _("Using game specified by --gameid on the command line")
  632. << std::endl;
  633. game_params->game_spec = commanded_gamespec;
  634. return true;
  635. }
  636. return false;
  637. }
  638. static bool determine_subgame(GameParams *game_params)
  639. {
  640. SubgameSpec gamespec;
  641. assert(game_params->world_path != ""); // Pre-condition
  642. verbosestream << _("Determining gameid/gamespec") << std::endl;
  643. // If world doesn't exist
  644. if (!game_params->world_path.empty()
  645. && !getWorldExists(game_params->world_path)) {
  646. // Try to take gamespec from command line
  647. if (game_params->game_spec.isValid()) {
  648. gamespec = game_params->game_spec;
  649. infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
  650. } else { // Otherwise we will be using "minetest"
  651. gamespec = findSubgame(g_settings->get("default_game"));
  652. infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
  653. if (!gamespec.isValid()) {
  654. errorstream << "Subgame specified in default_game ["
  655. << g_settings->get("default_game")
  656. << "] is invalid." << std::endl;
  657. return false;
  658. }
  659. }
  660. } else { // World exists
  661. std::string world_gameid = getWorldGameId(game_params->world_path, false);
  662. // If commanded to use a gameid, do so
  663. if (game_params->game_spec.isValid()) {
  664. gamespec = game_params->game_spec;
  665. if (game_params->game_spec.id != world_gameid) {
  666. warningstream << "Using commanded gameid ["
  667. << gamespec.id << "]" << " instead of world gameid ["
  668. << world_gameid << "]" << std::endl;
  669. }
  670. } else {
  671. // If world contains an embedded game, use it;
  672. // Otherwise find world from local system.
  673. gamespec = findWorldSubgame(game_params->world_path);
  674. infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
  675. }
  676. }
  677. if (!gamespec.isValid()) {
  678. errorstream << "Subgame [" << gamespec.id << "] could not be found."
  679. << std::endl;
  680. return false;
  681. }
  682. game_params->game_spec = gamespec;
  683. return true;
  684. }
  685. /*****************************************************************************
  686. * Dedicated server
  687. *****************************************************************************/
  688. static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
  689. {
  690. verbosestream << _("Using world path") << " ["
  691. << game_params.world_path << "]" << std::endl;
  692. verbosestream << _("Using gameid") << " ["
  693. << game_params.game_spec.id << "]" << std::endl;
  694. // Bind address
  695. std::string bind_str = g_settings->get("bind_address");
  696. Address bind_addr(0, 0, 0, 0, game_params.socket_port);
  697. if (g_settings->getBool("ipv6_server")) {
  698. bind_addr.setAddress((IPv6AddressBytes*) NULL);
  699. }
  700. try {
  701. bind_addr.Resolve(bind_str.c_str());
  702. } catch (ResolveError &e) {
  703. infostream << "Resolving bind address \"" << bind_str
  704. << "\" failed: " << e.what()
  705. << " -- Listening on all addresses." << std::endl;
  706. }
  707. if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
  708. errorstream << "Unable to listen on "
  709. << bind_addr.serializeString()
  710. << L" because IPv6 is disabled" << std::endl;
  711. return false;
  712. }
  713. // Database migration
  714. if (cmd_args.exists("migrate"))
  715. return migrate_map_database(game_params, cmd_args);
  716. if (cmd_args.exists("migrate-players"))
  717. return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
  718. if (cmd_args.exists("migrate-auth"))
  719. return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);
  720. if (cmd_args.exists("terminal")) {
  721. #if USE_CURSES
  722. bool name_ok = true;
  723. std::string admin_nick = g_settings->get("name");
  724. name_ok = name_ok && !admin_nick.empty();
  725. name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
  726. if (!name_ok) {
  727. if (admin_nick.empty()) {
  728. errorstream << "No name given for admin. "
  729. << "Please check your minetest.conf that it "
  730. << "contains a 'name = ' to your main admin account."
  731. << std::endl;
  732. } else {
  733. errorstream << "Name for admin '"
  734. << admin_nick << "' is not valid. "
  735. << "Please check that it only contains allowed characters. "
  736. << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
  737. << std::endl;
  738. }
  739. return false;
  740. }
  741. ChatInterface iface;
  742. bool &kill = *porting::signal_handler_killstatus();
  743. try {
  744. // Create server
  745. Server server(game_params.world_path, game_params.game_spec,
  746. false, bind_addr, true, &iface);
  747. server.init();
  748. g_term_console.setup(&iface, &kill, admin_nick);
  749. g_term_console.start();
  750. server.start();
  751. // Run server
  752. dedicated_server_loop(server, kill);
  753. } catch (const ModError &e) {
  754. g_term_console.stopAndWaitforThread();
  755. errorstream << "ModError: " << e.what() << std::endl;
  756. return false;
  757. } catch (const ServerError &e) {
  758. g_term_console.stopAndWaitforThread();
  759. errorstream << "ServerError: " << e.what() << std::endl;
  760. return false;
  761. }
  762. // Tell the console to stop, and wait for it to finish,
  763. // only then leave context and free iface
  764. g_term_console.stop();
  765. g_term_console.wait();
  766. g_term_console.clearKillStatus();
  767. } else {
  768. #else
  769. errorstream << "Cmd arg --terminal passed, but "
  770. << "compiled without ncurses. Ignoring." << std::endl;
  771. } {
  772. #endif
  773. try {
  774. // Create server
  775. Server server(game_params.world_path, game_params.game_spec, false,
  776. bind_addr, true);
  777. server.init();
  778. server.start();
  779. // Run server
  780. bool &kill = *porting::signal_handler_killstatus();
  781. dedicated_server_loop(server, kill);
  782. } catch (const ModError &e) {
  783. errorstream << "ModError: " << e.what() << std::endl;
  784. return false;
  785. } catch (const ServerError &e) {
  786. errorstream << "ServerError: " << e.what() << std::endl;
  787. return false;
  788. }
  789. }
  790. return true;
  791. }
  792. static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
  793. {
  794. std::string migrate_to = cmd_args.get("migrate");
  795. Settings world_mt;
  796. std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
  797. if (!world_mt.readConfigFile(world_mt_path.c_str())) {
  798. errorstream << "Cannot read world.mt!" << std::endl;
  799. return false;
  800. }
  801. if (!world_mt.exists("backend")) {
  802. errorstream << "Please specify your current backend in world.mt:"
  803. << std::endl
  804. << " backend = {sqlite3|leveldb|redis|dummy|postgresql}"
  805. << std::endl;
  806. return false;
  807. }
  808. std::string backend = world_mt.get("backend");
  809. if (backend == migrate_to) {
  810. errorstream << "Cannot migrate: new backend is same"
  811. << " as the old one" << std::endl;
  812. return false;
  813. }
  814. MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
  815. *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
  816. u32 count = 0;
  817. time_t last_update_time = 0;
  818. bool &kill = *porting::signal_handler_killstatus();
  819. std::vector<v3s16> blocks;
  820. old_db->listAllLoadableBlocks(blocks);
  821. new_db->beginSave();
  822. for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
  823. if (kill) return false;
  824. std::string data;
  825. old_db->loadBlock(*it, &data);
  826. if (!data.empty()) {
  827. new_db->saveBlock(*it, data);
  828. } else {
  829. errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
  830. }
  831. if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
  832. std::cerr << " Migrated " << count << " blocks, "
  833. << (100.0 * count / blocks.size()) << "% completed.\r";
  834. new_db->endSave();
  835. new_db->beginSave();
  836. last_update_time = time(NULL);
  837. }
  838. }
  839. std::cerr << std::endl;
  840. new_db->endSave();
  841. delete old_db;
  842. delete new_db;
  843. actionstream << "Successfully migrated " << count << " blocks" << std::endl;
  844. world_mt.set("backend", migrate_to);
  845. if (!world_mt.updateConfigFile(world_mt_path.c_str()))
  846. errorstream << "Failed to update world.mt!" << std::endl;
  847. else
  848. actionstream << "world.mt updated" << std::endl;
  849. return true;
  850. }