1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980 |
- #include "stdafx.h"
- #include "FreeRDPWrapFSM.h"
- #include "Common.h"
- #include "base64.h"
- #include "sm4.h"
- #include "AccountManage.h"
- #include "RDPWInst.h"
- #include <TlHelp32.h>
- #include "fileutil.h"
- #include <userenv.h>
- #include <WtsApi32.h>
- #include <Psapi.h>
- #include <tchar.h>
- #include "mod_FreeRDPWrap.h"
- #include <fstream>
- #include <io.h>
- #define FREERDP_PROCESS "wfreerdp.exe"
- #define REG_MSG_DESKSHARE_FLAG "{A284B1F9-FD11-463B-89FA-474CFFAA55E2}"
- #define DEF_KEY_SIZE 16 //default key size
- #define DEF_KEY_BUFF 256 //default key buff
- #define DEF_KEY_PATH "C:\\user.key" //passwd copy default path
- #define DEFAULT_CLIENT_USER_PASSWORD "11111111"
- unsigned char key[] = "usinxZsplM195447"; //default key
- using namespace std;
- static UINT WM_DESKSHARE_MSG = 0;
- #define DESKSHARE_FLAG_CONDITION 1 //我的共享状态
- #define FLAG_CONDITION_DONE 0 //共享结束
- #define FLAG_CONDITION_SHARER 1 //作为分享者
- #define FLAG_CONDITION_VIEWER 2 //作为观看者
- #define MOD_VERSION "2.0.0.1"
- BOOL GetProcessPath(DWORD PID, PTSTR szProcessPath, size_t cchSize)
- {
- HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
- FALSE, PID);
- if (hProcess == NULL) {
- strcpy_s(szProcessPath, cchSize, "???");
- return FALSE;
- }
- if (GetModuleFileNameEx(hProcess, (HMODULE)0, szProcessPath, cchSize) == 0) {
- DWORD dwSize = (DWORD) cchSize;
- if(QueryFullProcessImageName(hProcess, 0, szProcessPath, &dwSize) == 0)
- {
- if (!GetProcessImageFileName(hProcess, szProcessPath, cchSize)) {
- strcpy_s(szProcessPath, cchSize, "???");
- CloseHandle(hProcess);
- return FALSE;
- }
- }
- }
- CloseHandle(hProcess);
- return TRUE;
- }
- BOOL KillSpecifiedProcess(DWORD dwProcessID)
- {
- LOG_FUNCTION();
- BOOL ret = FALSE;
- HANDLE hProc = OpenProcess(PROCESS_TERMINATE, FALSE, dwProcessID);
- if (hProc == NULL) {
- Dbg("OpenProcess failed, GLE=%u", GetLastError());
- return FALSE;
- }
- if (!TerminateProcess(hProc, 0)) {
- Dbg("TerminateProcess failed, GLE=%u", GetLastError());
- }
- else {
- Dbg("Terminate process succ.");
- ret = TRUE;
- }
- CloseHandle(hProc);
- return ret;
- }
- /*
- Returned:
- -1: error;
- 0: no found;
- 1: other status;
- 2: disconnect;
- 3: actived
- */
- int CheckActivedSession(const char *lpcszUserName, DWORD *pSessionID)
- {
- HANDLE cur_token = NULL;
- HANDLE primary_token = NULL;
- PWTS_SESSION_INFO pWSessionInfo = NULL;
- DWORD count = 0;
- int size;
- DWORD i;
- int ret = 0;
- if(!WTSEnumerateSessionsA(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pWSessionInfo, &count)) {
- return -1;
- }
- size = (int)sizeof(WTS_SESSION_INFO);
- for(i=0; i<count; ++i) {
- LPTSTR pbuf = NULL;
- DWORD dwLen = 0;
- WTS_SESSION_INFO item = pWSessionInfo[i];
-
- Dbg("session#%d's connection state: %d", item.SessionId, item.State);
- if(!WTSQuerySessionInformation(WTS_CURRENT_SERVER_NAME,
- item.SessionId, WTSUserName,
- &pbuf, &dwLen)) {
- Dbg("WTSUserName failed, GLE=%u", GetLastError());
- ret = -1;
- } else {
- Dbg("UserName: %s", pbuf);
- if(strcmp(pbuf, lpcszUserName) == 0) {
- if(pSessionID)
- *pSessionID = item.SessionId;
- Dbg("Retrieve specified session id: %d", *pSessionID);
- if(WTSActive == item.State) {
- ret = 3;
- } else if(WTSDisconnected == item.State) {
- ret = 2;
- } else {
- ret = 1;
- }
- WTSFreeMemory(pbuf);
- return ret;
- }
- }
- if(pbuf) {
- WTSFreeMemory(pbuf);
- }
- pbuf = NULL;
- dwLen = 0;
- }
- return ret;
- }
- BOOLEAN SetPrivilege(HANDLE hToken,
- LPCTSTR lpszPrivilege,
- BOOL bEnablePrivilege
- )
- {
- TOKEN_PRIVILEGES tp;
- LUID luid;
- if(hToken == INVALID_HANDLE_VALUE) {
- if (!OpenProcessToken(GetCurrentProcess(),
- TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
- LOG_TRACE("OpenProcessToken error: %u", GetLastError());
- return FALSE;
- }
- }
- if ( !LookupPrivilegeValue(NULL,lpszPrivilege,&luid ) ){
- LOG_TRACE("LookupPrivilegeValue error: %u", GetLastError());
- return FALSE;
- }
- tp.PrivilegeCount = 1;
- tp.Privileges[0].Luid = luid;
- if (bEnablePrivilege)
- tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
- else
- tp.Privileges[0].Attributes = 0;
- if ( !AdjustTokenPrivileges(hToken, FALSE,&tp,
- sizeof(TOKEN_PRIVILEGES),(PTOKEN_PRIVILEGES) NULL,(PDWORD) NULL) ){
- Dbg("AdjustTokenPrivileges error: %u.", GetLastError());
- return FALSE;
- }
- if (GetLastError() == ERROR_NOT_ALL_ASSIGNED){
- Dbg("The token does not have the specified privilege.");
- return FALSE;
- }
- return TRUE;
- }
- CFreeRDPWrapFSM::CFreeRDPWrapFSM(void)
- :m_strUserName(CLIENET_USER)
- ,m_ecSelfTest(Error_Succeed)
- ,m_nSrcState(s0)
- ,m_hFreeRDPProc(NULL)
- ,m_dwFreeRDPProcID(-1)
- ,m_hRDPMaintainThread(NULL)
- ,m_dwRDPMaintainID(0)
- ,m_hWarerThread(NULL)
- ,m_dwWarerThreadID(0)
- ,m_bInvited(FALSE)
- ,m_bInterview(FALSE)
- ,m_dwLockScreenMinu(5)
- ,m_dwWndThreadID(0)
- ,m_hWndThread(NULL)
- ,m_hSrvMutex(NULL)
- ,m_strInviteFileName(true)
- ,m_bAgentSituation(FALSE)
- ,m_eShareMode(ClientIdle)
- ,m_bTestMode(FALSE)
- ,m_uMonitorNum(0)
- ,m_DeactiveClientManager(FALSE)
- {
- }
- CFreeRDPWrapFSM::~CFreeRDPWrapFSM(void)
- {
- LOG_FUNCTION();
- if(m_hSrvMutex) {
- CloseHandle(m_hSrvMutex);
- }
- //TerminateRDPRoutine();
- //Dbg("WM_EXIT_MSG : %d", WM_EXIT_MSG);
- //DWORD dwREcipents = BSM_APPLICATIONS | BSM_ALLDESKTOPS;
- //BroadcastSystemMessageA(BSF_POSTMESSAGE | BSF_FORCEIFHUNG, &dwREcipents, WM_EXIT_MSG, 0, 0);
- //BroadcastSystemMessageA(BSF_POSTMESSAGE | BSF_FORCEIFHUNG, &dwREcipents, WM_EXIT_MSG_CODE, 0, 0);
- if(m_hFreeRDPProc != NULL) {
- Dbg("Kill " FREERDP_PROCESS " last.");
- if(KillSpecifiedProcess(m_dwFreeRDPProcID)) {
- CloseHandle(m_hFreeRDPProc);
- }
- }
- }
- ErrorCodeEnum CFreeRDPWrapFSM::OnInit()
- {
- LOG_FUNCTION();
- #ifdef TWINKLE_LOCAL_DEBUG
- if (AllocConsole())
- {
- FILE* here = NULL;
- freopen_s(&here, "CONOUT$", "w", stdout);
- freopen_s(&here, "CONOUT$", "w", stderr);
- Dbg("Debug console created.");
- }
- #endif
-
- ErrorCodeEnum ec = Error_Unexpect;
- DWORD dwUserCode = 0;
- int errc = fs_error;
- BOOL bWrapInstalled = FALSE;
- CSmartPointer<IEntityFunction> spEntityFunction = GetEntityBase()->GetFunction();
- CSmartPointer<IConfigInfo> spConfig;
- CSimpleStringA strUserName = "";
- Dbg("Version %s; Complied at: %s %s", MOD_VERSION, __DATE__, __TIME__);
- AddStateHooker(this);
- CoInitialize(0);
- SendWfreeWrapEvt(-1);
- SetSysVal(fs_busy);
- ec = spEntityFunction->OpenConfig(Config_Software, spConfig);
- if(FAILURED(ec)) {
- Dbg("Open software config failed");
- m_strUserName = CLIENET_USER;
- } else {
- ec = spConfig->ReadConfigValue("Init", "UserName", strUserName);
- if(strUserName.IsNullOrEmpty()) {
- m_strUserName = CLIENET_USER;
- } else {
- m_strUserName = strUserName;
- }
- int testMode = 0;
- ec = spConfig->ReadConfigValueInt("Init", "TestMode", testMode);
- if(ISSUCCEEDED(ec) && testMode > 0) {
- Dbg("driver installed requires test mode!!");
- m_bTestMode = TRUE;
- }
- }
- WM_DESKSHARE_MSG = ::RegisterWindowMessageA(REG_MSG_DESKSHARE_FLAG);
- Dbg("WM_DESKSHARE_MSG = %d!", WM_DESKSHARE_MSG);
- RDPPipe_SetReference(this);
- RDPWarer_SetReference(this);
- DevMnt_SetReference(this);
- SetPrivilege(INVALID_HANDLE_VALUE, SE_TCB_NAME, TRUE);
- m_hSrvMutex = CreateMutex(NULL, FALSE, NULL);
- LOG_ASSERT(m_hSrvMutex != NULL && "Create mutex failed!");
- InitEnvironmentValue();
- m_uMonitorNum = GetSystemMetrics(SM_CMONITORS);
- Dbg("Current screen num:%d", m_uMonitorNum);
- if(IfDontActiveClientManagerDesk()) {
- LogWarn(Severity_High, Error_InvalidState, ERROR_FREERDP_DEPECRATE_CLIENT_MANAGER,
- "the machine has closed the client manager desktop function!");
- m_DeactiveClientManager = TRUE;
- return Error_Succeed;
- }
- #ifdef TWINKLE_LOCAL_DEBUG
- if(m_uMonitorNum != 2) {
- PromptInvalidMonitor();
- errc = fs_invalid_monitor;
- ec = Error_Succeed;
- m_hWndThread = CreateThread(
- NULL, 0,
- (LPTHREAD_START_ROUTINE)DevMnt_MainWndStartAndLoop,
- this,
- 0, &m_dwWndThreadID);
- if(m_hWndThread == NULL) {
- LogWarn(Severity_High, Error_Unexpect, ERROR_DEVICE_MONITOR_CREATE, "Create Wnd thread failed!");
- m_dwWndThreadID = 0;
- }
- goto Error;
- }
- #endif // TWINKLE_LOCAL_DEBUG
- /*RDPWrap component.*/
- IFCALLFAILED_LEAD_END(CheckRdpWrapInstall(bWrapInstalled), ERROR_CHECK_RDPWRAP_INSTALL);
- if(bWrapInstalled == FALSE) {
- IFCALLFAILED_LEAD_END(InstallRdpWrap(), ERROR_RDPWRAP_INSTALL);
- LogEvent(Severity_High, Error_Succeed, "Install RDP Wrapper library succ.");
-
- }else {
- if(IsWrapperNeedUpdate()) {
- IFCALLFAILED_LEAD_END(UpdateRdpWrap(), ERROR_RDPWRAP_UPDATE);
- LogEvent(Severity_High, Error_Succeed, "Update RDP Wrapper library succ.");
- }
- }
- /*Check and set Numlock status*/
- SetNumLockDefaultStatus();
- /*Service component.*/
- IFCALLFAILED_LEAD_END(UpdateAndChangeSrvStatus(), ERROR_SERVICE_UPDATE);
- /*mouse and keyboard redirect component.*/
- m_hWndThread = CreateThread(
- NULL, 0,
- (LPTHREAD_START_ROUTINE)DevMnt_MainWndStartAndLoop,
- this,
- 0, &m_dwWndThreadID);
- if(m_hWndThread == NULL) {
- LogWarn(Severity_High, Error_Unexpect, ERROR_DEVICE_MONITOR_CREATE, "Create Wnd thread failed!");
- m_dwWndThreadID = 0;
- }
- /*screen share component.*/
- m_hWarerThread = CreateThread(
- NULL, 0,
- (LPTHREAD_START_ROUTINE)RDPWarer_MainWndStartAndLoop,
- this,
- 0, &m_dwWarerThreadID);
- if(m_hWarerThread == NULL) {
- LogWarn(Severity_High, Error_Unexpect, ERROR_RDPWARE_THREAD_CREATE, "Create Warer thread failed!");
- m_dwWarerThreadID = 0;
- }
- /*Create and maintain the wfreerdp routine.*/
- hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
- LOG_ASSERT(hExitEvent != NULL && "Create event handle failed!");
- m_hRDPMaintainThread = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0,
- MaintainFreeRDPRoutine, this, 0, &m_dwRDPMaintainID));
- if(!m_hRDPMaintainThread || m_hRDPMaintainThread == INVALID_HANDLE_VALUE) {
- m_hRDPMaintainThread = NULL;
- ec = Error_Unexpect;
- dwUserCode = ERROR_FREERDP_THREAD_CREATE;
- goto Error;
- }
- /*process communication component.*/
- if(!RDPPipe_MainEntry(RVC_DESK2RDP_HOST_PIPE, GetEntityBase()->GetEntityName())) {
- dwUserCode = ERROR_BUILD_RDP_PIPE;
- ec = Error_Unexpect;
- goto Error;
- }
- DWORD dwRet = WaitForSingleObject(m_hRDPMaintainThread, 3000);
- if(dwRet != WAIT_TIMEOUT) {
- Dbg("WaitForSingleObject error %d", dwRet);
- dwUserCode = ERROR_FREERDP_THREAD_WAIT;
- ec = Error_Unexpect;
- goto Error;
- }
- GetEntityBase()->GetFunction()->PostThreadPoolTask(new SpDeskShareCreateTask(this, true));
- SetSysVal(fs_succ);
- return Error_Succeed;
- Error:
- SetSysVal(errc);
- LogError(Severity_High, ec, dwUserCode,
- (LPCTSTR)CSimpleStringA::Format("Fatal error occurs on init step UserCode = %d !", dwUserCode));
- return ec;
- }
- ErrorCodeEnum CFreeRDPWrapFSM::OnExit()
- {
- if(m_hWndThread != NULL) {
- DevMnt_Terminate();
- WaitForSingleObject(m_hWndThread, 3000);
- SAFE_CLOSE_HANDLE(m_hWndThread);
- }
- TerminateFreeRDPRoutine();
- char szCmdLine[MAX_PATH] = {0};
- strcpy_s(szCmdLine, "taskkill /F /IM SpDeskShare.exe /T");
- CreateProcessFromSrv(szCmdLine, (LPCTSTR)m_strUserName, NULL);
- CoUninitialize();
- RemoveStateHooker(this);
- return Error_Succeed;
- }
- void CFreeRDPWrapFSM::SelfTest(EntityTestEnum eTestType,CSmartPointer<ITransactionContext> pTransactionContext)
- {
- //LOG_FUNCTION();
- pTransactionContext->SendAnswer(m_ecSelfTest);
-
- if(!m_DeactiveClientManager)
- {
- BOOL bAvailable = FALSE;
- if(!RDPPipe_IsClientSurvival(bAvailable)) {
- Dbg("SelfTest: SpDeskShare not survival ?");
- CreateDeskShareProc();
- }else if(!bAvailable) {
- Dbg("SelfTest: SpDeskShare not available ?");
- CreateDeskShareProc(true);
- }
- CheckCriticalThread();
- }
- }
- void CFreeRDPWrapFSM::OnStateTrans(int iSrcState, int iDstState)
- {
- Dbg("FSMState transfers from %s to %s", GetStateName(iSrcState), GetStateName(iDstState));
- m_nSrcState = iSrcState;
- }
- void CFreeRDPWrapFSM::s0_on_entry()
- {
- LOG_FUNCTION();
- m_eShareMode = ClientIdle;
- if(m_DeactiveClientManager) {
- PostEventLIFO(new FSMEvent(USER_EVT_DEPECRATED));
- }
- }
- void CFreeRDPWrapFSM::s0_on_exit()
- {
- LOG_FUNCTION();
- }
- unsigned int CFreeRDPWrapFSM::s0_on_event(FSMEvent* e)
- {
- LOG_FUNCTION();
- unsigned int uRet = 0;
- switch(e->iEvt) {
- case USER_EVT_INVITE:
- {
- InviteEvent* pEvt = dynamic_cast<InviteEvent*>(e);
- if(this->CreateShareSession(pEvt->m_ctx)) {
- if(m_bInvited) {
- uRet = 2;
- }else {
- uRet = 1;
- }
- }
- e->SetHandled();
- }
- break;
- case USER_EVT_INSTALL_DRIVE:
- {
- if(m_bTestMode) {
- CSimpleStringA strResult;
- BOOL bRes = ExecWaitWithResultContent("C:\\Windows\\System32\\bcdedit.exe", strResult);
- if(bRes) {
- //strResult.Trim();
- //Dbg("Trim:%s", (LPCTSTR)strResult);
- if(strstr(strResult, "testsigning Yes") == NULL) {
- LogEvent(Severity_High,
- Error_InvalidState,
- "Need to set testsigning on before install driver");
- DWORD dwExitCode = 0;
- bRes = ExecWaitWithExitCode("C:\\Windows\\System32\\bcdedit.exe /set testsigning on", dwExitCode);
- if(dwExitCode == 0) {
- //TODO restart the computer
- Dbg("restart the computer..");
- if(WinExec("shutdown -r -t 10", SW_HIDE) > 31) {
- GetEntityBase()->GetFunction()->ShowFatalError("测试模式开启成功,为及时生效,将在10s后重启终端设备。");
- } else {
- GetEntityBase()->GetFunction()->ShowFatalError("测试模式开启成功,为及时生效,请手动重启终端设备!");
- }
- }
- else {
- GetEntityBase()->GetFunction()->ShowFatalError("开启系统测试模式失败,请手动进行设置!");
- }
- break;
- }
- }
- else {
- LogWarn(Severity_High,
- Error_NotMeetCondition,
- 0,
- "无法检测系统是否开启测试模式,驱动很可能会出现安装失败!!!");
- }
- }
- DriveInstallEvent* pEvt = dynamic_cast<DriveInstallEvent*>(e);
- uRet = CreateInstallDrvTask(pEvt->kbdRequired, pEvt->mouRequired);
- e->SetHandled();
- Dbg("uRet: %d", uRet);
- }
- break;
- case USER_EVT_AGENT_ASSIST:
- {
- AgentAssistantEvent* pEvt = dynamic_cast<AgentAssistantEvent*>(e);
- AgentAssistTask* task = new AgentAssistTask(this);
- task->m_ctx = pEvt->m_ctx;
- e->SetHandled();
- if(Error_Succeed == GetEntityBase()->GetFunction()->PostThreadPoolTask(task)) {
- uRet = 1;
- }
- }
- break;
- default:
- break;
- }
- return uRet;
- }
- void CFreeRDPWrapFSM::s1_on_entry()
- {
- if(m_eShareMode != ClientIdle) {
- SendWfreeWrapEvt((int)m_eShareMode);
- }
- else {
- LogWarn(Severity_High, Error_InvalidState, Error_Unexpect, "Invalid share mode storage!");
- }
- }
- void CFreeRDPWrapFSM::s1_on_exit()
- {
- if(m_eShareMode != ClientIdle) {
- SendWfreeWrapEvt(0 - (int)m_eShareMode);
- }
- }
- unsigned int CFreeRDPWrapFSM::s1_on_event(FSMEvent* e)
- {
- unsigned int uRet = 0;
- switch(e->iEvt) {
- case USER_EVT_CLOSE_SHARE:
- {
- e->SetHandled();
- CloseShareEvent* pEvt = dynamic_cast<CloseShareEvent*>(e);
- if(this->TerminateShareSession(pEvt->m_ctx)) {
- uRet = 1;
- } else {
- uRet = 2;
- }
- }
- break;
- case USER_EVT_AGENT_ASSIST_DONE:
- {
- uRet = e->param1;
- Dbg("USER_EVT_AGENT_ASSIST_DONE returned %u", uRet);
- e->SetHandled();
- }
- break;
- default:
- break;
- }
- return uRet;
- }
- void CFreeRDPWrapFSM::s2_on_entry()
- {
- if(m_eShareMode != ClientIdle) {
- SendWfreeWrapEvt((int)m_eShareMode);
- }
- else {
- LogWarn(Severity_High, Error_InvalidState, Error_Unexpect, "Invalid share mode storage!");
- }
- }
- void CFreeRDPWrapFSM::s2_on_exit()
- {
- if(m_eShareMode != ClientIdle) {
- SendWfreeWrapEvt(0 - (int)m_eShareMode);
- }
- }
- unsigned int CFreeRDPWrapFSM::s2_on_event(FSMEvent* e)
- {
- unsigned int uRet = 0;
- switch(e->iEvt) {
- case USER_EVT_CLOSE_SHARE:
- {
- CloseShareEvent* pEvt = dynamic_cast<CloseShareEvent*>(e);
- if(this->TerminateShareSession(pEvt->m_ctx)) {
- uRet = 1;
- }
- }
- break;
- default:
- break;
- }
- return uRet;
- }
- void CFreeRDPWrapFSM::s3_on_entry()
- {
- SetSelfCheckCode(Error_InvalidState);
- }
- void CFreeRDPWrapFSM::s3_on_exit()
- {
- SetSelfCheckCode(Error_Succeed);
- }
- unsigned int CFreeRDPWrapFSM::s3_on_event(FSMEvent* e)
- {
- unsigned int uRet = 0;
- return uRet;
- }
- void CFreeRDPWrapFSM::s4_on_entry()
- {
- LOG_FUNCTION();
- }
- void CFreeRDPWrapFSM::s4_on_exit()
- {
- LOG_FUNCTION();
- }
- unsigned int CFreeRDPWrapFSM::s4_on_event(FSMEvent* e)
- {
- unsigned int uRet = 0;
- if(e->iEvt == USER_EVT_INSTALL_DRIVE_DONE) {
- uRet = 1;
- e->SetHandled();
- }
- return uRet;
- }
- unsigned int CFreeRDPWrapFSM::s5_on_event(FSMEvent* e)
- {
- LOG_FUNCTION();
- Dbg("event id: %d", e->iEvt);
- return -1;
- }
- bool OperatorFile(string file,bool isRead,char *str)
- {
- std::fstream fs;
- WIN32_FIND_DATAW find_data;
- HANDLE hFind = FindFirstFileW(AccountManage::convertStr2wStr(file).c_str(),&find_data);
- //judge file whether exist,if no then create it
- if(hFind == INVALID_HANDLE_VALUE)
- {
- fs.open(file,ios::out|ios::binary);
- if(!fs){
- Dbg("user.key create FAIL");
- return false;
- }else
- {
- Dbg("user.key create SUSS");
- }
- fs.close();
- //after close,fs must be clear
- fs.clear();
- //set all user to DENY ACCESS
- std::vector<std::string> vUserName;
- int errorCode;
- if(!AccountManage::GetAllAccount(vUserName,errorCode))
- {
- Dbg("get all user name FAIL!");
- return false;
- }
- std::vector<std::string>::const_iterator it=vUserName.begin();
- while(it!=vUserName.end())
- {
- if(AccountManage::AdjustACL(AccountManage::convertStr2wStr((*it)).c_str(),AccountManage::convertStr2wStr(file).c_str(),GENERIC_ALL,DENY_ACCESS))
- {
- Dbg("adjust ACL to GRANT for all user FAIL!");
- }
- it++;
- }
- }
- WCHAR pUserName[MAX_PATH] = {0};
- DWORD sizeofUserName = sizeof(pUserName);
- GetUserNameW(pUserName,&sizeofUserName);
- if(wcslen(pUserName) == 0){
- Dbg("get user name FAIL!");
- return false;
- }
- //set current user to GRANT ACCESS
- if(AccountManage::AdjustACL(pUserName,AccountManage::convertStr2wStr(file).c_str(),GENERIC_ALL,GRANT_ACCESS))
- {
- Dbg("adjust ACL to GRANT FAIL!");
- return false;
- }
- //read mode
- if (isRead)
- {
- fs.open(file,ios::in | ios::binary);
- if(!fs){
- Dbg("open %s with read FAIL!",file.c_str());
- return false;
- }
- char tmp[DEF_KEY_BUFF*4]={0};
- fs.getline(tmp,sizeof(tmp));
- strcpy(str,tmp);
- fs.close();
- fs.clear();
- }
- //write mode
- else{
- fs.open(file,ios::out|ios::binary);
- if(!fs){
- Dbg("open %s with write FAIL!",file.c_str());
- return false;
- }
- fs<<str<<endl;
- fs.close();
- fs.clear();
- }
- //set current user to DENY ACCESS
- if(AccountManage::AdjustACL(pUserName,AccountManage::convertStr2wStr(file).c_str(),GENERIC_ALL,DENY_ACCESS))
- {
- Dbg("adjust ACL to DENY FAIL!");
- return false;
- }
- return true;
- }
- HANDLE CFreeRDPWrapFSM::CreateFreeRDPProc(DWORD &dwProcessID)
- {
- ErrorCodeEnum ec = Error_Succeed;
- CSmartPointer<IEntityFunction> spEntityFunction = GetEntityBase()->GetFunction();
- CSmartPointer<IConfigInfo> spConfig;
- CSmartPointer<IConfigInfo> spConfig_r;
- char cmdValue[MAX_PATH] = {0};
- char cmdParam[MAX_PATH] = {0};
- STARTUPINFOA si = {0};
- PROCESS_INFORMATION pi = {0};
- SECURITY_ATTRIBUTES sa = {0};
- DWORD dwSessionId;
- HANDLE hUserTokenDup, hThisToken;
- HANDLE hProcess = INVALID_HANDLE_VALUE;
- const char* USRNAME = (LPCTSTR)m_strUserName;
- const char* PASSWORD = "11111111";
- dwProcessID = 0;
- ec = spEntityFunction->OpenConfig(Config_Software, spConfig);
- if(FAILURED(ec)) {
- Dbg("Open software config failed");
- return INVALID_HANDLE_VALUE;
- }
- Dbg("user name: %s", m_strUserName.GetData());
-
- CSimpleStringA strPassword;
- if(Error_Succeed != RetrieveFreeRDPUserPassword(strPassword)) {
- return INVALID_HANDLE_VALUE;
- }
- bool bEmptyPsw = false;
- if(strPassword.IsNullOrEmpty()) {
- bEmptyPsw = true;
- Dbg("Detect strPassword is empty");
- }
- int nFullScreen = 1;
- bool bFullScreen = true;
- ec = spConfig->ReadConfigValueInt(m_strUserName, "FullScreen", nFullScreen);
- if(nFullScreen == 0) {
- bFullScreen = false;
- Dbg("Detect not full display request!");
- }
- CSimpleStringA strParam(true), strValue;
- ec = spConfig->ReadConfigValue(m_strUserName, "Optimizer", strValue);
- if(!strValue.IsNullOrEmpty()) {
- if(strValue.IsEndWith(" /rvc:ccdg")) {
- strParam = strValue.SubString(0, strValue.GetLength()-strlen(" /rvc:ccdg"));
- }
- }
- ZeroMemory(&si, sizeof(si));
- si.cb = sizeof(si);
- GetStartupInfo(&si);
- ZeroMemory(&pi, sizeof(pi));
- memset(cmdValue, 0, sizeof(cmdValue));
- strcpy_s(cmdValue, ".\\bin\\freerdp\\wfreerdp.exe");
-
- sprintf_s(cmdParam, " /u:%s", (LPCTSTR)m_strUserName);
- strcat_s(cmdValue, cmdParam);
- if(!bEmptyPsw) {
- sprintf_s(cmdParam, " /p:%s", (LPCTSTR)strPassword);
- strcat_s(cmdValue, cmdParam);
- }
- if(bFullScreen) {
- strcat_s(cmdValue, " /f");
- }
- strcat_s(cmdValue, " /t:\"rvc-wfreerdp\"");
- strcat_s(cmdValue, " +aero");
- strcat_s(cmdValue, " /v:127.0.0.2");
- if(!strParam.IsNullOrEmpty()) {
- if(!strParam.IsStartWith(" ")){
- strcat_s(cmdValue, " ");
- }
- strcat_s(cmdValue, (LPCTSTR)strParam);
- }
- Dbg("Process Param: %s", cmdValue);
- //该接口有时会出现阻塞,暂时要兼容一下,后续处理。
- SetFSMSickStatus(FALSE);
- dwSessionId = WTSGetActiveConsoleSessionId();
- SetFSMRecoverStatus();
- Dbg("WTSGetActiveConsoleSessionId...");
- if (OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &hThisToken)) {
- Dbg("OpenProcessToken...");
- LUID luid;
- TOKEN_PRIVILEGES tp;
- LPVOID pEnv = NULL;
- DWORD dwFlag = 0;
- Dbg("Start to LookupPrivilegeValueA...");
- LookupPrivilegeValueA(NULL, "SeDebugPrivilege", &luid);
- Dbg("Finished LookupPrivilegeValueA...");
- tp.PrivilegeCount = 1;
- tp.Privileges[0].Luid = luid;
- tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
- Dbg("DuplicateTokenEx...");
- DuplicateTokenEx(hThisToken,MAXIMUM_ALLOWED,NULL,
- SecurityIdentification, TokenPrimary, &hUserTokenDup);
- Dbg("SetTokenInformation...");
- SetTokenInformation(hUserTokenDup,
- TokenSessionId,(void*)&dwSessionId, sizeof(DWORD));
- Dbg("AdjustTokenPrivileges...");
- AdjustTokenPrivileges(hUserTokenDup, FALSE, &tp, sizeof(TOKEN_PRIVILEGES),
- (PTOKEN_PRIVILEGES)NULL,NULL);
- //if(CreateEnvironmentBlock(&pEnv, hUserTokenDup, TRUE)) {
- // //dwFlag |= CREATE_UNICODE_ENVIRONMENT;
- //}else {
- // pEnv = NULL;
- //}
- Dbg("Start to create wfreerdp process...");
- if (CreateProcessAsUserA(hUserTokenDup,
- NULL,
- cmdValue,
- NULL,
- NULL,
- FALSE,
- dwFlag,
- pEnv,
- NULL,
- &si,
- &pi)) {
- dwProcessID = pi.dwProcessId;
- CloseHandle(pi.hThread);
- hProcess = pi.hProcess;
- } else {
- dwProcessID = GetLastError();
- LogWarn(Severity_Middle, Error_Unexpect, ERROR_FREERDP_CREATE_FREERDP_PROCESS_FAILED,
- (LPCTSTR)CSimpleStringA::Format("CreateProcessAsUserA failed! GLE=%d", dwProcessID));
- }
- if (pEnv) {
- DestroyEnvironmentBlock(pEnv);
- }
- CloseHandle(hUserTokenDup);
- CloseHandle(hThisToken);
- } else {
- LogWarn(Severity_Middle, Error_Unexpect, ERROR_FREERDP_OPEN_CURRENT_PROCESS_TOKEN_FAILED,
- (LPCTSTR)CSimpleStringA::Format("open process token failed! Error : %d", GetLastError()));
- }
- return hProcess;
- }
- BOOL CFreeRDPWrapFSM::TerminateFreeRDPRoutine()
- {
- BOOL bNeedConfirm = FALSE;
- if(m_hRDPMaintainThread != INVALID_HANDLE_VALUE && m_hRDPMaintainThread != NULL) {
- if(hExitEvent != NULL) {
- SetEvent(hExitEvent);
- if(WaitForSingleObject(m_hRDPMaintainThread, /*INFINITE*/3000) != WAIT_OBJECT_0) {
- bNeedConfirm = TRUE;
- }
- SAFE_CLOSE_HANDLE(m_hRDPMaintainThread);
- m_dwRDPMaintainID = 0;
- }
- }
- return TRUE;
- }
- BOOL CFreeRDPWrapFSM::IsWrapperNeedUpdate()
- {
- ErrorCodeEnum ec = Error_Succeed;
- CSmartPointer<IEntityFunction> pFunc = GetEntityBase()->GetFunction();
- CSystemStaticInfo info;
- FILE_VERSION fvWrap = {0};
- BOOL bUpdate = FALSE;
- CSimpleStringA strPath;
- LOG_ASSERT(gszTermServicePath != NULL && strlen(gszTermServicePath) != 0);
- if(GetEntityBase()->GetFunction()->GetPath("Bin", strPath) != Error_Succeed
- || strPath.IsNullOrEmpty())
- {
- Dbg("GetPath about bin failed");
- return FALSE;
- }
- if(!strstr(gszTermServicePath, (LPCTSTR)strPath)) {
- Dbg("Run %s vs %s, it need to update.", gszTermServicePath, (LPCTSTR)strPath);
- bUpdate = TRUE;
- }
-
- return bUpdate;
- }
-
- BOOL CFreeRDPWrapFSM::CreateShareSession(
- SpReqAnsContext<FreeRDPWrapSrv_InviteRdpShare_Req,
- FreeRDPWrapSrv_InviteRdpShare_Ans>::Pointer ctx)
- {
- BOOL bRet = FALSE;
- char szFileName[MAX_PATH] = {0};
- m_strInviteFileName = "";
- /*
- CTRL_LEVEL_VIEW = 2,
- CTRL_LEVEL_INTERACTIVE = 3,
- */
- USHORT usViewLevel = CTRL_LEVEL_VIEW;
- m_bInterview = FALSE;
- if(ctx->Req.viewLevel == 1) {
- usViewLevel = CTRL_LEVEL_INTERACTIVE;
- m_bInterview = TRUE;
- }
- if(ctx->Req.bClientSide) {
- m_bInvited = TRUE;
- } else {
- m_bInvited = FALSE;
- }
- if(m_hWarerThread == NULL || !hWarerWnd) {
- Dbg("Share window handle is invalid");
- goto Error;
- }
-
- memset(szFileName, 0, sizeof(szFileName));
- if(!CreateInviteFileName(szFileName, MAX_PATH)) {
- goto Error;
- }
- m_strInviteFileName = szFileName;
- if(ctx != NULL && ctx->Req.bClientSide == true) {
- /*
- @step1: Tell the SpDeskShare that we want see the screen
- @step2: SpDeskShare send the invitation information.
- @step3: The entity connect the 'sharer host' with the invitation strings.
- */
- if(!RDPPipe_Request(CTXD_SHARE, TRUE, szFileName, (DWORD)ctx->Req.filterAppId, usViewLevel)) {
- Dbg("RDPPipe_Request for CTXD_SHARE invoked failed !");
- goto Error;
- }
- if(!RDPWarer_Connect(szFileName)) {
- LogWarn(Severity_Middle, Error_Param, ERROR_FREERDP_SHARE_ACCEPT_INVITE_FAILED, "Do the connect Job failed !");
- goto Error;
- }
- Dbg("Perform connect procedure succ.");
- }
- else {
- if(!RDPWarer_ShareAndInvite(szFileName, ctx->Req.filterAppId, usViewLevel)) {
- LogWarn(Severity_Middle, Error_Param, ERROR_FREERDP_SHARE_BUILD_UP_SHRER_FAILED, "Do the share and invite Job failed !");
- goto Error;
- }
- if(!RDPPipe_Request(CTXD_INVITE, TRUE, szFileName, NULL, NULL)) {
- Dbg("RDPPipe_Request invoked failed !");
- RDPWarer_CloseInvite();
- goto Error;
- }
- /*
- @step1: The entity create the invitation information and tell the Spdeskshare we want to be shared
- @step2: The SpDeskShare use the invitaion information to connect it!
- */
- Dbg("Perform invite procedure succ.");
- }
-
- if(m_bInterview && !m_bInvited) {
- //ShowFreeRDPCursor(FALSE);
- }
- m_bAgentSituation = FALSE;
- m_eShareMode = m_bInvited ? AM2Client : Client2AM;
- bRet = TRUE;
- Error:
- if(ctx != NULL) {
- ctx->Ans.retCode = bRet ? 1 : -1;
- ctx->Answer(Error_Succeed);
- }
- if(!m_strInviteFileName.IsNullOrEmpty()) {
- DeleteFileA(m_strInviteFileName);
- m_strInviteFileName = "";
- }
- return bRet;
- }
- BOOL CFreeRDPWrapFSM::TerminateShareSession(
- SpReqAnsContext<FreeRDPWrapSrv_CloseRdpShare_Req, FreeRDPWrapSrv_CloseRdpShare_Ans>::Pointer ctx)
- {
- Dbg("Start to close share screen, Agent(%d) Invited(%d)", m_bAgentSituation, m_bInvited);
- if(m_bInvited) {
- if(!RDPWarer_Disconnect()) {
- LogWarn(Severity_Middle, Error_Param, ERROR_FREERDP_SHARE_DISCONNECT_FAILED, "Disconnect as viewer failed !");
- goto Error;
- }
- if(!m_bAgentSituation && !RDPPipe_Request(CTXD_KILL_INVITE, TRUE)) {
- Dbg("RDPPipe_Request for CTXD_KILL_INVITE invoked failed !");
- goto Error;
- }
- }else {
- if(!m_bAgentSituation && !RDPPipe_Request(CTXD_DISCONNECT, TRUE)) {
- Dbg("RDPPipe_Request for CTXD_DISCONNECT invoked failed !");
- goto Error;
- }
- // Sleep a little time for receiving endpoint disconnect event! [6/17/2020 10:47 @Gifur]
- Sleep(300);
- if(!RDPWarer_CloseInvite()) {
- LogWarn(Severity_Middle, Error_Param, ERROR_FREERDP_SHARE_CLOSE_SESSION_FAILED, "Close invitation session as sharer failed !");
- goto Error;
- }
- }
- if(!m_bAgentSituation && m_bInterview && !m_bInvited) {
- //ShowFreeRDPCursor(TRUE);
- }
- if(ctx != NULL) {
- ctx->Ans.retCode = 1;
- ctx->Answer(Error_Succeed);
- }
- return TRUE;
- Error:
- if(ctx != NULL) {
- ctx->Ans.retCode = -1;
- ctx->Answer(Error_Succeed);
- }
- return FALSE;
- }
- BOOL CFreeRDPWrapFSM::CreateInviteFileName(CHAR* strFileName, const DWORD bufLen)
- {
- CSimpleStringA strPath;
- if(GetEntityBase()->GetFunction()->GetPath("Temp", strPath) != Error_Succeed
- || strPath.IsNullOrEmpty())
- {
- LogWarn(Severity_Middle, Error_Unexpect, 0, "GetPath about Temp failed");
- return FALSE;
- }
- if(!ExistsDirA(strPath)) {
- if(!CreateDirRecursiveA(strPath)) {
- LogWarn(Severity_Middle, Error_Unexpect, 0, "CreateDirRecursiveA failed");
- return FALSE;
- }
- }
- SYSTEMTIME st, stLocal;
- GetSystemTime(&st);
- SystemTimeToTzSpecificLocalTime(NULL, &st, &stLocal);
- CHAR fileName[MAX_PATH] = { 0 };
- sprintf_s(fileName, "%s\\%d%02d%02d-%02d_%02d_%02d.xml", (LPCTSTR)strPath,
- stLocal.wYear, stLocal.wMonth, stLocal.wDay,
- stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
- strcpy_s(strFileName, bufLen, fileName);
- Dbg("Combined XML FilePah: %s", strFileName);
- return (strlen(strFileName) > 0);
- }
- void CFreeRDPWrapFSM::InitEnvironmentValue()
- {
- ErrorCodeEnum ec = Error_Succeed;
- CSmartPointer<IEntityFunction> spEntityFunction = GetEntityBase()->GetFunction();
- CSmartPointer<IConfigInfo> spConfig;
- LPCTSTR name = "WLOG_APPENDER";
- ec = spEntityFunction->OpenConfig(Config_Software, spConfig);
- DWORD nSize = GetEnvironmentVariableA(name, NULL, 0);
- if (nSize == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
- {
- Dbg("Set wfreerdp child process environment...");
- CSimpleStringA strDbgPath;
- spEntityFunction->GetPath("Dbg", strDbgPath);
- CSimpleStringA strDbgBk = strDbgPath;
- if(!strDbgPath.IsNullOrEmpty()) {
- char logAppender[MAX_PATH] = "WLOG_APPENDER=";
- strcat(logAppender, "FILE");
- _putenv(logAppender);
- strDbgPath += "\\wfreerdp";
- char logFilePath[MAX_PATH] = "WLOG_FILEAPPENDER_OUTPUT_FILE_PATH=";
- strcat(logFilePath, strDbgPath);
- _putenv(logFilePath);
- //Dbg("Set wfreerdp dbg path: %s", (LPCTSTR)strDbgPath);
- memset(logFilePath, 0, sizeof(logFilePath));
- strcpy_s(logFilePath, "DbgPath=");
- strcat_s(logFilePath, (LPCTSTR)strDbgBk);
- _putenv(logFilePath);
- }
- else {
- Dbg("GetPath of DBG is null!!");
- }
- int nLockTime = 0;
- ec = spConfig->ReadConfigValueInt("Common", "LockScreenMin", nLockTime);
- if(nLockTime > 0) {
- m_dwLockScreenMinu = nLockTime;
- Dbg("Set lock screen time %d min.", m_dwLockScreenMinu);
- }
- CSimpleStringA strTo;
- strTo = CSimpleStringA::Format("WF_LOCK_SCREEN_TIMEOUT=%d", m_dwLockScreenMinu);
- _putenv(strTo);
- }
- }
- void CFreeRDPWrapFSM::SetSysVal(int nFlag)
- {
- CSmartPointer<IEntityFunction> spFunction = this->GetEntityBase()->GetFunction();
- CSimpleStringA csStatus;
- CSimpleStringA csNewStatus = FREERDPSTATUS_UNKOWN;
- ErrorCodeEnum err;
- err = spFunction->GetSysVar(SYSVAR_FREERDPSTATUS, csStatus);
- Dbg("Current sys val of " SYSVAR_FREERDPSTATUS " : %s(%d)", (LPCTSTR)csStatus, err);
- switch(nFlag) {
- case fs_error:
- csNewStatus = FREERDPSTATUS_ERROR;
- break;
- case fs_succ:
- csNewStatus = FREERDPSTATUS_SUCC;
- break;
- case fs_busy:
- csNewStatus = FREERDPSTATUS_BUSY;
- break;
- case fs_invalid_monitor:
- csNewStatus = FREERDPSTATUS_INVALID_MONITOR;
- break;
- case fs_unknown:
- csNewStatus = FREERDPSTATUS_UNKOWN;
- break;
- default:
- csNewStatus = FREERDPSTATUS_UNKOWN;
- break;
- }
- if(csNewStatus != csStatus) {
- err = spFunction->SetSysVar(SYSVAR_FREERDPSTATUS, csNewStatus, true);
- Dbg("SetSysVar " SYSVAR_FREERDPSTATUS " from '%s' to '%s' returned %d",
- (LPCTSTR)csStatus
- , (LPCTSTR)csNewStatus
- , err);
- }
- else {
- Dbg("system value is same with already one.");
- }
- return;
- }
- ErrorCodeEnum CFreeRDPWrapFSM::CreateClientUserAccount()
- {
- int errorCode;
- char newPasswd[DEF_KEY_BUFF] = {0};
- int addNewAccountNum=0;
- CSmartPointer<IEntityFunction> spEntityFunction = GetEntityBase()->GetFunction();
- CSmartPointer<IConfigInfo> spConfigRun;
- auto ec = spEntityFunction->OpenConfig(Config_Run, spConfigRun);
- if(FAILURED(ec)) {
- Dbg("Open run config failed");
- return ec;
- }
- Common::GenerateRandomPassword((unsigned char*)newPasswd, DEF_KEY_SIZE);
- Dbg("Add New Account...");
- while(!AccountManage::AddNewAccount(m_strUserName.GetData(),
- reinterpret_cast<char *>(newPasswd),errorCode))
- {
- addNewAccountNum++;
- Dbg("Create account failed errorCode=%d,addNewAccountNum=%d", errorCode, addNewAccountNum);
- if(addNewAccountNum > 3){
- LogWarn(Severity_Middle,Error_Unexpect,ERROR_ADD_NEW_ACCOUNT,"三次创建 ClienUser 均失败!");
- return Error_Unexpect;
- }
- }
- Dbg("Create New Account succ,errorCode=%d.", errorCode);
- //add user to Remote Desktop Users
- if(!AccountManage::ExtendGroupAdd(m_strUserName.GetData(),"Remote Desktop Users"))
- {
- Dbg("Append [Remote Desktop Users] group error");
- RemoveClientUser();
- ec = Error_Unexpect;
- } else {
- Dbg("Create %s SUSS,and Append [Remote Desktop Users] group SUSS",m_strUserName.GetData());
- CSimpleStringA strNewPassword(newPasswd);
- ec = StoreFreeRDPUserPassword(strNewPassword);
- }
- return ec;
- }
- ErrorCodeEnum CFreeRDPWrapFSM::GetClientUserPsw(bool bRuncfgInitialized, CSimpleStringA& plainPsw)
- {
- plainPsw = "";
- CSmartPointer<IEntityFunction> spEntityFunction = GetEntityBase()->GetFunction();
- CSmartPointer<IConfigInfo> spConfig;
- auto ec = spEntityFunction->OpenConfig(Config_Software, spConfig);
- if(FAILURED(ec)) {
- Dbg("Open software config failed");
- return ec;
- }
- CSmartPointer<IConfigInfo> spConfigRun;
- ec = spEntityFunction->OpenConfig(Config_Run, spConfigRun);
- if(FAILURED(ec)) {
- Dbg("Open run config failed");
- return ec;
- }
- if(!bRuncfgInitialized && !ExistsFileA(DEF_KEY_PATH))
- {
- //from software config read passwd
- CSimpleStringA originalPsw(true);
- ec = spConfig->ReadConfigValue(m_strUserName.GetData(), "Password", originalPsw);
- if(FAILURED(ec)) {
- Dbg("Read software config [%s.Password] failed",m_strUserName.GetData());
- originalPsw = DEFAULT_CLIENT_USER_PASSWORD;
- }
- ec = spConfigRun->WriteConfigValue("Init", "Compatible", "");
- if (FAILURED(ec)) {
- Dbg("Write run config Init.Compatible failed");
- }
- plainPsw = originalPsw;
- } else {
- CSimpleStringA cipherPassword(true);
- ec = spConfigRun->ReadConfigValue(m_strUserName.GetData(), "Password", cipherPassword);
- if(FAILURED(ec)) {
- Dbg("Read run config [%s.Password] failed",m_strUserName.GetData());
- cipherPassword = "";
- }
- if(cipherPassword.IsNullOrEmpty()) {
- Dbg("Read passwd is NULL");
- RetrieveClientUserPswFromBakup(cipherPassword);
- }
- if(IsInvalidCipherPsw(cipherPassword)) {
- return Error_DataCheck;
- }
- EncodeCipher2PlainString(cipherPassword, plainPsw);
- }
- Dbg("Passwd is %s,%d",(const char *)plainPsw, plainPsw.GetLength());
-
- if(plainPsw.IsNullOrEmpty())
- return Error_Unexpect;
- return Error_Succeed;
- }
- bool CFreeRDPWrapFSM::RemoveClientUser()
- {
- int errorCode;
- int rmAccountNum = 0;
- while(!AccountManage::RmAccount(m_strUserName.GetData(),errorCode)){
- rmAccountNum++;
- Dbg("rm account error,rmAccountNum=%d",rmAccountNum);
- if(rmAccountNum > 3){
- LogWarn(Severity_Middle,Error_Unexpect,ERROR_RM_ACCOUNT,"三次删除ClienUser均失败!");
- return false;
- }
- }
- Dbg("rm account succ.");
- return true;
- }
- bool CFreeRDPWrapFSM::Plain2EncodeCipherString(const char* newPasswd, CSimpleStringA& strEnCipherText)
- {
- unsigned char newCipherPasswd[DEF_KEY_SIZE*4] ={0};
- sm4_context sm4Contxt;
- sm4_setkey_enc(&sm4Contxt,key);
- sm4_crypt_ecb(&sm4Contxt,SM4_ENCRYPT,strlen(newPasswd),(unsigned char *)newPasswd, newCipherPasswd);
- Dbg("newCipherPasswd %d",strlen((char*)newCipherPasswd));
- char encodedPasswd[DEF_KEY_SIZE*4]={0};
- base64_encode(encodedPasswd,reinterpret_cast<char *>(newCipherPasswd),DEF_KEY_SIZE);
- Dbg("encodedPasswd %s",encodedPasswd);
- strEnCipherText = encodedPasswd;
- return true;
- }
- bool CFreeRDPWrapFSM::EncodeCipher2PlainString(const CSimpleStringA& strEnCipherText, CSimpleStringA& strPlainText)
- {
- if(strEnCipherText.IsNullOrEmpty()) {
- strPlainText = "";
- return false;
- }
- //base64 decode
- unsigned char decodedPasswd[DEF_KEY_BUFF *4]={0};
- base64_decode(reinterpret_cast<char*>(decodedPasswd),const_cast<char*>(strEnCipherText.GetData()));
- char passwd[DEF_KEY_BUFF] = {0};
- //sm4 decrypt
- sm4_context sm4Contxt;
- sm4_setkey_dec(&sm4Contxt,key);
- sm4_crypt_ecb(&sm4Contxt,SM4_DECRYPT, strlen(reinterpret_cast<char*>(decodedPasswd)),
- decodedPasswd,(unsigned char*)passwd);
- strPlainText = passwd;
- return true;
- }
- void CFreeRDPWrapFSM::BackupClientUserPsw(const CSimpleStringA& psw)
- {
- char encodedPasswd[DEF_KEY_SIZE*4]={0};
- strcpy_s(encodedPasswd, psw.GetData());
- if(OperatorFile(DEF_KEY_PATH,false,encodedPasswd)){
- Dbg("write copy passwd SUSS");
- } else {
- Dbg("write copy passwd FAIL");
- }
- }
- void CFreeRDPWrapFSM::RetrieveClientUserPswFromBakup(CSimpleStringA& psw)
- {
- char tmpPasswd[DEF_KEY_BUFF * 4]={0};
- if(OperatorFile(DEF_KEY_PATH, true, tmpPasswd)){
- Dbg("read copy passwd SUSS");
- psw = tmpPasswd;
- }
- else{
- Dbg("read copy passwd FAIL");
- psw = "";
- }
- }
- ErrorCodeEnum CFreeRDPWrapFSM::RetrieveFreeRDPUserPassword(CSimpleStringA& strOutPassword)
- {
- const int PASSWORD_UPDATE_INTERVAL_DAYS = 27;
- CSmartPointer<IEntityFunction> spEntityFunction = GetEntityBase()->GetFunction();
- CSmartPointer<IConfigInfo> spConfig;
- auto ec = spEntityFunction->OpenConfig(Config_Software, spConfig);
- if(FAILURED(ec)) {
- Dbg("Open software config failed");
- return ec;
- }
- CSmartPointer<IConfigInfo> spConfigRun;
- ec = spEntityFunction->OpenConfig(Config_Run, spConfigRun);
- if(FAILURED(ec)) {
- Dbg("Open run config failed");
- return ec;
- }
- strOutPassword = DEFAULT_CLIENT_USER_PASSWORD;
- bool isRuncfgNotInitialized = false;
- CSimpleStringA compatible = "";
- ec = spConfigRun->ReadConfigValue("Init","Compatible", compatible);
- //if run config no exist then create
- if(FAILURED(ec) || compatible.IsNullOrEmpty()) {
- Dbg("Read run config Init.Compatible failed");
- isRuncfgNotInitialized = true;
- ec = spConfigRun->WriteConfigValue("Init","Compatible", "Yes");
- if(FAILURED(ec)) {
- Dbg("Write run config Init.Compatible failed");
- }
- ec = spConfigRun->WriteConfigValue(m_strUserName.GetData(),"LastUpdatePasswdDate","");
- if(FAILURED(ec)) {
- Dbg("Write run config %s.LastUpdatePasswdDate failed with compatible mode",m_strUserName.GetData());
- }
- ec = spConfigRun->WriteConfigValue(m_strUserName.GetData(),"Password","");
- if(FAILURED(ec)) {
- Dbg("Write run config %s.Password failed with compatible mode",m_strUserName.GetData());
- }
- }
- CSimpleStringA lastUpdatePasswdDate;
- Common::Now *now = new Common::Now();
- CSimpleStringA strToday = now->Today();
- delete now;
- spConfigRun->ReadConfigValue(m_strUserName.GetData(), "LastUpdatePasswdDate", lastUpdatePasswdDate);
- //if lastUpdatePasswdDate is null or empty, then set it to today
- if(lastUpdatePasswdDate.IsNullOrEmpty())
- {
- spConfigRun->WriteConfigValue(m_strUserName.GetData(),"LastUpdatePasswdDate", strToday);
- lastUpdatePasswdDate = strToday;
- Dbg("There are no update history.");
- } else {
- Dbg("Last update date: %s",lastUpdatePasswdDate.GetData());
- }
- int updatePasswdIntervals = 0;
- // Change key from 'UpdatePasswdIntervals' to 'UpdatePswIntervals' for activing new interval value.
- spConfigRun->ReadConfigValueInt(m_strUserName.GetData(), "UpdatePswIntervals", updatePasswdIntervals);
- if(updatePasswdIntervals == 0) {
- updatePasswdIntervals = PASSWORD_UPDATE_INTERVAL_DAYS;
- }
- Dbg("updatePasswdIntervals %d(days)", updatePasswdIntervals);
- Common::Date theFutureUpdateDate(lastUpdatePasswdDate);
- theFutureUpdateDate += updatePasswdIntervals;
- Dbg("Today %s, The future update date %s", strToday.GetData(), theFutureUpdateDate.ToCSimpleStringA().GetData());
- bool isTimeExpired = (strcmp(strToday.GetData(),theFutureUpdateDate.ToCSimpleStringA().GetData()) >= 0);
- int createAccountTimes = 0;
- NEWACCOUNT:
- //judge user whether exist,if no then create
- if(!AccountManage::CheckAccount(m_strUserName.GetData()))
- {
- if(createAccountTimes > 3) {
- return Error_Break;
- }
- Dbg("To create client user account...");
- ec = CreateClientUserAccount();
- if(FAILURED(ec)) {
- return ec;
- }
- spConfigRun->WriteConfigValue(m_strUserName.GetData(),"LastUpdatePasswdDate", strToday);
- isTimeExpired = false;
- isRuncfgNotInitialized = false;
- createAccountTimes++;
- }
- ec = GetClientUserPsw(!isRuncfgNotInitialized, strOutPassword);
- if(ec == Error_DataCheck) {
- Dbg("passwd incorrect, will rm account");
- if(RemoveClientUser()) {
- goto NEWACCOUNT;
- } else {
- return Error_Unexpect;
- }
- } else if(ec != Error_Succeed) {
- return ec;
- }
- if(isTimeExpired || isRuncfgNotInitialized)
- {
- char passwd[DEF_KEY_BUFF] = {0};
- char newPasswd[DEF_KEY_BUFF] = {0};
- Dbg("start modefy user passwd ex");
- strcpy_s(passwd, strOutPassword.GetData());
- //generate new passwd
- memset(newPasswd,0,sizeof(newPasswd));
- Common::GenerateRandomPassword((unsigned char*)newPasswd, DEF_KEY_SIZE);
- Dbg("userName %s", m_strUserName.GetData());
- Dbg("passwd %s",passwd);
- Dbg("newPasswd %s",newPasswd);
- if(AccountManage::ModefyUserPsw(m_strUserName.GetData(), passwd, newPasswd))
- {
- Dbg("Modify passwd SUSS");
- CSimpleStringA strNewPassword(newPasswd);
- ec = StoreFreeRDPUserPassword(strNewPassword);
- if(ec == Error_Succeed) {
- spConfigRun->WriteConfigValue(m_strUserName.GetData(),"LastUpdatePasswdDate", strToday);
- }
- strOutPassword = strNewPassword;
- } else {
- Dbg("Modify passwd error");
- }
- } else {
- Dbg("Passwd not expired");
- }
- return ec;
- }
- ErrorCodeEnum CFreeRDPWrapFSM::StoreFreeRDPUserPassword(const CSimpleStringA& strInPassword)
- {
- CSmartPointer<IEntityFunction> spEntityFunction = GetEntityBase()->GetFunction();
- CSmartPointer<IConfigInfo> spConfigRun;
- auto ec = spEntityFunction->OpenConfig(Config_Run, spConfigRun);
- if(FAILURED(ec)) {
- Dbg("Open run config failed");
- return ec;
- }
- CSimpleStringA strEncodePassword(true);
- Plain2EncodeCipherString(strInPassword, strEncodePassword);
- ec = spConfigRun->WriteConfigValue(m_strUserName, "Password", strEncodePassword);
- if(FAILURED(ec)) {
- Dbg("Write run config encodedPasswd(%s) passwd(%s) error", strEncodePassword.GetData(), strInPassword.GetData());
- return ec;
- } else {
- Dbg("Write run config encodedPasswd(%s) passwd(%s) succeed.", strEncodePassword.GetData(), strInPassword.GetData());
- }
- BackupClientUserPsw(strEncodePassword);
- return Error_Succeed;
- }
- ErrorCodeEnum CFreeRDPWrapFSM::TryChangeClientUserPswWithDefault()
- {
- LOG_FUNCTION();
- CSimpleStringA strPassword;
- auto ec = GetClientUserPsw(true, strPassword);
- if(FAILURED(ec) || strPassword.Compare(DEFAULT_CLIENT_USER_PASSWORD) == 0) {
- return ec;
- }
- if(AccountManage::ModefyUserPsw(m_strUserName.GetData(), DEFAULT_CLIENT_USER_PASSWORD, strPassword.GetData()))
- {
- LogWarn(Severity_Middle, Error_DataCheck,
- ERROR_FREERDP_FREERDP_PASSWORD_RESET, "modify passwod with old default password succeed.");
- return Error_Succeed;
- }
- Dbg("Try to change client user psw failed.");
- return Error_NotMeetCondition;
- }
- BOOL CFreeRDPWrapFSM::ShowFreeRDPCursor(BOOL bShow /*= TRUE*/)
- {
- HWND hwnd = FindWindow(TEXT("rvc_cursor"), NULL);
- if(hwnd == NULL) {
- Dbg("Find rvc_cursor window handle failed");
- return FALSE;
- }
- DWORD dwEvent = bShow ? CDEVENT_SHOW_CURSOR : CDEVENT_HIDE_CURSOR;
- COPYDATASTRUCT cpd;
- cpd.dwData = 520;
- cpd.cbData = sizeof(DWORD);
- cpd.lpData = &dwEvent;
- if(SendMessage(hwnd, WM_COPYDATA, (WPARAM)hwnd, (LPARAM)(LPVOID)&cpd)) {
- Dbg("SendMessage to rvc_cursor window handle succ.");
- return TRUE;
- }
- return FALSE;
- }
- ErrorCodeEnum CFreeRDPWrapFSM::UpdateAndChangeSrvStatus()
- {
- ErrorCodeEnum ec = Error_Unexpect;
- SC_HANDLE h_scm = NULL;
- SC_HANDLE h_srv = NULL;
- CSimpleStringA strPath;
- LPCTSTR lpcszFileName = FREERDP_SVC_NAME;
- char szCmdLine[MAX_PATH] = {0};
- BOOL fReStarted = FALSE, fNeedUpdate = FALSE, fNeedChange = FALSE;
- DWORD dwBytesNeeded, cbBufSize, dwError;
- LPQUERY_SERVICE_CONFIG lpsc = NULL;
- SERVICE_STATUS_PROCESS ssStatus;
- if(GetEntityBase()->GetFunction()->GetPath("Bin", strPath) != Error_Succeed
- || strPath.IsNullOrEmpty())
- {
- Dbg("GetPath about bin failed");
- goto Error;
- }
- strPath += "\\";
- strPath += lpcszFileName;
- h_scm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
- if(h_scm == NULL) {
- dwError = GetLastError();
- Dbg("Open scm failed, GLE=%u", dwError);
- goto Error;
- }
- Restart:
- h_srv = OpenService(h_scm, SERVICE_SPECIFICED_NAME, SERVICE_QUERY_CONFIG);
- dwError = GetLastError();
- if(h_srv == NULL && dwError == ERROR_SERVICE_DOES_NOT_EXIST) {
- if(fReStarted) {
- ec = Error_NoPrivilege;
- goto Error;
- }
- if(!ExistsFileA(strPath)) {
- Dbg("%s is not existed.", lpcszFileName);
- ec = Error_NotExist;
- goto Error;
- }
- memset(szCmdLine, 0, sizeof(szCmdLine));
- strcpy_s(szCmdLine, strPath);
- strcat_s(szCmdLine, " -i");
- if(!(ExecWaitWithExitCode(szCmdLine, dwError)) || dwError != 0) {
- goto Error;
- }
- fReStarted = TRUE;
- goto Restart;
- }
- if(h_srv != NULL) {
- if(!QueryServiceConfig(h_srv, NULL, 0, &dwBytesNeeded)) {
- dwError = GetLastError();
- if(ERROR_INSUFFICIENT_BUFFER == dwError) {
- cbBufSize = dwBytesNeeded;
- lpsc = (LPQUERY_SERVICE_CONFIG)LocalAlloc(LMEM_FIXED, cbBufSize);
- } else {
- Dbg("QueryServiceConfig failed, GLE=%d", dwError);
- goto Error;
- }
- }
- if(!QueryServiceConfig(h_srv, lpsc, cbBufSize, &dwBytesNeeded)) {
- dwError = GetLastError();
- Dbg("QueryServiceConfig twice failed, GLE=%d", dwError);
- goto Error;
- }
- if(_strnicmp(strPath, lpsc->lpBinaryPathName, strPath.GetLength()) != 0) {
- Dbg("%s VS %s", lpsc->lpBinaryPathName, (LPCSTR)strPath);
- fNeedUpdate = TRUE;
- }
- if(lpsc->dwStartType != SERVICE_AUTO_START) {
- fNeedChange = TRUE;
- }
- }
- if(fNeedUpdate) {
- CloseServiceHandle(h_srv);
- h_srv = NULL;
- memset(szCmdLine, 0, sizeof(szCmdLine));
- strcpy_s(szCmdLine, strPath);
- strcat_s(szCmdLine, " -u");
- if(!(ExecWaitWithExitCode(szCmdLine, dwError)) || dwError != 0) {
- goto Error;
- }
- memset(szCmdLine, 0, sizeof(szCmdLine));
- strcpy_s(szCmdLine, strPath);
- strcat_s(szCmdLine, " -i");
- if(!(ExecWaitWithExitCode(szCmdLine, dwError)) || dwError != 0) {
- goto Error;
- }
- memset(szCmdLine, 0, sizeof(szCmdLine));
- strcpy_s(szCmdLine, strPath);
- strcat_s(szCmdLine, " -t");
- if(!(ExecWaitWithExitCode(szCmdLine, dwError)) || dwError != 0) {
- goto Error;
- }
- }
- if(h_srv != NULL) {
- CloseServiceHandle(h_srv);
- h_srv = NULL;
- }
- h_srv = OpenService(h_scm, SERVICE_SPECIFICED_NAME, SERVICE_QUERY_STATUS);
- dwError = GetLastError();
- if(h_srv == NULL) {
- Dbg("open service failed, GLE=%d", dwError);
- goto Error;
- }
- if(!QueryServiceStatusEx(h_srv, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssStatus, sizeof(SERVICE_STATUS_PROCESS), &dwBytesNeeded)) {
- dwError = GetLastError();
- Dbg("QueryServiceStatusEx failed, GLE=%d", dwError);
- goto Error;
- }
- Dbg("The service's current status: %d", ssStatus.dwCurrentState);
- if(ssStatus.dwCurrentState != SERVICE_RUNNING && ssStatus.dwCurrentState != SERVICE_START_PENDING) {
- memset(szCmdLine, 0, sizeof(szCmdLine));
- strcpy_s(szCmdLine, strPath);
- strcat_s(szCmdLine, " -t");
- if(!(ExecWaitWithExitCode(szCmdLine, dwError)) || dwError != 0) {
- goto Error;
- }
- }
- ec = Error_Succeed;
- Error:
- if(lpsc) {
- LocalFree(lpsc);
- }
- if(h_srv) {
- CloseServiceHandle(h_srv);
- }
- if(h_scm) {
- CloseServiceHandle(h_scm);
- }
- return ec;
- }
- BOOL CFreeRDPWrapFSM::ExecWaitWithExitCode(LPTSTR lpszCmdLine, DWORD& dwExitCode)
- {
- BOOL fResult = FALSE;
- STARTUPINFO si = { 0 };
- PROCESS_INFORMATION pi = { 0 };
- ZeroMemory(&si, sizeof(STARTUPINFO));
- si.cb = sizeof(si);
- dwExitCode = 0;
- if (!CreateProcess(NULL, lpszCmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
- dwExitCode = GetLastError();
- Dbg("CreateProcess with \"%s\" error, GLE=%u.", lpszCmdLine, dwExitCode);
- if(dwExitCode == 2 || dwExitCode == 5) {
- char* point = strstr(lpszCmdLine, "bcdedit.exe");
- if(point != NULL) {
- char bak[MAX_PATH] = {0};
- strcpy_s(bak, ".\\bin\\RvcHIDFilter\\bcdedit.exe");
- strcat_s(bak, point+strlen("bcdedit.exe"));
- if(!CreateProcess(NULL, bak, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
- dwExitCode = GetLastError();
- Dbg("CreateProcess with \"%s\" error, GLE=%u.", bak, dwExitCode);
- return fResult;
- }
- else {
- Dbg("CreateProcess with \"%s\" succ.", bak);
- }
- }
- }
- }
- CloseHandle(pi.hThread);
- WaitForSingleObject(pi.hProcess, INFINITE);
- GetExitCodeProcess(pi.hProcess, &dwExitCode);
- Dbg("\"%s\" process quit! exit code: %d", lpszCmdLine, dwExitCode);
- CloseHandle(pi.hProcess);
- return TRUE;
- }
- BOOL CFreeRDPWrapFSM::ExecWaitWithResultContent(LPTSTR lpszCmdLine, CSimpleStringA& strResult)
- {
- LOG_FUNCTION();
- BOOL fResult = FALSE;
- STARTUPINFO si = { 0 };
- SECURITY_ATTRIBUTES sa = {0};
- PROCESS_INFORMATION pi = { 0 };
- HANDLE hOutRead = NULL;
- HANDLE hOutWrite = NULL;
- HANDLE hInRead = NULL;
- HANDLE hInWrite = NULL;
- char szBuffer[2049] = {0};
- DWORD dwNumOfBytesRead = 0;
- DWORD dwExitCode = 0;
- sa.nLength = sizeof(sa);
- sa.bInheritHandle = TRUE;
- sa.lpSecurityDescriptor = NULL;
- CreatePipe(&hOutRead, &hOutWrite, &sa, 0);
- CreatePipe(&hInRead, &hInWrite, &sa, 0);
- ZeroMemory(&si, sizeof(STARTUPINFO));
- si.cb = sizeof(si);
- GetStartupInfo(&si);
- si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
- si.wShowWindow = SW_HIDE;
- si.hStdInput = hInRead;
- si.hStdOutput = hOutWrite;
- si.hStdError = hOutWrite;
- if (!CreateProcess(NULL, lpszCmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
- dwExitCode = GetLastError();
- Dbg("CreateProcess with <%s> error, GLE=%u.", lpszCmdLine, dwExitCode);
- if(dwExitCode == 2 || dwExitCode == 5) {
- char* point = strstr(lpszCmdLine, "bcdedit.exe");
- if(point != NULL) {
- char bakup[MAX_PATH] = {0};
- strcpy_s(bakup, ".\\bin\\RvcHIDFilter\\bcdedit.exe");
- strcat_s(bakup, point+strlen("bcdedit.exe"));
- if(!CreateProcess(NULL, bakup, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
- dwExitCode = GetLastError();
- Dbg("CreateProcess with <%s> error, GLE=%u.", bakup, dwExitCode);
- CloseHandle(hOutWrite);
- CloseHandle(hInRead);
- CloseHandle(pi.hThread);
- return fResult;
- } else {
- Dbg("CreateProcess with \"%s\" succ.", bakup);
- }
- }
- } else {
- CloseHandle(hOutWrite);
- CloseHandle(hInRead);
- CloseHandle(pi.hThread);
- return fResult;
- }
- }
- CloseHandle(hOutWrite);
- CloseHandle(hInRead);
- CloseHandle(pi.hThread);
- fResult = TRUE;
- strResult = "";
- while(TRUE) {
- fResult = ReadFile(hOutRead, &szBuffer, 2048, &dwNumOfBytesRead, NULL);
- if(!fResult) {
- LogError(Severity_Low, Error_IO, 0,
- CSimpleStringA::Format("Error reading pipe, GLE=%d", GetLastError()));
- break;
- }
- szBuffer[dwNumOfBytesRead > 2048 ? 2048 : dwNumOfBytesRead] = '\0';
- strResult += CSimpleStringA(szBuffer);
- //Dbg("%s", szBuffer);
- memset(szBuffer, 0, sizeof(szBuffer));
- }
- Dbg("Content==>");
- Dbg("%s", (LPCTSTR)strResult);
- Dbg("<==Content");
- WaitForSingleObject(pi.hProcess, 10 * 1000);
- GetExitCodeProcess(pi.hProcess, &dwExitCode);
- Dbg("\"%s\" process quit! exit code: %d", lpszCmdLine, dwExitCode);
- CloseHandle(pi.hProcess);
- CloseHandle(hOutRead);
- CloseHandle(hInWrite);
- return TRUE;
- }
- /*
- ErrorCodeEnum CFreeRDPWrapFSM::CreateProcessRunAs(LPCTSTR lpcszCmdLine, LPCTSTR lpcszUserName)
- {
- LPCTSTR lpcszFileName = "wFreeWrapSvc.exe";
- ErrorCodeEnum ec = Error_Unexpect;
- static char szCmdLine[MAX_PATH] = {0};
- DWORD dwError;
- BOOL fSvcCreated = FALSE;
- SC_HANDLE h_scm = NULL;
- SC_HANDLE h_srv = NULL;
- PROCESS_INFORMATION pi = {0};
- CSimpleStringA strPath;
- if(GetEntityBase()->GetFunction()->GetPath("Bin", strPath) != Error_Succeed
- || strPath.IsNullOrEmpty())
- {
- Dbg("GetPath about bin failed");
- return Error_Param;
- }
- strPath += "\\";
- strPath += lpcszFileName;
- Dbg("FilePath: %s", (LPCTSTR)strPath);
- if(!ExistsFileA(strPath)) {
- Dbg("%s is not existed.", lpcszFileName);
- return Error_Resource;
- }
- h_scm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
- if(h_scm == NULL) {
- dwError = GetLastError();
- Dbg("Open scm failed, GLE=%u", dwError);
- goto Error;
- }
- h_srv = OpenService(h_scm, SERVICE_SPECIFICED_NAME, SERVICE_USER_DEFINED_CONTROL);
- dwError = GetLastError();
- if(h_srv || (h_srv == NULL && dwError != ERROR_SERVICE_DOES_NOT_EXIST)) {
- if(h_srv) {
- CloseServiceHandle(h_srv);
- h_srv = NULL;
- }
- memset(szCmdLine, 0, sizeof(szCmdLine));
- strcpy_s(szCmdLine, strPath);
- strcat_s(szCmdLine, " -u");
-
- if(!(ExecWaitWithExitCode(szCmdLine, dwError)) || dwError != 0) {
- goto Error;
- }
- }
- memset(szCmdLine, 0, sizeof(szCmdLine));
- strcpy_s(szCmdLine, strPath);
- strcat_s(szCmdLine, " -i");
- if(!(ExecWaitWithExitCode(szCmdLine, dwError)) || dwError != 0) {
- goto Error;
- }
- memset(szCmdLine, 0, sizeof(szCmdLine));
- strcpy_s(szCmdLine, strPath);
- strcat_s(szCmdLine, " -t");
- if(!(ExecWaitWithExitCode(szCmdLine, dwError)) || dwError != 0) {
- goto Error;
- }
- CloseServiceHandle(h_scm);
- h_scm = NULL;
-
- fSvcCreated = TRUE;
- if(!CreateProcessFromSrv(lpcszCmdLine, lpcszUserName, &pi)) {
- goto Error;
- }
- ec = Error_Succeed;
- Error:
- if(fSvcCreated) {
- memset(szCmdLine, 0, sizeof(szCmdLine));
- strcpy_s(szCmdLine, strPath);
- strcat_s(szCmdLine, " -u");
- ExecWaitWithExitCode(szCmdLine, dwError);
- }
- if(h_srv) {
- CloseServiceHandle(h_srv);
- }
- if(h_scm) {
- CloseServiceHandle(h_scm);
- }
- return ec;
- }
- */
- ErrorCodeEnum CFreeRDPWrapFSM::CreateProcessFromSrvWait(
- LPCTSTR lpcszCmdLine, LPCTSTR lpcszUserName, PROCESS_INFORMATION *ppi)
- {
- ErrorCodeEnum ec;
- DWORD dwSession;
- int ret;
- ec = CreateProcessFromSrv(lpcszCmdLine, lpcszUserName, ppi);
- if(ec == Error_NoTarget) {
- int times = 0;
- do
- {
- Sleep(3000);
- ret = CheckActivedSession(lpcszUserName, &dwSession);
- Dbg("ret = %d", ret);
- if(ret == 3) {
- ec = CreateProcessFromSrv(lpcszCmdLine, lpcszUserName, NULL);
- break;
- }
- if(++times >= 10) {
- ec = Error_TimeOut;
- break;
- }
- } while (true);
- }
- return ec;
- }
- ErrorCodeEnum CFreeRDPWrapFSM::CreateProcessFromSrv(
- LPCTSTR lpcszCmdLine, LPCTSTR lpcszUserName, PROCESS_INFORMATION *ppi)
- {
- static const char szName[] = "Global\\SpModProcessXCreate";
- HANDLE hMapFile = NULL;
- SERVICE_STATUS status = {0};
- PSP_CREATE_PROCESS_INFO pbuf = NULL;
- int buf_size;
- SC_HANDLE h_scm = NULL;
- SC_HANDLE h_srv = NULL;
- DWORD dwError;
- ErrorCodeEnum ec = Error_Unexpect;
- if(m_DeactiveClientManager) {
- Dbg("the client user is depecrated!");
- ec = Error_InvalidState;
- return ec;
- }
- Dbg("Wait ...");
- dwError = WaitForSingleObject(m_hSrvMutex, 8000);
- if(dwError == WAIT_TIMEOUT) {
- Dbg("Need to wait a minute bz it make someone seem hurry up...");
- return Error_Pending;
- }
- Dbg("Wait finished.");
- h_scm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
- if(h_scm == NULL) {
- dwError = GetLastError();
- Dbg("Open scm failed, GLE=%u", dwError);
- goto Error;
- }
- h_srv = OpenService(h_scm, SERVICE_SPECIFICED_NAME, SERVICE_USER_DEFINED_CONTROL);
- if(h_srv == NULL) {
- dwError = GetLastError();
- if(dwError == ERROR_SERVICE_DOES_NOT_EXIST) {
- Dbg("The specified service does not exist ");
- ec = Error_NotExist;
- }else {
- Dbg("Open service failed, GLE=%u", dwError);
- }
- goto Error;
- }
- SP_CREATE_PROCESS_INFO info;
- ZeroMemory(&info, sizeof(SP_CREATE_PROCESS_INFO));
- buf_size = sizeof(SP_CREATE_PROCESS_INFO);
- hMapFile = CreateFileMapping(
- INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, buf_size, szName);
- if(hMapFile == NULL) {
- dwError = GetLastError();
- Dbg("Create file map failed, GLE=%u", dwError);
- goto Error;
- }
- pbuf = (PSP_CREATE_PROCESS_INFO)MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS,
- 0, 0, buf_size);
- if(pbuf == NULL) {
- dwError = GetLastError();
- Dbg("Could not map view of file (%d).", dwError);
- goto Error;
- }
- Dbg("MapViewOfFile succ.");
- info.usVersion = SVC_CREATE_PROCESS_VERSION_1;
- strcpy_s(info.szCmdline, lpcszCmdLine);
- strcpy_s(info.szUserName, lpcszUserName);
- Dbg("Srv::CmdLine: {%s}, user: {%s}", info.szCmdline, info.szUserName);
- CopyMemory((PVOID)pbuf, &info, buf_size);
- if(!ControlService(h_srv, SERVICE_CONTROL_CREATEPROCESS, &status)) {
- dwError = GetLastError();
- if(dwError == ERROR_SERVICE_NOT_ACTIVE) {
- Dbg("The service has not been started.");
- ec = Error_InvalidState;
- }
- else {
- Dbg("Control service failed, GLE=%u", dwError);
- }
- goto Error;
- }
- Dbg("Control Service succ.");
- ec = Error_Succeed;
- if(pbuf->usValiSize == 0) {
- Dbg("map file returned value indicates that operation is failed.");
- if(pbuf->dwLastError == ERROR_NO_SUCH_LOGON_SESSION) {
- ec = Error_NoTarget;
- } else {
- ec = Error_Process;
- }
- }else if(ppi) {
- memcpy(ppi, &(pbuf->pi), sizeof(PROCESS_INFORMATION));
- Dbg("pid %d, handle 0x%x", ppi->dwProcessId, ppi->hProcess);
- }
- Error:
- if(h_srv) {
- CloseServiceHandle(h_srv);
- }
- if(h_scm) {
- CloseServiceHandle(h_scm);
- }
- if(pbuf) {
- UnmapViewOfFile(pbuf);
- }
- if(hMapFile) {
- CloseHandle(hMapFile);
- }
- ReleaseMutex(m_hSrvMutex);
- return ec;
- }
- inline void CFreeRDPWrapFSM::SendWfreeWrapEvt(int evtType, int reserved1 /*= 0*/, int reserved2 /*= 0*/)
- {
- DWORD dwREcipents = BSM_APPLICATIONS | BSM_ALLDESKTOPS;
- WfreeWrapEvt evt;
- evt.evtType = evtType;
- ErrorCodeEnum ec = SpSendBroadcast(m_pEntity->GetFunction(),
- SP_MSG_OF(WfreeWrapEvt),SP_MSG_SIG_OF(WfreeWrapEvt), evt);
- Dbg("Send WfreeWrapEvt brocast: %d ! ec = 0x%X", evt.evtType, ec);
- if(evtType > 0 && (ShareMode)evtType == AM2Client) {
- if(WM_DESKSHARE_MSG != 0) {
- if(0 >= BroadcastSystemMessageA(BSF_POSTMESSAGE | BSF_FORCEIFHUNG | BSF_IGNORECURRENTTASK,
- &dwREcipents, WM_DESKSHARE_MSG, DESKSHARE_FLAG_CONDITION, FLAG_CONDITION_VIEWER)) {
- Dbg("BroadcastSystemMessageA failed %d", GetLastError());
- }
- } else {
- Dbg("WM_DESKSHARE_MSG is invalid!!");
- }
- } else if(evtType < 0 && (ShareMode)(0-evtType) == AM2Client) {
- if(WM_DESKSHARE_MSG != 0) {
- if(0 >= BroadcastSystemMessageA(BSF_POSTMESSAGE | BSF_FORCEIFHUNG | BSF_IGNORECURRENTTASK,
- &dwREcipents, WM_DESKSHARE_MSG, DESKSHARE_FLAG_CONDITION, FLAG_CONDITION_DONE)) {
- Dbg("BroadcastSystemMessageA failed %d", GetLastError());
- }
- } else {
- Dbg("WM_DESKSHARE_MSG is invalid!!");
- }
- }
- }
- ErrorCodeEnum CFreeRDPWrapFSM::CreateDeskShareProc(bool force)
- {
- DWORD dwSession = 0;
- int ret = 0;
- CSimpleStringA strPath;
- ErrorCodeEnum ec = Error_Succeed;
- BOOL bAvailable = FALSE;
- //Check whether the share desktop appliation is alive
- BOOL bAlive = RDPPipe_IsClientSurvival(bAvailable);
- if(bAlive) {
- if(!force) {
- if(bAvailable) {
- return Error_AlreadyExist;
- }
- Dbg("SpDeskShare is not available !!!!");
- }
- Dbg("SpDeskShare.exe is survived, force to kill it(%d).", bAvailable);
- char szCmdLine[MAX_PATH] = {0};
- strcpy_s(szCmdLine, "taskkill /F /IM SpDeskShare.exe /T");
- ec = CreateProcessFromSrvWait(szCmdLine, (LPCTSTR)m_strUserName, NULL);
- if(ec != Error_Succeed) {
- Dbg("taskkill failed, ec=%d", ec);
- bAlive = false;
- }
- }
- if(GetEntityBase()->GetFunction()->GetPath("Bin", strPath) != Error_Succeed
- || strPath.IsNullOrEmpty())
- {
- Dbg("GetPath about bin failed");
- return Error_NoPrivilege;
- }
- strPath += "\\SpDeskShare.exe";
- if(!ExistsFileA(strPath)) {
- Dbg("%s is not existed.", (LPCTSTR)strPath);
- return Error_NotExist;
- }
- Dbg("test: %s(%d)", (LPCTSTR)m_strUserName, bAlive);
- if(bAlive) {
- Sleep(1500);
- ec = CreateProcessFromSrv(strPath, (LPCTSTR)m_strUserName, NULL);
- } else {
- ec = CreateProcessFromSrvWait(strPath, (LPCTSTR)m_strUserName, NULL);
- }
- return ec;
- }
- int CFreeRDPWrapFSM::CreateInstallDrvTask(const BOOL& kbdRequired, const BOOL& mouRequired)
- {
- if(!kbdRequired && !mouRequired) {
- return 0;
- }
- DrvInstallTask* task = new DrvInstallTask(this);
- task->kbdRequired = kbdRequired;
- task->mouRequired = mouRequired;
- if(GetEntityBase()->GetFunction()->PostThreadPoolTask(task) == Error_Succeed) {
- return 1;
- }
- Dbg("Zero ???");
- return 0;
- }
- ErrorCodeEnum CFreeRDPWrapFSM::InstallFiltrDriver(DEVTYPE dt)
- {
- CSimpleStringA strInfPath = "";
- DWORD dwResult = 0;
- SYSTEM_INFO sysInfo = {};
- GetNativeSystemInfo(&sysInfo);
- bool bX64 = (sysInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64);
- char szCmdLine[MAX_PATH] = {0};
- CSimpleStringA strPath;
- if(this->GetEntityBase()->GetFunction()->GetPath("Bin", strPath) != Error_Succeed) {
- return Error_NoPrivilege;
- }
- if (bX64) {
- if(dt == DEV_MOUSE) {
- strInfPath = strPath + RVC_DRIV_INSTALL_DRI64;
- strInfPath += SYS_MOUSE_DRIVERNAME;
- }else if(dt == DEV_KEYBOARD) {
- strInfPath = strPath + RVC_DRIV_INSTALL_DRI64;
- strInfPath += SYS_KEYBOARD_DRIVERNAME;
- }
- }
- else {
- if(dt == DEV_MOUSE) {
- strInfPath = strPath + RVC_DRIV_INSTALL_DRI;
- strInfPath += SYS_MOUSE_DRIVERNAME;
- }else if(dt == DEV_KEYBOARD) {
- strInfPath = strPath + RVC_DRIV_INSTALL_DRI;
- strInfPath += SYS_KEYBOARD_DRIVERNAME;
- }
- }
- if(!strInfPath.IsNullOrEmpty()) {
- if(!ExistsFileA(strInfPath)) {
- LogWarn(Severity_Middle, Error_NotExist, ERROR_FREERDP_DRIVER_INF_FILE_NOT_EXIST,
- CSimpleStringA::Format("Inf file is not existed: %s", (LPCTSTR)strInfPath));
- return Error_NotExist;
- }
- } else {
- return Error_Param;
- }
- if(bX64) {
- strPath += RVC_DRIV_INSTALL_EXE64;
- } else {
- strPath += RVC_DRIV_INSTALL_EXE;
- }
- if(!ExistsFileA(strPath)) {
- LogWarn(Severity_Middle, Error_NotExist, ERROR_FREERDP_DRIVER_INSTALL_EXE_NOT_EXIST,
- CSimpleStringA::Format("execute program is not existed: %s", (LPCTSTR)strPath));
- Dbg("%s is not existed.", (LPCTSTR)strPath);
- return Error_NotExist;
- }
- memset(szCmdLine, 0, sizeof(szCmdLine));
- sprintf_s(szCmdLine, "%s /Install \"%s\"", (LPCTSTR)strPath, (LPCTSTR)strInfPath);
- if(!(ExecWaitWithExitCode(szCmdLine, dwResult)) || dwResult != 0) {
- LogWarn(Severity_Middle, Error_NotExist, ERROR_FREERDP_DRIVER_INSTALL_EXECUTE_FAILED,
- "execute install task failed!");
- return Error_Unexpect;
- }
- return Error_Succeed;
- }
- void CFreeRDPWrapFSM::CheckCriticalThread()
- {
- static DWORD dwExitCode = 0;
-
- if(m_hWarerThread == NULL
- ||
- (GetExitCodeThread(m_hWarerThread, &dwExitCode) && dwExitCode != STILL_ACTIVE)) {
- m_hWarerThread = NULL;
- m_hWarerThread = CreateThread(
- NULL, 0,
- (LPTHREAD_START_ROUTINE)RDPWarer_MainWndStartAndLoop,
- this,
- 0, &m_dwWarerThreadID);
- if(m_hWarerThread == NULL) {
- LogWarn(Severity_High, Error_Unexpect, 0, "Create Warer thread failed!");
- m_dwWarerThreadID = 0;
- }
- }
- dwExitCode = 0;
- if(m_hWndThread == NULL
- ||
- (GetExitCodeThread(m_hWndThread, &dwExitCode) && dwExitCode != STILL_ACTIVE)) {
- m_hWndThread = NULL;
- m_hWndThread = CreateThread(
- NULL, 0,
- (LPTHREAD_START_ROUTINE)DevMnt_MainWndStartAndLoop,
- this,
- 0, &m_dwWndThreadID);
- if(m_hWndThread == NULL) {
- LogWarn(Severity_High, Error_Unexpect, 0, "Create Wnd thread failed!");
- m_dwWndThreadID = 0;
- }
- }
- dwExitCode = 0;
- if(m_hRDPMaintainThread == NULL
- ||
- (GetExitCodeThread(m_hRDPMaintainThread, &dwExitCode) && dwExitCode != STILL_ACTIVE)) {
- m_hRDPMaintainThread = NULL;
- m_hRDPMaintainThread = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0,
- MaintainFreeRDPRoutine, this, 0, &m_dwRDPMaintainID));
- if(!m_hRDPMaintainThread || m_hRDPMaintainThread == INVALID_HANDLE_VALUE) {
- m_hRDPMaintainThread = NULL;
- LogWarn(Severity_High, Error_Unexpect, 0, "Create RDP maintain thread failed!");
- }
- }
- }
- ErrorCodeEnum CFreeRDPWrapFSM::SetNumLockDefaultStatus()
- {
- ErrorCodeEnum ec = Error_Unexpect;
- DWORD dwFlag = KEY_WRITE | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;;
- if (gArch == 64) {
- Dbg("64bit");
- dwFlag |= KEY_WOW64_64KEY;
- } else {
- Dbg("32bit");
- dwFlag |= KEY_WOW64_32KEY;
- }
- HKEY hKey;
- LONG lResult = RegOpenKeyEx(HKEY_CURRENT_USER, "Control Panel\\Keyboard", 0, dwFlag, &hKey);
- if(lResult == ERROR_SUCCESS) {
- DWORD dwType = REG_SZ;
- DWORD dwSize = MAX_PATH*sizeof(TCHAR);
- TCHAR szValue[MAX_PATH] = { 0 };
- lResult = RegQueryValueEx(hKey, "InitialKeyboardIndicators", NULL, &dwType, (LPBYTE)szValue, &dwSize);
- if(lResult == ERROR_SUCCESS) {
- Dbg("InitialKeyboardIndicators = %s", szValue);
- if(strlen(szValue) == 0 || szValue[0] != '2') {
- //Set num Lock on
- TCHAR szNewValue[] = "2\0";
- DWORD dwValSize = ((DWORD)(_tcslen(szNewValue)) + 1)*sizeof(TCHAR);
- lResult = RegSetValueEx(hKey, "InitialKeyboardIndicators", 0, REG_SZ, (const BYTE*)szNewValue, dwValSize);
- Dbg("Set InitialKeyboardIndicators returned: %d", lResult);
- if(lResult == ERROR_SUCCESS) {
- ec = Error_Succeed;
- }
- } else {
- Dbg("InitialKeyboardIndicators has been alreadly set.");
- ec = Error_Succeed;
- }
- } else {
- Dbg("query value for InitialKeyboardIndicators failed: %d", lResult);
- }
- } else {
- Dbg("open keyboard regedit node failed: %d", lResult);
- }
- if(hKey != NULL) {
- RegCloseKey(hKey);
- }
- SetNumLock(TRUE);
- return ec;
- }
- void CFreeRDPWrapFSM::SetNumLock(BOOL bState)
- {
- BYTE keyState[256];
- GetKeyboardState((LPBYTE)keyState);
- if( (bState && !(keyState[VK_NUMLOCK])) ||
- (!bState && (keyState[VK_NUMLOCK])) ) {
- // Simulate a key press
- keybd_event( VK_NUMLOCK, 0x45,KEYEVENTF_EXTENDEDKEY | 0, 0);
- // Simulate a key release
- keybd_event( VK_NUMLOCK, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
- }
- }
- void CFreeRDPWrapFSM::messageTest(BOOL on)
- {
- DWORD dwREcipents = BSM_APPLICATIONS | BSM_ALLDESKTOPS;
- if(on) {
- if(WM_DESKSHARE_MSG != 0) {
- if(0 >= BroadcastSystemMessageA(BSF_POSTMESSAGE | BSF_FORCEIFHUNG | BSF_IGNORECURRENTTASK,
- &dwREcipents, WM_DESKSHARE_MSG, DESKSHARE_FLAG_CONDITION, FLAG_CONDITION_VIEWER)) {
- Dbg("BroadcastSystemMessageA failed %d", GetLastError());
- }
- } else {
- Dbg("WM_DESKSHARE_MSG is invalid!!");
- }
- } else {
- if(WM_DESKSHARE_MSG != 0) {
- if(0 >= BroadcastSystemMessageA(BSF_POSTMESSAGE | BSF_FORCEIFHUNG | BSF_IGNORECURRENTTASK,
- &dwREcipents, WM_DESKSHARE_MSG, DESKSHARE_FLAG_CONDITION, FLAG_CONDITION_DONE)) {
- Dbg("BroadcastSystemMessageA failed %d", GetLastError());
- }
- } else {
- Dbg("WM_DESKSHARE_MSG is invalid!!");
- }
- }
- }
- UINT WINAPI CFreeRDPWrapFSM::MaintainFreeRDPRoutine(LPVOID param)
- {
- CFreeRDPWrapFSM* fsm = reinterpret_cast<CFreeRDPWrapFSM*>(param);
- if(fsm == NULL) {
- return 0;
- }
- DWORD dwRet;
- BOOL error;
- const int MAX_ERROR_TIMES = 5;
- int nFailedTimes;
- DWORD dwCurTimeoutLevel = 0;
- HANDLE hSnapshot;
- PROCESSENTRY32 procEntry;
- DWORD dwProcessID = (DWORD)-1;
- DWORD dwParentProcID = (DWORD)-1;
- HANDLE& hProcess = fsm->m_hFreeRDPProc;
- DWORD& dwRdpProcessId = fsm->m_dwFreeRDPProcID;
- HANDLE hEvents[2] = {NULL, NULL};
- BOOL bNeedToCreate = TRUE;
- ResetEvent(fsm->hExitEvent);
- hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
- if(hSnapshot == INVALID_HANDLE_VALUE) {
- Dbg("CreateToolhelp32Snapshot failed, GLE=%u", GetLastError());
- return 0;
- }
-
- procEntry.dwSize = sizeof(procEntry);
- if(!Process32First(hSnapshot, &procEntry)) {
- Dbg("Process32First failed, GLE=%u", GetLastError());
- CloseHandle(hSnapshot);
- return 0;
- }
- do
- {
- if(!_stricmp(procEntry.szExeFile, FREERDP_PROCESS)) {
- dwProcessID = procEntry.th32ProcessID;
- dwParentProcID = procEntry.th32ParentProcessID;
- break;
- }
- } while (Process32Next(hSnapshot, &procEntry));
- SAFE_CLOSE_HANDLE(hSnapshot);
-
- if(dwProcessID != (DWORD)-1) {
- Dbg("Find the duplicate " FREERDP_PROCESS " process ! id = %d", dwProcessID);
- CSimpleStringA strPath;
- if(fsm->GetEntityBase()->GetFunction()->GetPath("Bin", strPath) == Error_Succeed
- && !strPath.IsNullOrEmpty())
- {
- strPath += "\\freerdp\\wfreerdp.exe";
- char szProcessPath[MAX_PATH] = {0};
- GetProcessPath(dwProcessID, szProcessPath, MAX_PATH);
- Dbg("GetProcessPath: %s", szProcessPath);
- if(strcmp(szProcessPath, "???") != 0 && _stricmp(szProcessPath, (LPCTSTR)strPath) == 0) {
- bNeedToCreate = FALSE;
- }
- }
- if(bNeedToCreate) {
- if(!KillSpecifiedProcess(dwProcessID)) {
- hProcess = INVALID_HANDLE_VALUE;
- dwRdpProcessId = -1;
- return 0;
- }
- }
- else {
- hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessID);
- if(hProcess == NULL || hProcess == INVALID_HANDLE_VALUE) {
- Dbg("OpenProcess failed, GLE=%d", GetLastError());
- bNeedToCreate = TRUE;
- } else {
- dwRdpProcessId = dwProcessID;
- }
- }
- }
- if(bNeedToCreate) {
- hProcess = fsm->CreateFreeRDPProc(dwRdpProcessId);
- if(hProcess == INVALID_HANDLE_VALUE || hProcess == NULL) {
- hProcess = INVALID_HANDLE_VALUE;
- dwRdpProcessId = -1;
- return 0;
- }
- Dbg("Create " FREERDP_PROCESS " succ, pid = %d", dwRdpProcessId);
- }
- else {
- Dbg("Use the survived process handle.");
- }
- hEvents[0] = hProcess;
- hEvents[1] = fsm->hExitEvent;
- error = FALSE;
- nFailedTimes = 0;
- dwCurTimeoutLevel = 10*1000;
- do
- {
- dwRet = WaitForMultipleObjects(2, hEvents, FALSE, dwCurTimeoutLevel);
- if(dwRet == WAIT_OBJECT_0) {
- //password incorrect: 131092[0x20014]
- DWORD dwExitCode;
- GetExitCodeProcess(hProcess, &dwExitCode);
- Dbg(FREERDP_PROCESS " process quit! exit code: %d[0x%X]", dwExitCode, dwExitCode);
- CloseHandle(hProcess);
- hProcess = INVALID_HANDLE_VALUE;
- dwRdpProcessId = -1;
- if(dwCurTimeoutLevel == 10*1000) {
- if(++nFailedTimes >= MAX_ERROR_TIMES) {
- Dbg("Give up! wait to restart the entity.");
- LogWarn(Severity_Middle, Error_InvalidState,
- ERROR_FREERDP_STARTUP_FAILED_MUCH_TIMES,
- CSimpleStringA::Format("Startup wFreeRDP failed too much time! exit code: 0x%X", dwExitCode));
- fsm->SetSelfCheckCode(Error_InvalidState);
- break;
- }
- }
- if(dwExitCode == 0x20014 && nFailedTimes == MAX_ERROR_TIMES - 1) {
- fsm->TryChangeClientUserPswWithDefault();
- }
- Sleep(3000);
- hProcess = fsm->CreateFreeRDPProc(dwRdpProcessId);
- if(hProcess == INVALID_HANDLE_VALUE) {
- error = TRUE;
- break;
- }
- Dbg("ReCreate " FREERDP_PROCESS " succ, pid = %d", dwRdpProcessId);
- hEvents[0] = hProcess;
- } else if(dwRet == (WAIT_OBJECT_0 + 1)) {
- Dbg("Receive quit message.");
- break;
- } else if(dwRet != WAIT_TIMEOUT) {
- Dbg("Wait for rdp proc and quit event handle failed %d !", dwRet);
- error = TRUE;
- break;
- } else if(dwCurTimeoutLevel == 10*1000) {
- dwCurTimeoutLevel = INFINITE;
- }
- } while (true);
- Dbg("Out of while(true).");
- if(hProcess != INVALID_HANDLE_VALUE) {
- CloseHandle(hProcess);
-
- if(KillSpecifiedProcess(dwRdpProcessId))
- {
- hProcess = INVALID_HANDLE_VALUE;
- dwRdpProcessId = -1;
- }
- }
- Dbg("Exit FreeRDPRoutine thread.");
- ExitThread(0);
- return 0;
- }
- void CFreeRDPWrapFSM::BroadMonitorNumChange(const int curAvailMonitorNums)
- {
- DWORD userCode = 0;
- LOG_ASSERT(curAvailMonitorNums >= 0);
- if(curAvailMonitorNums != m_uMonitorNum)
- {
- switch(curAvailMonitorNums)
- {
- case 0:
- userCode = ERROR_FREERDP_MONITOR_NONE;
- break;
- case 1:
- userCode = ERROR_FREERDP_MONITOR_LACK;
- break;
- case 2:
- userCode = ERROR_FREERDP_MONITOR_ENOUGH;
- break;
- default:
- userCode = ERROR_FREERDP_MONITOR_DUPLICATE;
- break;
- }
- }
- if(curAvailMonitorNums == 1 && m_uMonitorNum > curAvailMonitorNums) {
- CAutoArray<MonitorInfo> monitorArrStatic;
- if(2 == GetMonitorInfoFromRunCfg(monitorArrStatic)) {
- CAutoArray<MonitorInfo> monitorRuntime(2);
- const int nums = GetRealtimeMonitorInfo(monitorRuntime);
- LOG_ASSERT(nums == 1);
- if(monitorRuntime[0].deviceID.Compare(monitorArrStatic[0].deviceID) == 0) {
- userCode = ERROR_FREERDP_MONITOR_VICE_LOST;
- Dbg("the vice monitor(client manager monitor) lost.");
- } else if(monitorRuntime[0].deviceID.Compare(monitorArrStatic[1].deviceID) == 0) {
- userCode = ERROR_FREERDP_MONITOR_PRIMARY_LOST;
- Dbg("the primer monitor(client monitor) lost.");
- } else {
- Dbg("Unknown device: %s", monitorRuntime[0].deviceID.GetData());
- }
- } else {
- Dbg("the RunCfg is not ready yet.");
- }
- }
- if(userCode != 0)
- {
- LogWarn(Severity_Middle, Error_DevNotAvailable, userCode,
- CSimpleStringA::Format("The Monitor num has been changed from %d to %d",
- m_uMonitorNum, curAvailMonitorNums));
- m_uMonitorNum = curAvailMonitorNums;
- }
- }
- ErrorCodeEnum CFreeRDPWrapFSM::AgentAssistant(
- SpReqAnsContext<FreeRDPWrapSrv_AgentAssistant_Req,
- FreeRDPWrapSrv_AgentAssistant_Ans>::Pointer ctx)
- {
- ErrorCodeEnum ec = Error_Succeed;
- USHORT usViewLevel = CTRL_LEVEL_VIEW;
- char szFileName[MAX_PATH] = {0};
- FILE *read = NULL;
- int flen;
- char* inviteString = NULL;
- CSimpleStringW strContent;
- CSimpleStringA str;
- CInteractCtrlClient* client = new CInteractCtrlClient(GetEntityBase());
- UIService_SendAgentText_Req req;
- UIService_SendAgentText_Ans ans;
- ec = client->Connect();
- if(FAILURED(ec)) {
- Display("Connect to InterctiveControl entity failed, EC=0x%X", ec);
- client->SafeDelete();
- client = NULL;
- return ec;
- }
- ec = Error_Unexpect;
- m_bInterview = FALSE;
- if(ctx->Req.viewLevel == 1) {
- usViewLevel = CTRL_LEVEL_INTERACTIVE;
- m_bInterview = TRUE;
- }
- if(m_hWarerThread == INVALID_HANDLE_VALUE || !hWarerWnd) {
- Display("Share window handle is invalid");
- goto Error;
- }
- memset(szFileName, 0, sizeof(szFileName));
- if(!CreateInviteFileName(szFileName, MAX_PATH)) {
- goto Error;
- }
- m_strInviteFileName = szFileName;
- if(!RDPWarer_ShareAndInvite(szFileName, ctx->Req.filterAppId, usViewLevel)) {
- LogWarn(Severity_Middle, Error_Param, ERROR_FREERDP_SHARE_BUILD_UP_SHRER_FAILED, "Do the share and invite Job failed !");
- goto Error;
- }
-
- fopen_s(&read, szFileName, "r");
- if(!read) {
- Display("Open inviation file failed: %s", szFileName);
- goto Error;
- }
- fseek(read, 0, SEEK_END);
- flen = ftell(read);
- if (flen <= 0) {
- fclose(read);
- read = NULL;
- Display("Invalid inviation file !");
- goto Error;
- }
- inviteString = new char[flen + 1];
- if (inviteString == NULL) {
- Display("Alloc invite string failed!");
- ec = Error_Resource;
- goto Error;
- }
- ZeroMemory(inviteString, sizeof(char)*(flen + 1));
- fseek(read, 0, SEEK_SET);
- fgets(inviteString, flen, read);
- inviteString[flen] = '\0';
- fclose(read);
- str = "START_INVITATION_STRING====";
- str += inviteString;
- str += "====END_INVITATION_STRING";
- strContent = CSimpleStringA2W(str);
- Display("==== START INVITATION STRING");
- Display("%s", (LPCTSTR)inviteString);
- Display("==== END INVITATION STRING");
- delete[] inviteString;
- inviteString = NULL;
- Display("==== START INVITATION STRING");
- Display("%ws", (LPCWSTR)strContent);
- Display("==== END INVITATION STRING");
- req.content = strContent;
- ec = client->SendAgentText(req, ans, 10 * 1000);
- if(FAILURED(ec)) {
- Display("Invoke SendAgentText failed, EC=0x%X", ec);
- goto Error;
- }
- Error:
- if(ctx != NULL) {
- ctx->Ans.retCode = Error_Succeed == ec ? 1 : -1;
- ctx->Answer(Error_Succeed);
- }
- if(FAILURED(ec)) {
- RDPWarer_CloseInvite();
- } else {
- m_bAgentSituation = TRUE;
- m_bInvited = FALSE;
- m_eShareMode = m_bInvited ? Seal2Client : Client2Seat;
- }
- client->GetFunction()->CloseSession();
- client->SafeDelete();
- client = NULL;
-
- if(!m_strInviteFileName.IsNullOrEmpty()) {
- DeleteFileA(m_strInviteFileName);
- m_strInviteFileName = "";
- }
- return ec;
- }
- UINT CFreeRDPWrapFSM::UnitTest(LPCTSTR testTag)
- {
- //m_fsm.ShowFreeRDPCursor(FALSE);
- //m_fsm.messageTest(TRUE);
- //m_fsm.unitest_install_rdpwrap_component();
- char test[] = "Cmb@2020";
- CSimpleStringA strEnCippher(true);
- if(!Plain2EncodeCipherString(test, strEnCippher))
- return 1;
- Dbg("encipher: %s", strEnCippher.GetData());
- CSimpleStringA strPlainText(true);
- if(!EncodeCipher2PlainString(strEnCippher, strPlainText))
- return 2;
- if(strPlainText.Compare(test) != 0)
- return 3;
- BackupClientUserPsw(strEnCippher);
- CSimpleStringA strEnCippher2;
- RetrieveClientUserPswFromBakup(strEnCippher2);
- if(strEnCippher2.Compare(strEnCippher) != 0)
- return 4;
- CAutoArray<MonitorInfo> monitorArr(5);
- const int nums = GetRealtimeMonitorInfo(monitorArr);
- if(nums != 1)
- return 5;
- CAutoArray<MonitorInfo> monitorArrStatic;
- if(0 != GetMonitorInfoFromRunCfg(monitorArrStatic)) {
- return 6;
- }
- return 0;
- }
- int CFreeRDPWrapFSM::GetRealtimeMonitorInfo(CAutoArray<MonitorInfo>& monitorArr)
- {
- DISPLAY_DEVICE dd;
- ZeroMemory(&dd, sizeof(dd));
- dd.cb = sizeof(dd);
- int validMonitorNum = 0;
- for(int i=0; EnumDisplayDevicesA(NULL, i, &dd, 0)
- && validMonitorNum < monitorArr.GetCount();
- ++i)
- {
- MonitorInfo& curMonitor = monitorArr[validMonitorNum];
- Dbg("===================");
- Dbg("Device Index(%d)", i);
- Dbg("Device Name: %s", dd.DeviceName);
- Dbg("Device String: %s", dd.DeviceString);
- Dbg("Device ID: %s", dd.DeviceID);
- Dbg("Device Key: %s", dd.DeviceKey);
- Dbg("StateFlags: %s%s%s%s",
- ((dd.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) ? "desktop " : ""),
- ((dd.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE) ? "primary " : ""),
- ((dd.StateFlags & DISPLAY_DEVICE_VGA_COMPATIBLE) ? "vga " : ""),
- ((dd.StateFlags & DISPLAY_DEVICE_MULTI_DRIVER) ? "multi " : ""),
- ((dd.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER) ? "mirror " : ""));
- DISPLAY_DEVICE dd2;
- ZeroMemory(&dd2, sizeof(dd2));
- dd2.cb = sizeof(dd2);
- EnumDisplayDevices(dd.DeviceName, 0, &dd2, 0);
- Dbg("Display Device Name: %s", dd2.DeviceName);
- Dbg("Display Device String: %s", dd2.DeviceString);
- Dbg("Display Device ID: %s", dd2.DeviceID);
- Dbg("Display Device Key: %s", dd2.DeviceKey);
- if(dd.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP
- && strlen(dd2.DeviceName) > 0
- && strlen(dd2.DeviceID) > 0
- && strlen(dd2.DeviceKey) > 0)
- {
- curMonitor.bSet = TRUE;
- curMonitor.bPrimary = (dd.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE);
- curMonitor.deviceName = dd2.DeviceName;
- curMonitor.deviceID = dd2.DeviceID;
- curMonitor.deviceKey = dd2.DeviceKey;
- validMonitorNum++;
- }
- }
-
- Dbg("Get realtime monitor count: %d", validMonitorNum);
- return validMonitorNum;
- }
- int CFreeRDPWrapFSM::GetMonitorInfoFromRunCfg(CAutoArray<MonitorInfo>& monitorArr)
- {
- CSmartPointer<IEntityFunction> spEntityFunction = GetEntityBase()->GetFunction();
- CSmartPointer<IConfigInfo> spConfigRun;
- auto ec = spEntityFunction->OpenConfig(Config_Run, spConfigRun);
- if(FAILURED(ec)) {
- Dbg("Open run config failed");
- return 0;
- }
- Dbg("Read monitor information from RunCfg.");
- int primaryIndex = 0, viceIndex = 1;
- monitorArr.Init(2);
- spConfigRun->ReadConfigValue("PrimaryMonitor", "Name", monitorArr[primaryIndex].deviceName);
- spConfigRun->ReadConfigValue("PrimaryMonitor", "ID", monitorArr[primaryIndex].deviceID);
- spConfigRun->ReadConfigValue("PrimaryMonitor", "Key", monitorArr[primaryIndex].deviceKey);
- spConfigRun->ReadConfigValue("ViceMonitor", "Name", monitorArr[viceIndex].deviceName);
- spConfigRun->ReadConfigValue("ViceMonitor", "ID", monitorArr[viceIndex].deviceID);
- spConfigRun->ReadConfigValue("ViceMonitor", "Key", monitorArr[viceIndex].deviceKey);
- if(monitorArr[primaryIndex].deviceID.IsNullOrEmpty()
- || monitorArr[viceIndex].deviceID.IsNullOrEmpty())
- return 0;
- return monitorArr.GetCount();
- }
- BOOL CFreeRDPWrapFSM::IfDontActiveClientManagerDesk()
- {
- CSmartPointer<IEntityFunction> spFunction = m_pEntity->GetFunction();
- CSmartPointer<IConfigInfo> spConfig;
- ErrorCodeEnum eErr = spFunction->OpenConfig(Config_CenterSetting, spConfig);
- int value = 0;
- if (Error_Succeed == eErr)
- {
- eErr = spConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "Depecrate", value);
- if (Error_Succeed == eErr)
- {
- Dbg("get Depecrate=%d from CenterSetting.ini", value);
- }
- else
- {
- Dbg("get Depecrate from CenterSetting.ini failed");
- }
- }
- return (value == 1);
- }
- bool CFreeRDPWrapFSM::DetectPrimaryMonitors()
- {
- CAutoArray<MonitorInfo> monitorArr(5);
- const int nums = GetRealtimeMonitorInfo(monitorArr);
- if(nums == 2) {
- int primaryIndex = monitorArr[0].bPrimary ? 0 : (monitorArr[1].bPrimary ? 1 : -1);
- int viceIndex = primaryIndex == 0 ? 1 : 0;
- if(primaryIndex == -1) {
- return false;
- }
- CSmartPointer<IEntityFunction> spEntityFunction = GetEntityBase()->GetFunction();
- CSmartPointer<IConfigInfo> spConfigRun;
- auto ec = spEntityFunction->OpenConfig(Config_Run, spConfigRun);
- if(FAILURED(ec)) {
- Dbg("Open run config failed");
- return false;
- }
- Dbg("Write monitor information to RunCfg.");
- spConfigRun->WriteConfigValue("PrimaryMonitor", "Name", monitorArr[primaryIndex].deviceName);
- spConfigRun->WriteConfigValue("PrimaryMonitor", "ID", monitorArr[primaryIndex].deviceID);
- spConfigRun->WriteConfigValue("PrimaryMonitor", "Key", monitorArr[primaryIndex].deviceKey);
- spConfigRun->WriteConfigValue("ViceMonitor", "Name", monitorArr[viceIndex].deviceName);
- spConfigRun->WriteConfigValue("ViceMonitor", "ID", monitorArr[viceIndex].deviceID);
- spConfigRun->WriteConfigValue("ViceMonitor", "Key", monitorArr[viceIndex].deviceKey);
- return true;
- }
- return false;
- }
|