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