Exemplo n.º 1
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);
				}
			}
		}
	}
}
Exemplo n.º 2
0
void CTextModeTestMultiTrans::ValidateBodyL(RHTTPTransaction aTransaction)
{
    // In this test, the test URLs point to resources that contain just characters from the test number
    // i.e. http:/xxx/1.txt will contain only the char 1, CR or LF.
    // These numbers should also align with the transaction ID, since they were created in order
    RHTTPResponse resp = aTransaction.Response();
    MHTTPDataSupplier* body = resp.Body();
    TPtrC8 data;
    body->GetNextDataPart(data);
    TChar reqdCh = (TChar)(aTransaction.Id() + 48);
    for (TInt ii = 0; ii < data.Length(); ii++)
    {
        TChar ch = data[ii];
        if ((ch != reqdCh) && (ch != (TChar)0x0d) && (ch != (TChar)0x0a))
            User::Leave(KMultiTransFailed);
    }

    // OK - release the block
    body->ReleaseData();
}
Exemplo n.º 3
0
AMInt32 AMHttpGetResponseInfo(AMHttpResponse response, AMHttpQueryCode code, 
        AMUInt8* outBuf, AMUInt32 inOutBufLen)
	{
	REINTERPRET( HttpConnectionInternal*, temp, response );
	RHTTPResponse resp = temp->Transaction->Response();
	RHTTPHeaders headers = resp.GetHeaderCollection();
	
	TPtr8 ptr( outBuf, inOutBufLen );
	
	switch( code )
		{
		case AM_HTTP_STATUS_CODE:
			{
			ptr.AppendNum( resp.StatusCode() );
			break;
			}
		case AM_HTTP_VERSION:
			{
			ptr.Append( resp.Version().Name() );
			break;
			}
		}
	}
/**
 * CSymbianTransportAgent::MHFRunL()
 * Inherited from MHTTPTransactionCallback
 * Called by framework to pass transaction events.
 */
