TPtr8 CSmtpAuthCramMd5MechanismHelper::FormSharedSecret(TPtr8 aPassword)
	{
	TPtr8 secret = aPassword;
	
	if (aPassword.Length() <= KMd5BlockLength)
		{
		//pad up to 64 bytes with zeros
		secret.SetLength(64);
		TInt origLen = aPassword.Length();
		TInt lengthToFill = KMd5BlockLength-aPassword.Length();
		for (TInt i = 0; i<lengthToFill; i++)
			{
			secret[origLen+i]=0x00;
			}
		}
	else
		{
		//make shared secret the Digest of the password
		secret.Zero();
		iMd5Hash->Reset();
		secret = (iMd5Hash->Hash(aPassword));
		//do we need to call this function again now to pad out the 16 byte result?
		}

	return secret;
	}
예제 #2
0
/**
 * Function that will look at all the devices on the RConnection
 * and update the device array accordingly.
 */		
TInt CPanConnections::UpdateCurrentConnections()
	{
	TInt rerr = KErrNone;
	HBufC8* buffer=0;
	const TInt KAddrLen = sizeof(TBTDevAddr);

	TRAP(rerr, buffer = HBufC8::NewL(7*KAddrLen));// create a buffer to house the device address
	if(rerr == KErrNone)
		{
		TPtr8 ptr = buffer->Des();
		// use RConnection to enumerate all the devices
		rerr = iConnection.Control(KCOLAgent, KCOAgentPanEnumerateDevices, ptr);
		if(rerr == KErrNone)
			{
			iActiveConnections.Reset();
			while(ptr.Length()>=KBTDevAddrSize)
				{
				// inspect the addr's in the descriptor and append them to the array.
				TBTDevAddr parsedAddr(ptr.Mid(ptr.Length()-KAddrLen, KBTDevAddrSize));
				ptr.SetLength(Max(ptr.Length()-KAddrLen, 0));
				iActiveConnections.Append(parsedAddr);
				}
			}
		}
	delete buffer;
	return rerr;
	}
/**
Intended Usage	: Stream out the internal state to aStream.	

Error Condition	: Leave with the error code.
@leave  		KErrNoMemory.
@leave  		@see RWriteStream.
@since			7.0
@param			aClientSide a boolean indicating whether the streaming is to performed in client/server side
@param			aStream The stream to store the data in.
@pre 			CImplementationInformation is fully constructed and initialized
*/
void CImplementationInformation::ExternalizeL(TBool aClientSide,RWriteStream& aStream) const
	{
	aStream.WriteInt32L(iImplementationUid.iUid);
	aStream.WriteInt32L(iVersion);
	if(iDisplayName)
		{
		TPtr outputBuf = iDisplayName->Des();
		aStream.WriteInt32L(outputBuf.Length());
		aStream.WriteL(outputBuf);
		}
	else
		{
		aStream.WriteInt32L(0);
		}

	if(iData)
		{
		TPtr8 outputBuf = iData->Des();
		aStream.WriteInt32L(outputBuf.Length());
		aStream.WriteL(outputBuf);
		}
	else
		{
		aStream.WriteInt32L(0);
		}

	if(iOpaqueData)
		{
		TPtr8 outputBuf = iOpaqueData->Des();
		aStream.WriteInt32L(outputBuf.Length());
		aStream.WriteL(outputBuf);
		}
	else
		{
		aStream.WriteInt32L(0);
		}
	if (aClientSide)
		{
		aStream.WriteInt32L(iDrive);		
		aStream.WriteInt32L(iVid.iId);		
		}
	TInt additionalImplInfo=iRomOnly;
	additionalImplInfo|=iRomBased<<1;
	additionalImplInfo|=iDisabled<<2;
	aStream.WriteInt8L(additionalImplInfo);
	
	if (iExtendedInterfaceList != NULL)
		{
		TInt count = iExtendedInterfaceList->Count();
		aStream.WriteInt32L(count);
		for(TInt i = 0; i < count; ++i)
			{
	   		aStream.WriteInt32L((*iExtendedInterfaceList)[i].iUid);
			}
		}
	else
		{
		aStream.WriteInt32L(KNoneExtendedInterface);
		}
	}
예제 #4
0
void CBrdSession::PrintfStr(TPtr8 &bufPtr, TPtr8 &bufPtr2)
    {
    CBrdServer *server = (CBrdServer*)Server();
    
    TInt lth = bufPtr.Length();
    HBufC* uniBuf=HBufC::NewL(lth*2);

    CleanupStack::PushL(uniBuf);
    
    TPtr uniBufPtr = uniBuf->Des();
    uniBufPtr.Copy(bufPtr);
    
    lth = bufPtr2.Length();
    HBufC* uniBuf2=HBufC::NewL((lth*2)+2);
    
    CleanupStack::PushL(uniBuf2);
    
    TPtr uniBufPtr2 = uniBuf2->Des();
    uniBufPtr2.Copy(bufPtr2);
    
    server->iControl->WriteText(uniBufPtr, uniBufPtr2.PtrZ());
    server->iControl->ShowText(_L("\n"));
    
    CleanupStack::Pop();
    CleanupStack::Pop();
    
    delete uniBuf;
    uniBuf = NULL;        
    delete uniBuf2;
    uniBuf2 = NULL;
    
    }
