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