- Notifications
You must be signed in to change notification settings - Fork 234
/
Copy pathutils.cpp
1880 lines (1592 loc) · 42.4 KB
/
utils.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
/*
* The contents of this file are subject to the Initial
* Developer's Public License Version 1.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
* http://www.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_idpl.
*
* Software distributed under the License is distributed AS IS,
* WITHOUT WARRANTY OF ANY KIND, either express or implied.
* See the License for the specific language governing rights
* and limitations under the License.
*
* The Original Code was created by Claudio Valderrama on 25-Dec-2003
* for the Firebird Open Source RDBMS project.
*
* Copyright (c) 2003 Claudio Valderrama
* and all contributors signed below.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*
* Nickolay Samofatov <nickolay@broadviewsoftware.com>
*/
// =====================================
// Utility functions
#include"firebird.h"
#include"../common/os/guid.h"
#ifdef HAVE_SYS_TYPES_H
#include<sys/types.h>
#else
#define__need_size_t
#include<stddef.h>
#undef __need_size_t
#endif
#include<stdarg.h>
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include"../common/gdsassert.h"
#include"../common/utils_proto.h"
#include"../common/classes/auto.h"
#include"../common/classes/locks.h"
#include"../common/classes/init.h"
#include"../common/isc_proto.h"
#include"../jrd/constants.h"
#include"firebird/impl/inf_pub.h"
#include"../jrd/align.h"
#include"../common/os/path_utils.h"
#include"../common/os/fbsyslog.h"
#include"../common/StatusArg.h"
#include"../common/os/os_utils.h"
#include"firebird/impl/sqlda_pub.h"
#include"../common/classes/ClumpletReader.h"
#include"../common/StatusArg.h"
#include"../common/TimeZoneUtil.h"
#include"../common/config/config.h"
#ifdef WIN_NT
#include<direct.h>
#include<io.h>// isatty()
#include<sddl.h>
#endif
#ifdef HAVE_UNISTD_H
#include<unistd.h>
#endif
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#ifdef HAVE_TERMIOS_H
#include<termios.h>
#endif
#ifdef HAVE_TIMES
#include<sys/times.h>
#endif
namespacefb_utils
{
boolimplicit_name(constchar* name, constchar* prefix, int prefix_len);
char* copy_terminate(char* dest, constchar* src, size_t bufsize)
{
/**************************************
*
* c o p y _ t e r m i n a t e
*
**************************************
*
* Functional description
* Do the same as strncpy but ensure the null terminator is written.
*
**************************************/
if (!bufsize) // Was it a joke?
return dest;
--bufsize;
strncpy(dest, src, bufsize);
dest[bufsize] = 0;
return dest;
}
char* exact_name(char* const name)
{
/**************************************
*
* e x a c t _ n a m e
*
**************************************
*
* Functional description
* Trim off trailing spaces from a metadata name.
* eg: insert a null after the last non-blank character.
*
* SQL delimited identifier may have blank as part of the name
*
* Parameters: str - the string to terminate
* Returns: str
*
**************************************/
char* p = name;
while (*p)
++p;
// Now, let's go back
--p;
while (p >= name && *p == '\x20') // blank character, ASCII(32)
--p;
*(p + 1) = '\0';
return name;
}
char* exact_name_limit(char* const name, size_t bufsize)
{
/**************************************
*
* e x a c t _ n a m e _ l i m i t
*
**************************************
*
* Functional description
* Trim off trailing spaces from a metadata name.
* eg: insert a null after the last non-blank character.
* It has a maximum length to ensure working between bounds.
*
* SQL delimited identifier may have blank as part of the name
*
* Parameters: str - the string to terminate
* bufsize - the size of the variable containing the string.
* Returns: str
*
**************************************/
constchar* const end = name + bufsize - 1;
char* p = name;
while (*p && p < end)
++p;
// Now, let's go back
--p;
while (p >= name && *p == '\x20') // blank character, ASCII(32)
--p;
*(p + 1) = '\0';
return name;
}
// *****************************
// i m p l i c i t _ d o m a i n
// *****************************
// Determines if a domain or index is of the form RDB$<n[...n]>[<spaces>]
// This may be true for implicit domains and for unique and non-unique indices except PKs.
boolimplicit_domain(constchar* domain_name)
{
returnimplicit_name(domain_name, IMPLICIT_DOMAIN_PREFIX, IMPLICIT_DOMAIN_PREFIX_LEN);
}
// ***********************************
// i m p l i c i t _ i n t e g r i t y
// ***********************************
// Determines if a table integrity constraint domain is of the form INTEG_<n[...n]>[<spaces>]
boolimplicit_integrity(constchar* integ_name)
{
returnimplicit_name(integ_name, IMPLICIT_INTEGRITY_PREFIX, IMPLICIT_INTEGRITY_PREFIX_LEN);
}
// ***********************************
// i m p l i c i t _ p k
// ***********************************
// Determines if an index is of the form RDB$PRIMARY<n[...n]>[<spaces>]
boolimplicit_pk(constchar* pk_name)
{
returnimplicit_name(pk_name, IMPLICIT_PK_PREFIX, IMPLICIT_PK_PREFIX_LEN);
}
// ***********************************
// i m p l i c i t _ n a m e
// ***********************************
// Determines if a name is of the form prefix<n[...n]>[<spaces>]
// where prefix has a fixed known length.
boolimplicit_name(constchar* name, constchar* prefix, int prefix_len)
{
if (strncmp(name, prefix, prefix_len) != 0)
returnfalse;
int i = prefix_len;
while (name[i] >= '0' && name[i] <= '9')
++i;
if (i == prefix_len) // 'prefix' alone isn't valid
returnfalse;
while (name[i] == '')
++i;
return !name[i]; // we reached null term
}
intname_length(const TEXT* const name)
{
/**************************************
*
* n a m e _ l e n g t h
*
**************************************
*
* Functional description
* Compute effective length of system relation name and others.
* SQL delimited identifier may contain blanks. Trailing blanks are ignored.
* Assumes input is null terminated.
*
**************************************/
const TEXT* q = name - 1;
for (const TEXT* p = name; *p; p++)
{
if (*p != '') {
q = p;
}
}
return (q + 1) - name;
}
// *********************************
// n a m e _ l e n g t h _ l i m i t
// *********************************
// Compute length without trailing blanks. The second parameter is maximum length.
intname_length_limit(const TEXT* const name, size_t bufsize)
{
constchar* p = name + bufsize - 1;
// Now, let's go back
while (p >= name && *p == '') // blank character, ASCII(32)
--p;
return (p + 1) - name;
}
//***************
// r e a d e n v
//***************
// Goes to read directly the environment variables from the operating system on Windows
// and provides a stub for UNIX.
boolreadenv(constchar* env_name, Firebird::string& env_value)
{
#ifdef WIN_NT
const DWORD rc = GetEnvironmentVariable(env_name, NULL, 0);
if (rc)
{
env_value.reserve(rc - 1);
DWORD rc2 = GetEnvironmentVariable(env_name, env_value.begin(), rc);
if (rc2 < rc && rc2 != 0)
{
env_value.recalculate_length();
returntrue;
}
}
#else
constchar* p = getenv(env_name);
if (p)
return env_value.assign(p).length() != 0;
#endif
// Not found, clear the output var.
env_value.begin()[0] = 0;
env_value.recalculate_length();
returnfalse;
}
boolreadenv(constchar* env_name, Firebird::PathName& env_value)
{
Firebird::string result;
bool rc = readenv(env_name, result);
env_value.assign(result.c_str(), result.length());
return rc;
}
// Set environment variable.
// If overwrite == false and variable already exist, return true.
boolsetenv(constchar* name, constchar* value, bool overwrite)
{
#ifdef WIN_NT
int errcode = 0;
if (!overwrite)
{
size_t envsize = 0;
errcode = getenv_s(&envsize, NULL, 0, name);
if (errcode || envsize)
return errcode ? false : true;
}
// In Windows, _putenv_s sets only the environment data in the CRT.
// Each DLL (for example ICU) may use a different CRT which different data
// or use Win32's GetEnvironmentVariable, so we also use SetEnvironmentVariable.
// This is a mess and is not guarenteed to work correctly in all situations.
if (SetEnvironmentVariable(name, value))
{
_putenv_s(name, value);
returntrue;
}
else
returnfalse;
#else
return ::setenv(name, value, (int) overwrite) == 0;
#endif
}
// ***************
// s n p r i n t f
// ***************
// Provide a single place to deal with vsnprintf and error detection.
intsnprintf(char* buffer, size_t count, constchar* format...)
{
va_list args;
va_start(args, format);
constint rc = VSNPRINTF(buffer, count, format, args);
buffer[count - 1] = 0;
va_end(args);
#if defined(DEV_BUILD) && !defined(HAVE_VSNPRINTF)
// We don't have the safe functions, then check if we overflowed the buffer.
// I would prefer to make this functionality available in prod build, too.
// If the docs are right, the null terminator is not counted => rc < count.
#if defined(fb_assert_continue)
fb_assert_continue(rc >= 0 && rc < count);
#else
fb_assert(rc >= 0 && rc < count);
#endif
#endif
return rc;
}
// *******************
// c l e a n u p _ p a s s w d
// *******************
// Copy password to newly allocated place and replace existing one in argv with spaces.
// Allocated space is released upon exit from utility.
// This is planned leak of a few bytes of memory in utilities.
// This function is deprecated. Use UtilSvc::hidePasswd(ArgvType&, int) whenever possible.
// However, there are several usages through fb_utils::get_passwd(char* arg);
char* cleanup_passwd(char* arg)
{
if (! arg)
{
return arg;
}
constint lpass = static_cast<int>(strlen(arg));
char* savePass = (char*) gds__alloc(lpass + 1);
if (! savePass)
{
// No clear idea, how will it work if there is no memory
// for password, but let others think. As a minimum avoid AV.
return arg;
}
memcpy(savePass, arg, lpass + 1);
memset(arg, '', lpass);
return savePass;
}
#ifdef WIN_NT
staticboolvalidateProductSuite (LPCSTR lpszSuiteToValidate);
// hvlad: begins from Windows 2000 we can safely add 'Global\' prefix for
// names of all kernel objects we use. For Win9x we must not add this prefix.
// Win NT will accept such names only if Terminal Server is installed.
// Check OS version carefully and add prefix if we can add it
boolprefix_kernel_object_name(char* name, size_t bufsize)
{
staticbool bGlobalPrefix = false;
staticbool bInitDone = false;
if (!bInitDone)
{
bGlobalPrefix = isGlobalKernelPrefix();
bInitDone = true;
}
// Backwards compatibility feature with Firebird 2.0.3 and earlier.
// If the name already contains some prefix (specified by the user, as was
// recommended in firebird.conf) additional prefix is not added
if (bGlobalPrefix && !strchr(name, '\\'))
{
constchar* prefix = "Global\\";
constsize_t len_prefix = strlen(prefix);
constsize_t len_name = strlen(name) + 1;
// if name and prefix can't fit in name's buffer than we must
// not overwrite end of name because it contains object type
constsize_t move_prefix = (len_name + len_prefix > bufsize) ?
(bufsize - len_name) : len_prefix;
memmove(name + move_prefix, name, len_name);
memcpy(name, prefix, move_prefix);
// CVC: Unfortunately, things like Glob instead of Global\\ do not achieve the objective
// of telling the NT kernel the object is global and hence I consider them failures.
//return move_prefix > 0; // Soft version of the check
return move_prefix == len_prefix; // Strict version of the check.
}
returntrue;
}
// Simply handle guardian.
classDynLibHandle
{
public:
explicitDynLibHandle(HMODULE mod)
: m_handle(mod)
{}
~DynLibHandle()
{
if (m_handle)
FreeLibrary(m_handle);
}
operatorHMODULE() const
{
return m_handle;
}
/* The previous conversion is invoked with !object so this is enough.
bool operator!() const
{
return !m_handle;
}
*/
private:
HMODULE m_handle;
};
// hvlad: two functions below got from
// http://msdn2.microsoft.com/en-us/library/aa380797.aspx
// and slightly adapted for our coding style
// -------------------------------------------------------------
// Note that the validateProductSuite and isTerminalServices
// functions use ANSI versions of the functions to maintain
// compatibility with Windows Me/98/95.
// -------------------------------------------------------------
boolisGlobalKernelPrefix()
{
// The strategy of this function is as follows: use Global\ kernel namespace
// for engine objects if we can. This can be prevented by either lack of OS support
// for the feature (Win9X) or lack of privileges (Vista, Windows 2000/XP restricted accounts)
const DWORD dwVersion = GetVersion();
// Is Windows NT running?
if (!(dwVersion & 0x80000000))
{
if (LOBYTE(LOWORD(dwVersion)) <= 4) // This is Windows NT 4.0 or earlier.
returnvalidateProductSuite("Terminal Server");
// Is it Windows 2000 or greater? It is possible to use Global\ prefix on any
// version of Windows from Windows 2000 and up
// Check if we have enough privileges to create global handles.
// If not fall back to creating local ones.
// The API for that is the NT thing, so we have to get addresses of the
// functions dynamically to avoid troubles on Windows 9X platforms
DynLibHandle hmodAdvApi(LoadLibrary("advapi32.dll"));
if (!hmodAdvApi)
{
gds__log("LoadLibrary failed for advapi32.dll. Error code: %lu", GetLastError());
returnfalse;
}
typedefBOOL (WINAPI *PFnOpenProcessToken) (HANDLE, DWORD, PHANDLE);
typedefBOOL (WINAPI *PFnLookupPrivilegeValue) (LPCSTR, LPCSTR, PLUID);
typedefBOOL (WINAPI *PFnPrivilegeCheck) (HANDLE, PPRIVILEGE_SET, LPBOOL);
PFnOpenProcessToken pfnOpenProcessToken =
(PFnOpenProcessToken) GetProcAddress(hmodAdvApi, "OpenProcessToken");
PFnLookupPrivilegeValue pfnLookupPrivilegeValue =
(PFnLookupPrivilegeValue) GetProcAddress(hmodAdvApi, "LookupPrivilegeValueA");
PFnPrivilegeCheck pfnPrivilegeCheck =
(PFnPrivilegeCheck) GetProcAddress(hmodAdvApi, "PrivilegeCheck");
if (!pfnOpenProcessToken || !pfnLookupPrivilegeValue || !pfnPrivilegeCheck)
{
// Should never happen, really
gds__log("Cannot access privilege management API");
returnfalse;
}
HANDLE hProcess = GetCurrentProcess();
HANDLE hToken;
if (pfnOpenProcessToken(hProcess, TOKEN_QUERY, &hToken) == 0)
{
gds__log("OpenProcessToken failed. Error code: %lu", GetLastError());
returnfalse;
}
PRIVILEGE_SET ps;
memset(&ps, 0, sizeof(ps));
ps.Control = PRIVILEGE_SET_ALL_NECESSARY;
ps.PrivilegeCount = 1;
if (pfnLookupPrivilegeValue(NULL, TEXT("SeCreateGlobalPrivilege"), &ps.Privilege[0].Luid) == 0)
{
// Failure here means we're running on old version of Windows 2000 or XP
// which always allow creating global handles
CloseHandle(hToken);
returntrue;
}
BOOL checkResult;
if (pfnPrivilegeCheck(hToken, &ps, &checkResult) == 0)
{
gds__log("PrivilegeCheck failed. Error code: %lu", GetLastError());
CloseHandle(hToken);
returnfalse;
}
CloseHandle(hToken);
return checkResult;
}
returnfalse;
}
// Incapsulates Windows private namespace
classPrivateNamespace
{
public:
PrivateNamespace(MemoryPool& pool) :
m_hNamespace(NULL),
m_hTestEvent(NULL)
{
try
{
init();
}
catch (const Firebird::Exception& ex)
{
iscLogException("Error creating private namespace", ex);
}
}
~PrivateNamespace()
{
if (m_hNamespace != NULL)
ClosePrivateNamespace(m_hNamespace, 0);
if (m_hTestEvent != NULL)
CloseHandle(m_hTestEvent);
}
// Add namespace prefix to the name, returns true on success.
booladdPrefix(char* name, size_t bufsize)
{
if (!isReady())
returnfalse;
if (strchr(name, '\\') != 0)
returnfalse;
constsize_t prefixLen = strlen(sPrivateNameSpace) + 1;
constsize_t nameLen = strlen(name) + 1;
if (prefixLen + nameLen > bufsize)
returnfalse;
memmove(name + prefixLen, name, nameLen + 1);
memcpy(name, sPrivateNameSpace, prefixLen - 1);
name[prefixLen - 1] = '\\';
returntrue;
}
boolisReady() const
{
return (m_hNamespace != NULL) || (m_hTestEvent != NULL);
}
private:
constchar* sPrivateNameSpace = "FirebirdCommon";
constchar* sBoundaryName = "FirebirdCommonBoundary";
voidraiseError(constchar* apiRoutine)
{
(Firebird::Arg::Gds(isc_sys_request) << apiRoutine << Firebird::Arg::OsError()).raise();
}
voidinit()
{
alignas(SID) char sid[SECURITY_MAX_SID_SIZE];
DWORD cbSid = sizeof(sid);
// For now use EVERYONE, could be changed later
cbSid = sizeof(sid);
if (!CreateWellKnownSid(WinWorldSid, NULL, &sid, &cbSid))
raiseError("CreateWellKnownSid");
// Create security descriptor which allows generic access to the just created SID
SECURITY_ATTRIBUTES sa;
RtlSecureZeroMemory(&sa, sizeof(sa));
sa.nLength = sizeof(sa);
sa.bInheritHandle = FALSE;
char strSecDesc[255];
LPSTR strSid = NULL;
if (ConvertSidToStringSid(&sid, &strSid))
{
snprintf(strSecDesc, sizeof(strSecDesc), "D:(A;;GA;;;%s)", strSid);
LocalFree(strSid);
}
else
strncpy(strSecDesc, "D:(A;;GA;;;WD)", sizeof(strSecDesc));
if (!ConvertStringSecurityDescriptorToSecurityDescriptor(strSecDesc, SDDL_REVISION_1,
&sa.lpSecurityDescriptor, NULL))
{
raiseError("ConvertStringSecurityDescriptorToSecurityDescriptor");
}
Firebird::Cleanup cleanSecDesc( [&sa] {
LocalFree(sa.lpSecurityDescriptor);
});
HANDLE hBoundaryDesc = CreateBoundaryDescriptor(sBoundaryName, 0);
if (hBoundaryDesc == NULL)
raiseError("CreateBoundaryDescriptor");
Firebird::Cleanup cleanBndDesc( [&hBoundaryDesc] {
DeleteBoundaryDescriptor(hBoundaryDesc);
});
if (!AddSIDToBoundaryDescriptor(&hBoundaryDesc, &sid))
raiseError("AddSIDToBoundaryDescriptor");
m_hNamespace = CreatePrivateNamespace(&sa, hBoundaryDesc, sPrivateNameSpace);
if (m_hNamespace == NULL)
{
DWORD err = GetLastError();
if (err != ERROR_ALREADY_EXISTS)
raiseError("CreatePrivateNamespace");
m_hNamespace = OpenPrivateNamespace(hBoundaryDesc, sPrivateNameSpace);
if (m_hNamespace == NULL)
{
err = GetLastError();
if (err != ERROR_DUP_NAME)
raiseError("OpenPrivateNamespace");
Firebird::string name(sPrivateNameSpace);
name.append("\\test");
m_hTestEvent = CreateEvent(ISC_get_security_desc(), TRUE, TRUE, name.c_str());
if (m_hTestEvent == NULL)
raiseError("CreateEvent");
}
}
}
HANDLE m_hNamespace;
HANDLE m_hTestEvent;
};
static Firebird::InitInstance<PrivateNamespace> privateNamespace;
boolprivate_kernel_object_name(char* name, size_t bufsize)
{
if (!privateNamespace().addPrefix(name, bufsize))
returnprefix_kernel_object_name(name, bufsize);
returntrue;
}
boolprivateNameSpaceReady()
{
returnprivateNamespace().isReady();
}
// This is a very basic registry querying class. Not much validation, but avoids
// leaving the registry open by mistake.
classNTRegQuery
{
public:
NTRegQuery();
~NTRegQuery();
boolopenForRead(constchar* key);
boolreadValueSize(constchar* value);
// Assumes previous call to readValueSize.
boolreadValueData(LPSTR data);
voidclose();
DWORD getDataType() const;
DWORD getDataSize() const;
private:
HKEY m_hKey;
DWORD m_dwType;
DWORD m_dwSize;
constchar* m_value;
};
inlineNTRegQuery::NTRegQuery()
: m_hKey(NULL), m_dwType(0), m_dwSize(0)
{
}
inlineNTRegQuery::~NTRegQuery()
{
close();
}
boolNTRegQuery::openForRead(constchar* key)
{
returnRegOpenKeyExA(HKEY_LOCAL_MACHINE, key, 0, KEY_QUERY_VALUE, &m_hKey) == ERROR_SUCCESS;
}
boolNTRegQuery::readValueSize(constchar* value)
{
m_value = value;
returnRegQueryValueExA(m_hKey, value, NULL, &m_dwType, NULL, &m_dwSize) == ERROR_SUCCESS;
}
boolNTRegQuery::readValueData(LPSTR data)
{
returnRegQueryValueExA(m_hKey, m_value, NULL, &m_dwType, (LPBYTE) data, &m_dwSize) == ERROR_SUCCESS;
}
voidNTRegQuery::close()
{
if (m_hKey)
RegCloseKey(m_hKey);
m_hKey = NULL;
}
inline DWORD NTRegQuery::getDataType() const
{
return m_dwType;
}
inline DWORD NTRegQuery::getDataSize() const
{
return m_dwSize;
}
// This class represents the local allocation of dynamic memory in Windows.
classNTLocalString
{
public:
explicitNTLocalString(DWORD dwSize);
LPCSTR c_str() const;
LPSTR getString();
boolallocated() const;
~NTLocalString();
private:
LPSTR m_string;
};
NTLocalString::NTLocalString(DWORD dwSize)
{
m_string = (LPSTR) LocalAlloc(LPTR, dwSize);
}
NTLocalString::~NTLocalString()
{
if (m_string)
LocalFree(m_string);
}
inline LPCSTR NTLocalString::c_str() const
{
return m_string;
}
inline LPSTR NTLocalString::getString()
{
return m_string;
}
inlineboolNTLocalString::allocated() const
{
return m_string != 0;
}
////////////////////////////////////////////////////////////
// validateProductSuite function
//
// Terminal Services detection code for systems running
// Windows NT 4.0 and earlier.
//
////////////////////////////////////////////////////////////
boolvalidateProductSuite (LPCSTR lpszSuiteToValidate)
{
NTRegQuery query;
// Open the ProductOptions key.
if (!query.openForRead("System\\CurrentControlSet\\Control\\ProductOptions"))
returnfalse;
// Determine required size of ProductSuite buffer.
// If we get size == 1 it means multi string data with only a terminator.
if (!query.readValueSize("ProductSuite") || query.getDataSize() < 2)
returnfalse;
// Allocate buffer.
NTLocalString lpszProductSuites(query.getDataSize());
if (!lpszProductSuites.allocated())
returnfalse;
// Retrieve array of product suite strings.
if (!query.readValueData(lpszProductSuites.getString()) || query.getDataType() != REG_MULTI_SZ)
returnfalse;
query.close(); // explicit but redundant.
// Search for suite name in array of strings.
boolfValidated = false;
LPCSTR lpszSuite = lpszProductSuites.c_str();
LPCSTR end = lpszSuite + query.getDataSize(); // paranoid check
while (*lpszSuite && lpszSuite < end)
{
if (lstrcmpA(lpszSuite, lpszSuiteToValidate) == 0)
{
fValidated = true;
break;
}
lpszSuite += (lstrlenA(lpszSuite) + 1);
}
returnfValidated;
}
#endif// WIN_NT
// *******************************
// g e t _ p r o c e s s _ n a m e
// *******************************
// Return the name of the current process
Firebird::PathName get_process_name()
{
char buffer[MAXPATHLEN];
#if defined(WIN_NT)
constint len = GetModuleFileName(NULL, buffer, sizeof(buffer));
#elif defined(HAVE__PROC_SELF_EXE)
constint len = readlink("/proc/self/exe", buffer, sizeof(buffer));
#else
constint len = 0;
#endif
if (len <= 0)
buffer[0] = 0;
elseif (size_t(len) < sizeof(buffer))
buffer[len] = 0;
else
buffer[len - 1] = 0;
return buffer;
}
SLONG genUniqueId()
{
static Firebird::AtomicCounter cnt;
return ++cnt;
}
voidgetCwd(Firebird::PathName& pn)
{
char* buffer = pn.getBuffer(MAXPATHLEN);
#if defined(WIN_NT)
_getcwd(buffer, MAXPATHLEN);
#elif defined(HAVE_GETCWD)
FB_UNUSED(getcwd(buffer, MAXPATHLEN));
#else
FB_UNUSED(getwd(buffer));
#endif
pn.recalculate_length();
}
namespace {
classInputFile
{
public:
explicitInputFile(const Firebird::PathName& name)
: flagEcho(false)
{
if (name == "stdin") {
f = stdin;
}
else {
f = os_utils::fopen(name.c_str(), "rt");
}
if (f && isatty(fileno(f)))
{
fprintf(stderr, "Enter password: ");
fflush(stderr);
#ifdef HAVE_TERMIOS_H
flagEcho = tcgetattr(fileno(f), &oldState) == 0;
if (flagEcho)
{
flagEcho = oldState.c_lflag & ECHO;
}
if (flagEcho)
{
structtermiosnewState(oldState);
newState.c_lflag &= ~ECHO;
tcsetattr(fileno(f), TCSANOW, &newState);
}
#elif defined(WIN_NT)
HANDLE handle = (HANDLE) _get_osfhandle(fileno(f));
DWORD dwMode;
flagEcho = GetConsoleMode(handle, &dwMode) && (dwMode & ENABLE_ECHO_INPUT);
if (flagEcho)
SetConsoleMode(handle, dwMode & ~ENABLE_ECHO_INPUT);
#endif
}
}
~InputFile()
{
if (flagEcho)
{
fprintf(stderr, "\n");
fflush(stderr);
#ifdef HAVE_TERMIOS_H
tcsetattr(fileno(f), TCSANOW, &oldState);
#elif defined(WIN_NT)
HANDLE handle = (HANDLE) _get_osfhandle(fileno(f));
DWORD dwMode;
if (GetConsoleMode(handle, &dwMode))
SetConsoleMode(handle, dwMode | ENABLE_ECHO_INPUT);
#endif
}
if (f && f != stdin) {
fclose(f);
}
}
FILE* getStdioFile() { return f; }
booloperator!() { return !f; }
private:
FILE* f;
#ifdef HAVE_TERMIOS_H
structtermios oldState;
#endif
bool flagEcho;
};
} // namespace
// fetch password from file
FetchPassResult fetchPassword(const Firebird::PathName& name, constchar*& password)
{
InputFile file(name);
if (!file)
{
return FETCH_PASS_FILE_OPEN_ERROR;
}
Firebird::string pwd;