// The caller must free the returned buffer. The buffer is guaranteed
// to have a zero terminator.
HBufC8* ConvToUtf8ZL(const TDesC& name16)
{
  // Note that there is no non-leaving variant of this function, such
  // that the result has no maximum size.
  // 
  // Do not know what happens if any 0 values appear in "name16"; this
  // is not documented.
  HBufC8* name8 = CnvUtfConverter::ConvertFromUnicodeToUtf8L(name16);

  // Ensure there is a zero terminator. Quite a lot of work to do this
  // efficiently.
  TPtr8 ptr = name8->Des();
  if (ptr.Length() < ptr.MaxLength()) {
    ptr.PtrZ(); // modifies HBufC8 content
  } else {
    HBufC8* bigger8 = name8->ReAlloc(ptr.Length() + 1);
    if (bigger8) {
      name8 = bigger8; // name8 already deleted by ReAlloc
      name8->Des().PtrZ(); // modifies HBufC8 content
    } else {
      delete name8;
      User::Leave(KErrNoMemory);
    }
  }

  return name8;
}
예제 #6
0
EXPORT_C TInt CDosExtensionBase::ExecuteMessageL(const RMessage2& aMessage)
{
    
    API_TRACE_( "[DOSSERVER] CDosExtensionBase::ExecuteMessageL(...)" );
	__ASSERT_DEBUG(aMessage.Function() == ECallFunction, 
		PanicClient(aMessage,EPanicIllegalFunction));

	TInt retVal(KErrNone);
	TBool parameterModifiedByDSY(EFalse);

	// Get data from RMessage
	TExtensionParPckg extPars;
	aMessage.ReadL(0, extPars);
	
	TInt dataLength(extPars().iParLength);
	if (dataLength >= 0)
	{
		HBufC8* dataBuffer = HBufC8::NewMaxLC( dataLength );
		TPtr8 dataPtr = dataBuffer->Des();
		aMessage.ReadL( 1, dataPtr );

		// Check autocomplete flag
		TUint autoCompl(aMessage.Int2());
		if (autoCompl == KAutoComplete)
		{
            COM_TRACE_4( "[DOSSERVER] MDosExtensionBaseDSY::CallFunctionL(0x%x,0x%x,0x%x,0x%x)"
                ,extPars().iFunc
                ,dataPtr.Ptr()
                ,dataPtr.Length()
                ,autoCompl );

			retVal = CallFunctionL(extPars().iFunc, const_cast<TUint8*>(dataPtr.Ptr()), dataPtr.Length(), parameterModifiedByDSY);

			if((retVal == KErrNone) && parameterModifiedByDSY)
			{
				// Write over client's parameters
				retVal = aMessage.Write(1, dataPtr);
			}
		}
		else
		{
			COM_TRACE_3( "[DOSSERVER] MDosExtensionBaseDSY::CallFunctionAndCompleteL(0x%x,0x%x,0x%x)"
                ,extPars().iFunc
                ,dataPtr.Ptr()
                ,dataPtr.Length() );
        
            CallFunctionAndCompleteL(extPars().iFunc, const_cast<TUint8*>(dataPtr.Ptr()), dataPtr.Length(), aMessage);
		}

		CleanupStack::PopAndDestroy(); // dataBuffer
	}
	else
	{
		// Client passed negative parameter length
		retVal = KErrGeneral;
	}

	return retVal;
}
예제 #7
0
TInt CTlsEncrypt::DecryptAndVerifyL(const TDesC8& aInput,HBufC8*& aOutput,
                                    TInt64& aSeqNumber, TRecordProtocol& aType)
{

    if(!aInput.Length())
        return KErrBadDescriptor;

    TLSPROV_LOG2(_L("Before Decryption...RecordType: %d"),(TInt)aType)

    TLSPROV_LOG_HEX(aInput.Ptr(),aInput.Size() )


    TInt nAlloc = iCryptos.iDecryptor->MaxFinalOutputLength(aInput.Size()) + 24;
    if ( !aOutput || aOutput->Des().MaxLength() < nAlloc )
    {
        delete aOutput;
        aOutput = NULL;
        aOutput = HBufC8::NewL( nAlloc );
    }
    TPtr8 DecOutput = aOutput->Des();
    DecOutput.Zero();

    TRAP_IGNORE(iCryptos.iDecryptor->ProcessFinalL(aInput,DecOutput));

    TUint HashSize = KSetOfTLSCipherSuites[iCipherIndex].iHashSize;

    if(DecOutput.Length() < HashSize)
    {
        return KErrSSLAlertDecryptError;
    }

    //set ptr to MAC
    TPtrC8 ReceivedMac = DecOutput.Mid(DecOutput.Length()-HashSize,HashSize);
    //& set length to trim MAC
    DecOutput.SetLength( DecOutput.Length()-HashSize );

    TBuf8<64> CalculatedMac;

    ComputeMacL(CalculatedMac,DecOutput,ETrue,aSeqNumber,aType);

    TInt err = KErrBadMAC;
    if(ReceivedMac.Compare(CalculatedMac) == 0)
    {
        err = KErrNone;
    }
    else
    {
        TLSPROV_LOG(_L("Decryption: Received MAC error"))
        err =  KErrSSLAlertBadRecordMac;
    }

    TLSPROV_LOG(_L("After Decryption , no mac"))
    TLSPROV_LOG_HEX(aOutput->Ptr(),aOutput->Size() )

    return err;

}
예제 #8
0
// ----------------------------------------------------------------------------
// TTCPCompMsgEnd::DataReceivedL
// ----------------------------------------------------------------------------
//
void TTCPCompMsgEnd::DataReceivedL( TPtr8 aData, TUint&  aNextLength )
	{
	// panic if sigcomp is not supported in debug mode.leaves in release mode.
	__SIP_ASSERT_LEAVE(	iMsgAssembler.SigComp().IsSupported(), KErrGeneral );
	// panic if received data is not compressed in debug mode.
	// leaves in release mode.
	__SIP_ASSERT_LEAVE(	iMsgAssembler.SigComp().IsSigCompMsg( aData ), 
	                    KErrGeneral );
	// panic if received data is not completed compressed msg in debug mode.
	// leaves in release mode.
	__SIP_ASSERT_LEAVE(	
			iMsgAssembler.SigComp().IsCompleteSigCompMessageL( aData ), 
	        KErrGeneral );
	        
	TUint bytesConsumed( 0 );
	CBufBase* decompressedData = iMsgAssembler.SigComp().DecompressL( 
											aData, bytesConsumed, ETrue);

    TUint dataLen( static_cast<TUint>( aData.Length() ) );
    
    // Whole data was not decompressed and non-decompressed data might
	// be part of next sigcomp message, remember amount of non-decompressed
	// data
	iMsgAssembler.SetUnConsumedBytes( dataLen - bytesConsumed );
		
	if ( bytesConsumed < dataLen )
		{	
    	CleanupStack::PushL(decompressedData);
		aData.Delete(0, bytesConsumed);

		HBufC8* newData = 
		   HBufC8::NewL( decompressedData->Size() + aData.Length() );
	    // copy the msg buffer data and the received data to new data buffer
	    TPtr8 newDataPtr = newData->Des();
	    newDataPtr.Append(decompressedData->Ptr(0));
 	    CleanupStack::PopAndDestroy(decompressedData);
	    newDataPtr.Append(aData);
	    // delete all content of received data
	    aData.Delete( 0, aData.Length() );
  	    CleanupStack::PushL(newData);
  	    DecideNextStateL( newDataPtr, aNextLength );
	    CleanupStack::PopAndDestroy(newData);	
		}	
	else if ( bytesConsumed == dataLen )
		{
		CleanupStack::PushL( decompressedData );
		aData.Delete(0, bytesConsumed);	
		TPtr8 decompressedDataPtr = decompressedData->Ptr(0);
	    DecideNextStateL( decompressedDataPtr, aNextLength );
	    CleanupStack::PopAndDestroy( decompressedData );
		}
	else // bytesConsumed > dataLen error happens, reset the state
		{
		delete decompressedData;
		iMsgAssembler.ChangeState( MMsgAssemblerContext::EMsgInit );
		}				
	}
