/**
    Check if the buffer is filled with aFill character.
    @param  aBufPtr buffer descriptor
    @param  aFill filling character
    @return ETrue if the buffer is filled with aFill byte.
*/
static TBool CheckBufFill(const TPtrC8& aBufPtr, TUint8 aFill)
{
    const TUint32 bufSz = (TUint32)aBufPtr.Size();
    
    //-- optimised by using DWORD granularity
    if(bufSz % sizeof(TUint32) == 0)
    {
        TUint32 wordPattern = aFill;
        wordPattern <<= 8; wordPattern |= aFill;
        wordPattern <<= 8; wordPattern |= aFill;
        wordPattern <<= 8; wordPattern |= aFill;

        const TUint nWords = bufSz / sizeof(TUint32);
        const TUint32* pWords = (const TUint32*) aBufPtr.Ptr();

        for(TUint32 i=0; i<nWords; ++i)
        {
            if(pWords[i] != wordPattern)
                return EFalse;
        }

        return ETrue;
    }
    
    //-- dumb implementation
    for(TUint32 i=0; i<bufSz; ++i)
    {
        if(aBufPtr[i] != aFill)
            return EFalse;
    }

    return ETrue;
}
Example #2
0
void RCdlSession::SetUidsToNotifyL(const CCdlUids& aUids)
	{
	TPtrC8 ptr = aUids.Export();

	TIpcArgs p(&ptr, ptr.Size());
	User::LeaveIfError(SendReceive(ECdlServCmdSetUidsToNotify,p));
	}
// -----------------------------------------------------------------------------
// TBTSUDataConverter::ConvertDataUnsignedL
// -----------------------------------------------------------------------------
//
TUint32 TBTSUDataConverter::ConvertDataUnsignedL( const TPtrC8& aData )
    {
    if ( aData.Size() != sizeof(TUint32) )
        {
        User::Leave( KErrArgument );
        }
    return BigEndian::Get32(aData.Ptr());
    }
EXPORT_C TInt CMTPTypeOpaqueData::Write( const TPtrC8 &aDes)
    {
    if(iBuffer.MaxSize() != 0)
        {
        iBuffer.Close();
        }
    
    iPtrBuffer.Set(const_cast<TUint8*>(aDes.Ptr()), aDes.Length(), aDes.Size());
    return KErrNone;
    }
EXPORT_C TInt TWsGraphicMsgAnimation::Load(const TWsGraphicMsgBufParser& aData,TInt aIndex)
	{
	if(aData.Uid(aIndex).iUid != TWsGraphicAnimation::ETypeId)
		{
		return KErrArgument;
		}
	const TPtrC8 pckg = aData.Data(aIndex);
	if(pckg.Size() != sizeof(TWsGraphicMsgAnimation))
		{
		return KErrCorrupt;
		}
	memcpy(this,pckg.Ptr(),sizeof(TWsGraphicMsgAnimation));
	return KErrNone;
	}
