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