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