void CSymbianTransportAgent::MHFRunL( RHTTPTransaction aTransaction, 
                                const THTTPEvent& aEvent )
{
    LOG.debug("entering CSymbianTransportAgent::MHFRunL: iStatus = %d", aEvent.iStatus);

    switch ( aEvent.iStatus ) 
    {
        case THTTPEvent::EGotResponseHeaders:
        {
            LOG.debug(" -> 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.
            // Get HTTP status code from header (e.g. 200)
            RHTTPResponse resp = aTransaction.Response();
            TInt status = resp.StatusCode();

            // Get status text (e.g. "OK")
            // TBuf<32> statusText;
            // statusText.Copy( resp.StatusText().DesC() );
        
            // Please see
            // Symbian OS v9.1 << Symbian OS reference >> C++ component reference
            // << Application protocols HTTP >> HTTPStatus
            // for other status methods and constants
            HTTPStatus httpStatus;
            if (httpStatus.IsClientError(status)) {
                // errors in range 4xx
                SetHttpClientError(status);
            } else if (httpStatus.IsServerError(status)) {
                // errors in range 5xx
                SetHttpServerError(status);
            }
            LOG.debug("Returned HTTP status: %d", status);
        }
        break;

        case THTTPEvent::EGotResponseBodyData:
        {
            LOG.debug(" -> EGotResponseBodyData: setting the response");
            // Part (or all) of response's body data received. Use 
            // aTransaction.Response().Body()->GetNextDataPart() to get the actual
            // body data.
            // Get body data
            MHTTPDataSupplier* dataSupplier = aTransaction.Response().Body();
            TPtrC8 ptr;
            dataSupplier->GetNextDataPart(ptr);

            // Append to buffer
            if(!iResponseBody)
            {
                iResponseBody = HBufC8::NewL(ptr.Length());
                iResponseBody->Des().Copy(ptr);
            }
            else
            {
                iResponseBody = iResponseBody->ReAllocL(iResponseBody->Length()+ptr.Length());
                iResponseBody->Des().Append(ptr);
            }
            
            // release the body data
            dataSupplier->ReleaseData();

        }
        break;

        case THTTPEvent::EResponseComplete:
        {
            LOG.debug(" -> EResponseComplete");
            // Indicates that header & body of response is completely received.
            // No further action here needed.
        }
        break;

        case THTTPEvent::ESucceeded:
        {
            LOG.debug(" -> ESucceeded: stopping the AScheduler");
            // Indicates that transaction succeeded. 
            iTransFailed = EFalse;
            iASWait->AsyncStop();
        }
        break;

        case THTTPEvent::EFailed:
        {
            LOG.debug(" -> EFailed: stopping the AScheduler");
            iTransFailed = ETrue;
            iASWait->AsyncStop();
        }
        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.     
            LOG.debug(" -> default");
            
            if (aEvent.iStatus < 0) {
                LOG.debug("error status: stopping the AScheduler");
                // Signal the active scheduler on errors
                iTransFailed = ETrue;
                iASWait->AsyncStop();
            } 
            else {
                LOG.debug("non error status: ignoring");
                // Other events are not errors (e.g. permanent and temporary redirections)
            }
        }
        break;
    }
    
    LOG.debug("exiting CSymbianTransportAgent::MHFRunL");
}
Exemplo n.º 5
0
// ----------------------------------------------------------------------------
// CClientEngine::MHFRunL()
//
// Inherited from MHTTPTransactionCallback
// Called by framework to pass transaction events.
// ----------------------------------------------------------------------------
void CClientEngine::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.

			// Get HTTP status code from header (e.g. 200)
			RHTTPResponse resp = aTransaction.Response();
			TInt status = resp.StatusCode();

			// Get status text (e.g. "OK")
			TBuf<KStatustextBufferSize> statusText;
			statusText.Copy(resp.StatusText().DesC());

			TBuf<KDefaultBufferSize> text;
			_LIT(KHeaderReceived, "Header received. Status: %d %S");
			text.Format(KHeaderReceived, status, &statusText);
			iObserver.ClientEvent(text);
			}
			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);
			iObserver.ClientBodyReceived(dataChunk);

			TBuf<KInfotextBufferSize> text;
			_LIT(KBodyPartReceived, "%d bytes received... ");
			text.Format(KBodyPartReceived, dataChunk.Length());
			iObserver.ClientEvent(text);

			// 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)
				{
				_LIT(KBodyReceived,"Body received");
				iObserver.ClientEvent(KBodyReceived);
				}

			// Always remember to release the body data.
			body->ReleaseData();
			}
			break;

		case THTTPEvent::EResponseComplete:
			{
			// Indicates that header & body of response is completely received.
			// No further action here needed.
			_LIT(KTransactionComplete, "Transaction Complete");
			iObserver.ClientEvent(KTransactionComplete);
			}
			break;

		case THTTPEvent::ESucceeded:
			{
			// Indicates that transaction succeeded.
			_LIT(KTransactionSuccessful, "Transaction Successful");
			iObserver.ClientEvent(KTransactionSuccessful);

			// Transaction can be closed now. It's not needed anymore.
			aTransaction.Close();
			iRunning = EFalse;
			}
			break;

		case THTTPEvent::EFailed:
			{
			// Transaction completed with failure.
			_LIT(KTransactionFailed, "Transaction Failed");
			iObserver.ClientEvent(KTransactionFailed);
			aTransaction.Close();
			iRunning = EFalse;
			}
			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<KInfotextBufferSize> text;
			if (aEvent.iStatus < 0)
				{
				_LIT(KErrorStr, "Error: %d");
				text.Format(KErrorStr, aEvent.iStatus);
				// Just close the transaction on errors
				aTransaction.Close();
				iRunning = EFalse;
				} 
			else 
				{
				// Other events are not errors (e.g. permanent and temporary
				// redirections)
				_LIT(KUnrecognisedEvent, "Unrecognised event: %d");
				text.Format(KUnrecognisedEvent, aEvent.iStatus);
				}
			iObserver.ClientEvent(text);
			}
			break;
		}
	}
Exemplo n.º 6
0
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;
		}
	}
// ----------------------------------------------------------------------------
// CWmDrmDlaDefaultHttpManager::MHFRunL
// ----------------------------------------------------------------------------
void CWmDrmDlaDefaultHttpManager::MHFRunL(
    RHTTPTransaction aTransaction,
    const THTTPEvent& aEvent )
    {
    LOGFN( "CWmDrmDlaDefaultHttpManager::MHFRunL" );
    RHTTPResponse response;
    TPtrC8 dataChunk;

    // Either ESucceeded or EFailed will eventually occur
    switch ( aEvent.iStatus )
        {
        case THTTPEvent::EGotResponseHeaders:
            response = aTransaction.Response();

            iInCallback = ETrue;
            iObserver.OnResponseHeadersL(
                response,
                response.GetHeaderCollection(),
                iHttpSession.StringPool(),
                response.StatusCode() );

            break;

        case THTTPEvent::EGotResponseBodyData:
            // A member variable is used to store the body to avoid two
            // potential problems:
            // - OnResponseBodyDataL leaves
            // - Stop is called from within OnResponseBodyDataL
            iBody = aTransaction.Response().Body();
            User::LeaveIfNull( iBody );

            iBody->GetNextDataPart( dataChunk );

            iInCallback = ETrue;
            iObserver.OnResponseBodyDataL( dataChunk );

            // Verify that iBody wasn't already released
            // for example by calling Stop within ResponseBodyDataL
            if ( iBody )
                {
                iBody->ReleaseData();
                iBody = NULL;
                }

            break;

        case THTTPEvent::ESucceeded:
        case THTTPEvent::EFailed:
            // Deal with both the same as iError will either be negative or
            // KErrNone
            // If the user cancelled the credentials dialog then make sure we
            // return KErrCancel
            HandleDownloadComplete( iCredentialsOk ? iError : KErrCancel );
            break;

        default:
            // This will capture system and HTTP lib errors
            // For positive codes iError will remain to KErrNone
            if ( aEvent.iStatus < KErrNone )
                {
                iError = aEvent.iStatus;
                }
            break;
        }

    iInCallback = EFalse;
    }
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);
		}
	}
}
Exemplo n.º 9
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;
		}
	}