TInt TMD5Checker::ReadAndHashFileL(class RFs& aFs, const TDesC& aFile)
{
   TInt ret = KErrNone;

   class RFile file;
   // CAP: dependent
   User::LeaveIfError(file.Open(aFs, aFile, EFileRead));
   CleanupClosePushL(file);

   HBufC8* readBuf = HBufC8::NewLC(6*1024);
   TPtr8 buf = readBuf->Des();

   Reset();

   User::LeaveIfError(file.Read(buf));
   while(buf.Length() > 0){
      Append(buf);
      User::LeaveIfError(file.Read(buf));
   }

   Finish();
      
   CleanupStack::PopAndDestroy(readBuf);
   CleanupStack::PopAndDestroy(/*file*/);
   return ret;
}
EXPORT_C int Tptr8ToWcharp(const TPtr8& aSrc, wchar_t* aDes, int& n_size)
{
   
    int retval = ESuccess;
    unsigned int ilen = aSrc.Length();
    int minusone = -1;
    
    if (0 == ilen)
    {
    	return EDescriptorNoData;
    }
    else if(!aDes)
    {
    	return EInvalidPointer;
    } 
	else if(n_size < ilen+1)
    {
        n_size = ilen+1 ;
    	return EInvalidSize;
    }
	
	if(minusone != mbstowcs(aDes, (const char*)aSrc.Ptr(), ilen))
	{
	    aDes[ilen] = L'\0';
	}
	else 
	{
		retval = EInvalidMBSSequence;
	}
	
	return retval;
}
void CBulkOnlyTransport::SendCbwL(const MClientCommandServiceReq* aReq,
                                  TBotCbw::TCbwDirection aDirection,
                                  TUint32 aTransferLength)
{
    __MSFNLOG
    __BOTPRINT1(_L("Cbw Tag=0x%x"), iCbwTag);

    iCbw.SetTag(iCbwTag++);
    iCbw.SetDataTransferLength(aTransferLength);
    iCbw.SetDataTransferDirection(aDirection);
    iCbw.SetLun(iLun);

    TPtr8 buf = iBulkOutCbwTd.WritableBuffer();
    iCbw.EncodeL(buf, aReq);

    iBulkOutCbwTd.SaveData(buf.Length());
    iBulkPipeOut.Transfer(iBulkOutCbwTd, iStatus);
    User::WaitForRequest(iStatus);

    TInt r = iStatus.Int();
    if (r != KErrNone)
    {
        if (r == KErrUsbStalled)
        {
            __BOTPRINT(_L("Cbw: BulkOut stalled"));
            DoResetRecovery();
        }
        __BOTPRINT1(_L("Usb transfer error %d"),r);
        User::Leave(KErrGeneral);
    }
}
int main()
{
    __UHEAP_MARK;
    int retval =ESuccess;
    wchar_t* mywcharstring = L"Hello Widechar String";
    int wchar_length= wcslen(mywcharstring);
    TBufC8<30> buf;
    TPtr8 myTptr = buf.Des();
    char* temp=new char[30];
    retval = WcharpToTptr8(mywcharstring,temp, myTptr);

    int buf_len = myTptr.Length();
    if (retval ==ESuccess &&\
    wchar_length == buf_len  )
    {
    printf("wcharptotptr8 boundary1 Passed\n");
    }
    else
    {
    assert_failed = true;	
    printf("wcharptotptr8 boundary1 Failed\n");
    }      
    delete[] temp;
    __UHEAP_MARKEND;
    testResultXml("test_wcharptotptr8_boundary1");
	
	return 0;
}
예제 #13
0
void CDomainNameCodec::DecodeL(TPtr8& aInDes)
	{
	TDomainName domainName;

	TUint8* pChar = const_cast<TUint8*>(aInDes.Ptr());
	TUint listLength = aInDes.Length();
	TUint8 labelLength = 0;
	
	// Walk the list of domain names
	while(pChar < aInDes.Ptr() + listLength)
		{
		domainName.Zero();
		
		while(*pChar++ != NULL)
			{
			if(domainName.Length() > 0)
				{
				domainName.Append('.');
				}
				
			labelLength = *(pChar - 1);
			
			// The two highest order bits must be clear
			User::LeaveIfError(labelLength & 0xC0 ? KErrArgument : KErrNone);
					
			// Add in the label data
			domainName.Append(pChar, labelLength);
			
			// Advance the pointer to the next length value
			pChar += labelLength;
			}
			
		iDomainList.Append(domainName);
		}
	}
