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