AsyncSocketExLayer.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  1. /*CAsyncSocketEx by Tim Kosse ([email protected])
  2. Version 1.1 (2002-11-01)
  3. --------------------------------------------------------
  4. Introduction:
  5. -------------
  6. CAsyncSocketEx is a replacement for the MFC class CAsyncSocket.
  7. This class was written because CAsyncSocket is not the fastest WinSock
  8. wrapper and it's very hard to add new functionality to CAsyncSocket
  9. derived classes. This class offers the same functionality as CAsyncSocket.
  10. Also, CAsyncSocketEx offers some enhancements which were not possible with
  11. CAsyncSocket without some tricks.
  12. How do I use it?
  13. ----------------
  14. Basically exactly like CAsyncSocket.
  15. To use CAsyncSocketEx, just replace all occurrences of CAsyncSocket in your
  16. code with CAsyncSocketEx, if you did not enhance CAsyncSocket yourself in
  17. any way, you won't have to change anything else in your code.
  18. Why is CAsyncSocketEx faster?
  19. -----------------------------
  20. CAsyncSocketEx is slightly faster when dispatching notification event messages.
  21. First have a look at the way CAsyncSocket works. For each thread that uses
  22. CAsyncSocket, a window is created. CAsyncSocket calls WSAAsyncSelect with
  23. the handle of that window. Until here, CAsyncSocketEx works the same way.
  24. But CAsyncSocket uses only one window message (WM_SOCKET_NOTIFY) for all
  25. sockets within one thread. When the window recieve WM_SOCKET_NOTIFY, wParam
  26. contains the socket handle and the window looks up an CAsyncSocket instance
  27. using a map. CAsyncSocketEx works differently. It's helper window uses a
  28. wide range of different window messages (WM_USER through 0xBFFF) and passes
  29. a different message to WSAAsyncSelect for each socket. When a message in
  30. the specified range is received, CAsyncSocketEx looks up the pointer to a
  31. CAsyncSocketEx instance in an Array using the index of message - WM_USER.
  32. As you can see, CAsyncSocketEx uses the helper window in a more efficient
  33. way, as it don't have to use the slow maps to lookup it's own instance.
  34. Still, speed increase is not very much, but it may be noticeable when using
  35. a lot of sockets at the same time.
  36. Please note that the changes do not affect the raw data throughput rate,
  37. CAsyncSocketEx only dispatches the notification messages faster.
  38. What else does CAsyncSocketEx offer?
  39. ------------------------------------
  40. CAsyncSocketEx offers a flexible layer system. One example is the proxy layer.
  41. Just create an instance of the proxy layer, configure it and add it to the layer
  42. chain of your CAsyncSocketEx instance. After that, you can connect through
  43. proxies.
  44. Benefit: You don't have to change much to use the layer system.
  45. Another layer that is currently in development is the SSL layer to establish
  46. SSL encrypted connections.
  47. License
  48. -------
  49. Feel free to use this class, as long as you don't claim that you wrote it
  50. and this copyright notice stays intact in the source files.
  51. If you use this class in commercial applications, please send a short message
  52. to [email protected]
  53. */#include "stdafx.h"
  54. #include "AsyncSocketExLayer.h"
  55. #include "AsyncSocketEx.h"
  56. #ifdef _DEBUG
  57. #undef THIS_FILE
  58. static char THIS_FILE[]=__FILE__;
  59. #ifdef DEBUG_NEW
  60. #define new DEBUG_NEW
  61. #endif
  62. #endif
  63. #define WM_SOCKETEX_NOTIFY (WM_USER+3)
  64. //////////////////////////////////////////////////////////////////////
  65. // Konstruktion/Destruktion
  66. //////////////////////////////////////////////////////////////////////
  67. CAsyncSocketExLayer::CAsyncSocketExLayer()
  68. {
  69. m_pOwnerSocket = NULL;
  70. m_pNextLayer = NULL;
  71. m_pPrevLayer = NULL;
  72. m_nLayerState = notsock;
  73. m_nCriticalError=0;
  74. m_nPendingEvents = 0;
  75. m_nFamily = AF_UNSPEC;
  76. m_lEvent = 0;
  77. m_lpszSocketAddress = 0;
  78. m_nSocketPort = 0;
  79. m_nextAddr = 0;
  80. m_addrInfo = 0;
  81. }
  82. CAsyncSocketExLayer::~CAsyncSocketExLayer()
  83. {
  84. delete [] m_lpszSocketAddress;
  85. }
  86. CAsyncSocketExLayer *CAsyncSocketExLayer::AddLayer(CAsyncSocketExLayer *pLayer, CAsyncSocketEx *pOwnerSocket)
  87. {
  88. ASSERT(pLayer);
  89. ASSERT(pOwnerSocket);
  90. if (m_pNextLayer)
  91. {
  92. return m_pNextLayer->AddLayer(pLayer, pOwnerSocket);
  93. }
  94. else
  95. {
  96. ASSERT(m_pOwnerSocket==pOwnerSocket);
  97. pLayer->Init(this, m_pOwnerSocket);
  98. m_pNextLayer=pLayer;
  99. }
  100. return m_pNextLayer;
  101. }
  102. int CAsyncSocketExLayer::Receive(void* lpBuf, int nBufLen, int nFlags /*=0*/)
  103. {
  104. int Result = ReceiveNext(lpBuf, nBufLen, nFlags);
  105. return Result;
  106. }
  107. int CAsyncSocketExLayer::Send(const void* lpBuf, int nBufLen, int nFlags /*=0*/)
  108. {
  109. int Result = SendNext(lpBuf, nBufLen, nFlags);
  110. return Result;
  111. }
  112. void CAsyncSocketExLayer::OnReceive(int nErrorCode)
  113. {
  114. if (m_pPrevLayer)
  115. {
  116. m_pPrevLayer->OnReceive(nErrorCode);
  117. }
  118. else
  119. {
  120. if (m_pOwnerSocket->m_lEvent&FD_READ)
  121. {
  122. m_pOwnerSocket->OnReceive(nErrorCode);
  123. }
  124. }
  125. }
  126. void CAsyncSocketExLayer::OnSend(int nErrorCode)
  127. {
  128. if (m_pPrevLayer)
  129. {
  130. m_pPrevLayer->OnSend(nErrorCode);
  131. }
  132. else
  133. {
  134. if (m_pOwnerSocket->m_lEvent&FD_WRITE)
  135. {
  136. m_pOwnerSocket->OnSend(nErrorCode);
  137. }
  138. }
  139. }
  140. void CAsyncSocketExLayer::OnConnect(int nErrorCode)
  141. {
  142. TriggerEvent(FD_CONNECT, nErrorCode, TRUE);
  143. }
  144. void CAsyncSocketExLayer::OnAccept(int nErrorCode)
  145. {
  146. if (m_pPrevLayer)
  147. m_pPrevLayer->OnAccept(nErrorCode);
  148. else
  149. if (m_pOwnerSocket->m_lEvent&FD_ACCEPT)
  150. m_pOwnerSocket->OnAccept(nErrorCode);
  151. }
  152. void CAsyncSocketExLayer::OnClose(int nErrorCode)
  153. {
  154. if (m_pPrevLayer)
  155. m_pPrevLayer->OnClose(nErrorCode);
  156. else
  157. if (m_pOwnerSocket->m_lEvent&FD_CLOSE)
  158. m_pOwnerSocket->OnClose(nErrorCode);
  159. }
  160. BOOL CAsyncSocketExLayer::TriggerEvent(long lEvent, int nErrorCode, BOOL bPassThrough /*=FALSE*/ )
  161. {
  162. ASSERT(m_pOwnerSocket);
  163. if (m_pOwnerSocket->m_SocketData.hSocket==INVALID_SOCKET)
  164. return FALSE;
  165. if (!bPassThrough)
  166. {
  167. if (m_nPendingEvents & lEvent)
  168. return TRUE;
  169. m_nPendingEvents |= lEvent;
  170. }
  171. if (lEvent & FD_CONNECT)
  172. {
  173. ASSERT(bPassThrough);
  174. if (!nErrorCode)
  175. ASSERT(bPassThrough && (GetLayerState()==connected || GetLayerState()==attached));
  176. else if (nErrorCode)
  177. {
  178. SetLayerState(aborted);
  179. m_nCriticalError=nErrorCode;
  180. }
  181. }
  182. else if (lEvent & FD_CLOSE)
  183. {
  184. if (!nErrorCode)
  185. SetLayerState(closed);
  186. else
  187. {
  188. SetLayerState(aborted);
  189. m_nCriticalError = nErrorCode;
  190. }
  191. }
  192. ASSERT(m_pOwnerSocket->m_pLocalAsyncSocketExThreadData);
  193. ASSERT(m_pOwnerSocket->m_pLocalAsyncSocketExThreadData->m_pHelperWindow);
  194. ASSERT(m_pOwnerSocket->m_SocketData.nSocketIndex!=-1);
  195. t_LayerNotifyMsg *pMsg=new t_LayerNotifyMsg;
  196. pMsg->hSocket = m_pOwnerSocket->m_SocketData.hSocket;
  197. pMsg->lEvent = ( lEvent % 0xffff ) + ( nErrorCode << 16);
  198. pMsg->pLayer=bPassThrough?m_pPrevLayer:this;
  199. BOOL res=PostMessage(m_pOwnerSocket->GetHelperWindowHandle(), WM_USER, (WPARAM)m_pOwnerSocket->m_SocketData.nSocketIndex, (LPARAM)pMsg);
  200. if (!res)
  201. delete pMsg;
  202. return res;
  203. }
  204. void CAsyncSocketExLayer::Close()
  205. {
  206. CloseNext();
  207. }
  208. void CAsyncSocketExLayer::CloseNext()
  209. {
  210. if (m_addrInfo)
  211. freeaddrinfo(m_addrInfo);
  212. m_nextAddr = 0;
  213. m_addrInfo = 0;
  214. m_nPendingEvents = 0;
  215. SetLayerState(notsock);
  216. if (m_pNextLayer)
  217. m_pNextLayer->Close();
  218. }
  219. BOOL CAsyncSocketExLayer::Connect(LPCTSTR lpszHostAddress, UINT nHostPort)
  220. {
  221. return ConnectNext(lpszHostAddress, nHostPort);
  222. }
  223. BOOL CAsyncSocketExLayer::Connect( const SOCKADDR* lpSockAddr, int nSockAddrLen )
  224. {
  225. return ConnectNext(lpSockAddr, nSockAddrLen);
  226. }
  227. int CAsyncSocketExLayer::SendNext(const void *lpBuf, int nBufLen, int nFlags /*=0*/)
  228. {
  229. if (m_nCriticalError)
  230. {
  231. WSASetLastError(m_nCriticalError);
  232. return SOCKET_ERROR;
  233. }
  234. else if (GetLayerState()==notsock)
  235. {
  236. WSASetLastError(WSAENOTSOCK);
  237. return SOCKET_ERROR;
  238. }
  239. else if (GetLayerState()==unconnected || GetLayerState()==connecting || GetLayerState()==listening)
  240. {
  241. WSASetLastError(WSAENOTCONN);
  242. return SOCKET_ERROR;
  243. }
  244. if (!m_pNextLayer)
  245. {
  246. ASSERT(m_pOwnerSocket);
  247. return send(m_pOwnerSocket->GetSocketHandle(), (LPSTR)lpBuf, nBufLen, nFlags);
  248. }
  249. else
  250. {
  251. return m_pNextLayer->Send(lpBuf, nBufLen, nFlags);
  252. }
  253. }
  254. int CAsyncSocketExLayer::ReceiveNext(void *lpBuf, int nBufLen, int nFlags /*=0*/)
  255. {
  256. if (m_nCriticalError)
  257. {
  258. WSASetLastError(m_nCriticalError);
  259. return SOCKET_ERROR;
  260. }
  261. else if (GetLayerState()==notsock)
  262. {
  263. WSASetLastError(WSAENOTSOCK);
  264. return SOCKET_ERROR;
  265. }
  266. else if (GetLayerState()==unconnected || GetLayerState()==connecting || GetLayerState()==listening)
  267. {
  268. WSASetLastError(WSAENOTCONN);
  269. return SOCKET_ERROR;
  270. }
  271. if (!m_pNextLayer)
  272. {
  273. ASSERT(m_pOwnerSocket);
  274. return recv(m_pOwnerSocket->GetSocketHandle(), (LPSTR)lpBuf, nBufLen, nFlags);
  275. }
  276. else
  277. {
  278. return m_pNextLayer->Receive(lpBuf, nBufLen, nFlags);
  279. }
  280. }
  281. BOOL CAsyncSocketExLayer::ConnectNext(LPCTSTR lpszHostAddress, UINT nHostPort)
  282. {
  283. ASSERT(GetLayerState()==unconnected);
  284. ASSERT(m_pOwnerSocket);
  285. BOOL res = FALSE;
  286. if (m_pNextLayer)
  287. res = m_pNextLayer->Connect(lpszHostAddress, nHostPort);
  288. else if (m_nFamily == AF_INET)
  289. {
  290. USES_CONVERSION;
  291. ASSERT(lpszHostAddress != NULL);
  292. SOCKADDR_IN sockAddr;
  293. memset(&sockAddr,0,sizeof(sockAddr));
  294. LPSTR lpszAscii = T2A((LPTSTR)lpszHostAddress);
  295. sockAddr.sin_family = AF_INET;
  296. sockAddr.sin_addr.s_addr = inet_addr(lpszAscii);
  297. if (sockAddr.sin_addr.s_addr == INADDR_NONE)
  298. {
  299. LPHOSTENT lphost;
  300. lphost = gethostbyname(lpszAscii);
  301. if (lphost != NULL)
  302. sockAddr.sin_addr.s_addr = ((LPIN_ADDR)lphost->h_addr)->s_addr;
  303. else
  304. {
  305. WSASetLastError(WSAEINVAL);
  306. res = FALSE;
  307. }
  308. }
  309. sockAddr.sin_port = htons((u_short)nHostPort);
  310. res = (SOCKET_ERROR != connect(m_pOwnerSocket->GetSocketHandle(), (SOCKADDR*)&sockAddr, sizeof(sockAddr)) );
  311. }
  312. else if (m_nFamily == AF_INET6 || m_nFamily == AF_UNSPEC)
  313. {
  314. USES_CONVERSION;
  315. ASSERT(lpszHostAddress != NULL);
  316. addrinfo hints, *res0, *res1;
  317. SOCKET hSocket;
  318. int error;
  319. char port[10];
  320. freeaddrinfo(m_addrInfo);
  321. m_nextAddr = 0;
  322. m_addrInfo = 0;
  323. memset(&hints, 0, sizeof(addrinfo));
  324. hints.ai_family = m_nFamily;
  325. hints.ai_socktype = SOCK_STREAM;
  326. hints.ai_flags = 0;
  327. _snprintf(port, 9, "%lu", nHostPort);
  328. error = getaddrinfo(T2CA(lpszHostAddress), port, &hints, &res0);
  329. if (error)
  330. return FALSE;
  331. for (res1 = res0; res1; res1 = res1->ai_next)
  332. {
  333. if (m_nFamily == AF_UNSPEC)
  334. hSocket = socket(res1->ai_family, res1->ai_socktype, res1->ai_protocol);
  335. else
  336. hSocket = m_pOwnerSocket->GetSocketHandle();
  337. if (INVALID_SOCKET == hSocket)
  338. {
  339. res = FALSE;
  340. continue;
  341. }
  342. if (m_nFamily == AF_UNSPEC)
  343. {
  344. m_pOwnerSocket->m_SocketData.hSocket = hSocket;
  345. m_pOwnerSocket->AttachHandle(hSocket);
  346. if (!m_pOwnerSocket->AsyncSelect(m_lEvent))
  347. {
  348. m_pOwnerSocket->Close();
  349. res = FALSE;
  350. continue ;
  351. }
  352. if (m_pOwnerSocket->m_pFirstLayer)
  353. {
  354. if (WSAAsyncSelect(m_pOwnerSocket->m_SocketData.hSocket, m_pOwnerSocket->GetHelperWindowHandle(), m_pOwnerSocket->m_SocketData.nSocketIndex+WM_SOCKETEX_NOTIFY, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE) )
  355. {
  356. m_pOwnerSocket->Close();
  357. res = FALSE;
  358. continue;
  359. }
  360. }
  361. if (m_pOwnerSocket->m_pendingCallbacks.size())
  362. PostMessage(m_pOwnerSocket->GetHelperWindowHandle(), WM_USER + 2, (WPARAM)m_pOwnerSocket->m_SocketData.nSocketIndex, 0);
  363. }
  364. if (m_nFamily == AF_UNSPEC)
  365. {
  366. m_pOwnerSocket->m_SocketData.nFamily = m_nFamily = res1->ai_family;
  367. if (!m_pOwnerSocket->Bind(m_nSocketPort, m_lpszSocketAddress))
  368. {
  369. m_pOwnerSocket->m_SocketData.nFamily = m_nFamily = AF_UNSPEC;
  370. Close();
  371. continue;
  372. }
  373. }
  374. if (!( res = ( SOCKET_ERROR != connect(m_pOwnerSocket->GetSocketHandle(), res1->ai_addr, res1->ai_addrlen) ) )
  375. && WSAGetLastError() != WSAEWOULDBLOCK)
  376. {
  377. if (hints.ai_family == AF_UNSPEC)
  378. {
  379. m_nFamily = AF_UNSPEC;
  380. Close();
  381. }
  382. continue ;
  383. }
  384. m_nFamily = res1->ai_family;
  385. m_pOwnerSocket->m_SocketData.nFamily = res1->ai_family;
  386. res = TRUE;
  387. break;
  388. }
  389. if (res1)
  390. res1 = res0->ai_next;
  391. if (res1)
  392. {
  393. m_addrInfo = res0;
  394. m_nextAddr = res1;
  395. }
  396. else
  397. freeaddrinfo(res0);
  398. if (INVALID_SOCKET == m_pOwnerSocket->GetSocketHandle())
  399. res = FALSE ;
  400. }
  401. if (res || WSAGetLastError() == WSAEWOULDBLOCK)
  402. {
  403. SetLayerState(connecting);
  404. }
  405. return res;
  406. }
  407. BOOL CAsyncSocketExLayer::ConnectNext( const SOCKADDR* lpSockAddr, int nSockAddrLen )
  408. {
  409. ASSERT(GetLayerState()==unconnected);
  410. ASSERT(m_pOwnerSocket);
  411. BOOL res;
  412. if (m_pNextLayer)
  413. res=m_pNextLayer->Connect(lpSockAddr, nSockAddrLen);
  414. else
  415. res = (SOCKET_ERROR!=connect(m_pOwnerSocket->GetSocketHandle(), lpSockAddr, nSockAddrLen));
  416. if (res || WSAGetLastError()==WSAEWOULDBLOCK)
  417. SetLayerState(connecting);
  418. return res;
  419. }
  420. //Gets the address of the peer socket to which the socket is connected
  421. #ifdef _AFX
  422. BOOL CAsyncSocketExLayer::GetPeerName( CString& rPeerAddress, UINT& rPeerPort )
  423. {
  424. return GetPeerNameNext(rPeerAddress, rPeerPort);
  425. }
  426. BOOL CAsyncSocketExLayer::GetPeerNameNext( CString& rPeerAddress, UINT& rPeerPort )
  427. {
  428. if (m_pNextLayer)
  429. return m_pNextLayer->GetPeerName(rPeerAddress, rPeerPort);
  430. else
  431. {
  432. SOCKADDR* sockAddr;
  433. int nSockAddrLen;
  434. if (m_nFamily == AF_INET6)
  435. {
  436. sockAddr = (SOCKADDR*)new SOCKADDR_IN6;
  437. nSockAddrLen = sizeof(SOCKADDR_IN6);
  438. }
  439. else if (m_nFamily == AF_INET)
  440. {
  441. sockAddr = (SOCKADDR*)new SOCKADDR_IN;
  442. nSockAddrLen = sizeof(SOCKADDR_IN);
  443. }
  444. memset(sockAddr, 0, nSockAddrLen);
  445. BOOL bResult = GetPeerName(sockAddr, &nSockAddrLen);
  446. if (bResult)
  447. {
  448. if (m_nFamily == AF_INET6)
  449. {
  450. rPeerPort = ntohs(((SOCKADDR_IN6*)sockAddr)->sin6_port);
  451. LPTSTR buf = Inet6AddrToString(((SOCKADDR_IN6*)sockAddr)->sin6_addr);
  452. rPeerAddress = buf;
  453. delete [] buf;
  454. }
  455. else if (m_nFamily == AF_INET)
  456. {
  457. rPeerPort = ntohs(((SOCKADDR_IN*)sockAddr)->sin_port);
  458. rPeerAddress = inet_ntoa(((SOCKADDR_IN*)sockAddr)->sin_addr);
  459. }
  460. else
  461. {
  462. delete sockAddr;
  463. return FALSE;
  464. }
  465. }
  466. delete sockAddr;
  467. return bResult;
  468. }
  469. }
  470. #endif //_AFX
  471. BOOL CAsyncSocketExLayer::GetPeerName( SOCKADDR* lpSockAddr, int* lpSockAddrLen )
  472. {
  473. return GetPeerNameNext(lpSockAddr, lpSockAddrLen);
  474. }
  475. BOOL CAsyncSocketExLayer::GetPeerNameNext( SOCKADDR* lpSockAddr, int* lpSockAddrLen )
  476. {
  477. if (m_pNextLayer)
  478. return m_pNextLayer->GetPeerName(lpSockAddr, lpSockAddrLen);
  479. else
  480. {
  481. ASSERT(m_pOwnerSocket);
  482. if ( !getpeername(m_pOwnerSocket->GetSocketHandle(), lpSockAddr, lpSockAddrLen) )
  483. return TRUE;
  484. else
  485. return FALSE;
  486. }
  487. }
  488. //Gets the address of the sock socket to which the socket is connected
  489. #ifdef _AFX
  490. BOOL CAsyncSocketExLayer::GetSockName( CString& rSockAddress, UINT& rSockPort )
  491. {
  492. return GetSockNameNext(rSockAddress, rSockPort);
  493. }
  494. BOOL CAsyncSocketExLayer::GetSockNameNext( CString& rSockAddress, UINT& rSockPort )
  495. {
  496. if (m_pNextLayer)
  497. return m_pNextLayer->GetSockName(rSockAddress, rSockPort);
  498. else
  499. {
  500. SOCKADDR* sockAddr;
  501. int nSockAddrLen;
  502. if (m_nFamily == AF_INET6)
  503. {
  504. sockAddr = (SOCKADDR*)new SOCKADDR_IN6;
  505. nSockAddrLen = sizeof(SOCKADDR_IN6);
  506. }
  507. else if (m_nFamily == AF_INET)
  508. {
  509. sockAddr = (SOCKADDR*)new SOCKADDR_IN;
  510. nSockAddrLen = sizeof(SOCKADDR_IN);
  511. }
  512. memset(sockAddr, 0, nSockAddrLen);
  513. BOOL bResult = GetSockName(sockAddr, &nSockAddrLen);
  514. if (bResult)
  515. {
  516. if (m_nFamily == AF_INET6)
  517. {
  518. rSockPort = ntohs(((SOCKADDR_IN6*)sockAddr)->sin6_port);
  519. LPTSTR buf = Inet6AddrToString(((SOCKADDR_IN6*)sockAddr)->sin6_addr);
  520. rSockAddress = buf;
  521. delete [] buf;
  522. }
  523. else if (m_nFamily == AF_INET)
  524. {
  525. rSockPort = ntohs(((SOCKADDR_IN*)sockAddr)->sin_port);
  526. rSockAddress = inet_ntoa(((SOCKADDR_IN*)sockAddr)->sin_addr);
  527. }
  528. else
  529. {
  530. delete sockAddr;
  531. return FALSE;
  532. }
  533. }
  534. delete sockAddr;
  535. return bResult;
  536. }
  537. }
  538. #endif //_AFX
  539. BOOL CAsyncSocketExLayer::GetSockName( SOCKADDR* lpSockAddr, int* lpSockAddrLen )
  540. {
  541. return GetSockNameNext(lpSockAddr, lpSockAddrLen);
  542. }
  543. BOOL CAsyncSocketExLayer::GetSockNameNext( SOCKADDR* lpSockAddr, int* lpSockAddrLen )
  544. {
  545. if (m_pNextLayer)
  546. return m_pNextLayer->GetSockName(lpSockAddr, lpSockAddrLen);
  547. else
  548. {
  549. ASSERT(m_pOwnerSocket);
  550. if ( !getsockname(m_pOwnerSocket->GetSocketHandle(), lpSockAddr, lpSockAddrLen) )
  551. return TRUE;
  552. else
  553. return FALSE;
  554. }
  555. }
  556. void CAsyncSocketExLayer::Init(CAsyncSocketExLayer *pPrevLayer, CAsyncSocketEx *pOwnerSocket)
  557. {
  558. ASSERT(pOwnerSocket);
  559. m_pPrevLayer=pPrevLayer;
  560. m_pOwnerSocket=pOwnerSocket;
  561. m_pNextLayer=0;
  562. #ifndef NOSOCKETSTATES
  563. SetLayerState(pOwnerSocket->GetState());
  564. #endif //NOSOCKETSTATES
  565. }
  566. int CAsyncSocketExLayer::GetLayerState()
  567. {
  568. return m_nLayerState;
  569. }
  570. void CAsyncSocketExLayer::SetLayerState(int nLayerState)
  571. {
  572. ASSERT(m_pOwnerSocket);
  573. int nOldLayerState=GetLayerState();
  574. m_nLayerState=nLayerState;
  575. if (nOldLayerState!=nLayerState)
  576. DoLayerCallback(LAYERCALLBACK_STATECHANGE, GetLayerState(), nOldLayerState);
  577. }
  578. void CAsyncSocketExLayer::CallEvent(int nEvent, int nErrorCode)
  579. {
  580. if (m_nCriticalError)
  581. {
  582. return;
  583. }
  584. m_nCriticalError = nErrorCode;
  585. switch (nEvent)
  586. {
  587. case FD_READ:
  588. case FD_FORCEREAD:
  589. if (GetLayerState()==connecting && !nErrorCode)
  590. {
  591. m_nPendingEvents |= nEvent;
  592. break;
  593. }
  594. else if (GetLayerState()==attached)
  595. SetLayerState(connected);
  596. if (nEvent & FD_READ)
  597. m_nPendingEvents &= ~FD_READ;
  598. else
  599. m_nPendingEvents &= ~FD_FORCEREAD;
  600. if (GetLayerState()==connected || nErrorCode)
  601. {
  602. if (nErrorCode)
  603. SetLayerState(aborted);
  604. OnReceive(nErrorCode);
  605. }
  606. break;
  607. case FD_WRITE:
  608. if (GetLayerState()==connecting && !nErrorCode)
  609. {
  610. m_nPendingEvents |= nEvent;
  611. break;
  612. }
  613. else if (GetLayerState()==attached)
  614. SetLayerState(connected);
  615. m_nPendingEvents &= ~FD_WRITE;
  616. if (GetLayerState()==connected || nErrorCode)
  617. {
  618. if (nErrorCode)
  619. SetLayerState(aborted);
  620. OnSend(nErrorCode);
  621. }
  622. break;
  623. case FD_CONNECT:
  624. if (GetLayerState()==connecting || GetLayerState() == attached)
  625. {
  626. if (!nErrorCode)
  627. SetLayerState(connected);
  628. else
  629. {
  630. if (!m_pNextLayer && m_nextAddr)
  631. if (TryNextProtocol())
  632. {
  633. m_nCriticalError = 0;
  634. return;
  635. }
  636. SetLayerState(aborted);
  637. }
  638. m_nPendingEvents &= ~FD_CONNECT;
  639. OnConnect(nErrorCode);
  640. if (!nErrorCode)
  641. {
  642. if ((m_nPendingEvents & FD_READ) && GetLayerState()==connected)
  643. OnReceive(0);
  644. if ((m_nPendingEvents & FD_FORCEREAD) && GetLayerState()==connected)
  645. OnReceive(0);
  646. if ((m_nPendingEvents & FD_WRITE) && GetLayerState()==connected)
  647. OnSend(0);
  648. }
  649. m_nPendingEvents = 0;
  650. }
  651. break;
  652. case FD_ACCEPT:
  653. if (GetLayerState()==listening)
  654. {
  655. if (nErrorCode)
  656. SetLayerState(aborted);
  657. m_nPendingEvents &= ~FD_ACCEPT;
  658. OnAccept(nErrorCode);
  659. }
  660. break;
  661. case FD_CLOSE:
  662. if (GetLayerState()==connected || GetLayerState()==attached)
  663. {
  664. if (nErrorCode)
  665. SetLayerState(aborted);
  666. else
  667. SetLayerState(closed);
  668. m_nPendingEvents &= ~FD_CLOSE;
  669. OnClose(nErrorCode);
  670. }
  671. break;
  672. }
  673. }
  674. //Creates a socket
  675. BOOL CAsyncSocketExLayer::Create(UINT nSocketPort, int nSocketType,
  676. long lEvent, LPCTSTR lpszSocketAddress, int nFamily /*=AF_INET*/)
  677. {
  678. return CreateNext(nSocketPort, nSocketType, lEvent, lpszSocketAddress, nFamily);
  679. }
  680. BOOL CAsyncSocketExLayer::CreateNext(UINT nSocketPort, int nSocketType, long lEvent, LPCTSTR lpszSocketAddress, int nFamily /*=AF_INET*/)
  681. {
  682. ASSERT(GetLayerState()==notsock);
  683. BOOL res = FALSE;
  684. m_nFamily = nFamily;
  685. if (m_pNextLayer)
  686. res = m_pNextLayer->Create(nSocketPort, nSocketType, lEvent, lpszSocketAddress, nFamily);
  687. else if (m_nFamily == AF_UNSPEC)
  688. {
  689. m_lEvent = lEvent;
  690. delete [] m_lpszSocketAddress;
  691. if (lpszSocketAddress && *lpszSocketAddress)
  692. {
  693. m_lpszSocketAddress = new TCHAR[_tcslen(lpszSocketAddress) + 1];
  694. _tcscpy(m_lpszSocketAddress, lpszSocketAddress);
  695. }
  696. else
  697. m_lpszSocketAddress = 0;
  698. m_nSocketPort = nSocketPort;
  699. res = TRUE;
  700. }
  701. else
  702. {
  703. SOCKET hSocket=socket(nFamily, nSocketType, 0);
  704. if (hSocket == INVALID_SOCKET)
  705. {
  706. m_pOwnerSocket->Close();
  707. return FALSE;
  708. }
  709. m_pOwnerSocket->m_SocketData.hSocket=hSocket;
  710. m_pOwnerSocket->AttachHandle(hSocket);
  711. if (!m_pOwnerSocket->AsyncSelect(lEvent))
  712. {
  713. m_pOwnerSocket->Close();
  714. return FALSE;
  715. }
  716. if (m_pOwnerSocket->m_pFirstLayer)
  717. {
  718. if (WSAAsyncSelect(m_pOwnerSocket->m_SocketData.hSocket, m_pOwnerSocket->GetHelperWindowHandle(), m_pOwnerSocket->m_SocketData.nSocketIndex+WM_SOCKETEX_NOTIFY, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE) )
  719. {
  720. m_pOwnerSocket->Close();
  721. return FALSE;
  722. }
  723. }
  724. if (!m_pOwnerSocket->Bind(nSocketPort, lpszSocketAddress))
  725. {
  726. m_pOwnerSocket->Close();
  727. return FALSE;
  728. }
  729. res = TRUE;
  730. }
  731. if (res)
  732. SetLayerState(unconnected);
  733. return res;
  734. }
  735. int CAsyncSocketExLayer::DoLayerCallback(int nType, int nParam1, int nParam2, char* str /*=0*/)
  736. {
  737. if (!m_pOwnerSocket)
  738. return 0;
  739. int nError = WSAGetLastError();
  740. t_callbackMsg msg;
  741. msg.pLayer = this;
  742. msg.nType = nType;
  743. msg.nParam1 = nParam1;
  744. msg.nParam2 = nParam2;
  745. msg.str = str;
  746. m_pOwnerSocket->AddCallbackNotification(msg);
  747. WSASetLastError(nError);
  748. return 0;
  749. }
  750. BOOL CAsyncSocketExLayer::Listen( int nConnectionBacklog)
  751. {
  752. return ListenNext( nConnectionBacklog);
  753. }
  754. BOOL CAsyncSocketExLayer::ListenNext( int nConnectionBacklog)
  755. {
  756. ASSERT(GetLayerState()==unconnected);
  757. BOOL res;
  758. if (m_pNextLayer)
  759. res=m_pNextLayer->Listen(nConnectionBacklog);
  760. else
  761. res=listen(m_pOwnerSocket->GetSocketHandle(), nConnectionBacklog);
  762. if (res!=SOCKET_ERROR)
  763. {
  764. SetLayerState(listening);
  765. }
  766. return res!=SOCKET_ERROR;
  767. }
  768. BOOL CAsyncSocketExLayer::Accept( CAsyncSocketEx& rConnectedSocket, SOCKADDR* lpSockAddr /*=NULL*/, int* lpSockAddrLen /*=NULL*/ )
  769. {
  770. return AcceptNext(rConnectedSocket, lpSockAddr, lpSockAddrLen);
  771. }
  772. BOOL CAsyncSocketExLayer::AcceptNext( CAsyncSocketEx& rConnectedSocket, SOCKADDR* lpSockAddr /*=NULL*/, int* lpSockAddrLen /*=NULL*/ )
  773. {
  774. ASSERT(GetLayerState()==listening);
  775. BOOL res;
  776. if (m_pNextLayer)
  777. res=m_pNextLayer->Accept(rConnectedSocket, lpSockAddr, lpSockAddrLen);
  778. else
  779. {
  780. SOCKET hTemp = accept(m_pOwnerSocket->m_SocketData.hSocket, lpSockAddr, lpSockAddrLen);
  781. if (hTemp == INVALID_SOCKET)
  782. return FALSE;
  783. VERIFY(rConnectedSocket.InitAsyncSocketExInstance());
  784. rConnectedSocket.m_SocketData.hSocket=hTemp;
  785. rConnectedSocket.AttachHandle(hTemp);
  786. rConnectedSocket.SetFamily(GetFamily());
  787. #ifndef NOSOCKETSTATES
  788. rConnectedSocket.SetState(connected);
  789. #endif //NOSOCKETSTATES
  790. }
  791. return TRUE;
  792. }
  793. BOOL CAsyncSocketExLayer::ShutDown(int nHow /*=sends*/)
  794. {
  795. return ShutDownNext(nHow);
  796. }
  797. BOOL CAsyncSocketExLayer::ShutDownNext(int nHow /*=sends*/)
  798. {
  799. if (m_nCriticalError)
  800. {
  801. WSASetLastError(m_nCriticalError);
  802. return FALSE;
  803. }
  804. else if (GetLayerState()==notsock)
  805. {
  806. WSASetLastError(WSAENOTSOCK);
  807. return FALSE;
  808. }
  809. else if (GetLayerState()==unconnected || GetLayerState()==connecting || GetLayerState()==listening)
  810. {
  811. WSASetLastError(WSAENOTCONN);
  812. return FALSE;
  813. }
  814. if (!m_pNextLayer)
  815. {
  816. ASSERT(m_pOwnerSocket);
  817. return shutdown(m_pOwnerSocket->GetSocketHandle(), nHow);
  818. }
  819. else
  820. {
  821. return m_pNextLayer->ShutDown(nHow);
  822. }
  823. }
  824. int CAsyncSocketExLayer::GetFamily() const
  825. {
  826. return m_nFamily;
  827. }
  828. bool CAsyncSocketExLayer::SetFamily(int nFamily)
  829. {
  830. if (m_nFamily != AF_UNSPEC)
  831. return false;
  832. m_nFamily = nFamily;
  833. return true;
  834. }
  835. bool CAsyncSocketExLayer::TryNextProtocol()
  836. {
  837. m_pOwnerSocket->DetachHandle(m_pOwnerSocket->m_SocketData.hSocket);
  838. closesocket(m_pOwnerSocket->m_SocketData.hSocket);
  839. m_pOwnerSocket->m_SocketData.hSocket = INVALID_SOCKET;
  840. BOOL ret = FALSE;
  841. for (; m_nextAddr; m_nextAddr = m_nextAddr->ai_next)
  842. {
  843. m_pOwnerSocket->m_SocketData.hSocket = socket(m_nextAddr->ai_family, m_nextAddr->ai_socktype, m_nextAddr->ai_protocol);
  844. if (m_pOwnerSocket->m_SocketData.hSocket == INVALID_SOCKET)
  845. continue;
  846. m_pOwnerSocket->AttachHandle(m_pOwnerSocket->m_SocketData.hSocket);
  847. if (!m_pOwnerSocket->AsyncSelect(m_lEvent))
  848. {
  849. m_pOwnerSocket->DetachHandle(m_pOwnerSocket->m_SocketData.hSocket);
  850. closesocket(m_pOwnerSocket->m_SocketData.hSocket);
  851. m_pOwnerSocket->m_SocketData.hSocket = INVALID_SOCKET;
  852. continue;
  853. }
  854. #ifndef NOLAYERS
  855. if (m_pOwnerSocket->m_pFirstLayer)
  856. {
  857. if (WSAAsyncSelect(m_pOwnerSocket->m_SocketData.hSocket, m_pOwnerSocket->GetHelperWindowHandle(), m_pOwnerSocket->m_SocketData.nSocketIndex+WM_SOCKETEX_NOTIFY, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE))
  858. {
  859. m_pOwnerSocket->DetachHandle(m_pOwnerSocket->m_SocketData.hSocket);
  860. closesocket(m_pOwnerSocket->m_SocketData.hSocket);
  861. m_pOwnerSocket->m_SocketData.hSocket = INVALID_SOCKET;
  862. continue;
  863. }
  864. }
  865. #endif //NOLAYERS
  866. m_pOwnerSocket->m_SocketData.nFamily = m_nextAddr->ai_family;
  867. m_nFamily = m_nextAddr->ai_family;
  868. if (!m_pOwnerSocket->Bind(m_nSocketPort, m_lpszSocketAddress))
  869. {
  870. m_pOwnerSocket->DetachHandle(m_pOwnerSocket->m_SocketData.hSocket);
  871. closesocket(m_pOwnerSocket->m_SocketData.hSocket);
  872. m_pOwnerSocket->m_SocketData.hSocket = INVALID_SOCKET;
  873. continue;
  874. }
  875. if (connect(m_pOwnerSocket->GetSocketHandle(), m_nextAddr->ai_addr, m_nextAddr->ai_addrlen) == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
  876. {
  877. m_pOwnerSocket->DetachHandle(m_pOwnerSocket->m_SocketData.hSocket);
  878. closesocket(m_pOwnerSocket->m_SocketData.hSocket);
  879. m_pOwnerSocket->m_SocketData.hSocket = INVALID_SOCKET;
  880. continue;
  881. }
  882. SetLayerState(connecting);
  883. ret = true;
  884. break;
  885. }
  886. if (m_nextAddr)
  887. m_nextAddr = m_nextAddr->ai_next;
  888. if (!m_nextAddr)
  889. {
  890. freeaddrinfo(m_addrInfo);
  891. m_nextAddr = 0;
  892. m_addrInfo = 0;
  893. }
  894. if (m_pOwnerSocket->m_SocketData.hSocket == INVALID_SOCKET || !ret)
  895. return FALSE;
  896. else
  897. return TRUE;
  898. }
  899. void CAsyncSocketExLayer::LogSocketMessage(int nMessageType, LPCTSTR pMsgFormat)
  900. {
  901. if (m_pPrevLayer)
  902. m_pPrevLayer->LogSocketMessage(nMessageType, pMsgFormat);
  903. else
  904. m_pOwnerSocket->LogSocketMessage(nMessageType, pMsgFormat);
  905. }