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