Repository navigation
Expand file tree
/
Copy pathPathLib.c
More file actions
2408 lines (2005 loc) · 75.4 KB
/
Copy pathPathLib.c
File metadata and controls
2408 lines (2005 loc) · 75.4 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
// encoding: UTF-8
/******************************************************************************
* *
* *
* Notepad3 *
* *
* PathLib.c *
* Implementation for dynamic wide char Long Path handling *
* Based on DynStrg module *
* *
* (c) Rizonesoft 2008-2026 *
* https://rizonesoft.com *
* *
* *
*******************************************************************************/
// ============================================================================
//
// https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
//
// https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation
//
// In the Windows API (with some exceptions discussed in the following paragraphs),
// the maximum length for a path is MAX_PATH, which is defined as 260 characters.
// A local path is structured in the following order: drive letter, colon, backslash,
// name components separated by backslashes, and a terminating null character.
// For example, the maximum path on drive D is "D:\some 256-character path string<NUL>"
// where "<NUL>" represents the invisible terminating null character for the current
// system codepage.
// (The characters < > are used here for visual clarity and cannot be part of a valid path string.)
//
// The Windows API has many functions that also have Unicode versions to permit an
// extended-length path for a maximum total path length of 32767 characters.
// This type of path is composed of components separated by backslashes,
// each up to the value returned in the lpMaximumComponentLength parameter of the
// GetVolumeInformation function (this value is commonly 255 characters).
// To specify an extended-length path, use the "\\?\" prefix. For example,
// "\\?\D:\very long path".
//
// The "\\?\" prefix can also be used with paths constructed according to the universal
// naming convention (UNC). To specify such a path using UNC, use the "\\?\UNC\" prefix.
// For example, "\\?\UNC\server\share", where "server" is the name of the computer and
// "share" is the name of the shared folder.
// These prefixes are not used as part of the path itself.
// They indicate that the path should be passed to the system with minimal modification,
// which means that you cannot use forward slashes to represent path separators,
// or a period to represent the current directory, or double dots to represent the
// parent directory. Because you cannot use the "\\?\" prefix with a relative path,
// relative paths are always limited to a total of MAX_PATH characters.
//
// There is no need to perform any Unicode normalization on path and file name strings
// for use by the Windows file I/O API functions because the file system treats path and
// file names as an opaque sequence of WCHARs. Any normalization that your application
// requires should be performed with this in mind, external of any calls to related
// Windows file I/O API functions.
//
// When using an API to create a directory, the specified path cannot be so long that you
// cannot append an 8.3 file name (that is, the directory name cannot exceed MAX_PATH minus 12).
//
// The shell and the file system have different requirements.
// It is possible to create a path with the Windows API that the shell user interface
// is not able to interpret properly.
//
// ============================================================================
// ============================================================================
// TODO: if (OptInRemovedMaxPathLimit()) {}
// https://docs.microsoft.com/de-de/windows/win32/api/fileapi/nf-fileapi-getfileattributesa
//
// These are the directory management functions that no longer have MAX_PATH restrictions
// if you opt - in to long path behavior :
// - CreateDirectoryW
// - CreateDirectoryExW
// - GetCurrentDirectoryW
// - RemoveDirectoryW
// - SetCurrentDirectoryW
//
// These are the file management functions that no longer have MAX_PATH restrictions
// if you opt - in to long path behavior :
// - CopyFileW
// - CopyFile2
// - CopyFileExW
// - CreateFileW
// - CreateFile2
// - CreateHardLinkW
// - CreateSymbolicLinkW
// - DeleteFileW
// - FindFirstFileW
// - FindFirstFileExW
// - FindNextFileW
// - GetFileAttributesW
// - GetFileAttributesExW
// - SetFileAttributesW
// - GetShortPathNameW
// - GetFullPathNameW
// - GetLongPathNameW
// - MoveFileW
// - MoveFileExW
// - MoveFileWithProgressW
// - ReplaceFileW
// - SearchPathW
// - FindFirstFileNameW
// - FindNextFileNameW
// - FindFirstStreamW
// - FindNextStreamW
// - GetCompressedFileSizeW
// - GetFinalPathNameByHandleW
//
// Additional helpers (<stdlib.h> oder <wchar.h>)
//
// wchar_t *_wfullpath(wchar_t *absPath, const wchar_t *relPath, size_t maxLength);
//
// errno_t _wmakepath_s(wchar_t *path, size_t sizeInWords,
// const wchar_t *drive, const wchar_t *dir, const wchar_t *fname, const wchar_t *ext);
//
// errno_t _wsplitpath_s(const wchar_t * path, wchar_t * drive, size_t driveNumberOfElements,
// wchar_t *dir, size_t dirNumberOfElements, wchar_t * fname, size_t nameNumberOfElements,
// wchar_t * ext, size_t extNumberOfElements);
//
// ============================================================================
#include <sdkddkver.h>
#ifndef _WIN32_WINNT
#define _WIN32_WINNT _WIN32_WINNT_WIN10
#endif
#ifndef WINVER
#define WINVER _WIN32_WINNT_WIN10
#endif
#ifndef NTDDI_VERSION
#define NTDDI_VERSION NTDDI_WIN10_RS5
#endif
#define NOMINMAX
#define VC_EXTRALEAN 1
#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>
#include <assert.h>
#include <wchar.h>
#include <processenv.h>
#include <stdbool.h>
#include <strsafe.h>
#include <fileapi.h>
// get rid of this:
#include <shlobj.h>
#include <shobjidl.h>
#include <shellapi.h>
#include <shlwapi.h>
#include "Dialogs.h"
#include "PathLib.h"
/**************************************************/
/* */
/* PRIVATE API */
/* */
/**************************************************/
#define COUNTOF(ar) ARRAYSIZE(ar)
#define CONSTSTRGLEN(s) (COUNTOF(s) - 1)
// -------------------------------------------------
LPCWSTR const PATHUNC_PREFIX1 = L"\\\\?\\UNC\\";
LPCWSTR const PATHUNC_PREFIX2 = L"\\\\.\\UNC\\";
// TODO: ???
//LPCWSTR const VOLUME_PREFIX = L"\\\\?\\Volume{";
LPCWSTR const PATHLONG_PREFIX = L"\\\\?\\";
LPCWSTR const NETSHARE_PREFIX = L"\\\\";
LPCWSTR const PATHPARENT_PREFIX = L"..\\";
LPCWSTR const PATHDSPL_INFIX = L" ... ";
LPCWSTR const PATH_CSIDL_MYDOCUMENTS = L"%CSIDL:MYDOCUMENTS%";
LPCWSTR const PATH_CSIDL_DESKTOP = L"%CSIDL:DESKTOP%";
LPCWSTR const PATH_CSIDL_FAVORITES = L"%CSIDL:FAVORITES%";
// TODO: ...
#define limit_len(len) (((len) < PATHLONG_MAX_CCH) ? (len) : (PATHLONG_MAX_CCH - 1))
#define IS_VALID_HANDLE(HNDL) ((HNDL) && ((HNDL) != INVALID_HANDLE_VALUE))
// ----------------------------------------------------------------------------
//
// HPATHL == HSTRINGW w/o typedef
//
__forceinline HSTRINGW ToHStrgW(HPATHL hpth)
{
if (!hpth)
return NULL;
return (HSTRINGW)hpth;
}
#define PathGet(HPTH) StrgGet((HSTRINGW)HPTH)
// ----------------------------------------------------------------------------
//==== StrSafe extensions =======================================================
__forceinline bool StrIsEmptyW(LPCWSTR s)
{
return (!s || (*s == L'\0'));
}
//inline size_t StringCchLenA(LPCSTR s, size_t n) {
// n = (n ? n : STRSAFE_MAX_CCH); size_t len; return (size_t)(!s ? 0 : (SUCCEEDED(StringCchLengthA(s, n, &len)) ? len : n));
//}
__forceinline size_t StringCchLenA(LPCSTR s, const size_t n)
{
return (s ? strnlen_s(s, (n ? n : STRSAFE_MAX_CCH)) : 0LL);
}
//inline size_t StringCchLenW(LPCWSTR s, size_t n) {
// n = (n ? n : STRSAFE_MAX_CCH); size_t len; return (size_t)(!s ? 0 : (SUCCEEDED(StringCchLengthW(s, n, &len)) ? len : n));
//}
__forceinline size_t StringCchLenW(LPCWSTR s, const size_t n)
{
return (s ? wcsnlen_s(s, (n ? n : STRSAFE_MAX_CCH)) : 0LL);
}
#if defined(UNICODE) || defined(_UNICODE)
#define StringCchLen(s, n) StringCchLenW((s), (n))
#else
#define StringCchLen(s, n) StringCchLenA((s), (n))
#endif
// ----------------------------------------------------------------------------
// typesafe min/max
//#define _min_(x,y) (((x) > (y)) ? (y) : (x))
#define _RETCMPMIN_ { return (x > y) ? y : x; }
__forceinline int min_i(const int x, const int y) _RETCMPMIN_
__forceinline size_t min_s(const size_t x, const size_t y) _RETCMPMIN_
//#define _max_(x,y) (((x) < (y)) ? (y) : (x))
#define _RETCMPMAX_ { return (x < y) ? y : x; }
__forceinline int max_i(const int x, const int y) _RETCMPMAX_
__forceinline size_t max_s(const size_t x, const size_t y) _RETCMPMAX_
// ----------------------------------------------------------------------------
__forceinline wchar_t _wcsgetprev(LPCWSTR str, LPCWSTR c)
{
if (!str)
return L'\0';
return (c && (c > str)) ? *(c - 1) : L'\0';
}
__forceinline wchar_t _wcsgetnext(LPCWSTR c)
{
return (c && *c) ? *(c + 1) : L'\0';
}
static void _PathFixBackslashes(LPWSTR pstrg)
{
LPWSTR c = wcschr(pstrg, L'/');
while (c) {
if ((_wcsgetprev(pstrg, c) == L':') && (_wcsgetnext(c) == L'/')) {
c += 2;
}
else {
*c = L'\\';
}
c = wcschr(c, L'/'); // next
}
}
// ----------------------------------------------------------------------------
static bool HasOptInToRemoveMaxPathLimit()
{
static int s_MaxPathLimitRemoved = -1;
switch (s_MaxPathLimitRemoved) {
case -1: {
// Function pointer to driver function
BOOLEAN(WINAPI * pRtlAreLongPathsEnabled)(void) = NULL;
s_MaxPathLimitRemoved = 0; // at least called once
HMODULE const hNTdllDll = GetModuleHandle(L"ntdll.dll");
if (hNTdllDll) {
// get the function pointer to RtlAreLongPathsEnabled
pRtlAreLongPathsEnabled = (BOOLEAN(WINAPI*)(void))GetProcAddress(hNTdllDll, "RtlAreLongPathsEnabled");
if (pRtlAreLongPathsEnabled != NULL) {
s_MaxPathLimitRemoved = pRtlAreLongPathsEnabled() ? 1 : 0;
}
}
return (s_MaxPathLimitRemoved == 1);
}
case 1:
return true;
default:
break;
}
return false;
}
// ----------------------------------------------------------------------------
// Prefix lifecycle:
// Added by: Path_Canonicalize() and Path_GetLongPathNameEx() during normalization.
// Stripped by: Path_NormalizeEx() when bRealPath=true (after GetFinalPathNameByHandleW).
// Retained when: Path_NormalizeEx() with bRealPath=false, or standalone Canonicalize.
//
// Only activates when RtlAreLongPathsEnabled() is false (no system opt-in) AND
// path length >= MAX_PATH_EXPLICIT (260). On modern Windows 10+ with the long-path
// registry key enabled, this is a no-op.
//
// External code should use PathLib wrapper functions (Path_CreateFile, Path_DeleteFile,
// Path_GetFileAttributes, etc.) rather than calling Win32 APIs directly — the wrappers
// apply the prefix internally via the copy-prefix-call-release pattern.
static void PrependLongPathPrefix(HPATHL hpth_in_out)
{
HSTRINGW hstr_io = ToHStrgW(hpth_in_out); // in place
if (!hstr_io)
return;
if (!HasOptInToRemoveMaxPathLimit()) {
if (StrgGetLength(hstr_io) >= MAX_PATH_EXPLICIT) {
// already has long-path prefix (\\?\...) — skip
if (StrgFind(hstr_io, PATHLONG_PREFIX, 0) == 0) {
return;
}
if (StrgFind(hstr_io, NETSHARE_PREFIX, 0) == 0) {
// skip device paths (\\.\...) — they already have a prefix
LPCWSTR const path = StrgGet(hstr_io);
if (path[2] == L'.') {
return;
}
// UNC path -- replace leading \\ with \\?\UNC\ prefix
StrgDelete(hstr_io, 0, wcslen(NETSHARE_PREFIX));
StrgInsert(hstr_io, 0, PATHUNC_PREFIX1);
}
else {
// drive letter path -- prepend long-path prefix
StrgInsert(hstr_io, 0, PATHLONG_PREFIX);
}
}
}
}
// ----------------------------------------------------------------------------
static LPCWSTR _Path_SkipLPPrefix(const HSTRINGW hpth_str)
{
LPCWSTR start = StrgGet(hpth_str);
if (wcsstr(start, PATHUNC_PREFIX1) == start) {
start += wcslen(PATHUNC_PREFIX1) - 1;
}
else if (wcsstr(start, PATHLONG_PREFIX) == start) {
start += wcslen(PATHLONG_PREFIX);
}
return start;
}
// ----------------------------------------------------------------------------
static void _UnExpandEnvStrgs(HSTRINGW hstr_in_out)
{
if (!hstr_in_out) {
return;
}
LPCWSTR env_var_list[] = {
L"ALLUSERSPROFILE",
L"APPDATA",
L"LOCALAPPDATA",
L"CommonProgramFiles",
L"TEMP",
L"USERPROFILE",
L"COMPUTERNAME",
L"ProgramFiles",
L"SystemRoot",
L"windir",
L"OneDrive"
};
size_t const env_var_cnt = COUNTOF(env_var_list);
wchar_t var_strg[64] = { L'\0' };
HSTRINGW htmp_str = StrgCreate(NULL);
for (size_t i = 0; i < env_var_cnt; ++i) {
DWORD const len = GetEnvironmentVariableW(env_var_list[i], NULL, 0);
if (len > 0) {
LPWSTR buf = StrgWriteAccessBuf(htmp_str, len);
if (buf) {
GetEnvironmentVariableW(env_var_list[i], buf, len);
size_t const hstr_len = StrgGetLength(hstr_in_out);
if (hstr_len >= len) {
size_t const idx = StrgFind(hstr_in_out, buf, 0);
if (idx == 0) {
StringCchPrintfW(var_strg, COUNTOF(var_strg), L"%%%s%%", env_var_list[i]);
StrgReplace(hstr_in_out, buf, var_strg);
}
}
StrgSanitize(htmp_str);
}
}
}
StrgDestroy(htmp_str);
}
// ----------------------------------------------------------------------------
static bool _PathCanonicalize(HSTRINGW hstr_in_out)
{
if (!hstr_in_out) {
return false;
}
LPCWSTR start = _Path_SkipLPPrefix(hstr_in_out);
LPWSTR const path = StrgWriteAccessBuf(hstr_in_out, 0);
size_t const cch = StrgGetAllocLength(hstr_in_out);
// Replace forward slashes with backslashes
_PathFixBackslashes(path);
// Move back to the beginning of the string
size_t i, j, k;
i = j = k = (start - path);
// Skip UNC Path
while ((path[i] == L'\\') && path[i + 1] == L'\\') {
i++;
}
j = k = i;
// Parse the entire string
do {
// Backslash separator found?
if (path[i] == L'\\' || path[i] == L'\0') {
// "." element found?
if ((i - j) == 1 && wcsncmp(path + j, L".", 1) == 0) {
// Check whether the pathname is empty?
if (k == 0) {
if (path[i] == L'\0') {
path[k++] = L'.';
}
else if (path[i] == L'\\' && path[i + 1] == L'\0') {
path[k++] = L'.';
path[k++] = L'\\';
}
}
else if (k > 1) {
// Remove the final slash if necessary
if (path[i] == L'\0')
k--;
}
}
// ".." element found?
else if ((i - j) == 2 && wcsncmp(path + j, L"..", 2) == 0) {
// Check whether the pathname is empty?
if (k == 0) {
path[k++] = L'.';
path[k++] = L'.';
// Append a slash if necessary
if (path[i] == L'\\')
path[k++] = L'\\';
}
else if (k > 1) {
// Search the path for the previous slash
for (j = 1; j < k; j++) {
if (path[k - j - 1] == L'\\')
break;
}
// Backslash separator found?
if (j < k) {
if (wcsncmp(path + k - j, L"..", 2) == 0) {
path[k++] = L'.';
path[k++] = L'.';
}
else {
k = k - j - 1;
}
// Append a slash if necessary
if (k == 0 && path[0] == L'\\')
path[k++] = L'\\';
else if (path[i] == L'\\')
path[k++] = L'\\';
}
// No slash separator found?
else {
if (k == 3 && wcsncmp(path, L"..", 2) == 0) {
path[k++] = L'.';
path[k++] = L'.';
// Append a slash if necessary
if (path[i] == L'\\')
path[k++] = L'\\';
}
else if (path[i] == L'\0') {
k = 0;
path[k++] = L'.';
}
else if (path[i] == L'\\' && path[i + 1] == L'\0') {
k = 0;
path[k++] = L'.';
path[k++] = L'\\';
}
else {
k = 0;
}
}
}
}
else {
// Copy directory name
wmemmove_s(path + k, cch - k, path + j, i - j);
// Advance write pointer
k += (i - j);
// Append a slash if necessary
if (path[i] == L'\\')
path[k++] = L'\\';
}
// Move to the next token
while (path[i] == L'\\')
i++;
j = i;
}
} while (path[i++] != L'\0');
// Properly terminate the string with a NULL character
path[k] = L'\0';
StrgSanitize(hstr_in_out);
return true;
}
// ----------------------------------------------------------------------------
// Determines whether a path string refers to the root of a volume.
//
// Path PathXCchIsRoot()
// ----------------------------------------------------------
// "c:" FALSE ==
// "c:\" TRUE ==
// "c:\path1" FALSE ==
// "c:\path1\" FALSE --
// "\path1" FALSE (MSDN DOC) -> TRUE
// "path1" FALSE ==
// "\\path1\path2" TRUE ==
// "\\path1\path2\" FALSE ==
// "\\path1\path2\path3" FALSE ==
// "\\path1" TRUE ==
// "\\path1\" FALSE ==
// "\\" TRUE ==
// "\\?\UNC\" TRUE ==
// "\\?\UNC\path1" TRUE ==
// "\\?\UNC\path1\" FALSE ==
// "\\?\UNC\path1\path2" TRUE ==
// "\\?\UNC\path1\path2\" FALSE ==
// "\\?\UNC\path1\path2\path3" FALSE ==
// "\\?\c:" FALSE ==
// "\\?\c:\" TRUE ==
// "\\?\c:\path1" FALSE ==
// "\\?\c:\path1\" FALSE --
// "\\?\Volume{guid}\" TRUE
// "\\?\Volume{guid}" FALSE
// "\\?\Volume{guid}\path1" FALSE
// NULL FALSE ==
// "" FALSE ==
// ----------------------------------------------------------
//
static LPCWSTR _Path_IsValidUNC(const HPATHL hpth, bool* isUNC_out)
{
if (!hpth) {
return NULL; // false
}
if (Path_GetLength(hpth) == 0) {
return PathGet(hpth);
}
LPCWSTR start = PathGet(hpth);
LPCWSTR const endz = start + Path_GetLength(hpth); // terminating zero (L'\0')
bool isUncOrNetShare = false;
if ((wcsstr(start, PATHUNC_PREFIX1) == start) ||
(wcsstr(start, PATHUNC_PREFIX2) == start)) {
start += wcslen(PATHUNC_PREFIX1);
isUncOrNetShare = true;
}
/// _Path_SkipLPPrefix()
if (wcsstr(start, PATHLONG_PREFIX) == start) {
start += wcslen(PATHLONG_PREFIX);
}
if (wcsstr(start, NETSHARE_PREFIX) == start) {
start += wcslen(NETSHARE_PREFIX);
isUncOrNetShare = true;
}
// check for valid net-server prefix
// \\<server-name>\<share>\...
if (isUncOrNetShare) {
// skip <server-name>
LPCWSTR nextbs = wcschr(start, L'\\');
isUncOrNetShare = (nextbs && (nextbs > start));
start = isUncOrNetShare ? (nextbs + 1) : endz;
// skip <share-name>
nextbs = wcschr(start, L'\\');
isUncOrNetShare = (nextbs && (nextbs > start));
start = isUncOrNetShare ? (nextbs + 1) : endz;
}
if (isUNC_out) {
*isUNC_out = isUncOrNetShare;
}
return start;
}
// ----------------------------------------------------------------------------
//
// needs converted forward slashes
//
static LPCWSTR _Path_SkipRoot(const HPATHL hpth)
{
if (!hpth) {
assert(hpth);
return NULL; // false
}
if (Path_GetLength(hpth) == 0) {
return PathGet(hpth);
}
bool isUncOrNetShare = false;
LPCWSTR start = _Path_IsValidUNC(hpth, &isUncOrNetShare);
LPCWSTR const endz = PathGet(hpth) + Path_GetLength(hpth); // terminating zero (L'\0')
if (*start && (*(start + 1) == L':')) { // has drive letter
start += 2;
if ((*start == L'\\') && !isUncOrNetShare) {
return (start + 1);
}
return endz; // invalid root
}
// anything else ?
return start;
}
// ----------------------------------------------------------------------------
//=============================================================================
//
// _Path_IsRelative()
// TODO: §§§ make LongPath version instead of slicing MAX_PATH
//
static bool _Path_IsRelative(const HPATHL hpth)
{
HSTRINGW hstr = ToHStrgW(hpth);
if (!hstr)
return true; // empty is relative
LPCWSTR const skip = _Path_SkipLPPrefix(hstr);
bool res = false;
if (StrgGetLength(hstr) >= MAX_PATH_EXPLICIT) {
// hack for MAX_PATH_EXPLICIT limit
wchar_t const wch = StrgGetAt(hstr, MAX_PATH_EXPLICIT);
StrgSetAt(hstr, MAX_PATH_EXPLICIT, L'\0');
res = PathIsRelativeW(skip);
StrgSetAt(hstr, MAX_PATH_EXPLICIT, wch);
}
else {
res = PathIsRelativeW(skip);
}
return res;
}
// ----------------------------------------------------------------------------
/**************************************************/
/* */
/* PUBLIC API */
/* */
/**************************************************/
HPATHL PTHAPI Path_Allocate(LPCWSTR path)
{
return (HPATHL)StrgCreate(path);
}
// ----------------------------------------------------------------------------
void PTHAPI Path_Release(HPATHL hpth)
{
StrgDestroy(ToHStrgW(hpth));
}
// ----------------------------------------------------------------------------
void PTHAPI Path_Empty(HPATHL hpth_in_out, bool truncate)
{
StrgEmpty(ToHStrgW(hpth_in_out), truncate);
}
// ----------------------------------------------------------------------------
int PTHAPI Path_Reset(HPATHL hpth_in_out, LPCWSTR path)
{
return (path ? StrgReset(ToHStrgW(hpth_in_out), path) : StrgReset(ToHStrgW(hpth_in_out), L""));
}
// ----------------------------------------------------------------------------
size_t PTHAPI Path_GetLength(HPATHL hpth)
{
return StrgGetLength(ToHStrgW(hpth));
}
// ----------------------------------------------------------------------------
HPATHL PTHAPI Path_Copy(const HPATHL hpth)
{
return Path_Allocate(PathGet(hpth));
}
// ----------------------------------------------------------------------------
bool PTHAPI Path_Append(HPATHL hpth_in_out, LPCWSTR more)
{
HSTRINGW hstr_io = ToHStrgW(hpth_in_out);
if (!hstr_io)
return false;
size_t const hstr_len = StrgGetLength(hstr_io);
size_t const hmore_len = StringCchLen(more, 0);
if (!hmore_len) {
return true;
}
LPWSTR const wbuf = StrgWriteAccessBuf(hstr_io, hstr_len + hmore_len + wcslen(PATHLONG_PREFIX) + 2);
size_t const cch = StrgGetAllocLength(hstr_io);
// append directory separator
if (hstr_len > 0) {
if (((wbuf[hstr_len - 1] != L'/') && (wbuf[hstr_len - 1] != L'\\')) &&
((more[0] != L'/') && (more[0] != L'\\'))) {
wbuf[hstr_len] = L'\\';
wbuf[hstr_len + 1] = L'\0';
}
}
//else {
// wbuf[0] = L'\\';
// wbuf[1] = L'\0';
//}
StringCchCatW(wbuf, cch, more);
StrgSanitize(hstr_io);
return Path_Canonicalize(hpth_in_out);
}
// ----------------------------------------------------------------------------
void PTHAPI Path_Swap(HPATHL hpth1, HPATHL hpth2)
{
HSTRINGW hstr1 = ToHStrgW(hpth1);
HSTRINGW hstr2 = ToHStrgW(hpth2);
assert(hstr1 && hstr2);
if (!hstr1 || !hstr2)
return;
StrgSwap(hstr1, hstr2);
}
// ----------------------------------------------------------------------------
void PTHAPI Path_FreeExtra(HPATHL hpth_in_out, size_t keep_length)
{
HSTRINGW hstr_io = ToHStrgW(hpth_in_out);
if (!hstr_io)
return;
StrgFreeExtra(hstr_io, keep_length);
}
// ----------------------------------------------------------------------------
//=============================================================================
//
// PathFixBackslashes() - in place conversion
//
bool PTHAPI Path_FixBackslashes(HPATHL hpth_in_out)
{
HSTRINGW hstr_io = ToHStrgW(hpth_in_out); // inplace hpth_in_out
if (!hstr_io)
return false;
LPWSTR const lpsz = StrgWriteAccessBuf(hstr_io, 0);
WCHAR* c = lpsz;
bool bFixed = false;
while ((c = StrChr(c, L'/')) != NULL) {
if (c != lpsz && c[-1] == L':' && c[1] == L'/') {
c += 2;
}
else {
*c++ = L'\\';
bFixed = true;
}
}
//~StrgSanitize(hstr_io); : '/' replaced by '\' only
return bFixed;
}
//=============================================================================
// With untrusted input, this function by itself, cannot be used to convert
// paths into a form that can be compared with other paths for sub-path or identity.
// Callers that need that ability should convert forward to back slashes before
// using this function.
bool PTHAPI Path_Canonicalize(HPATHL hpth_in_out)
{
if (!hpth_in_out) {
return false;
}
HSTRINGW hstr_io = ToHStrgW(hpth_in_out);
Path_FixBackslashes(hpth_in_out);
// remove quotes
StrgTrim(hstr_io, L'"');
bool const res = _PathCanonicalize(hstr_io);
StrgSanitize(hstr_io);
// canonicalize prefix
PrependLongPathPrefix(hpth_in_out);
return res;
}
// ----------------------------------------------------------------------------
bool PTHAPI Path_IsEmpty(const HPATHL hpth)
{
HSTRINGW hstr = ToHStrgW(hpth);
if (!hstr)
return true;
return StrgIsEmpty(hstr);
}
// ----------------------------------------------------------------------------
// TODO: §§§ make LongPath version instead of slicing MAX_PATH
bool PTHAPI Path_IsRoot(const HPATHL hpth)
{
HSTRINGW hstr = ToHStrgW(hpth);
if (!hstr)
return false;
//PrependLongPathPrefix(hpth);
///WCHAR wchPathBegin[MAX_PATH_EXPLICIT] = { L'\0' };
///StringCchCopy(wchPathBegin, COUNTOF(wchPathBegin), StrgGet(hstr));
///return PathIsRootW(wchPathBegin);
bool res = false;
if (StrgGetLength(hstr) >= MAX_PATH_EXPLICIT) {
// hack for MAX_PATH_EXPLICIT limit
wchar_t const wch = StrgGetAt(hstr, MAX_PATH_EXPLICIT);
StrgSetAt(hstr, MAX_PATH_EXPLICIT, L'\0');
res = PathIsRootW(StrgGet(hstr));
StrgSetAt(hstr, MAX_PATH_EXPLICIT, wch);
}
else {
res = PathIsRootW(StrgGet(hstr));
}
return res;
}
// ----------------------------------------------------------------------------
bool PTHAPI Path_IsValidUNC(const HPATHL hpth)
{
HSTRINGW hstr = ToHStrgW(hpth);
if (!hstr)
return false;
//PrependLongPathPrefix(hpth);
bool isUncOrNetShare = false;
_Path_IsValidUNC(hpth, &isUncOrNetShare);
return isUncOrNetShare;
}
// ----------------------------------------------------------------------------
static int _StrgComparePathNormalized(const HPATHL hpth1, const HPATHL hpth2)
{
if (Path_IsEmpty(hpth1)) { return -1; }
if (Path_IsEmpty(hpth2)) { return +1; }
// use locale-independent ordinal comparison (matches NTFS case mapping)
int const result = CompareStringOrdinal(
Path_Get(hpth1), (int)Path_GetLength(hpth1),
Path_Get(hpth2), (int)Path_GetLength(hpth2),
TRUE);
return result - CSTR_EQUAL;
}
// ----------------------------------------------------------------------------
int PTHAPI Path_StrgComparePath(const HPATHL hpth1, const HPATHL hpth2, const HPATHL hpth_wrkdir, const bool bNormalize)
{
if (!bNormalize) {
return _StrgComparePathNormalized(hpth1, hpth2);
}
if (Path_IsEmpty(hpth1)) {
return -1;
}
if (Path_IsEmpty(hpth2)) {
return +1;
}
HPATHL hpth1_tmp = Path_Copy(hpth1);
HPATHL hpth2_tmp = Path_Copy(hpth2);
Path_NormalizeEx(hpth1_tmp, hpth_wrkdir, true, false);
Path_NormalizeEx(hpth2_tmp, hpth_wrkdir, true, false);
int const cmp = _StrgComparePathNormalized(hpth1_tmp, hpth2_tmp);
Path_Release(hpth1_tmp);
Path_Release(hpth2_tmp);
return cmp;
}
// ----------------------------------------------------------------------------
bool PTHAPI Path_RemoveFileSpec(HPATHL hpth_in_out)
{
HSTRINGW hstr_io = ToHStrgW(hpth_in_out);
if (!hstr_io)
return false;
LPWSTR wbuf = StrgWriteAccessBuf(hstr_io, 0); // no need to ReAlloc
//size_t cch = StrgGetAllocLength(hstr_io);
LPCWSTR pfile = Path_FindFileName(hpth_in_out);
if (pfile > wbuf) {
StrgDelete(hstr_io, (size_t)(pfile - wbuf), StrgGetLength(hstr_io));
}
StrgSanitize(hstr_io);
StrgTrimRight(hstr_io, L'\\');
StrgTrimRight(hstr_io, L'/');
return true;
}
// ----------------------------------------------------------------------------
bool PTHAPI Path_StripPath(HPATHL hpth) // get filename only
{
HSTRINGW hstr = ToHStrgW(hpth);
if (!hstr)
return false;
LPCWSTR wbuf = StrgWriteAccessBuf(hstr, 0);
LPCWSTR pfile = Path_FindFileName(hpth);