void CHttpClientFilter::EnsureNoEndToEndHeadersInConnectionHeaderL(RHTTPTransaction aTransaction)
	{
	RHTTPHeaders headers = aTransaction.Request().GetHeaderCollection();
	RStringF connection = iStringPool.StringF(HTTP::EConnection,iStringTable);
	const TInt numConnectionHeaderParts = headers.FieldPartsL(connection);

	for( TInt ii = numConnectionHeaderParts - 1; ii >= 0; --ii ) 
		{
		// Examine connection-tokens from back to front so index is always valid. 
		// Check for an end to end header and remove it as a connection header
		// must not contain end to end headers.
		THTTPHdrVal value;
		TInt ret = headers.GetField(connection, ii, value);

		if( ( ret != KErrNotFound ) && ( value.Type() == THTTPHdrVal::KStrFVal ) )
			{
			RStringF valueStrF = value.StrF();
			if( valueStrF.Index(iStringTable) != HTTP::EClose  && 
				!IsHopByHopHeader(valueStrF) )
				{
				// The connection-token is not 'close' nor is it a end-to-end
				// header field name - remove it.
				User::LeaveIfError(headers.RemoveFieldPart(connection, ii)); 
				}
			}
		else
			{
			// The connection-token is not a hop-by-hop header field name -
			// remove it.
			User::LeaveIfError(headers.RemoveFieldPart(connection, ii));
			}			
		}
	}
TBool CExampleCookieManager::CheckPortMatch(CCookie& aCookie, const TUriC8& aUri) const
	{
	THTTPHdrVal val;
	if(aCookie.Attribute(CCookie::EPort, val) == KErrNone)
		{
		TChar portSeparator(',');
		_LIT8(KDefaultPort, "80");

		const TDesC8& port = aUri.IsPresent(EUriPort)? aUri.Extract(EUriPort) : KDefaultPort();

		const TPtrC8& portList = RemoveQuotes(val.StrF().DesC());
		TInt portPos = portList.FindF(port);
		// if we do not find the port in the list then do not match
		if(portPos == KErrNotFound)
			return EFalse;
		// if the number was the last in the list then match
		else if((portPos + port.Length()) == portList.Length())
			return ETrue;
		// check that the number is followed by a separator ie do not match 80 with 8000
		else if(portList[portPos + port.Length()] == TUint(portSeparator))
			return ETrue;
		// we have not found a match
		else
			return EFalse;
		}

	// If the cookie does not have a portlist return ETrue to match any port
	return ETrue;
	}
Example #3
0
void CHttpTestCaseGet12::LogConnectionProperties()
	{
	RHTTPConnectionInfo	connectionInfo = iSession.ConnectionInfo();
	RStringPool stringPool = iSession.StringPool();
	THTTPHdrVal value;
	TBool hasValue = connectionInfo.Property (stringPool.StringF(HTTP::EHttpSocketConnection, RHTTPSession::GetTable()), value);
	if (hasValue)
		{
		RConnection* conn = REINTERPRET_CAST(RConnection*, value.Int());
		TUint count;
		//get the no of active connections
		TInt err = conn->EnumerateConnections(count);
		if(err==KErrNone)
			{
			for (TUint i=1; i<=count; ++i)
				{
				TPckgBuf<TConnectionInfo> connInfo;
				conn->GetConnectionInfo(i, connInfo);
				iEngine->Utils().LogIt(_L("Connection %d: IapId=%d, NetId=%d\n"),i, connInfo().iIapId, connInfo().iNetId);
				}
			}
		else
			{
			iEngine->Utils().LogIt(_L("Unable to enumerate number of connections, Error: %d"), err);
			}
		}
	}
void CPipeliningConfigTest::CheckAndSetSessionSettingsL(RHTTPSession aSession)
{
    RStringPool stringPool = aSession.StringPool();
    RHTTPConnectionInfo sessionSettings = aSession.ConnectionInfo();

    if (iMaxNumberTransactionsToPipeline > 0)
    {
        RStringF maxToPipelineSetting = stringPool.StringF(HTTP::EMaxNumTransactionsToPipeline,
                                        aSession.GetTable());
        THTTPHdrVal value;
        if (sessionSettings.Property(maxToPipelineSetting, value) == EFalse)
        {
            value.SetInt(iMaxNumberTransactionsToPipeline);
            sessionSettings.SetPropertyL(maxToPipelineSetting,value);
        }
    }


    if (iMaxNumberTransportHandlers > 0)
    {
        RStringF maxTransportHandlers = stringPool.StringF(HTTP::EMaxNumTransportHandlers,
                                        aSession.GetTable());
        THTTPHdrVal value;
        if (sessionSettings.Property(maxTransportHandlers, value) == EFalse)
        {
            value.SetInt(iMaxNumberTransportHandlers);
            sessionSettings.SetPropertyL(maxTransportHandlers,value);
        }
    }
}
void CHttpClientFilter::EnsureContentLengthL(RHTTPTransaction aTransaction)
	{
	RHTTPRequest request = aTransaction.Request();

	if( request.HasBody() )
		{
		THTTPHdrVal hdrVal;
		RStringF teName = iStringPool.StringF(HTTP::ETransferEncoding, iStringTable);

		// Get rid of Content-Length header if present
		// NOTE - cannot use a local variable for the Content-Length as causes a 
		// compiler bug in thumb builds - grand! : (
		RHTTPHeaders headers = request.GetHeaderCollection();
		headers.RemoveField(iStringPool.StringF(HTTP::EContentLength, iStringTable)); 
		
		TInt bodySize = request.Body()->OverallDataSize();
		if( bodySize != KErrNotFound )
			{
			// Size is known - set the ContentLength header.
			headers.SetFieldL(iStringPool.StringF(HTTP::EContentLength, iStringTable), THTTPHdrVal(bodySize));
			}
		else if( headers.GetField(teName, 0, hdrVal) == KErrNotFound )
			{
			// Size is unknown and there's been no Encoding indicated by the 
			// client - set the 'TransferEncoding: chunked'
			hdrVal.SetStrF(iStringPool.StringF(HTTP::EChunked, iStringTable));
			headers.SetFieldL(teName, hdrVal);
			}
		}
	}
TBool CExampleCookieManager::CheckDomainMatch(CCookie& aCookie, const TUriC8& aUri) const
	{
	TChar domainSep = '.';

	if(aUri.IsPresent(EUriHost))
		{
		THTTPHdrVal attributeVal;
		aCookie.Attribute(CCookie::EDomain, attributeVal);

		const TDesC8& domain = aUri.Extract(EUriHost);
		const TPtrC8 cookieDomain = RemoveQuotes(attributeVal.StrF().DesC());

		// Domain matching rules:
		// if the cookie domain doesn't start with a dot then it must match the uri domain exactly
		// if it does start with a dot and it 
		TInt matchLoc = domain.FindF(cookieDomain);
		if((cookieDomain[0] != TUint(domainSep))		&& 
			(matchLoc == 0)								&& 
			(domain.Length() == cookieDomain.Length()))
			return ETrue;
		else if((matchLoc != KErrNotFound) &&
				(domain.Left(matchLoc).Locate(domainSep) == KErrNotFound))
				return ETrue;
		}

	return EFalse;
	}
TInt CWspHeaderReader::DecodeGenericParamTokenL(TWspPrimitiveDecoder& aDecoder, const TStringTable& aStrTable,
											THTTPHdrVal& aParamValue, RStringF& aParamDesValue) const
	{
	TInt err = 0;
	switch( aDecoder.VarType() )
		{
		case TWspPrimitiveDecoder::EString:
			{
			TPtrC8 fieldNameString;
			err = aDecoder.String(fieldNameString);
			User::LeaveIfError(err);
			aParamDesValue = iStrPool.OpenFStringL(fieldNameString);
			aParamValue.SetStrF(aParamDesValue);
			} break;
		case TWspPrimitiveDecoder::E7BitVal:
			{
			TUint8 fieldNameToken = 0;
			err = aDecoder.Val7Bit(fieldNameToken);
			User::LeaveIfError(err);
			aParamDesValue = iStrPool.StringF(fieldNameToken, aStrTable);
			aParamValue.SetStrF(aParamDesValue);
			} break;
		default:
			User::Leave(KErrCorrupt);
			break;
		}
	return err;
	}