예제 #14
0
// -----------------------------------------------------------------------------
// CMccCodecRed::SetRedCodecs
// Set the payload types used in redundancy
// -----------------------------------------------------------------------------
//
void CMccCodecRed::SetRedPayloadsL( RArray<TUint>& aRedPayloads )
    {
    iRedPayloads.Reset();
    TInt i;
    for( i = 0; i < aRedPayloads.Count(); i++ )
        {
        iRedPayloads.AppendL( aRedPayloads[ i ] );  
        }
    
    // Convert parsed payload formats back to string and set
    // the iFmtpAttr variable
    const TInt KCharsPerPayload( 4 );
    delete iFmtpAttr;
    iFmtpAttr = NULL;
    iFmtpAttr = HBufC8::NewL( iRedPayloads.Count() * KCharsPerPayload );
    
    TPtr8 descPtr = iFmtpAttr->Des();
    for( i = 0; i < iRedPayloads.Count(); i++ )
        {
        descPtr.AppendNum( static_cast<TUint64>( iRedPayloads[i] ), EDecimal );
        descPtr.Append( KCharSlash );       
        }   
    
    // Remove the last slash character
    descPtr.SetLength( descPtr.Length() - 1 );  
    }
int main()
{
    __UHEAP_MARK;
    int retval =ESuccess;
    wchar_t* mywcharstring = L"Hello Widechar String";
    int wchar_length= wcslen(mywcharstring);
    TBufC8<30> buf;
    TPtr8 myTptr = buf.Des();
    char* temp=new char[30];
    retval = WcharpToTptr8(mywcharstring,temp, myTptr);

    int buf_len = myTptr.Length();
    if (retval ==ESuccess &&\
    wchar_length == buf_len &&\
    strncmp("Hello Widechar String",(char*)myTptr.Ptr() , 21) ==0 )
    {
    printf("wcharptotptr8 content check Passed\n");
    }
    else
    {
    assert_failed = true;
    printf("wcharptotptr8 content check Failed\n");
    }      
    delete []temp;
    __UHEAP_MARKEND;
    testResultXml("test_wcharptotptr8_content_check");
	
	return 0;
}
예제 #16
0
void CLocationEngine::InsertIntoPayload(TInt aPosition, const TDesC8& aString, TPtr8& aLogStanza) {
	if(aLogStanza.Length() + aString.Length() > aLogStanza.MaxLength()) {
		iLogStanza = iLogStanza->ReAlloc(aLogStanza.MaxLength() + aString.Length() + 32);
		aLogStanza.Set(iLogStanza->Des());
	}

	aLogStanza.Insert(aPosition, aString);
}
예제 #17
0
TInt CIniFileParser::GetNextTokenAndCheck(TLex8& lex, TPtr8& tempPtr)
/*
Gets next token and ensures the token is simply not the EOF or a linefeed.
lex is the lexical string to get the next token from.
tempPtr points to the next token
Returns KErrGeneral if token is bad or if we've already read past the end.
*/
	{
	TUint8 ch;
	TInt len;

	if (lex.Eos())
		{
		return KErrGeneral;
		}
	
	tempPtr = lex.NextToken();

	len = tempPtr.Length();
	if (len == 0)
		{
		// lex has figured out what is left is just the EOF
		return KErrGeneral;
		}

	// this next part may be superfluous but we've had so much strife with
	// the parser thus far that for now we're leaving it in

	ch = tempPtr[0];
	if (ch == KCarriageReturn || ch == KLineFeed)
		{
		return KErrGeneral;
		}

	if (tempPtr.Length() < 2)
		{
		return KErrNone;
		}
	ch = tempPtr[1];
	if (ch == KCarriageReturn || ch == KLineFeed)
		{
		return KErrGeneral;
		}

	return KErrNone;
	}
