// -----------------------------------------------------------------------------
// LocalHostCheckL
// If the host is a local host, then remove the proxy property. Returns ETrue
// if the transaction request URI was for a localhost.
// -----------------------------------------------------------------------------
//
TBool LocalHostCheckL(RHTTPTransaction& aTransaction, RStringPool& aStringPool)
    {
    _LIT8(KLoopbackIPv4Url, "http://127.0.0.1"); 
    
    RHTTPRequest request = aTransaction.Request();
    TUriC8 uri = request.URI();

    TUriParser8 parserLoopBack;
    parserLoopBack.Parse(KLoopbackIPv4Url());
    TInt match = parserLoopBack.Compare(uri, EUriHost);

    if (KErrNone != match)
        {
        _LIT8(KLocalHostUrl, "http://localhost"); 

        // try another compare - compare against the "localhost".
        TUriParser8 parserLocalHost;
        parserLocalHost.Parse(KLocalHostUrl());
        match = parserLocalHost.Compare(uri, EUriHost);

        if (KErrNone == match) 
            {
            _LIT8(KLoopbackIPv4, "127.0.0.1"); 

            // "localhost" resolves to "::1", manually, replace with "127.0.0.1"
            CUri8* newUri = CUri8::NewLC(uri);
            newUri->SetComponentL(KLoopbackIPv4(), EUriHost);
            request.SetURIL(newUri->Uri());
            CleanupStack::PopAndDestroy(newUri);
            }
        }
              
    if (KErrNone == match)
        {
        // request is for localhost, explicitly state that this transaction
        // must not be sent to proxy.
    	RStringF proxyUsageStrF = aStringPool.StringF(HTTP::EProxyUsage, 
                                                      RHTTPSession::GetTable());
        
    	RStringF dontUseProxyStrF = aStringPool.StringF(HTTP::EDoNotUseProxy, 
                                                        RHTTPSession::GetTable());	

        aTransaction.PropertySet().RemoveProperty(proxyUsageStrF);
        aTransaction.PropertySet().SetPropertyL(proxyUsageStrF, dontUseProxyStrF);

    	//RStringF proxyAddrStrF = aStringPool.StringF(HTTP::EProxyAddress, 
        //                                             RHTTPSession::GetTable());

        //aTransaction.PropertySet().RemoveProperty(proxyAddrStrF);
        return ETrue;                                                          
        }
    return EFalse;
    }
