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