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