SpSecureClient.cpp 22 KB

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