/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: hxcloakedtcp.h,v 1.1.36.1 2004/07/09 02:08:59 hubbe Exp $
 * 
 * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
 * 
 * The contents of this file, and the files included with this file,
 * are subject to the current version of the RealNetworks Public
 * Source License (the "RPSL") available at
 * http://www.helixcommunity.org/content/rpsl unless you have licensed
 * the file under the current version of the RealNetworks Community
 * Source License (the "RCSL") available at
 * http://www.helixcommunity.org/content/rcsl, in which case the RCSL
 * will apply. You may also obtain the license terms directly from
 * RealNetworks.  You may not use this file except in compliance with
 * the RPSL or, if you have a valid RCSL with RealNetworks applicable
 * to this file, the RCSL.  Please see the applicable RPSL or RCSL for
 * the rights, obligations and limitations governing use of the
 * contents of the file.
 * 
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL") in which case the provisions of the GPL are applicable
 * instead of those above. If you wish to allow use of your version of
 * this file only under the terms of the GPL, and not to allow others
 * to use your version of this file under the terms of either the RPSL
 * or RCSL, indicate your decision by deleting the provisions above
 * and replace them with the notice and other provisions required by
 * the GPL. If you do not delete the provisions above, a recipient may
 * use your version of this file under the terms of any one of the
 * RPSL, the RCSL or the GPL.
 * 
 * This file is part of the Helix DNA Technology. RealNetworks is the
 * developer of the Original Code and owns the copyrights in the
 * portions it created.
 * 
 * This file, and the files included with this file, is distributed
 * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
 * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
 * ENJOYMENT OR NON-INFRINGEMENT.
 * 
 * Technology Compatibility Kit Test Suite(s) Location:
 *    http://www.helixcommunity.org/content/tck
 * 
 * Contributor(s):
 * 
 * ***** END LICENSE BLOCK ***** */
#ifndef HXCLOAKEDTCP_H
#define HXCLOAKEDTCP_H

#include "hxtypes.h"
#include "hxcom.h"
#include "hxengin.h"
#include "hxpnets.h"
#include "hxauthn.h"
#include "hxpreftr.h"

#include "hxstring.h"
#include "hxslist.h"
#include "growingq.h"
#include "smartptr.h"
#include "hxathsp.h"
#include "hxsockcallback.h"

class  HTTPResponseMessage;
class HXMutex;

