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