SpSecureClient.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. #include "SpSecureClient.h"
  2. #include "sp_cfg.h"
  3. #include "sp_env.h"
  4. #include "spShareMemoryBase.h"
  5. #include "toolkit.h"
  6. #include "dbgutil.h"
  7. #ifdef RVC_OS_WIN
  8. #include "IHttpFunc.h"
  9. #include "sp_checkEntity.h"
  10. #include "SpEntity.h"
  11. #endif
  12. #include <winpr/winsock.h>
  13. #include "TokenKeeper_client_g.h"
  14. using namespace TokenKeeper;
  15. #define TAG RVCCOMM_TAG("SecureClient")
  16. CEntityBase* SpSecureClient::m_pEntity = NULL;
  17. void getHttpToken(std::string &channelId, std::string &token, std::string &terminalNo, std::string &reserve1)
  18. {
  19. CSimpleString t_channelId, t_token;
  20. CSystemStaticInfo info;
  21. if (SpSecureClient::m_pEntity == NULL)
  22. return;
  23. if (SpSecureClient::m_pEntity->GetFunction()->GetToken(t_channelId, t_token) != ErrorCodeEnum::Error_Succeed ||
  24. SpSecureClient::m_pEntity->GetFunction()->GetSystemStaticInfo(info) != ErrorCodeEnum::Error_Succeed)
  25. return;
  26. if(t_channelId.GetLength() != 0 && t_token.GetLength() != 0 && info.strTerminalID.GetLength() != 0)
  27. {
  28. channelId = t_channelId.GetData();
  29. token = t_token.GetData();
  30. terminalNo = info.strTerminalID.GetData();
  31. }
  32. }
  33. enum CommEventEnum
  34. {
  35. //连接主用地址 事件 1 0xNNN08001 连接配置文件定义的主用地址,需要记录地址信息。如果为短连接,记录首次连接事件。
  36. CE_ConnectMasterServer = 0x00008001,
  37. //连接备用地址 事件 1 0xNNN08002 如果没有定义备用地址,就不会有这条信息
  38. CE_ConnectSlaveServer = 0x00008002,
  39. //主动断开连接 事件 1 0xNNN08011 如果为短连接,无需记录此事件
  40. CE_ActiveClose = 0x00008011,
  41. //读取配置失败 错误 3 0xNNN08021 不能读到需要配置项,代码或配置有误,可以切换备份区域,或需要人干预
  42. CE_ReadCfgFail = 0x00008021,
  43. //连接地址无效 错误 2 0xNNN88031 对端不存在,配置错误,或当前服务器故障
  44. CE_InvalidAddr = 0x00088031,
  45. //对端拒绝连接 错误 2 0xNNN88032 对端存在,但可能故障,导致服务器拒绝建立连接
  46. CE_PeerReject = 0x00088032,
  47. //连接超时 错误 2 0xNNN88033 等待连接超时
  48. CE_ConnectTimeout = 0x00088033,
  49. //容量拒绝 错误 2 0xNNN88034 由于达到后台的最大容量,连接拒绝,需要重试
  50. CE_ReachMaxNum = 0x00088034,
  51. //服务暂停 错误 2 0xNNN88035 后台暂停服务,实体可以切换主备服务或抛出连接失败,切换备份区域
  52. CE_OutOfService = 0x00088035,
  53. //失去连接 错误 2 0xNNN88036 由于对端或网络原因连接断开
  54. CE_LostConnection = 0x00088036,
  55. //无效请求包 错误 3 0xNNN88041 实体或后台代码错误,需要进行人工修复。在描述中应该说明错误的原因。
  56. CE_InvalidReqPack = 0x00088041,
  57. //鉴权不可识别 错误 3 0xNNN88051 由于服务准入服务证书不符,不能解开请求包,错误需要干预,不能自动修复。
  58. CE_AuthFailed = 0x00088051,
  59. //鉴权信息不匹配 错误 2 0xNNN88052 请求时鉴权信息不匹配,需要重新进行准入。
  60. CE_HashMismatch = 0x00088052,
  61. //当前区域连接失败 事件 2 0xNNN880F1 由于多次尝试失败,或发生不可尝试错误,实体放弃了当前区域连接尝试,用于驱动状态切换。记录区域代码。
  62. CE_CurRegionDisabled = 0x000880F1,
  63. };
  64. void* SpSecureClient::logProducer(NULL);
  65. void SpSecureClient::DbgWithLink_DualActive(const char* formatStr, ...) {
  66. if (formatStr == nullptr)
  67. return;
  68. va_list arg;
  69. va_start(arg, formatStr);
  70. //不这么写?貌似到DbgWithLink内后,arg会被析构?
  71. int n = _vscprintf(formatStr, arg) + 1;
  72. std::vector<char> buf(n + 1, '\0');
  73. vsnprintf(&buf[0], n, formatStr, arg);
  74. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__).withLogProducer(logProducer).withExtendLog(false)(&buf[0]);
  75. if(EntityResource::getSaveFile())
  76. m_log.LOGERROR(&buf[0]);
  77. va_end(arg);
  78. }
  79. // 不应该直接delete,而用DecRef()
  80. SpSecureClient::~SpSecureClient()
  81. {
  82. //this would lost the process at UOS plat.
  83. //#ifndef _WIN32
  84. // if (logProducer != NULL) {
  85. // destroy_log_producer_storage(logProducer);
  86. // logProducer = NULL;
  87. // }
  88. //#endif
  89. }
  90. SpSecureClient::SpSecureClient(CEntityBase *pEntityBase)
  91. : m_bClosed(true)
  92. {
  93. m_pEntity = pEntityBase;
  94. if(logProducer == NULL) {
  95. logProducer = create_log_producer_storage("DualActive", "0", "", "", "");
  96. }
  97. }
  98. std::pair<bool, std::string> FromAddressToIP(std::string host) {
  99. struct hostent* ht = NULL;
  100. ht = gethostbyname(host.c_str());
  101. if (ht) {
  102. for (int i = 0; ; i++) {
  103. if (ht->h_addr_list[i] != NULL)
  104. return std::make_pair(true, inet_ntoa(*((struct in_addr*)ht->h_addr_list[i])));
  105. else
  106. break;
  107. }
  108. for (int j = 0; ; j++) {
  109. if (ht->h_aliases[j] != NULL)
  110. return std::make_pair(true, ht->h_aliases[j]);
  111. else
  112. break;
  113. }
  114. }
  115. return std::make_pair(false, "");
  116. }
  117. bool SpSecureClient::Connect(const char *pServerAddr, int nPort, int nOption) // wait until all authentication operation has been finished
  118. {
  119. TOOLKIT_ASSERT(m_pEntity != NULL);
  120. auto ipRet = FromAddressToIP(pServerAddr);
  121. std::string dstIp = ipRet.first ? ipRet.second : pServerAddr;
  122. bool result = false;
  123. if (GetFunction()->Connect(dstIp.c_str(), nPort, nOption))
  124. {
  125. m_bClosed = false;
  126. result = true;
  127. }
  128. else {
  129. DbgWithLink_DualActive("connect to %s:%d, option=%d, result:%s", dstIp.c_str(), nPort, nOption, result ? "SUCCESS" : "FAIL");
  130. result = false;
  131. }
  132. return result;
  133. }
  134. void SpSecureClient::connectClose(const char *pEntityName)
  135. {
  136. if (NULL == pEntityName)
  137. return;
  138. ENTITY_CONNECT_INFO connectInfo;
  139. if (!findConnectInfo(pEntityName, &connectInfo))
  140. {
  141. DbgWithLink_DualActive("can not find %s in connection list.", pEntityName);
  142. return;
  143. }
  144. connectInfo.m_currentLink = -1;
  145. }
  146. bool SpSecureClient::findConnectInfo(const char *pEntityName, ENTITY_CONNECT_INFO *connectInfo)
  147. {
  148. if (NULL == pEntityName || NULL == connectInfo)
  149. return false;
  150. connectControl *entityConnect = connectControl::getInstance();
  151. if (entityConnect->getEntityInfo(pEntityName, connectInfo))
  152. return true;
  153. return false;
  154. }
  155. bool SpSecureClient::readConnectInfoFromCentralSetting(const char *pEntityName, ENTITY_CONNECT_INFO *connectInfo)
  156. {
  157. if (NULL == pEntityName || NULL == connectInfo)
  158. return false;
  159. connectControl *entityConnect = connectControl::getInstance();
  160. bool readSuccess = entityConnect->getEntityInfo(pEntityName, connectInfo);
  161. //获得集中配置信息
  162. auto pFunc = m_pEntity->GetFunction();
  163. CSmartPointer<IConfigInfo> spConfig;
  164. if (Error_Succeed != pFunc->OpenConfig(Config_CenterSetting, spConfig))
  165. {
  166. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("open center setting config fail");
  167. return false;
  168. }
  169. CSimpleStringA str;
  170. int readEach = 1;
  171. if (Error_Succeed == spConfig->ReadConfigValue("SpBase", "ReadEach", str) && !str.IsNullOrEmpty())
  172. readEach = atoi(str);
  173. if (0 == readEach && readSuccess)
  174. return true;//不是每次都读取新的Entity的IP和Port,只在实体启动时读取一次
  175. ErrorCodeEnum configRc = Error_Bug;
  176. if (Error_Succeed != (configRc = spConfig->ReadConfigValue(pEntityName, "Server", str)) || str.IsNullOrEmpty())
  177. {
  178. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("read Main::Server config fail, %d, %s", configRc, pEntityName);
  179. return false;
  180. }
  181. CSimpleStringA strServer1;
  182. int nServer1Port;
  183. if (Error_Succeed != (configRc = ParseIPAddress(str, strServer1, nServer1Port)))
  184. {
  185. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("parse ip addr fail: %s, %d", (const char*)str, configRc);
  186. return false;
  187. }
  188. CSimpleStringA strServer2 = "";
  189. int nServer2Port = 0;
  190. if (Error_Succeed == spConfig->ReadConfigValue(pEntityName, "Server_Backup", str) && !str.IsNullOrEmpty())
  191. ParseIPAddress(str, strServer2, nServer2Port);
  192. int dualActive = -1;
  193. if (Error_Succeed == spConfig->ReadConfigValue("SpBase", "DualActive", str) && !str.IsNullOrEmpty())
  194. dualActive = atoi(str);
  195. if (readSuccess)
  196. connectInfo->setParam(pEntityName, strServer1.GetData(), nServer1Port, strServer2.GetData(), nServer2Port, dualActive, connectInfo->m_currentLink);
  197. else
  198. {
  199. //DbgWithLink_DualActive("call clear");
  200. connectInfo->clear();
  201. connectInfo->setParam(pEntityName, strServer1.GetData(), nServer1Port, strServer2.GetData(), nServer2Port, dualActive);
  202. }
  203. entityConnect->setEntityInfo(connectInfo);
  204. return true;
  205. }
  206. bool SpSecureClient::setConnectInfo(const ENTITY_CONNECT_INFO *connectInfo)
  207. {
  208. if (NULL == connectInfo)
  209. return false;
  210. connectControl *entityConnect = connectControl::getInstance();
  211. entityConnect->setLastLink(connectInfo->m_currentLink);
  212. return entityConnect->setEntityInfo(connectInfo);
  213. }
  214. // 使用集中配置项连接
  215. bool SpSecureClient::ConnectFromCentralSetting()
  216. {
  217. #ifdef RVC_OS_WIN
  218. SetthreadGroup(GetCurrentThreadId(), m_pEntity->GetEntityName());
  219. #endif // RVC_OS_WIN
  220. if (IsConnectionOK())
  221. return true;
  222. const char* pEntityName = m_pEntity->GetEntityName();
  223. ENTITY_CONNECT_INFO connectInfo;
  224. if (!readConnectInfoFromCentralSetting(pEntityName, &connectInfo))
  225. {
  226. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Read %s Info Failed", pEntityName);
  227. DbgWithLink_DualActive("Read %s Info Failed", pEntityName);
  228. return false;
  229. }
  230. // 判断当前是否已经准入,已经准入则强制使用安全连接
  231. int nOption = 3;
  232. CSimpleStringA strVal;
  233. if (Error_Succeed == m_pEntity->GetFunction()->GetSysVar("EntryPermit", strVal)) {
  234. if (strVal == "L" && stricmp(pEntityName, "AccessAuthorization") != 0 && stricmp(pEntityName, "Initializer") != 0)
  235. nOption = 2; // 优先使用缓存密钥
  236. }
  237. if (1 == connectInfo.m_DualActive)
  238. return Connect_Dual(&connectInfo, nOption);
  239. else
  240. return Connect_Single(&connectInfo, nOption);
  241. }
  242. bool SpSecureClient::ConnectFromAddress(CSimpleStringA mainServ, CAutoArray<CSimpleStringA> backupServArr, CSimpleStringA& connectedServ)
  243. {
  244. #ifdef RVC_OS_WIN
  245. SetthreadGroup(GetCurrentThreadId(), m_pEntity->GetEntityName());
  246. #endif // RVC_OS_WIN
  247. if (IsConnectionOK()) {
  248. connectedServ = "";
  249. return true;
  250. }
  251. int nOption = 3;
  252. const char* pEntityName = m_pEntity->GetEntityName();
  253. CSimpleStringA strVal;
  254. if (Error_Succeed == m_pEntity->GetFunction()->GetSysVar("EntryPermit", strVal)) {
  255. if (strVal == "L" && stricmp(pEntityName, "AccessAuthorization") != 0)
  256. nOption = 2; // 优先使用缓存密钥
  257. }
  258. bool connSucc = Connect_Standby(mainServ, backupServArr, nOption, connectedServ);
  259. return connSucc;
  260. }
  261. int SpSecureClient::getCurrentLink()
  262. {
  263. if (!IsConnectionOK())
  264. return -1;
  265. const char* pEntityName = m_pEntity->GetEntityName();
  266. ENTITY_CONNECT_INFO connectInfo;
  267. if (!readConnectInfoFromCentralSetting(pEntityName, &connectInfo))
  268. {
  269. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Read %s Info Failed", pEntityName);
  270. return -1;
  271. }
  272. return connectInfo.m_currentLink;
  273. }
  274. bool SpSecureClient::Connect_Single(ENTITY_CONNECT_INFO *connectInfo, int option)
  275. {
  276. if (NULL == connectInfo || 0 == strlen(connectInfo->m_EntityName))
  277. return false;
  278. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("mod %s using option %d", connectInfo->m_EntityName, option);
  279. DbgWithLink_DualActive("mod %s using option %d", connectInfo->m_EntityName, option);
  280. if (Connect(connectInfo->m_ServerIP, connectInfo->m_ServerPort, option))
  281. connectInfo->m_currentLink = 0;
  282. else if (0 != strlen(connectInfo->m_Server_BackupIP) && strcmp(connectInfo->m_ServerIP, connectInfo->m_Server_BackupIP)
  283. && Connect(connectInfo->m_Server_BackupIP, connectInfo->m_Server_BackupPort, option))
  284. connectInfo->m_currentLink = 1;
  285. else
  286. connectInfo->m_currentLink = -1;
  287. setConnectInfo(connectInfo);
  288. DbgWithLink_DualActive("Single Connection: EntityName:%s, server:%s %d, serverBackup:%s %d, DualOpen: %d, currentLink:%d", connectInfo->m_EntityName, connectInfo->m_ServerIP,
  289. connectInfo->m_ServerPort, connectInfo->m_Server_BackupIP, connectInfo->m_Server_BackupPort, connectInfo->m_DualActive, connectInfo->m_currentLink);
  290. return -1 != connectInfo->m_currentLink;
  291. }
  292. bool SpSecureClient::Connect_Dual(ENTITY_CONNECT_INFO *connectInfo, int option)
  293. {
  294. if (NULL == connectInfo || 0 == strlen(connectInfo->m_EntityName))
  295. return false;
  296. connectControl *entityConnect = connectControl::getInstance();
  297. bool quickConnect = false;
  298. const int priorLink = entityConnect->getPriorLink(connectInfo->m_lastLink);
  299. if (-1 != priorLink)
  300. {
  301. /*
  302. 根据上次双活成功时的server进行连接
  303. */
  304. if (0 == priorLink && 0 != strlen(connectInfo->m_ServerIP)) {
  305. connectInfo->m_currentLink = (Connect(connectInfo->m_ServerIP, connectInfo->m_ServerPort, option) ? 0 : -1);
  306. }
  307. else if (1 == priorLink && 0 != strlen(connectInfo->m_Server_BackupIP)) {
  308. connectInfo->m_currentLink = (Connect(connectInfo->m_Server_BackupIP, connectInfo->m_Server_BackupPort, option) ? 1 : -1);
  309. }
  310. quickConnect = (-1 == connectInfo->m_currentLink ? false : true);
  311. }
  312. if (!IsConnectionOK()) {
  313. /*
  314. 根据终端号进行连接
  315. */
  316. //获取终端号,判断优先连接的IP和端口
  317. auto pFunc = m_pEntity->GetFunction();
  318. CSmartPointer<IConfigInfo> spConfig;
  319. auto rc = pFunc->OpenConfig(Config_Root, spConfig);
  320. if (rc != Error_Succeed) {
  321. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("read root.ini Fail: %s", SpStrError(rc));
  322. return false;
  323. }
  324. CSimpleStringA strValue;
  325. spConfig->ReadConfigValue("Terminal", "TerminalNo", strValue);
  326. bool isMainServer = true;
  327. if (strValue.GetLength() > 0) {
  328. char str[20] = "";
  329. sprintf(str, "%s", (const char*)strValue);
  330. const int f = (str[strlen(str) - 1] - '0');
  331. isMainServer = (0 == (f % 2));
  332. DbgWithLink_DualActive("TerminalNo: %s, lastByte: %d, MainServer:%d", str, f, isMainServer);
  333. }
  334. DbgWithLink_DualActive("mod %s using option %d", connectInfo->m_EntityName, option);
  335. if (0 == strlen(connectInfo->m_Server_BackupIP) && 0 == strlen(connectInfo->m_ServerIP)) {
  336. connectInfo->m_currentLink = -1;
  337. } else if (0 == strlen(connectInfo->m_Server_BackupIP))
  338. {//serverBackup Ip and port error, link to server
  339. connectInfo->m_currentLink = (Connect(connectInfo->m_ServerIP, connectInfo->m_ServerPort, option) ? 0 : -1);//Link to first one
  340. DbgWithLink_DualActive("%s serverBackup param error", connectInfo->m_EntityName);
  341. }
  342. else
  343. {
  344. if (isMainServer)
  345. {//link to first server
  346. if (Connect(connectInfo->m_ServerIP, connectInfo->m_ServerPort, option))
  347. connectInfo->m_currentLink = 0;
  348. else if (
  349. strcmp(connectInfo->m_ServerIP, connectInfo->m_Server_BackupIP)
  350. && Connect(connectInfo->m_Server_BackupIP, connectInfo->m_Server_BackupPort, option)
  351. ) {
  352. connectInfo->m_currentLink = 1;
  353. }
  354. else {
  355. connectInfo->m_currentLink = -1;
  356. }
  357. }
  358. else
  359. {//link to second server
  360. DbgWithLink_DualActive("BackUp");
  361. if (Connect(connectInfo->m_Server_BackupIP, connectInfo->m_Server_BackupPort, option))
  362. connectInfo->m_currentLink = 1;
  363. else if (strcmp(connectInfo->m_ServerIP, connectInfo->m_Server_BackupIP)
  364. && Connect(connectInfo->m_ServerIP, connectInfo->m_ServerPort, option))
  365. connectInfo->m_currentLink = 0;
  366. else
  367. connectInfo->m_currentLink = -1;
  368. }
  369. }
  370. }
  371. /*
  372. 连接结束
  373. */
  374. char msg[1024];
  375. sprintf(msg, "%sDual Connection: EntityName:%s, server:%s %d, serverBackup:%s %d, DualOpen: %d, currentLink:%d, curEntityNum:%d", (quickConnect ? "quick " : ""),
  376. connectInfo->m_EntityName, connectInfo->m_ServerIP, connectInfo->m_ServerPort, connectInfo->m_Server_BackupIP,
  377. connectInfo->m_Server_BackupPort, connectInfo->m_DualActive, connectInfo->m_currentLink, entityConnect->getEntityNum());
  378. DbgWithLink_DualActive(msg);
  379. setConnectInfo(connectInfo);
  380. return (-1 != connectInfo->m_currentLink);
  381. }
  382. bool SpSecureClient::Connect_Standby(CSimpleStringA mainServ, CAutoArray<CSimpleStringA> backupServArr, int option, CSimpleStringA &connectedServ)
  383. {
  384. const char* pEntityName = m_pEntity->GetEntityName();
  385. ENTITY_CONNECT_INFO connectInfo;
  386. DbgWithLink_DualActive("mod %s using option %d", pEntityName, option);
  387. ErrorCodeEnum configRc = Error_Bug;
  388. //主用地址
  389. CSimpleStringA strServer1 = "";
  390. int nServer1Port = 0;
  391. if (mainServ.IsNullOrEmpty())
  392. {
  393. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("read Main::Server config fail, %s", pEntityName);
  394. }
  395. else {
  396. if (Error_Succeed != (configRc = ParseIPAddress(mainServ.GetData(), strServer1, nServer1Port)))
  397. {
  398. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("parse Main ip addr fail: %s, %d", mainServ.GetData(), configRc);
  399. }
  400. else {
  401. if (Connect(strServer1, nServer1Port, option)) {
  402. connectInfo.setParam(pEntityName, strServer1.GetData(), nServer1Port, "", 0, -1, 0);//主机连接上
  403. setConnectInfo(&connectInfo);
  404. DbgWithLink_DualActive("Standby Connection: EntityName:%s, server:%s %d, serverBackup:%s %d, DualOpen: %d, currentLink:%d", connectInfo.m_EntityName, connectInfo.m_ServerIP,
  405. connectInfo.m_ServerPort, connectInfo.m_Server_BackupIP, connectInfo.m_Server_BackupPort, connectInfo.m_DualActive, connectInfo.m_currentLink);
  406. connectedServ = mainServ;
  407. return true;
  408. }
  409. }
  410. }
  411. //备用地址
  412. CSimpleStringA strServer2 = "";
  413. int nServer2Port = 0;
  414. for (int i = 0; i < backupServArr.GetCount(); i++)
  415. {
  416. CSimpleStringA backupSerStr = backupServArr[i];
  417. if (!backupSerStr.IsNullOrEmpty()) {
  418. if (Error_Succeed != (configRc = ParseIPAddress(backupSerStr.GetData(), strServer2, nServer2Port)))
  419. {
  420. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("parse backup ip addr fail: %s, %d", backupSerStr.GetData(), configRc);
  421. }
  422. else {
  423. if (Connect(strServer2, nServer2Port, option)) {
  424. connectInfo.setParam(pEntityName, strServer1.GetData(), nServer1Port, strServer2.GetData(), nServer2Port, -1, 1);//备机连接上
  425. setConnectInfo(&connectInfo);
  426. DbgWithLink_DualActive("Standby Connection: EntityName:%s, server:%s %d, serverBackup:%s %d, DualOpen: %d, currentLink:%d", connectInfo.m_EntityName, connectInfo.m_ServerIP,
  427. connectInfo.m_ServerPort, connectInfo.m_Server_BackupIP, connectInfo.m_Server_BackupPort, connectInfo.m_DualActive, connectInfo.m_currentLink);
  428. connectedServ = backupSerStr;
  429. return true;
  430. }
  431. }
  432. }
  433. }
  434. return false;
  435. }
  436. bool SpSecureClient::IsConnectionOK()
  437. {
  438. return GetFunction()->IsConnectionOK();
  439. }
  440. bool SpSecureClient::IsSecureConn()
  441. {
  442. return GetFunction()->IsSecureConnection();
  443. }
  444. void SpSecureClient::Close()
  445. {
  446. if (!m_bClosed)
  447. {
  448. m_bClosed = true;
  449. GetFunction()->Close();
  450. //clear the connect Info
  451. connectClose(m_pEntity->GetEntityName());
  452. DbgWithLink_DualActive("%s closed", m_pEntity->GetEntityName());
  453. }
  454. }
  455. string SpSecureClient::SendPackage(const CSmartPointer<IPackage>& pSendPkg)
  456. {
  457. return GetFunction()->SendPackage(pSendPkg);
  458. }
  459. CSmartPointer<IPackage> SpSecureClient::ReceivePackage(int nWaitSecond)
  460. {
  461. return GetFunction()->ReceivePackage(nWaitSecond);
  462. }
  463. CSmartPointer<IPackage> SpSecureClient::CreateNewPackage(const char *pServiceCode)
  464. {
  465. return GetFunction()->CreateNewPackage(pServiceCode);
  466. }
  467. CSmartPointer<IPackage> SpSecureClient::CreateReplyPackage(const CSmartPointer<IPackage>& pRecvPkg)
  468. {
  469. return GetFunction()->CreateReplyPackage(pRecvPkg);
  470. }
  471. void SpSecureClient::OnErrorMsg(DWORD dwSysCode, DWORD dwUserCode, const CSimpleStringA &pErrMsg)
  472. {
  473. // 切换到实体线程执行
  474. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("SpSecureClient error: %s", (const char*)pErrMsg);
  475. }
  476. void SpSecureClient::OnDisconnect()
  477. {
  478. DbgWithLink_DualActive("Entity %s OnDisconnect", m_pEntity->GetEntityName());
  479. }
  480. void SpSecureClient::OnReConnect()
  481. {
  482. if (!IsConnectionOK())
  483. {//可能OnDisconnect被重载,已重新连接
  484. DbgWithLink_DualActive("Entity %s disconnect, try to reconnect", m_pEntity->GetEntityName());
  485. ConnectFromCentralSetting();
  486. }
  487. }
  488. struct OnPackageTask : public ITaskSp
  489. {
  490. OnPackageTask(SpSecureClient *pClient, IPackage* pkg)
  491. :m_pSecureClient(pClient), m_pPackage(pkg)
  492. {}
  493. SpSecureClient *m_pSecureClient;
  494. IPackage * m_pPackage;
  495. virtual void Process()
  496. {
  497. TOOLKIT_ASSERT(m_pPackage != NULL);
  498. CSmartPointer<IPackage> ptr;
  499. ptr.Attach(m_pPackage);
  500. m_pSecureClient->OnPkgAnswer(ptr);
  501. m_pSecureClient->DecRefCount();
  502. }
  503. };
  504. struct OnDisconnectTask : public ITaskSp
  505. {
  506. OnDisconnectTask(SpSecureClient *pClient)
  507. :m_pSecureClient(pClient)
  508. {}
  509. SpSecureClient *m_pSecureClient;
  510. virtual void Process()
  511. {
  512. m_pSecureClient->Close();
  513. m_pSecureClient->OnDisconnect();
  514. m_pSecureClient->DecRefCount();
  515. //m_pSecureClient->OnReConnect();
  516. }
  517. };
  518. struct OnErrorTask : public ITaskSp
  519. {
  520. OnErrorTask(SpSecureClient *pClient, DWORD dwSysCode, DWORD dwUserCode, const char *pMsg)
  521. :m_pSecureClient(pClient), m_dwSysCode(dwSysCode), m_dwUserCode(dwUserCode), m_strErrMsg(pMsg)
  522. {}
  523. SpSecureClient *m_pSecureClient;
  524. DWORD m_dwSysCode;
  525. DWORD m_dwUserCode;
  526. CSimpleStringA m_strErrMsg;
  527. virtual void Process()
  528. {
  529. m_pSecureClient->OnErrorMsg(m_dwSysCode, m_dwUserCode, m_strErrMsg);
  530. m_pSecureClient->DecRefCount();
  531. }
  532. };
  533. void SpSecureClient::OnReceivePackage(CSmartPointer<IPackage> &pRecvPkg)
  534. {
  535. // 切换到实体线程执行
  536. OnPackageTask *pTask = new OnPackageTask(this, pRecvPkg.Detach());
  537. IncRefCount();
  538. m_pEntity->GetFunction()->PostEntityTaskFIFO(pTask);
  539. }
  540. void SpSecureClient::OnClose()
  541. {
  542. // 切换到实体线程执行
  543. OnDisconnectTask *pTask = new OnDisconnectTask(this);
  544. IncRefCount();
  545. m_pEntity->GetFunction()->PostEntityTaskFIFO(pTask);
  546. }
  547. void SpSecureClient::OnError(DWORD dwSysCode, DWORD dwUserCode, const char *pErrMsg)
  548. {
  549. // 切换到实体线程执行
  550. OnErrorTask *pTask = new OnErrorTask(this, dwSysCode, dwUserCode, pErrMsg);
  551. IncRefCount();
  552. m_pEntity->GetFunction()->PostEntityTaskFIFO(pTask);
  553. }
  554. void SpSecureClient::OnAuthPass()
  555. {
  556. }
  557. bool SpSecureClient::OnAuthRequestSM(CConnAuthSMReq* pReq)
  558. {
  559. ErrorCodeEnum Error = Error_Unexpect;
  560. CSystemStaticInfo si;
  561. m_pEntity->GetFunction()->GetSystemStaticInfo(si);
  562. CVerifyInfo info;
  563. memset(&info, 0, sizeof(info));
  564. strncpy(info.m_arrTerminalNo, (LPCSTR)si.strTerminalID, sizeof(info.m_arrTerminalNo) - 1);
  565. strcpy(info.m_arrServiceType, "CMBRVC");
  566. {
  567. //TODO: CrossPlaform 框架具备统一支持,但不清楚影响范围(继而无法评估测试范围),未敢轻易改动 [Gifur@2025730]
  568. #ifdef RVC_OS_LINUX
  569. char buf[512];
  570. toolkit_interface_address_t* addr;
  571. int count, i, aim = -1, backup = -1, third=-1;
  572. toolkit_interface_addresses(&addr, &count);
  573. i = count;
  574. WLog_DBG(TAG, "Number of interfaces: %d", count);
  575. while (i--) {
  576. toolkit_interface_address_t interface = addr[i];
  577. WLog_DBG(TAG, "Name: %s", interface.name);
  578. WLog_DBG(TAG, "Internal? %s", interface.is_internal ? "Yes" : "No");
  579. if (interface.address.address4.sin_family == AF_INET) {
  580. third = i;
  581. toolkit_ip4_name(&interface.address.address4, buf, sizeof(buf));
  582. WLog_DBG(TAG, "IPv4 address: %s", buf);
  583. CSimpleStringA s(buf);
  584. if (s.IsStartWith("99.") || s.IsStartWith("10.")) {
  585. aim = i;
  586. break;
  587. }
  588. if (!interface.is_internal && backup != -1) {
  589. backup = i;
  590. }
  591. } else if (interface.address.address4.sin_family == AF_INET6) {
  592. toolkit_ip6_name(&interface.address.address6, buf, sizeof(buf));
  593. WLog_DBG(TAG, "IPv6 address: %s", buf);
  594. }
  595. }
  596. if (aim == -1 && backup != -1) {
  597. aim = backup;
  598. }
  599. if (aim == -1 && third != -1)
  600. aim = third;
  601. memset(info.m_arrIP, 0, sizeof(info.m_arrIP));
  602. if (aim != -1) {
  603. char ipStr[32];
  604. int b1, b2, b3, b4;
  605. b1 = b2 = b3 = b4 = 0;
  606. toolkit_ip4_name(&addr[aim].address.address4, ipStr, sizeof(ipStr));
  607. WLog_DBG(TAG, "specified local ip: %s", ipStr);
  608. sscanf(ipStr, "%d.%d.%d.%d", &b1, &b2, &b3, &b4);
  609. info.m_arrIP[0] = (BYTE)b1;
  610. info.m_arrIP[1] = (BYTE)b2;
  611. info.m_arrIP[2] = (BYTE)b3;
  612. info.m_arrIP[3] = (BYTE)b4;
  613. }
  614. toolkit_free_interface_addresses(addr, count);
  615. #else
  616. hostent* ent = _gethostbyname(NULL);
  617. WLog_DBG(TAG, "_gethostbyname finished ");
  618. if (ent && ent->h_addr_list[0] != NULL) {
  619. int i = 0;
  620. WLog_DBG(TAG, "office hostname: %s", ent->h_name);
  621. for (; ent->h_addr_list[i] != NULL; ++i) {
  622. struct in_addr* in = (struct in_addr*)ent->h_addr_list[i];
  623. if (in->S_un.S_un_b.s_b1 == 99 || in->S_un.S_un_b.s_b1 == 10)
  624. break;
  625. }
  626. if (ent->h_addr_list[i] == NULL)
  627. i = 0;
  628. auto in = (struct in_addr*)ent->h_addr_list[i];
  629. info.m_arrIP[0] = in->S_un.S_un_b.s_b1;
  630. info.m_arrIP[1] = in->S_un.S_un_b.s_b2;
  631. info.m_arrIP[2] = in->S_un.S_un_b.s_b3;
  632. info.m_arrIP[3] = in->S_un.S_un_b.s_b4;
  633. }
  634. #endif //RVC_OS_LINUX
  635. }
  636. if(pReq != NULL)
  637. {
  638. // call token service to encrypt verify info
  639. TokenService_ClientBase* client = new TokenService_ClientBase(m_pEntity);
  640. Error = client->Connect();
  641. if (Error == Error_Succeed)
  642. {
  643. TokenService_EncryptWithPubKey_Req Req;
  644. TokenService_EncryptWithPubKey_Ans Ans;
  645. Req.raw_data.m_pData = (char*)&info;
  646. Req.raw_data.m_iLength = sizeof(info); //28
  647. Error = client->EncryptWithPubKey(Req, Ans, -1);
  648. if (Error != Error_Succeed) {
  649. LOG_TRACE("EncryptWithPriKey for VerifyInfo failed! Error = %s", SpStrError(Error));
  650. } else {
  651. memcpy_s(pReq->m_arrVerifyInfo, sizeof(pReq->m_arrVerifyInfo), Ans.enc_data.m_pData, Ans.enc_data.m_iLength);
  652. // get token
  653. TokenService_GetToken_Req Req1;
  654. TokenService_GetToken_Ans Ans1;
  655. Error = client->GetToken(Req1, Ans1, -1);
  656. if (Error != Error_Succeed) {
  657. LOG_TRACE("GetToken for VerifyInfo failed! Error = %s", SpStrError(Error));
  658. }
  659. else {
  660. memcpy_s(pReq->m_arrVerifyToken, sizeof(pReq->m_arrVerifyToken), Ans1.token.m_pData, Ans1.token.m_iLength);
  661. }
  662. }
  663. client->GetFunction()->CloseSession();
  664. }
  665. else {
  666. LOG_TRACE("connect to tokenservice failed! Error = %s", SpStrError(Error));
  667. client->SafeDelete();
  668. }
  669. }
  670. return Error == Error_Succeed;
  671. }
  672. bool SpSecureClient::OnSessionKeyRet(CConnAuthRet *pRet, BYTE *pBuf, int *pBufLen)
  673. {
  674. memset(pBuf, 0, *pBufLen);
  675. TokenService_ClientBase *client = new TokenService_ClientBase(m_pEntity);
  676. ErrorCodeEnum Error = client->Connect();
  677. if (Error == Error_Succeed)
  678. {
  679. TokenService_DecryptWithPriKey_Req Req;
  680. TokenService_DecryptWithPriKey_Ans Ans;
  681. Req.enc_data.m_pData = (char*)&pRet->m_arrEncSessionKey[0];
  682. Req.enc_data.m_iLength = sizeof(pRet->m_arrEncSessionKey);
  683. Error = client->DecryptWithPriKey(Req, Ans, -1);
  684. if (Error == Error_Succeed)
  685. {
  686. memcpy_s(pBuf, *pBufLen, Ans.raw_data.m_pData, Ans.raw_data.m_iLength);
  687. *pBufLen = Ans.raw_data.m_iLength;
  688. } else {
  689. *pBufLen = 0;
  690. LOG_TRACE("OnSessionKey decrypt session key failed! Error = %s", SpStrError(Error));
  691. }
  692. client->GetFunction()->CloseSession();
  693. } else {
  694. LOG_TRACE("connect to tokenservice failed! Error = %s", SpStrError(Error));
  695. client->SafeDelete();
  696. }
  697. return Error == Error_Succeed;
  698. }
  699. bool SpSecureClient::OnSessionKeySMRet(CConnAuthSMRet* pRet, BYTE* pBuf, int* pBufLen)
  700. {
  701. memset(pBuf, 0, *pBufLen);
  702. TokenService_ClientBase* client = new TokenService_ClientBase(m_pEntity);
  703. ErrorCodeEnum Error = client->Connect();
  704. if (Error == Error_Succeed)
  705. {
  706. TokenService_DecryptWithPriKey_Req Req;
  707. TokenService_DecryptWithPriKey_Ans Ans;
  708. Req.enc_data.m_pData = (char*)&pRet->m_arrEncSessionKey[0];
  709. Req.enc_data.m_iLength = sizeof(pRet->m_arrEncSessionKey);
  710. Error = client->DecryptWithPriKey(Req, Ans, -1);
  711. if (Error == Error_Succeed)
  712. {
  713. memcpy_s(pBuf, *pBufLen, Ans.raw_data.m_pData, Ans.raw_data.m_iLength);
  714. *pBufLen = Ans.raw_data.m_iLength;
  715. }
  716. else {
  717. *pBufLen = 0;
  718. LOG_TRACE("OnSessionKey decrypt session key failed! Error = %s", SpStrError(Error));
  719. }
  720. client->GetFunction()->CloseSession();
  721. } else {
  722. LOG_TRACE("connect to tokenservice failed! Error = %s", SpStrError(Error));
  723. client->SafeDelete();
  724. }
  725. return Error == Error_Succeed;
  726. }
  727. bool SpSecureClient::OnGetSharedSK(char *pTerminalNo, int *pTerminalNoLen, BYTE *pBuf, int *pBufLen)
  728. {
  729. #ifdef RVC_OS_WIN
  730. ErrorCodeEnum Error = Error_Unexpect;
  731. CSystemStaticInfo si;
  732. {
  733. m_pEntity->GetFunction()->GetSystemStaticInfo(si);
  734. }
  735. TOOLKIT_ASSERT(si.strTerminalID.GetLength() <= *pTerminalNoLen);
  736. strcpy(pTerminalNo, (LPCSTR)si.strTerminalID);
  737. *pTerminalNoLen = strlen(pTerminalNo);
  738. {
  739. TokenService_ClientBase *client = new TokenService_ClientBase(m_pEntity);
  740. Error = client->Connect();
  741. if (Error == Error_Succeed) {
  742. TokenService_GetSharedSK_Req Req;
  743. TokenService_GetSharedSK_Ans Ans;
  744. Error = client->GetSharedSK(Req, Ans, 10000);
  745. if (Error == Error_Succeed) {
  746. memcpy_s(pBuf, *pBufLen, Ans.ssk.m_pData, Ans.ssk.m_iLength);
  747. *pBufLen = Ans.ssk.m_iLength;
  748. } else {
  749. *pBufLen = 0;
  750. LOG_TRACE("OnSessionKey decrypt session key failed! Error = %s", SpStrError(Error));
  751. }
  752. client->GetFunction()->CloseSession();
  753. } else {
  754. LOG_TRACE("connect to tokenservice failed! Error = %s", SpStrError(Error));
  755. client->SafeDelete();
  756. }
  757. }
  758. return Error == Error_Succeed;
  759. #else
  760. return false;
  761. #endif //_MSC_VER
  762. }
  763. ErrorCodeEnum SpSecureClient::ParseIPAddress(const char *str, CSimpleStringA &ip, int &port)
  764. {
  765. ErrorCodeEnum Error = Error_Unexpect;
  766. if (str) {
  767. char tmp1[32] = {};
  768. char tmp2[16] = {};
  769. sscanf(str, "%s %s", tmp1, tmp2);
  770. if (tmp1[0] != 0 && tmp2[0] != 0)
  771. {
  772. ip = tmp1;
  773. port = atoi(tmp2);
  774. Error = Error_Succeed;
  775. }
  776. else
  777. return Error;
  778. }
  779. return Error;
  780. }
  781. DWORD SpSecureClient::GetEntityUserCode(DWORD code)
  782. {
  783. TOOLKIT_ASSERT(m_pEntity != NULL);
  784. auto pEnv = sp_get_env();
  785. TOOLKIT_ASSERT(pEnv != NULL);
  786. auto pCfg = pEnv->cfg;
  787. TOOLKIT_ASSERT(pCfg != NULL);
  788. auto pEntity = sp_cfg_get_entity_by_name(pCfg, m_pEntity->GetEntityName());
  789. TOOLKIT_ASSERT(pEntity != NULL);
  790. DWORD dwDevelopID = pEntity->devel_id;
  791. return (dwDevelopID << 20 | code);
  792. }