// ------------------------------------------------------------------------------------------------
// CHttpFilterConnHandler::MHFRunL
// Process a transaction event.
// ------------------------------------------------------------------------------------------------
//
void CHttpFilterConnHandler::MHFRunL(RHTTPTransaction aTransaction,
                                     const THTTPEvent& aEvent)
{
    TInt state = 0;
    TInt gprsState = 0;
    TInt wcdmaState = 0;
    TApBearerType bearerType;

    if (aEvent.iStatus == THTTPEvent::ESubmit)
    {
        THTTPHdrVal isNewConn;
        RHTTPConnectionInfo	connInfo = iSession->ConnectionInfo();
        RStringPool strPool = aTransaction.Session().StringPool();
        TBool ret = connInfo.Property (strPool.StringF(HttpFilterCommonStringsExt::EHttpNewConnFlag,
                                       HttpFilterCommonStringsExt::GetTable()), isNewConn);

        if ( LocalHostCheckL(aTransaction) && !( ret && isNewConn.Type() == THTTPHdrVal::KTIntVal ) )
            {
            return;
            }

        THTTPHdrVal callback;
        RHTTPTransactionPropertySet propSet = aTransaction.PropertySet();
        RStringF callbackStr = strPool.StringF( HttpFilterCommonStringsExt::EConnectionCallback, 
            HttpFilterCommonStringsExt::GetTable() );

        MConnectionCallback* callbackPtr = NULL;
    
        // this is a transaction, already forwarded to download manager
        if( propSet.Property( callbackStr, callback ) )
        {
            callbackPtr = REINTERPRET_CAST( MConnectionCallback*, callback.Int() );
        }        
void CTestFilter::EncodeBasicAuthL(RString& aUsername, 
										  RString& aPW, 
										  RHTTPTransaction& aTransaction)
	{
	// Standard, plain-text HTTP - Base 64 the name and password
	TBase64 codec;
	HBufC8* nameAndPW = HBufC8::NewMaxLC(aUsername.DesC().Length() + aPW.DesC().Length() + 1);
	_LIT8(KBasicAuthFormatString, "%S:%S");
	nameAndPW->Des().Format(KBasicAuthFormatString, &aUsername.DesC(), &aPW.DesC());
 
	// Conservatively allocate a buffer twice as big as the unencoded
	// buffer for the encoded string.
	HBufC8* encoded = HBufC8::NewMaxLC(nameAndPW->Des().Length() * 2);
	TPtr8 encodedPtr(encoded->Des());
	codec.Encode(*nameAndPW, encodedPtr);
	
	RString encodedString = iStringPool.OpenStringL(*encoded);
	CleanupStack::PopAndDestroy(2, nameAndPW); 

	CleanupClosePushL(encodedString);
	
	RHTTPHeaders requestHeaders(aTransaction.Request().GetHeaderCollection());
	
	requestHeaders.RemoveField(iStringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable())); 
	requestHeaders.SetFieldL(iStringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
									THTTPHdrVal(iStringPool.StringF(HTTP::EBasic,RHTTPSession::GetTable())));
	
	requestHeaders.SetFieldL(iStringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
									THTTPHdrVal(encodedString));

	aTransaction.PropertySet().SetPropertyL(iStringPool.StringF(HTTP::EAuthorization,RHTTPSession::GetTable()), 
																THTTPHdrVal(encodedString));
	
	CleanupStack::PopAndDestroy(&encodedString);
	
	}
//------------------------------------------------------------------------
// CTestFilter::CheckHeadersL
// Check HTTP headers and extract MIME type
//------------------------------------------------------------------------
// 
void CTestFilter::CheckHeadersL(  RHTTPTransaction& aTrans )
{
	// read the header data and check the MIME type here	
	// check the status and body
	RHTTPResponse response = aTrans.Response();
	TInt status = response.StatusCode();
	THTTPHdrVal fieldVal;
	// check if status == 401 and realm is 3GPP then we need to bootstrap, if we are already bootstrappign this is the second call
	if(  status == HTTPStatus::EUnauthorized )
	{				
	
	   TInt headerPart=0;    	
	   THTTPHdrVal headerVal;
       RStringF wwwAuthHeader = iStringPool.StringF(HTTP::EWWWAuthenticate,RHTTPSession::GetTable());
	   RHTTPHeaders headers(aTrans.Response().GetHeaderCollection());

	    RString realm;
	    THTTPHdrVal hdrVal;
	    if (!headers.GetParam(wwwAuthHeader, iStringPool.StringF(HTTP::ERealm,RHTTPSession::GetTable()), 
				  hdrVal, headerPart))
	    {
			realm = hdrVal;
			const TDesC8& val = realm.DesC();
	   			if (headerPart == KErrNotFound)
					return;
	            THTTPHdrVal authTypeParam;


	 				RHTTPTransactionPropertySet propSet = aTrans.PropertySet();
	 				// if we are already bootstrapping results will be retrieved when request is resubmitted
	                iBootstrapPending = ETrue;
	                
             
	                TTimeIntervalMicroSeconds32 aInterval(20000000);
	                
	                iTimeOut->Start(aInterval); //Start the http post request timer, aInterval - timeout in micro-seconds
	                
	                if(!iBootstrapWait.IsStarted())
	                    {
                        iBootstrapWait.Start();
	                    }
	                  
	                if( iHaveCredentials )
	                    {
                        RHTTPTransactionPropertySet propSet = aTrans.PropertySet();
                       
                        //user name/pass word for accessing http://replab.nrln.net/digest/ 
                        //username: dummy, password: dummy
                        TBuf8<KB64KeySize> keyBase64(_L8("Aladdin")); 
                        TBuf8<KB64KeySize> keyBase64Username(_L8("open sesame"));;
                        RString username = iStringPool.OpenStringL( keyBase64 );
                        CleanupClosePushL<RString>( username );
                        RString password = iStringPool.OpenStringL( keyBase64Username );
                       CleanupClosePushL<RString>( password );
                        propSet.SetPropertyL( iUsernameStr, username );
                        propSet.SetPropertyL( iPasswordStr, password );
                        CleanupStack::PopAndDestroy(&password);
                        CleanupStack::PopAndDestroy(&username);
                        //Cancel the transaction
                        aTrans.Cancel();
                        // Re-submit the http request with much needed credentials
                        aTrans.SubmitL(); 
                        }
	                else
	                    {
                        //Since bootstrapping failed,Do not have to resubmit the http request ?
                        return;
                        }
			
		}
	}
}