// ------------------------------------------------------------------------------------------------
// 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() );
        }        
Example #9
0
void CHttpHdrTest::TestLookupPartL()
	{
	// Open strings needed in this test
	RStringF accStr = iStrP.StringF(HTTP::EAccept,RHTTPSession::GetTable());
	RStringF textHtmlStr = iStrP.StringF(HTTP::ETextHtml,RHTTPSession::GetTable());
	RStringF textPlainStr = iStrP.StringF(HTTP::ETextPlain,RHTTPSession::GetTable());
	RStringF anyAnyStr = iStrP.StringF(HTTP::EAnyAny,RHTTPSession::GetTable());
	RStringF qStr = iStrP.StringF(HTTP::EQ,RHTTPSession::GetTable());

	//
	//	  Accept: text/html; q=0.8, text/plain; q=0.2, */*
	//
	CHeaderField* accept = CHeaderField::NewL(accStr, *iHdrColl);
	CleanupStack::PushL(accept);
	//
	CHeaderFieldPart* htmlPt = CHeaderFieldPart::NewL(THTTPHdrVal(textHtmlStr));
	CleanupStack::PushL(htmlPt);
	THTTPHdrVal::TQConv q(0.8);
	CHeaderFieldParam* headerParam = CHeaderFieldParam::NewL(qStr, THTTPHdrVal(q));
	CleanupStack::PushL(headerParam);
	htmlPt->AddParamL(headerParam);
	CleanupStack::Pop(headerParam);
	accept->AddPartL(htmlPt);
	CleanupStack::Pop(htmlPt); // now owned by the header
	//

	CHeaderFieldPart* plainPt = CHeaderFieldPart::NewL(THTTPHdrVal(textPlainStr));
	CleanupStack::PushL(plainPt);
	THTTPHdrVal::TQConv q2(0.2);
	headerParam = CHeaderFieldParam::NewL(qStr, THTTPHdrVal(q2));
	CleanupStack::PushL(headerParam);
	plainPt->AddParamL(headerParam);
	CleanupStack::Pop(headerParam);
	accept->AddPartL(plainPt);
	CleanupStack::Pop(plainPt); // now owned by the header
	//
	CHeaderFieldPart* headerPart = CHeaderFieldPart::NewL(THTTPHdrVal(anyAnyStr));
	CleanupStack::PushL(headerPart);
	accept->AddPartL(headerPart);
	CleanupStack::Pop(headerPart);

	// now lookup the parts by index and check they are correct
	CHeaderFieldPart* pt = accept->PartL(0);
	TestL(pt == htmlPt);
	pt = accept->PartL(1);
	TestL(pt == plainPt);
	pt = accept->PartL(2);
	THTTPHdrVal val = pt->Value();
	TestL(val.Type() == THTTPHdrVal::KStrFVal);
	TestL(val.StrF().Index(RHTTPSession::GetTable()) == anyAnyStr.Index(RHTTPSession::GetTable()));	

	// Now just destroy that lot
	CleanupStack::PopAndDestroy(accept);
	}
TInt CHttpController::ContentLength( RHTTPHeaders aHeaderCollection, RHTTPSession& aSession )
	{
	RStringF contetnLength = aSession.StringPool().StringF( HTTP::EContentLength,
			RHTTPSession::GetTable() );
	THTTPHdrVal contetnLengthValue;
	TInt error( aHeaderCollection.GetField( contetnLength, 0, contetnLengthValue ) );
	if ( error == KErrNone )
		{
		return contetnLengthValue.Int();
		}
	return error;
	}
Example #11
0
void CHttpEventHandler::ParseCookieL(RHTTPTransaction& aTrans)
{
	RHTTPResponse response = aTrans.Response();
	RHTTPResponse resp = aTrans.Response();
	RStringPool pool = aTrans.Session().StringPool();
    RHTTPHeaders headers = resp.GetHeaderCollection();
    
	RStringF fieldName = pool.StringF(HTTP::ESetCookie,RHTTPSession::GetTable());
	
	_LIT(KSeparator,";");
	_LIT(KPathName,";path=");
	_LIT(KEqual,"=");
	
	THTTPHdrVal val;
	if (headers.GetField(fieldName, 0, val) != KErrNotFound)
	{
		RStringF cookieValueName = pool.StringF(HTTP::ECookieValue,RHTTPSession::GetTable());
		RStringF cookieNameName = pool.StringF(HTTP::ECookieName,RHTTPSession::GetTable());
		RStringF cookiePathName = pool.StringF(HTTP::EPath,RHTTPSession::GetTable());
	
		if (val.StrF() == pool.StringF(HTTP::ECookie, RHTTPSession::GetTable()))
		{
			THTTPHdrVal cookieValue;
			THTTPHdrVal cookieName;
			THTTPHdrVal cookiePath;
			
			TInt parts = headers.FieldPartsL(fieldName);
	
			Mem::Fill((void*)iCookies.Ptr(), 1024, 0);
			
			// Get all the cookies.
			for (TInt i = 0; i < parts; i++)
			{
				headers.GetParam(fieldName, cookieValueName, cookieValue, i);
				headers.GetParam(fieldName, cookieNameName, cookieName, i);
				headers.GetParam(fieldName, cookiePathName, cookiePath, i);
				
				if ( GetHdrVal( cookieName, pool) )
					iCookies.Append(KEqual);
					
				if ( GetHdrVal( cookieValue, pool) )
				{	
					iCookies.Append(KPathName);
					GetHdrVal( cookiePath, pool);
					iCookies.Append(KSeparator);
				}
			}
		}
	}
}
void CHeaderDecode::ProcessHeadersL(RHTTPTransaction aTrans)
	{
	RStringPool stringPool = aTrans.Session().StringPool();
	RHTTPHeaders headers = aTrans.Response().GetHeaderCollection();
	THTTPHdrVal hdrVal;

	//Check Content-Length header parameter is stored correctly
	RStringF contentLengthStr = stringPool.StringF(HTTP::EContentLength, aTrans.Session().GetTable());
	User::LeaveIfError(headers.GetField(contentLengthStr,0,hdrVal));

	if(headers.FieldPartsL(contentLengthStr) != 1)
		User::Leave(KErrArgument);

	if (hdrVal.Int() != 6)
		User::Leave(KErrArgument);
	}
Example #13
0
TBool CHttpEventHandler::GetHdrVal( THTTPHdrVal& hdrVal, RStringPool& pool)
{
	TBool retval = ETrue;
	TPtrC8 auth_token((const TUint8*)"auth_token");
	
	switch (hdrVal.Type())
	{
		case THTTPHdrVal::KStrFVal:
			{
				RStringF fieldNameStr = pool.StringF(hdrVal.StrF());
				const TDesC8& fieldNameDesC = fieldNameStr.DesC();
				
				if (iVerbose)
				{
					TBuf<CHttpConstants::KMaxHeaderValueLen>  value;
					value.Copy(fieldNameDesC.Left(CHttpConstants::KMaxHeaderValueLen));
					iTest->Console()->Printf(_L("%S:\n"), &value);
				}

				if ( fieldNameDesC.Length() > 0 && fieldNameDesC.Compare(auth_token) )
					iCookies.Append(fieldNameDesC);
				else
					retval = EFalse;
			}
			break;
		case THTTPHdrVal::KStrVal:
			{
				RString fieldNameStr = pool.String(hdrVal.Str());
				const TDesC8& fieldNameDesC = fieldNameStr.DesC();
				
				if (iVerbose)
				{
					TBuf<CHttpConstants::KMaxHeaderValueLen>  value;
					value.Copy(fieldNameDesC.Left(CHttpConstants::KMaxHeaderValueLen));
					iTest->Console()->Printf(_L("%S:\n"), &value);
				}
				
				if ( fieldNameDesC.Length() > 0 && fieldNameDesC.Compare(auth_token) )
					iCookies.Append(fieldNameDesC);
				else
					retval = EFalse;
			}
			break;
	}
	
	return retval;
}
// -----------------------------------------------------------------------------
// CHttpFilterProxy::ReadProxyInfoL
// Purpose:	Reads the Proxy information from the comms database.
// Gives the Proxy usage, a proxy address (<proxy name>:<proxy port>),
// and proxy exceptions through the output arguments.
// -----------------------------------------------------------------------------
//
void CHttpFilterProxy::ReadProxyInfoL(const RStringPool aStringPool,
                                      TBool&      aUsage,
                                      RStringF&   aProxyAddress,
                                      RStringF&   aExceptions)

