3 Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
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.
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.
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.
21 #include "convert_json.h"
22 #include "database-files.h"
23 #include "remoteplayer.h"
27 #include "server/player_sao.h"
28 #include "util/string.h"
31 // This backend is intended to be used on Minetest 0.4.16 only for the transition backend
34 PlayerDatabaseFiles::PlayerDatabaseFiles(const std::string &savedir) : m_savedir(savedir)
36 fs::CreateDir(m_savedir);
39 void PlayerDatabaseFiles::deSerialize(RemotePlayer *p, std::istream &is,
40 const std::string &playername, PlayerSAO *sao)
42 Settings args("PlayerArgsEnd");
44 if (!args.parseConfigLines(is)) {
45 throw SerializationError("PlayerArgsEnd of player " + playername + " not found!");
49 //args.getS32("version"); // Version field value not used
50 const std::string &name = args.get("name");
51 strlcpy(p->m_name, name.c_str(), PLAYERNAME_SIZE);
55 sao->setHPRaw(args.getU16("hp"));
56 } catch(SettingNotFoundException &e) {
57 sao->setHPRaw(PLAYER_MAX_HP_DEFAULT);
61 sao->setBasePosition(args.getV3F("position"));
62 } catch (SettingNotFoundException &e) {}
65 sao->setLookPitch(args.getFloat("pitch"));
66 } catch (SettingNotFoundException &e) {}
68 sao->setPlayerYaw(args.getFloat("yaw"));
69 } catch (SettingNotFoundException &e) {}
72 sao->setBreath(args.getU16("breath"), false);
73 } catch (SettingNotFoundException &e) {}
76 const std::string &extended_attributes = args.get("extended_attributes");
77 std::istringstream iss(extended_attributes);
78 Json::CharReaderBuilder builder;
79 builder.settings_["collectComments"] = false;
82 Json::Value attr_root;
83 Json::parseFromStream(builder, iss, &attr_root, &errs);
85 const Json::Value::Members attr_list = attr_root.getMemberNames();
86 for (const auto &it : attr_list) {
87 Json::Value attr_value = attr_root[it];
88 sao->getMeta().setString(it, attr_value.asString());
90 sao->getMeta().setModified(false);
91 } catch (SettingNotFoundException &e) {}
95 p->inventory.deSerialize(is);
96 } catch (SerializationError &e) {
97 errorstream << "Failed to deserialize player inventory. player_name="
98 << name << " " << e.what() << std::endl;
101 if (!p->inventory.getList("craftpreview") && p->inventory.getList("craftresult")) {
102 // Convert players without craftpreview
103 p->inventory.addList("craftpreview", 1);
105 bool craftresult_is_preview = true;
106 if(args.exists("craftresult_is_preview"))
107 craftresult_is_preview = args.getBool("craftresult_is_preview");
108 if(craftresult_is_preview)
111 p->inventory.getList("craftresult")->changeItem(0, ItemStack());
116 void PlayerDatabaseFiles::serialize(RemotePlayer *p, std::ostream &os)
118 // Utilize a Settings object for storing values
119 Settings args("PlayerArgsEnd");
120 args.setS32("version", 1);
121 args.set("name", p->m_name);
123 PlayerSAO *sao = p->getPlayerSAO();
124 // This should not happen
126 args.setU16("hp", sao->getHP());
127 args.setV3F("position", sao->getBasePosition());
128 args.setFloat("pitch", sao->getLookPitch());
129 args.setFloat("yaw", sao->getRotation().Y);
130 args.setU16("breath", sao->getBreath());
132 std::string extended_attrs;
134 // serializeExtraAttributes
135 Json::Value json_root;
137 const StringMap &attrs = sao->getMeta().getStrings();
138 for (const auto &attr : attrs) {
139 json_root[attr.first] = attr.second;
142 extended_attrs = fastWriteJson(json_root);
144 args.set("extended_attributes", extended_attrs);
148 p->inventory.serialize(os);
151 void PlayerDatabaseFiles::savePlayer(RemotePlayer *player)
153 fs::CreateDir(m_savedir);
155 std::string savedir = m_savedir + DIR_DELIM;
156 std::string path = savedir + player->getName();
157 bool path_found = false;
158 RemotePlayer testplayer("", NULL);
160 for (u32 i = 0; i < PLAYER_FILE_ALTERNATE_TRIES && !path_found; i++) {
161 if (!fs::PathExists(path)) {
166 // Open and deserialize file to check player name
167 std::ifstream is(path.c_str(), std::ios_base::binary);
169 errorstream << "Failed to open " << path << std::endl;
173 deSerialize(&testplayer, is, path, NULL);
175 if (strcmp(testplayer.getName(), player->getName()) == 0) {
180 path = savedir + player->getName() + itos(i);
184 errorstream << "Didn't find free file for player " << player->getName()
189 // Open and serialize file
190 std::ostringstream ss(std::ios_base::binary);
191 serialize(player, ss);
192 if (!fs::safeWriteToFile(path, ss.str())) {
193 infostream << "Failed to write " << path << std::endl;
196 player->onSuccessfulSave();
199 bool PlayerDatabaseFiles::removePlayer(const std::string &name)
201 std::string players_path = m_savedir + DIR_DELIM;
202 std::string path = players_path + name;
204 RemotePlayer temp_player("", NULL);
205 for (u32 i = 0; i < PLAYER_FILE_ALTERNATE_TRIES; i++) {
206 // Open file and deserialize
207 std::ifstream is(path.c_str(), std::ios_base::binary);
211 deSerialize(&temp_player, is, path, NULL);
214 if (temp_player.getName() == name) {
215 fs::DeleteSingleFileOrEmptyDirectory(path);
219 path = players_path + name + itos(i);
225 bool PlayerDatabaseFiles::loadPlayer(RemotePlayer *player, PlayerSAO *sao)
227 std::string players_path = m_savedir + DIR_DELIM;
228 std::string path = players_path + player->getName();
230 const std::string player_to_load = player->getName();
231 for (u32 i = 0; i < PLAYER_FILE_ALTERNATE_TRIES; i++) {
232 // Open file and deserialize
233 std::ifstream is(path.c_str(), std::ios_base::binary);
237 deSerialize(player, is, path, sao);
240 if (player->getName() == player_to_load)
243 path = players_path + player_to_load + itos(i);
246 infostream << "Player file for player " << player_to_load << " not found" << std::endl;
250 void PlayerDatabaseFiles::listPlayers(std::vector<std::string> &res)
252 std::vector<fs::DirListNode> files = fs::GetDirListing(m_savedir);
253 // list files into players directory
254 for (std::vector<fs::DirListNode>::const_iterator it = files.begin(); it !=
256 // Ignore directories
260 const std::string &filename = it->name;
261 std::string full_path = m_savedir + DIR_DELIM + filename;
262 std::ifstream is(full_path.c_str(), std::ios_base::binary);
266 RemotePlayer player(filename.c_str(), NULL);
267 // Null env & dummy peer_id
268 PlayerSAO playerSAO(NULL, &player, 15789, false);
270 deSerialize(&player, is, "", &playerSAO);
273 res.emplace_back(player.getName());
277 AuthDatabaseFiles::AuthDatabaseFiles(const std::string &savedir) : m_savedir(savedir)
282 bool AuthDatabaseFiles::getAuth(const std::string &name, AuthEntry &res)
284 const auto res_i = m_auth_list.find(name);
285 if (res_i == m_auth_list.end()) {
292 bool AuthDatabaseFiles::saveAuth(const AuthEntry &authEntry)
294 m_auth_list[authEntry.name] = authEntry;
297 return writeAuthFile();
300 bool AuthDatabaseFiles::createAuth(AuthEntry &authEntry)
302 m_auth_list[authEntry.name] = authEntry;
305 return writeAuthFile();
308 bool AuthDatabaseFiles::deleteAuth(const std::string &name)
310 if (!m_auth_list.erase(name)) {
311 // did not delete anything -> hadn't existed
314 return writeAuthFile();
317 void AuthDatabaseFiles::listNames(std::vector<std::string> &res)
320 res.reserve(m_auth_list.size());
321 for (const auto &res_pair : m_auth_list) {
322 res.push_back(res_pair.first);
326 void AuthDatabaseFiles::reload()
331 bool AuthDatabaseFiles::readAuthFile()
333 std::string path = m_savedir + DIR_DELIM + "auth.txt";
334 std::ifstream file(path, std::ios::binary);
339 while (file.good()) {
341 std::getline(file, line);
342 std::vector<std::string> parts = str_split(line, ':');
343 if (parts.size() < 3) // also: empty line at end
345 const std::string &name = parts[0];
346 const std::string &password = parts[1];
347 std::vector<std::string> privileges = str_split(parts[2], ',');
348 s64 last_login = parts.size() > 3 ? atol(parts[3].c_str()) : 0;
350 m_auth_list[name] = {
361 bool AuthDatabaseFiles::writeAuthFile()
363 std::string path = m_savedir + DIR_DELIM + "auth.txt";
364 std::ostringstream output(std::ios_base::binary);
365 for (const auto &auth_i : m_auth_list) {
366 const AuthEntry &authEntry = auth_i.second;
367 output << authEntry.name << ":" << authEntry.password << ":";
368 output << str_join(authEntry.privileges, ",");
369 output << ":" << authEntry.last_login;
372 if (!fs::safeWriteToFile(path, output.str())) {
373 infostream << "Failed to write " << path << std::endl;
379 ModStorageDatabaseFiles::ModStorageDatabaseFiles(const std::string &savedir):
380 m_storage_dir(savedir + DIR_DELIM + "mod_storage")
384 void ModStorageDatabaseFiles::getModEntries(const std::string &modname, StringMap *storage)
386 Json::Value *meta = getOrCreateJson(modname);
390 const Json::Value::Members attr_list = meta->getMemberNames();
391 for (const auto &it : attr_list) {
392 Json::Value attr_value = (*meta)[it];
393 (*storage)[it] = attr_value.asString();
397 void ModStorageDatabaseFiles::getModKeys(const std::string &modname,
398 std::vector<std::string> *storage)
400 Json::Value *meta = getOrCreateJson(modname);
404 std::vector<std::string> keys = meta->getMemberNames();
405 storage->reserve(storage->size() + keys.size());
406 for (std::string &key : keys)
407 storage->push_back(std::move(key));
410 bool ModStorageDatabaseFiles::getModEntry(const std::string &modname,
411 const std::string &key, std::string *value)
413 Json::Value *meta = getOrCreateJson(modname);
417 if (meta->isMember(key)) {
418 *value = (*meta)[key].asString();
424 bool ModStorageDatabaseFiles::hasModEntry(const std::string &modname, const std::string &key)
426 Json::Value *meta = getOrCreateJson(modname);
427 return meta && meta->isMember(key);
430 bool ModStorageDatabaseFiles::setModEntry(const std::string &modname,
431 const std::string &key, const std::string &value)
433 Json::Value *meta = getOrCreateJson(modname);
437 (*meta)[key] = Json::Value(value);
438 m_modified.insert(modname);
443 bool ModStorageDatabaseFiles::removeModEntry(const std::string &modname,
444 const std::string &key)
446 Json::Value *meta = getOrCreateJson(modname);
451 if (meta->removeMember(key, &removed)) {
452 m_modified.insert(modname);
458 bool ModStorageDatabaseFiles::removeModEntries(const std::string &modname)
460 Json::Value *meta = getOrCreateJson(modname);
461 if (!meta || meta->empty())
465 m_modified.insert(modname);
469 void ModStorageDatabaseFiles::beginSave()
473 void ModStorageDatabaseFiles::endSave()
475 if (m_modified.empty())
478 if (!fs::CreateAllDirs(m_storage_dir)) {
479 errorstream << "ModStorageDatabaseFiles: Unable to save. '"
480 << m_storage_dir << "' cannot be created." << std::endl;
483 if (!fs::IsDir(m_storage_dir)) {
484 errorstream << "ModStorageDatabaseFiles: Unable to save. '"
485 << m_storage_dir << "' is not a directory." << std::endl;
489 for (auto it = m_modified.begin(); it != m_modified.end();) {
490 const std::string &modname = *it;
492 const Json::Value &json = m_mod_storage[modname];
494 if (!fs::safeWriteToFile(m_storage_dir + DIR_DELIM + modname, fastWriteJson(json))) {
495 errorstream << "ModStorageDatabaseFiles[" << modname
496 << "]: failed to write file." << std::endl;
501 it = m_modified.erase(it);
505 void ModStorageDatabaseFiles::listMods(std::vector<std::string> *res)
507 // List in-memory metadata first.
508 for (const auto &pair : m_mod_storage) {
509 res->push_back(pair.first);
512 // List other metadata present in the filesystem.
513 for (const auto &entry : fs::GetDirListing(m_storage_dir)) {
514 if (!entry.dir && m_mod_storage.count(entry.name) == 0)
515 res->push_back(entry.name);
519 Json::Value *ModStorageDatabaseFiles::getOrCreateJson(const std::string &modname)
521 auto found = m_mod_storage.find(modname);
522 if (found != m_mod_storage.end())
523 return &found->second;
525 Json::Value meta(Json::objectValue);
527 std::string path = m_storage_dir + DIR_DELIM + modname;
528 if (fs::PathExists(path)) {
529 std::ifstream is(path.c_str(), std::ios_base::binary);
531 Json::CharReaderBuilder builder;
532 builder.settings_["collectComments"] = false;
535 if (!Json::parseFromStream(builder, is, &meta, &errs)) {
536 errorstream << "ModStorageDatabaseFiles[" << modname
537 << "]: failed to decode data: " << errs << std::endl;
542 return &(m_mod_storage[modname] = std::move(meta));