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