void QBluetoothServiceDiscoveryAgentPrivate::VisitAttributeValueL(CSdpAttrValue &aValue, TSdpElementType aType)
{
  qDebug() << "VisitAttributeValueL";
    QVariant var;
    TUint datasize = aValue.DataSize();
    
    switch (aType) {
    case ETypeNil:
        break;
    case ETypeUint:
        if (datasize == 8) {
            TUint64 value;
            aValue.Uint64(value);
            var = QVariant::fromValue(value);
        } else
            var = QVariant::fromValue(aValue.Uint());
        break;
    case ETypeInt:
            var = QVariant::fromValue(aValue.Int());
        break;
    case ETypeUUID: {
        TPtrC8 shortForm(aValue.UUID().ShortestForm());
        if (shortForm.Size() == 2) {
            QBluetoothUuid uuid(ntohs(*reinterpret_cast<const quint16 *>(shortForm.Ptr())));
            var = QVariant::fromValue(uuid);
        } else if (shortForm.Size() == 4) {
            QBluetoothUuid uuid(ntohl(*reinterpret_cast<const quint32 *>(shortForm.Ptr())));
            var = QVariant::fromValue(uuid);
        } else if (shortForm.Size() == 16) {
            QBluetoothUuid uuid(*reinterpret_cast<const quint128 *>(shortForm.Ptr()));
            var = QVariant::fromValue(uuid);
        }
        break;
    }
    case ETypeString: {
        TPtrC8 stringBuffer = aValue.Des();
        var = QVariant::fromValue(QString::fromLocal8Bit(reinterpret_cast<const char *>(stringBuffer.Ptr()), stringBuffer.Size()));
        break;
    }
    case ETypeBoolean:
        var = QVariant::fromValue(static_cast<bool>(aValue.Bool()));
        break;
    case ETypeDES:
        m_stack.push(QVariant::fromValue(QBluetoothServiceInfo::Sequence()));
        break;
    case ETypeDEA:
        m_stack.push(QVariant::fromValue(QBluetoothServiceInfo::Alternative()));
        break;
    case ETypeURL: {
        TPtrC8 stringBuffer = aValue.Des();
        var = QVariant::fromValue(QUrl(QString::fromLocal8Bit(reinterpret_cast<const char *>(stringBuffer.Ptr()), stringBuffer.Size())));
        break;
    }
    case ETypeEncoded:
        qWarning() << "Don't know how to handle encoded type.";
        break;
    default:
        qWarning() << "Don't know how to handle type" << aType;
    }

    if (aType != ETypeDES && aType != ETypeDEA) {
        if (m_stack.size() == 0) {
            // single value attribute, just push onto stack
            m_stack.push(var);
        } else if (m_stack.size() >= 1) {
            // sequence or alternate attribute, add non-DES -DEA values to DES or DEA
            if (m_stack.top().canConvert<QBluetoothServiceInfo::Sequence>()) {
                QBluetoothServiceInfo::Sequence *sequence = static_cast<QBluetoothServiceInfo::Sequence *>(m_stack.top().data());
                sequence->append(var);
            } else if (m_stack.top().canConvert<QBluetoothServiceInfo::Alternative>()) {
                QBluetoothServiceInfo::Alternative *alternative = static_cast<QBluetoothServiceInfo::Alternative *>(m_stack.top().data());
                alternative->append(var);
            } else {
                qWarning("Unknown type in the QVariant, should be either a QBluetoothServiceInfo::Sequence or an QBluetoothServiceInfo::Alternative");
            }
        }
    }
}
// --------------------------------------------------------------------------------------
// Serializes TXmlEngNode to buffer
// --------------------------------------------------------------------------------------
//
TInt CXmlEngSerializerXOP::SerializeL( RBuf8& aBuffer, 
                                    const TXmlEngNode aRoot, 
									const TXmlEngSerializationOptions& aOptions )
    {
    if(aBuffer.Length())
        {
        aBuffer.Close();
        }
	LeaveIfXopIncludeL(aRoot);
    iDataContainerArray.Reset();	    
    if(aOptions.iDataSerializer)
    	{
    	return CXmlEngSerializer::SerializeL(aBuffer, aRoot, aOptions);
    	}    
    	
	TXmlEngSerializationOptions opt = aOptions;
	opt.iDataSerializer = this;
			
	RBuf8 xopDocument;
	CleanupClosePushL(xopDocument);
	aRoot.OwnerDocument().SaveL(xopDocument, aRoot, opt);

	if( iCleanXOPInfoset )		
		{
		if(xopDocument.Size() > aBuffer.MaxSize())
		    {
		    aBuffer.ReAllocL( xopDocument.Size() );
		    }
		aBuffer.Append(xopDocument);		
		}
	else		
		{    
	    // adjust buffer size
		TInt bufSize = KXOPDocumentStart().Size() 
					+ KMimeRoot().Size() 
					+ xopDocument.Size()
					+ KXOPDocumentEnd().Size();
		for(TInt j = 0; j < iDataContainerArray.Count(); j++)	
			{
			TPtrC8 contentTypeStr;
			if(GetContentTypeValue(iDataContainerArray[j], contentTypeStr))
				{
				bufSize += KMimeHeaderContentType().Size() 
						+ contentTypeStr.Size() 
						+ KNewLine().Size();					
				}
			bufSize += KMimeHeaderStart().Size() 
					+ KMimeHeaderContentIdStart().Size()
					+ iDataContainerArray[j].Cid().Length()
					+ KMimeHeaderContentIdEnd().Size()
					+ KNewLine().Size()
					+ iDataContainerArray[j].Size(); 
			}
		if (bufSize > aBuffer.MaxSize())
		    {
		    aBuffer.ReAllocL( bufSize );
		    }
		    
		// write to buffer
		aBuffer.Append(KXOPDocumentStart());
		aBuffer.Append(KMimeRoot());
		aBuffer.Append(xopDocument);
		for(TInt i = 0; i < iDataContainerArray.Count(); i++)	
			{
			aBuffer.Append(KMimeHeaderStart);
			TPtrC8 contentTypeStr;
			if(GetContentTypeValue(iDataContainerArray[i], contentTypeStr))
				{	
				aBuffer.Append(KMimeHeaderContentType);
				aBuffer.Append(contentTypeStr);
				aBuffer.Append(KNewLine);
				}
			aBuffer.Append(KMimeHeaderContentIdStart);				
			aBuffer.Append(iDataContainerArray[i].Cid());
			aBuffer.Append(KMimeHeaderContentIdEnd);
			aBuffer.Append(KNewLine);	
			switch(iDataContainerArray[i].NodeType())
				{
				case TXmlEngNode::EBinaryContainer:
					{
					if(opt.iOptions & TXmlEngSerializationOptions::KOptionDecodeBinaryContainers )	
						{						
						HBufC8* decodedData = CreateDecodedBufLC(iDataContainerArray[i].AsBinaryContainer().Contents());
						aBuffer.Append(decodedData->Des());
						CleanupStack::PopAndDestroy(); //decodedData
						}
					else
						{
						aBuffer.Append(iDataContainerArray[i].AsBinaryContainer().Contents());							
						}
					break;
					}
				case TXmlEngNode::EChunkContainer:
					{
					TPtrC8 data = TPtrC8(
						((RChunk&)iDataContainerArray[i].AsChunkContainer().Chunk()).Base()
						+ iDataContainerArray[i].AsChunkContainer().ChunkOffset(),
						iDataContainerArray[i].AsChunkContainer().Size());
					if(opt.iOptions & TXmlEngSerializationOptions::KOptionDecodeBinaryContainers )	
						{							
						HBufC8* decodedData = CreateDecodedBufLC(data); 
						aBuffer.Append(decodedData->Des());
						CleanupStack::PopAndDestroy(); //decodedData
						}
					else
						{
						aBuffer.Append(data);							
						}
					break;
					}
				case TXmlEngNode::EFileContainer:
					{
					TInt size = iDataContainerArray[i].AsFileContainer().Size();
					HBufC8* data = HBufC8::NewLC(size);
					TPtr8 dataPtr = data->Des();
					iDataContainerArray[i].AsFileContainer().File().Read(dataPtr, size);
					if(opt.iOptions & TXmlEngSerializationOptions::KOptionDecodeBinaryContainers )	
						{
						HBufC8* decodedData = CreateDecodedBufLC(dataPtr); 
						aBuffer.Append(decodedData->Des());
						CleanupStack::PopAndDestroy(); //decodedData							
						}
					else
						{
						aBuffer.Append(dataPtr);
						}
					CleanupStack::PopAndDestroy(); //data
					break;
					}														
				}						
			}
		aBuffer.Append(KXOPDocumentEnd);
		}
	CleanupStack::PopAndDestroy(); //xopDocument
	return aBuffer.Size(); 
    }
