-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathpath.cpp
More file actions
3401 lines (3043 loc) · 94.2 KB
/
path.cpp
File metadata and controls
3401 lines (3043 loc) · 94.2 KB
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
/* -*- coding: utf-8 -*-
* This file is part of Pathie.
*
* Copyright © 2015, 2017, 2019 Marvin Gülker
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "../include/pathie/path.hpp"
#include "../include/pathie/pathie.hpp"
#include "../include/pathie/errors.hpp"
#include <cstdlib>
#include <cstdio>
#include <ctime>
#include <cstring>
#include <iostream>
#include <sstream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdexcept>
#include <errno.h>
#if defined(_WIN32)
#include <windows.h>
#include <winioctl.h>
#include <direct.h>
#include <shlobj.h>
#include <shlwapi.h>
//#include <ntifs.h> // Currently not in msys2
#ifndef F_OK
#define F_OK 0
#endif
#ifndef W_OK
#define W_OK 2
#endif
#ifndef R_OK
#define R_OK 4
#endif
#elif defined(_PATHIE_UNIX)
#include <unistd.h>
#include <limits.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h> // defines "BSD" macro on BSD systems
#include <pwd.h>
#include <glob.h>
#include <fnmatch.h>
#else
#error Unsupported system.
#endif
#ifdef BSD
#include <sys/time.h>
#include <sys/sysctl.h>
#endif
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
using namespace Pathie;
using namespace std;
Path::localpathtype Path::c_localdefault = LOCALPATH_LOCAL;
/**
* The default constructor. It does **not** create an empty
* path, but a path whose value is ".", i.e. the current
* working directory as a relative path (see also pwd()).
*/
Path::Path()
{
m_path = ".";
}
/**
* Copies contents from path to a new instance.
*
* \param[in] path The Path instance to copy.
*/
Path::Path(const Path& path)
{
m_path = path.m_path;
}
/**
* This constructs a path from a given std::string. The path is
* automatically sanitized, i.e. backslashes are replaced with forward
* slashes (Windows perfectly well handles path separation with
* forward slashes), double slashes are replaced with a single slash,
* and a trailing slash (if exists) is removed.
*
* \param path String to construct from. Must be encoded in UTF-8.
*
* \returns a new instance of class Path.
*
* \remark On Windows, UNC paths (paths starting with a double leading
* forward or backward slash) are allowed. The constructor is not
* going to strip the double slash away. On UNIX, leading double
* slashes (forward and backward) are sanitised into a single leading
* (forward) slash.
*/
Path::Path(std::string path)
{
m_path = path;
sanitize();
}
/**
* Constructs a Path instance from a list of path components.
* This is the inverse of the burst() method.
*
* \param[in] components List of components to join.
*
* \returns A new instance.
*/
Path::Path(const std::vector<Path>& components)
{
m_path = components.front().m_path;
if (components.size() > 1) {
// Ensure that for both absolute and relative path we end in
// a slash for appending below
if (m_path[0] != '/') {
m_path += "/";
}
std::vector<Path>::const_iterator iter;
for(iter=components.begin()+1; iter != components.end(); iter++) { // first element has already been taken care of above
m_path += (*iter).m_path + "/";
}
// Trailing slash is unwanted, remove it
m_path = m_path.substr(0, m_path.length()-1);
}
}
/**
* Sanitizes the path. It:
*
* 1. Replaces any backslashes with forward slashes (read Windows).
* 2. Replaces all double forward slashes with single forward slashes
* 3. Delates a trailing slash, if any.
*/
void Path::sanitize()
{
#ifdef _WIN32
bool is_unc = m_path.length() > 2 && (m_path.substr(0, 2) == "\\\\" || m_path.substr(0, 2) == "//");
#else
bool is_unc = false;
#endif
// Replace any backslashes \ with forward slashes /.
size_t cur = string::npos;
while ((cur = m_path.find("\\")) != string::npos) { // assignment intended
m_path.replace(cur, 1, "/");
}
// Replace all double slashes // with a single one,
// except for UNC pathes on Windows.
cur = string::npos;
while ((cur = m_path.find("//", is_unc ? 1 : 0)) != string::npos) { // assignment intended
m_path.replace(cur, 2, "/");
}
// Remove trailing slash if any (except for the filesystem root)
long len = m_path.length();
#if defined(_PATHIE_UNIX)
if (len > 1 && m_path[len - 1] == '/')
m_path = m_path.substr(0, len - 1);
#elif defined(_WIN32)
if (len > 1) { // / is root of current drive, "x" is the relative path "./x"
// Check if X:/foo/bar
if (len > 3 && m_path[len - 1] == '/') { // More than 3 chars cannot be root
m_path = m_path.substr(0, len - 1);
}
else { // Only drive root?
if (m_path[1] == ':') {
// Here m_path must be a drive root. The colon ":" is not allowed in paths on Windows except as the 2nd char to denote the drive letter
if (len == 2) { // Whoa -- "X:" misses leading / for drive root, append it
m_path.append("/");
}
else if (len == 3 && m_path[2] != '/') { // Whoa -- "X:f" misses leading / for root directory, insert it
m_path.insert(2, "/");
}
// else length is 3 with a slash, i.e. "X:/". This is fine and shall not be touched.
}
else { // not a drive root, delete trailing / if any
if (m_path[len - 1] == '/') {
m_path = m_path.substr(0, len - 1);
}
}
}
}
#else
#error Unsupported system
#endif
}
/** \name Conversion methods
*
* Convert a path to other objects.
*/
///@{
/**
* Returns a copy of the underlying `std::string`. This is always
* encoded in UTF-8, regardless of the operating system.
*
* \see native() utf8_str()
*/
std::string Path::str() const
{
return m_path;
}
/**
* This method does the same as str(). It exists to make code using
* the UTF-8 variant more readable, because one tends to forget
* whether str() returns the native or the UTF-8 variant.
*
* \see native() str()
*/
std::string Path::utf8_str() const
{
return m_path;
}
#if defined(_PATHIE_UNIX)
std::string Path::native() const
{
return utf8_to_filename(m_path);
}
#elif defined(_WIN32)
/**
* Returns the path in the platform’s native format. Note
* that this method returns a `std::string` on UNIX,
* whereas it returns a `std::wstring` on Windows.
*
* On Windows, the returned string also uses exclusively backslashes
* instead of forward slashes. It is encoded in UTF-16LE.
*
* On UNIX, the returned string is in the encoding dictated by the locale
* ($LANG and $LC_ALL variables).
*/
std::wstring Path::native() const
{
std::string dup(m_path);
size_t pos = 0;
while((pos = dup.find("/", pos)) != std::string::npos) { // Single = intended
dup.replace(pos, 1, "\\");
}
return utf8_to_utf16(dup);
}
#else
#error Unsupported system.
#endif
///@}
/** \name Path decomposition
*
* Retrieve the parts of the path you want.
*/
///@{
/**
* Returns the path’s basename, i.e. the last component
* of the path, including the file excention.
*
* For example, "/foo/bar.txt" has a basename of "bar.txt",
* and "/foo/bar" has a basename of "bar".
*
* \returns a new Path instance with only the basename.
*
* \see dirname()
*/
Path Path::basename() const
{
if (m_path == ".")
return Path(".");
else if (m_path == "..")
return Path("..");
else if (is_root())
return Path(m_path);
size_t pos = 0;
if ((pos = m_path.rfind("/")) != string::npos) // Single = intended
return Path(m_path.substr(pos + 1));
else
return Path(m_path);
}
/**
* Returns the path’s dirname, i.e. all components of the
* path except for the basename component (see basename()).
*
* For example, "/foo/bar/baz.txt" has a dirname of "/foo/bar",
* and "/foo/bar/baz" has a dirname of "/foo/bar".
*
* \returns a new Path instance with only the dirname.
*
* \see basename() parent()
*/
Path Path::dirname() const
{
if (m_path == ".")
return Path(".");
else if (m_path == "..")
return Path(".");
else if (is_root())
return Path(m_path);
size_t pos = 0;
if ((pos = m_path.rfind("/")) != string::npos) { // Single = intended
if (pos == 0) { // /usr
return root();
}
#ifdef _WIN32
else if (pos == 1 && m_path[1] == ':') { // X:/foo
return root();
}
#endif
else { // regular/path or /regular/path
return Path(m_path.substr(0, pos));
}
}
else // single relative directory
return Path(".");
}
/**
* This is a convenience method that allows you to retrieve
* both the dirname() and the basename() in one call.
*
* \param[out] dname Receives the dirname() value.
* \param[out] bname Receives the basename() value.
*/
void Path::split(Path& dname, Path& bname) const
{
dname = dirname();
bname = basename();
}
/**
* This method returns the file extension of the path,
* if possible; otherwise it returns an empty string.
* Filenames that consist entirely of a "file extension",
* i.e. ".txt" or "/foo/.txt" will return an empty string.
*/
std::string Path::extension() const
{
if (m_path == ".")
return "";
else if (m_path == "..")
return "";
size_t pos = 0;
if ((pos = m_path.rfind(".")) != string::npos) { // assignment intended
if (pos == 0 || pos == m_path.length() - 1) // .foo and foo.
return "";
else {
if (m_path[pos - 1] == '/') // foo/.txt
return "";
else
return m_path.substr(pos);
}
}
else
return "";
}
/**
* This is the same as dirname() and is provided only for convenience.
*
* \see dirname()
*/
Path Path::parent() const
{
return dirname();
}
/**
* Returns the number of components in the path string, or
* in different words, counts the slashes and adds one for
* the last element, except if the path is just the root
* (see is_root()).
*
* The return value of this method minus one is the last
* possible index for operator[].
*/
size_t Path::component_count() const
{
if (is_root())
return 1;
size_t result = 0;
size_t pos = 0;
while ((pos = m_path.find("/", pos)) != string::npos) { // Assignment intended
result++;
pos++;
}
return ++result;
}
/**
* Returns the filesystem root for this path. On UNIX,
* this will always return /, but on Windows it will
* return X:/ if the referenced path is an absolute path
* with drive letter, and / if the referenced path is
* a relative path or an absolute path on the current
* drive.
*/
Path Path::root() const
{
#if defined(_PATHIE_UNIX)
return Path("/");
#elif defined(_WIN32)
// Check if we have an absolute path with drive,
// otherwise return the root for the current drive.
if (m_path[1] == ':') // Colon is on Windows only allowed here to denote a preceeding drive letter => absolute path
return Path(m_path.substr(0, 3));
else
return Path("/");
#else
#error Unsupported system.
#endif
}
/**
* This method splits up the paths into its separate components,
* i.e. it splits it up at every /, except for the leading / of
* an absolute path, which is considered a component on its own
* and is thus the first element of a bursted absolute path.
*
* \param descend (`false`) If this is true, keeps the parent paths when bursting.
*
* \returns A vector of Path instances, where each instance
* corresponds to one component of the Path.
*
* Example:
*
* ~~~~~~~~~~~~~~~~~~~~ c++
* Path p("/tmp/foo/bar");
* p.burst(); // => /, tmp, foo, bar
* p.burst(true); // => /, /tmp, /tmp/foo, /tmp/foo/bar
* ~~~~~~~~~~~~~~~~~~~~
*/
std::vector<Path> Path::burst(bool descend /* = false */) const
{
size_t pos = 0;
size_t lastpos = 0;
std::vector<Path> results;
std::string prefix;
// Take care of leading / of absolute paths
if (m_path[0] == '/') {
results.push_back(Path("/"));
prefix.append("/");
// Adjust pos so we don’t find the initial /
pos++;
lastpos++;
}
while((pos = m_path.find("/", pos)) != string::npos) {
std::string component = m_path.substr(lastpos, pos - lastpos);
if (descend) {
results.push_back(Path(prefix + component));
prefix.append(component);
prefix.append("/");
}
else {
results.push_back(Path(component));
}
lastpos = pos + 1;
pos++;
}
std::string lastcomponent = m_path.substr(lastpos);
if (descend)
results.push_back(Path(prefix + lastcomponent)); // Note no trailing /
else
results.push_back(Path(lastcomponent));
return results;
}
///@}
/** \name Path expansion
*
* Expand paths to a more fuller version without shortcuts.
*/
///@{
/**
* This method, removes all occurences of . and .. from the path,
* leaving a clean filesystem path.
*
* Note that neither an absolute path is created, nor
* are shortcuts other than . and .. expanded.
*
* This method does not access file filesystem, and thus does not
* know about symbolic links. Therefore, if the path contains symlinks,
* the result may not be the way you expect it. Use real() if
* you need to resolve all your symbolic links in the path.
*
* For example, if you have a directory `/tmp/foo`, which contains a
* symbolic link `bar` that points to `/tmp/bar`, then a path of
* `/tmp/foo/bar/..` will be prune()d to `/tmp/foo`, although the
* canonically correct result is `/tmp`. The latter is what you will
* get if you use real().
*
* \returns A new string with . and .. removed.
*
* \see expand() real()
*/
Path Path::prune() const
{
std::string newpath(m_path); // copy
size_t pos = 0;
while((pos = newpath.find("/.", pos)) != string::npos) { // assignment intended
if (newpath.substr(pos, 3) == "/..") {
// Weird path like /..foo or foo/..bar, which are NOT relative paths
if (newpath.length() > pos + 3 && newpath[pos + 3] != '/') {
// Do not reset `pos' -- this has to stay. Advance to the next char.
pos++;
continue;
}
if (pos == 0) {
// /.. at beginning of string, replace with root / (/ on Windows is root on current drive)
newpath.erase(pos, 3);
// Whoops -- the entire string was just "/.."
if (newpath.empty()) {
newpath.append("/");
}
}
#ifdef _WIN32
// Cater for paths with drive X:/ on Windows
else if (pos == 2 && newpath[1] == ':') { // ":" is on Windows only allowed at pos 1, where it signifies the preceding char is a drive letter
// X:/. or X:/.. at beginning of string
if(newpath.length() > 4 && newpath[4] == '.') { // X:/..
// Prevent special case "X:/..foo", which is directory "..foo" under the root
if (newpath.length() <= 5 || newpath[5] != '/') {
// X:/.. or X:/../foo/bar at beginning of string, replace with drive root
newpath.erase(pos, 3);
}
}
else { // X:/./foo/bar X:/..foo
// Prevent special case "X:/.foo", which is directory ".foo" under the root
if (newpath.length() <= 4 || newpath[4] != '/') {
// X:/. or X:/./foo/bar at beginning of string, replace with drive root
newpath.erase(pos, 2);
}
}
if (newpath.length() == 2) {
// Whoops -- the entire string was just "X:/.." or "X:/."
newpath.append("/");
}
}
#endif
else {
size_t pos2 = 0;
if ((pos2 = newpath.rfind("/", pos - 1)) != string::npos) { // assignment intended
// Remove parent directory.
newpath.erase(pos2, pos - pos2 + 3);
}
else { // ../ for relative path (as in foo/../baz.txt)
newpath.erase(0, pos + 4);
}
}
}
else { // Single /.
// Weird path like /..foo or foo/..bar, which are NOT relative paths
if (newpath.length() > pos + 2 && newpath[pos + 2] != '/') {
// Do not reset `pos' -- this has to stay. Advance to the next char.
pos++;
continue;
}
newpath.erase(pos, 2);
// Whoops -- the entire string was just "/."
if (newpath.empty()) {
newpath.append("/");
}
}
// Reset as we have modified the string and might need to go again over it
pos = 0;
}
/* If we are empty now, the original string was a one-element
* relative path with .. appended. We cannot know what to set
* without referring to pwd(), which is external access and
* forbidden for this method. So instead, we do the one sane thing
* and just use ".". */
if (newpath.empty())
newpath = ".";
return Path(newpath);
}
/**
* \note Under specific circumstances (see below), this method
* accesses the file system.
*
* This method creates an absolute path by use of prune(), but
* additionally expands any expandable strings. If one of the
* following substitution sequences are encountered, it will be
* replaced accordingly.
*
* "~" is expanded to the user’s home directory, see home().
*
* \returns a new instance with everything expanded.
*
* \remark This method uses prune() to expand ".." entries, therefore
* it will not consider symbolic links when resolving those. Use
* real() if you need to do that.
*
* \see prune() real()
*/
Path Path::expand() const
{
Path path(*this); // copy
if (m_path[0] != '~')
path = path.absolute();
std::string str = path.str();
if (str[0] == '~') {
Path homepath = home();
if (str[1] == '/' || str.length() == 1) {
// User home requested
str.replace(0, 1, homepath.m_path);
}
path = Path(str);
}
return path.prune();
}
/**
* \note This method acceses the filesystem.
*
* This is the bruteforce method for determing the real path
* of the entry in question on the filesystem. It looks on
* each single component of the path, checks if it is a
* symbolic link, and if so, resolves it.
*
* This method supports symbolic link resolving only on UNIX.
*
* It still does not consider hardlinks, mountpoints, and junctions,
* though. However, a hardlink is a real second valid name for an
* object; in contrast to a symbolic link, if one hardlink gets
* removed, the other one stays still valid. If you remove the file a
* symbolic link points to, the link breaks. Thus, it is not even
* possible to determine which of two hardlinks to a file is the
* "primary" one. Mountpoints and junctions (junctions are on Windows
* what mountpoints are on UNIX) behave similar with respect to
* entire directory hierarchies.
*
* \see expand() prune()
*/
Path Path::real() const
{
#if defined(_PATHIE_UNIX)
std::string nstr = native();
char path[PATH_MAX];
if (!realpath(nstr.c_str(), path))
throw(Pathie::ErrnoError(errno));
return Path(filename_to_utf8(path));
#elif defined(_WIN32)
// On Windows there sadly is no easy way to do this. We can
// only determine if a given path is a symlink and resolve it...
// Instructions taken from: http://msdn.microsoft.com/en-us/library/windows/desktop/aa363940%28v=vs.85%29.aspx
std::vector<Path> components = burst();
unsigned int pos = 0;
while (pos < components.size()) {
// Build path consisting of all elements upto our position pointer
Path reduced_path(components.front());
if (components.size() - pos > 1) {
for (unsigned int i=1; i <= pos; i++) { // i=0 is already in the initialization above
reduced_path = reduced_path.join(components[i]);
}
}
// If that’s a symlink, resolve it and replace our path until
// the symlink with the symlink’s target.
/*std::wstring reduced_path_utf16 = utf8_to_utf16(reduced_path.m_path);
if (is_ntfs_symlink(reduced_path_utf16.c_str())) {
wchar_t* target_utf16 = read_ntfs_symlink(reduced_path_utf16.c_str());
Path target(utf16_to_utf8(target_utf16));
std::vector<Path> target_components = target.burst();
free(target_utf16);
// Replace all components up to pos with the symlink target
components.erase(components.begin(), components.begin() + pos);
std::vector<Path> temp(components);
components.clear();
for(auto iter=target_components.begin(); iter != target_components.end(); iter++)
components.push_back(*iter);
for(auto iter=temp.begin(); iter != temp.end(); iter++)
components.push_back(*iter);
}
else {*/
// Note a symlink can point to another symlink, so we can only
// advance to the next element if this element has been tested
// for not being a symlink.
pos++;
//}
}
// BUild a new path from the now resolved components
Path result(components.front());
if (components.size() > 1) {
for(std::vector<Path>::const_iterator iter=components.begin();
iter != components.end(); iter++) {
result = result.join(*iter);
}
}
return result;
#else
#error Unsupported system.
#endif
}
// Msys2 does currently not have ntifs.h windows header, which
// is required for reading NTFS symlinks.
#if 0
//#ifdef __WIN32
/*
* Checking if a file is a symlink under Windows is insane.
* See http://msdn.microsoft.com/en-us/library/windows/desktop/aa363940%28v=vs.85%29.aspx
* for the detailed instructions by Microsoft on how to do
* that.
*/
bool Path::is_ntfs_symlink(const wchar_t* path) const
{
// First we need to obtain the file attributes.
DWORD attrs = GetFileAttributesW(path);
if (attrs == INVALID_FILE_ATTRIBUTES) {
DWORD err = GetLastError();
throw(Pathie::WindowsError(err));
}
/* These file attributes must contain the REPARSE_POINT attribute
* that mark the file as being symlink, junction, or similar.
* Actually, reparse points can contain many more custom data, but
* we are not intersted in those. */
if (attrs & FILE_ATTRIBUTE_REPARSE_POINT) {
// Now we have to retrieve a special attributes handle from the file.
WIN32_FIND_DATAW finddata;
HANDLE findhandle = FindFirstFileW(path, &finddata);
if (findhandle == INVALID_HANDLE_VALUE) {
DWORD err = GetLastError();
throw(Pathie::WindowsError(err));
}
FindClose(findhandle);
// These extended attributes contain the SYMLINK tag if this file
// is a symlink.
if (finddata.dwReserved0 & IO_REPARSE_TAG_SYMLINK)
return true;
// Junction or so, we do not resolve that
return false;
}
// Regular file
return false;
}
/*
* Reading the link target also is insanely hard.
* The process is documented at http://msdn.microsoft.com/en-us/library/windows/desktop/aa365503%28v=vs.85%29.aspx
* in general. The key function is DeviceIoControl(), documented
* at http://msdn.microsoft.com/en-us/library/windows/desktop/aa363216%28v=vs.85%29.aspx
* .
*
* This function does not check if `path` is a symlink, but assumes it.
* It will exhibit unexpactable behaviour if this assumption is wrong.
*
* The returned pointer must be freed by you.
*/
wchar_t* Path::read_ntfs_symlink(const wchar_t* path) const
{
// We have to open the file (directories are files on Windows also) first.
HANDLE filehandle = CreateFileW(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, NULL);
if (filehandle == INVALID_HANDLE_VALUE) {
DWORD err = GetLastError();
throw(Pathie::WindowsError(err));
}
// This infamous structure is documented here: http://msdn.microsoft.com/en-us/library/ff552012.aspx
unsigned long reparsebufsize = REPARSE_GUID_DATA_BUFFER_HEADER_SIZE; // According to docs this is the minimum size
REPARSE_DATA_BUFFER* p_reparse_data = NULL;
while (true) {
reparsebufsize += 4096; // Do you have a better guess?
p_reparse_data = (REPARSE_DATA_BUFFER*) realloc(p_reparse_data, reparsebufsize);
memset(p_reparse_data, '\0', reparsebufsize);
DWORD bytecount = 0;
// Obtain the reparse tag. FSCTL_GET_REPARSE_POINT is documented here: http://msdn.microsoft.com/en-us/library/windows/desktop/aa364571(v=vs.85).aspx
if (DeviceIoControl(filehandle, FSCTL_GET_REPARSE_POINT, NULL, 0, p_reparse_data, reparsebufsize, &bytecount, NULL) == 0) {
DWORD errsav = GetLastError();
if (errsav == ERROR_INSUFFICIENT_BUFFER) { // buffer was to small, try again
continue;
}
else {
throw(Pathie::WindowsError(errsav));
}
}
else { // success
break;
}
}
// See also http://msdn.microsoft.com/en-us/library/windows/desktop/aa365511(v=vs.85).aspx
// And this one: http://www.codeproject.com/Articles/21202/Reparse-Points-in-Vista
if (p_reparse_data->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
wchar_t* subsname = (wchar_t*) malloc(p_reparse_data->SymbolicLinkReparseBuffer.SubstituteNameLength + 2); // UTF-16 NUL
wchar_t* printname = (wchar_t*) malloc(p_reparse_data->SymbolicLinkReparseBuffer.PrintNameLength + 2); // UTF-16 NUL
memset(subsname, '\0', p_reparse_data->SymbolicLinkReparseBuffer.SubstituteNameLength + 2);
memset(printname, '\0', p_reparse_data->SymbolicLinkReparseBuffer.PrintNameLength + 2);
wcsncpy(subsname, &p_reparse_data->SymbolicLinkReparseBuffer.PathBuffer[p_reparse_data->SymbolicLinkReparseBuffer.SubstituteNameOffset], p_reparse_data->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(WCHAR));
wcsncpy(printname, &p_reparse_data->SymbolicLinkReparseBuffer.PathBuffer[p_reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset], p_reparse_data->SymbolicLinkReparseBuffer.PrintNameLength / sizeof(WCHAR));
// Actually, it appears the subsname has no real usecase...
free(subsname);
free(p_reparse_data);
CloseHandle(filehandle);
return printname;
}
else {
return NULL;
}
}
#endif
///@}
/** \name Special files and directories
*
* Files and directories with a special meaning that did not
* fit in the other groups.
*/
///@{
/**
* Determines the current process working directory and returns
* it as an absolute path. Contains a leading drive letter on
* Windows.
*/
Path Path::pwd()
{
#if defined(_PATHIE_UNIX)
char cwd[PATH_MAX];
if (getcwd(cwd, PATH_MAX) != NULL)
return Path(filename_to_utf8(cwd));
else
throw(std::runtime_error("Failed to retrieve current working directory."));
#elif defined(_WIN32)
wchar_t cwd[MAX_PATH];
if (GetCurrentDirectoryW(MAX_PATH, cwd) == 0)
throw(std::runtime_error("Failed to retrieve current working directory."));
else
return Path(utf16_to_utf8(std::wstring(cwd)));
#else
#error Unsupported platform.
#endif
}
/**
* \note On Linux, this method accesses the `/proc` filesystem.
*
* This method returns the full absolute path to the currently running
* executable.
*/
Path Path::exe()
{
#if defined(__linux__)
char buf[PATH_MAX];
ssize_t size = ::readlink("/proc/self/exe", buf, PATH_MAX);
if (size < 0)
throw(Pathie::ErrnoError(errno));
return Path(filename_to_utf8(std::string(buf, size)));
#elif defined(__APPLE__)
char buf[PATH_MAX];
uint32_t size = sizeof(buf);
if (_NSGetExecutablePath(buf, &size) == 0)
// Might contain symlinks or extra slashes. Shouldn't be an issue though
// https://stackoverflow.com/questions/799679/programmatically-retrieving-the-absolute-path-of-an-os-x-command-line-app/1024933#1024933
return Path(filename_to_utf8(std::string(buf, size)));
else
throw(Pathie::ErrnoError(errno));
#elif defined(BSD)
// BSD does not have /proc mounted by default. However, using raw syscalls,
// we can figure out what would have been in /proc/curproc/file. See
// sysctl(3) for the management info base identifiers that are used here.
int mib[4];
char buf[PATH_MAX];
size_t bufsize = PATH_MAX;
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PATHNAME;
mib[3] = -1; // According to sysctl(3), -1 means the current process.
if (sysctl(mib, 4, buf, &bufsize, NULL, 0) != 0) // Note this changes `bufsize' to the number of chars copied
throw(Pathie::ErrnoError(errno));
return Path(filename_to_utf8(std::string(buf, bufsize - 1))); // Exclude terminating NUL
#elif defined(_WIN32)
wchar_t buf[MAX_PATH];
if (GetModuleFileNameW(NULL, buf, MAX_PATH) == 0) {
DWORD err = GetLastError();
throw(Pathie::WindowsError(err));
}
std::string str = utf16_to_utf8(buf);
return Path(str);
#else
#error Unsupported platform.
#endif
}
/**
* This method returns the current user’s home directory. On UNIX
* systems, the $HOME environment variable is consulted, whereas
* on Windows the Windows API is queried for the directory.
*
* It will throw std::runtime_error if $HOME is not defined on
* UNIX.
*/
Path Path::home()
{
#if defined(_PATHIE_UNIX)
char* homedir = getenv("HOME");
if (homedir)
return Path(filename_to_utf8(homedir));
else
throw(std::runtime_error("$HOME not defined."));
#elif defined(_WIN32)
/* TODO: Switch to KNOWNFOLDERID system as explained
* on http://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx
* and http://msdn.microsoft.com/en-us/library/windows/desktop/bb762181%28v=vs.85%29.aspx
*. Howevever, MinGW does currently (September 2014) not have
* the new KNOWNFOLDERID declarations.
*/