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