AccessAuthFSM.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506
  1. #include "stdafx.h"
  2. #include "AccessAuthFSM.h"
  3. #include "mod_AccessAuth.h"
  4. #include "Event.h"
  5. #include "access_basefun.h"
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include "fileutil.h"
  9. #include "CommEntityUtil.hpp"
  10. #include "comm.h"
  11. #include "PinPad_client_g.h"
  12. using namespace PinPad;
  13. #ifdef RVC_OS_WIN
  14. #include <io.h>
  15. #include <stdint.h>"
  16. #include "MyBase64.h"
  17. #include <TlHelp32.h>
  18. #include <iphlpapi.h>
  19. #include <ws2tcpip.h>
  20. #include <Winsock2.h>
  21. #include <algorithm>
  22. #pragma comment(lib, "IPHLPAPI.lib")
  23. #define ALLOW_MULTI_NETWORKD_CARDS
  24. #else
  25. #include "CommEntityRestful.hpp"
  26. #include "SpUtility.h"
  27. #endif // RVC_OS_WIN
  28. int HexBuf2StrBuf(PBYTE hexBuf, char** strBuf, DWORD len)
  29. {
  30. char* tmpStr = *strBuf;
  31. int count = 0;
  32. for (int i = 0; i < len; ++i) {
  33. sprintf(tmpStr + count, "%0.2X", hexBuf[i]);
  34. count += 2;
  35. }
  36. return 0;
  37. }
  38. int StrBuf2HexBuf(LPCTSTR strBuf, PBYTE* hexBuf)
  39. {
  40. int len = strlen(strBuf);
  41. if (len == 0 || len % 2 != 0)
  42. return 0;
  43. BYTE* buf = new BYTE[len / 2];
  44. if (buf == NULL)
  45. return 0;
  46. int j = 0;
  47. for (int i = 0; i < len;) {
  48. int tmpVal;
  49. sscanf(strBuf + i, "%2X", &tmpVal);
  50. buf[j] = tmpVal;
  51. i += 2;
  52. j++;
  53. }
  54. *hexBuf = buf;
  55. return j;
  56. }
  57. CAccessAuthFSM::CAccessAuthFSM()
  58. :m_finishAccess(0), m_nAccessFailedCount(0)
  59. , m_accessAuthHost(true), m_initDeviceHost(true)
  60. , m_strNetworkCheckUrl(true), m_strDefaultDNS(true), m_strBackupDNS(true), m_fNetworkChecking(false)
  61. , m_strDevPubKey(""), m_torelateDiffSyncTimeSecs(180), isServeEvent(false)
  62. {
  63. }
  64. CAccessAuthFSM::~CAccessAuthFSM()
  65. {
  66. m_iState = FSM_STATE_EXIT; // 屏蔽退出ASSERT错误
  67. }
  68. void CAccessAuthFSM::OnStateTrans(int iSrcState, int iDstState)
  69. {
  70. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("trans from %s to %s", GetStateName(iSrcState), GetStateName(iDstState));
  71. }
  72. ErrorCodeEnum CAccessAuthFSM::OnInit()
  73. {
  74. LOG_FUNCTION();
  75. AddStateHooker(this);
  76. m_finishAccess = 0;
  77. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Complied at: %s %s", __DATE__, __TIME__);
  78. //设置初始锁定状态,0
  79. CSmartPointer<IEntityFunction> spFunction = m_pEntity->GetFunction();
  80. spFunction->SetSysVar("LockState", "0", true);
  81. ErrorCodeEnum Error = LoadCenterConfig();
  82. if (Error != Error_Succeed)
  83. {
  84. LOG_TRACE("load CenterSetting.ini failed!");
  85. }
  86. GetDiffSyncTimeFromCenterSettings();
  87. return Error_Succeed;
  88. }
  89. ErrorCodeEnum CAccessAuthFSM::OnExit()
  90. {
  91. RemoveStateHooker(this);
  92. return Error_Succeed;
  93. }
  94. void CAccessAuthFSM::HttpsLogCallBack(const char* logtxt)
  95. {
  96. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI("HttpsLogCallBack")("%s", logtxt);
  97. }
  98. struct TimeSynTask : ITaskSp
  99. {
  100. CAccessAuthFSM* m_fsm;
  101. TimeSynTask(CAccessAuthFSM* fsm) :m_fsm(fsm) {}
  102. void Process()
  103. {
  104. if (m_fsm->GetmAccessAuthHost().IsNullOrEmpty())
  105. {
  106. LogWarn(Severity_Middle, Error_Unexpect, AccessAuthorization_UserErrorCode_AccessAuth_NULL, "准入Url为空");
  107. FSMEvent* pEvent = new FSMEvent(CAccessAuthFSM::Event_ReqTokenCancel);
  108. pEvent->param1 = AccessAuthorization_UserErrorCode_AccessAuth_NULL;
  109. m_fsm->PostEventFIFO(pEvent);
  110. CSimpleStringA strMsg(true);
  111. strMsg = CSimpleStringA::Format("准入服务地址为空,请下载集中配置或重启应用");
  112. m_fsm->doWarnMsg(AccessAuthorization_UserErrorCode_AccessAuth_NULL, strMsg.GetData(), true);
  113. return;
  114. }
  115. CSystemStaticInfo si;
  116. m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(si);
  117. #ifdef RVC_OS_WIN
  118. IHttpFunc* client;
  119. client = create_http(m_fsm->HttpsLogCallBack);
  120. CSessionkeySynReq timeSynReq;
  121. CSessionkeySynRet timeSynRet;
  122. timeSynReq.terminalNo = si.strTerminalID.GetData();
  123. timeSynReq.curTime = CSmallDateTime::GetNow().GetTime64();
  124. timeSynReq.m_url = m_fsm->GetmAccessAuthHost();
  125. timeSynReq.m_url += "/api/v3/sessionkey";//v3 新接口,返回title、content
  126. long beg = GetTickCount();
  127. bool ret = client->Post(timeSynReq, timeSynRet);
  128. long end = GetTickCount();
  129. if (ret) {
  130. if (timeSynRet.m_userCode.compare(ACS_SUCCESS)) {
  131. m_fsm->AuthLogWarn(timeSynRet, timeSynReq.m_url, "获取会话密钥");
  132. if (client) client->Destory();
  133. return;
  134. }
  135. int decodedSessionKeyLen = 0;
  136. char* decodedSessionKey = MyBase64::Hex2Str(timeSynRet.data.sessionKey.c_str(), decodedSessionKeyLen);
  137. DWORD rc = m_fsm->HandleTimeSyn(timeSynRet.data.timeDiff, (BYTE*)decodedSessionKey);
  138. delete decodedSessionKey;
  139. if (rc == Error_Succeed) {
  140. auto pEvent = new FSMEvent(CAccessAuthFSM::Event_EndSyncTime);
  141. m_fsm->PostEventFIFO(pEvent);
  142. }
  143. else {
  144. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("TimeSynTask HandleTimeSyn error = %08X", rc);
  145. }
  146. }
  147. else {
  148. m_fsm->AuthLogWarn(timeSynRet, timeSynReq.m_url, "获取会话密钥");
  149. FSMEvent* pEvent = new FSMEvent(CAccessAuthFSM::Event_ReqTokenCancel);
  150. pEvent->param1 = AccessAuthorization_UserErrorCode_ACS_FAIL;
  151. m_fsm->PostEventFIFO(pEvent);
  152. }
  153. client->Destory();
  154. #else
  155. struct TimeSynReqStructJson
  156. {
  157. std::string terminalNo;
  158. int curTime;
  159. JSONCONVERT2OBJECT_MEMEBER_REGISTER(terminalNo, curTime)
  160. } timeSyncReq;
  161. struct TimeSyncAnsStructJson
  162. {
  163. int timeDiff;
  164. int authVersion;
  165. std::string sessionKey;
  166. std::string reserved;
  167. JSONCONVERT2OBJECT_MEMEBER_REGISTER(timeDiff, authVersion, sessionKey, reserved)
  168. }timeSyncAns;
  169. timeSyncReq.terminalNo = si.strTerminalID.GetData();
  170. timeSyncReq.curTime = CSmallDateTime::GetNow().GetTime64();
  171. HttpClientResponseResult result;
  172. HttpClientRequestConfig config(HttpRequestMethod::POST, m_fsm->GetmAccessAuthHost().GetData(), &SpGetToken);
  173. config.SetChildUri("/api/v3/sessionkey");
  174. SP::Module::Restful::FulfillRequestJsonBody(&config, timeSyncReq);
  175. RestfulClient client = RestfulClient::getInstance();
  176. std::string test;
  177. test = config.GetRequestUri();
  178. config.PreDo();
  179. client.Do(&config, &result);
  180. if (result.ResponseOK()) {
  181. SP::Module::Restful::CommResponseJson responseStatus;
  182. SP::Module::Restful::GetStatusFromDebranchResponse(result.content, responseStatus);
  183. if (!responseStatus.IsOperatedOK()) {
  184. m_fsm->AuthLogWarn(result, config.GetRequestUri(), "获取会话密钥");
  185. return;
  186. }
  187. SP::Module::Restful::ExtractDataFromDebranchResponse(result.content, timeSyncAns);
  188. auto printFunc = [&timeSyncAns]() {
  189. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("timeDiff: %d", timeSyncAns.timeDiff);
  190. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("authVersion: %d", timeSyncAns.authVersion);
  191. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("sessionKey: %s", timeSyncAns.sessionKey.c_str());
  192. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("reserved: %s", timeSyncAns.reserved.c_str());
  193. };
  194. printFunc();
  195. int decodedSessionKeyLen = 0;
  196. char* decodedSessionKey = Hex2Str(timeSyncAns.sessionKey.c_str(), decodedSessionKeyLen);
  197. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("decodedSessionKey=%s,%d", decodedSessionKey, decodedSessionKeyLen);
  198. DWORD rc = Error_InvalidState;
  199. rc = m_fsm->HandleTimeSyn(timeSyncAns.timeDiff, (BYTE*)decodedSessionKey);
  200. delete decodedSessionKey;
  201. if (rc == Error_Succeed) {
  202. auto pEvent = new FSMEvent(CAccessAuthFSM::Event_EndSyncTime);
  203. m_fsm->PostEventFIFO(pEvent);
  204. }
  205. else {
  206. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("TimeSynTask HandleTimeSyn error = %08X", rc);
  207. }
  208. }
  209. else {
  210. std::string errDetail(result.WhatError());
  211. if (errDetail.find("Error resolving address") != std::string::npos) {
  212. std::string tmpDetail = SP::Module::Net::GetWWWInfoThroughDig(config.GetBaseUri());
  213. if (!tmpDetail.empty()) {
  214. SP::Utility::replaceInPlace(tmpDetail, "\n", "$$");
  215. const int len = tmpDetail.length();
  216. int pos = 0, times = 0;
  217. const int each_size = 450;
  218. std::vector<std::string> contents;
  219. while (pos < len) {
  220. const std::string elem = tmpDetail.substr(pos, (len - pos) > each_size ? each_size : std::string::npos);
  221. pos = (++times) * each_size;
  222. contents.push_back(elem);
  223. LogWarn(Severity_Low, Error_Debug, ERROR_ACCESSAUTH_ACS_DIGINFO,
  224. CSimpleStringA::Format("[%d]%s", times, elem.c_str()));
  225. }
  226. }
  227. else {
  228. LogWarn(Severity_Low, Error_Debug, ERROR_ACCESSAUTH_ACS_DIGINFO, errDetail.c_str());
  229. }
  230. }
  231. m_fsm->AuthLogWarn(result, config.GetRequestUri(), "获取会话密钥");
  232. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("TimeSynTask Connect Failed.");
  233. FSMEvent* pEvent = new FSMEvent(CAccessAuthFSM::Event_ReqTokenCancel);
  234. pEvent->param1 = AccessAuthorization_UserErrorCode_ACS_FAIL;
  235. m_fsm->PostEventFIFO(pEvent);
  236. }
  237. #endif // RVC_OS_WIN
  238. }
  239. };
  240. struct UpdateWKTask : ITaskSp
  241. {
  242. CAccessAuthFSM* m_fsm;
  243. CAccessAuthEntity* m_entity;
  244. UpdateWKTask(CAccessAuthFSM* fsm, CAccessAuthEntity* entity) :m_fsm(fsm), m_entity(entity) {}
  245. void Process()
  246. {
  247. if (m_fsm->GetmAccessAuthHost().IsNullOrEmpty())
  248. {
  249. LogWarn(Severity_Middle, Error_Unexpect, AccessAuthorization_UserErrorCode_AccessAuth_NULL, "准入Url为空");
  250. return;
  251. }
  252. CSystemStaticInfo si;
  253. m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(si);
  254. #ifdef RVC_OS_WIN
  255. IHttpFunc* client;
  256. client = create_http(m_fsm->HttpsLogCallBack);
  257. CAccessAuthUpdateWKReq updateWKReq;
  258. updateWKReq.terminalNo = si.strTerminalID.GetData();
  259. auto tmkpair = m_entity->GenerateTmkToKMC();//first是加密的,seconde是没加密的
  260. updateWKReq.encRandom = tmkpair.first;
  261. PinPadService_ClientBase* pPinPad = new PinPadService_ClientBase(this->m_entity);
  262. auto errRc = pPinPad->Connect();
  263. if (errRc == Error_Succeed)
  264. {
  265. PinPadService_GetCheckCode_Req req = {};
  266. PinPadService_GetCheckCode_Ans ans = {};
  267. req.mSN.Init(1);
  268. req.wSN.Init(1);
  269. req.mSN[0] = 1;
  270. req.wSN[0] = 0;
  271. errRc = (*pPinPad)(EntityResource::getLink().upgradeLink())->GetCheckCode(req, ans, 10000);
  272. if (errRc == Error_Succeed)
  273. {
  274. updateWKReq.tpkKeyCheck = ans.checkcode[0].GetData();
  275. updateWKReq.keyIndex = ans.index[0].GetData();
  276. }
  277. else
  278. {
  279. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Get keyChek && keyIndex failed.");
  280. }
  281. pPinPad->GetFunction()->CloseSession();
  282. }
  283. else
  284. {
  285. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("connect to pinpad failed.error code:%d", errRc);
  286. }
  287. CAccessAuthUpdateWKRet updateWKRet;
  288. updateWKReq.m_url = m_fsm->GetmAccessAuthHost();
  289. updateWKReq.m_url += "/api/v5/wkupdate";
  290. long beg = GetTickCount();
  291. bool ret = client->Post(updateWKReq, updateWKRet);
  292. long end = GetTickCount();
  293. if (ret) {
  294. if (updateWKRet.m_userCode.compare(ACS_SUCCESS)) {
  295. m_fsm->doWarnMsg(ERR_ACCESSAUTH_UPDATE_WK,
  296. GetOutPutStr("%s%s%s%s", "UpdateWKTask", updateWKRet.m_userCode.c_str(), "message", updateWKRet.m_errMsg.c_str()).c_str());
  297. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)
  298. (GetOutPutStr("%s%s%s%s", "UpdateWKTask", updateWKRet.m_userCode.c_str(), "message", updateWKRet.m_errMsg.c_str()).c_str());
  299. if (client) client->Destory();
  300. return;
  301. }
  302. ErrorCodeEnum eLoadErr = m_entity->LoadKeysToPinPadACS(tmkpair.second, updateWKRet.tpk,
  303. updateWKRet.edk, updateWKRet.keyIndex);
  304. if (eLoadErr == Error_Succeed) {
  305. if (client) client->Destory();
  306. return;
  307. }
  308. else {
  309. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("UpdateWKTask 密钥加载失败,请检查密码键盘连接. error = %08X", eLoadErr);
  310. }
  311. }
  312. else {
  313. CSimpleStringA acsResoultCode = "RTA520F";
  314. int acsErrCode = ERROR_ACCESSAUTH_CONNECT_ACS_x;
  315. if (updateWKRet.m_sysCode == 6)
  316. {
  317. acsResoultCode = "RTA520D";
  318. acsErrCode = ERROR_ACCESSAUTH_CONNECT_ACS_6;
  319. }
  320. else if (updateWKRet.m_sysCode == 28)
  321. {
  322. acsResoultCode = "RTA520E";
  323. acsErrCode = ERROR_ACCESSAUTH_CONNECT_ACS_28;
  324. }
  325. m_fsm->doWarnMsg(acsErrCode,
  326. GetOutPutStr("%s%d", "连接总行ACS准入服务失败(StageReport).", updateWKRet.m_sysCode).c_str());
  327. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setBeginTime(beg).setEndTime(end).
  328. setResultCode(acsResoultCode.GetData()).
  329. setResultMsg(updateWKRet.m_errMsg.c_str())
  330. (GetOutPutStr("%s%d", "连接总行ACS准入服务失败(StageReport).", updateWKRet.m_sysCode).c_str());
  331. }
  332. client->Destory();
  333. #else
  334. struct UpdateWKReq
  335. {
  336. std::string terminalNo;
  337. std::string encRandom;
  338. string tpkKeyCheck; //tpk密钥校验值
  339. string edkKeyCheck; //edk密钥校验值
  340. string keyIndex; //密钥序号
  341. JSONCONVERT2OBJECT_MEMEBER_REGISTER(terminalNo, encRandom, tpkKeyCheck, edkKeyCheck, keyIndex)
  342. } updateWKReq;
  343. struct UpdateWKAns
  344. {
  345. string tmk;
  346. string tpk;
  347. string edk;
  348. string tpkKeyCheck; //密钥校验值
  349. string edkKeyCheck; //edk密钥校验值
  350. string keyIndex; //密钥序号
  351. JSONCONVERT2OBJECT_MEMEBER_REGISTER(tmk, tpk, edk, tpkKeyCheck, edkKeyCheck, keyIndex)
  352. } updateWKAns;
  353. updateWKReq.terminalNo = si.strTerminalID.GetData();
  354. auto tmkpair = m_entity->GenerateTmkToKMC();//first是加密的,seconde是没加密的
  355. updateWKReq.encRandom = tmkpair.first;
  356. PinPadService_ClientBase* pPinPad = new PinPadService_ClientBase(this->m_entity);
  357. auto errRc = pPinPad->Connect();
  358. if (errRc == Error_Succeed)
  359. {
  360. PinPadService_GetCheckCode_Req req = {};
  361. PinPadService_GetCheckCode_Ans ans = {};
  362. req.mSN.Init(1);
  363. req.wSN.Init(1);
  364. req.mSN[0] = 1;
  365. req.wSN[0] = 0;
  366. errRc = (*pPinPad)(EntityResource::getLink().upgradeLink())->GetCheckCode(req, ans, 10000);
  367. if (errRc == Error_Succeed)
  368. {
  369. updateWKReq.tpkKeyCheck = ans.checkcode[0].GetData();
  370. updateWKReq.keyIndex = ans.index[0].GetData();
  371. }
  372. else
  373. {
  374. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Get keyChek && keyIndex failed.");
  375. }
  376. pPinPad->GetFunction()->CloseSession();
  377. }
  378. else
  379. {
  380. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("connect to pinpad failed.error code:%d", errRc);
  381. }
  382. HttpClientResponseResult result;
  383. HttpClientRequestConfig config(HttpRequestMethod::POST, m_fsm->GetmAccessAuthHost().GetData(), &SpGetToken);
  384. config.SetChildUri("/api/v5/wkupdate");
  385. SP::Module::Restful::FulfillRequestJsonBody(&config, updateWKReq);
  386. std::string test;
  387. test = config.GetRequestUri();
  388. Dbg("请求地址:%s.", test.c_str());
  389. RestfulClient client = RestfulClient::getInstance();
  390. config.PreDo();
  391. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to Post with new restful....");
  392. client.Do(&config, &result);
  393. if (result.ResponseOK()) {
  394. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("UpdateWKTask Connect With Restful Success.");
  395. SP::Module::Restful::CommResponseJson responseStatus;
  396. SP::Module::Restful::GetStatusFromDebranchResponse(result.content, responseStatus);
  397. if (!responseStatus.IsOperatedOK()) {
  398. m_fsm->doWarnMsg(ERR_ACCESSAUTH_UPDATE_WK,
  399. GetOutPutStr("%s%s%s%s", "UpdateWKTask", responseStatus.errorCode.c_str(), "message", responseStatus.errorMsg.c_str()).c_str(), true);
  400. return;
  401. }
  402. SP::Module::Restful::ExtractDataFromDebranchResponse(result.content, updateWKAns);
  403. DWORD rc = m_entity->LoadKeysToPinPadACS(tmkpair.second, updateWKAns.tpk, updateWKAns.edk, updateWKAns.keyIndex);
  404. if (rc == Error_Succeed) {
  405. return;
  406. }
  407. else {
  408. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("UpdateWKTask 密钥加载失败,请检查密码键盘连接。 error = %08X", rc);
  409. }
  410. }
  411. else {
  412. m_fsm->doWarnMsg(ERROR_ACCESSAUTH_CONNECT_ACS,
  413. GetOutPutStr("%s%s", "连接总行ACS准入服务失败(UpdateWKTask).", result.WhatError().c_str()).c_str(), true);
  414. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA520G")("UpdateWKTask Connect Failed.");
  415. }
  416. UpdateWKRetError:
  417. FSMEvent* pEvent = new FSMEvent(CAccessAuthFSM::Event_ReqTokenCancel);
  418. m_fsm->PostEventFIFO(pEvent);
  419. #endif // RVC_OS_WIN
  420. }
  421. };
  422. struct GetTokenTask : ITaskSp
  423. {
  424. CAccessAuthFSM* m_fsm;
  425. CAccessAuthEntity* m_entity;
  426. GetTokenTask(CAccessAuthFSM* fsm, CAccessAuthEntity* entity) :m_fsm(fsm), m_entity(entity) {}
  427. void Process()
  428. {
  429. if (m_fsm->GetmAccessAuthHost().IsNullOrEmpty()) {
  430. LogWarn(Severity_Middle, Error_Unexpect, AccessAuthorization_UserErrorCode_AccessAuth_NULL, "准入Url为空");
  431. FSMEvent* pEvent = new FSMEvent(CAccessAuthFSM::Event_ReqTokenCancel);
  432. pEvent->param1 = AccessAuthorization_UserErrorCode_AccessAuth_NULL;
  433. m_fsm->PostEventFIFO(pEvent);
  434. CSimpleStringA strMsg(true);
  435. strMsg = CSimpleStringA::Format("准入服务地址为空,请下载集中配置或尝试重启应用");
  436. m_fsm->doWarnMsg(AccessAuthorization_UserErrorCode_AccessAuth_NULL, strMsg.GetData(), true);
  437. return;
  438. }
  439. CSystemStaticInfo si;
  440. m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(si);
  441. #ifdef RVC_OS_WIN
  442. IHttpFunc* client;
  443. client = create_http(m_fsm->HttpsLogCallBack);
  444. CAccessAuthGetTokenReq getTokenReq;
  445. if (m_fsm->GetTokenReq(&getTokenReq) != Error_Succeed) {
  446. if (client) client->Destory();
  447. return;
  448. }
  449. CAccessAuthGetTokenRet getTokenRet;
  450. getTokenReq.m_url = m_fsm->GetmAccessAuthHost();
  451. getTokenReq.m_url += "/api/v3/access"; //v3新接口,返回title,content
  452. long beg = GetTickCount();
  453. bool ret = client->Post(getTokenReq, getTokenRet);
  454. long end = GetTickCount();
  455. if (ret) {
  456. if (getTokenRet.m_userCode.compare(ACS_SUCCESS)) {
  457. m_fsm->AuthLogWarn(getTokenRet, getTokenReq.m_url, "获取准入token");
  458. if (client) client->Destory();
  459. return;
  460. }
  461. if (getTokenRet.data.flag != 0 /*&& flag?*/) //判断是否需要告警,通过标志位,标志位待确定
  462. {
  463. CSimpleStringA tmsg = CSimpleStringA::Format("{\"errcode\": \"%s\", \"message\": %s}",
  464. getTokenRet.m_userCode.c_str(), getTokenRet.data.warnMessage.c_str());
  465. m_fsm->GetEntityBase()->GetFunction()->SetSysVar("AuthErrMsg", tmsg.GetData(), true);
  466. }
  467. else
  468. {
  469. m_fsm->GetEntityBase()->GetFunction()->SetSysVar("AuthErrMsg", "", true);
  470. }
  471. DWORD rc = m_fsm->HandleGetToken((BYTE*)getTokenRet.data.sharedKey.enToken.c_str(), (BYTE*)getTokenRet.data.sharedKey.sharedSK.c_str(),
  472. (BYTE*)getTokenRet.data.accessToken.enToken.c_str(), (BYTE*)getTokenRet.data.accessToken.retHash.c_str());
  473. if (rc == Error_Succeed) {
  474. FSMEvent* pEvent = new FSMEvent(CAccessAuthFSM::Event_ReqTokenSucc);
  475. m_fsm->PostEventFIFO(pEvent);
  476. if (client) client->Destory();
  477. return;
  478. }
  479. else {
  480. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetTokenTask HandleGetToken error = %08X", rc);
  481. }
  482. }
  483. else {
  484. m_fsm->AuthLogWarn(getTokenRet, getTokenReq.m_url, "获取准入token");
  485. }
  486. FSMEvent* pEvent = new FSMEvent(CAccessAuthFSM::Event_ReqTokenFail);
  487. m_fsm->PostEventFIFO(pEvent);
  488. if (client) client->Destory();
  489. #else
  490. CAutoArray<CSimpleStringA> devNames;
  491. DWORD rc = m_fsm->GetAllDevices(m_entity, devNames);
  492. ///**TODO(Gifur@3/11/2022): 诗友确定是否还需要连分行!!!!! */
  493. CAccessAuthGetTokenReq getTokenReq;
  494. if (m_fsm->GetTokenReq(&getTokenReq) != Error_Succeed)
  495. {
  496. FSMEvent* pEvent = new FSMEvent(CAccessAuthFSM::Event_ReqTokenFail);
  497. m_fsm->PostEventFIFO(pEvent);
  498. return;
  499. }
  500. struct GetTokenReq
  501. {
  502. string installVersion;//终端版本(新加字段)
  503. string terminalCharacter;
  504. string terminalNo;
  505. string sessionTempPubKey;
  506. string encTerminalInfo;
  507. string publicKeySM;
  508. string pinPadID;
  509. string existPinPad;
  510. JSONCONVERT2OBJECT_MEMEBER_REGISTER(installVersion, terminalCharacter, terminalNo,
  511. sessionTempPubKey, encTerminalInfo, publicKeySM, pinPadID, existPinPad)
  512. } getTokenReqJson;
  513. struct AccessTokenJson
  514. {
  515. string enToken;
  516. string retHash;
  517. JSONCONVERT2OBJECT_MEMEBER_REGISTER(enToken, retHash)
  518. };
  519. struct SharedKeyJson
  520. {
  521. string enToken;
  522. string sharedSK;
  523. string retHash;
  524. JSONCONVERT2OBJECT_MEMEBER_REGISTER(enToken, sharedSK, retHash)
  525. };
  526. struct GetTokenAns
  527. {
  528. AccessTokenJson accessToken;
  529. SharedKeyJson sharedKey;
  530. bool flag;
  531. string warnMessage;
  532. JSONCONVERT2OBJECT_MEMEBER_REGISTER(accessToken, sharedKey, flag, warnMessage)
  533. } getTokenAns;
  534. HttpClientResponseResult result;
  535. HttpClientRequestConfig config(HttpRequestMethod::POST, m_fsm->GetmAccessAuthHost().GetData(), &SpGetToken);
  536. config.SetChildUri("/api/v3/access");
  537. getTokenReqJson.installVersion = getTokenReq.installVersion;
  538. getTokenReqJson.terminalCharacter = getTokenReq.terminalCharacter;
  539. getTokenReqJson.terminalNo = getTokenReq.terminalNo;
  540. getTokenReqJson.sessionTempPubKey = getTokenReq.sessionTempPubKey;
  541. getTokenReqJson.encTerminalInfo = getTokenReq.encTerminalInfo;
  542. getTokenReqJson.publicKeySM = getTokenReq.publicKeySM;
  543. getTokenReqJson.pinPadID = getTokenReq.pinPadID;
  544. getTokenReqJson.existPinPad = getTokenReq.existPinPad;
  545. SP::Module::Restful::FulfillRequestJsonBody(&config, getTokenReqJson);
  546. std::string test;
  547. test = config.GetRequestUri();
  548. RestfulClient client = RestfulClient::getInstance();
  549. config.PreDo();
  550. client.Do(&config, &result);
  551. if (result.ResponseOK()) {
  552. SP::Module::Restful::CommResponseJson responseStatus;
  553. SP::Module::Restful::GetStatusFromDebranchResponse(result.content, responseStatus);
  554. if (!responseStatus.IsOperatedOK()) {
  555. m_fsm->AuthLogWarn(result, config.GetRequestUri(), "获取准入token");
  556. return;
  557. }
  558. SP::Module::Restful::ExtractDataFromDebranchResponse(result.content, getTokenAns);
  559. if (getTokenAns.flag != false/*&& flag?*/) //判断是否需要告警,通过标志位,标志位待确定
  560. {
  561. CSimpleStringA tmsg = CSimpleStringA::Format("{\"errcode\": \"%s\", \"message\": %s}",
  562. responseStatus.errorCode.c_str(), getTokenAns.warnMessage.c_str());
  563. m_fsm->GetEntityBase()->GetFunction()->SetSysVar("AuthErrMsg", tmsg.GetData(), true);
  564. }
  565. else
  566. {
  567. m_fsm->GetEntityBase()->GetFunction()->SetSysVar("AuthErrMsg", "", true);
  568. }
  569. DWORD rc = m_fsm->HandleGetToken((BYTE*)getTokenAns.sharedKey.enToken.c_str(), (BYTE*)getTokenAns.sharedKey.sharedSK.c_str(),
  570. (BYTE*)getTokenAns.accessToken.enToken.c_str(), (BYTE*)getTokenAns.accessToken.retHash.c_str());
  571. if (rc == Error_Succeed) {
  572. FSMEvent* pEvent = new FSMEvent(CAccessAuthFSM::Event_ReqTokenSucc);
  573. m_fsm->PostEventFIFO(pEvent);
  574. return;
  575. }
  576. else {
  577. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetTokenTask HandleGetToken error = %08X", rc);
  578. }
  579. }
  580. else {
  581. std::string errDetail(result.WhatError());
  582. if (errDetail.find("Error resolving address") != std::string::npos) {
  583. std::string tmpDetail = SP::Module::Net::GetWWWInfoThroughDig(config.GetBaseUri());
  584. if (!tmpDetail.empty()) {
  585. SP::Utility::replaceInPlace(tmpDetail, "\n", "$$");
  586. const int len = tmpDetail.length();
  587. int pos = 0, times = 0;
  588. const int each_size = 450;
  589. std::vector<std::string> contents;
  590. while (pos < len) {
  591. const std::string elem = tmpDetail.substr(pos, (len - pos) > each_size ? each_size : std::string::npos);
  592. pos = (++times) * each_size;
  593. contents.push_back(elem);
  594. LogWarn(Severity_Low, Error_Debug, ERROR_ACCESSAUTH_ACS_DIGINFO,
  595. CSimpleStringA::Format("[%d]%s", times, elem.c_str()));
  596. }
  597. }
  598. else {
  599. LogWarn(Severity_Low, Error_Debug, ERROR_ACCESSAUTH_ACS_DIGINFO, errDetail.c_str());
  600. }
  601. }
  602. m_fsm->AuthLogWarn(result, config.GetRequestUri(), "获取准入token");
  603. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetTokenTask Connect Failed.");
  604. }
  605. FSMEvent* pEvent = new FSMEvent(CAccessAuthFSM::Event_ReqTokenFail);
  606. m_fsm->PostEventFIFO(pEvent);
  607. #endif // RVC_OS_WIN
  608. }
  609. };
  610. struct InitDeviceTask :public ITaskSp
  611. {
  612. CAccessAuthFSM* m_fsm;
  613. InitDeviceReq m_req;
  614. InitDeviceTask(CAccessAuthFSM* fsm, InitDeviceReq req) :m_fsm(fsm), m_req(req) {}
  615. void Process()
  616. {
  617. #ifdef RVC_OS_WIN
  618. if (m_fsm->GetmInitDeviceHost().IsNullOrEmpty()) {
  619. LogWarn(Severity_Middle, Error_Unexpect, AccessAuthorization_UserErrorCode_InitDev_NULL, "加密通道Url为空");
  620. return;
  621. }
  622. m_fsm->SetDevPubKey("");
  623. IHttpFunc* client;
  624. client = create_http(m_fsm->HttpsLogCallBack);
  625. CAccessAuthInitDeviceReq initDeviceReq;
  626. initDeviceReq.cr1 = m_req.CR1;
  627. initDeviceReq.cr3 = m_req.CR3;
  628. initDeviceReq.cDevPubKey = m_req.CDevPubKey;
  629. initDeviceReq.r2 = m_req.R2;
  630. initDeviceReq.vendor = m_req.Verdor;
  631. CSystemStaticInfo si;
  632. m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(si);
  633. initDeviceReq.terminalNo = si.strTerminalID;
  634. CAccessAuthInitDeviceRet initDeviceRet;
  635. initDeviceReq.m_url = m_fsm->GetmInitDeviceHost();
  636. initDeviceReq.m_url = initDeviceReq.m_url + "/api/v3/initdevice";
  637. long beg = GetTickCount();
  638. bool ret = client->Post(initDeviceReq, initDeviceRet);
  639. long end = GetTickCount();
  640. if (ret) {
  641. if (initDeviceRet.m_userCode.compare(ACS_SUCCESS)) {
  642. m_fsm->AuthLogWarn(initDeviceRet, initDeviceReq.m_url, "初始设备", false);
  643. }
  644. else {
  645. if (m_fsm->m_ctxInitDev != NULL) {
  646. m_fsm->m_ctxInitDev->Ans.R1 = initDeviceRet.r1.c_str();
  647. m_fsm->m_ctxInitDev->Ans.EncR2 = initDeviceRet.cr2.c_str();
  648. m_fsm->m_ctxInitDev->Ans.R3 = initDeviceRet.r3.c_str();
  649. m_fsm->SetDevPubKey(initDeviceRet.devPubKey.c_str());
  650. m_fsm->m_ctxInitDev->Answer(Error_Succeed);
  651. m_fsm->m_ctxInitDev.Clear();
  652. }
  653. }
  654. }
  655. else {
  656. m_fsm->AuthLogWarn(initDeviceRet, initDeviceReq.m_url, "初始设备", false);
  657. }
  658. if (client) client->Destory();
  659. #else
  660. return;
  661. #endif // RVC_OS_WIN
  662. }
  663. };
  664. void CAccessAuthFSM::doWarnMsg(int errReason, std::string errMsg, bool bNeedEvent, string varMsg)
  665. {
  666. #ifdef RVC_OS_WIN
  667. auto fullErrMsg = varMsg.length() > 0 ? varMsg : errMsg;
  668. #else
  669. const std::string errMsgStr = SP::Utility::GBK2UTF8(errMsg);
  670. const std::string varMsgStr = SP::Utility::GBK2UTF8(varMsg);
  671. auto fullErrMsg = varMsgStr.length() > 0 ? varMsgStr : errMsgStr;
  672. #endif // RVC_OS_WIN
  673. if (bNeedEvent)
  674. {
  675. #ifdef RVC_OS_WIN
  676. std::string alaramMSg(fullErrMsg);
  677. if (alaramMSg.length() >= 255) {
  678. std::string tmp = alaramMSg.substr(0, 252);
  679. tmp += "...";
  680. alaramMSg = tmp;
  681. }
  682. const ErrorCodeEnum ec = m_pEntity->GetFunction()->SetSysVar("AuthErrMsg", alaramMSg.c_str(), true);
  683. #else
  684. const ErrorCodeEnum ec = m_pEntity->GetFunction()->SetSysVar("AuthErrMsg", fullErrMsg.c_str(), true);
  685. #endif // RVC_OS_WIN
  686. if (ec != Error_Succeed) {
  687. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Update SysVar failed: 0x%X", ec);
  688. }
  689. if (errReason == ERR_ACCESSAUTH_SERVICE_FAILED)
  690. {
  691. m_pEntity->GetFunction()->SetSysVar("AuthErrMsg", errMsg.c_str(), true);
  692. LogEvent(Severity_Middle, ERR_ACCESSAUTH_SERVICE_FAILED, errMsg.c_str());
  693. }
  694. else
  695. {
  696. LogEvent(Severity_Middle, checkErrType(errReason), errMsg.c_str());
  697. }
  698. }
  699. LogWarn(Severity_Middle, Error_Unexpect, errReason, errMsg.c_str());
  700. }
  701. void CAccessAuthFSM::s1_on_entry()
  702. {
  703. CSimpleStringA strEntryStatus = GetEntryPermitSysVar();
  704. if (strEntryStatus.Compare("L") == 0) {
  705. PostEventFIFO(new FSMEvent(Event_AccessAuthSucc));
  706. }
  707. else {
  708. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("EntryStatus: %s", strEntryStatus.GetData());
  709. SetEntryPermitSysVar("I");
  710. }
  711. GetEntityBase()->GetFunction()->SetSysVar("AccessHavePath", "Y");//oiltmp to delete
  712. }
  713. void CAccessAuthFSM::s1_on_exit()
  714. {
  715. }
  716. unsigned int CAccessAuthFSM::s1_on_event(FSMEvent* pEvent)
  717. {
  718. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("s1_on_event: %d", pEvent->iEvt);
  719. return 0;
  720. }
  721. void CAccessAuthFSM::s2_on_entry()
  722. {
  723. LOG_FUNCTION();
  724. m_finishAccess = 0;
  725. SetEntryPermitSysVar("C");
  726. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("开始第%d次准入", m_nAccessFailedCount);
  727. CSmartPointer<TimeSynTask> timeSynTask = new TimeSynTask(this);
  728. GetEntityBase()->GetFunction()->PostThreadPoolTask(timeSynTask.GetRawPointer());
  729. }
  730. void CAccessAuthFSM::s2_on_exit()
  731. {
  732. }
  733. unsigned int CAccessAuthFSM::s2_on_event(FSMEvent* pEvent)
  734. {
  735. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s2 receives event id: %d", pEvent->iEvt);
  736. if (pEvent->iEvt == Event_EndSyncTime)
  737. {
  738. pEvent->SetHandled();
  739. CSmartPointer<GetTokenTask> getTokenTask = new GetTokenTask(this, (CAccessAuthEntity*)m_pEntity);
  740. GetEntityBase()->GetFunction()->PostThreadPoolTask(getTokenTask.GetRawPointer());
  741. return 0;
  742. }
  743. else if (pEvent->iEvt == Event_ReqTokenCancel)
  744. { //这里貌似会触发健康发起重试
  745. auto pEntity = (CAccessAuthEntity*)m_pEntity;
  746. if (pEvent->param1 == AccessAuthorization_UserErrorCode_AccessAuth_NULL)
  747. {
  748. CSimpleStringA strMsg = CSimpleStringA::Format("准入Url为空");
  749. pEntity->SetAuthErrMsg(strMsg);
  750. }
  751. else if (pEvent->param1 == AccessAuthorization_UserErrorCode_ACS_FAIL)
  752. {
  753. pEntity->SetAuthErrMsg("访问总行ACS失败");
  754. }
  755. else
  756. {
  757. CSimpleStringA strErrMsg = CSimpleStringA::Format("准入超时(%d)", m_finishAccess);
  758. pEntity->GetFunction()->ShowFatalError(strErrMsg);
  759. }
  760. SetEntryPermitSysVar("A");
  761. m_nAccessFailedCount++;
  762. pEvent->SetHandled();
  763. }
  764. else if (pEvent->iEvt == Event_ReqTokenFail)
  765. { //而这里不会触发健康发起重试
  766. SetEntryPermitSysVar("F");
  767. pEvent->SetHandled();
  768. auto pEntity = (CAccessAuthEntity*)m_pEntity;
  769. CSimpleStringA strErrMsg = CSimpleStringA::Format("%s", (const char*)pEntity->GetAuthErrMsg());
  770. // 发送准入失败事件,暂时不发送事件进去关门界面,原因关门界面显示中文乱码
  771. doWarnMsg(EVENT_ACCESSAUTH_FAILED, strErrMsg.GetData(), true);
  772. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA520B")("准入失败");
  773. pEntity->GetFunction()->ShowFatalError(strErrMsg);
  774. m_nAccessFailedCount = 0;
  775. }
  776. else if (pEvent->iEvt == Event_ReqTokenSucc)
  777. {
  778. SetEntryPermitSysVar("L");
  779. LogEvent(Severity_Middle, EVENT_ACCESSAUTH_SUCCEED, "终端准入成功");
  780. m_pEntity->GetFunction()->ShowStartupInfo("准入成功");
  781. m_nAccessFailedCount = 0;
  782. pEvent->SetHandled();
  783. PostEventFIFO(new FSMEvent(Event_AccessAuthSucc));
  784. }
  785. return 0;
  786. }
  787. void CAccessAuthFSM::s3_on_entry()
  788. {
  789. LOG_FUNCTION();
  790. CSystemStaticInfo si;
  791. m_pEntity->GetFunction()->GetSystemStaticInfo(si);
  792. if (si.InstallVersion.ToString().IsNullOrEmpty()) {
  793. LogWarn(Severity_Low, Error_Debug, AccessAuthorization_UserErrorCode_Start, "终端准入成功");
  794. }
  795. else {
  796. LogWarn(Severity_Low, Error_Debug, AccessAuthorization_UserErrorCode_Start, CSimpleStringA::Format("终端准入成功,版本: %s", si.InstallVersion.ToString().GetData()));
  797. }
  798. }
  799. unsigned int CAccessAuthFSM::s3_on_event(FSMEvent* event)
  800. {
  801. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s3 receives event id: %d", event->iEvt);
  802. return 0;
  803. }
  804. CSimpleStringA CAccessAuthFSM::GetEntryPermitSysVar()
  805. {
  806. CSimpleStringA strValue(true);
  807. CSmartPointer<IEntityFunction> spFunction = m_pEntity->GetFunction();
  808. spFunction->GetSysVar("EntryPermit", strValue);
  809. return strValue;
  810. }
  811. ErrorCodeEnum CAccessAuthFSM::SetEntryPermitSysVar(const CSimpleStringA& newVal)
  812. {
  813. CSmartPointer<IEntityFunction> spFunction = m_pEntity->GetFunction();
  814. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Set EntryPermit with %s", newVal.GetData());
  815. return spFunction->SetSysVar("EntryPermit", (const char*)newVal);
  816. }
  817. ErrorCodeEnum CAccessAuthFSM::LoadCenterConfig()
  818. {
  819. CSmartPointer<IEntityFunction> spFunction = m_pEntity->GetFunction();
  820. CSmartPointer<IConfigInfo> spConfig;
  821. ErrorCodeEnum Error = spFunction->OpenConfig(Config_CenterSetting, spConfig);
  822. if (Error_Succeed == Error)
  823. {
  824. spConfig->ReadConfigValue("AccessAuthorization", "HostUrl", m_accessAuthHost);
  825. spConfig->ReadConfigValue("AccessAuthorization", "HostInitDeviceUrl", m_initDeviceHost);
  826. }
  827. return Error;
  828. }
  829. ErrorCodeEnum CAccessAuthFSM::GetIntFromCS(const char* pcSection, const char* pcKey, int& retInt)
  830. {
  831. CSmartPointer<IEntityFunction> spFunction = m_pEntity->GetFunction();
  832. CSmartPointer<IConfigInfo> spConfig;
  833. ErrorCodeEnum Error = spFunction->OpenConfig(Config_CenterSetting, spConfig);
  834. if (Error_Succeed == Error)
  835. {
  836. Error = spConfig->ReadConfigValueInt(pcSection, pcKey, retInt);
  837. if (Error_Succeed != Error)
  838. {
  839. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("get retInt from CenterSetting.ini failed");
  840. }
  841. }
  842. return Error;
  843. }
  844. ErrorCodeEnum CAccessAuthFSM::GetStrFromCS(const char* pcSection, const char* pcKey, CSimpleStringA& retStr)
  845. {
  846. retStr = "";
  847. CSmartPointer<IEntityFunction> spFunction = m_pEntity->GetFunction();
  848. CSmartPointer<IConfigInfo> spConfig;
  849. ErrorCodeEnum Error = spFunction->OpenConfig(Config_CenterSetting, spConfig);
  850. if (Error_Succeed == Error)
  851. {
  852. Error = spConfig->ReadConfigValue(pcSection, pcKey, retStr);
  853. if (Error_Succeed != Error)
  854. {
  855. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI("GetStrFromCS")
  856. ("get retStr from CenterSetting.ini failed");
  857. }
  858. }
  859. return Error;
  860. }
  861. bool CAccessAuthFSM::DecryptWithSessionKey(BYTE* encText, int encTextLen, BYTE* decTest, int& decTestLen)
  862. {
  863. BYTE key[16] = { 0 };
  864. memcpy(key, ((CAccessAuthEntity*)m_pEntity)->m_AuthSessionKey, 16);
  865. #ifdef RVC_OS_WIN
  866. char* keyTmp = MyBase64::Str2Hex((char*)key, 16);
  867. #else
  868. char* keyTmp = Str2Hex((char*)key, 16);
  869. #endif // RVC_OS_WIN
  870. delete keyTmp;
  871. if (!DecWithSM4_ECB(key, encText, encTextLen, decTest, &decTestLen)) {
  872. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("DecryptWithSessionKey ECB error.");
  873. return false;
  874. }
  875. #ifdef RVC_OS_WIN
  876. keyTmp = MyBase64::Str2Hex((char*)decTest, decTestLen);
  877. #else
  878. keyTmp = Str2Hex((char*)decTest, decTestLen);
  879. #endif // RVC_OS_WIN
  880. delete keyTmp;
  881. return true;
  882. }
  883. int CAccessAuthFSM::RtsMapToUserCodeBakup(const char* pRtsCode, DWORD dwDefaultUserCode)
  884. {
  885. CSmartPointer<IConfigInfo> pConfig;
  886. m_pEntity->GetFunction()->OpenConfig(Config_Software, pConfig);
  887. int tmpUserCode = 0;
  888. pConfig->ReadConfigValueInt("RtsToUserCode", pRtsCode, tmpUserCode);
  889. if (tmpUserCode > 0)
  890. return tmpUserCode;
  891. else
  892. return dwDefaultUserCode;
  893. }
  894. int CAccessAuthFSM::RtsMapToUserCode(const char* pRtsCode, DWORD dwDefaultUserCode)
  895. {
  896. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("RtsCode:%s", pRtsCode);
  897. CSmartPointer<IConfigInfo> pConfig;
  898. m_pEntity->GetFunction()->OpenConfig(Config_CenterSetting, pConfig);
  899. int tmpUserCode = 0;
  900. pConfig->ReadConfigValueInt("RtsToUserCode", pRtsCode, tmpUserCode);
  901. if (tmpUserCode > 0)
  902. {
  903. return tmpUserCode;
  904. }
  905. else
  906. {
  907. std::map<std::string, DWORD> RtsToUserCode;
  908. RtsToUserCode["RTS1705"] = 0x5029000e;
  909. RtsToUserCode["RTS1707"] = 0x50290019;
  910. RtsToUserCode["RTS1711"] = 0x5029000b;
  911. RtsToUserCode["RTS1712"] = 0x50290018;
  912. RtsToUserCode["RTS1713"] = 0x50290019;
  913. RtsToUserCode["RTS1714"] = 0x5029000a;
  914. RtsToUserCode["RTS1715"] = 0x5029000f;
  915. if (RtsToUserCode.find(pRtsCode) != RtsToUserCode.end()) {
  916. return RtsToUserCode[pRtsCode];
  917. }
  918. else
  919. {
  920. return dwDefaultUserCode;
  921. }
  922. }
  923. }
  924. DWORD CAccessAuthFSM::HandleTimeSyn(long nTimeDiff, BYTE* nSessionKey)
  925. {
  926. // 比较终端和服务器时间, 时差小于3分钟(默认,可通过集中配置配置)不纠正
  927. const long dwTimeDiff = nTimeDiff > 0 ? nTimeDiff : 0 - nTimeDiff;
  928. const long torelateTime = m_torelateDiffSyncTimeSecs > 0 ? m_torelateDiffSyncTimeSecs : 0 - m_torelateDiffSyncTimeSecs;
  929. if (torelateTime < dwTimeDiff) {
  930. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("HandleTimeSyn")
  931. ("time diff is too large (%ds), sync time now", nTimeDiff);
  932. CSmallDateTime dtServerTime((DWORD)(CSmallDateTime::GetNow()) + nTimeDiff);
  933. SYSTEMTIME stServerTime = dtServerTime.ToSystemTime();
  934. #ifdef RVC_OS_WIN
  935. if (SetLocalTime(&stServerTime)) {
  936. #else
  937. if (set_system_time_by_sec(nTimeDiff)) {
  938. #endif // RVC_OS_WIN
  939. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("sync time with server succeed, server time: [%s]", (const char*)dtServerTime.ToTimeString());
  940. LogWarn(Severity_Low, Error_Debug, AccessAuthorization_UserErrorCode_Sync_Time_Succ,
  941. CSimpleStringA::Format("sync time succ: server time: [%s],diff[%ld],threshold:[%d]",
  942. (const char*)dtServerTime.ToTimeString(), nTimeDiff, m_torelateDiffSyncTimeSecs));
  943. }
  944. else {
  945. LogWarn(Severity_Middle, Error_Unexpect, AccessAuthorization_UserErrorCode_Sync_Time_Failed,
  946. CSimpleStringA::Format("sync time failed: server time: [%s],diff[%ld],threshold:[%d](GLE=%u)",
  947. (const char*)dtServerTime.ToTimeString(), nTimeDiff, m_torelateDiffSyncTimeSecs, GetLastError()));
  948. return ERR_ACCESSAUTH_SET_LOCALE_TIME;
  949. }
  950. }
  951. else {
  952. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("HandleTimeSyn")
  953. ("time diff is acceptable (%lds), threshold(%d),", nTimeDiff, m_torelateDiffSyncTimeSecs);
  954. }
  955. //会话密钥缓存
  956. if (((CAccessAuthEntity*)m_pEntity)->SaveAuthKey(nSessionKey))
  957. return Error_Succeed;
  958. return Error_Unexpect;
  959. }
  960. DWORD CAccessAuthFSM::HandleGetToken(BYTE* enToken1, BYTE* sharedKey, BYTE* enToken2, BYTE* retHash)
  961. {
  962. DWORD rc = Error_Succeed;
  963. auto pEntity = (CAccessAuthEntity*)m_pEntity;
  964. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI("HandleGetToken")("retHash=%s", (char*)retHash);
  965. char* enToken1_acs, * sharedKey_acs, * enToken2_acs, * hash_acs;
  966. int enToken1_acs_len = 0, sharedKey_acs_len = 0, enToken2_acs_len = 0, hash_acs_len = 0;
  967. #ifdef RVC_OS_WIN
  968. enToken1_acs = MyBase64::Hex2Str((char*)enToken1, enToken1_acs_len);
  969. sharedKey_acs = MyBase64::Hex2Str((char*)sharedKey, sharedKey_acs_len);
  970. enToken2_acs = MyBase64::Hex2Str((char*)enToken2, enToken2_acs_len);
  971. hash_acs = MyBase64::Hex2Str((char*)retHash, hash_acs_len);
  972. #else
  973. enToken1_acs = Hex2Str((char*)enToken1, enToken1_acs_len);
  974. sharedKey_acs = Hex2Str((char*)sharedKey, sharedKey_acs_len);
  975. enToken2_acs = Hex2Str((char*)enToken2, enToken2_acs_len);
  976. hash_acs = Hex2Str((char*)retHash, hash_acs_len);
  977. #endif // RVC_OS_WIN
  978. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI("HandleGetToken")("enToken1_acs_len=%d", enToken1_acs_len);
  979. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI("HandleGetToken")("sharedKey_acs_len=%d", sharedKey_acs_len);
  980. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI("HandleGetToken")("enToken2_acs_len=%d", enToken2_acs_len);
  981. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI("HandleGetToken")("hash_acs_len=%d", hash_acs_len);
  982. memset(enToken1, 0, strlen((char*)enToken1));
  983. memset(sharedKey, 0, strlen((char*)sharedKey));
  984. memset(enToken2, 0, strlen((char*)enToken2));
  985. memset(retHash, 0, strlen((char*)retHash));
  986. memcpy(enToken1, enToken1_acs, enToken1_acs_len);
  987. memcpy(sharedKey, sharedKey_acs, sharedKey_acs_len);
  988. memcpy(enToken2, enToken2_acs, enToken2_acs_len);
  989. memcpy(retHash, hash_acs, hash_acs_len);
  990. delete enToken1_acs;
  991. delete sharedKey_acs;
  992. delete enToken2_acs;
  993. delete hash_acs;
  994. BYTE enToken[512 + 16] = { 0 };
  995. memcpy(enToken, enToken1, 256);
  996. memcpy(enToken + 256, enToken2, 256);
  997. memcpy(enToken + 512, sharedKey, 16);
  998. BYTE sm3[32] = { 0 };
  999. if (!SM3Hash(enToken, 512 + 16, sm3)) {
  1000. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("SM3 Hash error at Token Ret.");
  1001. }
  1002. if (memcmp(sm3, retHash, 32) != 0)
  1003. {
  1004. rc = Error_Bug;
  1005. pEntity->SetAuthErrMsg("返回令牌校验不通过");
  1006. pEntity->GetFunction()->SetSysVar("AuthErrMsg", "返回令牌校验不通过", true);
  1007. #ifdef RVC_OS_WIN
  1008. char* sm3Ret = MyBase64::Str2Hex((char*)sm3, 32);
  1009. #else
  1010. char* sm3Ret = Str2Hex((char*)sm3, 32);
  1011. #endif // RVC_OS_WIN
  1012. delete sm3Ret;
  1013. doWarnMsg(ERR_ACCESSAUTH_TOKEN_HASH, "返回令牌校验不通过", true);
  1014. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)(GetOutPutStr("%s%s", "Hash", "返回令牌校验不通过").c_str());
  1015. }
  1016. else
  1017. {
  1018. CBlob token;
  1019. token.Alloc(512);
  1020. memcpy(token.m_pData, enToken, 512);
  1021. CBlob sharedSK;
  1022. sharedSK.Alloc(16);
  1023. memcpy(sharedSK.m_pData, sharedKey, 16);
  1024. rc = pEntity->SaveTokenAndSharedSK(token, sharedSK);
  1025. if (rc != Error_Succeed)
  1026. {
  1027. pEntity->SetAuthErrMsg("保存令牌失败");
  1028. pEntity->GetFunction()->SetSysVar("AuthErrMsg", "保存令牌失败", true);
  1029. pEntity->SetAuthErrMsg("保存令牌失败");
  1030. doWarnMsg(ERR_ACCESSAUTH_SAVE_TOKEN, "保存令牌失败", true);
  1031. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5208")(GetOutPutStr("%s%08X", "SaveTokenAndSharedSK", rc).c_str());
  1032. }
  1033. }
  1034. return rc;
  1035. }
  1036. DWORD CAccessAuthFSM::GetEncTerminalInfo(CBlob& encInfo)
  1037. {
  1038. LOG_FUNCTION();
  1039. RequestTokenReq1 req1;
  1040. memset(&req1, 0, sizeof(req1));
  1041. BYTE* pBuf = (BYTE*)&req1.encTerminalInfo;
  1042. // 设置长度
  1043. sprintf((char*)pBuf, "%.4d", sizeof(RequestTokenInfo));
  1044. RequestTokenInfo* pInfo = (RequestTokenInfo*)(pBuf + 4);
  1045. CSystemStaticInfo si;
  1046. m_pEntity->GetFunction()->GetSystemStaticInfo(si);
  1047. strncpy(pInfo->szTerminalNo, (const char*)si.strTerminalID, sizeof(pInfo->szTerminalNo) - 1);
  1048. CSimpleStringA strPinPadID = "", strDeviceID = "";
  1049. bool bHasPinPad = false;
  1050. int nRet = ((CAccessAuthEntity*)m_pEntity)->GetPinPadIDAndDeviceID(strPinPadID, strDeviceID, bHasPinPad);
  1051. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("GetPinPadIDAndDeviceID ret: %d, PinPadID: %s, DeviceID: %s", nRet, (const char*)strPinPadID, (const char*)strDeviceID);
  1052. if (nRet == 2 || nRet == 3) {
  1053. strncpy(pInfo->szPadDeviceID, (const char*)strDeviceID, sizeof(pInfo->szPadDeviceID) - 1);
  1054. }
  1055. strncpy(pInfo->szMachineType, (const char*)si.strMachineType, sizeof(pInfo->szMachineType) - 1);
  1056. // 设备版本,低两位为小版本号,高两位为大版本号 Binary 4
  1057. DWORD ver32 = si.MachineVersion.GetVersion32();
  1058. for (int i = 0; i < 4; i++) {
  1059. pInfo->machineVersion[3 - i] = ((BYTE*)&ver32)[i];
  1060. }
  1061. // 安装版本,其中包含软件框架版本 binary 8
  1062. __int64 ver64 = si.InstallVersion.GetVersion64();
  1063. for (int i = 0; i < 8; i++) {
  1064. pInfo->installVersion[7 - i] = ((BYTE*)&ver64)[i];
  1065. }
  1066. #ifdef RVC_OS_WIN
  1067. hostent* ent = gethostbyname(NULL);
  1068. if (ent && ent->h_addr_list[0] != NULL) {
  1069. int i = 0;
  1070. for (; ent->h_addr_list[i] != NULL; ++i) {
  1071. struct in_addr* in = (struct in_addr*)ent->h_addr_list[i];
  1072. if (in->S_un.S_un_b.s_b1 == 99 || in->S_un.S_un_b.s_b1 == 10)
  1073. break;
  1074. }
  1075. if (ent->h_addr_list[i] == NULL)
  1076. i = 0;
  1077. auto in = (struct in_addr*)ent->h_addr_list[i];
  1078. pInfo->ip[0] = in->S_un.S_un_b.s_b1;
  1079. pInfo->ip[1] = in->S_un.S_un_b.s_b2;
  1080. pInfo->ip[2] = in->S_un.S_un_b.s_b3;
  1081. pInfo->ip[3] = in->S_un.S_un_b.s_b4;
  1082. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("ip:%d.%d.%d.%d", pInfo->ip[0], pInfo->ip[1], pInfo->ip[2], pInfo->ip[3]);
  1083. }
  1084. #else
  1085. char ip[32] = { 0 };
  1086. if (getIPFromLinux(ip)) DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Get IP From Linux Error ex.");
  1087. else {
  1088. if (ip2byte(ip, pInfo->ip)) DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Ip 2 Byte Error");
  1089. else {
  1090. for (int i = 0; i < 4; i++) {
  1091. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("ip[%d]=%d", i, (int)pInfo->ip[i]);
  1092. }
  1093. }
  1094. }
  1095. #endif //#ifdef RVC_OS_WIN
  1096. strncpy(pInfo->szSites, si.strSite, sizeof(pInfo->szSites) - 1);
  1097. si.EnrolGPS.GetBinaryLongitude(&pInfo->currentGPS[0]);
  1098. si.EnrolGPS.GetBinaryLatitude(&pInfo->currentGPS[4]);
  1099. CSimpleStringA ts;
  1100. DWORD rc = m_pEntity->GetFunction()->GetSysVar("TerminalStage", ts);
  1101. if (rc != Error_Succeed)
  1102. {
  1103. doWarnMsg(ERR_ACCESSAUTH_GET_SYS_VAR,
  1104. GetOutPutStr("%s%08X%s%s", "GetSysVar", rc, "TerminalStage", ts).c_str());
  1105. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)(GetOutPutStr("%s%08X%s%s", "GetSysVar", rc, "TerminalStage", ts).c_str());
  1106. return ERR_ACCESSAUTH_GET_SYS_VAR;
  1107. }
  1108. assert(ts.GetLength() >= 1);
  1109. pInfo->chTerminalState = ts[0];
  1110. CSimpleStringA rs;
  1111. rc = m_pEntity->GetFunction()->GetSysVar("RunState", rs);
  1112. if (rc != Error_Succeed)
  1113. {
  1114. doWarnMsg(ERR_ACCESSAUTH_GET_SYS_VAR,
  1115. GetOutPutStr("%s%08X%s%s", "GetSysVar", rc, "RunState", rs).c_str());
  1116. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)(GetOutPutStr("%s%08X%s%s", "GetSysVar", rc, "RunState", ts).c_str());
  1117. return ERR_ACCESSAUTH_GET_SYS_VAR;
  1118. }
  1119. assert(rs.GetLength() >= 1);
  1120. pInfo->chRunState = rs[0];
  1121. CBlob raw;
  1122. auto pEntity = ((CAccessAuthEntity*)m_pEntity);
  1123. // 使用会话密钥加密
  1124. raw.Refer(pBuf, sizeof(RequestTokenInfo) + 4);
  1125. rc = pEntity->EncryptDataWithSessionKey(raw, encInfo);
  1126. if (rc != Error_Succeed)
  1127. {
  1128. doWarnMsg(ERR_ACCESSAUTH_ENCRYPT_KEY,
  1129. GetOutPutStr("%s%08X", "CryptEncrypt", rc).c_str());
  1130. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)(GetOutPutStr("%s%08X", "CryptEncrypt", rc).c_str());
  1131. return ERR_ACCESSAUTH_ENCRYPT_KEY;
  1132. }
  1133. return Error_Succeed;
  1134. }
  1135. //密钥加密并转成可见字符
  1136. DWORD CAccessAuthFSM::GetTmk(string& tmk)
  1137. {
  1138. BYTE tmp[140];
  1139. CBlob pubKey;
  1140. CBlob priKey;
  1141. DWORD rc = ((CAccessAuthEntity*)m_pEntity)->CreateSM2KeyPair(pubKey, priKey);
  1142. if (rc != Error_Succeed) return rc;
  1143. rc = ((CAccessAuthEntity*)m_pEntity)->SaveSM2KeyPair(pubKey, priKey);
  1144. if (rc != Error_Succeed) return rc;
  1145. memset(tmp, 0, sizeof(tmp));
  1146. if (pubKey.m_iLength > 70) {
  1147. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("临时公钥长度(%d)大于70。。。", pubKey.m_iLength);
  1148. return Error_TooSmallBuffer;
  1149. }
  1150. memcpy_s(tmp, sizeof(tmp) - 70, pubKey.m_pData, pubKey.m_iLength);
  1151. if (priKey.m_iLength > 70) {
  1152. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("临时私钥长度(%d)大于70。。。", priKey.m_iLength);
  1153. return Error_TooSmallBuffer;
  1154. }
  1155. memcpy_s(&tmp[70], sizeof(tmp) - 70, priKey.m_pData, priKey.m_iLength);
  1156. char* pRet = new char[512];
  1157. HexBuf2StrBuf(tmp, &pRet, 140);
  1158. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("data=%s,%d", pRet, strlen(pRet));
  1159. tmk.assign(pRet);
  1160. delete[] pRet;
  1161. return Error_Succeed;
  1162. }
  1163. DWORD CAccessAuthFSM::GetTokenReq(CAccessAuthGetTokenReq* getTokenReq)
  1164. {
  1165. DWORD rc;
  1166. auto pEntity = (CAccessAuthEntity*)m_pEntity;
  1167. CSystemStaticInfo si;
  1168. pEntity->GetFunction()->GetSystemStaticInfo(si);
  1169. getTokenReq->installVersion = si.InstallVersion.ToString();
  1170. BYTE fingerPrint[32] = { 0 };
  1171. int nBufLen = sizeof(fingerPrint);
  1172. if (!pEntity->GetTerminalFingerPrint(fingerPrint, nBufLen))
  1173. {
  1174. doWarnMsg(ERR_ACCESSAUTH_GET_TERMINAL_FINGERPRINT,
  1175. GetOutPutStr("%s%s", "GetTerminalFingerPrint", "False").c_str());
  1176. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5203")
  1177. (GetOutPutStr("%s%s", "GetTerminalFingerPrint", "False").c_str());
  1178. return ERR_ACCESSAUTH_GET_TERMINAL_FINGERPRINT;
  1179. }
  1180. char tmp[256] = { 0 };
  1181. #ifdef RVC_OS_WIN
  1182. char* fingerPrintHex = MyBase64::Str2Hex((char*)fingerPrint, 64);
  1183. #else
  1184. char* fingerPrintHex = Str2Hex((char*)fingerPrint, 64);
  1185. #endif // RVC_OS_WIN
  1186. memcpy(tmp, fingerPrintHex, 64);
  1187. getTokenReq->terminalCharacter = tmp;
  1188. delete fingerPrintHex;
  1189. CBlob encInfo;
  1190. if ((rc = GetEncTerminalInfo(encInfo)) != Error_Succeed)
  1191. {
  1192. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetEncTerminalInfo failed:%d", rc);
  1193. return rc;
  1194. }
  1195. #ifdef RVC_OS_WIN
  1196. char* pTmp = MyBase64::Str2Hex((char*)encInfo.m_pData, encInfo.m_iLength);
  1197. #else
  1198. char* pTmp = Str2Hex((char*)encInfo.m_pData, encInfo.m_iLength);
  1199. #endif // RVC_OS_WIN
  1200. getTokenReq->encTerminalInfo = pTmp;
  1201. delete pTmp;
  1202. getTokenReq->terminalNo = si.strTerminalID.GetData();
  1203. string tmpStr = "";
  1204. if ((rc = GetTmk(tmpStr)) != Error_Succeed) return rc;
  1205. getTokenReq->sessionTempPubKey = tmpStr;
  1206. CSimpleStringA strPinPadID = "", strDeviceID = "";
  1207. bool bHasPinPad = false;
  1208. int nRet = ((CAccessAuthEntity*)m_pEntity)->GetPinPadIDAndDeviceID(strPinPadID, strDeviceID, bHasPinPad);
  1209. getTokenReq->pinPadID = strPinPadID.GetData();
  1210. if (pEntity->HasPinPad())
  1211. {
  1212. getTokenReq->existPinPad = "1";
  1213. }
  1214. else
  1215. {
  1216. getTokenReq->existPinPad = "0";
  1217. }
  1218. return rc;
  1219. }
  1220. DWORD CAccessAuthFSM::GetAllDevices(CEntityBase* pEntity, CAutoArray<CSimpleStringA>& devs)
  1221. {
  1222. CSmartPointer<IConfigInfo> pConfig;
  1223. DWORD rc = pEntity->GetFunction()->OpenConfig(Config_Root, pConfig);
  1224. if (rc == Error_Succeed)
  1225. {
  1226. int nCount(0);
  1227. rc = pConfig->ReadConfigValueInt("Device", "Number", nCount);
  1228. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("nCount=%d", nCount);
  1229. if (rc == Error_Succeed && nCount > 0)
  1230. {
  1231. devs.Init(nCount);
  1232. for (int i = 0; i < nCount; i++)
  1233. {
  1234. CSimpleStringA str = CSimpleStringA::Format("%d", i + 1);
  1235. rc = pConfig->ReadConfigValue("Device", (const char*)str, devs[i]);
  1236. }
  1237. }
  1238. }
  1239. else
  1240. {
  1241. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetAllDevices OpenConfig error");
  1242. }
  1243. return rc;
  1244. }
  1245. void CAccessAuthFSM::UpdateWK()
  1246. {
  1247. LOG_FUNCTION();
  1248. auto pEntity = ((CAccessAuthEntity*)m_pEntity);
  1249. CSimpleStringA strPinPadID = "", strDeviceID = "";
  1250. bool bHasPinPad = false;
  1251. pEntity->GetPinPadIDAndDeviceID(strPinPadID, strDeviceID, bHasPinPad);
  1252. if (bHasPinPad) {
  1253. CSmartPointer<UpdateWKTask> updateWKTask = new UpdateWKTask(this, pEntity);
  1254. GetEntityBase()->GetFunction()->PostThreadPoolTask(updateWKTask.GetRawPointer());
  1255. }
  1256. }
  1257. DWORD CAccessAuthFSM::InitDevice(SpReqAnsContext<AccessAuthService_InitDev_Req, AccessAuthService_InitDev_Ans>::Pointer& ctx)
  1258. {
  1259. #ifdef RVC_OS_WIN
  1260. DWORD rc = 0;
  1261. InitDeviceReq req;
  1262. memset(&req, 0, sizeof(req));
  1263. strncpy(req.CR1, (const char*)ctx->Req.EncR1, sizeof(req.CR1));
  1264. strncpy(req.R2, (const char*)ctx->Req.R2, sizeof(req.R2));
  1265. strncpy(req.CR3, (const char*)ctx->Req.EncR3, sizeof(req.CR3));
  1266. strncpy(req.CDevPubKey, (const char*)ctx->Req.EncDevPubKey, sizeof(req.CDevPubKey));
  1267. strncpy(req.Verdor, (const char*)ctx->Req.Vendor, sizeof(req.Verdor));
  1268. m_ctxInitDev = ctx;
  1269. CSmartPointer<InitDeviceTask> initDeviceTask = new InitDeviceTask(this, req);
  1270. GetEntityBase()->GetFunction()->PostThreadPoolTask(initDeviceTask.GetRawPointer());
  1271. #endif // RVC_OS_WIN
  1272. return Error_Succeed;
  1273. }
  1274. void CAccessAuthFSM::GetDiffSyncTimeFromCenterSettings()
  1275. {
  1276. CSmartPointer<IConfigInfo> spConfig;
  1277. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
  1278. int nValue(0);
  1279. spConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "SyncTimeThreshold", nValue);
  1280. if (nValue != 0) {
  1281. m_torelateDiffSyncTimeSecs = nValue;
  1282. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_BUSINESS_SYSTEM)("Fetch SyncTimeThreshold from CS returns: %d", m_torelateDiffSyncTimeSecs);
  1283. }
  1284. }
  1285. template<class T>
  1286. void CAccessAuthFSM::AuthLogWarn(const T& ret, const string& url, const string& method, bool bNeedEvent)
  1287. {
  1288. CSimpleStringA msg;
  1289. #ifdef RVC_OS_WIN
  1290. if (ret.m_userCode != "0" && ret.m_sysCode != 200)
  1291. #else
  1292. if (!ret.ResponseOK())
  1293. #endif // RVC_OS_WIN
  1294. {
  1295. int acsErrCode = ERROR_ACCESSAUTH_CONNECT_ACS_x;
  1296. #ifdef RVC_OS_WIN
  1297. if (ret.m_sysCode == 6) {
  1298. #else
  1299. if (ret.statusCode == 6) {
  1300. #endif
  1301. acsErrCode = ERROR_ACCESSAUTH_CONNECT_ACS_6;
  1302. msg = CSimpleStringA::Format("%s失败:域名解析失败,请尝试重启应用", method.c_str());
  1303. }
  1304. #ifdef RVC_OS_WIN
  1305. else if (ret.m_sysCode == 28) {
  1306. #else
  1307. else if (ret.statusCode == 28) {
  1308. #endif
  1309. acsErrCode = ERROR_ACCESSAUTH_CONNECT_ACS_28;
  1310. msg = CSimpleStringA::Format("%s失败:连接总行服务超时,请尝试重启应用", method.c_str());
  1311. }
  1312. else {
  1313. msg = CSimpleStringA::Format("%s失败,请尝试重启应用", method.c_str());
  1314. }
  1315. doWarnMsg(acsErrCode, msg.GetData(), bNeedEvent);
  1316. }
  1317. else {
  1318. #ifdef RVC_OS_WIN
  1319. msg = CSimpleStringA::Format("{\"errcode\": \"%s\", \"message\": %s}",
  1320. ret.m_userCode.c_str(), ret.m_errMsg.c_str());
  1321. #else
  1322. SP::Module::Restful::CommResponseJson responseStatus;
  1323. SP::Module::Restful::GetStatusFromDebranchResponse(ret.content, responseStatus);
  1324. msg = CSimpleStringA::Format("{\"errcode\": \"%s\", \"message\": %s}",
  1325. responseStatus.errorCode.c_str(), responseStatus.errorMsg.c_str());
  1326. #endif // RVC_OS_WIN
  1327. doWarnMsg(ERR_ACCESSAUTH_SERVICE_FAILED, msg.GetData(), bNeedEvent);
  1328. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA520A")("准入服务端报错");
  1329. }
  1330. }
  1331. void CAccessAuthFSM::GetNetMsg(SpReqAnsContext<AccessAuthService_GetNetMsg_Req, AccessAuthService_GetNetMsg_Ans>::Pointer& ctx)
  1332. {
  1333. CSimpleStringA tmp;
  1334. ctx->Ans.netStatus = 1; //成功
  1335. ctx->Answer(Error_Succeed);
  1336. }