]> git.lizzy.rs Git - minetest.git/blob - src/main.cpp
Use a safer implementation of gsub in core.chat_format_message (#9133)
[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 "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                 return run_tests();
191         }
192 #endif
193
194         GameParams game_params;
195 #ifdef SERVER
196         porting::attachOrCreateConsole();
197         game_params.is_dedicated_server = true;
198 #else
199         const bool isServer = cmd_args.getFlag("server");
200         if (isServer)
201                 porting::attachOrCreateConsole();
202         game_params.is_dedicated_server = isServer;
203 #endif
204
205         if (!game_configure(&game_params, cmd_args))
206                 return 1;
207
208         sanity_check(!game_params.world_path.empty());
209
210         infostream << "Using commanded world path ["
211                    << game_params.world_path << "]" << std::endl;
212
213         if (game_params.is_dedicated_server)
214                 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
215
216 #ifndef SERVER
217         ClientLauncher launcher;
218         retval = launcher.run(game_params, cmd_args) ? 0 : 1;
219 #else
220         retval = 0;
221 #endif
222
223         // Update configuration file
224         if (!g_settings_path.empty())
225                 g_settings->updateConfigFile(g_settings_path.c_str());
226
227         print_modified_quicktune_values();
228
229         // Stop httpfetch thread (if started)
230         httpfetch_cleanup();
231
232         END_DEBUG_EXCEPTION_HANDLER
233
234         return retval;
235 }
236
237
238 /*****************************************************************************
239  * Startup / Init
240  *****************************************************************************/
241
242
243 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
244 {
245         set_allowed_options(&allowed_options);
246
247         return cmd_args->parseCommandLine(argc, argv, allowed_options);
248 }
249
250 static void set_allowed_options(OptionList *allowed_options)
251 {
252         allowed_options->clear();
253
254         allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
255                         _("Show allowed options"))));
256         allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
257                         _("Show version information"))));
258         allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
259                         _("Load configuration from specified file"))));
260         allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
261                         _("Set network port (UDP)"))));
262         allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
263                         _("Run the unit tests and exit"))));
264         allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
265                         _("Same as --world (deprecated)"))));
266         allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
267                         _("Set world path (implies local game if used with option --go)"))));
268         allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
269                         _("Set world by name (implies local game if used with option --go)"))));
270         allowed_options->insert(std::make_pair("worldlist", ValueSpec(VALUETYPE_STRING,
271                         _("Get list of worlds ('path' lists paths, "
272                         "'name' lists names, 'both' lists both)"))));
273         allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
274                         _("Print to console errors only"))));
275         allowed_options->insert(std::make_pair("color", ValueSpec(VALUETYPE_STRING,
276                         _("Coloured logs ('always', 'never' or 'auto'), defaults to 'auto'"
277                         ))));
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("migrate-auth", ValueSpec(VALUETYPE_STRING,
293                 _("Migrate from current auth backend to another (Only works when using minetestserver or with --server)"))));
294         allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
295                         _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
296 #ifndef SERVER
297         allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
298                         _("Show available video modes"))));
299         allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
300                         _("Run speed tests"))));
301         allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
302                         _("Address to connect to. ('' = local game)"))));
303         allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
304                         _("Enable random user input, for testing"))));
305         allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
306                         _("Run dedicated server"))));
307         allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
308                         _("Set player name"))));
309         allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
310                         _("Set password"))));
311         allowed_options->insert(std::make_pair("password-file", ValueSpec(VALUETYPE_STRING,
312                         _("Set password from contents of file"))));
313         allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
314                         _("Disable main menu"))));
315         allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
316                 _("Starts with the console (Windows only)"))));
317 #endif
318
319 }
320
321 static void print_help(const OptionList &allowed_options)
322 {
323         std::cout << _("Allowed options:") << std::endl;
324         print_allowed_options(allowed_options);
325 }
326
327 static void print_allowed_options(const OptionList &allowed_options)
328 {
329         for (const auto &allowed_option : allowed_options) {
330                 std::ostringstream os1(std::ios::binary);
331                 os1 << "  --" << allowed_option.first;
332                 if (allowed_option.second.type != VALUETYPE_FLAG)
333                         os1 << _(" <value>");
334
335                 std::cout << padStringRight(os1.str(), 30);
336
337                 if (allowed_option.second.help)
338                         std::cout << allowed_option.second.help;
339
340                 std::cout << std::endl;
341         }
342 }
343
344 static void print_version()
345 {
346         std::cout << PROJECT_NAME_C " " << g_version_hash
347                 << " (" << porting::getPlatformName() << ")" << std::endl;
348 #ifndef SERVER
349         std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl;
350 #endif
351         std::cout << g_build_info << std::endl;
352 }
353
354 static void list_game_ids()
355 {
356         std::set<std::string> gameids = getAvailableGameIds();
357         for (const std::string &gameid : gameids)
358                 std::cout << gameid <<std::endl;
359 }
360
361 static void list_worlds(bool print_name, bool print_path)
362 {
363         std::cout << _("Available worlds:") << std::endl;
364         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
365         print_worldspecs(worldspecs, std::cout, print_name, print_path);
366 }
367
368 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
369         std::ostream &os, bool print_name, bool print_path)
370 {
371         for (const WorldSpec &worldspec : worldspecs) {
372                 std::string name = worldspec.name;
373                 std::string path = worldspec.path;
374                 if (print_name && print_path) {
375                         os << "\t" << name << "\t\t" << path << std::endl;
376                 } else if (print_name) {
377                         os << "\t" << name << std::endl;
378                 } else if (print_path) {
379                         os << "\t" << path << std::endl;
380                 }
381         }
382 }
383
384 static void print_modified_quicktune_values()
385 {
386         bool header_printed = false;
387         std::vector<std::string> names = getQuicktuneNames();
388
389         for (const std::string &name : names) {
390                 QuicktuneValue val = getQuicktuneValue(name);
391                 if (!val.modified)
392                         continue;
393                 if (!header_printed) {
394                         dstream << "Modified quicktune values:" << std::endl;
395                         header_printed = true;
396                 }
397                 dstream << name << " = " << val.getString() << std::endl;
398         }
399 }
400
401 static bool setup_log_params(const Settings &cmd_args)
402 {
403         // Quiet mode, print errors only
404         if (cmd_args.getFlag("quiet")) {
405                 g_logger.removeOutput(&stderr_output);
406                 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
407         }
408
409         // Coloured log messages (see log.h)
410         std::string color_mode;
411         if (cmd_args.exists("color")) {
412                 color_mode = cmd_args.get("color");
413 #if !defined(_WIN32)
414         } else {
415                 char *color_mode_env = getenv("MT_LOGCOLOR");
416                 if (color_mode_env)
417                         color_mode = color_mode_env;
418 #endif
419         }
420         if (color_mode != "") {
421                 if (color_mode == "auto") {
422                         Logger::color_mode = LOG_COLOR_AUTO;
423                 } else if (color_mode == "always") {
424                         Logger::color_mode = LOG_COLOR_ALWAYS;
425                 } else if (color_mode == "never") {
426                         Logger::color_mode = LOG_COLOR_NEVER;
427                 } else {
428                         errorstream << "Invalid color mode: " << color_mode << std::endl;
429                         return false;
430                 }
431         }
432
433         // If trace is enabled, enable logging of certain things
434         if (cmd_args.getFlag("trace")) {
435                 dstream << _("Enabling trace level debug output") << std::endl;
436                 g_logger.setTraceEnabled(true);
437                 dout_con_ptr = &verbosestream; // This is somewhat old
438                 socket_enable_debug_output = true; // Sockets doesn't use log.h
439         }
440
441         // In certain cases, output info level on stderr
442         if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
443                         cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
444                 g_logger.addOutput(&stderr_output, LL_INFO);
445
446         // In certain cases, output verbose level on stderr
447         if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
448                 g_logger.addOutput(&stderr_output, LL_VERBOSE);
449
450         return true;
451 }
452
453 static bool create_userdata_path()
454 {
455         bool success;
456
457 #ifdef __ANDROID__
458         if (!fs::PathExists(porting::path_user)) {
459                 success = fs::CreateDir(porting::path_user);
460         } else {
461                 success = true;
462         }
463         porting::copyAssets();
464 #else
465         // Create user data directory
466         success = fs::CreateDir(porting::path_user);
467 #endif
468
469         return success;
470 }
471
472 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
473 {
474         startup_message();
475         set_default_settings(g_settings);
476
477         // Initialize sockets
478         sockets_init();
479         atexit(sockets_cleanup);
480
481         if (!read_config_file(cmd_args))
482                 return false;
483
484         init_log_streams(cmd_args);
485
486         // Initialize random seed
487         srand(time(0));
488         mysrand(time(0));
489
490         // Initialize HTTP fetcher
491         httpfetch_init(g_settings->getS32("curl_parallel_limit"));
492
493         init_gettext(porting::path_locale.c_str(),
494                 g_settings->get("language"), argc, argv);
495
496         return true;
497 }
498
499 static void startup_message()
500 {
501         infostream << PROJECT_NAME << " " << _("with")
502                    << " SER_FMT_VER_HIGHEST_READ="
503                << (int)SER_FMT_VER_HIGHEST_READ << ", "
504                << g_build_info << std::endl;
505 }
506
507 static bool read_config_file(const Settings &cmd_args)
508 {
509         // Path of configuration file in use
510         sanity_check(g_settings_path == "");    // Sanity check
511
512         if (cmd_args.exists("config")) {
513                 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
514                 if (!r) {
515                         errorstream << "Could not read configuration from \""
516                                     << cmd_args.get("config") << "\"" << std::endl;
517                         return false;
518                 }
519                 g_settings_path = cmd_args.get("config");
520         } else {
521                 std::vector<std::string> filenames;
522                 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
523                 // Legacy configuration file location
524                 filenames.push_back(porting::path_user +
525                                 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
526
527 #if RUN_IN_PLACE
528                 // Try also from a lower level (to aid having the same configuration
529                 // for many RUN_IN_PLACE installs)
530                 filenames.push_back(porting::path_user +
531                                 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
532 #endif
533
534                 for (const std::string &filename : filenames) {
535                         bool r = g_settings->readConfigFile(filename.c_str());
536                         if (r) {
537                                 g_settings_path = filename;
538                                 break;
539                         }
540                 }
541
542                 // If no path found, use the first one (menu creates the file)
543                 if (g_settings_path.empty())
544                         g_settings_path = filenames[0];
545         }
546
547         return true;
548 }
549
550 static void init_log_streams(const Settings &cmd_args)
551 {
552         std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
553
554         if (cmd_args.exists("logfile"))
555                 log_filename = cmd_args.get("logfile");
556
557         g_logger.removeOutput(&file_log_output);
558         std::string conf_loglev = g_settings->get("debug_log_level");
559
560         // Old integer format
561         if (std::isdigit(conf_loglev[0])) {
562                 warningstream << "Deprecated use of debug_log_level with an "
563                         "integer value; please update your configuration." << std::endl;
564                 static const char *lev_name[] =
565                         {"", "error", "action", "info", "verbose"};
566                 int lev_i = atoi(conf_loglev.c_str());
567                 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
568                         warningstream << "Supplied invalid debug_log_level!"
569                                 "  Assuming action level." << std::endl;
570                         lev_i = 2;
571                 }
572                 conf_loglev = lev_name[lev_i];
573         }
574
575         if (log_filename.empty() || conf_loglev.empty())  // No logging
576                 return;
577
578         LogLevel log_level = Logger::stringToLevel(conf_loglev);
579         if (log_level == LL_MAX) {
580                 warningstream << "Supplied unrecognized debug_log_level; "
581                         "using maximum." << std::endl;
582         }
583
584         file_log_output.setFile(log_filename,
585                 g_settings->getU64("debug_log_size_max") * 1000000);
586         g_logger.addOutputMaxLevel(&file_log_output, log_level);
587 }
588
589 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
590 {
591         game_configure_port(game_params, cmd_args);
592
593         if (!game_configure_world(game_params, cmd_args)) {
594                 errorstream << "No world path specified or found." << std::endl;
595                 return false;
596         }
597
598         game_configure_subgame(game_params, cmd_args);
599
600         return true;
601 }
602
603 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
604 {
605         if (cmd_args.exists("port"))
606                 game_params->socket_port = cmd_args.getU16("port");
607         else
608                 game_params->socket_port = g_settings->getU16("port");
609
610         if (game_params->socket_port == 0)
611                 game_params->socket_port = DEFAULT_SERVER_PORT;
612 }
613
614 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
615 {
616         if (get_world_from_cmdline(game_params, cmd_args))
617                 return true;
618
619         if (get_world_from_config(game_params, cmd_args))
620                 return true;
621
622         return auto_select_world(game_params);
623 }
624
625 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
626 {
627         std::string commanded_world;
628
629         // World name
630         std::string commanded_worldname;
631         if (cmd_args.exists("worldname"))
632                 commanded_worldname = cmd_args.get("worldname");
633
634         // If a world name was specified, convert it to a path
635         if (!commanded_worldname.empty()) {
636                 // Get information about available worlds
637                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
638                 bool found = false;
639                 for (const WorldSpec &worldspec : worldspecs) {
640                         std::string name = worldspec.name;
641                         if (name == commanded_worldname) {
642                                 dstream << _("Using world specified by --worldname on the "
643                                         "command line") << std::endl;
644                                 commanded_world = worldspec.path;
645                                 found = true;
646                                 break;
647                         }
648                 }
649                 if (!found) {
650                         dstream << _("World") << " '" << commanded_worldname
651                                 << _("' not available. Available worlds:") << std::endl;
652                         print_worldspecs(worldspecs, dstream);
653                         return false;
654                 }
655
656                 game_params->world_path = get_clean_world_path(commanded_world);
657                 return !commanded_world.empty();
658         }
659
660         if (cmd_args.exists("world"))
661                 commanded_world = cmd_args.get("world");
662         else if (cmd_args.exists("map-dir"))
663                 commanded_world = cmd_args.get("map-dir");
664         else if (cmd_args.exists("nonopt0")) // First nameless argument
665                 commanded_world = cmd_args.get("nonopt0");
666
667         game_params->world_path = get_clean_world_path(commanded_world);
668         return !commanded_world.empty();
669 }
670
671 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
672 {
673         // World directory
674         std::string commanded_world;
675
676         if (g_settings->exists("map-dir"))
677                 commanded_world = g_settings->get("map-dir");
678
679         game_params->world_path = get_clean_world_path(commanded_world);
680
681         return !commanded_world.empty();
682 }
683
684 static bool auto_select_world(GameParams *game_params)
685 {
686         // No world was specified; try to select it automatically
687         // Get information about available worlds
688
689         verbosestream << _("Determining world path") << std::endl;
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 << "Creating 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         verbosestream << _("Determining gameid/gamespec") << std::endl;
774         // If world doesn't exist
775         if (!game_params->world_path.empty()
776                 && !getWorldExists(game_params->world_path)) {
777                 // Try to take gamespec from command line
778                 if (game_params->game_spec.isValid()) {
779                         gamespec = game_params->game_spec;
780                         infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
781                 } else { // Otherwise we will be using "minetest"
782                         gamespec = findSubgame(g_settings->get("default_game"));
783                         infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
784                         if (!gamespec.isValid()) {
785                                 errorstream << "Subgame specified in default_game ["
786                                             << g_settings->get("default_game")
787                                             << "] is invalid." << std::endl;
788                                 return false;
789                         }
790                 }
791         } else { // World exists
792                 std::string world_gameid = getWorldGameId(game_params->world_path, false);
793                 // If commanded to use a gameid, do so
794                 if (game_params->game_spec.isValid()) {
795                         gamespec = game_params->game_spec;
796                         if (game_params->game_spec.id != world_gameid) {
797                                 warningstream << "Using commanded gameid ["
798                                             << gamespec.id << "]" << " instead of world gameid ["
799                                             << world_gameid << "]" << std::endl;
800                         }
801                 } else {
802                         // If world contains an embedded game, use it;
803                         // Otherwise find world from local system.
804                         gamespec = findWorldSubgame(game_params->world_path);
805                         infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
806                 }
807         }
808
809         if (!gamespec.isValid()) {
810                 errorstream << "Subgame [" << gamespec.id << "] could not be found."
811                             << std::endl;
812                 return false;
813         }
814
815         game_params->game_spec = gamespec;
816         return true;
817 }
818
819
820 /*****************************************************************************
821  * Dedicated server
822  *****************************************************************************/
823 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
824 {
825         verbosestream << _("Using world path") << " ["
826                       << game_params.world_path << "]" << std::endl;
827         verbosestream << _("Using gameid") << " ["
828                       << game_params.game_spec.id << "]" << std::endl;
829
830         // Bind address
831         std::string bind_str = g_settings->get("bind_address");
832         Address bind_addr(0, 0, 0, 0, game_params.socket_port);
833
834         if (g_settings->getBool("ipv6_server")) {
835                 bind_addr.setAddress((IPv6AddressBytes*) NULL);
836         }
837         try {
838                 bind_addr.Resolve(bind_str.c_str());
839         } catch (ResolveError &e) {
840                 infostream << "Resolving bind address \"" << bind_str
841                            << "\" failed: " << e.what()
842                            << " -- Listening on all addresses." << std::endl;
843         }
844         if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
845                 errorstream << "Unable to listen on "
846                             << bind_addr.serializeString()
847                             << L" because IPv6 is disabled" << std::endl;
848                 return false;
849         }
850
851         // Database migration
852         if (cmd_args.exists("migrate"))
853                 return migrate_map_database(game_params, cmd_args);
854
855         if (cmd_args.exists("migrate-players"))
856                 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
857
858         if (cmd_args.exists("migrate-auth"))
859                 return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);
860
861         if (cmd_args.exists("terminal")) {
862 #if USE_CURSES
863                 bool name_ok = true;
864                 std::string admin_nick = g_settings->get("name");
865
866                 name_ok = name_ok && !admin_nick.empty();
867                 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
868
869                 if (!name_ok) {
870                         if (admin_nick.empty()) {
871                                 errorstream << "No name given for admin. "
872                                         << "Please check your minetest.conf that it "
873                                         << "contains a 'name = ' to your main admin account."
874                                         << std::endl;
875                         } else {
876                                 errorstream << "Name for admin '"
877                                         << admin_nick << "' is not valid. "
878                                         << "Please check that it only contains allowed characters. "
879                                         << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
880                                         << std::endl;
881                         }
882                         return false;
883                 }
884                 ChatInterface iface;
885                 bool &kill = *porting::signal_handler_killstatus();
886
887                 try {
888                         // Create server
889                         Server server(game_params.world_path, game_params.game_spec,
890                                         false, bind_addr, true, &iface);
891                         server.init();
892
893                         g_term_console.setup(&iface, &kill, admin_nick);
894
895                         g_term_console.start();
896
897                         server.start();
898                         // Run server
899                         dedicated_server_loop(server, kill);
900                 } catch (const ModError &e) {
901                         g_term_console.stopAndWaitforThread();
902                         errorstream << "ModError: " << e.what() << std::endl;
903                         return false;
904                 } catch (const ServerError &e) {
905                         g_term_console.stopAndWaitforThread();
906                         errorstream << "ServerError: " << e.what() << std::endl;
907                         return false;
908                 }
909
910                 // Tell the console to stop, and wait for it to finish,
911                 // only then leave context and free iface
912                 g_term_console.stop();
913                 g_term_console.wait();
914
915                 g_term_console.clearKillStatus();
916         } else {
917 #else
918                 errorstream << "Cmd arg --terminal passed, but "
919                         << "compiled without ncurses. Ignoring." << std::endl;
920         } {
921 #endif
922                 try {
923                         // Create server
924                         Server server(game_params.world_path, game_params.game_spec, false,
925                                 bind_addr, true);
926                         server.init();
927                         server.start();
928
929                         // Run server
930                         bool &kill = *porting::signal_handler_killstatus();
931                         dedicated_server_loop(server, kill);
932
933                 } catch (const ModError &e) {
934                         errorstream << "ModError: " << e.what() << std::endl;
935                         return false;
936                 } catch (const ServerError &e) {
937                         errorstream << "ServerError: " << e.what() << std::endl;
938                         return false;
939                 }
940         }
941
942         return true;
943 }
944
945 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
946 {
947         std::string migrate_to = cmd_args.get("migrate");
948         Settings world_mt;
949         std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
950         if (!world_mt.readConfigFile(world_mt_path.c_str())) {
951                 errorstream << "Cannot read world.mt!" << std::endl;
952                 return false;
953         }
954
955         if (!world_mt.exists("backend")) {
956                 errorstream << "Please specify your current backend in world.mt:"
957                         << std::endl
958                         << "    backend = {sqlite3|leveldb|redis|dummy|postgresql}"
959                         << std::endl;
960                 return false;
961         }
962
963         std::string backend = world_mt.get("backend");
964         if (backend == migrate_to) {
965                 errorstream << "Cannot migrate: new backend is same"
966                         << " as the old one" << std::endl;
967                 return false;
968         }
969
970         MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
971                 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
972
973         u32 count = 0;
974         time_t last_update_time = 0;
975         bool &kill = *porting::signal_handler_killstatus();
976
977         std::vector<v3s16> blocks;
978         old_db->listAllLoadableBlocks(blocks);
979         new_db->beginSave();
980         for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
981                 if (kill) return false;
982
983                 std::string data;
984                 old_db->loadBlock(*it, &data);
985                 if (!data.empty()) {
986                         new_db->saveBlock(*it, data);
987                 } else {
988                         errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
989                 }
990                 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
991                         std::cerr << " Migrated " << count << " blocks, "
992                                 << (100.0 * count / blocks.size()) << "% completed.\r";
993                         new_db->endSave();
994                         new_db->beginSave();
995                         last_update_time = time(NULL);
996                 }
997         }
998         std::cerr << std::endl;
999         new_db->endSave();
1000         delete old_db;
1001         delete new_db;
1002
1003         actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1004         world_mt.set("backend", migrate_to);
1005         if (!world_mt.updateConfigFile(world_mt_path.c_str()))
1006                 errorstream << "Failed to update world.mt!" << std::endl;
1007         else
1008                 actionstream << "world.mt updated" << std::endl;
1009
1010         return true;
1011 }