예제 #18
0
// ----------------------------------------------------------------------------
// TTCPCompMsgStart::DataReceivedL
// ----------------------------------------------------------------------------
//
void TTCPCompMsgStart::DataReceivedL( TPtr8 aData, TUint&  aNextLength )
	{
	// panic if sigcomp is not supported in debug mode.leaves in release mode.
	__SIP_ASSERT_LEAVE(	iMsgAssembler.SigComp().IsSupported(), KErrGeneral );
	     
	if ( iMsgAssembler.MsgBuffer().Size() > 0 )
		{
		// insert the received data to msg buffer.
		iMsgAssembler.MsgBuffer().InsertL(
									iMsgAssembler.MsgBuffer().Size(), aData );
		iMsgAssembler.MsgBuffer().Compress();
		// clean the content of received data.
		aData.Delete( 0, aData.Length() );
		TPtr8 bufPtr = iMsgAssembler.MsgBuffer().Ptr( 0 );
		
		// check if the msg buffer a complete sig comp message, if so
		// copy the msg buffer to a new data buf, clean the msg buffer
		// and enter to comp msg end state.
		if ( iMsgAssembler.SigComp().IsCompleteSigCompMessageL( bufPtr ) )
			{
			HBufC8* newData = HBufC8::NewLC( bufPtr.Length() );
			// copy the msg buffer data and the received data to new buffer
			TPtr8 newDataPtr = newData->Des();
			newDataPtr.Append(bufPtr);
			// clean the msg buffer
			iMsgAssembler.MsgBuffer().Reset();
			iMsgAssembler.MsgBuffer().Compress();
			
			iMsgAssembler.ChangeState( MMsgAssemblerContext::ECompMsgEnd );
			iMsgAssembler.CurrentState().DataReceivedL( newDataPtr, 
			                                            aNextLength );
	    	CleanupStack::PopAndDestroy(newData);
			}
		}
	else if (iMsgAssembler.SigComp().IsCompleteSigCompMessageL( aData ) )
		{
		iMsgAssembler.ChangeState( MMsgAssemblerContext::ECompMsgEnd );
		iMsgAssembler.CurrentState().DataReceivedL( aData, aNextLength );
		}
	else
		{
		iMsgAssembler.MsgBuffer().InsertL(
									iMsgAssembler.MsgBuffer().Size(), aData );
		iMsgAssembler.MsgBuffer().Compress();
		}
	}
TInt CBulkOnlyTransport::SendDataTxCmdL(const MClientCommandServiceReq* aCommand,
                                        TDesC8& aData,
                                        TUint aPos,
                                        TInt& aLen)
{
    __MSFNLOG
    TInt r = KErrNone;

    SendCbwL(aCommand, TBotCbw::EDataOut, aLen);

    TInt len = aLen;
    TInt length = 0;
    iBulkDataTd.SetZlpStatus(RUsbTransferDescriptor::ESuppressZlp);
    while (len)
    {
        TPtr8 senddata = iBulkDataTd.WritableBuffer();
        senddata.Append(aData.Ptr() + length + aPos, len > KResponsePacketSize? KResponsePacketSize : len);

        iBulkDataTd.SaveData(senddata.Length());
        iBulkPipeOut.Transfer(iBulkDataTd, iStatus);
        User::WaitForRequest(iStatus);

        if (iStatus.Int() != KErrNone)
        {
            if (iStatus.Int() == KErrUsbStalled)
            {
                __BOTPRINT(_L("SendDataTxCmdL ClearRemoteStall"));
                iBulkPipeOut.ClearRemoteStall();
#ifdef MASSSTORAGE_PUBLISHER
                TMsPublisher publisher(TMsPublisher::KStallProperty);
#endif
                break;
            }
            DoResetRecovery();
            __BOTPRINT1(_L("Usb transfer error %d"), r);
            User::Leave(KErrGeneral);
        }

        if(len > KResponsePacketSize)
        {
            len -= KResponsePacketSize;
            length += KResponsePacketSize;
        }
        else
        {
            length += len;
            len = 0;
        }
    }

    ReceiveCswL();

    TUint32 lenSent = 0;
    r = ProcessOutTransferL(lenSent);
    aLen = lenSent;

    return r;
}
예제 #20
0
TInt RBTBaseband::Enumerate(RBTDevAddrArray& aBTDevAddrArray, TUint aMaxNumber)
	{
	if (!SubSessionHandle())
		{
		return KErrNotReady;
		}

	__ASSERT_DEBUG(aMaxNumber>=1, Panic(EBadArgument));
	if(!aMaxNumber)
		{
		return KErrArgument;
		}
	HBufC8* buffer=0;
	const TInt KAddrLen = sizeof(TBTDevAddr);

	TRAPD(err, buffer = HBufC8::NewL(aMaxNumber*KAddrLen));
	if(err)
		{
		return KErrNoMemory;
		}

	TPtr8 ptr = buffer->Des();
	err = iSocket.GetOpt(EBBEnumeratePhysicalLinks, KSolBtLMProxy, ptr);
	if (err)
		{
		delete buffer;
		return err;
		}

	/**
	Parse the supplied descriptor
	*/
	
	aBTDevAddrArray.Reset();
	while(ptr.Length()>=KBTDevAddrSize)
		{
		TBTDevAddr parsedAddr(ptr.Mid(ptr.Length()-KAddrLen, KBTDevAddrSize));
		ptr.SetLength(Max(ptr.Length()-KAddrLen, 0));
		aBTDevAddrArray.Append(parsedAddr);
		}

	delete buffer;
	return KErrNone;
	}
