Fix Android build, but there is a remaining linking issue in guiConfirmRegistration
[oweals/minetest.git] / src / mods.cpp
1 /*
2 Minetest
3 Copyright (C) 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 #include <cctype>
21 #include <fstream>
22 #include <json/json.h>
23 #include "mods.h"
24 #include "filesys.h"
25 #include "log.h"
26 #include "subgame.h"
27 #include "settings.h"
28 #include "porting.h"
29 #include "convert_json.h"
30
31 static bool parseDependsLine(std::istream &is,
32                 std::string &dep, std::set<char> &symbols)
33 {
34         std::getline(is, dep);
35         dep = trim(dep);
36         symbols.clear();
37         size_t pos = dep.size();
38         while(pos > 0 && !string_allowed(dep.substr(pos-1, 1), MODNAME_ALLOWED_CHARS)){
39                 // last character is a symbol, not part of the modname
40                 symbols.insert(dep[pos-1]);
41                 --pos;
42         }
43         dep = trim(dep.substr(0, pos));
44         return !dep.empty();
45 }
46
47 void parseModContents(ModSpec &spec)
48 {
49         // NOTE: this function works in mutual recursion with getModsInPath
50         Settings info;
51         info.readConfigFile((spec.path+DIR_DELIM+"mod.conf").c_str());
52
53         if (info.exists("name"))
54                 spec.name = info.get("name");
55
56         spec.depends.clear();
57         spec.optdepends.clear();
58         spec.is_modpack = false;
59         spec.modpack_content.clear();
60
61         // Handle modpacks (defined by containing modpack.txt)
62         std::ifstream modpack_is((spec.path+DIR_DELIM+"modpack.txt").c_str());
63         if(modpack_is.good()){ //a modpack, recursively get the mods in it
64                 modpack_is.close(); // We don't actually need the file
65                 spec.is_modpack = true;
66                 spec.modpack_content = getModsInPath(spec.path, true);
67
68                 // modpacks have no dependencies; they are defined and
69                 // tracked separately for each mod in the modpack
70         }
71         else{ // not a modpack, parse the dependencies
72                 std::ifstream is((spec.path+DIR_DELIM+"depends.txt").c_str());
73                 while(is.good()){
74                         std::string dep;
75                         std::set<char> symbols;
76                         if(parseDependsLine(is, dep, symbols)){
77                                 if(symbols.count('?') != 0){
78                                         spec.optdepends.insert(dep);
79                                 }
80                                 else{
81                                         spec.depends.insert(dep);
82                                 }
83                         }
84                 }
85         }
86 }
87
88 std::map<std::string, ModSpec> getModsInPath(const std::string &path,
89         bool part_of_modpack)
90 {
91         // NOTE: this function works in mutual recursion with parseModContents
92
93         std::map<std::string, ModSpec> result;
94         std::vector<fs::DirListNode> dirlist = fs::GetDirListing(path);
95         std::string modpath;
96
97         for (const fs::DirListNode &dln : dirlist) {
98                 if (!dln.dir)
99                         continue;
100
101                 const std::string &modname = dln.name;
102                 // Ignore all directories beginning with a ".", especially
103                 // VCS directories like ".git" or ".svn"
104                 if (modname[0] == '.')
105                         continue;
106
107                 modpath.clear();
108                 modpath.append(path)
109                         .append(DIR_DELIM)
110                         .append(modname);
111
112                 ModSpec spec(modname, modpath, part_of_modpack);
113                 parseModContents(spec);
114                 result.insert(std::make_pair(modname, spec));
115         }
116         return result;
117 }
118
119 std::vector<ModSpec> flattenMods(std::map<std::string, ModSpec> mods)
120 {
121         std::vector<ModSpec> result;
122         for (const auto &it : mods) {
123                 const ModSpec &mod = it.second;
124                 if (mod.is_modpack) {
125                         std::vector<ModSpec> content = flattenMods(mod.modpack_content);
126                         result.reserve(result.size() + content.size());
127                         result.insert(result.end(),content.begin(),content.end());
128
129                 }
130                 else //not a modpack
131                 {
132                         result.push_back(mod);
133                 }
134         }
135         return result;
136 }
137
138 ModConfiguration::ModConfiguration(const std::string &worldpath)
139 {
140 }
141
142 void ModConfiguration::printUnsatisfiedModsError() const
143 {
144         for (const ModSpec &mod : m_unsatisfied_mods) {
145                 errorstream << "mod \"" << mod.name << "\" has unsatisfied dependencies: ";
146                 for (const std::string &unsatisfied_depend : mod.unsatisfied_depends)
147                         errorstream << " \"" << unsatisfied_depend << "\"";
148                 errorstream << std::endl;
149         }
150 }
151
152 void ModConfiguration::addModsInPath(const std::string &path)
153 {
154         addMods(flattenMods(getModsInPath(path)));
155 }
156
157 void ModConfiguration::addMods(const std::vector<ModSpec> &new_mods)
158 {
159         // Maintain a map of all existing m_unsatisfied_mods.
160         // Keys are mod names and values are indices into m_unsatisfied_mods.
161         std::map<std::string, u32> existing_mods;
162         for(u32 i = 0; i < m_unsatisfied_mods.size(); ++i){
163                 existing_mods[m_unsatisfied_mods[i].name] = i;
164         }
165
166         // Add new mods
167         for(int want_from_modpack = 1; want_from_modpack >= 0; --want_from_modpack){
168                 // First iteration:
169                 // Add all the mods that come from modpacks
170                 // Second iteration:
171                 // Add all the mods that didn't come from modpacks
172
173                 std::set<std::string> seen_this_iteration;
174
175                 for (const ModSpec &mod : new_mods) {
176                         if (mod.part_of_modpack != (bool)want_from_modpack)
177                                 continue;
178
179                         if (existing_mods.count(mod.name) == 0) {
180                                 // GOOD CASE: completely new mod.
181                                 m_unsatisfied_mods.push_back(mod);
182                                 existing_mods[mod.name] = m_unsatisfied_mods.size() - 1;
183                         } else if(seen_this_iteration.count(mod.name) == 0) {
184                                 // BAD CASE: name conflict in different levels.
185                                 u32 oldindex = existing_mods[mod.name];
186                                 const ModSpec &oldmod = m_unsatisfied_mods[oldindex];
187                                 warningstream<<"Mod name conflict detected: \""
188                                         <<mod.name<<"\""<<std::endl
189                                         <<"Will not load: "<<oldmod.path<<std::endl
190                                         <<"Overridden by: "<<mod.path<<std::endl;
191                                 m_unsatisfied_mods[oldindex] = mod;
192
193                                 // If there was a "VERY BAD CASE" name conflict
194                                 // in an earlier level, ignore it.
195                                 m_name_conflicts.erase(mod.name);
196                         } else {
197                                 // VERY BAD CASE: name conflict in the same level.
198                                 u32 oldindex = existing_mods[mod.name];
199                                 const ModSpec &oldmod = m_unsatisfied_mods[oldindex];
200                                 warningstream<<"Mod name conflict detected: \""
201                                         <<mod.name<<"\""<<std::endl
202                                         <<"Will not load: "<<oldmod.path<<std::endl
203                                         <<"Will not load: "<<mod.path<<std::endl;
204                                 m_unsatisfied_mods[oldindex] = mod;
205                                 m_name_conflicts.insert(mod.name);
206                         }
207
208                         seen_this_iteration.insert(mod.name);
209                 }
210         }
211 }
212
213 void ModConfiguration::addModsFromConfig(const std::string &settings_path, const std::set<std::string> &mods)
214 {
215         Settings conf;
216         std::set<std::string> load_mod_names;
217
218         conf.readConfigFile(settings_path.c_str());
219         std::vector<std::string> names = conf.getNames();
220         for (const std::string &name : names) {
221                 if (name.compare(0,9,"load_mod_")==0 && conf.getBool(name))
222                         load_mod_names.insert(name.substr(9));
223         }
224
225         std::vector<ModSpec> addon_mods;
226         for (const std::string &i : mods) {
227                 std::vector<ModSpec> addon_mods_in_path = flattenMods(getModsInPath(i));
228                 for (std::vector<ModSpec>::const_iterator it = addon_mods_in_path.begin();
229                                 it != addon_mods_in_path.end(); ++it) {
230                         const ModSpec& mod = *it;
231                         if (load_mod_names.count(mod.name) != 0)
232                                 addon_mods.push_back(mod);
233                         else
234                                 conf.setBool("load_mod_" + mod.name, false);
235                 }
236         }
237         conf.updateConfigFile(settings_path.c_str());
238
239         addMods(addon_mods);
240         checkConflictsAndDeps();
241
242         // complain about mods declared to be loaded, but not found
243         for (const ModSpec &addon_mod : addon_mods)
244                 load_mod_names.erase(addon_mod.name);
245
246         std::vector<ModSpec> unsatisfiedMods = getUnsatisfiedMods();
247
248         for (const ModSpec &unsatisfiedMod : unsatisfiedMods)
249                 load_mod_names.erase(unsatisfiedMod.name);
250
251         if (!load_mod_names.empty()) {
252                 errorstream << "The following mods could not be found:";
253                 for (const std::string &mod : load_mod_names)
254                         errorstream << " \"" << mod << "\"";
255                 errorstream << std::endl;
256         }
257 }
258
259 void ModConfiguration::checkConflictsAndDeps()
260 {
261         // report on name conflicts
262         if (!m_name_conflicts.empty()) {
263                 std::string s = "Unresolved name conflicts for mods ";
264                 for (std::unordered_set<std::string>::const_iterator it =
265                         m_name_conflicts.begin(); it != m_name_conflicts.end(); ++it) {
266                         if (it != m_name_conflicts.begin()) s += ", ";
267                         s += std::string("\"") + (*it) + "\"";
268                 }
269                 s += ".";
270                 throw ModError(s);
271         }
272
273         // get the mods in order
274         resolveDependencies();
275 }
276
277 void ModConfiguration::resolveDependencies()
278 {
279         // Step 1: Compile a list of the mod names we're working with
280         std::set<std::string> modnames;
281         for (const ModSpec &mod : m_unsatisfied_mods) {
282                 modnames.insert(mod.name);
283         }
284
285         // Step 2: get dependencies (including optional dependencies)
286         // of each mod, split mods into satisfied and unsatisfied
287         std::list<ModSpec> satisfied;
288         std::list<ModSpec> unsatisfied;
289         for (ModSpec mod : m_unsatisfied_mods) {
290                 mod.unsatisfied_depends = mod.depends;
291                 // check which optional dependencies actually exist
292                 for (const std::string &optdep : mod.optdepends) {
293                         if (modnames.count(optdep) != 0)
294                                 mod.unsatisfied_depends.insert(optdep);
295                 }
296                 // if a mod has no depends it is initially satisfied
297                 if (mod.unsatisfied_depends.empty())
298                         satisfied.push_back(mod);
299                 else
300                         unsatisfied.push_back(mod);
301         }
302
303         // Step 3: mods without unmet dependencies can be appended to
304         // the sorted list.
305         while(!satisfied.empty()){
306                 ModSpec mod = satisfied.back();
307                 m_sorted_mods.push_back(mod);
308                 satisfied.pop_back();
309                 for (auto it = unsatisfied.begin(); it != unsatisfied.end(); ) {
310                         ModSpec& mod2 = *it;
311                         mod2.unsatisfied_depends.erase(mod.name);
312                         if (mod2.unsatisfied_depends.empty()) {
313                                 satisfied.push_back(mod2);
314                                 it = unsatisfied.erase(it);
315                         } else {
316                                 ++it;
317                         }
318                 }
319         }
320
321         // Step 4: write back list of unsatisfied mods
322         m_unsatisfied_mods.assign(unsatisfied.begin(), unsatisfied.end());
323 }
324
325 ServerModConfiguration::ServerModConfiguration(const std::string &worldpath):
326         ModConfiguration(worldpath)
327 {
328         SubgameSpec gamespec = findWorldSubgame(worldpath);
329
330         // Add all game mods and all world mods
331         addModsInPath(gamespec.gamemods_path);
332         addModsInPath(worldpath + DIR_DELIM + "worldmods");
333
334         // Load normal mods
335         std::string worldmt = worldpath + DIR_DELIM + "world.mt";
336         addModsFromConfig(worldmt, gamespec.addon_mods_paths);
337 }
338
339 #ifndef SERVER
340 ClientModConfiguration::ClientModConfiguration(const std::string &path):
341         ModConfiguration(path)
342 {
343         std::set<std::string> paths;
344         std::string path_user = porting::path_user + DIR_DELIM + "clientmods";
345         paths.insert(path);
346         paths.insert(path_user);
347
348         std::string settings_path = path_user + DIR_DELIM + "mods.conf";
349         addModsFromConfig(settings_path, paths);
350 }
351 #endif
352
353 ModMetadata::ModMetadata(const std::string &mod_name):
354         m_mod_name(mod_name)
355 {
356 }
357
358 void ModMetadata::clear()
359 {
360         Metadata::clear();
361         m_modified = true;
362 }
363
364 bool ModMetadata::save(const std::string &root_path)
365 {
366         Json::Value json;
367         for (StringMap::const_iterator it = m_stringvars.begin();
368                         it != m_stringvars.end(); ++it) {
369                 json[it->first] = it->second;
370         }
371
372         if (!fs::PathExists(root_path)) {
373                 if (!fs::CreateAllDirs(root_path)) {
374                         errorstream << "ModMetadata[" << m_mod_name << "]: Unable to save. '"
375                                 << root_path << "' tree cannot be created." << std::endl;
376                         return false;
377                 }
378         } else if (!fs::IsDir(root_path)) {
379                 errorstream << "ModMetadata[" << m_mod_name << "]: Unable to save. '"
380                         << root_path << "' is not a directory." << std::endl;
381                 return false;
382         }
383
384         bool w_ok = fs::safeWriteToFile(root_path + DIR_DELIM + m_mod_name,
385                         fastWriteJson(json));
386
387         if (w_ok) {
388                 m_modified = false;
389         } else {
390                 errorstream << "ModMetadata[" << m_mod_name << "]: failed write file." << std::endl;
391         }
392         return w_ok;
393 }
394
395 bool ModMetadata::load(const std::string &root_path)
396 {
397         m_stringvars.clear();
398
399         std::ifstream is((root_path + DIR_DELIM + m_mod_name).c_str(), std::ios_base::binary);
400         if (!is.good()) {
401                 return false;
402         }
403
404         Json::Value root;
405         Json::CharReaderBuilder builder;
406         builder.settings_["collectComments"] = false;
407         std::string errs;
408
409         if (!Json::parseFromStream(builder, is, &root, &errs)) {
410                 errorstream << "ModMetadata[" << m_mod_name << "]: failed read data "
411                         "(Json decoding failure). Message: " << errs << std::endl;
412                 return false;
413         }
414
415         const Json::Value::Members attr_list = root.getMemberNames();
416         for (const auto &it : attr_list) {
417                 Json::Value attr_value = root[it];
418                 m_stringvars[it] = attr_value.asString();
419         }
420
421         return true;
422 }
423
424 bool ModMetadata::setString(const std::string &name, const std::string &var)
425 {
426         m_modified = Metadata::setString(name, var);
427         return m_modified;
428 }