// -----------------------------------------------------------------------------
// CNATFWUNSAFErrorCodeAttribute::EncodeValueL
// -----------------------------------------------------------------------------
//
HBufC8* CNATFWUNSAFErrorCodeAttribute::EncodeValueL() const
{
    __TEST_INVARIANT;

    TInt encodedReasonPhraseLength = EncodedReasonPhraseLength();
    HBufC8* encodedValue =
        HBufC8::NewLC(EReasonPhraseOffset + encodedReasonPhraseLength);
    TPtr8 ptr = encodedValue->Des();
    ptr.FillZ(EReasonPhraseOffset);


    ptr[EClassOffset] = (iResponseCode / E100) & EClassMask;
    ptr[ENumberOffset] = iResponseCode % E100;


    ptr.Append(*iReasonPhrase);

    TInt spacesToAppend = encodedReasonPhraseLength - iReasonPhrase->Length();
    const TChar KSpace(' ');
    for (TInt i = 0; i < spacesToAppend; ++i)
    {
        ptr.Append(KSpace);
    }

    CleanupStack::Pop(encodedValue);
    return encodedValue;
}
Пример #2
0
HBufC8* DecryptFromStreamL( RReadStream& aInStream, TPtrC8& aKey )
	{
	
	CPBEncryptionData* data = CPBEncryptionData::NewL(aInStream);
	CleanupStack::PushL(data);

	TInt32 encKeyLength = aInStream.ReadInt32L();
	HBufC8* encKey = HBufC8::NewMaxLC(encKeyLength);
	TPtr8 encKeyPtr(encKey->Des());
	encKeyPtr.FillZ();
	aInStream.ReadL(encKeyPtr,encKeyLength);
	
	CPBEncryptElement* encryption = CPBEncryptElement::NewLC(*data,aKey);

	CPBDecryptor* decryptor = encryption->NewDecryptLC();
	HBufC8* plaintext = HBufC8::NewLC(decryptor->MaxOutputLength(encKeyPtr.Length())); 
	TPtr8 plaintextPtr = plaintext->Des();	
	plaintextPtr.FillZ();
	decryptor->ProcessFinalL(encKeyPtr, plaintextPtr);

	CleanupStack::Pop(plaintext);
	CleanupStack::PopAndDestroy(4,data); // encKey, encryption, decryptor 
	
	return plaintext;
	}
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();
	}
// Call Symbian random generator
void doRandomizeL(unsigned char* buffer, size_t length)
{
    HBufC8* hbuf = HBufC8::NewLC(length);
    TPtr8 ptr = hbuf->Des();
    ptr.FillZ(ptr.MaxLength());

    CSystemRandom* rand=CSystemRandom::NewLC();
    rand->GenerateBytesL(ptr);
    memcpy(buffer, hbuf->Ptr(), length);
    CleanupStack::PopAndDestroy(rand);
    CleanupStack::PopAndDestroy(hbuf);
}
// -----------------------------------------------------------------------------
// CNATFWUNSAFTimerValAttribute::EncodeValueL
// -----------------------------------------------------------------------------
//
HBufC8* CNATFWUNSAFTimerValAttribute::EncodeValueL() const
    {
    HBufC8* encodedValue = HBufC8::NewLC(EAttributeValueSize);

    TPtr8 ptr = encodedValue->Des();
    ptr.FillZ(EAttributeValueSize);

    TUint32 value(iTimerVal);
    NATFWUNSAFUtils::WriteNetworkOrder32L(ptr, 0, value);

    CleanupStack::Pop(encodedValue);
    return encodedValue;
    }
// -----------------------------------------------------------------------------
// CNATFWUNSAFIceControllingAttribute::EncodeValueL
// -----------------------------------------------------------------------------
//
HBufC8* CNATFWUNSAFIceControllingAttribute::EncodeValueL() const
    {
    HBufC8* encodedValue = HBufC8::NewLC(EAttributeValueSize);

    TPtr8 ptr = encodedValue->Des();
    ptr.FillZ(EAttributeValueSize);

    TUint64 value(iIceControlling);
    NATFWUNSAFUtils::WriteNetworkOrder64L(ptr, 0, value);

    CleanupStack::Pop(encodedValue);
    return encodedValue;
    }