예제 #21
0
/**
@SYMTestCaseID			PDS-SQL-UT-4207
@SYMTestCaseDesc		RFileBuf64::Write() OOM test.
						The test calls RFileBuf64:Write() in an OOM
						simulation loop and verifies that no memory is leaked.
						The test also check that RFileBuf::DoSetCapacity() correctly operates in
						"out of memory" situation.
@SYMTestActions			RFileBuf64::Write() OOM test.
@SYMTestExpectedResults Test must not fail
@SYMTestPriority		High
@SYMDEF					380056
*/
void WriteOomTest()
	{
	HBufC8* databuf = HBufC8::New(KPageSize);
	TEST(databuf != NULL);
	TPtr8 dataptr = databuf->Des();
	dataptr.SetLength(KPageSize);
	dataptr.Fill(TChar(KChar));
	
	TInt err = KErrNoMemory;
	TInt failingAllocationNo = 0;
	TheTest.Printf(_L("Iteration:\r\n"));
	while(err == KErrNoMemory)
		{
		TheTest.Printf(_L(" %d"), ++failingAllocationNo);

		(void)TheFs.Delete(KTestFile);
		
		MarkHandles();
		MarkAllocatedCells();
		
		__UHEAP_MARK;
		__UHEAP_SETBURSTFAIL(RAllocator::EBurstFailNext, failingAllocationNo, KBurstRate);

		const TInt KDefaultBufCapacity = 1024;
		RFileBuf64 fbuf(KDefaultBufCapacity);
		err = fbuf.Create(TheFs, KTestFile, EFileWrite | EFileRead);
		if(err == KErrNone)
			{
			err = fbuf.Write(0LL, dataptr);
			}
		fbuf.Close();
		
		__UHEAP_RESET;
		__UHEAP_MARKEND;

		CheckAllocatedCells();
		CheckHandles();
		}
	TEST2(err, KErrNone);
	RFile64 file;
	err = file.Open(TheFs, KTestFile, EFileRead);
	TEST2(err, KErrNone);
	dataptr.Zero();
	err = file.Read(dataptr);
	TEST2(err, KErrNone);
	file.Close();
	TEST2(dataptr.Length(), KPageSize);
	for(TInt i=0;i<KPageSize;++i)
		{
		TEST(dataptr[i] == KChar);
		}
	TheTest.Printf(_L("\r\n=== OOM Test succeeded at heap failure rate of %d ===\r\n"), failingAllocationNo);
	
	//The file is left undeleted - to be used in ReadOomTest().
	delete databuf;
	}
