main.cpp 29 KB

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