예제 #1
0
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)
	if (recvCount*iPacketSize[aExtraSocksToJoin] < (0.95*(iPackets[aExtraSocksToJoin]*iPacketSize[aExtraSocksToJoin])))
		{
		iQoSStep->iQoSSuite->Log(_L("The total packets received is less than 95 per cent of the overall packets sent"));
//		return Fail;
		}
	}
예제 #2
0
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);

    //read in Encryption data
    CPBEncryptionData* data = CPBEncryptionData::NewL(read);
    CleanupStack::PopAndDestroy(); //OpenLC()
    CleanupStack::PushL(data);

    //read in encrypted master key
    read.OpenLC(*store, keyStreamId);
    HBufC8* encryptedMasterKey = HBufC8::NewLC(read, 10000); //some large number

    //create a new set encryption class
    CPBEncryptSet* set2 = CPBEncryptSet::NewLC(*data, *encryptedMasterKey, newPassword);

    HBufC8* plaintextTemp = HBufC8::NewLC(ciphertext.Length());
    TPtr8 plaintext = plaintextTemp->Des();

    CPBDecryptor* decryptor = set2->NewDecryptLC();
    decryptor->Process(ciphertext, plaintext);

    //this Mid call is due to get rid of the decrypted padding at the end
    if(plaintext.Mid(0,iInput->Length()) == *iInput)
    {
        iResult = ETrue;
    }

    CleanupStack::PopAndDestroy(decryptor);
    CleanupStack::PopAndDestroy(plaintextTemp);
    CleanupStack::PopAndDestroy(set2);
    CleanupStack::PopAndDestroy(encryptedMasterKey);
    CleanupStack::PopAndDestroy(1); //OpenLC
    CleanupStack::PopAndDestroy(data);
    CleanupStack::PopAndDestroy(store);
    CleanupStack::PopAndDestroy(ciphertextTemp);
    CleanupStack::PopAndDestroy(encryptor);
    CleanupStack::PopAndDestroy(set);
    CleanupStack::PopAndDestroy(pkcs12Pwd);

    User::RequestComplete(status, KErrNone);
    iActionState = CTestAction::EPostrequisite;
    __UHEAP_MARKEND;
}
예제 #3
0
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
    	iPayloadizedBuffers.InsertL( pBuffer, iNalCount );
    	iNalCount++;
    	CleanupStack::Pop( pBuffer );
    	pBuffer = NULL; // ownership transferred
    	
    	fragsPacketized++; // to count the number of fragments
	
	    } // end while()
	
	aNalCount = iNalCount;
    }
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);			
		}
	} 
	else 
	{
		// Could not find parameter
		EAP_TRACE_DEBUG(
			m_am_tools,
			TRACE_FLAGS_DEFAULT,
			(EAPL("ERROR: read_configureL: Could not find configuration parameter.\n")));
		User::Leave(m_am_tools->convert_eapol_error_to_am_error(
							EAP_STATUS_RETURN(m_am_tools, eap_status_not_found)));
	}		
	
	// Close database
	CleanupStack::PopAndDestroy(&view);
	CleanupStack::PopAndDestroy(buf);
	CleanupStack::PopAndDestroy(unicodebuf);
	CleanupStack::PopAndDestroy(asciibuf);
	CleanupStack::PopAndDestroy(&db);


	EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
}
EXPORT_C TInt CMTPTypeOpaqueData::NextWriteChunk(TPtr8& aChunk)
    {
    aChunk.Set(NULL, 0, 0);
    return KErrNotReady;
    }
/**
@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);
			if(queryType.FindF(_L("INSERT")) >= 0)
				{
				++insertCnt;
				++insertTrnCnt;
				}
			else if(queryType.FindF(_L("UPDATE")) >= 0)
				{
				++updateCnt;
				++updateTrnCnt;
				}
			else if(queryType.FindF(_L("SELECT")) >= 0)
				{
				++selectCnt;
				++selectTrnCnt;
				}
			}
		}
	delete sqlBuf;
	
	TheDbC.Close();
	
	TheTest.Printf(_L("Total time to process Songs: %d us\n"), totalTime);
	TheTest.Printf(_L("Transactions count: %d, \"INSERT\" count: %d, \"UPDATE\" count: %d, \"SELECT\" count: %d\n"), 
			               trnCnt, insertCnt, updateCnt, selectCnt);
	TEST2(recordCount, KRecordCount);
	}
예제 #7
0
// ---------------------------------------------------------
// 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;
		}
	TInt entryID = 0;
	TBool statusIsMatching;
	statusIsMatching = iResponseController->MatchStatusElement( msgRef, *cmdRef , numericStatus, entryID );
	if ( !statusIsMatching )
		{
		}
	else
		{
		// chal element is stored for later use 
		if ( aStatus->chal )
			{
			if ( aStatus->chal->meta )
				{
				if ( aStatus->chal->meta->content && aStatus->chal->meta->contentType == SML_PCDATA_EXTENSION && aStatus->chal->meta->extension == SML_EXT_METINF )
					{
					SmlMetInfMetInf_t* metInf;
					metInf = (SmlMetInfMetInf_t*) aStatus->chal->meta->content;
					if ( metInf->type )
						{
						if ( metInf->type->content ) 
							{
							TPtr8 chalType( (TUint8*) metInf->type->content, metInf->type->length, metInf->type->length ); 
							TrimRightSpaceAndNull( chalType );
							if ( chalType.Length() > 0 )
								{
								iResponseController->SetChalTypeL( entryID, chalType );
								}
							}
						}
					if ( metInf->format )
						{
						if ( metInf->format->content )
							{
							TPtr8 chalFormat( (TUint8*) metInf->format->content, metInf->format->length, metInf->format->length ); 
							TrimRightSpaceAndNull( chalFormat );
							if ( chalFormat.Length() > 0 )
								{
								iResponseController->SetChalFormatL( entryID, chalFormat );
								}
							else
								{
								iResponseController->SetChalFormatL( entryID, KNSmlAgentChrFormat );
								}
							}
						else
							{
							iResponseController->SetChalFormatL( entryID, KNSmlAgentChrFormat );
							}
						}
					else
						{
						iResponseController->SetChalFormatL( entryID, KNSmlAgentChrFormat );
						}
					if ( metInf->nextnonce )
						{
						if ( metInf->nextnonce->content )
							{
							TPtr8 chalNextNonce( (TUint8*) metInf->nextnonce->content, metInf->nextnonce->length, metInf->nextnonce->length );
							TrimRightSpaceAndNull( chalNextNonce );
							if ( chalNextNonce.Length() > 0 )
								{
								iResponseController->SetChalNextNonceL( entryID, chalNextNonce );
								}
							}
						}
					}
				}
			}
		}
	CleanupStack::PopAndDestroy(); //cmdRef
	if ( statusIsMatching )
		{
		iAgent->CheckServerStatusCodeL( entryID );
		}
	}
예제 #8
0
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
}
/**
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());
			iObserver.OnSuplInit(iChannel, reqIdUnsgn , msgPtr);
			LBSLOG(ELogP9, "<-S MLbsSuplPushRecObserver::OnSuplInit() SuplPush\n");
			LBSLOG2(ELogP9, "  > TLbsSuplPushChannel aChannel = %d\n", iChannel);
			LBSLOG2(ELogP9, "  > TLbsSuplPushRequestId aReqId = %d\n", reqIdUnsgn);
			
			}
						
		delete msg;
		}
	else
		{
		iInitProperty.Subscribe(iStatus);
		SetActive();
		}
	LBSLOG(ELogP1, "CLbsSuplPushRecChannel::RunL() End\n");
	}
//
// Completion callback.
//
void CIoqueueCallback::RunL()
{
    pj_ioqueue_t *ioq = ioqueue_;
    Type cur_type = type_;

    type_ = TYPE_NONE;

    if (cur_type == TYPE_READ) {
	//
	// Completion of asynchronous RecvFrom()
	//

	/* Clear op_key (save it to temp variable first!) */
	pj_ioqueue_op_key_t	*op_key = pending_data_.read_.op_key_;
	pending_data_.read_.op_key_ = NULL;

	// Handle failure condition
	if (iStatus != KErrNone) {
	    if (cb_.on_read_complete) {
	    	cb_.on_read_complete( key_, op_key, 
				      -PJ_RETURN_OS_ERROR(iStatus.Int()));
	    }
	    return;
	}

	HandleReadCompletion();

	/* Call callback */
	if (cb_.on_read_complete) {
	    cb_.on_read_complete(key_, op_key, aBufferPtr_.Length());
	}

    } else if (cur_type == TYPE_ACCEPT) {
	//
	// Completion of asynchronous Accept()
	//
	
	/* Clear op_key (save it to temp variable first!) */
	pj_ioqueue_op_key_t	*op_key = pending_data_.read_.op_key_;
	pending_data_.read_.op_key_ = NULL;

	// Handle failure condition
	if (iStatus != KErrNone) {
	    if (pending_data_.accept_.new_sock_)
		*pending_data_.accept_.new_sock_ = PJ_INVALID_SOCKET;
	    
	    if (cb_.on_accept_complete) {
	    	cb_.on_accept_complete( key_, op_key, PJ_INVALID_SOCKET,
				        -PJ_RETURN_OS_ERROR(iStatus.Int()));
	    }
	    return;
	}

	CPjSocket *pjNewSock = HandleAcceptCompletion();
	
	// Call callback.
	if (cb_.on_accept_complete) {
	    cb_.on_accept_complete( key_, op_key, (pj_sock_t)pjNewSock, 
				    PJ_SUCCESS);
	}
    }

    ioq->eventCount++;
}
예제 #11
0
///////////////////////////////////////////////////////////////////
//  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;

    }