// -----------------------------------------------------------------------------
// CCMSX509CertificateList::ConstructL
// Symbian 2nd phase constructor can leave.
// -----------------------------------------------------------------------------
//
EXPORT_C void CCMSX509CertificateList::ConstructL(
	const CX509Certificate& aSigningCertificate,
	const CArrayPtrFlat<CX509Certificate>& aRevokedCertificates )
    {
	ConstructL();

	// setting signature
	const CSigningAlgorithmIdentifier& signAlgorithm =
		aSigningCertificate.SigningAlgorithm();
	iParams->iSignatureAlgorithm =
		CCMSX509AlgorithmIdentifier::NewL( signAlgorithm.AsymmetricAlgorithm(),
										   signAlgorithm.DigestAlgorithm() );

	// setting issuer
	iParams->iIssuer =
		CX500DistinguishedName::NewL( aSigningCertificate.IssuerName() );

	// setting validity
	const CValidityPeriod& validity = aSigningCertificate.ValidityPeriod();
	iParams->iThisUpdate = validity.Start();
	iParams->iNextUpdate = validity.Finish();


	// copying revoked certificates
	TInt revCerts = aRevokedCertificates.Count();
	if( revCerts > 0 )
		{
		iParams->iRevokedCertificates =
			new( ELeave )CArrayPtrFlat< CCMSX509RevokedCertificate >
												( KDefaultGranularity );
		for( TInt i = 0; i < revCerts; i++ )
			{
			CX509Certificate* cert = aRevokedCertificates[ i ];
			CCMSX509RevokedCertificate* tmpRevCer =
				new(ELeave) CCMSX509RevokedCertificate();
			CleanupStack::PushL( tmpRevCer );
			// convert serial from des to int
            TPtrC8 serialDes = cert->SerialNumber();
            TInt length = serialDes.Size();
            const TUint8* ptr = serialDes.Ptr();
            TInt serial = ( ptr[ 0 ] & 0x80 ) ? -1 : 0;
            for( TInt j = 0; j < length; j++ )
                {
                serial <<= 8;
                serial += *ptr++;
                }
			tmpRevCer->iUserCertificateSerialNumber = serial;

			const CValidityPeriod& reValidity = cert->ValidityPeriod();
			tmpRevCer->iRevokationDate = reValidity.Start();

			// copying extensions
			const CArrayPtrFlat<CX509CertExtension>& extensions =
				cert->Extensions();
			TInt extensionCount = extensions.Count();
			if( extensionCount > 0 )
				{
				tmpRevCer->iExtensions =
					new(ELeave) CArrayPtrFlat<CX509CertExtension>
														( KDefaultGranularity );
				for( TInt j = 0; j < extensionCount; j++ )
					{
					CX509CertExtension* ext = extensions[ j ];
					CX509CertExtension* tmpExt =
									CX509CertExtension::NewLC( *ext );
					tmpRevCer->iExtensions->AppendL( tmpExt );
					CleanupStack::Pop( tmpExt );
					}
				}
			iParams->iRevokedCertificates->AppendL( tmpRevCer );
			CleanupStack::Pop( tmpRevCer );
			}
		}
	// copying possible extensions
	TInt extensionCount = aSigningCertificate.Extensions().Count();
	if( extensionCount > 0 )
		{
		iParams->iExtensions =
			new( ELeave )CArrayPtrFlat< CX509CertExtension >
														( KDefaultGranularity );
		const CArrayPtrFlat< CX509CertExtension >& extensions =
			aSigningCertificate.Extensions();

		for( TInt i = 0; i < extensionCount; i++ )
			{
			CX509CertExtension* copy = CX509CertExtension::NewL( *extensions[ i ] );
			CleanupStack::PushL( copy );
			iParams->iExtensions->AppendL( copy );
			CleanupStack::Pop( copy );
			}
		}

	// copying signature
	iParams->iSignature = aSigningCertificate.Signature().AllocL();
    }
