Skip to content

Commit 3ce03d1

Browse files
author
Hugues Ross
authoredJul 28, 2020
Sanitize world directory names on create. Keep original name separate (#9432)
Blacklisted characters are replaced by '_' in the path. The display name is stored in world.mt, and duplicate file names are resolved by adding an incrementing suffix (_1, _2, _3, etc).
1 parent f948e2c commit 3ce03d1

File tree

6 files changed

+136
-17
lines changed

6 files changed

+136
-17
lines changed
 

Diff for: ‎src/content/subgames.cpp

+44-10
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ with this program; if not, write to the Free Software Foundation, Inc.,
3131
#include "client/tile.h" // getImagePath
3232
#endif
3333

34+
// The maximum number of identical world names allowed
35+
#define MAX_WORLD_NAMES 100
36+
3437
bool getGameMinetestConfig(const std::string &game_path, Settings &conf)
3538
{
3639
std::string conf_path = game_path + DIR_DELIM + "minetest.conf";
@@ -213,6 +216,21 @@ bool getWorldExists(const std::string &world_path)
213216
fs::PathExists(world_path + DIR_DELIM + "world.mt"));
214217
}
215218

219+
//! Try to get the displayed name of a world
220+
std::string getWorldName(const std::string &world_path, const std::string &default_name)
221+
{
222+
std::string conf_path = world_path + DIR_DELIM + "world.mt";
223+
Settings conf;
224+
bool succeeded = conf.readConfigFile(conf_path.c_str());
225+
if (!succeeded) {
226+
return default_name;
227+
}
228+
229+
if (!conf.exists("world_name"))
230+
return default_name;
231+
return conf.get("world_name");
232+
}
233+
216234
std::string getWorldGameId(const std::string &world_path, bool can_be_legacy)
217235
{
218236
std::string conf_path = world_path + DIR_DELIM + "world.mt";
@@ -259,7 +277,7 @@ std::vector<WorldSpec> getAvailableWorlds()
259277
if (!dln.dir)
260278
continue;
261279
std::string fullpath = worldspath + DIR_DELIM + dln.name;
262-
std::string name = dln.name;
280+
std::string name = getWorldName(fullpath, dln.name);
263281
// Just allow filling in the gameid always for now
264282
bool can_be_legacy = true;
265283
std::string gameid = getWorldGameId(fullpath, can_be_legacy);
@@ -288,8 +306,24 @@ std::vector<WorldSpec> getAvailableWorlds()
288306
return worlds;
289307
}
290308

