The Battle for Wesnoth  1.15.5+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 
494 std::string get_next_filename(const std::string& name, const std::string& extension)
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 }
895 {
896 #ifdef _WIN32
897  wchar_t process_path[MAX_PATH];
898  SetLastError(ERROR_SUCCESS);
899 
900  GetModuleFileNameW(nullptr, process_path, MAX_PATH);
901 
902  if(GetLastError() != ERROR_SUCCESS) {
903  return get_cwd();
904  }
905 
906  bfs::path exe(process_path);
907  return exe.parent_path().string();
908 #else
909  if(bfs::exists("/proc/")) {
910  bfs::path self_exe("/proc/self/exe");
911  error_code ec;
912  bfs::path exe = bfs::read_symlink(self_exe, ec);
913  if(ec) {
914  return std::string();
915  }
916 
917  return exe.parent_path().string();
918  } else {
919  return get_cwd();
920  }
921 #endif
922 }
923 
924 bool make_directory(const std::string& dirname)
925 {
926  error_code ec;
927  bool created = bfs::create_directory(bfs::path(dirname), ec);
928  if(ec) {
929  ERR_FS << "Failed to create directory " << dirname << ": " << ec.message() << '\n';
930  }
931 
932  return created;
933 }
934 
935 bool delete_directory(const std::string& dirname, const bool keep_pbl)
936 {
937  bool ret = true;
938  std::vector<std::string> files;
939  std::vector<std::string> dirs;
940  error_code ec;
941 
942  get_files_in_dir(dirname, &files, &dirs, ENTIRE_FILE_PATH, keep_pbl ? SKIP_PBL_FILES : NO_FILTER);
943 
944  if(!files.empty()) {
945  for(const std::string& f : files) {
946  bfs::remove(bfs::path(f), ec);
947  if(ec) {
948  LOG_FS << "remove(" << f << "): " << ec.message() << '\n';
949  ret = false;
950  }
951  }
952  }
953 
954  if(!dirs.empty()) {
955  for(const std::string& d : dirs) {
956  // TODO: this does not preserve any other PBL files
957  // filesystem.cpp does this too, so this might be intentional
958  if(!delete_directory(d))
959  ret = false;
960  }
961  }
962 
963  if(ret) {
964  bfs::remove(bfs::path(dirname), ec);
965  if(ec) {
966  LOG_FS << "remove(" << dirname << "): " << ec.message() << '\n';
967  ret = false;
968  }
969  }
970 
971  return ret;
972 }
973 
974 bool delete_file(const std::string& filename)
975 {
976  error_code ec;
977  bool ret = bfs::remove(bfs::path(filename), ec);
978  if(ec) {
979  ERR_FS << "Could not delete file " << filename << ": " << ec.message() << '\n';
980  }
981 
982  return ret;
983 }
984 
986 {
987  scoped_istream is = istream_file(fname);
988  std::stringstream ss;
989  ss << is->rdbuf();
990  return ss.str();
991 }
992 
993 filesystem::scoped_istream istream_file(const std::string& fname, bool treat_failure_as_error)
994 {
995  LOG_FS << "Streaming " << fname << " for reading.\n";
996 
997  if(fname.empty()) {
998  ERR_FS << "Trying to open file with empty name.\n";
999  filesystem::scoped_istream s(new bfs::ifstream());
1000  s->clear(std::ios_base::failbit);
1001  return s;
1002  }
1003 
1004  // mingw doesn't support std::basic_ifstream::basic_ifstream(const wchar_t* fname)
1005  // that why boost::filesystem::fstream.hpp doesn't work with mingw.
1006  try {
1007  boost::iostreams::file_descriptor_source fd(bfs::path(fname), std::ios_base::binary);
1008 
1009  // TODO: has this still use ?
1010  if(!fd.is_open() && treat_failure_as_error) {
1011  ERR_FS << "Could not open '" << fname << "' for reading.\n";
1012  } else if(!is_filename_case_correct(fname, fd)) {
1013  ERR_FS << "Not opening '" << fname << "' due to case mismatch.\n";
1014  filesystem::scoped_istream s(new bfs::ifstream());
1015  s->clear(std::ios_base::failbit);
1016  return s;
1017  }
1018 
1019  return std::make_unique<boost::iostreams::stream<boost::iostreams::file_descriptor_source>>(fd, 4096, 0);
1020  } catch(const std::exception&) {
1021  if(treat_failure_as_error) {
1022  ERR_FS << "Could not open '" << fname << "' for reading.\n";
1023  }
1024 
1025  filesystem::scoped_istream s(new bfs::ifstream());
1026  s->clear(std::ios_base::failbit);
1027  return s;
1028  }
1029 }
1030 
1031 filesystem::scoped_ostream ostream_file(const std::string& fname, bool create_directory)
1032 {
1033  LOG_FS << "streaming " << fname << " for writing.\n";
1034 #if 1
1035  try {
1036  boost::iostreams::file_descriptor_sink fd(bfs::path(fname), std::ios_base::binary);
1037  return std::make_unique<boost::iostreams::stream<boost::iostreams::file_descriptor_sink>>(fd, 4096, 0);
1038  } catch(const BOOST_IOSTREAMS_FAILURE& e) {
1039  // If this operation failed because the parent directory didn't exist, create the parent directory and
1040  // retry.
1041  error_code ec_unused;
1042  if(create_directory && bfs::create_directories(bfs::path(fname).parent_path(), ec_unused)) {
1043  return ostream_file(fname, false);
1044  }
1045 
1046  throw filesystem::io_exception(e.what());
1047  }
1048 #else
1049  return new bfs::ofstream(bfs::path(fname), std::ios_base::binary);
1050 #endif
1051 }
1052 
1053 // Throws io_exception if an error occurs
1054 void write_file(const std::string& fname, const std::string& data)
1055 {
1056  scoped_ostream os = ostream_file(fname);
1057  os->exceptions(std::ios_base::goodbit);
1058 
1059  const std::size_t block_size = 4096;
1060  char buf[block_size];
1061 
1062  for(std::size_t i = 0; i < data.size(); i += block_size) {
1063  const std::size_t bytes = std::min<std::size_t>(block_size, data.size() - i);
1064  std::copy(data.begin() + i, data.begin() + i + bytes, buf);
1065 
1066  os->write(buf, bytes);
1067  if(os->bad()) {
1068  throw io_exception("Error writing to file: '" + fname + "'");
1069  }
1070  }
1071 }
1072 
1074 {
1075  return create_directory_if_missing(bfs::path(dirname));
1076 }
1077 
1079 {
1081 }
1082 
1083 bool is_directory(const std::string& fname)
1084 {
1085  return is_directory_internal(bfs::path(fname));
1086 }
1087 
1088 bool file_exists(const std::string& name)
1089 {
1090  return file_exists(bfs::path(name));
1091 }
1092 
1093 std::time_t file_modified_time(const std::string& fname)
1094 {
1095  error_code ec;
1096  std::time_t mtime = bfs::last_write_time(bfs::path(fname), ec);
1097  if(ec) {
1098  LOG_FS << "Failed to read modification time of " << fname << ": " << ec.message() << '\n';
1099  }
1100 
1101  return mtime;
1102 }
1103 
1104 bool is_gzip_file(const std::string& filename)
1105 {
1106  return bfs::path(filename).extension() == ".gz";
1107 }
1108 
1109 bool is_bzip2_file(const std::string& filename)
1110 {
1111  return bfs::path(filename).extension() == ".bz2";
1112 }
1113 
1114 int file_size(const std::string& fname)
1115 {
1116  error_code ec;
1117  uintmax_t size = bfs::file_size(bfs::path(fname), ec);
1118  if(ec) {
1119  LOG_FS << "Failed to read filesize of " << fname << ": " << ec.message() << '\n';
1120  return -1;
1121  } else if(size > INT_MAX) {
1122  return INT_MAX;
1123  } else {
1124  return size;
1125  }
1126 }
1127 
1128 int dir_size(const std::string& pname)
1129 {
1130  bfs::path p(pname);
1131  uintmax_t size_sum = 0;
1132  error_code ec;
1133  for(bfs::recursive_directory_iterator i(p), end; i != end && !ec; ++i) {
1134  if(bfs::is_regular_file(i->path())) {
1135  size_sum += bfs::file_size(i->path(), ec);
1136  }
1137  }
1138 
1139  if(ec) {
1140  LOG_FS << "Failed to read directorysize of " << pname << ": " << ec.message() << '\n';
1141  return -1;
1142  } else if(size_sum > INT_MAX) {
1143  return INT_MAX;
1144  } else {
1145  return size_sum;
1146  }
1147 }
1148 
1149 std::string base_name(const std::string& file, const bool remove_extension)
1150 {
1151  if(!remove_extension) {
1152  return bfs::path(file).filename().string();
1153  } else {
1154  return bfs::path(file).stem().string();
1155  }
1156 }
1157 
1159 {
1160  return bfs::path(file).parent_path().string();
1161 }
1162 
1164 {
1165  if(file.empty()) {
1166  return "";
1167  }
1168 
1169  bfs::path p{file};
1170  error_code ec;
1171 
1172  do {
1173  p = p.parent_path();
1174  bfs::path q = canonical(p, ec);
1175  if(!ec) {
1176  p = q;
1177  }
1178  } while(ec && !is_root(p.string()));
1179 
1180  return ec ? "" : p.string();
1181 }
1182 
1183 bool is_path_sep(char c)
1184 {
1185  static const bfs::path sep = bfs::path("/").make_preferred();
1186  const std::string s = std::string(1, c);
1187  return sep == bfs::path(s).make_preferred();
1188 }
1189 
1191 {
1192  return bfs::path::preferred_separator;
1193 }
1194 
1196 {
1197 #ifndef _WIN32
1198  error_code ec;
1199  const bfs::path& p = bfs::canonical(path, ec);
1200  return ec ? false : !p.has_parent_path();
1201 #else
1202  //
1203  // Boost.Filesystem is completely unreliable when it comes to detecting
1204  // whether a path refers to a drive's root directory on Windows, so we are
1205  // forced to take an alternative approach here. Instead of hand-parsing
1206  // strings we'll just call a graphical shell service.
1207  //
1208  // There are several poorly-documented ways to refer to a drive in Windows by
1209  // escaping the filesystem namespace using \\.\, \\?\, and \??\. We're just
1210  // going to ignore those here, which may yield unexpected results in places
1211  // such as the file dialog. This function really shouldn't be used for
1212  // security validation anyway, and there are virtually infinite ways to name
1213  // a drive's root using the NT object namespace so it's pretty pointless to
1214  // try to catch those there.
1215  //
1216  // (And no, shlwapi.dll's PathIsRoot() doesn't recognize \\.\C:\, \\?\C:\, or
1217  // \??\C:\ as roots either.)
1218  //
1219  // More generally, do NOT use this code in security-sensitive applications.
1220  //
1221  // See also: <https://googleprojectzero.blogspot.com/2016/02/the-definitive-guide-on-win32-to-nt.html>
1222  //
1223  const std::wstring& wpath = bfs::path{path}.make_preferred().wstring();
1224  return PathIsRootW(wpath.c_str()) == TRUE;
1225 #endif
1226 }
1227 
1229 {
1230  return bfs::path{path}.root_name().string();
1231 }
1232 
1234 {
1235  return bfs::path{path}.is_relative();
1236 }
1237 
1238 std::string normalize_path(const std::string& fpath, bool normalize_separators, bool resolve_dot_entries)
1239 {
1240  if(fpath.empty()) {
1241  return fpath;
1242  }
1243 
1244  error_code ec;
1245  bfs::path p = resolve_dot_entries ? bfs::canonical(fpath, ec) : bfs::absolute(fpath);
1246 
1247  if(ec) {
1248  return "";
1249  }
1250 
1251  if(normalize_separators) {
1252  return p.make_preferred().string();
1253  } else {
1254  return p.string();
1255  }
1256 }
1257 
1258 /**
1259  * The paths manager is responsible for recording the various paths
1260  * that binary files may be located at.
1261  * It should be passed a config object which holds binary path information.
1262  * This is in the format
1263  *@verbatim
1264  * [binary_path]
1265  * path=<path>
1266  * [/binary_path]
1267  * Binaries will be searched for in [wesnoth-path]/data/<path>/images/
1268  *@endverbatim
1269  */
1270 namespace
1271 {
1272 std::set<std::string> binary_paths;
1273 
1274 typedef std::map<std::string, std::vector<std::string>> paths_map;
1275 paths_map binary_paths_cache;
1276 
1277 } // namespace
1278 
1279 static void init_binary_paths()
1280 {
1281  if(binary_paths.empty()) {
1282  binary_paths.insert("");
1283  }
1284 }
1285 
1286 binary_paths_manager::binary_paths_manager()
1287  : paths_()
1288 {
1289 }
1290 
1292  : paths_()
1293 {
1294  set_paths(cfg);
1295 }
1296 
1298 {
1299  cleanup();
1300 }
1301 
1303 {
1304  cleanup();
1306 
1307  for(const config& bp : cfg.child_range("binary_path")) {
1308  std::string path = bp["path"].str();
1309  if(path.find("..") != std::string::npos) {
1310  ERR_FS << "Invalid binary path '" << path << "'\n";
1311  continue;
1312  }
1313 
1314  if(!path.empty() && path.back() != '/')
1315  path += "/";
1316  if(binary_paths.count(path) == 0) {
1317  binary_paths.insert(path);
1318  paths_.push_back(path);
1319  }
1320  }
1321 }
1322 
1324 {
1325  binary_paths_cache.clear();
1326 
1327  for(const std::string& p : paths_) {
1328  binary_paths.erase(p);
1329  }
1330 }
1331 
1333 {
1334  binary_paths_cache.clear();
1335 }
1336 
1337 static bool is_legal_file(const std::string& filename_str)
1338 {
1339  DBG_FS << "Looking for '" << filename_str << "'.\n";
1340 
1341  if(filename_str.empty()) {
1342  LOG_FS << " invalid filename\n";
1343  return false;
1344  }
1345 
1346  if(filename_str.find("..") != std::string::npos) {
1347  ERR_FS << "Illegal path '" << filename_str << "' (\"..\" not allowed).\n";
1348  return false;
1349  }
1350 
1351  if(filename_str.find('\\') != std::string::npos) {
1352  ERR_FS << "Illegal path '" << filename_str
1353  << R"end(' ("\" not allowed, for compatibility with GNU/Linux and macOS).)end" << std::endl;
1354  return false;
1355  }
1356 
1357  bfs::path filepath(filename_str);
1358 
1359  if(default_blacklist.match_file(filepath.filename().string())) {
1360  ERR_FS << "Illegal path '" << filename_str << "' (blacklisted filename)." << std::endl;
1361  return false;
1362  }
1363 
1364  if(std::any_of(filepath.begin(), filepath.end(),
1365  [](const bfs::path& dirname) { return default_blacklist.match_dir(dirname.string()); })) {
1366  ERR_FS << "Illegal path '" << filename_str << "' (blacklisted directory name)." << std::endl;
1367  return false;
1368  }
1369 
1370  return true;
1371 }
1372 
1373 /**
1374  * Returns a vector with all possible paths to a given type of binary,
1375  * e.g. 'images', 'sounds', etc,
1376  */
1377 const std::vector<std::string>& get_binary_paths(const std::string& type)
1378 {
1379  const paths_map::const_iterator itor = binary_paths_cache.find(type);
1380  if(itor != binary_paths_cache.end()) {
1381  return itor->second;
1382  }
1383 
1384  if(type.find("..") != std::string::npos) {
1385  // Not an assertion, as language.cpp is passing user data as type.
1386  ERR_FS << "Invalid WML type '" << type << "' for binary paths\n";
1387  static std::vector<std::string> dummy;
1388  return dummy;
1389  }
1390 
1391  std::vector<std::string>& res = binary_paths_cache[type];
1392 
1394 
1395  for(const std::string& path : binary_paths) {
1396  res.push_back(get_user_data_dir() + "/" + path + type + "/");
1397 
1398  if(!game_config::path.empty()) {
1399  res.push_back(game_config::path + "/" + path + type + "/");
1400  }
1401  }
1402 
1403  // not found in "/type" directory, try main directory
1404  res.push_back(get_user_data_dir() + "/");
1405 
1406  if(!game_config::path.empty()) {
1407  res.push_back(game_config::path + "/");
1408  }
1409 
1410  return res;
1411 }
1412 
1414 {
1415  // We define ".." as "remove everything before" this is needed because
1416  // on the one hand allowing ".." would be a security risk but
1417  // especially for terrains the c++ engine puts a hardcoded "terrain/" before filename
1418  // and there would be no way to "escape" from "terrain/" otherwise. This is not the
1419  // best solution but we cannot remove it without another solution (subtypes maybe?).
1420 
1421  {
1422  std::string::size_type pos = filename.rfind("../");
1423  if(pos != std::string::npos) {
1424  return get_binary_file_location(type, filename.substr(pos + 3));
1425  }
1426  }
1427 
1428  if(!is_legal_file(filename)) {
1429  return std::string();
1430  }
1431 
1432  std::string result;
1433  for(const std::string& bp : get_binary_paths(type)) {
1434  bfs::path bpath(bp);
1435  bpath /= filename;
1436 
1437  DBG_FS << " checking '" << bp << "'\n";
1438 
1439  if(file_exists(bpath)) {
1440  DBG_FS << " found at '" << bpath.string() << "'\n";
1441  if(result.empty()) {
1442  result = bpath.string();
1443  } else {
1444  WRN_FS << "Conflicting files in binary_path: '" << sanitize_path(result)
1445  << "' and '" << sanitize_path(bpath.string()) << "'\n";
1446  }
1447  }
1448  }
1449 
1450  DBG_FS << " not found\n";
1451  return result;
1452 }
1453 
1455 {
1456  if(!is_legal_file(filename)) {
1457  return std::string();
1458  }
1459 
1460  for(const std::string& bp : get_binary_paths(type)) {
1461  bfs::path bpath(bp);
1462  bpath /= filename;
1463  DBG_FS << " checking '" << bp << "'\n";
1464  if(is_directory_internal(bpath)) {
1465  DBG_FS << " found at '" << bpath.string() << "'\n";
1466  return bpath.string();
1467  }
1468  }
1469 
1470  DBG_FS << " not found\n";
1471  return std::string();
1472 }
1473 
1474 std::string get_wml_location(const std::string& filename, const std::string& current_dir)
1475 {
1476  if(!is_legal_file(filename)) {
1477  return std::string();
1478  }
1479 
1480  assert(game_config::path.empty() == false);
1481 
1482  bfs::path fpath(filename);
1483  bfs::path result;
1484 
1485  if(filename[0] == '~') {
1486  result /= get_user_data_path() / "data" / filename.substr(1);
1487  DBG_FS << " trying '" << result.string() << "'\n";
1488  } else if(*fpath.begin() == ".") {
1489  if(!current_dir.empty()) {
1490  result /= bfs::path(current_dir);
1491  } else {
1492  result /= bfs::path(game_config::path) / "data";
1493  }
1494 
1495  result /= filename;
1496  } else if(!game_config::path.empty()) {
1497  result /= bfs::path(game_config::path) / "data" / filename;
1498  }
1499 
1500  if(result.empty() || !file_exists(result)) {
1501  DBG_FS << " not found\n";
1502  result.clear();
1503  } else {
1504  DBG_FS << " found: '" << result.string() << "'\n";
1505  }
1506 
1507  return result.string();
1508 }
1509 
1510 static bfs::path subtract_path(const bfs::path& full, const bfs::path& prefix)
1511 {
1512  bfs::path::iterator fi = full.begin(), fe = full.end(), pi = prefix.begin(), pe = prefix.end();
1513  while(fi != fe && pi != pe && *fi == *pi) {
1514  ++fi;
1515  ++pi;
1516  }
1517 
1518  bfs::path rest;
1519  if(pi == pe) {
1520  while(fi != fe) {
1521  rest /= *fi;
1522  ++fi;
1523  }
1524  }
1525 
1526  return rest;
1527 }
1528 
1530 {
1531  bfs::path full_path(filename);
1532 
1533  bfs::path partial = subtract_path(full_path, get_user_data_path() / "data");
1534  if(!partial.empty()) {
1535  return "~" + partial.generic_string();
1536  }
1537 
1538  partial = subtract_path(full_path, bfs::path(game_config::path) / "data");
1539  if(!partial.empty()) {
1540  return partial.generic_string();
1541  }
1542 
1543  return filename;
1544 }
1545 
1547 {
1548  bfs::path full_path(get_binary_file_location("images", filename));
1549 
1550  if(full_path.empty()) {
1551  return full_path.generic_string();
1552  }
1553 
1554  bfs::path partial = subtract_path(full_path, get_user_data_path());
1555  if(!partial.empty()) {
1556  return partial.generic_string();
1557  }
1558 
1559  partial = subtract_path(full_path, game_config::path);
1560  if(!partial.empty()) {
1561  return partial.generic_string();
1562  }
1563 
1564  return full_path.generic_string();
1565 }
1566 
1568 {
1569  const std::string real_program_name(program_name
1570 #ifdef DEBUG
1571  + "-debug"
1572 #endif
1573 #ifdef _WIN32
1574  + ".exe"
1575 #endif
1576  );
1577 
1578  return (bfs::path(game_config::wesnoth_program_dir) / real_program_name).string();
1579 }
1580 
1582 {
1583 #ifdef _WIN32
1584  const char* user_name = getenv("USERNAME");
1585 #else
1586  const char* user_name = getenv("USER");
1587 #endif
1588 
1589  std::string canonicalized = filesystem::normalize_path(path, true, false);
1590  if(user_name != nullptr) {
1591  boost::replace_all(canonicalized, user_name, "USER");
1592  }
1593 
1594  return canonicalized;
1595 }
1596 
1597 // Return path to localized counterpart of the given file, if any, or empty string.
1598 // Localized counterpart may also be requested to have a suffix to base name.
1600 {
1602  std::string base = filesystem::base_name(file);
1603 
1604  const std::size_t pos_ext = base.rfind(".");
1605 
1606  std::string loc_base;
1607  if(pos_ext != std::string::npos) {
1608  loc_base = base.substr(0, pos_ext) + suff + base.substr(pos_ext);
1609  } else {
1610  loc_base = base + suff;
1611  }
1612 
1613  // TRANSLATORS: This is the language code which will be used
1614  // to store and fetch localized non-textual resources, such as images,
1615  // when they exist. Normally it is just the code of the PO file itself,
1616  // e.g. "de" of de.po for German. But it can also be a comma-separated
1617  // list of language codes by priority, when the localized resource
1618  // found for first of those languages will be used. This is useful when
1619  // two languages share sufficient commonality, that they can use each
1620  // other's resources rather than duplicating them. For example,
1621  // Swedish (sv) and Danish (da) are such, so Swedish translator could
1622  // translate this message as "sv,da", while Danish as "da,sv".
1623  std::vector<std::string> langs = utils::split(_("language code for localized resources^en_US"));
1624 
1625  // In case even the original image is split into base and overlay,
1626  // add en_US with lowest priority, since the message above will
1627  // not have it when translated.
1628  langs.push_back("en_US");
1629  for(const std::string& lang : langs) {
1630  std::string loc_file = dir + "/" + "l10n" + "/" + lang + "/" + loc_base;
1631  if(filesystem::file_exists(loc_file)) {
1632  return loc_file;
1633  }
1634  }
1635 
1636  return "";
1637 }
1638 
1639 } // 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:935
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:974
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)
Definition: filesystem.cpp:993
#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.
Definition: filesystem.cpp:985
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:34
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:894
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:398
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:924
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.
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
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)