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