예제 #12
0
// -----------------------------------------------------------------------------
// 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 ); 
				}
			CleanupStack::Pop(); // listData
			break;
			}
		case EBSBuffer:
			{
			TInt bufferSize = aStream.ReadInt16L();
			HBufC8* buffeData = HBufC8::NewLC( bufferSize );

			TPtr8 bufferPtr = buffeData->Des();
			aStream.ReadL( bufferPtr, bufferSize );

			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
																  EBSBuffer,
																  *buffeData ); 
				}

			CleanupStack::PopAndDestroy( buffeData );
			break;
			}
		case EBSBitmap:
			{
			TInt length = aStream.ReadInt16L();
			HBufC8* fileId = HBufC8::NewLC( length );
			
			TPtr8 fileIdPtr = fileId->Des();
			aStream.ReadL( fileIdPtr, length );
			
			TInt bitmapId = aStream.ReadInt16L();
			TInt maskId = aStream.ReadInt16L();
			TInt skinId = aStream.ReadInt16L();
			TInt skinMaskId = aStream.ReadInt16L();

			TRACE( T_LIT( "CBSBrandHandler::ReadStreamL type BITMAP .. bitmap ID is [%d]"), bitmapId);
			if( match )
				{
				CBSBitmap* bitmap = CBSBitmap::NewLC( bitmapId,
													  maskId,
													  skinId,
													  skinMaskId,
													  fileIdPtr );

                // 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
																  EBSBitmap,
																  bitmap ); 
				CleanupStack::Pop( bitmap ); 
				}
		    CleanupStack::PopAndDestroy( fileId ); 

			break;
			}
		default:
			{
			TRACE( T_LIT( "CBSBrandHandler::ReadStreamL type DEFAULT : corrupt"));
			User::Leave( KErrCorrupt );
			break;
			}
		}

	if( elementId )
		{
		CleanupStack::PopAndDestroy( elementId );
		}

	TRACE( T_LIT( "CBSBrandHandler::ReadStreamL END"));
	return returnValue;
	}
예제 #13
0
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;

					// Advance to the last byte of data in this header
                    index += consumed + value;
					}
                else
					// Codes 32-127 are alphanumerics representing a text
					// string, up to a NUL termination
                    if (byteCode <= 127)
						// Hit the start of a 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;
                }
            }
        }

	// This return only occurs if the search ran off the end of the header
    return KErrNotFound;
    }
예제 #14
0
EXPORT_C TBool CHTTPResponse::CharSet(TPtrC8& aDesc) const
    {
//	__LOG_ENTER(_L("CHTTPResponse::CharSet"));
	// Find the byte index in the header for the content type value
    TInt index = LocateField(EHttpContentType);

    TUint8 byteCode = 0;
	TInt paramByteCode = KErrNotFound;
	TInt valueByteCode1 = KErrNotFound;
	TInt charsetCode = 0;
	// Read the byte code, unless KErrNotFound was returned
	if (index != KErrNotFound)
		{
		TPtr8 respChars = iResponse->Des();
		TInt respLength = iResponse->Length();

		// If the byteCode is in the range 0-30 then a range of bytes is
		// indicated: the following byte gives the content type and the
		// remainder are arranged as a series of parameter attribute-value
		// pairs. This method checks for the presence of a 'charset' parameter.
		byteCode = respChars[index];
//		__LOG1(_L("CHTTPResponse::CharSet : found bytecode = %d"), byteCode);

		// Check valid range ... note that a range of zero could not contain a charset
		// parameter anyway, so exclude it...
		if ((byteCode > 0) && (byteCode <= 30))
			{
			// Check for overrun... if this occurs it should be an error.  Note that
			// corruption _could_ occur in this response buffer - some gateways, which
			// don't return error decks (e.g. AnyTime GW) send a response buffer 1 byte
			// long, containing only the value 0x01 - which is invalid WSP.
			// Be conservative and safe here - we can't overrun.  Use the value of byte-
			// -Code (which should be the WSP encoding of how many bytes follow), or the
			// total length of the response - whichever is smaller.
			if (index + byteCode < respLength)
				{
				// e,g, header to illustrate use of offsets in this code:
				// 03 94 81 84 : Content-Type: application/vnd.wap.wmlc; charset=iso-8859-1
				// +0 +1 +2 +3 : 03 = no. bytes in Content-Type header
				//			   : 94 = 14 | 80 = application/vnd.wap.wmlc
				//			   : 81 = 01 | 80 = Charset parameter
				//			   : 84 = 04 | 80 = iso-8859-1
				paramByteCode = respChars[index + 2];

				if ((paramByteCode & 0x7f) == EHttpCharset)
					{
					// We have a charset
					paramByteCode &= 0x7f;
					valueByteCode1 = respChars[index + 3];

					if (valueByteCode1 & 0x80)
						{
						// A short one-byte value
						charsetCode = valueByteCode1 & 0x7f;
						}
					else
						{
						// A multibyte value
						ExtractMultiOctetInteger(charsetCode, 
												 respChars.Mid(index + 3));
						}
					}
				}
			else
				{
				index = KErrNotFound;
				}
			}
		}

	// If a parameter-value pair was found, determine whether it encodes a
	// charset
	if ( (index != KErrNotFound) && (paramByteCode == EHttpCharset) )
		{
		// Look up the value from the charset table.
		const TText8* chset;
		chset = CharSet(charsetCode);

		// Convert the charset string to the supplied descriptor
		if (chset)
			aDesc.Set(TPtrC8(chset));
		else
			index = KErrNotFound; // We've found a charset but we don't recognise it
		}
	else	// Either no content-type header (hence no charset) or a content-type
			// header with a parameter other than charset
		{
		index = KErrNotFound;
		}

//	__LOG1(_L("CHTTPResponse::CharSet : CharSet = %S"), &aDesc);
//	__LOG_RETURN;
	return (index !=KErrNotFound);
    }
예제 #15
0
/**
 *  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);
	}
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);
	
	INFO_PRINTF1(_L("Calling TLS Session to generate client finished message."));
	
	// ask TLS provider for our finished message and compare the two.
	HBufC8* theirFinished = NULL;
	err = GenerateClientFinishedL(handshakeSha, handshakeMd, theirFinished);
	if (err != KErrNone || *theirFinished != *ourFinished)
		{
		INFO_PRINTF2(_L("Failed! Either client finished message generation failed (Error %d), or finished message malformed!"),
			err);
		SetTestStepResult(EFail);
		}
	else
		{
		INFO_PRINTF1(_L("Test passed."));
		SetTestStepResult(EPass);
		}
	delete theirFinished;
	CleanupStack::PopAndDestroy(5, master);	// handshake, handshakeSha, handshakeMd, ourFinished
		
	return TestStepResult();
	}
예제 #17
0
/**
 *  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
 */
void CEmsPreDefSoundIE::EncodeBodyL(TPtr8 aPtr, TBool) const
	{
	aPtr.Append(static_cast<TUint8>(iSound));
	}
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;
						
						do 
							{
							//Create a heap based descriptor to store the data
							HBufC8* sourceData = HBufC8::NewL(readIncrement);
							CleanupStack::PushL(sourceData);
							TPtr8 sourcePtr = sourceData->Des();
							
							//Read in a block of data from the source file from the current position
							err = sourceFile.Read(readPosition,sourcePtr,readIncrement);
							
							//Update the read position by adding the number of bytes read
							readPosition += readIncrement;
							
							if(readPosition == readIncrement)
								{
								//Read in the first block from the data file into the Hmac implementation object
								hmacImpl->Hash(*sourceData);
								INFO_PRINTF2(_L("Intial Hmac - Bytes Read: %d"), readPosition);
								}
							else if(readPosition >= sourceLength)
								{
								//Reading in the final block, constructs the complete hash value and returns it within a TPtrC8
								hashStr.Set(hmacImpl->Final(*sourceData));
								
								//Sets the Complete Flag to ETrue in order to drop out of the loop
								hashComplete = ETrue;
								
								TInt totalRead = (readPosition - readIncrement) + (*sourceData).Length();
								INFO_PRINTF2(_L("Final Hmac - Bytes Read: %d"),totalRead);
								}
							//If the read position is half the source length and the implementation
							//object hasn't already been reset
							else if((readPosition >= sourceLength/2) && (hashReset == EFalse))
								{
								INFO_PRINTF1(_L("Resetting Hmac Object..."));
								
								hmacImpl->Reset();
								
								//Sets the read position back to 0 inorder to restart the file read from the beginning
								readPosition = 0;
								
								hashReset = ETrue;
								
								INFO_PRINTF2(_L("*** HMAC RESET - Bytes Read: %d ***"), readPosition);
								}
							else
								{
								//Update the message data within the Hmac object with the new block
								hmacImpl->Update(*sourceData);
								INFO_PRINTF2(_L("Hmac Update - Bytes Read: %d"), readPosition);	
								}
							
							CleanupStack::PopAndDestroy(sourceData);
								
							}while(hashComplete == EFalse);
							
						//Create a NULL TCharacteristics pointer
						const TCharacteristics* charsPtr(NULL);
						
						//Retrieve the characteristics for the hash implementation object
						TRAP_LOG(err, hmacImpl->GetCharacteristicsL(charsPtr));
						
						//Static cast the characteristics to type THashCharacteristics
						const THashCharacteristics* hashCharsPtr = static_cast<const THashCharacteristics*>(charsPtr);
						
						//The hash output size is returned in Bits, divide by 8 to get the Byte size
						TInt hashSize = hashCharsPtr->iOutputSize/8;
						
						//Retrieve the final 8bit hash value and convert to 16bit												
						HBufC* hashData = HBufC::NewLC(hashSize);
						TPtr hashPtr = hashData->Des();
						
						hashPtr.Copy(hashStr);
						
						//Take the 16bit descriptor and convert the string to hexadecimal
						TVariantPtrC convertHash;
						convertHash.Set(hashPtr);
						HBufC* hmacResult = convertHash.HexStringLC();								
						
						INFO_PRINTF2(_L("*** Hashed Data: %S ***"),&*hmacResult);
						INFO_PRINTF2(_L("*** Expected Hash: %S ***"),&expectedHash);
						
						//If the returned hash value matches the expected hash, Pass the test	
						if(*hmacResult == expectedHash)
							{
							INFO_PRINTF1(_L("*** Hmac - Incremental Hash with Reset : PASS ***"));
							SetTestStepResult(EPass);	
							}
						else
							{
							ERR_PRINTF2(_L("*** FAIL: Hashed and Expected Value Mismatch  ***"), err);
							SetTestStepResult(EFail);	
							}
													
						CleanupStack::PopAndDestroy(hmacResult);
						CleanupStack::PopAndDestroy(hashData);
						}
						
					//Cleanup the Source RFile	
					CleanupStack::PopAndDestroy();	
					}

				fsSession.Close();
				
				CleanupStack::PopAndDestroy(hmacImpl);	
				}
			else
				{
				ERR_PRINTF2(_L("*** FAIL: Failed to Create Hmac Object - %d ***"), err);
				SetTestStepResult(EFail);	
				}
			
			CleanupStack::PopAndDestroy(key);
			CleanupStack::PopAndDestroy(keyParams);	
			CleanupStack::PopAndDestroy(keyStr);
			}
		}
		
	INFO_PRINTF2(_L("HEAP CELLS: %d"), User::CountAllocCells());
	return TestStepResult();
	}
