main.cpp 29 KB

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