EncryptedConnection.cpp
上传用户:lds876
上传日期:2013-05-25
资源大小:567k
文件大小:12k
源码类别:

P2P编程

开发平台:

Visual C++

  1. // EncryptedConnection.cpp: implementation of the CEncryptedConnection class.
  2. //
  3. //////////////////////////////////////////////////////////////////////
  4. #include "stdafx.h"
  5. #include "testbt.h"
  6. #include "EncryptedConnection.h"
  7. #include "Encrypter.h"
  8. #include "Connector.h"
  9. #include "Connection.h"
  10. #include "download.h"
  11. #ifdef _DEBUG
  12. #undef THIS_FILE
  13. static char THIS_FILE[]=__FILE__;
  14. #define new DEBUG_NEW
  15. #endif
  16. const string strProtocolName = "BitTorrent protocol";
  17. const long lHeaderLen[7] = {1, 
  18. strlen(strProtocolName.data()), 
  19. 8, 20, 20, 4, 1};
  20. char* tobinary(long lnum, char* pBuf, long length=4);
  21. //////////////////////////////////////////////////////////////////////
  22. // Construction/Destruction
  23. //////////////////////////////////////////////////////////////////////
  24. CEncryptedConnection::CEncryptedConnection(CDownloaderFeedback* pMain, SOCKET hsocket,CConnector* pconnector, CEncrypter* pEncrypter, memstream& memPeerid, long lConnectionID)
  25. {
  26. m_pMain = pMain;
  27. m_pconnector = pconnector;
  28. m_pEncrypter = pEncrypter;
  29. m_hsocket = hsocket;
  30. m_memPeerid = memPeerid;
  31. m_bLocallyInitiated = (m_memPeerid.size() > 0) ? true:false;
  32. time(&m_lLastHit);
  33. memset(m_ReadBufferTemp, 0, READ_BUFFER_LEN );
  34. // select event.
  35. m_hReadEvent = CreateEvent(0, false, false, 0);
  36. assert(m_hReadEvent);
  37. int iRet = WSAEventSelect(hsocket, m_hReadEvent , FD_READ|FD_WRITE|FD_CLOSE);
  38. if (iRet == SOCKET_ERROR) assert(false);
  39. m_bCompleted = false;
  40. m_eStep = eread_header_len;
  41. m_lReadMessageLength = 0;
  42. //
  43. // get ip or id.
  44. //
  45. m_lConnectionID = lConnectionID;
  46. sockaddr_in addr = {0};
  47. int len = sizeof(addr);
  48. iRet = getpeername(m_hsocket, (sockaddr*)&addr, &len);
  49. if (iRet != 0)
  50. {
  51. string strErr = WSAShowError();
  52. assert(false);
  53. }
  54. m_lAddr = addr.sin_addr.S_un.S_addr;
  55. m_sPort = addr.sin_port;
  56. }
  57. CEncryptedConnection::~CEncryptedConnection()
  58. {
  59. CloseHandle(m_hReadEvent);
  60. closesocket(m_hsocket);
  61. }
  62. bool CEncryptedConnection::GetIP(long& lAddr, short& sPort)
  63. {
  64. lAddr = m_lAddr;
  65. sPort = m_sPort;
  66. return true;
  67. }
  68. string CEncryptedConnection::GetIP()
  69. {
  70. assert(m_hsocket);
  71. sockaddr_in addr = {0};
  72. int len = sizeof(addr);
  73. int iRet = getpeername(m_hsocket, (sockaddr*)&addr, &len);
  74. if (iRet != 0)
  75. {
  76. string strErr = WSAShowError();
  77. assert(false);
  78. return strErr;
  79. }
  80. string strRet(inet_ntoa(addr.sin_addr));
  81. strRet += ":" + ltostring(ntohs(addr.sin_port));
  82. return strRet;
  83. }
  84. void CEncryptedConnection::Shutdown(int how)
  85. {
  86. assert(m_hsocket);
  87. int iRet = shutdown(m_hsocket, how);
  88. if (iRet != 0)
  89. throw string ("shutdown socket error");
  90. }
  91. bool CEncryptedConnection::IsFlush()
  92. {
  93. return m_WriteBuffer.size() <= 0;
  94. }
  95. void CEncryptedConnection::Send(char *pBuf, long lBufLen)
  96. {
  97. assert(m_hsocket);
  98. m_WriteBuffer.write(pBuf, lBufLen);
  99. if (m_WriteBuffer.size() > 0)
  100. try_send();
  101. }
  102. void CEncryptedConnection::try_send()
  103. {
  104. while (m_WriteBuffer.size() > 0)
  105. {
  106. int iRet = send(m_hsocket, (char*)m_WriteBuffer, m_WriteBuffer.size(), 0);
  107. if (iRet == SOCKET_ERROR)
  108. {
  109. if (::WSAGetLastError() == WSAEWOULDBLOCK)
  110. break;
  111. else
  112. {
  113. string e = WSAShowError();
  114. // m_pEncrypter->m_connections_died.push_back(this);
  115. Close();
  116. return;
  117. }
  118. }
  119. else // succeed.
  120. {
  121. m_WriteBuffer.TrimLeft(iRet);
  122. }
  123. }
  124. /*
  125. int iRet = 0;
  126. if (m_WriteBuffer.size() > 0)
  127. iRet = WSAEventSelect(m_hsocket, m_hReadEvent , FD_READ|FD_WRITE|FD_CLOSE);
  128. else
  129. iRet = WSAEventSelect(m_hsocket, m_hReadEvent , FD_READ|FD_CLOSE);
  130. if (iRet == SOCKET_ERROR) 
  131. {
  132. assert(false);
  133. }
  134. //*/
  135. }
  136. void CEncryptedConnection::handle_events()
  137. {
  138. // string strPeerIp = GetIP();
  139. WSANETWORKEVENTS events;
  140. int iRet = WSAEnumNetworkEvents(m_hsocket, m_hReadEvent, &events);
  141. if (iRet == SOCKET_ERROR) 
  142. {
  143. string e = WSAShowError();
  144. assert(false);
  145. return;
  146. }
  147. if (events.lNetworkEvents & FD_CLOSE)
  148. {
  149. switch(events.iErrorCode[FD_CLOSE_BIT])
  150. {
  151. case WSAENETDOWN:
  152. break;
  153. case WSAECONNRESET:
  154. break;
  155. case WSAECONNABORTED:
  156. break;
  157. }
  158. int i = 0;
  159. Close();
  160. return;
  161. }
  162. if (events.lNetworkEvents & FD_WRITE)
  163. {
  164. // TRACE("try_send() rn");
  165. try_send();
  166. if (IsFlush())
  167. {
  168. if (m_bCompleted)
  169. m_pconnector->connection_flushed(this);
  170. }
  171. /*
  172. iRet = send(m_hsocket, (char*)m_WriteBuffer, m_WriteBuffer.size(), 0);
  173. if (iRet == SOCKET_ERROR)
  174. {
  175. Close();
  176. string e = WSAShowError();
  177. assert(false);
  178. return;
  179. }
  180. else // succeed.
  181. {
  182. m_WriteBuffer.TrimLeft(iRet);
  183. }
  184. //*/
  185. }
  186. if (events.lNetworkEvents & FD_READ)
  187. {
  188. iRet = recv(m_hsocket, m_ReadBufferTemp, READ_BUFFER_LEN, 0);
  189. if (iRet == SOCKET_ERROR)
  190. {
  191. Close();
  192. assert(false);
  193. return;
  194. }
  195. else if (iRet == 0) // connection closed.
  196. {
  197. Close();
  198. return;
  199. }
  200. else // succeed.
  201. {
  202. data_came_in(m_ReadBufferTemp, iRet);
  203. }
  204. }
  205. }
  206. ///////////////////////////////////////////////////////////////////////////
  207. //
  208. // data transfer.
  209. //
  210. ///////////////////////////////////////////////////////////////////////////
  211. void CEncryptedConnection::connection_init()
  212. {
  213. //
  214. // format header and send.
  215. // 
  216. char zero[8] = {0};
  217. memset(zero, 0, 8);
  218. memstream memHeader;
  219. char cprosize = strProtocolName.size();
  220. memHeader.write(&cprosize, 1);
  221. memHeader.write(strProtocolName.data(), strProtocolName.size());
  222. memHeader.write(zero, sizeof(zero));
  223. memHeader.write((char*)m_pEncrypter->m_memInfohash, m_pEncrypter->m_memInfohash.size());
  224. memHeader.write((char*)m_pEncrypter->m_memMyId, m_pEncrypter->m_memMyId.size());
  225. // string strPeer = GetIP();
  226. Send((char*)memHeader, memHeader.size());
  227. }
  228. void CEncryptedConnection::CloseDied()
  229. {
  230. m_pMain->ShowEncryptedMessage("CEncryptedConnection CloseDied()");
  231. if (m_bCompleted)
  232. m_pconnector->connection_lost(this);
  233. vector<CEncryptedConnection*>::iterator it = 
  234. find(m_pEncrypter->m_connections.begin(), m_pEncrypter->m_connections.end(), this);
  235. if (it != m_pEncrypter->m_connections.end())
  236. {
  237. m_pEncrypter->m_connections.erase(it);
  238. delete this;
  239. }
  240. else assert(false);
  241. }
  242. void CEncryptedConnection::Close()
  243. {
  244. vector<CEncryptedConnection*>::iterator it = 
  245. find(m_pEncrypter->m_connections.begin(), m_pEncrypter->m_connections.end(), this);
  246. assert(it != m_pEncrypter->m_connections.end());
  247. // if the connectionalready in deletes, skip it.
  248. it = find(m_pEncrypter->m_connections_died.begin(), m_pEncrypter->m_connections_died.end(), this);
  249. if (it != m_pEncrypter->m_connections_died.end())
  250. {
  251. // assert(false);
  252. TRACE("if the connectionalready in deletes, skip it.rn");
  253. return;
  254. }
  255. m_pEncrypter->m_connections_died.push_back(this);
  256. return;
  257. /*
  258. ShowMessage(this, "CEncryptedConnection close()");
  259. if (m_bCompleted)
  260. {
  261. m_pconnector->connection_lost(this);
  262. }
  263. vector<CEncryptedConnection*>::iterator it = 
  264. find(m_pEncrypter->m_connections.begin(), m_pEncrypter->m_connections.end(), this);
  265. if (it != m_pEncrypter->m_connections.end())
  266. {
  267. m_pEncrypter->m_connections.erase(it);
  268. delete this;
  269. }
  270. else assert(false);
  271. //*/
  272. }
  273. #define FORMAT_ERR 2
  274. void CEncryptedConnection::data_came_in(char *pBuf, long length)
  275. {
  276. // string strPeerIp = GetIP();
  277. m_ReadBuffer.write(pBuf, length);
  278. int bRet = true;
  279. while (bRet)
  280. {
  281. switch(m_eStep)
  282. {
  283. case eread_header_len:
  284. bRet = read_header_len();
  285. break;
  286. case eread_header:
  287. bRet = read_header();
  288. break;
  289. case eread_reserved:
  290. bRet = read_reserved();
  291. break;
  292. case eread_download_id:
  293. bRet = read_download_id();
  294. break;
  295. case eread_peer_id:
  296. bRet = read_peer_id();
  297. break;
  298. case eread_len:
  299. bRet = read_len();
  300. break;
  301. case  eread_message:
  302. bRet = read_message();
  303. break;
  304. }
  305. if (bRet == (int)true)
  306. {
  307. if (eread_message == m_eStep)
  308. m_eStep --;
  309. else
  310. m_eStep ++;
  311. }
  312. else if (bRet == FORMAT_ERR)
  313. {
  314. m_pMain->ShowEncryptedMessage(string("close HeadData format error peers : ") + GetIP());
  315. Close();
  316. return;
  317. }
  318. }
  319. }
  320. int  CEncryptedConnection::read_header_len()
  321. {
  322. if (m_ReadBuffer.size() < 1)
  323. return false;
  324. char* pbuf = m_ReadBuffer;
  325. char c = *pbuf;
  326. m_ReadBuffer.TrimLeft(1);
  327. if (c != strlen(strProtocolName.data()))
  328. return FORMAT_ERR;
  329. m_pMain->ShowEncryptedMessage(string("HeadData begin read peers : ") + GetIP());
  330. return true;
  331. }
  332. int   CEncryptedConnection::read_header()
  333. {
  334. if (m_ReadBuffer.size() < strlen(strProtocolName.data()))
  335. return false;
  336. char* pbuf = new char[strlen(strProtocolName.data()) + 1];
  337. memset(pbuf, 0, strlen(strProtocolName.data()) + 1);
  338. memcpy(pbuf, m_ReadBuffer, strlen(strProtocolName.data()));
  339. m_ReadBuffer.TrimLeft(strlen(strProtocolName.data()));
  340. if (string(pbuf) != strProtocolName)
  341. {
  342. delete pbuf;
  343. return FORMAT_ERR;
  344. }
  345. delete pbuf;
  346. return true;
  347. }
  348. int  CEncryptedConnection::read_reserved()
  349. {
  350. if (m_ReadBuffer.size() < 8)
  351. return false;
  352. m_ReadBuffer.TrimLeft(8);
  353. return true;
  354. }
  355. int   CEncryptedConnection::read_download_id()
  356. {
  357. if (m_ReadBuffer.size() < 20)
  358. return false;
  359. char pbuf [20];
  360. memcpy(pbuf, m_ReadBuffer, 20);
  361. m_ReadBuffer.TrimLeft(20);
  362. char* pInfohash = (char*)m_pEncrypter->m_memInfohash;
  363. for (int i=0; i<20; i++)
  364. {
  365. if (pbuf[i] != *(pInfohash+i))
  366. {
  367. return FORMAT_ERR;
  368. }
  369. }
  370. return true;
  371. }
  372. int   CEncryptedConnection::read_peer_id()
  373. {
  374. if (m_ReadBuffer.size() < 20)
  375. return false;
  376. if (m_memPeerid.size() <= 0) // connected by peer, peerid unknown.
  377. m_memPeerid.write(m_ReadBuffer, 20);
  378. char pbuf [20];
  379. memcpy(pbuf, m_ReadBuffer, 20);
  380. m_ReadBuffer.TrimLeft(20);
  381. char* pPeerid = (char*)m_memPeerid;
  382. for (int i=0; i<20; i++)
  383. {
  384. if (pbuf[i] != *(pPeerid+i))
  385. {
  386. return FORMAT_ERR;
  387. }
  388. }
  389. m_pconnector->connection_made(this);
  390. m_bCompleted = true;
  391. m_pMain->ShowEncryptedMessage(string("HeadData format succed peers : ") + GetIP());
  392. return true;
  393. }
  394. int   CEncryptedConnection::read_len()
  395. {
  396. if (m_ReadBuffer.size() < 4)
  397. return false;
  398. unsigned char len[4] = {0};
  399. memcpy(len, m_ReadBuffer, 4);
  400. m_lReadMessageLength = len[0]*0x1000000 + len[1]*0x10000 + len[2]*0x100 + len[3];
  401. m_ReadBuffer.TrimLeft(4);
  402. if (m_lReadMessageLength > m_pEncrypter->GetMaxLen())
  403. return FORMAT_ERR;
  404. return true;
  405. }
  406. int   CEncryptedConnection::read_message()
  407. {
  408. if (m_ReadBuffer.size() < m_lReadMessageLength)
  409. return false;
  410. if (m_lReadMessageLength <= 0)
  411. return true;
  412. memstream membuf;
  413. membuf.write(m_ReadBuffer, m_lReadMessageLength);
  414. m_ReadBuffer.TrimLeft(m_lReadMessageLength);
  415. // m_pconnector->got_message(this, membuf, membuf.size());
  416. m_pconnector->got_message(this, membuf);
  417. return true;
  418. }
  419. void CEncryptedConnection::send_message(char *pBuf, long length)
  420. {
  421. long len = length;
  422. char lenBuf[4] = {0};
  423. tobinary(len, lenBuf);
  424. memstream mBuf;
  425. mBuf.write(lenBuf, sizeof(long));
  426. mBuf.write(pBuf, length);
  427. Send(mBuf, mBuf.size());
  428. }
  429. bool CEncryptedConnection::is_locally_initiated()
  430. {
  431. return m_bLocallyInitiated;
  432. }
  433. memstream& CEncryptedConnection::GetID()
  434. {
  435. return m_memPeerid;
  436. }
  437. string CEncryptedConnection::GetInfohashString()
  438. {
  439. // assert(m_memPeerid.size() == 20);
  440. string strRet;
  441. char szText[20] = {0};
  442. for (int i=0; i<m_memPeerid.size(); i++)
  443. {
  444. if (((unsigned char) m_memPeerid[i] )< 0x10)
  445. sprintf(szText, "0%x", (unsigned char) m_memPeerid[i]);
  446. else
  447. sprintf(szText, "%x", (unsigned char) m_memPeerid[i]);
  448. strRet += szText;
  449. }
  450. return strRet;
  451. }