Exemplo n.º 10
0
void CHttpEventHandler::MHFRunL(RHTTPTransaction aTransaction, const THTTPEvent& aEvent)
	{
	switch (aEvent.iStatus)
		{
		case THTTPEvent::EGotResponseHeaders:
			{
			// HTTP response headers have been received. We can determine now if there is
			// going to be a response body to save.
			RHTTPResponse resp = aTransaction.Response();
			TInt status = resp.StatusCode();
			
			if (iVerbose)
			{
				RStringF statusStr = resp.StatusText();
				TBuf<32> statusStr16;
				statusStr16.Copy(statusStr.DesC());
				iTest->Console()->Printf(_L("Status: %d (%S)\n"), status, &statusStr16);

				// Dump the headers if we're being verbose
				DumpRespHeadersL(aTransaction);
			}
			// Determine if the body will be saved to disk
			iSavingResponseBody = EFalse;
			if (resp.HasBody() && (status >= 200) && (status < 300) && (status != 204))
			{
				if (iVerbose)
				{
					TInt dataSize = resp.Body()->OverallDataSize();
					if (dataSize >= 0)
						iTest->Console()->Printf(_L("Response body size is %d\n"), dataSize);
					else
						iTest->Console()->Printf(_L("Response body size is unknown\n"));
				}
				iSavingResponseBody = ETrue;
			}
			else
			{
				if (iVerbose)
					iTest->Console()->Printf(_L("Response status is bad\n"));
			}

			if ((status >= 200) && (status < 300) && (status != 204))
			{
				ParseCookieL(aTransaction);
			}
			
			if (iSavingResponseBody) // If we're saving, then open a file handle for the new file
			{
				if ( iUsingFile )
				{
					iHttpFileManager->GetNewFile(iRespBodyFilePath, iRespBodyFileName, EFalse);
					
					// Check it exists and open a file handle
					TInt valid = iFileServ.IsValidName(iRespBodyFilePath);
					if (!valid)
					{
						if (iVerbose)
							iTest->Console()->Printf(_L("The specified filename is not valid!.\n"));
						
						iSavingResponseBody = EFalse;
					}
					else
					{
						TInt err = iRespBodyFile.Create(iFileServ,
													  iRespBodyFilePath,
													  EFileWrite|EFileShareExclusive);
						if (err)
						{
							iSavingResponseBody = EFalse;
							User::Leave(err);
						}
					}
				}
				else
				{
					TInt dataSize = resp.Body()->OverallDataSize();
					
					if ( iResBodyBuffer )
						delete iResBodyBuffer;
						
					iResBodyBuffer = NULL;
					
					if ( dataSize > 50 * 1024) //skip large chunks of data
					{
						iSavingResponseBody = false;
						//try to stop current connection
						if (iVerbose)
							iTest->Console()->Printf(_L("Transaction Failed\n"));
						aTransaction.Close();
						CActiveScheduler::Stop();
					}
					else
					{
						iResBodyBuffer = HBufC8::NewMaxL(dataSize);
						iResBodyBufferPtr.Set(iResBodyBuffer->Des());
					}					
					iCurPos = 0;
				}
			}
			
		} break;
		case THTTPEvent::EGotResponseBodyData:
			{
			// Get the body data supplier
			iRespBody = aTransaction.Response().Body();

			// Some (more) body data has been received (in the HTTP response)
			if (iVerbose)
				DumpRespBody(aTransaction);
			
			// Append to the output file if we're saving responses
			if (iSavingResponseBody)
			{
				TPtrC8 bodyData;
				TBool lastChunk = iRespBody->GetNextDataPart(bodyData);
								
				if ( iUsingFile )
				{
					iRespBodyFile.Write(bodyData);
					if (lastChunk)
					{
						iRespBodyFile.Flush();
						iRespBodyFile.Rename(iRespBodyFileName);
						iRespBodyFile.Close();
					}
				}
				else
				{
					Mem::Copy((void*)(iResBodyBuffer->Ptr()+iCurPos), (void*)bodyData.Ptr(), bodyData.Size());
					iCurPos += bodyData.Size();
				}
			}

			// Done with that bit of body data
			iRespBody->ReleaseData();
			} break;
		case THTTPEvent::EResponseComplete:
			{
			// The transaction's response is complete
			if (iVerbose)
				iTest->Console()->Printf(_L("\nTransaction Complete\n"));
			} break;
		case THTTPEvent::ESucceeded:
			{
			if (iVerbose)
				iTest->Console()->Printf(_L("Transaction Successful\n"));
			aTransaction.Close();
			CActiveScheduler::Stop();
			} break;
		case THTTPEvent::EFailed:
			{
			if (iVerbose)
				iTest->Console()->Printf(_L("Transaction Failed\n"));
			aTransaction.Close();
			CActiveScheduler::Stop();
			} break;
		case THTTPEvent::ERedirectedPermanently:
			{
			if (iVerbose)
				iTest->Console()->Printf(_L("Permanent Redirection\n"));
			} break;
		case THTTPEvent::ERedirectedTemporarily:
			{
			if (iVerbose)
				iTest->Console()->Printf(_L("Temporary Redirection\n"));
			} break;
		default:
			{
			if (iVerbose)
				iTest->Console()->Printf(_L("<unrecognised event: %d>\n"), aEvent.iStatus);
			// close off the transaction if it's an error
			if (aEvent.iStatus < 0)
				{
				aTransaction.Close();
				CActiveScheduler::Stop();
				}
			} break;
		}
	}
