void CTLogger::LogL(const TDesC& aString) { // Open the file server and file RFs fs; User::LeaveIfError(fs.Connect()); CleanupClosePushL(fs); // Open the file or create it if doesn't exist, create it RFile file; TDriveUnit sysDrive (fs.GetSystemDrive()); TBuf<128> logFile (sysDrive.Name()); logFile.Append(KLogFilename); TInt error = file.Open(fs, logFile, EFileWrite|EFileShareAny); if (error == KErrNotFound) { error = file.Create(fs, logFile, EFileWrite|EFileShareAny); } User::LeaveIfError(error); CleanupClosePushL(file); // Seek to the end of the file TInt tmp = 0; file.Seek(ESeekEnd, tmp); // And do some logging TBuf8<MAX_LEN> buf; buf.Copy(aString); file.Write(buf); file.Write(KNewLine); // Close and tidy up CleanupStack::PopAndDestroy(2, &fs); }
/** Executes the supported operations specified in the given database configuration file and updates the settings table to store the version of this configuration file. @param aFileData The database file data @param aMatchingConfigFile The configuration file that is to be processed @param aDbConfigFileVersion The configuration file version @param aDbName Logical database name: "main" for the main database or attached database name @leave KErrNoMemory, if an out of memory condition occurs. One of the other system-wide error codes if the configuration file fails to be opened or read. One of the SQL errors of ESqlDbError type if the update to the database settings table fails @panic SqlDb 2 In _DEBUG mode if iDbHandle is NULL (uninitialized TSqlDbSysSettings object). */ void TSqlDbSysSettings::ExecuteConfigurationUpdateL(const TSqlSrvFileData& aFileData, const TDesC& aMatchingConfigFile, TInt aDbConfigFileVersion, const TDesC& aDbName) { __ASSERT_DEBUG(iDbHandle != NULL, __SQLPANIC(ESqlPanicInvalidObj)); //Execute the specified database config file operations that are supported #ifdef SYSLIBS_TEST TDriveUnit drive = EDriveC; #else TDriveUnit drive = EDriveZ; #endif TFileName configFilePath; TDriveName drvName = drive.Name(); configFilePath.Append(drvName); configFilePath.Append(aFileData.PrivatePath()); configFilePath.Append(aMatchingConfigFile); //If this method leaves then either the config file could not be //opened or read or an out of memory condition occured. Either way //another attempt will be made to process the config file when the //database is next opened DoExecuteDbConfigFileOpsL(aFileData.Fs(), configFilePath, aDbName); //Now update the settings table to store the current version of the database config file. //If this fails then another attempt will be made to process the config file and update //the settings table when the database is next opened TBuf<sizeof(KUpdateFileVersionSettingsSql) + KMaxFileName + 10> buf; buf.Format(KUpdateFileVersionSettingsSql(), &aDbName, aDbConfigFileVersion); __SQLLEAVE_IF_ERROR(::DbExecStmt16(iDbHandle, buf)); }
void CPolicyTest::RunTestL(TRequestStatus& aStatus) { HBufC* hptr16; hptr16 = CnvUtfConverter::ConvertToUnicodeFromUtf8L(*iNameInfo); RDebug::Print(KFormat,hptr16); delete hptr16; TDriveUnit sysDrive (RFs::GetSystemDrive()); TDriveName sysDriveName (sysDrive.Name()); TBuf<128> passScriptFile (sysDriveName); passScriptFile.Append(KPassScriptPath); TBuf<128> failScriptFile (sysDriveName); failScriptFile.Append(KFailScriptPath); TPtrC script = (iTestState == ETestPass) ? passScriptFile : failScriptFile; (iTestState == ETestPass) ? RDebug::RawPrint(KPassTestRunning) : RDebug::RawPrint(KFailTestRunning); TBuf<128> logTmpFile (sysDriveName); logTmpFile.Append(KLogTmpPath); iFs.Delete(logTmpFile); // ignore errors TBuf<128> commandLine; commandLine.AppendFormat(_L("%S %S"), &script, &logTmpFile); StartProcessL(iTestExeTmpNewPath, commandLine, aStatus); }
void CCompare::ConstructL(const TTestActionSpec& aTestActionSpec) { CKeyStoreTestAction::ConstructL(aTestActionSpec); TInt err = KErrNone; TInt pos = 0; TDriveUnit sysDrive (RFs::GetSystemDrive()); TBuf<128> ramDrive (sysDrive.Name()); ramDrive.Append(_L("\\tkeystore\\data\\")); iOriginalFile = ramDrive; iNewFile = ramDrive; TFileName buf; buf.FillZ(); buf.Copy(Input::ParseElement(aTestActionSpec.iActionBody, KOriginalFile, KOriginalFileEnd, pos, err)); // Now the filename itself iOriginalFile.Append(buf); buf.Copy(Input::ParseElement(aTestActionSpec.iActionBody, KNewFile, KNewFileEnd, pos, err)); // Now the filename itself iNewFile.Append(buf); // iExpectedResult = SetExpectedResultL(Input::ParseElement(aTestActionSpec.iActionResult, // KReturnStart, // KReturnEnd, pos, err)); }
void CPolicyTest::PerformAction(TRequestStatus& aStatus) { if (aStatus < 0) { iState = EFinished; } switch (iState) { case EInit: { TDriveUnit sysDrive (RFs::GetSystemDrive()); TDriveName sysDriveName (sysDrive.Name()); TBuf<128> scriptFile (sysDriveName); scriptFile.Append(KPassScriptPath); WriteScriptFileL(scriptFile, *iPassAction); scriptFile.Copy(sysDriveName); scriptFile.Append(KFailScriptPath); WriteScriptFileL(scriptFile, *iFailAction); } // fall through case ESetupTest: GetNextTest(); if (iTestState == ETestFinished) { iState = EFinished; TRequestStatus* status = &aStatus; User::RequestComplete(status, KErrNone); } else { SetupTestL(aStatus); iState = ERunTest; } break; case ERunTest: CheckProcessTermintationL(); RunTestL(aStatus); iState = EProcessResults; break; case EProcessResults: CheckProcessTermintationL(); ProcessResultsL(aStatus); iState = ESetupTest; break; case EFinished: iActionState = EPostrequisite; TRequestStatus* status = &aStatus; User::RequestComplete(status, aStatus.Int()); break; } }
void CTErrorStep::CleanUpResFilesL() { // Delete error rsc files in C: drive (accordingly, we remove the read-only attr kept from rom) // They need to be unlocked first CBaBackupSessionWrapper* backupSession = CBaBackupSessionWrapper::NewL(); CleanupStack::PushL(backupSession); TFileName fileName; for(TInt index=EResFile1; index<=EResFile5; ++index) { ResFileFullName(fileName, TTErrorResFile(index)); backupSession->CloseFileL(fileName, MBackupObserver::EReleaseLockNoAccess); User::After(100000); // wait 0.1s to allow the files to be closed User::LeaveIfError(iUtils.SetReadOnly(fileName, 0)); User::LeaveIfError(iUtils.DeleteFileL(fileName)); } CleanupStack::PopAndDestroy(backupSession); // Delete error lang rsc files in C: drive (accordingly, we remove the read-only attr kept from rom) User::LeaveIfError(iUtils.SetReadOnly(KTErrorLang1Tgt, 0)); User::LeaveIfError(iUtils.DeleteFileL(KTErrorLang1Tgt)); User::LeaveIfError(iUtils.SetReadOnly(KTErrorLang3Tgt, 0)); User::LeaveIfError(iUtils.DeleteFileL(KTErrorLang3Tgt)); User::LeaveIfError(iUtils.SetReadOnly(KTErrorLang6Tgt, 0)); User::LeaveIfError(iUtils.DeleteFileL(KTErrorLang6Tgt)); // Find where the removable media is (can vary on hardware builds) TDriveUnit drive; FindRemovableMediaL(drive); // Delete files in removable drive (accordingly, we remove the read-only attr kept from rom) TBuf<128> bufName; bufName = drive.Name(); bufName.Append(KTErrorLang2Tgt); User::LeaveIfError(iUtils.SetReadOnly(bufName, 0)); User::LeaveIfError(iUtils.DeleteFileL(bufName)); bufName.Zero(); bufName = drive.Name(); bufName.Append(KTErrorLang4Tgt); User::LeaveIfError(iUtils.SetReadOnly(bufName, 0)); User::LeaveIfError(iUtils.DeleteFileL(bufName)); bufName.Zero(); bufName = drive.Name(); bufName.Append(KTErrorLang5Tgt); User::LeaveIfError(iUtils.SetReadOnly(bufName, 0)); User::LeaveIfError(iUtils.DeleteFileL(bufName)); bufName.Zero(); bufName = drive.Name(); bufName.Append(KTErrorLang7Tgt); User::LeaveIfError(iUtils.SetReadOnly(bufName, 0)); User::LeaveIfError(iUtils.DeleteFileL(bufName)); }
void CWatcherActiveStep::RunTestsL() { switch (iTestState) { case EStateStartup: // Startup, test initial notify. { WaitForNotify(); iDriveWatcherX=CDriveWatcher::NewL(iFs, KDriveE, iWatcherStep); break; } case EStateTestNotify: // Test notification which should apply to a watched drive { WaitForNotify(); GenerateMediaChangeL(_L("E:\\private\\10202DCE\\mediachange\\")); break; } case EStateTestNotify2: { WaitForNotify(); TRAPD(err, GenerateMediaChangeL(_L("A:\\private\\10202DCE\\mediachange\\"))); if (err!=KErrNotReady && err!=KErrNone) { User::Leave(err); } TRAP(err, GenerateMediaChangeL(_L("B:\\private\\10202DCE\\mediachange\\"))); if (err!=KErrNotReady && err!=KErrNone) { User::Leave(err); } _LIT(KPath ,"\\private\\10202DCE\\mediachange\\"); TDriveUnit sysDrive (RFs::GetSystemDrive()); TBuf<128> mediaChangePath (sysDrive.Name()); mediaChangePath.Append(KPath); TRAP(err, GenerateMediaChangeL(mediaChangePath)); if (err!=KErrNotReady && err!=KErrNone) { User::Leave(err); } TRAP(err, GenerateMediaChangeL(_L("D:\\private\\10202DCE\\mediachange\\"))); if (err!=KErrNotReady && err!=KErrNone) { User::Leave(err); } GenerateMediaChangeL(_L("E:\\private\\10202DCE\\mediachange\\")); break; } } }
LOCAL_C void TestBrokenStoreL() { TDriveUnit unit =EDriveD; TFileName dest = unit.Name(); dest.Append(KMsvDbFile); RSqlDatabase::Delete(dest); //Call Copy Mail Store to check any existing broken files are //deleted first before copy begins TestCopyStoreOperationL(); }
LOCAL_D void callExampleL() // initialize and call example code under cleanup stack { START_SCRIPT_LIST SCRIPT_ITEM(CRSAEncryptFB,_L8("RSAEncryptStandardAndCRTFB")), SCRIPT_ITEM(CRSASignFB,_L8("RSASignStandardAndCRTFB")), SCRIPT_ITEM(CDSASignFB,_L8("DSASignFB")), SCRIPT_ITEM(CRSAEncryptVector,_L8("RSAEncryptVector")), SCRIPT_ITEM(CRSADecryptVector,_L8("RSADecryptVector")), SCRIPT_ITEM(CRSADecryptVectorCRT,_L8("RSADecryptVectorCRT")), SCRIPT_ITEM(CRSASignVector,_L8("RSASignVector")), SCRIPT_ITEM(CRSASignVectorCRT,_L8("RSASignVectorCRT")), SCRIPT_ITEM(CRSAVerifyVector,_L8("RSAVerifyVector")), SCRIPT_ITEM(CDSASignVector,_L8("DSASignVector")), SCRIPT_ITEM(CDSAVerifyVector,_L8("DSAVerifyVector")), SCRIPT_ITEM(CDSASignFB,_L8("DSASignFB")), SCRIPT_ITEM(CDSAPrimeGen,_L8("DSAPrimeGen")), SCRIPT_ITEM(CPerformanceTest, _L8("PerformanceTestSettings")), SCRIPT_ITEM(CDHVector,_L8("DHVector")), SCRIPT_ITEM(CRSATestPublicKey,_L8("RSAPublicKeyParams")), SCRIPT_ITEM(CRSATestPrivateKey,_L8("RSAPrivateKeyParams")), SCRIPT_ITEM(CRSATestPrivateKeyCRT,_L8("RSAPrivateKeyCRTParams")) END_SCRIPT_LIST // Either run the top level build and test script or, if running this test specifically, // uncomment the following and it'll run them all one after the other //get the system drive. TDriveUnit sysDrive (RFs::GetSystemDrive()); TBuf<64> scriptFile = sysDrive.Name(); scriptFile.Append(_L("\\tasymmetric\\tasymmetrictests.txt")); TBuf<64> logFile = sysDrive.Name(); logFile.Append(_L("\\tasymmetric\\tasymmetrictests.log")); CTestSetup::CreateAndRunTestsL(theTestTypes, scriptFile, logFile); /* The test framework can't handle more than one script * at a time. If you want to run all of the asymmetric tests from the command * line, uncomment this next section. #ifndef _DEBUG CTestSetup::CreateAndRunTestsL(theTestTypes, _L("c:\\tasymmetric\\asymmetricPerformance.txt"), _L("c:\\tasymmetric\\asymmetricPerformance.log")); #endif */ }
/** Set the current default Contacts database drive and optionally moves the default Contacts database from the current default drive to the new drive. @param aDriveUnit New current default Contacts database drive. @param aCopy ETrue if default Contacts database should be moved to new drive. */ void CCntDbManagerController::SetDatabaseDriveL(TDriveUnit aDriveUnit, TBool aCopy) { if (aDriveUnit == iDefaultDriveUnit) // Same drive? { aCopy = EFalse; if (iIniFileManager->DatabaseDriveSet()) { return; } } // Old drive name. TDriveName oldDrv = iDefaultDriveUnit.Name(); // New drive name. TDriveName newDrv = aDriveUnit.Name(); TBuf<KCntMaxFilePath> oldPath; User::LeaveIfError(iFs.PrivatePath(oldPath)); // Drive name goes before the path. oldPath.Insert(0,oldDrv); // Filename goes after the path. oldPath.Append(KSqLiteFilePrefix); oldPath.Append(KContactsBaseFilename); TBuf<KCntMaxFilePath> newPath; User::LeaveIfError(iFs.PrivatePath(newPath)); // Drive name goes before the path. newPath.Insert(0,newDrv); // Filename goes after the path. newPath.Append(KSqLiteFilePrefix); newPath.Append(KContactsBaseFilename); // Move the old file to the new drive location. CFileMan* fileManager = CFileMan::NewL(iFs); CleanupStack::PushL(fileManager); // The new file will be overwritten if it exists. If the file or the path // doesn't exist then it will be created. if (aCopy) { User::LeaveIfError(fileManager->Copy(oldPath, newPath, CFileMan::ERecurse | CFileMan::EOverWrite )); } // Change the default drive to the specified drive. iDefaultDriveUnit = aDriveUnit; // Save to Contacts initialisation file. iIniFileManager->SetDefaultDatabaseDrive(iDefaultDriveUnit, ETrue); iIniFileManager->ScheduleSaveIniFileSettings(CIniFileManager::ESaveDefaultDbDrive); // Remove the old file. if (aCopy) { (void)fileManager->Delete(oldPath); } CleanupStack::PopAndDestroy(fileManager); }
/** * This function sets up a console, a log file and checks * whether we need to wait for a key pressed after test * completion. * First DoThreadedTestsL is called, if everything is ok * it return ETrue and we move on to the standard tests. * If something went amiss (return EFalse) we skip * the standard test and return. */ LOCAL_D void SetupAndRunTests() { CConsoleBase* console = Console::NewL(_L("Test code"), TSize(KConsFullScreen, KConsFullScreen)); HBufC* logFile = GetArgument(1); if (logFile->Length()==0) { _LIT(defaultLog, "\\tcertstore.log"); TDriveUnit sysDrive (RFs::GetSystemDrive()); TDriveName sysdriveName (sysDrive.Name()); TBuf <18> fileName (sysdriveName); fileName.Append(defaultLog); logFile->ReAlloc(18); TPtr16 plog = logFile->Des(); plog.Append(fileName); } HBufC* wait = GetArgument(2); TBool waitAfterCompletion = EFalse; if (wait->Find(_L("-w")) != KErrNotFound) { waitAfterCompletion = ETrue; } TBool res = EFalse; TRAPD(err, res = DoThreadedTestsL(console, logFile, waitAfterCompletion)); if (res) { // Now run a normal tcertstore test to check store integrity TRAP(err, DoTests()); } delete console; delete wait; delete logFile; }
void TThreadData::InitialiseL(TInt aIteration, TInt aThreadNum) { ASSERT(aIteration >= 0 && aIteration < KMaxIterations); ASSERT(aThreadNum >= 1 && aThreadNum <= 3); TInt script = scriptCombinations[aIteration * 3 + aThreadNum - 1]; // Set script file TDriveUnit sysDrive (RFs::GetSystemDrive()); TDriveName sysdriveName (sysDrive.Name()); TBuf <60> scriptFile (sysdriveName); scriptFile.Append(scripts[script]); iScriptFile.Set(scriptFile); // Set log file iLogFile.Zero(); TBuf<80> scriptName (sysdriveName); scriptName.Append(_L("\\tcertstoreconcurrent\\iteration%02d_thread%d_script%d.txt")); TBuf<80> buf ; buf.Format(scriptName,aIteration, aThreadNum, script); iLogFile.Append(buf); }
void CRecogStep::ConvertFileToPrivateL() { // Read source file RFile fromFile; User::LeaveIfError(fromFile.Open(iTheFs, iFileName, EFileShareReadersOrWriters | EFileRead | EFileStream)); CleanupClosePushL(fromFile); TInt size; User::LeaveIfError(fromFile.Size(size)); HBufC8* memForFileContents = HBufC8::NewLC(size); TPtr8 fileContents(memForFileContents->Des()); User::LeaveIfError(fromFile.Read(fileContents, size)); // Create destination path TDriveUnit sysDrive = RFs::GetSystemDrive(); (void)iTheFs.CreatePrivatePath(static_cast<TInt> (sysDrive)); TFileName newFileName; User::LeaveIfError(iTheFs.PrivatePath(newFileName)); newFileName.Insert(0, sysDrive.Name()); TParsePtr parseFrom(iFileName); newFileName.Append(parseFrom.NameAndExt()); // Make sure destination does not already exist. (void) iTheFs.Delete(newFileName); // Copy file to private location RFile toFile; User::LeaveIfError(toFile.Create(iTheFs, newFileName, EFileShareExclusive | EFileWrite | EFileStream)); CleanupClosePushL(toFile); User::LeaveIfError(toFile.Write(fileContents)); // Update iFileName iFileName = newFileName; // Cleanup CleanupStack::PopAndDestroy(&toFile); CleanupStack::PopAndDestroy(memForFileContents); CleanupStack::PopAndDestroy(&fromFile); }
void CTErrorStep::SetupMultipleLangResFilesL() { // Copy files to target path in C: drive User::LeaveIfError(iUtils.CopyFileL(KTErrorLang1Src, KTErrorLang1Tgt)); User::LeaveIfError(iUtils.CopyFileL(KTErrorLang3Src, KTErrorLang3Tgt)); User::LeaveIfError(iUtils.CopyFileL(KTErrorLang6Src, KTErrorLang6Tgt)); // Find where the removable media is (can vary on hardware builds) TDriveUnit drive; FindRemovableMediaL(drive); // Create target directory in removable drive TBuf<128> bufName; bufName = drive.Name(); bufName.Append(KTErrorLang2Tgt); TInt err = iUtils.CreateDirectoryL(bufName); if(err != KErrNone && err != KErrAlreadyExists) { ERR_PRINTF2(_L("Create directory '%S' in removable media failed"), &bufName); User::LeaveIfError(err); } // Copy files to removable drive User::LeaveIfError(iUtils.CopyFileL(KTErrorLang2Src, bufName)); bufName.Zero(); bufName = drive.Name(); bufName.Append(KTErrorLang4Tgt); User::LeaveIfError(iUtils.CopyFileL(KTErrorLang4Src, bufName)); bufName.Zero(); bufName = drive.Name(); bufName.Append(KTErrorLang5Tgt); User::LeaveIfError(iUtils.CopyFileL(KTErrorLang5Src, bufName)); bufName.Zero(); bufName = drive.Name(); bufName.Append(KTErrorLang7Tgt); User::LeaveIfError(iUtils.CopyFileL(KTErrorLang7Src, bufName)); }
void CDeleteKeyStoreData::PerformAction(TRequestStatus& aStatus) { switch (iState) { case EDelete: { TDriveUnit sysDrive (RFs::GetSystemDrive()); TBuf<128> keystoreDataPath (sysDrive.Name()); keystoreDataPath.Append(KKeystoreDataPath); TInt err = iFs.Delete(keystoreDataPath); if (err == KErrNotFound) err = KErrNone; iState = EFinished; TRequestStatus* status = &aStatus; User::RequestComplete(status, err); } break; case EFinished: { TRequestStatus* status = &aStatus; User::RequestComplete(status, aStatus.Int()); if (aStatus == iExpectedResult) { iResult = ETrue; } else { iResult = EFalse; } iActionState = EPostrequisite; } break; } }
void CPlPerformanceAPI::CreateContactsBatchL(TInt aSize) { test.Next(_L("->... Create")); RDebug::Print(_L("CreateContactsTestL(TInt aSize)")); TBool testFlag = EFalse; testFlag = iCntTestImpl.DefaultContactDatabaseExistsL(); test.Printf(_L("CreateContactsBatchL_1, DefaultContactDatabaseExistsL:%d \n"),testFlag); TTime startTime; startTime.UniversalTime(); for (int ii = 0; ii < aSize; ii+=nsPlPerformance::KBatchSize) { CreateContactsTestL(aSize<nsPlPerformance::KBatchSize ? aSize:nsPlPerformance::KBatchSize); if (ii >= nsPlPerformance::KBatchSize - 1) { iCntTestImpl.CompactL(); } } TTime finishTime; finishTime.UniversalTime(); // Temporary required for ARMv5, adress of Int64() is taken in // parameter to Format method otherwise. TReal lapsed = (TReal) finishTime.MicroSecondsFrom(startTime).Int64(); TBuf8<64> row; // _LIT8 gives an error - illegal implicit conversion from long row.Format(_L8("Create,%d,%.4f\r\n"), aSize, lapsed/1000000); iCsvWriter->WriteNextLineL(row); // API Tests testFlag = iCntTestImpl.CompressRequired(); test.Printf(_L("CreateContactsBatchL, CompressRequired:%d \n"),testFlag); testFlag = iCntTestImpl.IsDamaged(); test.Printf(_L("CreateContactsBatchL, IsDamaged:%d \n"),testFlag); testFlag = iCntTestImpl.DefaultContactDatabaseExistsL(); test.Printf(_L("CreateContactsBatchL, DefaultContactDatabaseExistsL:%d \n"),testFlag); testFlag = iCntTestImpl.ContactDatabaseExistsL(KTestContactFileName); test.Printf(_L("CreateContactsBatchL, ContactDatabaseExistsL:%d \n"),testFlag); TInt theCount; theCount = iCntTestImpl.FileSize(); test.Printf(_L("CreateContactsBatchL, FileSize:%d \n"),theCount); theCount = iCntTestImpl.WastedSpaceInBytes(); test.Printf(_L("CreateContactsBatchL, WastedSpaceInBytes:%d \n"),theCount); TBuf<190> defaultName; iCntTestImpl.GetDefaultNameL(defaultName); test.Printf(_L("CreateContactsBatchL, GetDefaultNameL: %s \n"),defaultName.PtrZ()); defaultName.Delete(0,defaultName.Size()); TDriveUnit driveUnit; iCntTestImpl.DatabaseDrive(driveUnit); TBuf<190> driveName = driveUnit.Name(); test.Printf(_L("CreateContactsBatchL, DatabaseDrive: %s \n"),driveName.PtrZ()); }
void CPolicyTest::ProcessResultsL(TRequestStatus& aStatus) { _LIT8(KSummaryLine, " tests failed out of "); _LIT8(KNewLine, "\r\n"); TInt failCount = KErrNotFound, runCount; // Read entire log file into memory to process RFile file; TDriveUnit sysDrive (RFs::GetSystemDrive()); TBuf<128> logTmpFile (sysDrive.Name()); logTmpFile.Append(KLogTmpPath); User::LeaveIfError(file.Open(iFs, logTmpFile, EFileShareReadersOnly | EFileRead)); CleanupClosePushL(file); TInt size; User::LeaveIfError(file.Size(size)); HBufC8* buffer = HBufC8::NewLC(size); TPtr8 ptr = buffer->Des(); User::LeaveIfError(file.Read(ptr)); iOut.writeString(_L("Child test output:\n")); TInt pos = 0; while (pos < size) { TInt nextNewline = buffer->Mid(pos).Find(KNewLine); // Split buffer into lines TPtrC8 line; if (nextNewline == KErrNotFound) { line.Set(buffer->Mid(pos)); } else { line.Set(buffer->Mid(pos, nextNewline + KNewLine().Length())); } pos += line.Length(); // Search for summary line TInt pos2 = line.Find(KSummaryLine); if (pos2 != KErrNotFound) { // Parse the summary line to work out if the test passed TLex8 lex1(line.Left(pos2)); TInt err1 = lex1.Val(failCount); TLex8 lex2(line.Mid(pos2 + KSummaryLine().Length())); TInt err2 = lex2.Val(runCount); if (err1 != KErrNone || err2 != KErrNone) { iOut.writeString(_L("Failed to parse summary line\n")); User::LeaveIfError(err1); User::LeaveIfError(err2); } } else { // Don't print the summary line as this will confuse whatever parsed // the main log iOut.writeString(_L("> ")); iOut.writeString(line); } } if (failCount == KErrNotFound) { iOut.writeString(_L("Couldn't find summary line in test output\n")); User::Leave(KErrNotFound); } iFailCount += failCount; // Print results in different format iOut.write(_L("Tests run: %d\n"), runCount); iOut.write(_L("Tests failed: %d\n"), failCount); iOut.writeNewLine(); CleanupStack::PopAndDestroy(2, &file); TRequestStatus* status = &aStatus; User::RequestComplete(status, KErrNone); }
TVerdict CForceRemove::doTestStepL() { #ifndef SYMBIAN_UNIVERSAL_INSTALL_FRAMEWORK // Wait up to 30 seconds to ensure both SWIS and the sisregistry server // have shut down _LIT(KSisRegistryServerName, "!SisRegistryServer"); _LIT(KInstallServerName, "!InstallServer"); TInt delaytime = 30; while (delaytime-- > 0) { TFullName serverName; TFindServer find(KInstallServerName); if (KErrNotFound == find.Next(serverName)) { find.Find(KSisRegistryServerName); if (KErrNotFound == find.Next(serverName)) { break; } } User::After(1000000); // wait a second until the next test } #endif // SYMBIAN_UNIVERSAL_INSTALL_FRAMEWORK TPtrC name; RTestUtilSessionSwi testutil; User::LeaveIfError(testutil.Connect()); CleanupClosePushL(testutil); // If file deletion fails we'll try moving the file to a temp directory // for another process to clean up later. TTime currentTime; currentTime.UniversalTime(); _LIT(KTempPathFormat, "\\temp\\%Lu"); TDriveUnit sysDrive (RFs::GetSystemDrive()); TBuf<128> tempPathFormat(sysDrive.Name()); tempPathFormat.Append(KTempPathFormat); TFileName targetPath; targetPath.Format(tempPathFormat, currentTime.Int64()); _LIT(KNumFiles, "numfiles"); #ifdef SYMBIAN_UNIVERSAL_INSTALL_FRAMEWORK RArray<TUint> removeUids; CleanupClosePushL(removeUids); #endif TInt num(0); GetIntFromConfig(ConfigSection(), KNumFiles, num); // Get the file names and use testutil to remove them for (TInt i = 0; i < num; ++i) { _LIT(KFile, "file"); TBuf<32> key(KFile); key.AppendNum(i); if (!GetStringFromConfig(ConfigSection(), key, name)) continue; INFO_PRINTF2(_L("ForceRemove - trying to delete file %S"), &name); TInt err = testutil.Delete(name); if (err != KErrNone && err != KErrNotFound && err != KErrPathNotFound) { INFO_PRINTF3(_L("RTestUtilSessionSwi::Delete(%S) returned %d, attempting move instead."), &name, err); TFileName source(name); TParsePtr parse(source); TFileName dest(targetPath); dest.Append(parse.Path()); if (parse.DrivePresent()) { dest[0] = source[0]; } testutil.MkDirAll(dest); dest.Append(parse.NameAndExt()); err = testutil.Move(source, dest); if (err != KErrNone) { INFO_PRINTF4(_L("Attempt to move from %S to %S returned %d"), &source, &dest, err); } } #ifdef SYMBIAN_UNIVERSAL_INSTALL_FRAMEWORK _LIT(KRegistryPath, "\\sys\\install\\sisregistry\\"); if (name.FindF(KRegistryPath) == KErrNotFound) continue; // Extract the uid and add it to our list TInt slashPos = name.LocateReverse('\\'); TPtrC ptrUid = name.Mid(slashPos + 1); if (ptrUid.Length() != 8) continue; TUint uid = 0; TLex lex(ptrUid); if (lex.Val(uid, EHex) == KErrNone) { removeUids.InsertInOrder(uid); // Will not allow duplicates } #endif } #ifdef SYMBIAN_UNIVERSAL_INSTALL_FRAMEWORK // Use the sisregistry folder uid to remove the package entries from SCR // Note that we remove packages present in ROM too due to two reasons: // This is exactly what ForceRemove used to do (delete entire registry folder containing ALL reg files) // After deleting an entry SWIRegistry re-registers ROM apps (missing ones) TInt count = removeUids.Count(); RSisRegistryAccessSession regWrite; TInt err = regWrite.Connect(); User::LeaveIfError(err); CleanupClosePushL(regWrite); Swi::RSisRegistrySession regRead; User::LeaveIfError(regRead.Connect()); CleanupClosePushL(regRead); for (TInt i = 0; i < count; ++i) { TUid uid = TUid::Uid(removeUids[i]); Swi::RSisRegistryEntry entry; CleanupClosePushL(entry); if (entry.Open(regRead, uid) == KErrNone) { // Get its augmentations RPointerArray<Swi::CSisRegistryPackage> augmentations; CleanupResetAndDestroy<RPointerArray<Swi::CSisRegistryPackage> >::PushL(augmentations); entry.AugmentationsL(augmentations); TInt augCount = augmentations.Count(); for (TInt j = 0; j < augCount; ++j) { // Remove it TInt dummyTime; regWrite.DeleteEntryL(*augmentations[j], dummyTime); } // Finally remove the base package entry Swi::CSisRegistryPackage* package = entry.PackageL(); CleanupStack::PushL(package); TInt dummyTime; regWrite.DeleteEntryL(*package,dummyTime); CleanupStack::PopAndDestroy(2, &augmentations); // package } CleanupStack::PopAndDestroy(&entry); } CleanupStack::PopAndDestroy(3, &removeUids); // regWrite, regRead #endif CleanupStack::PopAndDestroy(&testutil); return EPass; }
TVerdict CTSISHelperStepData::doTestStepL() { SetTestStepResult(EFail); // Start the SISHelper TPtrC sisFileName; GetStringFromConfig(ConfigSection(),_L("SIS"), sisFileName); Swi::TSisHelperStartParams params(sisFileName); User::LeaveIfError(startSisHelper(params)); Swi::RSisHelper server; User::LeaveIfError(server.Connect()); server.OpenDrmContentL(ContentAccess::EExecute); TInt dataUnit = 0; GetIntFromConfig(ConfigSection(),_L("DataUnit"), dataUnit); TInt fileNumber = 0; GetIntFromConfig(ConfigSection(),_L("FileNumber"), fileNumber); // Create a file handle to pass RFs sharedFs; RFile sharedFile; User::LeaveIfError(sharedFs.Connect()); User::LeaveIfError(sharedFs.ShareProtected()); _LIT(KTempFileName,"\\tsishelper.temp"); TDriveUnit sysDrive (RFs::GetSystemDrive()); TBuf<64> tempFileName (sysDrive.Name()); tempFileName.Append(KTempFileName); User::LeaveIfError(sharedFile.Replace (sharedFs, tempFileName, EFileWrite)); TInt fakeUiHandler=0; Swi::RUiHandler& uiHandler=reinterpret_cast<Swi::RUiHandler&>(fakeUiHandler); User::LeaveIfError(server.ExtractFileL(sharedFs, sharedFile, fileNumber, dataUnit, uiHandler)); sharedFile.Close(); sharedFs.Close(); TPtrC expectedData; GetStringFromConfig(ConfigSection(),_L("ExpectedData"), expectedData); RFile oldFile; User::LeaveIfError(oldFile.Open(iFs, expectedData, EFileRead)); RFile newFile; User::LeaveIfError(newFile.Open(iFs, tempFileName, EFileRead)); // KErrBusy means SISHelper didn't close! TInt expectedLength(0); oldFile.Seek(ESeekEnd,expectedLength); TInt actualLength(0); newFile.Seek(ESeekEnd,actualLength); if (expectedLength == actualLength) { TInt pos = 0; oldFile.Seek(ESeekStart, pos); newFile.Seek(ESeekStart, pos); SetTestStepResult(EPass); for (TInt i=0; i<expectedLength; i++) { TInt8 oldChar; TInt8 newChar; TPckg<TInt8> oldPkg(oldChar); TPckg<TInt8> newPkg(newChar); oldFile.Read(oldPkg); newFile.Read(newPkg); if (oldChar != newChar) { SetTestStepResult(EFail); break; } } } oldFile.Close(); newFile.Close(); RFs fs; User::LeaveIfError(fs.Connect()); // Delete the temp file TInt error = fs.Delete(tempFileName); if (error != KErrNone && error != KErrNotFound) { User::Leave(error); } fs.Close(); server.Close(); return TestStepResult(); }
/* Test to check the new API ** CopyStoreL(TInt aDrive, TMsvOp aOperationId, TRequestStatus& aStatus) */ LOCAL_C void TestCopyStoreOperationL() { CMsgsTestUtils::SetDriveL(EDriveC); CSessionObserver* ob = new(ELeave)CSessionObserver; CleanupStack::PushL(ob); // Set session in observer CMsvSession* session = CMsvSession::OpenAsyncL(*ob); ob->iSession = session; CleanupStack::PushL(session); CActiveScheduler::Start(); test(ob->iType==MMsvSessionObserver::EMsvServerReady); //Create an entry in the mail CMsvEntry* entry=session->GetEntryL(KMsvDraftEntryId); CleanupStack::PushL(entry); // create entry to work under TMsvEntry folder; folder.iType = KUidMsvFolderEntry; folder.iMtm = KUidMsvLocalServiceMtm; folder.iServiceId = KMsvLocalServiceIndexEntryId; _LIT(KTestDescription,"A Description"); _LIT(KTestDetails,"A Details"); folder.iDescription.Set(KTestDescription); folder.iDetails.Set(KTestDetails); entry->CreateL(folder); entry->SetEntryL(folder.Id()); CMsvStore* store=entry->EditStoreL(); CleanupStack::PushL(store); RMsvWriteStream stream; stream.AssignLC(*store,TUid::Uid(0x1000)); stream.WriteL(KTestDescription); stream.CommitL(); store->CommitL(); CleanupStack::PopAndDestroy(3); CTestActive* active = new(ELeave)CTestActive; CleanupStack::PushL(active); // Test Copy MailStore active->StartL(); CMsvOperation* operation = NULL; TDriveUnit unit =(EDriveD); operation = session->CopyStoreL(unit, active->iStatus); test(operation->Mtm() == KUidMsvServerMtm); CleanupStack::PushL(operation); CActiveScheduler::Start(); //Retrieve progress TPckgBuf<TMsvCopyProgress> package; package.Copy(operation->ProgressL()); test(package().iError == KErrNone); //delete session; CleanupStack::PopAndDestroy(4); //Check that both the source and destination //MailStore directory structure is same CMsgsTestUtils::WaitForServerClose(); CDir *srcDir; CDir *destDir; _LIT(intro, "Testing the directory structure"); _LIT(KEntryname,"%S"); theUtils->Printf(intro); TFileName dest = unit.Name(); dest.Append(KMsvDefaultFolder2); User::LeaveIfError(theUtils->FileSession().GetDir(dest, KEntryAttDir|KEntryAttNormal, ESortByName, destDir)); unit =EDriveC; TFileName src = unit.Name(); src.Append(KMsvDefaultFolder2); User::LeaveIfError(theUtils->FileSession().GetDir(src, KEntryAttDir|KEntryAttNormal, ESortByName, srcDir)); TInt counter=0; TEntry srcEntry; TEntry destEntry; while (counter<srcDir->Count()) { srcEntry = (*srcDir)[counter]; destEntry = (*destDir)[counter]; //Check the sizes test(srcEntry.iSize == destEntry.iSize); //Check the names test(srcEntry.iName == destEntry.iName); //Print out the names on the log theUtils->Printf(KEntryname,&(srcEntry.iName)); counter++; } delete srcDir; delete destDir; }
/* HELPER: The actual step thta does the encryption and decryption */ TVerdict CTlsProvTestActive::EncryptAndDecryptL(CTLSSession* aPtrTlsSession, CTlsProvStep* /*aStep*/) { RFs filesys; filesys.Connect(); RFile fileTmp_t; TBuf8<1024> TempPrint; TDriveUnit sysDrive (filesys.GetSystemDrive()); TDriveName sysDriveName (sysDrive.Name()); TBuf<128> fileName (sysDriveName); fileName.Append(_L("\\data\\ActualAppData.bin")); TInt result_t = fileTmp_t.Open(filesys, fileName, EFileRead); INFO_PRINTF1(_L("EncryptAndDecryptL 1")); if(!result_t) fileTmp_t.Read( TempPrint ); fileTmp_t.Close(); iStatus = KRequestPending; HBufC8* Output = NULL; TRecordProtocol RecType; RecType= EHandshake; TInt64 ASeqNumber = 0; Output = HBufC8::NewL(TempPrint.Length() + 24); aPtrTlsSession->EncryptL( TempPrint, Output, ASeqNumber,RecType) ; INFO_PRINTF1(_L("EncryptAndDecryptL 2")); fileName.Copy(sysDriveName); fileName.Append(_L("\\data\\EncryptOutput.bin")); result_t = fileTmp_t.Open(filesys, fileName, EFileRead); TBuf8<1024> ActualOutput; if(!result_t) fileTmp_t.Read(ActualOutput); fileTmp_t.Close(); if(ActualOutput.Compare(Output->Des()) != 0) return EFail; //Test Decryption here INFO_PRINTF1(_L("EncryptAndDecryptL 3")); fileName.Copy(sysDriveName); fileName.Append(_L("\\data\\DecryptionInput.bin")); result_t = fileTmp_t.Open(filesys, fileName, EFileRead); if(!result_t) fileTmp_t.Read( ActualOutput ); fileTmp_t.Close(); iStatus = KRequestPending; HBufC8* OutputDe = NULL; RecType= EHandshake; TInt64 ASeqNumberDe = 0; OutputDe = HBufC8::NewL(ActualOutput.Length()); aPtrTlsSession->DecryptAndVerifyL( ActualOutput, OutputDe, ASeqNumberDe,RecType) ; fileName.Copy (sysDriveName); fileName.Append(_L("\\data\\DecryptionOutputNoMac.bin")); result_t = fileTmp_t.Open(filesys, fileName, EFileRead); if(!result_t) fileTmp_t.Read(ActualOutput); fileTmp_t.Close(); INFO_PRINTF1(_L("EncryptAndDecryptL 4")); if(ActualOutput.Compare(OutputDe->Des()) != 0) { iLogInfo.Copy(_L(" EncryptDecr Fail")); return EFail; } else { iLogInfo.Copy(_L(" EncryptDecr Success")); return EPass; } }
LOCAL_C void mainL() // initialize and call example code under cleanup stack { test.Title(); CTestConsole *con = CTestConsole::NewL(test.Console()); RFs fs; User::LeaveIfError(fs.Connect()); CleanupClosePushL(fs); TDriveUnit sysDrive (fs.GetSystemDrive()); TBuf<24> logFile (sysDrive.Name()); logFile.Append(_L("\\temblog.txt")); RFile file; User::LeaveIfError(file.Replace(fs, logFile, EFileShareAny|EFileWrite)); CleanupClosePushL(file); con->SetLogFile(file); test.SetConsole(con); TInt r; RDebug::Printf("Hello from user side\n"); test.Start(_L(" @SYMTestCaseID:SEC-CRYPTOSPI-TEMB-0001 Load driver ")); test.Next(_L("Loading Physical Device")); r=User::LoadPhysicalDevice(KPddFileName); test(r==KErrNone || r==KErrAlreadyExists); test.Next(_L("Loading Logical Device")); r=User::LoadLogicalDevice(KLddFileName); test(r==KErrNone || r==KErrAlreadyExists); // // Generate key and IV // test.Start(_L("Random - Generating key & IV for AES tests")); test.Printf(_L("\tGenerating random key\n")); // Generate random 16 byte key TBuf8<KEYLEN> key; key.SetLength(key.MaxLength()); TRandom::RandomL(key); key[0] = 'K'; key[1] = 'E'; key[2] = 'Y'; key[3] = '*'; for(int z=4; z<KEYLEN; ++z) key[z] = z; test.Printf(_L("\tGenerating random IV\n")); // Generate random 16 byte IV TBuf8<16> iv; iv.SetLength(iv.MaxLength()); TRandom::RandomL(iv); iv[0] = 'I'; iv[1] = 'V'; iv[2] = '*'; iv[3] = '*'; TBuf8<BUFLEN> plaintext; plaintext.FillZ(); plaintext.SetLength(BUFLEN); plaintext[0] = 'P'; plaintext[1] = 'L'; plaintext[2] = 'A'; plaintext[3] = 'I'; plaintext[4] = 'N'; for(int i=0; i<BUFLEN; ++i) { plaintext[i] = i; } // // KMS tests // test.Next(_L("KMS - Store key")); TBuf8<BUFLEN+16> kmsData; kmsData.FillZ(); kmsData.SetLength(0); do { RKeyMgmtSession kms; User::LeaveIfError(kms.Connect()); CleanupClosePushL(kms); TKeyHandle keyHandle; User::LeaveIfError(kms.StoreKey(key, keyHandle)); _LIT_SECURITY_POLICY_PASS(KAlwaysPass); User::LeaveIfError(kms.AddUsage(keyHandle, 0 /* operation */, KAlwaysPass)); test.Next(_L("KMS - Attempt to use key via embedded key handle")); TPckgBuf<TKeyHandle> keyHandlePkg; keyHandlePkg() = keyHandle; TKeyProperty keyProperty = {KAesUid, KNullUid, KSymmetricKeyUid, KNonExtractableKey}; CCryptoParams* keyParam =CCryptoParams::NewLC(); keyParam->AddL(keyHandlePkg, KSymmetricKeyParameterUid); CKey *ckey=CKey::NewL(keyProperty, *keyParam); CleanupStack::PopAndDestroy(keyParam); CleanupStack::PushL(ckey); CryptoSpi::CSymmetricCipher *aes = 0; CSymmetricCipherFactory::CreateSymmetricCipherL(aes, KAesUid, *ckey, KCryptoModeEncryptUid, KOperationModeCBCUid, KPaddingModePKCS7Uid, NULL); CleanupStack::PopAndDestroy(ckey); CleanupStack::PushL(aes); aes->SetOperationModeL(CryptoSpi::KOperationModeCBCUid); aes->SetIvL(iv); aes->ProcessFinalL(plaintext, kmsData); CleanupStack::PopAndDestroy(aes); CleanupStack::PopAndDestroy(&kms); } while(false); // // Encrypt using legacy API // TBuf8<BUFLEN+16> sw; sw.FillZ(); sw.SetLength(0); do { test.Next(_L("Encrypt using key directly (non-KMS)")); // ECB test.Printf(_L(" CBC\n")); CAESEncryptor *rawaes = CAESEncryptor::NewLC(key); // rawaes CModeCBCEncryptor *cbc = CModeCBCEncryptor::NewL(rawaes, iv); CleanupStack::Pop(rawaes); // CleanupStack::PushL(cbc); // cbc #ifdef PKCS7PAD CPadding *pad = CPaddingPKCS7::NewLC(16); // cbc, pad #else CPadding *pad = CPaddingNone::NewLC(16); // cbc, pad #endif CBufferedEncryptor *aes = CBufferedEncryptor::NewL(cbc, pad); CleanupStack::Pop(pad); // cbc CleanupStack::Pop(cbc); CleanupStack::PushL(aes); // aes test.Printf(_L("About to s/w encrypt (old api)\n")); aes->ProcessFinalL(plaintext, sw); CleanupStack::PopAndDestroy(aes); } while(false); test.Printf(_L("Checking KMS encrypt and direct encrypt had the same result\n")); test(kmsData == sw); test.End(); test.Printf(_L("\r\n0 tests failed out of 1\r\n")); // test.Printf(KTxtPressAnyKey); // test.Getch(); // get and ignore character test.Close(); CleanupStack::PopAndDestroy(&file); CleanupStack::PopAndDestroy(&fs); }