The Battle for Wesnoth  1.15.7+dev
filesystem.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2003 - 2012 by David White <dave@whitevine.net>
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 /**
16  * @file
17  * File-IO
18  */
19 #define GETTEXT_DOMAIN "wesnoth-lib"
20 
21 #include "filesystem.hpp"
22 
23 #include "config.hpp"
24 #include "deprecation.hpp"
25 #include "game_config.hpp"
26 #include "game_version.hpp"
27 #include "gettext.hpp"
28 #include "log.hpp"
31 
32 #include <boost/algorithm/string.hpp>
33 #include <boost/filesystem.hpp>
34 #include <boost/filesystem/fstream.hpp>
35 #include <boost/iostreams/device/file_descriptor.hpp>
36 #include <boost/iostreams/stream.hpp>
37 #include <boost/system/windows_error.hpp>
38 #include "game_config_view.hpp"
39 
40 #ifdef _WIN32
41 #include "log_windows.hpp"
42 
43 #include <boost/locale.hpp>
44 
45 #include <windows.h>
46 #include <shlobj.h>
47 #include <shlwapi.h>
48 
49 // Work around TDM-GCC not #defining this according to @newfrenchy83.
50 #ifndef VOLUME_NAME_NONE
51 #define VOLUME_NAME_NONE 0x4
52 #endif
53 
54 #endif /* !_WIN32 */
55 
56 #include <algorithm>
57 #include <set>
58 
59 // Copied from boost::predef, as it's there only since 1.55.
60 #if defined(__APPLE__) && defined(__MACH__) && defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__)
61 
62 #define WESNOTH_BOOST_OS_IOS (__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__*1000)
63 #include <SDL2/SDL_filesystem.h>
64 
65 #endif
66 
67 
68 static lg::log_domain log_filesystem("filesystem");
69 #define DBG_FS LOG_STREAM(debug, log_filesystem)
70 #define LOG_FS LOG_STREAM(info, log_filesystem)
71 #define WRN_FS LOG_STREAM(warn, log_filesystem)
72 #define ERR_FS LOG_STREAM(err, log_filesystem)
73 
74 namespace bfs = boost::filesystem;
75 using boost::system::error_code;
76 
77 namespace
78 {
79 // These are the filenames that get special processing
80 const std::string maincfg_filename = "_main.cfg";
81 const std::string finalcfg_filename = "_final.cfg";
82 const std::string initialcfg_filename = "_initial.cfg";
83 
84 // only used by windows but put outside the ifdef to let it check by ci build.
85 class customcodecvt : public std::codecvt<wchar_t /*intern*/, char /*extern*/, std::mbstate_t>
86 {
87 private:
88  // private static helper things
89  template<typename char_t_to>
90  struct customcodecvt_do_conversion_writer
91  {
92  customcodecvt_do_conversion_writer(char_t_to*& _to_next, char_t_to* _to_end)
93  : to_next(_to_next)
94  , to_end(_to_end)
95  {
96  }
97 
98  char_t_to*& to_next;
99  char_t_to* to_end;
100 
101  bool can_push(std::size_t count) const
102  {
103  return static_cast<std::size_t>(to_end - to_next) > count;
104  }
105 
106  void push(char_t_to val)
107  {
108  assert(to_next != to_end);
109  *to_next++ = val;
110  }
111  };
112 
113  template<typename char_t_from, typename char_t_to>
114  static void customcodecvt_do_conversion(std::mbstate_t& /*state*/,
115  const char_t_from* from,
116  const char_t_from* from_end,
117  const char_t_from*& from_next,
118  char_t_to* to,
119  char_t_to* to_end,
120  char_t_to*& to_next)
121  {
122  typedef typename ucs4_convert_impl::convert_impl<char_t_from>::type impl_type_from;
123  typedef typename ucs4_convert_impl::convert_impl<char_t_to>::type impl_type_to;
124 
125  from_next = from;
126  to_next = to;
127  customcodecvt_do_conversion_writer<char_t_to> writer(to_next, to_end);
128 
129  while(from_next != from_end) {
130  impl_type_to::write(writer, impl_type_from::read(from_next, from_end));
131  }
132  }
133 
134 public:
135  // Not used by boost filesystem
136  int do_encoding() const noexcept
137  {
138  return 0;
139  }
140 
141  // Not used by boost filesystem
142  bool do_always_noconv() const noexcept
143  {
144  return false;
145  }
146 
147  int do_length(std::mbstate_t& /*state*/, const char* /*from*/, const char* /*from_end*/, std::size_t /*max*/) const
148  {
149  // Not used by boost filesystem
150  throw "Not supported";
151  }
152 
153  std::codecvt_base::result unshift(
154  std::mbstate_t& /*state*/, char* /*to*/, char* /*to_end*/, char*& /*to_next*/) const
155  {
156  // Not used by boost filesystem
157  throw "Not supported";
158  }
159 
160  // there are still some methods which could be implemented but aren't because boost filesystem won't use them.
161  std::codecvt_base::result do_in(std::mbstate_t& state,
162  const char* from,
163  const char* from_end,
164  const char*& from_next,
165  wchar_t* to,
166  wchar_t* to_end,
167  wchar_t*& to_next) const
168  {
169  try {
170  customcodecvt_do_conversion<char, wchar_t>(state, from, from_end, from_next, to, to_end, to_next);
171  } catch(...) {
172  ERR_FS << "Invalid UTF-8 string'" << std::string(from, from_end) << "' " << std::endl;
174  }
175 
176  return std::codecvt_base::ok;
177  }
178 
179  std::codecvt_base::result do_out(std::mbstate_t& state,
180  const wchar_t* from,
181  const wchar_t* from_end,
182  const wchar_t*& from_next,
183  char* to,
184  char* to_end,
185  char*& to_next) const
186  {
187  try {
188  customcodecvt_do_conversion<wchar_t, char>(state, from, from_end, from_next, to, to_end, to_next);
189  } catch(...) {
190  ERR_FS << "Invalid UTF-16 string" << std::endl;
192  }
193 
194  return std::codecvt_base::ok;
195  }
196 };
197 
198 #ifdef _WIN32
199 class static_runner
200 {
201 public:
202  static_runner()
203  {
204  // Boost uses the current locale to generate a UTF-8 one
205  std::locale utf8_loc = boost::locale::generator().generate("");
206 
207  // use a custom locale because we want to use out log.hpp functions in case of an invalid string.
208  utf8_loc = std::locale(utf8_loc, new customcodecvt());
209 
210  boost::filesystem::path::imbue(utf8_loc);
211  }
212 };
213 
214 static static_runner static_bfs_path_imbuer;
215 
216 bool is_filename_case_correct(const std::string& fname, const boost::iostreams::file_descriptor_source& fd)
217 {
218  wchar_t real_path[MAX_PATH];
219  GetFinalPathNameByHandleW(fd.handle(), real_path, MAX_PATH - 1, VOLUME_NAME_NONE);
220 
221  std::string real_name = filesystem::base_name(unicode_cast<std::string>(std::wstring(real_path)));
222  return real_name == filesystem::base_name(fname);
223 }
224 
225 #else
226 bool is_filename_case_correct(const std::string& /*fname*/, const boost::iostreams::file_descriptor_source& /*fd*/)
227 {
228  return true;
229 }
230 #endif
231 } // namespace
232 
233 namespace filesystem
234 {
235 
236 static void push_if_exists(std::vector<std::string>* vec, const bfs::path& file, bool full)
237 {
238  if(vec != nullptr) {
239  if(full) {
240  vec->push_back(file.generic_string());
241  } else {
242  vec->push_back(file.filename().generic_string());
243  }
244  }
245 }
246 
247 static inline bool error_except_not_found(const error_code& ec)
248 {
249  return (ec && ec.value() != boost::system::errc::no_such_file_or_directory
250 #ifdef _WIN32
251  && ec.value() != boost::system::windows_error::path_not_found
252 #endif /*_WIN32*/
253  );
254 }
255 
256 static bool is_directory_internal(const bfs::path& fpath)
257 {
258  error_code ec;
259  bool is_dir = bfs::is_directory(fpath, ec);
260  if(error_except_not_found(ec)) {
261  LOG_FS << "Failed to check if " << fpath.string() << " is a directory: " << ec.message() << '\n';
262  }
263 
264  return is_dir;
265 }
266 
267 static bool file_exists(const bfs::path& fpath)
268 {
269  error_code ec;
270  bool exists = bfs::exists(fpath, ec);
271  if(error_except_not_found(ec)) {
272  ERR_FS << "Failed to check existence of file " << fpath.string() << ": " << ec.message() << '\n';
273  }
274 
275  return exists;
276 }
277 
278 static bfs::path get_dir(const bfs::path& dirpath)
279 {
280  bool is_dir = is_directory_internal(dirpath);
281  if(!is_dir) {
282  error_code ec;
283  bfs::create_directory(dirpath, ec);
284 
285  if(ec) {
286  ERR_FS << "Failed to create directory " << dirpath.string() << ": " << ec.message() << '\n';
287  }
288 
289  // This is probably redundant
290  is_dir = is_directory_internal(dirpath);
291  }
292 
293  if(!is_dir) {
294  ERR_FS << "Could not open or create directory " << dirpath.string() << '\n';
295  return std::string();
296  }
297 
298  return dirpath;
299 }
300 
301 static bool create_directory_if_missing(const bfs::path& dirpath)
302 {
303  error_code ec;
304  bfs::file_status fs = bfs::status(dirpath, ec);
305 
306  if(error_except_not_found(ec)) {
307  ERR_FS << "Failed to retrieve file status for " << dirpath.string() << ": " << ec.message() << '\n';
308  return false;
309  } else if(bfs::is_directory(fs)) {
310  DBG_FS << "directory " << dirpath.string() << " exists, not creating\n";
311  return true;
312  } else if(bfs::exists(fs)) {
313  ERR_FS << "cannot create directory " << dirpath.string() << "; file exists\n";
314  return false;
315  }
316 
317  bool created = bfs::create_directory(dirpath, ec);
318  if(ec) {
319  ERR_FS << "Failed to create directory " << dirpath.string() << ": " << ec.message() << '\n';
320  }
321 
322  return created;
323 }
324 
326 {
327  DBG_FS << "creating recursive directory: " << dirpath.string() << '\n';
328 
329  if(dirpath.empty()) {
330  return false;
331  }
332 
333  error_code ec;
334  bfs::file_status fs = bfs::status(dirpath);
335 
336  if(error_except_not_found(ec)) {
337  ERR_FS << "Failed to retrieve file status for " << dirpath.string() << ": " << ec.message() << '\n';
338  return false;
339  } else if(bfs::is_directory(fs)) {
340  return true;
341  } else if(bfs::exists(fs)) {
342  return false;
343  }
344 
345  if(!dirpath.has_parent_path() || create_directory_if_missing_recursive(dirpath.parent_path())) {
346  return create_directory_if_missing(dirpath);
347  } else {
348  ERR_FS << "Could not create parents to " << dirpath.string() << '\n';
349  return false;
350  }
351 }
352 
354  std::vector<std::string>* files,
355  std::vector<std::string>* dirs,
356  file_name_option mode,
357  file_filter_option filter,
358  file_reorder_option reorder,
359  file_tree_checksum* checksum)
360 {
361  if(bfs::path(dir).is_relative() && !game_config::path.empty()) {
362  bfs::path absolute_dir(game_config::path);
363  absolute_dir /= dir;
364 
365  if(is_directory_internal(absolute_dir)) {
366  get_files_in_dir(absolute_dir.string(), files, dirs, mode, filter, reorder, checksum);
367  return;
368  }
369  }
370 
371  const bfs::path dirpath(dir);
372 
373  if(reorder == DO_REORDER) {
374  LOG_FS << "searching for _main.cfg in directory " << dir << '\n';
375  const bfs::path maincfg = dirpath / maincfg_filename;
376 
377  if(file_exists(maincfg)) {
378  LOG_FS << "_main.cfg found : " << maincfg << '\n';
379  push_if_exists(files, maincfg, mode == ENTIRE_FILE_PATH);
380  return;
381  }
382  }
383 
384  error_code ec;
385  bfs::directory_iterator di(dirpath, ec);
386  bfs::directory_iterator end;
387 
388  // Probably not a directory, let the caller deal with it.
389  if(ec) {
390  return;
391  }
392 
393  for(; di != end; ++di) {
394  bfs::file_status st = di->status(ec);
395  if(ec) {
396  LOG_FS << "Failed to get file status of " << di->path().string() << ": " << ec.message() << '\n';
397  continue;
398  }
399 
400  if(st.type() == bfs::regular_file) {
401  {
402  std::string basename = di->path().filename().string();
403  if(filter == SKIP_PBL_FILES && looks_like_pbl(basename))
404  continue;
405  if(!basename.empty() && basename[0] == '.')
406  continue;
407  }
408 
409  push_if_exists(files, di->path(), mode == ENTIRE_FILE_PATH);
410 
411  if(checksum != nullptr) {
412  std::time_t mtime = bfs::last_write_time(di->path(), ec);
413  if(ec) {
414  LOG_FS << "Failed to read modification time of " << di->path().string() << ": " << ec.message()
415  << '\n';
416  } else if(mtime > checksum->modified) {
417  checksum->modified = mtime;
418  }
419 
420  uintmax_t size = bfs::file_size(di->path(), ec);
421  if(ec) {
422  LOG_FS << "Failed to read filesize of " << di->path().string() << ": " << ec.message() << '\n';
423  } else {
424  checksum->sum_size += size;
425  }
426 
427  checksum->nfiles++;
428  }
429  } else if(st.type() == bfs::directory_file) {
430  std::string basename = di->path().filename().string();
431 
432  if(!basename.empty() && basename[0] == '.') {
433  continue;
434  }
435 
436  if(filter == SKIP_MEDIA_DIR && (basename == "images" || basename == "sounds")) {
437  continue;
438  }
439 
440  const bfs::path inner_main(di->path() / maincfg_filename);
441  bfs::file_status main_st = bfs::status(inner_main, ec);
442 
443  if(error_except_not_found(ec)) {
444  LOG_FS << "Failed to get file status of " << inner_main.string() << ": " << ec.message() << '\n';
445  } else if(reorder == DO_REORDER && main_st.type() == bfs::regular_file) {
446  LOG_FS << "_main.cfg found : "
447  << (mode == ENTIRE_FILE_PATH ? inner_main.string() : inner_main.filename().string()) << '\n';
448  push_if_exists(files, inner_main, mode == ENTIRE_FILE_PATH);
449  } else {
450  push_if_exists(dirs, di->path(), mode == ENTIRE_FILE_PATH);
451  }
452  }
453  }
454 
455  if(files != nullptr) {
456  std::sort(files->begin(), files->end());
457  }
458 
459  if(dirs != nullptr) {
460  std::sort(dirs->begin(), dirs->end());
461  }
462 
463  if(files != nullptr && reorder == DO_REORDER) {
464  // move finalcfg_filename, if present, to the end of the vector
465  for(unsigned int i = 0; i < files->size(); i++) {
466  if(ends_with((*files)[i], "/" + finalcfg_filename)) {
467  files->push_back((*files)[i]);
468  files->erase(files->begin() + i);
469  break;
470  }
471  }
472 
473  // move initialcfg_filename, if present, to the beginning of the vector
474  int foundit = -1;
475  for(unsigned int i = 0; i < files->size(); i++)
476  if(ends_with((*files)[i], "/" + initialcfg_filename)) {
477  foundit = i;
478  break;
479  }
480  if(foundit > 0) {
481  std::string initialcfg = (*files)[foundit];
482  for(unsigned int i = foundit; i > 0; i--)
483  (*files)[i] = (*files)[i - 1];
484  (*files)[0] = initialcfg;
485  }
486  }
487 }
488 
490 {
491  return get_dir(bfs::path(dir)).string();
492 }
493 
495 {
496  std::string next_filename;
497  int counter = 0;
498 
499  do {
500  std::stringstream filename;
501 
502  filename << name;
503  filename.width(3);
504  filename.fill('0');
505  filename.setf(std::ios_base::right);
506  filename << counter << extension;
507 
508  counter++;
509  next_filename = filename.str();
510  } while(file_exists(next_filename) && counter < 1000);
511 
512  return next_filename;
513 }
514 
516 
518 {
519  std::ostringstream s;
520  s << version.major_version() << '.' << version.minor_version();
521  return s.str();
522 }
523 
525 {
526  static std::string suffix;
527 
528  // We only really need to generate this once since
529  // the version number cannot change during runtime.
530 
531  if(suffix.empty()) {
533  }
534 
535  return suffix;
536 }
537 
538 #if defined(__APPLE__) && !defined(__IPHONEOS__)
539  // Starting from Wesnoth 1.14.6, we have to use sandboxing function on macOS
540  // The problem is, that only signed builds can use sandbox. Unsigned builds
541  // would use other config directory then signed ones. So if we don't want
542  // to have two separate config dirs, we have to create symlink to new config
543  // location if exists. This part of code is only required on macOS.
544  static void migrate_apple_config_directory_for_unsandboxed_builds()
545  {
546  const char* home_str = getenv("HOME");
547  bfs::path home = home_str ? home_str : ".";
548 
549  // We don't know which of the two is in PREFERENCES_DIR now.
550  boost::filesystem::path old_saves_dir = home / "Library/Application Support/Wesnoth_";
551  old_saves_dir += get_version_path_suffix();
552  boost::filesystem::path new_saves_dir = home / "Library/Containers/org.wesnoth.Wesnoth/Data/Library/Application Support/Wesnoth_";
553  new_saves_dir += get_version_path_suffix();
554 
555  if(bfs::is_directory(new_saves_dir)) {
556  if(!bfs::exists(old_saves_dir)) {
557  std::cout << "Apple developer's userdata migration: ";
558  std::cout << "symlinking " << old_saves_dir << " to " << new_saves_dir << "\n";
559  bfs::create_symlink(new_saves_dir, old_saves_dir);
560  } else if(!bfs::symbolic_link_exists(old_saves_dir)) {
561  std::cout << "Apple developer's userdata migration: ";
562  std::cout << "Problem! Old (non-containerized) directory " << old_saves_dir << " is not a symlink. Your savegames are scattered around 2 locations.\n";
563  }
564  return;
565  }
566  }
567 #endif
568 
569 
570 static void setup_user_data_dir()
571 {
572 #if defined(__APPLE__) && !defined(__IPHONEOS__)
573  migrate_apple_config_directory_for_unsandboxed_builds();
574 #endif
575 
576  if(!create_directory_if_missing_recursive(user_data_dir)) {
577  ERR_FS << "could not open or create user data directory at " << user_data_dir.string() << '\n';
578  return;
579  }
580  // TODO: this may not print the error message if the directory exists but we don't have the proper permissions
581 
582  // Create user data and add-on directories
583  create_directory_if_missing(user_data_dir / "editor");
584  create_directory_if_missing(user_data_dir / "editor" / "maps");
585  create_directory_if_missing(user_data_dir / "editor" / "scenarios");
586  create_directory_if_missing(user_data_dir / "data");
587  create_directory_if_missing(user_data_dir / "data" / "add-ons");
588  create_directory_if_missing(user_data_dir / "saves");
589  create_directory_if_missing(user_data_dir / "persist");
590 
591 #ifdef _WIN32
593 #endif
594 }
595 
596 #ifdef _WIN32
597 // As a convenience for portable installs on Windows, relative paths with . or
598 // .. as the first component are considered relative to the current workdir
599 // instead of Documents/My Games.
600 static bool is_path_relative_to_cwd(const std::string& str)
601 {
602  const bfs::path p(str);
603 
604  if(p.empty()) {
605  return false;
606  }
607 
608  return *p.begin() == "." || *p.begin() == "..";
609 }
610 #endif
611 
613 {
614  bool relative_ok = false;
615  // Not always but it can be unused in some configurations
616  UNUSED(relative_ok);
617 
618 #ifdef PREFERENCES_DIR
619  if(newprefdir.empty()) {
620  newprefdir = PREFERENCES_DIR;
621  relative_ok = true;
622  }
623 #endif
624 
625 #ifdef _WIN32
626  if(newprefdir.size() > 2 && newprefdir[1] == ':') {
627  // allow absolute path override
628  user_data_dir = newprefdir;
629  } else if(is_path_relative_to_cwd(newprefdir)) {
630  // Custom directory relative to workdir (for portable installs, etc.)
631  user_data_dir = get_cwd() + "/" + newprefdir;
632  } else {
633  if(newprefdir.empty()) {
634  newprefdir = "Wesnoth" + get_version_path_suffix();
635  } else {
636 #ifdef PREFERENCES_DIR
637  if (newprefdir != PREFERENCES_DIR)
638 #endif
639  {
640  // TRANSLATORS: translate the part inside <...> only
641  deprecated_message(_("--userdata-dir=<relative path that doesn't start with a period>"),
643  {1, 17, 0},
644  _("Use an absolute path, or a relative path that starts with a period and a backslash"));
645  }
646  }
647 
648  PWSTR docs_path = nullptr;
649  HRESULT res = SHGetKnownFolderPath(FOLDERID_Documents, KF_FLAG_CREATE, nullptr, &docs_path);
650 
651  if(res != S_OK) {
652  //
653  // Crummy fallback path full of pain and suffering.
654  //
655  ERR_FS << "Could not determine path to user's Documents folder! (" << std::hex << "0x" << res << std::dec << ") "
656  << "User config/data directories may be unavailable for "
657  << "this session. Please report this as a bug.\n";
658  user_data_dir = bfs::path(get_cwd()) / newprefdir;
659  } else {
660  bfs::path games_path = bfs::path(docs_path) / "My Games";
661  create_directory_if_missing(games_path);
662 
663  user_data_dir = games_path / newprefdir;
664  }
665 
666  CoTaskMemFree(docs_path);
667  }
668 
669 #else /*_WIN32*/
670 
671  std::string backupprefdir = ".wesnoth" + get_version_path_suffix();
672 
673 #ifdef WESNOTH_BOOST_OS_IOS
674  char *sdl_pref_path = SDL_GetPrefPath("wesnoth.org", "iWesnoth");
675  if(sdl_pref_path) {
676  backupprefdir = std::string(sdl_pref_path) + backupprefdir;
677  SDL_free(sdl_pref_path);
678  }
679 #endif
680 
681 #ifdef _X11
682  const char* home_str = getenv("HOME");
683 
684  if(newprefdir.empty()) {
685  char const* xdg_data = getenv("XDG_DATA_HOME");
686  if(!xdg_data || xdg_data[0] == '\0') {
687  if(!home_str) {
688  newprefdir = backupprefdir;
689  goto other;
690  }
691 
692  user_data_dir = home_str;
693  user_data_dir /= ".local/share";
694  } else {
695  user_data_dir = xdg_data;
696  }
697 
698  user_data_dir /= "wesnoth";
699  user_data_dir /= get_version_path_suffix();
700  } else {
701  other:
702  bfs::path home = home_str ? home_str : ".";
703 
704  if(newprefdir[0] == '/') {
705  user_data_dir = newprefdir;
706  } else {
707  if(!relative_ok) {
708  // TRANSLATORS: translate the part inside <...> only
709  deprecated_message(_("--userdata-dir=<relative path>"),
711  {1, 17, 0},
712  _("Use absolute paths. Relative paths are deprecated because they are interpreted relative to $HOME"));
713  }
714  user_data_dir = home / newprefdir;
715  }
716  }
717 #else
718  if(newprefdir.empty()) {
719  newprefdir = backupprefdir;
720  }
721 
722  const char* home_str = getenv("HOME");
723  bfs::path home = home_str ? home_str : ".";
724 
725  if(newprefdir[0] == '/') {
726  user_data_dir = newprefdir;
727  } else {
728  if(!relative_ok) {
729  // TRANSLATORS: translate the part inside <...> only
730  deprecated_message(_("--userdata-dir=<relative path>"),
732  {1, 17, 0},
733  _("Use absolute paths. Relative paths are deprecated because they are interpreted relative to $HOME"));
734  }
735  user_data_dir = home / newprefdir;
736  }
737 #endif
738 
739 #endif /*_WIN32*/
741  user_data_dir = normalize_path(user_data_dir.string(), true, true);
742 }
743 
744 static void set_user_config_path(bfs::path newconfig)
745 {
746  user_config_dir = newconfig;
747  if(!create_directory_if_missing_recursive(user_config_dir)) {
748  ERR_FS << "could not open or create user config directory at " << user_config_dir.string() << '\n';
749  }
750 }
751 
752 void set_user_config_dir(const std::string& newconfigdir)
753 {
754  set_user_config_path(newconfigdir);
755 }
756 
758 {
759  if(user_data_dir.empty()) {
761  }
762 
763  return user_data_dir;
764 }
765 
767 {
768  if(user_config_dir.empty()) {
769 #if defined(_X11) && !defined(PREFERENCES_DIR)
770  char const* xdg_config = getenv("XDG_CONFIG_HOME");
771 
772  if(!xdg_config || xdg_config[0] == '\0') {
773  xdg_config = getenv("HOME");
774  if(!xdg_config) {
775  user_config_dir = get_user_data_path();
776  return user_config_dir.string();
777  }
778 
779  user_config_dir = xdg_config;
780  user_config_dir /= ".config";
781  } else {
782  user_config_dir = xdg_config;
783  }
784 
785  user_config_dir /= "wesnoth";
786  set_user_config_path(user_config_dir);
787 #else
788  user_config_dir = get_user_data_path();
789 #endif
790  }
791 
792  return user_config_dir.string();
793 }
794 
796 {
797  return get_user_data_path().string();
798 }
799 
801 {
802  if(cache_dir.empty()) {
803 #if defined(_X11) && !defined(PREFERENCES_DIR)
804  char const* xdg_cache = getenv("XDG_CACHE_HOME");
805 
806  if(!xdg_cache || xdg_cache[0] == '\0') {
807  xdg_cache = getenv("HOME");
808  if(!xdg_cache) {
809  cache_dir = get_dir(get_user_data_path() / "cache");
810  return cache_dir.string();
811  }
812 
813  cache_dir = xdg_cache;
814  cache_dir /= ".cache";
815  } else {
816  cache_dir = xdg_cache;
817  }
818 
819  cache_dir /= "wesnoth";
821 #else
822  cache_dir = get_dir(get_user_data_path() / "cache");
823 #endif
824  }
825 
826  return cache_dir.string();
827 }
828 
829 std::vector<other_version_dir> find_other_version_saves_dirs()
830 {
831 #if !defined(_WIN32) && !defined(_X11) && !defined(__APPLE__)
832  // By all means, this situation doesn't make sense
833  return {};
834 #else
835  const auto& w_ver = game_config::wesnoth_version;
836  const auto& ms_ver = game_config::min_savegame_version;
837 
838  if(w_ver.major_version() != 1 || ms_ver.major_version() != 1) {
839  // Unimplemented, assuming that version 2 won't use WML-based saves
840  return {};
841  }
842 
843  std::vector<other_version_dir> result;
844 
845  // For 1.16, check for saves from all versions up to 1.20.
846  for(auto minor = ms_ver.minor_version(); minor <= w_ver.minor_version() + 4; ++minor) {
847  if(minor == w_ver.minor_version())
848  continue;
849 
850  auto version = version_info{};
851  version.set_major_version(w_ver.major_version());
852  version.set_minor_version(minor);
853  auto suffix = get_version_path_suffix(version);
854 
855  bfs::path path;
856 
857  //
858  // NOTE:
859  // This is a bit of a naive approach. We assume on all platforms that
860  // get_user_data_path() will return something resembling the default
861  // configuration and that --user-data-dir wasn't used. We will get
862  // false negatives when any of these conditions don't hold true.
863  //
864 
865 #if defined(_WIN32)
866  path = get_user_data_path().parent_path() / ("Wesnoth" + suffix) / "saves";
867 #elif defined(_X11)
868  path = get_user_data_path().parent_path() / suffix / "saves";
869 #elif defined(__APPLE__)
870  path = get_user_data_path().parent_path() / ("Wesnoth_" + suffix) / "saves";
871 #endif
872 
873  if(bfs::exists(path)) {
874  result.emplace_back(suffix, path.string());
875  }
876  }
877 
878  return result;
879 #endif
880 }
881 
883 {
884  error_code ec;
885  bfs::path cwd = bfs::current_path(ec);
886 
887  if(ec) {
888  ERR_FS << "Failed to get current directory: " << ec.message() << '\n';
889  return "";
890  }
891 
892  return cwd.generic_string();
893 }
894 
895 bool set_cwd(const std::string& dir)
896 {
897  error_code ec;
898  bfs::current_path(bfs::path{dir}, ec);
899 
900  if(ec) {
901  ERR_FS << "Failed to set current directory: " << ec.message() << '\n';
902  return false;
903  } else {
904  LOG_FS << "Process working directory set to " << dir << '\n';
905  }
906 
907  return true;
908 }
909 
911 {
912 #ifdef _WIN32
913  wchar_t process_path[MAX_PATH];
914  SetLastError(ERROR_SUCCESS);
915 
916  GetModuleFileNameW(nullptr, process_path, MAX_PATH);
917 
918  if(GetLastError() != ERROR_SUCCESS) {
919  return get_cwd();
920  }
921 
922  bfs::path exe(process_path);
923  return exe.parent_path().string();
924 #else
925  if(bfs::exists("/proc/")) {
926  bfs::path self_exe("/proc/self/exe");
927  error_code ec;
928  bfs::path exe = bfs::read_symlink(self_exe, ec);
929  if(ec) {
930  return std::string();
931  }
932 
933  return exe.parent_path().string();
934  } else {
935  return get_cwd();
936  }
937 #endif
938 }
939 
940 bool make_directory(const std::string& dirname)
941 {
942  error_code ec;
943  bool created = bfs::create_directory(bfs::path(dirname), ec);
944  if(ec) {
945  ERR_FS << "Failed to create directory " << dirname << ": " << ec.message() << '\n';
946  }
947 
948  return created;
949 }
950 
951 bool delete_directory(const std::string& dirname, const bool keep_pbl)
952 {
953  bool ret = true;
954  std::vector<std::string> files;
955  std::vector<std::string> dirs;
956  error_code ec;
957 
958  get_files_in_dir(dirname, &files, &dirs, ENTIRE_FILE_PATH, keep_pbl ? SKIP_PBL_FILES : NO_FILTER);
959 
960  if(!files.empty()) {
961  for(const std::string& f : files) {
962  bfs::remove(bfs::path(f), ec);
963  if(ec) {
964  LOG_FS << "remove(" << f << "): " << ec.message() << '\n';
965  ret = false;
966  }
967  }
968  }
969 
970  if(!dirs.empty()) {
971  for(const std::string& d : dirs) {
972  // TODO: this does not preserve any other PBL files
973  // filesystem.cpp does this too, so this might be intentional
974  if(!delete_directory(d))
975  ret = false;
976  }
977  }
978 
979  if(ret) {
980  bfs::remove(bfs::path(dirname), ec);
981  if(ec) {
982  LOG_FS << "remove(" << dirname << "): " << ec.message() << '\n';
983  ret = false;
984  }
985  }
986 
987  return ret;
988 }
989 
990 bool delete_file(const std::string& filename)
991 {
992  error_code ec;
993  bool ret = bfs::remove(bfs::path(filename), ec);
994  if(ec) {
995  ERR_FS << "Could not delete file " << filename << ": " << ec.message() << '\n';
996  }
997 
998  return ret;
999 }
1000 
1002 {
1003  scoped_istream is = istream_file(fname);
1004  std::stringstream ss;
1005  ss << is->rdbuf();
1006  return ss.str();
1007 }
1008 
1009 filesystem::scoped_istream istream_file(const std::string& fname, bool treat_failure_as_error)
1010 {
1011  LOG_FS << "Streaming " << fname << " for reading.\n";
1012 
1013  if(fname.empty()) {
1014  ERR_FS << "Trying to open file with empty name.\n";
1015  filesystem::scoped_istream s(new bfs::ifstream());
1016  s->clear(std::ios_base::failbit);
1017  return s;
1018  }
1019 
1020  // mingw doesn't support std::basic_ifstream::basic_ifstream(const wchar_t* fname)
1021  // that why boost::filesystem::fstream.hpp doesn't work with mingw.
1022  try {
1023  boost::iostreams::file_descriptor_source fd(bfs::path(fname), std::ios_base::binary);
1024 
1025  // TODO: has this still use ?
1026  if(!fd.is_open() && treat_failure_as_error) {
1027  ERR_FS << "Could not open '" << fname << "' for reading.\n";
1028  } else if(!is_filename_case_correct(fname, fd)) {
1029  ERR_FS << "Not opening '" << fname << "' due to case mismatch.\n";
1030  filesystem::scoped_istream s(new bfs::ifstream());
1031  s->clear(std::ios_base::failbit);
1032  return s;
1033  }
1034 
1035  return std::make_unique<boost::iostreams::stream<boost::iostreams::file_descriptor_source>>(fd, 4096, 0);
1036  } catch(const std::exception&) {
1037  if(treat_failure_as_error) {
1038  ERR_FS << "Could not open '" << fname << "' for reading.\n";
1039  }
1040 
1041  filesystem::scoped_istream s(new bfs::ifstream());
1042  s->clear(std::ios_base::failbit);
1043  return s;
1044  }
1045 }
1046 
1047 filesystem::scoped_ostream ostream_file(const std::string& fname, bool create_directory)
1048 {
1049  LOG_FS << "streaming " << fname << " for writing.\n";
1050 #if 1
1051  try {
1052  boost::iostreams::file_descriptor_sink fd(bfs::path(fname), std::ios_base::binary);
1053  return std::make_unique<boost::iostreams::stream<boost::iostreams::file_descriptor_sink>>(fd, 4096, 0);
1054  } catch(const BOOST_IOSTREAMS_FAILURE& e) {
1055  // If this operation failed because the parent directory didn't exist, create the parent directory and
1056  // retry.
1057  error_code ec_unused;
1058  if(create_directory && bfs::create_directories(bfs::path(fname).parent_path(), ec_unused)) {
1059  return ostream_file(fname, false);
1060  }
1061 
1062  throw filesystem::io_exception(e.what());
1063  }
1064 #else
1065  return new bfs::ofstream(bfs::path(fname), std::ios_base::binary);
1066 #endif
1067 }
1068 
1069 // Throws io_exception if an error occurs
1070 void write_file(const std::string& fname, const std::string& data)
1071 {
1072  scoped_ostream os = ostream_file(fname);
1073  os->exceptions(std::ios_base::goodbit);
1074 
1075  const std::size_t block_size = 4096;
1076  char buf[block_size];
1077 
1078  for(std::size_t i = 0; i < data.size(); i += block_size) {
1079  const std::size_t bytes = std::min<std::size_t>(block_size, data.size() - i);
1080  std::copy(data.begin() + i, data.begin() + i + bytes, buf);
1081 
1082  os->write(buf, bytes);
1083  if(os->bad()) {
1084  throw io_exception("Error writing to file: '" + fname + "'");
1085  }
1086  }
1087 }
1088 
1090 {
1091  return create_directory_if_missing(bfs::path(dirname));
1092 }
1093 
1095 {
1097 }
1098 
1099 bool is_directory(const std::string& fname)
1100 {
1101  return is_directory_internal(bfs::path(fname));
1102 }
1103 
1105 {
1106  return file_exists(bfs::path(name));
1107 }
1108 
1109 std::time_t file_modified_time(const std::string& fname)
1110 {
1111  error_code ec;
1112  std::time_t mtime = bfs::last_write_time(bfs::path(fname), ec);
1113  if(ec) {
1114  LOG_FS << "Failed to read modification time of " << fname << ": " << ec.message() << '\n';
1115  }
1116 
1117  return mtime;
1118 }
1119 
1120 bool is_gzip_file(const std::string& filename)
1121 {
1122  return bfs::path(filename).extension() == ".gz";
1123 }
1124 
1125 bool is_bzip2_file(const std::string& filename)
1126 {
1127  return bfs::path(filename).extension() == ".bz2";
1128 }
1129 
1130 int file_size(const std::string& fname)
1131 {
1132  error_code ec;
1133  uintmax_t size = bfs::file_size(bfs::path(fname), ec);
1134  if(ec) {
1135  LOG_FS << "Failed to read filesize of " << fname << ": " << ec.message() << '\n';
1136  return -1;
1137  } else if(size > INT_MAX) {
1138  return INT_MAX;
1139  } else {
1140  return size;
1141  }
1142 }
1143 
1144 int dir_size(const std::string& pname)
1145 {
1146  bfs::path p(pname);
1147  uintmax_t size_sum = 0;
1148  error_code ec;
1149  for(bfs::recursive_directory_iterator i(p), end; i != end && !ec; ++i) {
1150  if(bfs::is_regular_file(i->path())) {
1151  size_sum += bfs::file_size(i->path(), ec);
1152  }
1153  }
1154 
1155  if(ec) {
1156  LOG_FS << "Failed to read directorysize of " << pname << ": " << ec.message() << '\n';
1157  return -1;
1158  } else if(size_sum > INT_MAX) {
1159  return INT_MAX;
1160  } else {
1161  return size_sum;
1162  }
1163 }
1164 
1165 std::string base_name(const std::string& file, const bool remove_extension)
1166 {
1167  if(!remove_extension) {
1168  return bfs::path(file).filename().string();
1169  } else {
1170  return bfs::path(file).stem().string();
1171  }
1172 }
1173 
1175 {
1176  return bfs::path(file).parent_path().string();
1177 }
1178 
1180 {
1181  if(file.empty()) {
1182  return "";
1183  }
1184 
1185  bfs::path p{file};
1186  error_code ec;
1187 
1188  do {
1189  p = p.parent_path();
1190  bfs::path q = canonical(p, ec);
1191  if(!ec) {
1192  p = q;
1193  }
1194  } while(ec && !is_root(p.string()));
1195 
1196  return ec ? "" : p.string();
1197 }
1198 
1199 bool is_path_sep(char c)
1200 {
1201  static const bfs::path sep = bfs::path("/").make_preferred();
1202  const std::string s = std::string(1, c);
1203  return sep == bfs::path(s).make_preferred();
1204 }
1205 
1207 {
1208  return bfs::path::preferred_separator;
1209 }
1210 
1212 {
1213 #ifndef _WIN32
1214  error_code ec;
1215  const bfs::path& p = bfs::canonical(path, ec);
1216  return ec ? false : !p.has_parent_path();
1217 #else
1218  //
1219  // Boost.Filesystem is completely unreliable when it comes to detecting
1220  // whether a path refers to a drive's root directory on Windows, so we are
1221  // forced to take an alternative approach here. Instead of hand-parsing
1222  // strings we'll just call a graphical shell service.
1223  //
1224  // There are several poorly-documented ways to refer to a drive in Windows by
1225  // escaping the filesystem namespace using \\.\, \\?\, and \??\. We're just
1226  // going to ignore those here, which may yield unexpected results in places
1227  // such as the file dialog. This function really shouldn't be used for
1228  // security validation anyway, and there are virtually infinite ways to name
1229  // a drive's root using the NT object namespace so it's pretty pointless to
1230  // try to catch those there.
1231  //
1232  // (And no, shlwapi.dll's PathIsRoot() doesn't recognize \\.\C:\, \\?\C:\, or
1233  // \??\C:\ as roots either.)
1234  //
1235  // More generally, do NOT use this code in security-sensitive applications.
1236  //
1237  // See also: <https://googleprojectzero.blogspot.com/2016/02/the-definitive-guide-on-win32-to-nt.html>
1238  //
1239  const std::wstring& wpath = bfs::path{path}.make_preferred().wstring();
1240  return PathIsRootW(wpath.c_str()) == TRUE;
1241 #endif
1242 }
1243 
1245 {
1246  return bfs::path{path}.root_name().string();
1247 }
1248 
1250 {
1251  return bfs::path{path}.is_relative();
1252 }
1253 
1254 std::string normalize_path(const std::string& fpath, bool normalize_separators, bool resolve_dot_entries)
1255 {
1256  if(fpath.empty()) {
1257  return fpath;
1258  }
1259 
1260  error_code ec;
1261  bfs::path p = resolve_dot_entries ? bfs::canonical(fpath, ec) : bfs::absolute(fpath);
1262 
1263  if(ec) {
1264  return "";
1265  }
1266 
1267  if(normalize_separators) {
1268  return p.make_preferred().string();
1269  } else {
1270  return p.string();
1271  }
1272 }
1273 
1274 /**
1275  * The paths manager is responsible for recording the various paths
1276  * that binary files may be located at.
1277  * It should be passed a config object which holds binary path information.
1278  * This is in the format
1279  *@verbatim
1280  * [binary_path]
1281  * path=<path>
1282  * [/binary_path]
1283  * Binaries will be searched for in [wesnoth-path]/data/<path>/images/
1284  *@endverbatim
1285  */
1286 namespace
1287 {
1288 std::set<std::string> binary_paths;
1289 
1290 typedef std::map<std::string, std::vector<std::string>> paths_map;
1291 paths_map binary_paths_cache;
1292 
1293 } // namespace
1294 
1295 static void init_binary_paths()
1296 {
1297  if(binary_paths.empty()) {
1298  binary_paths.insert("");
1299  }
1300 }
1301 
1302 binary_paths_manager::binary_paths_manager()
1303  : paths_()
1304 {
1305 }
1306 
1308  : paths_()
1309 {
1310  set_paths(cfg);
1311 }
1312 
1314 {
1315  cleanup();
1316 }
1317 
1319 {
1320  cleanup();
1322 
1323  for(const config& bp : cfg.child_range("binary_path")) {
1324  std::string path = bp["path"].str();
1325  if(path.find("..") != std::string::npos) {
1326  ERR_FS << "Invalid binary path '" << path << "'\n";
1327  continue;
1328  }
1329 
1330  if(!path.empty() && path.back() != '/')
1331  path += "/";
1332  if(binary_paths.count(path) == 0) {
1333  binary_paths.insert(path);
1334  paths_.push_back(path);
1335  }
1336  }
1337 }
1338 
1340 {
1341  binary_paths_cache.clear();
1342 
1343  for(const std::string& p : paths_) {
1344  binary_paths.erase(p);
1345  }
1346 }
1347 
1349 {
1350  binary_paths_cache.clear();
1351 }
1352 
1353 static bool is_legal_file(const std::string& filename_str)
1354 {
1355  DBG_FS << "Looking for '" << filename_str << "'.\n";
1356 
1357  if(filename_str.empty()) {
1358  LOG_FS << " invalid filename\n";
1359  return false;
1360  }
1361 
1362  if(filename_str.find("..") != std::string::npos) {
1363  ERR_FS << "Illegal path '" << filename_str << "' (\"..\" not allowed).\n";
1364  return false;
1365  }
1366 
1367  if(filename_str.find('\\') != std::string::npos) {
1368  ERR_FS << "Illegal path '" << filename_str
1369  << R"end(' ("\" not allowed, for compatibility with GNU/Linux and macOS).)end" << std::endl;
1370  return false;
1371  }
1372 
1373  bfs::path filepath(filename_str);
1374 
1375  if(default_blacklist.match_file(filepath.filename().string())) {
1376  ERR_FS << "Illegal path '" << filename_str << "' (blacklisted filename)." << std::endl;
1377  return false;
1378  }
1379 
1380  if(std::any_of(filepath.begin(), filepath.end(),
1381  [](const bfs::path& dirname) { return default_blacklist.match_dir(dirname.string()); })) {
1382  ERR_FS << "Illegal path '" << filename_str << "' (blacklisted directory name)." << std::endl;
1383  return false;
1384  }
1385 
1386  return true;
1387 }
1388 
1389 /**
1390  * Returns a vector with all possible paths to a given type of binary,
1391  * e.g. 'images', 'sounds', etc,
1392  */
1393 const std::vector<std::string>& get_binary_paths(const std::string& type)
1394 {
1395  const paths_map::const_iterator itor = binary_paths_cache.find(type);
1396  if(itor != binary_paths_cache.end()) {
1397  return itor->second;
1398  }
1399 
1400  if(type.find("..") != std::string::npos) {
1401  // Not an assertion, as language.cpp is passing user data as type.
1402  ERR_FS << "Invalid WML type '" << type << "' for binary paths\n";
1403  static std::vector<std::string> dummy;
1404  return dummy;
1405  }
1406 
1407  std::vector<std::string>& res = binary_paths_cache[type];
1408 
1410 
1411  for(const std::string& path : binary_paths) {
1412  res.push_back(get_user_data_dir() + "/" + path + type + "/");
1413 
1414  if(!game_config::path.empty()) {
1415  res.push_back(game_config::path + "/" + path + type + "/");
1416  }
1417  }
1418 
1419  // not found in "/type" directory, try main directory
1420  res.push_back(get_user_data_dir() + "/");
1421 
1422  if(!game_config::path.empty()) {
1423  res.push_back(game_config::path + "/");
1424  }
1425 
1426  return res;
1427 }
1428 
1430 {
1431  // We define ".." as "remove everything before" this is needed because
1432  // on the one hand allowing ".." would be a security risk but
1433  // especially for terrains the c++ engine puts a hardcoded "terrain/" before filename
1434  // and there would be no way to "escape" from "terrain/" otherwise. This is not the
1435  // best solution but we cannot remove it without another solution (subtypes maybe?).
1436 
1437  {
1438  std::string::size_type pos = filename.rfind("../");
1439  if(pos != std::string::npos) {
1440  return get_binary_file_location(type, filename.substr(pos + 3));
1441  }
1442  }
1443 
1444  if(!is_legal_file(filename)) {
1445  return std::string();
1446  }
1447 
1448  std::string result;
1449  for(const std::string& bp : get_binary_paths(type)) {
1450  bfs::path bpath(bp);
1451  bpath /= filename;
1452 
1453  DBG_FS << " checking '" << bp << "'\n";
1454 
1455  if(file_exists(bpath)) {
1456  DBG_FS << " found at '" << bpath.string() << "'\n";
1457  if(result.empty()) {
1458  result = bpath.string();
1459  } else {
1460  WRN_FS << "Conflicting files in binary_path: '" << sanitize_path(result)
1461  << "' and '" << sanitize_path(bpath.string()) << "'\n";
1462  }
1463  }
1464  }
1465 
1466  DBG_FS << " not found\n";
1467  return result;
1468 }
1469 
1471 {
1472  if(!is_legal_file(filename)) {
1473  return std::string();
1474  }
1475 
1476  for(const std::string& bp : get_binary_paths(type)) {
1477  bfs::path bpath(bp);
1478  bpath /= filename;
1479  DBG_FS << " checking '" << bp << "'\n";
1480  if(is_directory_internal(bpath)) {
1481  DBG_FS << " found at '" << bpath.string() << "'\n";
1482  return bpath.string();
1483  }
1484  }
1485 
1486  DBG_FS << " not found\n";
1487  return std::string();
1488 }
1489 
1490 std::string get_wml_location(const std::string& filename, const std::string& current_dir)
1491 {
1492  if(!is_legal_file(filename)) {
1493  return std::string();
1494  }
1495 
1496  assert(game_config::path.empty() == false);
1497 
1498  bfs::path fpath(filename);
1499  bfs::path result;
1500 
1501  if(filename[0] == '~') {
1502  result /= get_user_data_path() / "data" / filename.substr(1);
1503  DBG_FS << " trying '" << result.string() << "'\n";
1504  } else if(*fpath.begin() == ".") {
1505  if(!current_dir.empty()) {
1506  result /= bfs::path(current_dir);
1507  } else {
1508  result /= bfs::path(game_config::path) / "data";
1509  }
1510 
1511  result /= filename;
1512  } else if(!game_config::path.empty()) {
1513  result /= bfs::path(game_config::path) / "data" / filename;
1514  }
1515 
1516  if(result.empty() || !file_exists(result)) {
1517  DBG_FS << " not found\n";
1518  result.clear();
1519  } else {
1520  DBG_FS << " found: '" << result.string() << "'\n";
1521  }
1522 
1523  return result.string();
1524 }
1525 
1526 static bfs::path subtract_path(const bfs::path& full, const bfs::path& prefix)
1527 {
1528  bfs::path::iterator fi = full.begin(), fe = full.end(), pi = prefix.begin(), pe = prefix.end();
1529  while(fi != fe && pi != pe && *fi == *pi) {
1530  ++fi;
1531  ++pi;
1532  }
1533 
1534  bfs::path rest;
1535  if(pi == pe) {
1536  while(fi != fe) {
1537  rest /= *fi;
1538  ++fi;
1539  }
1540  }
1541 
1542  return rest;
1543 }
1544 
1546 {
1547  bfs::path full_path(filename);
1548 
1549  bfs::path partial = subtract_path(full_path, get_user_data_path() / "data");
1550  if(!partial.empty()) {
1551  return "~" + partial.generic_string();
1552  }
1553 
1554  partial = subtract_path(full_path, bfs::path(game_config::path) / "data");
1555  if(!partial.empty()) {
1556  return partial.generic_string();
1557  }
1558 
1559  return filename;
1560 }
1561 
1563 {
1564  bfs::path full_path(get_binary_file_location("images", filename));
1565 
1566  if(full_path.empty()) {
1567  return full_path.generic_string();
1568  }
1569 
1571  if(!partial.empty()) {
1572  return partial.generic_string();
1573  }
1574 
1575  partial = subtract_path(full_path, game_config::path);
1576  if(!partial.empty()) {
1577  return partial.generic_string();
1578  }
1579 
1580  return full_path.generic_string();
1581 }
1582 
1584 {
1585  const std::string real_program_name(program_name
1586 #ifdef DEBUG
1587  + "-debug"
1588 #endif
1589 #ifdef _WIN32
1590  + ".exe"
1591 #endif
1592  );
1593 
1594  return (bfs::path(game_config::wesnoth_program_dir) / real_program_name).string();
1595 }
1596 
1598 {
1599 #ifdef _WIN32
1600  const char* user_name = getenv("USERNAME");
1601 #else
1602  const char* user_name = getenv("USER");
1603 #endif
1604 
1605  std::string canonicalized = filesystem::normalize_path(path, true, false);
1606  if(user_name != nullptr) {
1607  boost::replace_all(canonicalized, user_name, "USER");
1608  }
1609 
1610  return canonicalized;
1611 }
1612 
1613 // Return path to localized counterpart of the given file, if any, or empty string.
1614 // Localized counterpart may also be requested to have a suffix to base name.
1616 {
1618  std::string base = filesystem::base_name(file);
1619 
1620  const std::size_t pos_ext = base.rfind(".");
1621 
1622  std::string loc_base;
1623  if(pos_ext != std::string::npos) {
1624  loc_base = base.substr(0, pos_ext) + suff + base.substr(pos_ext);
1625  } else {
1626  loc_base = base + suff;
1627  }
1628 
1629  // TRANSLATORS: This is the language code which will be used
1630  // to store and fetch localized non-textual resources, such as images,
1631  // when they exist. Normally it is just the code of the PO file itself,
1632  // e.g. "de" of de.po for German. But it can also be a comma-separated
1633  // list of language codes by priority, when the localized resource
1634  // found for first of those languages will be used. This is useful when
1635  // two languages share sufficient commonality, that they can use each
1636  // other's resources rather than duplicating them. For example,
1637  // Swedish (sv) and Danish (da) are such, so Swedish translator could
1638  // translate this message as "sv,da", while Danish as "da,sv".
1639  std::vector<std::string> langs = utils::split(_("language code for localized resources^en_US"));
1640 
1641  // In case even the original image is split into base and overlay,
1642  // add en_US with lowest priority, since the message above will
1643  // not have it when translated.
1644  langs.push_back("en_US");
1645  for(const std::string& lang : langs) {
1646  std::string loc_file = dir + "/" + "l10n" + "/" + lang + "/" + loc_base;
1647  if(filesystem::file_exists(loc_file)) {
1648  return loc_file;
1649  }
1650  }
1651 
1652  return "";
1653 }
1654 
1655 } // namespace filesystem
std::string get_binary_dir_location(const std::string &type, const std::string &filename)
Returns a complete path to the actual directory of a given type or an empty string if the directory i...
void remove()
Removes a tip.
Definition: tooltip.cpp:189
bool delete_directory(const std::string &dirname, const bool keep_pbl)
Definition: filesystem.cpp:951
static void push_if_exists(std::vector< std::string > *vec, const bfs::path &file, bool full)
Definition: filesystem.cpp:236
static const std::string & get_version_path_suffix()
Definition: filesystem.cpp:524
std::string get_program_invocation(const std::string &program_name)
Returns the appropriate invocation for a Wesnoth-related binary, assuming that it is located in the s...
std::string get_next_filename(const std::string &name, const std::string &extension)
Get the next free filename using "name + number (3 digits) + extension" maximum 1000 files then start...
Definition: filesystem.cpp:494
int dummy
Definition: lstrlib.cpp:1125
Interfaces for manipulating version numbers of engine, add-ons, etc.
bool delete_file(const std::string &filename)
Definition: filesystem.cpp:990
bool looks_like_pbl(const std::string &file)
static l_noret error(LoadState *S, const char *why)
Definition: lundump.cpp:39
void set_user_data_dir(std::string newprefdir)
Definition: filesystem.cpp:612
#define ERR_FS
Definition: filesystem.cpp:72
config_array_view child_range(config_key_type key) const
static bool file_exists(const bfs::path &fpath)
Definition: filesystem.cpp:267
bool ends_with(const std::string &str, const std::string &suffix)
void finish_log_file_setup()
Relocates the stdout+stderr log file to the user data directory.
void set_major_version(unsigned int)
Sets the major version number.
filesystem::scoped_istream istream_file(const std::string &fname, bool treat_failure_as_error)
#define DBG_FS
Definition: filesystem.cpp:69
static void init_binary_paths()
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 or an empty string if the file isn&#39;t prese...
std::string normalize_path(const std::string &fpath, bool normalize_separators, bool resolve_dot_entries)
Returns the absolute path of a file.
#define d
std::string str
Definition: statement.cpp:110
Definitions for the interface to Wesnoth Markup Language (WML).
void clear_binary_paths_cache()
std::string get_cwd()
Definition: filesystem.cpp:882
bool exists(const image::locator &i_locator)
returns true if the given image actually exists, without loading it.
Definition: picture.cpp:1028
void write(std::ostream &out, const configr_of &cfg, unsigned int level)
Definition: parser.cpp:762
#define LOG_FS
Definition: filesystem.cpp:70
static bool is_legal_file(const std::string &filename_str)
static UNUSEDNOWARN std::string _(const char *str)
Definition: gettext.hpp:100
bool match_file(const std::string &name) const
Definition: filesystem.hpp:70
#define WRN_FS
Definition: filesystem.cpp:71
std::string deprecated_message(const std::string &elem_name, DEP_LEVEL level, const version_info &version, const std::string &detail)
Definition: deprecation.cpp:29
bool create_directory_if_missing_recursive(const std::string &dirname)
Creates a recursive directory tree if it does not exist already.
bool create_directory_if_missing(const std::string &dirname)
Creates a directory if it does not exist already.
unsigned int major_version() const
Retrieves the major version number (x1 in "x1.x2.x3").
static bfs::path user_config_dir
Definition: filesystem.cpp:515
static bool is_directory_internal(const bfs::path &fpath)
Definition: filesystem.cpp:256
std::string get_user_data_dir()
Definition: filesystem.cpp:795
void write_file(const std::string &fname, const std::string &data)
Throws io_exception if an error occurs.
std::string root_name(const std::string &path)
Returns the name of the root device if included in the given path.
std::string nearest_extant_parent(const std::string &file)
Finds the nearest parent in existence for a file or directory.
unsigned int minor_version() const
Retrieves the minor version number (x2 in "x1.x2.x3").
bool is_directory(const std::string &fname)
Returns true if the given file is a directory.
std::unique_ptr< std::istream > scoped_istream
Definition: filesystem.hpp:39
std::string path
Definition: game_config.cpp:39
std::string get_short_wml_path(const std::string &filename)
Returns a short path to filename, skipping the (user) data directory.
std::string get_independent_image_path(const std::string &filename)
Returns an image path to filename for binary path-independent use in saved games. ...
static bfs::path user_data_dir
Definition: filesystem.cpp:515
std::string sanitize_path(const std::string &path)
Sanitizes a path to remove references to the user&#39;s name.
std::string get_dir(const std::string &dir)
Definition: filesystem.cpp:489
std::string read_file(const std::string &fname)
Basic disk I/O - read file.
lu_byte right
Definition: lparser.cpp:1027
bool is_path_sep(char c)
Returns whether c is a path separator.
std::unique_ptr< std::ostream > scoped_ostream
Definition: filesystem.hpp:40
bool is_gzip_file(const std::string &filename)
Returns true if the file ends with &#39;.gz&#39;.
#define UNUSED(x)
Definition: global.hpp:40
std::string get_cache_dir()
Definition: filesystem.cpp:800
value read(bind.buffer(), bind.length())
const std::vector< std::string > & get_binary_paths(const std::string &type)
Returns a vector with all possible paths to a given type of binary, e.g.
std::string get_exe_dir()
Definition: filesystem.cpp:910
void get_files_in_dir(const std::string &dir, std::vector< std::string > *files, std::vector< std::string > *dirs, file_name_option mode, file_filter_option filter, file_reorder_option reorder, file_tree_checksum *checksum)
Populates &#39;files&#39; with all the files and &#39;dirs&#39; with all the directories in dir.
Definition: filesystem.cpp:353
Log file control routines for Windows.
std::size_t i
Definition: function.cpp:933
void set_user_config_dir(const std::string &newconfigdir)
Definition: filesystem.cpp:752
bool is_relative(const std::string &path)
Returns whether the path seems to be relative.
int dir_size(const std::string &pname)
Returns the sum of the sizes of the files contained in a directory.
std::string get_wml_location(const std::string &filename, const std::string &current_dir)
Returns a complete path to the actual WML file or directory or an empty string if the file isn&#39;t pres...
std::vector< std::string > paths_
Definition: filesystem.hpp:400
u64 size
Definition: statement.cpp:80
mock_party p
An exception object used when an IO error occurs.
Definition: filesystem.hpp:48
static map_location::DIRECTION s
bool make_directory(const std::string &dirname)
Definition: filesystem.cpp:940
std::string name
Definition: sdl_ttf.cpp:70
bool is_root(const std::string &path)
Returns whether the path is the root of the file hierarchy.
Declarations for File-IO.
static int writer(lua_State *L, const void *b, size_t size, void *B)
Definition: lstrlib.cpp:182
std::string get_localized_path(const std::string &file, const std::string &suff)
Returns the localized version of the given filename, if it exists.
static int sort(lua_State *L)
Definition: ltablib.cpp:411
const version_info wesnoth_version(VERSION)
rng * generator
This generator is automatically synced during synced context.
Definition: random.cpp:60
Represents version numbers.
char path_separator()
Returns the standard path separator for the current platform.
static bfs::path cache_dir
Definition: filesystem.cpp:515
std::string base_name(const std::string &file, const bool remove_extension)
Returns the base filename of a file, with directory name stripped.
int file_size(const std::string &fname)
Returns the size of a file, or -1 if the file doesn&#39;t exist.
bool set_cwd(const std::string &dir)
Definition: filesystem.cpp:895
std::string get_user_config_dir()
Definition: filesystem.cpp:766
void set_paths(const game_config_view &cfg)
bool is_bzip2_file(const std::string &filename)
Returns true if the file ends with &#39;.bz2&#39;.
#define f
std::time_t file_modified_time(const std::string &fname)
Get the modification time of a file.
std::vector< std::string > split(const config_attribute_value &val)
static bool error_except_not_found(const error_code &ec)
Definition: filesystem.cpp:247
static void set_user_config_path(bfs::path newconfig)
Definition: filesystem.cpp:744
static bfs::path subtract_path(const bfs::path &full, const bfs::path &prefix)
Standard logging facilities (interface).
#define e
std::vector< other_version_dir > find_other_version_saves_dirs()
Searches for directories containing saves created by other versions of Wesnoth.
Definition: filesystem.cpp:829
There are still moves and/or attacks possible, but the unit doesn&#39;t fit in the "unmoved" status...
bool match_dir(const std::string &name) const
Definition: filesystem.hpp:76
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:68
mock_char c
static lg::log_domain log_filesystem("filesystem")
const version_info min_savegame_version(MIN_SAVEGAME_VERSION)
static void setup_user_data_dir()
Definition: filesystem.cpp:570
bool file_exists(const std::string &name)
Returns true if a file or directory with such name already exists.
std::string::const_iterator iterator
Definition: tokenizer.hpp:24
std::string directory_name(const std::string &file)
Returns the directory name of a file, with filename stripped.
std::string wesnoth_program_dir
Definition: game_config.cpp:48
static const bfs::path & get_user_data_path()
Definition: filesystem.cpp:757
static const blacklist_pattern_list default_blacklist
Definition: filesystem.hpp:99
auto * ss
Definition: result_set.cpp:281
filesystem::scoped_ostream ostream_file(const std::string &fname, bool create_directory)