-
-
Notifications
You must be signed in to change notification settings - Fork 994
/
filesystem.cpp
1201 lines (1032 loc) · 29.3 KB
/
filesystem.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2003 - 2014 by David White <dave@whitevine.net>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
/**
* @file
* File-IO
*/
#include "global.hpp"
// Include files for opendir(3), readdir(3), etc.
// These files may vary from platform to platform,
// since these functions are NOT ANSI-conforming functions.
// They may have to be altered to port to new platforms
//for mkdir
#include <sys/stat.h>
#ifdef _WIN32
#include "filesystem_win32.ii"
#include <cctype>
#else /* !_WIN32 */
#include <unistd.h>
#include <dirent.h>
#include <libgen.h>
#endif /* !_WIN32 */
#ifdef __BEOS__
#include <Directory.h>
#include <FindDirectory.h>
#include <Path.h>
BPath be_path;
#endif
// for getenv
#include <cerrno>
#include <fstream>
#include <iomanip>
#include <set>
#include <boost/algorithm/string.hpp>
// for strerror
#include <cstring>
#include "config.hpp"
#include "filesystem.hpp"
#include "game_config.hpp"
#include "game_preferences.hpp"
#include "log.hpp"
#include "scoped_resource.hpp"
#include "serialization/string_utils.hpp"
#include "version.hpp"
#include <boost/foreach.hpp>
static lg::log_domain log_filesystem("filesystem");
#define DBG_FS LOG_STREAM(debug, log_filesystem)
#define LOG_FS LOG_STREAM(info, log_filesystem)
#define WRN_FS LOG_STREAM(warn, log_filesystem)
#define ERR_FS LOG_STREAM(err, log_filesystem)
namespace {
const mode_t AccessMode = 00770;
// These are the filenames that get special processing
const std::string maincfg_filename = "_main.cfg";
const std::string finalcfg_filename = "_final.cfg";
const std::string initialcfg_filename = "_initial.cfg";
}
#ifdef __APPLE__
#include <CoreFoundation/CoreFoundation.h>
#include <CoreFoundation/CFString.h>
#include <CoreFoundation/CFBase.h>
#endif
namespace filesystem {
void get_files_in_dir(const std::string &directory,
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)
{
// If we have a path to find directories in,
// then convert relative pathnames to be rooted
// on the wesnoth path
#ifndef __AMIGAOS4__
if(!directory.empty() && directory[0] != '/' && !game_config::path.empty()){
std::string dir = game_config::path + "/" + directory;
if(is_directory(dir)) {
get_files_in_dir(dir,files,dirs,mode,filter,reorder,checksum);
return;
}
}
#endif /* __AMIGAOS4__ */
struct stat st;
if (reorder == DO_REORDER) {
LOG_FS << "searching for _main.cfg in directory " << directory << '\n';
std::string maincfg;
if (directory.empty() || directory[directory.size()-1] == '/'
#ifdef __AMIGAOS4__
|| (directory[directory.size()-1]==':')
#endif /* __AMIGAOS4__ */
)
maincfg = directory + maincfg_filename;
else
maincfg = (directory + "/") + maincfg_filename;
if (::stat(maincfg.c_str(), &st) != -1) {
LOG_FS << "_main.cfg found : " << maincfg << '\n';
if (files != NULL) {
if (mode == ENTIRE_FILE_PATH)
files->push_back(maincfg);
else
files->push_back(maincfg_filename);
}
return;
}
}
DIR* dir = opendir(directory.c_str());
if(dir == NULL) {
// Probably not a directory, let the caller deal with it.
return;
}
struct dirent* entry;
while((entry = readdir(dir)) != NULL) {
if(entry->d_name[0] == '.')
continue;
#ifdef __APPLE__
// HFS Mac OS X decomposes filenames using combining unicode characters.
// Try to get the precomposed form.
char macname[MAXNAMLEN+1];
CFStringRef cstr = CFStringCreateWithCString(NULL,
entry->d_name,
kCFStringEncodingUTF8);
CFMutableStringRef mut_str = CFStringCreateMutableCopy(NULL,
0, cstr);
CFStringNormalize(mut_str, kCFStringNormalizationFormC);
CFStringGetCString(mut_str,
macname,sizeof(macname)-1,
kCFStringEncodingUTF8);
CFRelease(cstr);
CFRelease(mut_str);
const std::string basename = macname;
#else
// generic Unix
const std::string basename = entry->d_name;
#endif /* !APPLE */
std::string fullname;
if (directory.empty() || directory[directory.size()-1] == '/'
#ifdef __AMIGAOS4__
|| (directory[directory.size()-1]==':')
#endif /* __AMIGAOS4__ */
)
fullname = directory + basename;
else
fullname = directory + "/" + basename;
if (::stat(fullname.c_str(), &st) != -1) {
if (S_ISREG(st.st_mode)) {
if(filter == SKIP_PBL_FILES && looks_like_pbl(basename)) {
continue;
}
if (files != NULL) {
if (mode == ENTIRE_FILE_PATH)
files->push_back(fullname);
else
files->push_back(basename);
}
if (checksum != NULL) {
if(st.st_mtime > checksum->modified) {
checksum->modified = st.st_mtime;
}
checksum->sum_size += st.st_size;
checksum->nfiles++;
}
} else if (S_ISDIR(st.st_mode)) {
if (filter == SKIP_MEDIA_DIR
&& (basename == "images"|| basename == "sounds"))
continue;
if (reorder == DO_REORDER &&
::stat((fullname+"/"+maincfg_filename).c_str(), &st)!=-1 &&
S_ISREG(st.st_mode)) {
LOG_FS << "_main.cfg found : ";
if (files != NULL) {
if (mode == ENTIRE_FILE_PATH) {
files->push_back(fullname + "/" + maincfg_filename);
LOG_FS << fullname << "/" << maincfg_filename << '\n';
} else {
files->push_back(basename + "/" + maincfg_filename);
LOG_FS << basename << "/" << maincfg_filename << '\n';
}
} else {
// Show what I consider strange
LOG_FS << fullname << "/" << maincfg_filename << " not used now but skip the directory \n";
}
} else if (dirs != NULL) {
if (mode == ENTIRE_FILE_PATH)
dirs->push_back(fullname);
else
dirs->push_back(basename);
}
}
}
}
closedir(dir);
if(files != NULL)
std::sort(files->begin(),files->end());
if (dirs != NULL)
std::sort(dirs->begin(),dirs->end());
if (files != NULL && reorder == DO_REORDER) {
// move finalcfg_filename, if present, to the end of the vector
for (unsigned int i = 0; i < files->size(); i++) {
if (ends_with((*files)[i], "/" + finalcfg_filename)) {
files->push_back((*files)[i]);
files->erase(files->begin()+i);
break;
}
}
// move initialcfg_filename, if present, to the beginning of the vector
unsigned int foundit = 0;
for (unsigned int i = 0; i < files->size(); i++)
if (ends_with((*files)[i], "/" + initialcfg_filename)) {
foundit = i;
break;
}
// If _initial.cfg needs to be moved (it was found, but not at index 0).
if (foundit > 0) {
std::string initialcfg = (*files)[foundit];
for (unsigned int i = foundit; i > 0; --i)
(*files)[i] = (*files)[i-1];
(*files)[0] = initialcfg;
}
}
}
std::string get_next_filename(const std::string& name, const std::string& extension)
{
std::string next_filename;
int counter = 0;
do {
std::stringstream filename;
filename << name;
filename.width(3);
filename.fill('0');
filename.setf(std::ios_base::right);
filename << counter << extension;
counter++;
next_filename = filename.str();
} while(file_exists(next_filename) && counter < 1000);
return next_filename;
}
std::string get_dir(const std::string& dir_path)
{
DIR* dir = opendir(dir_path.c_str());
if(dir == NULL) {
const int res = mkdir(dir_path.c_str(),AccessMode);
if(res == 0) {
dir = opendir(dir_path.c_str());
} else {
ERR_FS << "could not open or create directory: " << dir_path << '\n';
}
}
if(dir == NULL)
return "";
closedir(dir);
return dir_path;
}
bool make_directory(const std::string& path)
{
return (mkdir(path.c_str(),AccessMode) == 0);
}
// This deletes a directory with no hidden files and subdirectories.
// Also deletes a single file.
bool delete_directory(const std::string& path, const bool keep_pbl)
{
bool ret = true;
std::vector<std::string> files;
std::vector<std::string> dirs;
get_files_in_dir(path, &files, &dirs, ENTIRE_FILE_PATH, keep_pbl ? SKIP_PBL_FILES : NO_FILTER);
if(!files.empty()) {
for(std::vector<std::string>::const_iterator i = files.begin(); i != files.end(); ++i) {
errno = 0;
if(remove((*i).c_str()) != 0) {
LOG_FS << "remove(" << (*i) << "): " << strerror(errno) << "\n";
ret = false;
}
}
}
if(!dirs.empty()) {
for(std::vector<std::string>::const_iterator j = dirs.begin(); j != dirs.end(); ++j) {
if(!delete_directory(*j))
ret = false;
}
}
errno = 0;
#ifdef _WIN32
// remove() doesn't delete directories on windows.
int (*remove)(const char*);
if(is_directory(path))
remove = rmdir;
else
remove = ::remove;
#endif
if(remove(path.c_str()) != 0) {
LOG_FS << "remove(" << path << "): " << strerror(errno) << "\n";
ret = false;
}
return ret;
}
bool delete_file(const std::string& path)
{
bool ret = true;
if(remove(path.c_str()) != 0 && errno != ENOENT) {
ERR_FS << "remove(" << path << "): " << strerror(errno) << "\n";
ret = false;
}
return ret;
}
std::string get_cwd()
{
char buf[1024];
const char* const res = getcwd(buf,sizeof(buf));
if(res != NULL) {
std::string str(res);
#ifdef _WIN32
std::replace(str.begin(),str.end(),'\\','/');
#endif
return str;
} else {
return "";
}
}
std::string get_exe_dir()
{
#ifndef _WIN32
char buf[1024];
size_t path_size = readlink("/proc/self/exe", buf, sizeof(buf)-1);
if(path_size == static_cast<size_t>(-1))
return std::string();
buf[path_size] = 0;
return std::string(dirname(buf));
#else
return get_cwd();
#endif
}
bool create_directory_if_missing(const std::string& dirname)
{
if(is_directory(dirname)) {
DBG_FS << "directory " << dirname << " exists, not creating\n";
return true;
} else if(file_exists(dirname)) {
ERR_FS << "cannot create directory " << dirname << "; file exists\n";
return false;
}
DBG_FS << "creating missing directory " << dirname << '\n';
return make_directory(dirname);
}
bool create_directory_if_missing_recursive(const std::string& dirname)
{
DBG_FS<<"creating recursive directory: "<<dirname<<'\n';
if (is_directory(dirname) == false && dirname.empty() == false)
{
std::string tmp_dirname = dirname;
// remove trailing slashes or backslashes
while ((tmp_dirname[tmp_dirname.size()-1] == '/' ||
tmp_dirname[tmp_dirname.size()-1] == '\\') &&
!tmp_dirname.empty())
{
tmp_dirname.erase(tmp_dirname.size()-1);
}
// create the first non-existing directory
size_t pos = tmp_dirname.rfind("/");
// we get the most right directory and *skip* it
// we are creating it when we get back here
if (tmp_dirname.rfind('\\') != std::string::npos &&
tmp_dirname.rfind('\\') > pos )
pos = tmp_dirname.rfind('\\');
if (pos != std::string::npos)
create_directory_if_missing_recursive(tmp_dirname.substr(0,pos));
return create_directory_if_missing(tmp_dirname);
}
return create_directory_if_missing(dirname);
}
static std::string user_data_dir, user_config_dir, cache_dir;
static void setup_user_data_dir();
#ifndef _WIN32
static const std::string& get_version_path_suffix()
{
static std::string suffix;
// We only really need to generate this once since
// the version number cannot change during runtime.
if(suffix.empty()) {
std::ostringstream s;
s << game_config::wesnoth_version.major_version() << '.'
<< game_config::wesnoth_version.minor_version();
suffix = s.str();
}
return suffix;
}
#endif
void set_user_data_dir(std::string path)
{
#ifdef _WIN32
if(path.empty()) {
user_data_dir = get_cwd() + "/userdata";
} else if (path.size() > 2 && path[1] == ':') {
//allow absolute path override
user_data_dir = path;
} else {
typedef BOOL (WINAPI *SHGSFPAddress)(HWND, LPTSTR, int, BOOL);
SHGSFPAddress SHGetSpecialFolderPath;
HMODULE module = LoadLibrary("shell32");
SHGetSpecialFolderPath = reinterpret_cast<SHGSFPAddress>(GetProcAddress(module, "SHGetSpecialFolderPathA"));
if(SHGetSpecialFolderPath) {
LOG_FS << "Using SHGetSpecialFolderPath to find My Documents\n";
char my_documents_path[MAX_PATH];
if(SHGetSpecialFolderPath(NULL, my_documents_path, 5, 1)) {
std::string mygames_path = std::string(my_documents_path) + "/" + "My Games";
boost::algorithm::replace_all(mygames_path, std::string("\\"), std::string("/"));
create_directory_if_missing(mygames_path);
user_data_dir = mygames_path + "/" + path;
} else {
WRN_FS << "SHGetSpecialFolderPath failed\n";
user_data_dir = get_cwd() + "/" + path;
}
} else {
LOG_FS << "Failed to load SHGetSpecialFolderPath function\n";
user_data_dir = get_cwd() + "/" + path;
}
}
#else /*_WIN32*/
#ifdef PREFERENCES_DIR
if (path.empty()) path = PREFERENCES_DIR;
#endif
std::string path2 = ".wesnoth" + get_version_path_suffix();
#ifdef _X11
const char *home_str = getenv("HOME");
if (path.empty()) {
char const *xdg_data = getenv("XDG_DATA_HOME");
if (!xdg_data || xdg_data[0] == '\0') {
if (!home_str) {
path = path2;
goto other;
}
user_data_dir = home_str;
user_data_dir += "/.local/share";
} else user_data_dir = xdg_data;
user_data_dir += "/wesnoth/";
user_data_dir += get_version_path_suffix();
create_directory_if_missing_recursive(user_data_dir);
} else {
other:
std::string home = home_str ? home_str : ".";
if (path[0] == '/')
user_data_dir = path;
else
user_data_dir = home + "/" + path;
}
#else
if (path.empty()) path = path2;
#ifdef __AMIGAOS4__
user_data_dir = "PROGDIR:" + path;
#elif defined(__BEOS__)
if (be_path.InitCheck() != B_OK) {
BPath tpath;
if (find_directory(B_USER_SETTINGS_DIRECTORY, &be_path, true) == B_OK) {
be_path.Append("wesnoth");
} else {
be_path.SetTo("/boot/home/config/settings/wesnoth");
}
user_data_dir = be_path.Path();
}
#else
const char* home_str = getenv("HOME");
std::string home = home_str ? home_str : ".";
if (path[0] == '/')
user_data_dir = path;
else
user_data_dir = home + std::string("/") + path;
#endif
#endif
#endif /*_WIN32*/
setup_user_data_dir();
}
void set_user_config_dir(std::string path)
{
user_config_dir = path;
create_directory_if_missing(user_config_dir);
}
static void setup_user_data_dir()
{
#ifdef _WIN32
_mkdir(user_data_dir.c_str());
_mkdir((user_data_dir + "/editor").c_str());
_mkdir((user_data_dir + "/editor/maps").c_str());
_mkdir((user_data_dir + "/editor/scenarios").c_str());
_mkdir((user_data_dir + "/data").c_str());
_mkdir((user_data_dir + "/data/add-ons").c_str());
_mkdir((user_data_dir + "/saves").c_str());
_mkdir((user_data_dir + "/persist").c_str());
#elif defined(__BEOS__)
BPath tpath;
#define BEOS_CREATE_PREFERENCES_SUBDIR(subdir) \
tpath = be_path; \
tpath.Append(subdir); \
create_directory(tpath.Path(), 0775);
BEOS_CREATE_PREFERENCES_SUBDIR("editor");
BEOS_CREATE_PREFERENCES_SUBDIR("editor/maps");
BEOS_CREATE_PREFERENCES_SUBDIR("editor/scenarios");
BEOS_CREATE_PREFERENCES_SUBDIR("data");
BEOS_CREATE_PREFERENCES_SUBDIR("data/add-ons");
BEOS_CREATE_PREFERENCES_SUBDIR("saves");
BEOS_CREATE_PREFERENCES_SUBDIR("persist");
#undef BEOS_CREATE_PREFERENCES_SUBDIR
#else
const std::string& dir_path = user_data_dir;
const bool res = create_directory_if_missing(dir_path);
// probe read permissions (if we could make the directory)
DIR* const dir = res ? opendir(dir_path.c_str()) : NULL;
if(dir == NULL) {
ERR_FS << "could not open or create preferences directory at " << dir_path << '\n';
return;
}
closedir(dir);
// Create user data and add-on directories
create_directory_if_missing(dir_path + "/editor");
create_directory_if_missing(dir_path + "/editor/maps");
create_directory_if_missing(dir_path + "/editor/scenarios");
create_directory_if_missing(dir_path + "/data");
create_directory_if_missing(dir_path + "/data/add-ons");
create_directory_if_missing(dir_path + "/saves");
create_directory_if_missing(dir_path + "/persist");
#endif
}
std::string get_user_data_dir()
{
// ensure setup gets called only once per session
// FIXME: this is okay and optimized, but how should we react
// if the user deletes a dir while we are running?
if (user_data_dir.empty())
{
set_user_data_dir(std::string());
}
return user_data_dir;
}
std::string get_user_config_dir()
{
if (user_config_dir.empty())
{
#if defined(_X11) && !defined(PREFERENCES_DIR)
char const *xdg_config = getenv("XDG_CONFIG_HOME");
std::string path;
if (!xdg_config || xdg_config[0] == '\0') {
xdg_config = getenv("HOME");
if (!xdg_config) {
user_config_dir = get_user_data_dir();
return user_config_dir;
}
path = xdg_config;
path += "/.config";
} else path = xdg_config;
path += "/wesnoth";
set_user_config_dir(path);
#else
user_config_dir = get_user_data_dir();
#endif
}
return user_config_dir;
}
std::string get_cache_dir()
{
if (cache_dir.empty())
{
#if defined(_X11) && !defined(PREFERENCES_DIR)
char const *xdg_cache = getenv("XDG_CACHE_HOME");
if (!xdg_cache || xdg_cache[0] == '\0') {
xdg_cache = getenv("HOME");
if (!xdg_cache) {
cache_dir = get_dir(get_user_data_dir() + "/cache");
return cache_dir;
}
cache_dir = xdg_cache;
cache_dir += "/.cache";
} else cache_dir = xdg_cache;
cache_dir += "/wesnoth";
create_directory_if_missing_recursive(cache_dir);
#else
cache_dir = get_dir(get_user_data_dir() + "/cache");
#endif
}
return cache_dir;
}
static std::string read_stream(std::istream& s)
{
std::stringstream ss;
ss << s.rdbuf();
return ss.str();
}
std::istream *istream_file(const std::string &fname)
{
LOG_FS << "Streaming " << fname << " for reading.\n";
if (fname.empty())
{
ERR_FS << "Trying to open file with empty name.\n";
std::ifstream *s = new std::ifstream();
s->clear(std::ios_base::failbit);
return s;
}
std::ifstream *s = new std::ifstream(fname.c_str(),std::ios_base::binary);
if (s->is_open())
return s;
ERR_FS << "Could not open '" << fname << "' for reading.\n";
return s;
}
std::string read_file(const std::string &fname)
{
scoped_istream s = istream_file(fname);
return read_stream(*s);
}
std::ostream *ostream_file(std::string const &fname)
{
LOG_FS << "streaming " << fname << " for writing.\n";
return new std::ofstream(fname.c_str(), std::ios_base::binary);
}
// Throws io_exception if an error occurs
void write_file(const std::string& fname, const std::string& data)
{
//const util::scoped_resource<FILE*,close_FILE> file(fopen(fname.c_str(),"wb"));
const util::scoped_FILE file(fopen(fname.c_str(),"wb"));
if(file.get() == NULL) {
throw io_exception("Could not open file for writing: '" + fname + "'");
}
const size_t block_size = 4096;
char buf[block_size];
for(size_t i = 0; i < data.size(); i += block_size) {
const size_t bytes = std::min<size_t>(block_size,data.size() - i);
std::copy(data.begin() + i, data.begin() + i + bytes,buf);
const size_t res = fwrite(buf,1,bytes,file.get());
if(res != bytes) {
throw io_exception("Error writing to file: '" + fname + "'");
}
}
}
static bool is_directory_internal(const std::string& fname)
{
#ifdef _WIN32
_finddata_t info;
const long handle = _findfirst((fname + "/*").c_str(),&info);
if(handle >= 0) {
_findclose(handle);
return true;
} else {
return false;
}
#else
struct stat dir_stat;
if(::stat(fname.c_str(), &dir_stat) == -1) {
return false;
}
return S_ISDIR(dir_stat.st_mode);
#endif
}
bool is_directory(const std::string& fname)
{
if(fname.empty()) {
return false;
}
if(fname[0] != '/' && !game_config::path.empty()) {
if(is_directory_internal(game_config::path + "/" + fname))
return true;
}
return is_directory_internal(fname);
}
bool file_exists(const std::string& name)
{
#ifdef _WIN32
struct stat st;
return (::stat(name.c_str(), &st) == 0);
#else
struct stat st;
return (::stat(name.c_str(), &st) != -1);
#endif
}
time_t file_modified_time(const std::string& fname)
{
struct stat buf;
if(::stat(fname.c_str(),&buf) == -1)
return 0;
return buf.st_mtime;
}
/**
* Returns true if the file ends with '.gz'.
*
* @param filename The name to test.
*/
bool is_gzip_file(const std::string& filename)
{
return (filename.length() > 3
&& filename.substr(filename.length() - 3) == ".gz");
}
/**
* Returns true if the file ends with '.bz2'.
*
* @param filename The name to test.
*/
bool is_bzip2_file(const std::string& filename)
{
return (filename.length() > 4
&& filename.substr(filename.length() - 4) == ".bz2");
}
int file_size(const std::string& fname)
{
struct stat buf;
if(::stat(fname.c_str(),&buf) == -1)
return -1;
return buf.st_size;
}
std::string base_name(const std::string& file)
// Analogous to POSIX basename(3), but for C++ string-object pathnames
{
#ifdef _WIN32
static const std::string dir_separators = "\\/:";
#else
static const std::string dir_separators = "/";
#endif
std::string::size_type pos = file.find_last_of(dir_separators);
if(pos == std::string::npos)
return file;
if(pos >= file.size()-1)
return "";
return file.substr(pos+1);
}
std::string directory_name(const std::string& file)
// Analogous to POSIX dirname(3), but for C++ string-object pathnames
{
#ifdef _WIN32
static const std::string dir_separators = "\\/:";
#else
static const std::string dir_separators = "/";
#endif
std::string::size_type pos = file.find_last_of(dir_separators);
if(pos == std::string::npos)
return "";
return file.substr(0,pos+1);
}
namespace {
std::set<std::string> binary_paths;
typedef std::map<std::string,std::vector<std::string> > paths_map;
paths_map binary_paths_cache;
}
static void init_binary_paths()
{
if(binary_paths.empty()) {
binary_paths.insert("");
}
}
binary_paths_manager::binary_paths_manager() : paths_()
{}
binary_paths_manager::binary_paths_manager(const config& cfg) : paths_()
{
set_paths(cfg);
}
binary_paths_manager::~binary_paths_manager()
{
cleanup();
}
void binary_paths_manager::set_paths(const config& cfg)
{
cleanup();
init_binary_paths();
BOOST_FOREACH(const config &bp, cfg.child_range("binary_path"))
{
std::string path = bp["path"].str();
if (path.find("..") != std::string::npos) {
ERR_FS << "Invalid binary path '" << path << "'\n";
continue;
}
if (!path.empty() && path[path.size()-1] != '/') path += "/";
if(binary_paths.count(path) == 0) {
binary_paths.insert(path);
paths_.push_back(path);
}
}
}
void binary_paths_manager::cleanup()
{
binary_paths_cache.clear();
for(std::vector<std::string>::const_iterator i = paths_.begin(); i != paths_.end(); ++i) {
binary_paths.erase(*i);
}
}
void clear_binary_paths_cache()
{
binary_paths_cache.clear();
}
const std::vector<std::string>& get_binary_paths(const std::string& type)
{
const paths_map::const_iterator itor = binary_paths_cache.find(type);
if(itor != binary_paths_cache.end()) {
return itor->second;
}
if (type.find("..") != std::string::npos) {
// Not an assertion, as language.cpp is passing user data as type.
ERR_FS << "Invalid WML type '" << type << "' for binary paths\n";
static std::vector<std::string> dummy;
return dummy;
}
std::vector<std::string>& res = binary_paths_cache[type];
init_binary_paths();
BOOST_FOREACH(const std::string &path, binary_paths)
{
res.push_back(get_user_data_dir() + "/" + path + type + "/");
if(!game_config::path.empty()) {
res.push_back(game_config::path + "/" + path + type + "/");
}
}
// not found in "/type" directory, try main directory
res.push_back(get_user_data_dir() + "/");
if(!game_config::path.empty())
res.push_back(game_config::path+"/");
return res;
}
std::string get_binary_file_location(const std::string& type, const std::string& filename)
{
DBG_FS << "Looking for '" << filename << "'.\n";
if (filename.empty()) {
LOG_FS << " invalid filename (type: " << type <<")\n";
return std::string();
}
// Some parts of Wesnoth enjoy putting ".." inside filenames. This is
// bad and should be fixed. But in the meantime, deal with them in a dumb way.
std::string::size_type pos = filename.rfind("../");
if (pos != std::string::npos) {
std::string nf = filename.substr(pos + 3);
LOG_FS << "Illegal path '" << filename << "' replaced by '" << nf << "'\n";
return get_binary_file_location(type, nf);
}
if (filename.find("..") != std::string::npos) {
ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed).\n";
return std::string();
}
BOOST_FOREACH(const std::string &path, get_binary_paths(type))
{
const std::string file = path + filename;
DBG_FS << " checking '" << path << "'\n";
if(file_exists(file)) {
DBG_FS << " found at '" << file << "'\n";
return file;
}
}
DBG_FS << " not found\n";
return std::string();
}
std::string get_binary_dir_location(const std::string &type, const std::string &filename)
{
DBG_FS << "Looking for '" << filename << "'.\n";
if (filename.empty()) {
LOG_FS << " invalid filename (type: " << type <<")\n";
return std::string();
}
if (filename.find("..") != std::string::npos) {
ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed).\n";
return std::string();
}
BOOST_FOREACH(const std::string &path, get_binary_paths(type))
{
const std::string file = path + filename;