Replace auth.txt with SQLite auth database (#7279)
[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("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("go", ValueSpec(VALUETYPE_FLAG,
312                         _("Disable main menu"))));
313         allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
314                 _("Starts with the console (Windows only)"))));
315 #endif
316
317 }
318
319 static void print_help(const OptionList &allowed_options)
320 {
321         std::cout << _("Allowed options:") << std::endl;
322         print_allowed_options(allowed_options);
323 }
324
325 static void print_allowed_options(const OptionList &allowed_options)
326 {
327         for (const auto &allowed_option : allowed_options) {
328                 std::ostringstream os1(std::ios::binary);
329                 os1 << "  --" << allowed_option.first;
330                 if (allowed_option.second.type != VALUETYPE_FLAG)
331                         os1 << _(" <value>");
332
333                 std::cout << padStringRight(os1.str(), 30);
334
335                 if (allowed_option.second.help)
336                         std::cout << allowed_option.second.help;
337
338                 std::cout << std::endl;
339         }
340 }
341
342 static void print_version()
343 {
344         std::cout << PROJECT_NAME_C " " << g_version_hash
345                 << " (" << porting::getPlatformName() << ")" << std::endl;
346 #ifndef SERVER
347         std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl;
348 #endif
349         std::cout << g_build_info << std::endl;
350 }
351
352 static void list_game_ids()
353 {
354         std::set<std::string> gameids = getAvailableGameIds();
355         for (const std::string &gameid : gameids)
356                 std::cout << gameid <<std::endl;
357 }
358
359 static void list_worlds(bool print_name, bool print_path)
360 {
361         std::cout << _("Available worlds:") << std::endl;
362         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
363         print_worldspecs(worldspecs, std::cout, print_name, print_path);
364 }
365
366 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
367         std::ostream &os, bool print_name, bool print_path)
368 {
369         for (const WorldSpec &worldspec : worldspecs) {
370                 std::string name = worldspec.name;
371                 std::string path = worldspec.path;
372                 if (print_name && print_path) {
373                         os << "\t" << name << "\t\t" << path << std::endl;
374                 } else if (print_name) {
375                         os << "\t" << name << std::endl;
376                 } else if (print_path) {
377                         os << "\t" << path << std::endl;
378                 }
379         }
380 }
381
382 static void print_modified_quicktune_values()
383 {
384         bool header_printed = false;
385         std::vector<std::string> names = getQuicktuneNames();
386
387         for (const std::string &name : names) {
388                 QuicktuneValue val = getQuicktuneValue(name);
389                 if (!val.modified)
390                         continue;
391                 if (!header_printed) {
392                         dstream << "Modified quicktune values:" << std::endl;
393                         header_printed = true;
394                 }
395                 dstream << name << " = " << val.getString() << std::endl;
396         }
397 }
398
399 static void setup_log_params(const Settings &cmd_args)
400 {
401         // Quiet mode, print errors only
402         if (cmd_args.getFlag("quiet")) {
403                 g_logger.removeOutput(&stderr_output);
404                 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
405         }
406
407         // Coloured log messages (see log.h)
408         if (cmd_args.exists("color")) {
409                 std::string mode = cmd_args.get("color");
410                 if (mode == "auto")
411                         Logger::color_mode = LOG_COLOR_AUTO;
412                 else if (mode == "always")
413                         Logger::color_mode = LOG_COLOR_ALWAYS;
414                 else
415                         Logger::color_mode = LOG_COLOR_NEVER;
416         }
417
418         // If trace is enabled, enable logging of certain things
419         if (cmd_args.getFlag("trace")) {
420                 dstream << _("Enabling trace level debug output") << std::endl;
421                 g_logger.setTraceEnabled(true);
422                 dout_con_ptr = &verbosestream; // This is somewhat old
423                 socket_enable_debug_output = true; // Sockets doesn't use log.h
424         }
425
426         // In certain cases, output info level on stderr
427         if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
428                         cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
429                 g_logger.addOutput(&stderr_output, LL_INFO);
430
431         // In certain cases, output verbose level on stderr
432         if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
433                 g_logger.addOutput(&stderr_output, LL_VERBOSE);
434 }
435
436 static bool create_userdata_path()
437 {
438         bool success;
439
440 #ifdef __ANDROID__
441         if (!fs::PathExists(porting::path_user)) {
442                 success = fs::CreateDir(porting::path_user);
443         } else {
444                 success = true;
445         }
446         porting::copyAssets();
447 #else
448         // Create user data directory
449         success = fs::CreateDir(porting::path_user);
450 #endif
451
452         return success;
453 }
454
455 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
456 {
457         startup_message();
458         set_default_settings(g_settings);
459
460         // Initialize sockets
461         sockets_init();
462         atexit(sockets_cleanup);
463
464         if (!read_config_file(cmd_args))
465                 return false;
466
467         init_log_streams(cmd_args);
468
469         // Initialize random seed
470         srand(time(0));
471         mysrand(time(0));
472
473         // Initialize HTTP fetcher
474         httpfetch_init(g_settings->getS32("curl_parallel_limit"));
475
476         init_gettext(porting::path_locale.c_str(),
477                 g_settings->get("language"), argc, argv);
478
479         return true;
480 }
481
482 static void startup_message()
483 {
484         infostream << PROJECT_NAME << " " << _("with")
485                    << " SER_FMT_VER_HIGHEST_READ="
486                << (int)SER_FMT_VER_HIGHEST_READ << ", "
487                << g_build_info << std::endl;
488 }
489
490 static bool read_config_file(const Settings &cmd_args)
491 {
492         // Path of configuration file in use
493         sanity_check(g_settings_path == "");    // Sanity check
494
495         if (cmd_args.exists("config")) {
496                 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
497                 if (!r) {
498                         errorstream << "Could not read configuration from \""
499                                     << cmd_args.get("config") << "\"" << std::endl;
500                         return false;
501                 }
502                 g_settings_path = cmd_args.get("config");
503         } else {
504                 std::vector<std::string> filenames;
505                 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
506                 // Legacy configuration file location
507                 filenames.push_back(porting::path_user +
508                                 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
509
510 #if RUN_IN_PLACE
511                 // Try also from a lower level (to aid having the same configuration
512                 // for many RUN_IN_PLACE installs)
513                 filenames.push_back(porting::path_user +
514                                 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
515 #endif
516
517                 for (const std::string &filename : filenames) {
518                         bool r = g_settings->readConfigFile(filename.c_str());
519                         if (r) {
520                                 g_settings_path = filename;
521                                 break;
522                         }
523                 }
524
525                 // If no path found, use the first one (menu creates the file)
526                 if (g_settings_path.empty())
527                         g_settings_path = filenames[0];
528         }
529
530         return true;
531 }
532
533 static void init_log_streams(const Settings &cmd_args)
534 {
535 #if RUN_IN_PLACE
536         std::string log_filename = DEBUGFILE;
537 #else
538         std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
539 #endif
540         if (cmd_args.exists("logfile"))
541                 log_filename = cmd_args.get("logfile");
542
543         g_logger.removeOutput(&file_log_output);
544         std::string conf_loglev = g_settings->get("debug_log_level");
545
546         // Old integer format
547         if (std::isdigit(conf_loglev[0])) {
548                 warningstream << "Deprecated use of debug_log_level with an "
549                         "integer value; please update your configuration." << std::endl;
550                 static const char *lev_name[] =
551                         {"", "error", "action", "info", "verbose"};
552                 int lev_i = atoi(conf_loglev.c_str());
553                 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
554                         warningstream << "Supplied invalid debug_log_level!"
555                                 "  Assuming action level." << std::endl;
556                         lev_i = 2;
557                 }
558                 conf_loglev = lev_name[lev_i];
559         }
560
561         if (log_filename.empty() || conf_loglev.empty())  // No logging
562                 return;
563
564         LogLevel log_level = Logger::stringToLevel(conf_loglev);
565         if (log_level == LL_MAX) {
566                 warningstream << "Supplied unrecognized debug_log_level; "
567                         "using maximum." << std::endl;
568         }
569
570         verbosestream << "log_filename = " << log_filename << std::endl;
571
572         file_log_output.open(log_filename);
573         g_logger.addOutputMaxLevel(&file_log_output, log_level);
574 }
575
576 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
577 {
578         game_configure_port(game_params, cmd_args);
579
580         if (!game_configure_world(game_params, cmd_args)) {
581                 errorstream << "No world path specified or found." << std::endl;
582                 return false;
583         }
584
585         game_configure_subgame(game_params, cmd_args);
586
587         return true;
588 }
589
590 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
591 {
592         if (cmd_args.exists("port"))
593                 game_params->socket_port = cmd_args.getU16("port");
594         else
595                 game_params->socket_port = g_settings->getU16("port");
596
597         if (game_params->socket_port == 0)
598                 game_params->socket_port = DEFAULT_SERVER_PORT;
599 }
600
601 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
602 {
603         if (get_world_from_cmdline(game_params, cmd_args))
604                 return true;
605
606         if (get_world_from_config(game_params, cmd_args))
607                 return true;
608
609         return auto_select_world(game_params);
610 }
611
612 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
613 {
614         std::string commanded_world;
615
616         // World name
617         std::string commanded_worldname;
618         if (cmd_args.exists("worldname"))
619                 commanded_worldname = cmd_args.get("worldname");
620
621         // If a world name was specified, convert it to a path
622         if (!commanded_worldname.empty()) {
623                 // Get information about available worlds
624                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
625                 bool found = false;
626                 for (const WorldSpec &worldspec : worldspecs) {
627                         std::string name = worldspec.name;
628                         if (name == commanded_worldname) {
629                                 dstream << _("Using world specified by --worldname on the "
630                                         "command line") << std::endl;
631                                 commanded_world = worldspec.path;
632                                 found = true;
633                                 break;
634                         }
635                 }
636                 if (!found) {
637                         dstream << _("World") << " '" << commanded_worldname
638                                 << _("' not available. Available worlds:") << std::endl;
639                         print_worldspecs(worldspecs, dstream);
640                         return false;
641                 }
642
643                 game_params->world_path = get_clean_world_path(commanded_world);
644                 return !commanded_world.empty();
645         }
646
647         if (cmd_args.exists("world"))
648                 commanded_world = cmd_args.get("world");
649         else if (cmd_args.exists("map-dir"))
650                 commanded_world = cmd_args.get("map-dir");
651         else if (cmd_args.exists("nonopt0")) // First nameless argument
652                 commanded_world = cmd_args.get("nonopt0");
653
654         game_params->world_path = get_clean_world_path(commanded_world);
655         return !commanded_world.empty();
656 }
657
658 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
659 {
660         // World directory
661         std::string commanded_world;
662
663         if (g_settings->exists("map-dir"))
664                 commanded_world = g_settings->get("map-dir");
665
666         game_params->world_path = get_clean_world_path(commanded_world);
667
668         return !commanded_world.empty();
669 }
670
671 static bool auto_select_world(GameParams *game_params)
672 {
673         // No world was specified; try to select it automatically
674         // Get information about available worlds
675
676         verbosestream << _("Determining world path") << std::endl;
677
678         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
679         std::string world_path;
680
681         // If there is only a single world, use it
682         if (worldspecs.size() == 1) {
683                 world_path = worldspecs[0].path;
684                 dstream <<_("Automatically selecting world at") << " ["
685                         << world_path << "]" << std::endl;
686         // If there are multiple worlds, list them
687         } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
688                 std::cerr << _("Multiple worlds are available.") << std::endl;
689                 std::cerr << _("Please select one using --worldname <name>"
690                                 " or --world <path>") << std::endl;
691                 print_worldspecs(worldspecs, std::cerr);
692                 return false;
693         // If there are no worlds, automatically create a new one
694         } else {
695                 // This is the ultimate default world path
696                 world_path = porting::path_user + DIR_DELIM + "worlds" +
697                                 DIR_DELIM + "world";
698                 infostream << "Creating default world at ["
699                            << world_path << "]" << std::endl;
700         }
701
702         assert(world_path != "");       // Post-condition
703         game_params->world_path = world_path;
704         return true;
705 }
706
707 static std::string get_clean_world_path(const std::string &path)
708 {
709         const std::string worldmt = "world.mt";
710         std::string clean_path;
711
712         if (path.size() > worldmt.size()
713                         && path.substr(path.size() - worldmt.size()) == worldmt) {
714                 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
715                 clean_path = path.substr(0, path.size() - worldmt.size());
716         } else {
717                 clean_path = path;
718         }
719         return path;
720 }
721
722
723 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
724 {
725         bool success;
726
727         success = get_game_from_cmdline(game_params, cmd_args);
728         if (!success)
729                 success = determine_subgame(game_params);
730
731         return success;
732 }
733
734 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
735 {
736         SubgameSpec commanded_gamespec;
737
738         if (cmd_args.exists("gameid")) {
739                 std::string gameid = cmd_args.get("gameid");
740                 commanded_gamespec = findSubgame(gameid);
741                 if (!commanded_gamespec.isValid()) {
742                         errorstream << "Game \"" << gameid << "\" not found" << std::endl;
743                         return false;
744                 }
745                 dstream << _("Using game specified by --gameid on the command line")
746                         << std::endl;
747                 game_params->game_spec = commanded_gamespec;
748                 return true;
749         }
750
751         return false;
752 }
753
754 static bool determine_subgame(GameParams *game_params)
755 {
756         SubgameSpec gamespec;
757
758         assert(game_params->world_path != "");  // Pre-condition
759
760         verbosestream << _("Determining gameid/gamespec") << std::endl;
761         // If world doesn't exist
762         if (!game_params->world_path.empty()
763                 && !getWorldExists(game_params->world_path)) {
764                 // Try to take gamespec from command line
765                 if (game_params->game_spec.isValid()) {
766                         gamespec = game_params->game_spec;
767                         infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
768                 } else { // Otherwise we will be using "minetest"
769                         gamespec = findSubgame(g_settings->get("default_game"));
770                         infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
771                         if (!gamespec.isValid()) {
772                                 errorstream << "Subgame specified in default_game ["
773                                             << g_settings->get("default_game")
774                                             << "] is invalid." << std::endl;
775                                 return false;
776                         }
777                 }
778         } else { // World exists
779                 std::string world_gameid = getWorldGameId(game_params->world_path, false);
780                 // If commanded to use a gameid, do so
781                 if (game_params->game_spec.isValid()) {
782                         gamespec = game_params->game_spec;
783                         if (game_params->game_spec.id != world_gameid) {
784                                 warningstream << "Using commanded gameid ["
785                                             << gamespec.id << "]" << " instead of world gameid ["
786                                             << world_gameid << "]" << std::endl;
787                         }
788                 } else {
789                         // If world contains an embedded game, use it;
790                         // Otherwise find world from local system.
791                         gamespec = findWorldSubgame(game_params->world_path);
792                         infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
793                 }
794         }
795
796         if (!gamespec.isValid()) {
797                 errorstream << "Subgame [" << gamespec.id << "] could not be found."
798                             << std::endl;
799                 return false;
800         }
801
802         game_params->game_spec = gamespec;
803         return true;
804 }
805
806
807 /*****************************************************************************
808  * Dedicated server
809  *****************************************************************************/
810 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
811 {
812         verbosestream << _("Using world path") << " ["
813                       << game_params.world_path << "]" << std::endl;
814         verbosestream << _("Using gameid") << " ["
815                       << game_params.game_spec.id << "]" << std::endl;
816
817         // Bind address
818         std::string bind_str = g_settings->get("bind_address");
819         Address bind_addr(0, 0, 0, 0, game_params.socket_port);
820
821         if (g_settings->getBool("ipv6_server")) {
822                 bind_addr.setAddress((IPv6AddressBytes*) NULL);
823         }
824         try {
825                 bind_addr.Resolve(bind_str.c_str());
826         } catch (ResolveError &e) {
827                 infostream << "Resolving bind address \"" << bind_str
828                            << "\" failed: " << e.what()
829                            << " -- Listening on all addresses." << std::endl;
830         }
831         if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
832                 errorstream << "Unable to listen on "
833                             << bind_addr.serializeString()
834                             << L" because IPv6 is disabled" << std::endl;
835                 return false;
836         }
837
838         // Database migration
839         if (cmd_args.exists("migrate"))
840                 return migrate_map_database(game_params, cmd_args);
841
842         if (cmd_args.exists("migrate-players"))
843                 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
844
845         if (cmd_args.exists("migrate-auth"))
846                 return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);
847
848         if (cmd_args.exists("terminal")) {
849 #if USE_CURSES
850                 bool name_ok = true;
851                 std::string admin_nick = g_settings->get("name");
852
853                 name_ok = name_ok && !admin_nick.empty();
854                 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
855
856                 if (!name_ok) {
857                         if (admin_nick.empty()) {
858                                 errorstream << "No name given for admin. "
859                                         << "Please check your minetest.conf that it "
860                                         << "contains a 'name = ' to your main admin account."
861                                         << std::endl;
862                         } else {
863                                 errorstream << "Name for admin '"
864                                         << admin_nick << "' is not valid. "
865                                         << "Please check that it only contains allowed characters. "
866                                         << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
867                                         << std::endl;
868                         }
869                         return false;
870                 }
871                 ChatInterface iface;
872                 bool &kill = *porting::signal_handler_killstatus();
873
874                 try {
875                         // Create server
876                         Server server(game_params.world_path, game_params.game_spec,
877                                         false, bind_addr, true, &iface);
878                         server.init();
879
880                         g_term_console.setup(&iface, &kill, admin_nick);
881
882                         g_term_console.start();
883
884                         server.start();
885                         // Run server
886                         dedicated_server_loop(server, kill);
887                 } catch (const ModError &e) {
888                         g_term_console.stopAndWaitforThread();
889                         errorstream << "ModError: " << e.what() << std::endl;
890                         return false;
891                 } catch (const ServerError &e) {
892                         g_term_console.stopAndWaitforThread();
893                         errorstream << "ServerError: " << e.what() << std::endl;
894                         return false;
895                 }
896
897                 // Tell the console to stop, and wait for it to finish,
898                 // only then leave context and free iface
899                 g_term_console.stop();
900                 g_term_console.wait();
901
902                 g_term_console.clearKillStatus();
903         } else {
904 #else
905                 errorstream << "Cmd arg --terminal passed, but "
906                         << "compiled without ncurses. Ignoring." << std::endl;
907         } {
908 #endif
909                 try {
910                         // Create server
911                         Server server(game_params.world_path, game_params.game_spec, false,
912                                 bind_addr, true);
913                         server.init();
914                         server.start();
915
916                         // Run server
917                         bool &kill = *porting::signal_handler_killstatus();
918                         dedicated_server_loop(server, kill);
919
920                 } catch (const ModError &e) {
921                         errorstream << "ModError: " << e.what() << std::endl;
922                         return false;
923                 } catch (const ServerError &e) {
924                         errorstream << "ServerError: " << e.what() << std::endl;
925                         return false;
926                 }
927         }
928
929         return true;
930 }
931
932 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
933 {
934         std::string migrate_to = cmd_args.get("migrate");
935         Settings world_mt;
936         std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
937         if (!world_mt.readConfigFile(world_mt_path.c_str())) {
938                 errorstream << "Cannot read world.mt!" << std::endl;
939                 return false;
940         }
941
942         if (!world_mt.exists("backend")) {
943                 errorstream << "Please specify your current backend in world.mt:"
944                         << std::endl
945                         << "    backend = {sqlite3|leveldb|redis|dummy|postgresql}"
946                         << std::endl;
947                 return false;
948         }
949
950         std::string backend = world_mt.get("backend");
951         if (backend == migrate_to) {
952                 errorstream << "Cannot migrate: new backend is same"
953                         << " as the old one" << std::endl;
954                 return false;
955         }
956
957         MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
958                 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
959
960         u32 count = 0;
961         time_t last_update_time = 0;
962         bool &kill = *porting::signal_handler_killstatus();
963
964         std::vector<v3s16> blocks;
965         old_db->listAllLoadableBlocks(blocks);
966         new_db->beginSave();
967         for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
968                 if (kill) return false;
969
970                 std::string data;
971                 old_db->loadBlock(*it, &data);
972                 if (!data.empty()) {
973                         new_db->saveBlock(*it, data);
974                 } else {
975                         errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
976                 }
977                 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
978                         std::cerr << " Migrated " << count << " blocks, "
979                                 << (100.0 * count / blocks.size()) << "% completed.\r";
980                         new_db->endSave();
981                         new_db->beginSave();
982                         last_update_time = time(NULL);
983                 }
984         }
985         std::cerr << std::endl;
986         new_db->endSave();
987         delete old_db;
988         delete new_db;
989
990         actionstream << "Successfully migrated " << count << " blocks" << std::endl;
991         world_mt.set("backend", migrate_to);
992         if (!world_mt.updateConfigFile(world_mt_path.c_str()))
993                 errorstream << "Failed to update world.mt!" << std::endl;
994         else
995                 actionstream << "world.mt updated" << std::endl;
996
997         return true;
998 }