remove_detached_inventory: Fix segfault during mod load
[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 "client/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 bool 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         if (!setup_log_params(cmd_args))
139                 return 1;
140
141         porting::signal_handler_init();
142
143 #ifdef __ANDROID__
144         porting::initAndroid();
145         porting::initializePathsAndroid();
146 #else
147         porting::initializePaths();
148 #endif
149
150         if (!create_userdata_path()) {
151                 errorstream << "Cannot create user data directory" << std::endl;
152                 return 1;
153         }
154
155         // Debug handler
156         BEGIN_DEBUG_EXCEPTION_HANDLER
157
158         // List gameids if requested
159         if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
160                 list_game_ids();
161                 return 0;
162         }
163
164         // List worlds, world names, and world paths if requested
165         if (cmd_args.exists("worldlist")) {
166                 if (cmd_args.get("worldlist") == "name") {
167                         list_worlds(true, false);
168                 } else if (cmd_args.get("worldlist") == "path") {
169                         list_worlds(false, true);
170                 } else if (cmd_args.get("worldlist") == "both") {
171                         list_worlds(true, true);
172                 } else {
173                         errorstream << "Invalid --worldlist value: "
174                                 << cmd_args.get("worldlist") << std::endl;
175                         return 1; 
176                 }
177                 return 0;
178         }
179
180         if (!init_common(cmd_args, argc, argv))
181                 return 1;
182
183         if (g_settings->getBool("enable_console"))
184                 porting::attachOrCreateConsole();
185
186 #ifndef __ANDROID__
187         // Run unit tests
188         if (cmd_args.getFlag("run-unittests")) {
189                 return run_tests();
190         }
191 #endif
192
193         GameParams game_params;
194 #ifdef SERVER
195         porting::attachOrCreateConsole();
196         game_params.is_dedicated_server = true;
197 #else
198         const bool isServer = cmd_args.getFlag("server");
199         if (isServer)
200                 porting::attachOrCreateConsole();
201         game_params.is_dedicated_server = isServer;
202 #endif
203
204         if (!game_configure(&game_params, cmd_args))
205                 return 1;
206
207         sanity_check(!game_params.world_path.empty());
208
209         infostream << "Using commanded world path ["
210                    << game_params.world_path << "]" << std::endl;
211
212         if (game_params.is_dedicated_server)
213                 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
214
215 #ifndef SERVER
216         ClientLauncher launcher;
217         retval = launcher.run(game_params, cmd_args) ? 0 : 1;
218 #else
219         retval = 0;
220 #endif
221
222         // Update configuration file
223         if (!g_settings_path.empty())
224                 g_settings->updateConfigFile(g_settings_path.c_str());
225
226         print_modified_quicktune_values();
227
228         // Stop httpfetch thread (if started)
229         httpfetch_cleanup();
230
231         END_DEBUG_EXCEPTION_HANDLER
232
233         return retval;
234 }
235
236
237 /*****************************************************************************
238  * Startup / Init
239  *****************************************************************************/
240
241
242 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
243 {
244         set_allowed_options(&allowed_options);
245
246         return cmd_args->parseCommandLine(argc, argv, allowed_options);
247 }
248
249 static void set_allowed_options(OptionList *allowed_options)
250 {
251         allowed_options->clear();
252
253         allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
254                         _("Show allowed options"))));
255         allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
256                         _("Show version information"))));
257         allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
258                         _("Load configuration from specified file"))));
259         allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
260                         _("Set network port (UDP)"))));
261         allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
262                         _("Run the unit tests and exit"))));
263         allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
264                         _("Same as --world (deprecated)"))));
265         allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
266                         _("Set world path (implies local game if used with option --go)"))));
267         allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
268                         _("Set world by name (implies local game if used with option --go)"))));
269         allowed_options->insert(std::make_pair("worldlist", ValueSpec(VALUETYPE_STRING,
270                         _("Get list of worlds ('path' lists paths, "
271                         "'name' lists names, 'both' lists both)"))));
272         allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
273                         _("Print to console errors only"))));
274         allowed_options->insert(std::make_pair("color", ValueSpec(VALUETYPE_STRING,
275                         _("Coloured logs ('always', 'never' or 'auto'), defaults to 'auto'"
276                         ))));
277         allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
278                         _("Print more information to console"))));
279         allowed_options->insert(std::make_pair("verbose",  ValueSpec(VALUETYPE_FLAG,
280                         _("Print even more information to console"))));
281         allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
282                         _("Print enormous amounts of information to log and console"))));
283         allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
284                         _("Set logfile path ('' = no logging)"))));
285         allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
286                         _("Set gameid (\"--gameid list\" prints available ones)"))));
287         allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
288                         _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
289         allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING,
290                 _("Migrate from current players backend to another (Only works when using minetestserver or with --server)"))));
291         allowed_options->insert(std::make_pair("migrate-auth", ValueSpec(VALUETYPE_STRING,
292                 _("Migrate from current auth backend to another (Only works when using minetestserver or with --server)"))));
293         allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
294                         _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
295 #ifndef SERVER
296         allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
297                         _("Show available video modes"))));
298         allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
299                         _("Run speed tests"))));
300         allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
301                         _("Address to connect to. ('' = local game)"))));
302         allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
303                         _("Enable random user input, for testing"))));
304         allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
305                         _("Run dedicated server"))));
306         allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
307                         _("Set player name"))));
308         allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
309                         _("Set password"))));
310         allowed_options->insert(std::make_pair("password-file", ValueSpec(VALUETYPE_STRING,
311                         _("Set password from contents of file"))));
312         allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
313                         _("Disable main menu"))));
314         allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
315                 _("Starts with the console (Windows only)"))));
316 #endif
317
318 }
319
320 static void print_help(const OptionList &allowed_options)
321 {
322         std::cout << _("Allowed options:") << std::endl;
323         print_allowed_options(allowed_options);
324 }
325
326 static void print_allowed_options(const OptionList &allowed_options)
327 {
328         for (const auto &allowed_option : allowed_options) {
329                 std::ostringstream os1(std::ios::binary);
330                 os1 << "  --" << allowed_option.first;
331                 if (allowed_option.second.type != VALUETYPE_FLAG)
332                         os1 << _(" <value>");
333
334                 std::cout << padStringRight(os1.str(), 30);
335
336                 if (allowed_option.second.help)
337                         std::cout << allowed_option.second.help;
338
339                 std::cout << std::endl;
340         }
341 }
342
343 static void print_version()
344 {
345         std::cout << PROJECT_NAME_C " " << g_version_hash
346                 << " (" << porting::getPlatformName() << ")" << std::endl;
347 #ifndef SERVER
348         std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl;
349 #endif
350         std::cout << g_build_info << std::endl;
351 }
352
353 static void list_game_ids()
354 {
355         std::set<std::string> gameids = getAvailableGameIds();
356         for (const std::string &gameid : gameids)
357                 std::cout << gameid <<std::endl;
358 }
359
360 static void list_worlds(bool print_name, bool print_path)
361 {
362         std::cout << _("Available worlds:") << std::endl;
363         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
364         print_worldspecs(worldspecs, std::cout, print_name, print_path);
365 }
366
367 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
368         std::ostream &os, bool print_name, bool print_path)
369 {
370         for (const WorldSpec &worldspec : worldspecs) {
371                 std::string name = worldspec.name;
372                 std::string path = worldspec.path;
373                 if (print_name && print_path) {
374                         os << "\t" << name << "\t\t" << path << std::endl;
375                 } else if (print_name) {
376                         os << "\t" << name << std::endl;
377                 } else if (print_path) {
378                         os << "\t" << path << std::endl;
379                 }
380         }
381 }
382
383 static void print_modified_quicktune_values()
384 {
385         bool header_printed = false;
386         std::vector<std::string> names = getQuicktuneNames();
387
388         for (const std::string &name : names) {
389                 QuicktuneValue val = getQuicktuneValue(name);
390                 if (!val.modified)
391                         continue;
392                 if (!header_printed) {
393                         dstream << "Modified quicktune values:" << std::endl;
394                         header_printed = true;
395                 }
396                 dstream << name << " = " << val.getString() << std::endl;
397         }
398 }
399
400 static bool setup_log_params(const Settings &cmd_args)
401 {
402         // Quiet mode, print errors only
403         if (cmd_args.getFlag("quiet")) {
404                 g_logger.removeOutput(&stderr_output);
405                 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
406         }
407
408         // Coloured log messages (see log.h)
409         std::string color_mode;
410         if (cmd_args.exists("color")) {
411                 color_mode = cmd_args.get("color");
412 #if !defined(_WIN32)
413         } else {
414                 char *color_mode_env = getenv("MT_LOGCOLOR");
415                 if (color_mode_env)
416                         color_mode = color_mode_env;
417 #endif
418         }
419         if (color_mode != "") {
420                 if (color_mode == "auto") {
421                         Logger::color_mode = LOG_COLOR_AUTO;
422                 } else if (color_mode == "always") {
423                         Logger::color_mode = LOG_COLOR_ALWAYS;
424                 } else if (color_mode == "never") {
425                         Logger::color_mode = LOG_COLOR_NEVER;
426                 } else {
427                         errorstream << "Invalid color mode: " << color_mode << std::endl;
428                         return false;
429                 }                       
430         }
431
432         // If trace is enabled, enable logging of certain things
433         if (cmd_args.getFlag("trace")) {
434                 dstream << _("Enabling trace level debug output") << std::endl;
435                 g_logger.setTraceEnabled(true);
436                 dout_con_ptr = &verbosestream; // This is somewhat old
437                 socket_enable_debug_output = true; // Sockets doesn't use log.h
438         }
439
440         // In certain cases, output info level on stderr
441         if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
442                         cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
443                 g_logger.addOutput(&stderr_output, LL_INFO);
444
445         // In certain cases, output verbose level on stderr
446         if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
447                 g_logger.addOutput(&stderr_output, LL_VERBOSE);
448
449         return true;
450 }
451
452 static bool create_userdata_path()
453 {
454         bool success;
455
456 #ifdef __ANDROID__
457         if (!fs::PathExists(porting::path_user)) {
458                 success = fs::CreateDir(porting::path_user);
459         } else {
460                 success = true;
461         }
462         porting::copyAssets();
463 #else
464         // Create user data directory
465         success = fs::CreateDir(porting::path_user);
466 #endif
467
468         return success;
469 }
470
471 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
472 {
473         startup_message();
474         set_default_settings(g_settings);
475
476         // Initialize sockets
477         sockets_init();
478         atexit(sockets_cleanup);
479
480         if (!read_config_file(cmd_args))
481                 return false;
482
483         init_log_streams(cmd_args);
484
485         // Initialize random seed
486         srand(time(0));
487         mysrand(time(0));
488
489         // Initialize HTTP fetcher
490         httpfetch_init(g_settings->getS32("curl_parallel_limit"));
491
492         init_gettext(porting::path_locale.c_str(),
493                 g_settings->get("language"), argc, argv);
494
495         return true;
496 }
497
498 static void startup_message()
499 {
500         infostream << PROJECT_NAME << " " << _("with")
501                    << " SER_FMT_VER_HIGHEST_READ="
502                << (int)SER_FMT_VER_HIGHEST_READ << ", "
503                << g_build_info << std::endl;
504 }
505
506 static bool read_config_file(const Settings &cmd_args)
507 {
508         // Path of configuration file in use
509         sanity_check(g_settings_path == "");    // Sanity check
510
511         if (cmd_args.exists("config")) {
512                 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
513                 if (!r) {
514                         errorstream << "Could not read configuration from \""
515                                     << cmd_args.get("config") << "\"" << std::endl;
516                         return false;
517                 }
518                 g_settings_path = cmd_args.get("config");
519         } else {
520                 std::vector<std::string> filenames;
521                 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
522                 // Legacy configuration file location
523                 filenames.push_back(porting::path_user +
524                                 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
525
526 #if RUN_IN_PLACE
527                 // Try also from a lower level (to aid having the same configuration
528                 // for many RUN_IN_PLACE installs)
529                 filenames.push_back(porting::path_user +
530                                 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
531 #endif
532
533                 for (const std::string &filename : filenames) {
534                         bool r = g_settings->readConfigFile(filename.c_str());
535                         if (r) {
536                                 g_settings_path = filename;
537                                 break;
538                         }
539                 }
540
541                 // If no path found, use the first one (menu creates the file)
542                 if (g_settings_path.empty())
543                         g_settings_path = filenames[0];
544         }
545
546         return true;
547 }
548
549 static void init_log_streams(const Settings &cmd_args)
550 {
551         std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
552
553         if (cmd_args.exists("logfile"))
554                 log_filename = cmd_args.get("logfile");
555
556         g_logger.removeOutput(&file_log_output);
557         std::string conf_loglev = g_settings->get("debug_log_level");
558
559         // Old integer format
560         if (std::isdigit(conf_loglev[0])) {
561                 warningstream << "Deprecated use of debug_log_level with an "
562                         "integer value; please update your configuration." << std::endl;
563                 static const char *lev_name[] =
564                         {"", "error", "action", "info", "verbose"};
565                 int lev_i = atoi(conf_loglev.c_str());
566                 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
567                         warningstream << "Supplied invalid debug_log_level!"
568                                 "  Assuming action level." << std::endl;
569                         lev_i = 2;
570                 }
571                 conf_loglev = lev_name[lev_i];
572         }
573
574         if (log_filename.empty() || conf_loglev.empty())  // No logging
575                 return;
576
577         LogLevel log_level = Logger::stringToLevel(conf_loglev);
578         if (log_level == LL_MAX) {
579                 warningstream << "Supplied unrecognized debug_log_level; "
580                         "using maximum." << std::endl;
581         }
582
583         verbosestream << "log_filename = " << log_filename << std::endl;
584
585         file_log_output.open(log_filename);
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 }