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