]> git.lizzy.rs Git - dragonfireclient.git/blob - src/main.cpp
Improve lighting of entities.
[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         // If trace is enabled, enable logging of certain things
457         if (cmd_args.getFlag("trace")) {
458                 dstream << _("Enabling trace level debug output") << std::endl;
459                 g_logger.setTraceEnabled(true);
460                 dout_con_ptr = &verbosestream; // This is somewhat old
461                 socket_enable_debug_output = true; // Sockets doesn't use log.h
462         }
463
464         // In certain cases, output info level on stderr
465         if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
466                         cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
467                 g_logger.addOutput(&stderr_output, LL_INFO);
468
469         // In certain cases, output verbose level on stderr
470         if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
471                 g_logger.addOutput(&stderr_output, LL_VERBOSE);
472
473         return true;
474 }
475
476 static bool create_userdata_path()
477 {
478         bool success;
479
480 #ifdef __ANDROID__
481         if (!fs::PathExists(porting::path_user)) {
482                 success = fs::CreateDir(porting::path_user);
483         } else {
484                 success = true;
485         }
486 #else
487         // Create user data directory
488         success = fs::CreateDir(porting::path_user);
489 #endif
490
491         return success;
492 }
493
494 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
495 {
496         startup_message();
497         set_default_settings();
498
499         sockets_init();
500
501         // Initialize g_settings
502         Settings::createLayer(SL_GLOBAL);
503
504         // Set cleanup callback(s) to run at process exit
505         atexit(uninit_common);
506
507         if (!read_config_file(cmd_args))
508                 return false;
509
510         init_log_streams(cmd_args);
511
512         // Initialize random seed
513         srand(time(0));
514         mysrand(time(0));
515
516         // Initialize HTTP fetcher
517         httpfetch_init(g_settings->getS32("curl_parallel_limit"));
518
519         init_gettext(porting::path_locale.c_str(),
520                 g_settings->get("language"), argc, argv);
521
522         return true;
523 }
524
525 static void uninit_common()
526 {
527         httpfetch_cleanup();
528
529         sockets_cleanup();
530
531         // It'd actually be okay to leak these but we want to please valgrind...
532         for (int i = 0; i < (int)SL_TOTAL_COUNT; i++)
533                 delete Settings::getLayer((SettingsLayer)i);
534 }
535
536 static void startup_message()
537 {
538         infostream << PROJECT_NAME << " " << _("with")
539                    << " SER_FMT_VER_HIGHEST_READ="
540                << (int)SER_FMT_VER_HIGHEST_READ << ", "
541                << g_build_info << std::endl;
542 }
543
544 static bool read_config_file(const Settings &cmd_args)
545 {
546         // Path of configuration file in use
547         sanity_check(g_settings_path == "");    // Sanity check
548
549         if (cmd_args.exists("config")) {
550                 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
551                 if (!r) {
552                         errorstream << "Could not read configuration from \""
553                                     << cmd_args.get("config") << "\"" << std::endl;
554                         return false;
555                 }
556                 g_settings_path = cmd_args.get("config");
557         } else {
558                 std::vector<std::string> filenames;
559                 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
560                 // Legacy configuration file location
561                 filenames.push_back(porting::path_user +
562                                 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
563
564 #if RUN_IN_PLACE
565                 // Try also from a lower level (to aid having the same configuration
566                 // for many RUN_IN_PLACE installs)
567                 filenames.push_back(porting::path_user +
568                                 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
569 #endif
570
571                 for (const std::string &filename : filenames) {
572                         bool r = g_settings->readConfigFile(filename.c_str());
573                         if (r) {
574                                 g_settings_path = filename;
575                                 break;
576                         }
577                 }
578
579                 // If no path found, use the first one (menu creates the file)
580                 if (g_settings_path.empty())
581                         g_settings_path = filenames[0];
582         }
583
584         return true;
585 }
586
587 static void init_log_streams(const Settings &cmd_args)
588 {
589         std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
590
591         if (cmd_args.exists("logfile"))
592                 log_filename = cmd_args.get("logfile");
593
594         g_logger.removeOutput(&file_log_output);
595         std::string conf_loglev = g_settings->get("debug_log_level");
596
597         // Old integer format
598         if (std::isdigit(conf_loglev[0])) {
599                 warningstream << "Deprecated use of debug_log_level with an "
600                         "integer value; please update your configuration." << std::endl;
601                 static const char *lev_name[] =
602                         {"", "error", "action", "info", "verbose"};
603                 int lev_i = atoi(conf_loglev.c_str());
604                 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
605                         warningstream << "Supplied invalid debug_log_level!"
606                                 "  Assuming action level." << std::endl;
607                         lev_i = 2;
608                 }
609                 conf_loglev = lev_name[lev_i];
610         }
611
612         if (log_filename.empty() || conf_loglev.empty())  // No logging
613                 return;
614
615         LogLevel log_level = Logger::stringToLevel(conf_loglev);
616         if (log_level == LL_MAX) {
617                 warningstream << "Supplied unrecognized debug_log_level; "
618                         "using maximum." << std::endl;
619         }
620
621         file_log_output.setFile(log_filename,
622                 g_settings->getU64("debug_log_size_max") * 1000000);
623         g_logger.addOutputMaxLevel(&file_log_output, log_level);
624 }
625
626 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
627 {
628         game_configure_port(game_params, cmd_args);
629
630         if (!game_configure_world(game_params, cmd_args)) {
631                 errorstream << "No world path specified or found." << std::endl;
632                 return false;
633         }
634
635         game_configure_subgame(game_params, cmd_args);
636
637         return true;
638 }
639
640 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
641 {
642         if (cmd_args.exists("port")) {
643                 game_params->socket_port = cmd_args.getU16("port");
644         } else {
645                 if (game_params->is_dedicated_server)
646                         game_params->socket_port = g_settings->getU16("port");
647                 else
648                         game_params->socket_port = g_settings->getU16("remote_port");
649         }
650
651         if (game_params->socket_port == 0)
652                 game_params->socket_port = DEFAULT_SERVER_PORT;
653 }
654
655 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
656 {
657         if (get_world_from_cmdline(game_params, cmd_args))
658                 return true;
659
660         if (get_world_from_config(game_params, cmd_args))
661                 return true;
662
663         return auto_select_world(game_params);
664 }
665
666 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
667 {
668         std::string commanded_world;
669
670         // World name
671         std::string commanded_worldname;
672         if (cmd_args.exists("worldname"))
673                 commanded_worldname = cmd_args.get("worldname");
674
675         // If a world name was specified, convert it to a path
676         if (!commanded_worldname.empty()) {
677                 // Get information about available worlds
678                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
679                 bool found = false;
680                 for (const WorldSpec &worldspec : worldspecs) {
681                         std::string name = worldspec.name;
682                         if (name == commanded_worldname) {
683                                 dstream << _("Using world specified by --worldname on the "
684                                         "command line") << std::endl;
685                                 commanded_world = worldspec.path;
686                                 found = true;
687                                 break;
688                         }
689                 }
690                 if (!found) {
691                         dstream << _("World") << " '" << commanded_worldname
692                                 << _("' not available. Available worlds:") << std::endl;
693                         print_worldspecs(worldspecs, dstream);
694                         return false;
695                 }
696
697                 game_params->world_path = get_clean_world_path(commanded_world);
698                 return !commanded_world.empty();
699         }
700
701         if (cmd_args.exists("world"))
702                 commanded_world = cmd_args.get("world");
703         else if (cmd_args.exists("map-dir"))
704                 commanded_world = cmd_args.get("map-dir");
705         else if (cmd_args.exists("nonopt0")) // First nameless argument
706                 commanded_world = cmd_args.get("nonopt0");
707
708         game_params->world_path = get_clean_world_path(commanded_world);
709         return !commanded_world.empty();
710 }
711
712 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
713 {
714         // World directory
715         std::string commanded_world;
716
717         if (g_settings->exists("map-dir"))
718                 commanded_world = g_settings->get("map-dir");
719
720         game_params->world_path = get_clean_world_path(commanded_world);
721
722         return !commanded_world.empty();
723 }
724
725 static bool auto_select_world(GameParams *game_params)
726 {
727         // No world was specified; try to select it automatically
728         // Get information about available worlds
729
730         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
731         std::string world_path;
732
733         // If there is only a single world, use it
734         if (worldspecs.size() == 1) {
735                 world_path = worldspecs[0].path;
736                 dstream <<_("Automatically selecting world at") << " ["
737                         << world_path << "]" << std::endl;
738         // If there are multiple worlds, list them
739         } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
740                 std::cerr << _("Multiple worlds are available.") << std::endl;
741                 std::cerr << _("Please select one using --worldname <name>"
742                                 " or --world <path>") << std::endl;
743                 print_worldspecs(worldspecs, std::cerr);
744                 return false;
745         // If there are no worlds, automatically create a new one
746         } else {
747                 // This is the ultimate default world path
748                 world_path = porting::path_user + DIR_DELIM + "worlds" +
749                                 DIR_DELIM + "world";
750                 infostream << "Using default world at ["
751                            << world_path << "]" << std::endl;
752         }
753
754         assert(world_path != "");       // Post-condition
755         game_params->world_path = world_path;
756         return true;
757 }
758
759 static std::string get_clean_world_path(const std::string &path)
760 {
761         const std::string worldmt = "world.mt";
762         std::string clean_path;
763
764         if (path.size() > worldmt.size()
765                         && path.substr(path.size() - worldmt.size()) == worldmt) {
766                 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
767                 clean_path = path.substr(0, path.size() - worldmt.size());
768         } else {
769                 clean_path = path;
770         }
771         return path;
772 }
773
774
775 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
776 {
777         bool success;
778
779         success = get_game_from_cmdline(game_params, cmd_args);
780         if (!success)
781                 success = determine_subgame(game_params);
782
783         return success;
784 }
785
786 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
787 {
788         SubgameSpec commanded_gamespec;
789
790         if (cmd_args.exists("gameid")) {
791                 std::string gameid = cmd_args.get("gameid");
792                 commanded_gamespec = findSubgame(gameid);
793                 if (!commanded_gamespec.isValid()) {
794                         errorstream << "Game \"" << gameid << "\" not found" << std::endl;
795                         return false;
796                 }
797                 dstream << _("Using game specified by --gameid on the command line")
798                         << std::endl;
799                 game_params->game_spec = commanded_gamespec;
800                 return true;
801         }
802
803         return false;
804 }
805
806 static bool determine_subgame(GameParams *game_params)
807 {
808         SubgameSpec gamespec;
809
810         assert(game_params->world_path != "");  // Pre-condition
811
812         // If world doesn't exist
813         if (!game_params->world_path.empty()
814                 && !getWorldExists(game_params->world_path)) {
815                 // Try to take gamespec from command line
816                 if (game_params->game_spec.isValid()) {
817                         gamespec = game_params->game_spec;
818                         infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
819                 } else { // Otherwise we will be using "minetest"
820                         gamespec = findSubgame(g_settings->get("default_game"));
821                         infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
822                         if (!gamespec.isValid()) {
823                                 errorstream << "Game specified in default_game ["
824                                             << g_settings->get("default_game")
825                                             << "] is invalid." << std::endl;
826                                 return false;
827                         }
828                 }
829         } else { // World exists
830                 std::string world_gameid = getWorldGameId(game_params->world_path, false);
831                 // If commanded to use a gameid, do so
832                 if (game_params->game_spec.isValid()) {
833                         gamespec = game_params->game_spec;
834                         if (game_params->game_spec.id != world_gameid) {
835                                 warningstream << "Using commanded gameid ["
836                                             << gamespec.id << "]" << " instead of world gameid ["
837                                             << world_gameid << "]" << std::endl;
838                         }
839                 } else {
840                         // If world contains an embedded game, use it;
841                         // Otherwise find world from local system.
842                         gamespec = findWorldSubgame(game_params->world_path);
843                         infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
844                 }
845         }
846
847         if (!gamespec.isValid()) {
848                 errorstream << "Game [" << gamespec.id << "] could not be found."
849                             << std::endl;
850                 return false;
851         }
852
853         game_params->game_spec = gamespec;
854         return true;
855 }
856
857
858 /*****************************************************************************
859  * Dedicated server
860  *****************************************************************************/
861 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
862 {
863         verbosestream << _("Using world path") << " ["
864                       << game_params.world_path << "]" << std::endl;
865         verbosestream << _("Using gameid") << " ["
866                       << game_params.game_spec.id << "]" << std::endl;
867
868         // Bind address
869         std::string bind_str = g_settings->get("bind_address");
870         Address bind_addr(0, 0, 0, 0, game_params.socket_port);
871
872         if (g_settings->getBool("ipv6_server")) {
873                 bind_addr.setAddress((IPv6AddressBytes*) NULL);
874         }
875         try {
876                 bind_addr.Resolve(bind_str.c_str());
877         } catch (ResolveError &e) {
878                 infostream << "Resolving bind address \"" << bind_str
879                            << "\" failed: " << e.what()
880                            << " -- Listening on all addresses." << std::endl;
881         }
882         if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
883                 errorstream << "Unable to listen on "
884                             << bind_addr.serializeString()
885                             << L" because IPv6 is disabled" << std::endl;
886                 return false;
887         }
888
889         // Database migration/compression
890         if (cmd_args.exists("migrate"))
891                 return migrate_map_database(game_params, cmd_args);
892
893         if (cmd_args.exists("migrate-players"))
894                 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
895
896         if (cmd_args.exists("migrate-auth"))
897                 return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);
898
899         if (cmd_args.exists("migrate-mod-storage"))
900                 return Server::migrateModStorageDatabase(game_params, cmd_args);
901
902         if (cmd_args.getFlag("recompress"))
903                 return recompress_map_database(game_params, cmd_args, bind_addr);
904
905         if (cmd_args.exists("terminal")) {
906 #if USE_CURSES
907                 bool name_ok = true;
908                 std::string admin_nick = g_settings->get("name");
909
910                 name_ok = name_ok && !admin_nick.empty();
911                 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
912
913                 if (!name_ok) {
914                         if (admin_nick.empty()) {
915                                 errorstream << "No name given for admin. "
916                                         << "Please check your minetest.conf that it "
917                                         << "contains a 'name = ' to your main admin account."
918                                         << std::endl;
919                         } else {
920                                 errorstream << "Name for admin '"
921                                         << admin_nick << "' is not valid. "
922                                         << "Please check that it only contains allowed characters. "
923                                         << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
924                                         << std::endl;
925                         }
926                         return false;
927                 }
928                 ChatInterface iface;
929                 bool &kill = *porting::signal_handler_killstatus();
930
931                 try {
932                         // Create server
933                         Server server(game_params.world_path, game_params.game_spec,
934                                         false, bind_addr, true, &iface);
935
936                         g_term_console.setup(&iface, &kill, admin_nick);
937
938                         g_term_console.start();
939
940                         server.start();
941                         // Run server
942                         dedicated_server_loop(server, kill);
943                 } catch (const ModError &e) {
944                         g_term_console.stopAndWaitforThread();
945                         errorstream << "ModError: " << e.what() << std::endl;
946                         return false;
947                 } catch (const ServerError &e) {
948                         g_term_console.stopAndWaitforThread();
949                         errorstream << "ServerError: " << e.what() << std::endl;
950                         return false;
951                 }
952
953                 // Tell the console to stop, and wait for it to finish,
954                 // only then leave context and free iface
955                 g_term_console.stop();
956                 g_term_console.wait();
957
958                 g_term_console.clearKillStatus();
959         } else {
960 #else
961                 errorstream << "Cmd arg --terminal passed, but "
962                         << "compiled without ncurses. Ignoring." << std::endl;
963         } {
964 #endif
965                 try {
966                         // Create server
967                         Server server(game_params.world_path, game_params.game_spec, false,
968                                 bind_addr, true);
969                         server.start();
970
971                         // Run server
972                         bool &kill = *porting::signal_handler_killstatus();
973                         dedicated_server_loop(server, kill);
974
975                 } catch (const ModError &e) {
976                         errorstream << "ModError: " << e.what() << std::endl;
977                         return false;
978                 } catch (const ServerError &e) {
979                         errorstream << "ServerError: " << e.what() << std::endl;
980                         return false;
981                 }
982         }
983
984         return true;
985 }
986
987 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
988 {
989         std::string migrate_to = cmd_args.get("migrate");
990         Settings world_mt;
991         std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
992         if (!world_mt.readConfigFile(world_mt_path.c_str())) {
993                 errorstream << "Cannot read world.mt!" << std::endl;
994                 return false;
995         }
996
997         if (!world_mt.exists("backend")) {
998                 errorstream << "Please specify your current backend in world.mt:"
999                         << std::endl
1000                         << "    backend = {sqlite3|leveldb|redis|dummy|postgresql}"
1001                         << std::endl;
1002                 return false;
1003         }
1004
1005         std::string backend = world_mt.get("backend");
1006         if (backend == migrate_to) {
1007                 errorstream << "Cannot migrate: new backend is same"
1008                         << " as the old one" << std::endl;
1009                 return false;
1010         }
1011
1012         MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
1013                 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
1014
1015         u32 count = 0;
1016         time_t last_update_time = 0;
1017         bool &kill = *porting::signal_handler_killstatus();
1018
1019         std::vector<v3s16> blocks;
1020         old_db->listAllLoadableBlocks(blocks);
1021         new_db->beginSave();
1022         for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
1023                 if (kill) return false;
1024
1025                 std::string data;
1026                 old_db->loadBlock(*it, &data);
1027                 if (!data.empty()) {
1028                         new_db->saveBlock(*it, data);
1029                 } else {
1030                         errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
1031                 }
1032                 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
1033                         std::cerr << " Migrated " << count << " blocks, "
1034                                 << (100.0 * count / blocks.size()) << "% completed.\r";
1035                         new_db->endSave();
1036                         new_db->beginSave();
1037                         last_update_time = time(NULL);
1038                 }
1039         }
1040         std::cerr << std::endl;
1041         new_db->endSave();
1042         delete old_db;
1043         delete new_db;
1044
1045         actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1046         world_mt.set("backend", migrate_to);
1047         if (!world_mt.updateConfigFile(world_mt_path.c_str()))
1048                 errorstream << "Failed to update world.mt!" << std::endl;
1049         else
1050                 actionstream << "world.mt updated" << std::endl;
1051
1052         return true;
1053 }
1054
1055 static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr)
1056 {
1057         Settings world_mt;
1058         const std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
1059
1060         if (!world_mt.readConfigFile(world_mt_path.c_str())) {
1061                 errorstream << "Cannot read world.mt at " << world_mt_path << std::endl;
1062                 return false;
1063         }
1064         const std::string &backend = world_mt.get("backend");
1065         Server server(game_params.world_path, game_params.game_spec, false, addr, false);
1066         MapDatabase *db = ServerMap::createDatabase(backend, game_params.world_path, world_mt);
1067
1068         u32 count = 0;
1069         u64 last_update_time = 0;
1070         bool &kill = *porting::signal_handler_killstatus();
1071         const u8 serialize_as_ver = SER_FMT_VER_HIGHEST_WRITE;
1072
1073         // This is ok because the server doesn't actually run
1074         std::vector<v3s16> blocks;
1075         db->listAllLoadableBlocks(blocks);
1076         db->beginSave();
1077         std::istringstream iss(std::ios_base::binary);
1078         std::ostringstream oss(std::ios_base::binary);
1079         for (auto it = blocks.begin(); it != blocks.end(); ++it) {
1080                 if (kill) return false;
1081
1082                 std::string data;
1083                 db->loadBlock(*it, &data);
1084                 if (data.empty()) {
1085                         errorstream << "Failed to load block " << PP(*it) << std::endl;
1086                         return false;
1087                 }
1088
1089                 iss.str(data);
1090                 iss.clear();
1091
1092                 MapBlock mb(nullptr, v3s16(0,0,0), &server);
1093                 u8 ver = readU8(iss);
1094                 mb.deSerialize(iss, ver, true);
1095
1096                 oss.str("");
1097                 oss.clear();
1098                 writeU8(oss, serialize_as_ver);
1099                 mb.serialize(oss, serialize_as_ver, true, -1);
1100
1101                 db->saveBlock(*it, oss.str());
1102
1103                 count++;
1104                 if (count % 0xFF == 0 && porting::getTimeS() - last_update_time >= 1) {
1105                         std::cerr << " Recompressed " << count << " blocks, "
1106                                 << (100.0f * count / blocks.size()) << "% completed.\r";
1107                         db->endSave();
1108                         db->beginSave();
1109                         last_update_time = porting::getTimeS();
1110                 }
1111         }
1112         std::cerr << std::endl;
1113         db->endSave();
1114
1115         actionstream << "Done, " << count << " blocks were recompressed." << std::endl;
1116         return true;
1117 }