// -----------------------------------------------------------------------------
// CNATFWUNSAFAttribute::EncodeL
// -----------------------------------------------------------------------------
//
HBufC8* CNATFWUNSAFAttribute::EncodeL() const
    {
    HBufC8* value = EncodeValueL();
    CleanupStack::PushL(value);
    TInt attrValLength = value->Length();

    //Pad non-DWORD-boundary aligned attributes with spaces if needed. Spaces
    //used instead of \0 in order to not mess up buggy C implementations.
    const TInt KGranularity = 4;
    TInt bytesInLastBlock = attrValLength % KGranularity;
    TInt bytesToAppend = KGranularity - bytesInLastBlock;
    if (0 < bytesInLastBlock && !IsWordBoundaryAligned(Type()))
        {
        CBufBase* valueBuf = CBufFlat::NewL(attrValLength + bytesToAppend);
        CleanupStack::PushL(valueBuf);
        valueBuf->InsertL(0, *value, attrValLength);
        const TChar KSpace(' ');
        for (TInt i = 0; i < bytesToAppend; ++i)
            {
            valueBuf->InsertL(valueBuf->Size(), &KSpace, 1);
            }
        // Store value pointer for proper cleanupstack handling
        HBufC8* oldValue = value;
        value = valueBuf->Ptr(0).AllocL();
        CleanupStack::PopAndDestroy(valueBuf);
        CleanupStack::PopAndDestroy( oldValue );
        CleanupStack::PushL( value );
        }

    HBufC8* attribute = HBufC8::NewLC(value->Length() + EValueOffset);
    TPtr8 ptr = attribute->Des();
    ptr.FillZ(EValueOffset);

    NATFWUNSAFUtils::WriteNetworkOrder16L(ptr, ETypeOffset, Type());
    NATFWUNSAFUtils::WriteNetworkOrder16L(ptr,
                                     ELengthOffset,
                                     static_cast<TUint16>(attrValLength));
    ptr.Append(*value);
    CleanupStack::Pop(attribute);
    CleanupStack::PopAndDestroy(value);

    return attribute;
    }
/**
Encode CBW into the supplied buffer. The command is also encoded using the
supplied encoding method of MClientCommandServiceReq.

@param aBuffer The buffer to copy the encoded stream in to
@param aCommand The command to be encoded into the Command Block field
*/
void TBotCbw::EncodeL(TPtr8 &aBuffer, const MClientCommandServiceReq* aCommand) const
{
    __MSFNSLOG
    aBuffer.SetLength(KCbwLength);

    TPtr8 commandBlock = aBuffer.MidTPtr(TBotCbw::KCbwCbOffset);

    aBuffer.FillZ();

    TInt cbLength = aCommand->EncodeRequestL(commandBlock);

    TUint8* ptr = (TUint8 *) aBuffer.Ptr();
    LittleEndian::Put32(&ptr[KCbwSignatureOffset], 0x43425355);
    LittleEndian::Put32(&ptr[KCbwTagOffset], iTag);
    LittleEndian::Put32(&ptr[KCbwDataTransferLengthOffset], iDataTransferLength);
    aBuffer[KCbwFlagOffset] = (iDirection == EDataOut) ? 0x00 : 0x80;
    aBuffer[KCbwLunOffset] = iLun;
    aBuffer[KCbwCbLengthOffset] = cbLength;
    __BOTPRINT1(_L("BOT TBotCbw::Encode Lun=%d"), iLun);
}
// -----------------------------------------------------------------------------
// CNATFWUNSAFChangeRequestAttribute::EncodeValueL
// -----------------------------------------------------------------------------
//
HBufC8* CNATFWUNSAFChangeRequestAttribute::EncodeValueL() const
    {
    HBufC8* encodedValue = HBufC8::NewLC(EAttributeValueSize);

    TPtr8 ptr = encodedValue->Des();
    ptr.FillZ(EAttributeValueSize);

    TUint32 value(0);
    if (ChangeIP())
        {
        value = value | EChangeIPMask;
        }
    if (ChangePort())
        {
        value = value | EChangePortMask;
        }

    NATFWUNSAFUtils::WriteNetworkOrder32L(ptr, 0, value);

    CleanupStack::Pop(encodedValue);
    return encodedValue;
    }
