init_log_streams: check if log_filename is empty.
[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                 run_tests();
187                 return 0;
188         }
189 #endif
190
191         GameParams game_params;
192 #ifdef SERVER
193         game_params.is_dedicated_server = true;
194 #else
195         game_params.is_dedicated_server = cmd_args.getFlag("server");
196 #endif
197
198         if (!game_configure(&game_params, cmd_args))
199                 return 1;
200
201         sanity_check(!game_params.world_path.empty());
202
203         infostream << "Using commanded world path ["
204                    << game_params.world_path << "]" << std::endl;
205
206         //Run dedicated server if asked to or no other option
207         g_settings->set("server_dedicated",
208                         game_params.is_dedicated_server ? "true" : "false");
209
210         if (game_params.is_dedicated_server)
211                 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
212
213 #ifndef SERVER
214         ClientLauncher launcher;
215         retval = launcher.run(game_params, cmd_args) ? 0 : 1;
216 #else
217         retval = 0;
218 #endif
219
220         // Update configuration file
221         if (g_settings_path != "")
222                 g_settings->updateConfigFile(g_settings_path.c_str());
223
224         print_modified_quicktune_values();
225
226         // Stop httpfetch thread (if started)
227         httpfetch_cleanup();
228
229         END_DEBUG_EXCEPTION_HANDLER
230
231         return retval;
232 }
233
234
235 /*****************************************************************************
236  * Startup / Init
237  *****************************************************************************/
238
239
240 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
241 {
242         set_allowed_options(&allowed_options);
243
244         return cmd_args->parseCommandLine(argc, argv, allowed_options);
245 }
246
247 static void set_allowed_options(OptionList *allowed_options)
248 {
249         allowed_options->clear();
250
251         allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
252                         _("Show allowed options"))));
253         allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
254                         _("Show version information"))));
255         allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
256                         _("Load configuration from specified file"))));
257         allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
258                         _("Set network port (UDP)"))));
259         allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
260                         _("Run the unit tests and exit"))));
261         allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
262                         _("Same as --world (deprecated)"))));
263         allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
264                         _("Set world path (implies local game) ('list' lists all)"))));
265         allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
266                         _("Set world by name (implies local game)"))));
267         allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
268                         _("Print to console errors only"))));
269         allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
270                         _("Print more information to console"))));
271         allowed_options->insert(std::make_pair("verbose",  ValueSpec(VALUETYPE_FLAG,
272                         _("Print even more information to console"))));
273         allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
274                         _("Print enormous amounts of information to log and console"))));
275         allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
276                         _("Set logfile path ('' = no logging)"))));
277         allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
278                         _("Set gameid (\"--gameid list\" prints available ones)"))));
279         allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
280                         _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
281 #ifndef SERVER
282         allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
283                         _("Show available video modes"))));
284         allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
285                         _("Run speed tests"))));
286         allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
287                         _("Address to connect to. ('' = local game)"))));
288         allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
289                         _("Enable random user input, for testing"))));
290         allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
291                         _("Run dedicated server"))));
292         allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
293                         _("Set player name"))));
294         allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
295                         _("Set password"))));
296         allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
297                         _("Disable main menu"))));
298 #endif
299
300 }
301
302 static void print_help(const OptionList &allowed_options)
303 {
304         dstream << _("Allowed options:") << std::endl;
305         print_allowed_options(allowed_options);
306 }
307
308 static void print_allowed_options(const OptionList &allowed_options)
309 {
310         for (OptionList::const_iterator i = allowed_options.begin();
311                         i != allowed_options.end(); ++i) {
312                 std::ostringstream os1(std::ios::binary);
313                 os1 << "  --" << i->first;
314                 if (i->second.type != VALUETYPE_FLAG)
315                         os1 << _(" <value>");
316
317                 dstream << padStringRight(os1.str(), 24);
318
319                 if (i->second.help != NULL)
320                         dstream << i->second.help;
321
322                 dstream << std::endl;
323         }
324 }
325
326 static void print_version()
327 {
328         dstream << PROJECT_NAME_C " " << g_version_hash << std::endl;
329 #ifndef SERVER
330         dstream << "Using Irrlicht " << IRRLICHT_SDK_VERSION << std::endl;
331 #endif
332         dstream << "Build info: " << g_build_info << std::endl;
333 }
334
335 static void list_game_ids()
336 {
337         std::set<std::string> gameids = getAvailableGameIds();
338         for (std::set<std::string>::const_iterator i = gameids.begin();
339                         i != gameids.end(); ++i)
340                 dstream << (*i) <<std::endl;
341 }
342
343 static void list_worlds()
344 {
345         dstream << _("Available worlds:") << std::endl;
346         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
347         print_worldspecs(worldspecs, dstream);
348 }
349
350 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
351                                                          std::ostream &os)
352 {
353         for (size_t i = 0; i < worldspecs.size(); i++) {
354                 std::string name = worldspecs[i].name;
355                 std::string path = worldspecs[i].path;
356                 if (name.find(" ") != std::string::npos)
357                         name = std::string("'") + name + "'";
358                 path = std::string("'") + path + "'";
359                 name = padStringRight(name, 14);
360                 os << "  " << name << " " << path << std::endl;
361         }
362 }
363
364 static void print_modified_quicktune_values()
365 {
366         bool header_printed = false;
367         std::vector<std::string> names = getQuicktuneNames();
368
369         for (u32 i = 0; i < names.size(); i++) {
370                 QuicktuneValue val = getQuicktuneValue(names[i]);
371                 if (!val.modified)
372                         continue;
373                 if (!header_printed) {
374                         dstream << "Modified quicktune values:" << std::endl;
375                         header_printed = true;
376                 }
377                 dstream << names[i] << " = " << val.getString() << std::endl;
378         }
379 }
380
381 static void setup_log_params(const Settings &cmd_args)
382 {
383         // Quiet mode, print errors only
384         if (cmd_args.getFlag("quiet")) {
385                 g_logger.removeOutput(&stderr_output);
386                 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
387         }
388
389         // If trace is enabled, enable logging of certain things
390         if (cmd_args.getFlag("trace")) {
391                 dstream << _("Enabling trace level debug output") << std::endl;
392                 g_logger.setTraceEnabled(true);
393                 dout_con_ptr = &verbosestream; // This is somewhat old
394                 socket_enable_debug_output = true; // Sockets doesn't use log.h
395         }
396
397         // In certain cases, output info level on stderr
398         if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
399                         cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
400                 g_logger.addOutput(&stderr_output, LL_INFO);
401
402         // In certain cases, output verbose level on stderr
403         if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
404                 g_logger.addOutput(&stderr_output, LL_VERBOSE);
405 }
406
407 static bool create_userdata_path()
408 {
409         bool success;
410
411 #ifdef __ANDROID__
412         porting::initAndroid();
413
414         porting::setExternalStorageDir(porting::jnienv);
415         if (!fs::PathExists(porting::path_user)) {
416                 success = fs::CreateDir(porting::path_user);
417         } else {
418                 success = true;
419         }
420         porting::copyAssets();
421 #else
422         // Create user data directory
423         success = fs::CreateDir(porting::path_user);
424 #endif
425
426         infostream << "path_share = " << porting::path_share << std::endl;
427         infostream << "path_user  = " << porting::path_user << std::endl;
428
429         return success;
430 }
431
432 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
433 {
434         startup_message();
435         set_default_settings(g_settings);
436
437         // Initialize sockets
438         sockets_init();
439         atexit(sockets_cleanup);
440
441         if (!read_config_file(cmd_args))
442                 return false;
443
444         init_log_streams(cmd_args);
445
446         // Initialize random seed
447         srand(time(0));
448         mysrand(time(0));
449
450         // Initialize HTTP fetcher
451         httpfetch_init(g_settings->getS32("curl_parallel_limit"));
452
453 #ifdef _MSC_VER
454         init_gettext(porting::path_locale.c_str(),
455                 g_settings->get("language"), argc, argv);
456 #else
457         init_gettext(porting::path_locale.c_str(),
458                 g_settings->get("language"));
459 #endif
460
461         return true;
462 }
463
464 static void startup_message()
465 {
466         infostream << PROJECT_NAME << " " << _("with")
467                    << " SER_FMT_VER_HIGHEST_READ="
468                << (int)SER_FMT_VER_HIGHEST_READ << ", "
469                << g_build_info << std::endl;
470 }
471
472 static bool read_config_file(const Settings &cmd_args)
473 {
474         // Path of configuration file in use
475         sanity_check(g_settings_path == "");    // Sanity check
476
477         if (cmd_args.exists("config")) {
478                 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
479                 if (!r) {
480                         errorstream << "Could not read configuration from \""
481                                     << cmd_args.get("config") << "\"" << std::endl;
482                         return false;
483                 }
484                 g_settings_path = cmd_args.get("config");
485         } else {
486                 std::vector<std::string> filenames;
487                 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
488                 // Legacy configuration file location
489                 filenames.push_back(porting::path_user +
490                                 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
491
492 #if RUN_IN_PLACE
493                 // Try also from a lower level (to aid having the same configuration
494                 // for many RUN_IN_PLACE installs)
495                 filenames.push_back(porting::path_user +
496                                 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
497 #endif
498
499                 for (size_t i = 0; i < filenames.size(); i++) {
500                         bool r = g_settings->readConfigFile(filenames[i].c_str());
501                         if (r) {
502                                 g_settings_path = filenames[i];
503                                 break;
504                         }
505                 }
506
507                 // If no path found, use the first one (menu creates the file)
508                 if (g_settings_path == "")
509                         g_settings_path = filenames[0];
510         }
511
512         return true;
513 }
514
515 static void init_log_streams(const Settings &cmd_args)
516 {
517 #if RUN_IN_PLACE
518         std::string log_filename = DEBUGFILE;
519 #else
520         std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
521 #endif
522         if (cmd_args.exists("logfile"))
523                 log_filename = cmd_args.get("logfile");
524
525         g_logger.removeOutput(&file_log_output);
526         std::string conf_loglev = g_settings->get("debug_log_level");
527
528         // Old integer format
529         if (std::isdigit(conf_loglev[0])) {
530                 warningstream << "Deprecated use of debug_log_level with an "
531                         "integer value; please update your configuration." << std::endl;
532                 static const char *lev_name[] =
533                         {"", "error", "action", "info", "verbose"};
534                 int lev_i = atoi(conf_loglev.c_str());
535                 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
536                         warningstream << "Supplied invalid debug_log_level!"
537                                 "  Assuming action level." << std::endl;
538                         lev_i = 2;
539                 }
540                 conf_loglev = lev_name[lev_i];
541         }
542
543         if (log_filename.empty() || conf_loglev.empty())  // No logging
544                 return;
545
546         LogLevel log_level = Logger::stringToLevel(conf_loglev);
547         if (log_level == LL_MAX) {
548                 warningstream << "Supplied unrecognized debug_log_level; "
549                         "using maximum." << std::endl;
550         }
551
552         verbosestream << "log_filename = " << log_filename << std::endl;
553
554         file_log_output.open(log_filename.c_str());
555         g_logger.addOutputMaxLevel(&file_log_output, log_level);
556 }
557
558 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
559 {
560         game_configure_port(game_params, cmd_args);
561
562         if (!game_configure_world(game_params, cmd_args)) {
563                 errorstream << "No world path specified or found." << std::endl;
564                 return false;
565         }
566
567         game_configure_subgame(game_params, cmd_args);
568
569         return true;
570 }
571
572 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
573 {
574         if (cmd_args.exists("port"))
575                 game_params->socket_port = cmd_args.getU16("port");
576         else
577                 game_params->socket_port = g_settings->getU16("port");
578
579         if (game_params->socket_port == 0)
580                 game_params->socket_port = DEFAULT_SERVER_PORT;
581 }
582
583 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
584 {
585         if (get_world_from_cmdline(game_params, cmd_args))
586                 return true;
587         if (get_world_from_config(game_params, cmd_args))
588                 return true;
589
590         return auto_select_world(game_params);
591 }
592
593 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
594 {
595         std::string commanded_world = "";
596
597         // World name
598         std::string commanded_worldname = "";
599         if (cmd_args.exists("worldname"))
600                 commanded_worldname = cmd_args.get("worldname");
601
602         // If a world name was specified, convert it to a path
603         if (commanded_worldname != "") {
604                 // Get information about available worlds
605                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
606                 bool found = false;
607                 for (u32 i = 0; i < worldspecs.size(); i++) {
608                         std::string name = worldspecs[i].name;
609                         if (name == commanded_worldname) {
610                                 dstream << _("Using world specified by --worldname on the "
611                                         "command line") << std::endl;
612                                 commanded_world = worldspecs[i].path;
613                                 found = true;
614                                 break;
615                         }
616                 }
617                 if (!found) {
618                         dstream << _("World") << " '" << commanded_worldname
619                                 << _("' not available. Available worlds:") << std::endl;
620                         print_worldspecs(worldspecs, dstream);
621                         return false;
622                 }
623
624                 game_params->world_path = get_clean_world_path(commanded_world);
625                 return commanded_world != "";
626         }
627
628         if (cmd_args.exists("world"))
629                 commanded_world = cmd_args.get("world");
630         else if (cmd_args.exists("map-dir"))
631                 commanded_world = cmd_args.get("map-dir");
632         else if (cmd_args.exists("nonopt0")) // First nameless argument
633                 commanded_world = cmd_args.get("nonopt0");
634
635         game_params->world_path = get_clean_world_path(commanded_world);
636         return commanded_world != "";
637 }
638
639 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
640 {
641         // World directory
642         std::string commanded_world = "";
643
644         if (g_settings->exists("map-dir"))
645                 commanded_world = g_settings->get("map-dir");
646
647         game_params->world_path = get_clean_world_path(commanded_world);
648
649         return commanded_world != "";
650 }
651
652 static bool auto_select_world(GameParams *game_params)
653 {
654         // No world was specified; try to select it automatically
655         // Get information about available worlds
656
657         verbosestream << _("Determining world path") << std::endl;
658
659         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
660         std::string world_path;
661
662         // If there is only a single world, use it
663         if (worldspecs.size() == 1) {
664                 world_path = worldspecs[0].path;
665                 dstream <<_("Automatically selecting world at") << " ["
666                         << world_path << "]" << std::endl;
667         // If there are multiple worlds, list them
668         } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
669                 std::cerr << _("Multiple worlds are available.") << std::endl;
670                 std::cerr << _("Please select one using --worldname <name>"
671                                 " or --world <path>") << std::endl;
672                 print_worldspecs(worldspecs, std::cerr);
673                 return false;
674         // If there are no worlds, automatically create a new one
675         } else {
676                 // This is the ultimate default world path
677                 world_path = porting::path_user + DIR_DELIM + "worlds" +
678                                 DIR_DELIM + "world";
679                 infostream << "Creating default world at ["
680                            << world_path << "]" << std::endl;
681         }
682
683         assert(world_path != "");       // Post-condition
684         game_params->world_path = world_path;
685         return true;
686 }
687
688 static std::string get_clean_world_path(const std::string &path)
689 {
690         const std::string worldmt = "world.mt";
691         std::string clean_path;
692
693         if (path.size() > worldmt.size()
694                         && path.substr(path.size() - worldmt.size()) == worldmt) {
695                 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
696                 clean_path = path.substr(0, path.size() - worldmt.size());
697         } else {
698                 clean_path = path;
699         }
700         return path;
701 }
702
703
704 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
705 {
706         bool success;
707
708         success = get_game_from_cmdline(game_params, cmd_args);
709         if (!success)
710                 success = determine_subgame(game_params);
711
712         return success;
713 }
714
715 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
716 {
717         SubgameSpec commanded_gamespec;
718
719         if (cmd_args.exists("gameid")) {
720                 std::string gameid = cmd_args.get("gameid");
721                 commanded_gamespec = findSubgame(gameid);
722                 if (!commanded_gamespec.isValid()) {
723                         errorstream << "Game \"" << gameid << "\" not found" << std::endl;
724                         return false;
725                 }
726                 dstream << _("Using game specified by --gameid on the command line")
727                         << std::endl;
728                 game_params->game_spec = commanded_gamespec;
729                 return true;
730         }
731
732         return false;
733 }
734
735 static bool determine_subgame(GameParams *game_params)
736 {
737         SubgameSpec gamespec;
738
739         assert(game_params->world_path != "");  // Pre-condition
740
741         verbosestream << _("Determining gameid/gamespec") << std::endl;
742         // If world doesn't exist
743         if (game_params->world_path != ""
744                         && !getWorldExists(game_params->world_path)) {
745                 // Try to take gamespec from command line
746                 if (game_params->game_spec.isValid()) {
747                         gamespec = game_params->game_spec;
748                         infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
749                 } else { // Otherwise we will be using "minetest"
750                         gamespec = findSubgame(g_settings->get("default_game"));
751                         infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
752                         if (!gamespec.isValid()) {
753                                 errorstream << "Subgame specified in default_game ["
754                                             << g_settings->get("default_game")
755                                             << "] is invalid." << std::endl;
756                                 return false;
757                         }
758                 }
759         } else { // World exists
760                 std::string world_gameid = getWorldGameId(game_params->world_path, false);
761                 // If commanded to use a gameid, do so
762                 if (game_params->game_spec.isValid()) {
763                         gamespec = game_params->game_spec;
764                         if (game_params->game_spec.id != world_gameid) {
765                                 warningstream << "Using commanded gameid ["
766                                             << gamespec.id << "]" << " instead of world gameid ["
767                                             << world_gameid << "]" << std::endl;
768                         }
769                 } else {
770                         // If world contains an embedded game, use it;
771                         // Otherwise find world from local system.
772                         gamespec = findWorldSubgame(game_params->world_path);
773                         infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
774                 }
775         }
776
777         if (!gamespec.isValid()) {
778                 errorstream << "Subgame [" << gamespec.id << "] could not be found."
779                             << std::endl;
780                 return false;
781         }
782
783         game_params->game_spec = gamespec;
784         return true;
785 }
786
787
788 /*****************************************************************************
789  * Dedicated server
790  *****************************************************************************/
791 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
792 {
793         DSTACK("Dedicated server branch");
794
795         verbosestream << _("Using world path") << " ["
796                       << game_params.world_path << "]" << std::endl;
797         verbosestream << _("Using gameid") << " ["
798                       << game_params.game_spec.id << "]" << std::endl;
799
800         // Bind address
801         std::string bind_str = g_settings->get("bind_address");
802         Address bind_addr(0, 0, 0, 0, game_params.socket_port);
803
804         if (g_settings->getBool("ipv6_server")) {
805                 bind_addr.setAddress((IPv6AddressBytes*) NULL);
806         }
807         try {
808                 bind_addr.Resolve(bind_str.c_str());
809         } catch (ResolveError &e) {
810                 infostream << "Resolving bind address \"" << bind_str
811                            << "\" failed: " << e.what()
812                            << " -- Listening on all addresses." << std::endl;
813         }
814         if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
815                 errorstream << "Unable to listen on "
816                             << bind_addr.serializeString()
817                             << L" because IPv6 is disabled" << std::endl;
818                 return false;
819         }
820
821         // Database migration
822         if (cmd_args.exists("migrate"))
823                 return migrate_database(game_params, cmd_args);
824
825         // Create server
826         Server server(game_params.world_path, game_params.game_spec, false,
827                 bind_addr.isIPv6());
828         server.start(bind_addr);
829
830         // Run server
831         bool &kill = *porting::signal_handler_killstatus();
832         dedicated_server_loop(server, kill);
833
834         return true;
835 }
836
837 static bool migrate_database(const GameParams &game_params, const Settings &cmd_args)
838 {
839         std::string migrate_to = cmd_args.get("migrate");
840         Settings world_mt;
841         std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
842         if (!world_mt.readConfigFile(world_mt_path.c_str())) {
843                 errorstream << "Cannot read world.mt!" << std::endl;
844                 return false;
845         }
846         if (!world_mt.exists("backend")) {
847                 errorstream << "Please specify your current backend in world.mt:"
848                         << std::endl
849                         << "    backend = {sqlite3|leveldb|redis|dummy}"
850                         << std::endl;
851                 return false;
852         }
853         std::string backend = world_mt.get("backend");
854         if (backend == migrate_to) {
855                 errorstream << "Cannot migrate: new backend is same"
856                         << " as the old one" << std::endl;
857                 return false;
858         }
859         Database *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
860                 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
861
862         u32 count = 0;
863         time_t last_update_time = 0;
864         bool &kill = *porting::signal_handler_killstatus();
865
866         std::vector<v3s16> blocks;
867         old_db->listAllLoadableBlocks(blocks);
868         new_db->beginSave();
869         for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
870                 if (kill) return false;
871
872                 const std::string &data = old_db->loadBlock(*it);
873                 if (!data.empty()) {
874                         new_db->saveBlock(*it, data);
875                 } else {
876                         errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
877                 }
878                 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
879                         std::cerr << " Migrated " << count << " blocks, "
880                                 << (100.0 * count / blocks.size()) << "% completed.\r";
881                         new_db->endSave();
882                         new_db->beginSave();
883                         last_update_time = time(NULL);
884                 }
885         }
886         std::cerr << std::endl;
887         new_db->endSave();
888         delete old_db;
889         delete new_db;
890
891         actionstream << "Successfully migrated " << count << " blocks" << std::endl;
892         world_mt.set("backend", migrate_to);
893         if (!world_mt.updateConfigFile(world_mt_path.c_str()))
894                 errorstream << "Failed to update world.mt!" << std::endl;
895         else
896                 actionstream << "world.mt updated" << std::endl;
897
898         return true;
899 }
900