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