-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathutils.cc
More file actions
1515 lines (1375 loc) · 48.3 KB
/
Copy pathutils.cc
File metadata and controls
1515 lines (1375 loc) · 48.3 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
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef _WIN32
#include <iconv.h>
#endif // LINUX
#include "google/cloud/odbc/bq_client_interface/odbc_authentication.h"
#include "google/cloud/odbc/bq_driver/internal/trace_utils.h"
#include "google/cloud/odbc/bq_driver/internal/utils.h"
#include "google/cloud/internal/getenv.h"
#include "absl/types/optional.h"
#include <array>
#include <atomic>
#include <cstdint>
#include <random>
#include <sstream>
#include <string>
#ifdef _WIN32
#include <cstdlib>
#include <uxtheme.h> // Required for SetWindowTheme
#pragma comment(lib, "UxTheme.lib") // Link UxTheme.lib
HINSTANCE g_hDllInstance = NULL;
#endif
#include <filesystem>
namespace fs = std::filesystem;
namespace google::cloud::odbc_bq_driver_internal {
bool g_suppress_dropdown = false;
using ::google::cloud::odbc_internal::SQLStates;
using ::google::cloud::odbc_internal::StatusRecord;
using ::google::cloud::odbc_internal::StatusRecordOr;
#if defined(_WIN32)
WireEncoding GetEffectiveWireEncoding() { return WireEncoding::kUtf16Le; }
size_t WireWcharSize() { return sizeof(SQLWCHAR); }
void SetWcharEncodingFromConfig(std::string const&) {
// No-op on Windows: SQLWCHAR is always 2-byte UTF-16LE.
}
#else
namespace {
std::atomic<WireEncoding> g_wire_encoding{WireEncoding::kDefault};
} // namespace
WireEncoding GetEffectiveWireEncoding() {
auto configured = g_wire_encoding.load(std::memory_order_relaxed);
if (configured != WireEncoding::kDefault) {
return configured;
}
// Default is based on compile-time SQLWCHAR size
return (sizeof(SQLWCHAR) == 2) ? WireEncoding::kUtf16Le
: WireEncoding::kUtf32Le;
}
size_t WireWcharSize() {
switch (GetEffectiveWireEncoding()) {
case WireEncoding::kUtf32Le:
case WireEncoding::kDefault:
return 4;
case WireEncoding::kUtf16Le:
return 2;
case WireEncoding::kUtf8:
return 1;
}
return sizeof(SQLWCHAR);
}
void SetWcharEncodingFromConfig(std::string const& value) {
if (value == "UTF-8" || value == "UTF8") {
g_wire_encoding.store(WireEncoding::kUtf8, std::memory_order_relaxed);
LOG(INFO) << "WcharEncoding: UTF-8 wire format (1 byte/char)";
} else if (value == "UTF-16LE" || value == "UTF16LE" || value == "UTF-16") {
g_wire_encoding.store(WireEncoding::kUtf16Le, std::memory_order_relaxed);
LOG(INFO) << "WcharEncoding: UTF-16LE wire format (2 bytes/char)";
} else if (value == "UTF-32LE" || value == "UTF32LE" || value == "UTF-32" ||
value == "UCS-4LE") {
g_wire_encoding.store(WireEncoding::kUtf32Le, std::memory_order_relaxed);
LOG(INFO) << "WcharEncoding: UTF-32LE wire format (4 bytes/char)";
} else if (value.empty() || value == "default") {
g_wire_encoding.store(WireEncoding::kDefault, std::memory_order_relaxed);
LOG(INFO) << "WcharEncoding: default (sizeof(SQLWCHAR) bytes/char)";
} else {
LOG(WARNING) << "WcharEncoding: unrecognised value '" << value << "'";
}
}
#endif
#ifdef _WIN32
using google::cloud::odbc_bigquery_client_interface::OauthMechanism;
static std::string const kOAuthMechanism = "OAuthMechanism";
static std::string const kKeyFilePath = "KeyFilePath";
#endif
#ifdef __APPLE__
std::string const kFromCode = "UTF-32LE";
#else
std::string const kFromCode = "WCHAR_T";
#endif
constexpr char kRandomIdChars[] =
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789-_";
std::string GenerateRandomId(int length) {
std::random_device rd;
std::mt19937_64 gen(rd());
std::uniform_int_distribution<std::size_t> distrib(
0, sizeof(kRandomIdChars) - 2); // -2 because of null terminator
std::string id(length, ' ');
for (int i = 0; i < length; ++i) {
id[i] = kRandomIdChars[distrib(gen)];
}
return id;
}
std::string GetDefaultPemFile() {
fs::path base;
#ifdef WIN32
HMODULE hm = nullptr;
if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCSTR>(&GetDefaultPemFile), &hm)) {
return {};
}
char path[MAX_PATH];
if (GetModuleFileNameA(hm, path, MAX_PATH) == 0) {
return {};
}
base = fs::path(path).parent_path();
return (base / "assets" / "roots.pem").string();
#else
Dl_info info;
if (dladdr(reinterpret_cast<void*>(&GetDefaultPemFile), &info) == 0) {
return {};
}
base = fs::path(info.dli_fname).parent_path();
return (base / "roots.pem").string();
#endif /* WIN32 */
}
std::string GenerateTableId() {
auto now = std::chrono::system_clock::now();
auto epoch_time =
std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch())
.count();
std::string time_str = std::to_string(epoch_time);
std::string random_id = GenerateRandomId(6);
std::string table_id = time_str + "_" + random_id;
return table_id;
}
std::wstring SQLWcharToWstring(const SQLWCHAR* in_str) {
if (!in_str) return {};
#ifdef _WIN32
return std::wstring(reinterpret_cast<wchar_t const*>(in_str));
#else
std::wstring result;
while (*in_str) {
result.push_back(static_cast<wchar_t>(*in_str));
++in_str;
}
return result;
#endif /* _WIN32 */
}
StatusRecord DoubleStrToInt(std::string& double_str) {
std::istringstream iss(double_str);
int64_t int_value;
iss >> int_value;
if (iss.fail()) {
LOG(ERROR) << "DoubleStrToInt:: Not a valid floating point value: "
<< double_str;
return StatusRecord{SQLStates::k_HY000(),
"Internal error: Not a valid floating point value"};
}
double_str = std::to_string(int_value);
return StatusRecord::Ok();
}
size_t NormalizeBufferSize(int size, size_t max_size) {
size_t normalized = static_cast<size_t>(std::abs(size)) % max_size;
return std::max<size_t>(1, normalized);
}
size_t BufferSizeForType(SQLSMALLINT type, size_t requested) {
size_t minimum_size = 1;
switch (type) {
case SQL_C_LONG:
case SQL_C_SLONG:
minimum_size = sizeof(SQLINTEGER);
break;
case SQL_C_DOUBLE:
minimum_size = sizeof(SQLDOUBLE);
break;
case SQL_C_FLOAT:
minimum_size = sizeof(SQLREAL);
break;
case SQL_C_TYPE_DATE:
minimum_size = sizeof(SQL_DATE_STRUCT);
break;
case SQL_C_TYPE_TIME:
minimum_size = sizeof(SQL_TIME_STRUCT);
break;
case SQL_C_TYPE_TIMESTAMP:
minimum_size = sizeof(SQL_TIMESTAMP_STRUCT);
break;
case SQL_C_WCHAR:
minimum_size = WireWcharSize();
break;
case SQL_C_SBIGINT:
minimum_size = sizeof(SQLBIGINT);
break;
case SQL_C_UBIGINT:
minimum_size = sizeof(SQLUBIGINT);
break;
case SQL_C_NUMERIC:
minimum_size = sizeof(SQL_NUMERIC_STRUCT);
break;
case SQL_C_INTERVAL_YEAR:
case SQL_C_INTERVAL_MONTH:
case SQL_C_INTERVAL_YEAR_TO_MONTH:
case SQL_C_INTERVAL_DAY:
case SQL_C_INTERVAL_HOUR:
case SQL_C_INTERVAL_MINUTE:
case SQL_C_INTERVAL_SECOND:
case SQL_C_INTERVAL_DAY_TO_HOUR:
case SQL_C_INTERVAL_DAY_TO_MINUTE:
case SQL_C_INTERVAL_DAY_TO_SECOND:
case SQL_C_INTERVAL_HOUR_TO_MINUTE:
case SQL_C_INTERVAL_HOUR_TO_SECOND:
case SQL_C_INTERVAL_MINUTE_TO_SECOND:
minimum_size = sizeof(SQL_INTERVAL_STRUCT);
break;
default:
break;
}
return std::max(requested, minimum_size);
}
std::vector<std::string> Split(std::string const& s,
std::string const& delimiter, int limit) {
int start_ind = 0;
int end_ind;
int len_del = delimiter.length();
std::string split;
std::vector<std::string> splits;
while ((end_ind = s.find(delimiter, start_ind)) != std::string::npos &&
--limit) {
split = s.substr(start_ind, end_ind - start_ind);
start_ind = end_ind + len_del;
splits.push_back(split);
}
splits.push_back(s.substr(start_ind));
return splits;
}
std::string Join(std::vector<std::string> v, std::string const& separator,
int start_ind) {
if (v.empty() || start_ind >= v.size()) {
return "";
}
if (start_ind < 0) {
start_ind = 0;
}
std::string joined;
for (; start_ind < v.size() - 1; start_ind++) {
joined.append(v[start_ind]);
joined.append(separator);
}
joined.append(v[v.size() - 1]);
return joined;
}
#ifdef _WIN32
StatusRecordOr<std::shared_ptr<Section>> GetSectionWin(
std::string const& registry_key) {
Section section;
HKEY key_handle;
LONG status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, LPCSTR(registry_key.c_str()),
0, KEY_READ, &key_handle);
if (status != ERROR_SUCCESS) {
RegCloseKey(key_handle);
std::string msg = "Can't open registry key with path: ";
msg.append(registry_key);
LOG(ERROR) << "GetSectionWin::RegOpenKeyEx:: " << msg;
return StatusRecord{SQLStates::k_HY000(), msg};
}
DWORD num_values;
DWORD longest_data_len;
status = RegQueryInfoKey(key_handle, NULL, NULL, NULL, NULL, NULL, NULL,
&num_values, NULL, &longest_data_len, NULL, NULL);
BYTE buffer[kMaxValueNameLen];
TCHAR property_name[kMaxValueNameLen];
DWORD buffer_len = kMaxValueNameLen;
for (int i = 0, status = ERROR_SUCCESS; i < num_values; i++) {
buffer_len = kMaxValueNameLen;
DWORD data_len = sizeof(buffer);
property_name[0] = '\0';
status = RegEnumValue(key_handle, i, property_name, &buffer_len, NULL, NULL,
NULL, NULL);
if (status == ERROR_SUCCESS) {
buffer_len = longest_data_len;
buffer[0] = '\0';
LONG query_status = RegQueryValueEx(key_handle, property_name, 0, NULL,
buffer, &data_len);
if (query_status == ERROR_SUCCESS) {
std::string value(reinterpret_cast<char*>(buffer), data_len);
value.erase(std::find(value.begin(), value.end(), '\0'), value.end());
std::string property(property_name);
section[property] = value;
}
}
}
RegCloseKey(key_handle);
return std::make_shared<Section>(section);
}
StatusRecordOr<std::shared_ptr<Sections>> ParseConfig(
std::string const& registry_key) {
HKEY key_handle;
LONG status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, LPCSTR(registry_key.c_str()),
0, KEY_READ, &key_handle);
if (status != ERROR_SUCCESS) {
RegCloseKey(key_handle);
return std::make_shared<Sections>();
}
TCHAR subkey_name[kMaxKeyLength];
DWORD name_len;
DWORD num_sub_keys = 0;
status = RegQueryInfoKey(key_handle, NULL, NULL, NULL, &num_sub_keys, NULL,
NULL, NULL, NULL, NULL, NULL, NULL);
if (status != ERROR_SUCCESS) {
RegCloseKey(key_handle);
std::string msg = "RegQueryInfoKey failed with error code: ";
msg.append(registry_key);
LOG(ERROR) << "ParseConfig::RegQueryInfoKey:: " << msg;
return StatusRecord{SQLStates::k_HY000(), msg};
}
Sections sections;
// List all the sections
for (int i = 0; i < num_sub_keys; i++) {
name_len = kMaxKeyLength;
status = RegEnumKeyEx(key_handle, i, subkey_name, &name_len, NULL, NULL,
NULL, NULL);
if (status == ERROR_SUCCESS) {
auto get_sections_response_status =
GetSectionWin(registry_key + "\\" + std::string(subkey_name));
if (!get_sections_response_status) {
LOG(ERROR) << "ParseConfig::GetSectionWin:: "
<< get_sections_response_status.GetStatusRecord().message;
return get_sections_response_status.GetStatusRecord();
}
auto get_sections_response = *get_sections_response_status;
sections[subkey_name] = *get_sections_response;
}
}
RegCloseKey(key_handle);
return std::make_shared<Sections>(sections);
}
// Helper function to create a static label
HWND CreateLabel(HWND parent, char const* text, int x, int y, int width,
int height, int id) {
return CreateWindowEx(0, "STATIC", text,
WS_VISIBLE | WS_CHILD | SS_LEFT | SS_NOTIFY, x, y,
width, height, parent, (HMENU)id, g_hDllInstance, NULL);
}
// Helper function to create an edit box
HWND CreateEditBox(HWND parent, int x, int y, int width, int height, int id) {
return CreateWindowEx(
0, "EDIT", "",
WS_TABSTOP | WS_VISIBLE | WS_CHILD | WS_BORDER | ES_LEFT | ES_AUTOHSCROLL,
x, y, width, height, parent, (HMENU)id, g_hDllInstance, NULL);
}
HWND CreateScrollableEditBox(HWND parent, int x, int y, int width, int height,
int id) {
HWND hwndEdit = CreateWindowEx(
0, "EDIT", "",
WS_TABSTOP | WS_VISIBLE | WS_CHILD | WS_BORDER | ES_LEFT | ES_MULTILINE |
ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL,
x, y, width, height, parent, (HMENU)id, g_hDllInstance, NULL);
// Attach the input subclass to handle VK_TAB and VK_ESCAPE
if (hwndEdit) {
SetWindowSubclass(hwndEdit, InputSubclassProc, 1, 0);
}
return hwndEdit;
}
// Helper function to create a combo box (dropdown)
HWND CreateComboBox(HWND parent, int x, int y, int width, int height, int id) {
HWND hwndCombo = CreateWindowEx(
0, "COMBOBOX", "",
WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | WS_HSCROLL | ES_LEFT |
ES_MULTILINE | ES_AUTOHSCROLL | ES_AUTOVSCROLL | CBS_DROPDOWN |
CBS_HASSTRINGS,
x, y, width, height, parent, (HMENU)id, g_hDllInstance, NULL);
return hwndCombo;
}
HWND CreateButton(HWND parent, char const* text, int x, int y, int width,
int height, int id) {
HWND hButton = CreateWindowEx(
0, "BUTTON", text, WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_FLAT, x, y,
width, height, parent, (HMENU)id, g_hDllInstance, NULL);
// Disable Windows theme to remove any rounding
if (hButton) {
SetWindowTheme(hButton, L"", L"");
}
return hButton;
}
// Helper function to create a checkbox
HWND CreateCheckBox(HWND parent, char const* text, int x, int y, int width,
int height, int id) {
return CreateWindowEx(
0, "BUTTON", text, WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_AUTOCHECKBOX,
x, y, width, height, parent, (HMENU)id, g_hDllInstance, NULL);
}
// Helper function to create a group box
HWND CreateGroupBox(HWND parent, char const* text, int x, int y, int width,
int height, int id) {
return CreateWindowEx(0, "BUTTON", text, WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
x, y, width, height, parent, (HMENU)id, g_hDllInstance,
NULL);
}
HWND CreateNumericEditBox(HWND parent, char const* text, int x, int y,
int width, int height, int id) {
HWND hEditBox = CreateWindowEx(
WS_EX_CLIENTEDGE, "EDIT", text,
WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_NUMBER |
ES_RIGHT, // ES_NUMBER restricts input to numbers
x, y, width, height, parent, (HMENU)id, g_hDllInstance, NULL);
if (hEditBox) {
SendMessage(hEditBox, WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT),
TRUE);
}
return hEditBox;
}
HWND CreateHyperlinkLabel(HWND parent, char const* text, int x, int y,
int width, int height, int id) {
HWND h_hyperlink =
CreateWindowEx(0, "STATIC", text, WS_CHILD | WS_VISIBLE | SS_NOTIFY, x, y,
width, height, parent, (HMENU)id, g_hDllInstance, NULL);
return h_hyperlink;
}
void ShowErrorWindow(HWND hwnd, std::string const message) {
MessageBoxA(hwnd, message.c_str(), "DSN Configuration Error",
MB_OK | MB_ICONWARNING);
}
extern "C" BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason,
LPVOID lpReserved) {
switch (ul_reason) {
case DLL_PROCESS_ATTACH:
g_hDllInstance = hModule;
_putenv_s("GRPC_DNS_RESOLVER", "native");
break;
}
return TRUE;
}
std::wstring GetModuleDirectory() {
HMODULE hModule = NULL;
if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCSTR>(&GetModuleDirectory),
&hModule)) {
return L"";
}
wchar_t dll_path[MAX_PATH];
if (GetModuleFileNameW(hModule, dll_path, MAX_PATH) == 0) {
return L"";
}
std::wstring path(dll_path);
size_t pos = path.find_last_of(L"\\/");
if (pos == std::wstring::npos) return L"";
return path.substr(0, pos); // directory only
}
void setWindowIcon(HWND hwnd) {
std::wstring dir = GetModuleDirectory();
if (dir.empty()) return;
// Compose icon path (e.g., DLL directory + "\\assets\\bq.ico")
std::wstring iconPath = dir + L"\\assets\\bq.ico";
HICON hIcon = (HICON)LoadImageW(NULL, iconPath.c_str(), IMAGE_ICON, 32, 32,
LR_LOADFROMFILE);
if (!hIcon) {
OutputDebugStringW(
(L"Failed to load icon at: " + iconPath + L"\n").c_str());
return;
}
SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
}
std::string GetRootsPemPath() {
std::wstring dir = GetModuleDirectory();
if (dir.empty()) return "";
std::wstring full_wpath = dir + L"\\assets\\roots.pem";
int size_needed = WideCharToMultiByte(CP_UTF8, 0, full_wpath.c_str(), -1,
nullptr, 0, nullptr, nullptr);
std::string utf8_path(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, full_wpath.c_str(), -1, &utf8_path[0],
size_needed, nullptr, nullptr);
if (!utf8_path.empty() && utf8_path.back() == '\0') {
utf8_path.pop_back();
}
return utf8_path;
}
LRESULT CALLBACK InputSubclassProc(HWND hwnd, UINT msg, WPARAM w_param,
LPARAM l_param, UINT_PTR sub_id,
DWORD_PTR ref_data) {
if (msg == WM_KEYDOWN) {
if (w_param == VK_ESCAPE) {
SendMessage(GetParent(hwnd), WM_CLOSE, 0, 0); // Close the parent dialog
return 0; // Mark message as handled
} else if (w_param == VK_TAB) {
// Move focus to next or previous control
BOOL shiftPressed = (GetKeyState(VK_SHIFT) & 0x8000);
HWND next = GetNextDlgTabItem(GetParent(hwnd), hwnd, shiftPressed);
if (next) SetFocus(next);
return 0; // Mark as handled to prevent tab character insertion
}
}
return DefSubclassProc(hwnd, msg, w_param, l_param);
}
LRESULT CALLBACK EditBlockSubclassProc(HWND hwnd, UINT msg, WPARAM w_param,
LPARAM l_param, UINT_PTR sub_id,
DWORD_PTR ref_data) {
switch (msg) {
case WM_CHAR: // block character input
case WM_PASTE:
case WM_CUT:
return 0; // block typing and clipboard actions
}
return DefSubclassProc(hwnd, msg, w_param, l_param);
}
LRESULT CALLBACK ComboBoxSubclassProc(HWND hwnd, UINT msg, WPARAM w_param,
LPARAM l_param, UINT_PTR sub_id,
DWORD_PTR ref_data) {
if (msg == WM_CTLCOLORLISTBOX) {
if (g_suppress_dropdown) {
SendMessage(hwnd, CB_SHOWDROPDOWN, FALSE, 0);
return (LRESULT)GetStockObject(WHITE_BRUSH);
}
}
if (msg == WM_KEYDOWN) {
if (w_param == VK_ESCAPE) {
SendMessage(GetParent(hwnd), WM_CLOSE, 0, 0);
return 0;
} else if (w_param == VK_RETURN) {
HWND h_ok = GetDlgItem(GetParent(hwnd), IDOK);
if (h_ok) SendMessage(GetParent(hwnd), WM_COMMAND, IDOK, (LPARAM)h_ok);
return 0;
}
}
return DefSubclassProc(hwnd, msg, w_param, l_param);
}
LRESULT CALLBACK CheckboxSubclassProc(HWND hwnd, UINT msg, WPARAM w_param,
LPARAM l_param, UINT_PTR sub_id,
DWORD_PTR ref_data) {
if (msg == WM_KEYDOWN && w_param == VK_ESCAPE) {
SendMessage(GetParent(hwnd), WM_CLOSE, 0, 0);
return 0;
}
return DefSubclassProc(hwnd, msg, w_param, l_param);
}
#else
StatusRecordOr<std::shared_ptr<Sections>> ParseConfig(
std::string const& file_path) {
std::ifstream is(file_path);
is.exceptions(std::ios::badbit); // Minimal error handling
Sections sections;
if (is.is_open()) {
std::string line;
std::string current_section_name;
while (getline(is, line)) {
Trim(line);
if (line.empty() || line.at(0) == ';' || line.at(0) == '#') {
// Blank lines and comment lines are ignored.
} else if (line.at(0) == '[' && line.back() == ']') {
// Section line.
line.erase(0, 1);
line.pop_back();
Trim(line);
current_section_name = line;
} else {
// Property line.
size_t pos = line.find_first_of('=');
std::string property = line.substr(0, pos);
Trim(property);
std::string value;
if (pos != std::string::npos) {
value = line.substr(pos + 1);
Trim(value);
}
if (!current_section_name.empty()) {
sections[current_section_name][property] = value;
}
}
}
return std::make_shared<Sections>(sections);
}
return std::make_shared<Sections>();
}
#endif //_WIN32
StatusRecordOr<Section> ParseConnectionString(std::string& str) {
LOG(INFO) << "ParseConnectionString:: Received connection string: " << str
<< std::endl;
Section section;
std::vector<std::string> splits = Split(str, ";");
for (std::string& property : splits) {
Trim(property);
if (property.empty()) {
continue;
}
std::vector<std::string> property_splits = Split(property, "=", 2);
if (property_splits.size() < 2) {
LOG(ERROR) << "ParseConnectionString:: Invalid Connection String part: "
<< property;
return StatusRecord{SQLStates::k_HY000(), "Invalid Connection String"};
}
std::string field = property_splits[0];
std::string value = Join(property_splits, "", 1);
Trim(field);
Trim(value);
// Remove enclosing curly braces if they exist
if (!value.empty() && value.front() == '{' && value.back() == '}') {
value = value.substr(1, value.size() - 2);
}
if (field.empty() || value.empty()) {
continue;
}
if (!section.count(field)) {
section[field] = value;
}
}
return section;
}
std::string GetPathToOdbcIni() {
#ifdef _WIN32
// 64-bit
absl::optional<std::string> path = "SOFTWARE\\ODBC\\ODBC.INI";
#ifndef _WIN64
// 32-bit
path = "SOFTWARE\\WOW6432Node\\ODBC\\ODBC.INI";
#endif // _WIN64
if (path) {
return *path;
}
#else
absl::optional<std::string> path = google::cloud::internal::GetEnv("ODBCINI");
if (path) {
return *path;
}
absl::optional<std::string> home = google::cloud::internal::GetEnv("HOME");
if (home) {
return *home + "/.odbc.ini";
}
#endif // _WIN32
return "";
}
std::string GetOdbcTraceConfigPath() {
#ifndef _WIN32
absl::optional<std::string> path =
google::cloud::internal::GetEnv("GOOGLEBIGQUERYODBCINI");
if (path) {
return *path;
}
// Default to using ~ path directly
return "/etc/googlebigqueryodbc.ini";
#else
return k_trace_reg_path;
#endif // _WIN32
}
std::vector<std::string> SplitTableTypes(std::string const& table_types) {
std::vector<std::string> types = Split(table_types, ",");
for (auto& type : types) {
Trim(type);
if (type[0] == '\'' && type[type.length() - 1] == '\'') {
type = type.substr(1, type.length() - 2);
Trim(type);
}
}
return types;
}
odbc_internal::StatusRecordOr<std::string> Utf16ToUtf8(
std::wstring const& utf_16_str) {
if (utf_16_str.empty()) {
return std::string();
}
#ifdef _WIN32
// https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-widechartomultibyte
int utf8Length = WideCharToMultiByte(CP_UTF8, 0, utf_16_str.c_str(), -1, NULL,
0, NULL, NULL);
if (utf8Length == 0) {
LOG(ERROR) << "Utf16ToUtf8:: Error determining buffer size while "
"converting wstring to string";
return StatusRecord{
SQLStates::k_HY000(),
"Error determining buffer size while converting wstring to string"};
}
if (sizeof(SQLWCHAR) == 2) {
utf8Length = utf8Length * sizeof(SQLWCHAR);
}
std::string utf8Str(utf8Length, 0);
// https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-widechartomultibyte
int result = WideCharToMultiByte(CP_UTF8, 0, utf_16_str.c_str(), -1,
&utf8Str[0], utf8Length, NULL, NULL);
if (result == 0) {
LOG(ERROR) << "Utf16ToUtf8:: Error while converting wstring to string";
return StatusRecord{SQLStates::k_HY000(),
"Error while converting wstring to string"};
}
return utf8Str;
#else
iconv_t cd = iconv_open("UTF-8", kFromCode.c_str());
int errorno = -1;
int* errorptr = &errorno;
if (cd == reinterpret_cast<iconv_t>(errorptr)) {
return StatusRecord{
SQLStates::k_HY000(),
"iconv_open failed while converting wstring to string: " +
std::string(strerror(errno))};
}
std::vector<char> inbuf(
reinterpret_cast<char const*>(utf_16_str.data()),
reinterpret_cast<char const*>(utf_16_str.data() + utf_16_str.length()));
size_t inbytesleft = inbuf.size();
size_t outbytesleft = inbytesleft * 4; // Allocate more space for utf8 output
std::string utf8str(outbytesleft, '\0');
char* inptr = inbuf.data();
char* outptr = utf8str.data();
size_t res = iconv(cd, &inptr, &inbytesleft, &outptr, &outbytesleft);
if (res == static_cast<size_t>(-1)) {
iconv_close(cd);
return StatusRecord{SQLStates::k_HY000(),
"iconv16 failed while converting wstring to string " +
std::string(strerror(errno))};
}
iconv_close(cd);
utf8str.resize(outptr - utf8str.data());
return utf8str;
#endif
}
odbc_internal::StatusRecordOr<std::wstring> Utf8ToUtf16(
std::string_view utf_8_str) {
if (utf_8_str.empty()) {
return std::wstring();
}
#ifdef _WIN32
// https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar
int utf16Length =
MultiByteToWideChar(CP_UTF8, 0, utf_8_str.data(),
static_cast<int>(utf_8_str.length()), NULL, 0);
if (utf16Length == 0) {
return StatusRecord{
SQLStates::k_HY000(),
"Error determining buffer size while converting string to wstring"};
}
std::wstring utf16Str(utf16Length, 0);
// https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar
int result = MultiByteToWideChar(CP_UTF8, 0, utf_8_str.data(),
static_cast<int>(utf_8_str.length()),
&utf16Str[0], utf16Length);
if (result == 0) {
return StatusRecord{SQLStates::k_HY000(),
"Error while converting string to wstring"};
}
// MultiByteToWideChar was called with an explicit input length, so
// utf16Length is the character count without a null terminator and
// wstring::size() already reflects the actual character count,
// matching the Linux iconv path behaviour.
return utf16Str;
#else
iconv_t cd = iconv_open(kFromCode.c_str(), "UTF-8");
int errorno = -1;
int* errorptr = &errorno;
if (cd == reinterpret_cast<iconv_t>(errorptr)) {
return StatusRecord{
SQLStates::k_HY000(),
"iconv_open failed while converting string to wstring " +
std::string(strerror(errno))};
}
// Use string length for input byte count
size_t inbytesleft = utf_8_str.length();
// Allocate more space for the output buffer
size_t outbytesleft = inbytesleft * sizeof(wchar_t);
std::wstring utf16str(outbytesleft + sizeof(wchar_t), L'\0');
char* inbuf = const_cast<char*>(utf_8_str.data());
char* outbuf = reinterpret_cast<char*>(utf16str.data());
size_t res = iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
if (res == static_cast<size_t>(-1)) {
iconv_close(cd);
return StatusRecord{SQLStates::k_HY000(),
"iconv8 failed while converting string to wstring " +
std::string(strerror(errno))};
}
iconv_close(cd);
// Resize the output string to the actual converted size. No trailing NUL is
// appended: wstring::size() is the character count, matching the Windows
// MultiByteToWideChar path above. Callers own their own NUL termination.
utf16str.resize((outbuf - reinterpret_cast<char*>(utf16str.data())) /
sizeof(wchar_t));
return utf16str;
#endif
}
odbc_internal::StatusRecordOr<std::string> BqConvertSQLWCHARToString(
SQLWCHAR const* in_str, SQLINTEGER in_str_len) {
if (in_str == nullptr) {
return StatusRecord{SQLStates::k_HY000(), "in_str string is empty/Null"};
}
#if defined(_WIN32)
if (in_str[0] == '\0') {
return std::string();
}
if (in_str_len == SQL_NTS || in_str_len == 0) {
in_str_len =
static_cast<SQLINTEGER>(std::char_traits<SQLWCHAR>::length(in_str));
}
std::wstring wstr(in_str, in_str + in_str_len);
return Utf16ToUtf8(wstr);
#else
switch (GetEffectiveWireEncoding()) {
case WireEncoding::kUtf32Le:
case WireEncoding::kDefault: {
auto const* utf32 = reinterpret_cast<uint32_t const*>(in_str);
if (utf32[0] == 0) {
return std::string();
}
SQLINTEGER count = in_str_len;
if (count == SQL_NTS || count == 0) {
count = 0;
while (utf32[count] != 0) ++count;
}
std::wstring wstr;
wstr.reserve(count);
for (SQLINTEGER i = 0; i < count; ++i) {
wstr.push_back(static_cast<wchar_t>(utf32[i]));
}
return Utf16ToUtf8(wstr);
}
case WireEncoding::kUtf16Le: {
auto const* utf16 = reinterpret_cast<uint16_t const*>(in_str);
if (utf16[0] == 0) {
return std::string();
}
SQLINTEGER count = in_str_len;
if (count == SQL_NTS || count == 0) {
count = 0;
while (utf16[count] != 0) ++count;
}
std::wstring wstr;
wstr.reserve(count);
for (SQLINTEGER i = 0; i < count; ++i) {
wstr.push_back(static_cast<wchar_t>(utf16[i]));
}
return Utf16ToUtf8(wstr);
}
case WireEncoding::kUtf8: {
auto const* bytes = reinterpret_cast<char const*>(in_str);
if (bytes[0] == '\0') {
return std::string();
}
if (in_str_len == SQL_NTS || in_str_len == 0) {
return std::string(bytes);
}
return std::string(bytes, in_str_len);
}
}
return std::string();
#endif
}
bool IsDiagIdentifierString(SQLSMALLINT DiagIdentifier) {
switch (DiagIdentifier) {
case SQL_DIAG_DYNAMIC_FUNCTION:
case SQL_DIAG_CLASS_ORIGIN:
case SQL_DIAG_CONNECTION_NAME:
case SQL_DIAG_MESSAGE_TEXT:
case SQL_DIAG_SERVER_NAME:
case SQL_DIAG_SQLSTATE:
case SQL_DIAG_SUBCLASS_ORIGIN:
return true;
break;
default:
return false;
break;
}
}
StatusRecordOr<SQLUINTEGER> ParseStringToInteger(std::string const& input) {
SQLUINTEGER value = 0;
for (char c : input) {
if (!std::isdigit(c)) {
return StatusRecord{SQLStates::k_HY000(),
"Input value must be an integer"};
}
int digit = c - '0';
if (value > (std::numeric_limits<SQLUINTEGER>::max() - digit) / 10) {
return StatusRecord{SQLStates::k_HY000(),
"Input value value is too large"};
}
value = value * 10 + digit;
}
return value; // success
}
bool IsFieldIdentifierString(SQLSMALLINT FieldIdentifier) {
switch (FieldIdentifier) {
case SQL_DESC_BASE_COLUMN_NAME:
case SQL_DESC_BASE_TABLE_NAME:
case SQL_DESC_CATALOG_NAME:
case SQL_DESC_LABEL:
case SQL_DESC_LITERAL_PREFIX:
case SQL_DESC_LITERAL_SUFFIX:
case SQL_DESC_LOCAL_TYPE_NAME:
case SQL_DESC_NAME:
case SQL_DESC_SCHEMA_NAME:
case SQL_DESC_TABLE_NAME:
case SQL_DESC_TYPE_NAME:
return true;
break;