-
Notifications
You must be signed in to change notification settings - Fork 256
/
compat.cc
3255 lines (2711 loc) · 91.7 KB
/
compat.cc
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
/*
BAREOS® - Backup Archiving REcovery Open Sourced
Copyright (C) 2004-2010 Free Software Foundation Europe e.V.
Copyright (C) 2011-2012 Planets Communications B.V.
Copyright (C) 2013-2022 Bareos GmbH & Co. KG
This program is Free Software; you can redistribute it and/or
modify it under the terms of version three of the GNU Affero General Public
License as published by the Free Software Foundation and included
in the file LICENSE.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
/*
* Copyright transferred from Raider Solutions, Inc to
* Kern Sibbald and John Walker by express permission.
*
* Author : Christopher S. Hull
* Created On : Sat Jan 31 15:55:00 2004
*/
/**
* @file
* compatibilty layer to make bareos-fd run natively under windows
*/
#include "include/bareos.h"
#include "include/jcr.h"
#include "dlfcn.h"
#include "findlib/find.h"
#include "lib/btimers.h"
#include "lib/bsignal.h"
#include "lib/daemon.h"
#include "lib/berrno.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunknown-pragmas"
#include "vss.h"
#pragma GCC diagnostic pop
/**
* Sanity check to make sure FILE_ATTRIBUTE_VALID_FLAGS is always smaller
* than our define of FILE_ATTRIBUTE_VOLUME_MOUNT_POINT.
*/
#if FILE_ATTRIBUTE_VOLUME_MOUNT_POINT < FILE_ATTRIBUTE_VALID_FLAGS
# error "FILE_ATTRIBUTE_VALID_FLAGS smaller than FILE_ATTRIBUTE_VALID_FLAGS"
#endif
/**
* Note, if you want to see what Windows variables and structures
* are defined, include/bareos.h includes <windows.h>, which is found in:
*
* cross-tools/mingw32/mingw32/include
* or
* cross-tools/mingw-w64/x86_64-pc-mingw32/include
*
* depending on whether we are building the 32 bit version or
* the 64 bit version.
*/
static const int debuglevel = 500;
#define MAX_PATHLENGTH 1024
static pthread_mutex_t com_security_mutex = PTHREAD_MUTEX_INITIALIZER;
static bool com_security_initialized = false;
/**
* The CoInitializeSecurity function initializes the security layer and sets the
* specified values as the security default. If a process does not call
* CoInitializeSecurity, COM calls it automatically the first time an interface
* is marshaled or unmarshaled, registering the system default security. No
* default security packages are registered until then.
*
* This function may be called exactly once per process.
*/
bool InitializeComSecurity()
{
HRESULT hr;
bool retval = false;
lock_mutex(com_security_mutex);
if (com_security_initialized) {
retval = true;
goto bail_out;
}
hr = CoInitializeSecurity(
NULL, /* Allow *all* VSS writers to communicate back! */
-1, /* Default COM authentication service */
NULL, /* Default COM authorization service */
NULL, /* reserved parameter */
RPC_C_AUTHN_LEVEL_PKT_PRIVACY, /* Strongest COM authentication level */
RPC_C_IMP_LEVEL_IDENTIFY, /* Minimal impersonation abilities */
NULL, /* Default COM authentication settings */
EOAC_NONE, /* No special options */
NULL); /* Reserved parameter */
if (FAILED(hr)) {
Dmsg1(0, "InitializeComSecurity: CoInitializeSecurity returned 0x%08X\n",
hr);
errno = b_errno_win32;
goto bail_out;
}
com_security_initialized = true;
retval = true;
bail_out:
unlock_mutex(com_security_mutex);
return retval;
}
/**
* UTF-8 to UCS2 path conversion is expensive,
* so we cache the conversion. During backup the
* conversion is called 3 times (lstat, attribs, open),
* by using the cache this is reduced to 1 time
*/
struct thread_conversion_cache {
POOLMEM* pWin32ConvUTF8Cache;
POOLMEM* pWin32ConvUCS2Cache;
DWORD dwWin32ConvUTF8strlen;
};
struct thread_vss_path_convert {
t_pVSSPathConvert pPathConvert;
t_pVSSPathConvertW pPathConvertW;
};
/**
* We use thread specific data using pthread_set_specific and
* pthread_get_specific to have unique and separate data for each thread instead
* of global variables.
*/
static pthread_mutex_t tsd_mutex = PTHREAD_MUTEX_INITIALIZER;
static bool pc_tsd_initialized = false;
static bool cc_tsd_initialized = false;
static pthread_key_t path_conversion_key;
static pthread_key_t conversion_cache_key;
static void VSSPathConvertCleanup(void* arg)
{
thread_vss_path_convert* tvpc = (thread_vss_path_convert*)arg;
Dmsg1(debuglevel,
"VSSPathConvertCleanup: Cleanup thread specific conversion pointers at "
"address %p\n",
tvpc);
free(tvpc);
}
bool SetVSSPathConvert(t_pVSSPathConvert pPathConvert,
t_pVSSPathConvertW pPathConvertW)
{
int status;
thread_vss_path_convert* tvpc = NULL;
lock_mutex(tsd_mutex);
if (!pc_tsd_initialized) {
status = pthread_key_create(&path_conversion_key, VSSPathConvertCleanup);
if (status != 0) {
unlock_mutex(tsd_mutex);
goto bail_out;
}
pc_tsd_initialized = true;
}
unlock_mutex(tsd_mutex);
tvpc = (thread_vss_path_convert*)pthread_getspecific(path_conversion_key);
if (!tvpc) {
tvpc = (thread_vss_path_convert*)malloc(sizeof(thread_vss_path_convert));
status = pthread_setspecific(path_conversion_key, (void*)tvpc);
if (status != 0) { goto bail_out; }
}
Dmsg1(debuglevel,
"SetVSSPathConvert: Setup thread specific conversion pointers at "
"address %p\n",
tvpc);
tvpc->pPathConvert = pPathConvert;
tvpc->pPathConvertW = pPathConvertW;
return true;
bail_out:
if (tvpc) { free(tvpc); }
return false;
}
static thread_vss_path_convert* Win32GetPathConvert()
{
thread_vss_path_convert* tvpc = NULL;
lock_mutex(tsd_mutex);
if (pc_tsd_initialized) {
tvpc = (thread_vss_path_convert*)pthread_getspecific(path_conversion_key);
}
unlock_mutex(tsd_mutex);
return tvpc;
}
// UTF-8 to UCS2 path conversion caching.
static void Win32ConvCleanupCache(void* arg)
{
thread_conversion_cache* tcc = (thread_conversion_cache*)arg;
Dmsg1(
debuglevel,
"Win32ConvCleanupCache: Cleanup of thread specific cache at address %p\n",
tcc);
FreePoolMemory(tcc->pWin32ConvUCS2Cache);
FreePoolMemory(tcc->pWin32ConvUTF8Cache);
free(tcc);
}
static thread_conversion_cache* Win32ConvInitCache()
{
int status;
thread_conversion_cache* tcc = NULL;
lock_mutex(tsd_mutex);
if (!cc_tsd_initialized) {
status = pthread_key_create(&conversion_cache_key, Win32ConvCleanupCache);
if (status != 0) {
unlock_mutex(tsd_mutex);
goto bail_out;
}
cc_tsd_initialized = true;
}
unlock_mutex(tsd_mutex);
// Create a new cache.
tcc = (thread_conversion_cache*)malloc(sizeof(thread_conversion_cache));
tcc->pWin32ConvUTF8Cache = GetPoolMemory(PM_FNAME);
tcc->pWin32ConvUCS2Cache = GetPoolMemory(PM_FNAME);
tcc->dwWin32ConvUTF8strlen = 0;
status = pthread_setspecific(conversion_cache_key, (void*)tcc);
if (status != 0) { goto bail_out; }
Dmsg1(debuglevel,
"Win32ConvInitCache: Setup of thread specific cache at address %p\n",
tcc);
return tcc;
bail_out:
if (tcc) {
FreePoolMemory(tcc->pWin32ConvUCS2Cache);
FreePoolMemory(tcc->pWin32ConvUTF8Cache);
free(tcc);
}
return NULL;
}
static thread_conversion_cache* Win32GetCache()
{
thread_conversion_cache* tcc = NULL;
lock_mutex(tsd_mutex);
if (cc_tsd_initialized) {
tcc = (thread_conversion_cache*)pthread_getspecific(conversion_cache_key);
}
unlock_mutex(tsd_mutex);
return tcc;
}
void Win32TSDCleanup()
{
lock_mutex(tsd_mutex);
if (pc_tsd_initialized) {
pthread_key_delete(path_conversion_key);
pc_tsd_initialized = false;
}
if (cc_tsd_initialized) {
pthread_key_delete(conversion_cache_key);
cc_tsd_initialized = false;
}
unlock_mutex(tsd_mutex);
}
// Special flag used to enable or disable Bacula compatible win32 encoding.
static bool win32_bacula_compatible = true;
void Win32ClearCompatible() { win32_bacula_compatible = false; }
void Win32SetCompatible() { win32_bacula_compatible = true; }
bool Win32IsCompatible() { return win32_bacula_compatible; }
// Forward referenced functions
const char* errorString(void);
// To allow the usage of the original version in this file here
#undef fputs
#define USE_WIN32_32KPATHCONVERSION 1
extern DWORD g_platform_id;
extern DWORD g_MinorVersion;
// From Microsoft SDK (KES) is the diff between Jan 1 1601 and Jan 1 1970
#define WIN32_FILETIME_ADJUST 0x19DB1DED53E8000ULL
#define WIN32_FILETIME_SCALE 10000000 // 100ns/second
/**
* Convert from UTF-8 to VSS Windows path/file
* Used by compatibility layer for Unix system calls
*/
static inline void conv_unix_to_vss_win32_path(const char* name,
char* win32_name,
DWORD dwSize)
{
const char* fname = name;
char* tname = win32_name;
thread_vss_path_convert* tvpc;
Dmsg0(debuglevel, "Enter convert_unix_to_win32_path\n");
tvpc = Win32GetPathConvert();
if (IsPathSeparator(name[0]) && IsPathSeparator(name[1]) && name[2] == '.'
&& IsPathSeparator(name[3])) {
*win32_name++ = '\\';
*win32_name++ = '\\';
*win32_name++ = '.';
*win32_name++ = '\\';
name += 4;
} else if (g_platform_id != VER_PLATFORM_WIN32_WINDOWS && !tvpc) {
// Allow path to be 32767 bytes
*win32_name++ = '\\';
*win32_name++ = '\\';
*win32_name++ = '?';
*win32_name++ = '\\';
}
while (*name) {
// Check for Unix separator and convert to Win32
if (name[0] == '/' && name[1] == '/') { /* double slash? */
name++; /* yes, skip first one */
}
if (*name == '/') {
*win32_name++ = '\\'; /* convert char */
// If Win32 separator that is "quoted", remove quote
} else if (*name == '\\' && name[1] == '\\') {
*win32_name++ = '\\';
name++; /* skip first \ */
} else {
*win32_name++ = *name; /* copy character */
}
name++;
}
/**
* Strip any trailing slash, if we stored something
* but leave "c:\" with backslash (root directory case)
*/
if (*fname != 0 && win32_name[-1] == '\\' && strlen(fname) != 3) {
win32_name[-1] = 0;
} else {
*win32_name = 0;
}
/**
* Here we convert to VSS specific file name which
* can get longer because VSS will make something like
* \\\\?\\GLOBALROOT\\Device\\HarddiskVolumeShadowCopy1\\bareos\\uninstall.exe
* from c:\bareos\uninstall.exe
*/
Dmsg1(debuglevel, "path=%s\n", tname);
if (tvpc) {
POOLMEM* pszBuf = GetPoolMemory(PM_FNAME);
pszBuf = CheckPoolMemorySize(pszBuf, dwSize);
bstrncpy(pszBuf, tname, strlen(tname) + 1);
tvpc->pPathConvert(pszBuf, tname, dwSize);
FreePoolMemory(pszBuf);
}
Dmsg1(debuglevel, "Leave cvt_u_to_win32_path path=%s\n", tname);
}
// Conversion of a Unix filename to a Win32 filename
void unix_name_to_win32(POOLMEM*& win32_name, const char* name)
{
DWORD dwSize;
/*
* One extra byte should suffice, but we double it
* add MAX_PATH bytes for VSS shadow copy name.
*/
dwSize = 2 * strlen(name) + MAX_PATH;
win32_name = CheckPoolMemorySize(win32_name, dwSize);
conv_unix_to_vss_win32_path(name, win32_name, dwSize);
}
/**
* This function expects an UCS-encoded standard wchar_t in pszUCSPath and
* will complete the input path to an absolue path of the form \\?\c:\path\file
*
* With this trick, it is possible to have 32K characters long paths.
*
* Optionally one can use pBIsRawPath to determine id pszUCSPath contains a path
* to a raw windows partition.
*
* Created 02/27/2006 Thorsten Engel
*/
static inline POOLMEM* make_wchar_win32_path(POOLMEM* pszUCSPath,
BOOL* pBIsRawPath /*= NULL*/)
{
Dmsg0(debuglevel, "Enter make_wchar_win32_path\n");
if (pBIsRawPath) { *pBIsRawPath = FALSE; /* Initialize, set later */ }
if (!p_GetCurrentDirectoryW) {
Dmsg0(debuglevel, "Leave make_wchar_win32_path no change \n");
return pszUCSPath;
}
wchar_t* name = (wchar_t*)pszUCSPath;
// If it has already the desired form, exit without changes
if (wcslen(name) > 3 && wcsncmp(name, L"\\\\?\\", 4) == 0) {
Dmsg0(debuglevel, "Leave make_wchar_win32_path no change \n");
return pszUCSPath;
}
wchar_t* pwszBuf = (wchar_t*)GetPoolMemory(PM_FNAME);
wchar_t* pwszCurDirBuf = (wchar_t*)GetPoolMemory(PM_FNAME);
DWORD dwCurDirPathSize = 0;
// Get buffer with enough size (name+max 6. wchars+1 null terminator
DWORD dwBufCharsNeeded = (wcslen(name) + 7);
pwszBuf = (wchar_t*)CheckPoolMemorySize((POOLMEM*)pwszBuf,
dwBufCharsNeeded * sizeof(wchar_t));
/*
* Add \\?\ to support 32K long filepaths
* it is important to make absolute paths, so we add drive and
* current path if necessary
*/
BOOL bAddDrive = TRUE;
BOOL bAddCurrentPath = TRUE;
BOOL bAddPrefix = TRUE;
// Does path begin with drive? if yes, it is absolute
if (iswalpha(name[0]) && name[1] == ':' && IsPathSeparator(name[2])) {
bAddDrive = FALSE;
bAddCurrentPath = FALSE;
}
// Is path absolute?
if (IsPathSeparator(name[0])) bAddCurrentPath = FALSE;
// Is path relative to itself?, if yes, skip ./
if (name[0] == '.' && IsPathSeparator(name[1])) { name += 2; }
// Is path of form '//./'?
if (IsPathSeparator(name[0]) && IsPathSeparator(name[1]) && name[2] == '.'
&& IsPathSeparator(name[3])) {
bAddDrive = FALSE;
bAddCurrentPath = FALSE;
bAddPrefix = FALSE;
if (pBIsRawPath) { *pBIsRawPath = TRUE; }
}
int nParseOffset = 0;
// Add 4 bytes header
if (bAddPrefix) {
nParseOffset = 4;
wcscpy(pwszBuf, L"\\\\?\\");
}
// Get current path if needed
if (bAddDrive || bAddCurrentPath) {
dwCurDirPathSize = p_GetCurrentDirectoryW(0, NULL);
if (dwCurDirPathSize > 0) {
/*
* Get directory into own buffer as it may either return c:\... or
* \\?\C:\....
*/
pwszCurDirBuf = (wchar_t*)CheckPoolMemorySize(
(POOLMEM*)pwszCurDirBuf, (dwCurDirPathSize + 1) * sizeof(wchar_t));
p_GetCurrentDirectoryW(dwCurDirPathSize, pwszCurDirBuf);
} else {
// We have no info for doing so
bAddDrive = FALSE;
bAddCurrentPath = FALSE;
}
}
// Add drive if needed
if (bAddDrive && !bAddCurrentPath) {
wchar_t szDrive[3];
if (IsPathSeparator(pwszCurDirBuf[0]) && IsPathSeparator(pwszCurDirBuf[1])
&& pwszCurDirBuf[2] == '?' && IsPathSeparator(pwszCurDirBuf[3])) {
// Copy drive character
szDrive[0] = pwszCurDirBuf[4];
} else {
// Copy drive character
szDrive[0] = pwszCurDirBuf[0];
}
szDrive[1] = ':';
szDrive[2] = 0;
wcscat(pwszBuf, szDrive);
nParseOffset += 2;
}
// Add path if needed
if (bAddCurrentPath) {
// The 1 additional character is for the eventually added backslash
dwBufCharsNeeded += dwCurDirPathSize + 1;
pwszBuf = (wchar_t*)CheckPoolMemorySize((POOLMEM*)pwszBuf,
dwBufCharsNeeded * sizeof(wchar_t));
/*
* Get directory into own buffer as it may either return c:\... or
* \\?\C:\....
*/
if (IsPathSeparator(pwszCurDirBuf[0]) && IsPathSeparator(pwszCurDirBuf[1])
&& pwszCurDirBuf[2] == '?' && IsPathSeparator(pwszCurDirBuf[3])) {
// Copy complete string
wcscpy(pwszBuf, pwszCurDirBuf);
} else {
// Append path
wcscat(pwszBuf, pwszCurDirBuf);
}
nParseOffset = wcslen((LPCWSTR)pwszBuf);
// Check if path ends with backslash, if not, add one
if (!IsPathSeparator(pwszBuf[nParseOffset - 1])) {
wcscat(pwszBuf, L"\\");
nParseOffset++;
}
}
wchar_t* win32_name = &pwszBuf[nParseOffset];
wchar_t* name_start = name;
wchar_t previous_char = 0;
wchar_t next_char = 0;
while (*name) {
/*
* Check for Unix separator and convert to Win32, eliminating duplicate
* separators.
*/
if (IsPathSeparator(*name)) {
// Don't add a trailing slash.
next_char = *(name + 1);
if (previous_char != ':' && next_char == '\0') {
name++;
continue;
}
previous_char = '\\';
*win32_name++ = '\\'; /* convert char */
/*
* Eliminate consecutive slashes, but not at the start so that \\.\ still
* works.
*/
if (name_start != name && IsPathSeparator(name[1])) { name++; }
} else {
previous_char = *name;
*win32_name++ = *name; /* copy character */
}
name++;
}
// NULL Terminate string
*win32_name = 0;
/*
* Here we convert to VSS specific file name which can get longer because VSS
* will make something like
* \\\\?\\GLOBALROOT\\Device\\HarddiskVolumeShadowCopy1\\bareos\\uninstall.exe
* from c:\bareos\uninstall.exe
*/
thread_vss_path_convert* tvpc = Win32GetPathConvert();
if (tvpc) {
// Is output buffer large enough?
pwszBuf = (wchar_t*)CheckPoolMemorySize(
(POOLMEM*)pwszBuf, (dwBufCharsNeeded + MAX_PATH) * sizeof(wchar_t));
// Create temp. buffer
wchar_t* pszBuf = (wchar_t*)GetPoolMemory(PM_FNAME);
pszBuf = (wchar_t*)CheckPoolMemorySize(
(POOLMEM*)pszBuf, (dwBufCharsNeeded + MAX_PATH) * sizeof(wchar_t));
if (bAddPrefix) {
nParseOffset = 4;
} else {
nParseOffset = 0;
}
wcsncpy(pszBuf, &pwszBuf[nParseOffset], wcslen(pwszBuf) + 1 - nParseOffset);
tvpc->pPathConvertW(pszBuf, pwszBuf, dwBufCharsNeeded + MAX_PATH);
FreePoolMemory((POOLMEM*)pszBuf);
}
FreePoolMemory(pszUCSPath);
FreePoolMemory((POOLMEM*)pwszCurDirBuf);
Dmsg1(debuglevel, "Leave make_wchar_win32_path=%s\n", pwszBuf);
return (POOLMEM*)pwszBuf;
}
// Convert from WCHAR (UCS) to UTF-8
int wchar_2_UTF8(POOLMEM*& pszUTF, const WCHAR* pszUCS)
{
/**
* The return value is the number of bytes written to the buffer.
* The number includes the byte for the null terminator.
*/
if (p_WideCharToMultiByte) {
int nRet
= p_WideCharToMultiByte(CP_UTF8, 0, pszUCS, -1, NULL, 0, NULL, NULL);
pszUTF = CheckPoolMemorySize(pszUTF, nRet);
return p_WideCharToMultiByte(CP_UTF8, 0, pszUCS, -1, pszUTF, nRet, NULL,
NULL);
} else {
return 0;
}
}
// Convert from WCHAR (UCS) to UTF-8
int wchar_2_UTF8(char* pszUTF, const WCHAR* pszUCS, int cchChar)
{
/**
* The return value is the number of bytes written to the buffer.
* The number includes the byte for the null terminator.
*/
if (p_WideCharToMultiByte) {
int nRet = p_WideCharToMultiByte(CP_UTF8, 0, pszUCS, -1, pszUTF, cchChar,
NULL, NULL);
ASSERT(nRet > 0);
return nRet;
} else {
return 0;
}
}
int UTF8_2_wchar(POOLMEM*& ppszUCS, const char* pszUTF)
{
/*
* The return value is the number of wide characters written to the buffer.
* convert null terminated string from utf-8 to ucs2, enlarge buffer if
* necessary
*/
if (p_MultiByteToWideChar) {
// strlen of UTF8 +1 is enough
DWORD cchSize = (strlen(pszUTF) + 1);
ppszUCS = CheckPoolMemorySize(ppszUCS, cchSize * sizeof(wchar_t));
int nRet = p_MultiByteToWideChar(CP_UTF8, 0, pszUTF, -1, (LPWSTR)ppszUCS,
cchSize);
ASSERT(nRet > 0);
return nRet;
} else {
return 0;
}
}
// Convert a C character string into an BSTR.
BSTR str_2_BSTR(const char* pSrc)
{
DWORD cwch;
BSTR wsOut(NULL);
if (!pSrc) { return NULL; }
if (p_MultiByteToWideChar) {
if ((cwch = p_MultiByteToWideChar(CP_ACP, 0, pSrc, -1, NULL, 0))) {
cwch--;
wsOut = SysAllocStringLen(NULL, cwch);
if (wsOut) {
if (!p_MultiByteToWideChar(CP_ACP, 0, pSrc, -1, wsOut, cwch)) {
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { return wsOut; }
SysFreeString(wsOut);
wsOut = NULL;
}
}
}
}
return wsOut;
}
// Convert a BSTR into an C character string.
char* BSTR_2_str(const BSTR pSrc)
{
DWORD cb, cwch;
char* szOut = NULL;
if (!pSrc) { return NULL; }
if (p_WideCharToMultiByte) {
cwch = SysStringLen(pSrc);
if ((cb
= p_WideCharToMultiByte(CP_ACP, 0, pSrc, cwch + 1, NULL, 0, 0, 0))) {
szOut = (char*)malloc(cb);
szOut[cb - 1] = '\0';
if (!p_WideCharToMultiByte(CP_ACP, 0, pSrc, cwch + 1, szOut, cb, 0, 0)) {
free(szOut);
szOut = NULL;
}
}
}
return szOut;
}
int make_win32_path_UTF8_2_wchar(POOLMEM*& pszUCS,
const char* pszUTF,
BOOL* pBIsRawPath /*= NULL*/)
{
int nRet;
thread_conversion_cache* tcc;
/*
* If we find the utf8 string in cache, we use the cached ucs2 version.
* we compare the stringlength first (quick check) and then compare the
* content.
*/
tcc = Win32GetCache();
if (!tcc) {
tcc = Win32ConvInitCache();
} else if (tcc->dwWin32ConvUTF8strlen == strlen(pszUTF)) {
if (bstrcmp(pszUTF, tcc->pWin32ConvUTF8Cache)) {
int nBufSize;
// Return cached value
nBufSize = SizeofPoolMemory(tcc->pWin32ConvUCS2Cache);
pszUCS = CheckPoolMemorySize(pszUCS, nBufSize);
wcscpy((LPWSTR)pszUCS, (LPWSTR)tcc->pWin32ConvUCS2Cache);
return nBufSize / sizeof(WCHAR);
}
}
/*
* Helper to convert from utf-8 to UCS-2 and to complete a path for 32K path
* syntax
*/
nRet = UTF8_2_wchar(pszUCS, pszUTF);
#ifdef USE_WIN32_32KPATHCONVERSION
// Add \\?\ to support 32K long filepaths
pszUCS = make_wchar_win32_path(pszUCS, pBIsRawPath);
#else
if (pBIsRawPath) { *pBIsRawPath = FALSE; }
#endif
// Populate cache
if (tcc) {
tcc->pWin32ConvUCS2Cache = CheckPoolMemorySize(tcc->pWin32ConvUCS2Cache,
SizeofPoolMemory(pszUCS));
wcscpy((LPWSTR)tcc->pWin32ConvUCS2Cache, (LPWSTR)pszUCS);
tcc->dwWin32ConvUTF8strlen = strlen(pszUTF);
tcc->pWin32ConvUTF8Cache = CheckPoolMemorySize(
tcc->pWin32ConvUTF8Cache, tcc->dwWin32ConvUTF8strlen + 2);
bstrncpy(tcc->pWin32ConvUTF8Cache, pszUTF, tcc->dwWin32ConvUTF8strlen + 1);
}
return nRet;
}
#if !defined(_MSC_VER) || (_MSC_VER < 1400) // VC8+
int umask(int) { return 0; }
#endif
#ifndef LOAD_WITH_ALTERED_SEARCH_PATH
# define LOAD_WITH_ALTERED_SEARCH_PATH 0x00000008
#endif
void* dlopen(const char* filename, int mode)
{
void* handle;
DWORD dwFlags = 0;
dwFlags |= LOAD_WITH_ALTERED_SEARCH_PATH;
if (mode & RTLD_NOLOAD) { dwFlags |= LOAD_LIBRARY_AS_DATAFILE; }
handle = LoadLibraryEx(filename, NULL, dwFlags);
return handle;
}
void* dlsym(void* handle, const char* name)
{
void* symaddr;
symaddr = (void*)GetProcAddress((HMODULE)handle, name);
return symaddr;
}
int dlclose(void* handle)
{
if (handle && !FreeLibrary((HMODULE)handle)) {
errno = b_errno_win32;
return 1; /* failed */
}
return 0; /* OK */
}
char* dlerror(void)
{
static char buf[200];
const char* err = errorString();
bstrncpy(buf, (char*)err, sizeof(buf));
LocalFree((void*)err);
return buf;
}
int fcntl([[maybe_unused]] int fd, [[maybe_unused]] int cmd) { return 0; }
int chown([[maybe_unused]] const char* k,
[[maybe_unused]] uid_t,
[[maybe_unused]] gid_t)
{
return 0;
}
int lchown([[maybe_unused]] const char* k,
[[maybe_unused]] uid_t,
[[maybe_unused]] gid_t)
{
return 0;
}
long int random(void) { return rand(); }
void srandom(unsigned int seed) { srand(seed); }
static time_t CvtFtimeToUtime(const FILETIME& time)
{
uint64_t mstime;
mstime = time.dwHighDateTime;
mstime <<= 32;
mstime |= time.dwLowDateTime;
mstime -= WIN32_FILETIME_ADJUST;
mstime /= WIN32_FILETIME_SCALE; /* convert to seconds. */
return (time_t)(mstime & 0xffffffff);
}
static time_t CvtFtimeToUtime(const LARGE_INTEGER& time)
{
uint64_t mstime;
mstime = time.HighPart;
mstime <<= 32;
mstime |= time.LowPart;
mstime -= WIN32_FILETIME_ADJUST;
mstime /= WIN32_FILETIME_SCALE; /* convert to seconds. */
return (time_t)(mstime & 0xffffffff);
}
bool CreateJunction(const char* szJunction, const char* szPath)
{
DWORD dwRet;
HANDLE hDir;
bool retval = false;
int buf_length, data_length;
int SubstituteNameLength, PrintNameLength; /* length in bytes */
REPARSE_DATA_BUFFER* rdb;
PoolMem szDestDir(PM_FNAME);
POOLMEM *buf, *szJunctionW, *szPrintName, *szSubstituteName;
/*
* We only implement a Wide string version of CreateJunction.
* So if p_CreateDirectoryW is not available we refuse to do anything.
*/
if (!p_CreateDirectoryW) {
Dmsg0(debuglevel,
"CreateJunction: CreateDirectoryW not found, doing nothing\n");
return false;
}
// Create three buffers to hold the wide char strings.
szJunctionW = GetPoolMemory(PM_FNAME);
/* With \\?\\ */
szSubstituteName = GetPoolMemory(PM_FNAME);
/* Simple path */
szPrintName = GetPoolMemory(PM_FNAME);
// Create a buffer big enough to hold all data.
buf_length = sizeof(REPARSE_DATA_BUFFER) + 2 * MAX_PATH * sizeof(WCHAR);
buf = GetPoolMemory(PM_NAME);
buf = CheckPoolMemorySize(buf, buf_length);
rdb = (REPARSE_DATA_BUFFER*)buf;
// Create directory
if (!UTF8_2_wchar(szJunctionW, szJunction)) { goto bail_out; }
if (!p_CreateDirectoryW((LPCWSTR)szJunctionW, NULL)) {
Dmsg1(debuglevel, "CreateDirectory Failed:%s\n", errorString());
goto bail_out;
}
// Create file/open reparse point
hDir = p_CreateFileW(
(LPCWSTR)szJunctionW, GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (hDir == INVALID_HANDLE_VALUE) {
Dmsg0(debuglevel, "INVALID_FILE_HANDLE");
RemoveDirectoryW((LPCWSTR)szJunctionW);
goto bail_out;
}
if (!UTF8_2_wchar(szPrintName, szPath)) { goto bail_out; }
// Add \??\ prefix.
Mmsg(szDestDir, "\\??\\%s", szPath);
if (!UTF8_2_wchar(szSubstituteName, szDestDir.c_str())) { goto bail_out; }
// Put data junction target into reparse buffer
memset(buf, 0, buf_length);
#define MOUNTPOINTREPARSEBUFFER_FIXED_HEADER_SIZE 8
SubstituteNameLength = wcslen((LPWSTR)szSubstituteName) * sizeof(WCHAR);
PrintNameLength = wcslen((LPWSTR)szPrintName) * sizeof(WCHAR);
wcsncpy((LPWSTR)rdb->MountPointReparseBuffer.PathBuffer,
(LPWSTR)szSubstituteName, SubstituteNameLength);
wcsncpy((LPWSTR)rdb->MountPointReparseBuffer.PathBuffer
+ wcslen((LPWSTR)szSubstituteName) + 1,
(LPWSTR)szPrintName, PrintNameLength);
rdb->MountPointReparseBuffer.SubstituteNameLength = SubstituteNameLength;
rdb->MountPointReparseBuffer.PrintNameOffset = SubstituteNameLength + 2;
rdb->MountPointReparseBuffer.PrintNameLength = PrintNameLength;
rdb->ReparseDataLength = SubstituteNameLength + PrintNameLength + 12;
data_length
= rdb->ReparseDataLength + MOUNTPOINTREPARSEBUFFER_FIXED_HEADER_SIZE;
rdb->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
/*
* Write reparse point
* For debugging use "fsutil reparsepoint query"
*/
if (!DeviceIoControl(hDir, FSCTL_SET_REPARSE_POINT, (LPVOID)buf, data_length,
NULL, 0, &dwRet, 0)) {
Dmsg1(debuglevel, "DeviceIoControl Failed:%s\n", errorString());
CloseHandle(hDir);
RemoveDirectoryW((LPCWSTR)szJunctionW);
goto bail_out;
}
CloseHandle(hDir);
retval = true;
bail_out:
FreePoolMemory(buf);
FreePoolMemory(szJunctionW);
FreePoolMemory(szPrintName);
FreePoolMemory(szSubstituteName);
return retval;
}
const char* errorString(void)
{
LPVOID lpMsgBuf;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default lang */
(LPTSTR)&lpMsgBuf, 0, NULL);
// Strip any \r or \n