-
Notifications
You must be signed in to change notification settings - Fork 2
/
filesystem.cpp
1689 lines (1544 loc) · 56.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
/*
MIT License
Copyright © 2020-2022 Samuel Venable
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <set>
#include <sstream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <random>
#include <thread>
#include <climits>
#include <cstdlib>
#include <cstring>
#if defined(_WIN32)
#include <cwchar>
#endif
#include "filesystem.hpp"
#include "ghc/filesystem.hpp"
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#if defined(_WIN32)
#include <windows.h>
#include <Shlobj.h>
#include <share.h>
#include <io.h>
#else
#if defined(__APPLE__) && defined(__MACH__)
#include <sysdir.h>
#include <libproc.h>
#elif defined(__FreeBSD__) || defined(__DragonFly__) || defined(__NetBSD__) || defined(__OpenBSD__)
#include <sys/sysctl.h>
#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__OpenBSD__)
#if defined(__OpenBSD__)
#include <kvm.h>
#endif
#include <sys/user.h>
#endif
#endif
#include <unistd.h>
#endif
#if defined(_WIN32)
using std::wstring;
#endif
using std::string;
using std::vector;
using std::size_t;
namespace ngs::fs {
namespace {
void message_pump() {
#if defined(_WIN32)
MSG msg; while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
#endif
}
#if defined(_WIN32)
wstring widen(string str) {
if (str.empty()) return L"";
size_t wchar_count = str.size() + 1;
vector<wchar_t> buf(wchar_count);
return wstring{ buf.data(), (size_t)MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, buf.data(), (int)wchar_count) };
}
string narrow(wstring wstr) {
if (wstr.empty()) return "";
int nbytes = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), (int)wstr.length(), nullptr, 0, nullptr, nullptr);
vector<char> buf(nbytes);
return string{ buf.data(), (size_t)WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), (int)wstr.length(), buf.data(), nbytes, nullptr, nullptr) };
}
#endif
bool is_digit(char byte) {
return (byte >= '0' && byte <= '9');
}
vector<string> directory_contents;
unsigned directory_contents_index = 0;
unsigned directory_contents_order = DC_ATOZ;
unsigned directory_contents_cntfiles = 1;
unsigned directory_contents_maxfiles = 0;
bool directory_contents_completion_async = false;
bool directory_contents_completion_status = false;
time_t file_datetime_helper(string fname, int timestamp) {
int result = -1;
#if defined(_WIN32)
wstring wfname = widen(fname);
struct _stat info;
result = _wstat(wfname.c_str(), &info);
#else
struct stat info;
result = stat(fname.c_str(), &info);
#endif
if (result == -1) return 0;
time_t time = 0;
if (timestamp == 0) time = info.st_atime;
if (timestamp == 1) time = info.st_mtime;
if (timestamp == 2) time = info.st_ctime;
return time;
}
int file_datetime(string fname, int timestamp, int measurement) {
int result = -1;
time_t time = file_datetime_helper(fname, timestamp);
#if defined(_WIN32)
struct tm timeinfo;
if (localtime_s(&timeinfo, &time)) return -1;
switch (measurement) {
case 0: return timeinfo.tm_year + 1900;
case 1: return timeinfo.tm_mon + 1;
case 2: return timeinfo.tm_mday;
case 3: return timeinfo.tm_hour;
case 4: return timeinfo.tm_min;
case 5: return timeinfo.tm_sec;
default: return result;
}
#else
struct tm *timeinfo = std::localtime(&time);
switch (measurement) {
case 0: return timeinfo->tm_year + 1900;
case 1: return timeinfo->tm_mon + 1;
case 2: return timeinfo->tm_mday;
case 3: return timeinfo->tm_hour;
case 4: return timeinfo->tm_min;
case 5: return timeinfo->tm_sec;
default: return result;
}
#endif
return result;
}
int file_bin_datetime(int fd, int timestamp, int measurement) {
int result = -1;
#if defined(_WIN32)
struct _stat info;
result = _fstat(fd, &info);
#else
struct stat info;
result = fstat(fd, &info);
#endif
time_t time = 0;
if (timestamp == 0) time = info.st_atime;
if (timestamp == 1) time = info.st_mtime;
if (timestamp == 2) time = info.st_ctime;
if (result == -1) return result;
#if defined(_WIN32)
struct tm timeinfo;
if (localtime_s(&timeinfo, &time)) return -1;
switch (measurement) {
case 0: return timeinfo.tm_year + 1900;
case 1: return timeinfo.tm_mon + 1;
case 2: return timeinfo.tm_mday;
case 3: return timeinfo.tm_hour;
case 4: return timeinfo.tm_min;
case 5: return timeinfo.tm_sec;
default: return result;
}
#else
struct tm *timeinfo = std::localtime(&time);
switch (measurement) {
case 0: return timeinfo->tm_year + 1900;
case 1: return timeinfo->tm_mon + 1;
case 2: return timeinfo->tm_mday;
case 3: return timeinfo->tm_hour;
case 4: return timeinfo->tm_min;
case 5: return timeinfo->tm_sec;
default: return result;
}
#endif
return result;
}
string string_replace_all(string str, string substr, string nstr) {
size_t pos = 0;
while ((pos = str.find(substr, pos)) != string::npos) {
message_pump();
str.replace(pos, substr.length(), nstr);
pos += nstr.length();
}
return str;
}
vector<string> string_split(string str, char delimiter) {
vector<string> vec;
std::stringstream sstr(str);
string tmp;
while (std::getline(sstr, tmp, delimiter)) {
message_pump();
vec.push_back(tmp);
}
return vec;
}
string filename_path(string fname) {
#if defined(_WIN32)
size_t fp = fname.find_last_of("\\/");
#else
size_t fp = fname.find_last_of("/");
#endif
if (fp == string::npos) return fname;
return fname.substr(0, fp + 1);
}
string filename_name(string fname) {
#if defined(_WIN32)
size_t fp = fname.find_last_of("\\/");
#else
size_t fp = fname.find_last_of("/");
#endif
if (fp == string::npos) return fname;
return fname.substr(fp + 1);
}
string filename_ext(string fname) {
fname = filename_name(fname);
size_t fp = fname.find_last_of(".");
if (fp == string::npos) return "";
return fname.substr(fp);
}
string expand_without_trailing_slash(string dname) {
std::error_code ec;
dname = environment_expand_variables(dname);
ghc::filesystem::path p = ghc::filesystem::path(dname);
p = ghc::filesystem::absolute(p, ec);
if (ec.value() != 0) return "";
dname = p.string();
#if defined(_WIN32)
while ((dname.back() == '\\' || dname.back() == '/') &&
(p.root_name().string() + "\\" != dname && p.root_name().string() + "/" != dname)) {
message_pump(); p = ghc::filesystem::path(dname); dname.pop_back();
}
#else
while (dname.back() == '/' && (!dname.empty() && dname[0] != '/' && dname.length() != 1)) {
dname.pop_back();
}
#endif
return dname;
}
string expand_with_trailing_slash(string dname) {
dname = expand_without_trailing_slash(dname);
#if defined(_WIN32)
if (dname.back() != '\\') dname += "\\";
#else
if (dname.back() != '/') dname += "/";
#endif
return dname;
}
struct file_bin_hardlinks_struct {
vector<string> x;
vector<string> y;
bool recursive;
unsigned i;
unsigned j;
#if defined(_WIN32)
BY_HANDLE_FILE_INFORMATION info;
#else
struct stat info;
#endif
};
vector<string> file_bin_hardlinks_result;
void file_bin_hardlinks_helper(file_bin_hardlinks_struct *s) {
#if defined(_WIN32)
if (file_bin_hardlinks_result.size() >= s->info.nNumberOfLinks) return;
#else
if (file_bin_hardlinks_result.size() >= s->info.st_nlink) return;
#endif
if (s->i < s->x.size()) {
std::error_code ec; if (!directory_exists(s->x[s->i])) return;
s->x[s->i] = expand_without_trailing_slash(s->x[s->i]);
const ghc::filesystem::path path = ghc::filesystem::path(s->x[s->i]);
if (directory_exists(s->x[s->i]) || path.root_name().string() + "\\" == path.string()) {
ghc::filesystem::directory_iterator end_itr;
for (ghc::filesystem::directory_iterator dir_ite(path, ec); dir_ite != end_itr; dir_ite.increment(ec)) {
message_pump(); if (ec.value() != 0) { break; }
ghc::filesystem::path file_path = ghc::filesystem::path(filename_absolute(dir_ite->path().string()));
#if defined(_WIN32)
int fd = -1;
BY_HANDLE_FILE_INFORMATION info;
if (file_exists(file_path.string())) {
// printf("%s\n", file_path.string().c_str());
if (!_wsopen_s(&fd, file_path.wstring().c_str(), _O_RDONLY, _SH_DENYNO, _S_IREAD)) {
bool success = GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &info);
bool matches = (info.ftLastWriteTime.dwLowDateTime == s->info.ftLastWriteTime.dwLowDateTime &&
info.ftLastWriteTime.dwHighDateTime == s->info.ftLastWriteTime.dwHighDateTime &&
info.nFileSizeHigh == s->info.nFileSizeHigh && info.nFileSizeLow == s->info.nFileSizeLow &&
info.nFileIndexHigh == s->info.nFileIndexHigh && info.nFileIndexLow == s->info.nFileIndexLow &&
info.dwVolumeSerialNumber == s->info.dwVolumeSerialNumber);
if (matches && success) {
file_bin_hardlinks_result.push_back(file_path.string());
if (file_bin_hardlinks_result.size() >= info.nNumberOfLinks) {
s->info.nNumberOfLinks = info.nNumberOfLinks; s->x.clear();
_close(fd);
return;
}
}
_close(fd);
}
}
#else
struct stat info;
if (file_exists(file_path.string())) {
// printf("%s\n", file_path.string().c_str());
if (!stat(file_path.string().c_str(), &info)) {
if (info.st_dev == s->info.st_dev && info.st_ino == s->info.st_ino &&
info.st_size == s->info.st_size && info.st_mtime == s->info.st_mtime) {
file_bin_hardlinks_result.push_back(file_path.string());
if (file_bin_hardlinks_result.size() >= info.st_nlink) {
s->info.st_nlink = info.st_nlink; s->x.clear();
return;
}
}
}
}
#endif
if (s->recursive && directory_exists(file_path.string())) {
// printf("%s\n", file_path.string().c_str());
s->x.push_back(file_path.string());
s->i++; file_bin_hardlinks_helper(s);
}
}
}
}
while (s->j < s->y.size() && directory_exists(s->y[s->j])) {
message_pump(); s->x.clear(); s->x.push_back(s->y[s->j]);
s->j++; file_bin_hardlinks_helper(s);
}
}
string directory_get_special_path(int dtype) {
string result;
#if defined(_WIN32)
wchar_t *ptr = nullptr;
KNOWNFOLDERID fid;
switch (dtype) {
case 0: { fid = FOLDERID_Desktop; break; }
case 1: { fid = FOLDERID_Documents; break; }
case 2: { fid = FOLDERID_Downloads; break; }
case 3: { fid = FOLDERID_Music; break; }
case 4: { fid = FOLDERID_Pictures; break; }
case 5: { fid = FOLDERID_Videos; break; }
default: { fid = FOLDERID_Desktop; break; }
}
if (SUCCEEDED(SHGetKnownFolderPath(fid, KF_FLAG_CREATE | KF_FLAG_DONT_UNEXPAND, nullptr, &ptr))) {
result = narrow(ptr);
if (!result.empty() && result.back() != '\\') {
result.push_back('\\');
}
}
CoTaskMemFree(ptr);
#elif defined(__APPLE__) && defined(__MACH__)
char buf[PATH_MAX];
sysdir_search_path_directory_t fid;
sysdir_search_path_enumeration_state state;
switch (dtype) {
case 0: { fid = SYSDIR_DIRECTORY_DESKTOP; break; }
case 1: { fid = SYSDIR_DIRECTORY_DOCUMENT; break; }
case 2: { fid = SYSDIR_DIRECTORY_DOWNLOADS; break; }
case 3: { fid = SYSDIR_DIRECTORY_MUSIC; break; }
case 4: { fid = SYSDIR_DIRECTORY_PICTURES; break; }
case 5: { fid = SYSDIR_DIRECTORY_MOVIES; break; }
default: { fid = SYSDIR_DIRECTORY_DESKTOP; break; }
}
state = sysdir_start_search_path_enumeration(fid, SYSDIR_DOMAIN_MASK_USER);
while ((state = sysdir_get_next_search_path_enumeration(state, buf))) {
if (buf[0] == '~') {
result = buf;
result.replace(0, 1, environment_get_variable("HOME"));
if (!result.empty() && result.back() != '/') {
result.push_back('/');
}
break;
}
}
#else
string fid;
switch (dtype) {
case 0: { fid = "XDG_DESKTOP_DIR="; break; }
case 1: { fid = "XDG_DOCUMENTS_DIR="; break; }
case 2: { fid = "XDG_DOWNLOAD_DIR="; break; }
case 3: { fid = "XDG_MUSIC_DIR="; break; }
case 4: { fid = "XDG_PICTURES_DIR="; break; }
case 5: { fid = "XDG_VIDEOS_DIR="; break; }
default: { fid = "XDG_DESKTOP_DIR="; break; }
}
string conf = environment_get_variable("HOME") + "/.config/user-dirs.dirs";
if (file_exists(conf)) {
int dirs = file_text_open_read(conf);
if (dirs != -1) {
while (!file_text_eof(dirs)) {
string line = file_text_read_string(dirs);
file_text_readln(dirs);
size_t pos = line.find(fid, 0);
if (pos != string::npos) {
FILE *fp = popen(("echo " + line.substr(pos + fid.length())).c_str(), "r");
if (fp) {
char buf[PATH_MAX];
if (fgets(buf, sizeof(buf), fp)) {
string str = buf;
size_t pos = str.find("\n", strlen(buf) - 1);
if (pos != string::npos) {
str.replace(pos, 1, "");
}
if (!directory_exists(str)) {
directory_create(str);
}
result = str;
if (!result.empty() && result.back() != '/') {
result.push_back('/');
}
}
pclose(fp);
}
}
}
file_text_close(dirs);
}
}
#endif
return result;
}
} // anonymous namespace
string directory_get_current_working() {
std::error_code ec;
string result = expand_with_trailing_slash(ghc::filesystem::current_path(ec).string());
return (ec.value() == 0) ? result : "";
}
bool directory_set_current_working(string dname) {
std::error_code ec;
dname = expand_without_trailing_slash(dname);
const ghc::filesystem::path path = ghc::filesystem::path(dname);
ghc::filesystem::current_path(path, ec);
return (ec.value() == 0);
}
string directory_get_temporary_path() {
std::error_code ec;
string result = expand_with_trailing_slash(ghc::filesystem::temp_directory_path(ec).string());
return (ec.value() == 0) ? result : "";
}
string directory_get_desktop_path() {
return directory_get_special_path(0);
}
string directory_get_documents_path() {
return directory_get_special_path(1);
}
string directory_get_downloads_path() {
return directory_get_special_path(2);
}
string directory_get_music_path() {
return directory_get_special_path(3);
}
string directory_get_pictures_path() {
return directory_get_special_path(4);
}
string directory_get_videos_path() {
return directory_get_special_path(5);
}
string executable_get_pathname() {
string path;
#if defined(_WIN32)
wchar_t buffer[MAX_PATH];
if (GetModuleFileNameW(nullptr, buffer, sizeof(buffer)) != 0) {
wchar_t exe[MAX_PATH];
if (_wfullpath(exe, buffer, MAX_PATH)) {
path = narrow(exe);
}
}
#elif (defined(__APPLE__) && defined(__MACH__))
char exe[PROC_PIDPATHINFO_MAXSIZE];
if (proc_pidpath(getpid(), exe, sizeof(exe)) > 0) {
char buffer[PATH_MAX];
if (realpath(exe, buffer)) {
path = buffer;
}
}
#elif (defined(__linux__) && !defined(__ANDROID__))
char exe[PATH_MAX];
if (realpath("/proc/self/exe", exe)) {
path = exe;
}
#elif defined(__FreeBSD__) || defined(__DragonFly__)
int mib[4];
size_t len = 0;
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PATHNAME;
mib[3] = -1;
if (sysctl(mib, 4, nullptr, &len, nullptr, 0) == 0) {
string strbuff;
strbuff.resize(len, '\0');
char *exe = strbuff.data();
if (sysctl(mib, 4, exe, &len, nullptr, 0) == 0) {
char buffer[PATH_MAX];
if (realpath(exe, buffer)) {
path = buffer;
}
}
}
#elif defined(__NetBSD__)
int mib[4];
size_t len = 0;
mib[0] = CTL_KERN;
mib[1] = KERN_PROC_ARGS;
mib[2] = -1;
mib[3] = KERN_PROC_PATHNAME;
if (sysctl(mib, 4, nullptr, &len, nullptr, 0) == 0) {
string strbuff;
strbuff.resize(len, '\0');
char *exe = strbuff.data();
if (sysctl(mib, 4, exe, &len, nullptr, 0) == 0) {
char buffer[PATH_MAX];
if (realpath(exe, buffer)) {
path = buffer;
}
}
}
#elif defined(__OpenBSD__)
auto is_exe = [](string exe) {
int cntp = 0;
string res;
kvm_t *kd = nullptr;
kinfo_file *kif = nullptr;
bool error = false;
kd = kvm_openfiles(nullptr, nullptr, nullptr, KVM_NO_FILES, nullptr);
if (!kd) return res;
if ((kif = kvm_getfiles(kd, KERN_FILE_BYPID, getpid(), sizeof(struct kinfo_file), &cntp))) {
for (int i = 0; i < cntp && kif[i].fd_fd < 0; i++) {
if (kif[i].fd_fd == KERN_FILE_TEXT) {
struct stat st;
fallback:
char buffer[PATH_MAX];
if (!stat(exe.c_str(), &st) && (st.st_mode & S_IXUSR) &&
(st.st_mode & S_IFREG) && realpath(exe.c_str(), buffer) &&
st.st_dev == (dev_t)kif[i].va_fsid && st.st_ino == (ino_t)kif[i].va_fileid) {
res = buffer;
}
if (res.empty() && !error) {
error = true;
size_t last_slash_pos = exe.find_last_of("/");
if (last_slash_pos != string::npos) {
exe = exe.substr(0, last_slash_pos + 1) + kif[i].p_comm;
goto fallback;
}
}
break;
}
}
}
kvm_close(kd);
return res;
};
int mib[4];
char **cmd = nullptr;
size_t len = 0;
vector<string> buffer;
mib[0] = CTL_KERN;
mib[1] = KERN_PROC_ARGS;
mib[2] = getpid();
mib[3] = KERN_PROC_ARGV;
bool error = false, retried = false;
if (sysctl(mib, 4, nullptr, &len, nullptr, 0) == 0) {
if ((cmd = (char **)malloc(len))) {
if (sysctl(mib, 4, cmd, &len, nullptr, 0) == 0) {
buffer.push_back(cmd[0]);
}
free(cmd);
}
}
if (!buffer.empty()) {
string argv0;
if (!buffer[0].empty()) {
fallback:
size_t slash_pos = buffer[0].find('/');
size_t colon_pos = buffer[0].find(':');
if (slash_pos == 0) {
argv0 = buffer[0];
path = is_exe(argv0);
} else if (slash_pos == string::npos || slash_pos > colon_pos) {
string penv = environment_get_variable("PATH");
if (!penv.empty()) {
retry:
string tmp;
std::stringstream sstr(penv);
while (std::getline(sstr, tmp, ':')) {
argv0 = tmp + "/" + buffer[0];
path = is_exe(argv0);
if (!path.empty()) break;
if (slash_pos > colon_pos) {
argv0 = tmp + "/" + buffer[0].substr(0, colon_pos);
path = is_exe(argv0);
if (!path.empty()) break;
}
}
}
if (path.empty() && !retried) {
retried = true;
penv = "/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11R6/bin:/usr/local/bin:/usr/local/sbin";
string home = environment_get_variable("HOME");
if (!home.empty()) {
penv = home + "/bin:" + penv;
}
goto retry;
}
}
if (path.empty() && slash_pos > 0) {
string pwd = environment_get_variable("PWD");
if (!pwd.empty()) {
argv0 = pwd + "/" + buffer[0];
path = is_exe(argv0);
}
if (path.empty()) {
string cwd = directory_get_current_working();
if (!cwd.empty()) {
argv0 = cwd + "/" + buffer[0];
path = is_exe(argv0);
}
}
}
}
if (path.empty() && !error) {
error = true;
buffer.clear();
string underscore = environment_get_variable("_");
if (!underscore.empty()) {
buffer.push_back(underscore);
goto fallback;
}
}
}
if (!path.empty()) {
errno = 0;
}
#elif defined(__sun)
char exe[PATH_MAX];
if (realpath("/proc/self/path/a.out", exe)) {
path = exe;
}
#endif
return path;
}
bool symlink_create(string fname, string newname) {
std::error_code ec;
fname = expand_without_trailing_slash(fname);
newname = expand_without_trailing_slash(newname);
ghc::filesystem::path path1 = ghc::filesystem::path(fname);
ghc::filesystem::path path2 = ghc::filesystem::path(newname);
if (file_exists(fname)) {
if (!directory_exists(filename_path(newname)))
directory_create(filename_path(newname));
ghc::filesystem::create_symlink(path1, path2, ec);
return (ec.value() == 0);
} else if (directory_exists(fname)) {
if (!directory_exists(filename_path(newname)))
directory_create(filename_path(newname));
ghc::filesystem::create_directory_symlink(path1, path2, ec);
return (ec.value() == 0);
}
return false;
}
bool symlink_copy(string fname, string newname) {
std::error_code ec;
fname = expand_without_trailing_slash(fname);
newname = expand_without_trailing_slash(newname);
ghc::filesystem::path path1 = ghc::filesystem::path(fname);
ghc::filesystem::path path2 = ghc::filesystem::path(newname);
if (symlink_exists(fname)) {
if (!directory_exists(filename_path(newname)))
directory_create(filename_path(newname));
ghc::filesystem::copy_symlink(path1, path2, ec);
return (ec.value() == 0);
}
return false;
}
bool symlink_exists(string fname) {
std::error_code ec;
fname = expand_without_trailing_slash(fname);
ghc::filesystem::path path = ghc::filesystem::path(fname);
return (ghc::filesystem::exists(path, ec) && ec.value() == 0 &&
ghc::filesystem::is_symlink(path, ec) && ec.value() == 0);
}
bool hardlink_create(string fname, string newname) {
fname = expand_without_trailing_slash(fname);
newname = expand_without_trailing_slash(newname);
if (file_exists(fname)) {
if (!directory_exists(filename_path(newname)))
directory_create(filename_path(newname));
#if defined(_WIN32)
std::error_code ec;
const ghc::filesystem::path path1 = ghc::filesystem::path(fname);
const ghc::filesystem::path path2 = ghc::filesystem::path(newname);
ghc::filesystem::create_hard_link(path1, path2, ec);
return (ec.value() == 0);
#else
return (!link(fname.c_str(), newname.c_str()));
#endif
}
return false;
}
std::uintmax_t file_numblinks(string fname) {
std::error_code ec;
fname = expand_without_trailing_slash(fname);
if (file_exists(fname)) {
int fd = file_bin_open(fname, FD_RDONLY);
if (fd != -1) {
std::uintmax_t result = file_bin_numblinks(fd);
file_bin_close(fd);
return result;
}
}
return 0;
}
std::uintmax_t file_bin_numblinks(int fd) {
#if defined(_WIN32)
BY_HANDLE_FILE_INFORMATION info;
if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &info)) {
return info.nNumberOfLinks;
}
#else
struct stat info;
if (!fstat(fd, &info)) {
return info.st_nlink;
}
#endif
return 0;
}
string file_bin_hardlinks(int fd, string dnames, bool recursive) {
string paths;
#if defined(_WIN32)
BY_HANDLE_FILE_INFORMATION info;
if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &info) && info.nNumberOfLinks) {
#else
struct stat info;
if (!fstat(fd, &info) && info.st_nlink) {
#endif
file_bin_hardlinks_result.clear();
struct file_bin_hardlinks_struct s;
vector<string> in = string_split(dnames, '\n');
if (in.empty()) return paths;
vector<string> first;
first.push_back(in[0]);
in.erase(in.begin());
s.x = first;
s.y = in;
s.i = 0;
s.j = 0;
s.recursive = recursive;
s.info = info;
file_bin_hardlinks_helper(&s);
for (unsigned i = 0; i < file_bin_hardlinks_result.size(); i++) {
message_pump(); paths += file_bin_hardlinks_result[i] + "\n";
}
if (!paths.empty()) {
paths.pop_back();
}
}
return paths;
}
string executable_get_directory() {
return filename_path(executable_get_pathname());
}
string executable_get_filename() {
return filename_name(executable_get_pathname());
}
string environment_get_variable(string name) {
#if defined(_WIN32)
string value;
DWORD length = 0;
wstring u8name = widen(name);
if ((length = GetEnvironmentVariableW(u8name.c_str(), nullptr, 0)) != 0) {
wchar_t *buffer = new wchar_t[length]();
if (GetEnvironmentVariableW(u8name.c_str(), buffer, length) != 0) {
value = narrow(buffer);
}
delete[] buffer;
}
return value;
#else
char *value = getenv(name.c_str());
return value ? value : "";
#endif
}
bool environment_get_variable_exists(string name) {
#if defined(_WIN32)
wstring u8name = widen(name);
return (!(GetEnvironmentVariableW(u8name.c_str(), nullptr, 0) == 0 &&
GetLastError() == ERROR_ENVVAR_NOT_FOUND));
#else
return (getenv(name.c_str()) != nullptr);
#endif
}
bool environment_set_variable(string name, string value) {
#if defined(_WIN32)
wstring u8name = widen(name);
wstring u8value = widen(value);
return (SetEnvironmentVariableW(u8name.c_str(), u8value.c_str()) != 0);
#else
return (setenv(name.c_str(), value.c_str(), 1) == 0);
#endif
}
bool environment_unset_variable(string name) {
#if defined(_WIN32)
wstring u8name = widen(name);
return (SetEnvironmentVariableW(u8name.c_str(), nullptr) != 0);
#else
return (unsetenv(name.c_str()) == 0);
#endif
}
string environment_expand_variables(string str) {
if (str.find("${") == string::npos) return str;
string pre = str.substr(0, str.find("${"));
string post = str.substr(str.find("${") + 2);
if (post.find('}') == string::npos) return str;
string variable = post.substr(0, post.find('}'));
size_t pos = post.find('}') + 1; post = post.substr(pos);
string value = environment_get_variable(variable);
if (!environment_get_variable_exists(variable))
return str.substr(0, pos) + environment_expand_variables(str.substr(pos));
return environment_expand_variables(pre + value + post);
}
bool file_exists(string fname) {
std::error_code ec;
fname = expand_without_trailing_slash(fname);
const ghc::filesystem::path path = ghc::filesystem::path(fname);
return (ghc::filesystem::exists(path, ec) && ec.value() == 0 &&
(!ghc::filesystem::is_directory(path, ec)) && ec.value() == 0);
}
bool directory_exists(string dname) {
std::error_code ec;
dname = expand_without_trailing_slash(dname);
dname = expand_without_trailing_slash(dname);
const ghc::filesystem::path path = ghc::filesystem::path(dname);
return (ghc::filesystem::exists(path, ec) && ec.value() == 0 &&
ghc::filesystem::is_directory(path, ec) && ec.value() == 0);
}
string filename_canonical(string fname) {
std::error_code ec;
fname = expand_without_trailing_slash(fname);
const ghc::filesystem::path path = ghc::filesystem::path(fname);
string result = ghc::filesystem::weakly_canonical(path, ec).string();
if (ec.value() == 0 && directory_exists(result)) {
return expand_with_trailing_slash(result);
}
return (ec.value() == 0) ? result : "";
}
string filename_absolute(string fname) {
string result;
if (directory_exists(fname)) {
result = expand_with_trailing_slash(fname);
} else if (file_exists(fname)) {
result = expand_without_trailing_slash(fname);
}
return result;
}
bool filename_equivalent(string fname1, string fname2) {
std::error_code ec;
fname1 = expand_without_trailing_slash(fname1);
fname2 = expand_without_trailing_slash(fname2);
ghc::filesystem::path path1 = ghc::filesystem::path(fname1);
ghc::filesystem::path path2 = ghc::filesystem::path(fname2);
if (ghc::filesystem::exists(path1, ec) && ec.value() == 0 &&
ghc::filesystem::exists(path2, ec) && ec.value() == 0) {
return (ghc::filesystem::equivalent(path1, path2, ec) && ec.value() == 0);
}
return false;
}
std::uintmax_t file_size(string fname) {
std::error_code ec;
if (!file_exists(fname)) return 0;
fname = expand_without_trailing_slash(fname);
const ghc::filesystem::path path = ghc::filesystem::path(fname);
std::uintmax_t result = ghc::filesystem::file_size(path, ec);
return (ec.value() == 0) ? result : 0;
}
bool file_delete(string fname) {
std::error_code ec;
if (!file_exists(fname)) return false;
fname = expand_without_trailing_slash(fname);
const ghc::filesystem::path path = ghc::filesystem::path(fname);
return (ghc::filesystem::remove(path, ec) && ec.value() == 0);
}
bool directory_create(string dname) {
std::error_code ec;
dname = expand_without_trailing_slash(dname);
const ghc::filesystem::path path = ghc::filesystem::path(dname);
return (ghc::filesystem::create_directories(path, ec) && ec.value() == 0);
}
bool file_rename(string oldname, string newname) {
std::error_code ec;
if (!file_exists(oldname)) return false;
oldname = expand_without_trailing_slash(oldname);
newname = expand_without_trailing_slash(newname);
if (!directory_exists(filename_path(newname)))
directory_create(filename_path(newname));
const ghc::filesystem::path path1 = ghc::filesystem::path(oldname);
const ghc::filesystem::path path2 = ghc::filesystem::path(newname);
ghc::filesystem::rename(path1, path2, ec);
return (ec.value() == 0);
}
bool file_copy(string fname, string newname) {
std::error_code ec;
if (!file_exists(fname)) return false;
fname = expand_without_trailing_slash(fname);
newname = expand_without_trailing_slash(newname);
if (!directory_exists(filename_path(newname)))
directory_create(filename_path(newname));
const ghc::filesystem::path path1 = ghc::filesystem::path(fname);
const ghc::filesystem::path path2 = ghc::filesystem::path(newname);
ghc::filesystem::copy(path1, path2, ec);
return (ec.value() == 0);
}
std::uintmax_t directory_size(string dname) {
std::error_code ec;
std::uintmax_t result = 0;
if (!directory_exists(dname)) return 0;
const ghc::filesystem::path path = ghc::filesystem::path(expand_without_trailing_slash(dname));
if (ghc::filesystem::exists(path, ec)) {
ghc::filesystem::directory_iterator end_itr;
for (ghc::filesystem::directory_iterator dir_ite(path, ec); dir_ite != end_itr; dir_ite.increment(ec)) {
message_pump(); if (ec.value() != 0) { break; }
ghc::filesystem::path file_path = ghc::filesystem::path(filename_absolute(dir_ite->path().string()));
if (!directory_exists(file_path.string())) {
result += file_size(file_path.string());
} else {
result += directory_size(file_path.string());
}
}
}