SpSecureClient.cpp 22 KB

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