Exemplo n.º 11
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;
		}
	}
Exemplo n.º 12
0
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;
	}
}
Exemplo n.º 13
0
// MHTTPTransactionCallback interface functions
void CXmlHandler::MHFRunL(RHTTPTransaction aTransaction, const THTTPEvent& aEvent)
{
	switch (aEvent.iStatus) 
	{ 
	case THTTPEvent::EGotResponseHeaders: 
		{
			iObserver.GIEStateChanged(eStateFoundServer);				
			iModel.iState = eStateFoundServer;

			/*
			Not interested in the received header 
			*/
		}
		break; 
	case THTTPEvent::EGotResponseBodyData: 
		{

#ifdef _INCREMENTAL_H

#else
			/*
			The non incremental version of the parser will just build 
			up a string of the data until the EReponseComplete code is
			received. Then the string is sent to parser in one go
			*/
			RHTTPResponse response = aTransaction.Response();
			MHTTPDataSupplier* bodyPtr = response.Body();

			/*
			Received data is appended to the existing block (if there is a block),
			otherwise a new block is created
			*/
			TPtrC8 bodypart;
			bodyPtr->GetNextDataPart(bodypart);
			if (iQueryResponse == NULL)
			{
				iQueryResponse = HBufC8::NewL( bodypart.Length() );
			}
			else
			{
				const TInt newSize = iQueryResponse->Length() + bodypart.Length();
				iQueryResponse = iQueryResponse->ReAllocL( newSize );
			}
			TPtr8 tmp = iQueryResponse->Des();
			tmp.Append(bodypart);
			bodyPtr->ReleaseData();
#endif
		}
		break; 
	case THTTPEvent::EResponseComplete: 
		{
			iObserver.GIEStateChanged(eStateReceivedResponse);				
			iModel.iState = eStateReceivedResponse;

#ifdef _INCREMENTAL_H

#else
#ifdef LOG_RESONSE
			LogMessage(iFs, KResponseFilename, *iQueryResponse);
#endif
			/*
			Data block ready. Parse and fill data model
			*/
			OneTripParse(iQueryResponse->Des(), iModel.iError, iModel.iResult, iModel.iItems);
#endif				

			CleanupQueryText();
			iObserver.GIEStateChanged(eStateComplete);				
			iModel.iState = eStateComplete;

		}
		break; 
	case THTTPEvent::ESucceeded: 
		{
			// transaction successful
			// we do not do this in the response complete phase or error
			// phase as it is nicer to break it up because if the parser
			// is working non incrementally we have potientionally done
			// a lot of work in the ReponseComplete phase
			iObserver.GIEStateChanged(eStateComplete);				
			iModel.iState = eStateComplete;
		}
		break; 
	case THTTPEvent::EFailed: 
		{
			// Transaction failed
			MHFRunError(aEvent.iStatus, aTransaction, aEvent);
		}
		break;
	default: 
		{
			/* 
			All errors will fall through to the generic event handler
			The only exceptional error handling is done when the soap 
			request itself fails and it reports an error
			*/
			MHFRunError(aEvent.iStatus, aTransaction, aEvent);
		}
		break;
	}
}
Exemplo n.º 14
0
//------------------------------------------------------------------------
// 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;
                        }
			
		}
	}
}