TVerdict CHmacSetOperationModeCheckingStep::doTestStepL()
	{
	if (TestStepResult()==EPass)
		{
		
		//Assume faliure, unless all is successful
		SetTestStepResult(EFail);
		
		INFO_PRINTF1(_L("*** Hmac - Set Operation Mode Checking ***"));
		INFO_PRINTF2(_L("HEAP CELLS: %d"), User::CountAllocCells());
		
		TVariantPtrC algorithmUid;
		TVariantPtrC operationModeUid;
		TVariantPtrC secondOperationModeUid;
		TPtrC sourcePath;
		TPtrC expectedHash;
		TPtrC expectedHmac;
		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(),KConfigSecondOperationMode,secondOperationModeUid) ||
			!GetStringFromConfig(ConfigSection(),KConfigSourcePath,sourcePath) ||
			!GetStringFromConfig(ConfigSection(),KConfigExHashHmacValue,expectedHash) ||
			!GetStringFromConfig(ConfigSection(),KConfigExSecondHashHmacValue,expectedHmac) ||
			!GetStringFromConfig(ConfigSection(),KConfigEncryptKey,encryptKey) ||
			!GetStringFromConfig(ConfigSection(),KConfigEncryptKeyType,keyType))
			{
			ERR_PRINTF1(_L("** Error: Failed to Load Configuration Parameters **"));
			SetTestStepResult(EFail);
			}
		else
			{	
			RFs fsSession;
				
			//Create a connection to the file server	
			User::LeaveIfError(fsSession.Connect());
						
			RFile sourceFile;
	    	CleanupClosePushL(sourceFile);
	    			
	    	//Open the specified source file		
	    	User::LeaveIfError(sourceFile.Open(fsSession,sourcePath, EFileRead));
	    					
			TInt sourceLength = 0;
			User::LeaveIfError(sourceFile.Size(sourceLength));
						
			//Create a heap based descriptor to store the data
			HBufC8* sourceData = HBufC8::NewL(sourceLength);						
			CleanupStack::PushL(sourceData);
			TPtr8 sourcePtr = sourceData->Des();
						
			sourceFile.Read(sourcePtr);
							
			if(sourcePtr.Length() != sourceLength)
				{
				ERR_PRINTF1(_L("*** Error: Reading Source File ***"));
				SetTestStepResult(EFail);	
				}
			else
				{
				//Create a pointer for the Hash + Key (Hmac) Implementation Object
				CHash* hashHmacImpl = 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 invalid key type and key string
				CCryptoParams* keyParams = CCryptoParams::NewL();
				CleanupStack::PushL(keyParams);
				keyParams->AddL(*keyStr,keyType);
				
				//Create a valid CKey Object
				TKeyProperty keyProperty;
				CKey* key = CKey::NewL(keyProperty,*keyParams);
				CleanupStack::PushL(key);
				
				//Construct an initial hash object with NO key, Catching any possible Leaves			
				TRAPD(err,CHashFactory::CreateHashL(
									hashHmacImpl,
									algorithmUid,
									operationModeUid,
									NULL,
									NULL));
									
										
				if(hashHmacImpl && (err == KErrNone))
					{
					
					//Push the Implementation Object onto the Cleanup Stack
					CleanupStack::PushL(hashHmacImpl);
					
					//Create a NULL TCharacteristics pointer
					const TCharacteristics* charsPtrA(NULL);
					
					//Retrieve the characteristics for the hash implementation object
					TRAP_LOG(err, hashHmacImpl->GetCharacteristicsL(charsPtrA));
					
					//Static cast the characteristics to type THashCharacteristics
					const THashCharacteristics* hashCharsPtrA = static_cast<const THashCharacteristics*>(charsPtrA);
					
					//The hash output size is returned in Bits, divide by 8 to get the Byte size
					TInt hashSize = hashCharsPtrA->iOutputSize/8;
					
					//Retrieve the final 8bit hash value and convert to 16bit												
					HBufC* hashDataA = HBufC::NewLC(hashSize);
					TPtr hashPtrA = hashDataA->Des();
					
					hashPtrA.Copy(hashHmacImpl->Hash(*sourceData));
					
					//Take the 16bit descriptor and convert the string to hexadecimal
					TVariantPtrC convertHash;
					convertHash.Set(hashPtrA);
					
					HBufC* resultA = convertHash.HexStringLC();							
						
					INFO_PRINTF2(_L("*** Hashed Data: %S ***"),&*resultA);
					INFO_PRINTF2(_L("*** Expected Hash: %S ***"),&expectedHash);
					
					if(*resultA == expectedHash)
						{
						INFO_PRINTF1(_L("*** PRIMARY HASH VALID - STAGE 1 PASS ***"));
						
						//Set the valid key within the Hmac Implementation Object
						TRAP(err,hashHmacImpl->SetKeyL(*key));
						
						if(err!=KErrNone)
							{
							ERR_PRINTF2(_L("*** ERROR %d: Setting Key ***"),err);
							User::Leave(err);	
							}
						else
							{
							INFO_PRINTF1(_L("*** HMAC KEY SET ***"));	
							}
										
						//Set the Operation Mode of the Hmac Implementation Object
						hashHmacImpl->SetOperationModeL(secondOperationModeUid);
						
						if(err!=KErrNone)
							{
							ERR_PRINTF3(_L("*** ERROR %d: Setting Operation Mode %S ***"),err,&secondOperationModeUid);	
							User::Leave(err);
							}
						else
							{
							INFO_PRINTF2(_L("*** OPERATION MODE SET : %S ***"),&secondOperationModeUid);	
							}
						
						//Create a NULL TCharacteristics pointer
						const TCharacteristics* charsPtrB(NULL);
					
						//Retrieve the characteristics for the hash implementation object
						TRAP_LOG(err, hashHmacImpl->GetCharacteristicsL(charsPtrB));
					
						//Static cast the characteristics to type THashCharacteristics
						const THashCharacteristics* hashCharsPtrB = static_cast<const THashCharacteristics*>(charsPtrB);
						
						//The hash output size is returned in Bits, divide by 8 to get the Byte size
						hashSize = hashCharsPtrB->iOutputSize/8;
						
						//Retrieve the final 8bit hash value and convert to 16bit												
						HBufC* hashDataB = HBufC::NewLC(hashSize);
						TPtr hashPtrB = hashDataB->Des();
						
						hashPtrB.Copy(hashHmacImpl->Hash(*sourceData));
						
						//Take the 16bit descriptor and convert the string to hexadecimal
						convertHash.Set(hashPtrB);
						HBufC* resultB = convertHash.HexStringLC();						
						
						INFO_PRINTF2(_L("*** Hashed Data: %S ***"),&*resultB);
						INFO_PRINTF2(_L("*** Expected Hash: %S ***"),&expectedHmac);
						
						if(*resultB == expectedHmac)
							{
							INFO_PRINTF1(_L("*** SECONDARY HASH VALID - STAGE 2 PASS ***"));
							
							//Set the Operation Mode of the Hmac Implementation Object
							TRAP(err,hashHmacImpl->SetOperationModeL(operationModeUid));
							
							if(err!=KErrNone)
								{
								ERR_PRINTF3(_L("*** ERROR %d: Setting Operation Mode %S ***"),err,&operationModeUid);	
								User::Leave(err);
								}
							else
								{
								INFO_PRINTF2(_L("*** OPERATION MODE SET : %S ***"),&operationModeUid);	
								}
								
							//Create a NULL TCharacteristics pointer
							const TCharacteristics* charsPtrC(NULL);
						
							//Retrieve the characteristics for the hash implementation object
							TRAP_LOG(err, hashHmacImpl->GetCharacteristicsL(charsPtrC));
						
							//Static cast the characteristics to type THashCharacteristics
							const THashCharacteristics* hashCharsPtrC = static_cast<const THashCharacteristics*>(charsPtrC);
							
							//The hash output size is returned in Bits, divide by 8 to get the Byte size
							hashSize = hashCharsPtrC->iOutputSize/8;
							
							//Retrieve the final 8bit hash value and convert to 16bit												
							HBufC* hashDataC = HBufC::NewLC(hashSize);
							TPtr hashPtrC = hashDataC->Des();
							
							hashPtrC.Copy(hashHmacImpl->Hash(*sourceData));
							
							//Take the 16bit descriptor and convert the string to hexadecimal
							convertHash.Set(hashPtrC);
							HBufC* resultC = convertHash.HexStringLC();							
							
							INFO_PRINTF2(_L("*** Hashed Data: %S ***"),&*resultC);
							INFO_PRINTF2(_L("*** Expected Hash: %S ***"),&expectedHash);
									
							if(*resultC == expectedHash)
								{
								INFO_PRINTF1(_L("*** FINAL HASH VALID - STAGE 3 PASS ***"));
								INFO_PRINTF1(_L("*** Hmac - Set Operation Mode Checking : PASS ***"));
								SetTestStepResult(EPass);
								}
							else
								{
								ERR_PRINTF1(_L("*** STAGE 3 FAIL: Hash and Expected Value Mismatch ***"));
								SetTestStepResult(EFail);	
								}
								
							CleanupStack::PopAndDestroy(resultC);
							CleanupStack::PopAndDestroy(hashDataC);
							}
						else
							{
							ERR_PRINTF1(_L("*** STAGE 2 FAIL: Hash and Expected Value Mismatch ***"));
							SetTestStepResult(EFail);	
							}
							
						CleanupStack::PopAndDestroy(resultB);
						CleanupStack::PopAndDestroy(hashDataB);	
						}
					else
						{
						ERR_PRINTF1(_L("*** STAGE 1 FAIL: Hash and Expected Value Match ***"));
						SetTestStepResult(EFail);	
						}
						
					CleanupStack::PopAndDestroy(resultA);
					CleanupStack::PopAndDestroy(hashDataA);
					CleanupStack::PopAndDestroy(hashHmacImpl);										
					}
				else if(err==KErrNotSupported)
					{
					if((((TUid)operationModeUid != KHashModeUid) && ((TUid)operationModeUid != KHmacModeUid)) ||
						((TUid)algorithmUid != KMd2Uid) && (TUid)algorithmUid != KMd5Uid && (TUid)algorithmUid != KSha1Uid && (TUid)algorithmUid != KMd4Uid && (TUid)algorithmUid != KSha224Uid && (TUid)algorithmUid != KSha256Uid && (TUid)algorithmUid != KSha384Uid && (TUid)algorithmUid != KSha512Uid)
						{
						ERR_PRINTF2(_L("*** Object Load Failure - Invalid Operation Mode : %d ***"), err);
						User::Leave(err);	
						}
					else
						{
						SetTestStepResult(EFail);	
						}
					}
				else
					{
					ERR_PRINTF2(_L("*** Hash/Hmac Facotry Object Load Failure : %d ***"), err);
					User::Leave(err);	
					}
					
				CleanupStack::PopAndDestroy(key);
				CleanupStack::PopAndDestroy(keyParams);
				CleanupStack::PopAndDestroy(keyStr);
				}
							
			CleanupStack::PopAndDestroy(sourceData);
								
			//Cleanup the Source RFile	
			CleanupStack::PopAndDestroy();	
						
			fsSession.Close();	
			}
			
		}
		else
		{
			SetTestStepResult(EFail);	
		}		
		
	INFO_PRINTF2(_L("HEAP CELLS: %d"), User::CountAllocCells());	
	
	return TestStepResult();
	}