예제 #22
0
/**
Implementation of pure virtual function.
@see    MWTCacheInterface::ReadL()
*/
void CDynamicDirCache::ReadL(TInt64 aPos, TInt aLength, TDes8& aDes)
    {
#ifdef _DEBUG
    if(iCacheDisabled)
        {
        // cache is disabled for debug purposes
        __PRINT(_L("CDynamicDirCache disabled"));
        User::LeaveIfError(iDrive.ReadNonCritical(aPos, aLength, aDes));
        return;
        }
#endif //_DEBUG

    aDes.Zero();
    const TUint32 PageSz = iPageSizeInBytes;//-- cache page size

    TInt64 pageStartMedPos = CalcPageStartPos(aPos);
    const TUint32 bytesToPageEnd = (TUint32)(pageStartMedPos + PageSz - aPos); //-- number of bytes from aPos to the end of the page

//    __PRINT5(_L("CDynamicDirCache::ReadL: aPos=%lx, aLength=%x, page:%lx, pageSz:%x, bytesToPageEnd=%x"), aPos, aLength, pageStartMedPos, PageSz, bytesToPageEnd);
    // if all data needed is on a single page
    if((TUint32)aLength <= bytesToPageEnd)
        {
        ReadDataFromSinglePageL(aPos, aLength, aDes);
        }
    // or data to be read cross cache page boundary or probably we have more than 1 page to read
    else
        {
        __PRINT(_L("CDynamicDirCache::ReadL() CROSS PAGE!"));
        TUint32 dataLen(aLength);   //-- current data length
        TInt64  currMediaPos(aPos); //-- current media position

        //-- 1. read data that are already in the current page
        ReadDataFromSinglePageL(currMediaPos, bytesToPageEnd, aDes);
        dataLen -= bytesToPageEnd;
        currMediaPos += bytesToPageEnd;

        TPtr8 dataNext = aDes.MidTPtr(aDes.Length());

        //-- 2. read whole pages of data
        while (dataLen >= PageSz)
            {
            //-- find out if currMediaPos is in cache. If not, find a spare page and read data there
            ReadDataFromSinglePageL(currMediaPos, PageSz, dataNext);
            currMediaPos += PageSz;
            dataLen -= PageSz;
            dataNext = dataNext.MidTPtr(dataNext.Length());
            }

        //-- 3. read the rest of the data
        if(dataLen > 0)
            {
            ReadDataFromSinglePageL(currMediaPos, dataLen, dataNext);
            }
        } //else((TUint32)aLength <= bytesToPageEnd)
    }
예제 #23
0
/**
	Updates the strings specified in step c of section 5.2.4 of RFC 3986
	
	@param aInputBuf A reference to the inputBuf needs to be modified 
	@param aOutPutBuf A reference to the outPutBuf needs to be modified
	@param aLength length of the string to be replaced.
 */
void  updateStrings(TPtr8& aInputBuf, TPtr8& aOutPutBuf, TInt aLength)
	{
	aInputBuf.Replace(0,aLength,KSlash);

	//In outPutBuf to remove the last segment starting with / (if exist)
	//eg: /abc/def/fgh --> /abc/def
	TInt outputBufLength = aOutPutBuf.Length();
	TInt pos = aOutPutBuf.LocateReverse('/');	
	//remove the last segment including '/'
	pos != KErrNotFound ? aOutPutBuf.Delete( pos, outputBufLength - pos ) : aOutPutBuf.Delete( 0,outputBufLength );
	}
예제 #24
0
// -----------------------------------------------------------------------------
// AppendBufL
// -----------------------------------------------------------------------------
//
void AppendBufL( TPtr8& aDest, HBufC8* aSrc )
    {
    TInt length = aSrc ? aSrc->Length() : KNullBuffer;

    APPEND_BUF_INT( aDest, length );

    if( length > 0 )
        {
        __ASSERT_DEBUG( (aDest.MaxLength() - aDest.Length()) > length, User::Panic( KNullDesC, KErrTooBig ) );
        aDest.Append( *aSrc );
        }
    }
void CTestUTCParse::ReadDataL(CImRecvConvert* aRecvConvert, TFileName aFileName)
	{
	// open the file
	RFile file;

	TInt error = file.Open(iTestUtils->FileSession(), aFileName, EFileShareAny);
	if(error != KErrNone)
		{
		ERR_PRINTF2(TRefByValue<const TDesC>_L("\r\nFile open error %d"), error);
		User::Leave(KErrNotFound);
		}

	INFO_PRINTF2(TRefByValue<const TDesC>_L("Data from %s...\r\n"), aFileName.PtrZ());		

	// read the file into the conversion object
	HBufC8* lineBuffer = HBufC8::NewLC(1024);
	TPtr8 line = lineBuffer->Des();

	TBuf8<1> theChar;
	TBool finished = EFalse;

	aRecvConvert->ResetL();
	// supply a new attachment path since previous one is discarded by call to Reset()

	do {
		line.FillZ();
		line.SetLength(0);
		// compile a line one char at a time
		do {
			file.Read(theChar, 1);
			if(theChar.Length())
				line.Append(theChar);
			else
				finished = ETrue;
			// stop at the end of line or no more data
			} while(theChar.Length() && theChar[0] != 0x0A);
			if(!line.Length())
				break;
			
			aRecvConvert->ParseNextField(line); // This function doesnt actually leave, any leaves are relayed to the MessageCompleteL() function

		} while(!finished);

	TRAPD(err, aRecvConvert->MessageCompleteL());
	if(err!=KErrNone)
		{
		// At this point the message should be deleted and CImRecvConvert should be Reset()
		ERR_PRINTF3(TRefByValue<const TDesC>_L("\r\nError %d occured during the conversion of Message %d"), err, aRecvConvert->EntryId());
		}
	CleanupStack::PopAndDestroy(lineBuffer); 

	file.Close();
	}