TInt CSenBaseIdentityManager::AuthenticationForL(
                            CSenIdentityProvider& aProvider, 
                            TPckgBuf<TSenAuthentication>& aResponse)
    {
    TLSLOG_L(KSenCoreServiceManagerLogChannelBase  , KMinLogLevel,"CSenBaseIdentityManager::AuthenticationForL");

    TPtrC8 user = aProvider.AuthzID();
    if (user == KNullDesC8)
        {
        user.Set(aProvider.AdvisoryAuthnID());
        }


    if (!iShowPasswordDialog)
        {
        TLSLOG_L(KSenCoreServiceManagerLogChannelBase  , KMinLogLevel,"Not allowed to show password dialog");
        HBufC8* pDecodedPassword = SenXmlUtils::DecodeHttpCharactersLC(aProvider.Password());
        TPtrC8 decodedPassword = pDecodedPassword->Des();

        aResponse().iUsername.Append((const TUint8*)user.Ptr(), user.Size());
        aResponse().iPassword.Append((const TUint8*)decodedPassword.Ptr(), 
                                        decodedPassword.Size());
        CleanupStack::PopAndDestroy(); // delete pDecodedPassword
        return KErrNone;
        }


    RNotifier notifier;
    User::LeaveIfError(notifier.Connect());
    CleanupClosePushL(notifier);

    TPckgBuf<TAuthenticationDlgRequest>* request = 
                            new(ELeave)TPckgBuf<TAuthenticationDlgRequest>();
    CleanupStack::PushL(request);

    // convert username to unicode
    HBufC* pUserAsUnicode = SenXmlUtils::ToUnicodeLC(user); // push
    TPtrC username = pUserAsUnicode->Des();

    // decode password
    HBufC8* pDecodedPassword = SenXmlUtils::DecodeHttpCharactersLC(aProvider.Password());
    TPtrC8 decodedPassword = pDecodedPassword->Des();
    // convert decoded password to unicode
    HBufC* pPasswordAsUnicode = 
                SenXmlUtils::ToUnicodeLC(decodedPassword); // push
    TPtrC password = pPasswordAsUnicode->Des();

    // set data to request
    (*request)().SetData(username, password);

    CleanupStack::PopAndDestroy(3); // delete pPasswordAsUnicode, pDecodedPassword, pUserAsUnicode


    TPckgBuf<TAuthenticationDlgResponse>* response = 
                        new(ELeave)TPckgBuf<TAuthenticationDlgResponse>();
    CleanupStack::PushL(response);

    TRequestStatus reqStatus;
    notifier.StartNotifierAndGetResponse(reqStatus, 
                            KSenNotifierPluginUID, *request, *response);

    TBool illegalUsername = EFalse;

    HBufC8* pUsernameUtf8 = NULL;
    HBufC8* pPasswordUtf8 = NULL;
    User::WaitForRequest(reqStatus);

    notifier.Close();

    if(reqStatus.Int() == KErrNone)
        {
        if((*response)().OkButtonPressed())
            {
            TLSLOG(KSenCoreServiceManagerLogChannelBase  , KMinLogLevel,(_L("User pressed OK Button in Password dialog")));
            pUsernameUtf8 = SenXmlUtils::ToUtf8LC((*response)().Username());
            pPasswordUtf8 = SenXmlUtils::ToUtf8LC((*response)().Password());
            TLSLOG_FORMAT((KSenCoreServiceManagerLogChannelBase  , KMinLogLevel, _L8("Username: %S"), pUsernameUtf8));
            TLSLOG_FORMAT((KSenCoreServiceManagerLogChannelBase  , KMinLogLevel, _L8("Password: %S"), pPasswordUtf8 ));
            HBufC8* pEncodedUsername = NULL;
            illegalUsername = 
                SenXmlUtils::EncodeHttpCharactersL(*pUsernameUtf8,
                                                    pEncodedUsername);
            if (illegalUsername) 
                {
                TLSLOG(KSenCoreServiceManagerLogChannelBase  , KMinLogLevel,(_L("Username included illegal characters.")));
                delete pEncodedUsername;
                pEncodedUsername = NULL;
                }
#ifdef _SENDEBUG
            else
                {
                TLSLOG_L(KSenCoreServiceManagerLogChannelBase  , KMinLogLevel,"Username did NOT include illegal characters.");
                }
#endif
       		
       		//Check if iilegal chars are there then return
            if (!illegalUsername)
                {
                
                if(user != *pUsernameUtf8)
                {
                	
	                // User modified the username in the dialog prompt(!)
	                // We have to save it right away, because there is
	                // no in-memory/session based member variables in
	                // components calling identity manager (sec mechs and
	                // in ID-WSF AS client!
	                TLSLOG_L(KSenCoreServiceManagerLogChannelBase  , KMinLogLevel,"Username changed. Saving new username.");

	                // Use Advisory only if AuthzID is not available
	                if (aProvider.AuthzID() == KNullDesC8 
	                    && aProvider.AdvisoryAuthnID() != KNullDesC8)
	                    {
	                    aProvider.SetUserInfoL(aProvider.AuthzID(),
	                                            *pUsernameUtf8, 
	                                            aProvider.Password());
	                    }
	                else 
	                    {
	                    // There was at least AuthzID available, and possibly
	                    // also advisory value. Any way, if 

	                    
	                    // We have to NULL advisory value (set it to KNullDesC8), 
	                    // because if both were available, then user was
	                    // prompted to allow modification of AuthzID AND 
	                    // if advisory was changed in service (is no longer
	                    // valid), there would NOT be any way for end-user
	                    // to change (remove) it(!)

	                    CSenElement& element = aProvider.AsElement();
	                    delete element.RemoveElement(KSenIdpAdvisoryAuthnIdLocalname);

	                    aProvider.SetUserInfoL(*pUsernameUtf8, 
	                                            KNullDesC8,
	                                            aProvider.Password());
	                    }
	                // serialize changed username into sensessions.xml database immediately
	                WriteDatabase();
                }
                
	            if (AllowSavePasswordL())
	                {
	                HBufC8* pEncodedPassword = SenXmlUtils::EncodeHttpCharactersLC(*pPasswordUtf8);
#ifdef _SENDEBUG
                if(pEncodedPassword)
                    {
                    TLSLOG_FORMAT((KSenCoreServiceManagerLogChannelBase  , KMinLogLevel, _L8("Encoded password: %S"), pEncodedPassword));
                    }
#endif
					if(pEncodedPassword)
						{
							aProvider.SetUserInfoL(aProvider.AuthzID(),
	                                        aProvider.AdvisoryAuthnID(),
	                                        *pEncodedPassword);
						}
	                WriteDatabase();
	                CleanupStack::PopAndDestroy(1); // pEncodedPassword
	                }
                
                }

            aResponse().iUsername.Zero();
            aResponse().iPassword.Zero();
            if (!illegalUsername) 
            {
	            aResponse().iUsername.Copy(pUsernameUtf8->Des());
	            aResponse().iPassword.Copy(pPasswordUtf8->Des());
            }

            CleanupStack::PopAndDestroy(2); // pPasswordUtf8, pUsernameUtf8
            }
        else
            {
            TLSLOG(KSenCoreServiceManagerLogChannelBase  , KMinLogLevel,(_L("User pressed Cancel Button in Password dialog")));
            }
        }
    else if(reqStatus.Int() == KErrNotFound)
        {
        TLSLOG(KSenCoreServiceManagerLogChannelBase  , KMinLogLevel,(_L("Password dialog plugin notifier impl. was not found")));
        }
    else
        {
        TLSLOG_FORMAT((KSenCoreServiceManagerLogChannelBase  , KMinLogLevel, _L8(" Notifier plugin for 'Password' dialog returned an error: %d"), 
                                                        reqStatus.Int()));
        }

    CleanupStack::PopAndDestroy(2); // request, response;
    CleanupStack::Pop(); // notifier

    if (illegalUsername) return KErrArgument;
    return reqStatus.Int();
    }