// -----------------------------------------------------------------------------
// CNSmlDsProvisioningAdapter::SaveL
// -----------------------------------------------------------------------------
void CNSmlDsProvisioningAdapter::SaveL(TInt aItem)
	{
	_DBG_FILE("CNSmlDsProvisioningAdapter::SaveL(): begin");
	TPckgBuf<TUint32> uid;
	
	RSyncMLDataSyncProfile profile;
	TBool ret = EFalse;
	
	if(iProfiles[aItem]->iServerId != NULL)
	{
	RSyncMLDataSyncProfile ProfileToSearch;
	RArray<TSmlProfileId> arr;
    iSession.ListProfilesL( arr, ESmlDataSync );
    
    TInt ProfileId = KErrNotFound;
    CleanupClosePushL(arr);   	
	for ( TInt index = 0; index < arr.Count(); index++ )
		{
	    TRAPD( error, ProfileToSearch.OpenL(iSession, arr[index], ESmlOpenRead ) );
	    if ( error == KErrNone )
	        {	            	            	        
    	        if ( ( iProfiles[aItem]->iServerId->Des()).Compare(ProfileToSearch.ServerId() ) == 0 )
    	            {
    	            
                    ret = ETrue;                    
                    ProfileId = (TInt)arr[index];
                    ProfileToSearch.Close();
                    break;
                    }	            		    
	        }
	      ProfileToSearch.Close();  
		}
    CleanupStack::PopAndDestroy( &arr );
	
	if( ret )
		{
		profile.OpenL(iSession, ProfileId , ESmlOpenReadWrite );	
		}
	else
		{
	profile.CreateL( iSession );
		}
	CleanupClosePushL( profile );	
	}
	else
	{
		
		profile.CreateL( iSession );
		CleanupClosePushL( profile );	
	}
	
	// ui needs this to be set 0
	profile.SetCreatorId(0);//iProfiles[aItem]->iProfile.SetCreatorId(0);
	profile.SetSanUserInteractionL( iProfiles[aItem]->iServerAlertedAction );
	
	if ( iProfiles[aItem]->iDisplayName )
	    {
	    profile.SetDisplayNameL( iProfiles[aItem]->iDisplayName->Des() );    
	    }
	
	if ( iProfiles[aItem]->iServerId )
	    {
	    profile.SetServerIdL( iProfiles[aItem]->iServerId->Des() );    
	    }
	    
	if ( iProfiles[aItem]->iUsername )   
	    {
	    profile.SetUserNameL( iProfiles[aItem]->iUsername->Des() );    
	    }
	
	if ( iProfiles[aItem]->iPassword )
	    {
	    profile.SetPasswordL( iProfiles[aItem]->iPassword->Des() );    
	    }
	    
	// creates profile -> must be done before opening the connection
	profile.UpdateL();
		
	RSyncMLConnection connection;
	connection.OpenL( profile, KUidNSmlMediumTypeInternet.iUid );
	CleanupClosePushL( connection );
		
    if ( (iProfiles[aItem]->iVisitParameter
            && iProfiles[aItem]->iVisitParameter->Data().Length() == uid.MaxLength() )
            || iToNapIDInternetIndicator)
		{
        TUint apId = 0;
        TInt ERROR = KErrNone;
        TInt err1 = KErrNone;

        if (iToNapIDInternetIndicator)
            {
            //Get Access Point from DB or SNAP
            TRAP(err1, apId = WPAdapterUtil::GetAPIDL());
            }

        else
            {
            uid.Copy(iProfiles[aItem]->iVisitParameter->Data() );

            RCmManagerExt  cmmanagerExt;
		    cmmanagerExt.OpenL();
		    CleanupClosePushL(cmmanagerExt);
		    RCmConnectionMethodExt cm;
		    cm = cmmanagerExt.ConnectionMethodL( uid());
		    CleanupClosePushL( cm );

            TRAP( ERROR, apId = cm.GetIntAttributeL(CMManager::ECmIapId) );
            CleanupStack::PopAndDestroy(2); //cmmanager,cm
            }

        //Get default access point in failure of getting AP
        if (ERROR != KErrNone || err1 != KErrNone)
			{
			apId = GetDefaultIAPL();
			}
		
		HBufC8* iapBuf = HBufC8::NewLC( 8 );
		TPtr8 ptrBuf = iapBuf->Des();
		ptrBuf.Num( apId );
		
		connection.SetPropertyL( KNSmlIAPId, *iapBuf );
			
        CleanupStack::PopAndDestroy(); //iapBuf	
		}
		
	if( iProfiles[aItem]->iHostAddress )
		{
		// see if address contains also port
		TBool portFound = EFalse;
		TInt startPos(0);
		if(iProfiles[aItem]->iHostAddress->Find(KNSmlDsProvisioningHTTP)==0)
		    {
		    startPos=KNSmlDsProvisioningHTTP().Length();		    		    
		    }
		else if(iProfiles[aItem]->iHostAddress->Find(KNSmlDsProvisioningHTTPS)==0)
		    {
		    startPos=KNSmlDsProvisioningHTTPS().Length();		    		    
		    }
		TPtrC uriPtr = iProfiles[aItem]->iHostAddress->Mid(startPos);
		
		if(uriPtr.Locate(KNSmlDMColon)!=KErrNotFound)
		    {
			portFound = ETrue;
		    }
	
		if( portFound == EFalse )
			{
			HBufC *uri = 0;
			// port not found from URI -> see if it is given separately				
			if( iProfiles[aItem]->iPort )
				{
				// parse address and port into URI
			
				if( CombineURILC( iProfiles[aItem]->iHostAddress->Des(),
							  iProfiles[aItem]->iPort->Des(), uri ) == KErrNone )
					{
					if(iProfiles[aItem]->iHostAddress)
					{
						delete iProfiles[aItem]->iHostAddress;
						iProfiles[aItem]->iHostAddress = NULL;
					}
					iProfiles[aItem]->iHostAddress = uri->Des().AllocL();
					}
				CleanupStack::PopAndDestroy(); // uri		  
				}
			else
				{
				// use default port
				if( CombineURILC( iProfiles[aItem]->iHostAddress->Des(),
							  KNSmlDsDefaultPort(), uri ) == KErrNone )
					{
					if(iProfiles[aItem]->iHostAddress)
					{
						delete iProfiles[aItem]->iHostAddress;
						iProfiles[aItem]->iHostAddress = NULL;
					}
					iProfiles[aItem]->iHostAddress = uri->Des().AllocL();
					}
				CleanupStack::PopAndDestroy(); // uri		  
				}
			}
		

		connection.SetServerURIL( ConvertTo8LC( iProfiles[aItem]->iHostAddress->Des() ) );
		CleanupStack::PopAndDestroy(); // ConvertTo8LC
		}
		
	// set authtype, HTTPUserName, HTTPPassword
	if( iProfiles[aItem]->iHTTPUserName ||
	    iProfiles[aItem]->iHTTPPassword )
		{
		connection.SetPropertyL( KNSmlHTTPAuth, KNSmlTrueVal );
		
		if( iProfiles[aItem]->iHTTPUserName )
			{
			connection.SetPropertyL( KNSmlHTTPUsername, iProfiles[aItem]->iHTTPUserName->Des() );
			}
		if( iProfiles[aItem]->iHTTPPassword )
			{
			connection.SetPropertyL( KNSmlHTTPPassword, iProfiles[aItem]->iHTTPPassword->Des() );
			}
		}
	else
		{
		connection.SetPropertyL( KNSmlHTTPAuth, KNSmlFalseVal );
		}
		
	connection.UpdateL();
	CleanupStack::PopAndDestroy(); // connection
	
	
		
	
	
	if(iProfiles[aItem]->iProtocolVersion == ESmlVersion1_1_2 || 
			iProfiles[aItem]->iProtocolVersion == ESmlVersion1_2 )
	{
		profile.SetProtocolVersionL(iProfiles[aItem]->iProtocolVersion);
	}

	
	
	
	
		
	TInt iDataProvElementCount = iProfiles[aItem]->iDataProvElement.Count();
	_DBG_FILE("CNSmlDsProvisioningAdapter::SaveL(): Resource For loop: before Start");
	for ( TInt i = 0; i < iDataProvElementCount; i++ )
		{
        _DBG_FILE(
                "CNSmlDsProvisioningAdapter::SaveL(): Resource For loop: In");
		RSyncMLDataProvider dataProvider;

        TRAPD(error, dataProvider.OpenL(iSession,
                iProfiles[aItem]->iDataProvElement[i]->iUid));
		if (!error)
		    {
		    CleanupClosePushL(dataProvider);
            if (ret)
                {
                RArray<TSmlTaskId> providers;
                profile.ListTasksL(providers);
                TInt dataprovcount = providers.Count();

                for (TInt i = 0; i < dataprovcount; i++)
                    {
                    TSmlTaskId taskID = providers[i];
                    RSyncMLTask task;
                    task.OpenL(profile, taskID);
                    CleanupClosePushL(task);

                    if (dataProvider.Identifier() == task.DataProvider())
                        {
                        profile.DeleteTaskL(taskID);
                        CleanupStack::PopAndDestroy();
                        break;
                        }

                    CleanupStack::PopAndDestroy();

                    }
                providers.Reset();
                providers.Close();

                }
            HBufC* localDB = dataProvider.DefaultDataStoreName().AllocLC();
            _DBG_FILE("CNSmlDsProvisioningAdapter::SaveL(): DB value");
            DBG_ARGS(
                    iProfiles[aItem]->iDataProvElement[i]->iRemoteDBUri->Des().Ptr());

            RSyncMLTask task;
            task.CreateL(
                    profile,
                    iProfiles[aItem]->iDataProvElement[i]->iUid,
                    iProfiles[aItem]->iDataProvElement[i]->iRemoteDBUri->Des(),
                    localDB->Des());
            CleanupClosePushL(task);
            TRAPD(err, task.UpdateL());
            if (err != KErrAlreadyExists && err != KErrNone)
                {
                User::Leave(err);
                }
            CleanupStack::PopAndDestroy(3); // task, localDB, dataProvider
		    }
		
		}
	_DBG_FILE("CNSmlDsProvisioningAdapter::SaveL(): Resource For loop: after End");
				
	profile.UpdateL();
	iProfiles[aItem]->iProfileId = profile.Identifier();
	CleanupStack::PopAndDestroy( &profile );
	_DBG_FILE("CNSmlDsProvisioningAdapter::SaveL(): end");
	}
