home *** CD-ROM | disk | FTP | other *** search
/ Freelog 115 / FreelogNo115-MaiJuin2013.iso / Internet / Filezilla Server / FileZilla_Server-0_9_41.exe / source / AsyncSocketEx.h < prev    next >
Encoding:
C/C++ Source or Header  |  2011-11-06  |  11.8 KB  |  373 lines

  1. /*CAsyncSocketEx by Tim Kosse (Tim.Kosse@gmx.de)
  2.             Version 1.3 (2003-04-26)
  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. */
  63.  
  64. #if !defined(AFX_ASYNCSOCKETEX_H__AA9E4531_63B1_442F_9A71_09B2FEEDF34E__INCLUDED_)
  65. #define AFX_ASYNCSOCKETEX_H__AA9E4531_63B1_442F_9A71_09B2FEEDF34E__INCLUDED_
  66.  
  67. #if _MSC_VER > 1000
  68. #pragma once
  69. #endif // _MSC_VER > 1000
  70.  
  71. #ifdef _AFX
  72. #define CStdString CString
  73. #define CStdStringW CStringW
  74. #define CStdStringA CStringA
  75. #endif //_AFX
  76.  
  77. #define FD_FORCEREAD (1<<15)
  78.  
  79. #include <winsock2.h>
  80. #include <Ws2tcpip.h>
  81.  
  82. class CAsyncSocketExHelperWindow;
  83.  
  84. extern "C" {
  85.     typedef int (FAR PASCAL *t_getaddrinfo)(const char* nodename, const char* servname, const struct addrinfo* hints, struct addrinfo** res);
  86.     typedef    void (FAR PASCAL *t_freeaddrinfo)(struct addrinfo* ai);
  87. }
  88.  
  89. #ifndef NOLAYERS
  90. class CAsyncSocketExLayer;
  91.  
  92. struct t_callbackMsg
  93. {
  94.     CAsyncSocketExLayer* pLayer;
  95.     int nType;
  96.     int nParam1;
  97.     int nParam2;
  98.     char* str;
  99. };
  100.  
  101. #endif //NOLAYERS
  102.  
  103. class CCriticalSectionWrapper;
  104. class CAsyncSocketEx
  105. {
  106. public:
  107.     ///////////////////////////////////////
  108.     //Functions that imitate CAsyncSocket//
  109.     ///////////////////////////////////////
  110.  
  111.     //Construction
  112.     //------------
  113.  
  114.     //Constructs a CAsyncSocketEx object.
  115.     CAsyncSocketEx();
  116.     virtual ~CAsyncSocketEx();
  117.  
  118.     //Creates a socket.
  119.     BOOL Create(UINT nSocketPort = 0, int nSocketType = SOCK_STREAM,
  120.                 long lEvent = FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT |    FD_CONNECT | FD_CLOSE,
  121.                 LPCTSTR lpszSocketAddress = NULL, int nFamily = AF_INET, bool reusable = false);
  122.  
  123.     //Attributes
  124.     //---------
  125.  
  126.     //Attaches a socket handle to a CAsyncSocketEx object.
  127.     BOOL Attach( SOCKET hSocket,
  128.                 long lEvent = FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT |
  129.                 FD_CONNECT | FD_CLOSE );
  130.  
  131.     //Detaches a socket handle from a CAsyncSocketEx object.
  132.     SOCKET Detach( );
  133.  
  134.     //Gets the error status for the last operation that failed.
  135.     static int GetLastError();
  136.  
  137.     //Gets the address of the peer socket to which the socket is connected.
  138.     BOOL GetPeerName( CStdString& rPeerAddress, UINT& rPeerPort );
  139.  
  140.     //Gets the local name for a socket.
  141.     BOOL GetSockName( CStdString& rSocketAddress, UINT& rSocketPort );
  142.  
  143.     //Retrieves a socket option.
  144.     BOOL GetSockOpt(int nOptionName, void* lpOptionValue, int* lpOptionLen, int nLevel = SOL_SOCKET);
  145.  
  146.     //Sets a socket option.
  147.     BOOL SetSockOpt(int nOptionName, const void* lpOptionValue, int nOptionLen, int nLevel = SOL_SOCKET);
  148.  
  149.     //Gets the socket family
  150.     int GetFamily() const;
  151.  
  152.     //Sets the socket family
  153.     bool SetFamily(int nFamily);
  154.  
  155.     //Operations
  156.     //----------
  157.  
  158.     //Accepts a connection on the socket.
  159.     virtual BOOL Accept( CAsyncSocketEx& rConnectedSocket, SOCKADDR* lpSockAddr = NULL, int* lpSockAddrLen = NULL );
  160.  
  161.     //Requests event notification for the socket.
  162.     BOOL AsyncSelect( long lEvent = FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE );
  163.  
  164.     //Associates a local address with the socket.
  165.     BOOL Bind(UINT nSocketPort, LPCTSTR lpszSocketAddress);
  166.     BOOL Bind(const SOCKADDR* lpSockAddr, int nSockAddrLen);
  167.  
  168.     //Closes the socket.
  169.     virtual void Close();
  170.  
  171.     //Establishes a connection to a peer socket.
  172.     virtual BOOL Connect(LPCTSTR lpszHostAddress, UINT nHostPort);
  173.     virtual BOOL Connect(const SOCKADDR* lpSockAddr, int nSockAddrLen);
  174.  
  175.     //Controls the mode of the socket.
  176.     BOOL IOCtl( long lCommand, DWORD* lpArgument );
  177.  
  178.     //Establishes a socket to listen for incoming connection requests.
  179.     BOOL Listen( int nConnectionBacklog = 5 );
  180.  
  181.     //Receives data from the socket.
  182.     virtual int Receive(void* lpBuf, int nBufLen, int nFlags = 0);
  183.  
  184.     //Sends data to a connected socket.
  185.     virtual int Send(const void* lpBuf, int nBufLen, int nFlags = 0);
  186.  
  187.     //Disables Send and/or Receive calls on the socket.
  188.     BOOL ShutDown( int nHow = sends );
  189.     enum { receives = 0, sends = 1, both = 2 };
  190.  
  191.     //Overridable Notification Functions
  192.     //----------------------------------
  193.  
  194.     //Notifies a listening socket that it can accept pending connection requests by calling Accept.
  195.     virtual void OnAccept(int nErrorCode);
  196.  
  197.     //Notifies a socket that the socket connected to it has closed.
  198.     virtual void OnClose(int nErrorCode);
  199.  
  200.     //Notifies a connecting socket that the connection attempt is complete, whether successfully or in error.
  201.     virtual void OnConnect(int nErrorCode);
  202.  
  203.     //Notifies a listening socket that there is data to be retrieved by calling Receive.
  204.     virtual void OnReceive(int nErrorCode);
  205.  
  206.     //Notifies a socket that it can send data by calling Send.
  207.     virtual void OnSend(int nErrorCode);
  208.  
  209.     ////////////////////////
  210.     //Additional functions//
  211.     ////////////////////////
  212.  
  213. #ifndef NOLAYERS
  214.     //Resets layer chain.
  215.     void RemoveAllLayers();
  216.  
  217.     //Attaches a new layer to the socket.
  218.     BOOL AddLayer(CAsyncSocketExLayer *pLayer);
  219.  
  220.     //Is a layer attached to the socket?
  221.     BOOL IsLayerAttached() const;
  222. #endif //NOLAYERS
  223.  
  224.     //Returns the handle of the socket.
  225.     SOCKET GetSocketHandle();
  226.  
  227.     //Trigers an event on the socket
  228.     // Any combination of FD_READ, FD_WRITE, FD_CLOSE, FD_ACCEPT, FD_CONNECT and FD_FORCEREAD is valid for lEvent.
  229.     BOOL TriggerEvent(long lEvent);
  230.  
  231. protected:
  232.     //Strucure to hold the socket data
  233.     struct t_AsyncSocketExData
  234.     {
  235.         SOCKET hSocket; //Socket handle
  236.         int nSocketIndex; //Index of socket, required by CAsyncSocketExHelperWindow
  237.         int nFamily;
  238.         addrinfo *addrInfo, *nextAddr; // Iterate through protocols on connect failure
  239.         bool onCloseCalled; // Set to true on first received OnClose event
  240.     } m_SocketData;
  241.  
  242.     //If using layers, only the events specified with m_lEvent will send to the event handlers.
  243.     long m_lEvent;
  244.  
  245.     //AsyncGetHostByName
  246.     char *m_pAsyncGetHostByNameBuffer; //Buffer for hostend structure
  247.     HANDLE m_hAsyncGetHostByNameHandle; //TaskHandle
  248.     int m_nAsyncGetHostByNamePort; //Port to connect to
  249.  
  250.     //Returns the handle of the helper window
  251.     HWND GetHelperWindowHandle();
  252.  
  253.     //Attaches socket handle to helper window
  254.     void AttachHandle(SOCKET hSocket);
  255.  
  256.     //Detaches socket handle to helper window
  257.     void DetachHandle(SOCKET hSocket);
  258.  
  259.     //Critical section for thread synchronization
  260.     static CCriticalSectionWrapper m_sGlobalCriticalSection;
  261.  
  262.     //Pointer to the data of the local thread
  263.     struct t_AsyncSocketExThreadData
  264.     {
  265.         CAsyncSocketExHelperWindow *m_pHelperWindow;
  266.         int nInstanceCount;
  267.         DWORD nThreadId;
  268.         std::list<CAsyncSocketEx*> layerCloseNotify;
  269.     } *m_pLocalAsyncSocketExThreadData;
  270.  
  271.     //List of the data structures for all threads
  272.     static struct t_AsyncSocketExThreadDataList
  273.     {
  274.         t_AsyncSocketExThreadDataList *pNext;
  275.         t_AsyncSocketExThreadData *pThreadData;
  276.     } *m_spAsyncSocketExThreadDataList;
  277.  
  278.     //Initializes Thread data and helper window, fills m_pLocalAsyncSocketExThreadData
  279.     BOOL InitAsyncSocketExInstance();
  280.  
  281.     //Destroys helper window after last instance of CAsyncSocketEx in current thread has been closed
  282.     void FreeAsyncSocketExInstance();
  283.  
  284.     // Iterate through protocols on failure
  285.     bool TryNextProtocol();
  286.  
  287.     void ResendCloseNotify();
  288.  
  289. #ifndef NOLAYERS
  290.     // Add a new notification to the list of pending callbacks
  291.     void AddCallbackNotification(const t_callbackMsg& msg);
  292. #endif // NOLAYERS
  293.  
  294. #ifndef NOSOCKETSTATES
  295.     int m_nPendingEvents;
  296.  
  297.     int GetState() const;
  298.     void SetState(int nState);
  299.  
  300.     int m_nState;
  301. #endif //NOSOCKETSTATES
  302.  
  303. #ifndef NOLAYERS
  304.     //Layer chain
  305.     CAsyncSocketExLayer *m_pFirstLayer;
  306.     CAsyncSocketExLayer *m_pLastLayer;
  307.  
  308.     friend CAsyncSocketExLayer;
  309.  
  310.     //Called by the layers to notify application of some events
  311.     virtual int OnLayerCallback(std::list<t_callbackMsg>& callbacks);
  312. #endif //NOLAYERS
  313.  
  314.     // Used by Bind with AF_UNSPEC sockets
  315.     UINT m_nSocketPort;
  316.     LPTSTR m_lpszSocketAddress;
  317.  
  318.     // imported IPv6 functions
  319.     static HMODULE m_hDll;
  320.  
  321.     static t_getaddrinfo p_getaddrinfo;
  322.     static t_freeaddrinfo p_freeaddrinfo;
  323.  
  324.     friend CAsyncSocketExHelperWindow;
  325.  
  326. #ifndef NOLAYERS
  327.     // Pending callbacks
  328.     std::list<t_callbackMsg> m_pendingCallbacks;
  329. #endif // NOLAYERS
  330.  
  331. private:
  332.     BOOL GetPeerName( SOCKADDR* lpSockAddr, int* lpSockAddrLen );
  333.     BOOL GetSockName( SOCKADDR* lpSockAddr, int* lpSockAddrLen );
  334. };
  335.  
  336. #ifndef NOLAYERS
  337. #define LAYERCALLBACK_STATECHANGE 0
  338. #define LAYERCALLBACK_LAYERSPECIFIC 1
  339. #endif //NOLAYERS
  340.  
  341. enum SocketState
  342. {
  343.     notsock,
  344.     unconnected,
  345.     connecting,
  346.     listening,
  347.     connected,
  348.     closed,
  349.     aborted,
  350.     attached
  351. };
  352.  
  353. #ifdef _UNICODE
  354. #define _sntprintf _snwprintf
  355. #else
  356. #define _sntprintf _snprintf
  357. #endif
  358.  
  359. inline TCHAR* Inet6AddrToString(in6_addr& addr)
  360. {
  361.     LPTSTR buf = new TCHAR[512];
  362.  
  363.     _sntprintf(buf, 512, _T("%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x"),
  364.              addr.s6_bytes[0], addr.s6_bytes[1], addr.s6_bytes[2], addr.s6_bytes[3],
  365.              addr.s6_bytes[4], addr.s6_bytes[5], addr.s6_bytes[6], addr.s6_bytes[7],
  366.              addr.s6_bytes[8], addr.s6_bytes[9], addr.s6_bytes[10], addr.s6_bytes[11],
  367.              addr.s6_bytes[12], addr.s6_bytes[13], addr.s6_bytes[14], addr.s6_bytes[15]);
  368.  
  369.     return buf ;
  370. }
  371.  
  372. #endif // !defined(AFX_ASYNCSOCKETEX_H__AA9E4531_63B1_442F_9A71_09B2FEEDF34E__INCLUDED_)
  373.