{
    // Let's find Internet Access point ID (ServiceId) in use from the RConnection associated with the HTTP framework
    THTTPHdrVal connValue;
    TUint32     serviceId;
    TUint pushCount = 0;
    RConnection* connPtr = NULL;
	THTTPHdrVal		iapId;
	TCommDbConnPref pref;
    TBool hasValue = iConnInfo.Property (aStringPool.StringF(HTTP::EHttpSocketConnection, RHTTPSession::GetTable()),
                     connValue);

    if (hasValue && connValue.Type() == THTTPHdrVal::KTIntVal)
    {
        connPtr = REINTERPRET_CAST(RConnection*, connValue.Int());
	}
Example #15
0
AMInt32 AMHttpGetOption(AMHttpRequest request, AMHttpOption option,
    AMUInt8* outBuf, AMUInt32 inOutBufLen)
	{
	REINTERPRET( HttpConnectionInternal*, temp, request );
	RHTTPHeaders hdr = temp->Transaction->Request().GetHeaderCollection();
	
	TPtr8 ptr( outBuf, inOutBufLen );
	
	switch( option )
		{
		case AM_HTTP_TIMEOUT:
			{
			THTTPHdrVal val;
			hdr.GetField(temp->session->StringPool().StringF(HTTP::EWspProxyConnectionTimeout,
			    RHTTPSession::GetTable()), 0, val);
			ptr.Append( val.StrF().DesC() );
			break;
			}
		}
	}
void CHttpClientFilter::EnsureContentTypePresentL(RHTTPTransaction aTransaction)
	{
	// From RFC 2616 Section 7.2.1 - 
	//
	// Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type
	// header field defining the media type of that body. If and only if the 
	// media type is not given by a Content-Type field, the recipient MAY attempt
	// to guess the media type via inspection of its content and/or the name 
	// extension(s) of the URI used to identify the resource. If the media type
	// remains unknown, the recipient SHOULD treat it as type "application/octet-stream".

	RHTTPHeaders headers = aTransaction.Response().GetHeaderCollection();
	THTTPHdrVal contentType;
	RStringF contentTypeString = iStringPool.StringF(HTTP::EContentType, iStringTable);
	if( headers.GetField(contentTypeString, 0, contentType) == KErrNotFound )
		{
		// There is no Content-Type header - add it with a value of 
		// "application/octet-stream".
		contentType.SetStrF(iStringPool.StringF(HTTP::EApplicationOctetStream, iStringTable));
		headers.SetFieldL(contentTypeString, contentType);
		}
	}
TBool CExampleCookieManager::CheckPathMatch(CCookie& aCookie, const TUriC8& aUri) const
	{
	THTTPHdrVal attributeVal;
	aCookie.Attribute(CCookie::EPath, attributeVal);
	TPtrC8 cookiePath = RemoveQuotes(attributeVal.StrF().DesC());

	const TDesC8& uriPath = aUri.Extract(EUriPath);
	if(uriPath.Length() == 0)
		{
		// if the uri has no path then it matches against no cookie path
		// or a cookie path of just a /
		const TInt pathLength = cookiePath.Length();
		if(pathLength == 0 || pathLength == 1)
			return ETrue;
		}
	else if(uriPath.FindF(cookiePath) == 0)
		{
		TChar separator('/');
		// Check that the character after the matched bit is a / otherwise
		// /path would match against /path2
		const TInt uriLength = uriPath.Length();
		const TInt cookieLength = cookiePath.Length();

		if(uriLength == cookieLength)
			return ETrue;
		else if(uriLength > cookieLength)
			{
			if(cookiePath[cookieLength - 1] == TUint(separator))
				return ETrue;
			else if(uriPath[cookieLength] == TUint(separator))
				return ETrue;
			}
		}

	return EFalse;
	}
void CWspHeaderReader::DecodeWellKnownParamTokenL(TWspPrimitiveDecoder& aDecoder, TInt& aBytesRead,
												  TPtrC8& aRawParamBlock, CHeaderFieldPart& aHeaderFieldPart) const
	{
	TInt err = 0;
	TUint32 parameterToken = 0;
	aBytesRead = aDecoder.Integer(parameterToken);
	THTTPHdrVal paramValue;
	RStringF paramDesValue;
	CleanupClosePushL(paramDesValue);
	RStringF paramName = iStrPool.StringF(parameterToken, WSPParam::Table);
	switch( parameterToken )
		{
		case WSPParam::EQ:
			{
			// Decode Q value
			TUint32 qIntValue = 0;
			err = aDecoder.UintVar(qIntValue);
			User::LeaveIfError(err);
			aBytesRead += err;
			TReal q;
			TInt numDecimals = 0;
			TBuf8<KMaxNumQDigits> qDesC;
			if( qIntValue > 100 )
				{
				// Value is -100 and then divide by 1000
				qIntValue -= 100;
				q = ((TReal)(qIntValue/1000.));
				numDecimals = 3;
				}
			else
				{
				// Value is -1 and then divide by 100
				--qIntValue;
				if( qIntValue%10 ==0 )
					numDecimals = 1;
				else
					numDecimals = 2;
				q = ((TReal)(qIntValue/100.));
				}
			TRealFormat realFt(KMaxNumQDigits,numDecimals); // set max width and 3 decimal places
			// always use a decimal separator rather than the one supplied 
			// by the current locale
			realFt.iPoint = TChar('.'); 
			qDesC.Num(q, realFt);
			paramDesValue = iStrPool.OpenFStringL(qDesC);
			paramValue.SetStrF(paramDesValue);
			} break;
		case WSPParam::ECharset:
			{
			if( aRawParamBlock[aBytesRead] == 128 )
				{
				paramDesValue = iStrPool.StringF(WSPStdConstants::EAny, WSPStdConstants::Table);
				paramValue.SetStrF(paramDesValue);
				// Need to call Integer to update offset in WSP Decoder
				TUint8 updateDecoder =  0;
				err = aDecoder.Val7Bit(updateDecoder);
				User::LeaveIfError(err);
				aBytesRead += err;
				}
			else
				{
				switch( aDecoder.VarType() )
					{
					case TWspPrimitiveDecoder::E7BitVal:
					case TWspPrimitiveDecoder::ELengthVal:
						{
						TUint32 value = 0;
						err = aDecoder.Integer(value);
						User::LeaveIfError(err);
						aBytesRead += err;
						GetCharacterSetFromValueL(value, paramDesValue);
						paramValue.SetStrF(paramDesValue);
						} break;
					default:
						User::Leave(KErrCorrupt);
						break;
					}
				}
			} break;
		case WSPParam::ELevel:
			{
			// This is a version value
			err = aDecoder.VersionL(iStrPool,paramDesValue);
			User::LeaveIfError(err);
			aBytesRead += err;
			paramValue.SetStrF(paramDesValue);
			} break;
		case WSPParam::EType:
		case WSPParam::ESize:
		case WSPParam::EPadding:
		case WSPParam::ESEC:
		case WSPParam::EMaxAge:
			{
			TUint32 integerValue = 0;
			err = aDecoder.Integer(integerValue);
			User::LeaveIfError(err);
			aBytesRead += err;
			paramValue.SetInt(integerValue);
			} break;
		case WSPParam::ECreationDate:
		case WSPParam::EModificationDate:
		case WSPParam::EReadDate:
			{
			TDateTime dateTime(1970, EJanuary, 0, 0, 0, 0, 0);
			err = aDecoder.Date(dateTime);
			User::LeaveIfError(err);
			aBytesRead += err;
			paramValue.SetDateTime(dateTime);
			}
		case WSPParam::ENameDep:
		case WSPParam::EFilenameDep:
		case WSPParam::EStartDep:
		case WSPParam::EStartInfoDep:
		case WSPParam::ECommentDep:
		case WSPParam::EDomainDep:
		case WSPParam::EPathDep:
			{
			TPtrC8 textString;
			err = aDecoder.String(textString);
			User::LeaveIfError(err);
			aBytesRead += err;
			paramDesValue = iStrPool.OpenFStringL(textString);
			paramValue.SetStrF(paramDesValue);
			} break;
		case WSPParam::EMAC:
		case WSPParam::EName:
		case WSPParam::EFilename:
		case WSPParam::EStart:
		case WSPParam::EStartInfo:
		case WSPParam::EComment:
		case WSPParam::EDomain:
		case WSPParam::EPath:
			{
			// Check if the string has <no-value> ie <octet 0>
			if( aRawParamBlock[aBytesRead] == 0 )
				{
				paramDesValue = iStrPool.OpenFStringL(KNullDesC8());
				paramValue.SetStrF(paramDesValue);
				// Need to call Integer to update offset in WSP Decoder
				TUint32 updateDecoder =  0;
				err = aDecoder.Integer(updateDecoder);
				User::LeaveIfError(err);
				}
			else
				{
				TPtrC8 textString;
				err = aDecoder.String(textString);
				User::LeaveIfError(err);
				paramDesValue = iStrPool.OpenFStringL(textString);
				paramValue.SetStrF(paramDesValue);
				}
			aBytesRead += err;
			} break;
		case WSPParam::EDifferences:
			{
			aBytesRead += DecodeGenericParamTokenL(aDecoder, iStrTable, paramValue, paramDesValue);
			} break;
		case WSPParam::EContentTypeType:
			{
			aBytesRead += DecodeGenericParamTokenL(aDecoder, WSPContentTypes::Table, paramValue, paramDesValue);
			} break;
		case WSPParam::ESecure:
			{
			// <octet 0> no-value
			paramDesValue = iStrPool.OpenFStringL(KNullDesC8());
			paramValue.SetStrF(paramDesValue);
			// Need to call Integer to update offset in WSP Decoder
			TUint32 updateDecoder =  0;
			err = aDecoder.Integer(updateDecoder);
			User::LeaveIfError(err);
			aBytesRead += err;
			} break;
		default:
			User::Leave(KErrCorrupt);
			break;
		}

	// Add the parameter name and value
	TPtrC8 paramDes(paramName.DesC());
	SetNewParamL(aHeaderFieldPart, paramDes, paramValue);
	CleanupStack::PopAndDestroy(&paramDesValue);
	}
// -----------------------------------------------------------------------------
// CHttpFilterProxy::SetProxyL
// Function to handle Submit events.
// Set proxy properties (EUseProxy and EProxyAddress) in order to get connected throught
// proxy when a new HTTP session will be in effect.  The Proxy data will be taken from
// the CommDb if a new connection has been used. If a proxy property has already been 
// set by a higher filter or by the client, then those settings are preferred over 
// CommsDB.
// -----------------------------------------------------------------------------
//
void CHttpFilterProxy::SetProxyL(const RHTTPTransaction aTransaction)
{
    THTTPHdrVal isNewConn, proxyAddress;

    // If connection has been disconnected the user could change Access Point, so let's
    // check if a new connection has been used.
    TBool ret = iConnInfo.Property (iStringPool.StringF(HttpFilterCommonStringsExt::EHttpNewConnFlag,
                                   HttpFilterCommonStringsExt::GetTable()), isNewConn);

    if (ret && isNewConn.Type() == THTTPHdrVal::KTIntVal && (isNewConn.Int() == 1))
    {
        iUsage = EFalse;
        // Read proxy info from the CommDB
        ReadProxyInfoL(iStringPool,
                       iUsage,
                       iProxyAddress,
                       iExceptions);
    }
    else
    {
        TBool useProxy( ETrue );
        THTTPHdrVal proxyUsageVal;

	    // Is the property for proxy usage set?
        TBool hasUsageValue = iConnInfo.Property(iStringPool.StringF(HTTP::EProxyUsage,
                            RHTTPSession::GetTable()), proxyUsageVal);
                            
        // If the property is set, is it EUseProxy
        if (hasUsageValue)
        {
        useProxy = ( proxyUsageVal.StrF().Index(RHTTPSession::GetTable()) == HTTP::EUseProxy);
        }

        // Use proxy if the property value is EUseProxy or no property is set.
        if (useProxy || !hasUsageValue)
        {
            THTTPHdrVal proxyAddressVal;
            TBool hasValue = iConnInfo.Property(iStringPool.StringF(HTTP::EProxyAddress,
                                               RHTTPSession::GetTable()), proxyAddressVal);
            if (!hasValue)
            {
                // The proxyAddress has not been set, so Read proxy info from the CommDB
                ReadProxyInfoL(iStringPool,
                               iUsage,
                               iProxyAddress,
                               iExceptions);

            }
            else
            {
                // Now get the proxy address...
                iProxyAddress = proxyAddressVal.StrF().Copy();
                iUsage = ETrue;
            }
        }
//      }
    }

    // We should not use proxy if the uri matches to one of exceptions from the exception list
    // In this case the Origing server will be used

    ExcptionsCompare(aTransaction);
    
    // Respect proxy settings already defined by client or higher HTTP filter
    THTTPHdrVal proxyUsage;  // Check if property present or not present, not the value.
    if ( !iConnInfo.Property(iStringPool.StringF(HTTP::EProxyUsage,
                            RHTTPSession::GetTable()), proxyUsage)) 
   	{ 

		// Set the proxy address and proxy Usage
		proxyAddress = THTTPHdrVal(iProxyAddress);

		iConnInfo.RemoveProperty(iStringPool.StringF(HTTP::EProxyAddress,
		                        RHTTPSession::GetTable()));
		iConnInfo.SetPropertyL(iStringPool.StringF(HTTP::EProxyAddress,
		                      RHTTPSession::GetTable()), proxyAddress);

		iConnInfo.RemoveProperty(iStringPool.StringF(HTTP::EProxyUsage,
		                        RHTTPSession::GetTable()));
		if (iUsage)
		{
		    iConnInfo.SetPropertyL(iStringPool.StringF(HTTP::EProxyUsage,
		                          RHTTPSession::GetTable()), iStringPool.StringF(HTTP::EUseProxy,
		                                  RHTTPSession::GetTable()));
		}
		else
		{
		    iConnInfo.SetPropertyL(iStringPool.StringF(HTTP::EProxyUsage,
		                          RHTTPSession::GetTable()), iStringPool.StringF(HTTP::EDoNotUseProxy,
		                                  RHTTPSession::GetTable()));
		}
    	
   	}  
    

    // Cleanup strings.
    iProxyAddress.Close();
    iExceptions.Close();
}
TBool CExampleCookieManager::ValidateCookieL(CCookie& aCookie, const TUriC8& aUri)
	{
	THTTPHdrVal attributeVal;

	if(aCookie.Attribute(CCookie::EPath, attributeVal) == KErrNone)
		{
		// if the path attribute exists check it is a prefix of the path
		// of the uri that issued it (if not reject)
		RStringF cookiePath = attributeVal.StrF();
		const TDesC8& uriPath = aUri.Extract(EUriPath);
		if(uriPath.FindF(RemoveQuotes(cookiePath.DesC())) != 0)
			return EFalse;
		}
	else
		{
		// if the path attribute doesn't exist add it
		THTTPHdrVal val(iStringPool.OpenFStringL(aUri.Extract(EUriPath)));
		aCookie.SetAttributeL(CCookie::EPath, val);
		}

	if(aCookie.Attribute(CCookie::EDomain, attributeVal) == KErrNone)
		{
		const TChar dot('.');
		const TDesC8& cookieDomain = attributeVal.StrF().DesC();
		const TDesC8& uriDomain = aUri.Extract(EUriHost);

		// if the domain does not exactly match the uri and does not begin
		// with a dot then add one
		if((cookieDomain.Compare(uriDomain) != 0) &&
		   (cookieDomain.Locate(dot) != 0))
			{
			_LIT8(KAddDotString, ".%S");
			HBufC8* newDomain = HBufC8::NewLC(cookieDomain.Length() + 1);
			newDomain->Des().AppendFormat(KAddDotString(), &cookieDomain);

			RStringF domain = iStringPool.OpenFStringL(*newDomain);
			CleanupStack::PopAndDestroy(newDomain);

			THTTPHdrVal val(domain);
			aCookie.SetAttributeL(CCookie::EDomain, val);
			domain.Close();
			}

		// if the domain does not contain an embedded dot then reject it
		// ie reject .com or .com.
		// Start by removing one character from each end. ie start at pos 1 and take a length
		// which is 2 shorter than the original descriptor
		TPtrC8 domainMiddle = cookieDomain.Mid(1, cookieDomain.Length() - 2);
		if(domainMiddle.Locate(dot) == KErrNotFound)
			return EFalse;

		// Reject the cookie if the domain differs by two or more levels from the uri
		// ie if uri=www.x.y.com then accept a cookie with .x.y.com but reject .y.com
		TInt pos = uriDomain.FindF(cookieDomain);
		if(pos > 2)
			{
			const TDesC8& domainDiff = uriDomain.Left(pos);

			// Remove one character from each end. ie start at pos 1 and take a length
			// which is 2 shorter than the original descriptor
			const TDesC8& diffMiddle = domainDiff.Mid(1, domainDiff.Length() - 2);
			if(diffMiddle.Locate(dot) != KErrNotFound)
				return EFalse;
			}
		}
	else
		{
		// if the domain attribute is not found add it
		THTTPHdrVal val(iStringPool.OpenFStringL(aUri.Extract(EUriHost)));
		aCookie.SetAttributeL(CCookie::EDomain, val);
		val.StrF().Close();
		}

	if(!CheckPortMatch(aCookie, aUri))
		return EFalse;

	return ETrue;
	}
void CSTTrackerConnection::MHFRunL(RHTTPTransaction aTransaction, 
						  			const THTTPEvent& aEvent)
{
	switch (aEvent.iStatus)
	{
		case THTTPEvent::EGotResponseHeaders:
		{
			// HTTP response headers have been received. Use
			// aTransaction.Response() to get the response. However, it's not
			// necessary to do anything with the response when this event occurs.

			LWRITELN(iLog, _L("[Trackerconnection] Got HTTP headers"));
			// Get HTTP status code from header (e.g. 200)
			RHTTPResponse resp = aTransaction.Response();
			TInt status = resp.StatusCode();
			
			if (status != 200) // ERROR, hiba esetén mi legyen? 404-et lekezelni!
			{
				LWRITE(iLog, _L("[Trackerconnection] Error, status = "));
				TBuf<20> numBuf;
				numBuf.Num(status);
				LWRITELN(iLog, numBuf);
				Cancel();
				if (iObserver)
					iObserver->TrackerConnectionFailedL();
				break;
			}

			// Get status text (e.g. "OK")
			HLWRITE(iLog, _L("[Trackerconnection] Status text = "));
			TBuf<32> statusText;
			statusText.Copy(resp.StatusText().DesC());
			HLWRITELN(iLog, statusText);
			
			
			#ifdef LOG_TO_FILE
			RHTTPHeaders headers = 
				aTransaction.Response().GetHeaderCollection();		
			THTTPHdrFieldIter i =
				headers.Fields();
			for (i.First(); !(i.AtEnd()); ++i)
			{
				RStringF header = iSession.StringPool().StringF(i());
				
				if ((header.DesC() == _L8("Content-Type")))
				{
					HLWRITE(iLog, header.DesC());
					HLWRITE(iLog, _L(": "));
					THTTPHdrVal	val;
					headers.GetField(header, 0, val);
					RStringF value = val.StrF();
					HLWRITELN(iLog, value.DesC());
				}
				else
					HLWRITELN(iLog, header.DesC());
			}
						
			#endif
		}
		break;

		case THTTPEvent::EGotResponseBodyData:
		{			
			// Part (or all) of response's body data received. Use 
			// aTransaction.Response().Body()->GetNextDataPart() to get the actual
			// body data.						

			// Get the body data supplier
			MHTTPDataSupplier* body = aTransaction.Response().Body();
			TPtrC8 dataChunk;						

			// GetNextDataPart() returns ETrue, if the received part is the last 
			// one.
			TBool isLast = body->GetNextDataPart(dataChunk);
			
			//iDownloadedSize += dataChunk.Size();						
			
			HLWRITELN(iLog, _L8("[TrackerConnection] HTTP response body chunk received: "));
			HLWRITELN(iLog, dataChunk);
			
			if (iReceiveBuffer)
			{
				HBufC8* temp = HBufC8::NewL(
					iReceiveBuffer->Length() + dataChunk.Length());
				TPtr8 tempPtr(temp->Des());
				tempPtr.Copy(*iReceiveBuffer);
				tempPtr.Append(dataChunk);
				
				delete iReceiveBuffer;
				iReceiveBuffer = temp;
			}
			else
				iReceiveBuffer = dataChunk.AllocL();

			// Always remember to release the body data.
			body->ReleaseData();
		
			// NOTE: isLast may not be ETrue even if last data part received.
			// (e.g. multipart response without content length field)
			// Use EResponseComplete to reliably determine when body is completely
			// received.
			if (isLast)
			{
				
				#ifdef LOG_TO_FILE
				_LIT(KBodyReceived,"Body received");
				HLWRITELN(iLog, KBodyReceived);
				#endif
				
				//CSTBencode* bencodedResponse = CSTBencode::ParseL(*iReceiveBuffer);	
				//iLog->WriteLineL(*iReceiveBuffer);
				//
				//if (bencodedResponse)
				//{
				//	CleanupStack::PushL(bencodedResponse);
				//	iTorrent.ProcessTrackerResponseL(bencodedResponse);
				//	CleanupStack::PopAndDestroy(); // bencodedResponse
				//}
			}
		}
		break;

		case THTTPEvent::EResponseComplete:
		{
			// Indicates that header & body of response is completely received.
			// No further action here needed.
			//_LIT(KTransactionComplete, "Transaction Complete");
			//iLog->WriteLineL(KTransactionComplete);
			//iResult = ESucceeded;
		}
		break;

		case THTTPEvent::ESucceeded:
		{
			LWRITELN(iLog, _L("[Trackerconnection] HTTP transaction succeded"));

			CSTBencode* bencodedResponse = CSTBencode::ParseL(*iReceiveBuffer);	
			//iLog->WriteLineL(*iReceiveBuffer);
			
			if (bencodedResponse && iObserver)
			{
				CleanupStack::PushL(bencodedResponse);
				iObserver->TrackerResponseReceivedL(*bencodedResponse);
				CleanupStack::PopAndDestroy(); // bencodedResponse
			}
			
			iRunning = EFalse;
			
			if (iObserver)
				iObserver->TrackerConnectionSucceededL();
		}
		break;

		case THTTPEvent::EFailed:
		{
			LWRITELN(iLog, _L("[Trackerconnection] HTTP transaction failed"));
			iRunning = EFalse;
			if (iObserver)
				iObserver->TrackerConnectionFailedL();
		}
		break;

		default:
			// There are more events in THTTPEvent, but they are not usually 
			// needed. However, event status smaller than zero should be handled 
			// correctly since it's error.
		{
			TBuf<64> text;
			if (aEvent.iStatus < 0)
			{
				LWRITE(iLog, _L("[Trackerconnection] HTTP transaction failed, "));
				_LIT(KErrorStr, "Error: %d");
				text.Format(KErrorStr, aEvent.iStatus);
				LWRITELN(iLog, text);
			
				// Just close the transaction on errors
				aTransaction.Close();
				iRunning = EFalse;
				
				if (iObserver)
					iObserver->TrackerConnectionFailedL();
			}
			else
			{
				// Other events are not errors (e.g. permanent and temporary
				// redirections)
				_LIT(KUnrecognisedEvent, "[Trackerconnection] Unrecognised event: %d");
				text.Format(KUnrecognisedEvent, aEvent.iStatus);
				LWRITELN(iLog, text);
			}		
		}
		break;
	}
}
void CTestTransaction::DumpRespHeaders(RHTTPTransaction &aTrans)
	{
		
	RHTTPResponse resp = aTrans.Response();
	RStringPool strP = aTrans.Session().StringPool();
	RHTTPHeaders hdr = resp.GetHeaderCollection();
	THTTPHdrFieldIter it = hdr.Fields();

	TBuf<32>  fieldName16;
	TBuf<128> fieldVal16;

	while (it.AtEnd() == EFalse)
		{
		RStringTokenF fieldNameTk = it();
		RStringF fieldName = strP.StringF(fieldNameTk);
		THTTPHdrVal hVal;
		if (hdr.GetField(fieldName, 0, hVal) == KErrNone)
			{
			TPtrC8 fieldNameStr(strP.StringF(fieldName).DesC());
			if (fieldNameStr.Length() > 32)
				fieldNameStr.Set(fieldNameStr.Left(32));

			fieldName16.Copy(fieldNameStr);

			THTTPHdrVal fieldVal;
			hdr.GetField(fieldName, 0, fieldVal);
			switch (fieldVal.Type())
				{
				case THTTPHdrVal::KTIntVal: Log(_L("%S: %d"), &fieldName16, fieldVal.Int()); break;
				case THTTPHdrVal::KStrVal:
				case THTTPHdrVal::KStrFVal:
					{
					TPtrC8 fieldValStr(strP.StringF(fieldVal.StrF()).DesC());
					if (fieldValStr.Length() > 128)
						fieldValStr.Set(fieldValStr.Left(128));

					fieldVal16.Copy(fieldValStr);
					Log(_L("%S: %S"), &fieldName16, &fieldVal16);

					//	see if we've got the Content-Type header
					if (fieldName16.Find(KHTTPContentType) != KErrNotFound)
						{
						//	check that the contenttype script sets matches (in some way) received header
						TBuf8<KMaxContentTypeSize> contTypeBuf;
						contTypeBuf.Copy(Machine()->GetDefine(KITHContentType));

						TInt iPos = fieldValStr.Find(contTypeBuf);
						if (iPos == KErrNotFound)
							Log(_L("  - Content Type string [%S:%S] is different to ContentType setting"), &fieldName16, &fieldVal16);
						else	
							Log(_L("  - Content Type [%S:%S] acknowledged"), &fieldName16, &fieldVal16);
						}
					} 
					break;
				case THTTPHdrVal::KDateVal: 
					{
					TDateTime myDate = fieldVal.DateTime();
					WriteDateStamp(myDate); 
					Log(_L(" : %S"), &fieldName16);
					}
					break;

				default: Log(_L("%S: <unrecognised value type>"), &fieldName16); break;
				}
			}
		++it;
		}
	}
Example #23
0
void CHttpEventHandler::DumpRespHeadersL(RHTTPTransaction& aTrans)
	{
	RHTTPResponse resp = aTrans.Response();
	RStringPool strP = aTrans.Session().StringPool();
	RHTTPHeaders hdr = resp.GetHeaderCollection();
	THTTPHdrFieldIter it = hdr.Fields();

	TBuf<CHttpConstants::KMaxHeaderNameLen>  fieldName16;
	TBuf<CHttpConstants::KMaxHeaderValueLen> fieldVal16;

	while (it.AtEnd() == EFalse)
		{
		RStringTokenF fieldName = it();
		RStringF fieldNameStr = strP.StringF(fieldName);
		THTTPHdrVal fieldVal;
		if (hdr.GetField(fieldNameStr,0,fieldVal) == KErrNone)
			{
			const TDesC8& fieldNameDesC = fieldNameStr.DesC();
			fieldName16.Copy(fieldNameDesC.Left(CHttpConstants::KMaxHeaderNameLen));
			switch (fieldVal.Type())
				{
			case THTTPHdrVal::KTIntVal:
				iTest->Console()->Printf(_L("%S: %d\n"), &fieldName16, fieldVal.Int());
				break;
			case THTTPHdrVal::KStrFVal:
				{
				RStringF fieldValStr = strP.StringF(fieldVal.StrF());
				const TDesC8& fieldValDesC = fieldValStr.DesC();
				fieldVal16.Copy(fieldValDesC.Left(CHttpConstants::KMaxHeaderValueLen));
				iTest->Console()->Printf(_L("%S: %S\n"), &fieldName16, &fieldVal16);
				}
				break;
			case THTTPHdrVal::KStrVal:
				{
				RString fieldValStr = strP.String(fieldVal.Str());
				const TDesC8& fieldValDesC = fieldValStr.DesC();
				fieldVal16.Copy(fieldValDesC.Left(CHttpConstants::KMaxHeaderValueLen));
				iTest->Console()->Printf(_L("%S: %S\n"), &fieldName16, &fieldVal16);
				}
				break;
			case THTTPHdrVal::KDateVal:
				{
				TDateTime date = fieldVal.DateTime();
				TBuf<40> dateTimeString;
				TTime t(date);
				t.FormatL(dateTimeString,CHttpConstants::KDateFormat);

				iTest->Console()->Printf(_L("%S: %S\n"), &fieldName16, &dateTimeString);
				} 
				break;
			default:
				iTest->Console()->Printf(_L("%S: <unrecognised value type>\n"), &fieldName16);
				break;
				}

			// Display realm for WWW-Authenticate header
			RStringF wwwAuth = strP.StringF(HTTP::EWWWAuthenticate,RHTTPSession::GetTable());
			if (fieldNameStr == wwwAuth)
				{
				// check the auth scheme is 'basic'
				RStringF basic = strP.StringF(HTTP::EBasic,RHTTPSession::GetTable());
				RStringF realm = strP.StringF(HTTP::ERealm,RHTTPSession::GetTable());
				THTTPHdrVal realmVal;
				if ((fieldVal.StrF() == basic) && 
					(!hdr.GetParam(wwwAuth, realm, realmVal)))
					{
					RStringF realmValStr = strP.StringF(realmVal.StrF());
					fieldVal16.Copy(realmValStr.DesC());
					iTest->Console()->Printf(_L("Realm is: %S\n"), &fieldVal16);
					}
				}
			}
		++it;
		}
	}
void UPPayHttpConnection::ParaseResponseHeaders(RHTTPResponse resp)
{
	RHTTPHeaders headers = resp.GetHeaderCollection();
	THTTPHdrVal aHeaderValue;
	iStatusCode = resp.StatusCode();
	if (iStatusCode >= 200 && iStatusCode < 300)
	{
		
		RStringF contLength = stringPool.OpenFStringL(_L8("Content-Length"));
		headers.GetField(contLength, 0, aHeaderValue);
		contLength.Close();
		if (aHeaderValue.Type() == THTTPHdrVal::KTIntVal)
		{
			iContentLength = aHeaderValue.Int();
		}
		else
		{
			iContentLength = 200 * 1024;
		}
		//		if(iContentStartPos != 0)
		//		{
		//			HBufC8* fieldValBuf = HBufC8::NewLC(KMaxHeaderValueLength);
		//			RStringF  contentrange= stringPool.OpenFStringL(_L8("Content-Range"));
		//			TPtrC8 rawField(fieldValBuf->Des());
		//			if(headers.GetRawField(contentrange,rawField)==KErrNone)
		//			{
		//				fieldValBuf->Des().Zero();
		//			}
		//			contentrange.Close ( );
		//			CleanupStack::PopAndDestroy(fieldValBuf);
		//		}
	}
	//
	//	else
	//	{
	//		Stop(); 
	//		iObserver.StateChange(EHttpError);
	//	}

	if (response_header)
	{
		delete response_header;
	}
	response_header = HBufC8::NewL(2048);
	Mem::FillZ((void*) response_header->Ptr(), 2048);
	TPtr8 headPtr = response_header->Des();
	TVersion ver = resp.Version();
	headPtr.AppendFormat(_L8("HTTP/%d.%d %d "), ver.iMajor, ver.iMinor, iStatusCode);
	headPtr.Append(resp.StatusText().DesC());
	headPtr.Append(add2);

	RHTTPHeaders hdr = resp.GetHeaderCollection();
	THTTPHdrFieldIter it = hdr.Fields();
	THTTPHdrVal fieldVal;
	HBufC8* fieldValBuf = HBufC8::NewLC(KMaxHeaderValueLength);
	while (it.AtEnd() == EFalse)
	{
		RStringTokenF fieldName = it();
		RStringF fieldNameStr = stringPool.StringF(fieldName);
		TPtrC8 rawField(fieldValBuf->Des());
		if (hdr.GetRawField(fieldNameStr, rawField) == KErrNone)
		{
			headPtr.Append(fieldNameStr.DesC());
			headPtr.Append(add1);
			headPtr.Append(rawField);
			headPtr.Append(add2);
			fieldValBuf->Des().Zero();
		}
		++it;
	}
	CleanupStack::PopAndDestroy(fieldValBuf);
	
	if (iStatusCode == 301 || iStatusCode == 302)
	{
		if (iObserver)
		{
			iObserver->StateChange(ERedirect);
		}
	}
}
void CHttpController::ParseHeadersL( RHTTPTransaction& aTransaction )
	{
	const TInt KMaxNumericLen = 32;

	RStringPool stringPool = aTransaction.Session().StringPool();
	RHTTPHeaders header = aTransaction.Response().GetHeaderCollection();
	THTTPHdrFieldIter iterator = header.Fields();

	HBufC8* fieldName8 = NULL;
	HBufC8* fieldVal8 = NULL;
	CHttpHeaders* headers = CHttpHeaders::NewLC();
	while ( !iterator.AtEnd() )
		{
		RStringTokenF fieldName = iterator();
		RStringF fieldNameStr = stringPool.StringF( fieldName );
		THTTPHdrVal fieldVal;
		if ( header.GetField( fieldNameStr, 0, fieldVal ) == KErrNone )
			{
			fieldName8 = fieldNameStr.DesC().AllocLC();
			switch ( fieldVal.Type() )
				{
				case THTTPHdrVal::KTIntVal:
					{
					fieldVal8 = HBufC8::NewLC( KMaxNumericLen );
					TPtr8 ptr( fieldVal8->Des() );
					ptr.Num( fieldVal.Int() );
					break;
					}
				case THTTPHdrVal::KStrFVal:
					{
					RStringF fieldValStr = stringPool.StringF( fieldVal.StrF() );
					fieldVal8 = fieldValStr.DesC().AllocLC();
					break;
					}
				case THTTPHdrVal::KStrVal:
					{
					RString fieldValStr = stringPool.String( fieldVal.Str() );
					fieldVal8 = fieldValStr.DesC().AllocLC();
					break;
					}
				case THTTPHdrVal::KDateVal:
					{
					_LIT(KDateFormat,"%D%M%Y%/0%1%/1%2%/2%3%/3 %:0%H%:1%T%:2%S.%C%:3");
					TDateTime date = fieldVal.DateTime();
					const TInt KMaxDateBuferLength = 100;
					TBuf< KMaxDateBuferLength > dateBuffer;
					TTime time( date );
					time.FormatL( dateBuffer, KDateFormat );
					fieldVal8 = CnvUtfConverter::ConvertFromUnicodeToUtf8L( dateBuffer );
					CleanupDeletePushL( fieldVal8 );
					break;
					}
				default:
					User::Leave( KErrNotSupported );//new field types will be added in future
					break;
				}
			if ( !fieldVal8 )
				{
				CleanupStack::PopAndDestroy( fieldName8 );
				}
			else
				{
				headers->AddL( *fieldName8, *fieldVal8 );
				CleanupStack::PopAndDestroy( 2, fieldName8 );
				}
			fieldVal8 = NULL;
			fieldName8 = NULL;
			}
		++iterator;
		}

	iObserver->HeadersReceivedL( headers );
	CleanupStack::Pop( headers );
	}
void CHttpClientHeaderWriter::EncodeHostL(RHeaderField& aHeader) const
/**
	Encodes the host header. RFC2616 section 14.23

		Host			=	"Host" ":" host [ ":" port ]

	The host header value may be empty.
	@internalComponent
	@param		aHeader	The host header field to encode.
	@leave		RHeaderField::BeginRawDataL
	@leave		RHeaderField::PartsL
	@leave		RHeaderField::WriteRawDataL
	@leave		KErrHttpEncodeHost	There were no parts, or the part value type
									or the parameter value type was not a string
									or a folded string.
*/
	{
	__START_PERFORMANCE_LOGGER();
	// Our convention will be that a string called HTTP::EPort will be used to
	// set a parameter holding the integer port number
	// Check part 1
	THeaderFieldPartIter iter1 = aHeader.PartsL();
	iter1.First();
	if( iter1.AtEnd() )
		{
		User::Leave(KErrHttpEncodeHost);
		}
	const CHeaderFieldPart* part = iter1();
	if( part == NULL)
		{
		User::Leave(KErrHttpEncodeHost);
		}
	THTTPHdrVal pt1val = part->Value();
	if( pt1val.Type() != THTTPHdrVal::KStrFVal )
		{
		User::Leave(KErrHttpEncodeHost);
		}
	// Write the host string
	RStringF hostStr = pt1val.StrF();
	aHeader.BeginRawDataL();
	aHeader.WriteRawDataL(hostStr.DesC());

	// Check for a port number
	THeaderFieldParamIter iter2 = part->Parameters();
	iter2.First();
	if( !iter2.AtEnd() )
		{
		// Got a parameter - if its the port, check then write it
		const CHeaderFieldParam* param = iter2();
		if( !param )
			{
			User::Leave(KErrHttpEncodeHostPort);
			}
		if( param->Name() == iStringPool.StringF(HTTP::EPort,iStringTable) )
			{
			// Get the port value
			THTTPHdrVal portVal = param->Value();
			if (portVal.Type() != THTTPHdrVal::KTIntVal)
				{
				User::Leave(KErrHttpEncodeHostPort);
				}
			TBuf8<KMaxNumPortDigits> portDesC;
			const TInt portValue = portVal.Int();
			if(portValue > KMaxNumPortValue) 
				{
				User::Leave(KErrHttpEncodeHostPort);
				}
			portDesC.Num(portValue);
			aHeader.WriteRawDataL(':');
			aHeader.WriteRawDataL(portDesC);
			}
		}
	aHeader.CommitRawData();
	__END_PERFORMANCE_LOGGER(_L(",CHttpClientHeaderWriter::EncodeHostL()"));
	}
void CHttpClientHeaderWriter::EncodeAuthorizationL(RHeaderField& aHeader) const
/**
	Encodes the authorization header. RFC2616 section 14.4 - 
	
		Authorization		=	"Authorization" ":" credentials
		credentials			=	auth-scheme #auth-param
							|	"Digest" digest-response
							|	"Basic" basic-credentials

		basic-credentials	=	base64-user-pass
		base64-user-pass	=	<base64 [4] encoding of user-pass, except not limited to 76 char/line>
		user-pass			=	userid ":" password
		userid				=	*<TEXT excluding ":">
		password			=	*TEXT
		
		digest-response		=	1#( username | realm | nonce | digest-uri |	response |
								[ algorithm ] | [ cnonce ] |
								[ opaque ] | [ message-qop ] |
								[ nonce-count ] | [ auth-param ] )

		username			=	"******" "=" username-value
		username-value		=	quoted-string
		digest-uri			=	"uri" "=" digest-uri-value
		digest-uri-value	=	request-uri ; As specified by HTTP/1.1
		message-qop			=	"qop" "=" qop-value
		cnonce				=	"cnonce" "=" cnonce-value
		cnonce-value		=	nonce-value
		nonce-count			=	"nc" "=" nc-value
		nc-value			=	8LHEX
		response			=	"response" "=" request-digest
		request-digest		=	<"> 32LHEX <">
		LHEX				=	"0" | "1" | "2" | "3" |
								"4" | "5" | "6" | "7" |
								"8" | "9" | "a" | "b" |
								"c" | "d" | "e" | "f"
	
	Encoding here is interpreted very simply. Parts are encoded with no 
	punctuation after them and parameters are comma separated with the value in
	quotes. This means that for basic authentication, part 1 must be 'Basic' and
	part 2 is the credentials. For digest, part1 is 'Digest', and the 
	digest-response is stored in parameters.
	@internalComponent
	@param		aHeader	The authorization header field to encode.
	@leave		RHeaderField::BeginRawDataL
	@leave		RHeaderField::PartsL
	@leave		RHeaderField::WriteRawDataL
	@leave		KErrHttpEncodeAuthorization	There were no parts, or the part
											value type or the parameter value 
											type was not a string or a folded 
											string.
*/
	{
	__START_PERFORMANCE_LOGGER();
	// Check part 1
	aHeader.BeginRawDataL();
	THeaderFieldPartIter iter = aHeader.PartsL();
	for( iter.First(); !iter.AtEnd(); )
		{
		const CHeaderFieldPart* part = iter();
		if( part == NULL )
			{
			// No parts!!
			User::Leave(KErrHttpEncodeAuthorization);
			}
		THTTPHdrVal ptVal = part->Value();
		switch( ptVal.Type() )
			{
		case THTTPHdrVal::KStrFVal:
			{
			aHeader.WriteRawDataL(ptVal.StrF().DesC());
			} break;
		case THTTPHdrVal::KStrVal:
			{
			aHeader.WriteRawDataL(ptVal.Str().DesC());
			} break;			
		default:
			User::Leave(KErrHttpEncodeAuthorization);
			break;
			}

		// Now output the params
		THeaderFieldParamIter paramIter = part->Parameters();
		for( paramIter.First(); !paramIter.AtEnd(); )
			{
			const  TInt param = paramIter()->Name().Index(iStringTable);

			const TBool quoted = (param != HTTP::ENc && param != HTTP::EAlgorithm  && param != HTTP::EUri  && param != HTTP::EStale);
			aHeader.WriteRawDataL(' ');
			aHeader.WriteRawDataL(paramIter()->Name().DesC());
			aHeader.WriteRawDataL('=');
			
			if( quoted ) 
                {
                aHeader.WriteRawDataL('"');
                }

			THTTPHdrVal paramVal = paramIter()->Value();
			switch (paramVal.Type())
				{
			case THTTPHdrVal::KStrFVal:
				{
				aHeader.WriteRawDataL(paramVal.StrF().DesC());
				} break;				
			case THTTPHdrVal::KStrVal:
				{
				aHeader.WriteRawDataL(paramVal.Str().DesC());
				} break;				
			default:
				User::Leave(KErrHttpEncodeAuthorization);
				break;
				}
			if( quoted )
				{
				aHeader.WriteRawDataL('"');
				}

			
			++paramIter;
			if (!paramIter.AtEnd())
				{
				// This is not the last param so add a comma
				aHeader.WriteRawDataL(',');
				}
			}
		++iter;
		if( !iter.AtEnd() )
			{
			// This is not the last part so add a space.
			aHeader.WriteRawDataL(' ');
			}
		}
	aHeader.CommitRawData();
	__END_PERFORMANCE_LOGGER(_L(",CHttpClientHeaderWriter::EncodeAuthorizationL()"));
	}
Example #28
0
void CHttpTestCase5::MHFRunL(RHTTPTransaction aTransaction,
						 const THTTPEvent& aEvent)
	{
	switch (aEvent.iStatus)
			{
	case THTTPEvent::EGotResponseHeaders:
		{
		// HTTP response headers have been received
		iEngine->Utils().LogIt(_L("<EGotResponseHeaders>\n"));
		TInt  statusCode = aTransaction.Response().StatusCode();
		iEngine->Utils().LogIt(_L("Status Code: %d \n"),statusCode);
		DumpRespHeaders(aTransaction);
		iEngine->SetCurrentStatusCode(statusCode);
		//define 2 RStringF : I want to find a header-field header-vaulue match in the response headers
		_LIT8(KContentTypeValSyncMl, "application/vnd.syncml-xml"); // ota content type header
  		RStringF contTypeStr = iMyStrP.StringF(HTTP::EContentType,RHTTPSession::GetTable());
		RStringF syncmlStr = iMyStrP.OpenFStringL(KContentTypeValSyncMl);
		// get  a handle for the headers
		RHTTPHeaders hdr =aTransaction.Response().GetHeaderCollection();
		//parse the headers and look for application/vnd.syncml-xml header
		THTTPHdrVal hVal;
		if(hdr.GetField(contTypeStr,0,hVal)== KErrNone) 
			{// Content-Type header is present
			if (hVal.StrF()==syncmlStr)
				iEngine->Utils().LogIt(_L("\nOk header application/vnd.syncml-xml found"));
			else 
				iEngine->Utils().LogIt(_L("\nThe server doesn't support the application/vnd.syncml-xml header"));
			}
		syncmlStr.Close();
		if (iExpectedStatusCode != statusCode)
			{
			iTestFail=1;
			iEngine->Utils().LogIt(_L("<The Test will fail :The expected status code doesn't match the actual status code received>\n"));
			}
		} break;
	case THTTPEvent::EGotResponseBodyData:
		{
		// Some (more) body data has been received (in the HTTP response)
		iEngine->Utils().LogIt(_L("<EGotResponseBodyData received>\n"));
		DumpResponseBody(aTransaction);
		} break;
	case THTTPEvent::EResponseComplete:
		{
		// The transaction's response is complete
		iEngine->Utils().LogIt(_L("<EResponseComplete received >\n"));
		} break;
	case THTTPEvent::ESucceeded:
		{
		iEngine->Utils().LogIt(_L("<ESucceeded received >\n"));
		CActiveScheduler::Stop();
		} break;
	default:
		{
		iEngine->Utils().LogIt(_L("<unrecognised event>\n %d"),aEvent.iStatus);
		if (aEvent.iStatus < THTTPEvent::ERedirectedPermanently)
			{
			iTestFail=1;
			iEngine->Utils().LogIt(_L("Test Failed: The event received was not expected and it's not just a warning\n"));
			iEngine->PressAnyKey();
			CActiveScheduler::Stop();
			}
		} 
		break;
		}
	}
Example #29
0
EXPORT_C void CHttpTestTransBase::DumpRespHeaders(RHTTPTransaction& aTrans)
//dump the message's headers
	{
	//dump the message's headers
	RHTTPResponse resp = aTrans.Response();
	TInt status = resp.StatusCode();
	if (!iEngine->IsSilent())
		iEngine->Utils().LogIt(_L("Status code = %d\n"), status);

	RStringPool strP = aTrans.Session().StringPool();
	RHTTPHeaders hdr = resp.GetHeaderCollection();
	THTTPHdrFieldIter it = hdr.Fields();

	TBuf<32>  fieldName16;
	TBuf<128> fieldVal16;

	while (it.AtEnd() == EFalse)
		{
		RStringTokenF fieldNameTk = it();
		RStringF fieldName = strP.StringF(fieldNameTk);
		THTTPHdrVal hVal;
		if (hdr.GetField(fieldName,0,hVal) == KErrNone)
			{
			TPtrC8 fieldNameStr(strP.StringF(fieldName).DesC());
			if (fieldNameStr.Length() > 32)
				fieldNameStr.Set(fieldNameStr.Left(32));

			fieldName16.Copy(fieldNameStr);

			THTTPHdrVal fieldVal;
			hdr.GetField(fieldName,0,fieldVal);
			switch (fieldVal.Type())
				{
				case THTTPHdrVal::KTIntVal:
					{
					iEngine->Utils().LogIt(_L("%S: %d\n"), &fieldName16, fieldVal.Int());
					} break;
				case THTTPHdrVal::KStrVal:
				case THTTPHdrVal::KStrFVal:
					{
					TPtrC8 fieldValStr(strP.StringF(fieldVal.StrF()).DesC());
					if (fieldValStr.Length() > 128)
						fieldValStr.Set(fieldValStr.Left(128));

					fieldVal16.Copy(fieldValStr);
					iEngine->Utils().LogIt(_L("%S: %S\n"), &fieldName16, &fieldVal16);
					} break;
				case THTTPHdrVal::KDateVal:
					{
					TDateTime date = fieldVal.DateTime();
					TTime t(date);
					TBuf<128> dateTimeString;
					TRAPD(err,t.FormatL(dateTimeString,KDateFormat));
					if (err == KErrNone)
						iEngine->Utils().LogIt(_L("%S: %S\n"), &fieldName16, &dateTimeString);
					} break;
				default:
					{
					iEngine->Utils().LogIt(_L("%S: <unrecognised value type>\n"), &fieldName16);
					}
				}
			}
		++it;
		}
	}