]> git.lizzy.rs Git - minetest.git/blob - src/main.cpp
35dcb708b2634ffe7ef933e61746c141aefba13f
[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::string opt = "  --" + allowed_option.first;
393                 if (allowed_option.second.type != VALUETYPE_FLAG)
394                         opt += _(" <value>");
395
396                 std::string opt_padded = padStringRight(opt, 30);
397                 std::cout << opt_padded;
398                 if (opt == opt_padded) // Line is too long to pad
399                         std::cout << std::endl << padStringRight("", 30);
400
401                 if (allowed_option.second.help)
402                         std::cout << allowed_option.second.help;
403
404                 std::cout << std::endl;
405         }
406 }
407
408 static void print_version()
409 {
410         std::cout << PROJECT_NAME_C " " << g_version_hash
411                 << " (" << porting::getPlatformName() << ")" << std::endl;
412 #ifndef SERVER
413         std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl;
414 #endif
415 #if USE_LUAJIT
416         std::cout << "Using " << LUAJIT_VERSION << std::endl;
417 #else
418         std::cout << "Using " << LUA_RELEASE << std::endl;
419 #endif
420         std::cout << g_build_info << std::endl;
421 }
422
423 static void list_game_ids()
424 {
425         std::set<std::string> gameids = getAvailableGameIds();
426         for (const std::string &gameid : gameids)
427                 std::cout << gameid <<std::endl;
428 }
429
430 static void list_worlds(bool print_name, bool print_path)
431 {
432         std::cout << _("Available worlds:") << std::endl;
433         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
434         print_worldspecs(worldspecs, std::cout, print_name, print_path);
435 }
436
437 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
438         std::ostream &os, bool print_name, bool print_path)
439 {
440         for (const WorldSpec &worldspec : worldspecs) {
441                 std::string name = worldspec.name;
442                 std::string path = worldspec.path;
443                 if (print_name && print_path) {
444                         os << "\t" << name << "\t\t" << path << std::endl;
445                 } else if (print_name) {
446                         os << "\t" << name << std::endl;
447                 } else if (print_path) {
448                         os << "\t" << path << std::endl;
449                 }
450         }
451 }
452
453 static void print_modified_quicktune_values()
454 {
455         bool header_printed = false;
456         std::vector<std::string> names = getQuicktuneNames();
457
458         for (const std::string &name : names) {
459                 QuicktuneValue val = getQuicktuneValue(name);
460                 if (!val.modified)
461                         continue;
462                 if (!header_printed) {
463                         dstream << "Modified quicktune values:" << std::endl;
464                         header_printed = true;
465                 }
466                 dstream << name << " = " << val.getString() << std::endl;
467         }
468 }
469
470 static bool setup_log_params(const Settings &cmd_args)
471 {
472         // Quiet mode, print errors only
473         if (cmd_args.getFlag("quiet")) {
474                 g_logger.removeOutput(&stderr_output);
475                 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
476         }
477
478         // Coloured log messages (see log.h)
479         std::string color_mode;
480         if (cmd_args.exists("color")) {
481                 color_mode = cmd_args.get("color");
482 #if !defined(_WIN32)
483         } else {
484                 char *color_mode_env = getenv("MT_LOGCOLOR");
485                 if (color_mode_env)
486                         color_mode = color_mode_env;
487 #endif
488         }
489         if (!color_mode.empty()) {
490                 if (color_mode == "auto") {
491                         Logger::color_mode = LOG_COLOR_AUTO;
492                 } else if (color_mode == "always") {
493                         Logger::color_mode = LOG_COLOR_ALWAYS;
494                 } else if (color_mode == "never") {
495                         Logger::color_mode = LOG_COLOR_NEVER;
496                 } else {
497                         errorstream << "Invalid color mode: " << color_mode << std::endl;
498                         return false;
499                 }
500         }
501
502         // In certain cases, output info level on stderr
503         if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
504                         cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
505                 g_logger.addOutput(&stderr_output, LL_INFO);
506
507         // In certain cases, output verbose level on stderr
508         if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
509                 g_logger.addOutput(&stderr_output, LL_VERBOSE);
510
511         if (cmd_args.getFlag("trace")) {
512                 dstream << _("Enabling trace level debug output") << std::endl;
513                 g_logger.addOutput(&stderr_output, LL_TRACE);
514                 socket_enable_debug_output = true;
515         }
516
517         return true;
518 }
519
520 static bool create_userdata_path()
521 {
522         bool success;
523
524 #ifdef __ANDROID__
525         if (!fs::PathExists(porting::path_user)) {
526                 success = fs::CreateDir(porting::path_user);
527         } else {
528                 success = true;
529         }
530 #else
531         // Create user data directory
532         success = fs::CreateAllDirs(porting::path_user);
533 #endif
534
535         return success;
536 }
537
538 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
539 {
540         startup_message();
541         set_default_settings();
542
543         sockets_init();
544
545         // Initialize g_settings
546         Settings::createLayer(SL_GLOBAL);
547
548         // Set cleanup callback(s) to run at process exit
549         atexit(uninit_common);
550
551         if (!read_config_file(cmd_args))
552                 return false;
553
554         init_log_streams(cmd_args);
555
556         // Initialize random seed
557         srand(time(0));
558         mysrand(time(0));
559
560         // Initialize HTTP fetcher
561         httpfetch_init(g_settings->getS32("curl_parallel_limit"));
562
563         init_gettext(porting::path_locale.c_str(),
564                 g_settings->get("language"), argc, argv);
565
566         return true;
567 }
568
569 static void uninit_common()
570 {
571         httpfetch_cleanup();
572
573         sockets_cleanup();
574
575         // It'd actually be okay to leak these but we want to please valgrind...
576         for (int i = 0; i < (int)SL_TOTAL_COUNT; i++)
577                 delete Settings::getLayer((SettingsLayer)i);
578 }
579
580 static void startup_message()
581 {
582         infostream << PROJECT_NAME << " " << _("with")
583                    << " SER_FMT_VER_HIGHEST_READ="
584                << (int)SER_FMT_VER_HIGHEST_READ << ", "
585                << g_build_info << std::endl;
586 }
587
588 static bool read_config_file(const Settings &cmd_args)
589 {
590         // Path of configuration file in use
591         sanity_check(g_settings_path.empty());  // Sanity check
592
593         if (cmd_args.exists("config")) {
594                 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
595                 if (!r) {
596                         errorstream << "Could not read configuration from \""
597                                     << cmd_args.get("config") << "\"" << std::endl;
598                         return false;
599                 }
600                 g_settings_path = cmd_args.get("config");
601         } else {
602                 std::vector<std::string> filenames;
603                 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
604                 // Legacy configuration file location
605                 filenames.push_back(porting::path_user +
606                                 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
607
608 #if RUN_IN_PLACE
609                 // Try also from a lower level (to aid having the same configuration
610                 // for many RUN_IN_PLACE installs)
611                 filenames.push_back(porting::path_user +
612                                 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
613 #endif
614
615                 for (const std::string &filename : filenames) {
616                         bool r = g_settings->readConfigFile(filename.c_str());
617                         if (r) {
618                                 g_settings_path = filename;
619                                 break;
620                         }
621                 }
622
623                 // If no path found, use the first one (menu creates the file)
624                 if (g_settings_path.empty())
625                         g_settings_path = filenames[0];
626         }
627
628         return true;
629 }
630
631 static void init_log_streams(const Settings &cmd_args)
632 {
633         std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
634
635         if (cmd_args.exists("logfile"))
636                 log_filename = cmd_args.get("logfile");
637
638         g_logger.removeOutput(&file_log_output);
639         std::string conf_loglev = g_settings->get("debug_log_level");
640
641         // Old integer format
642         if (std::isdigit(conf_loglev[0])) {
643                 warningstream << "Deprecated use of debug_log_level with an "
644                         "integer value; please update your configuration." << std::endl;
645                 static const char *lev_name[] =
646                         {"", "error", "action", "info", "verbose", "trace"};
647                 int lev_i = atoi(conf_loglev.c_str());
648                 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
649                         warningstream << "Supplied invalid debug_log_level!"
650                                 "  Assuming action level." << std::endl;
651                         lev_i = 2;
652                 }
653                 conf_loglev = lev_name[lev_i];
654         }
655
656         if (log_filename.empty() || conf_loglev.empty())  // No logging
657                 return;
658
659         LogLevel log_level = Logger::stringToLevel(conf_loglev);
660         if (log_level == LL_MAX) {
661                 warningstream << "Supplied unrecognized debug_log_level; "
662                         "using maximum." << std::endl;
663         }
664
665         file_log_output.setFile(log_filename,
666                 g_settings->getU64("debug_log_size_max") * 1000000);
667         g_logger.addOutputMaxLevel(&file_log_output, log_level);
668 }
669
670 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
671 {
672         game_configure_port(game_params, cmd_args);
673
674         if (!game_configure_world(game_params, cmd_args)) {
675                 errorstream << "No world path specified or found." << std::endl;
676                 return false;
677         }
678
679         game_configure_subgame(game_params, cmd_args);
680
681         return true;
682 }
683
684 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
685 {
686         if (cmd_args.exists("port")) {
687                 game_params->socket_port = cmd_args.getU16("port");
688         } else {
689                 if (game_params->is_dedicated_server)
690                         game_params->socket_port = g_settings->getU16("port");
691                 else
692                         game_params->socket_port = g_settings->getU16("remote_port");
693         }
694
695         if (game_params->socket_port == 0)
696                 game_params->socket_port = DEFAULT_SERVER_PORT;
697 }
698
699 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
700 {
701         if (get_world_from_cmdline(game_params, cmd_args))
702                 return true;
703
704         if (get_world_from_config(game_params, cmd_args))
705                 return true;
706
707         return auto_select_world(game_params);
708 }
709
710 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
711 {
712         std::string commanded_world;
713
714         // World name
715         std::string commanded_worldname;
716         if (cmd_args.exists("worldname"))
717                 commanded_worldname = cmd_args.get("worldname");
718
719         // If a world name was specified, convert it to a path
720         if (!commanded_worldname.empty()) {
721                 // Get information about available worlds
722                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
723                 bool found = false;
724                 for (const WorldSpec &worldspec : worldspecs) {
725                         std::string name = worldspec.name;
726                         if (name == commanded_worldname) {
727                                 dstream << _("Using world specified by --worldname on the "
728                                         "command line") << std::endl;
729                                 commanded_world = worldspec.path;
730                                 found = true;
731                                 break;
732                         }
733                 }
734                 if (!found) {
735                         dstream << _("World") << " '" << commanded_worldname
736                                 << _("' not available. Available worlds:") << std::endl;
737                         print_worldspecs(worldspecs, dstream);
738                         return false;
739                 }
740
741                 game_params->world_path = get_clean_world_path(commanded_world);
742                 return !commanded_world.empty();
743         }
744
745         if (cmd_args.exists("world"))
746                 commanded_world = cmd_args.get("world");
747         else if (cmd_args.exists("map-dir"))
748                 commanded_world = cmd_args.get("map-dir");
749         else if (cmd_args.exists("nonopt0")) // First nameless argument
750                 commanded_world = cmd_args.get("nonopt0");
751
752         game_params->world_path = get_clean_world_path(commanded_world);
753         return !commanded_world.empty();
754 }
755
756 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
757 {
758         // World directory
759         std::string commanded_world;
760
761         if (g_settings->exists("map-dir"))
762                 commanded_world = g_settings->get("map-dir");
763
764         game_params->world_path = get_clean_world_path(commanded_world);
765
766         return !commanded_world.empty();
767 }
768
769 static bool auto_select_world(GameParams *game_params)
770 {
771         // No world was specified; try to select it automatically
772         // Get information about available worlds
773
774         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
775         std::string world_path;
776
777         // If there is only a single world, use it
778         if (worldspecs.size() == 1) {
779                 world_path = worldspecs[0].path;
780                 dstream <<_("Automatically selecting world at") << " ["
781                         << world_path << "]" << std::endl;
782         // If there are multiple worlds, list them
783         } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
784                 std::cerr << _("Multiple worlds are available.") << std::endl;
785                 std::cerr << _("Please select one using --worldname <name>"
786                                 " or --world <path>") << std::endl;
787                 print_worldspecs(worldspecs, std::cerr);
788                 return false;
789         // If there are no worlds, automatically create a new one
790         } else {
791                 // This is the ultimate default world path
792                 world_path = porting::path_user + DIR_DELIM + "worlds" +
793                                 DIR_DELIM + "world";
794                 infostream << "Using default world at ["
795                            << world_path << "]" << std::endl;
796         }
797
798         assert(!world_path.empty());    // Post-condition
799         game_params->world_path = world_path;
800         return true;
801 }
802
803 static std::string get_clean_world_path(const std::string &path)
804 {
805         const std::string worldmt = "world.mt";
806         std::string clean_path;
807
808         if (path.size() > worldmt.size()
809                         && path.substr(path.size() - worldmt.size()) == worldmt) {
810                 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
811                 clean_path = path.substr(0, path.size() - worldmt.size());
812         } else {
813                 clean_path = path;
814         }
815         return path;
816 }
817
818
819 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
820 {
821         bool success;
822
823         success = get_game_from_cmdline(game_params, cmd_args);
824         if (!success)
825                 success = determine_subgame(game_params);
826
827         return success;
828 }
829
830 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
831 {
832         SubgameSpec commanded_gamespec;
833
834         if (cmd_args.exists("gameid")) {
835                 std::string gameid = cmd_args.get("gameid");
836                 commanded_gamespec = findSubgame(gameid);
837                 if (!commanded_gamespec.isValid()) {
838                         errorstream << "Game \"" << gameid << "\" not found" << std::endl;
839                         return false;
840                 }
841                 dstream << _("Using game specified by --gameid on the command line")
842                         << std::endl;
843                 game_params->game_spec = commanded_gamespec;
844                 return true;
845         }
846
847         return false;
848 }
849
850 static bool determine_subgame(GameParams *game_params)
851 {
852         SubgameSpec gamespec;
853
854         assert(!game_params->world_path.empty());       // Pre-condition
855
856         // If world doesn't exist
857         if (!game_params->world_path.empty()
858                 && !getWorldExists(game_params->world_path)) {
859                 // Try to take gamespec from command line
860                 if (game_params->game_spec.isValid()) {
861                         gamespec = game_params->game_spec;
862                         infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
863                 } else { // Otherwise we will be using "minetest"
864                         gamespec = findSubgame(g_settings->get("default_game"));
865                         infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
866                         if (!gamespec.isValid()) {
867                                 errorstream << "Game specified in default_game ["
868                                             << g_settings->get("default_game")
869                                             << "] is invalid." << std::endl;
870                                 return false;
871                         }
872                 }
873         } else { // World exists
874                 std::string world_gameid = getWorldGameId(game_params->world_path, false);
875                 // If commanded to use a gameid, do so
876                 if (game_params->game_spec.isValid()) {
877                         gamespec = game_params->game_spec;
878                         if (game_params->game_spec.id != world_gameid) {
879                                 warningstream << "Using commanded gameid ["
880                                             << gamespec.id << "]" << " instead of world gameid ["
881                                             << world_gameid << "]" << std::endl;
882                         }
883                 } else {
884                         // If world contains an embedded game, use it;
885                         // Otherwise find world from local system.
886                         gamespec = findWorldSubgame(game_params->world_path);
887                         infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
888                 }
889         }
890
891         if (!gamespec.isValid()) {
892                 errorstream << "Game [" << gamespec.id << "] could not be found."
893                             << std::endl;
894                 return false;
895         }
896
897         game_params->game_spec = gamespec;
898         return true;
899 }
900
901
902 /*****************************************************************************
903  * Dedicated server
904  *****************************************************************************/
905 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
906 {
907         verbosestream << _("Using world path") << " ["
908                       << game_params.world_path << "]" << std::endl;
909         verbosestream << _("Using gameid") << " ["
910                       << game_params.game_spec.id << "]" << std::endl;
911
912         // Bind address
913         std::string bind_str = g_settings->get("bind_address");
914         Address bind_addr(0, 0, 0, 0, game_params.socket_port);
915
916         if (g_settings->getBool("ipv6_server")) {
917                 bind_addr.setAddress((IPv6AddressBytes*) NULL);
918         }
919         try {
920                 bind_addr.Resolve(bind_str.c_str());
921         } catch (ResolveError &e) {
922                 infostream << "Resolving bind address \"" << bind_str
923                            << "\" failed: " << e.what()
924                            << " -- Listening on all addresses." << std::endl;
925         }
926         if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
927                 errorstream << "Unable to listen on "
928                             << bind_addr.serializeString()
929                             << L" because IPv6 is disabled" << std::endl;
930                 return false;
931         }
932
933         // Database migration/compression
934         if (cmd_args.exists("migrate"))
935                 return migrate_map_database(game_params, cmd_args);
936
937         if (cmd_args.exists("migrate-players"))
938                 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
939
940         if (cmd_args.exists("migrate-auth"))
941                 return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);
942
943         if (cmd_args.exists("migrate-mod-storage"))
944                 return Server::migrateModStorageDatabase(game_params, cmd_args);
945
946         if (cmd_args.getFlag("recompress"))
947                 return recompress_map_database(game_params, cmd_args, bind_addr);
948
949         if (cmd_args.exists("terminal")) {
950 #if USE_CURSES
951                 bool name_ok = true;
952                 std::string admin_nick = g_settings->get("name");
953
954                 name_ok = name_ok && !admin_nick.empty();
955                 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
956
957                 if (!name_ok) {
958                         if (admin_nick.empty()) {
959                                 errorstream << "No name given for admin. "
960                                         << "Please check your minetest.conf that it "
961                                         << "contains a 'name = ' to your main admin account."
962                                         << std::endl;
963                         } else {
964                                 errorstream << "Name for admin '"
965                                         << admin_nick << "' is not valid. "
966                                         << "Please check that it only contains allowed characters. "
967                                         << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
968                                         << std::endl;
969                         }
970                         return false;
971                 }
972                 ChatInterface iface;
973                 bool &kill = *porting::signal_handler_killstatus();
974
975                 try {
976                         // Create server
977                         Server server(game_params.world_path, game_params.game_spec,
978                                         false, bind_addr, true, &iface);
979
980                         g_term_console.setup(&iface, &kill, admin_nick);
981
982                         g_term_console.start();
983
984                         server.start();
985                         // Run server
986                         dedicated_server_loop(server, kill);
987                 } catch (const ModError &e) {
988                         g_term_console.stopAndWaitforThread();
989                         errorstream << "ModError: " << e.what() << std::endl;
990                         return false;
991                 } catch (const ServerError &e) {
992                         g_term_console.stopAndWaitforThread();
993                         errorstream << "ServerError: " << e.what() << std::endl;
994                         return false;
995                 }
996
997                 // Tell the console to stop, and wait for it to finish,
998                 // only then leave context and free iface
999                 g_term_console.stop();
1000                 g_term_console.wait();
1001
1002                 g_term_console.clearKillStatus();
1003         } else {
1004 #else
1005                 errorstream << "Cmd arg --terminal passed, but "
1006                         << "compiled without ncurses. Ignoring." << std::endl;
1007         } {
1008 #endif
1009                 try {
1010                         // Create server
1011                         Server server(game_params.world_path, game_params.game_spec, false,
1012                                 bind_addr, true);
1013                         server.start();
1014
1015                         // Run server
1016                         bool &kill = *porting::signal_handler_killstatus();
1017                         dedicated_server_loop(server, kill);
1018
1019                 } catch (const ModError &e) {
1020                         errorstream << "ModError: " << e.what() << std::endl;
1021                         return false;
1022                 } catch (const ServerError &e) {
1023                         errorstream << "ServerError: " << e.what() << std::endl;
1024                         return false;
1025                 }
1026         }
1027
1028         return true;
1029 }
1030
1031 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
1032 {
1033         std::string migrate_to = cmd_args.get("migrate");
1034         Settings world_mt;
1035         std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
1036         if (!world_mt.readConfigFile(world_mt_path.c_str())) {
1037                 errorstream << "Cannot read world.mt!" << std::endl;
1038                 return false;
1039         }
1040
1041         if (!world_mt.exists("backend")) {
1042                 errorstream << "Please specify your current backend in world.mt:"
1043                         << std::endl
1044                         << "    backend = {sqlite3|leveldb|redis|dummy|postgresql}"
1045                         << std::endl;
1046                 return false;
1047         }
1048
1049         std::string backend = world_mt.get("backend");
1050         if (backend == migrate_to) {
1051                 errorstream << "Cannot migrate: new backend is same"
1052                         << " as the old one" << std::endl;
1053                 return false;
1054         }
1055
1056         MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
1057                 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
1058
1059         u32 count = 0;
1060         time_t last_update_time = 0;
1061         bool &kill = *porting::signal_handler_killstatus();
1062
1063         std::vector<v3s16> blocks;
1064         old_db->listAllLoadableBlocks(blocks);
1065         new_db->beginSave();
1066         for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
1067                 if (kill) return false;
1068
1069                 std::string data;
1070                 old_db->loadBlock(*it, &data);
1071                 if (!data.empty()) {
1072                         new_db->saveBlock(*it, data);
1073                 } else {
1074                         errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
1075                 }
1076                 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
1077                         std::cerr << " Migrated " << count << " blocks, "
1078                                 << (100.0 * count / blocks.size()) << "% completed.\r";
1079                         new_db->endSave();
1080                         new_db->beginSave();
1081                         last_update_time = time(NULL);
1082                 }
1083         }
1084         std::cerr << std::endl;
1085         new_db->endSave();
1086         delete old_db;
1087         delete new_db;
1088
1089         actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1090         world_mt.set("backend", migrate_to);
1091         if (!world_mt.updateConfigFile(world_mt_path.c_str()))
1092                 errorstream << "Failed to update world.mt!" << std::endl;
1093         else
1094                 actionstream << "world.mt updated" << std::endl;
1095
1096         return true;
1097 }
1098
1099 static bool recompress_map_database(const GameParams &game_params, const Settings &cmd_args, const Address &addr)
1100 {
1101         Settings world_mt;
1102         const std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
1103
1104         if (!world_mt.readConfigFile(world_mt_path.c_str())) {
1105                 errorstream << "Cannot read world.mt at " << world_mt_path << std::endl;
1106                 return false;
1107         }
1108         const std::string &backend = world_mt.get("backend");
1109         Server server(game_params.world_path, game_params.game_spec, false, addr, false);
1110         MapDatabase *db = ServerMap::createDatabase(backend, game_params.world_path, world_mt);
1111
1112         u32 count = 0;
1113         u64 last_update_time = 0;
1114         bool &kill = *porting::signal_handler_killstatus();
1115         const u8 serialize_as_ver = SER_FMT_VER_HIGHEST_WRITE;
1116
1117         // This is ok because the server doesn't actually run
1118         std::vector<v3s16> blocks;
1119         db->listAllLoadableBlocks(blocks);
1120         db->beginSave();
1121         std::istringstream iss(std::ios_base::binary);
1122         std::ostringstream oss(std::ios_base::binary);
1123         for (auto it = blocks.begin(); it != blocks.end(); ++it) {
1124                 if (kill) return false;
1125
1126                 std::string data;
1127                 db->loadBlock(*it, &data);
1128                 if (data.empty()) {
1129                         errorstream << "Failed to load block " << PP(*it) << std::endl;
1130                         return false;
1131                 }
1132
1133                 iss.str(data);
1134                 iss.clear();
1135
1136                 {
1137                         MapBlock mb(nullptr, v3s16(0,0,0), &server);
1138                         u8 ver = readU8(iss);
1139                         mb.deSerialize(iss, ver, true);
1140
1141                         oss.str("");
1142                         oss.clear();
1143                         writeU8(oss, serialize_as_ver);
1144                         mb.serialize(oss, serialize_as_ver, true, -1);
1145                 }
1146
1147                 db->saveBlock(*it, oss.str());
1148
1149                 count++;
1150                 if (count % 0xFF == 0 && porting::getTimeS() - last_update_time >= 1) {
1151                         std::cerr << " Recompressed " << count << " blocks, "
1152                                 << (100.0f * count / blocks.size()) << "% completed.\r";
1153                         db->endSave();
1154                         db->beginSave();
1155                         last_update_time = porting::getTimeS();
1156                 }
1157         }
1158         std::cerr << std::endl;
1159         db->endSave();
1160
1161         actionstream << "Done, " << count << " blocks were recompressed." << std::endl;
1162         return true;
1163 }