Example #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;
		}
	}
LOCAL_C void CreateNewPlaintextMessageL()
	{
	CTestActive* testActive = new(ELeave) CTestActive();
	CleanupStack::PushL(testActive);
	TMsvEmailTypeList msvEmailTypeList = 0;
	TMsvPartList partList = (KMsvMessagePartBody | KMsvMessagePartAttachments);
	CImEmailOperation* emailOperation = CImEmailOperation::CreateNewL(testActive->iStatus, *(testUtils->iMsvSession),KMsvGlobalOutBoxIndexEntryId, partList, msvEmailTypeList, KUidMsgTypeSMTP);
	CleanupStack::PushL(emailOperation);
	TestMsvOperationTimer* testMsvOperationTimer = TestMsvOperationTimer::NewLC(test.Console(), emailOperation, test);
	testActive->StartL();
	testMsvOperationTimer->IssueRequest();
	CActiveScheduler::Start();
	//check progress
	TMsvId temp;
	TPckgC<TMsvId> paramPack(temp);
	const TDesC8& progBuf = emailOperation->ProgressL();
	paramPack.Set(progBuf);
	TMsvId newMessageId;
	newMessageId = paramPack();
	test(newMessageId != NULL);
	CImEmailMessage* imEmailMessage = CImEmailMessage::NewLC(*(testUtils->iMsvEntry));
	// Make sure you are set on the Message Id
	testUtils->iMsvEntry->SetEntryL(newMessageId);
	CMsvAttachment* attachmentInfo = CMsvAttachment::NewL(CMsvAttachment::EMsvFile);
	CleanupStack::PushL(attachmentInfo);
	attachmentInfo->SetAttachmentNameL(KAttachmentFileName1());
	CleanupStack::Pop(attachmentInfo);	 // ownership passed to attachment manager
	imEmailMessage->AttachmentManager().AddAttachmentL(KAttachment1, attachmentInfo, testActive->iStatus);
	testActive->StartL();
	CActiveScheduler::Start();	// wait for the asynch operation to complete
	if (testActive->iStatus.Int())
		{
		testUtils->WriteComment(_L("CreateNewPlaintextMessageWithIncompleteAttachmentL failed"));
		testUtils->TestHarnessFailed(testActive->iStatus.Int());
		}
	testUtils->iMsvEntry->SetEntryL(newMessageId);
	CMsvAttachment* attachmentInfo1 = CMsvAttachment::NewL(CMsvAttachment::EMsvFile);
	CleanupStack::PushL(attachmentInfo1);
	attachmentInfo1->SetAttachmentNameL(KAttachmentFileName2());
    CleanupStack::Pop(attachmentInfo1);	 // ownership passed to attachment manager
	imEmailMessage->AttachmentManager().AddAttachmentL(KAttachment2, attachmentInfo1, testActive->iStatus);
	testActive->StartL();
	CActiveScheduler::Start();	// wait for the asynch operation to complete
	if (testActive->iStatus.Int())
		{
		testUtils->WriteComment(_L("CreateNewPlaintextMessageWithIncompleteAttachmentL failed"));
		testUtils->TestHarnessFailed(testActive->iStatus.Int());
		}
	testUtils->iMsvEntry->SetEntryL(newMessageId);
	CMsvAttachment* attachmentInfo2 = CMsvAttachment::NewL(CMsvAttachment::EMsvFile);
	CleanupStack::PushL(attachmentInfo2);
	attachmentInfo2->SetAttachmentNameL(KAttachmentFileName3());
    CleanupStack::Pop(attachmentInfo2);	 // ownership passed to attachment manager
	imEmailMessage->AttachmentManager().AddAttachmentL(KAttachment3, attachmentInfo2, testActive->iStatus);
	testActive->StartL();
	CActiveScheduler::Start();	// wait for the asynch operation to complete
	if (testActive->iStatus.Int())
		{
		testUtils->WriteComment(_L("CreateNewPlaintextMessageWithIncompleteAttachmentL failed"));
		testUtils->TestHarnessFailed(testActive->iStatus.Int());
		}	
	const TDesC8& progBuf2 = imEmailMessage->ProgressL();	
	paramPack.Set(progBuf2);
	TMsvId attachmentId = paramPack();
	testUtils->WriteComment(_L("\t Created New plaintext message"));
	testUtils->iMsvEntry->SetEntryL(attachmentId);
	
    imEmailMessage->GetAttachmentsListL(testActive->iStatus, newMessageId, CImEmailMessage::EAllAttachments, CImEmailMessage::EThisMessageOnly);	
  	testActive->StartL();
	CActiveScheduler::Start();	// wait for the asynch operation to complete
    const CMsvEntrySelection& selection = imEmailMessage->Selection();
	testUtils->Printf(KTotalNoOfAttachment , selection.Count());
	imEmailMessage->GetBodyTextEntryIdL(testActive->iStatus,newMessageId,CImEmailMessage::EThisMessageOnly);
	testActive->StartL();
	CActiveScheduler::Start();	// wait for the asynch operation to complete
	const CMsvEntrySelection& selection1 = imEmailMessage->Selection();
	TInt count = imEmailMessage->Selection().Count();
    if( count > 0)
			{
			// Get the Id of the body text
			// The body text part Id is present at index 0.  Not checking for other
			//  Ids, as currently only Plain text part is verified.
			TMsvId	iBodyTextId = imEmailMessage->Selection().At(0);
			testUtils->Printf(KBodytextId, iBodyTextId);
			}
	CleanupStack::PopAndDestroy(); // imEmailMessage  
		testUtils->iMsvEntry->SetEntryL(attachmentId);
    CMsvStore* store1 = testUtils->iMsvEntry->EditStoreL();
	CleanupStack::PushL(store1);
	CImMimeHeader *Head1 = CImMimeHeader::NewLC();
    Head1->RestoreL(*store1);
	const TPtrC8 contentSubType = Head1->ContentSubType();
	store1->CommitL();
    
    if(contentSubType.Size() == 0 )
    {
    testUtils->Printf(_L("ContentSubType Has NO SUB CONTENT****") );
    test(contentSubType.Size() != 0);
    }
    else
    {
    testUtils->Printf(_L("ContentSubType Has ****SUB CONTENT****"));	
    }
   	CleanupStack::PopAndDestroy(2, store1);//store1,Head1,Buffer
    testUtils->iMsvEntry->SetEntryL(newMessageId);
    CMsvStore* store = testUtils->iMsvEntry->EditStoreL();
	CleanupStack::PushL(store);
	CImHeader* header = CImHeader::NewLC();
	header->RestoreL(*store);
	TInt serverLength = testUtils->MachineName().Length();
	HBufC* serverad = HBufC::NewL(serverLength + 7 ); // 7 is the length of KServerAddress
	CleanupStack::PushL(serverad);
	serverad->Des().Copy(testUtils->MachineName());
	serverad->Des().Append(KServer);	
    HBufC* emailaddress = HBufC::NewL(serverLength + 8 + serverad->Des().Length() + 1 );
   	CleanupStack::PushL(emailaddress);
   	emailaddress->Des().Copy(testUtils->MachineName());
   	emailaddress->Des().Append(KAt);
   	emailaddress->Des().Append(*serverad);
   	header->ToRecipients().AppendL(*emailaddress);
	header->SetSubjectL(_L("Test sending message using CMsvEntry::CopyL!!"));
	header->StoreL(*store);
	store->CommitL();
	CleanupStack::PopAndDestroy(emailaddress);
	CleanupStack::PopAndDestroy(serverad);
	CleanupStack::PopAndDestroy(5,testActive); // header,store,testMsvOperationTimer,emailOperation,testActive
	
		
	}