当前位置: 首页>>代码示例>>C++>>正文


C++ TPtr8类代码示例

本文整理汇总了C++中TPtr8的典型用法代码示例。如果您正苦于以下问题:C++ TPtr8类的具体用法?C++ TPtr8怎么用?C++ TPtr8使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了TPtr8类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: SendAndRecvL

void CMultipleArray::SendAndRecvL(TInt aExtraSocksToJoin)
	{
	TRequestStatus stat;
	TBuf8<50> Data;

	// set up data buffers
	HBufC8 * writebuf = HBufC8::NewMaxLC( iPacketSize[aExtraSocksToJoin] );
	HBufC8 * readbuf  = HBufC8::NewMaxLC( iPacketSize[aExtraSocksToJoin] );
	TPtr8 ptrWritebuf = writebuf->Des();
	TPtr8 ptrReadbuf = readbuf->Des();

	TInt recvCount = 0;

	// Send / Recv TCP
	if (iProtocol[aExtraSocksToJoin] == KProtocolInetTcp)
		{
		for (TInt i = 0; i < iPackets[aExtraSocksToJoin]; i++)
			{
			iQoSStep->iQoSSuite->Log( _L("Sending TCP data, %d packets of %d bytes = %d"), 
			iPackets[aExtraSocksToJoin], iPacketSize[aExtraSocksToJoin], iPackets[aExtraSocksToJoin] * iPacketSize[aExtraSocksToJoin]);

			// initialise data
			Data.Format(_L8("TCP-packet:%d helloworld"),i);
			ptrWritebuf.Repeat( Data );

			// write data
			GetSocketHandle(aExtraSocksToJoin)->Write(ptrWritebuf, stat);
			User::WaitForRequest(stat);
			if (stat!=KErrNone)
				{
				iQoSStep->iQoSSuite->Log(_L("Failed to write tcp data to destination: return value = <%d>"), stat);
				User::Leave(stat.Int());
				}

			// read data
			GetSocketHandle(aExtraSocksToJoin)->Read(ptrReadbuf, stat);
			User::WaitForRequest(stat); //, TimerStatus);
			if (stat!=KErrNone)
				{
				iQoSStep->iQoSSuite->Log(_L("Failed to read tcp data from destination: return value = <%d>"), stat);
				User::Leave(stat.Int());
				}

			// compare the data
			if (ptrWritebuf.Compare( ptrReadbuf ) != 0)
				{
				iQoSStep->iQoSSuite->Log(_L("Data written to and read from destination address do not match in size"));
//				return Fail;
				}

			recvCount+=ptrReadbuf.Length();
			}

		CleanupStack::PopAndDestroy(2);	//	writebuf and readbuf
		} 

	// Send / Recv UDP 
	if (iProtocol[aExtraSocksToJoin] == KProtocolInetUdp)
		{
		iQoSStep->iQoSSuite->Log( _L("Send Udp Data, %d packets of %d bytes = %d"), 
		iPackets[aExtraSocksToJoin], iPacketSize[aExtraSocksToJoin], iPackets[aExtraSocksToJoin] * iPacketSize[aExtraSocksToJoin]);
	
		for (TInt i = 0; i < iPackets[aExtraSocksToJoin]; i++)
			{
			// initialise data
			Data.Format(_L8("UDP-packet:%d helloworld"),i);
			ptrWritebuf.Repeat( Data );	

			// write data
			GetSocketHandle(aExtraSocksToJoin)->Send(ptrWritebuf, 0, stat);
			User::WaitForRequest(stat);
			if (stat!=KErrNone)
				{
				iQoSStep->iQoSSuite->Log(_L("Failed to write udp data to destination: return value = <%d>"), stat);
				User::Leave(stat.Int());
				}

			GetSocketHandle(aExtraSocksToJoin)->Recv(ptrReadbuf, 0, stat);
			User::WaitForRequest(stat);
			if (stat!=KErrNone)
				{
				iQoSStep->iQoSSuite->Log(_L("Failed to read udp data from destination: return value = <%d>"), stat);
				User::Leave(stat.Int());
				}

			// compare the data
			if (ptrWritebuf.Compare( ptrReadbuf ) != 0 )
				{
				iQoSStep->iQoSSuite->Log(_L("Data written to and read from destination address do not match in sizevalue"));
//				return Fail;
				}
			recvCount += ptrReadbuf.Length();
			}

		// get rid of the old buffers 
		CleanupStack::PopAndDestroy(2);	//	writebuf and readbuf
		}


	// check the total received (95 per cent is allowable for us)
//.........这里部分代码省略.........
开发者ID:cdaffara,项目名称:symbiandump-os2,代码行数:101,代码来源:CMultipleArray.cpp

示例2: ASSERT

void CActionSet::PerformAction(TRequestStatus& aStatus)
{
    __UHEAP_MARK;
    TRequestStatus* status = &aStatus;
    iResult = EFalse;
    HBufC8* pkcs12Pwd = 0;

    // default value is NULL to avoid RVCT warning
    // C2874W: set may be used before being set
    CPBEncryptSet* set = 0;
    if (iKdf == 0)
    {
        CleanupStack::PushL(pkcs12Pwd);
        set = CPBEncryptSet::NewLC(*iPasswd, iCipher);
    }
    else
    {
        // if supply KDF, must also supply salt len and iteration count
        ASSERT(iSaltLenBytes != 0 && iIterCount != 0);

        CPBEncryptParms* ep = CPBEncryptParms::NewLC();

        ep->SetCipher(iCipher);

        TInt saltLenBytes;
        TInt r = TLex8(*iSaltLenBytes).Val(saltLenBytes);
        ASSERT(r == KErrNone);
        ep->ResizeSaltL(saltLenBytes);

        TInt iterCount;
        r = TLex8(*iIterCount).Val(iterCount);
        ASSERT(r == KErrNone);
        ep->SetIterations(iterCount);

        CleanupStack::PushL((CBase*)0);
        CleanupStack::Pop((CBase*)0);

        if (*iKdf == _L8("PKCS#5"))
        {
            ep->SetKdf(CPBEncryptParms::EKdfPkcs5);
            set = CPBEncryptSet::NewL(*iPasswd, *ep);
        }
        else if (*iKdf == _L8("PKCS#12"))
        {
            pkcs12Pwd = PKCS12KDF::GeneratePasswordLC(*iPasswd);
            ep->SetKdf(CPBEncryptParms::EKdfPkcs12);
            set = CPBEncryptSet::NewL(*pkcs12Pwd, *ep);
            CleanupStack::Pop(pkcs12Pwd);
        }
        else
            User::Panic(_L("Unrec KDF"), 0);

        CleanupStack::PopAndDestroy(ep);
        // encryption could leak here, but for reservation above
        CleanupStack::PushL(pkcs12Pwd);
        CleanupStack::PushL(set);
    }
    CPBEncryptor* encryptor = set->NewEncryptLC();
    HBufC8* ciphertextTemp = HBufC8::NewLC(encryptor->MaxFinalOutputLength(iInput->Length()));

    TPtr8 ciphertext = ciphertextTemp->Des();
    encryptor->ProcessFinalL(*iInput, ciphertext);
    TBuf<128> newPwdTemp(*iPasswd);
    newPwdTemp.Append('a');

    TBuf8<128> newPwdTemp8;

    TPBPassword newPassword(KNullDesC);
    if (pkcs12Pwd == 0)
        new(&newPassword) TPBPassword(newPwdTemp);
    else
    {
        HBufC8* newPwd = PKCS12KDF::GeneratePasswordLC(newPwdTemp);
        newPwdTemp8.Copy(*newPwd);
        new(&newPassword) TPBPassword(newPwdTemp8);
        CleanupStack::PopAndDestroy(newPwd);
    }

    set->ChangePasswordL(newPassword);

    //create a mem  buffer store
    CBufStore* store = CBufStore::NewLC(100);
    RStoreWriteStream write;

    //write the encrypted master key to a stream
    TStreamId keyStreamId = write.CreateLC(*store);
    write << set->EncryptedMasterKey();
    write.CommitL();
    CleanupStack::PopAndDestroy(); //CreateLC()

    //write the encryption data to another stream
    TStreamId dataStreamId = write.CreateLC(*store);
    set->EncryptionData().ExternalizeL(write);
    write.CommitL();
    CleanupStack::PopAndDestroy(); //CreateLC()

    //prepare to read the streams back in, creating a new TPBEncryptionData
    RStoreReadStream read;
    read.OpenLC(*store, dataStreamId);

//.........这里部分代码省略.........
开发者ID:kuailexs,项目名称:symbiandump-os2,代码行数:101,代码来源:tactionset.cpp

示例3: byte

void CRFC3984Encode::FragmentNaluL(
    TDes8 & aBuffer, 
    TUint32 /*aTimeStamp*/, 
    TUint32 & aMarkerBit, 
    TInt & aNalCount, 
    TInt aStartIndex, 
    TInt aSize, 
    TUint16 aDON )
    {
	TInt index = 0;
	TInt fragsPacketized = 0;
	TUint8 headerByte = 0; // FU-A packet header byte (contains F, NRI, Type Fields) 
	TUint8 fragHeaderByte = 0;
	TInt length = 0;
	// maximum size of fragment, 4 is to cater for DON field in FU-B
	TInt fragMaxSize = iMaxPacketSize - 4; 
	TInt fragSize = 0; // size of fragment
	HBufC8 * pBuffer = NULL;
	
	// index keeps track of indexes in the buffer
	index = aStartIndex; 
	// length of data packetized, the code decrements this after each fragment is made
	length = aSize;	
	
	while ( length > 0 )
	    {
	     // Actually should be based on (PacketizationMode == INTERLEAVED && fragsPacketized == 0)
		TBool fuB = EFalse;
		
		headerByte = aBuffer[aStartIndex]  & ( 0x07 << 5 ); // Extracting F and NRI bits
		
		// taking lower 5 type bits and putting into fragHeader
		fragHeaderByte = aBuffer[aStartIndex] & 0x1f; 
			
		if ( fragsPacketized == 0 )
		    {
		    fragHeaderByte |= (0x1 << 7); // setting start bit
		    }
		    
		if ( length <= fragMaxSize )
		    {
			fragHeaderByte |= ( 0x1 << 6 );	// setting end byte
			aMarkerBit = 1;	
		    }
		else
		    {
			aMarkerBit = 0;
		    }
		
		if ( fragsPacketized == 0 )	// skipping payload header byte for FU packets 
		    {	
		    index += 1;
			length -= 1;	
		    }
	    
	    fragSize = ( length > fragMaxSize ) ? fragMaxSize+2 : length+2; // 2 bytes for headers
		
		if( !fuB )
		    {
			headerByte |= PACKET_FU_A;	
		    }
		else
		    {
			fragSize += 2; // for additional DON field
			headerByte |= PACKET_FU_B;
		    }
		
		// allocating memory for fragmented NAL unit
	    pBuffer = HBufC8::NewLC(fragSize);
	     	
 		TPtr8 pDes = pBuffer->Des(); //new (ELeave) TBuf8<size>;
		pDes.Append( &headerByte, 1 ); // appending FU-A packet header byte
		pDes.Append( &fragHeaderByte, 1 ); // appending Fragment header
		
		if ( fuB )
		    {  
		    // writing DON in network byte order
			TUint16 val = ByteOrder::Swap16( aDON );
			TUint8* ptrByte = reinterpret_cast<TUint8*>( &val );
			pDes.Append( ptrByte, 2 );
		    }
		
		TPtr8 pStart = aBuffer.MidTPtr( index ); // pStart contains the data pointer    		
    	
    	if ( !fuB )
    	    {
    		pDes.Append( pStart.Ptr(), fragSize-2 ); // copying data	
    		index += Min( length, fragMaxSize );    	
    		length -= ( fragSize-2 );
        	}
    	else
    	    {
    	    // copying data, subtracting DON and header size from total size to copy
    		pDes.Append( pStart.Ptr( ), fragSize-4 );
			index += Min( length, fragMaxSize );
			length -= ( fragSize-4 );    		
    	    }
    
    	
    	// inserting into the payloadized NAL unit buffer for retreival
//.........这里部分代码省略.........
开发者ID:kuailexs,项目名称:symbiandump-mw1,代码行数:101,代码来源:rfc3984encode.cpp

示例4: EAP_TRACE_BEGIN

void eapol_am_wlan_authentication_symbian_c::read_configureL(
	const TDesC& aDbName,
	const TDesC& aTableName,
	eap_config_string field,
	const u32_t /*field_length*/,
	eap_variable_data_c * const data)
{	
	EAP_TRACE_BEGIN(m_am_tools, TRACE_FLAGS_DEFAULT);
	EAP_TRACE_DEBUG(
		m_am_tools, 
		TRACE_FLAGS_DEFAULT, 
		(EAPL("eapol_am_wlan_authentication_symbian_c::read_configureL(): %s, this = 0x%08x => 0x%08x\n"),
		 (m_is_client == true) ? "client": "server",
		 this,
		 dynamic_cast<abs_eap_base_timer_c *>(this)));
	EAP_TRACE_RETURN_STRING_FLAGS(m_am_tools, TRACE_FLAGS_DEFAULT, "returns: eapol_am_wlan_authentication_symbian_c::read_configureL()");

	// Open database
	RDbNamedDatabase db;

	TInt error = db.Open(m_session, aDbName);

	EAP_TRACE_DEBUG(
		m_am_tools, 
		TRACE_FLAGS_DEFAULT, 
		(EAPL("eapol_am_wlan_authentication_symbian_c::read_configureL(): db.Open(), error = %d\n"),
		 error));

	User::LeaveIfError(error);
	
	CleanupClosePushL(db);


	// Create a buffer for the ascii strings - initialised with the argument
	HBufC8* asciibuf = HBufC8::NewLC(128);
	TPtr8 asciiString = asciibuf->Des();
	asciiString.Copy(reinterpret_cast<const unsigned char *>(field));
		
	// Buffer for unicode parameter
	HBufC* unicodebuf = HBufC::NewLC(128);
	TPtr unicodeString = unicodebuf->Des();
	
	// Convert to unicode 
	unicodeString.Copy(asciiString);

	// Now do the database query
	HBufC* buf = HBufC::NewLC(KMaxSqlQueryLength);
	TPtr sqlStatement = buf->Des();
	_LIT(KSQLQueryRow, "SELECT %S FROM %S");
	sqlStatement.Format( KSQLQueryRow, &unicodeString, &aTableName );
	
	RDbView view;
	User::LeaveIfError(view.Prepare(db, TDbQuery(sqlStatement), TDbWindow::EUnlimited));
	CleanupClosePushL(view);
	User::LeaveIfError(view.EvaluateAll());	
	if (view.FirstL())
	{
		eap_status_e status(eap_status_process_general_error);
		view.GetL();		
		switch (view.ColType(1))
		{
		case EDbColText:				
			{
				unicodeString = view.ColDes(1);
				// Convert to 8-bit
				asciiString.Copy(unicodeString);
				if (asciiString.Size() > 0)
				{
					status = data->set_copy_of_buffer(asciiString.Ptr(), asciiString.Size());
					if (status != eap_status_ok)
					{
						User::Leave(m_am_tools->convert_eapol_error_to_am_error(
							EAP_STATUS_RETURN(m_am_tools, status)));
					}
				} 
				else 
				{
					// Empty field. Do nothing...data remains invalid and the stack knows what to do hopefully.
					break;
				}
			}
			break;
		case EDbColUint32:
			{
				TUint value;
				value = view.ColUint32(1);
				status = data->set_copy_of_buffer((const unsigned char *) &value, sizeof(value));
				if (status != eap_status_ok)
				{
					User::Leave(m_am_tools->convert_eapol_error_to_am_error(
						EAP_STATUS_RETURN(m_am_tools, status)));
				}
			}
			break;
		default:
			EAP_TRACE_DEBUG(
				m_am_tools,
				TRACE_FLAGS_DEFAULT,
				(EAPL("ERROR: read_configureL: Unexpected column type.\n")));
			User::Panic(_L("EAPOL"), 1);			
//.........这里部分代码省略.........
开发者ID:cdaffara,项目名称:symbiandump-mw1,代码行数:101,代码来源:eapol_am_wlan_authentication_symbian.cpp

示例5: NextWriteChunk

EXPORT_C TInt CMTPTypeOpaqueData::NextWriteChunk(TPtr8& aChunk)
    {
    aChunk.Set(NULL, 0, 0);
    return KErrNotReady;
    }
开发者ID:kuailexs,项目名称:symbiandump-mw3,代码行数:5,代码来源:cmtptypeopaquedata.cpp

示例6: RunTest

/**
@SYMTestCaseID			PDS-SQL-UT-4151
@SYMTestCaseDesc		Measures the performance of inserting multiple records
						into the Music Player MPX database.  This test is based on 
						a real Music Player Harvesting use case
@SYMTestPriority		Medium
@SYMTestActions			Reads SQL transactions from a file and executes them.  
						Records the time for executing each statement
@SYMTestExpectedResults All statements should be executed without error and 
						performance measurements logged
@SYMDEF					DEF142306
*/
void RunTest()
	{
	//Open the file with the sql statements 
	_LIT(KSqlFileName,"z:\\test\\t_sqlperformance4.sql");
	RFile sqlFile;
	TInt err = sqlFile.Open(TheFs, KSqlFileName, EFileRead); 
	TEST2(err, KErrNone);
	
	TInt fileLen = 0;
	err = sqlFile.Size(fileLen); 
	TEST2(err, KErrNone);
	
	HBufC8* sqlBuf = HBufC8::New(fileLen); 
	TEST(sqlBuf != NULL);
	TPtr8 sql = sqlBuf->Des();
	err = sqlFile.Read(sql);
	
	sqlFile.Close();
	TEST2(err, KErrNone);
	TEST2(sql.Length(), fileLen);
	
	//Open main database
	err = TheDbC.Open(TheDbFileName, &TheSqlConfigString);
	TEST2(err, KErrNone);
	
	TheTest.Printf(_L("Beginning INSERTS...\n"));
	
	const TInt KRecordCount = 6544;
	TInt recordCount = 0;
	TInt insertCnt = 0;
	TInt updateCnt = 0;
	TInt selectCnt = 0;
	TInt trnCnt = 0;
	TInt totalTime = 0;

	TInt insertTrnCnt = 0;
	TInt updateTrnCnt = 0;
	TInt selectTrnCnt = 0;
	
	for(;sql.Length()>0;)
		{
		TInt eolPos = sql.Locate(TChar('\n'));
		if(eolPos < 0)
			{
			break;//No more SQL statements
			}
		TInt stmtLength = eolPos;
		while (stmtLength > 0 && (sql[stmtLength-1] == '\r'))
			{
			--stmtLength; //Reduce length to remove carriage return characters from the end of the statement string
			}
		TPtrC8 sqlStmt8(sql.Ptr(), stmtLength);
		TPtrC8 ptr = sql.Mid(eolPos + 1);//"eolPos + 1" - first character after '\n'
		sql.Set(const_cast <TUint8*> (ptr.Ptr()), ptr.Length(), ptr.Length());
		++recordCount;
		
		//Convert to 16 bit query string
		TBuf<1024> query;
		query.Copy(sqlStmt8);
		
		//Execute the statement
		TInt start = User::FastCounter();
		err = TheDbC.Exec(query);
		TInt end = User::FastCounter();
		
		TEST(err >= 0);
		
		//Get the execution time for that statement
		TInt duration = GetDuration(start, end);
		totalTime += duration;
		
		if(query == KBeginTransaction)
			{		
			TheTest.Printf(_L("Execute Statement - BEGIN: %d us\n"), duration);
			}
		
		else if(query == KCommitTransaction)
			{
			++trnCnt;
			TheTest.Printf(_L("Execute Statement - COMMIT: %d us, Trn#%d, \"INSERT\" count: %d, \"UPDATE\" count: %d, \"SELECT\" count: %d\n"), 
					duration, trnCnt, insertTrnCnt, updateTrnCnt, selectTrnCnt);
			insertTrnCnt = updateTrnCnt = selectTrnCnt = 0;
			}

		else
			{	
			TPtrC queryType(query.Ptr(), 6);
			TheTest.Printf(_L("Execute Statement - %S: %d us\n"),&queryType, duration);
//.........这里部分代码省略.........
开发者ID:cdaffara,项目名称:symbiandump-os2,代码行数:101,代码来源:t_sqlperformance4.cpp

示例7: msgRef

// ---------------------------------------------------------
// CNSmlCmdsBase::ProcessStatusCmdL
// Handles Status command from a server.
// ---------------------------------------------------------
EXPORT_C void CNSmlCmdsBase::ProcessStatusCmdL( SmlStatus_t* aStatus )
	{
	//msgRef
	if ( !aStatus->msgRef )
		{
		return;
		}
	if ( !aStatus->msgRef->content )
		{
		return;
		}
	TPtr8 msgRef( (TUint8*) aStatus->msgRef->content, aStatus->msgRef->length, aStatus->msgRef->length );
	TrimRightSpaceAndNull( msgRef );
	if ( msgRef.Length() == 0 )  
		{
		return;
		}
	//cmd
	if ( !aStatus->cmd )
		{
		return;
		}
	if ( !aStatus->cmd->content )
		{
		return;
		}
	TPtr8 cmd( (TUint8*) aStatus->cmd->content, aStatus->cmd->length, aStatus->cmd->length );
	TrimRightSpaceAndNull( cmd );
	if ( cmd.Length() == 0 )  
		{
		return;
		}
	//cmdRef
	HBufC8* cmdRef = NULL;
	if ( !aStatus->cmdRef )
		{
		if ( cmd == KNSmlAgentSyncHdr )
			{
			cmdRef = HBufC8::NewLC( KNSmlAgentSyncHdrCmdID.iTypeLength );
			*cmdRef = KNSmlAgentSyncHdrCmdID;
			}
		else
			{
			return;
			}
		}
	else
	if ( !aStatus->cmdRef->content )
		{
		if ( cmd == KNSmlAgentSyncHdr )
			{
			cmdRef = HBufC8::NewLC( KNSmlAgentSyncHdrCmdID.iTypeLength );
			*cmdRef = KNSmlAgentSyncHdrCmdID;
			}
		else
			{
			return;
			}
		}
	else
		{
		TPtr8 cmdRefPtr ( (TUint8*) aStatus->cmdRef->content, aStatus->cmdRef->length, aStatus->cmdRef->length );
		TrimRightSpaceAndNull( cmdRefPtr );
		if ( cmdRefPtr.Length() == 0 )  
			{
			if ( cmd == KNSmlAgentSyncHdr )
				{
				cmdRef = HBufC8::NewLC( KNSmlAgentSyncHdrCmdID.iTypeLength );
				*cmdRef = KNSmlAgentSyncHdrCmdID;
				}
			else
				{
				return;
				}
			}
		else
			{
			cmdRef = HBufC8::NewLC( cmdRefPtr.Length() );
			*cmdRef = cmdRefPtr;
			}
		}
	// Status code
	TPtr8 statusCode( (TUint8*) aStatus->data->content, aStatus->data->length, aStatus->data->length );
	TrimRightSpaceAndNull( statusCode );
	if ( statusCode.Length() == 0 )
		{
		CleanupStack::PopAndDestroy(); //cmdRef
		return;
		}
	TLex8 lexicalStatus( statusCode );
	TInt numericStatus;
	if ( lexicalStatus.Val (numericStatus ) != KErrNone )
		{ 
		CleanupStack::PopAndDestroy(); //cmdRef
		return;
		}
//.........这里部分代码省略.........
开发者ID:kuailexs,项目名称:symbiandump-mw3,代码行数:101,代码来源:nsmlcmdsbase.cpp

示例8: sizeof

void CIkev1Dialog::StoreUserNameL(TPtr8 aUserName)
{
/*--------------------------------------------------------------------
 *
 *  Store specified user name into cache file (used as init value in
 *  the next user name specific dialog).
 *  User name shall be encrypted (DES) before stored into cache file. 
 *
 *---------------------------------------------------------------------*/

 
	if (aUserName.Length() == 0)
	    {
	    User::Leave(KErrArgument);
	    }
		
	//
	// Allocate buffer for file header and encrypted key
	//

	HBufC8* HeaderBfr = HBufC8::NewLC(aUserName.Length() + sizeof(TUserNameFileHdr) + 32);
    
	TUserNameFileHdr* FileHeader = (TUserNameFileHdr*)HeaderBfr->Ptr();
	//
	// Get random data values for salt and IV. 
	//
	TPtr8 ptr((TUint8*)FileHeader, sizeof(TUserNameFileHdr));
	ptr.SetLength(sizeof(TUserNameFileHdr));
	TRandom::RandomL(ptr);

	FileHeader->iFileId = USER_NAME_FILE_ID;	
	//
	// Build encryption key from just created salt data and fixed
	// secret passphrase using MD5 hash
	//
	TBuf8<16>  EncryptionKey;
	TPtr8 SaltPtr((TUint8*)FileHeader->iSalt, 8, 8);
	User::LeaveIfError(CIkev1Dialog::BuildEncryptionKey(SaltPtr, EncryptionKey));
	   //
	   // Encrypt user name data with just created key. 
	   // Because DES is used as encryption algorithm, the eight first
	   // octets of created encryption octets is used as encryption key.
	   //
	    TInt EncrLth = 0;
    EncrLth = SymmetricCipherL((TUint8*)aUserName.Ptr(),
					          ((TUint8*)FileHeader + sizeof(TUserNameFileHdr)),
           					    aUserName.Length(), FileHeader->iIV, (TUint8*)EncryptionKey.Ptr(), ETrue);
	if ( EncrLth ) 
	    {
        //
        // Write encrypted data into user name file
        //
		RFile NameFile;		  

		TBuf<128> Ppath;	
		User::LeaveIfError(iFs.PrivatePath(Ppath));

	    Ppath.Append(USER_NAME_CACHE_FILE);
	    TInt err = iFs.CreatePrivatePath(EDriveC);
	    if (err != KErrNone &&
	        err != KErrAlreadyExists)
	        {
	        User::Leave(err);
	        }
	    User::LeaveIfError(NameFile.Replace(iFs, Ppath, EFileShareAny|EFileWrite));

		TPtrC8 EncryptedData((TUint8*)FileHeader, sizeof(TUserNameFileHdr) + EncrLth); 

		NameFile.Write(EncryptedData);
		NameFile.Close();
	    }

    CleanupStack::PopAndDestroy(); // Delete encryption buffer
}
开发者ID:cdaffara,项目名称:symbiandump-mw4,代码行数:74,代码来源:ikev1dialog.cpp

示例9: LBSLOG

/**
Called when the INIT property is changed and once on the construction of the object. Extracts 
the message from the INIT property, notifies both the observer by calling the 
MLbsSuplPushRecObserver::OnSuplInit function and the sender by setting the ACK property.
Then it resubscribes for the INIT property to listen for next messages.

@see CSuplPushImpl
@see MLbsSuplPushRecObserver::OnSuplInit
@see CActive::RunL
*/
void CLbsSuplPushRecChannel::RunL()
	{
	LBSLOG(ELogP1, "CLbsSuplPushRecChannel::RunL() Begin\n");
	if(iStatus==KErrNone)
		{
		iInitProperty.Subscribe(iStatus);
		SetActive();
		
		TPckgBuf<TInt> length;
		TInt err = RProperty::Get(iPropOwnerSecureId, iInitPropKey, length);
		
		//The INIT propery has been defined but not set yet.
		if(err==KErrNone && length.Length()==0)
			{
			LBSLOG(ELogP1, "CLbsSuplPushRecChannel::RunL() - err==KErrNone && length.Length()==0 End\n");
			return;
			}
		
		//Can't do anything here, just resubscribe
		if(err!=KErrOverflow || length()<=0)
			{
			//The property must be set in the correct value.
			__ASSERT_DEBUG(0, User::Invariant());
			LBSLOG(ELogP1, "CLbsSuplPushRecChannel::RunL() - err!=KErrOverflow || length()<=0 End\n");
			return;
			}

		TInt len = length() + 2*sizeof(TInt);
		
		HBufC8* msg = HBufC8::New(len);
		
		//Not enough memory to handle the message, just resubscribe 
		if(msg==0)
			{
			LBSLOG(ELogP1, "CLbsSuplPushRecChannel::RunL() - msg==0 End\n");
			return;
			}
		
		TPtr8 ptr = msg->Des();
		err = RProperty::Get(iPropOwnerSecureId, iInitPropKey, ptr);
		if(err!=KErrNone || ptr.Length()!=len)
			{
			delete msg;
			//Unexpected environment error or the length of the message is not equal the length declared in
			//the header.
			__ASSERT_DEBUG(0, User::Invariant());
			LBSLOG(ELogP1, 
				"CLbsSuplPushRecChannel::RunL() RProperty::Get(iPropOwnerSecureId, iInitPropKey, ptr)|| ptr.Length()!=len End\n");
			return;
			}
		
		TPckgBuf<TInt> reqId;
		reqId.Copy(msg->Mid(sizeof(TInt), sizeof(TInt))); 
		
		if(reqId()<=0)
			{
			delete msg;
			//Message is corrupted, the reqId must be > 0. 
			__ASSERT_DEBUG(0, User::Invariant());
			LBSLOG(ELogP1, "CLbsSuplPushRecChannel::RunL() - reqId()<=0 End\n");
			return;
			}

			
		TInt ackId = 0;
		err = RProperty::Get(iPropOwnerSecureId, iAckPropKey, ackId);

		if(err!=KErrNone || ackId<0)
			{
			delete msg;
			if(ackId<0)
				{
				RProperty::Set(iPropOwnerSecureId, iAckPropKey, 0);
				}
			//Unexpected environment error or wrong ackId, it must be > 0.
			__ASSERT_DEBUG(0, User::Invariant());
			LBSLOG(ELogP1, 
					"CLbsSuplPushRecChannel::RunL() - RProperty::Get(iPropOwnerSecureId, iAckPropKey, ackId)!=KErrNone || ackId<0 End\n");
			return;
			}
		

		//We notify the observer only if message was not delivered before
		if(ackId!=reqId())
			{
			TLbsSuplPushRequestId reqIdUnsgn = reqId(); 
			TPtrC8 msgPtr = msg->Right(length());
			err = RProperty::Set(iPropOwnerSecureId, iAckPropKey, reqId());
			//Unexpected environment error.
			__ASSERT_DEBUG(err==KErrNone, User::Invariant());
//.........这里部分代码省略.........
开发者ID:kuailexs,项目名称:symbiandump-os1,代码行数:101,代码来源:lbssuplpushreceiverchannel.cpp

示例10: logFileBuf

///////////////////////////////////////////////////////////////////
//  GetStartPositionOfLogElem
//  This function calculates the start position of a log element.
//  As input parameter it has the position of the first byte
//  after the element.
///////////////////////////////////////////////////////////////////
TInt CEventViewer::GetStartPositionOfLogElem(TUint32 aPositionOfLogElemEnd,       
                                             TUint32* aPositionOfLogElem)
    {

    // Set base for the most recent log element trailer

    TPtr8 logFileBuf (iLogFileBuf->Des()); // Log file in memory
    TUint32  logElemTrailerPos = aPositionOfLogElemEnd - LOG_ELEM_TRAILER_LTH;

    if (iWrappingOccured && logElemTrailerPos <= iCurrFileHeader.iPositionOfNextFree)
        {

        return KErrNotFound;
        }

    TPtr8 elemTrailer (const_cast<TUint8*>(logFileBuf.Ptr())+ logElemTrailerPos, // Data ptr
                       LOG_ELEM_TRAILER_LTH,    // Data length
                       LOG_ELEM_TRAILER_LTH);   // Max length
    // Convert the TPtr8 parameter to TUint8* format

    TLogElemTrailer* elemTrailerPtr = (TLogElemTrailer*) elemTrailer.Ptr(); 

    // Copy the packet format trailer parameters to unpacked object

    iLogElemTrailer.iEndMark1             = elemTrailerPtr->GetEndMark1();
    iLogElemTrailer.iEndMark2             = elemTrailerPtr->GetEndMark2();
    iLogElemTrailer.iEventLength          = elemTrailerPtr->GetEventLength();

    // Check the validity of trailer

    if (iLogElemTrailer.iEndMark1 != END_MARK_1
        ||
        iLogElemTrailer.iEndMark2 != END_MARK_2
        ||
        iLogElemTrailer.iEventLength > aPositionOfLogElemEnd +
        EVENTLOG_FILE_HEADER_LTH)
        {

        return KErrGeneral;
        }

    // Set position for the current log element

    TUint32  logElemPos = aPositionOfLogElemEnd - iLogElemTrailer.iEventLength;

    if (iWrappingOccured && logElemPos < iCurrFileHeader.iPositionOfNextFree)
        {

        return KErrNotFound;
        }

    TPtr8 logElem (const_cast<TUint8*>(logFileBuf.Ptr())+ logElemPos, // Data ptr
                   iLogElemTrailer.iEventLength,   // Data length
                   iLogElemTrailer.iEventLength);

    // Convert the TPtr8 parameter to TUint8* format

    TLogElem* logElemPtr = (TLogElem*) logElem.Ptr(); 

    // Copy the event number and event length parameters
    // from packed format log element to unpacked object

    iUnpackedLogElem.iEventLength                 = logElemPtr->GetEventLength();
    iUnpackedLogElem.iEventNumber                 = logElemPtr->GetEventNumber();

    // Verify the extracted data

    if (iUnpackedLogElem.iEventNumber > iCurrFileHeader.iCurrEventNumber
        ||
        iUnpackedLogElem.iEventLength  != iLogElemTrailer.iEventLength)
        {

        return KErrGeneral;
        }

    *aPositionOfLogElem = logElemPos;

    return KErrNone;

    }
开发者ID:cdaffara,项目名称:symbiandump-mw4,代码行数:86,代码来源:logfilehandler.cpp

示例11: TRACE

// -----------------------------------------------------------------------------
// CBSBrandHandler::ReadStreamL()
// -----------------------------------------------------------------------------
//
MBSElement* CBSBrandHandler::ReadStreamL( const TDesC8& aId, RFileReadStream& aStream,
										  TBool aAllowEmptyId /* = EFalse */ )
	{
	TRACE( T_LIT( "CBSBrandHandler::ReadStreamL BEGIN"));
	TBSElementType type = (TBSElementType)aStream.ReadInt16L();
	MBSElement* returnValue = NULL;
	
	TInt idSize = aStream.ReadInt16L();
	
	HBufC8* elementId = HBufC8::NewLC( idSize );
	TPtr8 elementIdPtr = elementId->Des();

	if( idSize == 0 && aAllowEmptyId )
		{
		// we don't read empty ID
		}
	else
		{
		aStream.ReadL( elementIdPtr, idSize );
        elementIdPtr.SetLength( idSize );// Set length
		}
	

	TBool match = EFalse;
	if( aAllowEmptyId || ( 0 == elementIdPtr.Compare( aId ) ) )
		{
		match = ETrue;
		}
		
    TPtrC8 idPtrC( *elementId );// idPtrC creation moved here so it will be updated correctly.
	if( elementId->Length() == 0 )
		{
		CleanupStack::PopAndDestroy( elementId );
		elementId = NULL;
		idPtrC.Set( KNullDesC8 );
		}

	switch( type )
		{
		case EBSInt:
			{
			TInt intData = aStream.ReadInt16L();
			TRACE( T_LIT( "CBSBrandHandler::ReadStreamL type INT"));
			if( match )
				{
                // Codescanner warning: neglected to put variable on cleanup stack (id:35)
                // This method cannot leave after this line
				returnValue = BSElementFactory::CreateBSElementL( idPtrC, // CSI: 35 # See above
																  EBSInt,
																  intData ); 
				}
			break;
			}		
		case EBSText:
		case EBSFile: // flow through
			{
			TInt textSize = aStream.ReadInt16L();
			HBufC* textData = HBufC::NewLC( textSize );

			TPtr textPtr = textData->Des();
			aStream.ReadL( textPtr, textSize );

			TRACE( T_LIT( "CBSBrandHandler::ReadStreamL type TEXT/ FILE"));
			if( match )
				{
                // Codescanner warning: neglected to put variable on cleanup stack (id:35)
                // This method cannot leave after this line
				returnValue = BSElementFactory::CreateBSElementL( idPtrC, // CSI: 35 # See above
																  type,
																  *textData ); 
				}

			CleanupStack::PopAndDestroy( textData );
			break;
			}
		case EBSList:
			{
			RBSObjOwningPtrArray<MBSElement> listData;
			CleanupClosePushL( listData );
			TInt count = aStream.ReadInt16L();
			
			for( TInt i = 0; i < count; i++ )
				{
				MBSElement* subElement = ReadStreamL( KNullDesC8, aStream, ETrue );
				CleanupDeletePushL( subElement );
				listData.AppendL( subElement );
				CleanupStack::Pop(); // subElement
				}
				
			if( match )
				{
                // Codescanner warning: neglected to put variable on cleanup stack (id:35)
                // This method cannot leave after this line
				returnValue = BSElementFactory::CreateBSElementL( idPtrC, // CSI: 35 # See above
																  EBSList,
																  listData ); 
//.........这里部分代码省略.........
开发者ID:kuailexs,项目名称:symbiandump-mw1,代码行数:101,代码来源:cbsbrandhandler.cpp

示例12: LocateField

EXPORT_C TInt CHTTPResponse::LocateField(THttpHeaderField aField,
								TInt aStartIndex) const
    {
	// Content-Type is a special case; it appears to always be at the first
	// byte of the header, and doesn't have any encoding of the field name -
	// just straight into the Field Value at byte 0.  This is an assumption
	// however, since the WSP spec is not explicit - could it possibly be just
	// the NWSS GW's implementation of WSP that does this?
	if ( (aStartIndex == 0) && (aField == EHttpContentType) )
		{
		return aStartIndex; // the content-type field value position - ie. 0
		}
	
	// Deal with other Field Names, (Possibly including Content-Type if the
	// start index is offset into the header? Note that this is not likely to
	// occur though, with the abbreviated encoding.)
	TInt respLength = iResponse->Length();
	TPtr8 respChars  = iResponse->Des();
    for (TInt index = aStartIndex; index < respLength; index++)
        {
		// Examine the byte at this position in the header
        TUint8 byteCode = respChars[index];

		// Expect byteCode to be a Field Name code (unless the search is at
		// position zero, which has a missing content-type field name). Check
		// for the search field, remembering to clear the top bit
        if ( ( (byteCode & 0x7f) == aField) && (index != 0) )
            {
			// Got it - return the next position to locate the field value,
			// checking for potential overrun
			if (index < respLength - 1)
				{
				// Advance 1 to the header field value
				++index;
				return index;
				}
			else
				{
				return KErrNotFound;
				}
            }
        else
            {
			// Check that we aren't dealing with the Content-Type field
			// (expected at position 0), since it doesn't use a field type
			if (index != 0)
				{
				// WSP Spec Section 8.4.1.1 - Field Names
				//
				// If the byte is an alphanumeric, then it must be a field name that doesn't have
				// a WSP encoding.  In this circumstance, we can't handle the field, and must
				// therefore skip over it
				if ((byteCode >= 32) && (byteCode <= 127))
					{
					// Hit the start of a Header Name string - this will be assumed
					// continuous until the NUL is found or until the end
					// of the header is hit (which would be an error)
					while ( (respChars[index] != 0) && (index < respLength - 1) )
						++index;
					}

				// WSP Spec Section 8.4.1.2 - Field Values
				//
				// Now examine the field value by advancing one place.  If that advance takes us off
				// the end of the buffer, then (a) the WSP is invalid, and (b) the field is not found!
				++index;
				if (index == respLength)
					return KErrNotFound;
				}

			// Read the next byte at this position in the header
            byteCode = respChars[index];

			// Codes 0-30 represent that number of following data octets, so
			// they should be skipped
			if (byteCode == 0)			// 0 data octets follow !???? : (Strange but true)
				{
				// __DEBUGGER();
				}
            else if (byteCode <= 30)
				{
                index += byteCode;
				}
            else
                {
				// Code 31 indicates that the following bytes make a UIntVar,
				// which indicates the number of data octets after it. The
				// UIntVar itself could be composed of upto 5 bytes
                if (byteCode == 31)
					{
					// Copy a full 5 bytes from the header - note that actually
					// fewer might have been used; the UIntVar to Int
					// converter function returns the exact number that were
					// used.
					TInt value = 0;
					TInt consumed = ParseUIntVar(respChars.Mid(index + 1), value);
					
					if( consumed < KErrNone )
						return KErrCorrupt;

//.........这里部分代码省略.........
开发者ID:kuailexs,项目名称:symbiandump-mw2,代码行数:101,代码来源:CHTTPResponse.cpp

示例13: EncodeBodyL

/**
 *  Encodes the information element into its raw format. (no IE id)
 *  
 *  @param aPtr the buffer to be used which is to contain the data
 *  @param TBool boolean to indicate if it is for serialisation or encoding
 *  @leave KErrCorrupt If the melody has not been defined.
 */
void CEmsSoundIE::EncodeBodyL(TPtr8 aPtr, TBool) const
	{
	__ASSERT_ALWAYS(iMelody!=NULL, User::Leave(KErrCorrupt));
	aPtr.Append(*iMelody);
	}
开发者ID:cdaffara,项目名称:symbiandump-os1,代码行数:12,代码来源:EMSSoundIE.cpp

示例14: INFO_PRINTF1

TVerdict CClientFinishedStep::doTestStepL()
	{
	INFO_PRINTF1(_L("Calling TLS Provider to fetch cipher suites."));
	
	// first we have to retrieve the available cipher suites
	TInt err = GetCipherSuitesL();
	
	if (err != KErrNone)
		{
		INFO_PRINTF2(_L("Failed! Cannot retrieve supported cipher suites! (Error %d)"),
			err);
		SetTestStepResult(EFail);
		return TestStepResult();
		}

	// verifies certificate if is not a PSK cipher suite
  	if( !UsePsk() )
		{
			// we have to verify the server certificate, to supply the certificate
		// and its parameters to the TLS provider.

		INFO_PRINTF1(_L("Calling TLS Provider to verify server certificate."));

		CX509Certificate* cert = NULL;

		err = VerifyServerCertificateL(cert);
		delete cert;
		
			// make sure it completed sucessfully.
		if (err != KErrNone)
			{
			INFO_PRINTF2(_L("Failed! Server Certificate did not verify correctly! (Error %d)"),
				err);
			SetTestStepResult(EFail);
			return TestStepResult();
			}
		
		}   
		
	
	INFO_PRINTF1(_L("Creating TLS Session."));	
	
	// now, create a session with the parameters set in the preamble
	err = CreateSessionL();
	
	// ensure we succeeded
	if (err != KErrNone)
		{
		INFO_PRINTF2(_L("Failed! Create Session failed! (Error %d)"), err);
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	
	INFO_PRINTF1(_L("Calling TLS session key exchange."));
	
	HBufC8* keyExMessage = NULL;
	err = ClientKeyExchange(keyExMessage);
	
	if (err != KErrNone)
		{
		INFO_PRINTF2(_L("Failed! Key exchange failed! (Error %d)"), err);
		delete keyExMessage;
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	
	INFO_PRINTF1(_L("Deriving premaster secret."));
	
	// derive the premaster secret from the key exchange method	
	CleanupStack::PushL(keyExMessage);
	HBufC8* premaster = DerivePreMasterSecretL(*keyExMessage);
	CleanupStack::PopAndDestroy(keyExMessage);
	
	INFO_PRINTF1(_L("Deriving master secret."));
	
	// compute the master secret from the premaster.
	CleanupStack::PushL(premaster);
	HBufC8* master = ComputeMasterSecretL(*premaster);
	CleanupStack::PopAndDestroy(premaster);
	CleanupStack::PushL(master);
	
	// create a block of random data to represent our handshake messages,
	// and create hash objects from it.
	
	HBufC8* handshake = HBufC8::NewLC(1024); // totally arbitary length...
	TPtr8 handshakeBuf = handshake->Des();
	handshakeBuf.SetLength(1024);
	TRandom::RandomL(handshakeBuf);
	
	CMessageDigest* handshakeSha = CMessageDigestFactory::NewDigestLC(CMessageDigest::ESHA1);
	CMessageDigest* handshakeMd = CMessageDigestFactory::NewDigestLC(CMessageDigest::EMD5);
	
	handshakeSha->Update(handshakeBuf);
	handshakeMd->Update(handshakeBuf);
	
	INFO_PRINTF1(_L("Computing our test finished message."));
	
	// now, calculate our idea of what the finished message should be.
	HBufC8* ourFinished = ComputeFinishedMessageL(handshakeSha, handshakeMd, *master, ETrue);
	CleanupStack::PushL(ourFinished);
//.........这里部分代码省略.........
开发者ID:cdaffara,项目名称:symbiandump-os2,代码行数:101,代码来源:clientfinishedstep.cpp

示例15: SetTestStepResult

TVerdict CHmacIncrementalHmacWithResetStep::doTestStepL()
	{
	if (TestStepResult()==EPass)
		{
		
		//Assume faliure, unless all is successful
		SetTestStepResult(EFail);
		
		INFO_PRINTF1(_L("*** Hmac - Incremental Hash with Reset ***"));
		INFO_PRINTF2(_L("HEAP CELLS: %d"), User::CountAllocCells());
		
		TVariantPtrC algorithmUid;
		TVariantPtrC operationModeUid;
		TPtrC sourcePath;
		TPtrC expectedHash;
		TPtrC encryptKey;
		TVariantPtrC keyType;
		
		//Extract the Test Case ID parameter from the specified INI file
		if(!GetStringFromConfig(ConfigSection(),KConfigAlgorithmUid,algorithmUid) ||
			!GetStringFromConfig(ConfigSection(),KConfigOperationMode,operationModeUid) ||
			!GetStringFromConfig(ConfigSection(),KConfigSourcePath,sourcePath) ||
			!GetStringFromConfig(ConfigSection(),KConfigExHashHmacValue,expectedHash) ||
			!GetStringFromConfig(ConfigSection(),KConfigEncryptKey,encryptKey) ||
			!GetStringFromConfig(ConfigSection(),KConfigEncryptKeyType,keyType))
			{
			ERR_PRINTF1(_L("** Error: Failed to Load Configuration Parameters **"));
			SetTestStepResult(EFail);
			}
		else
			{
			//Create a pointer for the Hmac Implementation Object
			CHash* hmacImpl = NULL;
			
			//Convert encryption key to an 8 Bit Descriptor
			HBufC8* keyStr = HBufC8::NewLC(encryptKey.Length());
			TPtr8 keyStrPtr = keyStr->Des();
			
			keyStrPtr.Copy(encryptKey);
			
			//Create an new CryptoParams object to encapsulate the key type and secret key string
			CCryptoParams* keyParams = CCryptoParams::NewL();
			CleanupStack::PushL(keyParams);
			keyParams->AddL(*keyStr,keyType);
			
			//Create Key Object
			TKeyProperty keyProperty;
			CKey* key=CKey::NewL(keyProperty,*keyParams);
			CleanupStack::PushL(key);
			
			//Retrieve a Hmac Factory Object			
			TRAPD(err,CHashFactory::CreateHashL(hmacImpl,
												algorithmUid,
												operationModeUid,
												key,
												NULL));											
	
			if(hmacImpl && (err==KErrNone))
				{
				
				//Push the Hmac Implementation Object onto the Cleanup Stack
				CleanupStack::PushL(hmacImpl);
				
				RFs fsSession;
				
				//Create a connection to the file server	
				err = fsSession.Connect();
					
				if(err != KErrNone)
					{
					ERR_PRINTF2(_L("*** Error: File Server Connection - %d ***"), err);
					SetTestStepResult(EFail);
					}	
				else
					{
					RFile sourceFile;
					CleanupClosePushL(sourceFile);
	    			
	    			//Open the specified source file		
	    			err = sourceFile.Open(fsSession,sourcePath, EFileRead);
	    					
	    			if(err != KErrNone)
						{
						ERR_PRINTF2(_L("*** Error: Opening Source File - %d ***"), err);
						SetTestStepResult(EFail);
						}
					else
						{
						
						TInt sourceLength = 0;
						TInt readPosition = 0;
						TInt readIncrement = 0;
						TBool hashComplete = EFalse;
						TBool hashReset = EFalse;
						TPtrC8 hashStr;
						
						User::LeaveIfError(sourceFile.Size(sourceLength));
						
						//Divide the file size into seperate incremental blocks to read
						readIncrement = sourceLength/KDataReadBlocks;
//.........这里部分代码省略.........
开发者ID:cdaffara,项目名称:symbiandump-os2,代码行数:101,代码来源:hmacincrementalhmacwithresetstep.cpp


注:本文中的TPtr8类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。