EAP_FUNC_EXPORT eap_status_e eapol_am_wlan_authentication_symbian_c::read_configure(
	const eap_configuration_field_c * const field,
	eap_variable_data_c * const data)
{
	EAP_TRACE_BEGIN(m_am_tools, TRACE_FLAGS_DEFAULT);
	EAP_ASSERT_ALWAYS(data != NULL);
	
	EAP_TRACE_DEBUG(
		m_am_tools, 
		TRACE_FLAGS_DEFAULT, 
		(EAPL("eapol_am_wlan_authentication_symbian_c::read_configure(): %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_configure()");

	// Trap must be set here because the OS independent portion of EAPOL
	// that calls this function does not know anything about Symbian.	
	eap_status_e status(eap_status_ok);

	// Check if the wanted parameter is default type

	eap_variable_data_c wanted_field(m_am_tools);
	eap_variable_data_c type_field(m_am_tools);
	
	status = wanted_field.set_buffer(
		field->get_field(),
		field->get_field_length(),
		false,
		false);
	if (status != eap_status_ok)
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, status);
	}
	
	status = type_field.set_buffer(
		cf_str_EAP_default_type_hex_data.get_field()->get_field(),
		cf_str_EAP_default_type_hex_data.get_field()->get_field_length(),
		false,
		false);
	if (status != eap_status_ok)
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, status);
	}

	// It was something else than EAP type. Read it from eapol DB.
	_LIT( KEapolTableName, "eapol" );

	TFileName aPrivateDatabasePathName;

	TRAPD(err, EapPluginTools::GetPrivatePathL(
		m_session,
		aPrivateDatabasePathName));
		
	if (err)
		{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, m_am_tools->convert_am_error_to_eapol_error(err));
		}

	aPrivateDatabasePathName.Append(KEapolDatabaseName);

	EAP_TRACE_DATA_DEBUG_SYMBIAN(("aPrivateDatabasePathName",
		aPrivateDatabasePathName.Ptr(),
		aPrivateDatabasePathName.Size()));

	TRAPD( error, read_configureL(
		aPrivateDatabasePathName,
		KEapolTableName,
		field->get_field(),
		field->get_field_length(),
		data) );

	// Try to read it for eap fast DB	
	HBufC8* fieldBuf = HBufC8::New( field->get_field_length() );

	eap_automatic_variable_c<HBufC8> automatic_fieldBuf(
		m_am_tools,
		fieldBuf);

	if (fieldBuf == 0)
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, eap_status_allocation_error);
	}
	TPtr8 fieldPtr = fieldBuf->Des();
	fieldPtr.Copy( reinterpret_cast<const TUint8 *> ( field->get_field() ));

	if (error != KErrNone) 
	{
		status = m_am_tools->convert_am_error_to_eapol_error(error);

#if defined(USE_EAP_FILECONFIG)
		if (m_fileconfig != 0
			&& m_fileconfig->get_is_valid() == true)
		{
			// Here we could try the final configuration option.
			status = m_fileconfig->read_configure(
				field,
				data);
		}
#endif //#if defined(USE_EAP_FILECONFIG)
	}

	m_am_tools->trace_configuration(
		status,
		field,
		data);

	EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
	return EAP_STATUS_RETURN(m_am_tools, status);
}
// ---------------------------------------------------------
// CNSmlDsProvisioningAdapter::StoreAttributesL
// ---------------------------------------------------------
void CNSmlDsProvisioningAdapter::StoreAttributesL( const TDesC& aType )
    {
    _DBG_FILE("CNSmlDsProvisioningAdapter::StoreAttributesL(): begin");
    
    TInt iDataProvElementCount = iProfiles[iProfiles.Count()-1]->iDataProvElement.Count()-1;
	// Leave if aType cannot be assigned
    if( ( aType.Length() > 0 ) &&
        ( iProfiles[iProfiles.Count()-1]->iDataProvElement[iDataProvElementCount]->iRemoteDBUri ) )
        {
        TBool dataProvIdFoundInZ = FALSE;
        TSmlDataProviderId firstDataProvIdFound = 0;
        TSmlDataProviderId uidFound = 0;

        TBool doSearch = ETrue;
        if ( aType.FindF( KXVcardMimeType ) != KErrNotFound )
            {
            if ( IsOperatorProfile( *iProfiles[iProfiles.Count()-1] ) )
                {
                const CNSmlDsProfileElement& profile = *iProfiles[iProfiles.Count()-1];
                StoreOperatorUrlL( *profile.iHostAddress );
                
                // Do not make a search through adapter implementations
                doSearch = EFalse;
                uidFound = OperatorAdapterUid();
                if ( !uidFound )
                    {
                    // If OperatorAdapterUid returns 0, do a search
                    doSearch = ETrue;
                    }
                }
            }
		// look through every implementation adapter until one found
		// which supports MIME type in question
		
		// The first one located in ROM is chosen. If none found in ROM then
		// the first adapter found is chosen.

		HBufC8 *type = HBufC8::NewLC(aType.Size());
		TPtr8 typePtr = type->Des();
		CnvUtfConverter::ConvertFromUnicodeToUtf8( typePtr, aType);

		// get list of dataproviderIds
		RImplInfoPtrArray implArray;
		CleanupStack::PushL( PtrArrCleanupItemRArr( CImplementationInformation, &implArray ) );
		TUid ifUid = { KNSmlDSInterfaceUid };
		REComSession::ListImplementationsL( ifUid, implArray );
		
        if ( doSearch )
            {
            TInt countProviders = implArray.Count();
            for( TInt i = 0; i < countProviders; i++ )
                {
                CImplementationInformation* implInfo = implArray[i];

                RSyncMLDataProvider dataProvider;
                dataProvider.OpenL( iSession, implInfo->ImplementationUid().iUid );
                CleanupClosePushL( dataProvider );

                TInt mimeTypeCount = dataProvider.MimeTypeCount();
                for( TInt j = 0; j < mimeTypeCount; j++ )
                    {
                    HBufC* mimeType = dataProvider.MimeType( j ).AllocLC();
                    TPtrC8 convMimeType = ConvertTo8LC( *mimeType );
                    if( typePtr.Find( convMimeType ) == 0)
                        {
                        // MIME type in question was found
                        uidFound = implInfo->ImplementationUid().iUid;

                        if( firstDataProvIdFound == 0 )
                            {
                            // save the first in case of none found from ROM
                            firstDataProvIdFound = uidFound;
                            }
					
                        // check whether the provider is located in ROM (drive Z)
                        if( implInfo->Drive() == EDriveZ )
                            {
                            dataProvIdFoundInZ = TRUE;
                            }
                        }
				
                    CleanupStack::PopAndDestroy(2); // mimetype, ConvertTo8LC

                    if( uidFound )
                        {
                        break;
                        }
                    }
				
                CleanupStack::PopAndDestroy(); // dataProvider
			
                if ( dataProvIdFoundInZ )
                    {
                    break;
                    }
                else
                    {
                    uidFound = firstDataProvIdFound;
                    }
                }
            }
        
		REComSession::FinalClose();
		CleanupStack::PopAndDestroy( 2 ); // type, implArray

		if( uidFound )
			{
			iProfiles[iProfiles.Count()-1]->iDataProvElement[iDataProvElementCount]->iUid = uidFound;
			}		
        }
	
	_DBG_FILE("CNSmlDsProvisioningAdapter::StoreAttributesL(): end");
	}
