]> git.lizzy.rs Git - minetest.git/blob - src/main.cpp
e9b320af79d1db391faba7f89090d8b88c45c279
[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 "irrlichttypes.h" // must be included before anything irrlicht, see comment in the file
21 #include "irrlicht.h" // createDevice
22 #include "irrlichttypes_extrabloated.h"
23 #include "benchmark/benchmark.h"
24 #include "chat_interface.h"
25 #include "debug.h"
26 #include "unittest/test.h"
27 #include "server.h"
28 #include "filesys.h"
29 #include "version.h"
30 #include "client/game.h"
31 #include "defaultsettings.h"
32 #include "gettext.h"
33 #include "log.h"
34 #include "util/quicktune.h"
35 #include "httpfetch.h"
36 #include "gameparams.h"
37 #include "database/database.h"
38 #include "config.h"
39 #include "player.h"
40 #include "porting.h"
41 #include "network/socket.h"
42 #include "mapblock.h"
43 #if USE_CURSES
44         #include "terminal_chat_console.h"
45 #endif
46 #ifndef SERVER
47 #include "gui/guiMainMenu.h"
48 #include "client/clientlauncher.h"
49 #include "gui/guiEngine.h"
50 #include "gui/mainmenumanager.h"
51 #endif
52 #ifdef HAVE_TOUCHSCREENGUI
53         #include "gui/touchscreengui.h"
54 #endif
55
56 // for version information only
57 extern "C" {
58 #if USE_LUAJIT
59         #include <luajit.h>
60 #else
61         #include <lua.h>
62 #endif
63 }
64
65 #if !defined(__cpp_rtti) || !defined(__cpp_exceptions)
66 #error Minetest cannot be built without exceptions or RTTI
67 #endif
68
69 #if defined(__MINGW32__) && !defined(__MINGW64__) && !defined(__clang__) && \
70         (__GNUC__ < 11 || (__GNUC__ == 11 && __GNUC_MINOR__ < 1))
71 // see e.g. https://github.com/minetest/minetest/issues/10137
72 #warning ==================================
73 #warning 32-bit MinGW gcc before 11.1 has known issues with crashes on thread exit, you should upgrade.
74 #warning ==================================
75 #endif
76
77 #define DEBUGFILE "debug.txt"
78 #define DEFAULT_SERVER_PORT 30000
79
80 #define ENV_NO_COLOR "NO_COLOR"
81 #define ENV_CLICOLOR "CLICOLOR"
82 #define ENV_CLICOLOR_FORCE "CLICOLOR_FORCE"
83
84 typedef std::map<std::string, ValueSpec> OptionList;
85
86 /**********************************************************************
87  * Private functions
88  **********************************************************************/
89
90 static void get_env_opts(Settings &args);
91 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
92 static void set_allowed_options(OptionList *allowed_options);
93
94 static void print_help(const OptionList &allowed_options);
95 static void print_allowed_options(const OptionList &allowed_options);
96 static void print_version();
97 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
98         std::ostream &os, bool print_name = true, bool print_path = true);
99 static void print_modified_quicktune_values();
100
101 static void list_game_ids();
102 static void list_worlds(bool print_name, bool print_path);
103 static bool setup_log_params(const Settings &cmd_args);
104 static bool create_userdata_path();
105 static bool init_common(const Settings &cmd_args, int argc, char *argv[]);
106 static void uninit_common();
107 static void startup_message();
108 static bool read_config_file(const Settings &cmd_args);
109 static void init_log_streams(const Settings &cmd_args);
110
111 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
112 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
113
114 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
115 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
116 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
117 static bool auto_select_world(GameParams *game_params);
118 static std::string get_clean_world_path(const std::string &path);
119
120 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
121 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
122 static bool determine_subgame(GameParams *game_params);
123
124 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
125 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args);
126 static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr);
127
128 /**********************************************************************/
129
130
131 FileLogOutput file_log_output;
132
133 static OptionList allowed_options;
134
135 int main(int argc, char *argv[])
136 {
137         int retval;
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         get_env_opts(cmd_args);
145         bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
146         if (!cmd_args_ok
147                         || cmd_args.getFlag("help")
148                         || cmd_args.exists("nonopt1")) {
149                 porting::attachOrCreateConsole();
150                 print_help(allowed_options);
151                 return cmd_args_ok ? 0 : 1;
152         }
153         if (cmd_args.getFlag("console"))
154                 porting::attachOrCreateConsole();
155
156         if (cmd_args.getFlag("version")) {
157                 porting::attachOrCreateConsole();
158                 print_version();
159                 return 0;
160         }
161
162         if (!setup_log_params(cmd_args))
163                 return 1;
164
165         porting::signal_handler_init();
166
167 #ifdef __ANDROID__
168         porting::initAndroid();
169         porting::initializePathsAndroid();
170 #else
171         porting::initializePaths();
172 #endif
173
174         if (!create_userdata_path()) {
175                 errorstream << "Cannot create user data directory" << std::endl;
176                 return 1;
177         }
178
179         // Debug handler
180         BEGIN_DEBUG_EXCEPTION_HANDLER
181
182         // List gameids if requested
183         if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
184                 list_game_ids();
185                 return 0;
186         }
187
188         // List worlds, world names, and world paths if requested
189         if (cmd_args.exists("worldlist")) {
190                 if (cmd_args.get("worldlist") == "name") {
191                         list_worlds(true, false);
192                 } else if (cmd_args.get("worldlist") == "path") {
193                         list_worlds(false, true);
194                 } else if (cmd_args.get("worldlist") == "both") {
195                         list_worlds(true, true);
196                 } else {
197                         errorstream << "Invalid --worldlist value: "
198                                 << cmd_args.get("worldlist") << std::endl;
199                         return 1;
200                 }
201                 return 0;
202         }
203
204         if (!init_common(cmd_args, argc, argv))
205                 return 1;
206
207         if (g_settings->getBool("enable_console"))
208                 porting::attachOrCreateConsole();
209
210 #ifndef __ANDROID__
211         // Run unit tests
212         if (cmd_args.getFlag("run-unittests")) {
213 #if BUILD_UNITTESTS
214                 return run_tests();
215 #else
216                 errorstream << "Unittest support is not enabled in this binary. "
217                         << "If you want to enable it, compile project with BUILD_UNITTESTS=1 flag."
218                         << std::endl;
219                 return 1;
220 #endif
221         }
222
223         // Run benchmarks
224         if (cmd_args.getFlag("run-benchmarks")) {
225 #if BUILD_BENCHMARKS
226                 return run_benchmarks();
227 #else
228                 errorstream << "Benchmark support is not enabled in this binary. "
229                         << "If you want to enable it, compile project with BUILD_BENCHMARKS=1 flag."
230                         << std::endl;
231                 return 1;
232 #endif
233         }
234 #endif // __ANDROID__
235
236         GameStartData game_params;
237 #ifdef SERVER
238         porting::attachOrCreateConsole();
239         game_params.is_dedicated_server = true;
240 #else
241         const bool isServer = cmd_args.getFlag("server");
242         if (isServer)
243                 porting::attachOrCreateConsole();
244         game_params.is_dedicated_server = isServer;
245 #endif
246
247         if (!game_configure(&game_params, cmd_args))
248                 return 1;
249
250         sanity_check(!game_params.world_path.empty());
251
252         if (game_params.is_dedicated_server)
253                 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
254
255 #ifndef SERVER
256         retval = ClientLauncher().run(game_params, cmd_args) ? 0 : 1;
257 #else
258         retval = 0;
259 #endif
260
261         // Update configuration file
262         if (!g_settings_path.empty())
263                 g_settings->updateConfigFile(g_settings_path.c_str());
264
265         print_modified_quicktune_values();
266
267         END_DEBUG_EXCEPTION_HANDLER
268
269         return retval;
270 }
271
272
273 /*****************************************************************************
274  * Startup / Init
275  *****************************************************************************/
276
277
278 static void get_env_opts(Settings &args)
279 {
280         // CLICOLOR is a de-facto standard option for colors <https://bixense.com/clicolors/>
281         // CLICOLOR != 0: ANSI colors are supported (auto-detection, this is the default)
282         // CLICOLOR == 0: ANSI colors are NOT supported
283         const char *clicolor = std::getenv(ENV_CLICOLOR);
284         if (clicolor && std::string(clicolor) == "0") {
285                 args.set("color", "never");
286         }
287         // NO_COLOR only specifies that no color is allowed.
288         // Implemented according to <http://no-color.org/>
289         const char *no_color = std::getenv(ENV_NO_COLOR);
290         if (no_color && no_color[0]) {
291                 args.set("color", "never");
292         }
293         // CLICOLOR_FORCE is another option, which should turn on colors "no matter what".
294         const char *clicolor_force = std::getenv(ENV_CLICOLOR_FORCE);
295         if (clicolor_force && std::string(clicolor_force) != "0") {
296                 // should ALWAYS have colors, so we ignore tty (no "auto")
297                 args.set("color", "always");
298         }
299 }
300
301 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
302 {
303         set_allowed_options(&allowed_options);
304
305         return cmd_args->parseCommandLine(argc, argv, allowed_options);
306 }
307
308 static void set_allowed_options(OptionList *allowed_options)
309 {
310         allowed_options->clear();
311
312         allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
313                         _("Show allowed options"))));
314         allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
315                         _("Show version information"))));
316         allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
317                         _("Load configuration from specified file"))));
318         allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
319                         _("Set network port (UDP)"))));
320         allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
321                         _("Run the unit tests and exit"))));
322         allowed_options->insert(std::make_pair("run-benchmarks", ValueSpec(VALUETYPE_FLAG,
323                         _("Run the benchmarks and exit"))));
324         allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
325                         _("Same as --world (deprecated)"))));
326         allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
327                         _("Set world path (implies local game if used with option --go)"))));
328         allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
329                         _("Set world by name (implies local game if used with option --go)"))));
330         allowed_options->insert(std::make_pair("worldlist", ValueSpec(VALUETYPE_STRING,
331                         _("Get list of worlds ('path' lists paths, "
332                         "'name' lists names, 'both' lists both)"))));
333         allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
334                         _("Print to console errors only"))));
335         allowed_options->insert(std::make_pair("color", ValueSpec(VALUETYPE_STRING,
336                         _("Coloured logs ('always', 'never' or 'auto'), defaults to 'auto'"
337                         ))));
338         allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
339                         _("Print more information to console"))));
340         allowed_options->insert(std::make_pair("verbose",  ValueSpec(VALUETYPE_FLAG,
341                         _("Print even more information to console"))));
342         allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
343                         _("Print enormous amounts of information to log and console"))));
344         allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
345                         _("Set logfile path ('' = no logging)"))));
346         allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
347                         _("Set gameid (\"--gameid list\" prints available ones)"))));
348         allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
349                         _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
350         allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING,
351                 _("Migrate from current players backend to another (Only works when using minetestserver or with --server)"))));
352         allowed_options->insert(std::make_pair("migrate-auth", ValueSpec(VALUETYPE_STRING,
353                 _("Migrate from current auth backend to another (Only works when using minetestserver or with --server)"))));
354         allowed_options->insert(std::make_pair("migrate-mod-storage", ValueSpec(VALUETYPE_STRING,
355                 _("Migrate from current mod storage backend to another (Only works when using minetestserver or with --server)"))));
356         allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
357                         _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
358         allowed_options->insert(std::make_pair("recompress", ValueSpec(VALUETYPE_FLAG,
359                         _("Recompress the blocks of the given map database."))));
360 #ifndef SERVER
361         allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
362                         _("Run speed tests"))));
363         allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
364                         _("Address to connect to. ('' = local game)"))));
365         allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
366                         _("Enable random user input, for testing"))));
367         allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
368                         _("Run dedicated server"))));
369         allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
370                         _("Set player name"))));
371         allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
372                         _("Set password"))));
373         allowed_options->insert(std::make_pair("password-file", ValueSpec(VALUETYPE_STRING,
374                         _("Set password from contents of file"))));
375         allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
376                         _("Disable main menu"))));
377         allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
378                 _("Starts with the console (Windows only)"))));
379 #endif
380
381 }
382
383 static void print_help(const OptionList &allowed_options)
384 {
385         std::cout << _("Allowed options:") << std::endl;
386         print_allowed_options(allowed_options);
387 }
388
389 static void print_allowed_options(const OptionList &allowed_options)
390 {
391         for (const auto &allowed_option : allowed_options) {
392                 std::ostringstream os1(std::ios::binary);
393                 os1 << "  --" << allowed_option.first;
394                 if (allowed_option.second.type != VALUETYPE_FLAG)
395                         os1 << _(" <value>");
396
397                 std::cout << padStringRight(os1.str(), 30);
398
399                 if (allowed_option.second.help)
400                         std::cout << allowed_option.second.help;
401
402                 std::cout << std::endl;
403         }
404 }
405
406 static void print_version()
407 {
408         std::cout << PROJECT_NAME_C " " << g_version_hash
409                 << " (" << porting::getPlatformName() << ")" << std::endl;
410 #ifndef SERVER
411         std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl;
412 #endif
413 #if USE_LUAJIT
414         std::cout << "Using " << LUAJIT_VERSION << std::endl;
415 #else
416         std::cout << "Using " << LUA_RELEASE << std::endl;
417 #endif
418         std::cout << g_build_info << std::endl;
419 }
420
421 static void list_game_ids()
422 {
423         std::set<std::string> gameids = getAvailableGameIds();
424         for (const std::string &gameid : gameids)
425                 std::cout << gameid <<std::endl;
426 }
427
428 static void list_worlds(bool print_name, bool print_path)
429 {
430         std::cout << _("Available worlds:") << std::endl;
431         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
432         print_worldspecs(worldspecs, std::cout, print_name, print_path);
433 }
434
435 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
436         std::ostream &os, bool print_name, bool print_path)
437 {
438         for (const WorldSpec &worldspec : worldspecs) {
439                 std::string name = worldspec.name;
440                 std::string path = worldspec.path;
441                 if (print_name && print_path) {
442                         os << "\t" << name << "\t\t" << path << std::endl;
443                 } else if (print_name) {
444                         os << "\t" << name << std::endl;
445                 } else if (print_path) {
446                         os << "\t" << path << std::endl;
447                 }
448         }
449 }
450
451 static void print_modified_quicktune_values()
452 {
453         bool header_printed = false;
454         std::vector<std::string> names = getQuicktuneNames();
455
456         for (const std::string &name : names) {
457                 QuicktuneValue val = getQuicktuneValue(name);
458                 if (!val.modified)
459                         continue;
460                 if (!header_printed) {
461                         dstream << "Modified quicktune values:" << std::endl;
462                         header_printed = true;
463                 }
464                 dstream << name << " = " << val.getString() << std::endl;
465         }
466 }
467
468 static bool setup_log_params(const Settings &cmd_args)
469 {
470         // Quiet mode, print errors only
471         if (cmd_args.getFlag("quiet")) {
472                 g_logger.removeOutput(&stderr_output);
473                 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
474         }
475
476         // Coloured log messages (see log.h)
477         std::string color_mode;
478         if (cmd_args.exists("color")) {
479                 color_mode = cmd_args.get("color");
480 #if !defined(_WIN32)
481         } else {
482                 char *color_mode_env = getenv("MT_LOGCOLOR");
483                 if (color_mode_env)
484                         color_mode = color_mode_env;
485 #endif
486         }
487         if (!color_mode.empty()) {
488                 if (color_mode == "auto") {
489                         Logger::color_mode = LOG_COLOR_AUTO;
490                 } else if (color_mode == "always") {
491                         Logger::color_mode = LOG_COLOR_ALWAYS;
492                 } else if (color_mode == "never") {
493                         Logger::color_mode = LOG_COLOR_NEVER;
494                 } else {
495                         errorstream << "Invalid color mode: " << color_mode << std::endl;
496                         return false;
497                 }
498         }
499
500         // In certain cases, output info level on stderr
501         if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
502                         cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
503                 g_logger.addOutput(&stderr_output, LL_INFO);
504
505         // In certain cases, output verbose level on stderr
506         if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
507                 g_logger.addOutput(&stderr_output, LL_VERBOSE);
508
509         if (cmd_args.getFlag("trace")) {
510                 dstream << _("Enabling trace level debug output") << std::endl;
511                 g_logger.addOutput(&stderr_output, LL_TRACE);
512                 socket_enable_debug_output = true;
513         }
514
515         return true;
516 }
517
518 static bool create_userdata_path()
519 {
520         bool success;
521
522 #ifdef __ANDROID__
523         if (!fs::PathExists(porting::path_user)) {
524                 success = fs::CreateDir(porting::path_user);
525         } else {
526                 success = true;
527         }
528 #else
529         // Create user data directory
530         success = fs::CreateAllDirs(porting::path_user);
531 #endif
532
533         return success;
534 }
535
536 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
537 {
538         startup_message();
539         set_default_settings();
540
541         sockets_init();
542
543         // Initialize g_settings
544         Settings::createLayer(SL_GLOBAL);
545
546         // Set cleanup callback(s) to run at process exit
547         atexit(uninit_common);
548
549         if (!read_config_file(cmd_args))
550                 return false;
551
552         init_log_streams(cmd_args);
553
554         // Initialize random seed
555         srand(time(0));
556         mysrand(time(0));
557
558         // Initialize HTTP fetcher
559         httpfetch_init(g_settings->getS32("curl_parallel_limit"));
560
561         init_gettext(porting::path_locale.c_str(),
562                 g_settings->get("language"), argc, argv);
563
564         return true;
565 }
566
567 static void uninit_common()
568 {
569         httpfetch_cleanup();
570
571         sockets_cleanup();
572
573         // It'd actually be okay to leak these but we want to please valgrind...
574         for (int i = 0; i < (int)SL_TOTAL_COUNT; i++)
575                 delete Settings::getLayer((SettingsLayer)i);
576 }
577
578 static void startup_message()
579 {
580         infostream << PROJECT_NAME << " " << _("with")
581                    << " SER_FMT_VER_HIGHEST_READ="
582                << (int)SER_FMT_VER_HIGHEST_READ << ", "
583                << g_build_info << std::endl;
584 }
585
586 static bool read_config_file(const Settings &cmd_args)
587 {
588         // Path of configuration file in use
589         sanity_check(g_settings_path.empty());  // Sanity check
590
591         if (cmd_args.exists("config")) {
592                 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
593                 if (!r) {
594                         errorstream << "Could not read configuration from \""
595                                     << cmd_args.get("config") << "\"" << std::endl;
596                         return false;
597                 }
598                 g_settings_path = cmd_args.get("config");
599         } else {
600                 std::vector<std::string> filenames;
601                 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
602                 // Legacy configuration file location
603                 filenames.push_back(porting::path_user +
604                                 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
605
606 #if RUN_IN_PLACE
607                 // Try also from a lower level (to aid having the same configuration
608                 // for many RUN_IN_PLACE installs)
609                 filenames.push_back(porting::path_user +
610                                 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
611 #endif
612
613                 for (const std::string &filename : filenames) {
614                         bool r = g_settings->readConfigFile(filename.c_str());
615                         if (r) {
616                                 g_settings_path = filename;
617                                 break;
618                         }
619                 }
620
621                 // If no path found, use the first one (menu creates the file)
622                 if (g_settings_path.empty())
623                         g_settings_path = filenames[0];
624         }
625
626         return true;
627 }
628
629 static void init_log_streams(const Settings &cmd_args)
630 {
631         std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
632
633         if (cmd_args.exists("logfile"))
634                 log_filename = cmd_args.get("logfile");
635
636         g_logger.removeOutput(&file_log_output);
637         std::string conf_loglev = g_settings->get("debug_log_level");
638
639         // Old integer format
640         if (std::isdigit(conf_loglev[0])) {
641                 warningstream << "Deprecated use of debug_log_level with an "
642                         "integer value; please update your configuration." << std::endl;
643                 static const char *lev_name[] =
644                         {"", "error", "action", "info", "verbose", "trace"};
645                 int lev_i = atoi(conf_loglev.c_str());
646                 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
647                         warningstream << "Supplied invalid debug_log_level!"
648                                 "  Assuming action level." << std::endl;
649                         lev_i = 2;
650                 }
651                 conf_loglev = lev_name[lev_i];
652         }
653
654         if (log_filename.empty() || conf_loglev.empty())  // No logging
655                 return;
656
657         LogLevel log_level = Logger::stringToLevel(conf_loglev);
658         if (log_level == LL_MAX) {
659                 warningstream << "Supplied unrecognized debug_log_level; "
660                         "using maximum." << std::endl;
661         }
662
663         file_log_output.setFile(log_filename,
664                 g_settings->getU64("debug_log_size_max") * 1000000);
665         g_logger.addOutputMaxLevel(&file_log_output, log_level);
666 }
667
668 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
669 {
670         game_configure_port(game_params, cmd_args);
671
672         if (!game_configure_world(game_params, cmd_args)) {
673                 errorstream << "No world path specified or found." << std::endl;
674                 return false;
675         }
676
677         game_configure_subgame(game_params, cmd_args);
678
679         return true;
680 }
681
682 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
683 {
684         if (cmd_args.exists("port")) {
685                 game_params->socket_port = cmd_args.getU16("port");
686         } else {
687                 if (game_params->is_dedicated_server)
688                         game_params->socket_port = g_settings->getU16("port");
689                 else
690                         game_params->socket_port = g_settings->getU16("remote_port");
691         }
692
693         if (game_params->socket_port == 0)
694                 game_params->socket_port = DEFAULT_SERVER_PORT;
695 }
696
697 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
698 {
699         if (get_world_from_cmdline(game_params, cmd_args))
700                 return true;
701
702         if (get_world_from_config(game_params, cmd_args))
703                 return true;
704
705         return auto_select_world(game_params);
706 }
707
708 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
709 {
710         std::string commanded_world;
711
712         // World name
713         std::string commanded_worldname;
714         if (cmd_args.exists("worldname"))
715                 commanded_worldname = cmd_args.get("worldname");
716
717         // If a world name was specified, convert it to a path
718         if (!commanded_worldname.empty()) {
719                 // Get information about available worlds
720                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
721                 bool found = false;
722                 for (const WorldSpec &worldspec : worldspecs) {
723                         std::string name = worldspec.name;
724                         if (name == commanded_worldname) {
725                                 dstream << _("Using world specified by --worldname on the "
726                                         "command line") << std::endl;
727                                 commanded_world = worldspec.path;
728                                 found = true;
729                                 break;
730                         }
731                 }
732                 if (!found) {
733                         dstream << _("World") << " '" << commanded_worldname
734                                 << _("' not available. Available worlds:") << std::endl;
735                         print_worldspecs(worldspecs, dstream);
736                         return false;
737                 }
738
739                 game_params->world_path = get_clean_world_path(commanded_world);
740                 return !commanded_world.empty();
741         }
742
743         if (cmd_args.exists("world"))
744                 commanded_world = cmd_args.get("world");
745         else if (cmd_args.exists("map-dir"))
746                 commanded_world = cmd_args.get("map-dir");
747         else if (cmd_args.exists("nonopt0")) // First nameless argument
748                 commanded_world = cmd_args.get("nonopt0");
749
750         game_params->world_path = get_clean_world_path(commanded_world);
751         return !commanded_world.empty();
752 }
753
754 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
755 {
756         // World directory
757         std::string commanded_world;
758
759         if (g_settings->exists("map-dir"))
760                 commanded_world = g_settings->get("map-dir");
761
762         game_params->world_path = get_clean_world_path(commanded_world);
763
764         return !commanded_world.empty();
765 }
766
767 static bool auto_select_world(GameParams *game_params)
768 {
769         // No world was specified; try to select it automatically
770         // Get information about available worlds
771
772         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
773         std::string world_path;
774
775         // If there is only a single world, use it
776         if (worldspecs.size() == 1) {
777                 world_path = worldspecs[0].path;
778                 dstream <<_("Automatically selecting world at") << " ["
779                         << world_path << "]" << std::endl;
780         // If there are multiple worlds, list them
781         } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
782                 std::cerr << _("Multiple worlds are available.") << std::endl;
783                 std::cerr << _("Please select one using --worldname <name>"
784                                 " or --world <path>") << std::endl;
785                 print_worldspecs(worldspecs, std::cerr);
786                 return false;
787         // If there are no worlds, automatically create a new one
788         } else {
789                 // This is the ultimate default world path
790                 world_path = porting::path_user + DIR_DELIM + "worlds" +
791                                 DIR_DELIM + "world";
792                 infostream << "Using default world at ["
793                            << world_path << "]" << std::endl;
794         }
795
796         assert(!world_path.empty());    // Post-condition
797         game_params->world_path = world_path;
798         return true;
799 }
800
801 static std::string get_clean_world_path(const std::string &path)
802 {
803         const std::string worldmt = "world.mt";
804         std::string clean_path;
805
806         if (path.size() > worldmt.size()
807                         && path.substr(path.size() - worldmt.size()) == worldmt) {
808                 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
809                 clean_path = path.substr(0, path.size() - worldmt.size());
810         } else {
811                 clean_path = path;
812         }
813         return path;
814 }
815
816
817 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
818 {
819         bool success;
820
821         success = get_game_from_cmdline(game_params, cmd_args);
822         if (!success)
823                 success = determine_subgame(game_params);
824
825         return success;
826 }
827
828 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
829 {
830         SubgameSpec commanded_gamespec;
831
832         if (cmd_args.exists("gameid")) {
833                 std::string gameid = cmd_args.get("gameid");
834                 commanded_gamespec = findSubgame(gameid);
835                 if (!commanded_gamespec.isValid()) {
836                         errorstream << "Game \"" << gameid << "\" not found" << std::endl;
837                         return false;
838                 }
839                 dstream << _("Using game specified by --gameid on the command line")
840                         << std::endl;
841                 game_params->game_spec = commanded_gamespec;
842                 return true;
843         }
844
845         return false;
846 }
847
848 static bool determine_subgame(GameParams *game_params)
849 {
850         SubgameSpec gamespec;
851
852         assert(!game_params->world_path.empty());       // Pre-condition
853
854         // If world doesn't exist
855         if (!game_params->world_path.empty()
856                 && !getWorldExists(game_params->world_path)) {
857                 // Try to take gamespec from command line
858                 if (game_params->game_spec.isValid()) {
859                         gamespec = game_params->game_spec;
860                         infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
861                 } else { // Otherwise we will be using "minetest"
862                         gamespec = findSubgame(g_settings->get("default_game"));
863                         infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
864                         if (!gamespec.isValid()) {
865                                 errorstream << "Game specified in default_game ["
866                                             << g_settings->get("default_game")
867                                             << "] is invalid." << std::endl;
868                                 return false;
869                         }
870                 }
871         } else { // World exists
872                 std::string world_gameid = getWorldGameId(game_params->world_path, false);
873                 // If commanded to use a gameid, do so
874                 if (game_params->game_spec.isValid()) {
875                         gamespec = game_params->game_spec;
876                         if (game_params->game_spec.id != world_gameid) {
877                                 warningstream << "Using commanded gameid ["
878                                             << gamespec.id << "]" << " instead of world gameid ["
879                                             << world_gameid << "]" << std::endl;
880                         }
881                 } else {
882                         // If world contains an embedded game, use it;
883                         // Otherwise find world from local system.
884                         gamespec = findWorldSubgame(game_params->world_path);
885                         infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
886                 }
887         }
888
889         if (!gamespec.isValid()) {
890                 errorstream << "Game [" << gamespec.id << "] could not be found."
891                             << std::endl;
892                 return false;
893         }
894
895         game_params->game_spec = gamespec;
896         return true;
897 }
898
899
900 /*****************************************************************************
901  * Dedicated server
902  *****************************************************************************/
903 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
904 {
905         verbosestream << _("Using world path") << " ["
906                       << game_params.world_path << "]" << std::endl;
907         verbosestream << _("Using gameid") << " ["
908                       << game_params.game_spec.id << "]" << std::endl;
909
910         // Bind address
911         std::string bind_str = g_settings->get("bind_address");
912         Address bind_addr(0, 0, 0, 0, game_params.socket_port);
913
914         if (g_settings->getBool("ipv6_server")) {
915                 bind_addr.setAddress((IPv6AddressBytes*) NULL);
916         }
917         try {
918                 bind_addr.Resolve(bind_str.c_str());
919         } catch (ResolveError &e) {
920                 infostream << "Resolving bind address \"" << bind_str
921                            << "\" failed: " << e.what()
922                            << " -- Listening on all addresses." << std::endl;
923         }
924         if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
925                 errorstream << "Unable to listen on "
926                             << bind_addr.serializeString()
927                             << L" because IPv6 is disabled" << std::endl;
928                 return false;
929         }
930
931         // Database migration/compression
932         if (cmd_args.exists("migrate"))
933                 return migrate_map_database(game_params, cmd_args);
934
935         if (cmd_args.exists("migrate-players"))
936                 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
937
938         if (cmd_args.exists("migrate-auth"))
939                 return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);
940
941         if (cmd_args.exists("migrate-mod-storage"))
942                 return Server::migrateModStorageDatabase(game_params, cmd_args);
943
944         if (cmd_args.getFlag("recompress"))
945                 return recompress_map_database(game_params, cmd_args, bind_addr);
946
947         if (cmd_args.exists("terminal")) {
948 #if USE_CURSES
949                 bool name_ok = true;
950                 std::string admin_nick = g_settings->get("name");
951
952                 name_ok = name_ok && !admin_nick.empty();
953                 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
954
955                 if (!name_ok) {
956                         if (admin_nick.empty()) {
957                                 errorstream << "No name given for admin. "
958                                         << "Please check your minetest.conf that it "
959                                         << "contains a 'name = ' to your main admin account."
960                                         << std::endl;
961                         } else {
962                                 errorstream << "Name for admin '"
963                                         << admin_nick << "' is not valid. "
964                                         << "Please check that it only contains allowed characters. "
965                                         << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
966                                         << std::endl;
967                         }
968                         return false;
969                 }
970                 ChatInterface iface;
971                 bool &kill = *porting::signal_handler_killstatus();
972
973                 try {
974                         // Create server
975                         Server server(game_params.world_path, game_params.game_spec,
976                                         false, bind_addr, true, &iface);
977
978                         g_term_console.setup(&iface, &kill, admin_nick);
979
980                         g_term_console.start();
981
982                         server.start();
983                         // Run server
984                         dedicated_server_loop(server, kill);
985                 } catch (const ModError &e) {
986                         g_term_console.stopAndWaitforThread();
987                         errorstream << "ModError: " << e.what() << std::endl;
988                         return false;
989                 } catch (const ServerError &e) {
990                         g_term_console.stopAndWaitforThread();
991                         errorstream << "ServerError: " << e.what() << std::endl;
992                         return false;
993                 }
994
995                 // Tell the console to stop, and wait for it to finish,
996                 // only then leave context and free iface
997                 g_term_console.stop();
998                 g_term_console.wait();
999
1000                 g_term_console.clearKillStatus();
1001         } else {
1002 #else
1003                 errorstream << "Cmd arg --terminal passed, but "
1004                         << "compiled without ncurses. Ignoring." << std::endl;
1005         } {
1006 #endif
1007                 try {
1008                         // Create server
1009                         Server server(game_params.world_path, game_params.game_spec, false,
1010                                 bind_addr, true);
1011                         server.start();
1012
1013                         // Run server
1014                         bool &kill = *porting::signal_handler_killstatus();
1015                         dedicated_server_loop(server, kill);
1016
1017                 } catch (const ModError &e) {
1018                         errorstream << "ModError: " << e.what() << std::endl;
1019                         return false;
1020                 } catch (const ServerError &e) {
1021                         errorstream << "ServerError: " << e.what() << std::endl;
1022                         return false;
1023                 }
1024         }
1025
1026         return true;
1027 }
1028
1029 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
1030 {
1031         std::string migrate_to = cmd_args.get("migrate");
1032         Settings world_mt;
1033         std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
1034         if (!world_mt.readConfigFile(world_mt_path.c_str())) {
1035                 errorstream << "Cannot read world.mt!" << std::endl;
1036                 return false;
1037         }
1038
1039         if (!world_mt.exists("backend")) {
1040                 errorstream << "Please specify your current backend in world.mt:"
1041                         << std::endl
1042                         << "    backend = {sqlite3|leveldb|redis|dummy|postgresql}"
1043                         << std::endl;
1044                 return false;
1045         }
1046
1047         std::string backend = world_mt.get("backend");
1048         if (backend == migrate_to) {
1049                 errorstream << "Cannot migrate: new backend is same"
1050                         << " as the old one" << std::endl;
1051                 return false;
1052         }
1053
1054         MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
1055                 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
1056
1057         u32 count = 0;
1058         time_t last_update_time = 0;
1059         bool &kill = *porting::signal_handler_killstatus();
1060
1061         std::vector<v3s16> blocks;
1062         old_db->listAllLoadableBlocks(blocks);
1063         new_db->beginSave();
1064         for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
1065                 if (kill) return false;
1066
1067                 std::string data;
1068                 old_db->loadBlock(*it, &data);
1069                 if (!data.empty()) {
1070                         new_db->saveBlock(*it, data);
1071                 } else {
1072                         errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
1073                 }
1074                 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
1075                         std::cerr << " Migrated " << count << " blocks, "
1076                                 << (100.0 * count / blocks.size()) << "% completed.\r";
1077                         new_db->endSave();
1078                         new_db->beginSave();
1079                         last_update_time = time(NULL);
1080                 }
1081         }
1082         std::cerr << std::endl;
1083         new_db->endSave();
1084         delete old_db;
1085         delete new_db;
1086
1087         actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1088         world_mt.set("backend", migrate_to);
1089         if (!world_mt.updateConfigFile(world_mt_path.c_str()))
1090                 errorstream << "Failed to update world.mt!" << std::endl;
1091         else
1092                 actionstream << "world.mt updated" << std::endl;
1093
1094         return true;
1095 }
1096
1097 static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr)
1098 {
1099         Settings world_mt;
1100         const std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
1101
1102         if (!world_mt.readConfigFile(world_mt_path.c_str())) {
1103                 errorstream << "Cannot read world.mt at " << world_mt_path << std::endl;
1104                 return false;
1105         }
1106         const std::string &backend = world_mt.get("backend");
1107         Server server(game_params.world_path, game_params.game_spec, false, addr, false);
1108         MapDatabase *db = ServerMap::createDatabase(backend, game_params.world_path, world_mt);
1109
1110         u32 count = 0;
1111         u64 last_update_time = 0;
1112         bool &kill = *porting::signal_handler_killstatus();
1113         const u8 serialize_as_ver = SER_FMT_VER_HIGHEST_WRITE;
1114
1115         // This is ok because the server doesn't actually run
1116         std::vector<v3s16> blocks;
1117         db->listAllLoadableBlocks(blocks);
1118         db->beginSave();
1119         std::istringstream iss(std::ios_base::binary);
1120         std::ostringstream oss(std::ios_base::binary);
1121         for (auto it = blocks.begin(); it != blocks.end(); ++it) {
1122                 if (kill) return false;
1123
1124                 std::string data;
1125                 db->loadBlock(*it, &data);
1126                 if (data.empty()) {
1127                         errorstream << "Failed to load block " << PP(*it) << std::endl;
1128                         return false;
1129                 }
1130
1131                 iss.str(data);
1132                 iss.clear();
1133
1134                 {
1135                         MapBlock mb(nullptr, v3s16(0,0,0), &server);
1136                         u8 ver = readU8(iss);
1137                         mb.deSerialize(iss, ver, true);
1138
1139                         oss.str("");
1140                         oss.clear();
1141                         writeU8(oss, serialize_as_ver);
1142                         mb.serialize(oss, serialize_as_ver, true, -1);
1143                 }
1144
1145                 db->saveBlock(*it, oss.str());
1146
1147                 count++;
1148                 if (count % 0xFF == 0 && porting::getTimeS() - last_update_time >= 1) {
1149                         std::cerr << " Recompressed " << count << " blocks, "
1150                                 << (100.0f * count / blocks.size()) << "% completed.\r";
1151                         db->endSave();
1152                         db->beginSave();
1153                         last_update_time = porting::getTimeS();
1154                 }
1155         }
1156         std::cerr << std::endl;
1157         db->endSave();
1158
1159         actionstream << "Done, " << count << " blocks were recompressed." << std::endl;
1160         return true;
1161 }