home *** CD-ROM | disk | FTP | other *** search
/ Computer Shopper 217 / DPCS0306DVD.ISO / Toolkit / Internet / FileZilla / Server / FileZilla_Server-0.9.11.exe / source / AsyncSocketExLayer.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2005-04-26  |  25.7 KB  |  1,004 lines

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