class HXClientCloakedTCPSocket : public IHXTCPSocket, 
				 public IHXCloakedTCPSocket,
				 public IHXHTTPProxy, 
				 public SocketCallbackInterface,
				 public IHXClientAuthResponse
{
public:
				HXClientCloakedTCPSocket(IUnknown* pContext);
				~HXClientCloakedTCPSocket();
    
    /* IUnknown interface */
    STDMETHOD(QueryInterface)   (THIS_ 
				REFIID riid, void** ppvObj);

    STDMETHOD_(ULONG32,AddRef)  (THIS);

    STDMETHOD_(ULONG32,Release) (THIS);

   /* SocketCallbackInterface interface */
 	enum {
		CLOAKED_TCP_READ_COMMAND,
		CLOAKED_TCP_GETWRITE_COMMAND,
		CLOAKED_TCP_PUTWRITE_COMMAND,
		CLOAKED_TCP_PUTRESPONSE_TIMEOUT_COMMAND
		};		
	STDMETHODIMP HandleCallback(INT32 theCommand, HX_RESULT theError);

    /*
     *  IHXTCPSocket methods
     */

    STDMETHOD(Init)		(THIS_
				IHXTCPResponse*    /*IN*/  pTCPResponse);

    STDMETHOD(SetResponse)	(THIS_
				IHXTCPResponse*    /*IN*/  pTCPResponse);

    STDMETHOD(Bind)		(THIS_
				UINT32			    ulLocalAddr,
				UINT16 			    nPort);

    STDMETHOD(Connect)		(THIS_
				const char*		    pDestination,
				UINT16			    nPort);

    STDMETHOD(Read)		(THIS_
				UINT16			    uSize);

    STDMETHOD(Write)		(THIS_
				IHXBuffer*		    pBuffer);

    STDMETHOD(WantWrite)	(THIS);

    STDMETHOD(GetLocalAddress)	(THIS_
				UINT32&			    lAddress);
    STDMETHOD(GetForeignAddress)(THIS_
				UINT32&			    lAddress);
    STDMETHOD(GetLocalPort)	(THIS_
    				UINT16&			    nPort);
    STDMETHOD(GetForeignPort)	(THIS_
    				UINT16&			    nPort);

    // IHXClientAuthResponse
    
    STDMETHOD(ResponseReady)	(THIS_
    				HX_RESULT   HX_RESULTStatus,
				IHXRequest* pIHXRequestResponse);
    
    /*
     *	IHXHTTPProxy methods
     *
     *  Network addresses and ports are in native byte order
     *  
     */

    STDMETHOD(SetProxy)		(THIS_
				const char* /*IN*/  pProxyHostName,
				UINT16	    /*IN*/  nPort);

    /************************************************************************
     *	Method:
     *	    IHXCloakedTCPSocket::InitCloak
     */
    STDMETHOD(InitCloak)	(THIS_
				IHXValues* /*IN*/  pValues,
				IUnknown* pUnknown);

    class HTTPCloakTCPResponse : public IHXTCPResponse,
				 public IHXInterruptSafe
    {
    public:

	HTTPCloakTCPResponse(HXClientCloakedTCPSocket* pOwner, BOOL bIsRead);
	~HTTPCloakTCPResponse();
	/*
	 *  IUnknown methods
	 */
	STDMETHOD(QueryInterface)		(THIS_
					    REFIID riid,
					    void** ppvObj);

	STDMETHOD_(ULONG32,AddRef)		(THIS);

	STDMETHOD_(ULONG32,Release)		(THIS);

	/*
	 *	IHXTCPResponse methods
	 */

	STDMETHOD(ConnectDone)	(THIS_
				HX_RESULT		status);

	STDMETHOD(ReadDone)	(THIS_
				 HX_RESULT		status,
				 IHXBuffer*		pBuffer);

	STDMETHOD(WriteReady)	(THIS_
    				HX_RESULT		status);

	STDMETHOD(Closed)	(THIS_
				 HX_RESULT		status);
    	/*
     	 *	IHXInterruptSafe methods
     	 */
	STDMETHOD_(BOOL,IsInterruptSafe)	(THIS) {return TRUE;};

    private:
	LONG32			    m_lRefCount;
	HXClientCloakedTCPSocket*  m_pOwner;
	BOOL			    m_bIsRead;
    };

    friend class HTTPCloakTCPResponse;

private:
    void			TransferBuffers();

    HX_RESULT			DoRead();
    HX_RESULT			DoGetReadDone(HX_RESULT status, IHXBuffer* pBuffer);
    HX_RESULT			DoPutReadDone(HX_RESULT status, IHXBuffer* pBuffer);
    HX_RESULT			DoGetWrite();
    void			GetConnectDone(BOOL bResult);
    
    HX_RESULT			DoPutWrite(); /* only used by m_pWriteCtrl*/
    void			PutConnectDone(BOOL bResult);

    HX_RESULT			PreparePostMessage(const UCHAR *inData, UINT16 inLength);
    HX_RESULT			EncodeBase64(const UCHAR* inData, UINT16 inLength, UCHAR* outData, UINT16& outLength);
    HX_RESULT			PrepareGetMessage(void);
    void			CreateGuid(void);
    HX_RESULT			HandleHTTPResponse(UCHAR response);
    BOOL			IsSafe();

    void			FlushQueues(void);
    void			SendHTTPDone(void);
    HX_RESULT			ActualConnect(void);
    HX_RESULT			GetServerIPFromResponse(BOOL bGetResponse, const char* pszInBuffer);    
    HX_RESULT			CleanUpAndReInitializeStuff(void);
    HX_RESULT			ReconnectToSameServerIP(void);

    BOOL			AuthenticationRequired(HX_RESULT   status, IHXBuffer* pInBuffer);
    void			ObtainAuthenticationInformation(CHXString& strAuth);

    HX_RESULT			HandleAuthentication(IHXRequest* pRequest, HTTPResponseMessage* pMessage,
    						const char* pHost, const char* pProxyHost);

    LONG32                      m_lRefCount;
    IUnknown*			m_pContext;
    IHXScheduler*		m_pScheduler;
    IHXTCPResponse*		m_pTCPResponse;
    IHXNetworkServices*	m_pNetworkServices;    
    IHXTCPSocket*		m_pGetCtrl;
    IHXTCPSocket*		m_pPutCtrl;
    HTTPCloakTCPResponse*	m_pGetCtrlResponse;
    HTTPCloakTCPResponse*	m_pPutCtrlResponse;
    char*			m_pForiegnHost;
    UINT32			m_lForeignAddress;
    UINT16			m_nForeignPort : 16;
    UINT16			m_nRequired : 16;
    CByteGrowingQueue*		m_pSendTCP;
    CByteGrowingQueue*		m_pReceiveGetTCP;
    CByteGrowingQueue*		m_pReceivePutTCP;
    CByteGrowingQueue*		m_pPreEncodedSendHTTP;
    CByteGrowingQueue*		m_pPostEncodedSendHTTP;
    CHXSimpleList		m_PendingWriteBuffers;
    char*			m_pOutBuf;
    char*			m_pOutEncodedBuf;
    char*			m_pInBuf;
    char*			m_pGuid;
    HX_BITFIELD			m_bGetReadPending : 1;
    HX_BITFIELD			m_bPutReadPending : 1;
    HX_BITFIELD			m_bPutWantWritePending : 1;
    HX_BITFIELD			m_bReadPending : 1;
    HX_BITFIELD			m_bConnected : 1;
    HX_BITFIELD			m_bGetConnectDone : 1;
    HX_BITFIELD			m_bPutConnectDone : 1;
    HX_BITFIELD			m_bGetConnectSuccessful : 1;
    HX_BITFIELD			m_bPutConnectSuccessful : 1;
    HX_BITFIELD			m_bConnectResponsePending : 1;
    HX_BITFIELD			m_bOptionsReceived : 1;

    HX_BITFIELD			m_bUseExactContentLength : 1;
    /* == 1, close connection after write completes */
    HX_BITFIELD			m_bCloseHttpAfterWrite : 1;
    /* == 1 we must close the HTTP POST connection */
    HX_BITFIELD			m_bMustCloseHTTP : 1;
    HX_BITFIELD			m_bHttpInitialized : 1;
    HX_BITFIELD			m_bInitComplete : 1;

    HX_BITFIELD			m_bInDestructor : 1;

    HX_BITFIELD			m_bInDoRead: 1;
    HX_BITFIELD			m_bInDoGetWrite : 1;
    HX_BITFIELD			m_bInDoPutWrite : 1;
    HX_BITFIELD			m_bInTransferBuffers : 1;
    HX_BITFIELD			m_bDeletePadding : 1;
    
    HX_BITFIELD			m_bGetResponsed : 1;
    HX_BITFIELD			m_bPutResponsed : 1;
    char*			m_pszGetServerIP;
    char*			m_pszPutServerIP;
    HX_BITFIELD			m_bReconnectToSameServerIP : 1;
    HX_BITFIELD			m_bConnectToSameServerIP : 1;

    HX_BITFIELD			m_bHTTPGetHeaderReadDone : 1;
    HX_BITFIELD			m_bHTTPPutHeaderReadDone : 1;
    HX_RESULT			m_LastError;
    char*			m_pHTTPHeaderBuffer;
    UINT16			m_nHTTPHeaderBufferLength;

    UINT16			m_nProxyPortNumber;
    char*			m_pProxyHostName;

    UINT16			m_uPadLength;

    ScheduledSocketCallback*	m_pSchedulerCallback;
    ScheduledSocketCallback*	m_pNonInterruptCallback;
    IHXInterruptState*		m_pInterruptState;
    IHXInterruptSafe*		m_pResponseInterruptSafe;
    HXMutex*			m_pMutex;

    IHXValues*			m_pCloakValues;
    IUnknown*			m_pCloakContext;
    IHXPreferredTransport*	m_pPreferredTransport;
    IHXPreferredTransportManager* m_pPreferredTransportManager;


#ifdef _MACINTOSH
    class MacCloakedTCPSocketAuthenticationCallback : public IHXCallback
    {
    private:
	LONG32	m_lRefCount;
	
		~MacCloakedTCPSocketAuthenticationCallback();
		PRIVATE_DESTRUCTORS_ARE_NOT_A_CRIME

    public:
		MacCloakedTCPSocketAuthenticationCallback(
			HXClientCloakedTCPSocket* pSocket);

	// IUnknown methods
	STDMETHOD(QueryInterface) (THIS_ REFIID riid, void** ppvObj);
	STDMETHOD_(ULONG32, AddRef) (THIS);
	STDMETHOD_(ULONG32, Release) (THIS);
	
	// IHXCallback methods
	STDMETHOD(Func) (THIS);
	
	// callback specific stuff
	CallbackHandle		m_ulPendingCallbackID;
	HXClientCloakedTCPSocket* m_pSocket;
	HX_RESULT		m_Status;
	IHXBuffer*		m_pInBuffer;
    };
    
    friend class MacCloakedTCPSocketAuthenticationCallback;
    
    MacCloakedTCPSocketAuthenticationCallback* m_pAuthenticationCallback;
#endif

    BOOL m_bInAuthenticationKludge;

    DECLARE_SMART_POINTER
    (
	IHXClientAuthConversation
    )				spClientAuthConversationAuthenticator;

};

#endif /* HXCLOAKEDTCP_H */
