-
Notifications
You must be signed in to change notification settings - Fork 0
/
UIHandle.cpp
953 lines (765 loc) · 27.9 KB
/
UIHandle.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
#include "UIHandle.h"
UIHandle::UIHandle()
{
/* apply color for logs*/
spdlog::stdout_color_mt("UIHandle");
std::ifstream jsonFileStream("./credentials.json");
if (!jsonFileStream.is_open())
{
spdlog::error("missing .json file with credentials");
}
else
{
nlohmann::json jsonData = nlohmann::json::parse(jsonFileStream);
// Process the JSON data
std::vector<UICredential> credentialsList;
for (const auto& entry : jsonData) {
UICredential credentials;
credentials.ui_domain = entry["domain"];
credentials.ui_login = entry["login"];
credentials.ui_password = entry["password"];
credentialsList.push_back(credentials);
}
//TODO:
/* initialize domains credentials*/
ui_init_dict(credentialsList);
}
#ifdef _DEBUG
spdlog::set_level(spdlog::level::debug);
#else
spdlog::set_level(spdlog::level::error);
#endif
/* CoInitializeEx() Initializes the COM library for use by the calling thread,
sets the thread's concurrency model, and creates a new apartment for the thread
https://learn.microsoft.com/en-us/windows/win32/api/objbase/ne-objbase-coinit says that
for GUI I should use COINIT_APARTMENTTHREADED instead COINIT_MULTITHREADED*/
/* CoCreateInstance() create an instance of a COM class identified by its CLSID (Class Identifier).
CLSIDs uniquely identify COM classes and are typically stored in the Windows registry. */
if (CoInitializeEx(nullptr, COINIT_MULTITHREADED) == S_OK && SUCCEEDED(uia.CoCreateInstance(CLSID_CUIAutomation)))
{
spdlog::debug("Instance of UIAutomation successfully created");
}
else
{
spdlog::error("Failed to Create instance of UIAutomation");
}
}
UIHandle::~UIHandle()
{
/* stop wakeup thread if pending */
if (wakeup_t.joinable())
wakeup_t.join();
/* stop SerialCom callback thread*/
if (callback_t.joinable())
callback_t.join();
/* release smart pointer*/
uia.Release();
/* Closes the COM library on the current thread, unloads all DLLs loaded by the thread,
frees any other resources that the thread maintains, and forces all RPC connections on the thread to close. */
CoUninitialize();
/* release domains credentials*/
release_dict();
}
void UIHandle::prepare_notification(UI_ENUM mode,std::string domain)
{
/* stop SerialCom callback thread if pending */
if (callback_t.joinable())
callback_t.join();
/* create acknowledge message*/
int len = create_message(mode, domain);
/* start thread for SerialCom callback*/
callback_t = std::thread(callback, telegram, len);
}
bool UIHandle::add_callback(SerialComCb callback)
{
/* assign to class callback*/
this->callback = callback;
return true;
}
int UIHandle::create_message(UI_ENUM mode, std::string domain)
{
spdlog::debug("elements to create message: {} and {}", (int)mode, domain.c_str());
/* pointer for telegram*/
uint8_t* tmp = telegram;
/* mode int to char and move pointer*/
*tmp++ = static_cast<uint8_t>(mode + '0');
/* domain string has at least one character*/
if (domain.size())
{
/* insert delimiter and move pointer forward*/
*tmp++ = ',';
/* copy domain name into telegram*/
for (size_t i = 0; i < domain.size(); i++)
*tmp++ = domain[i];
/* insert ending null character */
*tmp = '\0';
}
spdlog::debug("created msg: {}", reinterpret_cast<char*>(telegram));
/* return difference of pointers*/
return (tmp - telegram);
}
void UIHandle::process_data(std::string authorization)
{
//spdlog::debug("received telegram from SERIALCOM:{} with size: {}", reinterpret_cast<char*>(buffer), size);
//reinterpret uint8_t* to char* is followed by convert the char* to std::string
//std::string input(reinterpret_cast<const char*>(buffer),size);
//release pointer to credentials
//free(buffer);
spdlog::debug("received telegram from SERIALCOM:{} ", authorization);
//spdlog::debug("created string input: {}", input);
// Regular expression pattern to match words between commas and first digit.
std::regex pattern("^(\\d)(?:,([^,\\s]+))?(?:,([^,\\s]+))?(?:,([^,\\s]+))?$");
/* check if pattern covers input */
if (std::regex_match(authorization, pattern))
{
std::stringstream ss(authorization);
std::string word;
std::vector <std::string> telegram_part;
/* split words in match*/
while (std::getline(ss, word, ','))
{
spdlog::debug("new word in regex found : {}", word);
/* add new element to list */
telegram_part.push_back(word);
}
spdlog::debug("received correct telegram {0}, with {1} element{2}", authorization, telegram_part.size(), (telegram_part.size() > 1) ? "s" : "");
spdlog::debug("regex recognized following parts:");
for (const auto& i :telegram_part)
spdlog::debug("element: {}",i);
/* according regex pattern 0 element is a digit example: char '2' -> int 50. 50-48('0')=2*/
UI_ENUM mode = static_cast<UI_ENUM>(telegram_part[0][0]-'0');
/* Start initialization if only if specific mode has been received*/
if (mode == UI_DOMAIN or
mode == UI_LOGIN or
mode == UI_PASSWORD or
mode == UI_LOGPASS)
{
/* start initialization*/
if (!initialize_instance())
{
/* initialization failed*/
prepare_notification(UI_FAIL, "");
spdlog::error("incomming message dropped without processing");
return;
}
}
spdlog::debug("initialization done");
switch (mode)
{
case UI_DOMAIN :
spdlog::debug("telegram requests UI_DOMAIN");
/* stop wakeup thread if pending */
if (wakeup_t.joinable())
wakeup_t.join();
/* start thread for wakeup functionality*/
wakeup_t = std::thread(&UIHandle::look_for_web_field,this);
break;
case UI_LOGIN:
case UI_PASSWORD:
spdlog::debug("telegram requests {}", (mode == UI_LOGIN) ? "UI_LOGIN" : "UI_PASSWORD");
/* following telegram should contain 3 elements in telegram*/
if (telegram_part.size() == 3)
{
/* enter found credential*/
if (credential(mode, telegram_part[1].c_str(), telegram_part[2].c_str()))
{
/* press enter*/
accept_credenetial();
prepare_notification(UI_DONE, telegram_part[1]);
}
else
{
spdlog::error("failed to enter {} credential", (mode == UI_LOGIN) ? "UI_LOGIN" : "UI_PASSWORD");
prepare_notification(UI_FAIL, telegram_part[1]);
}
}
else
{
spdlog::error("wrong amount of elements regex found :{} ", telegram_part.size());
}
break;
case UI_LOGPASS:
spdlog::debug("telegram requests UI_LOGPASS");
if (telegram_part.size() == 4)
{
/* enter found login*/
if (credential(UI_LOGIN, telegram_part[1].c_str(), telegram_part[2].c_str()))
{
/* enter found password*/
if (credential(UI_PASSWORD, telegram_part[1].c_str(), telegram_part[3].c_str()))
{
/* press enter*/
accept_credenetial();
prepare_notification(UI_DONE, telegram_part[1]);
}
else
{
spdlog::error("failed to enter UI_PASSWORD credential");
prepare_notification(UI_FAIL, telegram_part[1]);
}
}
else
{
spdlog::error("failed to enter UI_LOGIN credential");
prepare_notification(UI_FAIL, telegram_part[1]);
}
}
else
{
spdlog::error("wrong amount of elements regex found :{} ", telegram_part.size());
}
break;
case UI_DONE:
break;
case UI_NEW_CREDENTIAL:
break;
case UI_ERASE:
break;
case UI_MISSED:
spdlog::debug("telegram requests UI_MISSED");
break;
default:
spdlog::error("unknown mode received {}", (int)mode);
break;
}
}
else
{
spdlog::error("unknown message template has been received {}", authorization);
}
return;
}
void UIHandle::look_for_web_field()
{
/* time stamp now*/
auto startTime = std::chrono::high_resolution_clock::now();
/* result of function invocation*/
ret_url res = { nullptr,1 };
while (true)
{
// Calculate the elapsed time
auto currentTime = std::chrono::high_resolution_clock::now();
auto elapsedTime = std::chrono::duration_cast<std::chrono::seconds>(currentTime - startTime).count();
// Check if the loop duration is over (5 seconds)
if (elapsedTime >= 5)
{
spdlog::error(" searching url timeout");
return;
}
/* search for known website*/
res = find_url("");
/* fatal error*/
if (!res.val)
return;
else if (res.val and res.domain)
{
/* found familiar domain*/
/* check what elements are available on site*/
UI_ENUM element = which_element(res.domain);
if (element not_eq UI_ENUM::UI_UNKNOWN)
{;
/* request for credentials*/
prepare_notification(element, res.domain);
return;
}
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
bool UIHandle::initialize_instance()
{
HWND hwnd;
auto startTime = std::chrono::high_resolution_clock::now();
while (true)
{
// Calculate the elapsed time
auto currentTime = std::chrono::high_resolution_clock::now();
auto elapsedTime = std::chrono::duration_cast<std::chrono::seconds>(currentTime - startTime).count();
//printf("elapsedTime :%d\n",elapsedTime);
/* through 10 seconds, initialization cannot be finished*/
if (elapsedTime >= 10)
{
spdlog::error("initialization timeout");
return false;
}
/* handle is not nullptr*/
if (window_handle)
{
/* Window has title and is not closed/minimized */
if (IsWindowVisible(window_handle) && !IsIconic(window_handle) && GetWindowTextLength(window_handle) > 0)
{
spdlog::debug("elapsedTime: {}seconds", elapsedTime);
int c = GetWindowTextLength(window_handle);
//printf("%d\n", c);
LPWSTR pszMem = (LPWSTR)malloc(sizeof(LPWSTR) * (c + 1));
GetWindowText(window_handle, pszMem, c + 1);
/* null terminator; GetWindowText doesn't attach it*/
pszMem[c] = L'\0';
//TODO: implement spdlog for LPWSTR
wprintf(L"Window Text: %s", pszMem);
free(pszMem);
break;
}
}
HWND child_handl = nullptr; // always nullptr
/* Windows API function used to retrieve a handle to a child window */
/* check if some window has className "Chrome_WidgetWin_1"*/
window_handle = FindWindowEx(nullptr, child_handl, L"Chrome_WidgetWin_1", nullptr);
if (!window_handle)
{
spdlog::error("handle from FindWindowEx is nullptr");
return false;
}
}
spdlog::debug("root pointer :{}, uia pointer :{}", static_cast<void*>(root.p), static_cast<void*>(uia.p));
root = nullptr;
if SUCCEEDED(uia->ElementFromHandle(window_handle, &root))
{
return true;
}
return false;
}
bool UIHandle::accept_credenetial()
{
INPUT input[2] = { INPUT_KEYBOARD };
input[0].ki.wVk = VK_RETURN;
input[1] = input[0];
input[1].ki.dwFlags |= KEYEVENTF_KEYUP;
UINT uSent = SendInput(ARRAYSIZE(input), input, sizeof(INPUT));
return 0;
}
char* UIHandle::domain_recognition(const char* url,const char* req_dom)
{
char* domain=nullptr;
int first_let = 0;
int last_let = 0;
/*"com","net","pl","org","gov","de"
/*"stackoverflow","yandex","gmail","youtube","github","linkedin"
domain search*/
bool first_found = false;
bool hit = false;
for (int i = 0; (url[i] != '/' || !first_found) && url[i] != '\0' && !hit; i++)
{
//found dot on the way
if (url[i] == '.' || url[i] == '/')
{
if (url[i] == '/' && not first_found)
{
//https://
i++;
last_let = i;
continue;
}
if (last_let != first_let)
first_let = last_let + 1;
last_let = i;
char* page = _strdup(&url[first_let]);
page[last_let - first_let] = '\0';
spdlog::debug("{}", page);
if (ui_lookup(page))
{
/* requested domain page has some characters*/
if (req_dom!="")
{
/* compare requested domain with recognized alias of page*/
if (strcmp(page, req_dom)==0)
{
hit = true;
domain = page;
};
}
else
{
hit = true;
domain = page;
}
spdlog::debug("hit hashtable");
}
else
{
/* release memory if we don't have such domain in dictionary*/
free(page);
page = nullptr;
spdlog::debug("miss hashtable");
}
//printf("%s\n", strcmp(page, "yandex")==0 ? "success" : "miss");
first_found = true;
}
}
return domain;
}
ret_url UIHandle::find_url(const char* req_dom)
{
constexpr ret_url ERR{ nullptr, false };
//result value (default value, not found, but correctly finished)
ret_url res{ nullptr,true };
// The root window has several childs,
// one of them is a "pane" named "Google Chrome"
// This contains the toolbar. Find this "Google Chrome" pane:
CComPtr<IUIAutomationElement> pane;
CComPtr<IUIAutomationCondition> pane_cond;
uia->CreatePropertyCondition(UIA_ControlTypePropertyId,
CComVariant(UIA_PaneControlTypeId), &pane_cond);
CComPtr<IUIAutomationElementArray> arr;
if FAILED(root->FindAll(TreeScope_Children, pane_cond, &arr))
{
spdlog::error("root cannot find correct element");
return (res=ERR);
}
int count = 0;
arr->get_Length(&count);
spdlog::debug("editable_length:{}", count);
for (int i = 0; i < count; i++)
{
CComBSTR name;
if SUCCEEDED(arr->GetElement(i, &pane))
{
pane->get_CurrentClassName(&name);
wprintf(L"%ls\n", (wchar_t*)name);
uint8_t length = SysStringLen(name);
SysFreeString(name);
if (!length) //not correct element had length 23 "Intermediate D3D Window"; get_CurrentName gives nothing :(C
break;
}
pane.Release();
}
if (!pane)
{
spdlog::error("pointer error: pane is nullptr");
return (res = ERR);
}
//look for first UIA_EditControlTypeId under "Google Chrome" pane
CComPtr<IUIAutomationElement> url;
CComPtr<IUIAutomationCondition> url_cond;
uia->CreatePropertyCondition(UIA_ControlTypePropertyId,
CComVariant(UIA_EditControlTypeId), &url_cond);
if FAILED(pane->FindFirst(TreeScope_Descendants, url_cond, &url))
{
spdlog::error("pane cannot find correct element");
return (res = ERR);
}
if (!url)
{
spdlog::error("pointer error: url is nullptr");
return (res = ERR);
}
//CComPtr<IUIAutomationElementArray> url;
//if FAILED(pane->FindAll(TreeScope_Descendants, url_cond, &url))
// return false;
//count = 0;
//url->get_Length(&count);
//printf("editable_length:%d\n", count);
//for (int i = 0; i < count; i++)
//{
// CComBSTR name;
// if SUCCEEDED(url->GetElement(i, &pane))
// {
// pane->get_CurrentClassName(&name);
// wprintf(L"%ls\n", (wchar_t*)name);
// uint8_t length = SysStringLen(name);
// SysFreeString(name);
// if (!length) //not correct element had length 23 "Intermediate D3D Window"; get_CurrentName gives nothing :(C
// break;
// }
// pane.Release();
//}
//get value of `url`
CComVariant var;
//if FAILED(pane->GetCurrentPropertyValue(UIA_ValueValuePropertyId, &var))
// return false;
//TODO: here url is null pointer when brovser is not in front or minimized (but only on first shot 😐)
if FAILED(url->GetCurrentPropertyValue(UIA_ValueValuePropertyId, &var))
{
spdlog::error("url cannot GetCurrentPropertyValue ");
return (res = ERR);
}
if (!var.bstrVal)
{
spdlog::error("Variant string has nullpointer");
return (res = ERR);
}
wprintf(L"find_url: %s\n", var.bstrVal);
int length = SysStringLen(var.bstrVal);
spdlog::debug("{}", length);
size_t t;
char* mbstring = (char*)malloc(length + 1);
wcstombs_s(&t, mbstring, length + 1, var.bstrVal, length);
spdlog::debug("converted string: {} size is: {}", mbstring, t);
res.domain = domain_recognition(mbstring,req_dom);
free(mbstring);
//set new address ...
IValueProvider* pattern = nullptr;
//if (FAILED(pane->GetCurrentPattern(UIA_ValuePatternId, (IUnknown**)&pattern)))
// return false;
if (FAILED(url->GetCurrentPattern(UIA_ValuePatternId, (IUnknown**)&pattern)))
{
spdlog::error("url cannot GetCurrentPattern ");
return (res = ERR);
}
//pattern->SetValue(L"google.com");
pattern->Release();
return res;
}
CComPtr<IUIAutomationElement> UIHandle::find_element(UI_ENUM ui, const char* domain)
{
// The root window has several childs,
// one of them is a "pane" named "Google Chrome"
// This contains the toolbar. Find this "Google Chrome" element:
CComPtr<IUIAutomationElement> element;
CComPtr<IUIAutomationCondition> pane_cond;
CComVariant var;
HRESULT res;
std::shared_ptr<ui_nlist> map_entry = ui_lookup(domain);
if (!map_entry)
{
spdlog::error("shared_ptr<ui_nlist> allocation error: map_entry is nullptr");
return nullptr;
}
/* default property for searching datafield*/
PROPERTYID property = UIA_AutomationIdPropertyId;
/* request for login field*/
if (ui == UI_ENUM::UI_LOGIN)
{
var.bstrVal = SysAllocString(CA2W(map_entry->defn.ui_login.c_str()));
wprintf(L"allocated String: %ls\n", var.bstrVal);
var.vt = VT_BSTR;
if (!var.bstrVal)
{
spdlog::error("string allocation error: var.bstrVal is nullptr");
return nullptr;
}
}
/* request for password field*/
else if (ui == UI_ENUM::UI_PASSWORD)
{
spdlog::debug("password property");
var.boolVal = VARIANT_TRUE;
var.vt = VT_BOOL;
property = UIA_IsPasswordPropertyId;
}
/* wrong request*/
else
{
spdlog::error("Wrong UI_ENUM ");
return nullptr;
}
res = uia->CreatePropertyCondition(property, var, &pane_cond);
if FAILED(res)
{
spdlog::error("#### condition property creation error: CreatePropertyCondition() returns %08x \n", res);
pane_cond.Release();
return nullptr;
}
if (ui == UI_ENUM::UI_LOGIN)
{ /*release memory if has been used*/
SysFreeString(var.bstrVal);
}
res = root->FindFirst(TreeScope_Descendants, pane_cond, &element);
if FAILED(res)
{
spdlog::error("#### finding error: FindFirst() returns %08x \n", res);
pane_cond.Release();
return nullptr;
}
if (!element)
{
spdlog::error("#### element allocation error: element is nullptr \n");
return nullptr;
}
pane_cond.Release();
CComBSTR name;
element->get_CurrentAutomationId(&name);
wprintf(L"name:%ls\n", (wchar_t*)name);
SysFreeString(name);
spdlog::debug("[{}] found element address:{}", std::string(__FUNCTION__), static_cast<void*>(element));
return element;
}
UI_ENUM UIHandle::which_element(const char* domain)
{
// The root window has several childs,
// one of them is a "pane" named "Google Chrome"
// This contains the toolbar. Find this "Google Chrome" element:
UI_ENUM ret_val= UI_ENUM::UI_UNKNOWN;
std::shared_ptr<ui_nlist> map_entry = ui_lookup(domain);
if (!map_entry)
{
spdlog::error("#### shared_ptr<ui_nlist> allocation error: map_entry is nullptr \n");
return UI_ENUM::UI_UNKNOWN;
}
/* currently considered field UI_ENUM*/
int ui;
/* search for first available field Login or Password*/
for ( ui= UI_ENUM::UI_LOGIN; ui <= UI_ENUM::UI_PASSWORD; ui++)
{
HRESULT res;
CComVariant var;
PROPERTYID property;
if (ui == UI_ENUM::UI_LOGIN)
{
var.bstrVal = SysAllocString(CA2W(map_entry->defn.ui_login.c_str()));
wprintf(L"allocated String: %ls\n", var.bstrVal);
var.vt = VT_BSTR;
property = UIA_AutomationIdPropertyId;
if (!var.bstrVal)
{
spdlog::error("#### string allocation error: var.bstrVal is nullptr \n");
continue;
}
}
else if (ui == UI_ENUM::UI_PASSWORD)
{
spdlog::debug("password property\n");
var.boolVal = VARIANT_TRUE;
var.vt = VT_BOOL;
property = UIA_IsPasswordPropertyId;
}
/* condition to find UI Element*/
CComPtr<IUIAutomationCondition> pane_cond;
//UIA_HasKeyboardFocusPropertyId
res = uia->CreatePropertyCondition(property, var, &pane_cond);
if FAILED(res)
{
printf("#### condition property creation error: CreatePropertyCondition() returns %08x \n", res);
pane_cond.Release();
/*BSTR has been used for UI_LOGIN */
if (ui == UI_ENUM::UI_LOGIN)
SysFreeString(var.bstrVal);
continue;
}
if (ui == UI_ENUM::UI_LOGIN)
{ /*release memory if has been used*/
SysFreeString(var.bstrVal);
}
/* Login/Password field*/
CComPtr<IUIAutomationElement> element;
res = root->FindFirst(TreeScope_Descendants, pane_cond, &element);
if FAILED(res)
{
spdlog::error("#### finding error: FindFirst() returns %08x \n", res);
pane_cond.Release();
continue;
}
if (!element)
{
spdlog::error("#### element allocation error: element is nullptr \n");
continue;
}
pane_cond.Release();
CComBSTR name;
element->get_CurrentAutomationId(&name);
wprintf(L"name:%ls\n", (wchar_t*)name);
SysFreeString(name);
spdlog::debug("{}", static_cast<void*>(element));
//var.vt = VT_BSTR;
//TODO: func says that fields are empty but seems to be differently
/* check if field is filled out or empty*/
if FAILED(element->GetCurrentPropertyValue(UIA_ValueValuePropertyId, &var))
{
printf("#### current property value error: GetCurrentPropertyValue() returns %08x \n", res);
continue;
}
if (!var.bstrVal)
{
printf("#### element allocation error: element is nullptr \n");
continue;
}
wprintf(L"content of field: %s\n", var.bstrVal);
/* field is available to insert credential */
if (/* var.bstrVal[0] == L'\0' && */ ui == UI_ENUM::UI_LOGIN ||
ui == UI_ENUM::UI_PASSWORD)
{
/* UI_LOGIN already stored in ret_val -> BOTH fields available */
if (ret_val== UI_ENUM::UI_LOGIN)
ret_val = UI_ENUM::UI_LOGPASS;
/* save found UI*/
else
ret_val = static_cast<UI_ENUM>(ui);
}
SysFreeString(var.bstrVal);
element.Release();
}
return ret_val;
}
bool UIHandle::credential(UI_ENUM ui_mode, const char* domain, const char* credential)
{
ret_url url = find_url(domain);
if (!url.domain)
{
spdlog::error("#### finding requested url error");
return false;
}
CComPtr<IUIAutomationElement> elem = find_element(ui_mode, domain);
if (!elem)
{
spdlog::error("#### element finding error: {} for [{}] domain has not been found \n", (ui_mode == 1) ? "login" : "password", domain);
return false;
}
spdlog::debug("[{}] found element address:{}", std::string(__FUNCTION__), static_cast<void*>(elem));
CComBSTR name;
elem->get_CurrentAutomationId(&name);
wprintf(L"name:%ls\n", (wchar_t*)name);
SysFreeString(name);
CComVariant var;
if FAILED(elem->GetCurrentPropertyValue(UIA_ValueValuePropertyId, &var))
return false;
if (!var.bstrVal)
return false;
wprintf(L"content: %s\n", var.bstrVal);
SysFreeString(var.bstrVal);
int len = (int)strlen(credential);
wchar_t* w_text = (wchar_t*)malloc(sizeof(wchar_t) * (len + 1));
size_t t;
errno_t res = (mbstowcs_s(&t, w_text, len + 1, credential, len));
if (res)
{
spdlog::error("### conversion error: mbstowcs_s() returns {} ", res);
return false;
}
spdlog::debug("converted characters:{}", t);
wprintf(L"%s\n", w_text);
IValueProvider* pattern = nullptr;
if (FAILED(elem->GetCurrentPattern(UIA_ValuePatternId, (IUnknown**)&pattern)))
return false;
if (!pattern)
{
spdlog::error("### pointer error: pattern is nullptr \n");
return false;
}
pattern->SetValue(w_text);
//pattern->get_Value(&var.bstrVal);
if FAILED(elem->GetCurrentPropertyValue(UIA_ValueValuePropertyId, &var))
{
spdlog::error("### GetCurrentPropertyValue error: cannot check inserted credential \n");
return false;
}
if (!var.bstrVal)
{
spdlog::error("### string allocation memory error: !var.bstrVal is nullptr \n");
return false;
}
wprintf(L"inserted content: %s\n", var.bstrVal);
if (w_text != var.bstrVal)
{
spdlog::error("### set text is not same like get \n");
//TODO: return fault if texts are not the same
//return false;
}
SysFreeString(var.bstrVal);
// Check if the element HasKeyboardFocus property
VARIANT_BOOL hasKeyboardFocus;
if FAILED(elem->GetCurrentPropertyValue(UIA_HasKeyboardFocusPropertyId, &var))
{
spdlog::error("### GetCurrentPropertyValue error: cannot check if element HasKeyboardFocus\n");
//return false;
}
if (var.boolVal == VARIANT_TRUE)
spdlog::debug("The element has keyboard focus.");
else
spdlog::debug("The element does not have keyboard focus.");
pattern->Release();
free(w_text);
//SysFreeString(var.bstrVal);
elem.Release();
spdlog::debug("finished succesfully\n");
return true;
}