예제 #23
0
EXPORT_C void TRequestContext::AddSubjectAttributeL( const TDesC8& aAttributeId, const TCertInfo& aCertInfo)
{
	TInt certLength = aCertInfo.iIssuerDNInfo.iCountry.Length();
	certLength += aCertInfo.iIssuerDNInfo.iOrganizationUnit.Length();
	certLength += aCertInfo.iIssuerDNInfo.iOrganization.Length();
	certLength += aCertInfo.iIssuerDNInfo.iCommonName.Length();
	certLength += aCertInfo.iSerialNo.Length() * 2;
	certLength += aCertInfo.iFingerprint.Length() * 2;
	
	HBufC8 *casn = HBufC8::NewLC( certLength + 5);
	TPtr8 ptr = casn->Des();
	const TChar KCASNDelimeter = '-';

	
	if ( aCertInfo.iIssuerDNInfo.iCommonName.Length())
	{
		ptr.Append( aCertInfo.iIssuerDNInfo.iCommonName);
		ptr.Append( KCASNDelimeter);
	}
	
	if ( aCertInfo.iIssuerDNInfo.iOrganization.Length())
	{
		ptr.Append( aCertInfo.iIssuerDNInfo.iOrganization);
		ptr.Append( KCASNDelimeter);
	}
	
	if ( aCertInfo.iIssuerDNInfo.iOrganizationUnit.Length())
	{
		ptr.Append( aCertInfo.iIssuerDNInfo.iOrganizationUnit);
		ptr.Append( KCASNDelimeter);
	}
	
	if ( aCertInfo.iIssuerDNInfo.iCountry.Length())
	{
		ptr.Append( aCertInfo.iIssuerDNInfo.iCountry);
		ptr.Append( KCASNDelimeter);
	}
	
	if ( aCertInfo.iSerialNo.Length())
	{
		//convert fingerprint to plain text
		for ( TInt i(0); i < aCertInfo.iSerialNo.Length(); i++)
		{
			ptr.AppendNumFixedWidth( aCertInfo.iSerialNo[i], EHex, 2);
		}	
		ptr.Append( KCASNDelimeter);
	}

	if ( aCertInfo.iFingerprint.Length())
	{
		//convert fingerprint to plain text
		for ( TInt i(0); i < aCertInfo.iFingerprint.Length(); i++)
		{
			ptr.AppendNumFixedWidth( aCertInfo.iFingerprint[i], EHex, 2);
		}	
	}	

	AddSubjectAttributeL( aAttributeId, *casn, PolicyEngineXACML::KStringDataType);
	
	CleanupStack::PopAndDestroy( casn);
}
EXPORT_C TInt CMTPTypeObjectPropList::FirstWriteChunk(TPtr8& aChunk)
	{
    aChunk.Set(&(iIOPages[0][iTransportHeaderIndex]), 0, KMTPPropListBufferPageSize - iTransportHeaderIndex);
    return KErrNone;
	}
예제 #25
0
/*
-------------------------------------------------------------------------------

    Class: CStifParser

    Method: NextSectionMemoryL

    Description: Parses sections from configuration files.

    Open and read configuration source and parses a required section.
    If start tag is empty the parsing starts beginning of the configuration
    file. If end tag is empty the parsing goes end of configuration file.
    This method will parse next section after the earlier section if aSeeked
    parameter is not given.
    If configuration file includes several sections with both start and end
    tags so aSeeked parameter seeks the required section. The aSeeked
    parameters indicates section that will be parsed.

    Parameters: const TDesC& aStartTag: in: Indicates a start tag for parsing
                const TDesC& aEndTag: in: Indicates an end tag for parsing
                TInt aSeeked: in: a seeked section which will be parsed

    Return Values:  CStifSectionParser* : pointer to CStifSectionParser object
                    NULL will return if file size or aSeeked is not positive
                    NULL will return if start tag is not found
                    NULL will return if end tag is not found
                    NULL will return if parsed section length is not positive

    Errors/Exceptions:  Leaves if called Size method fails
                        Leaves if HBufC::NewLC method leaves
                        Leaves if called Read method fails
                        Leaves if CStifSectionParser::NewL methods leaves

    Status: Proposal

-------------------------------------------------------------------------------
*/
CStifSectionParser* CStifParser::NextSectionMemoryL( const TDesC& aStartTag,
                                                 	 const TDesC& aEndTag,
                                                     TInt aSeeked )
    {
    TInt size( 0 );
    // Parser is created straight with data
    if( iParsingMode == EBufferParsing )
        {
        size = iBuffer.Length();
        }
    // Parser is created with path and file informations
    else
        {
        User::LeaveIfError( iFile.Size( size ) );
        }

    // size or aSeeked cannot be 0 or negetive
    if( size <= 0 || aSeeked <= 0)
        {
        __TRACE(
            KInfo, ( _L( "STIFPARSER: NextSectionL method returns a NULL" ) ) );
        return NULL;
        }

    const TInt tmpSize = 128;//--UNICODE-- KMaxName; // 128 - set to even value, because KMaxName may change in the future
    TInt offset( 0 ); // Offset value to parts reading

    // Construct modifiable heap-based descriptor. tmp to CleanupStack
    HBufC* tmp = HBufC::NewLC( size );
    TPtr wholeSection = tmp->Des();

    // Construct modifiable heap-based descriptor. tmp2 to CleanupStack
    HBufC8* tmp2 = HBufC8::NewLC( tmpSize );    // 128
    TPtr8 buf = tmp2->Des();

    // Construct modifiable heap-based descriptor. tmp3 to CleanupStack
    HBufC* tmp3 = HBufC::NewLC( tmpSize );      // 128
    TPtr currentSection = tmp3->Des();

    // Parser is created straight with data
    if( iParsingMode == EBufferParsing )
        {
        // If 8 bit copy changes to 16
        wholeSection.Copy( iBuffer );
        }
    // Parser is created with path and file informations
    else
        {
        TPtrC16 currentSectionUnicode;
        do // Read data in parts(Maximum part size is KMaxName)
            {
            // Read data
            User::LeaveIfError( iFile.Read( offset, buf, tmpSize ) );

            // If file is unicode convert differently
            if(iIsUnicode)
                {
                // 8 bit to 16 with unicode conversion - simply point to byte array as to double-byte array
                currentSectionUnicode.Set((TUint16 *)(buf.Ptr()), buf.Length() / 2);
                // Appends current section to whole section
                wholeSection.Append( currentSectionUnicode );
                }
            else
                {
                // 8 bit to 16
                currentSection.Copy( buf );
                // Appends current section to whole section
                wholeSection.Append( currentSection );
                }

            offset += tmpSize;

            } while( offset < size );
        }

    CleanupStack::PopAndDestroy( tmp3 );
    CleanupStack::PopAndDestroy( tmp2 );

    // User wants section without c-style comments
    if( iCommentType == ECStyleComments )
        {
        ParseCommentsOff( wholeSection );
        }

    TLex lex( wholeSection );
    lex.SkipAndMark( iOffset );

    // For the required section length and positions
    TInt length( 0 );
    TInt lengthStartPos( 0 );
    TInt lengthEndPos( 0 );
    TBool eos( EFalse );
    TInt tagCount( 1 );

    // Check is aStartTag given
    if ( aStartTag.Length() == 0 )
        {
        // Skip line break, tabs, spaces etc.
        lex.SkipSpace();
        lengthStartPos = lex.Offset();
        }
    else
        {
        // While end of section
        while ( !lex.Eos() )
            {
            TPtrC ptr = lex.NextToken();
            // Start of the section is found and correct section
            if ( ptr == aStartTag && tagCount == aSeeked )
                {
                lengthStartPos = lex.Offset();
                break;
                }
            // Start tag is found but not correct section
            else if ( ptr == aStartTag )
                {
                tagCount++;
                }
            }
        }

    // If we are end of section lex.Eos() and eos will be ETrue
    eos = lex.Eos();

    // Seeked section is not found
    if ( tagCount != aSeeked )
        {
        __TRACE( KInfo, ( _L(
            "STIFPARSER: NextSectionL method: Seeked section is not found" ) ) );
        CleanupStack::PopAndDestroy( tmp );
        User::Leave( KErrNotFound );
        }

    // Check is aEndTag given
    if ( aEndTag.Length() == 0 )
        {
        lengthEndPos = wholeSection.Length();
        }
    else
        {
        // While end of section
        while ( !lex.Eos() )
            {
            TPtrC ptr = lex.NextToken();
            // End tag of the section is found
            if ( ptr == aEndTag )
                {
                lengthEndPos = lex.Offset();
                // Because Offset() position is after the aEndTag
                lengthEndPos -= aEndTag.Length();
                break;
                }
            }
        }

    // If we are end of section and lengthEndPos is 0
    if ( lengthEndPos == 0 )
        {
        // lex.Eos() and eos will be ETrue
        eos = lex.Eos();
        }

    // The length includes spaces and end of lines
    length = ( lengthEndPos - lengthStartPos );

    CStifSectionParser* section = NULL;

    // If eos is true or length is negative
    if ( eos || length <= 0  )
        {
        __TRACE(
            KInfo, ( _L( "STIFPARSER: NextSectionL method returns a NULL" ) ) );
        }
    else
        {
        // Make CStifSectionParser object and alloc required length
        section = CStifSectionParser::NewL( length );
        CleanupStack::PushL( section );

        // Copy required data to the section object
        section->SetData( wholeSection, lengthStartPos, length );

        //iOffset += lengthEndPos + aEndTag.Length();
        iOffset = lex.Offset();

        CleanupStack::Pop( section );
        }
    CleanupStack::PopAndDestroy( tmp );

    return section;

    }
