FreeRDPWrapFSM.cpp 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980
  1. #include "stdafx.h"
  2. #include "FreeRDPWrapFSM.h"
  3. #include "Common.h"
  4. #include "base64.h"
  5. #include "sm4.h"
  6. #include "AccountManage.h"
  7. #include "RDPWInst.h"
  8. #include <TlHelp32.h>
  9. #include "fileutil.h"
  10. #include <userenv.h>
  11. #include <WtsApi32.h>
  12. #include <Psapi.h>
  13. #include <tchar.h>
  14. #include "mod_FreeRDPWrap.h"
  15. #include <fstream>
  16. #include <io.h>
  17. #define FREERDP_PROCESS "wfreerdp.exe"
  18. #define REG_MSG_DESKSHARE_FLAG "{A284B1F9-FD11-463B-89FA-474CFFAA55E2}"
  19. #define DEF_KEY_SIZE 16 //default key size
  20. #define DEF_KEY_BUFF 256 //default key buff
  21. #define DEF_KEY_PATH "C:\\user.key" //passwd copy default path
  22. #define DEFAULT_CLIENT_USER_PASSWORD "11111111"
  23. unsigned char key[] = "usinxZsplM195447"; //default key
  24. using namespace std;
  25. static UINT WM_DESKSHARE_MSG = 0;
  26. #define DESKSHARE_FLAG_CONDITION 1 //我的共享状态
  27. #define FLAG_CONDITION_DONE 0 //共享结束
  28. #define FLAG_CONDITION_SHARER 1 //作为分享者
  29. #define FLAG_CONDITION_VIEWER 2 //作为观看者
  30. #define MOD_VERSION "2.0.0.1"
  31. BOOL GetProcessPath(DWORD PID, PTSTR szProcessPath, size_t cchSize)
  32. {
  33. HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
  34. FALSE, PID);
  35. if (hProcess == NULL) {
  36. strcpy_s(szProcessPath, cchSize, "???");
  37. return FALSE;
  38. }
  39. if (GetModuleFileNameEx(hProcess, (HMODULE)0, szProcessPath, cchSize) == 0) {
  40. DWORD dwSize = (DWORD) cchSize;
  41. if(QueryFullProcessImageName(hProcess, 0, szProcessPath, &dwSize) == 0)
  42. {
  43. if (!GetProcessImageFileName(hProcess, szProcessPath, cchSize)) {
  44. strcpy_s(szProcessPath, cchSize, "???");
  45. CloseHandle(hProcess);
  46. return FALSE;
  47. }
  48. }
  49. }
  50. CloseHandle(hProcess);
  51. return TRUE;
  52. }
  53. BOOL KillSpecifiedProcess(DWORD dwProcessID)
  54. {
  55. LOG_FUNCTION();
  56. BOOL ret = FALSE;
  57. HANDLE hProc = OpenProcess(PROCESS_TERMINATE, FALSE, dwProcessID);
  58. if (hProc == NULL) {
  59. Dbg("OpenProcess failed, GLE=%u", GetLastError());
  60. return FALSE;
  61. }
  62. if (!TerminateProcess(hProc, 0)) {
  63. Dbg("TerminateProcess failed, GLE=%u", GetLastError());
  64. }
  65. else {
  66. Dbg("Terminate process succ.");
  67. ret = TRUE;
  68. }
  69. CloseHandle(hProc);
  70. return ret;
  71. }
  72. /*
  73. Returned:
  74. -1: error;
  75. 0: no found;
  76. 1: other status;
  77. 2: disconnect;
  78. 3: actived
  79. */
  80. int CheckActivedSession(const char *lpcszUserName, DWORD *pSessionID)
  81. {
  82. HANDLE cur_token = NULL;
  83. HANDLE primary_token = NULL;
  84. PWTS_SESSION_INFO pWSessionInfo = NULL;
  85. DWORD count = 0;
  86. int size;
  87. DWORD i;
  88. int ret = 0;
  89. if(!WTSEnumerateSessionsA(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pWSessionInfo, &count)) {
  90. return -1;
  91. }
  92. size = (int)sizeof(WTS_SESSION_INFO);
  93. for(i=0; i<count; ++i) {
  94. LPTSTR pbuf = NULL;
  95. DWORD dwLen = 0;
  96. WTS_SESSION_INFO item = pWSessionInfo[i];
  97. Dbg("session#%d's connection state: %d", item.SessionId, item.State);
  98. if(!WTSQuerySessionInformation(WTS_CURRENT_SERVER_NAME,
  99. item.SessionId, WTSUserName,
  100. &pbuf, &dwLen)) {
  101. Dbg("WTSUserName failed, GLE=%u", GetLastError());
  102. ret = -1;
  103. } else {
  104. Dbg("UserName: %s", pbuf);
  105. if(strcmp(pbuf, lpcszUserName) == 0) {
  106. if(pSessionID)
  107. *pSessionID = item.SessionId;
  108. Dbg("Retrieve specified session id: %d", *pSessionID);
  109. if(WTSActive == item.State) {
  110. ret = 3;
  111. } else if(WTSDisconnected == item.State) {
  112. ret = 2;
  113. } else {
  114. ret = 1;
  115. }
  116. WTSFreeMemory(pbuf);
  117. return ret;
  118. }
  119. }
  120. if(pbuf) {
  121. WTSFreeMemory(pbuf);
  122. }
  123. pbuf = NULL;
  124. dwLen = 0;
  125. }
  126. return ret;
  127. }
  128. BOOLEAN SetPrivilege(HANDLE hToken,
  129. LPCTSTR lpszPrivilege,
  130. BOOL bEnablePrivilege
  131. )
  132. {
  133. TOKEN_PRIVILEGES tp;
  134. LUID luid;
  135. if(hToken == INVALID_HANDLE_VALUE) {
  136. if (!OpenProcessToken(GetCurrentProcess(),
  137. TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
  138. LOG_TRACE("OpenProcessToken error: %u", GetLastError());
  139. return FALSE;
  140. }
  141. }
  142. if ( !LookupPrivilegeValue(NULL,lpszPrivilege,&luid ) ){
  143. LOG_TRACE("LookupPrivilegeValue error: %u", GetLastError());
  144. return FALSE;
  145. }
  146. tp.PrivilegeCount = 1;
  147. tp.Privileges[0].Luid = luid;
  148. if (bEnablePrivilege)
  149. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  150. else
  151. tp.Privileges[0].Attributes = 0;
  152. if ( !AdjustTokenPrivileges(hToken, FALSE,&tp,
  153. sizeof(TOKEN_PRIVILEGES),(PTOKEN_PRIVILEGES) NULL,(PDWORD) NULL) ){
  154. Dbg("AdjustTokenPrivileges error: %u.", GetLastError());
  155. return FALSE;
  156. }
  157. if (GetLastError() == ERROR_NOT_ALL_ASSIGNED){
  158. Dbg("The token does not have the specified privilege.");
  159. return FALSE;
  160. }
  161. return TRUE;
  162. }
  163. CFreeRDPWrapFSM::CFreeRDPWrapFSM(void)
  164. :m_strUserName(CLIENET_USER)
  165. ,m_ecSelfTest(Error_Succeed)
  166. ,m_nSrcState(s0)
  167. ,m_hFreeRDPProc(NULL)
  168. ,m_dwFreeRDPProcID(-1)
  169. ,m_hRDPMaintainThread(NULL)
  170. ,m_dwRDPMaintainID(0)
  171. ,m_hWarerThread(NULL)
  172. ,m_dwWarerThreadID(0)
  173. ,m_bInvited(FALSE)
  174. ,m_bInterview(FALSE)
  175. ,m_dwLockScreenMinu(5)
  176. ,m_dwWndThreadID(0)
  177. ,m_hWndThread(NULL)
  178. ,m_hSrvMutex(NULL)
  179. ,m_strInviteFileName(true)
  180. ,m_bAgentSituation(FALSE)
  181. ,m_eShareMode(ClientIdle)
  182. ,m_bTestMode(FALSE)
  183. ,m_uMonitorNum(0)
  184. ,m_DeactiveClientManager(FALSE)
  185. {
  186. }
  187. CFreeRDPWrapFSM::~CFreeRDPWrapFSM(void)
  188. {
  189. LOG_FUNCTION();
  190. if(m_hSrvMutex) {
  191. CloseHandle(m_hSrvMutex);
  192. }
  193. //TerminateRDPRoutine();
  194. //Dbg("WM_EXIT_MSG : %d", WM_EXIT_MSG);
  195. //DWORD dwREcipents = BSM_APPLICATIONS | BSM_ALLDESKTOPS;
  196. //BroadcastSystemMessageA(BSF_POSTMESSAGE | BSF_FORCEIFHUNG, &dwREcipents, WM_EXIT_MSG, 0, 0);
  197. //BroadcastSystemMessageA(BSF_POSTMESSAGE | BSF_FORCEIFHUNG, &dwREcipents, WM_EXIT_MSG_CODE, 0, 0);
  198. if(m_hFreeRDPProc != NULL) {
  199. Dbg("Kill " FREERDP_PROCESS " last.");
  200. if(KillSpecifiedProcess(m_dwFreeRDPProcID)) {
  201. CloseHandle(m_hFreeRDPProc);
  202. }
  203. }
  204. }
  205. ErrorCodeEnum CFreeRDPWrapFSM::OnInit()
  206. {
  207. LOG_FUNCTION();
  208. #ifdef TWINKLE_LOCAL_DEBUG
  209. if (AllocConsole())
  210. {
  211. FILE* here = NULL;
  212. freopen_s(&here, "CONOUT$", "w", stdout);
  213. freopen_s(&here, "CONOUT$", "w", stderr);
  214. Dbg("Debug console created.");
  215. }
  216. #endif
  217. ErrorCodeEnum ec = Error_Unexpect;
  218. DWORD dwUserCode = 0;
  219. int errc = fs_error;
  220. BOOL bWrapInstalled = FALSE;
  221. CSmartPointer<IEntityFunction> spEntityFunction = GetEntityBase()->GetFunction();
  222. CSmartPointer<IConfigInfo> spConfig;
  223. CSimpleStringA strUserName = "";
  224. Dbg("Version %s; Complied at: %s %s", MOD_VERSION, __DATE__, __TIME__);
  225. AddStateHooker(this);
  226. CoInitialize(0);
  227. SendWfreeWrapEvt(-1);
  228. SetSysVal(fs_busy);
  229. ec = spEntityFunction->OpenConfig(Config_Software, spConfig);
  230. if(FAILURED(ec)) {
  231. Dbg("Open software config failed");
  232. m_strUserName = CLIENET_USER;
  233. } else {
  234. ec = spConfig->ReadConfigValue("Init", "UserName", strUserName);
  235. if(strUserName.IsNullOrEmpty()) {
  236. m_strUserName = CLIENET_USER;
  237. } else {
  238. m_strUserName = strUserName;
  239. }
  240. int testMode = 0;
  241. ec = spConfig->ReadConfigValueInt("Init", "TestMode", testMode);
  242. if(ISSUCCEEDED(ec) && testMode > 0) {
  243. Dbg("driver installed requires test mode!!");
  244. m_bTestMode = TRUE;
  245. }
  246. }
  247. WM_DESKSHARE_MSG = ::RegisterWindowMessageA(REG_MSG_DESKSHARE_FLAG);
  248. Dbg("WM_DESKSHARE_MSG = %d!", WM_DESKSHARE_MSG);
  249. RDPPipe_SetReference(this);
  250. RDPWarer_SetReference(this);
  251. DevMnt_SetReference(this);
  252. SetPrivilege(INVALID_HANDLE_VALUE, SE_TCB_NAME, TRUE);
  253. m_hSrvMutex = CreateMutex(NULL, FALSE, NULL);
  254. LOG_ASSERT(m_hSrvMutex != NULL && "Create mutex failed!");
  255. InitEnvironmentValue();
  256. m_uMonitorNum = GetSystemMetrics(SM_CMONITORS);
  257. Dbg("Current screen num:%d", m_uMonitorNum);
  258. if(IfDontActiveClientManagerDesk()) {
  259. LogWarn(Severity_High, Error_InvalidState, ERROR_FREERDP_DEPECRATE_CLIENT_MANAGER,
  260. "the machine has closed the client manager desktop function!");
  261. m_DeactiveClientManager = TRUE;
  262. return Error_Succeed;
  263. }
  264. #ifdef TWINKLE_LOCAL_DEBUG
  265. if(m_uMonitorNum != 2) {
  266. PromptInvalidMonitor();
  267. errc = fs_invalid_monitor;
  268. ec = Error_Succeed;
  269. m_hWndThread = CreateThread(
  270. NULL, 0,
  271. (LPTHREAD_START_ROUTINE)DevMnt_MainWndStartAndLoop,
  272. this,
  273. 0, &m_dwWndThreadID);
  274. if(m_hWndThread == NULL) {
  275. LogWarn(Severity_High, Error_Unexpect, ERROR_DEVICE_MONITOR_CREATE, "Create Wnd thread failed!");
  276. m_dwWndThreadID = 0;
  277. }
  278. goto Error;
  279. }
  280. #endif // TWINKLE_LOCAL_DEBUG
  281. /*RDPWrap component.*/
  282. IFCALLFAILED_LEAD_END(CheckRdpWrapInstall(bWrapInstalled), ERROR_CHECK_RDPWRAP_INSTALL);
  283. if(bWrapInstalled == FALSE) {
  284. IFCALLFAILED_LEAD_END(InstallRdpWrap(), ERROR_RDPWRAP_INSTALL);
  285. LogEvent(Severity_High, Error_Succeed, "Install RDP Wrapper library succ.");
  286. }else {
  287. if(IsWrapperNeedUpdate()) {
  288. IFCALLFAILED_LEAD_END(UpdateRdpWrap(), ERROR_RDPWRAP_UPDATE);
  289. LogEvent(Severity_High, Error_Succeed, "Update RDP Wrapper library succ.");
  290. }
  291. }
  292. /*Check and set Numlock status*/
  293. SetNumLockDefaultStatus();
  294. /*Service component.*/
  295. IFCALLFAILED_LEAD_END(UpdateAndChangeSrvStatus(), ERROR_SERVICE_UPDATE);
  296. /*mouse and keyboard redirect component.*/
  297. m_hWndThread = CreateThread(
  298. NULL, 0,
  299. (LPTHREAD_START_ROUTINE)DevMnt_MainWndStartAndLoop,
  300. this,
  301. 0, &m_dwWndThreadID);
  302. if(m_hWndThread == NULL) {
  303. LogWarn(Severity_High, Error_Unexpect, ERROR_DEVICE_MONITOR_CREATE, "Create Wnd thread failed!");
  304. m_dwWndThreadID = 0;
  305. }
  306. /*screen share component.*/
  307. m_hWarerThread = CreateThread(
  308. NULL, 0,
  309. (LPTHREAD_START_ROUTINE)RDPWarer_MainWndStartAndLoop,
  310. this,
  311. 0, &m_dwWarerThreadID);
  312. if(m_hWarerThread == NULL) {
  313. LogWarn(Severity_High, Error_Unexpect, ERROR_RDPWARE_THREAD_CREATE, "Create Warer thread failed!");
  314. m_dwWarerThreadID = 0;
  315. }
  316. /*Create and maintain the wfreerdp routine.*/
  317. hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  318. LOG_ASSERT(hExitEvent != NULL && "Create event handle failed!");
  319. m_hRDPMaintainThread = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0,
  320. MaintainFreeRDPRoutine, this, 0, &m_dwRDPMaintainID));
  321. if(!m_hRDPMaintainThread || m_hRDPMaintainThread == INVALID_HANDLE_VALUE) {
  322. m_hRDPMaintainThread = NULL;
  323. ec = Error_Unexpect;
  324. dwUserCode = ERROR_FREERDP_THREAD_CREATE;
  325. goto Error;
  326. }
  327. /*process communication component.*/
  328. if(!RDPPipe_MainEntry(RVC_DESK2RDP_HOST_PIPE, GetEntityBase()->GetEntityName())) {
  329. dwUserCode = ERROR_BUILD_RDP_PIPE;
  330. ec = Error_Unexpect;
  331. goto Error;
  332. }
  333. DWORD dwRet = WaitForSingleObject(m_hRDPMaintainThread, 3000);
  334. if(dwRet != WAIT_TIMEOUT) {
  335. Dbg("WaitForSingleObject error %d", dwRet);
  336. dwUserCode = ERROR_FREERDP_THREAD_WAIT;
  337. ec = Error_Unexpect;
  338. goto Error;
  339. }
  340. GetEntityBase()->GetFunction()->PostThreadPoolTask(new SpDeskShareCreateTask(this, true));
  341. SetSysVal(fs_succ);
  342. return Error_Succeed;
  343. Error:
  344. SetSysVal(errc);
  345. LogError(Severity_High, ec, dwUserCode,
  346. (LPCTSTR)CSimpleStringA::Format("Fatal error occurs on init step UserCode = %d !", dwUserCode));
  347. return ec;
  348. }
  349. ErrorCodeEnum CFreeRDPWrapFSM::OnExit()
  350. {
  351. if(m_hWndThread != NULL) {
  352. DevMnt_Terminate();
  353. WaitForSingleObject(m_hWndThread, 3000);
  354. SAFE_CLOSE_HANDLE(m_hWndThread);
  355. }
  356. TerminateFreeRDPRoutine();
  357. char szCmdLine[MAX_PATH] = {0};
  358. strcpy_s(szCmdLine, "taskkill /F /IM SpDeskShare.exe /T");
  359. CreateProcessFromSrv(szCmdLine, (LPCTSTR)m_strUserName, NULL);
  360. CoUninitialize();
  361. RemoveStateHooker(this);
  362. return Error_Succeed;
  363. }
  364. void CFreeRDPWrapFSM::SelfTest(EntityTestEnum eTestType,CSmartPointer<ITransactionContext> pTransactionContext)
  365. {
  366. //LOG_FUNCTION();
  367. pTransactionContext->SendAnswer(m_ecSelfTest);
  368. if(!m_DeactiveClientManager)
  369. {
  370. BOOL bAvailable = FALSE;
  371. if(!RDPPipe_IsClientSurvival(bAvailable)) {
  372. Dbg("SelfTest: SpDeskShare not survival ?");
  373. CreateDeskShareProc();
  374. }else if(!bAvailable) {
  375. Dbg("SelfTest: SpDeskShare not available ?");
  376. CreateDeskShareProc(true);
  377. }
  378. CheckCriticalThread();
  379. }
  380. }
  381. void CFreeRDPWrapFSM::OnStateTrans(int iSrcState, int iDstState)
  382. {
  383. Dbg("FSMState transfers from %s to %s", GetStateName(iSrcState), GetStateName(iDstState));
  384. m_nSrcState = iSrcState;
  385. }
  386. void CFreeRDPWrapFSM::s0_on_entry()
  387. {
  388. LOG_FUNCTION();
  389. m_eShareMode = ClientIdle;
  390. if(m_DeactiveClientManager) {
  391. PostEventLIFO(new FSMEvent(USER_EVT_DEPECRATED));
  392. }
  393. }
  394. void CFreeRDPWrapFSM::s0_on_exit()
  395. {
  396. LOG_FUNCTION();
  397. }
  398. unsigned int CFreeRDPWrapFSM::s0_on_event(FSMEvent* e)
  399. {
  400. LOG_FUNCTION();
  401. unsigned int uRet = 0;
  402. switch(e->iEvt) {
  403. case USER_EVT_INVITE:
  404. {
  405. InviteEvent* pEvt = dynamic_cast<InviteEvent*>(e);
  406. if(this->CreateShareSession(pEvt->m_ctx)) {
  407. if(m_bInvited) {
  408. uRet = 2;
  409. }else {
  410. uRet = 1;
  411. }
  412. }
  413. e->SetHandled();
  414. }
  415. break;
  416. case USER_EVT_INSTALL_DRIVE:
  417. {
  418. if(m_bTestMode) {
  419. CSimpleStringA strResult;
  420. BOOL bRes = ExecWaitWithResultContent("C:\\Windows\\System32\\bcdedit.exe", strResult);
  421. if(bRes) {
  422. //strResult.Trim();
  423. //Dbg("Trim:%s", (LPCTSTR)strResult);
  424. if(strstr(strResult, "testsigning Yes") == NULL) {
  425. LogEvent(Severity_High,
  426. Error_InvalidState,
  427. "Need to set testsigning on before install driver");
  428. DWORD dwExitCode = 0;
  429. bRes = ExecWaitWithExitCode("C:\\Windows\\System32\\bcdedit.exe /set testsigning on", dwExitCode);
  430. if(dwExitCode == 0) {
  431. //TODO restart the computer
  432. Dbg("restart the computer..");
  433. if(WinExec("shutdown -r -t 10", SW_HIDE) > 31) {
  434. GetEntityBase()->GetFunction()->ShowFatalError("测试模式开启成功,为及时生效,将在10s后重启终端设备。");
  435. } else {
  436. GetEntityBase()->GetFunction()->ShowFatalError("测试模式开启成功,为及时生效,请手动重启终端设备!");
  437. }
  438. }
  439. else {
  440. GetEntityBase()->GetFunction()->ShowFatalError("开启系统测试模式失败,请手动进行设置!");
  441. }
  442. break;
  443. }
  444. }
  445. else {
  446. LogWarn(Severity_High,
  447. Error_NotMeetCondition,
  448. 0,
  449. "无法检测系统是否开启测试模式,驱动很可能会出现安装失败!!!");
  450. }
  451. }
  452. DriveInstallEvent* pEvt = dynamic_cast<DriveInstallEvent*>(e);
  453. uRet = CreateInstallDrvTask(pEvt->kbdRequired, pEvt->mouRequired);
  454. e->SetHandled();
  455. Dbg("uRet: %d", uRet);
  456. }
  457. break;
  458. case USER_EVT_AGENT_ASSIST:
  459. {
  460. AgentAssistantEvent* pEvt = dynamic_cast<AgentAssistantEvent*>(e);
  461. AgentAssistTask* task = new AgentAssistTask(this);
  462. task->m_ctx = pEvt->m_ctx;
  463. e->SetHandled();
  464. if(Error_Succeed == GetEntityBase()->GetFunction()->PostThreadPoolTask(task)) {
  465. uRet = 1;
  466. }
  467. }
  468. break;
  469. default:
  470. break;
  471. }
  472. return uRet;
  473. }
  474. void CFreeRDPWrapFSM::s1_on_entry()
  475. {
  476. if(m_eShareMode != ClientIdle) {
  477. SendWfreeWrapEvt((int)m_eShareMode);
  478. }
  479. else {
  480. LogWarn(Severity_High, Error_InvalidState, Error_Unexpect, "Invalid share mode storage!");
  481. }
  482. }
  483. void CFreeRDPWrapFSM::s1_on_exit()
  484. {
  485. if(m_eShareMode != ClientIdle) {
  486. SendWfreeWrapEvt(0 - (int)m_eShareMode);
  487. }
  488. }
  489. unsigned int CFreeRDPWrapFSM::s1_on_event(FSMEvent* e)
  490. {
  491. unsigned int uRet = 0;
  492. switch(e->iEvt) {
  493. case USER_EVT_CLOSE_SHARE:
  494. {
  495. e->SetHandled();
  496. CloseShareEvent* pEvt = dynamic_cast<CloseShareEvent*>(e);
  497. if(this->TerminateShareSession(pEvt->m_ctx)) {
  498. uRet = 1;
  499. } else {
  500. uRet = 2;
  501. }
  502. }
  503. break;
  504. case USER_EVT_AGENT_ASSIST_DONE:
  505. {
  506. uRet = e->param1;
  507. Dbg("USER_EVT_AGENT_ASSIST_DONE returned %u", uRet);
  508. e->SetHandled();
  509. }
  510. break;
  511. default:
  512. break;
  513. }
  514. return uRet;
  515. }
  516. void CFreeRDPWrapFSM::s2_on_entry()
  517. {
  518. if(m_eShareMode != ClientIdle) {
  519. SendWfreeWrapEvt((int)m_eShareMode);
  520. }
  521. else {
  522. LogWarn(Severity_High, Error_InvalidState, Error_Unexpect, "Invalid share mode storage!");
  523. }
  524. }
  525. void CFreeRDPWrapFSM::s2_on_exit()
  526. {
  527. if(m_eShareMode != ClientIdle) {
  528. SendWfreeWrapEvt(0 - (int)m_eShareMode);
  529. }
  530. }
  531. unsigned int CFreeRDPWrapFSM::s2_on_event(FSMEvent* e)
  532. {
  533. unsigned int uRet = 0;
  534. switch(e->iEvt) {
  535. case USER_EVT_CLOSE_SHARE:
  536. {
  537. CloseShareEvent* pEvt = dynamic_cast<CloseShareEvent*>(e);
  538. if(this->TerminateShareSession(pEvt->m_ctx)) {
  539. uRet = 1;
  540. }
  541. }
  542. break;
  543. default:
  544. break;
  545. }
  546. return uRet;
  547. }
  548. void CFreeRDPWrapFSM::s3_on_entry()
  549. {
  550. SetSelfCheckCode(Error_InvalidState);
  551. }
  552. void CFreeRDPWrapFSM::s3_on_exit()
  553. {
  554. SetSelfCheckCode(Error_Succeed);
  555. }
  556. unsigned int CFreeRDPWrapFSM::s3_on_event(FSMEvent* e)
  557. {
  558. unsigned int uRet = 0;
  559. return uRet;
  560. }
  561. void CFreeRDPWrapFSM::s4_on_entry()
  562. {
  563. LOG_FUNCTION();
  564. }
  565. void CFreeRDPWrapFSM::s4_on_exit()
  566. {
  567. LOG_FUNCTION();
  568. }
  569. unsigned int CFreeRDPWrapFSM::s4_on_event(FSMEvent* e)
  570. {
  571. unsigned int uRet = 0;
  572. if(e->iEvt == USER_EVT_INSTALL_DRIVE_DONE) {
  573. uRet = 1;
  574. e->SetHandled();
  575. }
  576. return uRet;
  577. }
  578. unsigned int CFreeRDPWrapFSM::s5_on_event(FSMEvent* e)
  579. {
  580. LOG_FUNCTION();
  581. Dbg("event id: %d", e->iEvt);
  582. return -1;
  583. }
  584. bool OperatorFile(string file,bool isRead,char *str)
  585. {
  586. std::fstream fs;
  587. WIN32_FIND_DATAW find_data;
  588. HANDLE hFind = FindFirstFileW(AccountManage::convertStr2wStr(file).c_str(),&find_data);
  589. //judge file whether exist,if no then create it
  590. if(hFind == INVALID_HANDLE_VALUE)
  591. {
  592. fs.open(file,ios::out|ios::binary);
  593. if(!fs){
  594. Dbg("user.key create FAIL");
  595. return false;
  596. }else
  597. {
  598. Dbg("user.key create SUSS");
  599. }
  600. fs.close();
  601. //after close,fs must be clear
  602. fs.clear();
  603. //set all user to DENY ACCESS
  604. std::vector<std::string> vUserName;
  605. int errorCode;
  606. if(!AccountManage::GetAllAccount(vUserName,errorCode))
  607. {
  608. Dbg("get all user name FAIL!");
  609. return false;
  610. }
  611. std::vector<std::string>::const_iterator it=vUserName.begin();
  612. while(it!=vUserName.end())
  613. {
  614. if(AccountManage::AdjustACL(AccountManage::convertStr2wStr((*it)).c_str(),AccountManage::convertStr2wStr(file).c_str(),GENERIC_ALL,DENY_ACCESS))
  615. {
  616. Dbg("adjust ACL to GRANT for all user FAIL!");
  617. }
  618. it++;
  619. }
  620. }
  621. WCHAR pUserName[MAX_PATH] = {0};
  622. DWORD sizeofUserName = sizeof(pUserName);
  623. GetUserNameW(pUserName,&sizeofUserName);
  624. if(wcslen(pUserName) == 0){
  625. Dbg("get user name FAIL!");
  626. return false;
  627. }
  628. //set current user to GRANT ACCESS
  629. if(AccountManage::AdjustACL(pUserName,AccountManage::convertStr2wStr(file).c_str(),GENERIC_ALL,GRANT_ACCESS))
  630. {
  631. Dbg("adjust ACL to GRANT FAIL!");
  632. return false;
  633. }
  634. //read mode
  635. if (isRead)
  636. {
  637. fs.open(file,ios::in | ios::binary);
  638. if(!fs){
  639. Dbg("open %s with read FAIL!",file.c_str());
  640. return false;
  641. }
  642. char tmp[DEF_KEY_BUFF*4]={0};
  643. fs.getline(tmp,sizeof(tmp));
  644. strcpy(str,tmp);
  645. fs.close();
  646. fs.clear();
  647. }
  648. //write mode
  649. else{
  650. fs.open(file,ios::out|ios::binary);
  651. if(!fs){
  652. Dbg("open %s with write FAIL!",file.c_str());
  653. return false;
  654. }
  655. fs<<str<<endl;
  656. fs.close();
  657. fs.clear();
  658. }
  659. //set current user to DENY ACCESS
  660. if(AccountManage::AdjustACL(pUserName,AccountManage::convertStr2wStr(file).c_str(),GENERIC_ALL,DENY_ACCESS))
  661. {
  662. Dbg("adjust ACL to DENY FAIL!");
  663. return false;
  664. }
  665. return true;
  666. }
  667. HANDLE CFreeRDPWrapFSM::CreateFreeRDPProc(DWORD &dwProcessID)
  668. {
  669. ErrorCodeEnum ec = Error_Succeed;
  670. CSmartPointer<IEntityFunction> spEntityFunction = GetEntityBase()->GetFunction();
  671. CSmartPointer<IConfigInfo> spConfig;
  672. CSmartPointer<IConfigInfo> spConfig_r;
  673. char cmdValue[MAX_PATH] = {0};
  674. char cmdParam[MAX_PATH] = {0};
  675. STARTUPINFOA si = {0};
  676. PROCESS_INFORMATION pi = {0};
  677. SECURITY_ATTRIBUTES sa = {0};
  678. DWORD dwSessionId;
  679. HANDLE hUserTokenDup, hThisToken;
  680. HANDLE hProcess = INVALID_HANDLE_VALUE;
  681. const char* USRNAME = (LPCTSTR)m_strUserName;
  682. const char* PASSWORD = "11111111";
  683. dwProcessID = 0;
  684. ec = spEntityFunction->OpenConfig(Config_Software, spConfig);
  685. if(FAILURED(ec)) {
  686. Dbg("Open software config failed");
  687. return INVALID_HANDLE_VALUE;
  688. }
  689. Dbg("user name: %s", m_strUserName.GetData());
  690. CSimpleStringA strPassword;
  691. if(Error_Succeed != RetrieveFreeRDPUserPassword(strPassword)) {
  692. return INVALID_HANDLE_VALUE;
  693. }
  694. bool bEmptyPsw = false;
  695. if(strPassword.IsNullOrEmpty()) {
  696. bEmptyPsw = true;
  697. Dbg("Detect strPassword is empty");
  698. }
  699. int nFullScreen = 1;
  700. bool bFullScreen = true;
  701. ec = spConfig->ReadConfigValueInt(m_strUserName, "FullScreen", nFullScreen);
  702. if(nFullScreen == 0) {
  703. bFullScreen = false;
  704. Dbg("Detect not full display request!");
  705. }
  706. CSimpleStringA strParam(true), strValue;
  707. ec = spConfig->ReadConfigValue(m_strUserName, "Optimizer", strValue);
  708. if(!strValue.IsNullOrEmpty()) {
  709. if(strValue.IsEndWith(" /rvc:ccdg")) {
  710. strParam = strValue.SubString(0, strValue.GetLength()-strlen(" /rvc:ccdg"));
  711. }
  712. }
  713. ZeroMemory(&si, sizeof(si));
  714. si.cb = sizeof(si);
  715. GetStartupInfo(&si);
  716. ZeroMemory(&pi, sizeof(pi));
  717. memset(cmdValue, 0, sizeof(cmdValue));
  718. strcpy_s(cmdValue, ".\\bin\\freerdp\\wfreerdp.exe");
  719. sprintf_s(cmdParam, " /u:%s", (LPCTSTR)m_strUserName);
  720. strcat_s(cmdValue, cmdParam);
  721. if(!bEmptyPsw) {
  722. sprintf_s(cmdParam, " /p:%s", (LPCTSTR)strPassword);
  723. strcat_s(cmdValue, cmdParam);
  724. }
  725. if(bFullScreen) {
  726. strcat_s(cmdValue, " /f");
  727. }
  728. strcat_s(cmdValue, " /t:\"rvc-wfreerdp\"");
  729. strcat_s(cmdValue, " +aero");
  730. strcat_s(cmdValue, " /v:127.0.0.2");
  731. if(!strParam.IsNullOrEmpty()) {
  732. if(!strParam.IsStartWith(" ")){
  733. strcat_s(cmdValue, " ");
  734. }
  735. strcat_s(cmdValue, (LPCTSTR)strParam);
  736. }
  737. Dbg("Process Param: %s", cmdValue);
  738. //该接口有时会出现阻塞,暂时要兼容一下,后续处理。
  739. SetFSMSickStatus(FALSE);
  740. dwSessionId = WTSGetActiveConsoleSessionId();
  741. SetFSMRecoverStatus();
  742. Dbg("WTSGetActiveConsoleSessionId...");
  743. if (OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &hThisToken)) {
  744. Dbg("OpenProcessToken...");
  745. LUID luid;
  746. TOKEN_PRIVILEGES tp;
  747. LPVOID pEnv = NULL;
  748. DWORD dwFlag = 0;
  749. Dbg("Start to LookupPrivilegeValueA...");
  750. LookupPrivilegeValueA(NULL, "SeDebugPrivilege", &luid);
  751. Dbg("Finished LookupPrivilegeValueA...");
  752. tp.PrivilegeCount = 1;
  753. tp.Privileges[0].Luid = luid;
  754. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  755. Dbg("DuplicateTokenEx...");
  756. DuplicateTokenEx(hThisToken,MAXIMUM_ALLOWED,NULL,
  757. SecurityIdentification, TokenPrimary, &hUserTokenDup);
  758. Dbg("SetTokenInformation...");
  759. SetTokenInformation(hUserTokenDup,
  760. TokenSessionId,(void*)&dwSessionId, sizeof(DWORD));
  761. Dbg("AdjustTokenPrivileges...");
  762. AdjustTokenPrivileges(hUserTokenDup, FALSE, &tp, sizeof(TOKEN_PRIVILEGES),
  763. (PTOKEN_PRIVILEGES)NULL,NULL);
  764. //if(CreateEnvironmentBlock(&pEnv, hUserTokenDup, TRUE)) {
  765. // //dwFlag |= CREATE_UNICODE_ENVIRONMENT;
  766. //}else {
  767. // pEnv = NULL;
  768. //}
  769. Dbg("Start to create wfreerdp process...");
  770. if (CreateProcessAsUserA(hUserTokenDup,
  771. NULL,
  772. cmdValue,
  773. NULL,
  774. NULL,
  775. FALSE,
  776. dwFlag,
  777. pEnv,
  778. NULL,
  779. &si,
  780. &pi)) {
  781. dwProcessID = pi.dwProcessId;
  782. CloseHandle(pi.hThread);
  783. hProcess = pi.hProcess;
  784. } else {
  785. dwProcessID = GetLastError();
  786. LogWarn(Severity_Middle, Error_Unexpect, ERROR_FREERDP_CREATE_FREERDP_PROCESS_FAILED,
  787. (LPCTSTR)CSimpleStringA::Format("CreateProcessAsUserA failed! GLE=%d", dwProcessID));
  788. }
  789. if (pEnv) {
  790. DestroyEnvironmentBlock(pEnv);
  791. }
  792. CloseHandle(hUserTokenDup);
  793. CloseHandle(hThisToken);
  794. } else {
  795. LogWarn(Severity_Middle, Error_Unexpect, ERROR_FREERDP_OPEN_CURRENT_PROCESS_TOKEN_FAILED,
  796. (LPCTSTR)CSimpleStringA::Format("open process token failed! Error : %d", GetLastError()));
  797. }
  798. return hProcess;
  799. }
  800. BOOL CFreeRDPWrapFSM::TerminateFreeRDPRoutine()
  801. {
  802. BOOL bNeedConfirm = FALSE;
  803. if(m_hRDPMaintainThread != INVALID_HANDLE_VALUE && m_hRDPMaintainThread != NULL) {
  804. if(hExitEvent != NULL) {
  805. SetEvent(hExitEvent);
  806. if(WaitForSingleObject(m_hRDPMaintainThread, /*INFINITE*/3000) != WAIT_OBJECT_0) {
  807. bNeedConfirm = TRUE;
  808. }
  809. SAFE_CLOSE_HANDLE(m_hRDPMaintainThread);
  810. m_dwRDPMaintainID = 0;
  811. }
  812. }
  813. return TRUE;
  814. }
  815. BOOL CFreeRDPWrapFSM::IsWrapperNeedUpdate()
  816. {
  817. ErrorCodeEnum ec = Error_Succeed;
  818. CSmartPointer<IEntityFunction> pFunc = GetEntityBase()->GetFunction();
  819. CSystemStaticInfo info;
  820. FILE_VERSION fvWrap = {0};
  821. BOOL bUpdate = FALSE;
  822. CSimpleStringA strPath;
  823. LOG_ASSERT(gszTermServicePath != NULL && strlen(gszTermServicePath) != 0);
  824. if(GetEntityBase()->GetFunction()->GetPath("Bin", strPath) != Error_Succeed
  825. || strPath.IsNullOrEmpty())
  826. {
  827. Dbg("GetPath about bin failed");
  828. return FALSE;
  829. }
  830. if(!strstr(gszTermServicePath, (LPCTSTR)strPath)) {
  831. Dbg("Run %s vs %s, it need to update.", gszTermServicePath, (LPCTSTR)strPath);
  832. bUpdate = TRUE;
  833. }
  834. return bUpdate;
  835. }
  836. BOOL CFreeRDPWrapFSM::CreateShareSession(
  837. SpReqAnsContext<FreeRDPWrapSrv_InviteRdpShare_Req,
  838. FreeRDPWrapSrv_InviteRdpShare_Ans>::Pointer ctx)
  839. {
  840. BOOL bRet = FALSE;
  841. char szFileName[MAX_PATH] = {0};
  842. m_strInviteFileName = "";
  843. /*
  844. CTRL_LEVEL_VIEW = 2,
  845. CTRL_LEVEL_INTERACTIVE = 3,
  846. */
  847. USHORT usViewLevel = CTRL_LEVEL_VIEW;
  848. m_bInterview = FALSE;
  849. if(ctx->Req.viewLevel == 1) {
  850. usViewLevel = CTRL_LEVEL_INTERACTIVE;
  851. m_bInterview = TRUE;
  852. }
  853. if(ctx->Req.bClientSide) {
  854. m_bInvited = TRUE;
  855. } else {
  856. m_bInvited = FALSE;
  857. }
  858. if(m_hWarerThread == NULL || !hWarerWnd) {
  859. Dbg("Share window handle is invalid");
  860. goto Error;
  861. }
  862. memset(szFileName, 0, sizeof(szFileName));
  863. if(!CreateInviteFileName(szFileName, MAX_PATH)) {
  864. goto Error;
  865. }
  866. m_strInviteFileName = szFileName;
  867. if(ctx != NULL && ctx->Req.bClientSide == true) {
  868. /*
  869. @step1: Tell the SpDeskShare that we want see the screen
  870. @step2: SpDeskShare send the invitation information.
  871. @step3: The entity connect the 'sharer host' with the invitation strings.
  872. */
  873. if(!RDPPipe_Request(CTXD_SHARE, TRUE, szFileName, (DWORD)ctx->Req.filterAppId, usViewLevel)) {
  874. Dbg("RDPPipe_Request for CTXD_SHARE invoked failed !");
  875. goto Error;
  876. }
  877. if(!RDPWarer_Connect(szFileName)) {
  878. LogWarn(Severity_Middle, Error_Param, ERROR_FREERDP_SHARE_ACCEPT_INVITE_FAILED, "Do the connect Job failed !");
  879. goto Error;
  880. }
  881. Dbg("Perform connect procedure succ.");
  882. }
  883. else {
  884. if(!RDPWarer_ShareAndInvite(szFileName, ctx->Req.filterAppId, usViewLevel)) {
  885. LogWarn(Severity_Middle, Error_Param, ERROR_FREERDP_SHARE_BUILD_UP_SHRER_FAILED, "Do the share and invite Job failed !");
  886. goto Error;
  887. }
  888. if(!RDPPipe_Request(CTXD_INVITE, TRUE, szFileName, NULL, NULL)) {
  889. Dbg("RDPPipe_Request invoked failed !");
  890. RDPWarer_CloseInvite();
  891. goto Error;
  892. }
  893. /*
  894. @step1: The entity create the invitation information and tell the Spdeskshare we want to be shared
  895. @step2: The SpDeskShare use the invitaion information to connect it!
  896. */
  897. Dbg("Perform invite procedure succ.");
  898. }
  899. if(m_bInterview && !m_bInvited) {
  900. //ShowFreeRDPCursor(FALSE);
  901. }
  902. m_bAgentSituation = FALSE;
  903. m_eShareMode = m_bInvited ? AM2Client : Client2AM;
  904. bRet = TRUE;
  905. Error:
  906. if(ctx != NULL) {
  907. ctx->Ans.retCode = bRet ? 1 : -1;
  908. ctx->Answer(Error_Succeed);
  909. }
  910. if(!m_strInviteFileName.IsNullOrEmpty()) {
  911. DeleteFileA(m_strInviteFileName);
  912. m_strInviteFileName = "";
  913. }
  914. return bRet;
  915. }
  916. BOOL CFreeRDPWrapFSM::TerminateShareSession(
  917. SpReqAnsContext<FreeRDPWrapSrv_CloseRdpShare_Req, FreeRDPWrapSrv_CloseRdpShare_Ans>::Pointer ctx)
  918. {
  919. Dbg("Start to close share screen, Agent(%d) Invited(%d)", m_bAgentSituation, m_bInvited);
  920. if(m_bInvited) {
  921. if(!RDPWarer_Disconnect()) {
  922. LogWarn(Severity_Middle, Error_Param, ERROR_FREERDP_SHARE_DISCONNECT_FAILED, "Disconnect as viewer failed !");
  923. goto Error;
  924. }
  925. if(!m_bAgentSituation && !RDPPipe_Request(CTXD_KILL_INVITE, TRUE)) {
  926. Dbg("RDPPipe_Request for CTXD_KILL_INVITE invoked failed !");
  927. goto Error;
  928. }
  929. }else {
  930. if(!m_bAgentSituation && !RDPPipe_Request(CTXD_DISCONNECT, TRUE)) {
  931. Dbg("RDPPipe_Request for CTXD_DISCONNECT invoked failed !");
  932. goto Error;
  933. }
  934. // Sleep a little time for receiving endpoint disconnect event! [6/17/2020 10:47 @Gifur]
  935. Sleep(300);
  936. if(!RDPWarer_CloseInvite()) {
  937. LogWarn(Severity_Middle, Error_Param, ERROR_FREERDP_SHARE_CLOSE_SESSION_FAILED, "Close invitation session as sharer failed !");
  938. goto Error;
  939. }
  940. }
  941. if(!m_bAgentSituation && m_bInterview && !m_bInvited) {
  942. //ShowFreeRDPCursor(TRUE);
  943. }
  944. if(ctx != NULL) {
  945. ctx->Ans.retCode = 1;
  946. ctx->Answer(Error_Succeed);
  947. }
  948. return TRUE;
  949. Error:
  950. if(ctx != NULL) {
  951. ctx->Ans.retCode = -1;
  952. ctx->Answer(Error_Succeed);
  953. }
  954. return FALSE;
  955. }
  956. BOOL CFreeRDPWrapFSM::CreateInviteFileName(CHAR* strFileName, const DWORD bufLen)
  957. {
  958. CSimpleStringA strPath;
  959. if(GetEntityBase()->GetFunction()->GetPath("Temp", strPath) != Error_Succeed
  960. || strPath.IsNullOrEmpty())
  961. {
  962. LogWarn(Severity_Middle, Error_Unexpect, 0, "GetPath about Temp failed");
  963. return FALSE;
  964. }
  965. if(!ExistsDirA(strPath)) {
  966. if(!CreateDirRecursiveA(strPath)) {
  967. LogWarn(Severity_Middle, Error_Unexpect, 0, "CreateDirRecursiveA failed");
  968. return FALSE;
  969. }
  970. }
  971. SYSTEMTIME st, stLocal;
  972. GetSystemTime(&st);
  973. SystemTimeToTzSpecificLocalTime(NULL, &st, &stLocal);
  974. CHAR fileName[MAX_PATH] = { 0 };
  975. sprintf_s(fileName, "%s\\%d%02d%02d-%02d_%02d_%02d.xml", (LPCTSTR)strPath,
  976. stLocal.wYear, stLocal.wMonth, stLocal.wDay,
  977. stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
  978. strcpy_s(strFileName, bufLen, fileName);
  979. Dbg("Combined XML FilePah: %s", strFileName);
  980. return (strlen(strFileName) > 0);
  981. }
  982. void CFreeRDPWrapFSM::InitEnvironmentValue()
  983. {
  984. ErrorCodeEnum ec = Error_Succeed;
  985. CSmartPointer<IEntityFunction> spEntityFunction = GetEntityBase()->GetFunction();
  986. CSmartPointer<IConfigInfo> spConfig;
  987. LPCTSTR name = "WLOG_APPENDER";
  988. ec = spEntityFunction->OpenConfig(Config_Software, spConfig);
  989. DWORD nSize = GetEnvironmentVariableA(name, NULL, 0);
  990. if (nSize == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
  991. {
  992. Dbg("Set wfreerdp child process environment...");
  993. CSimpleStringA strDbgPath;
  994. spEntityFunction->GetPath("Dbg", strDbgPath);
  995. CSimpleStringA strDbgBk = strDbgPath;
  996. if(!strDbgPath.IsNullOrEmpty()) {
  997. char logAppender[MAX_PATH] = "WLOG_APPENDER=";
  998. strcat(logAppender, "FILE");
  999. _putenv(logAppender);
  1000. strDbgPath += "\\wfreerdp";
  1001. char logFilePath[MAX_PATH] = "WLOG_FILEAPPENDER_OUTPUT_FILE_PATH=";
  1002. strcat(logFilePath, strDbgPath);
  1003. _putenv(logFilePath);
  1004. //Dbg("Set wfreerdp dbg path: %s", (LPCTSTR)strDbgPath);
  1005. memset(logFilePath, 0, sizeof(logFilePath));
  1006. strcpy_s(logFilePath, "DbgPath=");
  1007. strcat_s(logFilePath, (LPCTSTR)strDbgBk);
  1008. _putenv(logFilePath);
  1009. }
  1010. else {
  1011. Dbg("GetPath of DBG is null!!");
  1012. }
  1013. int nLockTime = 0;
  1014. ec = spConfig->ReadConfigValueInt("Common", "LockScreenMin", nLockTime);
  1015. if(nLockTime > 0) {
  1016. m_dwLockScreenMinu = nLockTime;
  1017. Dbg("Set lock screen time %d min.", m_dwLockScreenMinu);
  1018. }
  1019. CSimpleStringA strTo;
  1020. strTo = CSimpleStringA::Format("WF_LOCK_SCREEN_TIMEOUT=%d", m_dwLockScreenMinu);
  1021. _putenv(strTo);
  1022. }
  1023. }
  1024. void CFreeRDPWrapFSM::SetSysVal(int nFlag)
  1025. {
  1026. CSmartPointer<IEntityFunction> spFunction = this->GetEntityBase()->GetFunction();
  1027. CSimpleStringA csStatus;
  1028. CSimpleStringA csNewStatus = FREERDPSTATUS_UNKOWN;
  1029. ErrorCodeEnum err;
  1030. err = spFunction->GetSysVar(SYSVAR_FREERDPSTATUS, csStatus);
  1031. Dbg("Current sys val of " SYSVAR_FREERDPSTATUS " : %s(%d)", (LPCTSTR)csStatus, err);
  1032. switch(nFlag) {
  1033. case fs_error:
  1034. csNewStatus = FREERDPSTATUS_ERROR;
  1035. break;
  1036. case fs_succ:
  1037. csNewStatus = FREERDPSTATUS_SUCC;
  1038. break;
  1039. case fs_busy:
  1040. csNewStatus = FREERDPSTATUS_BUSY;
  1041. break;
  1042. case fs_invalid_monitor:
  1043. csNewStatus = FREERDPSTATUS_INVALID_MONITOR;
  1044. break;
  1045. case fs_unknown:
  1046. csNewStatus = FREERDPSTATUS_UNKOWN;
  1047. break;
  1048. default:
  1049. csNewStatus = FREERDPSTATUS_UNKOWN;
  1050. break;
  1051. }
  1052. if(csNewStatus != csStatus) {
  1053. err = spFunction->SetSysVar(SYSVAR_FREERDPSTATUS, csNewStatus, true);
  1054. Dbg("SetSysVar " SYSVAR_FREERDPSTATUS " from '%s' to '%s' returned %d",
  1055. (LPCTSTR)csStatus
  1056. , (LPCTSTR)csNewStatus
  1057. , err);
  1058. }
  1059. else {
  1060. Dbg("system value is same with already one.");
  1061. }
  1062. return;
  1063. }
  1064. ErrorCodeEnum CFreeRDPWrapFSM::CreateClientUserAccount()
  1065. {
  1066. int errorCode;
  1067. char newPasswd[DEF_KEY_BUFF] = {0};
  1068. int addNewAccountNum=0;
  1069. CSmartPointer<IEntityFunction> spEntityFunction = GetEntityBase()->GetFunction();
  1070. CSmartPointer<IConfigInfo> spConfigRun;
  1071. auto ec = spEntityFunction->OpenConfig(Config_Run, spConfigRun);
  1072. if(FAILURED(ec)) {
  1073. Dbg("Open run config failed");
  1074. return ec;
  1075. }
  1076. Common::GenerateRandomPassword((unsigned char*)newPasswd, DEF_KEY_SIZE);
  1077. Dbg("Add New Account...");
  1078. while(!AccountManage::AddNewAccount(m_strUserName.GetData(),
  1079. reinterpret_cast<char *>(newPasswd),errorCode))
  1080. {
  1081. addNewAccountNum++;
  1082. Dbg("Create account failed errorCode=%d,addNewAccountNum=%d", errorCode, addNewAccountNum);
  1083. if(addNewAccountNum > 3){
  1084. LogWarn(Severity_Middle,Error_Unexpect,ERROR_ADD_NEW_ACCOUNT,"三次创建 ClienUser 均失败!");
  1085. return Error_Unexpect;
  1086. }
  1087. }
  1088. Dbg("Create New Account succ,errorCode=%d.", errorCode);
  1089. //add user to Remote Desktop Users
  1090. if(!AccountManage::ExtendGroupAdd(m_strUserName.GetData(),"Remote Desktop Users"))
  1091. {
  1092. Dbg("Append [Remote Desktop Users] group error");
  1093. RemoveClientUser();
  1094. ec = Error_Unexpect;
  1095. } else {
  1096. Dbg("Create %s SUSS,and Append [Remote Desktop Users] group SUSS",m_strUserName.GetData());
  1097. CSimpleStringA strNewPassword(newPasswd);
  1098. ec = StoreFreeRDPUserPassword(strNewPassword);
  1099. }
  1100. return ec;
  1101. }
  1102. ErrorCodeEnum CFreeRDPWrapFSM::GetClientUserPsw(bool bRuncfgInitialized, CSimpleStringA& plainPsw)
  1103. {
  1104. plainPsw = "";
  1105. CSmartPointer<IEntityFunction> spEntityFunction = GetEntityBase()->GetFunction();
  1106. CSmartPointer<IConfigInfo> spConfig;
  1107. auto ec = spEntityFunction->OpenConfig(Config_Software, spConfig);
  1108. if(FAILURED(ec)) {
  1109. Dbg("Open software config failed");
  1110. return ec;
  1111. }
  1112. CSmartPointer<IConfigInfo> spConfigRun;
  1113. ec = spEntityFunction->OpenConfig(Config_Run, spConfigRun);
  1114. if(FAILURED(ec)) {
  1115. Dbg("Open run config failed");
  1116. return ec;
  1117. }
  1118. if(!bRuncfgInitialized && !ExistsFileA(DEF_KEY_PATH))
  1119. {
  1120. //from software config read passwd
  1121. CSimpleStringA originalPsw(true);
  1122. ec = spConfig->ReadConfigValue(m_strUserName.GetData(), "Password", originalPsw);
  1123. if(FAILURED(ec)) {
  1124. Dbg("Read software config [%s.Password] failed",m_strUserName.GetData());
  1125. originalPsw = DEFAULT_CLIENT_USER_PASSWORD;
  1126. }
  1127. ec = spConfigRun->WriteConfigValue("Init", "Compatible", "");
  1128. if (FAILURED(ec)) {
  1129. Dbg("Write run config Init.Compatible failed");
  1130. }
  1131. plainPsw = originalPsw;
  1132. } else {
  1133. CSimpleStringA cipherPassword(true);
  1134. ec = spConfigRun->ReadConfigValue(m_strUserName.GetData(), "Password", cipherPassword);
  1135. if(FAILURED(ec)) {
  1136. Dbg("Read run config [%s.Password] failed",m_strUserName.GetData());
  1137. cipherPassword = "";
  1138. }
  1139. if(cipherPassword.IsNullOrEmpty()) {
  1140. Dbg("Read passwd is NULL");
  1141. RetrieveClientUserPswFromBakup(cipherPassword);
  1142. }
  1143. if(IsInvalidCipherPsw(cipherPassword)) {
  1144. return Error_DataCheck;
  1145. }
  1146. EncodeCipher2PlainString(cipherPassword, plainPsw);
  1147. }
  1148. Dbg("Passwd is %s,%d",(const char *)plainPsw, plainPsw.GetLength());
  1149. if(plainPsw.IsNullOrEmpty())
  1150. return Error_Unexpect;
  1151. return Error_Succeed;
  1152. }
  1153. bool CFreeRDPWrapFSM::RemoveClientUser()
  1154. {
  1155. int errorCode;
  1156. int rmAccountNum = 0;
  1157. while(!AccountManage::RmAccount(m_strUserName.GetData(),errorCode)){
  1158. rmAccountNum++;
  1159. Dbg("rm account error,rmAccountNum=%d",rmAccountNum);
  1160. if(rmAccountNum > 3){
  1161. LogWarn(Severity_Middle,Error_Unexpect,ERROR_RM_ACCOUNT,"三次删除ClienUser均失败!");
  1162. return false;
  1163. }
  1164. }
  1165. Dbg("rm account succ.");
  1166. return true;
  1167. }
  1168. bool CFreeRDPWrapFSM::Plain2EncodeCipherString(const char* newPasswd, CSimpleStringA& strEnCipherText)
  1169. {
  1170. unsigned char newCipherPasswd[DEF_KEY_SIZE*4] ={0};
  1171. sm4_context sm4Contxt;
  1172. sm4_setkey_enc(&sm4Contxt,key);
  1173. sm4_crypt_ecb(&sm4Contxt,SM4_ENCRYPT,strlen(newPasswd),(unsigned char *)newPasswd, newCipherPasswd);
  1174. Dbg("newCipherPasswd %d",strlen((char*)newCipherPasswd));
  1175. char encodedPasswd[DEF_KEY_SIZE*4]={0};
  1176. base64_encode(encodedPasswd,reinterpret_cast<char *>(newCipherPasswd),DEF_KEY_SIZE);
  1177. Dbg("encodedPasswd %s",encodedPasswd);
  1178. strEnCipherText = encodedPasswd;
  1179. return true;
  1180. }
  1181. bool CFreeRDPWrapFSM::EncodeCipher2PlainString(const CSimpleStringA& strEnCipherText, CSimpleStringA& strPlainText)
  1182. {
  1183. if(strEnCipherText.IsNullOrEmpty()) {
  1184. strPlainText = "";
  1185. return false;
  1186. }
  1187. //base64 decode
  1188. unsigned char decodedPasswd[DEF_KEY_BUFF *4]={0};
  1189. base64_decode(reinterpret_cast<char*>(decodedPasswd),const_cast<char*>(strEnCipherText.GetData()));
  1190. char passwd[DEF_KEY_BUFF] = {0};
  1191. //sm4 decrypt
  1192. sm4_context sm4Contxt;
  1193. sm4_setkey_dec(&sm4Contxt,key);
  1194. sm4_crypt_ecb(&sm4Contxt,SM4_DECRYPT, strlen(reinterpret_cast<char*>(decodedPasswd)),
  1195. decodedPasswd,(unsigned char*)passwd);
  1196. strPlainText = passwd;
  1197. return true;
  1198. }
  1199. void CFreeRDPWrapFSM::BackupClientUserPsw(const CSimpleStringA& psw)
  1200. {
  1201. char encodedPasswd[DEF_KEY_SIZE*4]={0};
  1202. strcpy_s(encodedPasswd, psw.GetData());
  1203. if(OperatorFile(DEF_KEY_PATH,false,encodedPasswd)){
  1204. Dbg("write copy passwd SUSS");
  1205. } else {
  1206. Dbg("write copy passwd FAIL");
  1207. }
  1208. }
  1209. void CFreeRDPWrapFSM::RetrieveClientUserPswFromBakup(CSimpleStringA& psw)
  1210. {
  1211. char tmpPasswd[DEF_KEY_BUFF * 4]={0};
  1212. if(OperatorFile(DEF_KEY_PATH, true, tmpPasswd)){
  1213. Dbg("read copy passwd SUSS");
  1214. psw = tmpPasswd;
  1215. }
  1216. else{
  1217. Dbg("read copy passwd FAIL");
  1218. psw = "";
  1219. }
  1220. }
  1221. ErrorCodeEnum CFreeRDPWrapFSM::RetrieveFreeRDPUserPassword(CSimpleStringA& strOutPassword)
  1222. {
  1223. const int PASSWORD_UPDATE_INTERVAL_DAYS = 27;
  1224. CSmartPointer<IEntityFunction> spEntityFunction = GetEntityBase()->GetFunction();
  1225. CSmartPointer<IConfigInfo> spConfig;
  1226. auto ec = spEntityFunction->OpenConfig(Config_Software, spConfig);
  1227. if(FAILURED(ec)) {
  1228. Dbg("Open software config failed");
  1229. return ec;
  1230. }
  1231. CSmartPointer<IConfigInfo> spConfigRun;
  1232. ec = spEntityFunction->OpenConfig(Config_Run, spConfigRun);
  1233. if(FAILURED(ec)) {
  1234. Dbg("Open run config failed");
  1235. return ec;
  1236. }
  1237. strOutPassword = DEFAULT_CLIENT_USER_PASSWORD;
  1238. bool isRuncfgNotInitialized = false;
  1239. CSimpleStringA compatible = "";
  1240. ec = spConfigRun->ReadConfigValue("Init","Compatible", compatible);
  1241. //if run config no exist then create
  1242. if(FAILURED(ec) || compatible.IsNullOrEmpty()) {
  1243. Dbg("Read run config Init.Compatible failed");
  1244. isRuncfgNotInitialized = true;
  1245. ec = spConfigRun->WriteConfigValue("Init","Compatible", "Yes");
  1246. if(FAILURED(ec)) {
  1247. Dbg("Write run config Init.Compatible failed");
  1248. }
  1249. ec = spConfigRun->WriteConfigValue(m_strUserName.GetData(),"LastUpdatePasswdDate","");
  1250. if(FAILURED(ec)) {
  1251. Dbg("Write run config %s.LastUpdatePasswdDate failed with compatible mode",m_strUserName.GetData());
  1252. }
  1253. ec = spConfigRun->WriteConfigValue(m_strUserName.GetData(),"Password","");
  1254. if(FAILURED(ec)) {
  1255. Dbg("Write run config %s.Password failed with compatible mode",m_strUserName.GetData());
  1256. }
  1257. }
  1258. CSimpleStringA lastUpdatePasswdDate;
  1259. Common::Now *now = new Common::Now();
  1260. CSimpleStringA strToday = now->Today();
  1261. delete now;
  1262. spConfigRun->ReadConfigValue(m_strUserName.GetData(), "LastUpdatePasswdDate", lastUpdatePasswdDate);
  1263. //if lastUpdatePasswdDate is null or empty, then set it to today
  1264. if(lastUpdatePasswdDate.IsNullOrEmpty())
  1265. {
  1266. spConfigRun->WriteConfigValue(m_strUserName.GetData(),"LastUpdatePasswdDate", strToday);
  1267. lastUpdatePasswdDate = strToday;
  1268. Dbg("There are no update history.");
  1269. } else {
  1270. Dbg("Last update date: %s",lastUpdatePasswdDate.GetData());
  1271. }
  1272. int updatePasswdIntervals = 0;
  1273. // Change key from 'UpdatePasswdIntervals' to 'UpdatePswIntervals' for activing new interval value.
  1274. spConfigRun->ReadConfigValueInt(m_strUserName.GetData(), "UpdatePswIntervals", updatePasswdIntervals);
  1275. if(updatePasswdIntervals == 0) {
  1276. updatePasswdIntervals = PASSWORD_UPDATE_INTERVAL_DAYS;
  1277. }
  1278. Dbg("updatePasswdIntervals %d(days)", updatePasswdIntervals);
  1279. Common::Date theFutureUpdateDate(lastUpdatePasswdDate);
  1280. theFutureUpdateDate += updatePasswdIntervals;
  1281. Dbg("Today %s, The future update date %s", strToday.GetData(), theFutureUpdateDate.ToCSimpleStringA().GetData());
  1282. bool isTimeExpired = (strcmp(strToday.GetData(),theFutureUpdateDate.ToCSimpleStringA().GetData()) >= 0);
  1283. int createAccountTimes = 0;
  1284. NEWACCOUNT:
  1285. //judge user whether exist,if no then create
  1286. if(!AccountManage::CheckAccount(m_strUserName.GetData()))
  1287. {
  1288. if(createAccountTimes > 3) {
  1289. return Error_Break;
  1290. }
  1291. Dbg("To create client user account...");
  1292. ec = CreateClientUserAccount();
  1293. if(FAILURED(ec)) {
  1294. return ec;
  1295. }
  1296. spConfigRun->WriteConfigValue(m_strUserName.GetData(),"LastUpdatePasswdDate", strToday);
  1297. isTimeExpired = false;
  1298. isRuncfgNotInitialized = false;
  1299. createAccountTimes++;
  1300. }
  1301. ec = GetClientUserPsw(!isRuncfgNotInitialized, strOutPassword);
  1302. if(ec == Error_DataCheck) {
  1303. Dbg("passwd incorrect, will rm account");
  1304. if(RemoveClientUser()) {
  1305. goto NEWACCOUNT;
  1306. } else {
  1307. return Error_Unexpect;
  1308. }
  1309. } else if(ec != Error_Succeed) {
  1310. return ec;
  1311. }
  1312. if(isTimeExpired || isRuncfgNotInitialized)
  1313. {
  1314. char passwd[DEF_KEY_BUFF] = {0};
  1315. char newPasswd[DEF_KEY_BUFF] = {0};
  1316. Dbg("start modefy user passwd ex");
  1317. strcpy_s(passwd, strOutPassword.GetData());
  1318. //generate new passwd
  1319. memset(newPasswd,0,sizeof(newPasswd));
  1320. Common::GenerateRandomPassword((unsigned char*)newPasswd, DEF_KEY_SIZE);
  1321. Dbg("userName %s", m_strUserName.GetData());
  1322. Dbg("passwd %s",passwd);
  1323. Dbg("newPasswd %s",newPasswd);
  1324. if(AccountManage::ModefyUserPsw(m_strUserName.GetData(), passwd, newPasswd))
  1325. {
  1326. Dbg("Modify passwd SUSS");
  1327. CSimpleStringA strNewPassword(newPasswd);
  1328. ec = StoreFreeRDPUserPassword(strNewPassword);
  1329. if(ec == Error_Succeed) {
  1330. spConfigRun->WriteConfigValue(m_strUserName.GetData(),"LastUpdatePasswdDate", strToday);
  1331. }
  1332. strOutPassword = strNewPassword;
  1333. } else {
  1334. Dbg("Modify passwd error");
  1335. }
  1336. } else {
  1337. Dbg("Passwd not expired");
  1338. }
  1339. return ec;
  1340. }
  1341. ErrorCodeEnum CFreeRDPWrapFSM::StoreFreeRDPUserPassword(const CSimpleStringA& strInPassword)
  1342. {
  1343. CSmartPointer<IEntityFunction> spEntityFunction = GetEntityBase()->GetFunction();
  1344. CSmartPointer<IConfigInfo> spConfigRun;
  1345. auto ec = spEntityFunction->OpenConfig(Config_Run, spConfigRun);
  1346. if(FAILURED(ec)) {
  1347. Dbg("Open run config failed");
  1348. return ec;
  1349. }
  1350. CSimpleStringA strEncodePassword(true);
  1351. Plain2EncodeCipherString(strInPassword, strEncodePassword);
  1352. ec = spConfigRun->WriteConfigValue(m_strUserName, "Password", strEncodePassword);
  1353. if(FAILURED(ec)) {
  1354. Dbg("Write run config encodedPasswd(%s) passwd(%s) error", strEncodePassword.GetData(), strInPassword.GetData());
  1355. return ec;
  1356. } else {
  1357. Dbg("Write run config encodedPasswd(%s) passwd(%s) succeed.", strEncodePassword.GetData(), strInPassword.GetData());
  1358. }
  1359. BackupClientUserPsw(strEncodePassword);
  1360. return Error_Succeed;
  1361. }
  1362. ErrorCodeEnum CFreeRDPWrapFSM::TryChangeClientUserPswWithDefault()
  1363. {
  1364. LOG_FUNCTION();
  1365. CSimpleStringA strPassword;
  1366. auto ec = GetClientUserPsw(true, strPassword);
  1367. if(FAILURED(ec) || strPassword.Compare(DEFAULT_CLIENT_USER_PASSWORD) == 0) {
  1368. return ec;
  1369. }
  1370. if(AccountManage::ModefyUserPsw(m_strUserName.GetData(), DEFAULT_CLIENT_USER_PASSWORD, strPassword.GetData()))
  1371. {
  1372. LogWarn(Severity_Middle, Error_DataCheck,
  1373. ERROR_FREERDP_FREERDP_PASSWORD_RESET, "modify passwod with old default password succeed.");
  1374. return Error_Succeed;
  1375. }
  1376. Dbg("Try to change client user psw failed.");
  1377. return Error_NotMeetCondition;
  1378. }
  1379. BOOL CFreeRDPWrapFSM::ShowFreeRDPCursor(BOOL bShow /*= TRUE*/)
  1380. {
  1381. HWND hwnd = FindWindow(TEXT("rvc_cursor"), NULL);
  1382. if(hwnd == NULL) {
  1383. Dbg("Find rvc_cursor window handle failed");
  1384. return FALSE;
  1385. }
  1386. DWORD dwEvent = bShow ? CDEVENT_SHOW_CURSOR : CDEVENT_HIDE_CURSOR;
  1387. COPYDATASTRUCT cpd;
  1388. cpd.dwData = 520;
  1389. cpd.cbData = sizeof(DWORD);
  1390. cpd.lpData = &dwEvent;
  1391. if(SendMessage(hwnd, WM_COPYDATA, (WPARAM)hwnd, (LPARAM)(LPVOID)&cpd)) {
  1392. Dbg("SendMessage to rvc_cursor window handle succ.");
  1393. return TRUE;
  1394. }
  1395. return FALSE;
  1396. }
  1397. ErrorCodeEnum CFreeRDPWrapFSM::UpdateAndChangeSrvStatus()
  1398. {
  1399. ErrorCodeEnum ec = Error_Unexpect;
  1400. SC_HANDLE h_scm = NULL;
  1401. SC_HANDLE h_srv = NULL;
  1402. CSimpleStringA strPath;
  1403. LPCTSTR lpcszFileName = FREERDP_SVC_NAME;
  1404. char szCmdLine[MAX_PATH] = {0};
  1405. BOOL fReStarted = FALSE, fNeedUpdate = FALSE, fNeedChange = FALSE;
  1406. DWORD dwBytesNeeded, cbBufSize, dwError;
  1407. LPQUERY_SERVICE_CONFIG lpsc = NULL;
  1408. SERVICE_STATUS_PROCESS ssStatus;
  1409. if(GetEntityBase()->GetFunction()->GetPath("Bin", strPath) != Error_Succeed
  1410. || strPath.IsNullOrEmpty())
  1411. {
  1412. Dbg("GetPath about bin failed");
  1413. goto Error;
  1414. }
  1415. strPath += "\\";
  1416. strPath += lpcszFileName;
  1417. h_scm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
  1418. if(h_scm == NULL) {
  1419. dwError = GetLastError();
  1420. Dbg("Open scm failed, GLE=%u", dwError);
  1421. goto Error;
  1422. }
  1423. Restart:
  1424. h_srv = OpenService(h_scm, SERVICE_SPECIFICED_NAME, SERVICE_QUERY_CONFIG);
  1425. dwError = GetLastError();
  1426. if(h_srv == NULL && dwError == ERROR_SERVICE_DOES_NOT_EXIST) {
  1427. if(fReStarted) {
  1428. ec = Error_NoPrivilege;
  1429. goto Error;
  1430. }
  1431. if(!ExistsFileA(strPath)) {
  1432. Dbg("%s is not existed.", lpcszFileName);
  1433. ec = Error_NotExist;
  1434. goto Error;
  1435. }
  1436. memset(szCmdLine, 0, sizeof(szCmdLine));
  1437. strcpy_s(szCmdLine, strPath);
  1438. strcat_s(szCmdLine, " -i");
  1439. if(!(ExecWaitWithExitCode(szCmdLine, dwError)) || dwError != 0) {
  1440. goto Error;
  1441. }
  1442. fReStarted = TRUE;
  1443. goto Restart;
  1444. }
  1445. if(h_srv != NULL) {
  1446. if(!QueryServiceConfig(h_srv, NULL, 0, &dwBytesNeeded)) {
  1447. dwError = GetLastError();
  1448. if(ERROR_INSUFFICIENT_BUFFER == dwError) {
  1449. cbBufSize = dwBytesNeeded;
  1450. lpsc = (LPQUERY_SERVICE_CONFIG)LocalAlloc(LMEM_FIXED, cbBufSize);
  1451. } else {
  1452. Dbg("QueryServiceConfig failed, GLE=%d", dwError);
  1453. goto Error;
  1454. }
  1455. }
  1456. if(!QueryServiceConfig(h_srv, lpsc, cbBufSize, &dwBytesNeeded)) {
  1457. dwError = GetLastError();
  1458. Dbg("QueryServiceConfig twice failed, GLE=%d", dwError);
  1459. goto Error;
  1460. }
  1461. if(_strnicmp(strPath, lpsc->lpBinaryPathName, strPath.GetLength()) != 0) {
  1462. Dbg("%s VS %s", lpsc->lpBinaryPathName, (LPCSTR)strPath);
  1463. fNeedUpdate = TRUE;
  1464. }
  1465. if(lpsc->dwStartType != SERVICE_AUTO_START) {
  1466. fNeedChange = TRUE;
  1467. }
  1468. }
  1469. if(fNeedUpdate) {
  1470. CloseServiceHandle(h_srv);
  1471. h_srv = NULL;
  1472. memset(szCmdLine, 0, sizeof(szCmdLine));
  1473. strcpy_s(szCmdLine, strPath);
  1474. strcat_s(szCmdLine, " -u");
  1475. if(!(ExecWaitWithExitCode(szCmdLine, dwError)) || dwError != 0) {
  1476. goto Error;
  1477. }
  1478. memset(szCmdLine, 0, sizeof(szCmdLine));
  1479. strcpy_s(szCmdLine, strPath);
  1480. strcat_s(szCmdLine, " -i");
  1481. if(!(ExecWaitWithExitCode(szCmdLine, dwError)) || dwError != 0) {
  1482. goto Error;
  1483. }
  1484. memset(szCmdLine, 0, sizeof(szCmdLine));
  1485. strcpy_s(szCmdLine, strPath);
  1486. strcat_s(szCmdLine, " -t");
  1487. if(!(ExecWaitWithExitCode(szCmdLine, dwError)) || dwError != 0) {
  1488. goto Error;
  1489. }
  1490. }
  1491. if(h_srv != NULL) {
  1492. CloseServiceHandle(h_srv);
  1493. h_srv = NULL;
  1494. }
  1495. h_srv = OpenService(h_scm, SERVICE_SPECIFICED_NAME, SERVICE_QUERY_STATUS);
  1496. dwError = GetLastError();
  1497. if(h_srv == NULL) {
  1498. Dbg("open service failed, GLE=%d", dwError);
  1499. goto Error;
  1500. }
  1501. if(!QueryServiceStatusEx(h_srv, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssStatus, sizeof(SERVICE_STATUS_PROCESS), &dwBytesNeeded)) {
  1502. dwError = GetLastError();
  1503. Dbg("QueryServiceStatusEx failed, GLE=%d", dwError);
  1504. goto Error;
  1505. }
  1506. Dbg("The service's current status: %d", ssStatus.dwCurrentState);
  1507. if(ssStatus.dwCurrentState != SERVICE_RUNNING && ssStatus.dwCurrentState != SERVICE_START_PENDING) {
  1508. memset(szCmdLine, 0, sizeof(szCmdLine));
  1509. strcpy_s(szCmdLine, strPath);
  1510. strcat_s(szCmdLine, " -t");
  1511. if(!(ExecWaitWithExitCode(szCmdLine, dwError)) || dwError != 0) {
  1512. goto Error;
  1513. }
  1514. }
  1515. ec = Error_Succeed;
  1516. Error:
  1517. if(lpsc) {
  1518. LocalFree(lpsc);
  1519. }
  1520. if(h_srv) {
  1521. CloseServiceHandle(h_srv);
  1522. }
  1523. if(h_scm) {
  1524. CloseServiceHandle(h_scm);
  1525. }
  1526. return ec;
  1527. }
  1528. BOOL CFreeRDPWrapFSM::ExecWaitWithExitCode(LPTSTR lpszCmdLine, DWORD& dwExitCode)
  1529. {
  1530. BOOL fResult = FALSE;
  1531. STARTUPINFO si = { 0 };
  1532. PROCESS_INFORMATION pi = { 0 };
  1533. ZeroMemory(&si, sizeof(STARTUPINFO));
  1534. si.cb = sizeof(si);
  1535. dwExitCode = 0;
  1536. if (!CreateProcess(NULL, lpszCmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
  1537. dwExitCode = GetLastError();
  1538. Dbg("CreateProcess with \"%s\" error, GLE=%u.", lpszCmdLine, dwExitCode);
  1539. if(dwExitCode == 2 || dwExitCode == 5) {
  1540. char* point = strstr(lpszCmdLine, "bcdedit.exe");
  1541. if(point != NULL) {
  1542. char bak[MAX_PATH] = {0};
  1543. strcpy_s(bak, ".\\bin\\RvcHIDFilter\\bcdedit.exe");
  1544. strcat_s(bak, point+strlen("bcdedit.exe"));
  1545. if(!CreateProcess(NULL, bak, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
  1546. dwExitCode = GetLastError();
  1547. Dbg("CreateProcess with \"%s\" error, GLE=%u.", bak, dwExitCode);
  1548. return fResult;
  1549. }
  1550. else {
  1551. Dbg("CreateProcess with \"%s\" succ.", bak);
  1552. }
  1553. }
  1554. }
  1555. }
  1556. CloseHandle(pi.hThread);
  1557. WaitForSingleObject(pi.hProcess, INFINITE);
  1558. GetExitCodeProcess(pi.hProcess, &dwExitCode);
  1559. Dbg("\"%s\" process quit! exit code: %d", lpszCmdLine, dwExitCode);
  1560. CloseHandle(pi.hProcess);
  1561. return TRUE;
  1562. }
  1563. BOOL CFreeRDPWrapFSM::ExecWaitWithResultContent(LPTSTR lpszCmdLine, CSimpleStringA& strResult)
  1564. {
  1565. LOG_FUNCTION();
  1566. BOOL fResult = FALSE;
  1567. STARTUPINFO si = { 0 };
  1568. SECURITY_ATTRIBUTES sa = {0};
  1569. PROCESS_INFORMATION pi = { 0 };
  1570. HANDLE hOutRead = NULL;
  1571. HANDLE hOutWrite = NULL;
  1572. HANDLE hInRead = NULL;
  1573. HANDLE hInWrite = NULL;
  1574. char szBuffer[2049] = {0};
  1575. DWORD dwNumOfBytesRead = 0;
  1576. DWORD dwExitCode = 0;
  1577. sa.nLength = sizeof(sa);
  1578. sa.bInheritHandle = TRUE;
  1579. sa.lpSecurityDescriptor = NULL;
  1580. CreatePipe(&hOutRead, &hOutWrite, &sa, 0);
  1581. CreatePipe(&hInRead, &hInWrite, &sa, 0);
  1582. ZeroMemory(&si, sizeof(STARTUPINFO));
  1583. si.cb = sizeof(si);
  1584. GetStartupInfo(&si);
  1585. si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
  1586. si.wShowWindow = SW_HIDE;
  1587. si.hStdInput = hInRead;
  1588. si.hStdOutput = hOutWrite;
  1589. si.hStdError = hOutWrite;
  1590. if (!CreateProcess(NULL, lpszCmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
  1591. dwExitCode = GetLastError();
  1592. Dbg("CreateProcess with <%s> error, GLE=%u.", lpszCmdLine, dwExitCode);
  1593. if(dwExitCode == 2 || dwExitCode == 5) {
  1594. char* point = strstr(lpszCmdLine, "bcdedit.exe");
  1595. if(point != NULL) {
  1596. char bakup[MAX_PATH] = {0};
  1597. strcpy_s(bakup, ".\\bin\\RvcHIDFilter\\bcdedit.exe");
  1598. strcat_s(bakup, point+strlen("bcdedit.exe"));
  1599. if(!CreateProcess(NULL, bakup, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
  1600. dwExitCode = GetLastError();
  1601. Dbg("CreateProcess with <%s> error, GLE=%u.", bakup, dwExitCode);
  1602. CloseHandle(hOutWrite);
  1603. CloseHandle(hInRead);
  1604. CloseHandle(pi.hThread);
  1605. return fResult;
  1606. } else {
  1607. Dbg("CreateProcess with \"%s\" succ.", bakup);
  1608. }
  1609. }
  1610. } else {
  1611. CloseHandle(hOutWrite);
  1612. CloseHandle(hInRead);
  1613. CloseHandle(pi.hThread);
  1614. return fResult;
  1615. }
  1616. }
  1617. CloseHandle(hOutWrite);
  1618. CloseHandle(hInRead);
  1619. CloseHandle(pi.hThread);
  1620. fResult = TRUE;
  1621. strResult = "";
  1622. while(TRUE) {
  1623. fResult = ReadFile(hOutRead, &szBuffer, 2048, &dwNumOfBytesRead, NULL);
  1624. if(!fResult) {
  1625. LogError(Severity_Low, Error_IO, 0,
  1626. CSimpleStringA::Format("Error reading pipe, GLE=%d", GetLastError()));
  1627. break;
  1628. }
  1629. szBuffer[dwNumOfBytesRead > 2048 ? 2048 : dwNumOfBytesRead] = '\0';
  1630. strResult += CSimpleStringA(szBuffer);
  1631. //Dbg("%s", szBuffer);
  1632. memset(szBuffer, 0, sizeof(szBuffer));
  1633. }
  1634. Dbg("Content==>");
  1635. Dbg("%s", (LPCTSTR)strResult);
  1636. Dbg("<==Content");
  1637. WaitForSingleObject(pi.hProcess, 10 * 1000);
  1638. GetExitCodeProcess(pi.hProcess, &dwExitCode);
  1639. Dbg("\"%s\" process quit! exit code: %d", lpszCmdLine, dwExitCode);
  1640. CloseHandle(pi.hProcess);
  1641. CloseHandle(hOutRead);
  1642. CloseHandle(hInWrite);
  1643. return TRUE;
  1644. }
  1645. /*
  1646. ErrorCodeEnum CFreeRDPWrapFSM::CreateProcessRunAs(LPCTSTR lpcszCmdLine, LPCTSTR lpcszUserName)
  1647. {
  1648. LPCTSTR lpcszFileName = "wFreeWrapSvc.exe";
  1649. ErrorCodeEnum ec = Error_Unexpect;
  1650. static char szCmdLine[MAX_PATH] = {0};
  1651. DWORD dwError;
  1652. BOOL fSvcCreated = FALSE;
  1653. SC_HANDLE h_scm = NULL;
  1654. SC_HANDLE h_srv = NULL;
  1655. PROCESS_INFORMATION pi = {0};
  1656. CSimpleStringA strPath;
  1657. if(GetEntityBase()->GetFunction()->GetPath("Bin", strPath) != Error_Succeed
  1658. || strPath.IsNullOrEmpty())
  1659. {
  1660. Dbg("GetPath about bin failed");
  1661. return Error_Param;
  1662. }
  1663. strPath += "\\";
  1664. strPath += lpcszFileName;
  1665. Dbg("FilePath: %s", (LPCTSTR)strPath);
  1666. if(!ExistsFileA(strPath)) {
  1667. Dbg("%s is not existed.", lpcszFileName);
  1668. return Error_Resource;
  1669. }
  1670. h_scm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
  1671. if(h_scm == NULL) {
  1672. dwError = GetLastError();
  1673. Dbg("Open scm failed, GLE=%u", dwError);
  1674. goto Error;
  1675. }
  1676. h_srv = OpenService(h_scm, SERVICE_SPECIFICED_NAME, SERVICE_USER_DEFINED_CONTROL);
  1677. dwError = GetLastError();
  1678. if(h_srv || (h_srv == NULL && dwError != ERROR_SERVICE_DOES_NOT_EXIST)) {
  1679. if(h_srv) {
  1680. CloseServiceHandle(h_srv);
  1681. h_srv = NULL;
  1682. }
  1683. memset(szCmdLine, 0, sizeof(szCmdLine));
  1684. strcpy_s(szCmdLine, strPath);
  1685. strcat_s(szCmdLine, " -u");
  1686. if(!(ExecWaitWithExitCode(szCmdLine, dwError)) || dwError != 0) {
  1687. goto Error;
  1688. }
  1689. }
  1690. memset(szCmdLine, 0, sizeof(szCmdLine));
  1691. strcpy_s(szCmdLine, strPath);
  1692. strcat_s(szCmdLine, " -i");
  1693. if(!(ExecWaitWithExitCode(szCmdLine, dwError)) || dwError != 0) {
  1694. goto Error;
  1695. }
  1696. memset(szCmdLine, 0, sizeof(szCmdLine));
  1697. strcpy_s(szCmdLine, strPath);
  1698. strcat_s(szCmdLine, " -t");
  1699. if(!(ExecWaitWithExitCode(szCmdLine, dwError)) || dwError != 0) {
  1700. goto Error;
  1701. }
  1702. CloseServiceHandle(h_scm);
  1703. h_scm = NULL;
  1704. fSvcCreated = TRUE;
  1705. if(!CreateProcessFromSrv(lpcszCmdLine, lpcszUserName, &pi)) {
  1706. goto Error;
  1707. }
  1708. ec = Error_Succeed;
  1709. Error:
  1710. if(fSvcCreated) {
  1711. memset(szCmdLine, 0, sizeof(szCmdLine));
  1712. strcpy_s(szCmdLine, strPath);
  1713. strcat_s(szCmdLine, " -u");
  1714. ExecWaitWithExitCode(szCmdLine, dwError);
  1715. }
  1716. if(h_srv) {
  1717. CloseServiceHandle(h_srv);
  1718. }
  1719. if(h_scm) {
  1720. CloseServiceHandle(h_scm);
  1721. }
  1722. return ec;
  1723. }
  1724. */
  1725. ErrorCodeEnum CFreeRDPWrapFSM::CreateProcessFromSrvWait(
  1726. LPCTSTR lpcszCmdLine, LPCTSTR lpcszUserName, PROCESS_INFORMATION *ppi)
  1727. {
  1728. ErrorCodeEnum ec;
  1729. DWORD dwSession;
  1730. int ret;
  1731. ec = CreateProcessFromSrv(lpcszCmdLine, lpcszUserName, ppi);
  1732. if(ec == Error_NoTarget) {
  1733. int times = 0;
  1734. do
  1735. {
  1736. Sleep(3000);
  1737. ret = CheckActivedSession(lpcszUserName, &dwSession);
  1738. Dbg("ret = %d", ret);
  1739. if(ret == 3) {
  1740. ec = CreateProcessFromSrv(lpcszCmdLine, lpcszUserName, NULL);
  1741. break;
  1742. }
  1743. if(++times >= 10) {
  1744. ec = Error_TimeOut;
  1745. break;
  1746. }
  1747. } while (true);
  1748. }
  1749. return ec;
  1750. }
  1751. ErrorCodeEnum CFreeRDPWrapFSM::CreateProcessFromSrv(
  1752. LPCTSTR lpcszCmdLine, LPCTSTR lpcszUserName, PROCESS_INFORMATION *ppi)
  1753. {
  1754. static const char szName[] = "Global\\SpModProcessXCreate";
  1755. HANDLE hMapFile = NULL;
  1756. SERVICE_STATUS status = {0};
  1757. PSP_CREATE_PROCESS_INFO pbuf = NULL;
  1758. int buf_size;
  1759. SC_HANDLE h_scm = NULL;
  1760. SC_HANDLE h_srv = NULL;
  1761. DWORD dwError;
  1762. ErrorCodeEnum ec = Error_Unexpect;
  1763. if(m_DeactiveClientManager) {
  1764. Dbg("the client user is depecrated!");
  1765. ec = Error_InvalidState;
  1766. return ec;
  1767. }
  1768. Dbg("Wait ...");
  1769. dwError = WaitForSingleObject(m_hSrvMutex, 8000);
  1770. if(dwError == WAIT_TIMEOUT) {
  1771. Dbg("Need to wait a minute bz it make someone seem hurry up...");
  1772. return Error_Pending;
  1773. }
  1774. Dbg("Wait finished.");
  1775. h_scm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
  1776. if(h_scm == NULL) {
  1777. dwError = GetLastError();
  1778. Dbg("Open scm failed, GLE=%u", dwError);
  1779. goto Error;
  1780. }
  1781. h_srv = OpenService(h_scm, SERVICE_SPECIFICED_NAME, SERVICE_USER_DEFINED_CONTROL);
  1782. if(h_srv == NULL) {
  1783. dwError = GetLastError();
  1784. if(dwError == ERROR_SERVICE_DOES_NOT_EXIST) {
  1785. Dbg("The specified service does not exist ");
  1786. ec = Error_NotExist;
  1787. }else {
  1788. Dbg("Open service failed, GLE=%u", dwError);
  1789. }
  1790. goto Error;
  1791. }
  1792. SP_CREATE_PROCESS_INFO info;
  1793. ZeroMemory(&info, sizeof(SP_CREATE_PROCESS_INFO));
  1794. buf_size = sizeof(SP_CREATE_PROCESS_INFO);
  1795. hMapFile = CreateFileMapping(
  1796. INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, buf_size, szName);
  1797. if(hMapFile == NULL) {
  1798. dwError = GetLastError();
  1799. Dbg("Create file map failed, GLE=%u", dwError);
  1800. goto Error;
  1801. }
  1802. pbuf = (PSP_CREATE_PROCESS_INFO)MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS,
  1803. 0, 0, buf_size);
  1804. if(pbuf == NULL) {
  1805. dwError = GetLastError();
  1806. Dbg("Could not map view of file (%d).", dwError);
  1807. goto Error;
  1808. }
  1809. Dbg("MapViewOfFile succ.");
  1810. info.usVersion = SVC_CREATE_PROCESS_VERSION_1;
  1811. strcpy_s(info.szCmdline, lpcszCmdLine);
  1812. strcpy_s(info.szUserName, lpcszUserName);
  1813. Dbg("Srv::CmdLine: {%s}, user: {%s}", info.szCmdline, info.szUserName);
  1814. CopyMemory((PVOID)pbuf, &info, buf_size);
  1815. if(!ControlService(h_srv, SERVICE_CONTROL_CREATEPROCESS, &status)) {
  1816. dwError = GetLastError();
  1817. if(dwError == ERROR_SERVICE_NOT_ACTIVE) {
  1818. Dbg("The service has not been started.");
  1819. ec = Error_InvalidState;
  1820. }
  1821. else {
  1822. Dbg("Control service failed, GLE=%u", dwError);
  1823. }
  1824. goto Error;
  1825. }
  1826. Dbg("Control Service succ.");
  1827. ec = Error_Succeed;
  1828. if(pbuf->usValiSize == 0) {
  1829. Dbg("map file returned value indicates that operation is failed.");
  1830. if(pbuf->dwLastError == ERROR_NO_SUCH_LOGON_SESSION) {
  1831. ec = Error_NoTarget;
  1832. } else {
  1833. ec = Error_Process;
  1834. }
  1835. }else if(ppi) {
  1836. memcpy(ppi, &(pbuf->pi), sizeof(PROCESS_INFORMATION));
  1837. Dbg("pid %d, handle 0x%x", ppi->dwProcessId, ppi->hProcess);
  1838. }
  1839. Error:
  1840. if(h_srv) {
  1841. CloseServiceHandle(h_srv);
  1842. }
  1843. if(h_scm) {
  1844. CloseServiceHandle(h_scm);
  1845. }
  1846. if(pbuf) {
  1847. UnmapViewOfFile(pbuf);
  1848. }
  1849. if(hMapFile) {
  1850. CloseHandle(hMapFile);
  1851. }
  1852. ReleaseMutex(m_hSrvMutex);
  1853. return ec;
  1854. }
  1855. inline void CFreeRDPWrapFSM::SendWfreeWrapEvt(int evtType, int reserved1 /*= 0*/, int reserved2 /*= 0*/)
  1856. {
  1857. DWORD dwREcipents = BSM_APPLICATIONS | BSM_ALLDESKTOPS;
  1858. WfreeWrapEvt evt;
  1859. evt.evtType = evtType;
  1860. ErrorCodeEnum ec = SpSendBroadcast(m_pEntity->GetFunction(),
  1861. SP_MSG_OF(WfreeWrapEvt),SP_MSG_SIG_OF(WfreeWrapEvt), evt);
  1862. Dbg("Send WfreeWrapEvt brocast: %d ! ec = 0x%X", evt.evtType, ec);
  1863. if(evtType > 0 && (ShareMode)evtType == AM2Client) {
  1864. if(WM_DESKSHARE_MSG != 0) {
  1865. if(0 >= BroadcastSystemMessageA(BSF_POSTMESSAGE | BSF_FORCEIFHUNG | BSF_IGNORECURRENTTASK,
  1866. &dwREcipents, WM_DESKSHARE_MSG, DESKSHARE_FLAG_CONDITION, FLAG_CONDITION_VIEWER)) {
  1867. Dbg("BroadcastSystemMessageA failed %d", GetLastError());
  1868. }
  1869. } else {
  1870. Dbg("WM_DESKSHARE_MSG is invalid!!");
  1871. }
  1872. } else if(evtType < 0 && (ShareMode)(0-evtType) == AM2Client) {
  1873. if(WM_DESKSHARE_MSG != 0) {
  1874. if(0 >= BroadcastSystemMessageA(BSF_POSTMESSAGE | BSF_FORCEIFHUNG | BSF_IGNORECURRENTTASK,
  1875. &dwREcipents, WM_DESKSHARE_MSG, DESKSHARE_FLAG_CONDITION, FLAG_CONDITION_DONE)) {
  1876. Dbg("BroadcastSystemMessageA failed %d", GetLastError());
  1877. }
  1878. } else {
  1879. Dbg("WM_DESKSHARE_MSG is invalid!!");
  1880. }
  1881. }
  1882. }
  1883. ErrorCodeEnum CFreeRDPWrapFSM::CreateDeskShareProc(bool force)
  1884. {
  1885. DWORD dwSession = 0;
  1886. int ret = 0;
  1887. CSimpleStringA strPath;
  1888. ErrorCodeEnum ec = Error_Succeed;
  1889. BOOL bAvailable = FALSE;
  1890. //Check whether the share desktop appliation is alive
  1891. BOOL bAlive = RDPPipe_IsClientSurvival(bAvailable);
  1892. if(bAlive) {
  1893. if(!force) {
  1894. if(bAvailable) {
  1895. return Error_AlreadyExist;
  1896. }
  1897. Dbg("SpDeskShare is not available !!!!");
  1898. }
  1899. Dbg("SpDeskShare.exe is survived, force to kill it(%d).", bAvailable);
  1900. char szCmdLine[MAX_PATH] = {0};
  1901. strcpy_s(szCmdLine, "taskkill /F /IM SpDeskShare.exe /T");
  1902. ec = CreateProcessFromSrvWait(szCmdLine, (LPCTSTR)m_strUserName, NULL);
  1903. if(ec != Error_Succeed) {
  1904. Dbg("taskkill failed, ec=%d", ec);
  1905. bAlive = false;
  1906. }
  1907. }
  1908. if(GetEntityBase()->GetFunction()->GetPath("Bin", strPath) != Error_Succeed
  1909. || strPath.IsNullOrEmpty())
  1910. {
  1911. Dbg("GetPath about bin failed");
  1912. return Error_NoPrivilege;
  1913. }
  1914. strPath += "\\SpDeskShare.exe";
  1915. if(!ExistsFileA(strPath)) {
  1916. Dbg("%s is not existed.", (LPCTSTR)strPath);
  1917. return Error_NotExist;
  1918. }
  1919. Dbg("test: %s(%d)", (LPCTSTR)m_strUserName, bAlive);
  1920. if(bAlive) {
  1921. Sleep(1500);
  1922. ec = CreateProcessFromSrv(strPath, (LPCTSTR)m_strUserName, NULL);
  1923. } else {
  1924. ec = CreateProcessFromSrvWait(strPath, (LPCTSTR)m_strUserName, NULL);
  1925. }
  1926. return ec;
  1927. }
  1928. int CFreeRDPWrapFSM::CreateInstallDrvTask(const BOOL& kbdRequired, const BOOL& mouRequired)
  1929. {
  1930. if(!kbdRequired && !mouRequired) {
  1931. return 0;
  1932. }
  1933. DrvInstallTask* task = new DrvInstallTask(this);
  1934. task->kbdRequired = kbdRequired;
  1935. task->mouRequired = mouRequired;
  1936. if(GetEntityBase()->GetFunction()->PostThreadPoolTask(task) == Error_Succeed) {
  1937. return 1;
  1938. }
  1939. Dbg("Zero ???");
  1940. return 0;
  1941. }
  1942. ErrorCodeEnum CFreeRDPWrapFSM::InstallFiltrDriver(DEVTYPE dt)
  1943. {
  1944. CSimpleStringA strInfPath = "";
  1945. DWORD dwResult = 0;
  1946. SYSTEM_INFO sysInfo = {};
  1947. GetNativeSystemInfo(&sysInfo);
  1948. bool bX64 = (sysInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64);
  1949. char szCmdLine[MAX_PATH] = {0};
  1950. CSimpleStringA strPath;
  1951. if(this->GetEntityBase()->GetFunction()->GetPath("Bin", strPath) != Error_Succeed) {
  1952. return Error_NoPrivilege;
  1953. }
  1954. if (bX64) {
  1955. if(dt == DEV_MOUSE) {
  1956. strInfPath = strPath + RVC_DRIV_INSTALL_DRI64;
  1957. strInfPath += SYS_MOUSE_DRIVERNAME;
  1958. }else if(dt == DEV_KEYBOARD) {
  1959. strInfPath = strPath + RVC_DRIV_INSTALL_DRI64;
  1960. strInfPath += SYS_KEYBOARD_DRIVERNAME;
  1961. }
  1962. }
  1963. else {
  1964. if(dt == DEV_MOUSE) {
  1965. strInfPath = strPath + RVC_DRIV_INSTALL_DRI;
  1966. strInfPath += SYS_MOUSE_DRIVERNAME;
  1967. }else if(dt == DEV_KEYBOARD) {
  1968. strInfPath = strPath + RVC_DRIV_INSTALL_DRI;
  1969. strInfPath += SYS_KEYBOARD_DRIVERNAME;
  1970. }
  1971. }
  1972. if(!strInfPath.IsNullOrEmpty()) {
  1973. if(!ExistsFileA(strInfPath)) {
  1974. LogWarn(Severity_Middle, Error_NotExist, ERROR_FREERDP_DRIVER_INF_FILE_NOT_EXIST,
  1975. CSimpleStringA::Format("Inf file is not existed: %s", (LPCTSTR)strInfPath));
  1976. return Error_NotExist;
  1977. }
  1978. } else {
  1979. return Error_Param;
  1980. }
  1981. if(bX64) {
  1982. strPath += RVC_DRIV_INSTALL_EXE64;
  1983. } else {
  1984. strPath += RVC_DRIV_INSTALL_EXE;
  1985. }
  1986. if(!ExistsFileA(strPath)) {
  1987. LogWarn(Severity_Middle, Error_NotExist, ERROR_FREERDP_DRIVER_INSTALL_EXE_NOT_EXIST,
  1988. CSimpleStringA::Format("execute program is not existed: %s", (LPCTSTR)strPath));
  1989. Dbg("%s is not existed.", (LPCTSTR)strPath);
  1990. return Error_NotExist;
  1991. }
  1992. memset(szCmdLine, 0, sizeof(szCmdLine));
  1993. sprintf_s(szCmdLine, "%s /Install \"%s\"", (LPCTSTR)strPath, (LPCTSTR)strInfPath);
  1994. if(!(ExecWaitWithExitCode(szCmdLine, dwResult)) || dwResult != 0) {
  1995. LogWarn(Severity_Middle, Error_NotExist, ERROR_FREERDP_DRIVER_INSTALL_EXECUTE_FAILED,
  1996. "execute install task failed!");
  1997. return Error_Unexpect;
  1998. }
  1999. return Error_Succeed;
  2000. }
  2001. void CFreeRDPWrapFSM::CheckCriticalThread()
  2002. {
  2003. static DWORD dwExitCode = 0;
  2004. if(m_hWarerThread == NULL
  2005. ||
  2006. (GetExitCodeThread(m_hWarerThread, &dwExitCode) && dwExitCode != STILL_ACTIVE)) {
  2007. m_hWarerThread = NULL;
  2008. m_hWarerThread = CreateThread(
  2009. NULL, 0,
  2010. (LPTHREAD_START_ROUTINE)RDPWarer_MainWndStartAndLoop,
  2011. this,
  2012. 0, &m_dwWarerThreadID);
  2013. if(m_hWarerThread == NULL) {
  2014. LogWarn(Severity_High, Error_Unexpect, 0, "Create Warer thread failed!");
  2015. m_dwWarerThreadID = 0;
  2016. }
  2017. }
  2018. dwExitCode = 0;
  2019. if(m_hWndThread == NULL
  2020. ||
  2021. (GetExitCodeThread(m_hWndThread, &dwExitCode) && dwExitCode != STILL_ACTIVE)) {
  2022. m_hWndThread = NULL;
  2023. m_hWndThread = CreateThread(
  2024. NULL, 0,
  2025. (LPTHREAD_START_ROUTINE)DevMnt_MainWndStartAndLoop,
  2026. this,
  2027. 0, &m_dwWndThreadID);
  2028. if(m_hWndThread == NULL) {
  2029. LogWarn(Severity_High, Error_Unexpect, 0, "Create Wnd thread failed!");
  2030. m_dwWndThreadID = 0;
  2031. }
  2032. }
  2033. dwExitCode = 0;
  2034. if(m_hRDPMaintainThread == NULL
  2035. ||
  2036. (GetExitCodeThread(m_hRDPMaintainThread, &dwExitCode) && dwExitCode != STILL_ACTIVE)) {
  2037. m_hRDPMaintainThread = NULL;
  2038. m_hRDPMaintainThread = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0,
  2039. MaintainFreeRDPRoutine, this, 0, &m_dwRDPMaintainID));
  2040. if(!m_hRDPMaintainThread || m_hRDPMaintainThread == INVALID_HANDLE_VALUE) {
  2041. m_hRDPMaintainThread = NULL;
  2042. LogWarn(Severity_High, Error_Unexpect, 0, "Create RDP maintain thread failed!");
  2043. }
  2044. }
  2045. }
  2046. ErrorCodeEnum CFreeRDPWrapFSM::SetNumLockDefaultStatus()
  2047. {
  2048. ErrorCodeEnum ec = Error_Unexpect;
  2049. DWORD dwFlag = KEY_WRITE | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;;
  2050. if (gArch == 64) {
  2051. Dbg("64bit");
  2052. dwFlag |= KEY_WOW64_64KEY;
  2053. } else {
  2054. Dbg("32bit");
  2055. dwFlag |= KEY_WOW64_32KEY;
  2056. }
  2057. HKEY hKey;
  2058. LONG lResult = RegOpenKeyEx(HKEY_CURRENT_USER, "Control Panel\\Keyboard", 0, dwFlag, &hKey);
  2059. if(lResult == ERROR_SUCCESS) {
  2060. DWORD dwType = REG_SZ;
  2061. DWORD dwSize = MAX_PATH*sizeof(TCHAR);
  2062. TCHAR szValue[MAX_PATH] = { 0 };
  2063. lResult = RegQueryValueEx(hKey, "InitialKeyboardIndicators", NULL, &dwType, (LPBYTE)szValue, &dwSize);
  2064. if(lResult == ERROR_SUCCESS) {
  2065. Dbg("InitialKeyboardIndicators = %s", szValue);
  2066. if(strlen(szValue) == 0 || szValue[0] != '2') {
  2067. //Set num Lock on
  2068. TCHAR szNewValue[] = "2\0";
  2069. DWORD dwValSize = ((DWORD)(_tcslen(szNewValue)) + 1)*sizeof(TCHAR);
  2070. lResult = RegSetValueEx(hKey, "InitialKeyboardIndicators", 0, REG_SZ, (const BYTE*)szNewValue, dwValSize);
  2071. Dbg("Set InitialKeyboardIndicators returned: %d", lResult);
  2072. if(lResult == ERROR_SUCCESS) {
  2073. ec = Error_Succeed;
  2074. }
  2075. } else {
  2076. Dbg("InitialKeyboardIndicators has been alreadly set.");
  2077. ec = Error_Succeed;
  2078. }
  2079. } else {
  2080. Dbg("query value for InitialKeyboardIndicators failed: %d", lResult);
  2081. }
  2082. } else {
  2083. Dbg("open keyboard regedit node failed: %d", lResult);
  2084. }
  2085. if(hKey != NULL) {
  2086. RegCloseKey(hKey);
  2087. }
  2088. SetNumLock(TRUE);
  2089. return ec;
  2090. }
  2091. void CFreeRDPWrapFSM::SetNumLock(BOOL bState)
  2092. {
  2093. BYTE keyState[256];
  2094. GetKeyboardState((LPBYTE)keyState);
  2095. if( (bState && !(keyState[VK_NUMLOCK])) ||
  2096. (!bState && (keyState[VK_NUMLOCK])) ) {
  2097. // Simulate a key press
  2098. keybd_event( VK_NUMLOCK, 0x45,KEYEVENTF_EXTENDEDKEY | 0, 0);
  2099. // Simulate a key release
  2100. keybd_event( VK_NUMLOCK, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
  2101. }
  2102. }
  2103. void CFreeRDPWrapFSM::messageTest(BOOL on)
  2104. {
  2105. DWORD dwREcipents = BSM_APPLICATIONS | BSM_ALLDESKTOPS;
  2106. if(on) {
  2107. if(WM_DESKSHARE_MSG != 0) {
  2108. if(0 >= BroadcastSystemMessageA(BSF_POSTMESSAGE | BSF_FORCEIFHUNG | BSF_IGNORECURRENTTASK,
  2109. &dwREcipents, WM_DESKSHARE_MSG, DESKSHARE_FLAG_CONDITION, FLAG_CONDITION_VIEWER)) {
  2110. Dbg("BroadcastSystemMessageA failed %d", GetLastError());
  2111. }
  2112. } else {
  2113. Dbg("WM_DESKSHARE_MSG is invalid!!");
  2114. }
  2115. } else {
  2116. if(WM_DESKSHARE_MSG != 0) {
  2117. if(0 >= BroadcastSystemMessageA(BSF_POSTMESSAGE | BSF_FORCEIFHUNG | BSF_IGNORECURRENTTASK,
  2118. &dwREcipents, WM_DESKSHARE_MSG, DESKSHARE_FLAG_CONDITION, FLAG_CONDITION_DONE)) {
  2119. Dbg("BroadcastSystemMessageA failed %d", GetLastError());
  2120. }
  2121. } else {
  2122. Dbg("WM_DESKSHARE_MSG is invalid!!");
  2123. }
  2124. }
  2125. }
  2126. UINT WINAPI CFreeRDPWrapFSM::MaintainFreeRDPRoutine(LPVOID param)
  2127. {
  2128. CFreeRDPWrapFSM* fsm = reinterpret_cast<CFreeRDPWrapFSM*>(param);
  2129. if(fsm == NULL) {
  2130. return 0;
  2131. }
  2132. DWORD dwRet;
  2133. BOOL error;
  2134. const int MAX_ERROR_TIMES = 5;
  2135. int nFailedTimes;
  2136. DWORD dwCurTimeoutLevel = 0;
  2137. HANDLE hSnapshot;
  2138. PROCESSENTRY32 procEntry;
  2139. DWORD dwProcessID = (DWORD)-1;
  2140. DWORD dwParentProcID = (DWORD)-1;
  2141. HANDLE& hProcess = fsm->m_hFreeRDPProc;
  2142. DWORD& dwRdpProcessId = fsm->m_dwFreeRDPProcID;
  2143. HANDLE hEvents[2] = {NULL, NULL};
  2144. BOOL bNeedToCreate = TRUE;
  2145. ResetEvent(fsm->hExitEvent);
  2146. hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  2147. if(hSnapshot == INVALID_HANDLE_VALUE) {
  2148. Dbg("CreateToolhelp32Snapshot failed, GLE=%u", GetLastError());
  2149. return 0;
  2150. }
  2151. procEntry.dwSize = sizeof(procEntry);
  2152. if(!Process32First(hSnapshot, &procEntry)) {
  2153. Dbg("Process32First failed, GLE=%u", GetLastError());
  2154. CloseHandle(hSnapshot);
  2155. return 0;
  2156. }
  2157. do
  2158. {
  2159. if(!_stricmp(procEntry.szExeFile, FREERDP_PROCESS)) {
  2160. dwProcessID = procEntry.th32ProcessID;
  2161. dwParentProcID = procEntry.th32ParentProcessID;
  2162. break;
  2163. }
  2164. } while (Process32Next(hSnapshot, &procEntry));
  2165. SAFE_CLOSE_HANDLE(hSnapshot);
  2166. if(dwProcessID != (DWORD)-1) {
  2167. Dbg("Find the duplicate " FREERDP_PROCESS " process ! id = %d", dwProcessID);
  2168. CSimpleStringA strPath;
  2169. if(fsm->GetEntityBase()->GetFunction()->GetPath("Bin", strPath) == Error_Succeed
  2170. && !strPath.IsNullOrEmpty())
  2171. {
  2172. strPath += "\\freerdp\\wfreerdp.exe";
  2173. char szProcessPath[MAX_PATH] = {0};
  2174. GetProcessPath(dwProcessID, szProcessPath, MAX_PATH);
  2175. Dbg("GetProcessPath: %s", szProcessPath);
  2176. if(strcmp(szProcessPath, "???") != 0 && _stricmp(szProcessPath, (LPCTSTR)strPath) == 0) {
  2177. bNeedToCreate = FALSE;
  2178. }
  2179. }
  2180. if(bNeedToCreate) {
  2181. if(!KillSpecifiedProcess(dwProcessID)) {
  2182. hProcess = INVALID_HANDLE_VALUE;
  2183. dwRdpProcessId = -1;
  2184. return 0;
  2185. }
  2186. }
  2187. else {
  2188. hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessID);
  2189. if(hProcess == NULL || hProcess == INVALID_HANDLE_VALUE) {
  2190. Dbg("OpenProcess failed, GLE=%d", GetLastError());
  2191. bNeedToCreate = TRUE;
  2192. } else {
  2193. dwRdpProcessId = dwProcessID;
  2194. }
  2195. }
  2196. }
  2197. if(bNeedToCreate) {
  2198. hProcess = fsm->CreateFreeRDPProc(dwRdpProcessId);
  2199. if(hProcess == INVALID_HANDLE_VALUE || hProcess == NULL) {
  2200. hProcess = INVALID_HANDLE_VALUE;
  2201. dwRdpProcessId = -1;
  2202. return 0;
  2203. }
  2204. Dbg("Create " FREERDP_PROCESS " succ, pid = %d", dwRdpProcessId);
  2205. }
  2206. else {
  2207. Dbg("Use the survived process handle.");
  2208. }
  2209. hEvents[0] = hProcess;
  2210. hEvents[1] = fsm->hExitEvent;
  2211. error = FALSE;
  2212. nFailedTimes = 0;
  2213. dwCurTimeoutLevel = 10*1000;
  2214. do
  2215. {
  2216. dwRet = WaitForMultipleObjects(2, hEvents, FALSE, dwCurTimeoutLevel);
  2217. if(dwRet == WAIT_OBJECT_0) {
  2218. //password incorrect: 131092[0x20014]
  2219. DWORD dwExitCode;
  2220. GetExitCodeProcess(hProcess, &dwExitCode);
  2221. Dbg(FREERDP_PROCESS " process quit! exit code: %d[0x%X]", dwExitCode, dwExitCode);
  2222. CloseHandle(hProcess);
  2223. hProcess = INVALID_HANDLE_VALUE;
  2224. dwRdpProcessId = -1;
  2225. if(dwCurTimeoutLevel == 10*1000) {
  2226. if(++nFailedTimes >= MAX_ERROR_TIMES) {
  2227. Dbg("Give up! wait to restart the entity.");
  2228. LogWarn(Severity_Middle, Error_InvalidState,
  2229. ERROR_FREERDP_STARTUP_FAILED_MUCH_TIMES,
  2230. CSimpleStringA::Format("Startup wFreeRDP failed too much time! exit code: 0x%X", dwExitCode));
  2231. fsm->SetSelfCheckCode(Error_InvalidState);
  2232. break;
  2233. }
  2234. }
  2235. if(dwExitCode == 0x20014 && nFailedTimes == MAX_ERROR_TIMES - 1) {
  2236. fsm->TryChangeClientUserPswWithDefault();
  2237. }
  2238. Sleep(3000);
  2239. hProcess = fsm->CreateFreeRDPProc(dwRdpProcessId);
  2240. if(hProcess == INVALID_HANDLE_VALUE) {
  2241. error = TRUE;
  2242. break;
  2243. }
  2244. Dbg("ReCreate " FREERDP_PROCESS " succ, pid = %d", dwRdpProcessId);
  2245. hEvents[0] = hProcess;
  2246. } else if(dwRet == (WAIT_OBJECT_0 + 1)) {
  2247. Dbg("Receive quit message.");
  2248. break;
  2249. } else if(dwRet != WAIT_TIMEOUT) {
  2250. Dbg("Wait for rdp proc and quit event handle failed %d !", dwRet);
  2251. error = TRUE;
  2252. break;
  2253. } else if(dwCurTimeoutLevel == 10*1000) {
  2254. dwCurTimeoutLevel = INFINITE;
  2255. }
  2256. } while (true);
  2257. Dbg("Out of while(true).");
  2258. if(hProcess != INVALID_HANDLE_VALUE) {
  2259. CloseHandle(hProcess);
  2260. if(KillSpecifiedProcess(dwRdpProcessId))
  2261. {
  2262. hProcess = INVALID_HANDLE_VALUE;
  2263. dwRdpProcessId = -1;
  2264. }
  2265. }
  2266. Dbg("Exit FreeRDPRoutine thread.");
  2267. ExitThread(0);
  2268. return 0;
  2269. }
  2270. void CFreeRDPWrapFSM::BroadMonitorNumChange(const int curAvailMonitorNums)
  2271. {
  2272. DWORD userCode = 0;
  2273. LOG_ASSERT(curAvailMonitorNums >= 0);
  2274. if(curAvailMonitorNums != m_uMonitorNum)
  2275. {
  2276. switch(curAvailMonitorNums)
  2277. {
  2278. case 0:
  2279. userCode = ERROR_FREERDP_MONITOR_NONE;
  2280. break;
  2281. case 1:
  2282. userCode = ERROR_FREERDP_MONITOR_LACK;
  2283. break;
  2284. case 2:
  2285. userCode = ERROR_FREERDP_MONITOR_ENOUGH;
  2286. break;
  2287. default:
  2288. userCode = ERROR_FREERDP_MONITOR_DUPLICATE;
  2289. break;
  2290. }
  2291. }
  2292. if(curAvailMonitorNums == 1 && m_uMonitorNum > curAvailMonitorNums) {
  2293. CAutoArray<MonitorInfo> monitorArrStatic;
  2294. if(2 == GetMonitorInfoFromRunCfg(monitorArrStatic)) {
  2295. CAutoArray<MonitorInfo> monitorRuntime(2);
  2296. const int nums = GetRealtimeMonitorInfo(monitorRuntime);
  2297. LOG_ASSERT(nums == 1);
  2298. if(monitorRuntime[0].deviceID.Compare(monitorArrStatic[0].deviceID) == 0) {
  2299. userCode = ERROR_FREERDP_MONITOR_VICE_LOST;
  2300. Dbg("the vice monitor(client manager monitor) lost.");
  2301. } else if(monitorRuntime[0].deviceID.Compare(monitorArrStatic[1].deviceID) == 0) {
  2302. userCode = ERROR_FREERDP_MONITOR_PRIMARY_LOST;
  2303. Dbg("the primer monitor(client monitor) lost.");
  2304. } else {
  2305. Dbg("Unknown device: %s", monitorRuntime[0].deviceID.GetData());
  2306. }
  2307. } else {
  2308. Dbg("the RunCfg is not ready yet.");
  2309. }
  2310. }
  2311. if(userCode != 0)
  2312. {
  2313. LogWarn(Severity_Middle, Error_DevNotAvailable, userCode,
  2314. CSimpleStringA::Format("The Monitor num has been changed from %d to %d",
  2315. m_uMonitorNum, curAvailMonitorNums));
  2316. m_uMonitorNum = curAvailMonitorNums;
  2317. }
  2318. }
  2319. ErrorCodeEnum CFreeRDPWrapFSM::AgentAssistant(
  2320. SpReqAnsContext<FreeRDPWrapSrv_AgentAssistant_Req,
  2321. FreeRDPWrapSrv_AgentAssistant_Ans>::Pointer ctx)
  2322. {
  2323. ErrorCodeEnum ec = Error_Succeed;
  2324. USHORT usViewLevel = CTRL_LEVEL_VIEW;
  2325. char szFileName[MAX_PATH] = {0};
  2326. FILE *read = NULL;
  2327. int flen;
  2328. char* inviteString = NULL;
  2329. CSimpleStringW strContent;
  2330. CSimpleStringA str;
  2331. CInteractCtrlClient* client = new CInteractCtrlClient(GetEntityBase());
  2332. UIService_SendAgentText_Req req;
  2333. UIService_SendAgentText_Ans ans;
  2334. ec = client->Connect();
  2335. if(FAILURED(ec)) {
  2336. Display("Connect to InterctiveControl entity failed, EC=0x%X", ec);
  2337. client->SafeDelete();
  2338. client = NULL;
  2339. return ec;
  2340. }
  2341. ec = Error_Unexpect;
  2342. m_bInterview = FALSE;
  2343. if(ctx->Req.viewLevel == 1) {
  2344. usViewLevel = CTRL_LEVEL_INTERACTIVE;
  2345. m_bInterview = TRUE;
  2346. }
  2347. if(m_hWarerThread == INVALID_HANDLE_VALUE || !hWarerWnd) {
  2348. Display("Share window handle is invalid");
  2349. goto Error;
  2350. }
  2351. memset(szFileName, 0, sizeof(szFileName));
  2352. if(!CreateInviteFileName(szFileName, MAX_PATH)) {
  2353. goto Error;
  2354. }
  2355. m_strInviteFileName = szFileName;
  2356. if(!RDPWarer_ShareAndInvite(szFileName, ctx->Req.filterAppId, usViewLevel)) {
  2357. LogWarn(Severity_Middle, Error_Param, ERROR_FREERDP_SHARE_BUILD_UP_SHRER_FAILED, "Do the share and invite Job failed !");
  2358. goto Error;
  2359. }
  2360. fopen_s(&read, szFileName, "r");
  2361. if(!read) {
  2362. Display("Open inviation file failed: %s", szFileName);
  2363. goto Error;
  2364. }
  2365. fseek(read, 0, SEEK_END);
  2366. flen = ftell(read);
  2367. if (flen <= 0) {
  2368. fclose(read);
  2369. read = NULL;
  2370. Display("Invalid inviation file !");
  2371. goto Error;
  2372. }
  2373. inviteString = new char[flen + 1];
  2374. if (inviteString == NULL) {
  2375. Display("Alloc invite string failed!");
  2376. ec = Error_Resource;
  2377. goto Error;
  2378. }
  2379. ZeroMemory(inviteString, sizeof(char)*(flen + 1));
  2380. fseek(read, 0, SEEK_SET);
  2381. fgets(inviteString, flen, read);
  2382. inviteString[flen] = '\0';
  2383. fclose(read);
  2384. str = "START_INVITATION_STRING====";
  2385. str += inviteString;
  2386. str += "====END_INVITATION_STRING";
  2387. strContent = CSimpleStringA2W(str);
  2388. Display("==== START INVITATION STRING");
  2389. Display("%s", (LPCTSTR)inviteString);
  2390. Display("==== END INVITATION STRING");
  2391. delete[] inviteString;
  2392. inviteString = NULL;
  2393. Display("==== START INVITATION STRING");
  2394. Display("%ws", (LPCWSTR)strContent);
  2395. Display("==== END INVITATION STRING");
  2396. req.content = strContent;
  2397. ec = client->SendAgentText(req, ans, 10 * 1000);
  2398. if(FAILURED(ec)) {
  2399. Display("Invoke SendAgentText failed, EC=0x%X", ec);
  2400. goto Error;
  2401. }
  2402. Error:
  2403. if(ctx != NULL) {
  2404. ctx->Ans.retCode = Error_Succeed == ec ? 1 : -1;
  2405. ctx->Answer(Error_Succeed);
  2406. }
  2407. if(FAILURED(ec)) {
  2408. RDPWarer_CloseInvite();
  2409. } else {
  2410. m_bAgentSituation = TRUE;
  2411. m_bInvited = FALSE;
  2412. m_eShareMode = m_bInvited ? Seal2Client : Client2Seat;
  2413. }
  2414. client->GetFunction()->CloseSession();
  2415. client->SafeDelete();
  2416. client = NULL;
  2417. if(!m_strInviteFileName.IsNullOrEmpty()) {
  2418. DeleteFileA(m_strInviteFileName);
  2419. m_strInviteFileName = "";
  2420. }
  2421. return ec;
  2422. }
  2423. UINT CFreeRDPWrapFSM::UnitTest(LPCTSTR testTag)
  2424. {
  2425. //m_fsm.ShowFreeRDPCursor(FALSE);
  2426. //m_fsm.messageTest(TRUE);
  2427. //m_fsm.unitest_install_rdpwrap_component();
  2428. char test[] = "Cmb@2020";
  2429. CSimpleStringA strEnCippher(true);
  2430. if(!Plain2EncodeCipherString(test, strEnCippher))
  2431. return 1;
  2432. Dbg("encipher: %s", strEnCippher.GetData());
  2433. CSimpleStringA strPlainText(true);
  2434. if(!EncodeCipher2PlainString(strEnCippher, strPlainText))
  2435. return 2;
  2436. if(strPlainText.Compare(test) != 0)
  2437. return 3;
  2438. BackupClientUserPsw(strEnCippher);
  2439. CSimpleStringA strEnCippher2;
  2440. RetrieveClientUserPswFromBakup(strEnCippher2);
  2441. if(strEnCippher2.Compare(strEnCippher) != 0)
  2442. return 4;
  2443. CAutoArray<MonitorInfo> monitorArr(5);
  2444. const int nums = GetRealtimeMonitorInfo(monitorArr);
  2445. if(nums != 1)
  2446. return 5;
  2447. CAutoArray<MonitorInfo> monitorArrStatic;
  2448. if(0 != GetMonitorInfoFromRunCfg(monitorArrStatic)) {
  2449. return 6;
  2450. }
  2451. return 0;
  2452. }
  2453. int CFreeRDPWrapFSM::GetRealtimeMonitorInfo(CAutoArray<MonitorInfo>& monitorArr)
  2454. {
  2455. DISPLAY_DEVICE dd;
  2456. ZeroMemory(&dd, sizeof(dd));
  2457. dd.cb = sizeof(dd);
  2458. int validMonitorNum = 0;
  2459. for(int i=0; EnumDisplayDevicesA(NULL, i, &dd, 0)
  2460. && validMonitorNum < monitorArr.GetCount();
  2461. ++i)
  2462. {
  2463. MonitorInfo& curMonitor = monitorArr[validMonitorNum];
  2464. Dbg("===================");
  2465. Dbg("Device Index(%d)", i);
  2466. Dbg("Device Name: %s", dd.DeviceName);
  2467. Dbg("Device String: %s", dd.DeviceString);
  2468. Dbg("Device ID: %s", dd.DeviceID);
  2469. Dbg("Device Key: %s", dd.DeviceKey);
  2470. Dbg("StateFlags: %s%s%s%s",
  2471. ((dd.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) ? "desktop " : ""),
  2472. ((dd.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE) ? "primary " : ""),
  2473. ((dd.StateFlags & DISPLAY_DEVICE_VGA_COMPATIBLE) ? "vga " : ""),
  2474. ((dd.StateFlags & DISPLAY_DEVICE_MULTI_DRIVER) ? "multi " : ""),
  2475. ((dd.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER) ? "mirror " : ""));
  2476. DISPLAY_DEVICE dd2;
  2477. ZeroMemory(&dd2, sizeof(dd2));
  2478. dd2.cb = sizeof(dd2);
  2479. EnumDisplayDevices(dd.DeviceName, 0, &dd2, 0);
  2480. Dbg("Display Device Name: %s", dd2.DeviceName);
  2481. Dbg("Display Device String: %s", dd2.DeviceString);
  2482. Dbg("Display Device ID: %s", dd2.DeviceID);
  2483. Dbg("Display Device Key: %s", dd2.DeviceKey);
  2484. if(dd.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP
  2485. && strlen(dd2.DeviceName) > 0
  2486. && strlen(dd2.DeviceID) > 0
  2487. && strlen(dd2.DeviceKey) > 0)
  2488. {
  2489. curMonitor.bSet = TRUE;
  2490. curMonitor.bPrimary = (dd.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE);
  2491. curMonitor.deviceName = dd2.DeviceName;
  2492. curMonitor.deviceID = dd2.DeviceID;
  2493. curMonitor.deviceKey = dd2.DeviceKey;
  2494. validMonitorNum++;
  2495. }
  2496. }
  2497. Dbg("Get realtime monitor count: %d", validMonitorNum);
  2498. return validMonitorNum;
  2499. }
  2500. int CFreeRDPWrapFSM::GetMonitorInfoFromRunCfg(CAutoArray<MonitorInfo>& monitorArr)
  2501. {
  2502. CSmartPointer<IEntityFunction> spEntityFunction = GetEntityBase()->GetFunction();
  2503. CSmartPointer<IConfigInfo> spConfigRun;
  2504. auto ec = spEntityFunction->OpenConfig(Config_Run, spConfigRun);
  2505. if(FAILURED(ec)) {
  2506. Dbg("Open run config failed");
  2507. return 0;
  2508. }
  2509. Dbg("Read monitor information from RunCfg.");
  2510. int primaryIndex = 0, viceIndex = 1;
  2511. monitorArr.Init(2);
  2512. spConfigRun->ReadConfigValue("PrimaryMonitor", "Name", monitorArr[primaryIndex].deviceName);
  2513. spConfigRun->ReadConfigValue("PrimaryMonitor", "ID", monitorArr[primaryIndex].deviceID);
  2514. spConfigRun->ReadConfigValue("PrimaryMonitor", "Key", monitorArr[primaryIndex].deviceKey);
  2515. spConfigRun->ReadConfigValue("ViceMonitor", "Name", monitorArr[viceIndex].deviceName);
  2516. spConfigRun->ReadConfigValue("ViceMonitor", "ID", monitorArr[viceIndex].deviceID);
  2517. spConfigRun->ReadConfigValue("ViceMonitor", "Key", monitorArr[viceIndex].deviceKey);
  2518. if(monitorArr[primaryIndex].deviceID.IsNullOrEmpty()
  2519. || monitorArr[viceIndex].deviceID.IsNullOrEmpty())
  2520. return 0;
  2521. return monitorArr.GetCount();
  2522. }
  2523. BOOL CFreeRDPWrapFSM::IfDontActiveClientManagerDesk()
  2524. {
  2525. CSmartPointer<IEntityFunction> spFunction = m_pEntity->GetFunction();
  2526. CSmartPointer<IConfigInfo> spConfig;
  2527. ErrorCodeEnum eErr = spFunction->OpenConfig(Config_CenterSetting, spConfig);
  2528. int value = 0;
  2529. if (Error_Succeed == eErr)
  2530. {
  2531. eErr = spConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "Depecrate", value);
  2532. if (Error_Succeed == eErr)
  2533. {
  2534. Dbg("get Depecrate=%d from CenterSetting.ini", value);
  2535. }
  2536. else
  2537. {
  2538. Dbg("get Depecrate from CenterSetting.ini failed");
  2539. }
  2540. }
  2541. return (value == 1);
  2542. }
  2543. bool CFreeRDPWrapFSM::DetectPrimaryMonitors()
  2544. {
  2545. CAutoArray<MonitorInfo> monitorArr(5);
  2546. const int nums = GetRealtimeMonitorInfo(monitorArr);
  2547. if(nums == 2) {
  2548. int primaryIndex = monitorArr[0].bPrimary ? 0 : (monitorArr[1].bPrimary ? 1 : -1);
  2549. int viceIndex = primaryIndex == 0 ? 1 : 0;
  2550. if(primaryIndex == -1) {
  2551. return false;
  2552. }
  2553. CSmartPointer<IEntityFunction> spEntityFunction = GetEntityBase()->GetFunction();
  2554. CSmartPointer<IConfigInfo> spConfigRun;
  2555. auto ec = spEntityFunction->OpenConfig(Config_Run, spConfigRun);
  2556. if(FAILURED(ec)) {
  2557. Dbg("Open run config failed");
  2558. return false;
  2559. }
  2560. Dbg("Write monitor information to RunCfg.");
  2561. spConfigRun->WriteConfigValue("PrimaryMonitor", "Name", monitorArr[primaryIndex].deviceName);
  2562. spConfigRun->WriteConfigValue("PrimaryMonitor", "ID", monitorArr[primaryIndex].deviceID);
  2563. spConfigRun->WriteConfigValue("PrimaryMonitor", "Key", monitorArr[primaryIndex].deviceKey);
  2564. spConfigRun->WriteConfigValue("ViceMonitor", "Name", monitorArr[viceIndex].deviceName);
  2565. spConfigRun->WriteConfigValue("ViceMonitor", "ID", monitorArr[viceIndex].deviceID);
  2566. spConfigRun->WriteConfigValue("ViceMonitor", "Key", monitorArr[viceIndex].deviceKey);
  2567. return true;
  2568. }
  2569. return false;
  2570. }