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

P2P编程

开发平台:

Visual C++

  1. // Encrypter.cpp: implementation of the CEncrypter class.
  2. //
  3. //////////////////////////////////////////////////////////////////////
  4. #include "stdafx.h"
  5. #include "testbt.h"
  6. #include "Encrypter.h"
  7. #include "Download.h"
  8. #include "Connector.h"
  9. #ifdef _DEBUG
  10. #undef THIS_FILE
  11. static char THIS_FILE[]=__FILE__;
  12. #define new DEBUG_NEW
  13. #endif
  14. //////////////////////////////////////////////////////////////////////
  15. // Construction/Destruction
  16. //////////////////////////////////////////////////////////////////////
  17. void CEncrypter::InitLocalIps()
  18. {
  19. char szHostName[128];
  20. if( gethostname(szHostName, 128) == 0 )
  21. {
  22. // const char* pszAddr;
  23. struct hostent * pHost;
  24. pHost = gethostbyname(szHostName); 
  25. for(int i=0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ ) 
  26. {
  27. /*对每一个IP地址进行处理*/
  28. // pszAddr=inet_ntoa (*(struct in_addr *)pHost->h_addr_list[i]);
  29. m_vlocalIps.push_back((long)(*(struct in_addr *)pHost->h_addr_list[i]).S_un.S_addr);
  30. }
  31. if (m_vlocalIps.empty())
  32. {
  33. assert(false);
  34. }
  35. }
  36. else
  37. {
  38. assert(false);
  39. }
  40. }
  41. CEncrypter::CEncrypter(long lMaxInitiate)
  42. {
  43. m_lMaxInitiate = lMaxInitiate;
  44. }
  45. bool CEncrypter::Create(CDownloaderFeedback* pMain, CConnector * pconnector, memstream& memMyid, memstream& memInfohash, long lMaxLen, long lKeepaliveDelay)
  46. {
  47. m_pMain = pMain;
  48. m_pconnector = pconnector;
  49. m_memMyId.write(memMyid, memMyid.size());
  50. m_memInfohash.write(memInfohash, memInfohash.size());
  51. m_lMaxLen = lMaxLen;
  52. m_lKeepaliveDelay = lKeepaliveDelay;
  53. time(&m_lKeepaliveDelayLast);
  54. // for socket id.
  55. m_lConnectionIDSeed = 100;
  56. InitLocalIps();
  57. return true;
  58. }
  59. CEncrypter::~CEncrypter()
  60. {
  61. for (int i=0; i<m_connections.size(); i++)
  62. delete m_connections[i];
  63. for (i=0; i<m_unConnections.size(); i++)
  64. {
  65. closesocket(m_unConnections[i]->m_socket);
  66. CloseHandle(m_unConnections[i]->m_hevConnecting);
  67. delete m_unConnections[i];
  68. }
  69. }
  70. void CEncrypter::SetMaxPeers(long lMaxInitiate)
  71. {
  72. m_lMaxInitiate = lMaxInitiate;
  73. }
  74. long CEncrypter::GetMaxLen()
  75. {
  76. return m_lMaxLen;
  77. }
  78. long CEncrypter::send_keepalives()
  79. {
  80. long ltime = 0;
  81. time(&ltime);
  82. if ( (ltime-m_lKeepaliveDelayLast) < m_lKeepaliveDelay)
  83. return m_lKeepaliveDelay - (ltime - m_lKeepaliveDelayLast);
  84. for (int i=0; i<m_connections.size(); i++)
  85. {
  86. m_connections[i]->send_message("", 0);
  87. }
  88. time(&m_lKeepaliveDelayLast);
  89. return m_lKeepaliveDelay;
  90. }
  91. void CEncrypter::connection_made(SOCKET newsocket)
  92. {
  93. // if (m_connections.size() < m_lMaxInitiate)
  94. if ((m_connections.size() + m_unConnections.size() + 3) < MAXIMUM_WAIT_OBJECTS && // 3 handles for other event to handle
  95. m_pconnector->m_connections.size() < m_lMaxInitiate)
  96. {
  97. CEncryptedConnection* pnew = new CEncryptedConnection(m_pMain, newsocket, m_pconnector, this, memstream(), m_lConnectionIDSeed ++);
  98. m_connections.push_back(pnew);
  99. pnew->connection_init();
  100. // m_pMain->ShowEncryptedMessage(string("accepted to peers : ") + pnew->GetIP());
  101. }
  102. else
  103. {
  104. closesocket(newsocket);
  105. // m_pMain->ShowEncryptedMessage(string("Close a accepted peers, because of too may connections"));
  106. }
  107. }
  108. void CEncrypter::start_connection(string strIP, short lPort, memstream &mPeerID)
  109. {
  110. // check peer whether connected.
  111. if ((m_connections.size() + m_unConnections.size() + 3) >= MAXIMUM_WAIT_OBJECTS || // 3 handles for other event to handle
  112. m_pconnector->m_connections.size() >= m_lMaxInitiate)
  113. {
  114. m_pMain->ShowEncryptedMessage(string("Close a connected peers, because of too may connections"));
  115. return;
  116. }
  117. if (mPeerID == m_memMyId)
  118. return ;
  119. //
  120. // if peer info is self, skip it.
  121. //
  122. for (int i=0; i<m_connections.size(); i++)
  123. {
  124. if (mPeerID == m_connections[i]->m_memPeerid)
  125. return;
  126. }
  127. //
  128. // if peer addr no valid skip it.
  129. //
  130. unsigned long laddr = inet_addr(strIP.data());
  131. if (laddr == INADDR_NONE)
  132. {
  133. m_pMain->errorFunc("start_connection error : the peer ip is invalid");
  134. return;
  135. }
  136. //
  137. // if the peer is self ip, skip it.
  138. //
  139. for (i=0; i<m_vlocalIps.size(); i++)
  140. {
  141. if (laddr == m_vlocalIps[i])
  142. {
  143. #ifdef _DEBUG
  144. in_addr inaddress;
  145. inaddress.S_un.S_addr = laddr;
  146. const char* pszAddr = inet_ntoa(inaddress);
  147. char szText[1024] = {0};
  148. sprintf(szText, "rn %s connect to self, the peer is left at the server by last runrn", pszAddr);
  149. TRACE(szText);
  150. #endif
  151. return;
  152. }
  153. }
  154. //
  155. // try to connect the peer.
  156. //
  157. SOCKET hnewSocket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, 0, 0, WSA_FLAG_OVERLAPPED);
  158. if (hnewSocket  == INVALID_SOCKET)
  159. {
  160. m_pMain->errorFunc("start_connection error:can't create socket");
  161. return ;
  162. }
  163. HANDLE hevConnecting = ::CreateEvent(0, false, false, 0);
  164. assert(hevConnecting);
  165. int iRet = WSAEventSelect(hnewSocket, hevConnecting , FD_CONNECT);
  166. if (iRet == SOCKET_ERROR)
  167. {
  168. assert(false);
  169. string e = WSAShowError();
  170. return;
  171. }
  172. //*
  173. sockaddr_in addr = {0};
  174. addr.sin_family = AF_INET;
  175. addr.sin_port = htons(lPort);
  176. addr.sin_addr.S_un.S_addr = laddr;
  177. int ilen = sizeof(addr);
  178. iRet = connect(hnewSocket, (sockaddr*)&addr, ilen);
  179. if (iRet != 0)
  180. {
  181. if (WSAGetLastError() != WSAEWOULDBLOCK)
  182. assert(false);
  183. }
  184. m_unConnections.push_back(new CUnConnectedSocket(hnewSocket, hevConnecting, laddr, lPort, mPeerID));
  185. }
  186. void CEncrypter::complete_connecting(long lInx)
  187. {
  188. vector<CUnConnectedSocket*>::iterator iter = m_unConnections.begin() + lInx;
  189. assert(iter != m_unConnections.end());
  190. WSANETWORKEVENTS events;
  191. int iRet = WSAEnumNetworkEvents((*iter)->m_socket, (*iter)->m_hevConnecting, &events);
  192. if (iRet == SOCKET_ERROR) 
  193. {
  194. string e = WSAShowError();
  195. assert(false);
  196. return;
  197. }
  198. if (!(events.lNetworkEvents & FD_CONNECT))
  199. return;
  200. int iErrCode = events.iErrorCode[FD_CONNECT_BIT];
  201. if (iErrCode != 0) // connect error.
  202. {
  203. switch (iErrCode)
  204. {
  205. case WSAEAFNOSUPPORT:
  206. break;
  207. case WSAECONNREFUSED:
  208. break;
  209. case WSAENETUNREACH:
  210. break;
  211. case WSAENOBUFS:
  212. break;
  213. case WSAETIMEDOUT:
  214. break;
  215. default:
  216. {
  217. iRet = 0;
  218. }
  219. break;
  220. }
  221. closesocket((*iter)->m_socket);
  222. }
  223. else
  224. {
  225. if ((m_connections.size() + m_unConnections.size() + 3) < MAXIMUM_WAIT_OBJECTS && // 3 handles for other event to handle
  226. m_pconnector->m_connections.size() < m_lMaxInitiate)
  227. {
  228. // TRACE("rnall, connected : %d, %drn", (m_connections.size() + m_unConnections.size()), m_pconnector->m_connections.size());
  229. CEncryptedConnection* pnew = new CEncryptedConnection(m_pMain, (*iter)->m_socket, m_pconnector, this, (*iter)->m_mPeerID, m_lConnectionIDSeed ++);
  230. m_connections.push_back(pnew);
  231. pnew->connection_init();
  232. m_pMain->ShowEncryptedMessage(string("connected to peers : ") + pnew->GetIP());
  233. }
  234. else // too many connections to handle. WaitForMultipleObjects only can handle count of MAXIMUM_WAIT_OBJECTS.
  235. {
  236. closesocket((*iter)->m_socket);
  237. m_pMain->ShowEncryptedMessage(string("Close a connected peers, because of too may connections"));
  238. }
  239. }
  240. // release select event.
  241. // WSAEventSelect((*iter)->m_socket, (*iter)->m_hevConnecting, 0); 
  242. CloseHandle((*iter)->m_hevConnecting);
  243. delete (*iter);
  244. iter = m_unConnections.erase(iter) - 1 ;
  245. }
  246. bool CEncrypter::detele_connections_died()
  247. {
  248. for (int i=0; i<m_connections_died.size(); i++)
  249. {
  250. CEncryptedConnection* pdied = m_connections_died[i];
  251. vector<CEncryptedConnection*>::iterator it = 
  252. find(m_connections.begin(), m_connections.end(), pdied);
  253. assert(it != m_connections.end());
  254. pdied->CloseDied();
  255. }
  256. m_connections_died.erase(m_connections_died.begin(), m_connections_died.end());
  257. return true;
  258. }