EXPORT_C TInt CMTPTypeObjectPropList::NextWriteChunk(TPtr8& aChunk)
	{
	ReserveNewPage();
	aChunk.Set(&(iIOPages[iIOPages.Count()-1][0]), 0, KMTPPropListBufferPageSize);
    return KErrNone;
	}
예제 #27
0
void CRFC3984Encode::PayloadizeNaluL(
    TDes8 & aBuffer, 
    TUint32 /*aTimeStamp*/, 
    TUint32& /*aMarkerBit*/, 
    TInt & aNalCount )
    {
	TInt startIndex = 0;
	TInt size = 0;
	
	__ASSERT_ALWAYS( iToPayloadizeCount > 0, User::Leave( KErrArgument ) );
	
	__ASSERT_ALWAYS( iToPayloadizeBuffer.Count() == iToPayloadizeSizeBuffer.Count(), 
	                 User::Leave( KErrArgument ) );
		
	if ( iToPayloadizeCount == 1 ) // SNALU packet
	    {
		startIndex = iToPayloadizeBuffer[0];
		size = iToPayloadizeSizeBuffer[0];	
		TPtr8 start = aBuffer.MidTPtr( startIndex );
		AddSnaluPacketL( start, size );
    	}
	else // payloadize STAP-A packet
	    {
		TInt count = 0;
		TInt totalSize = 0;
		TUint8 headerByte = 0;
		
		for ( count = 0; count < iToPayloadizeCount; count++ )
		    {
		    // finding total size of all the NALU's to aggregate
			totalSize += iToPayloadizeSizeBuffer[count]; 
		    }
		
		// addding the total size fields and STAP-A header size	
		totalSize += ( iToPayloadizeCount*2 + 1 ); 
		
		count = 0;
		
		// allocating memory for the total buffer size		
		HBufC8* pBuffer = HBufC8::NewLC( totalSize );
		
		TUint16 value = 0;
		TPtr8 pDes1 = pBuffer->Des();
		
		headerByte = PACKET_STAP_A | ( aBuffer[iToPayloadizeBuffer[count]] & ( 0x7 << 5 ) ); 
		pDes1.Append( &headerByte, 1 );
		
		 // Pps and sps are handled as SNALUs, 
		 // if there's nothing else to packetize, stap-a packet is not created
		TBool stapPacketCreated( EFalse );
		for( count = 0; count < iToPayloadizeCount; count++ )
		    {
			startIndex = iToPayloadizeBuffer[count];
			size = iToPayloadizeSizeBuffer[count];
			TPtr8 pStart = aBuffer.MidTPtr( startIndex ); // getting start index
			
			if ( TMccCodecInfo::IsAvcPpsOrSpsData( pStart, ETrue ) )
			    {
			    AddSnaluPacketL( pStart, size );
			    }
			else
			    {
    			// convert to network byte order
    			value = ByteOrder::Swap16( static_cast<TUint16>( size ) ); 
    			TUint8* ptrByte = reinterpret_cast<TUint8*>( &value );
    			pDes1.Append( ptrByte, 2 );
    			pDes1.Append( pStart.Ptr(), size );
    			stapPacketCreated = ETrue;
			    }
		    }
		
		if ( stapPacketCreated )
		    {
    		// inserting stap-a packet into the payloadized NAL unit buffer for retrieval
        	iPayloadizedBuffers.InsertL( pBuffer, iNalCount );
        	iNalCount++;
        	CleanupStack::Pop(pBuffer);
		    }
		else
		    {
		    // stap-a packet not created
		    CleanupStack::PopAndDestroy(pBuffer);
		    }
	    }
	
    //Now cleaning up the buffer
    iToPayloadizeBuffer.Reset();
    iToPayloadizeSizeBuffer.Reset();
    iToPayloadizeCount = 0;
    	
	aNalCount = iNalCount;
    }
TVerdict CUPSDbManagementStep::doTestStepPreambleL()
/**
 * @return - TVerdict code
 * Override of base class virtual
 */
	{
 	__UHEAP_MARK;
 	
 	INFO_PRINTF2(_L("START CELLS: %d"), User::CountAllocCells());
 	
 	// reads client name and SID
	TParse clientFullName;
	RThread client;
	clientFullName.Set(client.FullName(),NULL, NULL);
	iTEFServerName=clientFullName.Name();
	iExpectedClientSid = client.SecureId() ;
	client.Close();
 	
    // Read how many times the test step needs to be repeated.
    TName fStepRepeat(_L("StepRepeat"));
    TInt  repeats;
    
    if(GetIntFromConfig(ConfigSection(),fStepRepeat,repeats))
    	{
    	iStepRepeat=repeats;
    	}
	else
		{	
		iStepRepeat=1;		
		}
    
    // Read values for test sequence from INI file. (ARRAY of values)
	TInt index=0;
	TName fOperation;
	fOperation.Format(_L("Operation_%d"), index);
	TName fClientSid;
	fClientSid.Format(_L("ClientSid_%d"),index);
	TName fEvaluatorId;
	fEvaluatorId.Format(_L("EvaluatorId_%d"),index);
	TName fServiceId;
	fServiceId.Format(_L("ServiceId_%d"),index);
	TName fServerSid;
	fServerSid.Format(_L("ServerSid_%d"),index);
	TName fFingerprint;
	fFingerprint.Format(_L("Fingerprint_%d"),index);
	TName fClientEntity;
	fClientEntity.Format(_L("ClientEntity_%d"),index);
	TName fDescription;
	fDescription.Format(_L("Description_%d"),index);
	TName fDecisionResult;
	fDecisionResult.Format(_L("DecisionResult_%d"),index);
	TName fMajorPolicyVersion;
	fMajorPolicyVersion.Format(_L("MajorPolicyVersion_%d"),index);
	TName fRecordId;
	fRecordId.Format(_L("RecordId_%d"),index);
	TName fEvaluatorInfo;
	fEvaluatorInfo.Format(_L("EvaluatorInfo_%d"),index);
	TName fExpectedDecisionCount;
	fExpectedDecisionCount.Format(_L("ExpectedDecisionCount_%d"),index);
	
	TPtrC 	operation;
	TInt	clientSid;
	TInt	evaluatorId;
	TInt	serviceId;
	TInt	serverSid;
	TPtrC	fingerprint;
	TPtrC	clientEntity;
	TPtrC	description;
	TPtrC	decisionResult;
	TInt	majorPolicyVersion;
	TInt 	recordId;
	TInt	evaluatorInfo;
	TInt 	expectedDecisionCount;
	
	while (GetStringFromConfig(ConfigSection(),fOperation,operation))
		{
		
		// Create an instance of a new request
		CUpsDbRequest* newRequest = CUpsDbRequest::NewL();
		CleanupStack::PushL(newRequest);
		
		// Set the operation to be performed
	    newRequest->iOperation = operation;
	    
	    if(GetHexFromConfig(ConfigSection(),fClientSid,clientSid))
		    {
		    newRequest->iClientSid = clientSid;
		  	newRequest->iDecisionFilter->SetClientSid(TSecureId(clientSid),EEqual);
		    }
	    
		if(GetHexFromConfig(ConfigSection(),fEvaluatorId,evaluatorId))
			{
			newRequest->iEvaluatorId = evaluatorId;	
			newRequest->iDecisionFilter->SetEvaluatorId(TUid::Uid(evaluatorId),EEqual);
			}
		
		if(GetHexFromConfig(ConfigSection(),fServiceId,serviceId))
			{
			newRequest->iServiceId = serviceId;	
			newRequest->iDecisionFilter->SetServiceId(TUid::Uid(serviceId),EEqual);
			}
	
		if(GetHexFromConfig(ConfigSection(),fServerSid,serverSid))
			{
			newRequest->iServerSid = serverSid;	
			newRequest->iDecisionFilter->SetServerSid(TSecureId(serverSid),EEqual);
			}
			
		if(GetStringFromConfig(ConfigSection(),fFingerprint,fingerprint))
			{
			HBufC8* fingerprintConverter = HBufC8::NewLC(fingerprint.Length());
			TPtr8 fingerprintPtr = fingerprintConverter->Des();
			fingerprintPtr.Copy(fingerprint); 	
             
	       	newRequest->iFingerprint = fingerprintPtr;
	       	
	       	HBufC8* binaryFingerprint = StringToBinaryLC(fingerprintPtr);
	       	
	      	newRequest->iDecisionFilter->SetFingerprintL(*binaryFingerprint,EEqual);	
	       	CleanupStack::PopAndDestroy(binaryFingerprint);
	       	CleanupStack::PopAndDestroy(fingerprintConverter); 
			}

		if(GetStringFromConfig(ConfigSection(),fClientEntity,clientEntity))
			{
			HBufC8* clientEntityConverter = HBufC8::NewLC(clientEntity.Length());
			TPtr8 clientEntityPtr = clientEntityConverter->Des();
			clientEntityPtr.Copy(clientEntity); 	
             
	       	newRequest->iClientEntity = clientEntityPtr;
	       	newRequest->iDecisionFilter->SetClientEntityL(clientEntityPtr,EEqual);		
	       	CleanupStack::PopAndDestroy(clientEntityConverter); 
			}
			
		if(GetStringFromConfig(ConfigSection(),fDescription,description))
			{
		    newRequest->iDescription = description;
			}
			
		if(GetStringFromConfig(ConfigSection(),fDecisionResult,decisionResult))
			{
			if(decisionResult.CompareF(_L("Yes"))==0 || decisionResult.CompareF(_L("No"))==0 || decisionResult.CompareF(_L(""))==0 )
				{
				newRequest->iDecisionResult = decisionResult;	
				}
			else 
				{
				ERR_PRINTF3(_L("%S: Unexpected Decision Result - %S"),&iTEFServerName, &decisionResult);
				}
			}

		if(GetIntFromConfig(ConfigSection(),fMajorPolicyVersion,majorPolicyVersion)) 
			{
			newRequest->iMajorPolicyVersion = majorPolicyVersion;
			newRequest->iDecisionFilter->SetMajorPolicyVersion(majorPolicyVersion,EEqual);		
			}
		
		if(GetIntFromConfig(ConfigSection(),fRecordId,recordId))
			{
			newRequest->iRecordId = recordId;
			newRequest->iDecisionFilter->SetRecordId(recordId,EEqual);		
			}
			
		if(GetIntFromConfig(ConfigSection(),fEvaluatorInfo,evaluatorInfo))
			{
			newRequest->iEvaluatorInfo = evaluatorInfo;		
			}
			
		if(GetIntFromConfig(ConfigSection(),fExpectedDecisionCount,expectedDecisionCount))
			{
			newRequest->iExpectedDecisionCount = expectedDecisionCount;		
			}
	    
	    // Add the new service to be requested to array.
	    iArraySersToRequest.AppendL(newRequest);
	    
	    CleanupStack::Pop(newRequest);
	       
	    index++;
	    fOperation.Format(_L("Operation_%d"), index);
	    fClientSid.Format(_L("ClientSid_%d"),index);
		fEvaluatorId.Format(_L("EvaluatorId_%d"),index);
		fServiceId.Format(_L("ServiceId_%d"),index);
		fServerSid.Format(_L("ServerSid_%d"),index);
		fFingerprint.Format(_L("Fingerprint_%d"),index);
		fClientEntity.Format(_L("ClientEntity_%d"),index);
		fDescription.Format(_L("Description_%d"),index);
		fDecisionResult.Format(_L("DecisionResult_%d"),index);
		fMajorPolicyVersion.Format(_L("MajorPolicyVersion_%d"),index);
		fRecordId.Format(_L("RecordId_%d"),index);
		fEvaluatorInfo.Format(_L("EvaluatorInfo_%d"),index);
		fExpectedDecisionCount.Format(_L("ExpectedDecisionCount_%d"),index);
		}
	
	SetTestStepResult(EPass);
	return TestStepResult();
	}
