SpSecureClient.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. #include "SpSecureClient.h"
  2. #include "sp_cfg.h"
  3. #include "sp_env.h"
  4. #include "spShareMemoryBase.h"
  5. #include "sp_checkEntity.h"
  6. #include "TokenKeeper_client_g.h"
  7. using namespace TokenKeeper;
  8. //#include "..\..\Module\mod_centersetting\CenterSetting_client_g.h"
  9. //using namespace CenterSetting ;
  10. enum CommEventEnum
  11. {
  12. //连接主用地址 事件 1 0xNNN08001 连接配置文件定义的主用地址,需要记录地址信息。如果为短连接,记录首次连接事件。
  13. CE_ConnectMasterServer = 0x00008001,
  14. //连接备用地址 事件 1 0xNNN08002 如果没有定义备用地址,就不会有这条信息
  15. CE_ConnectSlaveServer = 0x00008002,
  16. //主动断开连接 事件 1 0xNNN08011 如果为短连接,无需记录此事件
  17. CE_ActiveClose = 0x00008011,
  18. //读取配置失败 错误 3 0xNNN08021 不能读到需要配置项,代码或配置有误,可以切换备份区域,或需要人干预
  19. CE_ReadCfgFail = 0x00008021,
  20. //连接地址无效 错误 2 0xNNN88031 对端不存在,配置错误,或当前服务器故障
  21. CE_InvalidAddr = 0x00088031,
  22. //对端拒绝连接 错误 2 0xNNN88032 对端存在,但可能故障,导致服务器拒绝建立连接
  23. CE_PeerReject = 0x00088032,
  24. //连接超时 错误 2 0xNNN88033 等待连接超时
  25. CE_ConnectTimeout = 0x00088033,
  26. //容量拒绝 错误 2 0xNNN88034 由于达到后台的最大容量,连接拒绝,需要重试
  27. CE_ReachMaxNum = 0x00088034,
  28. //服务暂停 错误 2 0xNNN88035 后台暂停服务,实体可以切换主备服务或抛出连接失败,切换备份区域
  29. CE_OutOfService = 0x00088035,
  30. //失去连接 错误 2 0xNNN88036 由于对端或网络原因连接断开
  31. CE_LostConnection = 0x00088036,
  32. //无效请求包 错误 3 0xNNN88041 实体或后台代码错误,需要进行人工修复。在描述中应该说明错误的原因。
  33. CE_InvalidReqPack = 0x00088041,
  34. //鉴权不可识别 错误 3 0xNNN88051 由于服务准入服务证书不符,不能解开请求包,错误需要干预,不能自动修复。
  35. CE_AuthFailed = 0x00088051,
  36. //鉴权信息不匹配 错误 2 0xNNN88052 请求时鉴权信息不匹配,需要重新进行准入。
  37. CE_HashMismatch = 0x00088052,
  38. //当前区域连接失败 事件 2 0xNNN880F1 由于多次尝试失败,或发生不可尝试错误,实体放弃了当前区域连接尝试,用于驱动状态切换。记录区域代码。
  39. CE_CurRegionDisabled = 0x000880F1,
  40. };
  41. // 不应该直接delete,而用DecRef()
  42. SpSecureClient::~SpSecureClient()
  43. {
  44. }
  45. SpSecureClient::SpSecureClient(CEntityBase *pEntityBase)
  46. : m_pEntity(pEntityBase), m_bClosed(true)
  47. {
  48. //Dbg("SpSecureClient");
  49. }
  50. bool SpSecureClient::Connect(const char *pServerAddr, int nPort, int nOption) // wait until all authentication operation has been finished
  51. {
  52. assert(m_pEntity != NULL);
  53. bool result = false;
  54. if (GetFunction()->Connect(pServerAddr, nPort, nOption))
  55. {
  56. m_bClosed = false;
  57. result = true;
  58. }
  59. else
  60. result = false;
  61. Dbg("connect to %s:%d, option=%d, result:%s", pServerAddr, nPort, nOption, result ? "SUCCESS" : "FAIL");
  62. return result;
  63. }
  64. // 使用配置项连接, 连接参数从实体配置文件中读取 [Main]/Server和[Main]/Server_Backup项
  65. // @option:1、重新鉴权新建会话密钥;2、通过握手使用缓存会话密钥;
  66. // 3、不使用会话密钥,即非安全通道; 4、不协商,直接使用共享会话密钥
  67. bool SpSecureClient::ConnectFromConfig(int nOption)
  68. {
  69. if (IsConnectionOK())
  70. return true;
  71. const char* pEntityName = m_pEntity->GetEntityName();
  72. ENTITY_CONNECT_INFO connectInfo;
  73. if (!readConnectInfoFromConfig(pEntityName, &connectInfo))
  74. {
  75. Dbg("Read %s Info Failed", pEntityName);
  76. return false;
  77. }
  78. // 判断当前是否已经准入,已准入时强制使用加密通道
  79. int nActOption = nOption;
  80. CSimpleStringA strVal;
  81. m_pEntity->GetFunction()->GetSysVar("EntryPermit", strVal);
  82. if (strVal == "L" && stricmp(pEntityName, "AccessAuthorization") != 0 && stricmp(pEntityName, "Initializer") != 0)
  83. nActOption = 2; // 优先使用缓存密钥
  84. if (1 == connectInfo.m_DualActive)
  85. return Connect_Dual(&connectInfo, nOption);
  86. else
  87. return Connect_Single(&connectInfo, nOption);
  88. }
  89. bool SpSecureClient::readConnectInfoFromConfig(const char *pEntityName, ENTITY_CONNECT_INFO *connectInfo)
  90. {
  91. if (NULL == pEntityName || NULL == connectInfo)
  92. return false;
  93. connectControl *entityConnect = connectControl::getInstance();
  94. bool readSuccess = entityConnect->getEntityInfo(pEntityName, connectInfo);
  95. auto pFunc = m_pEntity->GetFunction();
  96. CSmartPointer<IConfigInfo> spConfig;
  97. if (Error_Succeed != pFunc->OpenConfig(Config_CenterSetting, spConfig))
  98. {
  99. Dbg("open center setting config fail");
  100. return false;
  101. }
  102. CSimpleStringA str;
  103. int readEach = 0;
  104. if (Error_Succeed == spConfig->ReadConfigValue("SpBase", "ReadEach", str) && !str.IsNullOrEmpty())
  105. readEach = atoi(str);
  106. if (0 == readEach && readSuccess)
  107. return true;//不是每次都读取新的Entity的IP和Port,只在实体启动时读取一次
  108. int dualActive = -1;
  109. if (Error_Succeed == spConfig->ReadConfigValue("SpBase", "DualActive", str) && !str.IsNullOrEmpty())
  110. dualActive = atoi(str);
  111. if (Error_Succeed != pFunc->OpenConfig(Config_Software, spConfig))
  112. {
  113. Dbg("open entity config fail");
  114. return false;
  115. }
  116. if (Error_Succeed != spConfig->ReadConfigValue("Main", "Server", str) || str.IsNullOrEmpty())
  117. {
  118. Dbg("read Main::Server config fail");
  119. return false;
  120. }
  121. CSimpleStringA strServer1;
  122. int nServer1Port;
  123. if (Error_Succeed != ParseIPAddress(str, strServer1, nServer1Port))
  124. {
  125. Dbg("parse ip addr fail: %s", (const char*)str);
  126. return false;
  127. }
  128. CSimpleStringA strServer2;
  129. int nServer2Port = 0;
  130. if (Error_Succeed == spConfig->ReadConfigValue("Main", "Server_Backup", str) && !str.IsNullOrEmpty())
  131. ParseIPAddress(str, strServer2, nServer2Port);
  132. if (readSuccess)
  133. connectInfo->setParam(pEntityName, strServer1.GetData(), nServer1Port, strServer2.GetData(), nServer2Port, dualActive, connectInfo->m_currentLink);
  134. else
  135. {
  136. connectInfo->clear();
  137. connectInfo->setParam(pEntityName, strServer1.GetData(), nServer1Port, strServer2.GetData(), nServer2Port, dualActive);
  138. }
  139. entityConnect->setEntityInfo(connectInfo);
  140. return true;
  141. }
  142. void SpSecureClient::connectClose(const char *pEntityName)
  143. {
  144. if (NULL == pEntityName)
  145. return;
  146. ENTITY_CONNECT_INFO connectInfo;
  147. if (!findConnectInfo(pEntityName, &connectInfo))
  148. {
  149. m_log.LOGERROR("can note find %s in connection list.", pEntityName);
  150. return;
  151. }
  152. connectInfo.m_currentLink = -1;
  153. }
  154. bool SpSecureClient::findConnectInfo(const char *pEntityName, ENTITY_CONNECT_INFO *connectInfo)
  155. {
  156. if (NULL == pEntityName || NULL == connectInfo)
  157. return false;
  158. connectControl *entityConnect = connectControl::getInstance();
  159. if (entityConnect->getEntityInfo(pEntityName, connectInfo))
  160. return true;
  161. return false;
  162. }
  163. bool SpSecureClient::readConnectInfoFromCentralSetting(const char *pEntityName, ENTITY_CONNECT_INFO *connectInfo)
  164. {
  165. if (NULL == pEntityName || NULL == connectInfo)
  166. return false;
  167. connectControl *entityConnect = connectControl::getInstance();
  168. bool readSuccess = entityConnect->getEntityInfo(pEntityName, connectInfo);
  169. //获得集中配置信息
  170. auto pFunc = m_pEntity->GetFunction();
  171. CSmartPointer<IConfigInfo> spConfig;
  172. if (Error_Succeed != pFunc->OpenConfig(Config_CenterSetting, spConfig))
  173. {
  174. Dbg("open center setting config fail");
  175. return false;
  176. }
  177. CSimpleStringA str;
  178. int readEach = 1;
  179. if (Error_Succeed == spConfig->ReadConfigValue("SpBase", "ReadEach", str) && !str.IsNullOrEmpty())
  180. readEach = atoi(str);
  181. if (0 == readEach && readSuccess)
  182. return true;//不是每次都读取新的Entity的IP和Port,只在实体启动时读取一次
  183. if (Error_Succeed != spConfig->ReadConfigValue(pEntityName, "Server", str) || str.IsNullOrEmpty())
  184. {
  185. Dbg("read Main::Server config fail");
  186. return false;
  187. }
  188. CSimpleStringA strServer1;
  189. int nServer1Port;
  190. if (Error_Succeed != ParseIPAddress(str, strServer1, nServer1Port))
  191. {
  192. Dbg("parse ip addr fail: %s", (const char*)str);
  193. return false;
  194. }
  195. CSimpleStringA strServer2 = "";
  196. int nServer2Port = 0;
  197. if (Error_Succeed == spConfig->ReadConfigValue(pEntityName, "Server_Backup", str) && !str.IsNullOrEmpty())
  198. ParseIPAddress(str, strServer2, nServer2Port);
  199. int dualActive = -1;
  200. if (Error_Succeed == spConfig->ReadConfigValue("SpBase", "DualActive", str) && !str.IsNullOrEmpty())
  201. dualActive = atoi(str);
  202. if (readSuccess)
  203. connectInfo->setParam(pEntityName, strServer1.GetData(), nServer1Port, strServer2.GetData(), nServer2Port, dualActive, connectInfo->m_currentLink);
  204. else
  205. {
  206. //m_log.LOGERROR("call clear");
  207. connectInfo->clear();
  208. connectInfo->setParam(pEntityName, strServer1.GetData(), nServer1Port, strServer2.GetData(), nServer2Port, dualActive);
  209. }
  210. entityConnect->setEntityInfo(connectInfo);
  211. return true;
  212. }
  213. bool SpSecureClient::setConnectInfo(const ENTITY_CONNECT_INFO *connectInfo)
  214. {
  215. if (NULL == connectInfo)
  216. return false;
  217. connectControl *entityConnect = connectControl::getInstance();
  218. entityConnect->setLastLink(connectInfo->m_currentLink);
  219. return entityConnect->setEntityInfo(connectInfo);
  220. }
  221. // 使用集中配置项连接
  222. bool SpSecureClient::ConnectFromCentralSetting()
  223. {
  224. SetthreadGroup(GetCurrentThreadId(), m_pEntity->GetEntityName());
  225. if (IsConnectionOK())
  226. return true;
  227. const char* pEntityName = m_pEntity->GetEntityName();
  228. ENTITY_CONNECT_INFO connectInfo;
  229. if (!readConnectInfoFromCentralSetting(pEntityName, &connectInfo))
  230. {
  231. Dbg("Read %s Info Failed", pEntityName);
  232. m_log.LOGERROR("Read %s Info Failed", pEntityName);
  233. return false;
  234. }
  235. // 判断当前是否已经准入,已经准入则强制使用安全连接
  236. int nOption = 3;
  237. CSimpleStringA strVal;
  238. m_pEntity->GetFunction()->GetSysVar("EntryPermit", strVal);
  239. if (strVal == "L" && stricmp(pEntityName, "AccessAuthorization") != 0 && stricmp(pEntityName, "Initializer") != 0)
  240. nOption = 2; // 优先使用缓存密钥
  241. //Dbg("connect using center setting");
  242. if (1 == connectInfo.m_DualActive)
  243. return Connect_Dual(&connectInfo, nOption);
  244. else
  245. return Connect_Single(&connectInfo, nOption);
  246. }
  247. int SpSecureClient::getCurrentLink()
  248. {
  249. if (!IsConnectionOK())
  250. return -1;
  251. const char* pEntityName = m_pEntity->GetEntityName();
  252. ENTITY_CONNECT_INFO connectInfo;
  253. if (!readConnectInfoFromCentralSetting(pEntityName, &connectInfo))
  254. {
  255. Dbg("Read %s Info Failed", pEntityName);
  256. return -1;
  257. }
  258. return connectInfo.m_currentLink;
  259. }
  260. bool SpSecureClient::Connect_Single(ENTITY_CONNECT_INFO *connectInfo, int option)
  261. {
  262. if (NULL == connectInfo || 0 == strlen(connectInfo->m_EntityName))
  263. return false;
  264. Dbg("mod %s using option %d", connectInfo->m_EntityName, option);
  265. if (Connect(connectInfo->m_ServerIP, connectInfo->m_ServerPort, option))
  266. connectInfo->m_currentLink = 0;
  267. else if (0 != strlen(connectInfo->m_Server_BackupIP) && strcmp(connectInfo->m_ServerIP, connectInfo->m_Server_BackupIP)
  268. && Connect(connectInfo->m_Server_BackupIP, connectInfo->m_Server_BackupPort, option))
  269. connectInfo->m_currentLink = 1;
  270. else
  271. connectInfo->m_currentLink = -1;
  272. setConnectInfo(connectInfo);
  273. m_log.LOGERROR("Single Connection: EntityName:%s, server:%s %d, serverBackup:%s %d, DualOpen: %d, currentLink:%d", connectInfo->m_EntityName, connectInfo->m_ServerIP,
  274. connectInfo->m_ServerPort, connectInfo->m_Server_BackupIP, connectInfo->m_Server_BackupPort, connectInfo->m_DualActive, connectInfo->m_currentLink);
  275. return -1 != connectInfo->m_currentLink;
  276. }
  277. bool SpSecureClient::Connect_Dual(ENTITY_CONNECT_INFO *connectInfo, int option)
  278. {
  279. if (NULL == connectInfo || 0 == strlen(connectInfo->m_EntityName))
  280. return false;
  281. connectControl *entityConnect = connectControl::getInstance();
  282. bool quickConnect = false;
  283. int priorLink = entityConnect->getPriorLink(connectInfo->m_lastLink);
  284. if (-1 != priorLink)
  285. {
  286. /*
  287. 根据上次双活成功时的server进行连接
  288. */
  289. m_log.LOGERROR("lastLink:%d", connectInfo->m_lastLink);
  290. if (0 == priorLink && 0 != strlen(connectInfo->m_ServerIP))
  291. connectInfo->m_currentLink = (Connect(connectInfo->m_ServerIP, connectInfo->m_ServerPort, option) ? 0 : -1);
  292. else if (1 == priorLink && 0 != strlen(connectInfo->m_Server_BackupIP))
  293. connectInfo->m_currentLink = (Connect(connectInfo->m_Server_BackupIP, connectInfo->m_Server_BackupPort, option) ? 1 : -1);
  294. quickConnect = (-1 == connectInfo->m_currentLink ? false : true);
  295. m_log.LOGERROR("lastLink:%d,currentLink:%d", connectInfo->m_lastLink, connectInfo->m_currentLink);
  296. }
  297. if (!IsConnectionOK())
  298. {
  299. /*
  300. 根据终端号进行连接
  301. */
  302. //获取终端号,判断优先连接的IP和端口
  303. auto pFunc = m_pEntity->GetFunction();
  304. CSmartPointer<IConfigInfo> spConfig;
  305. auto rc = pFunc->OpenConfig(Config_Root, spConfig);
  306. if (rc != Error_Succeed)
  307. {
  308. Dbg("read root.ini Fail\r\n");
  309. return false;
  310. }
  311. CSimpleStringA strValue;
  312. spConfig->ReadConfigValue("Terminal", "TerminalNo", strValue);
  313. bool isMainServer = true;
  314. if (strValue.GetLength() > 0)
  315. {
  316. char str[20] = "";
  317. sprintf(str, "%s", strValue);
  318. isMainServer = (0 == ((str[strlen(str) - 1] - '0') % 2));
  319. m_log.LOGERROR("lastByte:%s, %d, MainServer:%d", str, str[strlen(str) - 1] - '0', isMainServer);
  320. }
  321. Dbg("mod %s using option %d", connectInfo->m_EntityName, option);
  322. if (0 == strlen(connectInfo->m_Server_BackupIP) && 0 == strlen(connectInfo->m_ServerIP))
  323. connectInfo->m_currentLink = -1;
  324. else if (0 == strlen(connectInfo->m_Server_BackupIP))
  325. {//serverBackup Ip and port error, link to server
  326. connectInfo->m_currentLink = (Connect(connectInfo->m_ServerIP, connectInfo->m_ServerPort, option) ? 0 : -1);//Link to first one
  327. m_log.LOGERROR("%s serverBackup param error", connectInfo->m_EntityName);
  328. }
  329. else
  330. {
  331. if (isMainServer)
  332. {//link to first server
  333. if (Connect(connectInfo->m_ServerIP, connectInfo->m_ServerPort, option))
  334. connectInfo->m_currentLink = 0;
  335. else if (strcmp(connectInfo->m_ServerIP, connectInfo->m_Server_BackupIP) && Connect(connectInfo->m_Server_BackupIP, connectInfo->m_Server_BackupPort, option))
  336. connectInfo->m_currentLink = 1;
  337. else
  338. connectInfo->m_currentLink = -1;
  339. }
  340. else
  341. {//link to second server
  342. m_log.LOGERROR("BackUp");
  343. if (Connect(connectInfo->m_Server_BackupIP, connectInfo->m_Server_BackupPort, option))
  344. connectInfo->m_currentLink = 1;
  345. else if (strcmp(connectInfo->m_ServerIP, connectInfo->m_Server_BackupIP) && Connect(connectInfo->m_ServerIP, connectInfo->m_ServerPort, option))
  346. connectInfo->m_currentLink = 0;
  347. else
  348. connectInfo->m_currentLink = -1;
  349. }
  350. }
  351. }
  352. /*
  353. 连接结束
  354. */
  355. char msg[1024];
  356. sprintf(msg, "%sDual Connection: EntityName:%s, server:%s %d, serverBackup:%s %d, DualOpen: %d, currentLink:%d, curEntityNum:%d", (quickConnect ? "quick " : ""),
  357. connectInfo->m_EntityName, connectInfo->m_ServerIP, connectInfo->m_ServerPort, connectInfo->m_Server_BackupIP,
  358. connectInfo->m_Server_BackupPort, connectInfo->m_DualActive, connectInfo->m_currentLink, entityConnect->getEntityNum());
  359. m_log.LOGERROR(msg);
  360. setConnectInfo(connectInfo);
  361. return -1 != connectInfo->m_currentLink;
  362. }
  363. bool SpSecureClient::IsConnectionOK()
  364. {
  365. return GetFunction()->IsConnectionOK();
  366. }
  367. bool SpSecureClient::IsSecureConn()
  368. {
  369. return GetFunction()->IsSecureConnection();
  370. }
  371. void SpSecureClient::Close()
  372. {
  373. if (!m_bClosed)
  374. {
  375. m_bClosed = true;
  376. GetFunction()->Close();
  377. //clear the connect Info
  378. connectClose(m_pEntity->GetEntityName());
  379. m_log.LOGERROR("%s closed", m_pEntity->GetEntityName());
  380. }
  381. }
  382. string SpSecureClient::SendPackage(const CSmartPointer<IPackage>& pSendPkg)
  383. {
  384. return GetFunction()->SendPackage(pSendPkg);
  385. }
  386. CSmartPointer<IPackage> SpSecureClient::ReceivePackage(int nWaitSecond)
  387. {
  388. return GetFunction()->ReceivePackage(nWaitSecond);
  389. }
  390. CSmartPointer<IPackage> SpSecureClient::CreateNewPackage(const char *pServiceCode)
  391. {
  392. return GetFunction()->CreateNewPackage(pServiceCode);
  393. }
  394. CSmartPointer<IPackage> SpSecureClient::CreateReplyPackage(const CSmartPointer<IPackage>& pRecvPkg)
  395. {
  396. return GetFunction()->CreateReplyPackage(pRecvPkg);
  397. }
  398. void SpSecureClient::OnErrorMsg(DWORD dwSysCode, DWORD dwUserCode, const CSimpleStringA &pErrMsg)
  399. {
  400. // 切换到实体线程执行
  401. Dbg("SpSecureClient error: %s", (const char*)pErrMsg);
  402. }
  403. void SpSecureClient::OnDisconnect()
  404. {
  405. Dbg("SpSecureClient disconnect");
  406. m_log.LOGERROR("Entity %s OnDisconnect", m_pEntity->GetEntityName());
  407. }
  408. void SpSecureClient::OnReConnect()
  409. {
  410. if (!IsConnectionOK())
  411. {//可能OnDisconnect被重载,已重新连接
  412. m_log.LOGERROR("Entity %s disconnect, try to reconnect", m_pEntity->GetEntityName());
  413. ConnectFromCentralSetting();
  414. }
  415. }
  416. struct OnPackageTask : public ITaskSp
  417. {
  418. OnPackageTask(SpSecureClient *pClient, IPackage* pkg)
  419. :m_pSecureClient(pClient), m_pPackage(pkg)
  420. {}
  421. SpSecureClient *m_pSecureClient;
  422. IPackage * m_pPackage;
  423. virtual void Process()
  424. {
  425. assert(m_pPackage != NULL);
  426. CSmartPointer<IPackage> ptr;
  427. ptr.Attach(m_pPackage);
  428. m_pSecureClient->OnPkgAnswer(ptr);
  429. m_pSecureClient->DecRefCount();
  430. }
  431. };
  432. struct OnDisconnectTask : public ITaskSp
  433. {
  434. OnDisconnectTask(SpSecureClient *pClient)
  435. :m_pSecureClient(pClient)
  436. {}
  437. SpSecureClient *m_pSecureClient;
  438. virtual void Process()
  439. {
  440. m_pSecureClient->Close();
  441. m_pSecureClient->OnDisconnect();
  442. m_pSecureClient->DecRefCount();
  443. m_pSecureClient->OnReConnect();
  444. }
  445. };
  446. struct OnErrorTask : public ITaskSp
  447. {
  448. OnErrorTask(SpSecureClient *pClient, DWORD dwSysCode, DWORD dwUserCode, const char *pMsg)
  449. :m_pSecureClient(pClient), m_dwSysCode(dwSysCode), m_dwUserCode(dwUserCode), m_strErrMsg(pMsg)
  450. {}
  451. SpSecureClient *m_pSecureClient;
  452. DWORD m_dwSysCode;
  453. DWORD m_dwUserCode;
  454. CSimpleStringA m_strErrMsg;
  455. virtual void Process()
  456. {
  457. m_pSecureClient->OnErrorMsg(m_dwSysCode, m_dwUserCode, m_strErrMsg);
  458. m_pSecureClient->DecRefCount();
  459. }
  460. };
  461. void SpSecureClient::OnReceivePackage(CSmartPointer<IPackage> &pRecvPkg)
  462. {
  463. // 切换到实体线程执行
  464. OnPackageTask *pTask = new OnPackageTask(this, pRecvPkg.Detach());
  465. IncRefCount();
  466. m_pEntity->GetFunction()->PostEntityTaskFIFO(pTask);
  467. }
  468. void SpSecureClient::OnClose()
  469. {
  470. // 切换到实体线程执行
  471. OnDisconnectTask *pTask = new OnDisconnectTask(this);
  472. IncRefCount();
  473. m_pEntity->GetFunction()->PostEntityTaskFIFO(pTask);
  474. }
  475. void SpSecureClient::OnError(DWORD dwSysCode, DWORD dwUserCode, const char *pErrMsg)
  476. {
  477. // 切换到实体线程执行
  478. OnErrorTask *pTask = new OnErrorTask(this, dwSysCode, dwUserCode, pErrMsg);
  479. IncRefCount();
  480. m_pEntity->GetFunction()->PostEntityTaskFIFO(pTask);
  481. }
  482. void SpSecureClient::OnAuthPass()
  483. {
  484. Dbg("SpSecureClient AuthPass");
  485. }
  486. bool SpSecureClient::OnAuthRequest(CConnAuthReq *pReq)
  487. {
  488. ErrorCodeEnum Error = Error_Unexpect;
  489. // prepare verify info
  490. CSystemStaticInfo si;
  491. {
  492. m_pEntity->GetFunction()->GetSystemStaticInfo(si);
  493. }
  494. CVerifyInfo info;
  495. memset(&info, 0, sizeof(info));
  496. strncpy(info.m_arrTerminalNo, (LPCSTR)si.strTerminalID, sizeof(info.m_arrTerminalNo)-1);
  497. strcpy(info.m_arrServiceType, "CMBRVC");
  498. {
  499. hostent *ent = gethostbyname(NULL);
  500. if (ent && ent->h_addr_list[0] != NULL)
  501. {
  502. int i = 0;
  503. for (; ent->h_addr_list[i] != NULL; ++i)
  504. {
  505. struct in_addr *in = (struct in_addr*)ent->h_addr_list[i];
  506. if (in->S_un.S_un_b.s_b1 == 99 || in->S_un.S_un_b.s_b1 == 10)
  507. break;
  508. }
  509. if (ent->h_addr_list[i] == NULL)
  510. i = 0;
  511. auto in = (struct in_addr*)ent->h_addr_list[i];
  512. info.m_arrIP[0] = in->S_un.S_un_b.s_b1;
  513. info.m_arrIP[1] = in->S_un.S_un_b.s_b2;
  514. info.m_arrIP[2] = in->S_un.S_un_b.s_b3;
  515. info.m_arrIP[3] = in->S_un.S_un_b.s_b4;
  516. }
  517. }
  518. {
  519. // call token service to encrypt verify info
  520. int nDestLen = sizeof(pReq->m_arrVerifyInfo);
  521. TokenService_ClientBase *client = new TokenService_ClientBase(m_pEntity);
  522. Error = client->Connect();
  523. if (Error == Error_Succeed)
  524. {
  525. TokenService_EncryptWithPriKey_Req Req;
  526. TokenService_EncryptWithPriKey_Ans Ans;
  527. Req.raw_data.m_pData = &info;
  528. Req.raw_data.m_iLength = sizeof(info);
  529. Error = client->EncryptWithPriKey(Req, Ans, -1);
  530. if (Error != Error_Succeed) {
  531. LOG_TRACE("EncryptWithPriKey for VerifyInfo failed! Error = %d", Error);
  532. }
  533. else
  534. {
  535. memcpy_s(pReq->m_arrVerifyInfo, sizeof(pReq->m_arrVerifyInfo), Ans.enc_data.m_pData, Ans.enc_data.m_iLength);
  536. // get token
  537. TokenService_GetToken_Req Req1;
  538. TokenService_GetToken_Ans Ans1;
  539. Error = client->GetToken(Req1, Ans1, -1);
  540. if (Error != Error_Succeed) {
  541. LOG_TRACE("GetToken for VerifyInfo failed! Error = %d", Error);
  542. } else {
  543. memcpy_s(pReq->m_arrVerifyToken, sizeof(pReq->m_arrVerifyToken), Ans1.token.m_pData, Ans1.token.m_iLength);
  544. }
  545. }
  546. client->GetFunction()->CloseSession();
  547. } else {
  548. LOG_TRACE("connect to tokenservice failed! Error = %d", Error);
  549. }
  550. client->SafeDelete();
  551. }
  552. return Error == Error_Succeed;
  553. }
  554. bool SpSecureClient::OnSessionKeyRet(CConnAuthRet *pRet, BYTE *pBuf, int *pBufLen)
  555. {
  556. memset(pBuf, 0, *pBufLen);
  557. TokenService_ClientBase *client = new TokenService_ClientBase(m_pEntity);
  558. ErrorCodeEnum Error = client->Connect();
  559. if (Error == Error_Succeed)
  560. {
  561. TokenService_DecryptWithPriKey_Req Req;
  562. TokenService_DecryptWithPriKey_Ans Ans;
  563. Req.enc_data.m_pData = &pRet->m_arrEncSessionKey[0];
  564. Req.enc_data.m_iLength = sizeof(pRet->m_arrEncSessionKey);
  565. Error = client->DecryptWithPriKey(Req, Ans, -1);
  566. if (Error == Error_Succeed)
  567. {
  568. memcpy_s(pBuf, *pBufLen, Ans.raw_data.m_pData, Ans.raw_data.m_iLength);
  569. *pBufLen = Ans.raw_data.m_iLength;
  570. } else {
  571. *pBufLen = 0;
  572. LOG_TRACE("OnSessionKey decrypt session key failed! Error = %d", Error);
  573. }
  574. client->GetFunction()->CloseSession();
  575. }
  576. client->SafeDelete();
  577. return Error == Error_Succeed;
  578. }
  579. bool SpSecureClient::OnGetSharedSK(char *pTerminalNo, int *pTerminalNoLen, BYTE *pBuf, int *pBufLen)
  580. {
  581. ErrorCodeEnum Error = Error_Unexpect;
  582. CSystemStaticInfo si;
  583. {
  584. m_pEntity->GetFunction()->GetSystemStaticInfo(si);
  585. }
  586. assert(si.strTerminalID.GetLength() <= *pTerminalNoLen);
  587. strcpy(pTerminalNo, (LPCSTR)si.strTerminalID);
  588. *pTerminalNoLen = strlen(pTerminalNo);
  589. {
  590. TokenService_ClientBase *client = new TokenService_ClientBase(m_pEntity);
  591. Error = client->Connect();
  592. if (Error == Error_Succeed) {
  593. TokenService_GetSharedSK_Req Req;
  594. TokenService_GetSharedSK_Ans Ans;
  595. Error = client->GetSharedSK(Req, Ans, 10000);
  596. if (Error == Error_Succeed) {
  597. memcpy_s(pBuf, *pBufLen, Ans.ssk.m_pData, Ans.ssk.m_iLength);
  598. *pBufLen = Ans.ssk.m_iLength;
  599. } else {
  600. *pBufLen = 0;
  601. LOG_TRACE("OnSessionKey decrypt session key failed! Error = %d", Error);
  602. }
  603. client->GetFunction()->CloseSession();
  604. }
  605. client->SafeDelete();
  606. }
  607. return Error == Error_Succeed;
  608. }
  609. ErrorCodeEnum SpSecureClient::ParseIPAddress(const char *str, CSimpleStringA &ip, int &port)
  610. {
  611. ErrorCodeEnum Error = Error_Unexpect;
  612. if (str) {
  613. char tmp1[32] = {};
  614. char tmp2[16] = {};
  615. sscanf(str, "%s %s", tmp1, tmp2);
  616. if (tmp1[0] != 0 && tmp2[0] != 0)
  617. {
  618. ip = tmp1;
  619. port = atoi(tmp2);
  620. Error = Error_Succeed;
  621. }
  622. else
  623. return Error;
  624. }
  625. return Error;
  626. }
  627. DWORD SpSecureClient::GetEntityUserCode(DWORD code)
  628. {
  629. assert(m_pEntity != NULL);
  630. auto pEnv = sp_get_env();
  631. assert(pEnv != NULL);
  632. auto pCfg = pEnv->cfg;
  633. assert(pCfg != NULL);
  634. auto pEntity = sp_cfg_get_entity_by_name(pCfg, m_pEntity->GetEntityName());
  635. assert(pEntity != NULL);
  636. DWORD dwDevelopID = pEntity->devel_id;
  637. return (dwDevelopID << 20 | code);
  638. }