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