// ---------------------------------------------------------------------------
// Run state machine for backup. Each file is opened and streamed to the
// BUR engine.
// ---------------------------------------------------------------------------
//
void CAknsSrvActiveBackupDataClient::GetBackupDataSectionL(
    TPtr8& aBuffer, TBool& aFinished)
    {
    AKNS_TRACE_DEBUG("CAknsSrvActiveBackupDataClient::GetBackupDataSectionL" );
    // Make sure that the buffer is empty and starts from the beginning
    aBuffer.SetLength(0);

    // don't assume they set it to false
    aFinished = EFalse;
    // any files to backup
    if( iFileArray.Count() == 0 )
        {
        // nothing to backup - just return the finished flag
        aFinished = ETrue;
        // clear the list and stop.
        iFileArray.Reset();
        AKNS_TRACE_DEBUG("CAknsSrvActiveBackupDataClient::GetBackupDataSectionL no files" );
        return;
        }

    // run the state machine
    while( ETrue )
        {
        switch( iBackupState )
            {
            // open a file for processing
            case EBackupNoFileOpen:
                {
                AKNS_TRACE_DEBUG1("CAknsSrvActiveBackupDataClient::GetBackupDataSectionL state %d", iBackupState );
                if( iFileIndex >= iFileArray.Count() )
                    {
                    // all files have been processed - send the finished flag
                    aFinished = ETrue;
                    // clear the list and stop.
                    iFileArray.Reset();
                    AKNS_TRACE_DEBUG("CAknsSrvActiveBackupDataClient::GetBackupDataSectionL all processed" );
                    return;
                    }

                // open file to send
                TInt rc=iFile.Open( iFsSession,
                                    iFileArray[iFileIndex].FullName(),
                                    ( EFileRead | EFileShareExclusive | EFileStream ) );
                if( rc != KErrNone )
                    {
                    // there's nothing we can do if we can't open the file
                    // so we just skip it
                    AKNS_TRACE_DEBUG("CAknsSrvActiveBackupDataClient::GetBackupDataSectionL skip file" );
                    ++iFileIndex;
                    break;
                    }
                iBackupState = EBackupOpenNothingSent;
                break;
                }
            // nothing sent (so far) for this file - send the header info
            case EBackupOpenNothingSent:
                {
                AKNS_TRACE_DEBUG1("CAknsSrvActiveBackupDataClient::GetBackupDataSectionL state %d", iBackupState );
                TInt fileSize;
                TInt retValue = iFile.Size( fileSize );
                if( retValue != KErrNone || fileSize == 0 )
                    {
                    // empty or unreadable - skip this file
                    iBackupState = EBackupEndOfFile;
                    AKNS_TRACE_DEBUG("CAknsSrvActiveBackupDataClient::GetBackupDataSectionL skip file2" );
                    break;
                    }

                // build the header - this is an instance member because it
                // has to persist over multiple calls to this method
                TPtr headerPtr = iBuffer->Des();

                // get the checksum - only grab last 4 bytes - enough to be satisfied that
                // the backup and restore worked ok
                TUint64 checksum = CheckSumL( iFile ) & 0xffffffff;

                // build the header - note NOT AppendFormat(); wipes out previous content.
                // <no of files><checksum><filesize><filenamelen><filename>
                headerPtr.Format(_L("%8x%8lx%8x%8x"),
                    iFileArray.Count(),
                    checksum,
                    fileSize,
                    iFileArray[iFileIndex].FullName().Length());
                headerPtr.Append( iFileArray[iFileIndex].FullName() );

                // we need it to look like an 8bit buffer
                TPtr8 headerPtr8(
                    (TUint8*)headerPtr.Ptr(),
                    headerPtr.Size(),
                    headerPtr.Size() );

                // Check how much room is left in the buffer.
                // it starts out empty when we get it from the BUE
                TInt available = aBuffer.MaxSize() - aBuffer.Size();

                // Check is there enough room for the whole header.
                TBool enoughRoom = headerPtr8.Size() < available;

                // append the header to the buffer (only till it's full)
                aBuffer.Append(
                    headerPtr8.Ptr(),
                    enoughRoom ? headerPtr8.Size() : available) ;

                // decide what needs to happen next
                // if complete then we need data, otherwise we need to put
                // the rest of the header in the next chunk
                if( enoughRoom )
                    {
                    iBackupState = EBackupOpenAllHeaderSent;
                    }
                else
                    {
                    // we need to keep track of how much of the header has
                    // been sent so that we only send the reminder on the next
                    // iteration
                    iHeaderSent = available;
                    iBackupState = EBackupOpenPartHeaderSent;
                    }

                // if the buffer's full we need to return control to the backup engine
                // Because the finishedFlag is not set, the BUE will process this
                // chunk and then ask for another
                if( aBuffer.Size() == aBuffer.MaxSize() )
                    {
                    return;
                    }
                break;
                }
            // need to send the rest of the header
            case EBackupOpenPartHeaderSent:
                {
                AKNS_TRACE_DEBUG1("CAknsSrvActiveBackupDataClient::GetBackupDataSectionL state %d", iBackupState );
                // get back the header - this is already loaded with the necessary info
                // from the previous state we were in
                TPtr headerPtr = iBuffer->Des();

                // we need it to look like an 8bit buffer
                TPtr8 headerPtr8(
                    (TUint8*)headerPtr.Ptr(),
                    headerPtr.Size(),
                    headerPtr.Size() );

                // Check how many bytes have we yet to send.
                TInt bytesRemaining = headerPtr.Size() - iHeaderSent;

                // Check how much room in the buffer.
                TInt available = aBuffer.MaxSize() - aBuffer.Size();

                // enough, if not send as much as we can
                TBool enoughRoom = bytesRemaining < available;
                aBuffer.Append(
                    headerPtr8.Ptr() + iHeaderSent,
                    enoughRoom ? bytesRemaining : available );

                if( enoughRoom )
                    {
                    iHeaderSent = 0; // ready for next header
                    iBackupState = EBackupOpenAllHeaderSent;
                    }
                else
                    {
                    iHeaderSent += available; // ready to do round again
                    // state remains as EBackupOpenPartHeaderSent
                    }

                // if the buffer's full we need to return control to the backup engine
                // Because the finishedFlag is not set, the BUE will process this
                // chunk and then ask for another
                if( aBuffer.Size() == aBuffer.MaxSize() )
                    {
                    return;
                    }
                break;
                }
            // need to send some data
            case EBackupOpenAllHeaderSent:
                {
                AKNS_TRACE_DEBUG1("CAknsSrvActiveBackupDataClient::GetBackupDataSectionL state %d", iBackupState );
                // how many bytes can we send
                TInt available = aBuffer.MaxSize() - aBuffer.Size();

                // create a buffer for this data (plus one for PtrZ)
                HBufC8* transferBuffer = HBufC8::NewLC( available + 1 );
                TPtr8 bufferToSend = transferBuffer->Des();

                // get the data
                User::LeaveIfError( iFile.Read( bufferToSend, available ) );

                // Check how much did we actually read.
                TInt bytesRead = bufferToSend.Size();

                // EOF
                if( bytesRead == 0 )
                    {
                    CleanupStack::PopAndDestroy( transferBuffer );
                    iBackupState = EBackupEndOfFile;
                    break;
                    }

                // add it to the aBuffer
                aBuffer.Append( bufferToSend.PtrZ(), bytesRead );

                // tidy up
                CleanupStack::PopAndDestroy( transferBuffer );

                // if the buffer's full we need to return control to the backup engine
                if( aBuffer.Size() == aBuffer.MaxSize() )
                    {
                    return;
                    }
                break;
                }
            // At the end of the current file.
            case EBackupEndOfFile:
                {
                AKNS_TRACE_DEBUG1("CAknsSrvActiveBackupDataClient::GetBackupDataSectionL state %d", iBackupState );

                // how many bytes can we send
                if ( aBuffer.Size() != 0 )
                    {
                    TInt available = aBuffer.MaxSize() - aBuffer.Size();
                    // pad the end of the buffer with NULL.
                    HBufC8* transferBuffer = HBufC8::NewLC( available + 1 );
                    TPtr8 bufferToSend = transferBuffer->Des();
                    bufferToSend.FillZ();
                    aBuffer.Append( bufferToSend.PtrZ(), available );
                    CleanupStack::PopAndDestroy( transferBuffer );
                    if( aBuffer.Size() != aBuffer.MaxSize() )
                        {
                        // Sanity check
                        User::Leave( KErrGeneral );
                        }
                    }
                // Close file and move on to next file.
                iFile.Close();
                ++iFileIndex;
                // Start all over again.
                iBackupState = EBackupNoFileOpen;
                break;
                }
            default:
                {
                // not reachable
                return;
                }
            }
        }
    }