예제 #26
0
//------------------------------------------------------------
// CNsmlObexClient::ReceiveDataL( TDes8& aStartPtr, TRequestStatus &aStatus )
//------------------------------------------------------------
void CNsmlObexClient::ReceiveDataL( TPtr8& aStartPtr, TRequestStatus &aStatus )
    {
	iAgentStatus = &aStatus;
	// agent
	*iAgentStatus = KRequestPending;
	
	iDataPtr.Set( aStartPtr );

    if ( iState != EWaitingToReceive )
        {
        User::Leave( KErrDisconnected );
        }
    else if ( IsActive() ) 
        {
        User::Leave( KErrInUse );
        }
	iDataBuf->Reset();
	iCurrObject->Reset();

	TBuf8<KNameLen> str;
	str.Copy( this->iMimeType->Des() );
	iCurrObject->SetTypeL( str );

	iClient->Get( *iCurrObject, iStatus );
	
	DBG_DUMP((void*)aStartPtr.Ptr(), aStartPtr.Length(), 
	_S8("ReceiveDataL (WBXML)"));
#ifdef __NSML_DEBUG__
	_DBG_FILE("CNsmlObexClient::ReceiveDataL: CWbxml2XmlConverter::ConvertL()\
	 begin");
	CWbxml2XmlConverter* c = CWbxml2XmlConverter::NewLC();
	c->ConvertL(aStartPtr.Ptr(), aStartPtr.Length());
	DBG_DUMP((void*)c->Document().Ptr(), c->Document().Length(), 
	_S8("ReceiveDataL (XML)") );
	CleanupStack::PopAndDestroy(); // c
	_DBG_FILE("CNsmlObexClient::ReceiveDataL: CWbxml2XmlConverter::ConvertL() end");
#endif // __NSML_DEBUG__

	SetActive ();
    }
예제 #27
0
// -----------------------------------------------------------------------------
// AppendBufL
// -----------------------------------------------------------------------------
//
void AppendBufL( TPtr8& aDest, HBufC* aSrc )
    {
    TInt length = aSrc ? aSrc->Length() * 2 : KNullBuffer;

    APPEND_BUF_INT( aDest, length );

    if( length > 0 )
        {
        TPtr8 tmp8( (TUint8*)aSrc->Ptr(), length, length);
        __ASSERT_DEBUG( (aDest.MaxLength() - aDest.Length()) > tmp8.Length() , User::Panic( KNullDesC, KErrTooBig ) );
        aDest.Append( tmp8 );
        }
    }
// --------------------------------------------------------------------------------------
// Decodes input data from base64 to binary octets and creates
// heap buffer with the decoded data. The buffer is pushed on the cleanup stack.
// --------------------------------------------------------------------------------------
//
HBufC8* CXmlEngSerializerXOP::CreateDecodedBufLC(TPtrC8 aEncodedData)
	{
	// The decoded length of base64 is about half (use same) encoded length
	HBufC8* decodedData = HBufC8::NewLC(aEncodedData.Size());
	TPtr8 decodedDataPtr = decodedData->Des();
	// Decode the base64 Content-Transfer-Encoding
	using namespace BSUL;
	Base64Codec::Decode(aEncodedData, decodedDataPtr);
	if(decodedDataPtr.Length() == 0)
		{
		User::Leave(KXmlEngErrDecodingFailed);
		}
	return decodedData;	
	}
예제 #29
0
EXPORT_C TInt RRtaContent::GetStringAttributeSetL(const TDesC& aUniqueId, RStringAttributeSet &aStringAttributeSet) const
	{
	TInt err = KErrOverflow;
	TInt length = 0;
	TPckg <TInt> lengthPckg(length);
	
	// Write the object out to a buffer, send to client
	CBufFlat* buf = CBufFlat::NewL(50);
	CleanupStack::PushL(buf);
	
	// create write stream
	RBufWriteStream writeStream(*buf);
	CleanupClosePushL(writeStream);

	// write the directory to the stream
	aStringAttributeSet.ExternalizeL(writeStream);
	CleanupStack::PopAndDestroy(&writeStream);
	
	
	TPtr8 bufPtr = buf->Ptr(0);
	// allocate arbitary receive buffer much larger than the size of the source buffer
	length = bufPtr.Length() * 15;
	
	while(err == KErrOverflow)
		{
		HBufC8* transferBuffer = HBufC8::NewLC(length);
		transferBuffer->Des().Copy(bufPtr);
		TPtr8 transferPtr = transferBuffer->Des();
	
		// attempt to retrieve the attributes
		err = SendReceive(EGetStringAttributeSet, TIpcArgs(&aUniqueId, &transferPtr));	
		if(err == KErrOverflow)
			{
			// Find out the length required to receive the resulting attribute set
			lengthPckg.Copy(transferPtr.Left(lengthPckg.MaxLength()));	
			}
		else if(err == KErrNone)
			{
			// read in the attribute values from the buffer
			RDesReadStream readStream(transferPtr);
			CleanupClosePushL(readStream);
			aStringAttributeSet.InternalizeL(readStream);
			CleanupStack::PopAndDestroy(&readStream);
			}
		CleanupStack::PopAndDestroy(transferBuffer);	
		}

	CleanupStack::PopAndDestroy(buf);
	return err;
	}
예제 #30
0
void CActiveWriter::RunL()
	{
	TPtr8 currentbuffer = (iWriteBuffers[0])->Des();

	iConsole.Printf(_L("Write of %d bytes (including header) returned result %d.\n"), currentbuffer.Length(), iStatus.Int());
	
	// the write has completed - clear up the buffer
	delete iWriteBuffers[0];
	iWriteBuffers.Remove(0);

	if (iWriteBuffers.Count())
		// more to send
		DoWrite();
	}