예제 #29
0
TInt CTestSession::CheckDesPresent(const RMessage2& aMessage, TUint aArgIndex, TBool aExpected, TBool aWrite)
	{
	TRequestStatus clientStat;
	
	if (aExpected)
		{
		RDebug::Printf("  Checking message argument at %d is present", aArgIndex);
		}
	else
		{
		RDebug::Printf("  Checking message argument at %d is not present", aArgIndex);
		// Start watching for client thread death
		RThread clientThread;
		aMessage.Client(clientThread);
		clientThread.Logon(clientStat);
		clientThread.Close();
		}
		
	// Get the length of the descriptor and verify it is as expected.
	TInt length = aMessage.GetDesLength(aArgIndex);
	if (length < KErrNone)
		{
		RDebug::Printf("  Error getting descriptor length %d", length);
		return length;
		}
	if (length < 3)
		{// The incorrect descriptor length.
		RDebug::Printf("  Error - Descriptor length too small %d", length);
		return KErrArgument;
		}
	if (!aWrite)
		{// Now read the descriptor and verify that it is present or not.
		TBuf8<5> des;
		TInt r = aMessage.Read(aArgIndex, des);
		if (r != (aExpected ? KErrNone : KErrBadDescriptor))
			{
			RDebug::Printf("  Unexpected value returned from aMessage.Read:%d", r);
			return KErrGeneral;
			}
		if (r==KErrNone && (des[0] != 'a' || des[1] != 'r' || des[2] != 'g'))
			{// The incorrect descriptor data has been passed.
			RDebug::Printf("  Error in descriptor data is corrupt r %d", r);
			return KErrArgument;
			}
		}
	else
		{// Now write to the maximum length of the descriptor.
		TInt max = aMessage.GetDesMaxLength(aArgIndex);
		if (max < 0)
			{
			RDebug::Printf("  Error getting descriptor max. length %d", max);
			return length;
			}
		HBufC8* argTmp = HBufC8::New(max);
		TPtr8 argPtr = argTmp->Des();
		argPtr.SetLength(max);
		for (TInt i = 0; i < max; i++)
			argPtr[i] = (TUint8)aArgIndex;
		TInt r = aMessage.Write(aArgIndex, argPtr);
		if (r != (aExpected ? KErrNone : KErrBadDescriptor))
			{
			RDebug::Printf("  Unexpected value returned from aMessage.Write:%d", r);
			return KErrGeneral;
			}
		}

	if (!aExpected)
		{// The client should have been killed as the data wasn't present.
		RDebug::Printf("  CheckDesPresent: Waiting for client to die");
		User::WaitForRequest(clientStat);
		iClientDied = ETrue;
		RDebug::Printf("  CheckDesPresent: Client dead");
		}
	return KErrNone;
	}
void CMacBasicDataStep::doTestL()
	{
	INFO_PRINTF1(_L("*** Mac - Basic Data ***"));
	INFO_PRINTF2(_L("HEAP CELLS: %d"), User::CountAllocCells());
	
	TVariantPtrC algorithmUid;
	TPtrC sourcePath;
	TPtrC expectedMac;
	TPtrC encryptKey;
	TVariantPtrC keyType;
	
	//Extract the Test Case ID parameter from the specified INI file
	if (!GetStringFromConfig(ConfigSection(),KConfigAlgorithmUid,algorithmUid) ||
		!GetStringFromConfig(ConfigSection(),KConfigSourcePath,sourcePath) ||
		!GetStringFromConfig(ConfigSection(),KConfigExMacValue,expectedMac)||
		!GetStringFromConfig(ConfigSection(),KConfigEncryptKey,encryptKey) ||
		!GetStringFromConfig(ConfigSection(),KConfigEncryptKeyType,keyType))
		{
		ERR_PRINTF1(_L("** Error: Failed to Load Configuration Parameters **"));
		return;
		}
	
	//Create a pointer for the Mac Implementation Object
	CMac* macImpl = 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 Mac Factory Object			
	TRAPD(err, CMacFactory::CreateMacL(macImpl,
										algorithmUid,
										*key,
										NULL));											

	if (err != KErrNone)
		{
		CleanupStack::PopAndDestroy(3, keyStr);	// keyStr, keyParams, key
		delete macImpl;
		ERR_PRINTF2(_L("*** FAIL: Failed to Create Mac Object - %d ***"), err);
		User::Leave(err);
		}

	//Push the Mac Implementation Object onto the Cleanup Stack
	CleanupStack::PushL(macImpl);
	
	RFs fsSession;
	User::LeaveIfError(fsSession.Connect());
	CleanupClosePushL(fsSession);
		
	RFile sourceFile;
	
	//Open the specified source file
	User::LeaveIfError(sourceFile.Open(fsSession,sourcePath, EFileRead));
	CleanupClosePushL(sourceFile);
	
	TInt sourceLength = 0;
	User::LeaveIfError(sourceFile.Size(sourceLength));

	//Create a heap based descriptor to store the data
	HBufC8* sourceData = HBufC8::NewL(sourceLength);						
	CleanupStack::PushL(sourceData);
	TPtr8 sourcePtr = sourceData->Des();
	
	sourceFile.Read(sourcePtr);
	
	if(sourcePtr.Length() != sourceLength)
		{
		ERR_PRINTF1(_L("*** Error: Reading Source File ***"));
		}
	else
		{
		//Create a NULL TCharacteristics pointer
		const TCharacteristics* charsPtr(NULL);
		
		//Retrieve the characteristics for the Mac implementation object
		TRAP_LOG(err, macImpl->GetCharacteristicsL(charsPtr));
		
		//Static cast the characteristics to type TMacCharacteristics
		const TMacCharacteristics* macCharsPtr = static_cast<const TMacCharacteristics*>(charsPtr);
		
		//The mac output size is returned in Bits, divide by 8 to get the Byte size
	 	TInt macSize = macCharsPtr->iHashAlgorithmChar->iOutputSize/8;
		
		//Retrieve the final 8bit mac value and convert to 16bit												
		HBufC* macData = HBufC::NewLC(macSize);
		TPtr macPtr = macData->Des();
		
		// This is just a simple performance measurement on generating 
		// the Mac
		TTime startTime;
		startTime.UniversalTime();
		
		macPtr.Copy(macImpl->MacL(*sourceData));
		
		TTime endTime;
		endTime.UniversalTime();
		TTimeIntervalMicroSeconds time = endTime.MicroSecondsFrom(startTime);
		
		//Take the 16bit descriptor and convert the string to hexadecimal
		TVariantPtrC convertMac;
		convertMac.Set(macPtr);
		HBufC* macResult = convertMac.HexStringLC();		
		
		INFO_PRINTF2(_L("*** Mac: %S ***"), &*macResult);
		INFO_PRINTF2(_L("*** Expected Mac: %S ***"), &expectedMac);
		
		//If the returned mac value matches the expected mac, Pass the test	
		if(*macResult == expectedMac)
			{
			INFO_PRINTF2(_L("*** Mac - Basic Data generated after setup in %d micro sec.: PASS ***"), time.Int64());
			SetTestStepResult(EPass);	
			}
		else
			{
			ERR_PRINTF1(_L("*** FAIL: Generated Mac and Expected Mac Mismatch ***"));
			}
		
		CleanupStack::PopAndDestroy(2, macData);	// macData, macResult 	
		}

	CleanupStack::PopAndDestroy(7, keyStr);	// keyStr, keyParams, key, macImpl, &fsSession, &sourceFile, sourceData
	INFO_PRINTF2(_L("HEAP CELLS: %d"), User::CountAllocCells());
	}