291-
bool loadGameConfAndInitWorld(const std::string &path, const SubgameSpec &gamespec)
309+
void loadGameConfAndInitWorld(const std::string &path, const std::string &name,
310+
const SubgameSpec &gamespec, bool create_world)
292311
{
312+
std::string final_path = path;
313+
314+
// If we're creating a new world, ensure that the path isn't already taken
315+
if (create_world) {
316+
int counter = 1;
317+
while (fs::PathExists(final_path) && counter < MAX_WORLD_NAMES) {
318+
final_path = path + "_" + std::to_string(counter);
319+
counter++;
320+
}
321+
322+
if (fs::PathExists(final_path)) {
323+
throw BaseException("Too many similar filenames");
324+
}
325+
}
326+
293327
// Override defaults with those provided by the game.
294328
// We clear and reload the defaults because the defaults
295329
// might have been overridden by other subgame config
@@ -300,32 +334,33 @@ bool loadGameConfAndInitWorld(const std::string &path, const SubgameSpec &gamesp
300334
getGameMinetestConfig(gamespec.path, game_defaults);
301335
g_settings->overrideDefaults(&game_defaults);
302336

303-
infostream << "Initializing world at " << path << std::endl;
337+
infostream << "Initializing world at " << final_path << std::endl;
304338

305-
fs::CreateAllDirs(path);
339+
fs::CreateAllDirs(final_path);
306340

307341
// Create world.mt if does not already exist
308-
std::string worldmt_path = path + DIR_DELIM "world.mt";
342+
std::string worldmt_path = final_path + DIR_DELIM "world.mt";
309343
if (!fs::PathExists(worldmt_path)) {
310344
Settings conf;
311345

346+
conf.set("world_name", name);
312347
conf.set("gameid", gamespec.id);
313348
conf.set("backend", "sqlite3");
314349
conf.set("player_backend", "sqlite3");
315350
conf.set("auth_backend", "sqlite3");
316351
conf.setBool("creative_mode", g_settings->getBool("creative_mode"));
317352
conf.setBool("enable_damage", g_settings->getBool("enable_damage"));
318353

319-
if (!conf.updateConfigFile(worldmt_path.c_str()))
320-
return false;
354+
if (!conf.updateConfigFile(worldmt_path.c_str())) {
355+
throw BaseException("Failed to update the config file");
356+
}
321357
}
322358

323359
// Create map_meta.txt if does not already exist
324-
std::string map_meta_path = path + DIR_DELIM + "map_meta.txt";
360+
std::string map_meta_path = final_path + DIR_DELIM + "map_meta.txt";
325361
if (!fs::PathExists(map_meta_path)) {
326362
verbosestream << "Creating map_meta.txt (" << map_meta_path << ")"
327363
<< std::endl;
328-
fs::CreateAllDirs(path);
329364
std::ostringstream oss(std::ios_base::binary);
330365

331366
Settings conf;
@@ -338,5 +373,4 @@ bool loadGameConfAndInitWorld(const std::string &path, const SubgameSpec &gamesp
338373

339374
fs::safeWriteToFile(map_meta_path, oss.str());
340375
}
341-
return true;
342376
}

Diff for: ‎src/content/subgames.h

+4-1
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ std::set<std::string> getAvailableGameIds();
6363
std::vector<SubgameSpec> getAvailableGames();
6464

6565
bool getWorldExists(const std::string &world_path);
66+
//! Try to get the displayed name of a world
67+
std::string getWorldName(const std::string &world_path, const std::string &default_name);
6668
std::string getWorldGameId(const std::string &world_path, bool can_be_legacy = false);
6769

6870
struct WorldSpec
@@ -88,4 +90,5 @@ std::vector<WorldSpec> getAvailableWorlds();
8890

8991
// loads the subgame's config and creates world directory
9092
// and world.mt if they don't exist
91-
bool loadGameConfAndInitWorld(const std::string &path, const SubgameSpec &gamespec);
93+
void loadGameConfAndInitWorld(const std::string &path, const std::string &name,
94+
const SubgameSpec &gamespec, bool create_world);

Diff for: ‎src/script/lua_api/l_mainmenu.cpp

+5-4
Original file line numberDiff line numberDiff line change
@@ -618,18 +618,19 @@ int ModApiMainMenu::l_create_world(lua_State *L)
618618

619619
std::string path = porting::path_user + DIR_DELIM
620620
"worlds" + DIR_DELIM
621-
+ name;
621+
+ sanitizeDirName(name, "world_");
622622

623623
std::vector<SubgameSpec> games = getAvailableGames();
624624

625625
if ((gameidx >= 0) &&
626626
(gameidx < (int) games.size())) {
627627

628628
// Create world if it doesn't exist
629-
if (!loadGameConfAndInitWorld(path, games[gameidx])) {
630-
lua_pushstring(L, "Failed to initialize world");
631-
} else {
629+
try {
630+
loadGameConfAndInitWorld(path, name, games[gameidx], true);
632631
lua_pushnil(L);
632+
} catch (const BaseException &e) {
633+
lua_pushstring(L, (std::string("Failed to initialize world: ") + e.what()).c_str());
633634
}
634635
} else {
635636
lua_pushstring(L, "Invalid game index");

Diff for: ‎src/server.cpp

+7-2
Original file line numberDiff line numberDiff line change
@@ -356,8 +356,13 @@ void Server::init()
356356
infostream << "- game: " << m_gamespec.path << std::endl;
357357

358358
// Create world if it doesn't exist
359-
if (!loadGameConfAndInitWorld(m_path_world, m_gamespec))
360-
throw ServerError("Failed to initialize world");
359+
try {
360+
loadGameConfAndInitWorld(m_path_world,
361+
fs::GetFilenameFromPath(m_path_world.c_str()),
362+
m_gamespec, false);
363+
} catch (const BaseException &e) {
364+
throw ServerError(std::string("Failed to initialize world: ") + e.what());
365+
}
361366

362367
// Create emerge manager
363368
m_emerge = new EmergeManager(this);

Diff for: ‎src/util/string.cpp

+68
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
2727
#include "translation.h"
2828

2929
#include <algorithm>
30+
#include <array>
3031
#include <sstream>
3132
#include <iomanip>
3233
#include <map>
@@ -889,3 +890,70 @@ std::wstring translate_string(const std::wstring &s)
889890
return translate_string(s, g_client_translations);
890891
#endif
891892
}
893+
894+
static const std::array<std::wstring, 22> disallowed_dir_names = {
895+
// Problematic filenames from here:
896+
// https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#file-and-directory-names
897+
L"CON",
898+
L"PRN",
899+
L"AUX",
900+
L"NUL",
901+
L"COM1",
902+
L"COM2",
903+
L"COM3",
904+
L"COM4",
905+
L"COM5",
906+
L"COM6",
907+
L"COM7",
908+
L"COM8",
909+
L"COM9",
910+
L"LPT1",
911+
L"LPT2",
912+
L"LPT3",
913+
L"LPT4",
914+
L"LPT5",
915+
L"LPT6",
916+
L"LPT7",
917+
L"LPT8",
918+
L"LPT9",
919+
};
920+
921+
/**
922+
* List of characters that are blacklisted from created directories
923+
*/
924+
static const std::wstring disallowed_path_chars = L"<>:\"/\\|?*.";
925+
926+
/**
927+
* Sanitize the name of a new directory. This consists of two stages:
928+
* 1. Check for 'reserved filenames' that can't be used on some filesystems
929+
* and add a prefix to them
930+
* 2. Remove 'unsafe' characters from the name by replacing them with '_'
931+
*/
932+
std::string sanitizeDirName(const std::string &str, const std::string &optional_prefix)
933+
{
934+
std::wstring safe_name = utf8_to_wide(str);
935+
936+
for (std::wstring disallowed_name : disallowed_dir_names) {
937+
if (str_equal(safe_name, disallowed_name, true)) {
938+
safe_name = utf8_to_wide(optional_prefix) + safe_name;
939+
break;
940+
}
941+
}
942+
943+
for (unsigned long i = 0; i < safe_name.length(); i++) {
944+
bool is_valid = true;
945+
946+
// Unlikely, but control characters should always be blacklisted
947+
if (safe_name[i] < 32) {
948+
is_valid = false;
949+
} else if (safe_name[i] < 128) {
950+
is_valid = disallowed_path_chars.find_first_of(safe_name[i])
951+
== std::wstring::npos;
952+
}
953+
954+
if (!is_valid)
955+
safe_name[i] = '_';
956+
}
957+
958+
return wide_to_utf8(safe_name);
959+
}

Diff for: ‎src/util/string.h

+8
Original file line numberDiff line numberDiff line change
@@ -746,3 +746,11 @@ inline irr::core::stringw utf8_to_stringw(const std::string &input)
746746
std::wstring str = utf8_to_wide(input);
747747
return irr::core::stringw(str.c_str());
748748
}
749+
750+
/**
751+
* Sanitize the name of a new directory. This consists of two stages:
752+
* 1. Check for 'reserved filenames' that can't be used on some filesystems
753+
* and prefix them
754+
* 2. Remove 'unsafe' characters from the name by replacing them with '_'
755+
*/
756+
std::string sanitizeDirName(const std::string &str, const std::string &optional_prefix);

0 commit comments

Comments
 (0)
Please sign in to comment.