The Battle for Wesnoth  1.19.7+dev
filesystem_common.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2017 - 2024
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
15 #include "filesystem.hpp"
16 #include "wesconfig.h"
17 
18 #include "config.hpp"
19 #include "log.hpp"
22 #include "utils/general.hpp"
23 
24 #include <boost/algorithm/string.hpp>
25 
26 static lg::log_domain log_filesystem("filesystem");
27 #define LOG_FS LOG_STREAM(info, log_filesystem)
28 #define ERR_FS LOG_STREAM(err, log_filesystem)
29 
30 namespace filesystem
31 {
32 
33 bool is_legal_user_file_name(const std::string& name, bool allow_whitespace)
34 {
35  //
36  // IMPORTANT NOTE:
37  //
38  // If you modify this function you must be aware that it is used by the
39  // add-on server validation routines both on the client and server sides.
40  // The addition or removal of any criteria here should be carefully
41  // evaluated with this in mind.
42  //
43 
44  if(name.empty() || name.back() == '.' || name.find("..") != std::string::npos || name.size() > 255) {
45  return false;
46  }
47 
48  // Reserved DOS device names on Windows.
49  static const std::set<std::string> dos_device_names = {
50  // Hardware devices
51  "NUL", "CON", "AUX", "PRN",
52  "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
53  "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
54  // Console API pseudo-devices
55  "CONIN$", "CONOUT$",
56  };
57 
58  // We can't use filesystem::base_name() here, because it returns the
59  // filename up to the *last* dot. "CON.foo.bar" is still redirected to
60  // "CON" on Windows, although "foo.CON.bar" and "foo.bar.CON" are not.
61  //
62  // Do also note that we're relying on the char-by-char check further below
63  // to flag the name as illegal if it contains a colon ':', the reason
64  // being that is valid to refer to DOS device names with a trailing colon
65  // (e.g. "CON:" is synonymous with "CON").
66 
67  const auto& first_name =
68  boost::algorithm::to_upper_copy(name.substr(0, name.find('.')), std::locale::classic());
69 
70  if(dos_device_names.count(first_name)) {
71  return false;
72  }
73 
74  const auto& name_ucs4 = unicode_cast<std::u32string>(name);
75  if(name != unicode_cast<std::string>(name_ucs4)){
76  return false; // name is an invalid UTF-8 sequence
77  }
78 
79  return name_ucs4.end() == std::find_if(name_ucs4.begin(), name_ucs4.end(), [=](char32_t c)
80  {
81  switch(c) {
82  case ' ':
83  return !allow_whitespace;
84  case '"':
85  case '*':
86  case '/':
87  case ':':
88  case '<':
89  case '>':
90  case '?':
91  case '\\':
92  case '|':
93  case '~':
94  case 0x7F: // DEL
95  return true;
96  default:
97  return c < 0x20 || // C0 control characters
98  (c >= 0x80 && c < 0xA0) || // C1 control characters
99  (c >= 0xD800 && c < 0xE000); // surrogate pairs
100  }
101  });
102 }
103 
104 void blacklist_pattern_list::remove_blacklisted_files_and_dirs(std::vector<std::string>& files, std::vector<std::string>& directories) const
105 {
106  utils::erase_if(files, [this](const std::string& name) { return match_file(name); });
107  utils::erase_if(directories, [this](const std::string& name) { return match_dir(name); });
108 }
109 
110 bool blacklist_pattern_list::match_file(const std::string& name) const
111 {
112  return std::any_of(file_patterns_.begin(), file_patterns_.end(),
113  std::bind(&utils::wildcard_string_match, std::ref(name), std::placeholders::_1));
114 }
115 
116 bool blacklist_pattern_list::match_dir(const std::string& name) const
117 {
118  return std::any_of(directory_patterns_.begin(), directory_patterns_.end(),
119  std::bind(&utils::wildcard_string_match, std::ref(name), std::placeholders::_1));
120 }
121 
122 std::string autodetect_game_data_dir(std::string exe_dir)
123 {
124  std::string auto_dir;
125 
126  // scons leaves the resulting binaries at the root of the source
127  // tree by default.
128  if(filesystem::file_exists(exe_dir + "/data/_main.cfg")) {
129  auto_dir = std::move(exe_dir);
130  }
131  // cmake encourages creating a subdir at the root of the source
132  // tree for the build, and the resulting binaries are found in it.
133  else if(filesystem::file_exists(exe_dir + "/../data/_main.cfg")) {
134  auto_dir = filesystem::normalize_path(exe_dir + "/..");
135  }
136  // Allow using the current working directory as the game data dir
137  else if(filesystem::file_exists(filesystem::get_cwd() + "/data/_main.cfg")) {
138  auto_dir = filesystem::get_cwd();
139  }
140 #ifdef _WIN32
141  // In Windows builds made using Visual Studio and its CMake
142  // integration, the EXE is placed a few levels below the game data
143  // dir (e.g. .\out\build\x64-Debug).
144  else if(filesystem::file_exists(exe_dir + "/../../build") && filesystem::file_exists(exe_dir + "/../../../out")
145  && filesystem::file_exists(exe_dir + "/../../../data/_main.cfg")) {
146  auto_dir = filesystem::normalize_path(exe_dir + "/../../..");
147  }
148 #endif
149 
150  return auto_dir;
151 }
152 
154 {
155  return get_sync_dir() + "/preferences";
156 }
157 
159 {
160  return get_user_data_dir() + "/preferences";
161 }
162 
163 std::string get_credentials_file()
164 {
165  return get_user_data_dir() + "/credentials-aes";
166 }
167 
169 {
170 #ifdef HAS_RELATIVE_DEFPREF
172 #else
174 #endif
175 }
176 
177 std::string get_save_index_file()
178 {
179  return get_user_data_dir() + "/save_index";
180 }
181 
182 std::string get_lua_history_file()
183 {
184  return get_sync_dir() + "/lua_command_history";
185 }
186 
187 std::string get_sync_dir()
188 {
189  return get_user_data_dir() + "/sync";
190 }
191 
192 std::string get_saves_dir()
193 {
194  const std::string dir_path = get_sync_dir() + "/saves";
195  return get_dir(dir_path);
196 }
197 
198 std::string get_addons_data_dir()
199 {
200  const std::string dir_path = get_user_data_dir() + "/data";
201  return get_dir(dir_path);
202 }
203 
204 std::string get_addons_dir()
205 {
206  const std::string dir_path = get_addons_data_dir() + "/add-ons";
207  return get_dir(dir_path);
208 }
209 
210 std::string get_wml_persist_dir()
211 {
212  const std::string dir_path = get_sync_dir() + "/persist";
213  return get_dir(dir_path);
214 }
215 
217 {
218  const std::string dir_path = get_sync_dir() + "/editor";
219  return get_dir(dir_path);
220 }
221 
222 std::string get_current_editor_dir(const std::string& addon_id)
223 {
224  if(addon_id == "mainline") {
225  return get_dir(game_config::path) + "/data/multiplayer";
226  } else {
227  return get_addons_dir() + "/" + addon_id;
228  }
229 }
230 
231 std::string get_core_images_dir()
232 {
233  return get_dir(game_config::path + "/data/core/images");
234 }
235 
236 std::string get_intl_dir()
237 {
238 #ifdef _WIN32
239  return game_config::path + "/" LOCALEDIR;
240 #else
241 
242 #ifdef USE_INTERNAL_DATA
243  return get_cwd() + "/" LOCALEDIR;
244 #endif
245 
246 #if HAS_RELATIVE_LOCALEDIR
247  std::string res = game_config::path + "/" LOCALEDIR;
248 #else
249  std::string res = LOCALEDIR;
250 #endif
251 
252  return res;
253 #endif
254 }
255 
256 std::string get_screenshot_dir()
257 {
258  const std::string dir_path = get_user_data_dir() + "/screenshots";
259  return get_dir(dir_path);
260 }
261 
262 bool looks_like_pbl(const std::string& file)
263 {
264  return utils::wildcard_string_match(utf8::lowercase(file), "*.pbl");
265 }
266 
267 file_tree_checksum::file_tree_checksum()
268  : nfiles(0), sum_size(0), modified(0)
269 {}
270 
272  nfiles (cfg["nfiles"].to_size_t()),
273  sum_size(cfg["size"].to_size_t()),
274  modified(cfg["modified"].to_time_t())
275 {
276 }
277 
279 {
280  cfg["nfiles"] = nfiles;
281  cfg["size"] = sum_size;
282  cfg["modified"] = modified;
283 }
284 
286 {
287  return nfiles == rhs.nfiles && sum_size == rhs.sum_size &&
288  modified == rhs.modified;
289 }
290 
291 std::string read_map(const std::string& name)
292 {
293  std::string res;
294  auto map_location = get_wml_location(name);
295  if(!map_location) {
296  // Consult [binary_path] for maps as well.
297  map_location = get_binary_file_location("maps", name);
298  }
299  if(map_location) {
300  res = read_file(map_location.value());
301  }
302 
303  if(res.empty()) {
304  res = read_file(get_legacy_editor_dir() + "/maps/" + name);
305  }
306 
307  return res;
308 }
309 
310 std::string read_scenario(const std::string& name)
311 {
312  std::string res;
313  auto file_location = get_wml_location(name);
314  if(!file_location) {
315  // Consult [binary_path] for scenarios as well.
316  file_location = get_binary_file_location("scenarios", name);
317  }
318  if(file_location) {
319  res = read_file(file_location.value());
320  }
321 
322  if(res.empty()) {
323  res = read_file(get_legacy_editor_dir() + "/scenarios/" + name);
324  }
325 
326  return res;
327 }
328 
329 static void get_file_tree_checksum_internal(const std::string& path, file_tree_checksum& res)
330 {
331 
332  std::vector<std::string> dirs;
334 
335  for(std::vector<std::string>::const_iterator j = dirs.begin(); j != dirs.end(); ++j) {
337  }
338 }
339 
341 {
342  static file_tree_checksum checksum;
343  if (reset)
344  checksum.reset();
345  if(checksum.nfiles == 0) {
346  get_file_tree_checksum_internal("data/",checksum);
347  get_file_tree_checksum_internal(get_user_data_dir() + "/data/",checksum);
348  LOG_FS << "calculated data tree checksum: "
349  << checksum.nfiles << " files; "
350  << checksum.sum_size << " bytes";
351  }
352 
353  return checksum;
354 }
355 
356 }
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:172
Definitions for the interface to Wesnoth Markup Language (WML).
Declarations for File-IO.
static lg::log_domain log_filesystem("filesystem")
#define LOG_FS
Standard logging facilities (interface).
std::string get_legacy_editor_dir()
void get_files_in_dir(const std::string &dir, std::vector< std::string > *files, std::vector< std::string > *dirs, name_mode mode, filter_mode filter, reorder_mode reorder, file_tree_checksum *checksum)
Get a list of all files and/or directories in a given directory.
Definition: filesystem.cpp:445
static bfs::path get_dir(const bfs::path &dirpath)
Definition: filesystem.cpp:337
std::string get_user_data_dir()
Definition: filesystem.cpp:828
std::string get_wml_persist_dir()
static bool file_exists(const bfs::path &fpath)
Definition: filesystem.cpp:326
bool is_legal_user_file_name(const std::string &name, bool allow_whitespace=true)
Returns whether the given filename is a legal name for a user-created file.
std::string get_synced_prefs_file()
location of preferences file containing preferences that are synced between computers note that wesno...
utils::optional< std::string > get_wml_location(const std::string &path, const utils::optional< std::string > &current_dir)
Returns a translated path to the actual file or directory, if it exists.
std::string get_saves_dir()
const file_tree_checksum & data_tree_checksum(bool reset=false)
Get the time at which the data/ tree was last modified at.
std::string read_file(const std::string &fname)
Basic disk I/O - read file.
std::string get_unsynced_prefs_file()
location of preferences file containing preferences that aren't synced between computers
std::string get_save_index_file()
utils::optional< std::string > get_binary_file_location(const std::string &type, const std::string &filename)
Returns a complete path to the actual file of a given type, if it exists.
std::string get_lua_history_file()
std::string autodetect_game_data_dir(std::string exe_dir)
Try to autodetect the location of the game data dir.
std::string read_scenario(const std::string &name)
std::string get_screenshot_dir()
std::string get_credentials_file()
std::string get_sync_dir()
parent directory for everything that should be synced between systems.
bool looks_like_pbl(const std::string &file)
std::string get_addons_data_dir()
std::string get_default_prefs_file()
std::string get_addons_dir()
std::string get_intl_dir()
std::string get_core_images_dir()
static void get_file_tree_checksum_internal(const std::string &path, file_tree_checksum &res)
std::string get_current_editor_dir(const std::string &addon_id)
std::string read_map(const std::string &name)
std::string get_cwd()
Definition: filesystem.cpp:920
std::string normalize_path(const std::string &fpath, bool normalize_separators, bool resolve_dot_entries)
Returns the absolute path of a file.
std::string path
Definition: filesystem.cpp:91
std::string default_preferences_path
Definition: filesystem.cpp:97
std::string lowercase(std::string_view s)
Returns a lowercased version of the string.
Definition: unicode.cpp:50
bool wildcard_string_match(const std::string &str, const std::string &match)
Match using '*' as any number of characters (including none), '+' as one or more characters,...
void erase_if(Container &container, const Predicate &predicate)
Convenience wrapper for using std::remove_if on a container.
Definition: general.hpp:106
bool operator==(const file_tree_checksum &rhs) const
Encapsulates the map of the game.
Definition: location.hpp:45
mock_char c
Some defines: VERSION, PACKAGE, MIN_SAVEGAME_VERSION.
#define LOCALEDIR
Definition: wesconfig.h:19